# Actors kit (TypeScript)

Reference for @omazyai/sdk/actors. Turns a form into a conversation. Code owns the order of questions, every check, the card and the submit; the model only reads one reply or attachment into slot values. Sessions on D1, Postgres or Durable Objects, and the same actor over MCP and in a copilot.

Source: https://docs.omazy.ai/build-on-omazy/kits/actors/

:::caution[Preview]
The kit is a preview in `@omazyai/sdk` 0.5.3. Its interface may change before 1.0, so pin the exact version. It is TypeScript only.
:::

```ts
import { actor, actorRuntime, d1SessionStore, expireIdle, EXTRACT_PROMPT, minorUnits, slot } from '@omazyai/sdk/actors'
```

An actor collects the input of one capability, its **target**, through a conversation. A person
writes "Hemi Hossain paid 29,900 taka for the November invoice" and sends a photo of the bank
slip; the actor reads both, looks up the tenant and the invoice, checks the bank reference, asks
for what is missing or doubtful, and ends with a card the person confirms.

**The rule: code owns the journey, the model only reads.** Which slot comes next, which are
required, every check and the submit are code. Each turn the model does one narrow job: it reads
what the person sent into `{slot, value, confidence, evidence}` items. Nothing it returns can
reach the target. Only the person's click on the card does, through the
[guard](/build-on-omazy/kits/guard/).

The kit builds on the [capabilities](/build-on-omazy/kits/capabilities/), guard and
[AI](/build-on-omazy/kits/ai/) kits. It uses only Web standard APIs and runs on Cloudflare
Workers, Node, Bun and Deno.

## Define an actor

The payment receipt actor from Joya. Its target records a pending manual bank payment, which is
R3: a second person approves it.

```ts
export const paymentReceipt = actor<AppCtx>({
  id: 'payment_receipt', version: 3, owner: 'payments',
  target: 'payment_record_manual_bank',               // the one capability it submits
  title: { en: 'Record a manual bank payment', bn: 'ব্যাংক পেমেন্ট লিখুন' },
  model: { use: 'extract.fast', fallback: 'extract.strong' },
  prompt: { template: 'actors/payment-receipt', version: 1, languages: ['en', 'bn'] },
  attachments: { kinds: ['image/jpeg', 'image/png', 'application/pdf'], vision: 'vision.strong', maxBytes: 5_000_000 },
  evals: 'evals/actors/payment-receipt.jsonl',
  caps: { perRunUsd: 0.05, perDayUsd: 5 },
  slots: [
    slot('tenant_id', {
      label: { en: 'tenant', bn: 'প্রতিষ্ঠান' },
      hint: 'The organisation that paid, by name.',
      lookup: { capability: 'tenants_list', args: (q) => ({ q }), choices: (r) => r.rows.map((t) => ({ id: t.id, label: t.name })) },
    }),
    slot('amount', { ...minorUnits({ currency: 'BDT' }), threshold: 0.85 }),
    slot('currency', { default: 'BDT' }),
    slot('external_ref', {
      label: { en: 'bank reference', bn: 'ব্যাংক রেফারেন্স' },
      check: { capability: 'payment_ref_unused', args: (v) => ({ ref: v }), ok: (r) => r.unused || 'That bank reference is already used by another payment.' },
    }),
    slot('invoice_id', {
      label: 'invoice', after: ['tenant_id'],
      lookup: { capability: 'invoices_open', args: (q, v) => ({ tenant_id: v.tenant_id, hint: q }), choices: (r) => r.rows.map((i) => ({ id: i.id, label: i.id })), auto: true },
    }),
    slot('proof_key', { derive: ({ attachments }) => attachments.find((a) => a.kind.startsWith('image/'))?.key }),
    slot('recorded_by', { derive: ({ ctx }) => ctx.principal.id }),   // never typed, never extracted
  ],
  summary: (_values, _lang, rows) => {
    const v = Object.fromEntries(rows.map((r) => [r.slot, r.display]))
    return `Record a pending bank payment of ${v.amount} from ${v.tenant_id}, bank ref ${v.external_ref}, for ${v.invoice_id}.`
  },
  handoff: (prefill) => `/payments/new?${new URLSearchParams(prefill as Record<string, string>)}`,
})
```

