# Copilot kit (TypeScript)

Reference for @omazyai/sdk/copilot. An open conversation on the product's own data, streamed to useChat. Tool search, a whole-batch check before any call runs, consent cards for R2, approval cards for R3, standing grants, actors and workflows. Threads in Durable Objects.

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

:::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 { createCopilot, createGrants, d1GrantStore, durableObjectThreads, CopilotThreadObject } from '@omazyai/sdk/copilot'
```

A copilot is a conversation with the people who run an account. It answers from the product's
data, hands the person to an [actor](/build-on-omazy/kits/actors/) when they want to fill a form,
starts [workflows](/build-on-omazy/kits/flows/), and proposes changes.

**The rules:**

- Each turn is one run of a copilot unit in the [AI kit](/build-on-omazy/kits/ai/): its role,
  caps, tags and usage.
- Every capability call goes through the [guard](/build-on-omazy/kits/guard/) and is in the run's
  effects ledger.
- The whole batch of calls the model proposes is checked before any of it runs. A read paired
  with a send does not run first.
- An R2 call becomes a consent card. Only the person's click runs it.
- An R3 or R4 call becomes an approval card with the review link. Nothing runs until the decider
  approves it.
- It never says an action is done that it did not complete: each tool result tells the model what
  happened, and the outcomes the next turn reads are written by code.

The reply streams as the AI SDK UI message stream, so `useChat` from `@ai-sdk/react` reads it with
no adapter. The kit itself does not import `ai` or React.

## Set it up

```ts
// The unit: Joya's admin copilot.
const joyaCopilot = copilotUnit({
  id: 'admin_copilot', version: 1, owner: 'ops',
  model: { use: 'converse' },
  prompt: { template: 'copilot/admin', version: 1, languages: ['en', 'bn'] },
  context: { layers: ['platform', 'tenant', 'role', 'surface', 'unit'], budgetTokens: 20_000, untrusted: ['message'] },
  memory: { read: ['working', 'known', 'conversation', 'person'], write: ['person'] },
  tools: { allow: ['tenant_get', 'staff_list', 'staff_add', 'message_send', 'report_get'], maxTier: 'R3' },
  evals: 'evals/copilot.jsonl',
  caps: { perRunUsd: 0.10, perDayUsd: 20 },
})

const copilot = createCopilot<JoyaCtx>({
  ai, registry,                                   // createAi with the guard, the registry and a memory store
  unit: joyaCopilot,
  threads: durableObjectThreads(env.COPILOT_THREADS),
  audience: 'admin',                              // the door whose tools search may find
  toolSearch: { core: 16 },                       // the first 16 allowed tools up front
  standingGrants: createGrants({ store: d1GrantStore(env.OPS_DB), registry }),
  surface: (ctx, screen, id) => screenContext(ctx, screen, id),
  actors: { runtime: actorRuntime },             // optional when the registry holds actorTools
})

export class CopilotThreads extends CopilotThreadObject {}

// The guard (made before the copilot) sends its approval events to it:
//   createGuard({ ..., onApproval: (e) => Promise.all([flows.onApproval(e), copilot.onApproval(e)]) })

// In the Worker's fetch:
const res = await copilot.handle(req, ctx, { waitUntil: (p) => ectx.waitUntil(p) })
if (res) return res
```

`createCopilot` checks the unit when it is built: it must be a copilot unit, fence the person's
message (`untrusted: ['message']`), read `working` memory (that is how a turn learns what
happened to its cards), and allow only capabilities the registry has.

`copilot.handle(req, ctx)` serves five routes under any prefix:

| Route | What it does |
|---|---|
| `POST …/chat` | One turn, from a `useChat` request. The chat id is the thread id |
| `GET …/threads` | The person's threads in this tenant, newest first: `{ threads: [{ id, summary, updatedAt }], next }`. `?limit=` 1 to 100 (default 20), `?cursor=` the `next` of the page before |
| `GET …/threads/<id>` | The thread's messages, to start `useChat` from, the consent cards still waiting, and the approvals not yet settled |
| `POST …/cards/<id>/confirm` | The person's click on a consent card, or on an actor's card. Body `{ thread }` |
| `POST …/cards/<id>/decline` | Declines the card. It never runs |

`copilot.turn(ctx, { thread, text, screen })`, `copilot.confirm`, `copilot.decline`,
`copilot.history` and `copilot.listThreads(ctx, { limit, cursor })` are the same without HTTP.

## In the page

```tsx
import { useChat } from '@ai-sdk/react'
import { DefaultChatTransport } from 'ai'

