AI kit (TypeScript)
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 and guard kits. Every capability call a run makes goes through the guard.
Units and manifests
Section titled “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:
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.useandmodel.fallbackare roles such asextract.fast, never a model name. The account maps roles to models.- The prompt names a template key, a version and its languages.
context.layersmust includeunit. Budgets are whole tokens, and a layer’s budget is at most the whole budget.- Memory scopes come from
working,known,conversation,personandtenant. A unit cannot writeworking. tools.maxTieris R0 to R4.evalsis a.jsonlpath, or{ path, threshold }when the unit carries its own pass mark (0 to 1).caps.perDayUsdis at leastcaps.perRunUsd.cacheTtlis 0, or 60 to 2592000 seconds, and cannot be set on alivecontext.
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
Section titled “Set it up”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:
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
Section titled “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:
const run = await ai.start(ctx, intake, { vars, tags }) // first request// ... save run.id with the conversationconst again = await ai.resume(ctx, intake, runId, { vars, tags }) // a later requestThe 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
Section titled “A role for one call”A call can ask for another role than the unit’s, for one call only:
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
Section titled “The gateway”Every call a run makes goes out with:
model: "role:<name>", or the model yourrolesmap gives the role. The platform resolves a role per install, workspace and account, with its own fallbacks. The unit’sfallbackrole 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 asrole:<name>has its role in the platform’s ledger too. When yourrolesmap turns a role into a model name, the platform cannot see the role, so the kit adds aroletag, as long as your own tags leave one of the 8 keys free.- Your own tags in the same
metadata: the unit’stags, then the run’s (ai.run(..., { tags })orai.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 androleare reserved. A manifest that breaks a rule throws when it loads; a run or call that does throwsTagErrorbefore anything is sent. The usage API groups bytag.<key>. - The unit’s temperature and output limit. A caller may lower the limit, never raise it.
cache_ttl: 0when the context islive, or the unit’scacheTtl. Sendlive: trueon 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.
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
Section titled “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
Section titled “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_unitwithtool_not_allowedfor a capability outsidetools.allow(the target is always allowed), ortier_above_unitfor one abovetools.maxTier.duplicatewithalready_donefor 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
Section titled “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, thenguard.preview(switches, permission, tier, tenant, the capability’s preview), never the capability. The row isplannedwithpreview: trueand the preview’s summary, or the refusal’s outcome withpreview: 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, incode),stale, orokfor 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
Section titled “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
Section titled “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’smemory.write. The subject comes from the ctx, never from the model. - A person confirms or rejects it with
ai.memory.confirm(ctx, id). OnlydecideChannelsmay decide (default['console']): a copilot, actor, workflow or MCP call cannot confirm memory. A person decides only their own person memory.canDecideadds 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_threadshas the key(tenant, person, id)andai_turnsthe key(tenant, person, thread_id, seq). A person with no tenant is stored with tenant'', so an empty tenant id is refused withRangeError. 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, andupdatedAt. 20 a page by default, at most 100; pass the page’snextascursorfor the next one (nullon the last page). A cursor the kit did not make throwsRangeError. D1 reads theai_threads_ownerindex 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, throughmentions) andforgetTenantare for erasure and purges.
Keep visitors’ personal data out of long-term memory. Reach it through R1 tools instead.
Prompts
Section titled “Prompts”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
Section titled “Vercel AI SDK provider”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.
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.
What the platform must have
Section titled “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 |
Omazy CX documentation. One voice. Every channel. Always on.
Founded by Mosthofa Imran · imran@omazy.ai
© 2026 Omazy CX