# Prosaic docs (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 every Prosaic developer doc, 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. # Overview > What Prosaic is, the ways to build on it, and when it is the right fit. Source: https://developer.prosaic.works/docs/getting-started/overview 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. You send journals. Prosaic keeps the books: the chart of accounts, GST-coded lines, the trial balance, profit and loss and balance sheet. The same books open in the Prosaic app, where an accountant can review them, correct them and, in New Zealand, file the GST return. ## Where things stand Australia is in early access. The ledger, AU GST tax codes, an AU chart of accounts, AUD and a 1 July financial year work today. AU bank feeds and BAS are coming. ## The pieces A few words come up on every page: - **Workspace** — your Prosaic account. It has users, chart-of-accounts templates and a country, and it holds entities. - **Entity** — one set of books for one business. Each entity has its own chart of accounts, tax rates, currency and financial year. - **Chart of accounts** — the entity's accounts, each with a code such as `4030`. Journal lines name accounts by code. - **Tax rate** — the entity's GST codes, such as `NZ_GST_15_EXP`. Every journal line with an amount carries one. - **Journal** — a balanced set of debit and credit lines on a date. Posted journals are what the reports read. ## Ways to build ### Embed the ledger Use the REST API or the Node SDK to give your product a real general ledger. The usual shape is one entity per end customer, all inside your own platform workspace, in the way a payments platform holds one connected account per merchant. [Embedded ledger](/docs/ledger/embedded-ledger) walks through the model, and the [quickstart](/docs/getting-started/quickstart) takes you from an API key to a posted journal and a trial balance. ### Connect to accountants If your product serves businesses whose accountants already use Prosaic, register an OAuth app. A user approves your app, and it then works in the books they can reach, with their permissions. See [OAuth apps](/docs/apps/oauth-apps). ### Automate with extensions Extensions are small TypeScript programs that Prosaic hosts and runs in a sandbox: when something happens in the books, on a schedule, or from a button in the app. They are the low-code option, with no servers for you to run. See [Extensions](/docs/extensions/overview). ### Build with AI Every page on this site is also published as Markdown, with an index at [`llms.txt`](/llms.txt) and the full text at [`llms-full.txt`](/llms-full.txt). Two MCP servers sit alongside it: - `https://developer.prosaic.works/mcp` lets a coding agent search these docs and the API reference, and scaffold and validate extensions. It needs no sign-in. - `https://mcp.prosaic.works/mcp` lets an AI assistant work in a user's own books once they sign in with OAuth. See [Build with AI](/docs/ai/build-with-ai). ## Is Prosaic a good fit? Good fit: - Software for New Zealand or Australian businesses that needs a real general ledger (journals, chart of accounts, trial balance, P&L, balance sheet) without building one. - Embedded accounting in vertical SaaS, point of sale, marketplaces and fintech. - GST-coded bookkeeping, and NZ GST returns. - Connecting your product to NZ accounting firms' Prosaic workspaces through OAuth apps. - Low-code automation with sandboxed TypeScript extensions. - AI agents that read and write the books over MCP. Not a fit today: - Businesses outside New Zealand and Australia. - Multi-currency or foreign exchange. An entity keeps its books in one currency: NZD in New Zealand, AUD in Australia. - AU BAS preparation and ATO lodgement. Both are coming. - Payroll. Prosaic does not run pay; post payroll journals from your payroll system instead. - Push notifications to your servers. There are no outbound webhooks, so poll the API for changes. ## Next steps - [**Quickstart**](/docs/getting-started/quickstart) — an API key, an entity, a journal and a trial balance. - [**Authentication**](/docs/getting-started/authentication) — API keys, OAuth, and choosing a workspace. - [**Node SDK**](/docs/sdk/node) — install it and learn its conventions. - [**API reference**](/docs/api) — every endpoint, with the [OpenAPI document](/openapi.json) behind it. Questions? Write to [developer@prosaic.works](mailto:developer@prosaic.works). --- # Quickstart > From an API key to a posted journal and a trial balance, with the Node SDK or curl. Source: https://developer.prosaic.works/docs/getting-started/quickstart This walks through the core loop: create an entity, post a balanced journal to it, and read the trial balance back. Each step is shown with the [Node SDK](/docs/sdk/node) and with curl. ## Before you start - **A Prosaic workspace.** Sign up at [app.prosaic.works/signup](https://app.prosaic.works/signup). A new workspace starts on a 14-day trial, is set to New Zealand, and comes with a couple of demo entities you can ignore. For an Australian workspace, which is in early access, write to [developer@prosaic.works](mailto:developer@prosaic.works). - **For the SDK:** Node.js 22 or later, and the SDK installed from its tarball as described in [Node SDK](/docs/sdk/node#install). It is not on npm yet. - **For curl:** nothing else. ## 1. Create an API key API keys are created in the Prosaic app by a workspace owner or admin. 1. Go to **Settings → Users**. 2. Find the user the key should act as (often yourself), open the **Actions** menu (⋯) and choose **Manage API keys**. 3. Choose **Create API Key**, give it a name and an expiry, and copy the key. It starts with `prsk_` and is shown only once. Keep it in your server environment: ```bash export PROSAIC_API_KEY="prsk_..." ``` A key acts as its user, with that user's access. [Authentication](/docs/getting-started/authentication) covers the details, including OAuth. ## 2. Check the key works `GET /me` returns the user the key belongs to and the workspaces they are in. ```ts import Prosaic from 'prosaic-node'; const apiKey = process.env.PROSAIC_API_KEY; if (!apiKey) throw new Error('Set PROSAIC_API_KEY first.'); const prosaic = new Prosaic(apiKey); const { data: me } = await prosaic.me.retrieve(); console.log( me.email, me.workspaces.map((w) => `${w.name} (${w.id})`), ); ``` ```bash curl https://app.prosaic.works/api/public/v1/me \ -H "Authorization: Bearer $PROSAIC_API_KEY" ``` If the user belongs to more than one workspace, requests go to the one they last used in the app. Send `x-workspace-id` (or set `workspaceId` on the SDK client) to choose another. ## 3. List your entities An entity is one set of books. Your new workspace already has its demo entities. ```ts for await (const entity of prosaic.entities.list()) { console.log(entity.id, entity.name, entity.currency); } ``` ```bash curl https://app.prosaic.works/api/public/v1/entities \ -H "Authorization: Bearer $PROSAIC_API_KEY" ``` ## 4. Pick a chart of accounts template A new entity's accounts are copied from a template. Every workspace starts with a standard chart for its country (`Standard NZ Business Template` or `Standard AU Business Template`) plus Company, Trust, Sole Trader and Partnership charts. ```ts const templates = await prosaic.charts.list().autoPagingToArray({ limit: 50 }); const standard = templates.find((t) => t.name.startsWith('Standard')); if (!standard) throw new Error('No standard template in this workspace.'); ``` ```bash curl https://app.prosaic.works/api/public/v1/charts \ -H "Authorization: Bearer $PROSAIC_API_KEY" ``` Note the `id` of the template you want. ## 5. Create an entity `name`, `type` and `accountTemplateId` are required. `type` is one of `individual`, `company`, `trust`, `partnership`, `rental` or `other`. ```ts const { data: entity } = await prosaic.entities.create({ name: 'Kowhai Cafe Ltd', type: 'company', accountTemplateId: standard.id, }); console.log(entity.id); ``` ```bash curl -X POST https://app.prosaic.works/api/public/v1/entities \ -H "Authorization: Bearer $PROSAIC_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Kowhai Cafe Ltd", "type": "company", "accountTemplateId": "YOUR_TEMPLATE_ID" }' ``` The response wraps the entity in `data`. The entity takes its country, currency and financial year from the workspace. It is not GST registered unless you say so; [Tax in NZ and AU](/docs/ledger/tax-nz-au) covers the GST fields. ## 6. Find account codes and a tax rate Journal lines name each account by its `code`, and each line with an amount needs a `taxRateId`. **Account codes** come from the entity's chart of accounts: ```ts const accounts = await prosaic.entityAccounts .list(entity.id) .autoPagingToArray({ limit: 500 }); for (const account of accounts) { console.log(account.code, account.name, account.type); } ``` ```bash curl https://app.prosaic.works/api/public/v1/entities/YOUR_ENTITY_ID/charts \ -H "Authorization: Bearer $PROSAIC_API_KEY" ``` In the standard templates, `4030` is Office Expense and `8220` is Accounts Payable. Templates can be edited, so check your own chart. **Tax rate IDs** are on the entity itself, in `taxRates[]`, both in the create response and in `GET /entities?entityId=YOUR_ENTITY_ID`. This journal carries no GST, so use the "No GST" rate: `NZ_GST_0_NONE` in New Zealand, `AU_GST_0_NONE` in Australia. ```ts const noGst = entity.taxRates.find((rate) => rate.code === 'NZ_GST_0_NONE'); if (!noGst) throw new Error('No "No GST" rate on this entity.'); ``` ```bash curl "https://app.prosaic.works/api/public/v1/entities?entityId=YOUR_ENTITY_ID" \ -H "Authorization: Bearer $PROSAIC_API_KEY" ``` ## 7. Post a balanced journal Debits must equal credits. Send amounts as decimal strings, and put each line's amount on one side only. Journals are posted straight away unless you send `autoPost: false`. ```ts const journal = await prosaic.journals.create(entity.id, { date: '2026-10-01', narration: 'Office supplies, supplier invoice 1042', taxMode: 'NO_TAX', lines: [ { entityAccountCode: '4030', taxRateId: noGst.id, debit: '115.00' }, { entityAccountCode: '8220', taxRateId: noGst.id, credit: '115.00' }, ], }); console.log(journal.id, journal.status); // status is "posted" ``` ```bash curl -X POST https://app.prosaic.works/api/public/v1/entities/YOUR_ENTITY_ID/journals \ -H "Authorization: Bearer $PROSAIC_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "date": "2026-10-01", "narration": "Office supplies, supplier invoice 1042", "taxMode": "NO_TAX", "lines": [ { "entityAccountCode": "4030", "taxRateId": "YOUR_NO_GST_RATE_ID", "debit": "115.00" }, { "entityAccountCode": "8220", "taxRateId": "YOUR_NO_GST_RATE_ID", "credit": "115.00" } ] }' ``` Unlike most endpoints, journal creation returns the journal itself rather than a `data` envelope. Keep its `logicalJournalId`: voiding the journal or attaching files to it later takes that ID. [Journals](/docs/ledger/journals) covers GST on lines, drafts, voids and attachments. ## 8. Read the trial balance ```ts const trialBalance = await prosaic.reports.trialBalance(entity.id, { asOfDate: '2026-10-31', }); console.log(trialBalance.totals); // totalDebits, totalCredits, isBalanced, variance ``` ```bash curl "https://app.prosaic.works/api/public/v1/entities/YOUR_ENTITY_ID/trial-balance?asOfDate=2026-10-31" \ -H "Authorization: Bearer $PROSAIC_API_KEY" ``` Reports return plain objects, not a `data` envelope. Amounts come back as decimal strings; use a decimal library such as Decimal.js for any arithmetic on them. `accountGroups` holds the per-account lines, signed as debits minus credits. ## What next - [**Embedded ledger**](/docs/ledger/embedded-ledger) — one entity per customer, and giving their accountant access. - [**Journals**](/docs/ledger/journals) — every field, GST handling, drafts and voids. - [**Reports**](/docs/ledger/reports) — P&L, balance sheet, general ledger and more. - [**API reference**](/docs/api) — every endpoint, with its SDK method. --- # Authentication > API keys, OAuth 2.1 with PKCE, choosing a workspace, and keeping credentials safe. Source: https://developer.prosaic.works/docs/getting-started/authentication Every request to `https://app.prosaic.works/api/public/v1` carries a credential. There are two kinds: - **API keys**, for your own server-side integration. This is what an embedded ledger uses. - **OAuth access tokens**, for an app that other Prosaic users connect to their own workspaces. Both are sent the same way, and both act as a Prosaic user. ## API keys Workspace owners and admins create keys in the Prosaic app: **Settings → Users**, then the user's **Actions** menu (⋯), then **Manage API keys**. The [quickstart](/docs/getting-started/quickstart#1-create-an-api-key) has the steps. A key starts with `prsk_`, is shown once when it is created, and has an expiry date. The same dialog lists a user's keys and deletes them. Send the key as a bearer token: ```bash curl https://app.prosaic.works/api/public/v1/me \ -H "Authorization: Bearer prsk_..." ``` An `x-api-key: prsk_...` header is accepted too. The SDK uses the bearer form: ```ts import Prosaic from 'prosaic-node'; const prosaic = new Prosaic(process.env.PROSAIC_API_KEY!); ``` ### What a key can reach A key acts as the user it was created for. It can reach every workspace that user belongs to, and within a workspace it sees what their role allows: - **Workspace owners and admins** see every entity in the workspace. - **Advisors** see only the entities they have been given access to. - **Client** and **standard user** roles cannot use the API with a key. Creating entities needs an owner, admin or advisor role. Journals and other changes made with the key are recorded against its user. For an integration, consider a dedicated user so its activity is easy to tell apart from a person's. An entity the key cannot see returns `404`, not `403`, so the API does not reveal that it exists. ## Choosing a workspace A user can belong to several workspaces. Each request acts in one of them: 1. The workspace named in the `x-workspace-id` header, if you send one. If the user is not a member of it, the request fails with `403` and `Not a member of requested workspace`. 2. Otherwise, the workspace the user last switched to in the app, or their first workspace if they are no longer in that one. `GET /me` lists the user's workspaces and their IDs. With the SDK, set `workspaceId` on the client or on a single call: ```ts const prosaic = new Prosaic(apiKey, { workspaceId: 'YOUR_WORKSPACE_ID' }); const { data: me } = await prosaic.me.retrieve({ workspaceId: 'ANOTHER_WORKSPACE_ID', }); ``` Choosing a workspace never widens what the user can do. Send `x-workspace-id` whenever the user is in more than one workspace, so a change of workspace in the app cannot redirect your integration. ## OAuth 2.1 with PKCE Use OAuth when your app acts for other Prosaic users, such as accountants connecting their firm's workspace to your product. Prosaic uses the authorization-code flow with PKCE, and the code challenge must use `S256`. - **Scopes:** `openid`, `profile`, `email`, and `offline_access` to receive a refresh token. - **Lifetimes:** access tokens last 24 hours; refresh tokens last 30 days. - **Discovery:** `https://app.prosaic.works/.well-known/oauth-authorization-server` An access token is sent exactly like an API key, `Authorization: Bearer ...`, and acts as the user who approved your app, with that user's access. Workspace selection works the same way. [OAuth apps](/docs/apps/oauth-apps) covers registering an app, the full flow, and the review policy for apps connected to many workspaces. The [Node SDK](/docs/sdk/node#oauth) has helpers for PKCE, token exchange and refresh. ## Errors you may see | Status | When | | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `401` | No credential, or one that is invalid, expired or deleted. | | `403` | Not a member of the workspace in `x-workspace-id`; the workspace's trial has expired (`TRIAL_EXPIRED`); or the user has a client role (`CLIENT_API_ACCESS_DISABLED`). | | `404` | The entity does not exist, or the credential cannot see it. | ## Keep credentials on your server - Keep API keys and OAuth client secrets out of browser bundles, mobile apps and source control. Load them from your server's environment or a secrets manager. - Call Prosaic from your backend, never directly from a user's browser. - Use HTTPS. The SDK refuses a non-HTTPS `baseUrl` unless it is a loopback address for local development. - Rotate keys before they expire: create the new key, deploy it, then delete the old one. - Keep validation details from error responses out of public logs; they can contain accounting data. --- # Embedded ledger > Run your customers' books on Prosaic: a platform workspace, one entity per customer, and their accountant working alongside. Source: https://developer.prosaic.works/docs/ledger/embedded-ledger The embedded model gives every one of your customers a real set of double-entry books without you building a ledger. It works like connected accounts on a payments platform: you hold one platform account, and each of your customers is an account inside it. ```text Your platform workspace (one per country) ├── API key ──────────────► your backend ├── Entity: Kowhai Cafe Ltd ◄── your customer #1 ├── Entity: Harbour Physio Ltd ◄── your customer #2 └── Entity: ... ◄── one per customer ▲ └── their accountant, invited as an advisor with access to that entity ``` Your customers do not need Prosaic logins. Your backend writes to their books with your API key, and their accountant can work in the same books in the Prosaic app. ## The platform workspace Sign up at [app.prosaic.works/signup](https://app.prosaic.works/signup). The workspace you get is your platform workspace: it holds your users, your API keys, your chart-of-accounts templates and your customers' entities. Create your integration's API key for a user who is a workspace owner or admin. A key acts as its user, and owners and admins see every entity in the workspace, including the ones the key creates. See [Authentication](/docs/getting-started/authentication). ## One workspace per country An entity's country is not chosen per entity. It comes from its workspace, and so does everything that follows from the country: | | New Zealand workspace | Australian workspace | | -------------- | ----------------------------- | ----------------------------- | | Currency | NZD | AUD | | Financial year | Starts 1 April | Starts 1 July | | Timezone | Pacific/Auckland | Australia/Sydney | | GST codes | NZ 15% codes | AU 10% codes | | Standard chart | Standard NZ Business Template | Standard AU Business Template | | GST returns | Yes | Not yet (BAS is coming) | If you serve both countries, run two platform workspaces, one each, and route each customer to the right one. A user who is a member of both can use one API key and pick the workspace per request with `x-workspace-id`. New sign-ups get a New Zealand workspace. Australia is in early access: write to [developer@prosaic.works](mailto:developer@prosaic.works) for an Australian workspace before you create entities in it. A workspace's region is set when it is created, and changing it later is a support request. ## One entity per customer When a customer signs up to your product, create an entity for them and store its `id` against your customer record. ```ts const { data: entity } = await prosaic.entities.create({ name: customer.legalName, type: 'company', // individual, company, trust, partnership, rental or other accountTemplateId: STANDARD_TEMPLATE_ID, isGstRegistered: customer.gstRegistered, gstNumber: customer.gstNumber, // NZ: 9 digits. AU: the 11-digit ABN. }); await db.customers.update(customer.id, { prosaicEntityId: entity.id }); ``` - **Chart of accounts.** The entity's accounts are copied from the template you name. Use one of the seeded templates, or build your own with `charts.create` so every customer starts with the accounts your product posts to. See [Chart of accounts](/docs/ledger/chart-of-accounts). - **GST.** An entity not marked GST registered has every account defaulted to its country's "No GST" code. [Tax in NZ and AU](/docs/ledger/tax-nz-au) lists the GST fields, including the ones that switch on NZ GST returns. - **Tax rates.** The entity is created with its country's tax rates. Their IDs are in `taxRates[]` on the entity; cache them alongside the entity ID, because every journal line needs one. ## Writing to the books - **Journals** are the main write: one balanced journal per business event you record, such as a sale, a payout or a fee. See [Journals](/docs/ledger/journals). - **Bank lines.** `bankAccounts.createWithTransactions` creates a bank account fed by imported files and loads statement lines into it; `bankAccounts.importTransactions` adds lines to an existing one. `importTransactions` skips lines the account already holds, with the same date, amount and description, so re-sending an overlapping batch to an existing account is safe. `createWithTransactions` always creates a new account, so after an uncertain failure check the entity's `bankAccounts[]` before retrying. Imported lines are then reconciled in the app or with `transactions.reconcile`. - **Invoices and contacts** have their own endpoints ([`invoices.create`](/docs/api/invoices#invoices-create), [`contacts.create`](/docs/api/contacts#contacts-create)). See the [API reference](/docs/api). Read the results back with the [report endpoints](/docs/ledger/reports): trial balance, P&L, balance sheet and the general ledger. ## Avoiding double-posting Journal creation has no idempotency key, and the SDK never retries a write on its own. A `4xx` response means nothing was written. But if a create fails without a clear answer (a timeout, a dropped connection or a `5xx`), the journal may or may not exist. Check before you try again: 1. Put your own reference in the journal's `narration`, for example `Order 10442`. 2. Once a create succeeds, store the returned `logicalJournalId` against your record, and skip records that already have one. 3. After an uncertain failure, list the entity's journals around that date and look for your reference before posting again. ```ts import { APIError, ConnectionError, type JournalsCreateParams, } from 'prosaic-node'; async function postJournalOnce( entityId: string, reference: string, params: JournalsCreateParams, ): Promise { try { const journal = await prosaic.journals.create(entityId, params); return journal.logicalJournalId; } catch (error) { const uncertain = error instanceof ConnectionError || (error instanceof APIError && error.status >= 500); if (!uncertain) throw error; // The outcome is unknown. Look before posting again. for await (const journal of prosaic.journals.list(entityId, { dateFrom: dayBefore(params.date), dateTo: dayAfter(params.date), })) { if (journal.narration.includes(reference)) return journal.logicalJournalId; } const journal = await prosaic.journals.create(entityId, params); return journal.logicalJournalId; } } ``` `dayBefore` and `dayAfter` stand in for your own date helpers. Search a day either side of the journal date, because the list's date filters do not yet adjust for the entity's timezone. `TimeoutError` is a kind of `ConnectionError`, so the check covers timeouts too. ## Giving a customer's accountant access Many of your customers will have an accountant. You can let them into that customer's books, and only that customer's: 1. In the Prosaic app, go to **Settings → Users → Add new user**. 2. Enter the accountant's name and email, choose the **Advisor** role, and select the customer's entity under **Entity Access**. 3. Prosaic invites them by email. They sign in and switch to your workspace to see the entity. An advisor can work with the entities they have been given (transactions, journals and reports) but cannot see your other customers or manage users. Change which entities they can reach later from the Users table, under **Actions → Entity access**. Do not make an outside accountant an admin: admins see every entity in the workspace. Not yet available: - Inviting users or granting entity access through the API. It is done in the app. - Moving an entity into the accountant's own firm workspace, or sharing it with another workspace. The entity stays in your platform workspace. --- # Journals > Post balanced journals with account codes and tax rates, handle GST, keep drafts for review, void and attach files. Source: https://developer.prosaic.works/docs/ledger/journals A journal is a dated set of debit and credit lines that balance. It is the main way to write to an entity's books. ```text POST /api/public/v1/entities/{entityId}/journals prosaic.journals.create(entityId, params) ``` ## A journal with GST This records a $100 office expense plus 15% GST, owed to a supplier. With `taxMode: 'TAX_EXCLUSIVE'`, each line's amount is before GST, and Prosaic adds the GST when it posts. ```ts const journal = await prosaic.journals.create(entityId, { date: '2026-10-01', narration: 'Stationery, supplier invoice 1042', taxMode: 'TAX_EXCLUSIVE', lines: [ { entityAccountCode: '4030', // Office Expense taxRateId: gstOnExpensesId, // NZ_GST_15_EXP debit: '100.00', description: 'Printer paper and toner', }, { entityAccountCode: '8220', // Accounts Payable taxRateId: noGstId, // NZ_GST_0_NONE credit: '115.00', }, ], }); ``` ```bash curl -X POST https://app.prosaic.works/api/public/v1/entities/YOUR_ENTITY_ID/journals \ -H "Authorization: Bearer $PROSAIC_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "date": "2026-10-01", "narration": "Stationery, supplier invoice 1042", "taxMode": "TAX_EXCLUSIVE", "lines": [ { "entityAccountCode": "4030", "taxRateId": "GST_ON_EXPENSES_RATE_ID", "debit": "100.00", "description": "Printer paper and toner" }, { "entityAccountCode": "8220", "taxRateId": "NO_GST_RATE_ID", "credit": "115.00" } ] }' ``` When it posts, the journal has three lines: $100 to Office Expense, a generated $15 GST line to the entity's GST account, and $115 to Accounts Payable. ## Request fields | Field | Required | Notes | | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `date` | Yes | `YYYY-MM-DD`, a calendar day in the entity's own timezone. | | `narration` | Yes | 1 to 300 characters. Put your own reference here; see [avoiding double-posting](/docs/ledger/embedded-ledger#avoiding-double-posting). | | `lines` | Yes | The journal lines. A posted journal needs at least two lines with an amount. | | `taxMode` | No | `NO_TAX`, `TAX_EXCLUSIVE` or `TAX_INCLUSIVE`. Leaving it out behaves like `NO_TAX`. | | `autoPost` | No | Defaults to `true`, which posts the journal. `false` saves a draft. | | `fileIds` | No | Uploaded files to attach. See [attachments](#attachments). | Each line: | Field | Notes | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `entityAccountCode` | The account's `code` from the entity's [chart of accounts](/docs/ledger/chart-of-accounts). Required on a line with an amount. | | `taxRateId` | An `id` from the entity's `taxRates[]` (see [Tax in NZ and AU](/docs/ledger/tax-nz-au)). Required on a line with an amount. | | `debit` or `credit` | A decimal string such as `"115.00"` (numbers are accepted too). Zero or positive. Use one side per line. | | `description` | Optional, up to 200 characters. | | `dimensionOptionIds` | Optional tracking categories; see [dimensions](#dimensions). | Lines with nothing on either side are dropped. An unknown account code or tax rate ID is rejected with `400`. ### Amounts - Send amounts as decimal strings and do your sums with a decimal library such as Decimal.js, not floating point. - Never send a negative amount to flip a line's direction. A negative number is rejected, and in a string the minus sign is stripped, so `"-50.00"` is read as `50.00` on the side you put it. Move the amount to the other side instead. - Strings are cleaned of currency formatting, so `"$1,000.00"` is read as `1000.00`. Prefer plain digits anyway. ## Balancing and GST A posted journal must balance to within one cent. How the check counts GST depends on `taxMode`: | `taxMode` | Line amounts are | At posting | | --------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `NO_TAX` | Final | Nothing is added. Debits must equal credits as sent. | | `TAX_EXCLUSIVE` | Before GST | For each line whose tax rate is above 0%, a GST line is added to the entity's GST account. Debits must equal credits once GST is added. | | `TAX_INCLUSIVE` | Including GST | GST is split out of each taxed line into a GST line, so the line keeps its net amount. Debits must equal credits as sent. | So with `TAX_INCLUSIVE`, the example above would send `"115.00"` on both lines, and post as the same three lines. Check the balance before you send. An unbalanced journal is refused when it posts, nothing is saved, and today the API reports it as `500 Failed to create journal` rather than a `400`. ## Drafts and posted journals - **Posted** (`autoPost` left out or `true`): the journal is in the ledger and the reports straight away. The response's `status` is `posted`. - **Draft** (`autoPost: false`): saved with `status` `draft`, without the balance check and without GST lines. Drafts are not in the reports. Someone reviews and posts them in the Prosaic app; the API cannot post a draft. Drafts are the simplest review step: your product writes drafts, and the customer's accountant posts them. ## The response Journal creation returns the journal itself, not a `data` envelope: - `id` is this version of the journal. - `logicalJournalId` identifies the journal across versions. **Voiding and attaching files take this ID**, so store it. - `date` is an instant: the start of the journal's day in the entity's timezone, in UTC. A New Zealand journal dated `2026-10-01` comes back as `2026-09-30T11:00:00.000Z`. - `lines` includes any generated GST lines, each with `entityAccount` and `taxRate`. Amounts are decimal strings. - `attachments` lists attached files. ## Listing journals ```ts for await (const journal of prosaic.journals.list(entityId, { dateFrom: '2026-09-30', // the day before: dateFrom is compared with UTC midnight dateTo: '2026-10-31', })) { console.log(journal.logicalJournalId, journal.narration, journal.status); } ``` `GET /entities/{entityId}/journals` returns manual journals, newest first, a page at a time (`page`, `pageSize`). It does not include journals Prosaic creates itself, such as bank reconciliations. The date filters compare against UTC midnight rather than the entity's day. In New Zealand and Australia that misses journals dated on `dateFrom` itself, so pass the day before. `dateTo` already includes its own day. For every posted line, from every source, use the [general ledger](/docs/ledger/reports#general-ledger). ## Voiding a journal ```ts await prosaic.journals.void(entityId, journal.logicalJournalId!); ``` ```bash curl -X PATCH https://app.prosaic.works/api/public/v1/entities/YOUR_ENTITY_ID/journals/YOUR_LOGICAL_JOURNAL_ID/void \ -H "Authorization: Bearer $PROSAIC_API_KEY" ``` Only posted journals can be voided. Voiding marks the journal `voided` and posts a reversal on the same date. The reports then leave both out; the general ledger shows them when you pass `includeVoided=true`. Journals that belong to an invoice or record a payment cannot be voided this way (`409`); undo those through the invoice or the bank transaction. There is no endpoint to edit a posted journal or to delete a draft. To correct a posted journal, void it and post a new one. ## Attachments Attach receipts, invoices and other evidence. First upload the file to the entity, then attach it, either when you create the journal or afterwards. ```ts import { readFile } from 'node:fs/promises'; const bytes = await readFile('receipt-1042.pdf'); const upload = await prosaic.files.upload( entityId, new File([bytes], 'receipt-1042.pdf', { type: 'application/pdf' }), ); // When creating the journal: await prosaic.journals.create(entityId, { ...params, fileIds: [upload.file.id], }); // Or on an existing journal: await prosaic.journals.attachFiles(entityId, logicalJournalId, { fileIds: [upload.file.id], }); ``` Uploads are `multipart/form-data` with a `file` field, up to 20 MB. Set the file's type: PDF, JPEG, PNG, GIF, WebP, CSV, plain text, Excel, Word and Outlook MSG are accepted, and anything else is refused with `415`. `files.list(entityId)` lists files already on the entity. ## Dimensions Dimensions are tracking categories, such as Property or Department. `dimensions.list(entityId)` returns the entity's dimensions and their options. Tag a line with `dimensionOptionIds`, at most one option per dimension. Options from another entity, or two from the same dimension, are rejected with `400`. ## Change-sets `POST /entities/{entityId}/change-sets` (`prosaic.changeSets.create`) records proposed writes (journals to post, bank transactions to reconcile) as a pending change-set instead of writing them. Nothing reaches the ledger until the set is approved, and resubmitting identical content returns the existing set. A change-set's journal lines name accounts by `entityAccountId` and take amounts as numbers, unlike `journals.create`. Change-sets were built for AI agents, and today approval happens in Prosaic's own review tooling rather than in your workspace. For a review step that you and your customers' accountants control, use [drafts](#drafts-and-posted-journals). --- # Chart of accounts > Templates, an entity's own accounts, system accounts, and adding or changing accounts. Source: https://developer.prosaic.works/docs/ledger/chart-of-accounts Every entity has its own chart of accounts. It is copied from a **template** when the entity is created, and journal lines name its accounts by **code**. In the new chart architecture, each account has its own code and an explicit reporting placement. The placement consists of a report group and, where applicable, a report category. There are two levels, and their IDs are not interchangeable: | Level | What it is | Read with | | -------- | ----------------------------------------------------------- | ------------------------------------ | | Template | A workspace-level blueprint that entities are created from. | `charts.list`, `charts.listAccounts` | | Entity | The accounts one entity actually posts to. | `entityAccounts.list` | Post journals against the entity's accounts. Template account IDs are never valid on a journal. ## An entity's accounts ```ts const accounts = await prosaic.entityAccounts .list(entityId) .autoPagingToArray({ limit: 1000 }); ``` ```bash curl https://app.prosaic.works/api/public/v1/entities/YOUR_ENTITY_ID/charts \ -H "Authorization: Bearer $PROSAIC_API_KEY" ``` Each account has: | Field | Notes | | ------------ | ----------------------------------------------------------------------------------- | | `id` | The entity account's ID. | | `code` | What journal lines send as `entityAccountCode`, for example `4030`. | | `name` | For example `Office Expense`. | | `type` | `Asset`, `Liability`, `Equity`, `Revenue` or `Expense`. | | `subtype` | Stored legacy compatibility data; use the saved reporting pair for classification. | | `taxCode` | The account's default tax code, such as `NZ_GST_15_EXP`. | | `mappedCode` | Optional alternate code for a workflow that uses different codes. | | `isSystem` | `true` for accounts Prosaic relies on, such as GST, Rounding and Retained Earnings. | | `parentId` | A legacy hierarchy reference. Use the saved reporting pair for placement. | | `source` | `template`, `overridden` (a template account changed for this entity) or `custom`. | Query options: - `includeSystem=false` leaves out system accounts (it defaults to `true`). - `includeExcluded=true` adds template accounts that have been hidden from this entity, flagged `isExcluded: true`. In the SDK these are strings: `{ includeSystem: 'false' }`. An account's `taxCode` is a default, not a rule: each journal line names its own tax rate. If an entity is created without `isGstRegistered: true`, every account defaults to its country's "No GST" code. Bank accounts linked to an entity get their own account in the chart. You can find it at `bankAccounts[].entityAccount` on the entity in `GET /entities`. ## Changing an entity's chart All of these are on `entityAccounts`, under `/entities/{entityId}/charts`: | Method | What it does | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `create(entityId, params)` | Adds an account with reporting choices when inputs are enabled; uses a parent otherwise. | | `update(entityId, accountId, params)` | Updates eligible account metadata or reporting. Parent account fields have additional restrictions in earlier workspaces. | | `del(entityId, accountId)` | Deletes an eligible custom account or excludes a template-linked account so `restore` can bring it back. | | `restore(entityId, templateAccountId)` | Brings back a hidden template account. | | `reset(entityId, accountId)` | Returns a changed template account to the template's values. | Adding an account: ```ts await prosaic.entityAccounts.create(entityId, { reporting: { groupKey: 'exp.operating', categoryKey: null }, code: '4050', name: 'Software subscriptions', taxCode: 'NZ_GST_15_EXP', }); ``` Call `reportCategories.list(entityId)` first. In enabled workspaces, choose an active assignable group and an eligible category or explicit null. Account type derives from the group. Bank and other verified functions can require a category. Do not send a parent with the pair. Nonactivated workspaces retain the legacy parent-based write shape and reject explicit assignment writes. Codes contain only digits and dots. Use the firm's own account code for posting, and keep the account ID when renaming it. A report group places the account in a report section. A category adds detail within that section. Each account has one saved pair even when discovery lists the same category under several groups. Compare the selected group's ID with the category's `allowedGroupIds` and send the keys in the write. If the firm recodes an account, reread the chart and refresh any rules, imports or integrations that reference the old code. Use the entity editor or pass `code` to the SDK’s `entityAccounts.update` to change an eligible account code. The MCP `update_chart_account` tool currently exposes other account fields. ## Discovery and conflict handling Before an entity exists, call `reportCategories.listForWorkspace()` (`GET /api/public/v1/report-categories`). It uses the authorised workspace, returns `workspaceId`, `country`, `groups`, `categories` and `reportingInputsEnabled`, and accepts no country override. Entity discovery uses all active connected workspaces. The capability is observational; writes recheck policy and permissions. ```ts const { data: taxonomy } = await prosaic.reportCategories.listForWorkspace(); const group = taxonomy.groups.find((g) => g.key === 'exp.operating'); if (!group?.isAssignable) throw new Error('Assignable group unavailable'); ``` A metadata-only patch preserves classification: ```ts await prosaic.entityAccounts.update(entityId, accountId, { description: 'Monthly subscriptions', }); ``` Read current assignments before editing. Include the saved pair in `expected`; explicit null means it was unassigned. A valid group-only edit has `categoryKey: null`: ```ts await prosaic.entityAccounts.update(entityId, accountId, { reporting: { groupKey: 'exp.operating', categoryKey: null, expected: { groupKey: current.reportGroup.key, categoryKey: current.reportCategory?.key ?? null, }, }, }); ``` Missing, mixed or invalid choices return `400 VALIDATION_ERROR`. `409 CHART_INPUT_CONTRACT_MISMATCH` requires rediscovery. Other stale-state conflicts require rereading and reviewing current data before another save. Policy evaluation failure returns `503 CHART_INPUT_POLICY_UNAVAILABLE`. Never retry a mutation automatically with a different shape. Read-only subtype compatibility and trial-balance `groupBy=subtype` remain available; their retirement is separate. ## Templates Templates live in the workspace. A new workspace starts with five: a standard chart for its country (`Standard NZ Business Template` or `Standard AU Business Template`) and the Company, Trust, Sole Trader and Partnership charts. The standard chart carries the workspace's own GST codes. | Method | What it does | | -------------------------------------------------------- | ---------------------------------------------------------------------------- | | `charts.list()` | The workspace's templates, with an account count for each. | | `charts.listAccounts(chartId)` | A template's accounts. `includeHidden: true` adds global accounts not in it. | | `charts.create(params)` | Creates a template from a list of accounts. | | `charts.update(chartId, params)` | Renames it, or replaces its whole account list. | | `charts.createAccount`, `updateAccount`, `deleteAccount` | Changes one account in a template. | | `charts.del(chartId)` | Deletes a template no entity uses. | | `globalAccounts.list()` | Standard accounts for the earlier chart contract. | Template metadata propagation respects entity overrides. Reporting changes require human review and propagation approval. API and OAuth credentials cannot confirm template review, approve propagation or bypass role locks. In enabled workspaces, included template rows carry `groupKey`, explicit `categoryKey` (nullable), and required system-role mappings. A full replacement includes stable existing row `id` values and row `expectedUpdatedAt` values, plus the template `expectedUpdatedAt`. Keep IDs when codes change. API-created or changed pairs remain unreviewed. A person must confirm them in the chart editor before application. First-use role locks remain permanent. Nonactivated workspaces keep the legacy global-library/system-account flow. Before replacing the account list, read every page with `charts.listAccounts(chartId)` and check that each response has the same `templateUpdatedAt`. Send that version as the template's `expectedUpdatedAt`. If the version changes between pages, discard the partial list and start again. Two details catch people out: - **Template reads show tax names, writes take tax codes.** `charts.listAccounts` returns a tax _name_ such as `15% GST on Income` in `taxCode`. When you write a template, send the machine code (`NZ_GST_15_INC`) instead. Entity accounts return the machine code. - **Template IDs are not entity IDs.** An entity's `currentTemplateId` names the template it was created from, not its chart. Read the chart with `entityAccounts.list`. --- # Reports > Trial balance, profit and loss, balance sheet, general ledger, current accounts and depreciation schedule. Source: https://developer.prosaic.works/docs/ledger/reports Reports are read straight from an entity's posted journals, so they are current the moment a journal posts. Drafts are not included, and nor are voided journals or their reversals. | Report | Endpoint | SDK | | -------------------------- | -------------------------------------------------------- | ------------------------------ | | Trial balance | `GET /entities/{entityId}/trial-balance` | `reports.trialBalance` | | Profit and loss | `GET /entities/{entityId}/reports/profit-loss` | `reports.profitLoss` | | Balance sheet | `GET /entities/{entityId}/reports/balance-sheet` | `reports.balanceSheet` | | General ledger, by account | `GET /entities/{entityId}/general-ledger/account` | `generalLedger.byAccount` | | General ledger, entries | `GET /entities/{entityId}/general-ledger/transaction` | `generalLedger.byTransaction` | | Current accounts | `GET /entities/{entityId}/reports/current-accounts` | `reports.currentAccounts` | | Depreciation schedule | `GET /entities/{entityId}/reports/depreciation-schedule` | `reports.depreciationSchedule` | GST returns are covered in [Tax in NZ and AU](/docs/ledger/tax-nz-au#nz-gst-returns). ## Conventions - **No envelope.** Reports return the report object itself, with a `metadata` block (the entity, its currency and the report dates), not a `data` wrapper. - **Decimal strings.** Amounts are strings. Parse them with a decimal library such as Decimal.js rather than adding them as floating-point numbers. - **Dates** are `YYYY-MM-DD`. A regional format such as `31-10-2026` is rejected with `400`. - **The entity's own calendar.** Periods such as `this-financial-year` follow the entity's financial year (1 April in New Zealand, 1 July in Australia), and day boundaries fall at midnight in the entity's timezone. - **Query values are strings.** In the SDK, flags are passed as `'true'` or `'false'` and counts as strings, matching the query string. The exceptions are the general ledger's `includeVoided` (a boolean) and `accountIds` (an array). ## Trial balance ```ts const tb = await prosaic.reports.trialBalance(entityId, { asOfDate: '2026-10-31', groupBy: 'reportGroup', }); console.log( tb.totals.isBalanced, tb.totals.totalDebits, tb.totals.totalCredits, ); for (const group of tb.accountGroups) { for (const account of group.accounts) { console.log(account.accountCode, account.accountName, account.netBalance); } } ``` | Parameter | Values | | ---------------------------------------------------- | ---------------------------------------------------------------------- | | `asOfDate` | Defaults to today. | | `reportMode` | `cumulative` (default) or `movement`. | | `movementStartDate`, `movementEndDate` | The range for `movement` mode. Defaults to the current financial year. | | `groupBy` | `type` (default), `reportGroup`, `none`, or `subtype` (deprecated). | | `includeZeroBalances` | `'false'` (default) or `'true'`. | | `comparison` | `none` (default) or `periods`. | | `comparisonType` | `year` (default) or `month`. | | `comparisonPeriods` | `1` to `12`. Defaults to `1`. | | `compareToEndOfMonth`, `compareToEndOfFinancialYear` | Snap comparison dates to a month or year end. | In `cumulative` mode, balance sheet accounts show their balance to date and income and expense accounts show the current financial year. `movement` mode shows only the activity in the range, for every account. Use `groupBy=reportGroup` to group rows by the entity's saved report groups in country order. The group's `type` is its stable key (such as `ass.current`) and `name` is its label (such as Current assets). Rows with no saved group share the `unassigned` group. Every row includes nullable `reportGroup` and `reportCategory` objects with `key` and `name`. A null category is valid for a group-only assignment. Use `groupBy=none` to build your own groups from the rows. `groupBy=subtype` is deprecated. It still groups rows by their stored `accountSubtype`. To see the groups and categories available for an entity, use `GET /api/public/v1/entities/{entityId}/report-categories`, `reportCategories.list(entityId)` in the SDK, or `list_report_categories` in MCP. Each account's `netBalance` is **debits minus credits**: positive for a debit balance, negative for a credit balance, whatever the account type. `totals` has `totalDebits`, `totalCredits`, `isBalanced` and `variance`. ## Profit and loss ```ts const pl = await prosaic.reports.profitLoss(entityId, { periodType: 'last-financial-year', }); ``` | Parameter | Values | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `periodType` | `this-financial-year` (default), `last-financial-year`, `this-quarter`, `last-quarter`, `this-month`, `last-month` or `custom`. | | `startDate`, `endDate` | The range for `custom`. Leave them out for the other period types. | | `comparison` | `none` (default) or `periods`. | | `comparisonType` | `year` (default), `quarter`, `month` or `custom`. Pair it with the matching `periodType`. | | `comparisonPeriods` | `1` to `12`. | | `includeZeroBalances` | `'false'` (default) or `'true'`. | The response is split into `tradingIncome`, `costOfSales`, `otherIncome` and `operatingExpenses`, with `totals`. ## Balance sheet ```ts const bs = await prosaic.reports.balanceSheet(entityId, { asOfDate: '2027-03-31', }); ``` Takes `asOfDate` (defaults to today), `includeZeroBalances`, and the same `comparison`, `comparisonType` (`year` or `month`) and `comparisonPeriods` as the trial balance. The response has `sections` and `totals`. ## General ledger Every posted line, from every source: manual journals, bank reconciliations, invoices and the rest. ```ts const ledger = await prosaic.generalLedger.byAccount(entityId, { periodType: 'custom', startDate: '2026-04-01', endDate: '2027-03-31', }); ``` - `byAccount` groups entries under each account, with running balances and period totals. Its response has `accounts`. - `byTransaction` returns a flat list of entries. Its response has `entries`. | Parameter | Values | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `periodType` | `custom` (the default), `this-month`, `last-month`, `this-quarter`, `last-quarter`, `this-financial-year`, `last-financial-year`, `month-to-date`, `quarter-to-date` or `year-to-date`. | | `startDate`, `endDate` | Both required with `custom`. | | `accountIds` | Entity account IDs: an array in the SDK, which sends them comma-separated. | | `includeVoided` | `true` to include voided journals and their reversals (a boolean in the SDK; `includeVoided=true` in the query string). | Balances here are debits minus credits too. `GET /entities/{entityId}/ledger` (`ledger.list`) is the older version of this endpoint and is deprecated. Use the general ledger endpoints instead. ## Current accounts The owners' or shareholders' current accounts: an opening balance, increases (funds introduced and advances), decreases (drawings), and the closing balance for the period. It takes the same `periodType`, `startDate`, `endDate` and comparison parameters as the profit and loss. ```ts const current = await prosaic.reports.currentAccounts(entityId, { periodType: 'this-financial-year', }); ``` ## Depreciation schedule The entity's fixed assets over a period, one row per asset, with `totals`. Both dates are required. ```ts const schedule = await prosaic.reports.depreciationSchedule(entityId, { startDate: '2026-04-01', endDate: '2027-03-31', }); ``` Assets themselves are managed with `fixedAssets` and `fixedAssetTypes`; see [Fixed assets](/docs/api/fixed-assets) in the API reference. ## Chart reporting assignments Discover workspace choices with `GET /api/public/v1/report-categories`, or entity choices with `GET /api/public/v1/entities/{entityId}/report-categories`. The saved reporting group/category pair is authoritative in activated workspaces. Stored `subtype` remains compatibility data, not a promise that reports derive from it. Trial-balance `groupBy=subtype` remains available pending its separate retirement. See [Chart of accounts](/docs/ledger/chart-of-accounts) for required write choices, permissions and conflict recovery. --- # Tax in NZ and AU > GST tax codes for New Zealand and Australia, GST registration on entities, and reading NZ GST returns. Source: https://developer.prosaic.works/docs/ledger/tax-nz-au Every entity holds its own country's GST tax rates, and every journal line with an amount names one of them. The country, and so the set of codes, comes from the entity's workspace. See [one workspace per country](/docs/ledger/embedded-ledger#one-workspace-per-country). ## Tax codes **New Zealand** (GST at 15%): | Code | Name | Rate | | --------------- | ------------------- | ---- | | `NZ_GST_15_INC` | 15% GST on Income | 15% | | `NZ_GST_15_EXP` | 15% GST on Expenses | 15% | | `NZ_GST_0_ZERO` | Zero-rated GST | 0% | | `NZ_GST_0_NONE` | No GST | 0% | **Australia** (GST at 10%): | Code | Name | Rate | | ----------------- | --------------- | ---- | | `AU_GST_10_INC` | GST on Income | 10% | | `AU_GST_10_EXP` | GST on Expenses | 10% | | `AU_GST_0_EXPORT` | GST Free | 0% | | `AU_GST_0_INPUT` | Input Taxed | 0% | | `AU_GST_0_NONE` | BAS Excluded | 0% | An entity only has its own country's codes. Its tax rates are created with it and listed in `taxRates[]` on the entity, from `entities.list` or the `entities.create` response: ```ts const { data: [entity], } = await prosaic.entities.list({ entityId }); const rates = new Map(entity.taxRates.map((rate) => [rate.code, rate.id])); const gstOnExpensesId = rates.get('NZ_GST_15_EXP'); ``` Each rate has an `id`, a `code`, a `name` and a `rate`, the percentage as a decimal string. Different endpoints take different halves of a rate: - **Journal lines** take the rate's `id`, as `taxRateId`. - **Accounts** and **bank reconciliations** take the machine `code`, as `taxCode`. ## GST on journals A journal's `taxMode` decides whether line amounts include GST, and Prosaic writes the GST lines to the entity's GST account when the journal posts: - `NO_TAX` (or no `taxMode`): amounts are final and no GST lines are added. - `TAX_EXCLUSIVE`: amounts are before GST, and GST is added on top. - `TAX_INCLUSIVE`: amounts include GST, and GST is split out. [Journals](/docs/ledger/journals#balancing-and-gst) has worked examples and the balancing rules. ## GST registration on an entity Set these on `entities.create`: | Field | Notes | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------- | | `isGstRegistered` | `true` if the business is registered for GST. Without it, every account defaults to the "No GST" code. | | `gstNumber` | New Zealand: the 9-digit GST number. Australia: the 11-digit ABN, which is checked against the ABN checksum. | | `gstPeriod` | Months per GST period, as a string: `'1'`, `'2'`, `'3'`, `'6'` or `'12'`. New Zealand files one-, two- or six-monthly. | | `gstFilingStartDate` | `YYYY-MM-DD`, the start of the first period Prosaic should prepare. | | `areGstReportsAutomated` | `true` to have Prosaic create the entity's GST returns (New Zealand only). Needs all four fields above. | The entity response reports these back as `isGstRegistered`, `gstPeriodMonths` and `gstBasis`. ## NZ GST returns For a New Zealand entity with `areGstReportsAutomated` on, Prosaic creates a GST return for each period from the filing start date. An accountant reviews, finalises and files each return with IRD in the Prosaic app. The API reads returns; it does not finalise or file them. | Endpoint | SDK | | ---------------------------------------------------- | ----------------------------------- | | `GET /gst-returns` | `gstReturns.list` (whole workspace) | | `GET /entities/{entityId}/gst-returns` | `gstReturns.listForEntity` | | `GET /entities/{entityId}/gst-returns/{gstReturnId}` | `gstReturns.retrieve` | ```ts for await (const gstReturn of prosaic.gstReturns.listForEntity(entityId, { status: ['draft', 'finalised'], })) { console.log( gstReturn.name, gstReturn.dateFrom, gstReturn.dateTo, gstReturn.status, ); } const { data: detail } = await prosaic.gstReturns.retrieve( entityId, gstReturnId, ); console.log( detail.amountsSource, detail.totalGstCollected, detail.totalGstCredit, ); ``` - **Statuses:** `draft`, `finalised`, `filed`, `filed_externally`, `accepted`, `rejected`, `awaiting_payment` and `completed`. Filter with `status`, which can repeat or be comma-separated. - **Box amounts.** `retrieve` returns IRD boxes 5 to 15. For a `draft`, they are calculated live from the posted journals and move as the books change (`amountsSource: 'calculated'`). For every other status, they come from the snapshot taken at finalisation (`'finalised'`). - **Lists** carry each return's period, due date, `netGstPosition` (Box 15) and a count of unreconciled bank transactions. `netGstPosition` is `null` until the return has been calculated. - **Dates** (`dateFrom`, `dateTo`, `dueDate`) are New Zealand calendar days. - Drafts for periods that have not started are hidden unless you pass `includeFutureDrafts: 'true'`. - GST return amounts are numbers, unlike most amounts in the API. ## Australia today Australian entities have: - the AU GST codes above, at 10%; - the Standard AU Business Template, carrying AU codes; - AUD as their currency; - a financial year starting 1 July, with reports cut at midnight Sydney time; - the ABN as their GST number. Not yet available: BAS preparation and ATO lodgement, and AU bank feeds. GST returns are not created for Australian entities, so the GST return endpoints return nothing for them. AU bank lines can be imported through the API with `bankAccounts.createWithTransactions` and `bankAccounts.importTransactions` in the meantime. --- # Node SDK > Install prosaic-node, set up a client with an API key or OAuth token, and work with pagination, errors and uploads. Source: https://developer.prosaic.works/docs/sdk/node `prosaic-node` is the TypeScript and JavaScript client for the Prosaic API. It wraps every public endpoint in a typed method, such as `prosaic.journals.create(...)`, and handles pagination, retries on safe reads, and OAuth. - Node.js 22 or later - TypeScript types included - ESM and CommonJS - No runtime dependencies The SDK is in alpha (`0.1.0-alpha.2`) and uses the public contract shipped with that package. The source is at [github.com/prosaichq/prosaic-node](https://github.com/prosaichq/prosaic-node). ## Install Install the released alpha package: ```sh yarn add prosaic-node@next ``` The monorepo's `@prosaic/sdk` name is an internal alias. The SDK package version, API `/v1` path and workspace reporting capability are separate. See [Chart of accounts](/docs/ledger/chart-of-accounts) before chart writes. Activated workspaces require explicit reporting assignments; metadata-only patches preserve them. ## Create a client With an API key, for your own server-side integration: ```ts import Prosaic from 'prosaic-node'; const apiKey = process.env.PROSAIC_API_KEY; if (!apiKey) throw new Error('Set PROSAIC_API_KEY first.'); const prosaic = new Prosaic(apiKey); const { data: me } = await prosaic.me.retrieve(); console.log(`Connected as ${me.name}`); ``` CommonJS code can use `const { Prosaic } = require('prosaic-node')`. With an OAuth access token, pass a single options object. The second argument is only read when the first is an API key string, so put every option in the object: ```ts const prosaic = new Prosaic({ accessToken: tokenProvider, // a string, or a function that returns one workspaceId: 'YOUR_WORKSPACE_ID', }); ``` See [OAuth](#oauth) for building `tokenProvider`. ### Options | Option | Default | Purpose | | ------------------- | --------------------------- | ---------------------------------------------------------- | | `baseUrl` | `https://app.prosaic.works` | Server origin, without `/api/public/v1`. | | `timeout` | `30000` | Total request deadline in milliseconds, including retries. | | `maxNetworkRetries` | `2` | Retries for transient failures on `GET` and `HEAD`. | | `workspaceId` | Unset | Workspace to act in, sent as `x-workspace-id`. | Every method takes a final request-options argument that can override `timeout`, `maxNetworkRetries` and `workspaceId` for that call, and take an `AbortSignal` as `signal`: ```ts const controller = new AbortController(); await prosaic.entities.list( {}, { workspaceId: 'ANOTHER_WORKSPACE_ID', signal: controller.signal }, ); ``` `baseUrl` must be HTTPS, except for a loopback address during local development. See [Authentication](/docs/getting-started/authentication) for how workspaces are chosen. ## Methods Methods are grouped by resource and named for what they do: `list`, `retrieve`, `create`, `update`, `del`, and specific verbs such as `journals.void` or `transactions.reconcile`. Path parameters come first, then the body or query, then request options. ```ts await prosaic.journals.create(entityId, params); await prosaic.reports.trialBalance(entityId, { asOfDate: '2026-10-31' }); await prosaic.transactions.reconcile(entityId, transactionId, params); ``` The SDK covers 76 operations in 24 resource groups: | Area | Resources | | ------------------------- | ---------------------------------------------------------- | | Identity and setup | `me`, `version`, `entities`, `clients` | | Accounts and dimensions | `charts`, `entityAccounts`, `globalAccounts`, `dimensions` | | Transactions and journals | `transactions`, `bankAccounts`, `journals`, `changeSets` | | Financial reporting | `ledger`, `generalLedger`, `reports`, `gstReturns` | | Contacts and invoices | `contacts`, `invoices` | | Assets and files | `fixedAssets`, `fixedAssetTypes`, `files` | | Automation and extensions | `rules`, `scheduledTasks`, `extensions` | Request and response types are exported under predictable names, such as `JournalsCreateParams`, `EntitiesListResponse` and `ReportsTrialBalanceParams`. The repository's `docs/api-reference.md` lists every method, and the [API reference](/docs/api) documents each endpoint with its SDK method. ## Responses The SDK keeps the API's response shapes: - Most methods return a `{ data }` envelope: `const { data: entity } = await prosaic.entities.create(...)`. - Journal creation, reports and file uploads return the object directly. - `.withResponse()` on any call also gives you the request ID and the raw `Response`: ```ts const { data: payload, requestId } = await prosaic.me.retrieve().withResponse(); ``` ## Pagination List methods return a promise you can use in three ways: ```ts // One page, with its envelope. const page = await prosaic.transactions.list(entityId, { pageSize: 100 }); // Every item, fetching pages as you go. for await (const transaction of prosaic.transactions.list(entityId, { dateFrom: '2026-04-01', dateTo: '2026-04-30', })) { console.log(transaction.id, transaction.amount); } // At most `limit` items, in an array. const recent = await prosaic.transactions .list(entityId) .autoPagingToArray({ limit: 50 }); ``` `autoPagingEach(callback)` visits each item and stops fetching when the callback returns `false`. Pagination is not a snapshot: records can change while you iterate. ## Errors HTTP errors throw `APIError` or a subclass, with the status, the API's error `code`, `details` when the API gives them, and the `requestId`: ```ts import { APIError, ValidationError } from 'prosaic-node'; try { await prosaic.journals.create(entityId, params); } catch (error) { if (error instanceof ValidationError) { console.error('Rejected:', error.message, error.details); } else if (error instanceof APIError) { console.error(error.status, error.code, error.requestId); } else { throw error; } } ``` | Class | When | | ---------------------- | ----------------------------------------- | | `ValidationError` | `400` or `422` | | `AuthenticationError` | `401` | | `PermissionError` | `403` | | `NotFoundError` | `404` | | `ConflictError` | `409` | | `RateLimitError` | `429` | | `APIError` | Any other HTTP error, including `5xx` | | `ConnectionError` | The request did not get a response | | `TimeoutError` | The deadline passed (a `ConnectionError`) | | `InvalidResponseError` | The response could not be read | | `OAuthError` | An OAuth protocol error, with its `code` | `error.details` can contain accounting data, so keep it out of public logs. Quote the `requestId` when you report a problem. ### Retries `GET` and `HEAD` requests are retried on transient failures, up to `maxNetworkRetries` times within the `timeout`, and respect `Retry-After`. **Writes and OAuth token requests are never retried.** The API has no general idempotency key, so after a failed write, check what happened before you try again. [Avoiding double-posting](/docs/ledger/embedded-ledger#avoiding-double-posting) shows one way. ## Uploads `files.upload(entityId, file)` takes a `File` or `Blob`. Give it a filename, either with a named `File` or with the `filename` request option for a `Blob`, and a content type the API accepts. ```ts import { readFile } from 'node:fs/promises'; const bytes = await readFile('receipt.pdf'); const { file } = await prosaic.files.upload( entityId, new File([bytes], 'receipt.pdf', { type: 'application/pdf' }), ); await prosaic.journals.attachFiles(entityId, logicalJournalId, { fileIds: [file.id], }); ``` [Journals](/docs/ledger/journals#attachments) lists the accepted file types and the size limit. ## OAuth `OAuth` runs the authorization-code flow with S256 PKCE, for public and confidential clients. Register an app first; see [OAuth apps](/docs/apps/oauth-apps). ```ts import Prosaic, { OAuth } from 'prosaic-node'; const oauth = new OAuth({ clientId: process.env.PROSAIC_CLIENT_ID!, clientSecret: process.env.PROSAIC_CLIENT_SECRET, // leave out for a public client }); // 1. Start: store `authorization` in the user's server-side session, then // redirect their browser to authorization.url. const authorization = oauth.createAuthorization({ redirectUri: 'https://your-app.example/oauth/callback', }); // 2. Callback: checks the redirect and state, then exchanges the code. const tokens = await oauth.completeAuthorization(callbackUrl, authorization); await saveTokens(userId, tokens); // 3. Use: the provider refreshes the access token when it is about to expire. const prosaic = new Prosaic({ accessToken: oauth.createTokenProvider(tokens, (updated) => saveTokens(userId, updated), ), }); ``` - The default scopes are `openid profile email offline_access`. Pass `scopes` to `createAuthorization` to change them. - Use each stored authorization once, and expire it quickly. - Save tokens securely, including `expires_at` and the refresh token. Your save callback must store the updated tokens atomically and return a promise. - Create one token provider per user grant. If several processes share a grant, coordinate refreshes between them, because refresh tokens rotate. - An `invalid_grant` error means the user must authorise your app again. - `refreshToken`, `exchangeCode` and `revokeToken` are there for flows that need them. - The SDK returns ID tokens unchanged and does not verify them, so do not use them to sign users in to your app. ## Money and dates - **Amounts.** Keep values exactly as returned. Most amounts are decimal strings; a few endpoints, such as invoices and GST returns, return numbers. Use Decimal.js for arithmetic. Send journal amounts as decimal strings. - **Dates.** Send calendar dates as `YYYY-MM-DD` strings, and avoid converting them through your machine's timezone. ## For coding agents The package ships an agent skill at `skills/prosaic-sdk/SKILL.md` that teaches Claude Code and other agents these conventions. See [Build with AI](/docs/ai/build-with-ai) for that and the MCP servers. --- # OAuth apps > Connect your product to accounting firms' Prosaic workspaces with OAuth and PKCE, and the review policy for new apps. Source: https://developer.prosaic.works/docs/apps/oauth-apps An OAuth app lets someone connect your product to their Prosaic workspace without handing you an API key. They sign in to Prosaic, approve your app, and your server gets tokens that act as them. Use one when your product works with workspaces that belong to other people. Usually that's an accounting firm: its staff keep their clients' books in Prosaic, and your practice-management, document-collection or point-of-sale product reads and writes those books on the firm's behalf. Two other routes don't need an OAuth app: - **Your own workspace.** For a server-side integration with books you control, use an [API key](/docs/getting-started/authentication). - **Embedding a ledger in your product.** If you keep books for your own customers, your platform workspace owns one entity per customer. That's the [embedded ledger](/docs/ledger/embedded-ledger), and it runs on your API key. ## What works today | Endpoint | URL | | ------------- | ------------------------------------------------------------------ | | Discovery | `https://app.prosaic.works/.well-known/oauth-authorization-server` | | Authorisation | `https://app.prosaic.works/api/auth/oauth2/authorize` | | Token | `https://app.prosaic.works/api/auth/oauth2/token` | | Registration | `https://app.prosaic.works/api/auth/oauth2/register` | | Revocation | `https://app.prosaic.works/api/auth/oauth2/revoke` | Read the endpoints from the discovery document rather than hard-coding them. OpenID Connect clients can use `https://app.prosaic.works/.well-known/openid-configuration`, which lists the same endpoints plus `userinfo`. - **Grant:** authorisation code with PKCE. The only code challenge method is `S256`, and PKCE is required. - **Scopes:** `openid`, `profile`, `email` and `offline_access`. The first three identify the user; `offline_access` gets you a refresh token. There are no narrower API scopes: the access token can do what the consenting user can do in Prosaic. - **Access tokens** last 24 hours. - **Refresh tokens** last 30 days and rotate. Each refresh returns a new refresh token and retires the old one, so save the new one every time. - **Registration:** a workspace admin or owner registers an app in Prosaic, under **Settings → Developer**. Dynamic client registration ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591)) at the registration endpoint is for tools that register one client per person, such as MCP clients. ## 1. Register your app In Prosaic, open **Settings → Developer** and choose **Register an app**. You need to be an admin or owner of your workspace; the app belongs to the workspace, not to you. Registering apps is in early access: if your workspace says so, email [hello@prosaic.works](mailto:hello@prosaic.works) and we'll turn it on. - **Type.** Choose **Web app** if your app has a server that can keep a secret: you get a client ID and a client secret. Choose **Native app** for desktop and mobile apps, or **Single-page app** for code that runs only in the browser: these are public clients with no secret, and PKCE protects the exchange. - **Redirect URIs.** Where Prosaic sends people back with a code. They must use `https`. Native apps may also use a loopback address such as `http://127.0.0.1:8123/callback`, or a reverse-domain scheme such as `com.example.app:/callback`. No wildcards or fragments. - **Links.** A homepage, privacy policy and terms (all optional, all `https`). They appear on the consent screen next to your app's name and your workspace's name. Copy the client secret when it appears: it's shown once. You can rotate it later from the app's page; the old secret stops working straight away. Register a product integration here rather than through dynamic registration. A client registered dynamically isn't tied to a workspace, so the consent screen can't say who built it, and it can't be reviewed. ## 2. Send the user to Prosaic The [Node SDK](/docs/sdk/node) has the flow built in. It generates the PKCE verifier and `state` for you: ```ts import { OAuth } from 'prosaic-node'; const clientId = process.env.PROSAIC_CLIENT_ID; if (!clientId) throw new Error('Set PROSAIC_CLIENT_ID'); const oauth = new OAuth({ clientId, clientSecret: process.env.PROSAIC_CLIENT_SECRET, // Omit for a public client }); const authorization = oauth.createAuthorization({ redirectUri: 'https://acme.example/oauth/callback', }); // Save `authorization` in this user's server-side session, // then redirect their browser to authorization.url. ``` By default it asks for `openid profile email offline_access`. The user signs in to Prosaic if they need to, then sees a consent screen listing the scopes, and allows or denies your app. The screen shows your app's name, your workspace's name and your links, and until Prosaic has reviewed your app, it says so. Without the SDK, redirect to the authorisation endpoint with `response_type=code`, `client_id`, `redirect_uri`, `scope`, `state`, `code_challenge` and `code_challenge_method=S256`. ## 3. Exchange the code On your callback route, finish the flow with the authorisation you saved. `completeAuthorization` checks the callback's address and `state` before it exchanges the code: ```ts const tokens = await oauth.completeAuthorization(callbackUrl, authorization); // { access_token, refresh_token, expires_at, scope, id_token, ... } ``` Use the saved authorisation once, then delete it. Store the tokens encrypted, including `expires_at` and the refresh token. Without the SDK, POST a form to the token endpoint: ```bash curl -X POST https://app.prosaic.works/api/auth/oauth2/token \ -u "$PROSAIC_CLIENT_ID:$PROSAIC_CLIENT_SECRET" \ -d grant_type=authorization_code \ -d code="$CODE" \ -d redirect_uri=https://acme.example/oauth/callback \ -d code_verifier="$CODE_VERIFIER" ``` A public client sends `client_id` in the form instead of the `-u` credentials. To refresh, send `grant_type=refresh_token` with the `refresh_token`. ## 4. Call the API Send the access token as a Bearer token. Each request acts as the user who approved your app, with the role they hold in the workspace you select: ```ts import Prosaic from 'prosaic-node'; const prosaic = new Prosaic({ // Refreshes before expiry and hands you the rotated tokens to save. accessToken: oauth.createTokenProvider(tokens, (updated) => saveTokens(userId, updated), ), }); // Which workspaces can this user reach? const { data: me } = await prosaic.me.retrieve(); for (const workspace of me.workspaces) { console.log(workspace.id, workspace.name, workspace.role); } // Work in one of them. const entities = await prosaic.entities .list({}, { workspaceId: me.workspaces[0].id }) .autoPagingToArray({ limit: 100 }); ``` `saveTokens` is your own function, and it must save atomically. Pass `workspaceId` in a method's last argument, as above, or once to `new Prosaic({ accessToken, workspaceId })`. If your app runs in several processes, make sure only one refreshes a given grant at a time. Over plain HTTP: ```bash curl https://app.prosaic.works/api/public/v1/entities \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "x-workspace-id: $WORKSPACE_ID" ``` - **`x-workspace-id`** picks the workspace. Without it, the request uses the user's active workspace in Prosaic, which can change under you, so always send it. A workspace the user doesn't belong to returns `403 Not a member of requested workspace`. - **Firm accounts only.** People who reach Prosaic through a client portal (the `client` and `standard_user` roles) can't use the API through third-party apps. Their requests return `403` with the code `CLIENT_API_ACCESS_DISABLED`. - **Expired trials.** A workspace whose trial has ended returns `403` with the code `TRIAL_EXPIRED`. - **`invalid_grant` on refresh** means the grant can't be refreshed. Ask the user to connect again rather than retrying. When a user disconnects your app, revoke the refresh token with `oauth.revokeToken(refreshToken, 'refresh_token')` or the revocation endpoint. ## Review New apps start unreviewed, and an unreviewed app can connect to **5 workspaces besides your own**. That's enough to build, test and pilot with a few firms; ask for a review when you need more. - **What counts.** A workspace counts once anyone in it approves your app. Approving connects every workspace that person belongs to, because your token can reach each of them, so a person in two firms' workspaces uses two places. Several people in the same workspace count once. - **Your own workspace never counts**, so test there as much as you like. - **Disconnecting doesn't free a place.** The count is every workspace your app has reached. - **At the limit,** Prosaic refuses the consent for a new workspace and tells the person to ask you to request a review. People in workspaces you already reach can still connect. - **Request a review** from your app's page in Settings → Developer. Prosaic approves or rejects it, with a note you'll see on the same page. - **Once approved** there's no limit. An approved app's redirect URIs are locked so they can't be swapped after review; contact Prosaic to change them. - **If it's rejected,** your existing connections keep working and the limit stays at 5. Fix what the note says and request a review again. - **Turning an app off** in Settings signs everyone out of it: their tokens stop working, and they reconnect once you turn it back on. Apps Prosaic registers, and clients registered dynamically, aren't limited. The [embedded ledger](/docs/ledger/embedded-ledger) isn't affected either: it runs in your own workspace on your API key, with no OAuth app involved. Questions about reviews: [support@prosaic.works](mailto:support@prosaic.works). --- # 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. --- # Build with AI > Give AI tools the Prosaic docs, API and your books: llms.txt, Markdown pages, two MCP servers, the SDK skill and the manifest schema. Source: https://developer.prosaic.works/docs/ai/build-with-ai This site is written for language models as well as people. You can hand a model the docs as plain Markdown, connect it to an MCP server that searches the docs and the API, connect it to your own books, and give a coding agent a skill that knows how the SDK should be used. Which to reach for: - **Writing code against the API?** The developer MCP server and the SDK skill. - **Building an extension?** The developer MCP server, then the CLI to deploy. - **Working in your books from a chat — questions, reports, bookkeeping?** The data MCP server. ## Docs as Markdown | URL | What it is | | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `https://developer.prosaic.works/llms.txt` | An index of every doc page with a one-line summary, following [llmstxt.org](https://llmstxt.org), plus links to the SDK, CLI, MCP servers and OpenAPI document | | `https://developer.prosaic.works/llms-full.txt` | Every doc page in one Markdown file | | `https://developer.prosaic.works/docs/{category}/llms-full.txt` | One section in one file — for example `/docs/ledger/llms-full.txt` or `/docs/extensions/llms-full.txt` | | `https://developer.prosaic.works/docs/{category}/{slug}.md` | One page as Markdown — add `.md` to any doc URL | The section names are `getting-started`, `ledger`, `sdk`, `apps`, `extensions` and `ai`. A prompt as short as this works with any model that can fetch a URL: > Read https://developer.prosaic.works/llms.txt, then write a Node script that posts a balanced journal to a Prosaic entity using prosaic-node. The API itself is described in the [API reference](/docs/api), which is also served as Markdown at `https://developer.prosaic.works/docs/api.md`, and as an [OpenAPI document](/openapi.json) if your tool imports specs. ## The developer MCP server `prosaic-dev`, at `https://developer.prosaic.works/mcp`, is a read-only MCP server for building on Prosaic. It needs no sign-in and never touches anyone's books: it searches these docs, looks up API operations, and scaffolds and checks extensions. | Tool | What it does | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `search_docs` | Keyword search over these docs. Returns each match's page URL, Markdown URL and a snippet. | | `get_doc` | Returns one doc as Markdown, by `category` and `slug` or by its `url`. | | `search_api` | Keyword search over the public API. Each result has its method, path and SDK call, such as `prosaic.journals.create(entityId, params)`. | | `get_api_operation` | One operation in full: parameters, request body schema, responses and the SDK call. Look it up by `operationId` (the SDK method name, such as `journals.create`) or by `method` and `path`. | | `list_extension_scopes` | Every scope an extension can declare, and what it grants. | | `list_extension_triggers` | Every event with its input payload, the cron format, and the action-link placements. | | `scaffold_extension` | The files for a new extension project, as a map of paths to contents. | | `validate_extension_manifest` | Checks a `prosaic.extension.toml` with the same rules as the CLI. | | `get_extension_reference` | All the extension docs in one response. | The API tools read the OpenAPI document published with the [Node SDK](/docs/sdk/node), so a result names the SDK method as well as the HTTP route. If that document can't be fetched, the tools say so and point at the API reference. ### Claude Code ```bash claude mcp add --transport http prosaic-dev https://developer.prosaic.works/mcp ``` Add `--scope project` to share it with your team through the project's `.mcp.json`, or `--scope user` to have it in every project. ### Codex ```bash codex mcp add prosaic-dev --url https://developer.prosaic.works/mcp ``` This writes the server to `~/.codex/config.toml`, which the Codex CLI, app and IDE extension share. You can add it there by hand instead: ```toml [mcp_servers.prosaic-dev] url = "https://developer.prosaic.works/mcp" ``` ### Cursor Open this install link, and Cursor asks you to confirm: ```text cursor://anysphere.cursor-deeplink/mcp/install?name=prosaic-dev&config=eyJ1cmwiOiJodHRwczovL2RldmVsb3Blci5wcm9zYWljLndvcmtzL21jcCJ9 ``` Or add it to `.cursor/mcp.json` in your project, or `~/.cursor/mcp.json` for every project: ```json { "mcpServers": { "prosaic-dev": { "url": "https://developer.prosaic.works/mcp" } } } ``` ### VS Code Open this install link, and VS Code asks you to confirm: ```text vscode:mcp/install?%7B%22name%22%3A%22prosaic-dev%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fdeveloper.prosaic.works%2Fmcp%22%7D ``` Or add it to your user profile from a terminal: ```bash code --add-mcp '{"name":"prosaic-dev","type":"http","url":"https://developer.prosaic.works/mcp"}' ``` Or add it to `.vscode/mcp.json` in your workspace: ```json { "servers": { "prosaic-dev": { "type": "http", "url": "https://developer.prosaic.works/mcp" } } } ``` ### Gemini CLI ```bash gemini mcp add --transport http prosaic-dev https://developer.prosaic.works/mcp ``` This adds it to the project's `.gemini/settings.json`. Add `--scope user` to put it in `~/.gemini/settings.json` for every project. ### Claude.ai and Claude Desktop 1. Open **Customize → Connectors**. 2. Click **+ Add**, then **Add custom connector**. 3. Name it `Prosaic developer docs`, enter `https://developer.prosaic.works/mcp` and click **Continue**. 4. Under **Authentication**, choose **No sign in**, then click **Add**. On Team and Enterprise plans, an organisation owner adds connectors under **Organization settings → Connectors**: click **Add**, hover over **Custom** and choose **Web**. Members then connect it from **Customize → Connectors**. ### ChatGPT 1. In ChatGPT on the web, open [Plugins](https://chatgpt.com/plugins). 2. Click the plus button, then **Add custom MCP server**. 3. Name it `Prosaic developer docs`, and under **Connection** enter `https://developer.prosaic.works/mcp` as the **Server URL**. 4. Set authentication to **No authentication**. 5. Confirm the risk warning and choose **Create as a plugin**, then install the plugin to use it in a conversation. ## The data MCP server `prosaic`, at `https://mcp.prosaic.works/mcp`, connects a model to your own books. It signs in with your Prosaic account over OAuth, then acts as you, with the role you hold in your workspace. Its tools cover entities and clients, contacts, bank transactions and reconciliation, journals, the ledger and general ledger, the chart of accounts, fixed assets, GST returns, invoices, financial reports, files and rules, plus the same extension tools as `prosaic-dev`. Many of its tools write: they create journals, reconcile transactions and change accounts in real books. Most clients ask before each write; read what the model proposes before you approve it. It's for accounting-firm accounts. People who reach Prosaic through a client portal can't use it. There's nothing to configure beyond the URL. The client discovers Prosaic's sign-in, registers itself and opens your browser for you to sign in. ### Claude Code ```bash claude mcp add --transport http prosaic https://mcp.prosaic.works/mcp claude mcp login prosaic ``` `claude mcp login` opens your browser to sign in. You can sign in from a session instead: run `/mcp` and choose the server. ### Codex ```bash codex mcp add prosaic --url https://mcp.prosaic.works/mcp codex mcp login prosaic ``` Codex doesn't sign in when you add the server, so run `codex mcp login` before you use it. In `~/.codex/config.toml` the server is: ```toml [mcp_servers.prosaic] url = "https://mcp.prosaic.works/mcp" ``` ### Cursor Open this install link, and Cursor asks you to confirm: ```text cursor://anysphere.cursor-deeplink/mcp/install?name=prosaic&config=eyJ1cmwiOiJodHRwczovL21jcC5wcm9zYWljLndvcmtzL21jcCJ9 ``` Or use the `mcp.json` config for `prosaic-dev` above, named `prosaic` and with `https://mcp.prosaic.works/mcp` as its URL. Cursor runs the sign-in in your browser. ### VS Code Open this install link, and VS Code asks you to confirm: ```text vscode:mcp/install?%7B%22name%22%3A%22prosaic%22%2C%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fmcp.prosaic.works%2Fmcp%22%7D ``` Or run: ```bash code --add-mcp '{"name":"prosaic","type":"http","url":"https://mcp.prosaic.works/mcp"}' ``` VS Code opens your browser to sign in the first time it connects. ### Gemini CLI ```bash gemini mcp add --transport http prosaic https://mcp.prosaic.works/mcp ``` Gemini CLI opens your browser to sign in the first time it connects. To sign in again, run `/mcp auth prosaic` in a session. ### Claude.ai and Claude Desktop Follow the same steps as for `prosaic-dev`, with the URL `https://mcp.prosaic.works/mcp`. Keep the authentication settings Claude detects for it, which sign in with OAuth, and sign in to Prosaic when Claude asks. ### ChatGPT Follow the same steps as for `prosaic-dev`, with the URL `https://mcp.prosaic.works/mcp` and authentication set to **OAuth**. ChatGPT asks you to confirm each write. ## The SDK skill for Claude Code `prosaic-node` ships a [Claude Code skill](https://code.claude.com/docs/en/skills) at `skills/prosaic-sdk/SKILL.md`. It's a page of rules for an agent writing an integration, taken from how the SDK is meant to be used: - Use the typed resource methods rather than inventing HTTP paths. - Use an API key for your own server-side integration, and OAuth with PKCE for acting on someone else's behalf. Persist rotated refresh tokens atomically, and treat `invalid_grant` as "sign in again". - Keep the `{ data }` envelopes, keep dates as strings, and use a decimal library for money. - Never retry a financial write automatically after a connection error — the API has no idempotency keys, so check whether it happened first. - Test against a local server or a stubbed `fetch`, never by writing to production. To use it, [install the SDK](/docs/sdk/node), then copy the skill into your project: ```bash mkdir -p .claude/skills cp -R node_modules/prosaic-node/skills/prosaic-sdk .claude/skills/ ``` Claude Code reads project skills from `.claude/skills/` and loads this one when a task matches its description: building an integration with the Prosaic SDK. Copy it to `~/.claude/skills/` instead to have it in every project. In other agents, add the file to the agent's rules or point the agent at it. The package carries two more skills, `sdk-endpoints` and `sdk-release`. They're for maintaining the SDK itself, and you don't need them to build on it. ## Manifest schema for editors Extension manifests have a JSON Schema at `https://developer.prosaic.works/schemas/extension-manifest.json`. Scaffolded manifests start with this line, which tells TOML editors where to find it: ```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, then flag unknown scopes, event types and placements as you type. See the [Manifest reference](/docs/extensions/manifest#validation-in-your-editor).