`actor()` checks the definition when the module loads and builds the unit manifest for its model
calls (`actorUnit` from the AI kit). The lookups and checks of its slots become the unit's
allowed tools, at most R1. A turn that carries an image asks for the `vision` role for that one
call (the AI kit's per-call `role`), so text and images stay one unit.

**The target is R2 or higher.** At R0 and R1 the guard runs a call with no confirm, so a
conversation would end in a change no person agreed to on a card. `actor()` throws `ActorError`
for an R0 or R1 target. Give the capability itself (`target: recordPayment`) and the tier is
checked when the module loads; give its name and it is checked when the runtime is built. A target
whose `riskFor` lowers some input below R2 gets no card for that input: the session stays open
with the refusal `tier_below_confirm`, and the person finishes in the form.

Put the extractor's prompt in your prompt map. `EXTRACT_PROMPT` is the kit's; you may write your
own with the same two variables, `{{title}}` and `{{fields}}`, which come from code:

```ts
const prompts = promptTemplates({ 'actors/payment-receipt': { 1: { en: EXTRACT_PROMPT, bn: EXTRACT_PROMPT } } })
```

## Run it

```ts
const actors = actorRuntime<AppCtx>({
  ai,                                   // createAi({ ..., guard, registry })
  registry: reg,                        // the target's schema and tier come from here
  guard,                                // lets status() settle an approval
  actors: [paymentReceipt],
  sessions: d1SessionStore(env.OPS_DB),
  language: (ctx) => ctx.locale,
})

const r = await actors.start(ctx, 'payment_receipt', { text, attachments })
await actors.reply(ctx, r.session, { text: 'DBBL-7731-20261121' })
await actors.reply(ctx, r.session, { choose: { slot: 'tenant_id', id: 'hemihossain' } })
await actors.reply(ctx, r.session, { affirm: true })        // the "yes" button on a doubtful value
await actors.confirm(ctx, r.session, r.card.id)             // the person's click
await actors.handoff(ctx, r.session)                        // finish in the form
```

Every call returns an `ActorReply`: the `state`, a `message` to show (what changed, then the
question or the card), the `question` with its `choices`, the `card`, the `changes`, `notes`, a
`refusal` when something was refused, and `handoff` with the pre-fill.

### A typed "yes"

`affirm` is the click on the yes or no button of a doubtful question. A typed "yes" is text, and
the kit reads text through the extractor, which may settle the value or not. To make a typed yes
act like the button, map it in your surface before calling `reply`, and only while the question
asks for one:

```ts
const YES = /^(yes|y|yeah|correct|right|ঠিক|হ্যাঁ|জি)[.!]?$/i
const NO = /^(no|n|nope|wrong|না)[.!]?$/i

async function answer(ctx: AppCtx, session: string, last: ActorReply, text: string) {
  const t = text.trim()
  if (last.question?.affirm && YES.test(t)) return actors.reply(ctx, session, { affirm: true })
  if (last.question?.affirm && NO.test(t)) return actors.reply(ctx, session, { affirm: false })
  return actors.reply(ctx, session, { text })
}
```

Keep the words to a short list you own. Anything longer, such as "yes but it was 52,000", goes
to the extractor as text, which reads the correction.

An attachment is `{ kind, name?, key?, bytes?, text?, image? }`. Put text already read from a PDF
or a spreadsheet in `text`; a photo goes in `image` (a URL or base64) for the vision model. A
kind the actor does not list is refused with a note.

## The payment receipt, turn by turn

1. **The person:** "Hemi Hossain paid 29,900 taka by bank for the November invoice."
   The extractor returns `tenant_id: "Hemi Hossain"`, `amount: "29,900"`, `currency: "BDT"`,
   `invoice_id: "November"`. Code reads them: the tenant is looked up through `tenants_list` and
   finds one, `hemihossain`; the amount becomes 2,990,000 minor units; the invoice is looked up
   for that tenant and finds `INV-0042`. The bank reference is missing, so the clarifier asks:
   **"What is the bank reference?"**
2. **The person** sends the slip photo. This turn's call runs on `vision.strong`, in the same run.
   The extractor reads
   `external_ref: "DBBL-7731-20261121"` and the amount again from the slip, which agrees.
   `payment_ref_unused` passes, `proof_key` is the slip's storage key and `recorded_by` is the
   signed-in person. Nothing is missing, so the card shows: **"Record a pending bank payment of
   BDT 29,900.00 from Hemi Hossain, bank ref DBBL-7731-20261121, for INV-0042. Please check every
   value and confirm. A second person approves it before it takes effect."** Each row says where
   its value came from.
3. **The person** clicks confirm. The target is R3, so the guard creates an approval and the
   session is `pending_approval`. Finance approves with step-up; the route records the payment as
   pending; `status()` then answers `done` with the result.

Three messages, the same checks as the form, and one more human check than before.

## What the model can and cannot do

| | |
|---|---|
| Reads | One message and its attachments per turn, into items for the slots it is told about |
| Cannot | Choose the next question, fill a derived slot, give an id, change the target, submit, or see the confirm token |

- An item for an unknown slot, a derived slot or a slot with `extract: false` is dropped and
  recorded on the turn's `dropped`.
- A lookup slot takes what the person wrote as a query, never as an id. An id in an attachment is
  looked up as a name and finds nothing.
- The message, the attachments and the values so far are fenced as untrusted data after the
  rules. The prompt holds only text from code.
- The model's output is checked against a closed schema. An output that fails is treated as
  nothing read.

## Slots

The slots are the target's input fields. The ones the actor lists come first, in its order; the
other fields follow in schema order (`only: true` leaves them out).

| Option | What it does |
|---|---|
| `label`, `hint`, `ask` | The slot's name for a person, what the extractor is told, the question for a missing value. Words per language |
| `required` | Default: required in the schema, with no default and not derived |
| `after` | Slots that must be filled first. A lookup waits for them; a change to them looks it up again |
| `when` | The slot is part of the input only while this holds |
| `default` | A value, or a function of the values so far, used at the card |
| `derive` | Computed by code from the values, the ctx and the attachments. Never extracted or asked |
| `threshold` | Below this confidence the value is asked about. Default the actor's, 0.8 |
| `lookup` | `{ capability, args, choices, auto }`: an R0 or R1 read that turns a name into an id |
| `check` | `{ capability, args, ok }`: an R0 or R1 read that must pass, such as a duplicate check |
| `validate` | The product's own function, the one its route runs. True, or one sentence |
| `parse`, `format` | From what was read to the target's value, and back for a person. `minorUnits()` does both for money |
| `choices` | Fixed choices offered with the question |

Without a `parse`, a value is read by its schema type: numbers with commas or Bangla digits,
yes and no, an enum ignoring case. Then the schema's own limits are checked (range, length,
pattern, date). Before the card, the target's own `parse` runs on the whole input and
`check(values, ctx)` on the actor runs the cross-field rules.