const { messages, sendMessage } = useChat({
  id: threadId,
  messages: initial,                               // from GET /copilot/threads/<id>
  transport: new DefaultChatTransport({ api: '/copilot/chat', body: () => ({ screen: { name: 'tenant', id: tenantId } }) }),
})
```

Each message's parts are `text`, `dynamic-tool` (every call and its outcome), and the kit's data
parts:

| Part | Holds |
|---|---|
| `data-consent` | A consent card: capability, title, the guard's preview, the arguments, expiry and status (`waiting`, `confirmed`, `declined`, `expired`, `stale`, `failed`) |
| `data-approval` | An approval card: capability, preview, who decides, expiry, `reviewUrl` and status (`waiting`, `approved` while it runs, `executed`, `refused`, `failed`, `stale`, `expired`, `withdrawn`), with `message` for the reason or the error |
| `data-actor` | The actor's question or its card, while the conversation is handed to it |
| `data-memory` | A memory the model proposed. It is kept only after the person confirms it |

A confirm button posts to `…/cards/<id>/confirm`. The guard's confirm token stays on the server:
it is never in the stream, the page or the model's context.

The [UI kit](/build-on-omazy/kits/ui/) draws these parts: its `CopilotPanel` takes this `useChat`
result, or runs its own chat on the same routes.

## One turn

1. The thread is locked, so two turns of one thread never run at once (a second gets 409; a lock
   left by a crash runs out after two minutes).
2. When an actor has the conversation, the person's message goes to it, word for word, and no
   copilot model call is made.
3. Otherwise a run of the unit starts. The context is built from the unit's recipe: the screen
   context, card outcomes since the last turn and cards still waiting (in working memory),
   confirmed long-term memory, the conversation from the AI kit's thread store, and the person's
   message, fenced.
4. The model gets the core tools, `tool_search`, the actor tool and `memory_propose` when the unit
   writes memory. It streams its reply.
5. Each batch of tool calls is checked whole (below). After a batch that waits for the person, the
   model answers in words only.
6. The run finishes. The turn goes into the conversation with a line per call outcome, written by
   code, such as `[message_send: pending_approval, card appr_…]`.

## The batch check

Before any call in a batch runs, every call is checked: is the tool offered now, are its
arguments valid, is its tier for these arguments within the unit's `maxTier`. Each call then
falls in one of four kinds: a read (R0, R1), an R2 a standing grant covers, an R2 that needs a
card, or an R3 or R4 that needs an approval.

| The batch holds | What happens |
|---|---|
| A call that fails a check | Nothing runs. No card, no approval. The model reads which call failed |
| Only reads and granted R2 calls | They run in order. Each granted run is held against today's cap first, and given back when the guard does not run it |
| Any call that needs a card or an approval | Nothing runs now. Reads in the batch are `not_run`. R2 calls become consent cards; then R3 calls become approvals. If the guard refuses one of the R2 calls, no card is shown and no approval asked for. If it refuses one of the R3 calls, the approvals the batch already asked for are withdrawn (`guard.withdraw`), the later R3 calls are not asked, and no card is shown |

So "read the staff list and tell the front desk" never reads first and sends later: both wait for
the person, and the model can ask again for the read on its own.

## Approval card status

An approval card's status follows the guard. Give `copilot.onApproval` to the guard as
`onApproval` (with a late-bound reference, since the guard is made first; beside
`flows.onApproval` if you run workflows). When the copilot asks for an approval it links the
approval id to the thread (`threads.link`); each event then moves the card:

| Event | Card status |
|---|---|
| `decided`, approved | `approved`, while the change runs |
| `decided`, refused | `refused`, with the approver's reason in `message` |
| `executed` | `executed` |
| `failed`, `stale` | `failed` (the error code in `message`), `stale` |
| `expired` | `expired` |
| `withdrawn` | `withdrawn`, with the reason |

The card changes in the message the person saw, so `GET …/threads/<id>` shows it. The next turn
streams the card again with its new status, and its working memory tells the model what happened,
in a sentence written by code. A settled card never moves again, and a late `approved` never
follows a later status.

An event that comes while a turn holds the thread waits in the store, and the write that lets the
thread go applies it. Only the thread that asked, of the person who asked in that tenant, is
changed. `onApproval` never throws; errors go to `onError`.

## Tool search

The model starts with a core set: `toolSearch.core` as a number takes the first of the unit's
`tools.allow`, a list names them. `tool_search` finds the rest with BM25 over names, titles,
descriptions and synonyms (`registry.search`), at most `toolSearch.limit` (5) a search, and only
tools the unit allows, at or below its `maxTier`, at the copilot's door. A tool found once stays
offered for the rest of the thread.

## Standing grants

A person may let the copilot run one named R2 capability without a card.

```ts
const grants = createGrants({ store: d1GrantStore(env.OPS_DB), registry })

