# 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<void> {
  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 `"<Extension Name> 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 `"<Firm Name>" <extensions@prosaic.works>`, 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.