## The clarifier

It asks for one slot at a time, the first in order that is missing or in doubt:

| Kind | Example |
|---|---|
| `missing` | What is the bank reference? |
| `doubtful` | I read BDT 25,000.00 for the amount. Is that right? |
| `choice` | More than one tenant matches "Hemi". Which one? |
| `not_found` | I could not find a tenant matching "Hemy". Could you check it? |
| `invalid` | That bank reference is already used by another payment. What is the bank reference? |
| `conflict` | The amount reads BDT 29,900.00 in one place and BDT 25,000.00 in another. Which is right? |

A correction ("no, it was 52,000") moves the slot and the reply says so: "Changed the amount from
BDT 29,900.00 to BDT 52,000.00." What depends on a changed slot is looked up or checked again.

English and Bangla ship with the kit, Bangla with Bangla numerals and lakh grouping. Change a
sentence or add a language with `text: { bn: { missing: (label) => ... } }`. To have a model
reword a question, pass `phrase(ctx, question, language)`, which should run a task of your own;
the template's text is used when it returns nothing, and the choices never change.

## The card and the submit

The card lists every value of the target's input with its label, how it reads, its source
(`message`, `attachment`, `lookup`, `person`, `default`, `derived`, `prefill`) and its evidence.
Its `id` is a hash of the input; `confirm()` with an older card is refused as `stale_card`.

`confirm(ctx, session, cardId)` is the only call that reaches the target, and only for the
person who owns the session:

| Target tier | At the card | On confirm |
|---|---|---|
| R2 | the guard's preview and confirm token, kept on the session | runs with the token |
| R3, R4 | nothing | `pending_approval`; `status()` settles it when the approval is decided |

A refusal from the guard (permission, a switch, a rate limit, stale state) is shown and the
session goes back to collecting.

## One run per session

A session is one run of the actor's unit. The first turn that needs the model, a lookup or the
submit starts it; every later turn opens the same run again with `ai.resume`, so the run record
holds the whole conversation: each model call, each lookup and check, and the submit, in order.
The unit's `perRunUsd` caps the whole session. The run ends when the session does: `ok` at done,
pending approval or handoff, `cancelled` at cancel or expiry.

A spend cap stops model calls, not the person's own submit: when the run cannot be resumed because
a day cap is reached, the confirm is still recorded on it. A session continued from another seat,
or after a new version of the actor, cannot carry its run on; the old run is closed and a new one
starts, and the session's `runs` lists both.

## Handoff

`handoff()` ends the session and returns the form's pre-fill: the filled, default and derived
values, never a doubtful one. `pending` holds the values still in doubt, for the form to show as
suggestions, and `url` is the product's link. Every open reply carries the same pre-fill, so a
surface can offer "finish in the form" at any point.

