# AI kit (TypeScript)

Reference for @omazyai/sdk/ai. Every model call belongs to a unit with a manifest. Runs and their capability calls are recorded, calls are tagged and capped before they start, context is layered with budgets and fenced input, and long-term memory reaches a prompt only after a person confirms it. An optional Vercel AI SDK provider runs on the same gateway.

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

:::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 { createAi, d1MemoryStore, d1RunStore, promptTemplates, task } from '@omazyai/sdk/ai'
```

The AI kit is the run layer between your product and Omazy's models. Model calls go to the
Core API through the SDK client. The kit adds what each product needs on top: a manifest for
every unit, a record of every run and of each capability call it makes, the context builder,
memory and prompt versions. It uses only Web standard APIs and runs on Cloudflare Workers, Node,
Bun and Deno. Runs, effects and memory live in your database.

It builds on the [capabilities](/build-on-omazy/kits/capabilities/) and
[guard](/build-on-omazy/kits/guard/) kits. Every capability call a run makes goes through the
guard.

## Units and manifests

Every model call belongs to a unit. A unit is a task, an actor, a copilot or a workflow, and
each is declared once:

```ts
const BriefDraft = schema.object({ title: schema.text(200), summary: schema.text(2000) })

export const briefFromSite = task({
  id: 'brief_draft_from_site', version: 2, owner: 'onboarding',
  surfaces: ['console:onboarding'],
  model: { use: 'extract.strong', fallback: 'extract.fast', temperature: 0, maxOutputTokens: 2000 },
  prompt: { template: 'tasks/brief-from-site', version: 2, languages: ['en', 'bn'] },
  context: { layers: ['platform', 'tenant', 'unit'], retrievers: ['site_pages'], budgetTokens: 12000, untrusted: ['site_text'] },
  memory: { read: ['tenant'], write: [] },
  input: schema.object({ url: schema.text(300), site_text: schema.text(200_000) }),
  output: BriefDraft,
  target: 'brief_draft_save',                 // the capability the output is saved through
  tools: { allow: ['tenants_list'], maxTier: 'R1' },
  evals: 'evals/tasks/brief-from-site.jsonl',
  caps: { perRunUsd: 0.05, perDayUsd: 5 },
  tags: { feature: 'onboarding' },             // optional, on every call of the unit
})
```

| Kind | Function | Notes |
|---|---|---|
| Task | `task()` | One structured call. Needs `output`; `target` saves it |
| Actor | `actorUnit()` | Needs `target`, the one capability it submits. Extra fields (slots, handoff) are kept for the actors kit |
| Copilot | `copilotUnit()` | No target; it calls tools |
| Workflow | `workflowUnit()` | For the model calls a workflow's steps make |

A manifest that breaks a rule throws `UnitError` when the module loads, listing every problem.
The rules:

- `model.use` and `model.fallback` are roles such as `extract.fast`, never a model name. The account maps roles to models.
- The prompt names a template key, a version and its languages.
- `context.layers` must include `unit`. Budgets are whole tokens, and a layer's budget is at most the whole budget.
- Memory scopes come from `working`, `known`, `conversation`, `person` and `tenant`. A unit cannot write `working`.
- `tools.maxTier` is R0 to R4. `evals` is a `.jsonl` path, or `{ path, threshold }` when the unit carries its own pass mark (0 to 1). `caps.perDayUsd` is at least `caps.perRunUsd`.
- `cacheTtl` is 0, or 60 to 2592000 seconds, and cannot be set on a `live` context.

For CI, `checkUnits(units, { registry, prompts, retrievers })` reports repeated ids, tools the
registry lacks or holds above the unit's tier, and missing prompts and retrievers.
`findDirectModelCalls(files, { allow })` finds every `.ai.complete(`, `.ai.stream(` and
`/ai/complete` outside the paths you allow. Fail the build when either returns anything.

## Set it up

```ts
const ai = createAi<AppCtx>({
  omazy: (ctx) => coreClientFor(ctx.tenant),      // the tenant's install token
  runs: d1RunStore(env.OPS_DB),                   // ai_runs, ai_effects
  memory: d1MemoryStore(env.OPS_DB),              // ai_memory, ai_threads, ai_turns
  prompts: promptTemplates(PROMPTS),
  guard, registry: reg,
  layers: {
    platform: () => PERSONA,                      // fixed per version
    tenant: (ctx) => tenantLine(ctx.tenant),
    role: (ctx) => whatThisSeatMayDo(ctx),
  },
  retrievers: { site_pages: (ctx, { input }) => fetchPages(input.url) },
  limits: { perTenantDayUsd: 2, globalDayUsd: 300 },
})

const r = await ai.run(ctx, briefFromSite, { url, site_text })
// { outcome: 'ok', runId, output, save, usage }
// | { outcome: 'refused_cap', cap, message } | { outcome: 'invalid_output', issues } | { outcome: 'error', code, message }
```

Apply `AI_MIGRATIONS` once, with wrangler migrations (`aiMigrationSql()` gives the text) or
`applyAiMigrations(db)`. They are additive and idempotent. `memoryRunStore()` and
`memoryMemoryStore()` do the same in memory for tests.

`ai.run` runs a task: it renders the prompt, builds the context, checks the caps, makes one
structured call, checks the output and saves it through `target`. It never throws for a refusal
from the model or the platform. When the save is an R2 capability, `save` is the guard's
`confirm_required` with its preview and token. Record the person's confirm against the same run:

```ts
await ai.callInRun(ctx, briefFromSite, r.runId, 'brief_draft_save', r.output, { confirmToken: r.save.token })
```

Units that hold a conversation open a run with `ai.start(ctx, unit, { language, vars })` and
use its scope: `context()`, `complete()`, `stream()`, `structured()`, `call()`, `propose()`,
`known`, `working` and `finish()`.

### Resume a run

A conversation spans requests, and a Worker keeps nothing between them. Keep the run's id with
the conversation and open the same run again in the next request:

```ts
const run = await ai.start(ctx, intake, { vars, tags })       // first request
// ... save run.id with the conversation
const again = await ai.resume(ctx, intake, runId, { vars, tags }) // a later request
```

The scope is bound to the same `ai_runs` row. Its usage carries on from what the row holds, the
run cap keeps counting what the run has already spent, new effects continue its sequence, and the
day caps are checked again as at start (a refusal leaves the run open). Pass the same `vars` and
`tags` as at start: the prompt is rendered again in the run's language, and tags are not stored.

`resume` throws `ResumeRefusal` with a `code` when the run cannot carry on:

| Code | When |
|---|---|
| `not_found` | No such run, or it is in another tenant |
| `finished` | The run has an outcome already |
| `other_seat` | Another seat or person started it |
| `other_unit` | Another unit started it |
| `other_version` | Another version of the unit, or of its prompt, started it |

Resume a run from one request at a time. Usage is written as totals, so two requests on the same
run at once can lose one call's count. The actors kit holds this already: a session write that
loses a race is refused.

### A role for one call

A call can ask for another role than the unit's, for one call only:

```ts
const built = await run.context({ input, images })
const r = await run.structured(built, { role: 'vision.strong' })
```

Only a role the manifest declares is allowed: `model.use`, `model.fallback` or
`attachments.vision`. Any other throws before anything is sent. A role other than `model.use` is
tried alone, with no fallback. The platform records the role of each call, and the run row keeps
the last one, so a unit that reads text and images stays one unit with one run.

## The gateway

Every call a run makes goes out with:

- `model: "role:<name>"`, or the model your `roles` map gives the role. The platform resolves a role per install, workspace and account, with its own fallbacks. The unit's `fallback` role is tried once when the first fails with a model error, before any text arrived.
- `metadata: { unit, unit_version, prompt_version, run_id }`. The platform stores these beside each call, and the usage API groups by them. A call sent as `role:<name>` has its role in the platform's ledger too. When your `roles` map turns a role into a model name, the platform cannot see the role, so the kit adds a `role` tag, as long as your own tags leave one of the 8 keys free.
- Your own tags in the same `metadata`: the unit's `tags`, then the run's (`ai.run(..., { tags })` or `ai.start(..., { tags })`), then the call's (`scope.complete(req, { tags })`), a later layer replacing an earlier key. The platform's rules hold: at most 8 keys in all, each matching `[a-z][a-z0-9_.-]*` and at most 40 characters, values at most 200 bytes, sent as text. The four run tags and `role` are reserved. A manifest that breaks a rule throws when it loads; a run or call that does throws `TagError` before anything is sent. The usage API groups by `tag.<key>`.
- The unit's temperature and output limit. A caller may lower the limit, never raise it.
- `cache_ttl: 0` when the context is `live`, or the unit's `cacheTtl`. Send `live: true` on any call that carries live data.

Usage is summed on the run after each call and written at once, so a crash keeps it. Cost is
`usage.cost_micros` from the platform. When the platform gives none, the kit prices the tokens
from your `prices` card (US dollars per million tokens) and marks the run `costEstimated`. A call
with neither is counted in `unpricedCalls`.

### Caps

Before a run starts, the kit sums today's spend (UTC) in the run store and refuses the run when
it has reached a cap or the run's estimate would pass one: the unit's `perDayUsd` in this tenant,
then the `limits` for the tenant, the person and the product. Before every further call it checks
the run's own spend against `perRunUsd`. A 402 from the platform is a cap refusal too, never an
error. A refused run is recorded with outcome `refused_cap`.

The estimate is the context's tokens plus the output limit, at the role's price. Without a price,
only spend already made counts, and the platform's own caps are the backstop.

The kit's caps are per run and per UTC day. Monthly caps per person and per tenant (RFC-0901's $5
and $15) are the platform's: caps per tag, checked by Omazy before each call. The kit sends the
tags they key on and turns the platform's 402 into `refused_cap` with `cap: 'platform'`, so a
product does not count months itself.

### Structured output

A task's output is forced through its JSON Schema. The kit sends `response_format` with
`json_schema` (strict when every object is closed and every property required). When the model
answers `MODEL_UNSUPPORTED`, it sends the same schema as one forced tool, `submit_output`. Set
`structured: 'tool'` to always use the tool. The reply is checked against the schema either way:
a reply that does not match ends the run `invalid_output` and nothing is saved.

## Runs and effects

One `ai_runs` row per run: unit, kind, version, prompt template, version and language, role and
the model that answered, seat, tenant, person, channel, request id, start and end, outcome, calls,
cache hits, tokens, cost, and the context builder's report (tokens per layer, what was dropped,
compaction).

One `ai_effects` row per capability call the run made, in order: the capability, its tier, read
or write, the hash of the arguments, an idempotency key (a hash of the tenant, the capability and
the arguments, which is the intended effect), the outcome, the code, the approval id and a plain
sentence (the guard's refusal, or the preview's summary for a confirm or an approval). The kit
refuses before the guard, and still records:

- `refused_unit` with `tool_not_allowed` for a capability outside `tools.allow` (the target is always allowed), or `tier_above_unit` for one above `tools.maxTier`.
- `duplicate` with `already_done` for a write this run already made or holds for approval. Writes are never sent twice.

Everything else is the guard's outcome.

### Workflow steps in the ledger

The flows kit keeps its step records here, so one ledger holds every effect of a run. A row can
carry the workflow `step` it belongs to (`level`, or `add#2` for a bulk chunk), the step's kind,
and a `ref` to the task's own run or the actor session it started.

- `ai.callInRun(ctx, unit, runId, name, args, { step })` tags the guard call's row with the step.
- `ai.previewInRun(ctx, unit, runId, name, args, { step })` is a dry run's effect. It runs the
  unit's checks, then `guard.preview` (switches, permission, tier, tenant, the capability's
  preview), never the capability. The row is `planned` with `preview: true` and the preview's
  summary, or the refusal's outcome with `preview: true`. A planned row never counts as a change
  made, so the live write later still runs once.
- `ai.recordInRun(runId, { capability, outcome, step, requestId, ... })` writes a row that is not a
  guard call: `planned`, `skipped`, `waiting`, `failed`, `refused` (a workflow's own reason, such
  as a budget or a refused approval, in `code`), `stale`, or `ok` for a step that ended outside a
  guard call (an approved change run later, a task, a notice). Any other outcome comes only from
  the guard and is refused.

The table gains `step`, `step_kind`, `message`, `ref` and `preview`. The kits are unreleased, so
these are in the first migration, `0001_ai`, rather than a second one: drop and recreate a test
database made before this change.

## Context

The builder assembles each call in this order:

| # | Layer | Where it goes |
|---|---|---|
| 1 | platform | System prompt |
| 2 | tenant | System prompt |
| 3 | role | System prompt |
| 4 | surface | System prompt |
| 5 | unit | System prompt: the rendered template |
| 6 | memory | System prompt, fenced as data: known ids, then confirmed memory |
| 7 | retrieved | System prompt, each source fenced as data |
| 8 | conversation | The summary fenced as data, then the turns as messages |
| 9 | untrusted | The last user turn, fenced as untrusted |

The system prompt always starts with the same fence rule, then the fixed layers, so the
provider's prompt cache sees one prefix for every call of a unit. Inputs the recipe names in
`untrusted` never reach the template: they go only into the fenced last turn, and a template that
asks for one fails the run. Fenced text cannot close its fence, because `<data` and `<untrusted`
inside it are escaped.

Each layer can have its own budget; the whole call has `budgetTokens`. Over budget, retrieved
text goes first (the last sources first), then the oldest turns, then memory, then the untrusted
input (cut and marked). Fixed layers are never cut: a unit whose fixed layers do not fit fails
with `ContextError`. When turns are dropped, the `compact` hook folds them into the thread's
summary, and the thread keeps only the turns still in the prompt. Make `compact` run a summary
task of its own, so that call has a unit too.

Tokens are estimated, not counted: about four characters a token for Latin text and one and a
half for Bangla and other scripts. The estimate errs high.

## Memory

| Kind | Lives | Reaches a prompt |
|---|---|---|
| Working | `scope.working`, the run | When the unit reads `working` |
| Known ids | `scope.known`, the run | As `[known] tenant = tA` lines, when the unit reads `known` |
| Conversation | `ai_threads`, `ai_turns` | The summary and recent turns, when the unit reads `conversation` and the call names a thread |
| Long-term | `ai_memory`, per person or per tenant | Only confirmed rows, at most 25, when the unit reads `person` or `tenant` |

- A model proposes long-term memory with `scope.propose('tenant', text, mentions)`, and only for a scope in the unit's `memory.write`. The subject comes from the ctx, never from the model.
- A person confirms or rejects it with `ai.memory.confirm(ctx, id)`. Only `decideChannels` may decide (default `['console']`): a copilot, actor, workflow or MCP call cannot confirm memory. A person decides only their own person memory. `canDecide` adds your own rule, such as owners only for tenant memory.
- Scope is in every store query: a row is visible only in its tenant, and person rows only to their person. A thread is read only by its own person in its own tenant.
- A thread is keyed by tenant, person and id, in memory and in D1. Two people who use the same thread id each have their own thread, history and list; neither turn fails. In D1, `ai_threads` has the key `(tenant, person, id)` and `ai_turns` the key `(tenant, person, thread_id, seq)`. A person with no tenant is stored with tenant `''`, so an empty tenant id is refused with `RangeError`. The kit is unreleased, so this changed the first migration, `0001_ai`, in place: drop and recreate a test database made before it.
- `ai.memory.store.listThreads({ tenant, person }, { limit, cursor })` lists one person's threads in one tenant, newest change first: each thread's id, its summary once compacted, and `updatedAt`. 20 a page by default, at most 100; pass the page's `next` as `cursor` for the next one (`null` on the last page). A cursor the kit did not make throws `RangeError`. D1 reads the `ai_threads_owner` index on `(tenant, person, updated_at)`.
- `ai.memory.list(ctx)` is the "what we remember" page. `forget(ctx, id)` removes one row. `forgetPerson`, `forgetMentioning` (a visitor's erasure, through `mentions`) and `forgetTenant` are for erasure and purges.

Keep visitors' personal data out of long-term memory. Reach it through R1 tools instead.

## Prompts

```ts
const PROMPTS = {
  'tasks/brief-from-site': {
    2: { en: 'Draft a brief for the business at {{url}}.', bn: '{{url}} ঠিকানার ব্যবসার জন্য একটি খসড়া লিখুন।' },
  },
}
```

Templates live in your code: template key, then version, then language. `{{name}}` fills from the
run's variables, and a missing variable throws. A template can also be a function of the
variables. A run asks for one of the unit's languages and falls back to the first. Every run
records the template, version and language it used.

## Vercel AI SDK provider

```ts
import { aiSdkTools, omazyModel } from '@omazyai/sdk/ai-sdk'
import { generateText, streamText } from 'ai'

const run = await ai.start(ctx, copilot)
const result = streamText({
  model: omazyModel(run),
  tools: aiSdkTools(run, reg, { onOutcome: showCardOrApproval }),
  messages,
})
// ... when the turn is over:
await run.finish('ok')
```

`omazyModel(run)` is a `LanguageModelV4` made from a run, never from a token, so every call it
makes carries the unit's role, tags, cache policy and caps, and adds to the run's usage. It
supports text, tool calls, tool choice, JSON output with or without a schema, images (https URLs
or bytes) and streaming. The unit owns the temperature: a temperature passed to the AI SDK, and
settings the Core API does not take (topP, topK, seed, stop sequences, penalties, reasoning,
provider tools, non-image files), come back as warnings. Install `@ai-sdk/provider` 4.0.39 beside
the SDK; it is an optional peer dependency and only its types are used.

### Tools

`aiSdkTools(run, registry, { names, onOutcome })` builds AI SDK tools from the registry, by
default the unit's `tools.allow`. Each tool's description is the capability's, its input schema
is the capability's closed JSON Schema, and its `execute` calls `run.call()`: the unit's allow
list and tier, then the guard, then a row in the effects ledger.

The model reads back `{ status: 'ok', result }`, or what happened instead: `confirm_required`
with the preview's summary, `pending_approval` with the decider and expiry, or `refused` with the
guard's sentence. Each says plainly that nothing was done. The confirm token never reaches the
model. `onOutcome` gets the guard's full outcome, token included, so your UI can show the confirm
card or the approval; record the person's confirm with `ai.callInRun`.

:::danger[Hand-built tools bypass the guard]
A tool you write yourself with its own `execute` runs outside the guard: no permission check, no
tier, no confirm or approval, no kill switch and no effects row. Build every tool that reads or
changes the product with `aiSdkTools`, or call `run.call()` inside its `execute`.
:::

## What the platform must have

| Needed | State |
|---|---|
| `response_format`, a forced tool, images | On the Core API. Not deployed yet |
| `model: "role:<name>"` | On the Core API. Not deployed yet. Until then, give `roles` a model per role |
| `metadata` tags in the ledger, usage by label | On the Core API. Not deployed yet. The kit also keeps its own copy in `ai_runs` |
| `usage.cost_micros` | On the Core API. Not deployed yet. Until then, cost comes from your `prices` card |
| Caps per tag, 402 before the call | Being added. The kit's own caps work without it |
