# agent

[← All adapters](/docs/reference/adapters)

```ts
import { agent } from '@routecraft/ai'
```

Run an LLM with a fixed system prompt on each incoming exchange. Replaces the body with `AgentResult { text, usage? }`. Two forms:

- **Inline** (`agent({ model, system, user? })`) -- identity and description come from the enclosing route (`.id()`, `.description()`). Suitable when the route _is_ the agent.
- **By name** (`agent("summariser")`) -- resolves a registered agent from the context. Register agents via `agentPlugin({ agents: { name: {...} } })` ([`agentPlugin` reference](/docs/reference/plugins/agentplugin)).

```ts
import { agent, agentPlugin } from '@routecraft/ai'
import { readFileSync } from 'node:fs'

// Inline: the route IS the agent. Other routes call it via direct("zoe").
craft()
  .id('zoe')
  .description('Internal ops assistant')
  .from(direct())
  .to(agent({
    model: 'anthropic:claude-opus-4-7',
    system: readFileSync('./prompts/zoe.md', 'utf-8'),
  }))
  .to(direct('reply'))

// By name: register once, use from any route in the context. Per-agent
// fields can be omitted when defaultOptions supplies them.
agentPlugin({
  defaultOptions: {
    model: 'anthropic:claude-opus-4-7',
  },
  agents: {
    summariser: {
      description: 'Summarises documents into bullet points',
      system: 'Be concise.',
      // model inherited from defaultOptions
    },
  },
})

craft()
  .id('periodic-summary')
  .from(timer({ interval: 60_000 }))
  .to(agent('summariser'))
  .to(log())
```

Model ID format: `"provider:model-name"` (same as `llm()`). The provider must be registered via `llmPlugin({ providers: {...} })`. There is no inline-credentials escape hatch on `agent({...})`; centralised wiring via `llmPlugin` is the only path.

**Supported providers:** `openai`, `anthropic`, `ollama`, `openrouter`, `gemini`, `lmstudio`, `custom`

**`AgentOptions` (inline form):**

