Agents
An agent is a typed config object passed to defineModelAgent() (or, for a simple agent that runs a function in place of a model, defineSimpleAgent()). It names a model, its instructions, the channels that may start it, its tools and tool hooks, a budget and typed state.
// defined once at module scope: each call gets its run's context
const lastReport = defineTool({
description: 'Returns the date of the previous report.',
inputSchema: z.object({}),
execute: async (_input, { context }) => (await context.state.get<string>('lastReport')) ?? 'never',
});
const saveReport = defineTool({
description: 'Remembers that a report was written now.',
inputSchema: z.object({}),
execute: async (_input, { context }) => {
await context.state.set('lastReport', context.run.trigger.receivedAt.toISOString());
return { saved: true };
},
});
export const reporter = defineModelAgent({
name: 'weekly-report',
model,
instructions: 'Summarize the open work items in the trigger payload.',
channels: [
http.on(),
cron.on('0 8 * * 1', { timezone: 'Europe/Berlin' }),
],
budget: {
maxSteps: 10,
maxTokens: 50_000,
timeoutMs: 5 * 60 * 1000,
},
tools: { lastReport, saveReport },
});What defineModelAgent() checks
defineModelAgent() validates the definition and returns { kind: 'model', name, definition } with defaults applied. It throws InvalidAgentDefinitionError when:
- the definition has
run(build a simple agent withdefineSimpleAgent()instead), - the name does not match
^[a-z0-9]+(-[a-z0-9]+)*$(lowercase words joined by single hyphens), or is longer than 64 characters, - instructions are neither a string nor an array of native system/user/assistant messages (tool roles are refused),
- two subscriptions of the agent share an id,
- the agent's or a subscription's
concurrencyMaxRunsis neitherundefined,falsenor a positive safe integer, privateis given and is not a boolean,trust.onTaintedis neither'approve'nor'deny', or atrust.toolsoverride has invalid flags or names no available tool (names are checked at execution when a tools factory, state or non-empty skills are declared; flags are always checked at definition),- a tool of a plain tool set declares the AI SDK's
needsApproval(useapprove()instead), - a
toolsContextentry names a chamvi tool or no tool of a plain tool set (see Third-party tools with their own context).
The engine checks the rest when you construct it: agent names must be unique within one Engine, and every subscription must name a channel registered on the engine.
const agent = defineModelAgent({
name: 'echo',
model,
instructions: 'Repeat the payload.',
});
agent.name; // 'echo'
agent.definition.budget; // { maxSteps: 20, timeoutMs: 900_000 }Fields
| Field | Type | Default | Description |
|---|---|---|---|
name | string | required | Unique per engine, lowercase words joined by -, at most 64 characters |
model | ModelRef | EngineOptions.model | A '<provider>/<model id>' string resolved through EngineOptions.models, or any AI SDK LanguageModel |
instructions | AgentInstructions | required | A string or an ordered readonly array of native system/user/assistant messages |
description | string | the leading system instruction | The text of the agent's MCP run tool (its first line; without one and without a system instruction: Starts a run of agent "<name>".) |
run | (payload, ctx) => unknown | none | defineSimpleAgent() only, in place of model and instructions: a simple agent |
concurrencyMaxRuns | number | false | none | Shared-store ceiling for this agent's running runs; positive safe integer, or false for no additional ceiling |
private | boolean | false | Reading the agent's runs and state through @chamvi/http needs chamvi_agent_read for the agent; chamvi_run_read, chamvi_agent_run and chamvi_state_read do not cover it |
channels | ChannelSubscription[] | none | From http.on(), webhook.on(), cron.on(), github.on(). See Channels |
tools | ToolSet | (ctx) => ToolSet | none | A plain tool set, or a factory called for each execution. See Tools and their context |
trust | AgentTrust | { onTainted: 'approve' } | Untrusted-run outbound policy and boolean tool-name classifications. See Untrusted content |
toolsContext | Record<string, unknown> | none | Per tool name, the context of a third-party tool. See Tools |
toolPolicy | (toolName, { run, now }) => boolean | Promise<boolean> | none | Tools the run may use, e.g. requireToolPermission(). See Restricting tools per invoker |
state | Record<string, StandardSchemaV1> | none | Typed state collections. See Agent State |
budget | Partial<Budget> | { maxSteps: 20, timeoutMs: 900_000 } | See Budgets & Timeouts |
hooks | { beforeToolExecution?, afterToolExecution? } | none | Run around every tool call: rewrite input or output, gate a tool with approve(). See Approvals & Hooks |
output | Output | none | AI SDK structured output, e.g. Output.object({ schema }). See Structured output |
The budget you pass is merged over the defaults, so budget: { maxSteps: 5 } keeps the 15 minute timeout.
Instructions
A string remains shorthand for one system message. For structured instructions, import AgentInstructions, SystemModelMessage, UserModelMessage and AssistantModelMessage from @chamvi/core (also re-exported by @chamvi/app):
import { defineModelAgent } from '@chamvi/core';
import type {
AgentInstructions,
AssistantModelMessage,
SystemModelMessage,
UserModelMessage,
} from '@chamvi/core';
const policy: SystemModelMessage = {
role: 'system',
content: 'Summarize reports in one sentence.',
providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } },
};
const example: UserModelMessage = {
role: 'user',
content: [{ type: 'text', text: 'Report: the release passed all checks.' }],
};
const answer: AssistantModelMessage = {
role: 'assistant',
content: 'The release is ready.',
};
const instructions: AgentInstructions = [policy, example, answer];
export const reporter = defineModelAgent({ name: 'reporter', instructions });These message types are the native AI SDK types. System content is a string; user and assistant content retain their respective SDK multipart unions, including file data, URLs and provider options. Core also exports native ModelMessage, UserContent, AssistantContent, TextPart, ImagePart and FilePart. Provider support and SDK content validation still apply. The installed AI SDK deprecates image content parts in favor of file parts with an image media type; native ImagePart remains available for compatibility.
The engine sends the longest leading system prefix through SDK instructions. It keeps the rest, including any later system messages, in authored order before the run transcript. First-class skills append a separate metadata-only system block after the configured instructions. For example, a string role plus skills produces two system blocks; an example conversation followed by skills keeps the catalog after those examples.
Configured messages are trusted operator inputs. They are rebuilt once for each execution and appear once per model prompt, including after an approval pause. They are never stored in checkpoints or conversation history, or replayed as pending tool calls. Recalled conversation messages follow this configured prefix; approval resume uses the captured conversation snapshot. Artifact file markers in examples hydrate for model and tool context without changing configuration or checkpoints. A restored run transcript containing a system role is rejected before replay or model work; role-like text in a trigger payload stays user content.
Tools and their context
tools is usually a plain AI SDK ToolSet, defined once at module scope (see the example above). Tools built with defineTool() (or defineEffectTool()) get the run context as context, the second argument of execute:
| Field | Type | Description |
|---|---|---|
state | AgentState | The agent's state |
run.runId | string | Id of the run being executed |
run.agent | string | Agent name |
run.trigger | TriggerEnvelope | The envelope that started the run; run.trigger.invoker is who started it, if an authenticator knew |
run.signal | AbortSignal | Aborts on cancel, drain, a lost lease or the run timeout, and once the execution has ended |
artifacts | IRunArtifacts | The run's files: put(), get(id), list(). See Files |
The engine builds one ToolContext per execution and hands it, through the AI SDK's toolsContext, to every tool whose contextSchema is chamvi's toolContextSchema, which is what defineTool() sets. Other tools (a plain tool(), a third-party tool) get no chamvi context. Every call of an execution gets the same object: treat it as immutable. It holds run, state, artifacts and channels, the run-bound handles a tool sends through (see Outbound from tools). Pass context.run.signal on to fetch and other cancellable work.
For typed state, name the schema: defineTool<Input, Output, typeof schema>({ ... }) types context.state by the agent's collections. The agent does not check that schema against its own state: a tool typed for other collections still compiles, and at run time reads of an undeclared collection are empty and writes fail as tool errors.
tools can also be a factory (ctx) => ToolSet, called once per execution with the same ToolContext. Use it for dynamic sets: tools from an MCP client, or descriptions built from async state (a tool's description function runs synchronously, so it cannot read the store itself).
The tools stay plain AI SDK tools. When the agent declares state, the engine adds generated state tools; your tools win on a name clash. Every effect tool is then wrapped so it applies at most once per effect key.
Structured output
By default a completed run's output is the text of the model's last answer. With output, an AI SDK Output, output is the parsed value instead:
const labeler = defineModelAgent({
name: 'labeler',
model,
instructions: 'Label the issue in the trigger payload.',
channels: [http.on()],
// run.output is { label, reason } instead of the final text
output: Output.object({
schema: z.object({
label: z.enum(['bug', 'feature', 'question']),
reason: z.string(),
}),
}),
});The model may call tools first; only the final answer is parsed. A final answer that is no valid JSON or fails the schema fails the run with ValidationError (run.error.code validation_error, the message from the AI SDK's cause, its quoted text cut to 500 characters; the whole answer stays in the llm step). Two loop ends have no answer to parse and fail the run with IncompleteResponseError (incomplete_response) instead: an answer cut off at the output token limit (finish reason length), and a loop that ended on a tool call nothing executed (a tool without execute, outside a budget stop). A run whose step budget an earlier execution used up parses the last answer in its checkpoint the same way. An agent without output keeps completing with the text it got in both cases.
The ToolLoopAgent gets your Output with one change: its parsePartialOutput is not called while the answer streams (chamvi reads no partial output, and re-parsing the growing answer on every delta costs time). run.delta events arrive per model delta, as without output.
Files
A run can start with files (attachments) and tools can store files of their own. Both are artifacts of the run: metadata (id, runId, agent, mediaType, filename?, size, createdAt) plus the bytes, kept by the engine's ArtifactService in an IArtifactRepository of @chamvi/store. The artifacts of the tool context is scoped to the run: put({ mediaType, filename?, data }) stores a Uint8Array and returns the Artifact, get(id) returns { artifact, data } (or undefined, also for another run's artifact) and list() returns the run's artifacts by createdAt (attachments in the order they were given; every artifact id is a time-ordered UUID v7).
// an effect tool: a recovered run does not store the chart twice
const saveChart = defineEffectTool({
description: 'Renders the points as a PNG chart and store it with the run.',
inputSchema: z.object({ points: z.array(z.number()) }),
execute: async ({ points }, { context }) => {
const artifact = await context.artifacts.put({
mediaType: 'image/png',
filename: 'chart.png',
data: await renderChart(points),
});
return { artifactId: artifact.id };
},
});
export const charter = defineModelAgent({
name: 'charter',
model,
instructions: 'Chart the numbers in the attached CSV.',
channels: [http.on()],
tools: { saveChart },
});put() is not an effect by itself: a recovered run repeats the step in progress, so call it inside a defineEffectTool to store a file exactly once. Or give it a key (1 to 255 characters, no NUL): put({ key, mediaType, data }) stores the file under the key within the run, and a later put() with the same key replaces the bytes and metadata and keeps the stored id, instead of adding a second file (the key itself is private and never part of the Artifact), so a repeated or replayed call stores it once. Over HTTP, GET /runs/:id/artifacts lists them and GET /runs/:id/artifacts/:artifactId downloads one (see HTTP API). Once the execution ended (the run settled or paused), a put() from work a tool left behind throws InvalidRunStateError and stores nothing; a call that has not returned yet, such as a cleanup after the abort, can still put.
Simple agents
defineSimpleAgent() builds a simple agent (kind: 'simple'), one with run(payload, ctx) in place of model and instructions: the engine runs the function as a durable run, with no model call. It takes name, description (the text of its MCP run tool), channels, concurrencyMaxRuns, a plain tools set, trust, hooks, toolPolicy, state and budget; model, instructions, skills, output, conversation, toolsContext or a tools factory next to run are an InvalidAgentDefinitionError. Of the budget only timeoutMs and maxSubtreeTokens apply. agent.kind ('model' or 'simple') tells the two kinds apart and narrows agent.definition; the engine refuses an agent whose kind is neither or disagrees with its definition. A simple agent fans out runs that its function can wait on, see Simple agents.
Declared tools preserve their SDK output types in ctx.tools. Inputs stay unknown because the engine validates raw values before schema transforms. Keep the concrete tool-set type when declaring or returning tools; annotating it only as ToolSet loses that information. Dynamic tool names keep unknown results. Inferred types do not validate returned values or result rewrites by hooks.
Many agents per engine
One engine runs any number of agents. They share the store, the engine's local concurrency limit and the channels. Optional agent and subscription ceilings also apply across replicas sharing the store; see Concurrency:
const triage = defineModelAgent({
name: 'triage',
model,
instructions: 'Triage the issue.',
});
const digest = defineModelAgent({
name: 'digest',
model,
instructions: 'Summarize the day.',
});
// runs, steps, checkpoints, effects, artifacts and state in memory, gone with the process: @chamvi/app keeps them in PostgreSQL
const registry = new MemoryRegistry();
const runs = new MemoryRunRepository({ registry });
const locks = new MemoryLockRepository({ registry });
const engine = new Engine({
runService: new RunService({ repository: runs, clock: systemClock }),
stepService: new StepService({ repository: new MemoryStepRepository({ registry }) }),
checkpointService: new CheckpointService({ repository: new MemoryCheckpointRepository({ registry }) }),
effectService: new EffectService({ repository: new MemoryEffectRepository({ registry }) }),
agentRevisionService: new AgentRevisionService({ repository: new MemoryAgentRevisionRepository({ registry }) }),
artifactService: new ArtifactService({ repository: new MemoryArtifactRepository({ registry }) }),
stateService: new StateService({
repository: new MemoryStateRepository({ registry }),
documentRepository: new MemoryStateDocumentRepository({ registry }),
}),
lockService: new LockService({ repository: locks, clock: systemClock }),
idempotencyService: new IdempotencyService({ repository: new MemoryIdempotencyRepository({ registry }), clock: systemClock }),
agents: [triage, digest],
// tools reach it with ctx.channels.findOneOrFail('console')
channels: [consoleChannel()],
concurrencyMaxRuns: 8,
claimTtlMs: 30_000,
});dispatch() names the agent per run. An agent the engine does not hold throws AgentNotFoundError (agent_not_found, 404 over HTTP).
Code that checks a permission before it dispatches passes the agent object it checked: engine.dispatch({ ..., checked: agent }). When the engine holds another object under the name by then, dispatch() throws AgentReplacedError (agent_replaced, 409 over HTTP) before it stores anything; check the replacement and dispatch again. A replacement while the run is created cancels that run (run.error.code agent_replaced), and the run is bound to the agent's folder revision: a replica that loaded a newer revision cancels it instead of running the new code. A replica that holds the agent without a folder revision leaves a bound run queued for one that has it. A dispatch without checked (a cron job, a direct call) is bound to nothing: a replacement cancels it like any unsettled run created before the replacement began, and one created after that runs on the replacement. The HTTP and MCP starts, webhooks and dispatchTo() with an invoker pass checked themselves. checked is never stored.
The set can change while the engine runs: engine.putAgent(agent) adds an agent or replaces the one of the same name, engine.removeAgent(name) removes it, and both emit agents.changed ({ name, kind: 'added' | 'replaced' | 'removed' }), which the cron channel and @chamvi/http follow. Replacing or removing an agent first cancels its unsettled runs. An app loads such agents from a folder: see Agent Folders.
Pass engine.putAgent(agent, { signal }) to cancel candidate preparation before registry changes. Cancellation leaves the previous registration, revision marker and unsettled runs intact. Once a registry operation starts, it finishes with local publication even if the caller or engine stops, keeping the registration and durable state consistent. Folder loading forwards the app shutdown signal through preparation and publication.