// The settings page's handler. ctx.channel is 'console'.
await grants.set(ctx, { capability: 'staff_add', days: 30, dailyCap: 5 })
await grants.revoke(ctx, grantId)
await grants.list(ctx)
```

- Set only from a settings channel (`console` by default). A copilot, actor, MCP or automation
  call cannot set one, and `createGrants` refuses a channel list that holds `copilot`.
- Only a capability whose declared tier is R2. Never R3 or R4: an approval cannot be waived. A
  call whose tier for its arguments is not R2 is not covered.
- At most 90 days, and 1 to 500 runs a UTC day. The count is atomic in D1.
- A run counts only when the guard runs it. The copilot holds one of the day's runs before the
  call (`grants.take`), so two turns at once cannot pass the cap, and gives it back
  (`grants.release`) when the guard refuses the call or it fails. With a cap of 1 and two turns
  at once, one runs and the other gets a consent card.
- One person in one tenant. Setting a grant again replaces the earlier one. Revoking works from
  any channel.

A granted call runs through the guard as confirmed upstream, so the request log shows it and the
guard still checks the preview's state.

Apply `GRANT_MIGRATIONS` once (`applyGrantMigrations(db)`, or `grantMigrationSql()` for a
migration file). Tables: `copilot_grants` and `copilot_grant_uses`.

## Screen context

The client names the screen and the record id, nothing else:
`{ screen: { name: 'tenant', id: 'hemibeauty' } }`. The name must match `[a-z][a-z0-9_./-]*` and
the id `[A-Za-z0-9_.:-]+`; anything else is dropped. `surface(ctx, screen, id)` rebuilds the
context on the server, as the person may see it, and its text is fenced as data. Any other field
the client sends (a title, a "context", earlier messages) never reaches the model. The thread's
history is the server's.

## Actors

With `actors: { runtime }`, the model gets `actor_start`. When it calls it, the person's own
message (not the model's paraphrase) goes to the actor, the rest of the batch does not run, and
every later message goes to the actor until its session closes. The actor's card is confirmed
through the same `…/cards/<id>/confirm` route.

One registry serves an actor over MCP and in the copilot. When the registry holds the
capabilities from `actorTools`, `createCopilot` finds their runtime and actor ids there, so
`actors` may be left out. The door's `actor_start`, `actor_reply`, `actor_status` and
`actor_confirm` are never shown to the copilot's model, even when the unit allows them: the copilot hands off with its own
`actor_start` and routes replies by code. A capability named `actor_start` that does not come from
`actorTools` is still refused when the copilot is built. Pass `actors` to name other actors or
another runtime; it wins over the registry's.

## Workflows

A workflow starts through a capability, so the guard decides it like any other change:

```ts
const fulfilStart = workflowCapability(flows, paymentFulfil, {
  name: 'fulfilment_start', audiences: ['admin'], title: 'Start fulfilment',
  description: 'Starts fulfilment for a paid order: level, term, go-live and a notice to the owner. …',
  permission: 'payments.write', risk: 'R2',
  input: schema.object({ payment_id: schema.id() }),
  key: (_ctx, i) => `fulfil:${i.payment_id}`,
})
```

Add it to the registry and the unit's `tools.allow`. The person confirms the card, then
`flows.start` runs it, one run per key.

## Memory

`memory_propose` stores a proposal; only a person confirms it, from a channel the memory kit
allows (`console` by default), never from the copilot. Only confirmed memory reaches a prompt.

## The support agent

RFC-0901 7.11: a copilot unit with a help-centre recipe.

```ts
const support = supportRecipe<JoyaCtx>({
  owner: 'support', model: { use: 'converse' },
  prompt: { template: 'copilot/support', version: 1, languages: ['en', 'bn'] },   // include SUPPORT_PROMPT
  help: helpSearch,                        // help pages and release notes
  health: accountHealth,                   // account checks and recent errors, as findings
  mayReadTenant: (ctx) => hasSupportGrant(ctx),
  ticket: 'support_ticket_draft',
  evals: 'evals/support.jsonl', caps: { perRunUsd: 0.05, perDayUsd: 5 },
})
const ai = createAi({ ..., retrievers: { ...support.retrievers } })
const helpDesk = createCopilot({ ai, registry, unit: support.unit, threads })
```

`supportTicketCapability({ audiences, permission, save })` is the R2 capability that drafts the
ticket: the question, what was checked, the findings and the steps tried. The person confirms the
draft on a card. The findings are live data, so the unit never uses a cached reply.

## Threads

A thread belongs to one tenant and one person. The Durable Object is found by tenant, person and
thread id, so another person's thread of the same id is a different object, and theirs.

| Where | Holds |
|---|---|
| The thread's Durable Object (`CopilotThreadObject`) | The UI messages, the consent and approval cards, the open actor, tools found, the lock, and approval updates that came while a turn held it |
| An approval's Durable Object (same class, named by the approval id) | Which thread asked for it |
| The AI kit's memory store (`d1MemoryStore`: `ai_threads`, `ai_turns`) | The conversation the model reads, keyed by tenant, person and thread id, compacted past its budget |

`memoryThreadStore()` is for tests.

The list of a person's threads comes from the AI kit's store (`listThreads` on `ai_threads`, by
the `(tenant, person, updated_at)` index), so it needs a unit that reads `conversation` and an AI kit with a
memory store. Without them `listThreads` is null and `GET …/threads` answers 404. A thread is
listed once its first turn is written.

A thread id is the person's own. When two people pick the same id (`th1`, or a chat id a client
made up), each has their own Durable Object, their own conversation in the AI kit's store and their
own entry in their list. Neither sees the other's, and neither turn fails.

## Planned

Not in the kit yet:

- **Resuming a stream mid-turn.** A page that reloads while a turn streams sees the reply when the
  turn ends (`GET …/threads/<id>`), not the rest of the stream. `useChat`'s `resume` is not
  served.
- **The copilot over MCP: `ask` and `do` tools (W23).** An MCP client will reach the copilot
  through two tools on a door, one that asks and one that proposes a change, with the same batch
  check and cards. Until then the copilot is served only over HTTP.

## Why not AIChatAgent

`@cloudflare/ai-chat` 0.12 runs chat turns over its own WebSocket protocol (`useAgentChat`), runs
tool approvals and continuations its own way, and changes most weeks. The batch check, the cards
and the grants must behave the same on Node, so the kit keeps its own loop and a plain Durable
Object, and speaks the AI SDK's HTTP stream that `useChat` reads.

## Testing

`fakeCore` from the [testing kit](/build-on-omazy/kits/testing/) scripts the model; `spyGuard`
records what reached the guard. The kit's own tests run the injection suite against the copilot
with a model that obeys every hostile text: no R3 or R4 runs, and no R2 runs without the card the
person was shown.

## Example

`sdk/typescript/examples/copilot-worker.ts`: a notes product with a copilot on a Durable Object and
D1, a settings route for grants, and a page on the UI kit's panel. Its workerd test runs it under
Miniflare with a fake Core API.