| Option | Type | Default | Required | Description |
|--------|------|---------|----------|-------------|
| `model` | `LlmModelId` | -- | No\* | `"provider:model"` string resolved via `llmPlugin`. Required unless `defaultOptions.model` supplies a fallback; otherwise dispatch throws `RC5003` |
| `system` | `string` | -- | Yes | System prompt. Load from disk yourself when sourcing from a file |
| `user` | `string \| LlmPromptPart[] \| (exchange) => string \| LlmPromptPart[]` | body as-is / JSON | No | Override for deriving the user prompt. Defaults to body (string as-is, JSON for objects). The array form sends content parts, so an agent can take a recording or an image directly: see [content parts](/docs/reference/adapters/llm#content-parts) |
| `tools` | `ToolSelection` | -- | No | Tool whitelist built via `tools([...])`. Inherits `defaultOptions.tools` when omitted; an explicit value replaces the default entirely |
| `principal` | `boolean \| (principal, exchange) => string` | `false` | No | When `true`, append a built-in `## Caller` section to the system prompt describing `exchange.principal` (identity + roles), or stating the request is unauthenticated. Pass a function to render the section yourself. See [Telling the agent who the caller is](#telling-the-agent-who-the-caller-is) |
| `output` | `StandardSchemaV1` | -- | No | Schema for structured output. The agent requests provider-level structured output, validates the response, and parses it onto `AgentResult.output` |
| `validate` | `(result, { exchange, turnsUsed }) => void \| string \| Promise<void \| string>` | -- | No | Checked after the final reply (and after `output` parsing). Return nothing to accept the result, return a non-empty string to send the agent back for another turn with that string as a corrective message (a blank string fails the dispatch with `RC5003`), or throw to fail the dispatch. Retries share the `maxTurns` budget; when it runs out while `validate` still rejects, the dispatch fails with `RC5003`. Per-agent only, never a default. See [Judging agent results](/docs/advanced/judging-agent-results) |
| `session` | `string \| (exchange) => string` | -- | No | The conversation this message continues. The id is the conversation's identity, so naming the same one twice continues the same conversation, exactly as `headers["routecraft.id"]` names an exchange. Every message for one id shares one transcript, kept in the context's [session store](/docs/reference/configuration#sessions). See [Sessions](#sessions-an-agent-that-remembers) |
| `interrupt` | `boolean \| (exchange) => boolean` | `false` | No | Cancel the session's running turn before answering this message. Only meaningful with `session`; ignored when no turn is running |
| `stream` | `boolean` | `false` | No | Produce the token deltas instead of the consolidated `AgentResult`. See [Streaming the reply](#streaming-the-reply). Does not combine with `session` |
| `onDelta` | `(delta) => void \| Promise<void>` | -- | No | Push form of the same streaming run: each token delta goes to this listener and the consolidated result is still returned. Refused alongside `stream` |
| `temperature` | `number` | `0` | No | Sampling temperature |
| `maxTokens` | `number` | `1024` | No | Maximum tokens per model call |
| `topP` | `number` | -- | No | Top-p sampling |
| `frequencyPenalty` | `number` | -- | No | Frequency penalty |
| `presencePenalty` | `number` | -- | No | Presence penalty |
| `reasoning` | `'none' \| 'low' \| 'medium' \| 'high'` | -- | No | How much the model should reason per turn, mapped to each provider's own control. Same option and same [mapping table](/docs/reference/adapters/llm#reasoning-effort) as `llm()` |
| `providerOptions` | `Record<string, Record<string, unknown>>` | -- | No | Raw provider settings forwarded to the SDK, winning over `reasoning` for the settings they name. See [Reaching a provider directly](/docs/reference/adapters/llm#reaching-a-provider-directly) |

The last seven are the same sampling block `llm()` takes, and they mean the same thing here: one agent can run a narrow classification at `reasoning: 'none'` while another names the same model and asks for `'high'`. An agent that sets none of them behaves exactly as it did before they existed. They can be set once for every agent in a context via `agentPlugin({ defaultOptions })`, where a per-agent value wins per key, and markdown agents declare them in frontmatter like any other field.

They apply to every model call in a run: the first turn, each tool-calling turn, and each `validate` retry. A run that defers and resumes resolves them again from the context it resumes in rather than replaying what was resolved before it deferred, so a changed `defaultOptions` takes effect on the resumed turns.

**`AgentRegisteredOptions` (entries in `agentPlugin({ agents: {...} })`, for by-name reuse):** same as `AgentOptions` plus:

| Option | Type | Default | Required | Description |
|--------|------|---------|----------|-------------|
| `description` | `string` | -- | Yes | Human-readable description. Surfaces in observability and is used as the tool description when the agent is exposed to other agents |
| `models` | `readonly LlmModelId[]` | -- | No | The models a person talking to this agent may choose from. `model` stays what it runs on. A list of fewer than two advertises nothing. See [Offering a choice](/docs/reference/plugins/agentplugin#offering-a-choice-of-model-or-thinking-level) |
| `reasoningLevels` | `readonly LlmReasoningEffort[]` | -- | No | The thinking levels a person may choose from, on the same terms as `models` |

The id is the record key in `agentPlugin({ agents: { [id]: {...} } })`.

**`AgentByNameOverrides` (the second argument of `agent("name", { ... })`):** per-call fields, which are the ones that belong to the message rather than to the agent. A per-call value wins over the registered one.

| Option | Type | Description |
|--------|------|-------------|
| `session` | `string \| (exchange) => string` | Same as `AgentOptions.session` |
| `interrupt` | `boolean \| (exchange) => boolean` | Cancel the session's running turn before answering this message. Ignored when no turn is running, and without `session` |
| `onDelta` | `(delta) => void \| Promise<void>` | Per-request token-delta listener |

**Result shape (body is replaced by `.to()`):**

| Field | Type | Description |
|-------|------|-------------|
| `text` | `string` | Generated text from the model |
| `output` | `T` | Parsed structured output (only when an `output` schema was supplied) |
| `usage.inputTokens` | `number` | Input token count (when reported) |
| `usage.outputTokens` | `number` | Output token count (when reported) |
| `usage.totalTokens` | `number` | Total token count (when reported) |
| `session` | `{ agent, id, status, queued }` | Present only when the dispatch carried `session`. `status` is `replied` (`text` is this message's reply), `queued` (a turn was running; `text` is empty and the reply belongs to the turn that consumes the inbox), `interrupted` (this call's own turn was cancelled by a later message) or `idle` (only on a revived continuation whose inbox another turn consumed first; `text` is empty and no model call was made). `queued` is the inbox depth afterwards |

#### Sessions: an agent that remembers

Without `session`, an agent run is one turn from a fresh prompt and nothing is remembered. With it, one route serves as many conversations as there are session ids, and each is a record in the store rather than a process: kill the instance, start it again, and the next message continues where the last one stopped.

```ts
const MaxMessage = z.object({
  session: z.string(),
  message: z.string(),
  interrupt: z.boolean().optional(),
});
type MaxMessage = z.infer<typeof MaxMessage>;

agentPlugin({
  agents: {
    max: {
      description: 'Max, the development agent',
      system: readFileSync('agents/max.md', 'utf-8'),
      user: (ex) => (ex.body as MaxMessage).message,
      maxTurns: 200,
      tools: tools(['sandbox-run', 'github-create-pr']),
    },
  },
})

// One route, many conversations. The instance is a record in the store, not a process.
craft()
  .id('max')
  .input({ body: MaxMessage })
  .from(direct())
  .to(agent<MaxMessage>('max', {
    session: (ex) => ex.body.session,
    interrupt: (ex) => ex.body.interrupt === true,
  }))

// A webhook continues the same conversation: the branch name carries the session id.
craft()
  .id('github-hook')
  .input({ body: DeploymentStatus })
  .from(http({ path: '/hooks/github', signature: github }))
  .filter((ex) => ex.body.deployment_status.state === 'success')
  .transform((body) => ({
    session: body.deployment.ref.replace('max/', ''),
    message: `Preview is up: ${body.deployment_status.environment_url}`,
  }))
  .to(direct('max'))
```

**The transcript.** Per message the adapter loads the transcript stored under the session id, appends the message, runs the turn with the agent's registered options, and stores the transcript back. A session the store has never seen starts empty. Records live in the context's [session store](/docs/reference/configuration#sessions): SQLite at `.routecraft/sessions.db` by default, created by the first session written, or whatever `sessions: { store }` names, including a [`SessionStore`](/docs/reference/configuration#sessions) of your own. A store failure is [`AI1012`](/docs/reference/errors#ai-1012). The continuation a turn stores between turns is a deferred exchange and lives in the [`deferral`](/docs/reference/configuration#deferral) store, so a context without that block refuses `session` with [`RC5052`](/docs/reference/errors#rc-5052). The model is told which conversation it is in through a `## Session` block appended to the system prompt, so a tool that takes a session id (a per-session workspace, say) can be handed it. Because the id reaches that prompt and keys the record, it is bounded before it reaches either: 1 to 128 characters of letters, digits, `.`, `_`, `:` or `-`, starting with a letter or digit, and [`RC5003`](/docs/reference/errors#rc-5003) otherwise, so a value taken from a message that carries other characters (a branch name with a slash, a subject with an `@`) must be normalised onto that shape before dispatch; the runtime refuses, it does not map. The agent recorded on the session is the agent's registered name, or the route id for an inline `agent({ session })`, and it never changes for the life of that session.

**One turn at a time.** A message that arrives while the session's turn is running does not start a second turn. It goes to the session's inbox, its caller gets `session.status === 'queued'` with an empty `text`, and it is delivered at the next turn boundary: when the running turn ends, whatever queued becomes the next user message, in arrival order, several messages as one message with the parts in order, and that turn runs on its own. The reply to a queued message belongs to the turn that consumed it and reaches the transcript, not the caller. (An editor talking over [ACP](/docs/introduction/talk-from-your-editor#sending-while-a-turn-runs) is the exception: the mount holds its request open until that turn has replied, because the editor is showing the message and waiting.) The inbox is durable: it lives in the same record as the transcript.

**The boundary turn runs on the route.** A turn that ends with work outstanding, messages queued or a [background tool](/docs/reference/plugins/agentplugin#background-tools) still running, stores its exchange's continuation: the body and the headers, exactly as a `.defer()` deferral stores them, at the agent step, after the caller has its reply (`route:agent:session:deferred`). The boundary turn is that continuation revived on the running process (`route:exchange:resumed`, then `route:agent:session:revived`): the agent step runs with the inbox as its user message, and the route's steps after the agent run on the reply, so a queued message or a finished build reaches whatever the route does with a reply. What does not run again is the route's pre-from chain: no `.authorize()`, `.input()`, `.throttle()` or `.timeout()` of the route applies to a revived turn. The revived turn runs under the exchange that stored the continuation: its headers, its principal, its tools. One continuation per session; a turn that ends with work outstanding while one is stored keeps it. The transcript and the inbox never live in the continuation, only in the session record. An agent step that sits where a deferral cannot be revived from (inside a `.split()`) has no continuation: queued messages then run in process on the route that just ended, and a completion waits for the next message.

**Interrupt.** `interrupt: true` cancels the running turn at its next checkpoint through the ordinary cancellation path, so a tool in flight sees its abort signal. The interrupted turn's partial transcript is kept, including the call that was running and an error result saying it did not finish, so the model knows what it was doing. The interrupted caller gets `session.status === 'interrupted'` rather than a failure; the interrupting caller waits for the turn that starts with the queued messages plus theirs and gets its reply.

**Restart.** A turn running when the process stops is treated as interrupted: what it persisted (every finished step) is kept, the messages it had not consumed stay in the inbox, and the next message for the session starts a turn that closes any open tool call as interrupted and reports each background call the dead process was waiting on as lost. A session that had stored a continuation is not left waiting for that message: at boot, after the routes are live, the dead process's background calls become lost-run messages in its inbox and the continuation is revived, so the loss reaches the model as a turn. The context's own shutdown aborts a running turn the same way it aborts any agent run ([`AI1005`](/docs/reference/errors#ai-1005) to that caller), after persisting what the turn reached. A message that reaches an idle session once shutdown has begun is queued rather than run, and waits in the inbox for the next process. A continuation the previous process stored but died before naming on the session record is released at the next boot, so a crash between those two writes never leaves a deferral nothing references.

**Limits.** `maxTurns` bounds one turn, not the conversation; there is no compaction, so a long enough conversation ends in [`AI1009`](/docs/reference/errors#ai-1009). `session` does not combine with `stream: true` (`RC5003`): a stream is handed over before the turn ends, and the turn boundary is where the transcript is stored. A session turn is not deferrable: a tool that calls `ctx.defer()` inside one fails the turn. The one-turn bound is per process: two instances sharing one store are not coordinated, and a turn marker set by a live sibling is read as one a restart cut short, so run one process per store. A session with no stored continuation is not resumed on boot; its next message drains the inbox. A stored continuation carries no deadline: it waits for the completion, however long the run takes, and shows on the session's summary until then. Records never expire and the transcript has no bound; retiring a session or trimming its transcript is not built.

**Who a turn runs as, and who said what.** A turn runs under the principal of the exchange it runs on: the message's own exchange when that message starts the turn, and the deferred exchange when a revival starts it. The runtime never switches principal mid-turn and never picks one for a queued message, so a tool guard reading `ctx.principal` sees the turn's caller, whoever queued the text. What the model and the transcript see is who said it: every inbox item records the subject of the principal that posted it (`null` when the exchange carried none, so a caller whose subject is literally `anonymous` is still named), and the delivered message renders that per part as a bracketed line, `[Message from "bob"]`, in the same quoted-data shape blocks use, so it is something the model reads and never something it obeys. A background result names who started the call the same way. The session record keeps who the conversation belongs to as `owner`: the subject of the principal whose turn opened it, written once and never transferred by a later speaker. It is shown on the [management API](/docs/reference/plugins/opsplugin#contributed-resources), and it IS a gate on a protocol surface such as [`acpPlugin()`](/docs/reference/plugins/acpplugin), where a listing carries only the caller's own conversations and a session owned by somebody else answers exactly as one that does not exist. Inside a route it gates nothing: who may post is still the route's `.authorize()`.

Who may post to a session is the route's own [`.authorize()`](/docs/reference/operations/authorize), in one of two shapes. A session that must be one caller's derives its id from the principal, so no two callers share one:

```ts
agent('max', { session: (ex) => `${ex.principal?.subject}:${ex.body.session}` })
```

The id is a retrieval handle, so it has to be known to be retrieved, the same way a deferral is resumed by its token. A hardcoded id (`session: 'support'`) is therefore a deliberate choice rather than a mistake: every invocation of that route continues one conversation, on one transcript that grows for as long as the route runs. Derive the id from the message when each caller, thread or ticket should get its own.

A session several principals share on purpose (a webhook, a mail reply and a terminal all posting into one conversation) keeps the id as the caller names it and restricts posting by role or scope at the route, and reads the attribution to tell them apart. A runtime allowlist of subjects per session is not built.

Every session is listable on the management API at [`GET /ops/agent-sessions`](/docs/reference/plugins/opsplugin#contributed-resources), with its turn state and inbox depth, and an editor speaking the Agent Client Protocol is a client on this: see [Talk from your editor](/docs/introduction/talk-from-your-editor).

#### Streaming the reply

`stream: true` replaces that result with an `AgentStream`, an async iterable of `AgentDelta` handed over before the run starts. Iterating it is what starts the run, so the first `next()` is where the model begins writing. The [http source frames an async iterable as Server-Sent Events](/docs/reference/adapters/http#streaming-responses-sse), so a token-by-token endpoint is one declarative route:

```typescript
craft()
  .id('chat-stream')
  .input({ body: ChatInput })
  .from(http({ path: '/chat/stream', method: 'POST' }))
  .to(
    agent({
      system: aria,
      user: (ex) => (ex.body as z.infer<typeof ChatInput>).message,
      stream: true,
    }),
  );
```

The queue and the abort that closes it live inside the adapter. Iterating the stream is what drives the run, and abandoning it aborts that run, so a client that disconnects mid-answer stops the model. Custom SSE event names are one ordinary `.transform()` step away; a queue and a wake loop written by hand in a transform are not the way there.

The trade is what a stream cannot carry. `text`, `output`, `usage` and `toolCalls` are consolidated when a run finishes, and a stream is handed over before that. A route that needs both sends the stream to its reader and takes the completed record from the coarse `route:agent:*` events. Under `.enrich()` the stream merges like any other enrichment value. See [the agent plugin's observability channels](/docs/reference/plugins/agentplugin#observability-three-channels) for the full comparison with `onDelta`.

**Resolution semantics:**

- `agent("name")` only resolves registered agents. To call a route-backed agent from another route, use `.to(direct("route-id"))`. `direct` runs the full pipeline of the target route; `agent("name")` runs the registered agent's LLM call inline.
- Model resolution at dispatch is `instance value > defaultOptions.model > throw RC5003`.
- Duplicate registered agent ids, missing description, malformed model string when present, or a non-`ToolSelection` `tools` value fail at context init with `RC5003` (Adapter misconfigured).
- Referencing an unknown registered agent name fails at dispatch with `RC5004` (No handler available).

Provider credentials are configured once in `llmPlugin()` and shared across all `agent()` calls. See [`llmPlugin` reference](/docs/reference/plugins/llmplugin).

#### Telling the agent who the caller is

By default the only part of the exchange that reaches the model is the body (as the user prompt). The authenticated caller (`exchange.principal`) is **not** in the prompt, so the model does not know who it is serving unless you put that there yourself.

Set `principal: true` to append a `## Caller` section to the system prompt. It is appended after your own prompt and any `blocks`, and it covers the unauthenticated case explicitly so the model never invents an identity:

```typescript
agent({
  model: 'anthropic:claude-opus-4-7',
  system: 'You are a support assistant.',
  principal: true,
});
```

When the request is authenticated, the model sees:

```text
## Caller

The current request is authenticated.
- Name: Jane Doe
- Email: jane@example.com
- Subject: user_2a9f
- Roles: admin, editor
```

When there is no principal:

```text
## Caller

The current request is not authenticated. No verified user identity is
available. Do not assume, infer, or invent the caller's name, email, or
permissions.
```

Only the loggable identity fields (`name`, `email`, `subject`) and `roles` are surfaced; fields that are absent on the principal are omitted, and interpolated values have newlines collapsed so a subject-controlled field (a self-service display name, say) cannot forge prompt structure. Scopes, `claims`, `userinfoClaims`, and the bearer token are never injected. The block is informational context only: authorization is still enforced by [`.authorize()`](/docs/reference/operations/authorize) and tool guards, never by the model.

To control the wording or which fields are shown, pass a function instead of `true`. It receives the principal (`undefined` when unauthenticated) and the exchange, and returns the markdown to append (return `''` to append nothing). Your renderer owns its own escaping and the same field exclusions apply:

```typescript
agent({
  model: 'anthropic:claude-opus-4-7',
  system: 'You are a support assistant.',
  principal: (p) =>
    p ? `## Caller\n\nYou are assisting ${p.name ?? p.subject}.` : '',
});
```

To opt every agent in a context into caller-awareness at once, set `principal` on `agentPlugin({ defaultOptions })`; a per-agent `principal` (including `false`) overrides it.

Inside a tool handler, the same principal is available as `ctx.principal` (a deep-frozen, read-only snapshot).
