# Prosaic docs: Extensions (full text) > Prosaic is the headless ledger for New Zealand and Australia: double-entry accounting as an API, with GST built in, that your customers' accountants can work in directly. This file holds the Extensions docs, concatenated. The canonical pages are at https://developer.prosaic.works/docs/{category}/{slug}, and each is also served as Markdown at https://developer.prosaic.works/docs/{category}/{slug}.md. The index is https://developer.prosaic.works/llms.txt. # Extensions overview > What extensions are, when to write one, and where to start — creating one, or using one in a workspace. Source: https://developer.prosaic.works/docs/extensions/overview Extensions are small TypeScript programs that run inside Prosaic when something happens — a journal gets posted, a bank transaction is reconciled, IRD accepts a GST return, the clock strikes nine, or someone clicks a button. You write the code and declare what it's allowed to do, and Prosaic hosts and runs it in a sandbox next to the accounting data. Think of them as the hook system every accountant has asked for, without the spreadsheet macros. ## Start here ### Create an extension For developers, and for anyone working with a coding agent. 1. [**Quickstart**](/docs/extensions/quickstart) — install the CLI, scaffold a project, deploy it and watch it run, in about five minutes. 2. [**Manifest reference**](/docs/extensions/manifest) — the name, scopes, triggers and connections in `prosaic.extension.toml`. 3. [**Sandbox API**](/docs/extensions/sandbox-api) — everything on the `prosaic` global your code calls. 4. [**Triggers**](/docs/extensions/triggers) — events, cron schedules and action buttons, with a handler for each. 5. [**Testing and deploy**](/docs/extensions/testing-and-deploy) — `validate`, the `dev` loop, `logs`, and how versions and permissions change. 6. [**Examples**](/docs/extensions/examples) — complete extensions to copy. 7. [**Build with an LLM**](/docs/extensions/llm-tools) — have Claude, Cursor or ChatGPT scaffold and validate one through the developer MCP server. ### Use an extension For the workspace admins, advisors and accountants it runs for. - [**Using extensions**](/docs/extensions/using-extensions) — install it on a client's entity, connect its credentials, run its actions, read its runs, and pause, approve, update or remove it. ## Extension or API? Both reach the same ledger. Pick by where the work starts. - **Use the [API](/docs/getting-started/overview)** when your product is the source of the data. It creates entities, posts journals, imports bank transactions and reads reports back into your app. Your server calls Prosaic. - **Write an extension** when the work belongs inside Prosaic: reacting to what accountants do in the books, running on a schedule for each client, or adding a button to the app. Prosaic calls your code, and there's no server of yours to run. ## When to build one Good fits: - **Notifications** — email a client when their GST return is filed, or post to Slack when a large transaction is reconciled. - **Reminders and chasers** — ask clients for documents when a new GST period starts, and handle their replies. - **Scheduled reports** — generate last month's profit and loss on the 1st and email it. - **Integrations** — push data to another system's API through a connection you declare, with Prosaic holding the credential. - **Workflow helpers** — add an action to the transaction list that runs whatever you want, such as AI account suggestions. Not a great fit: - **Writing to the ledger.** Extensions read journals but can't create, edit or void them, or reconcile a transaction. Post journals from your own server with the [public API](/docs/ledger/journals). - **Arbitrary network access or runtime dependencies.** Outbound HTTP goes only to hosts you declare, and your code is bundled before it's deployed. - **Long-running work** (over 10 seconds, or 2 minutes with `use:ai`). Break it up over a cron. - **UI beyond an action.** An action is a menu item or a button with your label on it; there are no custom screens. - **Distribution.** An extension runs in the workspace it was deployed to. There's no marketplace for publishing it to other workspaces. ## How it works ``` trigger fires → installation matches → runtime executes → run recorded (event, cron, (entity, switched on, (V8 isolate) action, reply) grant still covers it) ▲ │ │ ▼ prosaic.* bridge API ``` Each extension has: - A **manifest** (`prosaic.extension.toml`) that declares its triggers, scopes, connections and metadata. - An **entry point** (`src/index.ts`) — the code that runs on each trigger. - An **installation** per entity — each client or business is switched on separately, and each installation records the scopes and hosts it was granted. When a trigger fires, Prosaic queues a job. The runtime starts a V8 isolate, injects the `prosaic.*` global, runs your code, and records the run — logs, input, output, errors — so you can debug it later. Every call through the global is checked against the scopes in your manifest and the grant on the installation. ## What you get inside the sandbox The `prosaic` global gives you: - `context` — what triggered this run, and which entity it's for - `transactions` — list and read bank transactions, and change a transaction's description - `journals`, `entities` — read-only - `reports` — profit and loss, balance sheet, trial balance and the other financial reports - `gst` — GST returns: status, periods and IRD box amounts - `email.send` — send from a Prosaic-managed address; replies come back to your extension - `ai.complete` — call a large language model through Prosaic's account, no API key of your own - `http.fetch` — call a third-party API you declared, with Prosaic attaching the credential - `links` — remember which record in another system matches which Prosaic record - `storage` — a small key-value store for the extension - `tools` — Prosaic's tool registry, including the chart of accounts - `log` — structured logs you read with `prosaic extension logs` No global `fetch`. No `require`. No filesystem. No process environment. Anything that leaves the sandbox goes through one of the bridges above, which is what makes it safe to install one extension on many clients' entities. The full surface, with examples, is in the [Sandbox API](/docs/extensions/sandbox-api). Questions? We read every message at [support@prosaic.works](mailto:support@prosaic.works). --- # Extensions quickstart > From zero to a deployed extension, running on a real journal, in about five minutes. Source: https://developer.prosaic.works/docs/extensions/quickstart This walks one extension all the way through: scaffold it, write it, validate it, deploy it to an entity, make it run, and read what it did. The extension logs a line every time a journal is posted. You'll need Node 22 or later, and a Prosaic login that is a workspace admin or owner — deploying an extension requires one of those roles. Use an entity you don't mind experimenting on; a test client is ideal. ## 1. Install the CLI ```bash npm install -g prosaic-cli ``` The package is `prosaic-cli`; the command it installs is `prosaic`. Confirm it works: ```bash prosaic --version ``` ## 2. Log in ```bash prosaic auth login ``` This opens a browser, you sign in, and the CLI saves its credentials to `~/.prosaic/config.toml`. It uses them for every later command — deploy, logs, the lot. `prosaic auth whoami` shows who you're signed in as. In CI, pass an API key instead: `prosaic auth login --token `. ## 3. Scaffold a project ```bash prosaic extension init journal-posted-logger --trigger event cd journal-posted-logger ``` What you just got: ``` journal-posted-logger/ prosaic.extension.toml # Manifest: name, scopes, triggers src/ index.ts # Your code package.json tsconfig.json ``` The project is named after its folder. The scaffolded manifest listens for `journal.created` with the `read:transactions` scope, and its first line is a `#:schema` directive, so TOML editors check the file as you type — see [Validation in your editor](/docs/extensions/manifest#validation-in-your-editor). `--trigger` picks the starting point: | `--trigger` | What it sets up | | ------------- | -------------------------------------------------------- | | `event` | `[[targets.events]]` for `journal.created` (the default) | | `cron` | `[targets.cron]` running daily at 09:00 UTC | | `action-link` | Two `[[targets.actions]]` on single + bulk transactions | | `manual` | No trigger — a commented example for you to fill in | ## 4. Write the extension Replace the scaffolded manifest with one that listens for posted journals and can read them. `prosaic.extension.toml`: ```toml #:schema https://developer.prosaic.works/schemas/extension-manifest.json name = "journal-posted-logger" version = "0.0.1" description = "Logs posted journals" [scopes] required = ["read:journals"] [[targets.events]] type = "journal.posted" ``` Then replace `src/index.ts`: ```typescript const { input } = prosaic.context; const journal = await prosaic.journals.get(input.journalId); prosaic.log.info('Journal posted', { journalId: journal.id, date: journal.date, narration: journal.narration, }); ``` `prosaic` is a global the runtime provides — there's nothing to import. For a `journal.posted` event, `prosaic.context.input` is `{ journalId }`. Reading the journal needs `read:journals`, which is why the manifest asks for it; without it the call throws a permission error. ## 5. Validate ```bash prosaic extension validate ``` This runs the same manifest checks as a deploy and a trial build of `src/`. It needs no network and no login, so run it whenever you change either file. ## 6. Find your entity ID Extensions install per entity — each business or client is its own entity. Open the entity in Prosaic and take the ID from the address bar; it's the part after `/entities/`: ``` https://app.prosaic.works/entities/ ``` Or list them from the CLI: ```bash prosaic entities list ``` ## 7. Deploy ```bash prosaic extension deploy --entity-id ``` The first time, this: 1. Validates your manifest 2. Bundles `src/index.ts` with esbuild into a single ES module with no runtime imports 3. Creates the extension in your workspace 4. Uploads the bundle 5. Installs it on the entity you passed Later deploys find the extension by its `name` and update it in place, so it's safe to re-run as often as you like. ## 8. Make it run Post a journal on that entity in Prosaic — a manual journal is quickest. Then pull the extension's runs: ```bash prosaic extension logs --dir . --follow ``` Each run prints its status, ID, trigger and start time, then the lines it logged. Something like: ``` completed 8c41… journal.posted 2026-10-27T21:04:12.381Z [21:04:12] INFO Journal posted {"journalId":"5d1e…","narration":"Office supplies"} ``` `--dir .` tells the CLI to look the extension up by the name in your manifest; unlike the other commands, `logs` doesn't assume the current folder. You can pass the extension's ID instead: `prosaic extension logs `. ## 9. See it in Prosaic Open **Settings → Extensions** in the app (`https://app.prosaic.works/settings/extensions` if it isn't in your settings menu yet). Your extension is listed with its version and counts; open it to see its triggers and scopes, the entity it's installed on with a switch to turn it off, and its recent runs. [Using extensions](/docs/extensions/using-extensions) covers that page, and what everyone else in the workspace sees. ## 10. Iterate with `extension dev` ```bash prosaic extension dev --entity-id ``` `dev` deploys, then watches `src/` and the manifest and redeploys when you save. It polls for runs every 3 seconds and prints them, so post another journal and the result appears in your terminal. `Ctrl+C` stops it; what you deployed stays deployed. That's the full loop: write, validate, deploy, trigger, read the logs. ## Next - [Triggers](/docs/extensions/triggers) — swap the event for a schedule or an action button, with a handler for each. - [Sandbox API](/docs/extensions/sandbox-api) — the whole `prosaic.*` surface: reports, GST, email, AI, outbound HTTP. - [Using extensions](/docs/extensions/using-extensions) — install it on more entities, connect credentials, and approve wider permissions. - [Build with an LLM](/docs/extensions/llm-tools) — skip the typing and have Claude write it for you. --- # Using extensions > Install, connect, run, pause, update and remove an extension in a Prosaic workspace — who can do each, and where runs show up. Source: https://developer.prosaic.works/docs/extensions/using-extensions This page is about an extension once it's deployed: how it gets onto a client's entity, how people in the workspace run it, and where to look when it does something unexpected. To build one, start with the [quickstart](/docs/extensions/quickstart). ## Where extensions live An extension belongs to the workspace it was deployed to. There's no marketplace or shared catalogue: to run the same extension in a second workspace, deploy it there too, signed in as an admin of that workspace. Inside the workspace it runs only for the entities it's installed on. Each installation is one entity — one client or business — and is switched on and off on its own. An extension installed on three entities runs three times on a schedule, and an event on an entity it isn't installed on doesn't run it at all. In the Prosaic app, extensions are under **Settings → Extensions**, at `https://app.prosaic.works/settings/extensions`. The link in the settings menu is still rolling out to workspaces, so if you don't see it, open that address directly. ## Who can do what | Task | Who | | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | Deploy or update an extension, and install it on an entity | Workspace admin or owner | | Enter, replace, authorise or disconnect a connection's credential | Workspace admin or owner | | Open **Settings → Extensions**, turn an installation off or on, approve it | Advisor, admin or owner, for the entities they can see | | Click an extension's action in the app | Anyone in the workspace who can see the entity | | Read run logs with `prosaic extension logs` | Anyone signed in to the CLI for the workspace | | Delete an extension from the workspace | Prosaic support — email [support@prosaic.works](mailto:support@prosaic.works) | ## Install it on an entity An extension is installed on an entity when it's deployed with that entity's ID: ```bash prosaic extension deploy --dir . --entity-id ``` Run it once for each entity. Every run finds the extension by the `name` in its manifest, updates it, and then installs it on the entity you named, or refreshes the installation if it's already there. The entity ID is the part of the app's address after `/entities/` when you have that entity open, or run `prosaic entities list`. **Settings → Extensions** has no button for installing on another entity yet, so new installations come from the CLI. ### What installing grants There's no separate consent screen. Installing is the consent: Prosaic records what the extension asked for at that moment — its scopes, and every host its connections can reach — together with who installed it and when. Every run is checked against that record as well as against the manifest, so a later deploy can't quietly give an installed extension more access. See [Approve a wider extension](#approve-a-wider-extension). ## Connect outside services An extension that calls another system's API declares a [connection](/docs/extensions/manifest#connections) for it. Each connection shows in the extension's panel under **Settings → Extensions** with its label, base URL, the hosts it can reach and a status: _Not connected_, _Awaiting authorisation_, _Connected_, _Expired_ or _Needs attention_. A workspace admin connects it there: - **API key, bearer token, username and password, or a custom header** — type the values into the fields the connection asks for and choose **Save**. Prosaic never shows a stored value again, so to change one, type the new value and choose **Replace**. - **OAuth** — enter the client ID and client secret from your app at the third party, choose **Save client details**, then **Authorise** and sign in to the third party. Register `https://app.prosaic.works/api/extensions/oauth/callback` as the redirect URI in their developer console first. Prosaic refreshes the access token from then on; **Reauthorise** starts the sign-in again. **Disconnect** deletes the stored credential. If calls through a connection start failing, the panel shows the last failure's error code. Prosaic encrypts the credential, attaches it to each request on the server, and never passes it into the sandbox. The extension's code can't read it, log it or send it anywhere else. Connections declared with `scope = "entity"`, which keep a separate credential for each client, can't be connected from **Settings → Extensions** yet. Use the default workspace scope, which shares one credential across the workspace. ## Run it How an extension runs depends on the triggers in its manifest. One extension can have all three. ### Events An event trigger runs the extension when something happens on an entity it's installed on: a journal is created, posted or voided, a bank transaction is reconciled, a file is uploaded, a GST period starts or a GST return changes status. Nobody has to do anything beyond their normal work — post the journal, reconcile the transaction, file the return. The [Triggers](/docs/extensions/triggers#events) page lists every event. ### Schedules A cron trigger runs the extension on its schedule, once for each entity it's installed on. Schedules are in UTC, so a 9am New Zealand run is `0 21 * * *` in winter. A new or changed schedule takes effect within a minute of deploying. ### Actions An action trigger adds an item to the Prosaic app. Where it appears depends on its `placement`: | Placement | Where it appears | | -------------------- | ------------------------------------------------------------------------------------------------------------- | | `transaction.single` | The actions menu on the Transactions page (⌘K or Ctrl+K), under **Extensions**, with one transaction selected | | `transaction.bulk` | The same menu with two or more transactions selected | | `report` | A button above the Profit and loss report | The item shows the action's `label`. It appears only on entities where the extension is installed and switched on. Clicking it runs the extension for that entity, with the selected transactions, or the report's dates, as its input. The person who clicked is the run's triggering user, so the extension can send email in the firm's name with replies going to them. The app shows _Running…_ and then _finished_, or _failed_ with the error the run ended on. If a run takes longer than three minutes, the app stops waiting and says it's still running; the result is under **Settings → Extensions**. ### Email replies An extension that sends a conversational email runs again when the recipient replies, with the reply as its input. Replies need no setup on the workspace's side. See [Replies](/docs/extensions/sandbox-api#replies). ## See what it did **Settings → Extensions** lists every extension in the workspace with its status, version, and how many installations and runs it has. Open one to see: - **Execution Flow** — its triggers and the scopes it holds. - **Connections** — the credentials it needs, as above. - **Installations** — each entity it's installed on, when, and a switch to turn it off and on. - **Recent Executions** — the last five runs, with trigger, status and how long each took. - **Bundle Code** — the code that actually runs. Deployed from the CLI, this is the built bundle; the source stays with the developer. The log lines an extension writes with `prosaic.log` aren't shown in the app. Read them with the CLI: ```bash prosaic extension logs --dir . --follow ``` Each run shows its status, ID, trigger and start time, every log line, and the error if it failed. A run that went over its time limit has the status `timeout`. See [Logs](/docs/extensions/testing-and-deploy#logs) for the flags. ## Pause it Turn an installation off with its switch under **Settings → Extensions → Installations**. While it's off, events and schedules skip that entity and its actions disappear from the app. Turn it back on the same way. Other entities' installations carry on. Deploying with `--entity-id` turns that entity's installation back on, so a developer redeploying to a test entity doesn't need the app. ## Update it A developer updates an extension by deploying again. The new code takes effect on every installation at once — there's no per-entity version and no history to roll back to, so rolling back means deploying the earlier code again. The manifest's `version` is shown in **Settings → Extensions** but is otherwise a label. ### Approve a wider extension When a deploy adds a scope, or a connection host, every installation made before it stops running for that entity. Events and schedules are skipped, and clicking one of its actions fails with `GRANT_REQUIRED`. Removing a scope never pauses anything. The installation is marked _Paused until you approve what it now asks for_, listing the new scopes and hosts. **Approve and resume** records the wider grant and starts it again. Deploying with `--entity-id` does the same for that one entity. ## Remove it There's no uninstall in the app or the CLI yet. To stop an extension running for an entity, turn its installation off. To delete it from the workspace entirely, email [support@prosaic.works](mailto:support@prosaic.works). Its runs are kept for audit. ## Next - [Triggers](/docs/extensions/triggers) — every event, the cron format and each action placement, with handlers. - [Testing and deploy](/docs/extensions/testing-and-deploy) — the `validate`, `dev`, `deploy` and `logs` loop. - [Examples](/docs/extensions/examples) — complete extensions to copy. --- # Manifest reference > Every field in prosaic.extension.toml — scopes, triggers, connections, validation. Source: https://developer.prosaic.works/docs/extensions/manifest The manifest is the contract between your extension and the platform. It declares who you are, what you can touch, and when you run. The runtime enforces every bit of it. ## Shape ```toml #:schema https://developer.prosaic.works/schemas/extension-manifest.json name = "my-extension" version = "0.0.1" description = "Optional one-liner" [scopes] required = ["read:transactions", "send:email"] # At least one trigger block below is required. [[targets.events]] type = "journal.posted" [targets.cron] schedule = "0 9 * * *" [[targets.actions]] placement = "transaction.single" label = "Analyse this transaction" ``` ## Validation in your editor The first line points TOML editors at the manifest's JSON Schema: ```toml #:schema https://developer.prosaic.works/schemas/extension-manifest.json ``` Editors built on [Taplo](https://taplo.tamasfe.dev/), such as the Even Better TOML extension for VS Code, read that line and check the file as you type: unknown scopes, misspelt event types, missing labels. `prosaic extension init` and the `scaffold_extension` MCP tool write it for you. To a TOML parser it is a comment, so the platform ignores it. The schema is generated from the same lists the validator uses, so the editor and `prosaic extension validate` agree. You can fetch it directly at `https://developer.prosaic.works/schemas/extension-manifest.json`. ## Top-level fields | Field | Required | Description | | ------------- | -------- | ------------------------------------------------------------------------------------------------------- | | `name` | Yes | Kebab-case by convention. Deploy finds the extension by this name, so keep it unique in your workspace. | | `version` | Yes | Any string; semver recommended. Shown in Settings → Extensions. | | `description` | No | Free-text. Appears alongside the name. | ## `[scopes]` Declare every permission you need. Calling a method your manifest didn't authorise throws `Permission denied: scope '…' is required to call prosaic.…`. Start minimal — you can add more on the next deploy. | Scope | Grants access to | | --- | --- | | `read:transactions` | `prosaic.transactions.list` and `.get` | | `write:transactions` | `prosaic.transactions.update` | | `read:journals` | `prosaic.journals.list` and `.get` | | `read:entities` | `prosaic.entities.list` and `.get` | | `send:email` | `prosaic.email.send` | | `use:ai` | `prosaic.ai.complete` (also extends execution timeout to 120s) | | `use:tools` | `prosaic.tools.list` and `.invoke` | | `use:http` | `prosaic.http.fetch` — outbound requests to a declared [[connections]] target | | `read:reports` | `prosaic.reports.list` and `.generate` — profit & loss, balance sheet, trial balance and the other financial reports | | `read:gst-returns` | `prosaic.gst.list` and `.get` — GST return status, periods and IRD box amounts | `prosaic.storage.*`, `prosaic.links.*` and `prosaic.log.*` need no scope — they're always available. `prosaic.tools.invoke` checks two scopes: `use:tools` for the call itself, and the scope of the tool you invoke. `accounts.list`, the entity's chart of accounts, needs `read:entities`. See [`prosaic.tools`](/docs/extensions/sandbox-api#prosaictools). ## Triggers You need at least one. You can mix them — an extension can have events, a cron, and action links all at once. ### `[[targets.events]]` Runs when a domain event fires on an entity the extension is installed on. Multiple event blocks are fine. ```toml [[targets.events]] type = "journal.posted" [[targets.events]] type = "transaction.reconciled" ``` | Event type | Fires when | `input` payload | | --- | --- | --- | | `journal.created` | A manual journal is created | `{ journalId: string, logicalJournalId: string }` | | `journal.posted` | A journal is posted (becomes final) | `{ journalId: string }` | | `journal.voided` | A journal is voided | `{ journalId: string, reversalJournalId: string }` | | `transaction.reconciled` | A bank transaction is matched to a journal | `{ transactionId: string, journalId: string }` | | `file.uploaded` | A file is uploaded to an entity | `{ fileId: string, filename: string }` | | `gst.period.rollover` | A new GST period starts (phase: 'started') or the previous period's return is finalised (phase: 'previous-finalised') | `{ phase: 'started' \| 'previous-finalised', gstReturnId: string, periodStart: string, periodEnd: string, dueDate: string, gstPeriodMonths: 1 \| 2 \| 6, previousReturnId: string \| null }` | | `gst.return.finalised` | A GST return is finalised (draft → finalised); its figures are locked | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | | `gst.return.reverted_to_draft` | A finalised or rejected GST return is reverted to draft | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | | `gst.return.filed` | A finalised GST return is filed with IRD (finalised → filed) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | | `gst.return.accepted` | IRD accepts a filed GST return (filed → accepted) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | | `gst.return.rejected` | IRD rejects a filed GST return (filed → rejected) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean, rejectionCode: string, rejectionMessage: string }` | | `gst.return.awaiting_payment` | An accepted GST return has an outstanding IRD balance (accepted → awaiting_payment) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean, balance: string }` | | `gst.return.completed` | A GST return reaches its end state — paid/settled (auto) or marked completed (manual) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | The payload arrives on `prosaic.context.input`, and `prosaic.context.trigger` is the event type. ### `[targets.cron]` Runs on a schedule. Standard 5-field Unix cron — minute, hour, day, month, weekday. All in UTC. ```toml [targets.cron] schedule = "0 9 * * *" # Every day at 09:00 UTC ``` Only one cron block per extension. It runs once per installation, so an extension installed on three entities runs three times. `prosaic.context.trigger` is `"cron"` and `prosaic.context.input` is empty. Some common patterns: | Schedule | Meaning | | -------------- | -------------------------------- | | `*/15 * * * *` | Every 15 minutes | | `0 * * * *` | Every hour on the hour | | `0 9 * * *` | Daily at 09:00 UTC | | `0 9 * * 1` | 09:00 UTC every Monday | | `0 9 1 * *` | 09:00 UTC on the 1st every month | ### `[[targets.actions]]` Adds a button to the Prosaic UI. Users click it, your extension runs. Good for one-off bulk jobs or "look at this thing" actions. ```toml [[targets.actions]] placement = "transaction.single" label = "Categorise with AI" [[targets.actions]] placement = "transaction.bulk" label = "Bulk categorise" ``` | Placement | Shows up | `input` payload | | --- | --- | --- | | `transaction.single` | In the detail view of a single transaction | `{ placement: "transaction.single", transactionId: string }` | | `transaction.bulk` | On the transaction list after multi-selecting rows | `{ placement: "transaction.bulk", transactionIds: string[] }` | | `report` | Above the Profit and loss report | `{ placement: "report", reportType: "profit-loss", entityId: string, startDate: string, endDate: string }` | `label` is the button text — keep it short. `prosaic.context.trigger` is `"action.link"`. ## `[[connections]]` A connection declares a third-party API your extension calls with [`prosaic.http.fetch`](/docs/extensions/sandbox-api#prosaichttpfetch). Declaring one requires the `use:http` scope. A workspace admin connects it from the extension's page under **Settings → Extensions**, by entering the credential (or, for `oauth2`, the third party's client ID and secret, then authorising) — see [Connect outside services](/docs/extensions/using-extensions#connect-outside-services). Prosaic stores the credential and attaches it to each request on the server, so your code never holds it. ```toml [scopes] required = ["use:http", "read:transactions"] [[connections]] name = "acme" label = "Acme CRM" auth = "bearer" base_url = "https://api.acme.example" allowed_hosts = ["api.acme.example"] [[connections.fields]] key = "token" label = "API token" secret = true ``` | Field | Required | Description | | --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `name` | Yes | Lowercase kebab-case, starting with a letter, up to 64 characters. You pass it to `http.fetch`. | | `label` | Yes | Shown to the admin who connects it. | | `description` | No | Shown alongside the label. | | `auth` | Yes | `bearer`, `basic`, `header` or `oauth2` — see below. | | `base_url` | Yes | An `https://` URL. Request paths resolve against it. | | `allowed_hosts` | Yes | Hosts requests may reach. `*.example.com` matches subdomains but not `example.com` itself. Must cover the `base_url` host. | | `scope` | No | `workspace` (the default) shares one credential across the workspace; `entity` keeps one per entity and uses the one for the run's entity, but can't be connected from Settings yet. | | `fields` | Depends | `[[connections.fields]]` blocks, each with `key` and `label`, and optionally `secret`, `required` and `placeholder`. | What each `auth` strategy sends, and what it needs declared: | `auth` | Sends | Declare | | -------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `bearer` | `Authorization: Bearer {token}` | A field with `key = "token"` | | `basic` | `Authorization: Basic base64(username:password)` | Fields `username` and `password` | | `header` | A header you name, such as `X-Api-Key: {api_key}` | `[connections.header]` with `name` and `template`; each `{placeholder}` must be a field key | | `oauth2` | `Authorization: Bearer `, refreshed | `[connections.oauth2]` with `authorize_url` and `token_url` (optional `scopes`, `pkce`, `audience`); no fields. Both URLs' hosts must be in `allowed_hosts` | ## Validation `prosaic extension validate`, `prosaic extension deploy` and the `validate_extension_manifest` MCP tool all run the same checks: - `name` and `version` are required. - Every scope must be one of the scopes listed above. Typos fail. - Every event `type` must be one of the events listed above. - Cron schedules must have exactly 5 fields. - Every action must have a valid `placement` and a non-empty `label`. - At least one of `targets.events`, `targets.cron`, or `targets.actions` is required — no trigger, no extension. - Every connection needs a valid `name`, a `label`, a known `auth`, an `https` `base_url` and at least one allowed host, and declaring any connection requires `use:http`. When you deploy, Prosaic also checks each connection's strategy against its fields (a `bearer` connection without a `token` field is refused, for example) and that `allowed_hosts` covers every URL the connection uses. Check locally before deploying: ```bash prosaic extension validate --dir . ``` ## Full example — AI categorisation suggestions ```toml #:schema https://developer.prosaic.works/schemas/extension-manifest.json name = "categorisation-suggestions" version = "0.1.0" description = "Suggest accounts for selected transactions using AI" [scopes] required = [ "read:transactions", "read:entities", "use:tools", "use:ai", ] [[targets.actions]] placement = "transaction.single" label = "Suggest an account" [[targets.actions]] placement = "transaction.bulk" label = "Suggest accounts" ``` Two buttons, four scopes. `read:entities` and `use:tools` together let it read the chart of accounts through `prosaic.tools.invoke('accounts.list', {})`. The handler is in [Triggers](/docs/extensions/triggers#handler-recipe--suggest-accounts-for-selected-transactions). --- # Sandbox API > The prosaic.* global — every method your extension can call. Source: https://developer.prosaic.works/docs/extensions/sandbox-api Inside the sandbox, everything you need hangs off one global: `prosaic`. No imports, no setup, no `require`. The runtime injects it before your code runs. Top-level `await` works — the runtime wraps your code in an async function. Top-level `return` does not: the CLI bundles your code as an ES module, and the build rejects it. Put early exits inside a function: ```typescript async function main(): Promise { const { input } = prosaic.context; if (!input?.transactionId) return; const txn = await prosaic.transactions.get(input.transactionId); prosaic.log.info('Transaction', { id: txn.id, amount: txn.amount }); } await main(); ``` Every call returns a promise and throws on failure, so `try`/`catch` works as you'd expect. A call your manifest has no scope for throws `Permission denied: scope '…' is required to call prosaic.…`. Extensions read the books; they don't write journals. There is no method to create, edit or void a journal. To post journals from your own server, use the [public API](/docs/ledger/journals). ## `prosaic.context` What triggered this run and where it's scoped to. ```typescript prosaic.context.trigger; // The event type, "cron", "action.link" or "email.reply" prosaic.context.input; // Trigger-specific payload; undefined for cron prosaic.context.entityId; // The entity this run is for prosaic.context.workspaceId; // The workspace the extension belongs to prosaic.context.executionId; // This run's ID, as shown in the logs prosaic.context.config; // Per-installation settings object ({} when none are set) ``` The shape of `input` depends on the trigger — see the [Manifest reference](/docs/extensions/manifest) for each event's and placement's payload. Installs made with `prosaic extension deploy` have an empty `config`. ## `prosaic.log` Captured in execution records and shown by `prosaic extension logs`. Use it liberally — it's cheap and it's the only window you get when things go sideways. ```typescript prosaic.log.info('Started processing', { journalId: 'j_123' }); prosaic.log.warn('Missing tax code, using default'); prosaic.log.error('Upstream failure', { status: 502 }); ``` The second argument is structured data, printed as JSON alongside the message. No scope needed. ## `prosaic.transactions` Bank transactions on the run's entity. Scope: `read:transactions` for `list` and `get`, `write:transactions` for `update`. ```typescript // The 50 most recent, newest first. Filter on reconciliation status. const { data, totalCount } = await prosaic.transactions.list({ isReconciled: false, }); // One transaction, with every field const txn = await prosaic.transactions.get(data[0].id); // Change its description await prosaic.transactions.update(txn.id, { description: 'Office supplies — Warehouse Stationery', }); ``` `list` returns each transaction's `id`, `bankAccountId`, `entityId`, `date`, `type`, `amount`, `description`, `balance`, `particulars`, `code`, `reference` and `createdAt`. `isReconciled` is the only filter. `update` changes `description`. Other fields are dropped or rejected, and it does not reconcile anything. Amounts are decimal strings — Prosaic uses arbitrary-precision decimals. Parse them with a decimal library rather than `Number()` if you do arithmetic on money. Dates are ISO strings in UTC, and an accounting date is stored as midnight in the entity's timezone, so `date.slice(0, 10)` gives the day before in New Zealand and Australia. Format them with `new Date(date).toLocaleDateString('en-CA', { timeZone: entity.timezone })` instead (`en-CA` gives `YYYY-MM-DD`). ## `prosaic.journals` Journals on the run's entity, read-only. Scope: `read:journals`. ```typescript // The 100 most recent, newest first const { data, totalCount } = await prosaic.journals.list(); // One journal, or null when it isn't on this entity const journal = await prosaic.journals.get(prosaic.context.input.journalId); prosaic.log.info('Journal', { date: journal.date, narration: journal.narration, status: journal.status, }); ``` Both return the journal header — `id`, `date`, `narration`, `status`, `type`, `postedAt`, `logicalJournalId` and the like. Lines aren't included. ## `prosaic.entities` Entities the workspace can access. Scope: `read:entities`. ```typescript const entity = await prosaic.entities.get(prosaic.context.entityId); prosaic.log.info('Entity', { name: entity.name, country: entity.countryCode, currency: entity.currency, }); const { data, totalCount } = await prosaic.entities.list(); // Up to 50 ``` `get` returns `null` for an entity the workspace can't access. ## `prosaic.reports` Financial reports for the run's entity. Scope: `read:reports`. ```typescript const types = await prosaic.reports.list(); // [{ type: 'profit-loss', name: 'Profit & Loss', requiredParams: [], optionalParams: [...] }, ...] const profitLoss = await prosaic.reports.generate('profit-loss', { periodType: 'last-month', }); const trialBalance = await prosaic.reports.generate('trial-balance', { asOfDate: '2026-06-30', }); ``` The report types are `profit-loss`, `balance-sheet`, `trial-balance`, `current-accounts`, `depreciation-schedule`, `general-ledger-account` and `general-ledger-transaction`. `reports.list()` returns each one's required and optional parameters. `generate` returns the same JSON as the matching [public API report](/docs/ledger/reports). Reports are fetched through the public API as the user who created the extension, so they show what that user can see. ## `prosaic.gst` GST returns for the run's entity: status, periods and IRD box amounts. Scope: `read:gst-returns`. ```typescript const { data: returns } = await prosaic.gst.list({ status: ['draft', 'finalised'], }); const gstReturn = await prosaic.gst.get(returns[0].id); ``` `list` takes the same filters as the public API's GST returns list: `status`, `dateFrom`, `dateTo`, `dueAfter`, `dueBefore` and `includeFutureDrafts`. Like reports, these calls run as the extension's creator. ## `prosaic.email.send` Scope: `send:email`. Sends from `extensions@prosaic.works`, shown as `" via Prosaic"`. ```typescript const { threadId } = await prosaic.email.send({ to: 'client@example.com', subject: 'Your GST return is ready', text: 'Hi,\n\nThe March GST return is prepared. Reply to this email with any questions.', }); await prosaic.storage.set(`thread:${threadId}`, { status: 'awaiting-reply' }); ``` | Field | Required | Notes | | ----------- | -------------- | ----------------------------------------------------- | | `to` | Yes | One address, or an array of up to 10 | | `subject` | Yes | | | `text` | One of the two | Plain-text body | | `html` | One of the two | HTML body. Send both if you like. | | `emailMode` | No | `"conversational"` (the default) or `"outbound-only"` | | `onBehalf` | No | Send as the firm — see below | It returns `{ threadId, messageId, replyToAddress }`. Attachments aren't supported — host the file elsewhere and link to it. ### Replies A conversational email gets a Reply-To address that routes back to Prosaic. When the recipient replies, your extension runs again with `prosaic.context.trigger` set to `"email.reply"` and this `input`: ```typescript const { threadId, // The threadId email.send returned fromAddress, subject, textBody, htmlBody, conversationHistory, // Up to 50 messages: direction, fromAddress, subject, textBody, sentAt } = prosaic.context.input; ``` Check the trigger at the top of your code so a reply doesn't send the first email again. `outbound-only` emails have no Reply-To, and replies to them don't reach your extension. ### Sending on behalf of the firm Set `onBehalf: true` to render the email with the firm's logo and name. The sender display becomes `"" `, the body is wrapped in a branded shell matching the client-invitation email, and Reply-To goes to the user who triggered the extension. ```typescript await prosaic.email.send({ to: 'client@example.com', subject: 'Please send your commission statements', text: 'A new GST period has started — please reply with your latest commission statements.', emailMode: 'outbound-only', onBehalf: true, }); ``` Constraints (the call is rejected otherwise): - `emailMode` can't be `"conversational"`. Leave it out or set `"outbound-only"`. Replies go to a person, not back to your extension. - The run must have a triggering user. Action links and events a person caused, such as `journal.posted`, have one. Cron runs, `email.reply` runs and the `started` phase of `gst.period.rollover` don't. - HTML you supply is sanitised before it goes inside the firm's shell — scripts, iframes, inline event handlers, `javascript:` URLs and unknown tags are stripped. ## `prosaic.ai.complete` Scope: `use:ai`. Calls a large language model through Prosaic's account — no API key or billing setup of your own. ```typescript const result = await prosaic.ai.complete({ messages: [ { role: 'system', content: 'You suggest chart-of-accounts categories. Reply with the category only.', }, { role: 'user', content: "Transaction description: 'STRIPE PAYOUT'" }, ], }); prosaic.log.info('AI response', { text: result.content }); ``` | Field | Required | Notes | | ----------- | -------- | ------------------------------------------------------------------------------------------------- | | `messages` | Yes | `{ role, content }` objects; `role` is `system`, `user` or `assistant` | | `maxTokens` | No | Defaults to 4096. Reasoning models spend some of it before they answer, so don't set it very low. | | `model` | No | Prosaic picks a default. A workspace can limit which models are allowed. | | `tools` | No | `{ name, description, parameters }` definitions the model may call | It returns `{ content, model, toolCalls, usage, finishReason }`, where `usage` is `{ inputTokens, outputTokens, totalTokens, cachedInputTokens }`. `content` is `null` when the model only called tools. A workspace can set a token budget; once it's spent, calls throw `AI token budget exceeded for this workspace`. `use:ai` also extends your execution timeout from 10 seconds to 120 seconds. If you're doing anything iterative, the extra budget matters. ## `prosaic.http.fetch` Scope: `use:http`. Makes one request to a third-party API you declared as a [connection](/docs/extensions/manifest#connections) in your manifest. Prosaic attaches the connection's credential on the server; your code never sees it. ```typescript const res = await prosaic.http.fetch({ connection: 'acme', path: '/v1/contacts', method: 'POST', body: { name: 'Kauri Joinery Ltd' }, }); if (!res.ok) { prosaic.log.error('Acme refused the contact', { status: res.status, body: res.body, }); } ``` | Field | Required | Notes | | ------------ | -------- | ---------------------------------------------------------------------------- | | `connection` | Yes | The connection's `name` from the manifest | | `path` | Yes | Resolved against the connection's `base_url` | | `method` | No | `GET`, `POST`, `PUT`, `PATCH`, `DELETE` or `HEAD` | | `headers` | No | Up to 20. You can't set `Authorization`. | | `body` | No | JSON-serialisable, up to 1 MB | | `timeoutMs` | No | Defaults to 10,000; at most 30,000. Your run's own time limit still applies. | It returns `{ status, ok, headers, body }`. `body` is parsed when the response is JSON and raw text otherwise. A third party's error status comes back here with `ok: false` rather than throwing. The call throws when Prosaic refuses the request: an undeclared connection, one nobody has connected yet, a host outside `allowed_hosts`, a private network address, a response over 2 MB, or more than the per-extension rate limit (120 requests a minute by default). Like reports, outbound requests need the extension's creator, so they fail for an extension that has none. ## `prosaic.links` Remembers which record in another system matches which record in Prosaic, so a sync can update rather than duplicate. Links are scoped to your extension and the run's entity. No scope needed. ```typescript const key = `transaction:${txn.id}`; const existing = await prosaic.links.get(key); // { externalId, externalUrl, contentHash, metadata, updatedAt }, or null await prosaic.links.set(key, { externalId: 'C-1042', // Required externalUrl: 'https://crm.acme.example/contacts/C-1042', contentHash: 'sha256-of-what-you-sent', metadata: { pushedBy: prosaic.context.executionId }, }); await prosaic.links.delete(key); ``` Store a hash of what you last sent in `contentHash` and compare it next run to skip records that haven't changed. ## `prosaic.storage` A key-value store that persists across runs. No scope needed. Values are JSON-serialisable. ```typescript await prosaic.storage.set('lastRunDate', '2026-04-19'); const lastRun = await prosaic.storage.get('lastRunDate'); // null when unset await prosaic.storage.delete('lastRunDate'); ``` Storage belongs to the extension, not the installation: every entity the extension is installed on reads and writes the same keys. Prefix keys with `prosaic.context.entityId` when they're per entity. Good for cursors (where did I leave off?), dedup ("have I seen this ID?"), and small bits of state. Not a database — keep values small. ## `prosaic.tools` Scope: `use:tools`, plus the scope of the tool you invoke. Invokes a tool from Prosaic's tool registry by name. ```typescript const tools = await prosaic.tools.list(); // [{ name, description, parameters }, ...] // The entity's chart of accounts. Needs read:entities as well as use:tools. const accounts = await prosaic.tools.invoke('accounts.list', {}); // [{ id, code, name, type, taxCode }, ...] ordered by code ``` The tools available to extensions are `accounts.list`, `transactions.list`, `transactions.get`, `transactions.update`, `entities.list`, `entities.get`, `journals.list`, `journals.get` and `email.send`. Apart from `accounts.list` they mirror the methods above, so call those directly. A tool's arguments go in the second parameter — `transactions.get` takes `{ id }`. `tools.list()` returns each tool's JSON Schema. A workspace can restrict which tools are enabled; invoking a disabled one throws. ## Constraints Everything runs in a V8 isolate. That buys safety, and it costs a few things you might reach for: - **128 MB memory** per execution. Keep object graphs small. - **10 second timeout** (120 seconds with `use:ai`). Break long jobs over a cron. - **No `fetch`**. Outbound HTTP goes through `prosaic.http.fetch`, and only to hosts you declared. - **No filesystem, no Node APIs**. `require`, `process`, `fs`, `child_process` — none of them exist. - **No runtime imports**. The CLI bundles `src/index.ts` with esbuild into a single ES module. If you need a library, import it normally at dev time and it'll be bundled in. Bundles are capped at 5 MB. If you hit a wall against any of these, the odds are the problem wants to be smaller or split over multiple runs. Tell us at [support@prosaic.works](mailto:support@prosaic.works) if you need something the sandbox doesn't allow. --- # Triggers > Events, cron, and action links — with handler recipes for each. Source: https://developer.prosaic.works/docs/extensions/triggers Every extension has to declare at least one trigger. You can mix them freely — an extension can react to three events, run nightly on cron, and expose an action button, all from the same manifest. This page covers the three trigger families and shows a real handler for each. `prosaic.context.trigger` tells your code which one fired: the event type, `"cron"` or `"action.link"`. Replies to emails your extension sent arrive as a fourth, `"email.reply"` — see [Replies](/docs/extensions/sandbox-api#replies). ## Events The platform emits events when domain things happen. If an event matches your manifest and the extension is installed on that entity, the runtime queues an execution. Declared like this: ```toml [[targets.events]] type = "journal.posted" [[targets.events]] type = "transaction.reconciled" ``` The full list: | Event type | Fires when | `input` payload | | --- | --- | --- | | `journal.created` | A manual journal is created | `{ journalId: string, logicalJournalId: string }` | | `journal.posted` | A journal is posted (becomes final) | `{ journalId: string }` | | `journal.voided` | A journal is voided | `{ journalId: string, reversalJournalId: string }` | | `transaction.reconciled` | A bank transaction is matched to a journal | `{ transactionId: string, journalId: string }` | | `file.uploaded` | A file is uploaded to an entity | `{ fileId: string, filename: string }` | | `gst.period.rollover` | A new GST period starts (phase: 'started') or the previous period's return is finalised (phase: 'previous-finalised') | `{ phase: 'started' \| 'previous-finalised', gstReturnId: string, periodStart: string, periodEnd: string, dueDate: string, gstPeriodMonths: 1 \| 2 \| 6, previousReturnId: string \| null }` | | `gst.return.finalised` | A GST return is finalised (draft → finalised); its figures are locked | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | | `gst.return.reverted_to_draft` | A finalised or rejected GST return is reverted to draft | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | | `gst.return.filed` | A finalised GST return is filed with IRD (finalised → filed) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | | `gst.return.accepted` | IRD accepts a filed GST return (filed → accepted) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | | `gst.return.rejected` | IRD rejects a filed GST return (filed → rejected) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean, rejectionCode: string, rejectionMessage: string }` | | `gst.return.awaiting_payment` | An accepted GST return has an outstanding IRD balance (accepted → awaiting_payment) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean, balance: string }` | | `gst.return.completed` | A GST return reaches its end state — paid/settled (auto) or marked completed (manual) | `{ gstReturnId: string, status: string, periodStart: string, periodEnd: string, dueDate: string, netGstPosition: string \| null, isAmendment: boolean }` | ### Handler recipe — react to journal.posted ```toml name = "journal-posted-notifier" version = "0.0.1" [scopes] required = ["read:journals", "read:entities", "send:email"] [[targets.events]] type = "journal.posted" ``` ```typescript const { input, entityId } = prosaic.context; const journal = await prosaic.journals.get(input.journalId); const entity = await prosaic.entities.get(entityId); // The date is midnight in the entity's timezone, stored as UTC. const date = new Date(journal.date).toLocaleDateString('en-CA', { timeZone: entity.timezone ?? 'Pacific/Auckland', }); await prosaic.email.send({ to: 'accountant@example.com', subject: `Journal posted — ${entity.name}`, text: `A journal dated ${date} was posted.\n\n${journal.narration}`, emailMode: 'outbound-only', }); ``` ### Handler recipe — chase commission statements when a new GST period starts `gst.period.rollover` fires twice through the GST lifecycle. Filter on `input.phase` to pick a moment: - `'started'` — fires on day 1 (NZ time) of a new period, when the draft return is created. There is no triggering user, so this phase cannot use `email.send` with `onBehalf: true`. - `'previous-finalised'` — fires when someone finalises the prior period's return. The person who finalised it is the triggering user. ```toml name = "commission-statement-chaser" version = "0.0.1" [scopes] required = ["read:entities", "send:email"] [[targets.events]] type = "gst.period.rollover" ``` ```typescript const CLIENT_EMAIL = 'client@example.com'; // Your client's address async function main(): Promise { const { trigger, input, entityId } = prosaic.context; // The client's reply runs this extension again. if (trigger === 'email.reply') { prosaic.log.info('Client replied', { from: input.fromAddress, subject: input.subject, }); return; } if (input.phase !== 'started') return; const entity = await prosaic.entities.get(entityId); const localDate = (iso: string): string => new Date(iso).toLocaleDateString('en-CA', { timeZone: entity.timezone ?? 'Pacific/Auckland', }); await prosaic.email.send({ to: CLIENT_EMAIL, subject: 'New GST period — please send your commission statements', text: `Hi ${entity.name},\n\nA new GST period started on ${localDate(input.periodStart)} (due ${localDate(input.dueDate)}). Please reply with your latest commission statements when ready.\n\nThanks.`, }); } await main(); ``` ### Gotchas - **Each matching event gets its own execution.** If you have two `[[targets.events]]` blocks and both fire, your code runs twice. - **Events are per entity.** An extension only fires for entities it's installed on. - **Order isn't guaranteed.** If you need ordering, track it yourself in `storage`. - **Errors in your code aren't retried.** The run is recorded as failed, with your logs and the error. The queue does retry a job when the platform itself fails, so make handlers safe to run twice — a dedupe key in `storage` is usually enough. ## Cron Runs on a schedule. One cron block per extension, five-field Unix syntax, all UTC. ```toml [targets.cron] schedule = "0 9 * * *" # 09:00 UTC daily ``` A cron runs once for each entity the extension is installed on. `prosaic.context.input` is undefined — the trigger is the schedule itself. `context.entityId` says which entity this run is for, and every `prosaic.*` call is already scoped to it. ### Handler recipe — daily unreconciled summary ```toml name = "daily-unreconciled-summary" version = "0.0.1" [scopes] required = ["read:transactions", "read:entities", "send:email"] [targets.cron] schedule = "0 20 * * 0-4" # 08:00 or 09:00 NZ time, Monday to Friday ``` ```typescript async function main(): Promise { const { data, totalCount } = await prosaic.transactions.list({ isReconciled: false, }); if (totalCount === 0) { prosaic.log.info('Nothing unreconciled, skipping email'); return; } const entity = await prosaic.entities.get(prosaic.context.entityId); const timeZone = entity.timezone ?? 'Pacific/Auckland'; const lines = data .slice(0, 20) .map((t) => { const date = new Date(t.date).toLocaleDateString('en-CA', { timeZone }); return `• ${date} ${t.amount} ${t.description}`; }) .join('\n'); await prosaic.email.send({ to: 'client@example.com', subject: `${totalCount} unreconciled transactions`, text: `The 20 most recent:\n\n${lines}`, emailMode: 'outbound-only', }); } await main(); ``` ### Schedule cheatsheet | Schedule | Runs | | -------------- | -------------------------------- | | `*/15 * * * *` | Every 15 minutes | | `0 * * * *` | Every hour on the hour | | `0 9 * * *` | 09:00 UTC daily | | `0 9 * * 1-5` | 09:00 UTC weekdays | | `0 9 * * 1` | 09:00 UTC every Monday | | `0 9 1 * *` | 09:00 UTC on the 1st every month | | `0 0 1 */3 *` | Midnight UTC every quarter-start | Schedules are in UTC, so convert from local time. New Zealand is UTC+12, or UTC+13 in daylight saving; eastern Australia is UTC+10, or UTC+11. A morning run in either country is the previous evening in UTC, which is why the recipe above uses `0-4` (Sunday to Thursday in UTC) for Monday to Friday locally. ## Action links A button in the Prosaic UI. User clicks, your extension runs. Good for "look at this thing" or "do this thing to these things" flows. ```toml [[targets.actions]] placement = "transaction.single" label = "Analyse this" [[targets.actions]] placement = "transaction.bulk" label = "Analyse selected" ``` | Placement | Shows up | `input` payload | | --- | --- | --- | | `transaction.single` | In the detail view of a single transaction | `{ placement: "transaction.single", transactionId: string }` | | `transaction.bulk` | On the transaction list after multi-selecting rows | `{ placement: "transaction.bulk", transactionIds: string[] }` | | `report` | Above the Profit and loss report | `{ placement: "report", reportType: "profit-loss", entityId: string, startDate: string, endDate: string }` | In the app, the transaction actions are listed under **Extensions** in the Transactions page's actions menu (⌘K or Ctrl+K): `transaction.single` with one transaction selected, `transaction.bulk` with two or more. The `report` button appears above the Profit and loss report, and its `input` also carries `reportType: "profit-loss"`, `entityId`, and the report's `startDate` and `endDate` as `YYYY-MM-DD`. [Using extensions](/docs/extensions/using-extensions#actions) shows what the person clicking sees. The person who clicked is the triggering user, so action links can send email with `onBehalf: true`. ### Handler recipe — suggest accounts for selected transactions This uses the manifest from the [Manifest reference](/docs/extensions/manifest#full-example--ai-categorisation-suggestions): `read:transactions`, `read:entities`, `use:tools` and `use:ai`, with a single and a bulk button. ```typescript async function main(): Promise { const { input, entityId } = prosaic.context; const ids: string[] = input?.transactionIds ?? (input?.transactionId ? [input.transactionId] : []); if (ids.length === 0) { prosaic.log.warn('No transactions selected'); return; } // The chart of accounts is only reachable through the tool registry. const accounts = await prosaic.tools.invoke('accounts.list', {}); const chart = accounts.map((a) => `${a.code}: ${a.name}`).join('\n'); for (const id of ids.slice(0, 20)) { const txn = await prosaic.transactions.get(id); const { content } = await prosaic.ai.complete({ messages: [ { role: 'system', content: `Pick the best account for a bank transaction from this chart of accounts. Reply with the account code only.\n\n${chart}`, }, { role: 'user', content: `${txn.description} (${txn.amount})` }, ], }); const code = content?.trim() ?? ''; prosaic.log.info('Suggested account', { transactionId: id, description: txn.description, code, }); await prosaic.storage.set(`${entityId}:suggestion:${id}`, code); } } await main(); ``` The suggestions land in the execution logs and in `storage`. Extensions can't reconcile a transaction or post a journal, so a person applies the suggestion in Prosaic. ### Gotchas - **The extension must be installed on the entity, and switched on.** Otherwise the action doesn't show. - **Bulk selections can be long.** Hundreds of IDs is possible. Cap how many you process (the recipe takes 20) so you stay inside the time limit, and page the rest over later runs if you need to. - **Labels matter.** They're what users click. "Run my-extension" ages badly — make the label a verb that describes the action. - **Buttons get clicked twice.** Make the handler safe to repeat. ## Picking the right trigger Rough rule of thumb: - Reactive to a domain event? **Event**. - Periodic, no user in the loop? **Cron**. - User in the loop, triggered on demand? **Action link**. - Waiting for someone to answer an email? Send a conversational email and handle **`email.reply`**. - Two of the above? Declare both. They coexist happily. --- # Testing and deploy > The CLI workflow — validate, dev, deploy, logs, and how versioning works. Source: https://developer.prosaic.works/docs/extensions/testing-and-deploy Every iteration loop uses the same four CLI commands: `validate`, `dev`, `deploy`, `logs`. Once you've got them in your fingers the feedback loop is fast — save a file and your new code is deployed moments later. ## Validate locally Before you deploy anything, check the manifest is sound: ```bash prosaic extension validate --dir . ``` This parses `prosaic.extension.toml`, runs the same manifest checks as `deploy`, and does a trial build of `src/` with esbuild to catch bundler errors. No network calls, no auth needed. What it catches: - Missing or invalid `name`, `version`. - Unknown scopes, unknown event types, unknown action placements. - Broken cron schedules. - Missing labels on actions. - No triggers declared at all. - Incomplete `[[connections]]` blocks, or connections without the `use:http` scope. - esbuild errors in `src/`, including a top-level `return`. Run it any time you touch the manifest. It's fast. ## Deploy ```bash prosaic extension deploy --dir . --entity-id ``` One command, full pipeline: 1. Validate (as above). 2. Bundle `src/index.ts` with esbuild into a single ES module with no runtime imports. 3. Look the extension up by `name` in your workspace: create it on the first run, update its manifest and scopes after that. 4. Upload the bundle. Prosaic records its SHA-256 hash. 5. Install it on the given entity, or refresh the installation if it's already there. Deploying with `--entity-id` (including every save in `dev`) re-enables that entity's installation if it was turned off. Deploying needs the workspace admin role. When you deploy, Prosaic also checks each connection's auth strategy against its fields and allowed hosts, which the local validator doesn't. Flags worth knowing: | Flag | Default | What it does | | ------------- | ------- | ----------------------------------------------------------------- | | `--dir` | `.` | Project directory containing `prosaic.extension.toml` | | `--entity-id` | — | Install on this entity too. Omit it to update the extension only. | ## The `dev` loop ```bash prosaic extension dev --dir . --entity-id ``` `dev` deploys once, then watches `src/` and the manifest. When you save, it runs the full deploy again. It also polls execution logs every 3 seconds and prints them in your terminal, so you see the result soon after your trigger fires. Flow: 1. Edit `src/index.ts` 2. Save 3. The CLI notices the change and redeploys 4. Trigger the event (post a journal, click the button, wait for cron…) 5. Watch the logs print Press `Ctrl+C` to stop. The deployed version stays — `dev` deploys the real extension, not a separate dev build. ## Logs After a run has happened, pull the history: ```bash prosaic extension logs --limit 20 ``` Or let the CLI find the extension from the manifest in your project: ```bash prosaic extension logs --dir . --follow ``` | Flag | Default | What it does | | ---------- | ------- | ----------------------------------------- | | `--follow` | false | Poll for new executions every 3 seconds | | `--limit` | 10 | How many executions to show | | `--dir` | — | Read the extension name from the manifest | Each execution shows its status, ID, trigger and start time, any log lines you wrote, and — if the run failed — the error. ## Versioning `version` in the manifest is a string, and it's yours to manage. The platform shows it in **Settings → Extensions** and does nothing else with it. Bumping it is a convention for tracking what's deployed, not a runtime constraint. A reasonable approach: - Bump the patch (`0.0.1` → `0.0.2`) when you ship a bugfix. - Bump the minor (`0.1.0`) when you change behaviour. - Bump the major when you widen what the extension can do (more scopes, more hosts). Rolling back is manual — deploy the earlier code again. There's no version history on the platform; use your own source control. ## Widening permissions Each installation records the scopes and hosts it was installed with. If a deploy adds a scope, or a connection host, the installations made before it stop running until someone re-installs them and accepts the new permissions. Event and cron runs are skipped without an entry in `prosaic extension logs`; clicking an action link fails with `GRANT_REQUIRED`. Deploying with `--entity-id` re-installs that one entity; re-install the others from **Settings → Extensions**. Removing a scope never pauses anything. ## Testing before deploy The sandbox is hard to replicate locally because of the `prosaic.*` global and the bridge behind it. The realistic workflow is: 1. Write the code. 2. `prosaic extension validate --dir .` catches manifest issues and build errors. 3. `prosaic extension dev` against a test entity. Trigger the event, watch the logs. 4. Only when that works, install it on a real client entity. There's no published type declaration for the `prosaic` global yet, so `tsc` reports it as an unknown name. Rely on `validate` and the logs rather than a strict type-check. If you have more than one workspace, keep a dedicated "dev" workspace and entity for this. Deploying broken code against a client is always uncomfortable. ## Disabling and uninstalling - **Disable on an entity** — turn the installation off from **Settings → Extensions**. The extension stays in the workspace and stops running for that entity. Turn it back on the same way. - **Delete the extension** — removes it from the workspace entirely. Only Prosaic can do this today, so email [support@prosaic.works](mailto:support@prosaic.works). Executions are kept for audit. There's no CLI command for either yet. Deploying without `--entity-id` doesn't uninstall anything; it just skips the install step. [Using extensions](/docs/extensions/using-extensions) covers the rest of what a workspace sees and does once an extension is deployed. ## Tips that save time - Start with `--trigger event` even if you'll end up on cron. The input payload makes events easier to debug. - Put `prosaic.log.info('context', prosaic.context)` as the first line of any new handler. You'll thank yourself when something surprising lands in `input`. - Use `storage.get/set` for dedupe. Action links can be double-clicked, and the queue retries a job when the platform fails. - Keep the bundle small. Bundles are capped at 5 MB; aim for well under 500 KB. --- # Examples > Worked examples — copy, tweak, deploy. Source: https://developer.prosaic.works/docs/extensions/examples Reading reference docs is fine. Reading a working extension is better. Each full example below is a complete project: create the two files, change a bit, deploy it. ## Action link demo **What it shows**: the action-link trigger — single and bulk placements, reading transactions, logging a summary. **Scopes**: `read:transactions` `prosaic.extension.toml`: ```toml #:schema https://developer.prosaic.works/schemas/extension-manifest.json name = "action-link-demo" version = "0.0.1" description = "Reads selected transactions and logs a summary" [scopes] required = ["read:transactions"] [[targets.actions]] placement = "transaction.single" label = "Describe transaction" [[targets.actions]] placement = "transaction.bulk" label = "Summarise transactions" ``` `src/index.ts`: ```typescript const { input } = prosaic.context; if (input?.transactionId) { const txn = await prosaic.transactions.get(input.transactionId); prosaic.log.info('Transaction details', { id: txn.id, date: txn.date, description: txn.description, amount: txn.amount, }); } if (input?.transactionIds) { const ids = input.transactionIds as string[]; prosaic.log.info(`Processing ${ids.length} transactions`); for (const id of ids.slice(0, 10)) { const txn = await prosaic.transactions.get(id); prosaic.log.info(`${txn.description}: ${txn.amount}`); } if (ids.length > 10) { prosaic.log.info(`... and ${ids.length - 10} more`); } } ``` Deploy it against a test entity: ```bash prosaic extension deploy --dir . --entity-id ``` Then click the button on a transaction — the execution shows up in `prosaic extension logs`. ## Large-transaction alerts in Slack **What it shows**: an event trigger, a `[[connections]]` declaration, `prosaic.http.fetch`, and dedupe with `storage`. **Scopes**: `read:transactions`, `read:entities`, `use:http` `prosaic.extension.toml`: ```toml #:schema https://developer.prosaic.works/schemas/extension-manifest.json name = "large-transaction-alerts" version = "0.0.1" description = "Posts to Slack when a large transaction is reconciled" [scopes] required = ["read:transactions", "read:entities", "use:http"] [[targets.events]] type = "transaction.reconciled" [[connections]] name = "slack" label = "Slack" description = "A Slack bot token with the chat:write scope" auth = "bearer" base_url = "https://slack.com" allowed_hosts = ["slack.com"] [[connections.fields]] key = "token" label = "Bot token" secret = true ``` `src/index.ts`: ```typescript const CHANNEL = '#bookkeeping'; const THRESHOLD = 10000; async function main(): Promise { const { input, entityId } = prosaic.context; const seenKey = `${entityId}:slack:${input.transactionId}`; if (await prosaic.storage.get(seenKey)) return; const txn = await prosaic.transactions.get(input.transactionId); if (Math.abs(Number(txn.amount)) < THRESHOLD) return; // The date is midnight in the entity's timezone, stored as UTC. const entity = await prosaic.entities.get(entityId); const date = new Date(txn.date).toLocaleDateString('en-CA', { timeZone: entity.timezone ?? 'Pacific/Auckland', }); const res = await prosaic.http.fetch({ connection: 'slack', path: '/api/chat.postMessage', method: 'POST', body: { channel: CHANNEL, text: `Reconciled: ${txn.description} for ${txn.amount} on ${date}`, }, }); // Slack reports most failures in the body of a 200 response. if (!res.ok || !(res.body as { ok?: boolean }).ok) { prosaic.log.error('Slack refused the message', { status: res.status, body: res.body, }); return; } await prosaic.storage.set(seenKey, true); } await main(); ``` After you deploy, a workspace admin opens the extension under **Settings → Extensions** and enters the bot token. Until then, `http.fetch` throws because the connection isn't connected. ## Sketches These are shapes rather than finished projects. Each uses only methods and scopes that exist today. ### Monthly profit and loss email (cron + reports + email) Runs on the 1st of each month. Calls `prosaic.reports.generate('profit-loss', { periodType: 'last-month' })`, picks out the totals, and emails them to the client. Scopes: `read:reports`, `send:email`. ### AI account suggestions (action link + tools + AI) Select transactions, click the button. The extension reads the chart of accounts with `prosaic.tools.invoke('accounts.list', {})`, asks `prosaic.ai.complete` for the best account for each, and logs the suggestions for a person to apply. The full handler is in [Triggers](/docs/extensions/triggers#handler-recipe--suggest-accounts-for-selected-transactions). Scopes: `read:transactions`, `read:entities`, `use:tools`, `use:ai`. ### GST return filed notice (event + GST + email) React to `gst.return.filed`. Fetch the return with `prosaic.gst.get(input.gstReturnId)` and email the client the period, the net GST position and the due date. Scopes: `read:gst-returns`, `send:email`. ### Client reply handler (email + storage) Send a conversational email asking a client for documents, and record the `threadId` in `storage`. When they reply, the extension runs with `prosaic.context.trigger === 'email.reply'`; look the thread up, log what they said, and mark it answered. Scopes: `send:email`. ## Build your own The fastest path from idea to deployed extension is [Build with an LLM](/docs/extensions/llm-tools) — describe what you want, let Claude or Cursor scaffold it, deploy. If you've got a pattern you'd like us to ship as an example, drop a note at [support@prosaic.works](mailto:support@prosaic.works). --- # Build with an LLM > Let Claude, Cursor, or ChatGPT scaffold your extension from a sentence. Source: https://developer.prosaic.works/docs/extensions/llm-tools The extension system is built so an LLM can drive it. Every doc on this site is available as Markdown, there's an `llms.txt` index for discovery, and two Prosaic MCP servers expose tools that scaffold and validate extensions on demand. If you use Claude, Cursor, Claude Code or ChatGPT, you can describe what you want in plain English and get a working extension back. [Build with AI](/docs/ai/build-with-ai) covers the same tools for the rest of the platform. ## Option 1: point an LLM at the docs The lowest-friction path. Tell your model: > Build me a Prosaic extension that emails me a summary whenever a journal is posted. Fetch https://developer.prosaic.works/llms.txt first so you know the schema. `llms.txt` is a short index of every page on this site. Your model follows the links, reads the manifest and sandbox docs, and writes the code. Every page is also available as Markdown by adding `.md` to its URL, for example `https://developer.prosaic.works/docs/extensions/manifest.md`. If the model supports long context and you'd rather skip the per-link fetches, point it at the extension docs in one file: > Read https://developer.prosaic.works/docs/extensions/llms-full.txt — everything's there. ## Option 2: connect an MCP server If your client supports MCP, connect a Prosaic server and the model gets tools built for extension work. Both servers carry the same extension tools: | Server | URL | Sign-in | What else it has | | ------------- | ------------------------------------- | -------------------- | -------------------------------------------------------------- | | `prosaic-dev` | `https://developer.prosaic.works/mcp` | None | Search these docs, look up API operations | | `prosaic` | `https://mcp.prosaic.works/mcp` | Your Prosaic account | Your books: entities, transactions, journals, reports and more | For building an extension, `prosaic-dev` is enough, and there's nothing to log in to. In Claude Code: ```bash claude mcp add --transport http prosaic-dev https://developer.prosaic.works/mcp ``` Setup for Cursor, VS Code and Claude.ai is in [Build with AI](/docs/ai/build-with-ai#the-developer-mcp-server). Connect `prosaic` as well if you want the model to look at real data while it works — the chart of accounts, recent transactions — so its code matches your books. ## Extension tools Once a server is connected, your LLM can call: ### `list_extension_scopes` Returns every scope your manifest can declare, with what each one grants. No input. Useful when the model needs to decide what permissions to request. ### `list_extension_triggers` Returns every trigger type — events, the cron format, action placements — with the exact `input` payload shape for each. No input. The model uses this to match the right trigger to your request. ### `scaffold_extension` Input: ```json { "name": "my-extension", "trigger": "event", "scopes": ["read:journals", "send:email"], "description": "Emails a summary when a journal is posted" } ``` `trigger` is `event`, `cron`, `action-link` or `manual`. Returns `files`, a map of file paths to contents — manifest, `src/index.ts`, `package.json`, `tsconfig.json` — and the next steps. It's the same scaffold `prosaic extension init` writes, so the manifest starts with the `#:schema` line. Nothing is deployed. ### `validate_extension_manifest` Input: `{ "manifestToml": "" }`. Returns `{ valid, errors }`, where each error has a `field` and a `message`, using the same validator the CLI runs. Good for "I wrote this by hand, did I miss anything?" ### `get_extension_reference` No input. Returns the full extension docs inline. Useful when the LLM can't fetch URLs but does have MCP. ## What the flow looks like With an MCP server connected, a typical session goes: 1. You say: _"Build me an extension that posts to Slack when a transaction over $10,000 is reconciled."_ 2. The model calls `list_extension_triggers`, sees `transaction.reconciled`, and picks it. 3. It calls `list_extension_scopes` and settles on `read:transactions` and `use:http`. 4. It calls `scaffold_extension` with `{ name, trigger: "event", scopes: ["read:transactions", "use:http"] }`. 5. It writes the files to disk, changes the event to `transaction.reconciled`, adds a `[[connections]]` block for Slack, and edits `src/index.ts` to call `prosaic.http.fetch` — much like the [Slack example](/docs/extensions/examples#large-transaction-alerts-in-slack). Then it calls `validate_extension_manifest` to check the TOML. 6. You run `prosaic extension deploy --dir . --entity-id `, and a workspace admin enters the Slack token under **Settings → Extensions**. Most of that happens while the model streams its plan at you. You read the code, approve, deploy. ## Rough edges - **Deploy is still a CLI command.** The MCP tools scaffold and validate — they don't deploy. That's deliberate for now. If you want it added, let us know. - **The model can't run your code.** There's no local sandbox. Deploy to a test entity and read `prosaic extension logs`. - **No web fetch in some clients.** If your LLM can't fetch URLs, use `get_extension_reference` instead of linking `llms-full.txt`. ## Without MCP You don't need MCP for any of this — `llms.txt` works with every model that can fetch a URL. MCP just makes the loop tighter. Start with the docs-only path, and add `prosaic-dev` when you want scaffold and validate in the conversation.