import { M as Machine, I as Interpret, S as Subscribe, H as HandlerCtx, b as Cmd } from '../core-sEWVgnpI.js'; import { b as DeadlinesSub } from '../index-CCs-QGGu.js'; export { a as DeadlineSub, m as deadlineSub, o as deadlinesSub, s as subscribeDeadline } from '../index-CCs-QGGu.js'; import { M as MessageContent, T as ToolCall, a as ToolOutcome, C as ContentPart, b as Conversation, c as AnyToolDef, d as ToolsCtx, e as AgentState, f as AgentTurn, g as ToolResult, A as AgentEvent, h as TurnChunk, i as AgentMachineMsg, W as WiredToolMsg, j as AgentCmd, k as ToolCmd, P as PlainModel, S as StreamingModel, l as ToolFailureOf, m as AgentTerminalFailure, N as NotReserved, n as ToolDef, o as ToolThrown, p as Nudge, q as AgentEndedStatus, r as AgentConfigCore, s as CompactionPolicy, t as AgentKnob } from '../machine-rN7E-yh-.js'; export { u as AGENT_EVENT_TYPES, v as AgentBootMsg, w as AgentCancelMsg, x as AgentCompactErrMsg, y as AgentCompactOkMsg, z as AgentCompactRunCmd, B as AgentCompactionConfig, D as AgentConfig, E as AgentEventHead, F as AgentFailure, G as AgentLifecycleNote, H as AgentLlmErrMsg, I as AgentLlmOkMsg, J as AgentLlmRunCmd, K as AgentSnapshotConfig, L as AgentStatus, O as AgentTimerMsg, Q as AgentToMachine, R as Awaiting, U as COMPACTION_PURPOSE, V as CompactInterpret, X as CompactionOutputs, Y as CompactionPurpose, Z as CompactionSummary, _ as FILE_OMITTED, $ as FilePart, a0 as IMAGE_OMITTED, a1 as ImagePart, a2 as Llm, a3 as LlmCall, a4 as LlmErr, a5 as LlmFailMsg, a6 as LlmOk, a7 as LlmRunCmd, a8 as LlmSucceedMsg, a9 as MediaReference, aa as MediaSource, ab as MessageLoader, ac as ModelFactory, ad as ModelPort, ae as ModelStream, af as PLAIN_MODEL_MISROUTE_REASON, ag as ReservedToolName, ah as ResolvedContentPart, ai as ResolvedMediaSource, aj as Schema, ak as SnapshotInterpret, al as TOOL_RETRY_EXHAUSTED_TAG, am as TOOL_TIMEOUT_TAG, an as TaggedFailure, ao as TextPart, ap as ToolConstructors, aq as ToolError, ar as ToolFail, as as ToolFailure, at as ToolHandler, au as ToolInput, av as ToolMsg, aw as ToolOk, ax as ToolRecord, ay as ToolRejectedCmd, az as ToolRejection, aA as ToolResilience, aB as ToolResilienceError, aC as ToolRetryExhausted, aD as ToolRouter, aE as ToolSettlement, aF as ToolTimedOut, aG as TurnUsage, aH as WiredToolCmd, aI as agentBootMsg, aJ as agentCancelMsg, aK as agentEvents, aL as agentTurnSchema, aM as compactionSummarySchema, aN as contentParts, aO as fanOutInterpret, aP as isAgentTurn, aQ as isCompactionSummary, aR as isReservedToolName, aS as isStreamingModel, aT as isTurnUsage, aU as liftAgent, aV as mergeInterpret, aW as omitMedia, aX as plainModel, aY as resolveMediaParts, aZ as status, a_ as tool, a$ as toolErrorReason, b0 as toolRouter } from '../machine-rN7E-yh-.js'; import { StandardSchemaV1 } from '@standard-schema/spec'; import { C as CtxArg, a as StoreAndOnError, O as OnError, U as UnfencedStore, S as Store } from '../runtime-types-f231H8Gq.js'; import { E as EndedRun } from '../index-tFnc-ElD.js'; export { M as MonitoredRunCmd, R as RunFailure } from '../index-tFnc-ElD.js'; import { RetryPolicy } from '../retry-backoff/index.js'; import '../types-CtM4tWPp.js'; import '../index-C1BK3MNo.js'; import '../protocol-CqdURF0g.js'; import '../index-D5RP0MjN.js'; import '../index-DmoyvP-O.js'; import '../index-DUdoElz8.js'; /** * @demlik/tea/agent — `defineAgent`, the convenience layer over `createAgent`. * * `defineAgent({ model, tools, instructions })` is the three-line entry: it * defaults the single-stage wiring (`stages`, `turnOf`, `schemas`), derives the * tool handlers from `toolRouter`, renders the prompt off the Model, and absorbs * the drive loop through `driveToDone`. It hides wiring, never state (ADR * 0015): the Model it runs is the same `AgentState` a hand-wired `createAgent` * produces, under the same keys, and `machine(input)` is the way down to the * raw kernel `run`. Each hidden thing is a named helper below. */ /** * One message a `defineAgent` `model` receives. Plain data the adapter renders into * its provider's shape: the head is the `instructions` (when set) and the * run's `input`; then, per model turn, the `assistant` turn followed by the * `tool` outcomes that turn asked for. A tool outcome rides as data — the * adapter decides how a failure reads to its model. An `assistant` message * carries the turn's opaque `provider` slot exactly as the adapter returned it * (see `AgentTurn`), present only when the stored turn has one. * * A `user` message's content is a string or a list of {@link ContentPart}s — * `contentParts` reads either as parts. A `tool` message carries `parts` beside * its outcome when the tool declared `content` and settled `ok`: those parts * are what the model should see (a screenshot, say), so an adapter sends them * in place of the stringified result. No `parts` → the outcome is the payload. */ type AgentMessage = { readonly role: "system"; readonly content: string; } | { readonly role: "user"; readonly content: MessageContent; } | { readonly role: "assistant"; readonly content: string; readonly toolCalls: readonly ToolCall[]; readonly provider?: unknown; } | { readonly role: "tool"; readonly callId: string; readonly name: string; readonly outcome: ToolOutcome; readonly parts?: readonly ContentPart[]; }; /** * How `renderPrompt` reads the parts a settled call shows the model — a * `ToolRouter`'s `partsOf`. `null` → the message carries no `parts`. */ type ToolPartsOf = (call: ToolCall, outcome: ToolOutcome) => readonly ContentPart[] | null; /** * The brain-call payload `defineAgent` builds from the durable state — everything * `messagesOf` renders, so the prompt is a pure function of the Model and the * resilient slice carries exactly what was sent. */ interface AgentPrompt { readonly instructions: string | null; readonly input: string | null; readonly conversation: Conversation; } /** The one purpose a `defineAgent` agent runs. */ type LidPurpose = "act"; type LidOutputs = { readonly [K in LidPurpose]: AgentTurn; }; /** The Model a defined agent runs — a hand-wired `createAgent`'s, key for key. */ type DefinedAgentState = AgentState>; /** * The Model `run` RESOLVES with — {@link DefinedAgentState} whose `run` slice is * narrowed to the ended phases ({@link EndedRun}). * * `run`'s terminal predicate is `done || cancelled` and its `failed` one rejects, * so the never-started `idle` arm is unreachable on the resolved value. Typing * the promise as the whole Model published that unreachable arm anyway, and * `idle` carries no `runId` — so `(await agent.run(input)).run.runId`, a field * every resolved run has, did not typecheck (#155). The narrow is on what `run` * can RESOLVE; the `idle` arm is untouched and still carries no `runId`. * * `DefinedAgentState` itself stays wide, because it is the DURABLE Model: an * `init` slice is `idle`, and a `Store>` has to hold one. */ type DefinedAgentResolvedState = Omit, "run"> & { readonly run: EndedRun; }; /** The ctx the tools' handlers read, intersected — what `run` asks for. */ type DefinedAgentCtx = ToolsCtx; /** The Msg union a defined agent's machine folds. */ type DefinedAgentMsg = AgentMachineMsg> | WiredToolMsg; /** * The Cmd union a defined agent's machine emits — one interpret cell per member. * * Snapshotting is fixed OFF (the lid checkpoints through the run's `store`, not * the monitored-run cadence), so `snapshot_write` is out of the union. * Compaction is fixed ON, which is the SUPERSET of the two machines * `defineAgent` builds: with the knob set the `compact_run` cell is the one the * lid wires, and without it the reducer provably emits no such Cmd, so the * machine carries no cell for it and the union simply has a member nothing * reaches. Naming the superset is what lets one type describe both arms — and * it is why `with` may wrap `compact_run` on a compacting agent and gets * `overlaid`'s "this machine has none of that cell" throw on one without. */ type DefinedAgentCmd = AgentCmd, false, true>; /** * The interpret table of the machine `defineAgent` wired: one cell per * {@link DefinedAgentCmd}, keyed by its `_tag` — a tool's own Cmd type, the * router's `tool_rejected`, and the agent-owned brain call. */ type DefinedAgentInterpret = Interpret, DefinedAgentCmd, DefinedAgentCtx>; /** The wired machine `defineAgent` builds per `input`. */ type DefinedAgentMachine = Machine, DefinedAgentMsg, DefinedAgentCmd, DeadlinesSub, DefinedAgentCtx>; /** * The machine `defineAgent` builds per `input` beside the handlers it runs * under — the interpret table and the `deadline` runner (a machine carries * none — #278, #279). It is a `Wired`; feed it to the raw `run`: * `run(wired.machine, { ...wired, ctx })`. */ type DefinedAgentWired = { readonly machine: DefinedAgentMachine; readonly interpret: DefinedAgentInterpret; readonly subscribe: Subscribe, DeadlinesSub, DefinedAgentCtx>; }; /** * The brain a defined agent runs, in either of its two shapes: * * - `async (messages) => turn` — the plain port, and the common path. * - `async (messages, { onChunk }) => turn` — the same call, plus a side * channel it may write token deltas to while the turn is in flight. * * `defineAgent` takes one field for both and tells them apart by arity * (`isStreamingModel`), so there is no config flag saying which you passed and * no way for that flag to disagree with the function. Whichever shape you * write, the run's Model is the same: the turn it RESOLVES is what the reducer * folds, and the deltas end at the `onChunk` run option (see * {@link DefinedAgentRunOptions}). * * Both members are unions of one signature so a model written inline still gets * its `messages` parameter typed from the config field. */ type DefinedAgentModel = PlainModel | StreamingModel; /** * What `defineAgent` takes: the model, the tools and the instructions, plus the * four optional guards that stop a run — `maxTurns`, `deadlineMs`, * `maxElapsedMs` and `stopWhen` — plus `retry`, the brain call's backoff * ladder, and `continueWhen`, the caller's rule for refusing an early finish. * Omit every guard and the run is unbounded: * it ends only when the model stops asking for tools. * * Two more knobs bound what a run COSTS rather than whether it ends: * `compaction`, which stops the transcript growing, and `toolConcurrency`, * which says how many of a turn's tool calls go out at once. */ interface DefineAgentConfig { /** The brain — either {@link DefinedAgentModel} shape. */ readonly model: DefinedAgentModel; /** The `tool()`s the model may call. */ readonly tools: readonly T[]; /** * The system prompt — stored on the Model at `init` (ADR 0004) and never * re-read, so a resumed run keeps the prompt it started with even across a * redeploy that changed this string; to replace a bad prompt already in * flight, end that run and start a new one rather than resuming it. */ readonly instructions: string; /** * Stops a run that keeps going: the maximum number of model round-trips it * may take. Once the completed-turn count reaches it the run fails rather * than calling the model again. Omit → no limit on turns. * * The count is COMPLETED model round-trips. A compaction pass is not one, and * tool calls are not counted at all: a turn that asks for six tools is one * turn. * * The failure is `{ reason: "turn_limit", at }` on the Model's own `failure` * field. `run` rejects with a `DriveFailedError` whose `.state` is that final * Model. */ readonly maxTurns?: number; /** * Stops a run that stops progressing: milliseconds the run may sit without * advancing before it fails. The budget is a no-progress watchdog, not a * total wall-clock cap — it restarts each time the run moves. Omit → no * watchdog. * * The failure is `{ reason: "deadline", at }` on the Model's `run.failure`, * the monitored-run slice, and not on the agent's own `failure` field where * `turn_limit` and `elapsed_limit` land. `at` is when the watchdog fired. A * tool or model call already out runs to its own end first, so `run` can * settle later than `at`. */ readonly deadlineMs?: number; /** * Stops a run that keeps going, by the clock: total milliseconds from the * run's start it may take before it fails. This is the total wall-clock cap * `deadlineMs` is not — the budget never restarts, so a run that keeps * progressing is bounded by it where `deadlineMs` would let it run forever, * and it counts elapsed time where `maxTurns` counts round-trips. It is read * at the turn boundary, so like both of those it stops the run rather than * cancelling the work already in flight. Omit → no wall-clock cap. * * Read at the turn boundary means the run ends at the first boundary past * the budget, not at the millisecond it comes due: a run 10ms into a 400ms * tool call under a 150ms budget fails when that tool settles. The failure * is `{ reason: "elapsed_limit", at }` on the Model's own `failure` field, * beside `turn_limit`. * * The run's start time is on the durable Model, so a run killed and resumed * continues the ORIGINAL budget — the time it spent dead counts against it. * * The same name on a `DurationRetryPolicy` (`retry`, and a tool's own) is the * same idea one altitude down: that one bounds how long ONE call's retry * ladder may keep climbing, this one how long the whole run may take. */ readonly maxElapsedMs?: number; /** * Stops a run on a condition only you can see: a predicate consulted at the * turn boundary, after the other three guards have passed, over the run's * durable Model. Answer `true` and the run ends there — settled `cancelled`, * the same terminal an aborted `signal` reaches, with the transcript intact * and no further model call made. Where `maxTurns` and `maxElapsedMs` bound * a quantity the agent counts for you and `deadlineMs` watches for a stall, * this bounds whatever you name — a token budget over `state.usage` (the * run's provider-reported total), an external flag, a condition on the turns * so far. Omit → no predicate. * * A stop you asked for is not a failure, so `run` RESOLVES with the final * Model where the other three guards make it reject, and `status(state)` * answers `{ kind: "cancelled", at }`. * * It must be PURE: the reducer calls it, so a replay hands it the same state * and must get the same answer. And it is config rather than Model — a * resumed run consults the predicate the config passed to THIS boot, exactly * as it uses the `maxTurns` passed to this boot. */ readonly stopWhen?: (state: DefinedAgentState) => 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: DefinedAgentState) => string | null; /** * The backoff ladder a FAILED BRAIN CALL climbs — the same `RetryPolicy` * shape `AgentConfigCore.retry` takes, threaded straight to it, so the ladder * runs in the resilient slice that already exists and lives on the Model: * each failure is recorded there and the next attempt is armed as a timer * Sub, which is what makes the wait durable and the attempt count survive a * reload. * * The per-tool knob grows no lid option because a `tool()` is a spec object * that declares its own policy (`ToolResilience.retry`). A * `defineAgent` `model` is a bare function with no spec object, so the lid is * the only declaration site a brain-call policy has. * * Omit → NO backoff, exactly as before: one throw from `model` ends the run * after a single attempt. Nothing is defaulted on your behalf — a silent * default would change the failure timing of every existing caller. */ readonly retry?: RetryPolicy; /** * Observe a tool call that failed, typed against THIS agent's tools: the * outcome is `{ kind: "error", _tag, …payload, reason }` over * `ToolError`'s union — declared tags, `thrown`, `malformed_result`, * `unknown_tool`, `malformed_args` — so a `switch` on `_tag` is exhaustive and an * unhandled failure mode is a compile error rather than a silent turn (#115). * The model still reads `reason` next turn either way — this is the host's * channel beside it, never instead of it. * * Called ONCE per failed call, at the interpret boundary: after the handler * settled, before the failure is folded into the conversation. It is awaited, * so an async hook holds the settle until it resolves — keep it short, and put * anything slow on your own queue. * * A resume calls it for the calls THIS process runs and no others: an outcome * a previous process already folded is in the Model the Store handed back and * is never re-interpreted, so a durable run does not re-fire the hook over its * history. * * The hook is CONTAINED, exactly as `onEvent` is: a throw (or a rejected * promise) is warned about and the run goes on, so `run`'s contract does not * depend on the hook's. * * Omit → the router is wired unwrapped and nothing observes failures. */ readonly onToolError?: (outcome: ToolFailureOf, ctx: ToolErrorContext) => void | Promise; /** * Bounds a run that keeps going without ever failing: the transcript budget, * past which the OLDEST turns are folded into one model-written summary * before the next brain call, so a long run's prompt stops growing instead of * climbing until the provider rejects it. * * The knob is a THRESHOLD, not a policy function — see * {@link DefineAgentCompaction}. `compaction` is what a run tolerates, and the * summarize round-trip that enforces it is wiring, so the lid takes the * former and supplies the latter from the `model` it already has. * * `afterTurns: 20` folds once the conversation holds twenty turns. * `afterContextTokens: 8_000` folds once the last brain turn's reported * `inputTokens + outputTokens` reaches eight thousand; the number is yours, * because tea knows no model's window size. `afterInputTokens` folds when * provider-reported input (cached tokens included) strictly exceeds its limit. * `afterImageBytes` folds above its held payload byte limit; `afterImageCount` * folds at its held image count. Each works alone; configured triggers use OR. * `keepTurns` is how many of the newest turns survive the fold intact. * It is not a guard: nothing fails, and the run goes on. * * Omit → NO compaction, exactly as before: the transcript grows for as long * as the model keeps asking for tools. Nothing is defaulted on your behalf — * a silent budget would change the prompt every existing caller sends. */ readonly compaction?: DefineAgentCompaction; /** * Retain images from the newest tool results in a stepwise window. Both * numbers must be positive integers, with `floor < ceiling`. * With ceiling 8 and floor 4, 1..13 image-bearing results show * 1,2,3,4,5,6,7,4,5,6,7,4,5 results' images. Between drops the * existing prompt prefix stays stable. Text and files always survive. * Compaction image thresholds count only these visible image parts. * Omit to render and count every projected image. */ readonly media?: { readonly retain: { readonly ceiling: number; readonly floor: number; }; }; /** * 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, each waiting for the last * to settle; raise it and up to that many are launched together, so they are * all in flight in the fan-out ledger rather than queued behind each other. * A turn asking for more calls than this runs them in waves. * * Launched together means overlapping on the clock: a turn of two slow tools * costs the slower of them, not their sum. The overlap lives inside the tool * Cmds' own handlers and NOT in the kernel — `runInterpret` still interprets * a transition's Cmds one after another and never interleaves two handlers, * which is ADR 0018's ruling and the reason a replay is unaffected. Settle * Msgs fold in Cmd-EMISSION order whichever call finishes first, so raising * the knob changes the turn's latency and nothing about its Model. * * Omit (or `1`) → serial dispatch, exactly as before. */ readonly toolConcurrency?: number; } /** * The lid's compaction budget: when a transcript is too long, and how much of * it survives the fold. Turn count, last-turn context or input tokens, and * held image bytes or count are independent triggers: whichever is reached * first requests one fold. At least one trigger is required. * * All triggers read durable facts through pure projections, so replay re-decides * identically. Token readings come from the provider, with no clock, token * estimate or model window registry (ADR 0004). * * This is deliberately a threshold rather than the core's `planCompaction` * function: a policy function is a second place a lid agent would have to learn * the conversation shape, and the lid hides wiring, never state (ADR 0015). A * run that needs its own heuristic descends to `createAgent`, whose * `CompactionPolicy` this is built from. */ type DefineAgentCompaction = { [K in CompactionTriggerTag]: CompactionTriggers & Required>; }[CompactionTriggerTag]; type CompactionTriggerTag = Exclude; /** Independent thresholds and the retained tail of {@link DefineAgentCompaction}. */ interface CompactionTriggers { /** * Fold once the conversation holds at least this many turns, counted BEFORE * the brain call about to fire. Must be at least `1`. */ readonly afterTurns?: number; /** * Fold once the latest context size — `inputTokens + outputTokens` the * provider reported for the most recent brain turn — reaches this many * tokens, checked BEFORE the brain call about to fire (#332). The number is * yours: tea keeps no per-model window registry. * * A turn that reported no usage never fires it, and a fold clears the * reading, so one reading folds at most once: the next fold waits for a turn * to report what the shrunk transcript costs. It needs a `model` whose turns * carry `usage`; with one that never reports it, this trigger never fires. */ readonly afterContextTokens?: number; /** * Fold when the latest brain turn's provider-reported `usage.inputTokens` * strictly exceeds this number, including cached input. Output tokens and * cumulative spend do not count. Missing usage and a fold clear the reading. */ readonly afterInputTokens?: number; /** * Fold when held image payload bytes strictly exceed this number. Counts * projected tool image parts: decoded base64 and byte views' byteLength. * URLs contribute zero bytes, without fetching; files and text do not count. */ readonly afterImageBytes?: number; /** * Fold when held projected tool image occurrences reach this number, including * URL images and repeated images. Recomputed from surviving records after a fold. */ readonly afterImageCount?: number; /** * How many of the NEWEST turns survive the fold intact, beside the summary. * Everything older becomes the summary's one synthetic head turn. Omit → `0`: * the whole transcript folds into the summary. * * A fold worth fewer than two turns is skipped by the agent itself — one turn * replaced by one summary shrinks nothing — so `keepTurns` within one of * `afterTurns` is a policy that never fires. */ readonly keepTurns?: number; } /** * Which call an `onToolError` failure belongs to: the model's `callId` — the * fan-out identity the outcome folds back on — and the tool `name` the model * asked for, which for an `unknown_tool` is the name it invented rather than * any declared tool. */ interface ToolErrorContext { readonly callId: string; readonly name: string; } /** * One lifecycle event a defined agent's run emits — {@link AgentEvent} with the * tool results typed against this agent's own tool set. */ type DefinedAgentEvent = AgentEvent>; /** * Host wiring for one `run`: the store, the ctx the tools need, a runId, a clock. * * `ctx` is the plain object the tools' handlers read (ADR 0020). A host with a * resource to release wraps `run` in its own `try` / `finally`. * * `onError` is the run's sink, and a fenced `store` needs one (see * {@link StoreAndOnError}). */ type DefinedAgentRunOptions = CtxArg> & StoreAndOnError> & { /** The run's identity. Omit → a fresh UUID. */ readonly runId?: string; /** The clock that stamps `at`. Omit → `Date.now`. */ readonly clock?: () => number; /** * Observe the run's turn-level lifecycle events — `TurnSettled`, * `ToolSettled`, `RunDone` — in the order the kernel settles them. This is * the progress seam: without it the only way to see anything mid-run is * `machine(input)` plus the raw kernel loop. * * It forwards the runtime's existing semantic stream (`agentEvents()` / * `runtime.on`); it mints no vocabulary of its own, so a consumer folds the * same {@link AgentEvent}s a hand-wired `run` would. * * The listener is CONTAINED: a throw is caught and warned, never allowed to * take the run down, and never observable in `run`'s resolution. Only * transitions applied by THIS process project events, so a store-backed * resume replays nothing that settled before the boot. * * Omit → no projector is wired and the run behaves exactly as before. */ readonly onEvent?: (event: DefinedAgentEvent) => void; /** * Observe the token deltas of the turn being produced right now — the * granularity below `onEvent`'s. Wired only when the configured `model` is * the streaming shape (`async (messages, { onChunk }) => turn`); a plain * model has no deltas to give, so passing this beside one is silent. * * Chunks ride a SIDE CHANNEL, never state. They are not projected off * transitions like an {@link AgentEvent} is, because nothing about a chunk is * a transition: it is never journaled, never written to the `Store`, and * never folded into the Model. That is the whole rule this option obeys — a * delta that has not settled is not an outcome, so a run that dies mid-turn * loses its chunks and resumes from the last SETTLED turn, and a resumed run * re-emits nothing it did not itself re-produce. * * The listener is CONTAINED exactly as `onEvent`'s is: a throw is caught and * warned, never allowed to fail the model call it fired from. * * Omit → the streaming model is still invoked in its streaming shape, with a * sink that drops every chunk. */ readonly onChunk?: (chunk: TurnChunk) => void; /** * Stop the run from outside — the stop button's seam. On abort the run settles * on a CANCELLED terminal Model and `run` RESOLVES with it; it does not reject, * and no `DriveFailedError` is thrown. Read the outcome with `status(state)`, * which answers `{ kind: "cancelled", at }` — distinct from `failed`, because a * run someone stopped did not fail. * * The outcome is durable, so it is also the answer on the next boot: a process * killed after an abort resumes reading a run that ENDED, not one to restart. * A signal already aborted when `run` is called ends it before the first model * call is made. * * It stops DISPATCH, not the work already in flight — a promise cannot be * cancelled, so a tool handler mid-call runs to its own end. Those late results * reach no `onEvent`, no `onToolError` and no Model, and they do not hold the * runtime's teardown. Propagating the signal INTO handlers is a separate seam * this option does not open. * * Omit → the run has no stop button and every path behaves exactly as before. */ readonly signal?: AbortSignal; }; /** * One decorator per interpret cell you name: it receives the cell the agent * wired (`next`) and returns the cell that runs in its place. Every key is * optional and a cell nobody names is passed through by REFERENCE, so an * overlay that wraps one tool leaves the others the exact functions * `defineAgent` built. * * The wrapper's signature is the cell's, so calling `next(cmd, ctx, dispatch)` * is how the wrapped work happens. A tool cell returns its outcome and the * engine mints `_ok` / `_err` from it (ADR 0021), so returning * what `next` returned is what keeps the fold, and therefore a replay, * identical to the unwrapped run's. */ type InterpretOverlay = CellWrappers>; /** * The decorator table over an interpret table `I`. Written over a bare type * parameter because `I[K]` is only indexable when `I` is one: applying the * mapped type to `DefinedAgentInterpret` inline leaves TypeScript indexing * an unreduced generic mapped type, which it refuses. */ type CellWrappers = { readonly [K in keyof I]?: (next: I[K]) => I[K]; }; /** * What `defineAgent(cfg).with(...)` takes — the one documented wrap point over * the machine the lid built. */ interface DefinedAgentOverlay { readonly interpret: InterpretOverlay; } /** What `defineAgent` returns. */ interface DefinedAgent { /** * Run `input` to its terminal Model. Resolves on `run.phase: "done"`; a * failed run rejects with `DriveFailedError` carrying the failed Model. * * With a `store`, the same call is also the resume: a Model the Store hands * back mid-run is booted (`agent_boot`) at its one outstanding effect — * same `runId`, no tool re-run — and one already `done` resolves as it is. * A fresh start needs an empty Store. * * It resolves with {@link DefinedAgentResolvedState} — the Model whose `run` * slice is narrowed to the ENDED phases, so `(await agent.run(i)).run.runId` * reads without a guard against an `idle` arm this promise cannot produce. */ readonly run: (input: string, ...opts: [Record] extends [DefinedAgentCtx] ? [opts?: DefinedAgentRunOptions] : [opts: DefinedAgentRunOptions]) => Promise>; /** * The machine `run` drives for `input` and the interpret table it runs under * — the way down to the raw kernel. */ readonly machine: (input: string) => DefinedAgentWired; /** * The ramp between the lid and `createAgent`: wrap ONE interpret cell of the * machine this agent builds and get back a NEW defined agent that runs the * wrapped table. The agent it is called on is untouched, and so is every cell * the overlay does not name. * * const traced = agent.with({ * interpret: { * fetch_rate: (next) => async (cmd, ctx, dispatch) => { * console.time(cmd.callId); * try { return await next(cmd, ctx, dispatch); } * finally { console.timeEnd(cmd.callId); } * }, * }, * }); * * The wrapped cell settles through the SAME typed Cmd→Msg edge as the cell it * wraps — it returns whatever `next` returned — so the reducer folds the same * Msgs and a replay of a wrapped run is the unwrapped run's replay. That is * the whole contract: the wrapper is one over the effect boundary, never over * the fold. A cell that must settle DIFFERENTLY is a different machine, and * `createAgent` is still where you build one. * * `with` composes — `agent.with(a).with(b)` puts `b`'s wrapper OUTSIDE `a`'s, * so `b` is entered first and `a`'s cell is what its `next` calls. Naming a * cell the machine has none of throws at `machine(input)`, where the table it * is checked against exists. */ readonly with: (overlay: DefinedAgentOverlay) => DefinedAgent; } /** * Define an agent from a model, the tools it may call and its instructions, and * get back `run(input)` — a promise of the finished state — plus `machine(input)` * for driving the same run yourself, which is the entry point a newcomer picks, * `createAgent` being the layer underneath that you drop to only to walk a stage * pipeline of your own. * * Add `maxTurns`, `deadlineMs`, `maxElapsedMs` or `stopWhen` to bound the run; * all four are described on `DefineAgentConfig`. The run's `input` is its single stage, so it is durable * beside `instructions`, and the prompt is rendered from those two and the * conversation on every model call. * * One unusual requirement does not cost you the lid: `.with({ interpret })` * wraps one interpret cell of the machine this built and hands back another * defined agent, so `createAgent` is for a rebuild rather than for a detour. */ declare function defineAgent(config: DefineAgentConfig): DefinedAgent; /** * The prompt as messages: the head, then each turn with its tool outcomes * and caller feedback. * `partsOf` reads the parts a settled call shows the model; omit it and no * `tool` message carries `parts`. PURE. */ declare function renderPrompt(prompt: AgentPrompt, partsOf?: ToolPartsOf, media?: DefineAgentConfig["media"]): AgentMessage[]; /** * @demlik/tea/agent — `agentTool()`: a child `defineAgent` as one tool a parent * agent calls and awaits. * * The child is a durable run of its own, never a slice of the parent's Model: * its `Store` and `runId` are keyed by the parent call's `callId` under a * namespace the consumer reads off the parent's ctx. That key is the whole * durability story. A parent resumed after an eviction re-fires the tool Cmd it * was waiting on; the re-fired call reaches the same key, so `defineAgent`'s own * `run` boots the child where its Store left it, or resolves a child that * already ended without calling its model again. This is Temporal's child * workflow (a re-issued start with the same id attaches to the same run), * LangGraph's namespaced subgraph checkpoint and the OpenAI Agents SDK's * `agent.as_tool()` (the parent keeps control and gets a result back). */ /** Why a child run ended `failed` — the reason `status()` reports for it. */ type ChildFailureReason = AgentTerminalFailure["reason"]; /** * The failures an agent tool settles with beside `thrown`. Each carries the * child's `childRunId`, so the parent model's reason names the run a human can * go and read. A child that `failed` also carries why — `turn_limit` when it hit * its own `maxTurns`, `elapsed_limit`, `llm`, `deadline` or `stage`. A child that * was `cancelled` (its `stopWhen` answered `true`) carries nothing more, because * nothing went wrong. */ type AgentToolError = { readonly _tag: "child_failed"; readonly childRunId: string; readonly failure: ChildFailureReason; } | { readonly _tag: "child_cancelled"; readonly childRunId: string; }; /** * How the child's ctx is derived from the parent's. Required when the child's * tools read a ctx, and optional — defaulting to none — when they read nothing, * the same rule `run`'s own `ctx` option follows. */ type ChildCtxOption = [ Record ] extends [DefinedAgentCtx] ? { readonly childCtx?: (ctx: HandlerCtx) => DefinedAgentCtx; } : { readonly childCtx: (ctx: HandlerCtx) => DefinedAgentCtx; }; /** What `agentTool` takes. */ type AgentToolSpec = { /** The model-facing sentence — the same field `tool()` declares. */ readonly description: string; /** Parses the parent model's `args`. */ readonly input: StandardSchemaV1; /** Parses what `result` returns, at the edge, like any tool's `ok`. */ readonly ok: StandardSchemaV1; /** * The child. Its bounds (`maxTurns`, `maxElapsedMs`, `stopWhen`), its tools * and its instructions are all its own definition's; the helper adds none. */ readonly agent: DefinedAgent; /** * The child's whole input, derived from the call's args. It is the only thing * the child is told: the parent's conversation never reaches it. */ readonly prompt: (args: Args) => string; /** The value the parent call settles with, read off the child's final turn. */ readonly result: (output: AgentTurn) => Ok; /** * The namespace the child run's key sits under, read off the parent's ctx — * the parent run's id, a tenant, whatever keeps two parents' calls apart. * The key is `/`. */ readonly namespace: (ctx: HandlerCtx) => string; /** * What the child run's failures with no caller to reject at reach. See * `run`'s `onError`. */ readonly onError?: OnError; } & ChildCtxOption & ChildStoreOption; /** * The child run's Store at `key`. The same key must reach the same durable cell * on every call, in every process — that is what makes a re-fired call resume * the child instead of restarting it. A child on a fenced Store needs an * `onError`, the same rule `run`'s own `store` follows (ADR 0031). */ type ChildStoreOption = { readonly store: (key: string, ctx: HandlerCtx) => UnfencedStore>; } | { readonly store: (key: string, ctx: HandlerCtx) => Store>; readonly onError: OnError; }; /** * Wrap a child `defineAgent` as a tool a parent `defineAgent` calls and awaits * — pass it the child, how to phrase its input and how to read its answer, and * get back a tool definition the parent's `tools` accepts like any `tool()`. * * A call runs the child to the end of its run and settles the parent's call: * * - child `done` → `ok(result(output))`; * - child `failed` → `{ _tag: "child_failed", childRunId, failure }`; * - child `cancelled` → `{ _tag: "child_cancelled", childRunId }`. * * Both failures are data the parent model reads as the call's reason, so the * parent run neither rejects nor throws when its child fails; it takes its next * turn. * * The child's Store and `runId` are both the key `/`. Firing * the same call twice reaches the same child run, and a different call reaches * a different one. So a parent killed while its child runs resumes the child * from its Store when the tool Cmd re-fires: no settled child turn calls the * model again, and no settled child tool runs again. A child that had already * ended resolves with the outcome it recorded. * * It declares no `timeoutMs` and no `retry`. A timeout would settle the parent * call while the child keeps running under the same key, and a retry of a child * that ended `failed` reaches that same ended run and reads the same failure. */ declare function agentTool(name: Name & NotReserved, spec: AgentToolSpec): ToolDef; /** * @packageDocumentation * The transcript collector — the built-in way to KEEP a run's turns, given that * a finished run's Model does not. * * A run that reaches `phase: "done"` clears `conversation` to `null` on * purpose: the terminating turn is stamped onto `output` first, so the answer * survives, and the history that would otherwise grow without bound in storage * kept for its state is dropped (`docs/explanation/durability-model.md`). That * policy is not what this module changes. What it changes is that every * consumer wanting the history had to hand-write the same fold over `onEvent`. * * So this is a COLLECTOR over the event stream that already exists, not a knob * on the Model. Nothing here is durable, nothing here is written to a `Store`, * and a run with a collector attached is byte for byte the run it was without * one — the same reason `onChunk` rides a side channel rather than state. * * const t = transcript>(); * const final = await agent.run(input, { store, onEvent: t.onEvent }); * t.read().turns; // every turn this process settled * * ## What a resume needs from you * * Events are projected off the transitions THIS process applies, so a run * resumed from a `Store` re-emits nothing the killed process already settled. * A collector that only ever listened would therefore hold the tail of a * resumed run and call it the whole thing. Hence the seed: hand * {@link transcript} the Model the `Store` handed back and it starts from that * Model's live conversation, so the resumed collector reads as the whole run * rather than its last leg. */ /** * One tool call the run settled OK, as the transcript keeps it — the `callId` * and the result, which is exactly what the `ToolSettled` event carries. * * A tool that FAILED is absent, and that is the event stream's shape rather * than a choice made here: `ToolSettled` is projected off the OK settle alone. * Branch on failures through `onToolError`, whose argument is typed per tag. */ interface TranscriptToolResult { readonly callId: string; readonly result: R; } /** * Whether the run has ended, and how: `running` until `RunDone`, then the * ending it carried — `done` with the terminal turn, `failed` with the * failure, or `cancelled`. * * `done` keeps `output` inside its own arm because `output` is legitimately * `null` on a finished run, and a single nullable field would make "not * finished yet" and "finished with nothing" the same reading. */ type TranscriptOutcome = { readonly kind: "running"; } | AgentEndedStatus; /** What a collector holds right now — a plain, immutable read. */ interface TranscriptSnapshot { /** Every model turn the transcript holds, in order. */ readonly turns: readonly AgentTurn[]; /** Every tool call that settled OK, in settle order. */ readonly tools: readonly TranscriptToolResult[]; /** Caller feedback, indexed by the empty turn it answers in this transcript. */ readonly nudges: readonly Nudge[]; /** Whether `RunDone` has been seen, and how the run ended if so. */ readonly outcome: TranscriptOutcome; } /** * The Model a resumed collector starts from — structural on purpose, so any * agent state (`DefinedAgentState`, `AgentState<…>`) satisfies it without * this module importing the lid, and a bare `{ conversation }` object works in * a test. */ interface TranscriptSeed { readonly conversation: Conversation | null; } /** * A live transcript: the listener you wire, and the read you take off it. * * `onEvent` is a bound function, so `{ onEvent: t.onEvent }` is the whole * wiring — there is no `this` to lose. */ interface Transcript { /** Wire this to `run`'s `onEvent`. */ readonly onEvent: (event: AgentEvent) => void; /** The transcript as of now. Each call returns a fresh immutable snapshot. */ readonly read: () => TranscriptSnapshot; } /** * Open a transcript collector over an agent run's event stream. * * Wire `onEvent` to `run`'s `onEvent` option and `read()` gives you the turns * and settled tool results afterwards — the transcript the finished Model no * longer carries. * * Pass `seed` when the run is a RESUME: the Model the `Store` handed back still * holds the live conversation the killed process built, and seeding from it is * what makes the collector hold the whole run rather than the leg this process * ran. One collector per process is the honest unit; a fresh run needs no seed. * * A seed taken from an already-finished Model contributes nothing, and * correctly so: that Model's `conversation` is `null` and its answer is its * `output`, which you already hold. */ declare function transcript(seed?: TranscriptSeed): Transcript; /** * @packageDocumentation * @demlik/tea/agent — THE headline Level-3 machine: a durable, crash-recoverable * AI agent that runs an ordered stage pipeline, and inside the agentic stage * drives the classic loop `llm → tools → fold → llm` until the model stops * asking for tools. * * This generalizes a production audit agent: the domain specifics are stripped, * and what remains — the loop, the durability, the boot-reconcile crash * recovery, the serial-vs-fanned tool dispatch — is yours. The consumer * supplies the only things that are genuinely domain: the tools, the prompts * (via the llm-call message loader), the schemas, and the model. `createAgent(config)` returns the uniform handle contract every * composition exposes (`init` / verbs returning `readonly [State, Cmd[]]` / * `subs`) AND a ready-to-`run` `defineMachine` (`toMachine`) — THE one wired * path. (`brainInterpret` and `brain` are the pieces a consumer wiring the * verbs by hand reaches for.) * * ## The composition (three siblings wired into ONE machine) * * - `../monitored-run` — the OUTER pipeline + lifecycle + safety watchdog. * The agent's stages (`plan → act → report`, say) are its stages; the * position survives eviction, the no-progress deadline auto-fails a wedged * run, and `boot` resumes mid-pipeline. The agent slice OWNS this slice and * delegates `start` / `advance` / `progress` / `onDeadline` / `boot` to it. * - `../llm-call` — every brain call. One * `LlmCall` per turn, structured-output parsed, retry composed in. The agent * delegates the resilient slice + verbs, and owns the one Promise handler * that invokes the model (`./model`). * - `../fan-out` — the tool calls a turn produced. Tools dispatch SERIALLY by * default (concurrency 1); fan-out generalizes that to a bounded number * LAUNCHED per transition, `config.toolConcurrency`. Above `1` a router's * tool cells overlap on the clock while `runInterpret` stays serial — the * fan-out is inside the Cmd handler, and its settles fold in emission * order (ADR 0018). Each * tool is an `of(call)` Cmd the consumer's own interpret performs; results * route back through `toolOk` / `toolErr`. When the batch drains, the agent * folds the gathered results back into the conversation and fires the next * brain call (`fold → llm`). * * ## The flow loop, as TEA * * 1. `start` enters the pipeline; the consumer wires the per-stage outstanding * effect (often a `call_llm` for the agentic stage) off the current stage. * 2. `turn(msg)` folds one model turn: * - no tool calls → the loop is done for this stage → `advance` the * pipeline (next stage, or finish to `done`). * - tool calls → `scatter` them across fan-out (≤ concurrency in flight), * emitting the per-tool effect Cmds. The conversation records the model * turn; `awaiting` flips to `tools`. * 3. `toolOk` / `toolErr` fold each settled tool back, launching the next * queued tool. When the batch drains, fold the gathered outcomes into the * conversation, bump the turn count (livelock guard), and fire the next * brain call — `awaiting` flips back to `llm`. * 4. The watchdog bounds a stall and the turn boundary's own stop conditions * bound the loop: the deadline fires `failed`, the turn limit fires * `failed { turn_limit }`, the wall-clock cap `failed { elapsed_limit }`, * and the consumer's `stopWhen` settles the run `cancelled`. * * ## Boot reconcile (crash recovery) * * Cold wake re-derives the ONE outstanding effect from `phase × awaiting`: a * brain call in flight re-fires `call_llm`; tools in flight re-fire the in-flight * tool Cmds. Re-fire is Model-idempotent — had the prior effect's result been * processed, the durable Model would already have advanced and boot re-emits the * NEXT effect. `boot` re-seeds the watchdog clock to NOW (a cold wake is not a * no-progress wedge) via the inherited monitored-run `boot`. * * ## The two non-negotiables (canon, inherited) * * - **Durable** — the whole slice is plain data: the monitored-run slice, the * resilient (retry) slice, the fan-out ledger, and the conversation are all * JSON-serializable. It survives DO eviction / reload. * - **Replayable** — every transition is a pure verb returning new state + * Cmds; nothing here reads the clock or RNG. Time arrives as an `at` * parameter, jitter RNG is injected once at `createAgent`, and the only clock * reads live inside the spliced handlers (the effect boundary). * * ## Typical wiring * * // Type params: . `ToolCmd` * // is the discriminated Cmd `toolOf` returns — keep it precise (not the open * // `Cmd`) so the wired machine's interpret merge type-checks per key. * type RunTool = { readonly _tag: "run_tool" } & ToolCall; * const agent = createAgent({ * stages: ["plan", "act", "report"], * // The brain: a plain `async (messages) => turn` (the common path), or the * // `(id) => Llm` factory when the model binds the schema itself. * model: async (messages) => client.chat(messages), * schemas: { plan: planSchema, act: turnSchema, report: reportSchema }, * turnOf: (stage) => stageToPurpose[stage], // which brain call a stage runs * toolOf: (call): RunTool => ({ _tag: "run_tool", ...call }), * toolConcurrency: 1, // launched per transition * deadlineMs: 10 * 60_000, * maxTurns: 60, * retry: defaultRetryPolicy, * loadMessages, * }); * // The consumer supplies the per-tool (+ snapshot) interpret; the agent owns * // the brain interpret and merges them in `toMachine`. * const wired = agent.toMachine({ toolInterpret }); * const runtime = run(wired.machine, { ...wired, ctx, store }); */ /** * Assemble an agent from `config` — the model, the stages it walks, and how a * tool call is turned into a command — and get back its `init`, verbs and `subs` * plus a `toMachine()` that wires all of it into one machine you hand to `run`, * which is the layer to reach for only once `defineAgent` cannot express the run * you want — a newcomer starts there, not here. * * Pass `snapshotEvery` to have the run persist itself every N steps, and * `compaction` to have long conversations summarized as they grow; each one you * pass obliges you to supply the matching handler at `toMachine`, and each one * you omit forbids it. `rng` is the determinism seam for the retry backoff — * pass a fixed `() => 0` to pin it in tests; omit for `Math.random`. * * The four overloads exist because the two obligations are derived * from the `config` VALUE, never inferred. `{ snapshotEvery: number }` REQUIRES * the `snapshot_write` cell, `{ snapshotEvery?: never }` FORBIDS it; `{ compaction: * policy }` REQUIRES the `compact_run` cell, `{ compaction?: never }` FORBIDS it. * They enumerate the snapshot × compaction grid: overload resolution * reads the two fields off `config`, so the right `Snap`/`Compact` pair is fixed * even when the call site passes explicit type arguments (TS does not infer * trailing type params — a `Cfg`-inference scheme would silently fall back to OFF * at every explicit-type-arg call site). The overloads fix both concretely. */ declare function createAgent, R, TC extends Cmd = Cmd, Msg = unknown>(config: AgentConfigCore & { readonly snapshotEvery: number; readonly compaction: CompactionPolicy; }): AgentKnob; declare function createAgent, R, TC extends Cmd = Cmd, Msg = unknown>(config: AgentConfigCore & { readonly snapshotEvery: number; readonly compaction?: never; }): AgentKnob; declare function createAgent, R, TC extends Cmd = Cmd, Msg = unknown>(config: AgentConfigCore & { readonly snapshotEvery?: never; readonly compaction: CompactionPolicy; }): AgentKnob; declare function createAgent, R, TC extends Cmd = Cmd, Msg = unknown>(config: AgentConfigCore & { readonly snapshotEvery?: never; readonly compaction?: never; }): AgentKnob; export { AgentCmd, AgentConfigCore, AgentEndedStatus, AgentEvent, AgentKnob, AgentMachineMsg, type AgentMessage, type AgentPrompt, AgentState, AgentTerminalFailure, type AgentToolError, type AgentToolSpec, AgentTurn, AnyToolDef, type ChildFailureReason, CompactionPolicy, ContentPart, Conversation, DeadlinesSub, type DefineAgentCompaction, type DefineAgentConfig, type DefinedAgent, type DefinedAgentCmd, type DefinedAgentCtx, type DefinedAgentEvent, type DefinedAgentInterpret, type DefinedAgentMachine, type DefinedAgentModel, type DefinedAgentMsg, type DefinedAgentOverlay, type DefinedAgentResolvedState, type DefinedAgentRunOptions, type DefinedAgentState, type DefinedAgentWired, EndedRun, type InterpretOverlay, type LidPurpose, MessageContent, Nudge, PlainModel, StreamingModel, ToolCall, ToolCmd, ToolDef, type ToolErrorContext, ToolFailureOf, ToolOutcome, type ToolPartsOf, ToolResult, ToolThrown, ToolsCtx, type Transcript, type TranscriptOutcome, type TranscriptSeed, type TranscriptSnapshot, type TranscriptToolResult, TurnChunk, WiredToolMsg, agentTool, createAgent, defineAgent, renderPrompt, transcript };