import { b as Cmd, v as Tagged, I as Interpret, A as AnyCmdDef, C as CmdOf, a as CmdDef, k as Settled, w as OkOf, x as ErrOf, p as MalformedResult, O as Outcome, o as CmdValue, H as HandlerCtx, f as TaggedError, M as Machine, S as Subscribe } from './core-sEWVgnpI.js'; import { b as MonitoredRunState, R as RunFailure, M as MonitoredRunCmd } from './index-tFnc-ElD.js'; import { R as RunCmd, S as SucceedMsg, F as FailMsg, b as ResilientState, r as RunCmdDef } from './index-C1BK3MNo.js'; import { D as DeadlineExceeded, a as DeadlineSub, b as DeadlinesSub } from './index-CCs-QGGu.js'; import { M as MsgType, a as MsgTypeValue } from './protocol-CqdURF0g.js'; import { F as FanOutState } from './index-D5RP0MjN.js'; import { RetryPolicy, AnyRetryPolicy } from './retry-backoff/index.js'; import { StandardSchemaV1 } from '@standard-schema/spec'; /** * The minimal structured-output schema contract: `parse(unknown) => T`, the * zod-style call `decode` uses to validate the model's output before it * settles `resilient_run_ok`. A throwing `parse` (the zod contract on invalid * input) becomes a `port_rejected` outcome — a parse failure is a failure, * never a silent pass. Structural so a real `z.ZodType` satisfies it * without an import. */ interface Schema { /** Validate + narrow `value` to `T`, or throw on mismatch (the zod contract). */ parse(value: unknown): T; } /** * One LLM call request — the resilient-call `input` for this module, carried on * the `resilient_run` Cmd as plain data — no closures, so it survives * persistence and replay. Purpose-discriminated: a `purpose` selecting the * schema + prompt assembly, the `model` id, and the opaque per-purpose * `payload` the handler's message loader consumes. * * `key` defaults to `purpose` when the consumer calls `attempt(s, input, at)`, * so one in-flight call per purpose is tracked under the resilient-call slice — * the common single-call-per-stage shape. A consumer that fans out many calls * of one purpose passes a distinct `key`. */ interface LlmCall

{ /** The stage / schema selector — drives both `schemas[purpose]` and message assembly. */ readonly purpose: P; /** The model id to invoke; `null` = the host's default model. */ readonly model: string | null; /** The per-purpose prompt payload the message loader consumes. Opaque to the knob. */ readonly payload: unknown; } /** The parsed, typed success carried on `resilient_run_ok`, tagged with its purpose. */ interface LlmOk

> { readonly key: string; readonly purpose: P; readonly output: O[P]; } /** The typed failure variant — every failure path surfaces this, tagged by purpose. */ interface LlmErr

{ readonly key: string; readonly purpose: P; /** A human-readable cause (model throw, retry-exhaustion, or schema parse). */ readonly reason: string; /** The original error, carried untouched for the consumer to inspect. */ readonly error: unknown; } /** * The effect Cmd this module emits: run the LLM call for `key` with `input`. It * is `../resilient-call`'s `Cmd.define`d `RunCmd` specialized to the `LlmCall` * input — NOT a re-declared shape — so the resilient verbs' return tuples * thread through `attempt` / `succeed` / `fail` / `onTimer` with no cast. */ type LlmRunCmd

= RunCmd>; /** The success Msg the engine mints — resilient-call's, with the parsed `LlmOk`. */ type LlmSucceedMsg

> = SucceedMsg, "resilient", LlmCall

>; /** * The failure Msg the engine mints — resilient-call's. Its `error` is the * handler's `port_rejected` (an {@link LlmRejected} when the handler used * `decode` / `rejected`); read it as the typed {@link LlmErr} with `errOf`. */ type LlmFailMsg

= FailMsg<"resilient", LlmCall

>; /** The retry / deadline timer Msg — `DeadlineExceeded`, inherited from resilient-call. */ type LlmTimerMsg = DeadlineExceeded; /** * @demlik/tea/agent — the model ports and the brain call's Promise handler. * * `../internal/llm-call` is pure: it owns the brain call's slice, its * `Cmd.define`d run Cmd and the parse that turns a model's answer into that * Cmd's outcome, and it ships no engine code (ADR 0021). The agent is a Promise * host — `toMachine` hands its caller an `interpret` table and `defineAgent` * runs itself — so the one handler that actually invokes the model lives here: * the two DI ports (`model`, `loadMessages`) and {@link brainHandler}, which * calls them and returns the outcome `llm.decode` builds. */ /** * The minimal chat-model contract every model the handler talks to must * satisfy — the seed's `InjectableChatModel`, trimmed to the one operation * the brain call drives for brain-only stages: * * `withStructuredOutput(schema)` → a runnable whose `invoke(messages)` * resolves to a typed object matching `schema`. * * `BaseChatModel` from `@langchain/core` is the runtime type; this surface * names only what the handler calls so a test fake can ignore the rest. Generic * over the message shape `Msg` so a consumer's loader and model agree on it * without the agent inspecting messages. */ interface Llm { withStructuredOutput(schema: Schema): { invoke(messages: readonly Msg[]): Promise; }; } /** * Build the `Msg[]` the handler hands to the bound model for a given call. The * SDK / message-assembly seam — the seed's `buildBaseMessages` + the lazy * `loadMessages` loader rolled into one injected port. Async because the seed * lazy-imports the SDK (a top-level `import type` of the langchain messages * package explodes the workers test runner). Receives the full `LlmCall` so it * can branch on `purpose` exactly as the seed's `buildBaseMessages` did. */ type MessageLoader