## Sessions

A session holds the slots, the question asked, the card, the attachments it has seen (references
only), its run and its turns. It expires after 24 hours without a reply (`idleMs`), and a session
waiting for approval does not expire. Every write names the version it read; a second
surface writing at the same time gets `ActorRefusal('conflict')`.

| Store | Use |
|---|---|
| `memorySessionStore()` | Tests and one process |
| `d1SessionStore(db)` | Cloudflare D1. Apply `ACTOR_MIGRATIONS` once (`applyActorMigrations`) |
| `pgSessionStore(query)` | Postgres from Node, through `pool.query` or any driver of that shape. The same SQL (`applyActorMigrationsPg`) |
| `durableObjectSessions(env.ACTOR_SESSIONS)` | One Durable Object per session. Export `class ActorSession extends ActorSessionObject {}` and bind it |

With a Durable Object, give D1 as `drafts`: every write is copied there, so `resume(ctx)` finds a
person's open session from another surface. A session lives with one person in one tenant;
anyone else gets `not_found`.

### Expiry

A session past its idle time expires the next time anyone loads it. To close the ones nobody comes
back to, run `expireIdle` from a cron:

```ts
export default {
  async scheduled(_event, env) {
    const r = await expireIdle(d1SessionStore(env.OPS_DB), Date.now(), { runs: d1RunStore(env.OPS_DB) })
    // { expired, skipped }: run it again while expired equals the limit (100 by default)
  },
}
```

It reads open sessions past their idle time, oldest first, marks each `expired` with a turn from
`cron`, and with `runs` closes each one's run as `cancelled`. A session someone wrote to in the
meantime is skipped, since the write names the version it read. It takes the memory store, D1 or
Postgres (`idle(at)` and `put`). With a Durable Object, run it over the D1 drafts; the object
expires its own copy on the next load.

## Over MCP and in a copilot

`actorTools(runtime, { audiences, permission })` returns `actor_start`, `actor_reply`,
`actor_status` and `actor_confirm` as capabilities. Add them to your registry and a door serves
them with the guard like any tool. The first three only read and write the session, so they are
R1, and they never submit: an R1 tool that reached the target would let the client's model make
the change with no person in the loop. At the card the result names the call that submits it:

```json
{ "state": "confirm", "card": { "id": "c_...", ... }, "submit": { "capability": "actor_confirm", "arguments": { "session": "act_...", "card": "c_..." } } }
```

`actor_confirm` is R2. The client calls it on the same door, and the guard asks the person first
(an elicitation or a confirm token), with the card's summary and rows as the preview. Then the
runtime submits the card exactly as a click on it does: an R2 target runs, an R3 target waits for
approval. The session records the outcome, so `actor_status` then reads `done` or
`pending_approval`. A confirm given for a card that changed since (the person said something
more) is refused as stale. The model still cannot submit on its own: the guard's confirm on
`actor_confirm` is the person's click.

A client that calls the target itself, with the card's `input`, still makes the change through
the guard, but the session does not see it and stays at `confirm`. Point clients at `submit`.

With `actors: [...]`, `actor_start` takes only those ids, and its version is how many there are.
Adding an actor to the door is then an additive change in the catalog snapshot (one more value, a
higher version), which `OMAZY_UPDATE_SNAPSHOTS=1` accepts. Removing one is breaking. Without
`actors`, `actor_start` takes any id and stays at version 1.

`copilotActorStep(runtime)` gives a copilot's model one tool, `actor_start`, to open an actor.
After that, `route(ctx, session, message)` sends the person's own messages to the actor by code
until the session closes, then returns null so the copilot answers again. The runtime may be a
function that returns it, read on first use.

Pass the same registry, `actorTools` included, to the door and to `createCopilot`. The copilot
finds the actors behind those four tools, hands off with its own `actor_start`, and keeps the
door's four away from its model. No filtered registry is needed.

## Testing

Script the model's extractions with a fake Core client and run conversations end to end:

```ts
const items = [[{ slot: 'tenant_id', value: 'Hemi', confidence: 0.95, evidence: 'Hemi', from: 'message' }]]
const r = await actors.start(ctx, 'payment_receipt', { text: 'Hemi paid 29,900' })
expect(r.question?.kind).toBe('choice')
```

The kit's own suite covers the payment receipt in three turns, corrections, doubtful values,
ambiguous lookups, refused values, no submit without the confirm, R3 approvals, handoff, resume
from D1, one run per session, expiry from a cron, targets below R2, and injection text in an
attachment. Give each actor a golden set of real
conversations in its `evals` file.