= (call: LlmCall

) => Promise; /** * The model factory — the first DI port. `(modelId) => Llm`. Tests pass a fake * builder; production wires `createChatModel(env, getModelConfig(id))`. `null` * means "the host's default model" (the seed's `string | null`). */ type ModelFactory = (modelId: string | null) => Llm; /** * The plain-function model port — the common path. One async function * from the assembled messages to the model's answer; the handler validates the * answer through the purpose's `Schema` exactly as it re-validates the * structured-output path, so a malformed answer is a `resilient_run_err`, never * a corrupt success. `ModelFactory` → `withStructuredOutput(schema).invoke(...)` * stays the advanced form for a model that binds the schema itself. * * `T` is the answer type the schema narrows to — for the agent, an `AgentTurn`. */ type PlainModel = (messages: readonly Msg[]) => Promise; /** * Either model port. A bare `async` function is read as a `PlainModel` (see * {@link asModelFactory}); a sync function is the factory. */ type ModelPort = ModelFactory | PlainModel; /** * Lift a plain-function model into the `ModelFactory` port. The factory ignores * `modelId` (the function IS the model) and its `Llm` runs the bound schema over * the function's answer, so both ports meet the handler as one shape. * * Reach for this explicitly when the function is not declared `async` — a sync * function that returns a promise (`(m) => client.chat(m)`) carries no runtime * mark that tells it apart from a factory. Passed bare, `asModelFactory` * refuses it on the first call with an `LlmErr` whose reason is * {@link PLAIN_MODEL_MISROUTE_REASON}. */ declare function plainModel(fn: PlainModel): ModelFactory; /** * The reason an `LlmErr` carries when a sync promise-returning function was * passed as `model` bare — the one runtime shape neither port can own. */ declare const PLAIN_MODEL_MISROUTE_REASON: string; /** * @demlik/tea/agent — the domain data model: the tool + turn shapes the consumer * supplies, the agentic-stage conversation, the `createAgent` config object, and * the durable agent slice + its lifecycle status. * * Everything here is plain data (durable + replayable): the composed wrappers' * slices, the conversation, and the config are all JSON-serializable. The * compaction vocabulary lives in `./compaction`; this module imports its * types where the slice / config reference them. The reducer core (the verbs + * the wired `toMachine`) lives in `./index`. */ /** * One tool the model asked to call this turn. Plain data so it round-trips through the * durable fan-out ledger: a stable `callId` (the fan-out identity), the tool * `name`, and the opaque `args` the consumer's own interpret reads. */ interface ToolCall { /** Stable id the model minted; the fan-out item identity (`idOf`). */ readonly callId: string; /** The tool to invoke. The consumer's `toolOf` maps it to an effect Cmd. */ readonly name: string; /** Args the model emitted, opaque to the agent. */ readonly args: Readonly>; } /** * One model turn: the narration `content` the model produced and the * `toolCalls` it asked us to run. An empty * `toolCalls` means the model is done with this stage (advance the pipeline). * This is the parsed output of a brain call; the consumer's schema produces it. * * `provider` is the opaque passthrough slot (#93): whatever the adapter hands * back beside `content` / `toolCalls` that its provider expects echoed * verbatim on the next turn — Anthropic's signed `thinking` blocks, * `server_tool_use`, OpenAI reasoning items. tea stores it on the turn and * returns it unchanged on the `assistant` `AgentMessage` that replays this * turn; it never reads, validates or transforms it. The adapter owns its shape, * which must be JSON-serializable like the rest of the Model. A compaction fold * (ADR 0004) summarises turns into text, so it drops the slot with the turns it * summarises. Optional and additive: a persisted turn without it still parses. * * `usage` is what the provider REPORTED this call cost (#332) — never an * estimate tea computes. It is part of the brain call's journaled outcome, like * `content`, so a replay folds the same numbers (ADR 0004's "no token estimate * enters the Model" still holds). The run sums it into its running total * ({@link AgentState.usage}) and the conversation reads the latest context size * off it. Optional and additive: a turn * whose adapter maps no usage, or one persisted before the field existed, * parses and simply counts for nothing. */ interface AgentTurn { /** Free-text narration the model produced this turn (folded into the conversation). */ readonly content: string; /** The tools the model asked us to run; empty = stage done. */ readonly toolCalls: readonly ToolCall[]; /** Provider-opaque blocks to echo back verbatim next turn. tea never reads it. */ readonly provider?: unknown; /** The token usage the provider reported for this call. Omit → none reported. */ readonly usage?: TurnUsage; } /** * The token usage a provider reported for one model call, in the provider's own * counts. Every field is a non-negative integer; `agentTurnSchema` refuses * anything else, so a malformed report is the brain call's `llm` failure rather * than a `NaN` in the running total. * * `inputTokens` is the WHOLE prompt the call read, cached tokens included — * the number that says how full the context window is. `cachedInputTokens` is * the part of it the provider served from its prompt cache, so it never exceeds * `inputTokens`. An adapter whose provider reports the two apart (Anthropic's * `input_tokens` excludes cache reads) adds them back together here. * * The same shape is the run's running total ({@link AgentState.usage}): the * sum, field by field, of every turn that reported one. */ interface TurnUsage { /** Prompt tokens the call read, cached ones included. */ readonly inputTokens: number; /** Tokens the model produced. */ readonly outputTokens: number; /** Of `outputTokens`, those spent on reasoning — when the provider says. */ readonly reasoningTokens?: number; /** Of `inputTokens`, those served from the provider's prompt cache — when it says. */ readonly cachedInputTokens?: number; } /** * Narrow an unknown to a {@link TurnUsage} — the two required counts present, * and each optional one either absent or a count too. PURE — allocates no Error. */ declare function isTurnUsage(value: unknown): value is TurnUsage; /** * One partial piece of a turn the model is still producing — a token delta, as * the provider emitted it. * * A chunk is NOT state. It never reaches the Model, the journal or the Store: * by the time a turn is durable it has settled, and a delta that has not settled * is not an outcome ADR 0011 could fold. So `TurnChunk` carries only what a * progress surface renders — the text so far — and carries no identity, because * an identity would invite someone to store it. */ interface TurnChunk { /** The text delta this chunk adds to the turn's `content`. */ readonly text: string; } /** * The side channel a {@link StreamingModel} writes its deltas to — the second * argument of the streaming port. One sink, called synchronously by the adapter * as the provider yields; a throw from it is contained by the caller that * supplied it, so a progress surface's defect cannot fail a model call. */ interface ModelStream { /** Hand one delta to whoever is watching this run. */ readonly onChunk: (chunk: TurnChunk) => void; } /** * The streaming model port — `(messages, { onChunk }) => Promise`. * * The second, OPTIONAL shape of the brain. It differs from * `PlainModel` in one thing: it is handed a {@link ModelStream} it may * write deltas to while the turn is in flight. What it RESOLVES is the same * settled turn the plain port resolves, and that turn is the only thing the * reducer ever sees — the deltas are a side channel that ends at the caller's * listener. * * A `PlainModel` is assignable here (a function may declare fewer parameters * than its type), which is what lets one config field accept either shape. * `isStreamingModel` tells them apart at runtime so a plain model is still * invoked with exactly one argument, as it always was. */ type StreamingModel = (messages: readonly Msg[], stream: ModelStream) => Promise; /** * Whether a model port wants the {@link ModelStream} — read off its declared * arity, which is the mark JavaScript already carries. No config flag, and no * marker property for a consumer to forget: a brain written * `async (messages, { onChunk }) => …` streams, and one written * `async (messages) => …` does not. * * The cost of the arity read is the cost of every arity read — a model that * declares a parameter it ignores, or takes `...args`, reads as the other shape. * Both misreads are benign: a `...args` model is handed no stream and emits no * chunks; a model with an unused second parameter is handed a stream it never * writes to. Neither can change the settled turn. PURE. */ declare function isStreamingModel(model: (...args: never[]) => unknown): boolean; /** * Narrow an unknown to an `AgentTurn` — the runtime witness for tea's own * structured-output type. A consumer's brain schema parses the model's output * into an `AgentTurn` (the agentic purpose's output); rather than every consumer * hand-rolling this guard + a `Schema` for a type the agent OWNS, the * agent exports both. Checks the load-bearing fields: `content` is a string and * `toolCalls` is an array of `ToolCall` (each element guarded — the narrow is a * real parse of the boundary, not a shallow `Array.isArray`). `provider` is * opaque, so its presence or absence is not a fact the guard reads. `usage` is * not opaque — the reducer sums it — so it is either absent or a well-formed * {@link TurnUsage}. PURE — allocates no Error. */ declare function isAgentTurn(value: unknown): value is AgentTurn; /** * The `Schema` for tea's own turn type — the parse target a brain * call binds when the agentic purpose's output is a bare `AgentTurn` (the common * case). Throws on a non-`AgentTurn` (the zod-style `parse` contract the * llm-call handler relies on). Deletes the consumer's hand-rolled * `auditSchema` / `isAgentTurn` pair. * * A consumer whose turn type EXTENDS `AgentTurn` with extra fields still writes * its own schema (it must validate the extra fields); this is for the plain case. */ declare const agentTurnSchema: Schema; /** * One settled tool outcome the consumer routes back into the loop. * `ok` carries the result the consumer's interpret produced; * `error` carries the failure as data — see {@link ToolFailure}. */ type ToolOutcome = { readonly kind: "ok"; readonly result: R; } | ToolFailure; /** * A settled tool failure as the conversation keeps it: the `{ _tag, …payload }` * the tool failed with, spread beside the `reason` string the model reads. * * Both halves are load-bearing and neither replaces the other. `reason` is the * model's channel — `toolErrorReason`'s rendering, which is what the next brain * call carries; `_tag` and the payload are the program's, so host code can * branch on the failure instead of parsing prose out of `reason` (#115). A * payload field never shadows `kind` or `reason`: the router writes those last. * * `_tag` is OPTIONAL here for one reason only — a record persisted by 0.12.x or * earlier was written before the tag was kept, so a Store handing one back has * a failure with no tag, and a required field would be a lie about durable * state. Every failure THIS version mints carries one. For the exhaustive * per-tag union, take `onToolError`'s argument, which is typed from the tools * themselves ({@link ToolFailureOf}). */ interface ToolFailure { readonly kind: "error"; /** The model-facing rendering — `toolErrorReason(error)`. */ readonly reason: string; /** The failure's tag; absent only on a record persisted before 0.13. */ readonly _tag?: string; } /** * The failure arm typed against a KNOWN tag union — `{ kind, reason }` beside * each arm of `E`, distributed, so a `switch` on `_tag` narrows the payload and * an unhandled tag is a compile error. `ToolFailure` is its erased form. */ type TaggedFailure = E extends unknown ? { readonly kind: "error"; readonly reason: string; } & E : never; /** * The per-tool resilience knob — a timeout, a retry ladder, or both, declared on * the `tool()` spec and executed by the agent's reducer through * `../internal/resilience/resilient-call`. * * Both fields are optional and a tool that names neither behaves exactly as it * did before this knob existed: no slice entry is minted, no timer is armed, and * its settle path is the plain fan-out one. The ladder lives in the Model, so a * process killed between two attempts resumes at the attempt it was on rather * than restarting the run — the property a `Promise.race` or a `for` loop inside * the handler cannot have, because those live inside the effect boundary. */ interface ToolResilience { /** * The budget one tool CALL gets, in ms, measured from the first attempt and * NOT restarted by a retry — the overall cap `resilient-call`'s deadline brick * enforces. When it elapses the call settles as a `ToolOutcome` error * carrying `_tag: "timeout"` beside its `reason`, and the loop moves on, whatever the * in-flight attempt does next — its late settle arrives for a call nothing is * waiting on and folds nothing, so a slow tool costs the budget and not the * turn. * * What it does NOT do is cancel the handler: a promise cannot be cancelled in * JavaScript, so the attempt runs to its own end, and `run`'s teardown still * drains it. A handler that resolves LATE is bounded by this knob; a handler * that never resolves at all holds the runtime's shutdown regardless. tea * hands a tool handler no `AbortSignal`: if the work has to stop, put a signal * of your own on the `ctx` you pass to `agent.run` and read it from the * handler's second argument. * * Omit → the call has no cap and ends only when its handler settles. */ readonly timeoutMs?: number; /** * The backoff ladder a FAILED attempt climbs — the same * `BackoffCurve & RetryBudget` shape `AgentConfigCore.retry` takes for the * brain call. Each failure is recorded in the Model and the next attempt is * armed as a timer Sub, so the wait is durable and the attempt count survives * a reload. When the budget is spent the call settles as a `ToolOutcome` error * carrying `_tag: "retry_exhausted"` beside its `reason`, plus `attempts` and * `last` as fields — see {@link ToolRetryExhausted}. * * Omit → the first failure is the outcome, exactly as before. */ readonly retry?: AnyRetryPolicy; } /** The reason-tag a timed-out tool call settles under. */ declare const TOOL_TIMEOUT_TAG = "timeout"; /** The reason-tag a tool call that spent its retry budget settles under. */ declare const TOOL_RETRY_EXHAUSTED_TAG = "retry_exhausted"; /** A call that spent its `timeoutMs` budget — {@link ToolResilience.timeoutMs}. */ interface ToolTimedOut { readonly _tag: typeof TOOL_TIMEOUT_TAG; } /** A call that spent its retry budget — {@link ToolResilience.retry}. */ interface ToolRetryExhausted { readonly _tag: typeof TOOL_RETRY_EXHAUSTED_TAG; /** How many attempts the ladder burned, the failed last one included. */ readonly attempts: number; /** The last attempt's own `reason`, so the real failure is not buried. */ readonly last: string; } /** * The two failures the resilience ladder itself authors — `timeout` and * `retry_exhausted`. They are in every tool's * error union rather than only a policied tool's: the policy is a `tool()` spec * field a maintainer can add later, and a union that narrowed with it would turn * adding a `timeoutMs` into a silent behaviour change at every `onToolError` * that had switched exhaustively without them. */ type ToolResilienceError = ToolTimedOut | ToolRetryExhausted; /** * A folded tool record kept on the conversation once a tool settles — the * call + its outcome, in settle order. The consumer's message loader reads * these (plus `turns`) to assemble the next brain call's prompt. * * `turn` is the index of the producing turn in `turns` — the association * compaction needs to drop the RIGHT records (#85 / design A1). When compaction * folds `turns[0..N]` into a summary, it must also drop every tool record that * belonged to those turns; without a turn stamp on the record there is no honest * way to know which. It is the round-trip index, not a wall clock — small and * JSON-stable, preserving the durability invariant. */ interface ToolRecord { readonly call: ToolCall; readonly outcome: ToolOutcome; /** The producing turn's index in the current conversation. */ readonly turn: number; } /** Feedback answering the empty model turn at index `turn` in the conversation. */ interface Nudge { readonly turn: number; readonly text: string; } /** * Whether the agentic stage is waiting on the model (`llm`), on tools * (`tools`), or on a compaction round-trip (`compacting`). The in-flight * fan-out batch exists ONLY in the `tools` variant — "awaiting llm with tools * pending" is structurally impossible (TEA canon §2.6 / Rule 1 * impossible-states pin). Discriminated on `kind`. * * `compacting` is the honest state for the dedicated compaction round-trip * (design B1): the transcript grew, the policy asked to fold `folding` of the * OLDEST turns, and the summarize call is in flight INSTEAD of the next brain * call. `folding` is the count `planCompaction` returned — the fold-back * (`compact_ok`) drops exactly that many head turns + their tool records. */ type Awaiting = { readonly kind: "llm"; } | { readonly kind: "tools"; readonly batchTurn: number; } | { readonly kind: "compacting"; readonly folding: number; }; /** * The agentic-stage conversation — durable inside the agent slice so an * eviction mid-loop resumes the exact turn. The model turns + folded tool * records are the consumer's prompt source (via the llm-call message loader); * `turnCount` drives the livelock guard; `awaiting` carries the ONE outstanding * effect for the agentic stage. * * Generic over the consumer's tool-result type `R` (what `toolOk` carries). * * `contextTokens` is this transcript's reading of provider-reported usage * (#332); the run's total is not the transcript's, so it lives on * {@link AgentState.usage}. A Model persisted before `contextTokens` existed * comes back without it, and the first transition fills it in as `null`. */ interface Conversation { /** Model turns this stage has produced, in order. */ readonly turns: readonly AgentTurn[]; /** Settled tool records, in settle order — the model sees these next turn. */ readonly toolRecords: readonly ToolRecord[]; /** Feedback answering empty model turns, in conversation order. */ readonly nudges: readonly Nudge[]; /** Monotonic round-trip count; the livelock guard compares it to `maxTurns`. */ readonly turnCount: number; /** What the loop is waiting for next. */ readonly awaiting: Awaiting; /** * The latest context size: `inputTokens + outputTokens` of the most recent * brain turn — how much of the context window the transcript now fills. * `null` when that turn reported no usage, when a compaction fold has run * since (the pre-fold size describes a transcript that no longer exists), and * at the start of each stage. `compaction.afterContextTokens` reads it. */ readonly contextTokens: number | null; } /** * The snapshotting discriminant. Checkpointing is either OFF — in which * case `snapshotEvery` is structurally absent and the monitored-run slice never * emits a `snapshot_write` Cmd — or ON, in which case `snapshotEvery` is a * `number`. A `{ snapshotEvery?: never }` member (rather than a bare optional) * makes the OFF case load-bearing: it forbids passing `snapshotEvery` at all, so * `toMachine` can config-derive whether the `snapshot_write` interpret handler * is REQUIRED (ON) or FORBIDDEN (OFF) instead of defaulting it to a silent * no-op. * * This is what kills the type lie: with checkpointing off, `snapshot_write` is * absent from the consumer's interpret contract entirely — never a * `snapshot_write: async () => undefined` ceremony that masks a real wiring bug. */ type AgentSnapshotConfig = { readonly snapshotEvery?: never; } | { readonly snapshotEvery: number; }; /** * The core (non-snapshot, non-compaction) agent configuration. The full `AgentConfig` * intersects this with the `AgentSnapshotConfig` + `AgentCompactionConfig` * discriminants — see those types for why the cadence / policy are discriminated * unions rather than bare optionals. * * Type parameters: * - `Stage` — the consumer's pipeline stage id (any JSON value). * - `P` — the brain-call purpose union (`"plan" | "act" | ...`). * - `O` — the purpose→output map. Every purpose drives the agentic loop, * so each output is pinned to `AgentTurn` (or a subtype) by the * `O extends Record` bound — that is what the loop * folds. An `Outputs` whose purpose output is NOT an `AgentTurn` * fails to compile here; the rule lives in the type, not a cast. * - `R` — the consumer's tool-result type (what `toolOk` carries). * - `TC` — the consumer's per-tool effect Cmd, the discriminated variant * `toolOf` produces. Kept PRECISE (a closed Cmd variant, not the * open `Cmd`) so `AgentCmd` stays a closed discriminated * union and the wired machine's interpret merge type-checks per * key — the brain handler maps to `resilient_run`, the tool one to * `TC["_tag"]` — with no laundering cast. Defaults to `Cmd` for * the consumer that does not care to name its tool Cmd. * - `Msg` — the model's message shape (threaded through the llm-call loader). */ interface AgentConfigCore, R, TC extends Cmd = Cmd, Msg = unknown> { /** The ordered stages. Omit / empty → a single-shot run (one agentic stage). */ readonly stages?: readonly Stage[]; /** No-progress watchdog budget, in ms. Omit → no watchdog. */ readonly deadlineMs?: number; /** * DI port — the brain. `async (messages) => turn` is the common path: * the returned turn is validated through the purpose's schema * (`agentTurnSchema` for the plain case), so a malformed turn is the run's * `llm` failure, not a throw. `(modelId) => Llm` is the advanced form for a * model that binds the structured-output schema itself. */ readonly model: ModelPort; /** * The system prompt, stored ON THE MODEL at `init` (`AgentState.instructions`) * rather than closed over — so a replay reproduces the exact prompt that ran, * a rehydrated run keeps the prompt it started with, and a compaction fold * (which touches only the conversation) can never lose it (ADR 0004). It * reaches the brain call through `payloadOf`'s third argument. Omit → `null`. */ readonly instructions?: string; /** One structured-output schema per purpose; the parse target per brain call. */ readonly schemas: { readonly [K in P]: Schema; }; /** Backoff policy for brain calls, composed into `../llm-call`. Omit → no backoff. */ readonly retry?: RetryPolicy; /** DI port — the SDK / message loader. Omit → brain calls invoke with `[]`. */ readonly loadMessages?: MessageLoader; /** Map one tool call to the effect Cmd the consumer's interpret performs. */ readonly toolOf: (call: ToolCall) => TC; /** * The per-tool timeout / retry knob for a call, read once per launch. `null` * (or an omitted seam) → the tool runs bare and its settle path is the plain * fan-out one, byte for byte what it was before the knob existed. * * This is the seam a `toolRouter` fills from the `tool()` specs * (`router.resilienceOf`), which is how `defineAgent` grows the knob without * growing a lid option: the policy is declared where the tool is. A hand-wired * `createAgent` supplies it directly. It must be PURE and config-derived — the * reducer calls it on the launch path. */ readonly toolResilienceOf?: (call: ToolCall) => ToolResilience | null; /** * How many of ONE turn's tool calls a transition LAUNCHES at once. At the * default `1` a turn's calls go out one at a time; raise it and up to that * many move from `pending` to `running` in the fan-out ledger in a single * transition, so the durable Model (and a `store`'s record of it) says what * was launched. * * Above `1` those calls also OVERLAP on the clock, so a turn of two slow * tools costs the slower rather than the sum — but only for the tool cells a * `toolRouter` owns (the `toMachine({ tools })` path, which `defineAgent` * takes). The overlap lives inside those cells, never in the kernel: * `runInterpret` still interprets a transition's Cmds one after another and * never interleaves two handlers (ADR 0018). A hand-wired `toolInterpret` * cell is yours, so it overlaps only if you write it to. * * Overlapping does NOT reorder the fold. Settle Msgs are dispatched in * Cmd-EMISSION order whichever call finishes first, so a replayed log * reproduces the same Model — invariant 2's serializability, which the knob * was never allowed to spend. * * Omit (or `1`) → serial dispatch, exactly as before. */ readonly toolConcurrency?: number; /** * Which brain-call purpose a given stage runs. The agent fires * `call_llm{ turnOf(stage) }` to drive the agentic stage's loop. The purpose's * schema output is an `AgentTurn` — enforced by the `O extends Record` bound, not left to a doc-comment. */ readonly turnOf: (stage: Stage | undefined) => P; /** * Build the per-purpose brain-call payload from the durable state: the * stage, the conversation, and the Model's `instructions` slot. Omit → `null`. */ readonly payloadOf?: (stage: Stage | undefined, conversation: Conversation, instructions: string | null) => unknown; /** The model id every brain call invokes. Omit → `null` (the host's default). */ readonly modelId?: string | null; /** * Livelock guard: bound on model round-trips within one run. On * `turnCount >= maxTurns` the run fails `{ reason: "turn_limit" }`. Omit → no * turn guard (the other stop conditions still bound the loop). */ readonly maxTurns?: number; /** * Wall-clock guard: total milliseconds from `run.startedAt` the run may take. * At the turn boundary, `at - run.startedAt >= maxElapsedMs` fails the run * `{ reason: "elapsed_limit" }`. Unlike `deadlineMs` — a no-progress watchdog * that RESTARTS on every advance — this budget never restarts, so a run that * keeps progressing is bounded by it. Omit → no wall-clock cap. * * `startedAt` is durable, so a resumed run continues the ORIGINAL budget * rather than starting a fresh one; the elapsed span a killed run spent dead * counts against it. */ readonly maxElapsedMs?: number; /** * The consumer's own stop condition, consulted at the turn boundary once the * turn-count and wall-clock guards have passed. `true` settles the run * `cancelled` at `at` — the same terminal an aborted `signal` reaches, so the * transcript stands and no further model call goes out. Omit → no predicate. * * Where `maxTurns` and `maxElapsedMs` bound a quantity this agent counts, * this bounds one only the caller can see (an external flag, a condition on * the turns so far) — or a token budget: `state.usage` is the run's running * total of provider-reported usage, so a budget stop is a predicate over it * and needs no knob of its own (#332). It must be PURE and total over the state * it is handed — the reducer calls it, so a replay of the same Msg log calls * it with the same state and must get the same answer. It is config, not * Model: a resumed run consults the predicate the config passed to THIS boot. */ readonly stopWhen?: (state: AgentState) => boolean; /** * Consulted when a turn asks for no tools. `null` lets the stage retire; * a string keeps it running and is read next turn as a user message. * Omit → the stage retires on its first turn without tools. * * It must be PURE and total over the state it is handed — the reducer calls * it, so a replay of the same Msg log calls it with the same state and must * get the same answer. It is config, not Model: a resumed run consults the * predicate the config passed to THIS boot. */ readonly continueWhen?: (state: AgentState) => string | null; /** * The impurity-injection seam for the inherited brain-call retry jitter — the * ONE place this otherwise-pure machine reads randomness. Pass a fixed * `() => 0` to pin backoff (tests, replay, durability proofs). Omit → * `Math.random`, read only at the resilient-call verb boundary. */ readonly rng?: () => number; } /** * The agent configuration — the core seams intersected with the snapshotting discriminant * (`AgentSnapshotConfig`). Type parameters are documented on `AgentConfigCore`; * the only addition here is that `snapshotEvery` is the discriminant that drives * whether `toMachine` requires (or forbids) the `snapshot_write` interpret * handler. */ type AgentConfig, R, TC extends Cmd = Cmd, Msg = unknown> = AgentConfigCore & AgentSnapshotConfig & AgentCompactionConfig; /** * Why a run terminated as `failed`, beyond monitored-run's own reasons. The * `turn_limit` reason is the agent's livelock guard and `elapsed_limit` its * wall-clock one; deadline / stage failures surface through the monitored-run * slice's own `failure`. */ type AgentFailure = { readonly reason: "turn_limit"; readonly at: number; } | { readonly reason: "elapsed_limit"; readonly at: number; } | { readonly reason: "llm"; readonly error: unknown; readonly at: number; }; /** * The agent slice — every composed wrapper's slice plus the loop's conversation * and the agent-specific failure annotation. * * - `run` — the `../monitored-run` slice (pipeline position + * lifecycle + watchdog). The OUTER lifecycle truth. * - `resilience` — the `../llm-call` (= resilient-call) slice (brain-call * retry / backoff). Per-purpose retry lives here. * - `tools` — the `../fan-out` ledger for the current turn's tools. * - `conversation` — the agentic-stage loop state. `null` until the loop is * entered (the consumer seeds it at the agentic stage). * - `usage` — the run's provider-reported token total. It outlives * every conversation, `done` included. * - `failure` — the agent-specific terminal annotation (turn-limit / * llm), null otherwise. Distinct from `run.failure`. * - `instructions` — the system prompt this run was configured with, set at * `init` and never touched by a fold (ADR 0004). */ interface AgentState, R> { readonly run: MonitoredRunState; readonly resilience: ResilientState, LlmOk>; readonly tools: FanOutState>; readonly conversation: Conversation | null; /** * The run's running usage total (#332, #354): every brain turn of this RUN * that reported usage, summed field by field. It is what the run cost, so it * belongs to the run and not to any one conversation: a compaction fold keeps * it, a stage advance keeps it, and the retire to `done` keeps it after the * conversation is cleared — `status(state)`'s `done` arm hands it on. Only a * start for a new run resets it to zero; a repeated start for the stored * `runId` leaves it as it is. Read it from `stopWhen` for a token budget. * * The one place the total lives. A Model persisted before this field held its * total on `conversation.usage`, and one persisted by 0.17.x held none; the * first transition either takes over lifts the old total here (or starts from * zero) and drops the conversation's copy. */ readonly usage: TurnUsage; /** * The compaction round-trip's resilient slice (#85, design B1) — a DEDICATED * resilient-call slice for the reserved `$compact` purpose, separate from the * brain `resilience` slice so a compaction retry/backoff never disturbs the * brain call's breaker or retry counter. Always present (empty `calls` when no * compaction is in flight, or when no policy is configured) so the slice stays * a flat plain-data record — durable + replayable like every composed wrapper. */ readonly compaction: ResilientState, LlmOk>; /** * The per-tool timeout / retry ladders (#117) — one dedicated resilient-call * slice PER TOOL NAME, because the policy is declared per tool and one slice * carries one config. Keyed by tool name; each slice's own keys are * {@link toolCallKey}s, so two concurrent calls to the same tool climb * independent ladders while sharing the tool's declared policy. * * A tool declaring neither `timeoutMs` nor `retry` mints no entry, so this is * `{}` for every agent that uses no per-tool knob — the addition costs an * empty record on the durable Model and nothing else. * * The result arm is `null`: a tool's VALUE settles through the fan-out ledger * and the conversation, exactly as before. This slice tracks only the ladder — * which attempt is out, when the next one is due, and when the budget is spent * — which is what has to survive a reload. */ readonly toolResilience: Readonly>>; /** * The `callId`s whose PUBLIC outcome is already a failure (#145) — a tool the * ladder settled on its deadline or on a spent retry budget, or one whose own * error was folded. A promise cannot be cancelled, so the abandoned attempt * may still resolve; when it does, its late `_ok` names a `callId` listed * here and every public channel stays silent about it. * * The fan-out already drops the late value (its entry is gone, so the fold is * a no-op), but "folds nothing" and "emits nothing" are two different facts: * the event projector is Msg-shaped and would otherwise push a `ToolSettled` * for a `callId` `onToolError` already reported as `{ _tag: "timeout" }`. The * projector reads the post-transition state, by which point the ladder has * forgotten the key, so the discriminator is carried HERE rather than derived * from a presence check that erases both readings. * * Plain data, one string per failed call, cleared by `start` with the rest of * the prior run's bookkeeping. It survives the batch drain and the stage * retire on purpose — that is exactly when a late settle arrives. */ readonly refusedCalls: readonly string[]; /** * What THIS transition started, failed or ended (#331) — the outbox the * event projector reads. Cleared on entry to every verb, so it only ever * holds the one transition's facts. * * The projector sees `(msg, post-state)` and nothing else, and none of these * facts can be read back off that pair: a brain call issued after a batch * drains, a queued tool backfilling a slot, a timeout the ladder settled and * the transition that ended the run all leave a state that looks like the * one before. The reducer knows at the moment it does them, so it writes * them down here, the same way `refusedCalls` carries the one fact the * projector could not derive. * * Absent on a Model persisted before 0.18; every reader treats that as empty. */ readonly lifecycle: readonly AgentLifecycleNote[]; readonly failure: AgentFailure | null; /** * The run's terminal output — the FIRST-CLASS result (issue #46). `null` * until the pipeline finishes; set to the last model turn (the empty-tool * turn that retired the final stage) the instant `run.phase` becomes `"done"`. * * This survives the `conversation` clear on stage retire: clearing the * conversation is correct durability hygiene (a finished stage's transcript * is not live state), but the run's PRODUCT is, so it lives here on the * durable slice rather than being scraped off the `observe` firehose by * matching the private `resilient_ok` Msg and racing the clear (the old * `captureLastTurn` dance this field deletes). A consumer reads * `runtime.result()?.output` / `(await runtime.done()).output`. * * Typed `AgentTurn | null` (not `O[P]`): the run's output is always a model * turn — the `O extends Record` type bound pins every purpose's * output to an `AgentTurn`, and the terminating turn is the one with no tool * calls. The wider `Record` bound on `AgentState` itself does not * constrain `O[P]`, so naming the concrete `AgentTurn` keeps this field's type * total without a purpose-indexing narrow. */ readonly output: AgentTurn | null; /** * The system prompt, durable beside the transcript it governs. `null` when * the config named none. Read by `brainCall` on every model call — a * rehydrated or replayed run prompts with what the Model says, never with * what a closure happens to hold now. */ readonly instructions: string | null; } /** * The unified terminal failure the agent settles on. The agent terminates `failed` * through TWO independent slice channels: * * - `state.failure` (`AgentFailure`) — the AGENT'S OWN annotation * (`turn_limit` livelock guard / `elapsed_limit` wall-clock guard / `llm` * exhausted-retry). Set WITHOUT moving * `run.phase` (it stays `running`); `isSettled` treats a non-null `failure` * as terminal regardless of `run.phase`. * - `state.run.failure` (`RunFailure`) — the monitored-run channel * (`deadline` watchdog / `stage` failure), present iff `run.phase` is * `"failed"`. * * Callers used to union these by hand at every status question. `status` * collapses them into ONE `failure`, so a consumer reads `status(s).failure` * without knowing which channel produced it. */ type AgentTerminalFailure = AgentFailure | RunFailure; /** * One fact a transition recorded on {@link AgentState.lifecycle} — the input * the `agentEvents` projector turns into `BrainStarted`, `ToolStarted`, * `ToolFailed` and `RunDone`. * * - `brain_started` — a brain call was issued for conversation turn `turn`. * Once per turn, and again on a cold-wake `boot` that re-fires it; a retry * of the same turn is not a new start. It names the call by its `purpose`, * which is the call's key on {@link AgentState.resilience}, and carries no * copy of the request: the in-flight `LlmCall` is already on that slice, so * a checkpoint holds the prompt once (#354). The projector reads the * request's `payload` from there. * - `tool_started` — a tool call was issued: launched from a batch, a * queued call backfilling a slot, or re-fired by `boot`. A retry is not a * new start. * - `tool_failed` — a call ended on a failure the model will read: its own * error, a spent retry budget, or its timeout. * - `run_ended` — the run reached `done`, `failed` or `cancelled` on * this transition. */ type AgentLifecycleNote = { readonly kind: "nudge_recorded"; readonly text: string; readonly at: number; } | { readonly kind: "brain_started"; readonly turn: number; readonly purpose: string; readonly model: string | null; readonly at: number; } | { readonly kind: "tool_started"; readonly call: ToolCall; readonly at: number; } | { readonly kind: "tool_failed"; readonly call: ToolCall; readonly failure: ToolFailure; readonly at: number; } | { readonly kind: "run_ended"; readonly at: number; }; /** * The agent's lifecycle status — THE single typed channel for "what is this run * doing?". A discriminated union on `kind` so any change to the * private slice shape (`Awaiting`, the failure channels, `run.phase`) forces a * compile error at the call sites that switch on it, instead of silently * breaking a hand-rolled re-derivation. Make-invalid-states-unrepresentable: * * - `idle` — never started: `run.phase === "idle"`, the slice straight * out of `init` before any `agent_start`. Distinct from * `running` so a "start or resume?" decision never boots a * run that has not begun (#92); the next move is `agent_start`. * - `running` — live, NOT awaiting tools (a brain call or a compaction is * in flight, or the run is between stages). Resumable on cold * wake, the same as `suspended`: the in-flight call re-fires * from `boot`. A `stale` run reads here too: monitored-run * documents it as a soft, still-resumable live mark that the * next `progress` flips back to `running`. * - `suspended` — running + a live conversation + `awaiting.kind === "tools"`. * `pending` is the outstanding tool calls * (`conversation.awaiting` … the in-flight batch), read off * `tools.running`. Resumable on cold wake: `boot` re-fires * every call still in flight. * - `done` — the pipeline finished; `output` is the terminal model turn * stamped on `state.output` (issue #46), `null` if the run * produced no turn. `usage` is what the whole run cost, * `state.usage` (#354). * - `failed` — terminal failure; `failure` is the UNIFIED channel * (`AgentTerminalFailure`), absorbing the `state.failure` vs * `state.run.failure` dual channel so callers stop unioning. * - `cancelled` — stopped because the caller asked — an aborted `AbortSignal`, * or their own `stopWhen` answering `true` at a turn boundary; * `at` is when the stop landed. Terminal and distinct from * `failed`: nothing went wrong, the caller asked, so a consumer * branching on failure does not have to except one reason. There is no * `output` — a cancelled run produced no terminal turn, and a * `null` one here would be indistinguishable from a `done` run * that produced none. */ type AgentStatus = { readonly kind: "idle"; } | { readonly kind: "running"; } | { readonly kind: "suspended"; readonly pending: readonly ToolCall[]; } | { readonly kind: "done"; readonly output: AgentTurn | null; readonly usage: TurnUsage; } | { readonly kind: "failed"; readonly failure: AgentTerminalFailure; } | { readonly kind: "cancelled"; readonly at: number; }; /** * The three {@link AgentStatus} arms a run can end on — what `RunDone` carries. * `done` holds the output, `failed` the unified failure, `cancelled` when the * stop landed. */ type AgentEndedStatus = Extract, { readonly kind: "done" | "failed" | "cancelled"; }>; /** * Ask where an agent run stands: pass its state, get back one of `idle`, * `running`, `suspended` (with the tool calls it is waiting on), `done` (with * the output) or `failed` (with the failure). * * Read this instead of picking at the state's own fields. PURE — reads no * clock or randomness, allocates one small record. * * Ordering is terminal-first so a settled run never reports `running`, and a * never-started one never reports live: * * 1. `state.failure` (the agent's own annotation, set WITHOUT moving * `run.phase`) → `failed`. Checked first because `turn_limit` / `llm` * leave `run.phase === "running"`; reading `run.phase` first would * misreport such a run as `running`. This is the canonical failure source * when present. * 2. `run.phase === "idle"` → `idle`. Never started (#92); after the failure * check so the annotation stays canonical, before every live reading so * an `init` slice is never mistaken for a run in flight. * 3. `run.phase === "failed"` → `failed`, carrying `run.failure` (deadline / * stage). The fallback channel. * 4. `run.phase === "done"` → `done` with `state.output` (#46) and the run's * usage total (#354). * 5. `run.phase === "cancelled"` → `cancelled`, carrying when the stop landed. * 6. `running` / `stale` + conversation + `awaiting.kind === "tools"` → * `suspended` with the outstanding tool calls (`tools.running`); otherwise * the run reads `running`. Both are mid-run states a cold wake resumes. * * Steps 2–6 are ONE exhaustive `switch` over `run.phase` closed by `absurd`, not * an `if` chain with a trailing `return { kind: "running" }`. Under the chain a * phase added to the slice and forgotten here reported as `running` — a terminal * run described as live, which is the worst answer this function can give and one * nothing would have caught. The switch turns that omission into a type error. */ declare function status, R>(s: AgentState): AgentStatus; /** * @demlik/tea/agent — the context-compaction seam. * * The opt-in transcript snapshot-and-compact policy, shaped exactly like * `AgentSnapshotConfig` (see `./types`) so a short agent pays nothing and cannot * even mention the machinery. This module owns the whole `$compact` vocabulary: * the reserved purpose, the summary schema, the consumer policy, the config * discriminant, and the dedicated `compact_run` / `compact_ok` / `compact_err` * Cmd + Msgs re-keyed off the composed resilient call at the agent boundary. */ /** * The reserved purpose the compaction round-trip runs under. Compaction * is a DEDICATED resilient LLM call (design B1), NOT one of the consumer's brain * purposes `P` — so it carries its own purpose literal, kept in the agent's * private `$`-namespace (the same reserved-namespace discipline `with-resilience` * uses) so it never collides with a consumer purpose. A consumer never names it. */ type CompactionPurpose = "$compact"; /** The reserved compaction purpose's value — the single in-flight summarize call's key. */ declare const COMPACTION_PURPOSE: CompactionPurpose; /** * The purpose→output map for the compaction LLM call — the single reserved * `$compact` purpose mapping to a {@link CompactionSummary}. Mirrors the brain * call's `O` map, scoped to the one compaction purpose, so the composed * `createLlmCall` parses the summarize output under the same structured-output * contract the brain call uses. */ interface CompactionOutputs extends Record { readonly $compact: CompactionSummary; } /** * Narrow an unknown to a {@link CompactionSummary} — the runtime witness for the * compaction call's structured output. Checks the one load-bearing field * (`summary` is a string). PURE — allocates no Error. */ declare function isCompactionSummary(value: unknown): value is CompactionSummary; /** * The `Schema` the compaction call binds — tea's own parse * target for the summarize round-trip (it OWNS the `$compact` purpose's output). * Throws on a non-summary (the zod-style `parse` contract the llm-call handler * relies on), so a malformed summary is a `compact_err` (errors are data), never * a corrupt fold-back. */ declare const compactionSummarySchema: Schema; /** * The result a compaction round-trip produces — the model's summary of the * folded-away turns. Tea OWNS this shape (the `$compact` purpose's output): the * fold-back (`compact_ok`) writes `summary` into a synthetic head `AgentTurn` * (design A1), so a consumer's `loadMessages` reads it as a normal turn with no * watermark to learn. Generic-free — the summary is always plain text. */ interface CompactionSummary { /** The model's summary of the folded-away (oldest) turns + their tool records. */ readonly summary: string; } /** * The consumer's compaction policy. One PURE trigger; the impure * summarize round-trip is composed by the agent (a dedicated resilient LLM call * under the reserved `$compact` purpose, inheriting retry/backoff — design B1), * so the policy never reaches the model itself. * * - `planCompaction` — PURE: given the live conversation ABOUT to fire a brain * call, return how many of the OLDEST turns to fold into a summary, or `0` * to skip. No clock, no RNG → replay re-decides identically (design D). A * char-length / turn-count / real deterministic-tokenizer heuristic all * qualify. Returning `>= turns.length` is clamped to "fold all but keep the * loop alive" by the trigger (it never folds the turn currently in flight). * - `payloadOf` — build the per-call prompt payload the compaction * `MessageLoader` reads (the turns being folded). Omit → `null` (the loader, * if any, reads the conversation off the agent's own state). Opaque to the * agent, exactly like the brain call's `payloadOf`. */ interface CompactionPolicy { /** PURE trigger: how many OLDEST turns to fold (`0` = skip). No clock/RNG. */ readonly planCompaction: (conversation: Conversation) => number; /** Build the summarize call's prompt payload from the turns being folded. Omit → `null`. */ readonly payloadOf?: (conversation: Conversation, folding: number) => unknown; /** DI port — the SDK / message loader for the summarize call. Omit → invoke with `[]`. */ readonly loadMessages?: MessageLoader; } /** * The compaction discriminant, shaped exactly like {@link * AgentSnapshotConfig}. Compaction is either OFF — * `compaction` is structurally absent and the agent never emits a `compact_run` * Cmd — or ON, in which case `compaction` is a {@link CompactionPolicy}. A `{ * compaction?: never }` member (rather than a bare optional) makes the OFF case * load-bearing: it forbids passing `compaction` at all, so `toMachine` * config-derives whether the `compact_run` interpret handler is REQUIRED (ON) or * FORBIDDEN (OFF) — never a silent no-op handler, the same type-lie-killer * `AgentSnapshotConfig` uses. */ type AgentCompactionConfig = { readonly compaction?: never; } | { readonly compaction: CompactionPolicy; }; /** * The "summarize the oldest N turns" effect Cmd — the compaction round-trip's * carrier. It mirrors the brain `resilient_run` Cmd's shape (a `key` + the * plain `LlmCall` input, no closures) but under the dedicated * `compact_run` discriminant so it routes to the compaction interpret handler, not * the brain one. The handler composes the resilient-call wrapper (retry/backoff) and * returns the re-keyed `compact_ok` / `compact_err` settle for re-entry. */ type AgentCompactRunCmd = Cmd & { readonly key: CompactionPurpose; readonly input: LlmCall; }; /** The compaction round-trip success settle Msg — carries the parsed {@link CompactionSummary}. */ type AgentCompactOkMsg = { readonly _tag: typeof MsgType.CompactOk; readonly key: CompactionPurpose; readonly result: LlmOk; readonly at: number; }; /** The compaction round-trip failure settle Msg — carries the typed {@link LlmErr}. */ type AgentCompactErrMsg = { readonly _tag: typeof MsgType.CompactErr; readonly key: CompactionPurpose; readonly error: LlmErr; readonly at: number; }; /** * The CONFIG-DERIVED compaction obligation on `toMachine`'s `toolInterpret` * — the exact twin of {@link SnapshotInterpret}. * Resolves on the `Compact` discriminant the compaction overload of * `createAgent` fixes: * * - compaction ON → a REQUIRED `compact_run` handler * (`Interpret`). The summarize round-trip MUST be * wired — the agent never defaults it to a no-op. * - compaction OFF → `{ compact_run?: never }`. The handler is FORBIDDEN: with no * policy the agent never emits a `compact_run` Cmd, so wiring it would be * dead code. The consumer cannot even mention `compact_run`. * * Same type-lie-killer as the snapshot derivation: the obligation is present * EXACTLY when the Cmd can fire, never as a silent gap the agent backfills. */ type CompactInterpret = Compact extends true ? Interpret : { readonly compact_run?: never; }; /** * @demlik/tea/agent — content parts: the provider-neutral shape a multimodal * message is written in. * * A `user` message's content is a string or a list of parts, and a tool can * hand the model parts beside its outcome (a screenshot, a PDF). The three * kinds are the intersection Anthropic's and OpenAI's content blocks both map * onto — text, an image, a file — and tea imports neither SDK: the adapter * maps a part to its provider's block, exactly as it maps a whole message. */ /** Bytes or a URL a model adapter can send to its provider. */ type ResolvedMediaSource = { readonly type: "base64"; readonly data: string; } | { readonly type: "bytes"; readonly data: Uint8Array; } | { readonly type: "url"; readonly url: string; }; /** An opaque host-owned blob key and its decoded byte length, safe to persist. */ interface MediaReference { readonly type: "reference"; readonly key: string; readonly byteLength: number; } /** * Inline content, a URL, or a blob the model adapter resolves before sending. * Tool results are durable: keep the reference metadata in the result and * derive a reference part from it. Rendering and compaction never read the * blob; only the host's model adapter calls `resolveMediaParts` to read it. */ type MediaSource = ResolvedMediaSource | MediaReference; /** A run of text. */ interface TextPart { readonly type: "text"; readonly text: string; } /** An image the model looks at; `mediaType` is its IANA type, such as `image/jpeg`. */ interface ImagePart { readonly type: "image"; readonly mediaType: string; readonly source: MediaSource; } /** A document the model reads; `mediaType` is its IANA type, such as `application/pdf`. */ interface FilePart { readonly type: "file"; readonly mediaType: string; readonly source: MediaSource; } /** One part of a multimodal message. */ type ContentPart = TextPart | ImagePart | FilePart; /** Provider-ready content whose sources contain no unresolved blob keys. */ type ResolvedContentPart = TextPart | ((ImagePart | FilePart) & { readonly source: ResolvedMediaSource; }); /** * Resolve references at the model boundary using the host's blob reader. * Stored parts are never mutated. Text, ordering, media types and resolved * sources are preserved; a failed read rejects for the model's retry policy. */ declare function resolveMediaParts(parts: readonly ContentPart[], resolve: (reference: MediaReference) => Promise): Promise; /** A message's content: a plain string, or a list of parts. */ type MessageContent = string | readonly ContentPart[]; /** * A message's content as parts — a string reads as one text part, so an adapter * maps one shape whichever it was handed. PURE. */ declare function contentParts(content: MessageContent): readonly ContentPart[]; /** The text an omitted image stands in as. */ declare const IMAGE_OMITTED = "[image omitted]"; /** The text an omitted file stands in as. */ declare const FILE_OMITTED = "[file omitted]"; /** * The parts with every image and file replaced by a text placeholder — what a * summarizer is handed, since the summary is text and cannot carry the pixels * forward. Text parts pass through by reference. PURE. */ declare function omitMedia(parts: readonly ContentPart[]): readonly ContentPart[]; /** * @demlik/tea/agent — the one construction every tool definition goes through. * * NOT part of the public `./agent` barrel. `tool()` and `agentTool()` are two * constructors of the same `ToolDef`: `tool()` hands its handler the parsed `args`, * and `agentTool()` needs the whole Cmd — `callId` included — because the call's * identity is what keys the child run. Both are built here, so the reserved-name * refusal, the `thrown` channel and the resilience knob have one definition. */ /** * The prefix a protocol discriminant was minted from: `resilient_run_ok` → * `resilient_run`, `compact_run` → `compact`. A tool named by that prefix would * mint the same `_ok` / `_err` the agent's reducer already owns. */ type SettlePrefixOf = T extends `${infer P}_ok` | `${infer P}_err` | `${infer P}_run` ? P : never; declare const REJECTED_TYPE = "tool_rejected"; declare const SNAPSHOT_WRITE_TYPE = "snapshot_write"; /** * A tool name `tool()` and `agentTool()` refuse. A tool's name is its Cmd `_tag` — so * its interpret key — and the prefix of its settle Msgs, so every string * already spoken by the protocol is taken twice over: the settle prefixes * (`resilient_run`, `agent_tool`, `compact`) would overwrite the agent's own * reducer handlers through `toMachine`'s last-wins spread, and the discriminants * themselves (`compact_run`, `resilient_run`, …) would shadow the interpret * handler of that name. `resilient` is reserved as a Cmd prefix — the part * before `_run` in the brain Cmd `resilient_run` — not as a settle prefix: its * `resilient_ok` / `resilient_err` name nothing the agent settles. Both halves * derive from `MsgType`: a new entry there * reserves its name and its prefix with no second edit. The two names outside * the protocol are the router's own `tool_rejected` and the checkpoint handler * `snapshot_write`, which `toMachine` merges under the consumer's key. */ type ReservedToolName = MsgTypeValue | SettlePrefixOf | typeof REJECTED_TYPE | typeof SNAPSHOT_WRITE_TYPE; /** Whether `name` is one a tool constructor refuses — the set `ReservedToolName` types. */ declare function isReservedToolName(name: string): name is ReservedToolName; /** * Widens to `unknown` for a name outside the reserved set and to `never` * inside it, so `Name & NotReserved` is the name itself or * unconstructible. A widened `string` passes here — the runtime check in * `definedTool` is what catches a reserved name built from one. */ type NotReserved = Name extends ReservedToolName ? never : unknown; /** * @demlik/tea/agent — `tool()` + `toolRouter()`: declare a tool once and derive * what a consumer used to hand-write twice — the `toolOf` mapping from a * model's `ToolCall` to an effect Cmd, and the interpret handler that runs it * and settles it. * * A tool is a `Cmd.define`d effect whose input is the model's call — * `{ callId, args }` — with the handler colocated on the constructor. The * router folds a set of them into one `toolOf` and one interpret table; the * handlers settle through the minted `_ok` / `_err` Msgs, errors as * `{ _tag }` data (ADR 0011). `createAgent(...).toMachine({ tools })` folds * those settles into the conversation, so a consumer names nothing twice. */ /** * The input a tool Cmd carries: the model's `callId` (the fan-out identity the * settle folds back on) and the `args` already parsed against the tool's * `input` schema — the boundary parses, the handler trusts. */ type ToolInput = { readonly callId: string; readonly args: Args; }; /** * The router-minted failure beside a tool's declared tags: the handler threw * (or rejected) with something that is not a declared `{ _tag }`. Plain data * the model sees as a reason, never a rejection out of the interpret handler. */ type ToolThrown = { readonly _tag: "thrown"; readonly message: string; }; /** * The typed success constructor a handler receives: `ok(value)` with `Ok` * fixed to what the `ok` schema parses, so a value of the wrong shape is * refused where it is written. */ type ToolOk = (value: Ok) => Outcome; /** * The typed failure constructor a handler receives: `fail({ _tag })` with `E` * fixed to the declared tags, so the literal is checked against them where it * is written. (A bare `{ _tag: "x" }` built elsewhere infers `_tag: string` * and cannot be — the parameter type is what keeps it literal.) */ type ToolFail = (error: E) => Outcome; /** * The two constructors a handler is handed, one per channel — `ok` for the * value the `ok` schema parses, `fail` for a declared `{ _tag }`. Both build * the core's `Outcome` record (ADR 0021). */ type ToolConstructors = { readonly ok: ToolOk; readonly fail: ToolFail; }; /** * A tool's handler: the parsed `args`, the plain `ctx` the host handed `run`, * and the typed `{ ok, fail }`, to an outcome over the declared channels — `Ok` * is what the `ok` schema parses, `E` the declared `_tag` union. An undeclared * tag does not compile. `Ctx` is whatever the handler annotates its `ctx` * parameter with; tea does no dependency injection (ADR 0020). */ type ToolHandler = (args: Args, ctx: HandlerCtx, settle: ToolConstructors) => Promise>; /** * What `tool()` returns: the `Cmd.define`d constructor (so `Settled` * / `CmdOf` read it like any def) plus the colocated `interpret` handler, * the bare `args` schema the router parses a call against, and the * `description` a provider adapter declares to the model beside that schema. * `E` is the full failure union the Cmd settles with — the declared tags plus * `thrown`. `Ctx` is the ctx the colocated handler reads — a fact about the * handler, never about the Cmd it builds (ADR 0020). */ type ToolDef = CmdDef, Ok, E> & { readonly description: string; readonly args: StandardSchemaV1; /** * The timeout / retry knob this tool declared, or `null` when it declared * neither. `toolRouter` serves it to the agent as `resilienceOf`. */ readonly resilience: ToolResilience | null; /** * The parts the model reads for an `ok` result, or `null` when the tool * declared no `content` and the model reads the result as data. */ readonly content: ((result: Ok) => readonly ContentPart[]) | null; /** * The colocated handler, as an interpret cell: it returns the tool's * outcome, and the engine mints `_ok` / `_err` from it. */ readonly interpret: (cmd: CmdValue, Ok, E>, ctx: HandlerCtx) => Promise>; /** Phantom — the ctx the handler reads. Never assigned. */ readonly __ctx?: Ctx; }; /** The declaration-erased view the router reads. */ type AnyToolDef = AnyCmdDef & { readonly description: string; readonly args: StandardSchemaV1; readonly resilience: ToolResilience | null; readonly content: ((result: never) => readonly ContentPart[]) | null; readonly interpret: (cmd: never, ctx: never) => Promise; }; /** * Declare one tool the model may call — its name, the schemas for its arguments * and result, the failures it may return and the handler that runs it — and get * back a `Cmd` definition, whose `Ok` is what `ok` parses and whose `E` * is the `err` tag union, that you pass to `toolRouter` or `defineAgent`. * * So a tool's two declared channels ARE the kernel's two typed effect channels * (ADR 0014), spelled in schemas rather than in type parameters: a settled * failure keeps its `_tag` into the conversation, so a reducer switching over * `err`'s tags is exhaustive and an unhandled one is a compile error. * * `name` is the name the model calls it * by; `description` is the model-facing sentence — the one place it lives — a * provider adapter declares to the model beside the schema (Anthropic * `description`, OpenAI `function.description`) so the model can tell when to * call the tool, read off `def.description`, never off the `input` schema; * `input` parses the model's `args`; `ok` parses the handler's value at the * edge; `err` is the `_tag` list the handler may fail with. The handler reads * its services off the plain `ctx` `run` was handed — annotate its `ctx` * parameter and `defineAgent` asks for that ctx at `run`. The handler returns * one of the two constructors it is handed — `ok(value)` or the typed `fail({ _tag })`; a * throw settles `_err` — with the thrown `_tag` when it is a declared * one, else as `{ _tag: "thrown", message }`. * * A `ReservedToolName` does not compile as `name`, and one that reaches here * as a widened `string` throws — the same declaration-bug refusal * `toolRouter` gives a name declared twice. */ declare function tool(name: Name & NotReserved, spec: { readonly description: string; readonly input: StandardSchemaV1; readonly ok: StandardSchemaV1; readonly err: Tags; /** * The budget one call of this tool gets, in ms — the overall cap, measured * from the first attempt and not restarted by a retry. When it elapses the * call settles as a `ToolOutcome` error carrying `_tag: "timeout"` beside * its `reason`, and the loop moves on; the attempt is NOT cancelled (a promise cannot be), so it runs to its * own end and its late settle folds nothing. Omit → no cap. */ readonly timeoutMs?: number; /** * The backoff ladder a failed attempt of this tool climbs — the same * `{ baseMs, factor, capMs, jitter, maxAttempts }` shape the brain call's * `retry` takes. The ladder is folded into the Model and its wait is a timer * Sub, so a process killed between two attempts resumes at the attempt it * was on. A spent budget settles as a `ToolOutcome` error carrying * `_tag: "retry_exhausted"` beside its `reason`, with the attempt count and * the last attempt's reason as the `attempts` / `last` fields. * Omit → the first failure is the outcome. */ readonly retry?: ToolResilience["retry"]; /** * What the model SEES of an `ok` result, as content parts. A screenshot * tool whose result is `{ jpeg }` (base64) declares * `content: (r) => [{ type: "image", mediaType: "image/jpeg", source: { type: "base64", data: r.jpeg } }]`. * The parts ride on the `tool` message beside the outcome, so an adapter * sends them instead of stringifying the result. PURE: it runs on every * render, over the result as the `Store` hands it back, and never on a * failure. Omit → the model reads the outcome as data, as before. */ readonly content?: (result: Ok) => readonly ContentPart[]; }, handler: ToolHandler, Ctx>): ToolDef, Ctx>; /** * A call the router could not hand to a tool: the model named a tool nobody * declared, or its `args` failed the tool's `input` schema. `toolOf` is total — * it never throws inside the reducer — so the refusal rides its own Cmd and * settles `tool_rejected_err`, which the loop folds like any tool failure. */ type ToolRejection = { readonly _tag: "unknown_tool"; readonly name: string; } | { readonly _tag: "malformed_args"; readonly name: string; readonly issues: ReadonlyArray<{ readonly path: string; readonly message: string; }>; }; declare const rejected: CmdDef<"tool_rejected", { readonly callId: string; readonly error: ToolRejection; }, never, { readonly [detail: string]: unknown; readonly _tag: "unknown_tool"; } | { readonly [detail: string]: unknown; readonly _tag: "malformed_args"; }>; /** The Cmd `tool_rejected` builds — the router-owned variant of `ToolCmd`. */ type ToolRejectedCmd = CmdOf; /** The Cmd union a router's `toolOf` produces — `TC` for `createAgent`. */ type ToolCmd = CmdOf | ToolRejectedCmd; /** The ctx one tool's handler reads; `unknown` for a handler that reads none. */ type ToolCtxOf = T extends { readonly __ctx?: infer Ctx; } ? Ctx : unknown; type UnionToIntersection = (U extends unknown ? (u: U) => void : never) extends (u: infer I) => void ? I : never; type ToolCtxBoxed = T extends unknown ? [ToolCtxOf] : never; type KnownToolCtx = B extends [infer Ctx] ? unknown extends Ctx ? never : Ctx : never; /** * The ctx a tool set's handlers read, intersected — what `run` asks the host * for once the tools are wired into a machine. A tool whose handler reads * nothing leaves its siblings' demand intact. */ type ToolsCtx = UnionToIntersection>>; /** The settled Msg union a router's handlers return — folded by `toMachine`. */ type ToolMsg = Settled | Settled; /** * `ToolCmd` as `toMachine` reads it: `never` for `T = never` — the "no * router" reading it defaults to — so the router-owned `tool_rejected` arm * does not leak into a machine that wired no router. */ type WiredToolCmd = [T] extends [never] ? never : ToolCmd; /** `ToolMsg` as `toMachine` / `agentEvents` read it — see `WiredToolCmd`. */ type WiredToolMsg = [T] extends [never] ? never : ToolMsg; /** The union of every tool's `ok` value — `R` for `createAgent`. */ type ToolResult = OkOf; /** * Every failure a router over `T` can settle with — the union `outcomeOf`'s * error arm is typed from. Five sources, and a consumer branching on `_tag` * meets all five: each tool's DECLARED tags plus the `thrown` `tool()` appends * (`ErrOf`), the kernel's `malformed_result` (a handler returned a value its * own `ok` schema rejects), the router's own `unknown_tool` / `malformed_args` * rejections, and the ladder's `timeout` / `retry_exhausted` (#117) — which end * a call from outside the handler and so are nothing a tool can declare. */ type ToolError = ErrOf | MalformedResult | ToolRejection | ToolResilienceError; /** * The error outcome a router over `T` produces: `{ kind: "error", _tag, * …payload, reason }`, discriminable on `_tag` over {@link ToolError}. This is * what `defineAgent`'s `onToolError` hands the consumer. */ type ToolFailureOf = TaggedFailure>; /** One settled tool, read back off a `ToolMsg` by `outcomeOf`. */ type ToolSettlement = { readonly callId: string; readonly outcome: { readonly kind: "ok"; readonly result: R; } | TaggedFailure; }; /** * What `toolRouter()` returns: the derived `toolOf` for `createAgent`'s config, * the interpret table `toMachine({ tools })` merges, the defs it puts on * `Machine.cmds`, and the one reader that turns a settled Msg back into the * conversation's `ToolOutcome`. */ interface ToolRouter { /** Every def the router settles through — hand to `Machine.cmds`. */ readonly defs: readonly AnyCmdDef[]; /** The `toolOf` for `createAgent`: total, pure, parses `args` at the edge. */ readonly toolOf: (call: ToolCall) => ToolCmd; /** One interpret handler per tool plus the `tool_rejected` handler. */ readonly interpret: Interpret, ToolCmd, ToolsCtx>; /** * The timeout / retry knob the called tool declared — `AgentConfigCore`'s * `toolResilienceOf` seam, filled from the `tool()` specs. `null` for a tool * that declared neither field and for a call no tool answers (the rejection * path settles in the reducer and never runs an effect to time out). PURE. */ readonly resilienceOf: (call: ToolCall) => ToolResilience | null; /** * The parts the model reads for one settled call: the called tool's * `content` over an `ok` result. `null` for a failure, for a tool that * declared no `content`, and for a call no tool answers. PURE. */ readonly partsOf: (call: ToolCall, outcome: ToolOutcome) => readonly ContentPart[] | null; /** * Read a settled tool off a Msg: `null` when the Msg is not one of this * router's `_ok` / `_err`. The one place a `{ _tag }` failure is * rendered to the `reason` string the conversation carries — and the tag and * its payload ride beside that rendering, never instead of it (#115). */ readonly outcomeOf: (msg: { readonly _tag: string; }) => ToolSettlement, ToolError> | null; } /** * Fold a set of `tool()`s into one router — pass it the tools, get back the * lookup `createAgent` needs, the handlers `toMachine` merges, and a reader that * turns a settled message back into a plain outcome. * * Two tools with one name is a declaration bug, refused here with * `CmdNameCollisionError` rather than by a silent last-wins map. */ declare function toolRouter(tools: readonly T[]): ToolRouter; /** * Give a router's interpret cells real wall-clock overlap without touching the * kernel — pass the table `toolRouter` built, get back one whose cells launch * their tool and RETURN, so `runInterpret` reaches the next Cmd of the turn * while the first tool is still running. * * This is ADR 0018's option (c), and the whole of it. `runInterpret` stays the * serial loop the ADR ruled it must be: it still awaits one handler before * reaching the next Cmd — the handlers just stop being the thing that takes the * time. Three properties are what make that safe, and each is a line below: * * - **Settles fold in Cmd-EMISSION order, never completion order.** Each cell * chains its dispatch behind the previous cell's, so two tools that overlap * on the clock still settle a-then-b when a's Cmd was emitted first, whichever * finished first. That is invariant 2's serializability, and it is what keeps * a replay of a fanned run identical to the run itself. * - **The settle crosses the SAME edge.** A returned Msg is parsed and stamped * by `run`'s `cmdEdge`; a dispatched one would not be, so the cell settles * through `cmdEdgeOf(ctx)` — the edge `run` hands handlers for exactly this. * One parse, one clock, fanned or not. * - **The work stays counted.** The promise the cell does not return is enlisted * with `detachWorkOf(ctx)`, so `inFlightCmds` and the dispatch tail see it and * `stop()` / `idle()` answer under fan-out what they answer serially. * * The ordering has a price, and it is the honest one: a call whose Cmd was * emitted FIRST holds its siblings' settles until it finishes. They still RUN * in parallel — the turn costs the slowest call, not the sum — but a first call * that never returns leaves the later folds parked behind it, exactly as a * serial run would leave them unstarted. `timeoutMs` on the tool is what bounds * that, fanned or not. * * The per-turn LIMIT is not this function's: the agent's fan-out slice already * launches at most `toolConcurrency` calls per transition, so the table simply * must not block. Nothing here is applied below that knob — `toMachine` wires * the bare cells at the serial default, and a tool that never overlaps is the * exact function `toolRouter` built. */ declare function fanOutInterpret(interpret: Interpret, ToolCmd, ToolsCtx>): Interpret, ToolCmd, ToolsCtx>; /** * Turn a tool failure into the human-readable reason string the conversation * carries — pass the `{ _tag, ...detail }` a tool failed with, get the tag * followed by any remaining detail as JSON. * * The * model reads this next turn, so the data survives the rendering intact. */ declare function toolErrorReason(error: Tagged): string; /** * @demlik/tea/agent — the wired-machine surface. * * The Cmd / Msg vocabulary the agent speaks, the handle interface `createAgent` * returns (`AgentKnob` / `AgentToMachine`), the do↔agent boot port, the * semantic lifecycle event stream + its projector (`agentEvents`), and the two * pure wiring helpers `mergeInterpret` / `liftAgent`. The reducer core (the * `createAgent` factory that implements this surface) lives in `./index`. */ /** The brain-call effect Cmd, inherited from `../llm-call`. */ type AgentLlmRunCmd

= LlmRunCmd

; /** * The Cmd union the agent emits, as a CLOSED discriminated union (precise `TC`, * not the open `Cmd`) so `Interpret, Ctx>` maps each key * precisely and `toMachine` merges the interpret halves with no laundering cast: * * - `AgentLlmRunCmd

` — the brain-call run Cmd (`resilient_run`), folded * by the wired `brainHandlers` handler. * - `MonitoredRunCmd` — the durable checkpoint write the monitored-run * slice emits, present in the union ONLY when * checkpointing is on (`Snap = true`). With * checkpointing off the monitored-run slice never * emits a `snapshot_write` Cmd, so it is config-derived * OUT of the emitted set — the consumer is never asked * to interpret a Cmd that can never fire. * - `TC` — the consumer's per-tool effect, mapped to the * consumer's own tool interpret handler. * * `Snap` defaults to `true` so the verb-internal usage (which forwards whatever * monitored-run emits) and the published type stay a safe superset; the wired * machine `toMachine` returns is parametrized on the overload-fixed `Snap` so its * Cmd set is exact (`MonitoredRunCmd` present only when checkpointing is on). */ type AgentCmd

= AgentLlmRunCmd

| (Snap extends true ? MonitoredRunCmd : never) | (Compact extends true ? AgentCompactRunCmd : never) | TC; /** * The CONFIG-DERIVED snapshot obligation on `toMachine`'s `toolInterpret`. * Resolves on the `Snap` discriminant the snapshotting overload of `createAgent` * fixes (`true` checkpointing-on / `false` off): * * - checkpointing ON → a REQUIRED `snapshot_write` handler * (`Interpret, Ctx>`). A real checkpoint write * MUST be wired — the agent never defaults it to a no-op. * - checkpointing OFF → `{ snapshot_write?: never }`. The handler is FORBIDDEN: * the Cmd is config-derived out of the emitted set, so wiring it would be * dead code. The consumer cannot even mention `snapshot_write`. * * This is the type that kills the `snapshot_write: async () => undefined` * ceremony: the obligation is present in the contract EXACTLY when the Cmd can * fire, never as a silent gap the agent backfills. */ type SnapshotInterpret = Snap extends true ? Interpret, Ctx> : { readonly snapshot_write?: never; }; /** * The `toMachine` signature. It returns a `Wired`: the machine and, beside it, * the merged `interpret` table and the `deadline` runner its one Sub needs — a * machine carries no handlers (#278, #279), so it is run as * `run(wired.machine, { ...wired, ctx })`. Parametrized on the `Snap` + `Compact` discriminants * so the snapshotting / compaction overloads of `createAgent` hand back the right * obligations. The `toolInterpret` requires (ON) or forbids (OFF) the * `snapshot_write` handler via {@link SnapshotInterpret} and the `compact_run` handler * via {@link CompactInterpret}, and the machine's Cmd type is the config-derived * `AgentCmd`. * * `tools` is a `toolRouter`: its handlers are merged in, its settled * `_ok` / `_err` Msgs join the machine's `M` and fold into the * conversation, and its Cmds leave the `toolInterpret` obligation — a consumer * whose `toolOf` is the router's supplies only the snapshot / compaction handlers. * With no router (`T = never`) every type here reads exactly as before. */ type AgentToMachine, R, TC extends Cmd, Snap extends boolean, Compact extends boolean> = (opts?: { readonly tools?: ToolRouter; readonly toolInterpret?: Interpret | WiredToolMsg, Exclude>, Ctx> & SnapshotInterpret | WiredToolMsg, Snap, Ctx> & CompactInterpret | WiredToolMsg, Compact, Ctx>; }) => { readonly machine: Machine, AgentMachineMsg | WiredToolMsg, AgentCmd, DeadlinesSub, Ctx & ToolsCtx>; readonly interpret: Interpret | WiredToolMsg, AgentCmd, Ctx & ToolsCtx>; readonly subscribe: Subscribe | WiredToolMsg, DeadlinesSub, Ctx & ToolsCtx>; }; /** * The agent handle `createAgent` returns — the uniform verb contract every tea * composition exposes, plus the wired `toMachine` and `brainInterpret`, the * brain call's handler for a consumer wiring the verbs by hand. `Snap` flows * ONLY into `toMachine`'s `toolInterpret` obligation * (the snapshot derivation); every verb is snapshot-agnostic. The model * message shape `Msg` does not appear on the handle's surface (it is internal to the * brain call's loader), so it is not a type parameter here — only `createAgent` * carries it, to thread the config's `loadMessages` / `model` ports. */ interface AgentKnob, R, TC extends Cmd, Snap extends boolean, Compact extends boolean> { readonly init: () => AgentState; /** * Start the run `runId`: seed the pipeline and a fresh conversation, zero the * run's usage, clear its output and failure, and fire the first brain call. * The `runId` is the run's identity, so a start for the run the State already * holds, in any phase, is a repeat: it returns that State itself and no * commands. That is what makes a retried or concurrent start request safe. * Only a State with no run, or a different `runId`, starts a run. */ readonly start: AgentVerb1; readonly turn: AgentVerb1; readonly toolOk: AgentVerb1; /** * A bare `reason` string still works and settles an untagged failure — the * hand-wired shape this verb has always had. Hand it a whole `ToolFailure` * instead to keep the `{ _tag, …payload }` beside that reason, which is what * `onToolError` and any host code discriminating on `_tag` then read (#115). */ readonly toolErr: AgentVerb1; readonly succeed: AgentVerb1, at: number ]>; readonly fail: AgentVerb1, at: number ]>; readonly compactOk: AgentVerb1; readonly compactErr: AgentVerb1; readonly onTimer: AgentVerb1; readonly boot: AgentVerb1; readonly isSettled: (s: AgentState) => boolean; readonly currentStage: (s: AgentState) => Stage | undefined; readonly brainCall: (s: AgentState) => LlmCall

; readonly subs: (s: AgentState) => readonly DeadlineSub[]; readonly toMachine: AgentToMachine; /** * The brain call's `resilient_run` handler — the one `toMachine` wires. Its * Cmd is `Cmd.define`d, so it returns an outcome and the engine mints the * `resilient_run_ok` / `resilient_run_err` Msg that `succeed` / `fail` fold * (ADR 0021). List `AgentKnob`'s brain Cmd def in `cmds` when you hand-wire. */ readonly brainInterpret: () => Interpret | AgentLlmErrMsg

, AgentLlmRunCmd

, unknown>; /** The brain call's `Cmd.define`d run Cmd def — list it in `cmds` when you hand-wire. */ readonly brain: RunCmdDef, LlmOk>; } /** A verb taking the state + `Args`, returning the agent's `[State, Cmd[]]` tuple. */ type AgentVerb1, R, TC extends Cmd, Args extends readonly unknown[]> = (s: AgentState, ...args: Args) => readonly [AgentState, readonly AgentCmd[]]; /** The brain-call SUCCESS settle Msg, inherited from `../llm-call`. */ type AgentLlmOkMsg

> = LlmSucceedMsg; /** * The brain-call FAILURE settle Msg, inherited from `../llm-call` — the engine * mints it from the brain handler's outcome and it drives the agent's `fail` verb, which backs off via the retry ladder rather than * ending the run. */ type AgentLlmErrMsg

= LlmFailMsg

; /** * The timer Msg (retry + safety deadline) — `DeadlineExceeded`, the shared * shape of both composed wrappers' timer Msgs (`LlmTimerMsg` and `MonitoredRunTimerMsg` * are both `DeadlineExceeded`). One Msg variant covers both timers; `onTimer` * disambiguates by deadline id. This is also the machine Msg the * `subscribeDeadline` runner dispatches directly (no wrapping), matching the * sibling gold standard. */ type AgentTimerMsg = LlmTimerMsg; /** The Msg `do/host`'s `autoBoot` fires to re-enter the agent's `boot` verb on rehydrate. */ type AgentBootMsg = { readonly _tag: typeof MsgType.AgentBoot; readonly at: number; }; /** * The do↔agent boot port: construct the `agent_boot` Msg `autoBoot` dispatches * on a resumable rehydrate. The agent owns this constructor so the boot Msg * shape lives in ONE place — the host fires it through here, never as a raw * `{ _tag: "agent_boot" }` literal. */ declare function agentBootMsg(at: number): AgentBootMsg; /** * The Msg an aborted `AbortSignal` fires to settle the run `cancelled`. Owned * here beside the boot Msg for the same reason: the cancel seam lives on the * drive (`driveToDone`'s `cancel`, the lid's `signal`), which is a different * module from the reducer that folds it, so the shape gets ONE home and a * constructor rather than a literal duplicated across the seam. */ type AgentCancelMsg = { readonly _tag: typeof MsgType.AgentCancel; readonly at: number; }; /** Construct the `agent_cancel` Msg an abort dispatches. `at` stamps the outcome. */ declare function agentCancelMsg(at: number): AgentCancelMsg; /** * The agent machine's Msg union — one variant per reducer entry point. A * consumer using `toMachine` dispatches `agent_start` to begin and `agent_tool_ok` * / `agent_tool_err` to route settled tools back; the brain-call settle Msgs * (`resilient_run_ok` / `resilient_run_err`) are minted by the engine from the * outcome the FIXED `brainHandlers` returns (ADR 0021), driving `succeed` / * `fail`. Time enters via `at` on every variant — the * reducer never reads the clock. * * There is deliberately NO `agent_turn` variant here. The wired loop folds a * model turn INSIDE `succeed` from the minted `resilient_run_ok` — a single * settle Msg advances both the retry slice and the conversation (the L3 fix). * Exposing `agent_turn` as a dispatchable Msg re-opened the stuck-`running` bug: * a hand-fed turn folds the conversation without ever settling `resilient_run_ok`, * so `succeed` never runs and the resilient slice stays `running`. The * `turn` verb remains on the handle for the consumer that wires the verbs by hand * (manual wiring), but it is not part of the one wired machine's Msg surface. */ type AgentMachineMsg

, R> = { readonly _tag: typeof MsgType.AgentStart; readonly runId: string; readonly at: number; } | { readonly _tag: typeof MsgType.AgentToolOk; readonly callId: string; readonly result: R; readonly at: number; } | { readonly _tag: typeof MsgType.AgentToolErr; readonly callId: string; readonly reason: string; readonly at: number; } | AgentLlmOkMsg | AgentLlmErrMsg

| AgentCompactOkMsg | AgentCompactErrMsg | AgentTimerMsg | AgentBootMsg | AgentCancelMsg; /** * The agent's PUBLIC lifecycle events — the semantic stream a consumer * subscribes to via `runtime.on(type, …)`. This is the seam that * DECOUPLES observability/SSE code from the agent's PRIVATE retry/loop Msg * vocabulary: where the old code switched on `resilient_ok` / `agent_tool_ok` * (the inherited resilient-call / tool-fan-out plumbing) off the raw `observe` * firehose, a consumer now folds these named events. The private Msg names live * ONLY inside `agentEvents` (the projector) — they appear nowhere in this union * or any exported type, so a UI built on `TurnSettled` does not break the day * the retry plumbing is renamed. * * Every event carries the run's `runId` and the `at` of the transition that * produced it. `runId` is the one the host passed to `agent_start` and it lives * on the durable Model, so a run killed and resumed from its `Store` reports * the same id on both sides of the kill (#331). * * - `BrainStarted` — a brain call was issued for conversation turn `turn`, * with the request's `purpose`, `model` and `payload`. Once per turn: a * retry of the same turn is not a new start, a cold-wake `boot` that * re-fires it is. * - `TurnSettled` — a brain turn settled (the model produced an `AgentTurn`). * Carries the parsed `turn`, and — when the provider reported one — that * call's `usage` beside it (#332), so a progress surface reads the context * size without digging into the turn. * - `ToolStarted` — a tool call was issued: launched with its batch, a * queued call backfilling a freed slot, or re-fired by `boot`. A laddered * retry is not a new start. * - `ToolSettled` — a tool call settled OK, with the `callId` and `result`. * - `ToolFailed` — a tool call ended on the failure the model will read: its * own error, a spent retry budget, or its timeout. `failure` is the * `{ kind, reason, _tag? }` the conversation keeps. * - `RunDone` — the run ended, once. `status` says how: `done` with the * terminal turn, `failed` with the unified failure, or `cancelled`. */ type AgentEvent = (AgentEventHead & { readonly _tag: "BrainStarted"; readonly turn: number; readonly purpose: string; readonly model: string | null; readonly payload: unknown; }) | (AgentEventHead & { readonly _tag: "TurnSettled"; readonly turn: AgentTurn; /** Feedback issued for this empty turn, when the caller refused its finish. */ readonly nudge?: string; /** The usage the provider reported for this turn. Absent → none reported. */ readonly usage?: TurnUsage; }) | (AgentEventHead & { readonly _tag: "ToolStarted"; readonly callId: string; readonly name: string; readonly args: Readonly>; }) | (AgentEventHead & { readonly _tag: "ToolSettled"; readonly callId: string; readonly result: R; }) | (AgentEventHead & { readonly _tag: "ToolFailed"; readonly callId: string; readonly name: string; readonly failure: ToolFailure; }) | (AgentEventHead & { readonly _tag: "RunDone"; readonly status: AgentEndedStatus; }); /** The two fields every {@link AgentEvent} carries. */ interface AgentEventHead { /** The run this event belongs to — stable across a kill and resume. */ readonly runId: string; /** When the transition that produced it happened. */ readonly at: number; } /** * Every {@link AgentEvent} `_tag`. A subscriber that wants the whole stream * off `runtime.on` subscribes once per entry. `satisfies` proves each entry is * a real type; a type test proves no real type is missing. */ declare const AGENT_EVENT_TYPES: readonly ["BrainStarted", "TurnSettled", "ToolStarted", "ToolSettled", "ToolFailed", "RunDone"]; /** * Project one APPLIED agent transition `(msg, state)` to its semantic * {@link AgentEvent}s — the `events` projector a consumer passes to * `run(machine, { events: agentEvents() })` to light up `runtime.on(...)`. * * Two sources, in this order: * * 1. The Msg. `resilient_run_ok` → `TurnSettled`, `agent_tool_ok` (or a * router's `_ok`) → `ToolSettled`. This is the ONE place the * agent's PRIVATE Msg names are read; the switch is total over the Msg * union, so a private name never escapes into `AgentEvent`. * 2. The transition's lifecycle outbox, `state.lifecycle` — what the reducer * noted as it started a brain call or a tool, failed a tool, or ended the * run. These cannot be read off `(msg, state)`: a brain call issued after * a batch drains, a queued tool backfilling a slot, a timeout the ladder * settled and the transition that ended the run all leave a state that * looks like the one before (#331). * * So a turn that asks for tools reads `TurnSettled`, then one `ToolStarted` * per launched call; the last tool of a batch reads `ToolSettled` (or * `ToolFailed`), then the next `BrainStarted`; and the final turn reads * `TurnSettled`, then `RunDone`. * * A `ToolSettled` is gated on `state.refusedCalls` (#145): a call whose public * outcome was already a failure — the ladder's `timeout` / `retry_exhausted`, * or the tool's own error — never emits a success here, however late its * abandoned attempt resolves. Both settle arms read the same list, so a * router-wired agent and a fan-out-wired one are silent on the same calls. * A cancelled run's Msg-shaped events are closed the same way — a tool that * was in flight when the abort landed pushes nothing — while the cancel's own * `RunDone` still comes through, because it is noted, not Msg-shaped. * * A run cancelled before it ever started has no `runId`, and projects nothing. * * A machine wired with `toMachine({ tools })` settles tools through the * router's `_ok` Msgs instead of `agent_tool_ok`; pass the same router * here so those settles project to `ToolSettled` too. * * Each outbox is projected once per projector (#355). A host that wires the * verbs by hand and folds a Msg of its own leaves `state.lifecycle` as the * previous agent transition left it, and that transition's notes are not * projected a second time. * * Reads only the passed `(msg, state)` and the set of outboxes it has already * projected; no clock, no RNG, no throw. * * @typeParam P Brain-call purposes. * @typeParam O Per-purpose outputs (bound to `AgentTurn`, the agentic shape). * @typeParam R Tool result type. * @typeParam Stage Pipeline stage type. * @typeParam T The router's tool defs, when one is wired. */ declare function agentEvents, R, T extends AnyToolDef = never>(opts?: { readonly tools?: ToolRouter; }): (msg: AgentMachineMsg | WiredToolMsg, state: AgentState) => readonly AgentEvent[]; /** * Join two `Interpret` dictionaries over DISJOINT Cmd subsets `A` and `B` (over * the same Msg union `M` and Ctx) into the full `Interpret`. The * agent uses it to merge the consumer's per-tool / snapshot interpret (`A`) with * the agent-owned brain-call handler (`B = AgentLlmRunCmd`) into the wired * machine's single interpret table. * * The runtime result is exactly the spread of the two key-disjoint records. The * single `as` is a SOUND mapped-type identity, not a laundering cast: `Interpret` * is a homomorphic mapped type keyed by `Cmd["_tag"]`, so * `Interpret & Interpret` IS `Interpret` * (`(A | B)["_tag"] = A["_tag"] | B["_tag"]`). TypeScript does not reduce that * intersection of two GENERIC mapped types on its own, so the equality is * asserted ONCE here — preserving `M` and `Ctx` exactly — rather than smuggled * through `as unknown as Interpret<...>` at every wiring site. Pure. */ declare function mergeInterpret(a: Interpret | undefined, b: Interpret): Interpret; /** * Lift an agent result `[slice, cmds]` into a host `[State, cmds]` where the slice * lives at `state.agent`. Convenience for a host that nests the agent slice * under a named field; the single-slice host uses the verbs' tuple directly. * PURE — a thin record rebuild, no clock / RNG. */ declare function liftAgent; }, Stage, P extends string, O extends Record, R, C extends Cmd>(state: S, [slice, cmds]: readonly [AgentState, readonly C[]]): readonly [S, readonly C[]]; export { type FilePart as $, type AgentEvent as A, type AgentCompactionConfig as B, type ContentPart as C, type AgentConfig as D, type AgentEventHead as E, type AgentFailure as F, type AgentLifecycleNote as G, type AgentLlmErrMsg as H, type AgentLlmOkMsg as I, type AgentLlmRunCmd as J, type AgentSnapshotConfig as K, type AgentStatus as L, type MessageContent as M, type NotReserved as N, type AgentTimerMsg as O, type PlainModel as P, type AgentToMachine as Q, type Awaiting as R, type StreamingModel as S, type ToolCall as T, COMPACTION_PURPOSE as U, type CompactInterpret as V, type WiredToolMsg as W, type CompactionOutputs as X, type CompactionPurpose as Y, type CompactionSummary as Z, FILE_OMITTED as _, type ToolOutcome as a, toolErrorReason as a$, IMAGE_OMITTED as a0, type ImagePart as a1, type Llm as a2, type LlmCall as a3, type LlmErr as a4, type LlmFailMsg as a5, type LlmOk as a6, type LlmRunCmd as a7, type LlmSucceedMsg as a8, type MediaReference as a9, type ToolResilience as aA, type ToolResilienceError as aB, type ToolRetryExhausted as aC, type ToolRouter as aD, type ToolSettlement as aE, type ToolTimedOut as aF, type TurnUsage as aG, type WiredToolCmd as aH, agentBootMsg as aI, agentCancelMsg as aJ, agentEvents as aK, agentTurnSchema as aL, compactionSummarySchema as aM, contentParts as aN, fanOutInterpret as aO, isAgentTurn as aP, isCompactionSummary as aQ, isReservedToolName as aR, isStreamingModel as aS, isTurnUsage as aT, liftAgent as aU, mergeInterpret as aV, omitMedia as aW, plainModel as aX, resolveMediaParts as aY, status as aZ, tool as a_, type MediaSource as aa, type MessageLoader as ab, type ModelFactory as ac, type ModelPort as ad, type ModelStream as ae, PLAIN_MODEL_MISROUTE_REASON as af, type ReservedToolName as ag, type ResolvedContentPart as ah, type ResolvedMediaSource as ai, type Schema as aj, type SnapshotInterpret as ak, TOOL_RETRY_EXHAUSTED_TAG as al, TOOL_TIMEOUT_TAG as am, type TaggedFailure as an, type TextPart as ao, type ToolConstructors as ap, type ToolError as aq, type ToolFail as ar, type ToolFailure as as, type ToolHandler as at, type ToolInput as au, type ToolMsg as av, type ToolOk as aw, type ToolRecord as ax, type ToolRejectedCmd as ay, type ToolRejection as az, type Conversation as b, toolRouter as b0, type AnyToolDef as c, type ToolsCtx as d, type AgentState as e, type AgentTurn as f, type ToolResult as g, type TurnChunk as h, type AgentMachineMsg as i, type AgentCmd as j, type ToolCmd as k, type ToolFailureOf as l, type AgentTerminalFailure as m, type ToolDef as n, type ToolThrown as o, type Nudge as p, type AgentEndedStatus as q, type AgentConfigCore as r, type CompactionPolicy as s, type AgentKnob as t, AGENT_EVENT_TYPES as u, type AgentBootMsg as v, type AgentCancelMsg as w, type AgentCompactErrMsg as x, type AgentCompactOkMsg as y, type AgentCompactRunCmd as z };