@demlik/tea 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/agent/index.d.ts +13 -13
  2. package/dist/agent/index.js +9 -9
  3. package/dist/{chunk-CIHSHLQX.js → chunk-4NTCPTNQ.js} +3 -3
  4. package/dist/{chunk-CIHSHLQX.js.map → chunk-4NTCPTNQ.js.map} +1 -1
  5. package/dist/{chunk-7MGXQZPW.js → chunk-4PXNZ5UY.js} +4 -4
  6. package/dist/{chunk-7MGXQZPW.js.map → chunk-4PXNZ5UY.js.map} +1 -1
  7. package/dist/{chunk-6NG4V5SB.js → chunk-6XBEYZME.js} +5 -5
  8. package/dist/{chunk-6NG4V5SB.js.map → chunk-6XBEYZME.js.map} +1 -1
  9. package/dist/{chunk-GOX2CYIM.js → chunk-C4U5D5HP.js} +3 -3
  10. package/dist/{chunk-GOX2CYIM.js.map → chunk-C4U5D5HP.js.map} +1 -1
  11. package/dist/{chunk-MVZS5FDM.js → chunk-DFUEAA6L.js} +3 -3
  12. package/dist/{chunk-MVZS5FDM.js.map → chunk-DFUEAA6L.js.map} +1 -1
  13. package/dist/{chunk-IVJP3GKJ.js → chunk-GWWCCSDH.js} +4 -4
  14. package/dist/{chunk-IVJP3GKJ.js.map → chunk-GWWCCSDH.js.map} +1 -1
  15. package/dist/{chunk-CH5KTOEZ.js → chunk-K4ETBNKS.js} +32 -9
  16. package/dist/chunk-K4ETBNKS.js.map +1 -0
  17. package/dist/{chunk-5XU6ZJO2.js → chunk-KWNCM6XM.js} +19 -13
  18. package/dist/chunk-KWNCM6XM.js.map +1 -0
  19. package/dist/{chunk-BCTEOVOU.js → chunk-LYVOGOBC.js} +3 -3
  20. package/dist/{chunk-BCTEOVOU.js.map → chunk-LYVOGOBC.js.map} +1 -1
  21. package/dist/{chunk-MYNLY3HP.js → chunk-OPH6Y4UT.js} +3 -3
  22. package/dist/{chunk-MYNLY3HP.js.map → chunk-OPH6Y4UT.js.map} +1 -1
  23. package/dist/{chunk-NSIAORRY.js → chunk-OYR7ENKU.js} +3 -3
  24. package/dist/{chunk-NSIAORRY.js.map → chunk-OYR7ENKU.js.map} +1 -1
  25. package/dist/{chunk-WT5PBPLB.js → chunk-QWIPH4YH.js} +4 -4
  26. package/dist/{chunk-WT5PBPLB.js.map → chunk-QWIPH4YH.js.map} +1 -1
  27. package/dist/{chunk-EHUDXAKC.js → chunk-XBZQT2TD.js} +7 -7
  28. package/dist/chunk-XBZQT2TD.js.map +1 -0
  29. package/dist/{core-BbgtiXdg.d.ts → core-rDbOaJTN.d.ts} +7 -3
  30. package/dist/do/index.d.ts +12 -12
  31. package/dist/do/index.js +10 -10
  32. package/dist/{durable-effects-7MTK_jnj.d.ts → durable-effects-CNaw97Be.d.ts} +1 -1
  33. package/dist/effect/index.d.ts +2 -2
  34. package/dist/effect/index.js +2 -2
  35. package/dist/extension/index.d.ts +3 -3
  36. package/dist/extension/index.js +2 -2
  37. package/dist/flow/index.d.ts +13 -13
  38. package/dist/flow/index.js +10 -10
  39. package/dist/idempotency/index.d.ts +3 -3
  40. package/dist/idempotency/index.js +3 -3
  41. package/dist/{index-Bz5Rh9Ga.d.ts → index-BOrsbdAf.d.ts} +4 -4
  42. package/dist/{index-DU6JpQ8G.d.ts → index-B_BxplWi.d.ts} +1 -1
  43. package/dist/{index-CjFDUBeq.d.ts → index-CWmsXNdX.d.ts} +1 -1
  44. package/dist/{index-_dOR3xqA.d.ts → index-Cberb5Rr.d.ts} +2 -2
  45. package/dist/{index-7vV8xmsD.d.ts → index-CcrKLtse.d.ts} +1 -1
  46. package/dist/{index-CkFYA9Y6.d.ts → index-Cx0F2M34.d.ts} +2 -2
  47. package/dist/{index-Xufl55W8.d.ts → index-DaX_P35Q.d.ts} +2 -2
  48. package/dist/{index-Cou86-GX.d.ts → index-q1PoukOZ.d.ts} +2 -2
  49. package/dist/index.d.ts +5 -5
  50. package/dist/index.js +2 -2
  51. package/dist/jev/index.d.ts +8 -8
  52. package/dist/jev/index.js +5 -5
  53. package/dist/{machine-BQzTV8On.d.ts → machine-BcfCFMYF.d.ts} +7 -7
  54. package/dist/machine-viz/index.d.ts +1 -1
  55. package/dist/machine-viz/index.js +2 -2
  56. package/dist/mem/index.d.ts +2 -2
  57. package/dist/mem/index.js +2 -2
  58. package/dist/node/index.d.ts +2 -2
  59. package/dist/node/index.js +2 -2
  60. package/dist/paginate/index.d.ts +4 -4
  61. package/dist/paginate/index.js +5 -5
  62. package/dist/parity/index.d.ts +3 -3
  63. package/dist/parity/index.js +3 -3
  64. package/dist/pbt/index.d.ts +1 -1
  65. package/dist/pbt/index.js +2 -2
  66. package/dist/persistence/index.d.ts +9 -10
  67. package/dist/persistence/index.js +4 -4
  68. package/dist/promise/index.d.ts +2 -2
  69. package/dist/promise/index.js +3 -3
  70. package/dist/react/index.d.ts +2 -2
  71. package/dist/resilience/index.d.ts +6 -6
  72. package/dist/resilience/index.js +5 -5
  73. package/dist/{runtime-types-CiVpC0HN.d.ts → runtime-types-B62Ucnxr.d.ts} +2 -2
  74. package/dist/testing/index.d.ts +22 -108
  75. package/dist/testing/index.js +27 -177
  76. package/dist/testing/index.js.map +1 -1
  77. package/dist/timing/index.d.ts +4 -4
  78. package/dist/timing/index.js +4 -4
  79. package/dist/{types-LxZxGYda.d.ts → types-DPm5YCDQ.d.ts} +1 -1
  80. package/dist/work-queue/index.d.ts +4 -4
  81. package/package.json +3 -3
  82. package/dist/chunk-5XU6ZJO2.js.map +0 -1
  83. package/dist/chunk-CH5KTOEZ.js.map +0 -1
  84. package/dist/chunk-EHUDXAKC.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/llm-call/index.ts","../src/protocol.ts","../src/agent/schema.ts","../src/agent/compaction.ts","../src/agent/internal.ts","../src/agent/machine.ts","../src/agent/model.ts","../src/agent/tool.ts","../src/agent/types.ts","../src/agent/tool-resilience.ts","../src/agent/define-agent.ts","../src/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A,EAAM,CAAC,GAAA,CAAI,GAAA,EAAK,GAAI,KAAA,EAAO,IAAA,IAAQ,EAAG;AAAA,KACxC;AAQA,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,cAAc,OAAO,CAAA;AAAA,MAC9B,SAAA;AAAA,MACA,SAAA,EAAW,EAAE,QAAA,EAAU,iBAAA;AAAkB,KAC3C;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA;AAAA,IACA,IAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,IAAA;AAAA,IACA,SAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,IAAA;AAAA,IACA,SAAA;AAAA,IACA,YAAA;AAAA,IACA,SAAA;AAAA,IACA,IAAA;AAAA;AAAA;AAAA,IAGA,SAAA;AAAA,IACA,cAAA,EAAgB,aAAA;AAAA,IAChB,OAAO,GAAA,CAAI;AAAA,GACb;AACF","file":"chunk-XBZQT2TD.js","sourcesContent":["/**\n * @packageDocumentation\n * internal/llm-call — `resilient-call` + structured-output parse + a typed\n * failure variant, around a purpose-discriminated LLM invocation. Internal\n * since #49 — not published on any subpath; `@demlik/tea/agent` re-exports\n * the types a consumer meets.\n *\n * This is the ~60-line `call_llm` handler from the audit-agent seed collapsed\n * into plain functions (ADR 0022): a config object, the resilient-call slice it\n * inherits, the `Cmd.define`d run Cmd, and the pure pieces a handler needs to\n * turn a model's raw answer into that Cmd's outcome. It ships no I/O (ADR\n * 0021): invoking the model is the handler YOU write, in your engine's style —\n * `@demlik/tea/agent` writes the Promise one — and it hands the model's raw\n * answer to `decode`.\n *\n * ## What it adds over `../resilient-call`\n *\n * - **Structured-output parse** — each `purpose` maps to a `Schema` in\n * `config.schemas`. `decode(cmd, raw)` runs `schemas[purpose].parse` over\n * the model's answer: a pass is the parsed, purpose-tagged `LlmOk`; a throw\n * is a `port_rejected` failure (a parse failure is a failure, not a stall —\n * \"errors are data\"), and a malformed answer never becomes a corrupt\n * success.\n * - **A typed failure variant** — every failure (model throw, schema parse)\n * settles as `resilient_run_err`, and `fail` / `errOf` read it back as the\n * typed `LlmErr`, tagged with the `purpose` so the consumer's reducer routes\n * per-stage.\n *\n * ## Inheriting resilient-call by composition (not reinvention)\n *\n * The retry / backoff lives in `../resilient-call`: `createLlmCall` builds a\n * `createResilientCall` knob and DELEGATES `init`, `attempt`, `onTimer`,\n * `deadlines`, `timer` to it verbatim, and `succeed` / `fail` to its `settle`\n * — the slice is literally resilient-call's slice. There is no second backoff\n * implementation here.\n *\n * ## The two non-negotiables (canon, inherited)\n *\n * - **Durable** — the slice is resilient-call's plain-data slice (a Model\n * field). Input carried on the `resilient_run` Cmd is the plain `LlmCall`\n * request (purpose + modelId + payload) — no closures.\n * - **Replayable** — every transition is a resilient-call verb; nothing here\n * reads a clock. The settled Msgs carry the `at` the engine stamps.\n *\n * ## Typical wiring\n *\n * const llm = createLlmCall<MyPurpose, MyOutputs>({\n * schemas: { plan: planSchema, report: reportSchema },\n * retry: defaultRetryPolicy,\n * });\n *\n * // in the machine:\n * cmds: [llm.run],\n * update: {\n * call_llm: (s, m) => liftLlmCall(s, llm.attempt(s.resilience, m.input, m.at)),\n * resilient_run_ok: (s, m) => …llm.succeed(s.resilience, m)… m.value.output …,\n * resilient_run_err: (s, m) => …llm.fail(s.resilience, m)… llm.errOf(m) …,\n * deadline_exceeded: (s, m) => liftLlmCall(s, llm.onTimer(s.resilience, m)),\n * },\n * subs: [{ type: \"timer\", deps: (s) => llm.timer(s.resilience) }],\n *\n * // and where it runs — invoking the model is your handler:\n * run(machine, {\n * interpret: {\n * resilient_run: async (cmd) => {\n * try { return llm.decode(cmd, await model(cmd.input)); }\n * catch (cause) { return llm.rejected(cause); }\n * },\n * },\n * });\n */\n\nimport { describeError } from \"../../describe-error\";\nimport { type Cmd, Outcome } from \"../../index\";\nimport type { RetryPolicy } from \"../../retry-backoff\";\nimport type { DeadlineExceeded, DeadlineSub } from \"../resilience/deadline\";\nimport {\n createResilientCall,\n type FailMsg,\n liftResilience,\n type ResilientConfig,\n type ResilientState,\n type RunCmd,\n type SucceedMsg,\n} from \"../resilience/resilient-call\";\n\n// ===========================================================================\n// The structured-output schema contract.\n// ===========================================================================\n\n/**\n * The minimal structured-output schema contract: `parse(unknown) => T`, the\n * zod-style call `decode` uses to validate the model's output before it\n * settles `resilient_run_ok`. A throwing `parse` (the zod contract on invalid\n * input) becomes a `port_rejected` outcome — a parse failure is a failure,\n * never a silent pass. Structural so a real `z.ZodType<T>` satisfies it\n * without an import.\n */\nexport interface Schema<T> {\n /** Validate + narrow `value` to `T`, or throw on mismatch (the zod contract). */\n parse(value: unknown): T;\n}\n\n// ===========================================================================\n// Config — the knob. `schemas` required; `retry` optional.\n// ===========================================================================\n\n/**\n * The llm-call knob. `schemas` is the load-bearing field — the per-purpose\n * structured-output targets `decode` parses against; `retry` is the\n * resilient-call \"omit a brick → omit its gate\" story. Omit it and a model\n * failure is terminal (no backoff).\n *\n * `P` is the purpose union (e.g. `\"plan\" | \"report\"`); `O` maps each purpose to\n * its parsed output type.\n */\nexport interface LlmCallConfig<P extends string, O extends Record<P, unknown>> {\n /** One structured-output schema per purpose; the parse target `decode` binds. */\n readonly schemas: { readonly [K in P]: Schema<O[K]> };\n /** Backoff policy, composed into `../resilient-call`. Omit → no backoff. */\n readonly retry?: RetryPolicy;\n}\n\n// ===========================================================================\n// The request / response shapes the knob speaks.\n// ===========================================================================\n\n/**\n * One LLM call request — the resilient-call `input` for this module, carried on\n * the `resilient_run` Cmd as plain data — no closures, so it survives\n * persistence and replay. Purpose-discriminated: a `purpose` selecting the\n * schema + prompt assembly, the `model` id, and the opaque per-purpose\n * `payload` the handler's message loader consumes.\n *\n * `key` defaults to `purpose` when the consumer calls `attempt(s, input, at)`,\n * so one in-flight call per purpose is tracked under the resilient-call slice —\n * the common single-call-per-stage shape. A consumer that fans out many calls\n * of one purpose passes a distinct `key`.\n */\nexport interface LlmCall<P extends string> {\n /** The stage / schema selector — drives both `schemas[purpose]` and message assembly. */\n readonly purpose: P;\n /** The model id to invoke; `null` = the host's default model. */\n readonly model: string | null;\n /** The per-purpose prompt payload the message loader consumes. Opaque to the knob. */\n readonly payload: unknown;\n}\n\n/** The parsed, typed success carried on `resilient_run_ok`, tagged with its purpose. */\nexport interface LlmOk<P extends string, O extends Record<P, unknown>> {\n readonly key: string;\n readonly purpose: P;\n readonly output: O[P];\n}\n\n/** The typed failure variant — every failure path surfaces this, tagged by purpose. */\nexport interface LlmErr<P extends string> {\n readonly key: string;\n readonly purpose: P;\n /** A human-readable cause (model throw, retry-exhaustion, or schema parse). */\n readonly reason: string;\n /** The original error, carried untouched for the consumer to inspect. */\n readonly error: unknown;\n}\n\n/**\n * How a failure crosses the handler: the run Cmd's declared `port_rejected`\n * tag with the raw failure on `cause`. `errOf` reads it back as {@link LlmErr}.\n */\nexport type LlmRejected = {\n readonly _tag: \"port_rejected\";\n readonly cause: unknown;\n};\n\n/**\n * The effect Cmd this module emits: run the LLM call for `key` with `input`. It\n * is `../resilient-call`'s `Cmd.define`d `RunCmd` specialized to the `LlmCall`\n * input — NOT a re-declared shape — so the resilient verbs' return tuples\n * thread through `attempt` / `succeed` / `fail` / `onTimer` with no cast.\n */\nexport type LlmRunCmd<P extends string> = RunCmd<LlmCall<P>>;\n\n/** The success Msg the engine mints — resilient-call's, with the parsed `LlmOk`. */\nexport type LlmSucceedMsg<\n P extends string,\n O extends Record<P, unknown>,\n> = SucceedMsg<LlmOk<P, O>, \"resilient\", LlmCall<P>>;\n\n/**\n * The failure Msg the engine mints — resilient-call's. Its `error` is the\n * handler's `port_rejected` (an {@link LlmRejected} when the handler used\n * `decode` / `rejected`); read it as the typed {@link LlmErr} with `errOf`.\n */\nexport type LlmFailMsg<P extends string> = FailMsg<\"resilient\", LlmCall<P>>;\n\n/** The retry / deadline timer Msg — `DeadlineExceeded`, inherited from resilient-call. */\nexport type LlmTimerMsg = DeadlineExceeded;\n\n// ===========================================================================\n// The knob factory.\n// ===========================================================================\n\n/**\n * Build an llm-call knob from `config`. `rng` is injected for the inherited\n * retry jitter (pass a fixed `() => 0.5` in tests to pin backoff; defaults to\n * `Math.random`, read only at the resilient-call verb boundary).\n *\n * The slice + verbs (`init`, `attempt`, `succeed`, `fail`, `onTimer`,\n * `deadlines`, `timer`) are DELEGATED to a `../resilient-call` knob — no second\n * backoff here. `decode` / `rejected` / `errOf` are the pure pieces that turn a\n * model's answer into the run Cmd's outcome and read a failure back.\n *\n * `P` is the purpose union, `O` the purpose→output map.\n */\nexport function createLlmCall<P extends string, O extends Record<P, unknown>>(\n config: LlmCallConfig<P, O>,\n rng: () => number = Math.random,\n) {\n // Only the `retry` brick is forwarded — a stage call is a single brain\n // invocation, not a keyed downstream target, so llm-call exposes no circuit /\n // rate-limit / cache / deadline knobs.\n const resilientConfig: ResilientConfig = {\n ...(config.retry === undefined ? {} : { retry: config.retry }),\n };\n const rc = createResilientCall<LlmCall<P>, LlmOk<P, O>>(resilientConfig, rng);\n\n /** The slice this knob owns — resilient-call's slice verbatim. */\n type State = ResilientState<LlmCall<P>, LlmOk<P, O>>;\n\n /** The starting slice — resilient-call's. */\n function init(): State {\n return rc.init();\n }\n\n /**\n * Start (or restart) an LLM call. `key` defaults to the call's `purpose` so\n * one in-flight call per stage is tracked under the slice (the common shape);\n * pass a distinct key to fan out. PURE — delegates straight to\n * resilient-call's gate.\n */\n function attempt(\n s: State,\n input: LlmCall<P>,\n at: number,\n key: string = input.purpose,\n ): readonly [State, readonly LlmRunCmd<P>[]] {\n return rc.attempt(s, key, input, at);\n }\n\n /** Record a parsed success. PURE — resilient-call's `settle`. */\n function succeed(\n s: State,\n msg: LlmSucceedMsg<P, O>,\n ): readonly [State, readonly LlmRunCmd<P>[]] {\n const { call, cmds } = rc.settle(s, msg);\n return [call, cmds];\n }\n\n /**\n * Read a settled failure as the typed {@link LlmErr}: the call's key and\n * purpose off the run Cmd, and the handler's `cause` (or the whole error,\n * when the handler returned no `cause`). PURE.\n */\n function errOf(msg: LlmFailMsg<P>): LlmErr<P> {\n const error = msg.error;\n const cause = \"cause\" in error ? error.cause : error;\n return {\n key: msg.cmd.key,\n purpose: msg.cmd.input.purpose,\n reason: describeError(cause),\n error: cause,\n };\n }\n\n /**\n * Record a failure: back off via the inherited retry, or settle `failed`.\n * PURE — resilient-call's `settle`. The `failed` phase carries the typed\n * {@link LlmErr}, never the handler's carrier.\n */\n function fail(\n s: State,\n msg: LlmFailMsg<P>,\n ): readonly [State, readonly LlmRunCmd<P>[]] {\n const { call, cmds } = rc.settle(s, { ...msg, error: errOf(msg) });\n return [call, cmds];\n }\n\n /** A retry / deadline timer fired. PURE — resilient-call's `onTimer`. */\n function onTimer(\n s: State,\n msg: LlmTimerMsg,\n ): readonly [State, readonly LlmRunCmd<P>[]] {\n return rc.onTimer(s, msg);\n }\n\n /** The call's deadlines — resilient-call's retry and deadline timers. */\n function deadlines(s: State): readonly DeadlineSub[] {\n return rc.deadlines(s);\n }\n\n /**\n * Turn a model's raw answer into the run Cmd's outcome. PURE: parse it with\n * the call's purpose schema. A pass is the parsed, purpose-tagged `LlmOk`,\n * keyed by the Cmd's own `key` (so a fanned-out success carries the key its\n * failure would); a `parse` throw is a `port_rejected` outcome carrying the\n * throw.\n */\n function decode(\n cmd: LlmRunCmd<P>,\n raw: unknown,\n ): Outcome<LlmOk<P, O>, LlmRejected> {\n const { purpose } = cmd.input;\n try {\n const output = config.schemas[purpose].parse(raw);\n return Outcome.ok({ key: cmd.key, purpose, output });\n } catch (cause) {\n return rejected(cause);\n }\n }\n\n /** The outcome for a model call that threw. PURE. */\n function rejected(cause: unknown): Outcome<never, LlmRejected> {\n return Outcome.err({ _tag: \"port_rejected\", cause });\n }\n\n return {\n name: rc.name,\n /** The `Cmd.define`d run Cmd — list it in the machine's `cmds`. */\n run: rc.run,\n init,\n attempt,\n succeed,\n fail,\n errOf,\n onTimer,\n deadlines,\n /** The built-in `timer` Sub's deps — resilient-call's `timer`. */\n timer: rc.timer,\n decode,\n rejected,\n /** The structured-output schema for `purpose`. */\n schemaOf: <K extends P>(purpose: K): Schema<O[K]> =>\n config.schemas[purpose],\n };\n}\n\n/**\n * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the\n * slice lives at `state.resilience` — the same convenience `../resilient-call`\n * ships, re-typed for the llm-call slice so consumers wire one import. Pure.\n */\nexport function liftLlmCall<\n S extends { resilience: ResilientState<LlmCall<P>, LlmOk<P, O>> },\n P extends string,\n O extends Record<P, unknown>,\n C extends Cmd,\n>(\n state: S,\n result: readonly [ResilientState<LlmCall<P>, LlmOk<P, O>>, readonly C[]],\n): readonly [S, readonly C[]] {\n return liftResilience(state, result);\n}\n\nexport type { DeadlineSub, DeadlineExceeded, ResilientState };\n","// ===========================================================================\n// Protocol — the ONE typed source of truth for the cross-module Msg/Cmd\n// discriminant strings (issue #60).\n// ===========================================================================\n//\n// The resilient/agent/auth plumbing speaks a small fixed vocabulary of\n// discriminant strings on `{ type: ... }` Msgs and Cmds. Before this module\n// those literals were retyped inline across ~8 modules — `resilient_ok` alone\n// appeared as a hand-written `\"resilient_ok\"` in resilient-call, a wrapper,\n// llm-call, agent, do/host, paginated-walk, reconciler. Adding a variant or\n// renaming one was shotgun surgery with no compiler to catch a missed site.\n//\n// `MsgType` is that vocabulary, declared ONCE `as const`. Each entry is BOTH:\n// - a value — `MsgType.ResilientOk` is the string `\"resilient_run_ok\"`, used at\n// construction sites (`{ type: MsgType.ResilientOk, ... }`), reducer keys\n// (`[MsgType.ResilientOk]: ...`), and switch labels (`case MsgType.ResilientOk:`).\n// - a type — `typeof MsgType.ResilientOk` is the literal type `\"resilient_run_ok\"`,\n// used in the `readonly type:` field of every Msg/Cmd interface.\n//\n// Because the value and the type both derive from the single `as const`\n// declaration, a new variant or a rename is a ONE-LINE change here that\n// propagates with full exhaustiveness — not an 8-file edit.\n//\n// This module is BEHAVIOR-PRESERVING: every string is byte-identical to the\n// literal it replaces. It is internal plumbing vocabulary, NOT a public event\n// surface — `resilient_run_ok` / `agent_tool_ok` stay PRIVATE (the agent's\n// `agentEvents` projector is the ONE place they are read; #47). Centralizing\n// the literal here does NOT re-expose them to consumers.\n\n/**\n * The closed set of cross-module Msg/Cmd discriminant strings. Declared `as\n * const` so each entry is usable as both a value (construction / reducer keys /\n * switch labels) and, via `typeof MsgType.X`, a literal type (`readonly type:`\n * fields). The single source of truth for issue #60.\n */\nexport const MsgType = {\n // --- resilient-call: the run Cmd + its two settle Msgs -------------------\n /** The \"run the port for `key`\" effect Cmd resilient-call emits. */\n ResilientRun: \"resilient_run\",\n /**\n * PRIVATE success settle Msg (read only by `agentEvents`, #47). The engine\n * mints it from the run Cmd's outcome (ADR 0021), so it is `<run>_ok`.\n */\n ResilientOk: \"resilient_run_ok\",\n /** Failure settle Msg — routed to `settle` (back off via retry). */\n ResilientErr: \"resilient_run_err\",\n\n // --- agent: the wired machine's own entry-point Msgs ---------------------\n /** Begin a run. */\n AgentStart: \"agent_start\",\n /** PRIVATE tool-fan-out success settle Msg (read only by `agentEvents`, #47). */\n AgentToolOk: \"agent_tool_ok\",\n /** Tool-fan-out failure settle Msg. */\n AgentToolErr: \"agent_tool_err\",\n /**\n * Re-fire the one outstanding effect on rehydrate (the do↔agent seam). Fired\n * by `do/host`'s `autoBoot` via the typed `agentBootMsg` constructor, matched\n * by the agent reducer — see `AgentBootPort` in `../agent`.\n */\n AgentBoot: \"agent_boot\",\n /**\n * Stop the run from outside and settle it `cancelled` — what an `AbortSignal`\n * handed to `driveToDone` / a defined agent's `run` dispatches on abort. A\n * transition, never a throw: the outcome lands in the Model, so a reload reads\n * a run that ended rather than one to resume.\n */\n AgentCancel: \"agent_cancel\",\n\n // --- agent: the context-compaction round-trip (#85) ----------------------\n /**\n * The \"summarize the oldest N turns\" effect Cmd the agent emits when its\n * `CompactionPolicy` asks to compact before a brain call. A DEDICATED\n * round-trip (design B1), distinct from the brain call's `resilient_run`, so\n * compaction is its own honest `Awaiting` state — see `../agent`.\n */\n CompactRun: \"compact_run\",\n /** Compaction round-trip resolved — carries the summary text the fold-back folds. */\n CompactOk: \"compact_ok\",\n /** Compaction round-trip failed (exhausted retry) — surfaced as data, not a stall. */\n CompactErr: \"compact_err\",\n\n // --- authed-call: the 401 trigger ----------------------------------------\n /** The 401 the consumer dispatches when a guarded call comes back unauthorized. */\n Unauthorized: \"unauthorized\",\n} as const;\n\n/** The union of every discriminant string in the protocol. */\nexport type MsgTypeValue = (typeof MsgType)[keyof typeof MsgType];\n","/**\n * @demlik/tea/agent — internal structured-output schema helper.\n *\n * NOT part of the public `./agent` barrel: `schemaFromGuard` is the shared\n * zod-style `parse` throw-wrapper the two owned structured-output schemas\n * (`agentTurnSchema`, `compactionSummarySchema`) are built from. It lives in its\n * own module so both `types.ts` and `compaction.ts` can import it without either\n * re-exporting it (the barrel `index.ts` never re-exports this file, so the\n * helper stays internal).\n */\n\nimport type { Schema } from \"../internal/llm-call\";\n\n/**\n * Build a `Schema<T>` from a type guard — the zod-style `parse` throw-wrapper the\n * llm-call handler relies on, factored so tea's two owned structured-output\n * schemas ({@link agentTurnSchema}, {@link compactionSummarySchema}) share one\n * shape. On a\n * value the guard rejects it throws `structured-output parse failed: not <name>`\n * (a `*_err` at the boundary — errors are data); otherwise it narrows through.\n * `name` is the full noun phrase incl. article (\"an AgentTurn\").\n */\nexport function schemaFromGuard<T>(\n guard: (value: unknown) => value is T,\n name: string,\n): Schema<T> {\n return {\n parse: (value: unknown): T => {\n if (!guard(value)) {\n throw new Error(`structured-output parse failed: not ${name}`);\n }\n return value;\n },\n };\n}\n","/**\n * @demlik/tea/agent — the context-compaction seam.\n *\n * The opt-in transcript snapshot-and-compact policy, shaped exactly like\n * `AgentSnapshotConfig` (see `./types`) so a short agent pays nothing and cannot\n * even mention the machinery. This module owns the whole `$compact` vocabulary:\n * the reserved purpose, the summary schema, the consumer policy, the config\n * discriminant, and the dedicated `compact_run` / `compact_ok` / `compact_err`\n * Cmd + Msgs re-keyed off the composed resilient call at the agent boundary.\n */\n\nimport type { Cmd, Interpret } from \"../index\";\nimport type { LlmCall, LlmErr, LlmOk, Schema } from \"../internal/llm-call\";\nimport type { MsgType } from \"../protocol\";\nimport type { MessageLoader } from \"./model\";\nimport { schemaFromGuard } from \"./schema\";\nimport type { Conversation } from \"./types\";\n\n/**\n * The reserved purpose the compaction round-trip runs under. Compaction\n * is a DEDICATED resilient LLM call (design B1), NOT one of the consumer's brain\n * purposes `P` — so it carries its own purpose literal, kept in the agent's\n * private `$`-namespace (the same reserved-namespace discipline `with-resilience`\n * uses) so it never collides with a consumer purpose. A consumer never names it.\n */\nexport type CompactionPurpose = \"$compact\";\n\n/** The reserved compaction purpose's value — the single in-flight summarize call's key. */\nexport const COMPACTION_PURPOSE: CompactionPurpose = \"$compact\";\n\n/**\n * The purpose→output map for the compaction LLM call — the single reserved\n * `$compact` purpose mapping to a {@link CompactionSummary}. Mirrors the brain\n * call's `O` map, scoped to the one compaction purpose, so the composed\n * `createLlmCall` parses the summarize output under the same structured-output\n * contract the brain call uses.\n */\nexport interface CompactionOutputs extends Record<CompactionPurpose, unknown> {\n readonly $compact: CompactionSummary;\n}\n\n/**\n * Narrow an unknown to a {@link CompactionSummary} — the runtime witness for the\n * compaction call's structured output. Checks the one load-bearing field\n * (`summary` is a string). PURE — allocates no Error.\n */\nexport function isCompactionSummary(\n value: unknown,\n): value is CompactionSummary {\n if (value === null || typeof value !== \"object\") return false;\n return typeof (value as { summary?: unknown }).summary === \"string\";\n}\n\n/**\n * The `Schema<CompactionSummary>` the compaction call binds — tea's own parse\n * target for the summarize round-trip (it OWNS the `$compact` purpose's output).\n * Throws on a non-summary (the zod-style `parse` contract the llm-call handler\n * relies on), so a malformed summary is a `compact_err` (errors are data), never\n * a corrupt fold-back.\n */\nexport const compactionSummarySchema: Schema<CompactionSummary> =\n schemaFromGuard(isCompactionSummary, \"a CompactionSummary\");\n\n/**\n * The result a compaction round-trip produces — the model's summary of the\n * folded-away turns. Tea OWNS this shape (the `$compact` purpose's output): the\n * fold-back (`compact_ok`) writes `summary` into a synthetic head `AgentTurn`\n * (design A1), so a consumer's `loadMessages` reads it as a normal turn with no\n * watermark to learn. Generic-free — the summary is always plain text.\n */\nexport interface CompactionSummary {\n /** The model's summary of the folded-away (oldest) turns + their tool records. */\n readonly summary: string;\n}\n\n/**\n * The consumer's compaction policy. One PURE trigger; the impure\n * summarize round-trip is composed by the agent (a dedicated resilient LLM call\n * under the reserved `$compact` purpose, inheriting retry/backoff — design B1),\n * so the policy never reaches the model itself.\n *\n * - `planCompaction` — PURE: given the live conversation ABOUT to fire a brain\n * call, return how many of the OLDEST turns to fold into a summary, or `0`\n * to skip. No clock, no RNG → replay re-decides identically (design D). A\n * char-length / turn-count / real deterministic-tokenizer heuristic all\n * qualify. Returning `>= turns.length` is clamped to \"fold all but keep the\n * loop alive\" by the trigger (it never folds the turn currently in flight).\n * - `payloadOf` — build the per-call prompt payload the compaction\n * `MessageLoader` reads (the turns being folded). Omit → `null` (the loader,\n * if any, reads the conversation off the agent's own state). Opaque to the\n * agent, exactly like the brain call's `payloadOf`.\n */\nexport interface CompactionPolicy<R, Msg = unknown> {\n /** PURE trigger: how many OLDEST turns to fold (`0` = skip). No clock/RNG. */\n readonly planCompaction: (conversation: Conversation<R>) => number;\n /** Build the summarize call's prompt payload from the turns being folded. Omit → `null`. */\n readonly payloadOf?: (\n conversation: Conversation<R>,\n folding: number,\n ) => unknown;\n /** DI port — the SDK / message loader for the summarize call. Omit → invoke with `[]`. */\n readonly loadMessages?: MessageLoader<CompactionPurpose, Msg>;\n}\n\n/**\n * The compaction discriminant, shaped exactly like {@link\n * AgentSnapshotConfig}. Compaction is either OFF —\n * `compaction` is structurally absent and the agent never emits a `compact_run`\n * Cmd — or ON, in which case `compaction` is a {@link CompactionPolicy}. A `{\n * compaction?: never }` member (rather than a bare optional) makes the OFF case\n * load-bearing: it forbids passing `compaction` at all, so `toMachine`\n * config-derives whether the `compact_run` interpret handler is REQUIRED (ON) or\n * FORBIDDEN (OFF) — never a silent no-op handler, the same type-lie-killer\n * `AgentSnapshotConfig` uses.\n */\nexport type AgentCompactionConfig<R, Msg> =\n | { readonly compaction?: never }\n | { readonly compaction: CompactionPolicy<R, Msg> };\n\n/**\n * The \"summarize the oldest N turns\" effect Cmd — the compaction round-trip's\n * carrier. It mirrors the brain `resilient_run` Cmd's shape (a `key` + the\n * plain `LlmCall<CompactionPurpose>` input, no closures) but under the dedicated\n * `compact_run` discriminant so it routes to the compaction interpret handler, not\n * the brain one. The handler composes the resilient-call wrapper (retry/backoff) and\n * returns the re-keyed `compact_ok` / `compact_err` settle for re-entry.\n */\nexport type AgentCompactRunCmd = Cmd<typeof MsgType.CompactRun> & {\n readonly key: CompactionPurpose;\n readonly input: LlmCall<CompactionPurpose>;\n};\n\n/** The compaction round-trip success settle Msg — carries the parsed {@link CompactionSummary}. */\nexport type AgentCompactOkMsg = {\n readonly type: typeof MsgType.CompactOk;\n readonly key: CompactionPurpose;\n readonly result: LlmOk<CompactionPurpose, CompactionOutputs>;\n readonly at: number;\n};\n\n/** The compaction round-trip failure settle Msg — carries the typed {@link LlmErr}. */\nexport type AgentCompactErrMsg = {\n readonly type: typeof MsgType.CompactErr;\n readonly key: CompactionPurpose;\n readonly error: LlmErr<CompactionPurpose>;\n readonly at: number;\n};\n\n/**\n * The CONFIG-DERIVED compaction obligation on `toMachine`'s `toolInterpret`\n * — the exact twin of {@link SnapshotInterpret}.\n * Resolves on the `Compact` discriminant the compaction overload of\n * `createAgent` fixes:\n *\n * - compaction ON → a REQUIRED `compact_run` handler\n * (`Interpret<M, AgentCompactRunCmd, Ctx>`). The summarize round-trip MUST be\n * wired — the agent never defaults it to a no-op.\n * - compaction OFF → `{ compact_run?: never }`. The handler is FORBIDDEN: with no\n * policy the agent never emits a `compact_run` Cmd, so wiring it would be\n * dead code. The consumer cannot even mention `compact_run`.\n *\n * Same type-lie-killer as the snapshot derivation: the obligation is present\n * EXACTLY when the Cmd can fire, never as a silent gap the agent backfills.\n */\nexport type CompactInterpret<\n M extends { type: string },\n Compact extends boolean,\n Ctx,\n> = Compact extends true\n ? Interpret<M, AgentCompactRunCmd, Ctx>\n : { readonly compact_run?: never };\n","/**\n * @demlik/tea/agent — the closure-free PURE reducer helpers.\n *\n * NOT part of the public `./agent` barrel: these are the reducer core's pure\n * conversation / state operations, factored OUT of the `createAgent` closure so\n * the factory module holds only the verbs that genuinely close over the composed\n * bricks (`run` / `llm` / `fan` / `compactRc` / `config`). Each function here is\n * pure and generic over the same `Stage / P / O / R` params the closure fixes,\n * so the call sites inside `createAgent` read identically (TS infers the params\n * from the state argument). The barrel `index.ts` never re-exports this file, so\n * everything stays internal.\n */\n\nimport type { LlmRunCmd } from \"../internal/llm-call\";\nimport { MsgType } from \"../protocol\";\nimport type { AgentCompactRunCmd, CompactionPurpose } from \"./compaction\";\nimport { COMPACTION_PURPOSE } from \"./compaction\";\nimport type {\n AgentState,\n AgentTurn,\n Awaiting,\n Conversation,\n ToolCall,\n} from \"./types\";\n\n/** The narrowed `awaiting` variant for a given `kind`. */\nexport type AwaitingOf<K extends Awaiting[\"kind\"]> = Extract<\n Awaiting,\n { kind: K }\n>;\n\n/** A fresh conversation entering the agentic loop — awaiting the first brain call. */\nexport function freshConversation<R>(): Conversation<R> {\n return {\n turns: [],\n toolRecords: [],\n turnCount: 0,\n awaiting: { kind: \"llm\" },\n };\n}\n\n/**\n * Collapse a turn's tool calls to one per `callId` (first occurrence wins).\n * `callId` is the fan-out identity (`idOf`); duplicates in one batch are a\n * model defect that, un-deduped, would double-execute the tool and wedge the\n * batch (one settle Msg cannot close two same-id `running` entries). PURE —\n * preserves order, allocates no Error.\n */\nexport function dedupeByCallId(\n calls: readonly ToolCall[],\n): readonly ToolCall[] {\n const seen = new Set<string>();\n const out: ToolCall[] = [];\n for (const call of calls) {\n if (seen.has(call.callId)) continue;\n seen.add(call.callId);\n out.push(call);\n }\n return out;\n}\n\n/**\n * Fold the oldest `folding` turns of a conversation into a single synthetic\n * `summaryTurn` (#85, design A1) — PURE. The summary becomes the new head turn\n * (index 0); the surviving turns (`turns.slice(folding)`) follow. Every tool\n * record whose producing turn was folded (`turn < folding`) is DROPPED; each\n * survivor's `turn` is RE-INDEXED by `-folding + 1` so it still equals the new\n * index in `turns` of its producing turn (the summary occupies one slot where\n * `folding` turns stood, so survivors shift left by `folding` then right by 1).\n * `turnCount` is UNCHANGED — compaction is not a model round-trip (decision C).\n *\n * Caller guarantees `2 <= folding <= turns.length` (the trigger clamps + skips\n * `< 2`), so the result is strictly shorter (`length - folding + 1`).\n */\nexport function foldSummary<R>(\n conv: Conversation<R>,\n folding: number,\n summaryTurn: AgentTurn,\n): Conversation<R> {\n const shift = folding - 1; // survivors move left by this many slots.\n const survivingTurns = conv.turns.slice(folding);\n const survivingRecords = conv.toolRecords\n .filter((rec) => rec.turn >= folding)\n .map((rec) => ({ ...rec, turn: rec.turn - shift }));\n return {\n ...conv,\n turns: [summaryTurn, ...survivingTurns],\n toolRecords: survivingRecords,\n awaiting: { kind: \"llm\" },\n };\n}\n\n/** The current pipeline stage value (`undefined` for a single-shot run). */\nexport function currentStage<\n Stage,\n P extends string,\n O extends Record<P, unknown>,\n R,\n>(s: AgentState<Stage, P, O, R>): Stage | undefined {\n return s.run.stepStates.find((i) => i.status === \"running\")?.input;\n}\n\n/**\n * True iff the run is in a terminal state (monitored-run done/failed/cancelled,\n * or agent failure). Every verb gates on this, so `cancelled` belonging here is\n * what makes an abort stop the loop: past it, a settling tool or brain call\n * folds to a no-op and emits nothing.\n */\nexport function isSettled<\n Stage,\n P extends string,\n O extends Record<P, unknown>,\n R,\n>(s: AgentState<Stage, P, O, R>): boolean {\n return (\n s.run.phase === \"done\" ||\n s.run.phase === \"failed\" ||\n s.run.phase === \"cancelled\" ||\n s.failure !== null\n );\n}\n\n/**\n * The stale-settle guard shared by the awaiting-scoped verbs (`turn` /\n * `settleTool` / `compactOk` / `compactErr`): return the live conversation\n * ALREADY narrowed to the given `awaiting.kind`, or `null` when the verb must\n * no-op — the run is settled, there is no conversation, or it is awaiting\n * something else (a stale settle after boot / advance). Collapses the\n * `isSettled → conv === null → awaiting.kind` triple that recurred verbatim\n * across the four verbs; each caller supplies its own no-op return. PURE.\n */\nexport function requireAwaiting<\n Stage,\n P extends string,\n O extends Record<P, unknown>,\n R,\n K extends Awaiting[\"kind\"],\n>(\n s: AgentState<Stage, P, O, R>,\n kind: K,\n): (Conversation<R> & { readonly awaiting: AwaitingOf<K> }) | null {\n if (isSettled(s)) return null;\n const conv = s.conversation;\n if (conv === null || conv.awaiting.kind !== kind) return null;\n return conv as Conversation<R> & { readonly awaiting: AwaitingOf<K> };\n}\n\n/** Re-key a composed compaction `resilient_run` Cmd to the dedicated `compact_run`. */\nexport function toCompactRunCmd(\n cmd: LlmRunCmd<CompactionPurpose>,\n): AgentCompactRunCmd {\n return {\n type: MsgType.CompactRun,\n key: COMPACTION_PURPOSE,\n input: cmd.input,\n };\n}\n","/**\n * @demlik/tea/agent — the wired-machine surface.\n *\n * The Cmd / Msg vocabulary the agent speaks, the handle interface `createAgent`\n * returns (`AgentKnob` / `AgentToMachine`), the do↔agent boot port, the\n * semantic lifecycle event stream + its projector (`agentEvents`), and the two\n * pure wiring helpers `mergeInterpret` / `liftAgent`. The reducer core (the\n * `createAgent` factory that implements this surface) lives in `./index`.\n */\n\nimport type { Cmd, Interpret, Machine, Subscribe } from \"../index\";\nimport type { MonitoredRunCmd } from \"../internal/flow/monitored-run\";\nimport type {\n LlmCall,\n LlmFailMsg,\n LlmOk,\n LlmRunCmd,\n LlmSucceedMsg,\n LlmTimerMsg,\n} from \"../internal/llm-call\";\nimport type {\n DeadlineSub,\n DeadlinesSub,\n} from \"../internal/resilience/deadline\";\nimport type { RunCmdDef } from \"../internal/resilience/resilient-call\";\nimport { MsgType } from \"../protocol\";\nimport type {\n AgentCompactErrMsg,\n AgentCompactOkMsg,\n AgentCompactRunCmd,\n CompactInterpret,\n} from \"./compaction\";\nimport type {\n AnyToolDef,\n ToolRouter,\n ToolsCtx,\n WiredToolCmd,\n WiredToolMsg,\n} from \"./tool\";\nimport type { AgentState, AgentTurn, ToolFailure } from \"./types\";\n\n// ===========================================================================\n// Cmds + Msgs the agent speaks. Generic over the composed wrappers' shapes.\n// ===========================================================================\n\n/** The brain-call effect Cmd, inherited from `../llm-call`. */\nexport type AgentLlmRunCmd<P extends string> = LlmRunCmd<P>;\n\n/**\n * The Cmd union the agent emits, as a CLOSED discriminated union (precise `TC`,\n * not the open `Cmd`) so `Interpret<M, AgentCmd<P, TC>, Ctx>` maps each key\n * precisely and `toMachine` merges the interpret halves with no laundering cast:\n *\n * - `AgentLlmRunCmd<P>` — the brain-call run Cmd (`resilient_run`), folded\n * by the wired `brainHandlers` handler.\n * - `MonitoredRunCmd<unknown>` — the durable checkpoint write the monitored-run\n * slice emits, present in the union ONLY when\n * checkpointing is on (`Snap = true`). With\n * checkpointing off the monitored-run slice never\n * emits a `snapshot_write` Cmd, so it is config-derived\n * OUT of the emitted set — the consumer is never asked\n * to interpret a Cmd that can never fire.\n * - `TC` — the consumer's per-tool effect, mapped to the\n * consumer's own tool interpret handler.\n *\n * `Snap` defaults to `true` so the verb-internal usage (which forwards whatever\n * monitored-run emits) and the published type stay a safe superset; the wired\n * machine `toMachine` returns is parametrized on the overload-fixed `Snap` so its\n * Cmd set is exact (`MonitoredRunCmd` present only when checkpointing is on).\n */\nexport type AgentCmd<\n P extends string,\n TC extends Cmd = Cmd,\n Snap extends boolean = true,\n Compact extends boolean = true,\n> =\n | AgentLlmRunCmd<P>\n | (Snap extends true ? MonitoredRunCmd<unknown> : never)\n | (Compact extends true ? AgentCompactRunCmd : never)\n | TC;\n\n/**\n * The CONFIG-DERIVED snapshot obligation on `toMachine`'s `toolInterpret`.\n * Resolves on the `Snap` discriminant the snapshotting overload of `createAgent`\n * fixes (`true` checkpointing-on / `false` off):\n *\n * - checkpointing ON → a REQUIRED `snapshot_write` handler\n * (`Interpret<M, MonitoredRunCmd<unknown>, Ctx>`). A real checkpoint write\n * MUST be wired — the agent never defaults it to a no-op.\n * - checkpointing OFF → `{ snapshot_write?: never }`. The handler is FORBIDDEN:\n * the Cmd is config-derived out of the emitted set, so wiring it would be\n * dead code. The consumer cannot even mention `snapshot_write`.\n *\n * This is the type that kills the `snapshot_write: async () => undefined`\n * ceremony: the obligation is present in the contract EXACTLY when the Cmd can\n * fire, never as a silent gap the agent backfills.\n */\nexport type SnapshotInterpret<\n M extends { type: string },\n Snap extends boolean,\n Ctx,\n> = Snap extends true\n ? Interpret<M, MonitoredRunCmd<unknown>, Ctx>\n : { readonly snapshot_write?: never };\n\n/**\n * The `toMachine` signature. It returns a `Wired`: the machine and, beside it,\n * the merged `interpret` table and the `deadline` runner its one Sub needs — a\n * machine carries no handlers (#278, #279), so it is run as\n * `run(wired.machine, { ...wired, ctx })`. Parametrized on the `Snap` + `Compact` discriminants\n * so the snapshotting / compaction overloads of `createAgent` hand back the right\n * obligations. The `toolInterpret` requires (ON) or forbids (OFF) the\n * `snapshot_write` handler via {@link SnapshotInterpret} and the `compact_run` handler\n * via {@link CompactInterpret}, and the machine's Cmd type is the config-derived\n * `AgentCmd<P, TC, Snap, Compact>`.\n *\n * `tools` is a `toolRouter`: its handlers are merged in, its settled\n * `<name>_ok` / `<name>_err` Msgs join the machine's `M` and fold into the\n * conversation, and its Cmds leave the `toolInterpret` obligation — a consumer\n * whose `toolOf` is the router's supplies only the snapshot / compaction handlers.\n * With no router (`T = never`) every type here reads exactly as before.\n */\nexport type AgentToMachine<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd,\n Snap extends boolean,\n Compact extends boolean,\n> = <Ctx = object, T extends AnyToolDef = never>(opts?: {\n readonly tools?: ToolRouter<T>;\n readonly toolInterpret?: Interpret<\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n Exclude<TC, WiredToolCmd<T>>,\n Ctx\n > &\n SnapshotInterpret<AgentMachineMsg<P, O, R> | WiredToolMsg<T>, Snap, Ctx> &\n CompactInterpret<AgentMachineMsg<P, O, R> | WiredToolMsg<T>, Compact, Ctx>;\n}) => {\n readonly machine: Machine<\n AgentState<Stage, P, O, R>,\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n AgentCmd<P, TC, Snap, Compact>,\n DeadlinesSub,\n Ctx & ToolsCtx<T>\n >;\n readonly interpret: Interpret<\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n AgentCmd<P, TC, Snap, Compact>,\n Ctx & ToolsCtx<T>\n >;\n readonly subscribe: Subscribe<\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n DeadlinesSub,\n Ctx & ToolsCtx<T>\n >;\n};\n\n/**\n * The agent handle `createAgent` returns — the uniform verb contract every tea\n * composition exposes, plus the wired `toMachine` and `brainInterpret`, the\n * brain call's handler for a consumer wiring the verbs by hand. `Snap` flows\n * ONLY into `toMachine`'s `toolInterpret` obligation\n * (the snapshot derivation); every verb is snapshot-agnostic. The model\n * message shape `Msg` does not appear on the handle's surface (it is internal to the\n * brain call's loader), so it is not a type parameter here — only `createAgent`\n * carries it, to thread the config's `loadMessages` / `model` ports.\n */\nexport interface AgentKnob<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd,\n Snap extends boolean,\n Compact extends boolean,\n> {\n readonly init: () => AgentState<Stage, P, O, R>;\n readonly start: AgentVerb1<Stage, P, O, R, TC, [runId: string, at: number]>;\n readonly turn: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [result: AgentTurn, at: number]\n >;\n readonly toolOk: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [callId: string, result: R, at: number]\n >;\n /**\n * A bare `reason` string still works and settles an untagged failure — the\n * hand-wired shape this verb has always had. Hand it a whole `ToolFailure`\n * instead to keep the `{ _tag, …payload }` beside that reason, which is what\n * `onToolError` and any host code discriminating on `_tag` then read (#115).\n */\n readonly toolErr: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [callId: string, failure: string | ToolFailure, at: number]\n >;\n readonly succeed: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [msg: AgentLlmOkMsg<P, O>, at: number]\n >;\n readonly fail: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [msg: AgentLlmErrMsg<P>, at: number]\n >;\n readonly compactOk: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [key: string, msg: AgentCompactOkMsg, at: number]\n >;\n readonly compactErr: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [key: string, msg: AgentCompactErrMsg, at: number]\n >;\n readonly onTimer: AgentVerb1<Stage, P, O, R, TC, [msg: AgentTimerMsg]>;\n readonly boot: AgentVerb1<Stage, P, O, R, TC, [at: number]>;\n readonly isSettled: (s: AgentState<Stage, P, O, R>) => boolean;\n readonly currentStage: (s: AgentState<Stage, P, O, R>) => Stage | undefined;\n readonly brainCall: (s: AgentState<Stage, P, O, R>) => LlmCall<P>;\n readonly subs: (s: AgentState<Stage, P, O, R>) => readonly DeadlineSub[];\n readonly toMachine: AgentToMachine<Stage, P, O, R, TC, Snap, Compact>;\n /**\n * The brain call's `resilient_run` handler — the one `toMachine` wires. Its\n * Cmd is `Cmd.define`d, so it returns an outcome and the engine mints the\n * `resilient_run_ok` / `resilient_run_err` Msg that `succeed` / `fail` fold\n * (ADR 0021). List `AgentKnob`'s brain Cmd def in `cmds` when you hand-wire.\n */\n readonly brainInterpret: () => Interpret<\n AgentLlmOkMsg<P, O> | AgentLlmErrMsg<P>,\n AgentLlmRunCmd<P>,\n unknown\n >;\n /** The brain call's `Cmd.define`d run Cmd def — list it in `cmds` when you hand-wire. */\n readonly brain: RunCmdDef<LlmCall<P>, LlmOk<P, O>>;\n}\n\n/** A verb taking the state + `Args`, returning the agent's `[State, Cmd[]]` tuple. */\ntype AgentVerb1<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd,\n Args extends readonly unknown[],\n> = (\n s: AgentState<Stage, P, O, R>,\n ...args: Args\n) => readonly [AgentState<Stage, P, O, R>, readonly AgentCmd<P, TC>[]];\n\n/** The brain-call SUCCESS settle Msg, inherited from `../llm-call`. */\nexport type AgentLlmOkMsg<\n P extends string,\n O extends Record<P, unknown>,\n> = LlmSucceedMsg<P, O>;\n/**\n * The brain-call FAILURE settle Msg, inherited from `../llm-call` — the engine\n * 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\n * ending the run.\n */\nexport type AgentLlmErrMsg<P extends string> = LlmFailMsg<P>;\n\n/**\n * The timer Msg (retry + safety deadline) — `DeadlineExceeded`, the shared\n * shape of both composed wrappers' timer Msgs (`LlmTimerMsg` and `MonitoredRunTimerMsg`\n * are both `DeadlineExceeded`). One Msg variant covers both timers; `onTimer`\n * disambiguates by deadline id. This is also the machine Msg the\n * `subscribeDeadline` runner dispatches directly (no wrapping), matching the\n * sibling gold standard.\n */\nexport type AgentTimerMsg = LlmTimerMsg;\n\n// ===========================================================================\n// AgentBootPort — the typed do↔agent boot seam.\n// ===========================================================================\n//\n// A run that rehydrated mid-loop must re-fire its one outstanding effect on\n// activation. `do/host`'s `autoBoot` is the firing side; this agent reducer's\n// `boot` verb is the receiving side. The coupling used to be a RAW string:\n// host built `{ type: \"agent_boot\", at }` by hand and the agent string-matched\n// it — a literal duplicated across the seam with nothing tying the two ends.\n//\n// `AgentBootPort` promotes that coupling to a typed contract OWNED by the agent\n// (which owns the boot Msg shape): the `AgentBootMsg` type and the\n// `agentBootMsg` constructor. `do/host` imports the constructor instead of\n// hand-writing the literal. Adding a field to boot (or renaming it) is now a\n// one-file change here with the constructor's signature flagging every caller,\n// not a silent cross-module string drift.\n\n/** The Msg `do/host`'s `autoBoot` fires to re-enter the agent's `boot` verb on rehydrate. */\nexport type AgentBootMsg = {\n readonly type: typeof MsgType.AgentBoot;\n readonly at: number;\n};\n\n/**\n * The do↔agent boot port: construct the `agent_boot` Msg `autoBoot` dispatches\n * on a resumable rehydrate. The agent owns this constructor so the boot Msg\n * shape lives in ONE place — the host fires it through here, never as a raw\n * `{ type: \"agent_boot\" }` literal.\n */\nexport function agentBootMsg(at: number): AgentBootMsg {\n return { type: MsgType.AgentBoot, at };\n}\n\n/**\n * The Msg an aborted `AbortSignal` fires to settle the run `cancelled`. Owned\n * here beside the boot Msg for the same reason: the cancel seam lives on the\n * drive (`driveToDone`'s `cancel`, the lid's `signal`), which is a different\n * module from the reducer that folds it, so the shape gets ONE home and a\n * constructor rather than a literal duplicated across the seam.\n */\nexport type AgentCancelMsg = {\n readonly type: typeof MsgType.AgentCancel;\n readonly at: number;\n};\n\n/** Construct the `agent_cancel` Msg an abort dispatches. `at` stamps the outcome. */\nexport function agentCancelMsg(at: number): AgentCancelMsg {\n return { type: MsgType.AgentCancel, at };\n}\n\n// ===========================================================================\n// The machine Msg union — the closed set of verb entry points `toMachine` wires.\n// ===========================================================================\n\n/**\n * The agent machine's Msg union — one variant per reducer entry point. A\n * consumer using `toMachine` dispatches `agent_start` to begin and `agent_tool_ok`\n * / `agent_tool_err` to route settled tools back; the brain-call settle Msgs\n * (`resilient_run_ok` / `resilient_run_err`) are minted by the engine from the\n * outcome the FIXED `brainHandlers` returns (ADR 0021), driving `succeed` /\n * `fail`. Time enters via `at` on every variant — the\n * reducer never reads the clock.\n *\n * There is deliberately NO `agent_turn` variant here. The wired loop folds a\n * model turn INSIDE `succeed` from the minted `resilient_run_ok` — a single\n * settle Msg advances both the retry slice and the conversation (the L3 fix).\n * Exposing `agent_turn` as a dispatchable Msg re-opened the stuck-`running` bug:\n * a hand-fed turn folds the conversation without ever settling `resilient_run_ok`,\n * so `succeed` never runs and the resilient slice stays `running`. The\n * `turn` verb remains on the handle for the consumer that wires the verbs by hand\n * (manual wiring), but it is not part of the one wired machine's Msg surface.\n */\nexport type AgentMachineMsg<P extends string, O extends Record<P, unknown>, R> =\n | {\n readonly type: typeof MsgType.AgentStart;\n readonly runId: string;\n readonly at: number;\n }\n | {\n readonly type: typeof MsgType.AgentToolOk;\n readonly callId: string;\n readonly result: R;\n readonly at: number;\n }\n | {\n readonly type: typeof MsgType.AgentToolErr;\n readonly callId: string;\n readonly reason: string;\n readonly at: number;\n }\n // The brain-call settle Msgs the engine mints from `brainHandlers`' outcome\n // (ADR 0021) — `resilient_run_ok` runs `succeed` (reset retry + fold the\n // turn), `resilient_run_err` runs `fail` (back off via retry). This is the\n // inherited llm-call settle shape.\n | AgentLlmOkMsg<P, O>\n | AgentLlmErrMsg<P>\n // The compaction settle Msgs RE-ENTER from the compaction interpret handler\n // — `compact_ok` folds the summary back (drops the oldest N turns +\n // their tool records, then fires the next brain call), `compact_err` backs off\n // via the compaction slice's retry or — on exhaustion — proceeds without\n // compacting (errors are data). Dedicated discriminants, re-keyed off the\n // composed resilient settle at the handler boundary.\n | AgentCompactOkMsg\n | AgentCompactErrMsg\n // The timer Msg is `DeadlineExceeded` itself (not wrapped) so the\n // `subscribeDeadline` runner dispatches it straight into `update`, exactly as\n // the resilient-call / llm-call / monitored-run gold standards wire it.\n | AgentTimerMsg\n | AgentBootMsg\n // The outside-in stop. Unlike every other variant here it is dispatched by the\n // DRIVE rather than re-entered from a handler — an abort is the one transition\n // whose cause is not the machine's own work settling.\n | AgentCancelMsg;\n\n// ===========================================================================\n// AgentEvent — the SEMANTIC lifecycle event stream.\n// ===========================================================================\n\n/**\n * The agent's PUBLIC lifecycle events — the semantic stream a consumer\n * subscribes to via `runtime.on(type, …)`. This is the seam that\n * DECOUPLES observability/SSE code from the agent's PRIVATE retry/loop Msg\n * vocabulary: where the old code switched on `resilient_ok` / `agent_tool_ok`\n * (the inherited resilient-call / tool-fan-out plumbing) off the raw `observe`\n * firehose, a consumer now folds these named events. The private Msg names live\n * ONLY inside `agentEvents` (the projector) — they appear nowhere in this union\n * or any exported type, so a UI built on `TurnSettled` does not break the day\n * the retry plumbing is renamed.\n *\n * - `TurnSettled` — a brain turn settled (the model produced an `AgentTurn`).\n * Projected off the private `resilient_run_ok` settle Msg; carries the parsed\n * `turn` (the narration + tool calls the model asked for).\n * - `ToolSettled` — a tool call settled OK. Projected off the private\n * `agent_tool_ok` Msg; carries the `callId` and the tool `result`.\n * - `RunDone` — the run finished. Projected off the post-transition State\n * reaching `run.phase === \"done\"`; carries the run's `output` (the terminal\n * model turn, or `null`) — the same first-class result `Runtime.result()`\n * reads (#46), surfaced as an event for the streaming consumer.\n */\nexport type AgentEvent<R> =\n | { readonly type: \"TurnSettled\"; readonly turn: AgentTurn }\n | {\n readonly type: \"ToolSettled\";\n readonly callId: string;\n readonly result: R;\n }\n | { readonly type: \"RunDone\"; readonly output: AgentTurn | null };\n\n/**\n * Project one APPLIED agent transition `(msg, state)` to its semantic\n * {@link AgentEvent}s — the `events` projector a consumer passes to\n * `run(machine, { events: agentEvents() })` to light up `runtime.on(...)`.\n *\n * This is the ONE place the agent's PRIVATE Msg names are read: it maps\n * `resilient_run_ok` → `TurnSettled` and `agent_tool_ok` → `ToolSettled`, and reads\n * the post-transition `run.phase` for `RunDone`. The mapping is total over the\n * Msg union (a `default`-free switch on the discriminant) and returns `[]` for\n * the transitions that carry no public event (start / boot / timer / the error\n * arms), so a private name never escapes into `AgentEvent`.\n *\n * A single transition may emit more than one event: the brain turn that retires\n * the final stage settles a turn (`TurnSettled`) AND finishes the run\n * (`RunDone`) — both are projected from that one `resilient_run_ok` transition.\n * `RunDone` is gated on `run.phase === \"done\"`, which the wired loop reaches\n * exactly once (the agent is terminal there and dispatches no further\n * transition), so the event fires once per run.\n *\n * A `ToolSettled` is gated on `state.refusedCalls` (#145): a call whose public\n * outcome was already a failure — the ladder's `timeout` / `retry_exhausted`,\n * or the tool's own error — never emits a success here, however late its\n * abandoned attempt resolves. Both settle arms read the same list, so a\n * router-wired agent and a fan-out-wired one are silent on the same calls, and\n * the decision is made in the PURE layer rather than filtered at a\n * subscription seam — `runtime.on` and `defineAgent`'s `onEvent` see one\n * stream.\n *\n * A machine wired with `toMachine({ tools })` settles tools through the\n * router's `<name>_ok` Msgs instead of `agent_tool_ok`; pass the same router\n * here so those settles project to `ToolSettled` too.\n *\n * PURE — reads only the passed `(msg, state)`; no clock, no RNG, no throw.\n *\n * @typeParam P Brain-call purposes.\n * @typeParam O Per-purpose outputs (bound to `AgentTurn`, the agentic shape).\n * @typeParam R Tool result type.\n * @typeParam Stage Pipeline stage type.\n * @typeParam T The router's tool defs, when one is wired.\n */\nexport function agentEvents<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n T extends AnyToolDef = never,\n>(opts?: {\n readonly tools?: ToolRouter<T>;\n}): (\n msg: AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n state: AgentState<Stage, P, O, R>,\n) => readonly AgentEvent<R>[] {\n const tools = opts?.tools;\n return (msg, state) => {\n const events: AgentEvent<R>[] = [];\n // A cancelled run's public channel is CLOSED. The fold already ignores what\n // arrives after the stop (`isSettled`), but this projector is Msg-shaped:\n // without this gate a tool handler that was in flight when the abort landed\n // would still push its `ToolSettled` to a listener whose run is over. Same\n // reasoning as `refusedCalls` (#145), one phase up — there the discriminator\n // is per call, here the whole run is the answer.\n if (state.run.phase === \"cancelled\") return events;\n // A call the ladder already settled is silent on EVERY public channel: the\n // fan-out drops its late value, and `state.refusedCalls` is what lets this\n // projector drop the matching event (#145). The `??` is the same\n // rehydration guard the reducer's own reader carries.\n const refused = new Set(state.refusedCalls ?? []);\n const routed = tools === undefined ? null : tools.outcomeOf(msg);\n if (routed !== null) {\n // A router-settled tool: its `_ok` is the public ToolSettled, its `_err`\n // stays silent like `agent_tool_err`. The router's `R` is the machine's.\n if (routed.outcome.kind === \"ok\" && !refused.has(routed.callId)) {\n events.push({\n type: \"ToolSettled\",\n callId: routed.callId,\n result: routed.outcome.result as R,\n });\n }\n } else {\n projectOwn(msg as AgentMachineMsg<P, O, R>, events, refused);\n }\n // RunDone is a STATE-shaped event (the run's terminal output, #46), not a\n // Msg-shaped one: the transition that lands `done` is the final brain turn\n // (which also emits TurnSettled above). Gate on the post-transition phase so\n // the same projector reports both.\n if (state.run.phase === \"done\") {\n events.push({ type: \"RunDone\", output: state.output });\n }\n return events;\n };\n}\n\n// The agent's own Msg union, projected exhaustively. A Msg the router did not\n// claim is one of these: `WiredToolMsg<T>` and `AgentMachineMsg` are disjoint on\n// `type`, which the cast at the one call site records.\nfunction projectOwn<P extends string, O extends Record<P, AgentTurn>, R>(\n msg: AgentMachineMsg<P, O, R>,\n events: AgentEvent<R>[],\n refused: ReadonlySet<string>,\n): void {\n switch (msg.type) {\n case MsgType.ResilientOk:\n // The PRIVATE brain-call settle Msg → the public TurnSettled. Its\n // `value.output` is the parsed `AgentTurn` (the `O extends Record<P,\n // AgentTurn>` bound pins every purpose's output to an `AgentTurn`, the\n // same reasoning `state.output` relies on, #46/#48).\n events.push({ type: \"TurnSettled\", turn: msg.value.output });\n break;\n case MsgType.AgentToolOk:\n // The PRIVATE tool-fan-out settle Msg → the public ToolSettled, unless\n // this `callId` already ended in a failure the model was told about: then\n // this is the abandoned attempt resolving late, and it is refused (#145).\n if (!refused.has(msg.callId)) {\n events.push({\n type: \"ToolSettled\",\n callId: msg.callId,\n result: msg.result,\n });\n }\n break;\n // start / boot / cancel / timer / the *_err arms / the compaction settles\n // carry no public event. (No `default`: the switch is exhaustive over the Msg\n // discriminant, so a new Msg variant forces a decision here at compile\n // time.) Compaction is an internal optimization, not a semantic lifecycle\n // moment a UI folds — its settles are deliberately silent here. Cancel is\n // silent for a stronger reason: the run the caller stopped owes the public\n // channel nothing after the stop, so a `RunCancelled` would be one more\n // late thing to have to ignore.\n case MsgType.AgentStart:\n case MsgType.AgentCancel:\n case MsgType.AgentToolErr:\n case MsgType.ResilientErr:\n case MsgType.CompactOk:\n case MsgType.CompactErr:\n case \"deadline_exceeded\":\n case MsgType.AgentBoot:\n break;\n }\n}\n\n/**\n * Join two `Interpret` dictionaries over DISJOINT Cmd subsets `A` and `B` (over\n * the same Msg union `M` and Ctx) into the full `Interpret<M, A | B, Ctx>`. The\n * agent uses it to merge the consumer's per-tool / snapshot interpret (`A`) with\n * the agent-owned brain-call handler (`B = AgentLlmRunCmd`) into the wired\n * machine's single interpret table.\n *\n * The runtime result is exactly the spread of the two key-disjoint records. The\n * single `as` is a SOUND mapped-type identity, not a laundering cast: `Interpret`\n * is a homomorphic mapped type keyed by `Cmd[\"type\"]`, so\n * `Interpret<M, A, Ctx> & Interpret<M, B, Ctx>` IS `Interpret<M, A | B, Ctx>`\n * (`(A | B)[\"type\"] = A[\"type\"] | B[\"type\"]`). TypeScript does not reduce that\n * intersection of two GENERIC mapped types on its own, so the equality is\n * asserted ONCE here — preserving `M` and `Ctx` exactly — rather than smuggled\n * through `as unknown as Interpret<...>` at every wiring site. Pure.\n */\nexport function mergeInterpret<\n M extends { type: string },\n A extends Cmd,\n B extends Cmd,\n Ctx,\n>(\n a: Interpret<M, A, Ctx> | undefined,\n b: Interpret<M, B, Ctx>,\n): Interpret<M, A | B, Ctx> {\n return { ...(a ?? {}), ...b } as Interpret<M, A | B, Ctx>;\n}\n\n/**\n * Lift an agent result `[slice, cmds]` into a host `[State, cmds]` where the slice\n * lives at `state.agent`. Convenience for a host that nests the agent slice\n * under a named field; the single-slice host uses the verbs' tuple directly.\n * PURE — a thin record rebuild, no clock / RNG.\n */\nexport function liftAgent<\n S extends { agent: AgentState<Stage, P, O, R> },\n Stage,\n P extends string,\n O extends Record<P, unknown>,\n R,\n C extends Cmd,\n>(\n state: S,\n [slice, cmds]: readonly [AgentState<Stage, P, O, R>, readonly C[]],\n): readonly [S, readonly C[]] {\n return [{ ...state, agent: slice }, cmds];\n}\n","/**\n * @demlik/tea/agent — the model ports and the brain call's Promise handler.\n *\n * `../internal/llm-call` is pure: it owns the brain call's slice, its\n * `Cmd.define`d run Cmd and the parse that turns a model's answer into that\n * Cmd's outcome, and it ships no engine code (ADR 0021). The agent is a Promise\n * host — `toMachine` hands its caller an `interpret` table and `defineAgent`\n * runs itself — so the one handler that actually invokes the model lives here:\n * the two DI ports (`model`, `loadMessages`) and {@link brainHandler}, which\n * calls them and returns the outcome `llm.decode` builds.\n */\n\nimport type { Outcome } from \"../index\";\nimport type {\n createLlmCall,\n LlmCall,\n LlmOk,\n LlmRejected,\n LlmRunCmd,\n Schema,\n} from \"../internal/llm-call\";\n\n/**\n * The minimal chat-model contract every model the handler talks to must\n * satisfy — the seed's `InjectableChatModel`, trimmed to the one operation\n * the brain call drives for brain-only stages:\n *\n * `withStructuredOutput(schema)` → a runnable whose `invoke(messages)`\n * resolves to a typed object matching `schema`.\n *\n * `BaseChatModel` from `@langchain/core` is the runtime type; this surface\n * names only what the handler calls so a test fake can ignore the rest. Generic\n * over the message shape `Msg` so a consumer's loader and model agree on it\n * without the agent inspecting messages.\n */\nexport interface Llm<Msg> {\n withStructuredOutput<T>(schema: Schema<T>): {\n invoke(messages: readonly Msg[]): Promise<T>;\n };\n}\n\n/**\n * Build the `Msg[]` the handler hands to the bound model for a given call. The\n * SDK / message-assembly seam — the seed's `buildBaseMessages` + the lazy\n * `loadMessages` loader rolled into one injected port. Async because the seed\n * lazy-imports the SDK (a top-level `import type` of the langchain messages\n * package explodes the workers test runner). Receives the full `LlmCall` so it\n * can branch on `purpose` exactly as the seed's `buildBaseMessages` did.\n */\nexport type MessageLoader<P extends string, Msg> = (\n call: LlmCall<P>,\n) => Promise<readonly Msg[]>;\n\n/**\n * The model factory — the first DI port. `(modelId) => Llm`. Tests pass a fake\n * builder; production wires `createChatModel(env, getModelConfig(id))`. `null`\n * means \"the host's default model\" (the seed's `string | null`).\n */\nexport type ModelFactory<Msg> = (modelId: string | null) => Llm<Msg>;\n\n/**\n * The plain-function model port — the common path. One async function\n * from the assembled messages to the model's answer; the handler validates the\n * answer through the purpose's `Schema` exactly as it re-validates the\n * structured-output path, so a malformed answer is a `resilient_run_err`, never\n * a corrupt success. `ModelFactory` → `withStructuredOutput(schema).invoke(...)`\n * stays the advanced form for a model that binds the schema itself.\n *\n * `T` is the answer type the schema narrows to — for the agent, an `AgentTurn`.\n */\nexport type PlainModel<Msg, T = unknown> = (\n messages: readonly Msg[],\n) => Promise<T>;\n\n/**\n * Either model port. A bare `async` function is read as a `PlainModel` (see\n * {@link asModelFactory}); a sync function is the factory.\n */\nexport type ModelPort<Msg, T = unknown> =\n | ModelFactory<Msg>\n | PlainModel<Msg, T>;\n\n/**\n * Lift a plain-function model into the `ModelFactory` port. The factory ignores\n * `modelId` (the function IS the model) and its `Llm` runs the bound schema over\n * the function's answer, so both ports meet the handler as one shape.\n *\n * Reach for this explicitly when the function is not declared `async` — a sync\n * function that returns a promise (`(m) => client.chat(m)`) carries no runtime\n * mark that tells it apart from a factory. Passed bare, `asModelFactory`\n * refuses it on the first call with an `LlmErr` whose reason is\n * {@link PLAIN_MODEL_MISROUTE_REASON}.\n */\nexport function plainModel<Msg, T>(fn: PlainModel<Msg, T>): ModelFactory<Msg> {\n return () => ({\n withStructuredOutput<U>(schema: Schema<U>) {\n return {\n invoke: async (messages: readonly Msg[]): Promise<U> =>\n schema.parse(await fn(messages)),\n };\n },\n });\n}\n\n/**\n * Narrow a `ModelPort` to its plain-function member. The two ports are both\n * unary functions, so the only runtime mark that separates them is the\n * `AsyncFunction` tag an `async` declaration carries — a factory is never\n * `async` (its `Llm` is read synchronously). A promise-returning sync function\n * goes through {@link plainModel} instead.\n */\nexport function isPlainModel<Msg, T>(\n model: ModelPort<Msg, T>,\n): model is PlainModel<Msg, T> {\n return Object.prototype.toString.call(model) === \"[object AsyncFunction]\";\n}\n\n/**\n * The reason an `LlmErr` carries when a sync promise-returning function was\n * passed as `model` bare — the one runtime shape neither port can own.\n */\nexport const PLAIN_MODEL_MISROUTE_REASON =\n \"model: a sync function returned a Promise where an Llm was expected — \" +\n \"a promise-returning model that is not declared `async` must be wrapped in \" +\n \"plainModel(fn) (see the agent's model ports)\";\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof (value as { then: unknown }).then === \"function\"\n );\n}\n\n/**\n * Resolve either model port to the factory the handler drives.\n *\n * A sync function that returns a promise (`(m) => client.chat(m)`) carries no\n * runtime mark, so it reaches here as a factory and is called with `modelId`.\n * The one thing that tells it apart is what it returns: an `Llm` is never a\n * thenable. The resolved factory refuses that answer with\n * {@link PLAIN_MODEL_MISROUTE_REASON} before anything touches\n * `.withStructuredOutput`, so the misroute surfaces as an `LlmErr` naming the\n * fix — never as a bare `TypeError` off a property that is not there.\n */\nexport function asModelFactory<Msg, T>(\n model: ModelPort<Msg, T>,\n): ModelFactory<Msg> {\n if (isPlainModel(model)) return plainModel(model);\n return (modelId) => {\n const llm = model(modelId);\n if (isThenable(llm)) {\n // The misrouted call already happened; settle its promise quietly so a\n // rejection there is not an unhandled one beside the error we do raise.\n llm.then(undefined, () => undefined);\n throw new Error(PLAIN_MODEL_MISROUTE_REASON);\n }\n return llm;\n };\n}\n\n/** What {@link brainHandler} is built from: the two ports, beside the pure knob. */\nexport interface BrainPorts<\n P extends string,\n O extends Record<P, unknown>,\n Msg,\n> {\n /** DI port 1 — `async (messages) => answer`, or the factory `(modelId) => Llm`. */\n readonly model: ModelPort<Msg, O[P]>;\n /** DI port 2 — the SDK / message loader. Omit → the model is invoked with `[]`. */\n readonly loadMessages?: MessageLoader<P, Msg>;\n}\n\n/**\n * The brain call's `resilient_run` handler: assemble the messages, bind the\n * purpose's structured-output schema, invoke the model, and return the outcome\n * `llm.decode` builds from its answer — `llm.rejected(cause)` when anything on\n * the way throws. The engine mints `resilient_run_ok` / `resilient_run_err`\n * from that outcome (ADR 0021), so the agent's `succeed` / `fail` arms drive\n * the inherited retry loop.\n *\n * `decode` re-validates the answer even on the structured-output path (a fake\n * model might skip validation, and a real provider can drift), so a malformed\n * structured response is a failure, never a corrupt success.\n */\nexport function brainHandler<\n P extends string,\n O extends Record<P, unknown>,\n Msg,\n>(\n llm: ReturnType<typeof createLlmCall<P, O>>,\n ports: BrainPorts<P, O, Msg>,\n): (cmd: LlmRunCmd<P>) => Promise<Outcome<LlmOk<P, O>, LlmRejected>> {\n const modelOf = asModelFactory(ports.model);\n return async (cmd) => {\n try {\n const model = modelOf(cmd.input.model);\n const messages = ports.loadMessages\n ? await ports.loadMessages(cmd.input)\n : [];\n const bound = model.withStructuredOutput(llm.schemaOf(cmd.input.purpose));\n return llm.decode(cmd, await bound.invoke(messages));\n } catch (cause) {\n return llm.rejected(cause);\n }\n };\n}\n","/**\n * @demlik/tea/agent — `tool()` + `toolRouter()`: declare a tool once and derive\n * what a consumer used to hand-write twice — the `toolOf` mapping from a\n * model's `ToolCall` to an effect Cmd, and the interpret handler that runs it\n * and settles it.\n *\n * A tool is a `Cmd.define`d effect whose input is the model's call —\n * `{ callId, args }` — with the handler colocated on the constructor. The\n * router folds a set of them into one `toolOf` and one interpret table; the\n * handlers settle through the minted `<name>_ok` / `<name>_err` Msgs, errors as\n * `{ _tag }` data (ADR 0011). `createAgent(...).toMachine({ tools })` folds\n * those settles into the conversation, so a consumer names nothing twice.\n */\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { describeError } from \"../describe-error\";\nimport {\n type AnyCmdDef,\n Cmd,\n type CmdDef,\n type CmdOf,\n type CmdValue,\n type ErrOf,\n type Interpret,\n type MalformedResult,\n type OkOf,\n Outcome,\n type Settled,\n type Tagged,\n type TaggedError,\n} from \"../index\";\nimport { rejectAll, unchecked } from \"../internal/schema\";\nimport { MsgType, type MsgTypeValue } from \"../protocol\";\nimport {\n cmdEdgeOf,\n detachWorkOf,\n type HandlerCtx,\n malformedResult,\n validateSync,\n} from \"../pure/core\";\nimport type {\n TaggedFailure,\n ToolCall,\n ToolResilience,\n ToolResilienceError,\n} from \"./types\";\n\n// ===========================================================================\n// Reserved names — the agent's own Msg vocabulary a tool may not mint over.\n// ===========================================================================\n\n/**\n * The prefix a protocol discriminant was minted from: `resilient_run_ok` →\n * `resilient_run`, `compact_run` → `compact`. A tool named by that prefix would\n * mint the same `<name>_ok` / `<name>_err` the agent's reducer already owns.\n */\ntype SettlePrefixOf<T extends string> = T extends\n | `${infer P}_ok`\n | `${infer P}_err`\n | `${infer P}_run`\n ? P\n : never;\n\nconst REJECTED_TYPE = \"tool_rejected\";\nconst SNAPSHOT_WRITE_TYPE = \"snapshot_write\";\n\n/**\n * A tool name `tool()` refuses. A tool's name is its Cmd `type` — so\n * its interpret key — and the prefix of its settle Msgs, so every string\n * already spoken by the protocol is taken twice over: the settle prefixes\n * (`resilient_run`, `agent_tool`, `compact`) would overwrite the agent's own\n * reducer handlers through `toMachine`'s last-wins spread, and the discriminants\n * themselves (`compact_run`, `resilient_run`, …) would shadow the interpret\n * handler of that name. `resilient` is reserved as a Cmd prefix — the part\n * before `_run` in the brain Cmd `resilient_run` — not as a settle prefix: its\n * `resilient_ok` / `resilient_err` name nothing the agent settles. Both halves\n * derive from `MsgType`: a new entry there\n * reserves its name and its prefix with no second edit. The two names outside\n * the protocol are the router's own `tool_rejected` and the checkpoint handler\n * `snapshot_write`, which `toMachine` merges under the consumer's key.\n */\nexport type ReservedToolName =\n | MsgTypeValue\n | SettlePrefixOf<MsgTypeValue>\n | typeof REJECTED_TYPE\n | typeof SNAPSHOT_WRITE_TYPE;\n\n/**\n * Widens to `unknown` for a name outside the reserved set and to `never`\n * inside it, so `Name & NotReserved<Name>` is the name itself or\n * unconstructible. A widened `string` passes here — the runtime check in\n * `tool()` is what catches a reserved name built from one.\n */\ntype NotReserved<Name extends string> = Name extends ReservedToolName\n ? never\n : unknown;\n\nconst SETTLE_SUFFIX = /_(?:ok|err|run)$/;\n\n/** The runtime mirror of `ReservedToolName`, read off the same `MsgType`. */\nconst reservedToolNames: ReadonlySet<string> = new Set<string>([\n ...Object.values(MsgType),\n ...Object.values(MsgType).flatMap((t) => {\n const suffix = SETTLE_SUFFIX.exec(t);\n return suffix === null ? [] : [t.slice(0, suffix.index)];\n }),\n REJECTED_TYPE,\n SNAPSHOT_WRITE_TYPE,\n]);\n\n/** Whether `name` is one `tool()` refuses — the set `ReservedToolName` types. */\nexport function isReservedToolName(name: string): name is ReservedToolName {\n return reservedToolNames.has(name);\n}\n\n// ===========================================================================\n// tool() — one declaration: the Cmd, its channels, and the handler.\n// ===========================================================================\n\n/**\n * The input a tool Cmd carries: the model's `callId` (the fan-out identity the\n * settle folds back on) and the `args` already parsed against the tool's\n * `input` schema — the boundary parses, the handler trusts.\n */\nexport type ToolInput<Args> = {\n readonly callId: string;\n readonly args: Args;\n};\n\n/**\n * The router-minted failure beside a tool's declared tags: the handler threw\n * (or rejected) with something that is not a declared `{ _tag }`. Plain data\n * the model sees as a reason, never a rejection out of the interpret handler.\n */\nexport type ToolThrown = { readonly _tag: \"thrown\"; readonly message: string };\n\n/**\n * The typed success constructor a handler receives: `ok(value)` with `Ok`\n * fixed to what the `ok` schema parses, so a value of the wrong shape is\n * refused where it is written.\n */\nexport type ToolOk<Ok, E extends Tagged> = (value: Ok) => Outcome<Ok, E>;\n\n/**\n * The typed failure constructor a handler receives: `fail({ _tag })` with `E`\n * fixed to the declared tags, so the literal is checked against them where it\n * is written. (A bare `{ _tag: \"x\" }` built elsewhere infers `_tag: string`\n * and cannot be — the parameter type is what keeps it literal.)\n */\nexport type ToolFail<Ok, E extends Tagged> = (error: E) => Outcome<Ok, E>;\n\n/**\n * The two constructors a handler is handed, one per channel — `ok` for the\n * value the `ok` schema parses, `fail` for a declared `{ _tag }`. Both build\n * the core's `Outcome` record (ADR 0021).\n */\nexport type ToolConstructors<Ok, E extends Tagged> = {\n readonly ok: ToolOk<Ok, E>;\n readonly fail: ToolFail<Ok, E>;\n};\n\n/**\n * A tool's handler: the parsed `args`, the plain `ctx` the host handed `run`,\n * and the typed `{ ok, fail }`, to an outcome over the declared channels — `Ok`\n * is what the `ok` schema parses, `E` the declared `_tag` union. An undeclared\n * tag does not compile. `Ctx` is whatever the handler annotates its `ctx`\n * parameter with; tea does no dependency injection (ADR 0020).\n */\nexport type ToolHandler<Args, Ok, E extends Tagged, Ctx> = (\n args: Args,\n ctx: HandlerCtx<Ctx>,\n settle: ToolConstructors<Ok, E>,\n) => Promise<Outcome<Ok, E>>;\n\n/**\n * What `tool()` returns: the `Cmd.define`d constructor (so `Settled<typeof t>`\n * / `CmdOf<typeof t>` read it like any def) plus the colocated `interpret` handler,\n * the bare `args` schema the router parses a call against, and the\n * `description` a provider adapter declares to the model beside that schema.\n * `E` is the full failure union the Cmd settles with — the declared tags plus\n * `thrown`. `Ctx` is the ctx the colocated handler reads — a fact about the\n * handler, never about the Cmd it builds (ADR 0020).\n */\nexport type ToolDef<\n Name extends string,\n Args,\n Ok,\n E extends Tagged,\n Ctx,\n> = CmdDef<Name, ToolInput<Args>, Ok, E> & {\n readonly description: string;\n readonly args: StandardSchemaV1<unknown, Args>;\n /**\n * The timeout / retry knob this tool declared, or `null` when it declared\n * neither. `toolRouter` serves it to the agent as `resilienceOf`.\n */\n readonly resilience: ToolResilience | null;\n /**\n * The colocated handler, as an interpret cell: it returns the tool's\n * outcome, and the engine mints `<name>_ok` / `<name>_err` from it.\n */\n readonly interpret: (\n cmd: CmdValue<Name, ToolInput<Args>, Ok, E>,\n ctx: HandlerCtx<Ctx>,\n ) => Promise<Outcome<Ok, E>>;\n /** Phantom — the ctx the handler reads. Never assigned. */\n readonly __ctx?: Ctx;\n};\n\n/** The declaration-erased view the router reads. */\nexport type AnyToolDef = AnyCmdDef & {\n readonly description: string;\n readonly args: StandardSchemaV1;\n readonly resilience: ToolResilience | null;\n readonly interpret: (cmd: never, ctx: never) => Promise<unknown>;\n};\n\n/**\n * Declare one tool the model may call — its name, the schemas for its arguments\n * and result, the failures it may return and the handler that runs it — and get\n * back a `Cmd<T, Ok, E>` definition, whose `Ok` is what `ok` parses and whose `E`\n * is the `err` tag union, that you pass to `toolRouter` or `defineAgent`.\n *\n * So a tool's two declared channels ARE the kernel's two typed effect channels\n * (ADR 0014), spelled in schemas rather than in type parameters: a settled\n * failure keeps its `_tag` into the conversation, so a reducer switching over\n * `err`'s tags is exhaustive and an unhandled one is a compile error.\n *\n * `name` is the name the model calls it\n * by; `description` is the model-facing sentence — the one place it lives — a\n * provider adapter declares to the model beside the schema (Anthropic\n * `description`, OpenAI `function.description`) so the model can tell when to\n * call the tool, read off `def.description`, never off the `input` schema;\n * `input` parses the model's `args`; `ok` parses the handler's value at the\n * edge; `err` is the `_tag` list the handler may fail with. The handler reads\n * its services off the plain `ctx` `run` was handed — annotate its `ctx`\n * parameter and `defineAgent` asks for that ctx at `run`. The handler returns\n * one of the two constructors it is handed — `ok(value)` or the typed `fail({ _tag })`; a\n * throw settles `<name>_err` — with the thrown `_tag` when it is a declared\n * one, else as `{ _tag: \"thrown\", message }`.\n *\n * A `ReservedToolName` does not compile as `name`, and one that reaches here\n * as a widened `string` throws — the same declaration-bug refusal\n * `toolRouter` gives a name declared twice.\n */\nexport function tool<\n const Name extends string,\n Args,\n Ok,\n const Tags extends readonly string[],\n Ctx = unknown,\n>(\n name: Name & NotReserved<Name>,\n spec: {\n readonly description: string;\n readonly input: StandardSchemaV1<unknown, Args>;\n readonly ok: StandardSchemaV1<unknown, Ok>;\n readonly err: Tags;\n /**\n * The budget one call of this tool gets, in ms — the overall cap, measured\n * from the first attempt and not restarted by a retry. When it elapses the\n * call settles as a `ToolOutcome` error carrying `_tag: \"timeout\"` beside\n * its `reason`, and the loop moves on; the attempt is NOT cancelled (a promise cannot be), so it runs to its\n * own end and its late settle folds nothing. Omit → no cap.\n */\n readonly timeoutMs?: number;\n /**\n * The backoff ladder a failed attempt of this tool climbs — the same\n * `{ baseMs, factor, capMs, jitter, maxAttempts }` shape the brain call's\n * `retry` takes. The ladder is folded into the Model and its wait is a timer\n * Sub, so a process killed between two attempts resumes at the attempt it\n * was on. A spent budget settles as a `ToolOutcome` error carrying\n * `_tag: \"retry_exhausted\"` beside its `reason`, with the attempt count and\n * the last attempt's reason as the `attempts` / `last` fields.\n * Omit → the first failure is the outcome.\n */\n readonly retry?: ToolResilience[\"retry\"];\n },\n handler: ToolHandler<Args, Ok, TaggedError<Tags[number]>, Ctx>,\n): ToolDef<Name, Args, Ok, TaggedError<Tags[number] | \"thrown\">, Ctx> {\n if (isReservedToolName(name)) {\n throw new Error(\n `tool: \"${name}\" is reserved — it is an agent-owned Msg prefix`,\n );\n }\n type E = TaggedError<Tags[number] | \"thrown\">;\n type Def = CmdDef<Name, ToolInput<Args>, Ok, E>;\n const def: Def = Cmd.define(name as Name, {\n // The router parses `args` against `spec.input` before it builds the Cmd,\n // so the Cmd's own input schema only names the type.\n input: unchecked<ToolInput<Args>>(),\n ok: spec.ok,\n err: [...spec.err, \"thrown\"] as readonly (Tags[number] | \"thrown\")[],\n });\n type C = CmdValue<Name, ToolInput<Args>, Ok, E>;\n const declared = new Set<string>(spec.err);\n const settle: ToolConstructors<Ok, TaggedError<Tags[number]>> = {\n ok: Outcome.ok,\n fail: Outcome.err,\n };\n const asDeclared = (thrown: unknown): E => {\n if (isTagged(thrown) && declared.has(thrown._tag)) return thrown as E;\n return { _tag: \"thrown\", message: describeError(thrown) };\n };\n // A throw is data here, not a contract breach: `thrown` is one of the tool's\n // declared tags, so the engine mints it into `<name>_err` like any other.\n const interpret = async (\n cmd: C,\n ctx: HandlerCtx<Ctx>,\n ): Promise<Outcome<Ok, E>> => {\n try {\n return await handler(cmd.args, ctx, settle);\n } catch (thrown) {\n return Outcome.err(asDeclared(thrown));\n }\n };\n return Object.assign(def, {\n description: spec.description,\n args: spec.input,\n resilience: resilienceOf(spec),\n interpret,\n });\n}\n\n/**\n * The declared knob as one value, or `null` when neither field was named. The\n * `null` is load-bearing: it is what tells the ladder to leave this tool on the\n * plain fan-out path, so a tool that declares nothing keeps behaving exactly as\n * it did before the knob existed. PURE.\n */\nfunction resilienceOf(spec: {\n readonly timeoutMs?: number;\n readonly retry?: ToolResilience[\"retry\"];\n}): ToolResilience | null {\n if (spec.timeoutMs === undefined && spec.retry === undefined) return null;\n return {\n ...(spec.timeoutMs !== undefined ? { timeoutMs: spec.timeoutMs } : {}),\n ...(spec.retry !== undefined ? { retry: spec.retry } : {}),\n };\n}\n\nfunction isTagged(value: unknown): value is Tagged {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { _tag?: unknown })._tag === \"string\"\n );\n}\n\n// ===========================================================================\n// toolRouter() — the set: one toolOf, one interpret table, one fold.\n// ===========================================================================\n\n/**\n * A call the router could not hand to a tool: the model named a tool nobody\n * declared, or its `args` failed the tool's `input` schema. `toolOf` is total —\n * it never throws inside the reducer — so the refusal rides its own Cmd and\n * settles `tool_rejected_err`, which the loop folds like any tool failure.\n */\nexport type ToolRejection =\n | { readonly _tag: \"unknown_tool\"; readonly name: string }\n | {\n readonly _tag: \"malformed_args\";\n readonly name: string;\n readonly issues: ReadonlyArray<{\n readonly path: string;\n readonly message: string;\n }>;\n };\n\nconst rejected = Cmd.define(REJECTED_TYPE, {\n input: unchecked<{\n readonly callId: string;\n readonly error: ToolRejection;\n }>(),\n ok: rejectAll,\n err: [\"unknown_tool\", \"malformed_args\"],\n});\n\n/** The Cmd `tool_rejected` builds — the router-owned variant of `ToolCmd`. */\nexport type ToolRejectedCmd = CmdOf<typeof rejected>;\n\n/** The Cmd union a router's `toolOf` produces — `TC` for `createAgent`. */\nexport type ToolCmd<T extends AnyToolDef> = CmdOf<T> | ToolRejectedCmd;\n\n/** The ctx one tool's handler reads; `unknown` for a handler that reads none. */\ntype ToolCtxOf<T> = T extends { readonly __ctx?: infer Ctx } ? Ctx : unknown;\n\ntype UnionToIntersection<U> = (\n U extends unknown\n ? (u: U) => void\n : never\n) extends (u: infer I) => void\n ? I\n : never;\n\n// `unknown` absorbs a union (`{ kb } | unknown` is `unknown`), so each tool's\n// ctx is boxed first and the \"reads nothing\" arms dropped before intersecting.\ntype ToolCtxBoxed<T> = T extends unknown ? [ToolCtxOf<T>] : never;\ntype KnownToolCtx<B> = B extends [infer Ctx]\n ? unknown extends Ctx\n ? never\n : Ctx\n : never;\n\n/**\n * The ctx a tool set's handlers read, intersected — what `run` asks the host\n * for once the tools are wired into a machine. A tool whose handler reads\n * nothing leaves its siblings' demand intact.\n */\nexport type ToolsCtx<T extends AnyToolDef> = UnionToIntersection<\n KnownToolCtx<ToolCtxBoxed<T>>\n>;\n\n/** The settled Msg union a router's handlers return — folded by `toMachine`. */\nexport type ToolMsg<T extends AnyToolDef> =\n | Settled<T>\n | Settled<typeof rejected>;\n\n/**\n * `ToolCmd<T>` as `toMachine` reads it: `never` for `T = never` — the \"no\n * router\" reading it defaults to — so the router-owned `tool_rejected` arm\n * does not leak into a machine that wired no router.\n */\nexport type WiredToolCmd<T extends AnyToolDef> = [T] extends [never]\n ? never\n : ToolCmd<T>;\n\n/** `ToolMsg<T>` as `toMachine` / `agentEvents` read it — see `WiredToolCmd`. */\nexport type WiredToolMsg<T extends AnyToolDef> = [T] extends [never]\n ? never\n : ToolMsg<T>;\n\n/** The union of every tool's `ok` value — `R` for `createAgent`. */\nexport type ToolResult<T extends AnyToolDef> = OkOf<T>;\n\n/**\n * Every failure a router over `T` can settle with — the union `outcomeOf`'s\n * error arm is typed from. Five sources, and a consumer branching on `_tag`\n * meets all five: each tool's DECLARED tags plus the `thrown` `tool()` appends\n * (`ErrOf<T>`), the kernel's `malformed_result` (a handler returned a value its\n * own `ok` schema rejects), the router's own `unknown_tool` / `malformed_args`\n * rejections, and the ladder's `timeout` / `retry_exhausted` (#117) — which end\n * a call from outside the handler and so are nothing a tool can declare.\n */\nexport type ToolError<T extends AnyToolDef> =\n | ErrOf<T>\n | MalformedResult\n | ToolRejection\n | ToolResilienceError;\n\n/**\n * The error outcome a router over `T` produces: `{ kind: \"error\", _tag,\n * …payload, reason }`, discriminable on `_tag` over {@link ToolError}. This is\n * what `defineAgent`'s `onToolError` hands the consumer.\n */\nexport type ToolFailureOf<T extends AnyToolDef> = TaggedFailure<ToolError<T>>;\n\n/** One settled tool, read back off a `ToolMsg` by `outcomeOf`. */\nexport type ToolSettlement<R, E extends Tagged = Tagged> = {\n readonly callId: string;\n readonly outcome:\n | { readonly kind: \"ok\"; readonly result: R }\n | TaggedFailure<E>;\n};\n\n/**\n * What `toolRouter()` returns: the derived `toolOf` for `createAgent`'s config,\n * the interpret table `toMachine({ tools })` merges, the defs it puts on\n * `Machine.cmds`, and the one reader that turns a settled Msg back into the\n * conversation's `ToolOutcome`.\n */\nexport interface ToolRouter<T extends AnyToolDef> {\n /** Every def the router settles through — hand to `Machine.cmds`. */\n readonly defs: readonly AnyCmdDef[];\n /** The `toolOf` for `createAgent`: total, pure, parses `args` at the edge. */\n readonly toolOf: (call: ToolCall) => ToolCmd<T>;\n /** One interpret handler per tool plus the `tool_rejected` handler. */\n readonly interpret: Interpret<ToolMsg<T>, ToolCmd<T>, ToolsCtx<T>>;\n /**\n * The timeout / retry knob the called tool declared — `AgentConfigCore`'s\n * `toolResilienceOf` seam, filled from the `tool()` specs. `null` for a tool\n * that declared neither field and for a call no tool answers (the rejection\n * path settles in the reducer and never runs an effect to time out). PURE.\n */\n readonly resilienceOf: (call: ToolCall) => ToolResilience | null;\n /**\n * Read a settled tool off a Msg: `null` when the Msg is not one of this\n * router's `<name>_ok` / `<name>_err`. The one place a `{ _tag }` failure is\n * rendered to the `reason` string the conversation carries — and the tag and\n * its payload ride beside that rendering, never instead of it (#115).\n */\n readonly outcomeOf: (msg: {\n readonly type: string;\n }) => ToolSettlement<ToolResult<T>, ToolError<T>> | null;\n}\n\n/**\n * Fold a set of `tool()`s into one router — pass it the tools, get back the\n * lookup `createAgent` needs, the handlers `toMachine` merges, and a reader that\n * turns a settled message back into a plain outcome.\n *\n * Two tools with one name is a declaration bug, refused here rather than by a\n * silent last-wins map.\n */\nexport function toolRouter<T extends AnyToolDef>(\n tools: readonly T[],\n): ToolRouter<T> {\n const byName = new Map<string, T>();\n for (const t of tools) {\n if (byName.has(t.cmdType)) {\n throw new Error(`toolRouter: tool \"${t.cmdType}\" is declared twice`);\n }\n byName.set(t.cmdType, t);\n }\n const defs: readonly AnyCmdDef[] = [...tools, rejected];\n const okTypes = new Map(defs.map((d) => [d.okType, d]));\n const errTypes = new Map(defs.map((d) => [d.errType, d]));\n\n const toolOf = (call: ToolCall): ToolCmd<T> => {\n const t = byName.get(call.name);\n if (t === undefined) {\n return rejected({\n callId: call.callId,\n error: { _tag: \"unknown_tool\", name: call.name },\n });\n }\n const parsed = validateSync(\n t.args,\n call.args,\n `the \"${call.name}\" tool's input schema`,\n );\n if (parsed.issues !== undefined) {\n return rejected({\n callId: call.callId,\n error: {\n _tag: \"malformed_args\",\n name: call.name,\n issues: malformedResult(parsed.issues).issues,\n },\n });\n }\n // `t` is the def the name resolved to, so its constructor builds exactly\n // the `CmdOf<T>` arm for that name; `AnyToolDef` erases the call signature.\n const build = t as unknown as (input: ToolInput<unknown>) => CmdOf<T>;\n return build({ callId: call.callId, args: parsed.value });\n };\n\n const handlers: Record<string, unknown> = {\n [rejected.cmdType]: async (cmd: ToolRejectedCmd) => Outcome.err(cmd.error),\n };\n for (const t of tools) handlers[t.cmdType] = t.interpret;\n // Each handler is the def's own typed `interpret`, keyed by the `type` it\n // builds; the record is assembled per name, which the mapped type cannot see.\n const interpret = handlers as unknown as Interpret<\n ToolMsg<T>,\n ToolCmd<T>,\n ToolsCtx<T>\n >;\n\n const outcomeOf = (msg: {\n readonly type: string;\n }): ToolSettlement<ToolResult<T>, ToolError<T>> | null => {\n if (okTypes.has(msg.type)) {\n const ok = msg as unknown as SettledShape<ToolResult<T>>;\n return {\n callId: ok.cmd.callId,\n outcome: { kind: \"ok\", result: ok.value },\n };\n }\n if (errTypes.has(msg.type)) {\n const err = msg as unknown as SettledShape<ToolResult<T>>;\n return {\n callId: err.cmd.callId,\n // The tag and its payload spread FIRST, so `kind` and `reason` are\n // written over anything a payload field of those names carries: the\n // discriminant and the model's channel are the router's to state, and a\n // tool that fails with `{ _tag, kind: \"ok\" }` must not be able to say\n // otherwise.\n outcome: {\n ...err.error,\n reason: toolErrorReason(err.error),\n kind: \"error\",\n } as TaggedFailure<ToolError<T>>,\n };\n }\n return null;\n };\n\n const resilienceOf = (call: ToolCall): ToolResilience | null =>\n byName.get(call.name)?.resilience ?? null;\n\n return { defs, toolOf, interpret, outcomeOf, resilienceOf };\n}\n\n// ===========================================================================\n// fanOutInterpret() — ADR 0018 option (c): overlap INSIDE the Cmd handler.\n// ===========================================================================\n\n/** One interpret cell, erased of its per-tool narrowing. */\ntype AnyCell = (\n cmd: never,\n ctx: never,\n dispatch?: (msg: never) => void,\n) => Promise<unknown>;\n\n/**\n * Give a router's interpret cells real wall-clock overlap without touching the\n * kernel — pass the table `toolRouter` built, get back one whose cells launch\n * their tool and RETURN, so `runInterpret` reaches the next Cmd of the turn\n * while the first tool is still running.\n *\n * This is ADR 0018's option (c), and the whole of it. `runInterpret` stays the\n * serial loop the ADR ruled it must be: it still awaits one handler before\n * reaching the next Cmd — the handlers just stop being the thing that takes the\n * time. Three properties are what make that safe, and each is a line below:\n *\n * - **Settles fold in Cmd-EMISSION order, never completion order.** Each cell\n * chains its dispatch behind the previous cell's, so two tools that overlap\n * on the clock still settle a-then-b when a's Cmd was emitted first, whichever\n * finished first. That is invariant 2's serializability, and it is what keeps\n * a replay of a fanned run identical to the run itself.\n * - **The settle crosses the SAME edge.** A returned Msg is parsed and stamped\n * by `run`'s `cmdEdge`; a dispatched one would not be, so the cell settles\n * through `cmdEdgeOf(ctx)` — the edge `run` hands handlers for exactly this.\n * One parse, one clock, fanned or not.\n * - **The work stays counted.** The promise the cell does not return is enlisted\n * with `detachWorkOf(ctx)`, so `inFlightCmds` and the dispatch tail see it and\n * `stop()` / `idle()` answer under fan-out what they answer serially.\n *\n * The ordering has a price, and it is the honest one: a call whose Cmd was\n * emitted FIRST holds its siblings' settles until it finishes. They still RUN\n * in parallel — the turn costs the slowest call, not the sum — but a first call\n * that never returns leaves the later folds parked behind it, exactly as a\n * serial run would leave them unstarted. `timeoutMs` on the tool is what bounds\n * that, fanned or not.\n *\n * The per-turn LIMIT is not this function's: the agent's fan-out slice already\n * launches at most `toolConcurrency` calls per transition, so the table simply\n * must not block. Nothing here is applied below that knob — `toMachine` wires\n * the bare cells at the serial default, and a tool that never overlaps is the\n * exact function `toolRouter` built.\n */\nexport function fanOutInterpret<T extends AnyToolDef>(\n interpret: Interpret<ToolMsg<T>, ToolCmd<T>, ToolsCtx<T>>,\n): Interpret<ToolMsg<T>, ToolCmd<T>, ToolsCtx<T>> {\n // The release chain: one per table, so the ordering it imposes is the\n // ordering of the Cmds that entered THIS machine's interpret.\n let release: Promise<void> = Promise.resolve();\n const fanned: Record<string, AnyCell> = {};\n for (const [type, cell] of Object.entries(\n interpret as unknown as Record<string, AnyCell>,\n )) {\n fanned[type] = async (cmd, ctx, dispatch) => {\n const edge = cmdEdgeOf(ctx);\n const detach = detachWorkOf(ctx);\n // Launched, NOT awaited — this one line is the overlap.\n const work = (async () => cell(cmd, ctx, dispatch))();\n const prior = release;\n const settled = work.then(async (follow) => {\n // The wait is here rather than before `work` so the tools overlap and\n // only their SETTLES queue: a tool whose Cmd came second still starts\n // at once and merely waits its turn to fold.\n await prior;\n const msg = edge(cmd, follow);\n if (msg === undefined || msg === null) return;\n dispatch?.(msg as never);\n });\n // A rejecting cell must not strand the tools behind it — `detach` is what\n // routes that rejection to the runtime's sink.\n release = settled.then(swallow, swallow);\n detach(settled);\n return undefined;\n };\n }\n return fanned as unknown as Interpret<ToolMsg<T>, ToolCmd<T>, ToolsCtx<T>>;\n}\n\n/** The release chain carries no value and must not break — both arms land here. */\nfunction swallow(): void {}\n\n// The two settled arms share one shape once the `type` has been matched\n// against the router's own def; `value` / `error` are read per arm.\ntype SettledShape<R> = {\n readonly cmd: { readonly callId: string };\n readonly value: R;\n readonly error: Tagged;\n};\n\n/**\n * Turn a tool failure into the human-readable reason string the conversation\n * carries — pass the `{ _tag, ...detail }` a tool failed with, get the tag\n * followed by any remaining detail as JSON.\n *\n * The\n * model reads this next turn, so the data survives the rendering intact.\n */\nexport function toolErrorReason(error: Tagged): string {\n const { _tag, ...detail } = error;\n return Object.keys(detail).length === 0\n ? _tag\n : `${_tag} ${JSON.stringify(detail)}`;\n}\n","/**\n * @demlik/tea/agent — the domain data model: the tool + turn shapes the consumer\n * supplies, the agentic-stage conversation, the `createAgent` config object, and\n * the durable agent slice + its lifecycle status.\n *\n * Everything here is plain data (durable + replayable): the composed wrappers'\n * slices, the conversation, and the config are all JSON-serializable. The\n * compaction vocabulary lives in `./compaction`; this module imports its\n * types where the slice / config reference them. The reducer core (the verbs +\n * the wired `toMachine`) lives in `./index`.\n */\n\nimport { absurd, type Cmd, type Tagged } from \"../index\";\nimport type { FanOutState } from \"../internal/flow/fan-out\";\nimport type {\n MonitoredRunState,\n RunFailure,\n} from \"../internal/flow/monitored-run\";\nimport type {\n LlmCall,\n LlmOk,\n ResilientState,\n Schema,\n} from \"../internal/llm-call\";\nimport type { AnyRetryPolicy, RetryPolicy } from \"../retry-backoff\";\nimport type {\n AgentCompactionConfig,\n CompactionOutputs,\n CompactionPurpose,\n} from \"./compaction\";\nimport type { MessageLoader, ModelPort } from \"./model\";\nimport { schemaFromGuard } from \"./schema\";\n\n// ===========================================================================\n// Domain seams the consumer supplies — the tool + turn shapes.\n// ===========================================================================\n\n/**\n * One tool the model asked to call this turn. Plain data so it round-trips through the\n * durable fan-out ledger: a stable `callId` (the fan-out identity), the tool\n * `name`, and the opaque `args` the consumer's own interpret reads.\n */\nexport interface ToolCall {\n /** Stable id the model minted; the fan-out item identity (`idOf`). */\n readonly callId: string;\n /** The tool to invoke. The consumer's `toolOf` maps it to an effect Cmd. */\n readonly name: string;\n /** Args the model emitted, opaque to the agent. */\n readonly args: Readonly<Record<string, unknown>>;\n}\n\n/**\n * One model turn: the narration `content` the model produced and the\n * `toolCalls` it asked us to run. An empty\n * `toolCalls` means the model is done with this stage (advance the pipeline).\n * This is the parsed output of a brain call; the consumer's schema produces it.\n *\n * `provider` is the opaque passthrough slot (#93): whatever the adapter hands\n * back beside `content` / `toolCalls` that its provider expects echoed\n * verbatim on the next turn — Anthropic's signed `thinking` blocks,\n * `server_tool_use`, OpenAI reasoning items. tea stores it on the turn and\n * returns it unchanged on the `assistant` `AgentMessage` that replays this\n * turn; it never reads, validates or transforms it. The adapter owns its shape,\n * which must be JSON-serializable like the rest of the Model. A compaction fold\n * (ADR 0004) summarises turns into text, so it drops the slot with the turns it\n * summarises. Optional and additive: a persisted turn without it still parses.\n */\nexport interface AgentTurn {\n /** Free-text narration the model produced this turn (folded into the conversation). */\n readonly content: string;\n /** The tools the model asked us to run; empty = stage done. */\n readonly toolCalls: readonly ToolCall[];\n /** Provider-opaque blocks to echo back verbatim next turn. tea never reads it. */\n readonly provider?: unknown;\n}\n\n/**\n * One partial piece of a turn the model is still producing — a token delta, as\n * the provider emitted it.\n *\n * A chunk is NOT state. It never reaches the Model, the journal or the Store:\n * by the time a turn is durable it has settled, and a delta that has not settled\n * is not an outcome ADR 0011 could fold. So `TurnChunk` carries only what a\n * progress surface renders — the text so far — and carries no identity, because\n * an identity would invite someone to store it.\n */\nexport interface TurnChunk {\n /** The text delta this chunk adds to the turn's `content`. */\n readonly text: string;\n}\n\n/**\n * The side channel a {@link StreamingModel} writes its deltas to — the second\n * argument of the streaming port. One sink, called synchronously by the adapter\n * as the provider yields; a throw from it is contained by the caller that\n * supplied it, so a progress surface's defect cannot fail a model call.\n */\nexport interface ModelStream {\n /** Hand one delta to whoever is watching this run. */\n readonly onChunk: (chunk: TurnChunk) => void;\n}\n\n/**\n * The streaming model port — `(messages, { onChunk }) => Promise<AgentTurn>`.\n *\n * The second, OPTIONAL shape of the brain. It differs from\n * `PlainModel<Msg, T>` in one thing: it is handed a {@link ModelStream} it may\n * write deltas to while the turn is in flight. What it RESOLVES is the same\n * settled turn the plain port resolves, and that turn is the only thing the\n * reducer ever sees — the deltas are a side channel that ends at the caller's\n * listener.\n *\n * A `PlainModel` is assignable here (a function may declare fewer parameters\n * than its type), which is what lets one config field accept either shape.\n * `isStreamingModel` tells them apart at runtime so a plain model is still\n * invoked with exactly one argument, as it always was.\n */\nexport type StreamingModel<Msg, T = unknown> = (\n messages: readonly Msg[],\n stream: ModelStream,\n) => Promise<T>;\n\n/**\n * Whether a model port wants the {@link ModelStream} — read off its declared\n * arity, which is the mark JavaScript already carries. No config flag, and no\n * marker property for a consumer to forget: a brain written\n * `async (messages, { onChunk }) => …` streams, and one written\n * `async (messages) => …` does not.\n *\n * The cost of the arity read is the cost of every arity read — a model that\n * declares a parameter it ignores, or takes `...args`, reads as the other shape.\n * Both misreads are benign: a `...args` model is handed no stream and emits no\n * chunks; a model with an unused second parameter is handed a stream it never\n * writes to. Neither can change the settled turn. PURE.\n */\nexport function isStreamingModel(\n model: (...args: never[]) => unknown,\n): boolean {\n return model.length >= 2;\n}\n\n/**\n * Narrow an unknown to a `ToolCall` — the per-element witness `isAgentTurn`\n * folds over the `toolCalls` array. Checks the three load-bearing fields:\n * `callId`/`name` are strings, `args` is a non-null object. PURE — allocates no\n * Error. Without this the array-of-`ToolCall` narrow would be validation\n * masquerading as parse: `toolCalls: [1, 2, 3]` would pass, then the downstream\n * `dedupeByCallId` / `fan.scatter` read an `undefined` `callId` and wedge the\n * fan-out batch.\n */\nfunction isToolCall(value: unknown): value is ToolCall {\n if (value === null || typeof value !== \"object\") return false;\n const t = value as { callId?: unknown; name?: unknown; args?: unknown };\n return (\n typeof t.callId === \"string\" &&\n typeof t.name === \"string\" &&\n t.args !== null &&\n typeof t.args === \"object\"\n );\n}\n\n/**\n * Narrow an unknown to an `AgentTurn` — the runtime witness for tea's own\n * structured-output type. A consumer's brain schema parses the model's output\n * into an `AgentTurn` (the agentic purpose's output); rather than every consumer\n * hand-rolling this guard + a `Schema<AgentTurn>` for a type the agent OWNS, the\n * agent exports both. Checks the load-bearing fields: `content` is a string and\n * `toolCalls` is an array of `ToolCall` (each element guarded — the narrow is a\n * real parse of the boundary, not a shallow `Array.isArray`). `provider` is\n * opaque, so its presence or absence is not a fact the guard reads. PURE —\n * allocates no Error.\n */\nexport function isAgentTurn(value: unknown): value is AgentTurn {\n if (value === null || typeof value !== \"object\") return false;\n const t = value as { content?: unknown; toolCalls?: unknown };\n return (\n typeof t.content === \"string\" &&\n Array.isArray(t.toolCalls) &&\n t.toolCalls.every(isToolCall)\n );\n}\n\n/**\n * The `Schema<AgentTurn>` for tea's own turn type — the parse target a brain\n * call binds when the agentic purpose's output is a bare `AgentTurn` (the common\n * case). Throws on a non-`AgentTurn` (the zod-style `parse` contract the\n * llm-call handler relies on). Deletes the consumer's hand-rolled\n * `auditSchema` / `isAgentTurn` pair.\n *\n * A consumer whose turn type EXTENDS `AgentTurn` with extra fields still writes\n * its own schema (it must validate the extra fields); this is for the plain case.\n */\nexport const agentTurnSchema: Schema<AgentTurn> = schemaFromGuard(\n isAgentTurn,\n \"an AgentTurn\",\n);\n\n/**\n * One settled tool outcome the consumer routes back into the loop.\n * `ok` carries the result the consumer's interpret produced;\n * `error` carries the failure as data — see {@link ToolFailure}.\n */\nexport type ToolOutcome<R> =\n | { readonly kind: \"ok\"; readonly result: R }\n | ToolFailure;\n\n/**\n * A settled tool failure as the conversation keeps it: the `{ _tag, …payload }`\n * the tool failed with, spread beside the `reason` string the model reads.\n *\n * Both halves are load-bearing and neither replaces the other. `reason` is the\n * model's channel — `toolErrorReason`'s rendering, which is what the next brain\n * call carries; `_tag` and the payload are the program's, so host code can\n * branch on the failure instead of parsing prose out of `reason` (#115). A\n * payload field never shadows `kind` or `reason`: the router writes those last.\n *\n * `_tag` is OPTIONAL here for one reason only — a record persisted by 0.12.x or\n * earlier was written before the tag was kept, so a Store handing one back has\n * a failure with no tag, and a required field would be a lie about durable\n * state. Every failure THIS version mints carries one. For the exhaustive\n * per-tag union, take `onToolError`'s argument, which is typed from the tools\n * themselves ({@link ToolFailureOf}).\n */\nexport interface ToolFailure {\n readonly kind: \"error\";\n /** The model-facing rendering — `toolErrorReason(error)`. */\n readonly reason: string;\n /** The failure's tag; absent only on a record persisted before 0.13. */\n readonly _tag?: string;\n}\n\n/**\n * The failure arm typed against a KNOWN tag union — `{ kind, reason }` beside\n * each arm of `E`, distributed, so a `switch` on `_tag` narrows the payload and\n * an unhandled tag is a compile error. `ToolFailure` is its erased form.\n */\nexport type TaggedFailure<E extends Tagged> = E extends unknown\n ? { readonly kind: \"error\"; readonly reason: string } & E\n : never;\n\n/**\n * The per-tool resilience knob — a timeout, a retry ladder, or both, declared on\n * the `tool()` spec and executed by the agent's reducer through\n * `../internal/resilience/resilient-call`.\n *\n * Both fields are optional and a tool that names neither behaves exactly as it\n * did before this knob existed: no slice entry is minted, no timer is armed, and\n * its settle path is the plain fan-out one. The ladder lives in the Model, so a\n * process killed between two attempts resumes at the attempt it was on rather\n * than restarting the run — the property a `Promise.race` or a `for` loop inside\n * the handler cannot have, because those live inside the effect boundary.\n */\nexport interface ToolResilience {\n /**\n * The budget one tool CALL gets, in ms, measured from the first attempt and\n * NOT restarted by a retry — the overall cap `resilient-call`'s deadline brick\n * enforces. When it elapses the call settles as a `ToolOutcome` error\n * carrying `_tag: \"timeout\"` beside its `reason`, and the loop moves on, whatever the\n * in-flight attempt does next — its late settle arrives for a call nothing is\n * waiting on and folds nothing, so a slow tool costs the budget and not the\n * turn.\n *\n * What it does NOT do is cancel the handler: a promise cannot be cancelled in\n * JavaScript, so the attempt runs to its own end, and `run`'s teardown still\n * drains it. A handler that resolves LATE is bounded by this knob; a handler\n * that never resolves at all holds the runtime's shutdown regardless, and\n * wants an `AbortSignal` in the handler rather than a budget out here.\n *\n * Omit → the call has no cap and ends only when its handler settles.\n */\n readonly timeoutMs?: number;\n /**\n * The backoff ladder a FAILED attempt climbs — the same\n * `BackoffCurve & RetryBudget` shape `AgentConfigCore.retry` takes for the\n * brain call. Each failure is recorded in the Model and the next attempt is\n * armed as a timer Sub, so the wait is durable and the attempt count survives\n * a reload. When the budget is spent the call settles as a `ToolOutcome` error\n * carrying `_tag: \"retry_exhausted\"` beside its `reason`, plus `attempts` and\n * `last` as fields — see {@link ToolRetryExhausted}.\n *\n * Omit → the first failure is the outcome, exactly as before.\n */\n readonly retry?: AnyRetryPolicy;\n}\n\n/** The reason-tag a timed-out tool call settles under. */\nexport const TOOL_TIMEOUT_TAG = \"timeout\";\n/** The reason-tag a tool call that spent its retry budget settles under. */\nexport const TOOL_RETRY_EXHAUSTED_TAG = \"retry_exhausted\";\n\n/** A call that spent its `timeoutMs` budget — {@link ToolResilience.timeoutMs}. */\nexport interface ToolTimedOut {\n readonly _tag: typeof TOOL_TIMEOUT_TAG;\n}\n\n/** A call that spent its retry budget — {@link ToolResilience.retry}. */\nexport interface ToolRetryExhausted {\n readonly _tag: typeof TOOL_RETRY_EXHAUSTED_TAG;\n /** How many attempts the ladder burned, the failed last one included. */\n readonly attempts: number;\n /** The last attempt's own `reason`, so the real failure is not buried. */\n readonly last: string;\n}\n\n/**\n * The two failures the resilience ladder itself authors — `timeout` and\n * `retry_exhausted`. They are in every tool's\n * error union rather than only a policied tool's: the policy is a `tool()` spec\n * field a maintainer can add later, and a union that narrowed with it would turn\n * adding a `timeoutMs` into a silent behaviour change at every `onToolError`\n * that had switched exhaustively without them.\n */\nexport type ToolResilienceError = ToolTimedOut | ToolRetryExhausted;\n\n/**\n * A folded tool record kept on the conversation once a tool settles — the\n * call + its outcome, in settle order. The consumer's message loader reads\n * these (plus `turns`) to assemble the next brain call's prompt.\n *\n * `turn` is the `turnCount` at the time the record was folded — the association\n * compaction needs to drop the RIGHT records (#85 / design A1). When compaction\n * folds `turns[0..N]` into a summary, it must also drop every tool record that\n * belonged to those turns; without a turn stamp on the record there is no honest\n * way to know which. It is the round-trip index, not a wall clock — small and\n * JSON-stable, preserving the durability invariant.\n */\nexport interface ToolRecord<R> {\n readonly call: ToolCall;\n readonly outcome: ToolOutcome<R>;\n /** The `turnCount` at fold time — which round-trip this record belongs to (#85, A1). */\n readonly turn: number;\n}\n\n// ===========================================================================\n// Conversation — the agentic-stage loop state.\n// ===========================================================================\n\n/**\n * Whether the agentic stage is waiting on the model (`llm`), on tools\n * (`tools`), or on a compaction round-trip (`compacting`). The in-flight\n * fan-out batch exists ONLY in the `tools` variant — \"awaiting llm with tools\n * pending\" is structurally impossible (TEA canon §2.6 / Rule 1\n * impossible-states pin). Discriminated on `kind`.\n *\n * `compacting` is the honest state for the dedicated compaction round-trip\n * (design B1): the transcript grew, the policy asked to fold `folding` of the\n * OLDEST turns, and the summarize call is in flight INSTEAD of the next brain\n * call. `folding` is the count `planCompaction` returned — the fold-back\n * (`compact_ok`) drops exactly that many head turns + their tool records.\n */\nexport type Awaiting =\n | { readonly kind: \"llm\" }\n | { readonly kind: \"tools\"; readonly batchTurn: number }\n | { readonly kind: \"compacting\"; readonly folding: number };\n\n/**\n * The agentic-stage conversation — durable inside the agent slice so an\n * eviction mid-loop resumes the exact turn. The model turns + folded tool\n * records are the consumer's prompt source (via the llm-call message loader);\n * `turnCount` drives the livelock guard; `awaiting` carries the ONE outstanding\n * effect for the agentic stage.\n *\n * Generic over the consumer's tool-result type `R` (what `toolOk` carries).\n */\nexport interface Conversation<R> {\n /** Model turns this stage has produced, in order. */\n readonly turns: readonly AgentTurn[];\n /** Settled tool records, in settle order — the model sees these next turn. */\n readonly toolRecords: readonly ToolRecord<R>[];\n /** Monotonic round-trip count; the livelock guard compares it to `maxTurns`. */\n readonly turnCount: number;\n /** What the loop is waiting for next. */\n readonly awaiting: Awaiting;\n}\n\n// ===========================================================================\n// Config — what the agent is configured with. The domain seams (tools /\n// schemas / model / stages) are required; everything cross-cutting (retry /\n// deadline / concurrency / loader / maxTurns) is optional, per the\n// resilient-call \"omit a composed wrapper → omit its gate\".\n// ===========================================================================\n\n/**\n * The snapshotting discriminant. Checkpointing is either OFF — in which\n * case `snapshotEvery` is structurally absent and the monitored-run slice never\n * emits a `snapshot_write` Cmd — or ON, in which case `snapshotEvery` is a\n * `number`. A `{ snapshotEvery?: never }` member (rather than a bare optional)\n * makes the OFF case load-bearing: it forbids passing `snapshotEvery` at all, so\n * `toMachine` can config-derive whether the `snapshot_write` interpret handler\n * is REQUIRED (ON) or FORBIDDEN (OFF) instead of defaulting it to a silent\n * no-op.\n *\n * This is what kills the type lie: with checkpointing off, `snapshot_write` is\n * absent from the consumer's interpret contract entirely — never a\n * `snapshot_write: async () => undefined` ceremony that masks a real wiring bug.\n */\nexport type AgentSnapshotConfig =\n | { readonly snapshotEvery?: never }\n | { readonly snapshotEvery: number };\n\n/**\n * The core (non-snapshot, non-compaction) agent configuration. The full `AgentConfig`\n * intersects this with the `AgentSnapshotConfig` + `AgentCompactionConfig`\n * discriminants — see those types for why the cadence / policy are discriminated\n * unions rather than bare optionals.\n *\n * Type parameters:\n * - `Stage` — the consumer's pipeline stage id (any JSON value).\n * - `P` — the brain-call purpose union (`\"plan\" | \"act\" | ...`).\n * - `O` — the purpose→output map. Every purpose drives the agentic loop,\n * so each output is pinned to `AgentTurn` (or a subtype) by the\n * `O extends Record<P, AgentTurn>` bound — that is what the loop\n * folds. An `Outputs` whose purpose output is NOT an `AgentTurn`\n * fails to compile here; the rule lives in the type, not a cast.\n * - `R` — the consumer's tool-result type (what `toolOk` carries).\n * - `TC` — the consumer's per-tool effect Cmd, the discriminated variant\n * `toolOf` produces. Kept PRECISE (a closed Cmd variant, not the\n * open `Cmd`) so `AgentCmd<P, TC>` stays a closed discriminated\n * union and the wired machine's interpret merge type-checks per\n * key — the brain handler maps to `resilient_run`, the tool one to\n * `TC[\"type\"]` — with no laundering cast. Defaults to `Cmd` for\n * the consumer that does not care to name its tool Cmd.\n * - `Msg` — the model's message shape (threaded through the llm-call loader).\n */\nexport interface AgentConfigCore<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd = Cmd,\n Msg = unknown,\n> {\n // ---- monitored-run seam (the outer pipeline) ----------------------------\n /** The ordered stages. Omit / empty → a single-shot run (one agentic stage). */\n readonly stages?: readonly Stage[];\n /** No-progress watchdog budget, in ms. Omit → no watchdog. */\n readonly deadlineMs?: number;\n\n // ---- llm-call seam (the brain) ------------------------------------------\n /**\n * DI port — the brain. `async (messages) => turn` is the common path:\n * the returned turn is validated through the purpose's schema\n * (`agentTurnSchema` for the plain case), so a malformed turn is the run's\n * `llm` failure, not a throw. `(modelId) => Llm` is the advanced form for a\n * model that binds the structured-output schema itself.\n */\n readonly model: ModelPort<Msg, O[P]>;\n /**\n * The system prompt, stored ON THE MODEL at `init` (`AgentState.instructions`)\n * rather than closed over — so a replay reproduces the exact prompt that ran,\n * a rehydrated run keeps the prompt it started with, and a compaction fold\n * (which touches only the conversation) can never lose it (ADR 0004). It\n * reaches the brain call through `payloadOf`'s third argument. Omit → `null`.\n */\n readonly instructions?: string;\n /** One structured-output schema per purpose; the parse target per brain call. */\n readonly schemas: { readonly [K in P]: Schema<O[K]> };\n /** Backoff policy for brain calls, composed into `../llm-call`. Omit → no backoff. */\n readonly retry?: RetryPolicy;\n /** DI port — the SDK / message loader. Omit → brain calls invoke with `[]`. */\n readonly loadMessages?: MessageLoader<P, Msg>;\n\n // ---- fan-out seam (the tools) -------------------------------------------\n /** Map one tool call to the effect Cmd the consumer's interpret performs. */\n readonly toolOf: (call: ToolCall) => TC;\n /**\n * The per-tool timeout / retry knob for a call, read once per launch. `null`\n * (or an omitted seam) → the tool runs bare and its settle path is the plain\n * fan-out one, byte for byte what it was before the knob existed.\n *\n * This is the seam a `toolRouter` fills from the `tool()` specs\n * (`router.resilienceOf`), which is how `defineAgent` grows the knob without\n * growing a lid option: the policy is declared where the tool is. A hand-wired\n * `createAgent` supplies it directly. It must be PURE and config-derived — the\n * reducer calls it on the launch path.\n */\n readonly toolResilienceOf?: (call: ToolCall) => ToolResilience | null;\n /**\n * How many of ONE turn's tool calls a transition LAUNCHES at once. At the\n * default `1` a turn's calls go out one at a time; raise it and up to that\n * many move from `pending` to `running` in the fan-out ledger in a single\n * transition, so the durable Model (and a `store`'s record of it) says what\n * was launched.\n *\n * Above `1` those calls also OVERLAP on the clock, so a turn of two slow\n * tools costs the slower rather than the sum — but only for the tool cells a\n * `toolRouter` owns (the `toMachine({ tools })` path, which `defineAgent`\n * takes). The overlap lives inside those cells, never in the kernel:\n * `runInterpret` still interprets a transition's Cmds one after another and\n * never interleaves two handlers (ADR 0018). A hand-wired `toolInterpret`\n * cell is yours, so it overlaps only if you write it to.\n *\n * Overlapping does NOT reorder the fold. Settle Msgs are dispatched in\n * Cmd-EMISSION order whichever call finishes first, so a replayed log\n * reproduces the same Model — invariant 2's serializability, which the knob\n * was never allowed to spend.\n *\n * Omit (or `1`) → serial dispatch, exactly as before.\n */\n readonly toolConcurrency?: number;\n\n // ---- the loop wiring -----------------------------------------------------\n /**\n * Which brain-call purpose a given stage runs. The agent fires\n * `call_llm{ turnOf(stage) }` to drive the agentic stage's loop. The purpose's\n * schema output is an `AgentTurn` — enforced by the `O extends Record<P,\n * AgentTurn>` bound, not left to a doc-comment.\n */\n readonly turnOf: (stage: Stage | undefined) => P;\n /**\n * Build the per-purpose brain-call payload from the durable state: the\n * stage, the conversation, and the Model's `instructions` slot. Omit → `null`.\n */\n readonly payloadOf?: (\n stage: Stage | undefined,\n conversation: Conversation<R>,\n instructions: string | null,\n ) => unknown;\n /** The model id every brain call invokes. Omit → `null` (the host's default). */\n readonly modelId?: string | null;\n /**\n * Livelock guard: bound on model round-trips within one run. On\n * `turnCount >= maxTurns` the run fails `{ reason: \"turn_limit\" }`. Omit → no\n * turn guard (the other stop conditions still bound the loop).\n */\n readonly maxTurns?: number;\n /**\n * Wall-clock guard: total milliseconds from `run.startedAt` the run may take.\n * At the turn boundary, `at - run.startedAt >= maxElapsedMs` fails the run\n * `{ reason: \"elapsed_limit\" }`. Unlike `deadlineMs` — a no-progress watchdog\n * that RESTARTS on every advance — this budget never restarts, so a run that\n * keeps progressing is bounded by it. Omit → no wall-clock cap.\n *\n * `startedAt` is durable, so a resumed run continues the ORIGINAL budget\n * rather than starting a fresh one; the elapsed span a killed run spent dead\n * counts against it.\n */\n readonly maxElapsedMs?: number;\n /**\n * The consumer's own stop condition, consulted at the turn boundary once the\n * turn-count and wall-clock guards have passed. `true` settles the run\n * `cancelled` at `at` — the same terminal an aborted `signal` reaches, so the\n * transcript stands and no further model call goes out. Omit → no predicate.\n *\n * Where `maxTurns` and `maxElapsedMs` bound a quantity this agent counts,\n * this bounds one only the caller can see (a token ledger, an external flag,\n * a condition on the turns so far). It must be PURE and total over the state\n * it is handed — the reducer calls it, so a replay of the same Msg log calls\n * it with the same state and must get the same answer. It is config, not\n * Model: a resumed run consults the predicate the config passed to THIS boot.\n */\n readonly stopWhen?: (state: AgentState<Stage, P, O, R>) => boolean;\n\n // ---- determinism seam ----------------------------------------------------\n /**\n * The impurity-injection seam for the inherited brain-call retry jitter — the\n * ONE place this otherwise-pure machine reads randomness. Pass a fixed\n * `() => 0` to pin backoff (tests, replay, durability proofs). Omit →\n * `Math.random`, read only at the resilient-call verb boundary.\n */\n readonly rng?: () => number;\n}\n\n/**\n * The agent configuration — the core seams intersected with the snapshotting discriminant\n * (`AgentSnapshotConfig`). Type parameters are documented on `AgentConfigCore`;\n * the only addition here is that `snapshotEvery` is the discriminant that drives\n * whether `toMachine` requires (or forbids) the `snapshot_write` interpret\n * handler.\n */\nexport type AgentConfig<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd = Cmd,\n Msg = unknown,\n> = AgentConfigCore<Stage, P, O, R, TC, Msg> &\n AgentSnapshotConfig &\n AgentCompactionConfig<R, Msg>;\n\n// ===========================================================================\n// Slice — the Model field this configuration owns. Three composed slices + the loop's\n// conversation. Plain data end to end → durable + replayable.\n// ===========================================================================\n\n/**\n * Why a run terminated as `failed`, beyond monitored-run's own reasons. The\n * `turn_limit` reason is the agent's livelock guard and `elapsed_limit` its\n * wall-clock one; deadline / stage failures surface through the monitored-run\n * slice's own `failure`.\n */\nexport type AgentFailure =\n | { readonly reason: \"turn_limit\"; readonly at: number }\n | { readonly reason: \"elapsed_limit\"; readonly at: number }\n | { readonly reason: \"llm\"; readonly error: unknown; readonly at: number };\n\n/**\n * The agent slice — every composed wrapper's slice plus the loop's conversation\n * and the agent-specific failure annotation.\n *\n * - `run` — the `../monitored-run` slice (pipeline position +\n * lifecycle + watchdog). The OUTER lifecycle truth.\n * - `resilience` — the `../llm-call` (= resilient-call) slice (brain-call\n * retry / backoff). Per-purpose retry lives here.\n * - `tools` — the `../fan-out` ledger for the current turn's tools.\n * - `conversation` — the agentic-stage loop state. `null` until the loop is\n * entered (the consumer seeds it at the agentic stage).\n * - `failure` — the agent-specific terminal annotation (turn-limit /\n * llm), null otherwise. Distinct from `run.failure`.\n * - `instructions` — the system prompt this run was configured with, set at\n * `init` and never touched by a fold (ADR 0004).\n */\nexport interface AgentState<\n Stage,\n P extends string,\n O extends Record<P, unknown>,\n R,\n> {\n readonly run: MonitoredRunState<Stage>;\n readonly resilience: ResilientState<LlmCall<P>, LlmOk<P, O>>;\n readonly tools: FanOutState<ToolCall, ToolOutcome<R>>;\n readonly conversation: Conversation<R> | null;\n /**\n * The compaction round-trip's resilient slice (#85, design B1) — a DEDICATED\n * resilient-call slice for the reserved `$compact` purpose, separate from the\n * brain `resilience` slice so a compaction retry/backoff never disturbs the\n * brain call's breaker or retry counter. Always present (empty `calls` when no\n * compaction is in flight, or when no policy is configured) so the slice stays\n * a flat plain-data record — durable + replayable like every composed wrapper.\n */\n readonly compaction: ResilientState<\n LlmCall<CompactionPurpose>,\n LlmOk<CompactionPurpose, CompactionOutputs>\n >;\n /**\n * The per-tool timeout / retry ladders (#117) — one dedicated resilient-call\n * slice PER TOOL NAME, because the policy is declared per tool and one slice\n * carries one config. Keyed by tool name; each slice's own keys are\n * {@link toolCallKey}s, so two concurrent calls to the same tool climb\n * independent ladders while sharing the tool's declared policy.\n *\n * A tool declaring neither `timeoutMs` nor `retry` mints no entry, so this is\n * `{}` for every agent that uses no per-tool knob — the addition costs an\n * empty record on the durable Model and nothing else.\n *\n * The result arm is `null`: a tool's VALUE settles through the fan-out ledger\n * and the conversation, exactly as before. This slice tracks only the ladder —\n * which attempt is out, when the next one is due, and when the budget is spent\n * — which is what has to survive a reload.\n */\n readonly toolResilience: Readonly<\n Record<string, ResilientState<ToolCall, null>>\n >;\n /**\n * The `callId`s whose PUBLIC outcome is already a failure (#145) — a tool the\n * ladder settled on its deadline or on a spent retry budget, or one whose own\n * error was folded. A promise cannot be cancelled, so the abandoned attempt\n * may still resolve; when it does, its late `_ok` names a `callId` listed\n * here and every public channel stays silent about it.\n *\n * The fan-out already drops the late value (its entry is gone, so the fold is\n * a no-op), but \"folds nothing\" and \"emits nothing\" are two different facts:\n * the event projector is Msg-shaped and would otherwise push a `ToolSettled`\n * for a `callId` `onToolError` already reported as `{ _tag: \"timeout\" }`. The\n * projector reads the post-transition state, by which point the ladder has\n * forgotten the key, so the discriminator is carried HERE rather than derived\n * from a presence check that erases both readings.\n *\n * Plain data, one string per failed call, cleared by `start` with the rest of\n * the prior run's bookkeeping. It survives the batch drain and the stage\n * retire on purpose — that is exactly when a late settle arrives.\n */\n readonly refusedCalls: readonly string[];\n readonly failure: AgentFailure | null;\n /**\n * The run's terminal output — the FIRST-CLASS result (issue #46). `null`\n * until the pipeline finishes; set to the last model turn (the empty-tool\n * turn that retired the final stage) the instant `run.phase` becomes `\"done\"`.\n *\n * This survives the `conversation` clear on stage retire: clearing the\n * conversation is correct durability hygiene (a finished stage's transcript\n * is not live state), but the run's PRODUCT is, so it lives here on the\n * durable slice rather than being scraped off the `observe` firehose by\n * matching the private `resilient_ok` Msg and racing the clear (the old\n * `captureLastTurn` dance this field deletes). A consumer reads\n * `runtime.result()?.output` / `(await runtime.done()).output`.\n *\n * Typed `AgentTurn | null` (not `O[P]`): the run's output is always a model\n * turn — the `O extends Record<P, AgentTurn>` type bound pins every purpose's\n * output to an `AgentTurn`, and the terminating turn is the one with no tool\n * calls. The wider `Record<P, unknown>` bound on `AgentState` itself does not\n * constrain `O[P]`, so naming the concrete `AgentTurn` keeps this field's type\n * total without a purpose-indexing narrow.\n */\n readonly output: AgentTurn | null;\n /**\n * The system prompt, durable beside the transcript it governs. `null` when\n * the config named none. Read by `brainCall` on every model call — a\n * rehydrated or replayed run prompts with what the Model says, never with\n * what a closure happens to hold now.\n */\n readonly instructions: string | null;\n}\n\n// ===========================================================================\n// Lifecycle status — the ONE typed channel callers read instead of re-deriving\n// the private slice shape.\n// ===========================================================================\n\n/**\n * The unified terminal failure the agent settles on. The agent terminates `failed`\n * through TWO independent slice channels:\n *\n * - `state.failure` (`AgentFailure`) — the AGENT'S OWN annotation\n * (`turn_limit` livelock guard / `elapsed_limit` wall-clock guard / `llm`\n * exhausted-retry). Set WITHOUT moving\n * `run.phase` (it stays `running`); `isSettled` treats a non-null `failure`\n * as terminal regardless of `run.phase`.\n * - `state.run.failure` (`RunFailure`) — the monitored-run channel\n * (`deadline` watchdog / `stage` failure), present iff `run.phase` is\n * `\"failed\"`.\n *\n * Callers used to union these by hand at every status question. `status`\n * collapses them into ONE `failure`, so a consumer reads `status(s).failure`\n * without knowing which channel produced it.\n */\nexport type AgentTerminalFailure<Stage> = AgentFailure | RunFailure<Stage>;\n\n/**\n * The agent's lifecycle status — THE single typed channel for \"what is this run\n * doing?\". A discriminated union on `kind` so any change to the\n * private slice shape (`Awaiting`, the failure channels, `run.phase`) forces a\n * compile error at the call sites that switch on it, instead of silently\n * breaking a hand-rolled re-derivation. Make-invalid-states-unrepresentable:\n *\n * - `idle` — never started: `run.phase === \"idle\"`, the slice straight\n * out of `init` before any `agent_start`. Distinct from\n * `running` so a \"start or resume?\" decision never boots a\n * run that has not begun (#92); the next move is `agent_start`.\n * - `running` — live, NOT awaiting tools (a brain call is in flight, or the\n * run is between stages). Not resumable on cold wake by\n * itself — the in-flight brain call re-fires from `boot`.\n * A `stale` run reads here too: monitored-run documents it\n * as a soft, still-resumable live mark that the next\n * `progress` flips back to `running`.\n * - `suspended` — the RESUMABLE case: running + a live conversation +\n * `awaiting.kind === \"tools\"`. `pending` is the outstanding\n * tool calls (`conversation.awaiting` … the in-flight batch),\n * read off `tools.running`. This is exactly the shape\n * `agentIsResumable` re-derived by hand.\n * - `done` — the pipeline finished; `output` is the terminal model turn\n * stamped on `state.output` (issue #46), `null` if the run\n * produced no turn.\n * - `failed` — terminal failure; `failure` is the UNIFIED channel\n * (`AgentTerminalFailure`), absorbing the `state.failure` vs\n * `state.run.failure` dual channel so callers stop unioning.\n * - `cancelled` — stopped because the caller asked — an aborted `AbortSignal`,\n * or their own `stopWhen` answering `true` at a turn boundary;\n * `at` is when the stop landed. Terminal and distinct from\n * `failed`: nothing went wrong, the caller asked, so a consumer\n * branching on failure does not have to except one reason. There is no\n * `output` — a cancelled run produced no terminal turn, and a\n * `null` one here would be indistinguishable from a `done` run\n * that produced none.\n */\nexport type AgentStatus<Stage> =\n | { readonly kind: \"idle\" }\n | { readonly kind: \"running\" }\n | { readonly kind: \"suspended\"; readonly pending: readonly ToolCall[] }\n | { readonly kind: \"done\"; readonly output: AgentTurn | null }\n | { readonly kind: \"failed\"; readonly failure: AgentTerminalFailure<Stage> }\n | { readonly kind: \"cancelled\"; readonly at: number };\n\n/**\n * Ask where an agent run stands: pass its state, get back one of `idle`,\n * `running`, `suspended` (with the tool calls it is waiting on), `done` (with\n * the output) or `failed` (with the failure).\n *\n * Read this instead of picking at the state's own fields. PURE — reads no\n * clock or randomness, allocates one small record.\n *\n * Ordering is terminal-first so a settled run never reports `running`, and a\n * never-started one never reports live:\n *\n * 1. `state.failure` (the agent's own annotation, set WITHOUT moving\n * `run.phase`) → `failed`. Checked first because `turn_limit` / `llm`\n * leave `run.phase === \"running\"`; reading `run.phase` first would\n * misreport such a run as `running`. This is the canonical failure source\n * when present.\n * 2. `run.phase === \"idle\"` → `idle`. Never started (#92); after the failure\n * check so the annotation stays canonical, before every live reading so\n * an `init` slice is never mistaken for a run in flight.\n * 3. `run.phase === \"failed\"` → `failed`, carrying `run.failure` (deadline /\n * stage). The fallback channel.\n * 4. `run.phase === \"done\"` → `done` with `state.output` (#46).\n * 5. `run.phase === \"cancelled\"` → `cancelled`, carrying when the stop landed.\n * 6. `running` / `stale` + conversation + `awaiting.kind === \"tools\"` →\n * `suspended` with the outstanding tool calls (`tools.running`). THE\n * resumability condition; otherwise the run reads `running`.\n *\n * Steps 2–6 are ONE exhaustive `switch` over `run.phase` closed by `absurd`, not\n * an `if` chain with a trailing `return { kind: \"running\" }`. Under the chain a\n * phase added to the slice and forgotten here reported as `running` — a terminal\n * run described as live, which is the worst answer this function can give and one\n * nothing would have caught. The switch turns that omission into a type error.\n */\nexport function status<\n Stage,\n P extends string,\n O extends Record<P, unknown>,\n R,\n>(s: AgentState<Stage, P, O, R>): AgentStatus<Stage> {\n // 1) The agent's own failure annotation is canonical — it is set without\n // moving `run.phase` (turn_limit / llm leave the run `running`), so it\n // MUST be read before `run.phase` or such a failure reports as `running`.\n if (s.failure !== null) {\n return { kind: \"failed\", failure: s.failure };\n }\n // Bound to a local so the switch narrows ONE reference: `absurd(run)` below is\n // only reachable — and only type-checks — while every phase above returns.\n const run = s.run;\n switch (run.phase) {\n // 2) Never started — monitored-run's `idle` phase is exactly the \"has this\n // actually started?\" guard, and the status channel keeps that distinction.\n case \"idle\":\n return { kind: \"idle\" };\n // 3) The monitored-run terminal failure (deadline / stage). `run.failure`\n // rides ONLY the `failed` arm of the discriminated union, so narrowing on\n // `phase === \"failed\"` surfaces it with no nullable side field and no\n // fabricated fallback — the old \"failed-yet-failure-null\" state is\n // unrepresentable.\n case \"failed\":\n return { kind: \"failed\", failure: run.failure };\n // 4) The pipeline finished — the terminal output landed on `state.output`.\n case \"done\":\n return { kind: \"done\", output: s.output };\n // 5) Stopped from outside. Terminal, and deliberately NOT folded into\n // `failed`: the unified failure channel answers \"what went wrong\", and\n // nothing did.\n case \"cancelled\":\n return { kind: \"cancelled\", at: run.at };\n // 6) Live. Awaiting tools is the resumable shape — the outstanding calls are\n // the in-flight fan-out batch (`tools.running`); anything else is plain\n // `running`, which is also where `stale` reads (a soft mark the next\n // progress clears, not an outcome).\n case \"running\":\n case \"stale\":\n return s.conversation !== null && s.conversation.awaiting.kind === \"tools\"\n ? { kind: \"suspended\", pending: s.tools.running }\n : { kind: \"running\" };\n }\n // No `default` arm: an unhandled phase reaches here still typed, and `absurd`\n // takes only `never` — so adding a phase to the slice breaks the build at\n // exactly the reader that would otherwise mis-describe it.\n return absurd(run);\n}\n","/**\n * @demlik/tea/agent — the per-tool timeout / retry ladder (#117).\n *\n * A `tool()` declares `timeoutMs` and/or `retry`; this module is what runs them.\n * It is the agent's third `resilient-call` composition, beside the brain slice\n * and the dedicated `$compact` one, and it exists for the same reason those do:\n * the ladder has to be DATA on the Model, not control flow inside the handler.\n * A backoff loop written inside the effect boundary is lost to a process kill\n * mid-ladder — which is exactly the durability `@demlik/tea` exists to provide,\n * so the appliance may not ask a user to give it up to get a retry.\n *\n * ## One slice per tool NAME, one key per CALL\n *\n * `createResilientCall` closes over ONE config, and the policy here is declared\n * per tool — so there is one instance, and one slice, per tool name. Within a\n * name, each in-flight call gets its own key ({@link toolCallKey}), so two\n * concurrent calls to the same tool climb independent ladders under one policy.\n * The name rides INSIDE the key because the timer Subs the family arms are keyed\n * `resilient:retry:{key}` / `resilient:deadline:{key}`: the key is the only\n * thing a fired timer carries, so it must be enough to find the slice again.\n *\n * ## What it does not touch\n *\n * A tool declaring neither field mints no slice entry and takes the plain\n * fan-out launch/settle path unchanged — the \"omit a brick, skip its gate\" rule\n * the resilience family already holds, lifted to the tool set.\n */\n\nimport type {\n DeadlineExceeded,\n DeadlineSub,\n} from \"../internal/resilience/deadline\";\nimport {\n createResilientCall,\n type ResilientState,\n type RunCmd,\n} from \"../internal/resilience/resilient-call\";\nimport { toolErrorReason } from \"./tool\";\nimport {\n TOOL_RETRY_EXHAUSTED_TAG,\n TOOL_TIMEOUT_TAG,\n type ToolCall,\n type ToolFailure,\n type ToolResilience,\n} from \"./types\";\n\n/**\n * The prefix every tool ladder key carries. It namespaces tool keys away from\n * the brain slice's purpose keys and the compaction slice's `$compact`, so a\n * fired timer routes by id with no ambiguity — the same convention `$compact`\n * already uses, one level down.\n */\nconst TOOL_KEY_PREFIX = \"$tool:\";\n\n/** The separator between the tool's name and the call's id inside a key. */\nconst NAME_CALL_SEP = \"#\";\n\n/**\n * The ladder key for one in-flight call: the tool's name and the model's\n * `callId`, both recoverable from the key a fired timer carries. PURE.\n */\nexport function toolCallKey(name: string, callId: string): string {\n return `${TOOL_KEY_PREFIX}${name}${NAME_CALL_SEP}${callId}`;\n}\n\n/** The tool name and callId a {@link toolCallKey} was built from, or `null`. PURE. */\nfunction readToolCallKey(\n key: string,\n): { readonly name: string; readonly callId: string } | null {\n if (!key.startsWith(TOOL_KEY_PREFIX)) return null;\n const body = key.slice(TOOL_KEY_PREFIX.length);\n const at = body.indexOf(NAME_CALL_SEP);\n if (at <= 0) return null;\n return { name: body.slice(0, at), callId: body.slice(at + 1) };\n}\n\n/**\n * Whether a fired timer's Sub id belongs to a tool ladder — the routing test\n * the agent's `onTimer` uses to pick this slice over the brain / compaction\n * ones. PURE.\n */\nexport function isToolTimerId(id: string): boolean {\n return keyOfTimerId(id) !== null;\n}\n\n/** The ladder key a `resilient:*` Sub id was minted for, or `null`. PURE. */\nfunction keyOfTimerId(id: string): string | null {\n for (const prefix of [\"resilient:retry:\", \"resilient:deadline:\"]) {\n if (id.startsWith(prefix)) {\n const key = id.slice(prefix.length);\n return key.startsWith(TOOL_KEY_PREFIX) ? key : null;\n }\n }\n return null;\n}\n\n/** The per-tool-name slice map the agent Model carries. */\nexport type ToolResilienceState = Readonly<\n Record<string, ResilientState<ToolCall, null>>\n>;\n\n/**\n * A call the ladder has decided is over — settle it into the fan-out with\n * `failure`. The failure is structural: it carries the `_tag` the ladder settled\n * under (`timeout` / `retry_exhausted`) beside the `reason` the model reads, so\n * a ladder-authored ending is discriminable by host code exactly as a tool's own\n * declared failure is (#115).\n */\nexport interface ToolSettleOrder {\n readonly callId: string;\n readonly failure: ToolFailure;\n}\n\n/** What a timer fire produced: launches to re-issue, and calls the ladder gave up on. */\nexport interface ToolTimerOutcome<TC> {\n readonly cmds: readonly TC[];\n readonly settle: readonly ToolSettleOrder[];\n}\n\n/**\n * The ladder as the agent's reducer uses it — every verb PURE, `at` the only\n * clock, and every return a `[slice, …]` tuple the caller folds onto the Model.\n */\nexport interface ToolLadder<TC> {\n /** The starting slice: no tool has laddered yet. */\n readonly init: () => ToolResilienceState;\n /**\n * Launch `calls`: each one either through its tool's resilient gate (which\n * arms the timeout and emits the run Cmd) or, for a tool with no policy,\n * straight through `toolOf` as it always was.\n */\n readonly launch: (\n s: ToolResilienceState,\n calls: readonly ToolCall[],\n at: number,\n ) => readonly [ToolResilienceState, readonly TC[]];\n /**\n * Record a settled-OK call: drop its ladder bookkeeping so the timeout Sub\n * disarms and the tool's next call starts a fresh ladder.\n */\n readonly ok: (\n s: ToolResilienceState,\n call: ToolCall,\n at: number,\n ) => ToolResilienceState;\n /**\n * Record a failed attempt. The second element is `null` when the ladder\n * ABSORBED the failure — another attempt is armed, the fan-out must not see\n * it — and the failure to settle with when the call is over. That failure is\n * either the attempt's own, passed through untouched, or the ladder's\n * `retry_exhausted` one; both carry a `_tag` beside the model's `reason`.\n */\n readonly err: (\n s: ToolResilienceState,\n call: ToolCall,\n failure: ToolFailure,\n at: number,\n ) => readonly [ToolResilienceState, ToolFailure | null];\n /** A tool ladder's timer fired: re-issue the next attempt, or give the call up. */\n readonly onTimer: (\n s: ToolResilienceState,\n msg: DeadlineExceeded,\n ) => readonly [ToolResilienceState, ToolTimerOutcome<TC>];\n /**\n * Re-issue the in-flight attempts a cold boot found — see the note on the body.\n * Returns the same outcome shape a timer fire does, because a boot can also END\n * a call: one whose timeout budget was already spent before the kill settles\n * here, without its handler being called again.\n */\n readonly boot: (\n s: ToolResilienceState,\n calls: readonly ToolCall[],\n at: number,\n ) => readonly [ToolResilienceState, ToolTimerOutcome<TC>];\n /** Every armed retry / timeout timer across every tool's ladder. */\n readonly subs: (s: ToolResilienceState) => readonly DeadlineSub[];\n}\n\n/**\n * Build the ladder for one agent from its two config seams: how a call maps to\n * a policy (`resilienceOf`) and how it maps to the effect Cmd (`toolOf`).\n *\n * `rng` is the determinism seam for the backoff jitter, the same one the brain\n * slice takes; it is read only at the family's verb boundary.\n */\nexport function createToolLadder<TC>(\n resilienceOf: (call: ToolCall) => ToolResilience | null,\n toolOf: (call: ToolCall) => TC,\n rng: (() => number) | undefined,\n): ToolLadder<TC> {\n // One `resilient-call` per tool name, memoized on the name. This is\n // config-derived construction, not state: the instance closes over the tool's\n // declared policy and nothing else, so the same name always yields the same\n // verbs and a replay reproduces them exactly.\n const instances = new Map<\n string,\n ReturnType<typeof createResilientCall<ToolCall, null>>\n >();\n\n /** The resilient-call for `call`'s tool, or `null` when it declared no policy. */\n function rcFor(call: ToolCall) {\n const policy = resilienceOf(call);\n if (policy === null) return null;\n if (policy.timeoutMs === undefined && policy.retry === undefined) {\n return null;\n }\n const cached = instances.get(call.name);\n if (cached !== undefined) return cached;\n const made = createResilientCall<ToolCall, null>(\n {\n ...(policy.retry !== undefined ? { retry: policy.retry } : {}),\n ...(policy.timeoutMs !== undefined\n ? { deadline: { ms: policy.timeoutMs } }\n : {}),\n },\n rng,\n );\n instances.set(call.name, made);\n return made;\n }\n\n /** This tool's slice, defaulting to a fresh one — also the rehydration guard. */\n function sliceOf(\n s: ToolResilienceState,\n name: string,\n rc: ReturnType<typeof createResilientCall<ToolCall, null>>,\n ): ResilientState<ToolCall, null> {\n return s[name] ?? rc.init();\n }\n\n /** Re-key the family's `resilient_run` carriers to the consumer's tool Cmds. */\n function toLaunchCmds(runCmds: readonly RunCmd<ToolCall>[]): readonly TC[] {\n return runCmds.map((cmd) => toolOf(cmd.input));\n }\n\n const launch: ToolLadder<TC>[\"launch\"] = (s, calls, at) => {\n let next = s;\n const cmds: TC[] = [];\n for (const call of calls) {\n const rc = rcFor(call);\n if (rc === null) {\n cmds.push(toolOf(call));\n continue;\n }\n const [slice, runCmds] = rc.attempt(\n sliceOf(next, call.name, rc),\n toolCallKey(call.name, call.callId),\n call,\n at,\n );\n next = { ...next, [call.name]: slice };\n cmds.push(...toLaunchCmds(runCmds));\n }\n return [next, cmds];\n };\n\n const ok: ToolLadder<TC>[\"ok\"] = (s, call, at) => {\n const rc = rcFor(call);\n if (rc === null) return s;\n const key = toolCallKey(call.name, call.callId);\n // Settling an `_ok` closes the ladder for this key: it drops `retry[key]`\n // and moves the phase to `succeeded`, which is what disarms the timeout Sub.\n // The result arm is `null` on purpose — the tool's VALUE travels through\n // the fan-out ledger, and duplicating it here would put one fact in two\n // places on the durable Model.\n const { call: slice } = rc.settle(sliceOf(s, call.name, rc), {\n cmd: { key },\n value: null,\n at,\n });\n return { ...s, [call.name]: forget(slice, key) };\n };\n\n const err: ToolLadder<TC>[\"err\"] = (s, call, failure, at) => {\n const rc = rcFor(call);\n if (rc === null) return [s, failure];\n const key = toolCallKey(call.name, call.callId);\n const before = sliceOf(s, call.name, rc);\n // Settling an `_err` records the attempt and consults the policy: it either\n // arms the next one (`retrying`, with the retry timer in `subs`) or settles\n // the key `failed`. Both outcomes are Model writes — nothing is retried\n // inside an effect, which is the whole point of routing through here.\n const { call: slice, outcome } = rc.settle(before, {\n cmd: { key },\n error: failure,\n at,\n });\n if (outcome.kind === \"retrying\") {\n // Absorbed: the fan-out entry stays `running` and the conversation learns\n // nothing, so the model never sees an attempt the ladder is still working.\n return [{ ...s, [call.name]: slice }, null];\n }\n // Over. With a retry policy the call spent its budget and says so, carrying\n // the attempt count and the last attempt's own reason so the model reads the\n // real failure rather than only the bookkeeping. With no retry policy\n // (a `timeoutMs`-only tool) the first failure IS the outcome, unchanged.\n const attempts = before.retry[key]?.attempt;\n const settled =\n resilienceOf(call)?.retry === undefined\n ? failure\n : exhaustedFailure((attempts ?? 0) + 1, failure);\n return [{ ...s, [call.name]: forget(slice, key) }, settled];\n };\n\n const onTimer: ToolLadder<TC>[\"onTimer\"] = (s, msg) => {\n const key = keyOfTimerId(msg.id);\n const parsed = key === null ? null : readToolCallKey(key);\n if (key === null || parsed === null) return [s, { cmds: [], settle: [] }];\n const slice = s[parsed.name];\n if (slice === undefined) return [s, { cmds: [], settle: [] }];\n // The instance is rebuilt from the call the ladder remembers, so a timer\n // that fires after a reload runs under the tool's declared policy without\n // the slice having to carry the policy itself.\n const remembered = inputOf(slice, key);\n const rc = remembered === null ? null : rcFor(remembered);\n if (rc === null) return [s, { cmds: [], settle: [] }];\n const [next, runCmds] = rc.onTimer(slice, msg);\n const phase = next.calls[key];\n // The deadline arm settles `failed` with the family's plain-data sentinel,\n // whatever the attempt in flight is doing — so the CALL ends on time even\n // though nothing here can end the promise. The attempt's late settle then\n // arrives for a callId the fan-out no longer has running and folds nothing.\n if (phase?.phase === \"failed\" && isDeadline(phase.error)) {\n return [\n { ...s, [parsed.name]: forget(next, key) },\n {\n cmds: [],\n settle: [{ callId: parsed.callId, failure: timeoutFailure() }],\n },\n ];\n }\n return [\n { ...s, [parsed.name]: next },\n { cmds: toLaunchCmds(runCmds), settle: [] },\n ];\n };\n\n const boot: ToolLadder<TC>[\"boot\"] = (s, calls, at) => {\n let next = s;\n const cmds: TC[] = [];\n const settle: ToolSettleOrder[] = [];\n for (const call of calls) {\n const rc = rcFor(call);\n if (rc === null) {\n cmds.push(toolOf(call));\n continue;\n }\n const key = toolCallKey(call.name, call.callId);\n // Re-anchor this tool's whole slice FIRST. The downtime between the kill\n // and this wake is time in which no attempt ran, so it is not the tool's\n // to be charged for; `resume` moves every live call's charging clock to\n // `at` and leaves the remaining budget alone. It runs before the phase is\n // read, before `attempt`, and before `subs` derives any timer instant.\n next = {\n ...next,\n [call.name]: rc.resume(sliceOf(next, call.name, rc), at),\n };\n const phase = sliceOf(next, call.name, rc).calls[key]?.phase;\n // A call the kill caught BETWEEN attempts is not re-issued: its next\n // attempt is already owed to the retry timer, which `subs` re-arms off the\n // rehydrated slice. Re-issuing here would run an extra handler call the\n // ladder never authorized and reset nothing — the resume would silently\n // buy an attempt the budget did not have.\n if (phase === \"waiting_retry\") continue;\n const [slice, runCmds] = rc.attempt(\n sliceOf(next, call.name, rc),\n key,\n call,\n at,\n );\n // The gate settles instead of dispatching when the budget is spent, so a\n // call that ran out of time before the kill ends HERE — the port is not\n // called again to produce a result the ladder would throw away.\n const settled = slice.calls[key];\n if (settled?.phase === \"failed\" && isDeadline(settled.error)) {\n next = { ...next, [call.name]: forget(slice, key) };\n settle.push({ callId: call.callId, failure: timeoutFailure() });\n continue;\n }\n next = { ...next, [call.name]: slice };\n cmds.push(...toLaunchCmds(runCmds));\n }\n return [next, { cmds, settle }];\n };\n\n const subs: ToolLadder<TC>[\"subs\"] = (s) => {\n const out: DeadlineSub[] = [];\n for (const slice of Object.values(s)) {\n // Every key in one name's slice shares that tool's policy, so any live\n // call rebuilds the instance whose `subs` knows which timers to arm. No\n // live call → nothing to arm, and nothing to rebuild it from.\n const sample = firstInput(slice);\n const rc = sample === null ? null : rcFor(sample);\n if (rc !== null) out.push(...rc.deadlines(slice));\n }\n return out;\n };\n\n return { init: () => ({}), launch, ok, err, onTimer, boot, subs };\n}\n\n/**\n * Drop a settled key's entry entirely rather than leaving it `succeeded` /\n * `failed` on the Model. The fan-out ledger and the conversation already carry\n * the outcome; a per-call entry that outlived its call would grow the durable\n * slice once per tool call for the whole run. PURE.\n */\nfunction forget(\n s: ResilientState<ToolCall, null>,\n key: string,\n): ResilientState<ToolCall, null> {\n const { [key]: _settled, ...calls } = s.calls;\n const { [key]: _spent, ...retry } = s.retry;\n return { ...s, calls, retry };\n}\n\n/** The `ToolCall` a key's live phase remembers, or `null`. PURE. */\nfunction inputOf(\n s: ResilientState<ToolCall, null>,\n key: string,\n): ToolCall | null {\n const call = s.calls[key];\n if (call === undefined) return null;\n return call.phase === \"running\" || call.phase === \"waiting_retry\"\n ? call.input\n : null;\n}\n\n/** Any live call in a slice — enough to rebuild the tool's instance. PURE. */\nfunction firstInput(s: ResilientState<ToolCall, null>): ToolCall | null {\n for (const key of Object.keys(s.calls)) {\n const input = inputOf(s, key);\n if (input !== null) return input;\n }\n return null;\n}\n\n/** Whether a settled error is the family's deadline sentinel. PURE. */\nfunction isDeadline(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { _tag?: unknown })._tag === \"deadline_exceeded\"\n );\n}\n\n/**\n * The failure a spent ladder settles under: the tag, the attempts it burned, and\n * the last attempt's own reason — so the model reads the actual failure and not\n * only the fact that a budget ran out, and host code branching on\n * `_tag === \"retry_exhausted\"` reads `attempts` and `last` as fields rather than\n * parsing them back out of the sentence. PURE.\n */\nfunction exhaustedFailure(attempts: number, last: ToolFailure): ToolFailure {\n return taggedFailure({\n _tag: TOOL_RETRY_EXHAUSTED_TAG,\n attempts,\n last: last.reason,\n });\n}\n\n/** The failure a call that spent its `timeoutMs` budget settles under. PURE. */\nfunction timeoutFailure(): ToolFailure {\n return taggedFailure({ _tag: TOOL_TIMEOUT_TAG });\n}\n\n/**\n * Render a ladder-authored `{ _tag, …payload }` into the settled failure: the\n * tag and its payload spread first, then `reason` and `kind` written over them,\n * exactly as the router does for a tool's own declared failure. One rendering\n * rule for both sources is what makes `onToolError`'s `switch` total. PURE.\n */\nfunction taggedFailure(tagged: {\n readonly _tag: string;\n readonly [field: string]: unknown;\n}): ToolFailure {\n return { ...tagged, reason: toolErrorReason(tagged), kind: \"error\" };\n}\n","/**\n * @demlik/tea/agent — `defineAgent`, the convenience layer over `createAgent`.\n *\n * `defineAgent({ model, tools, instructions })` is the three-line door: it\n * defaults the single-stage wiring (`stages`, `turnOf`, `schemas`), derives the\n * tool handlers from `toolRouter`, renders the prompt off the Model, and absorbs\n * the drive loop through `driveToDone`. It hides wiring, never state (ADR\n * 0015): the Model it runs is the same `AgentState` a hand-wired `createAgent`\n * produces, under the same keys, and `machine(input)` is the door down to the\n * raw kernel `run`. Each hidden thing is a named helper below.\n */\n\nimport type { Machine, Subscribe } from \"../index\";\nimport type { EndedRun } from \"../internal/flow/monitored-run\";\nimport type { LlmCall } from \"../internal/llm-call\";\nimport type { DeadlinesSub } from \"../internal/resilience/deadline\";\nimport { driveToDone, run } from \"../promise\";\nimport { MsgType } from \"../protocol\";\nimport { cmdEdgeOf, type Interpret } from \"../pure/core\";\nimport type { RetryPolicy } from \"../retry-backoff\";\nimport type { BootingRuntime, CtxArg, Store } from \"../runtime-types\";\nimport {\n type AgentCompactOkMsg,\n type AgentCompactRunCmd,\n COMPACTION_PURPOSE,\n type CompactionPolicy,\n} from \"./compaction\";\nimport { createAgent } from \"./index\";\nimport {\n type AgentCmd,\n type AgentEvent,\n type AgentMachineMsg,\n agentBootMsg,\n agentCancelMsg,\n agentEvents,\n} from \"./machine\";\nimport type { MessageLoader, PlainModel } from \"./model\";\nimport {\n type AnyToolDef,\n type ToolCmd,\n type ToolFailureOf,\n type ToolResult,\n type ToolRouter,\n type ToolsCtx,\n toolRouter,\n type WiredToolMsg,\n} from \"./tool\";\nimport {\n type AgentConfigCore,\n type AgentState,\n type AgentTurn,\n agentTurnSchema,\n type Conversation,\n isStreamingModel,\n type ModelStream,\n type StreamingModel,\n status,\n type ToolCall,\n type ToolOutcome,\n type TurnChunk,\n} from \"./types\";\n\n// ===========================================================================\n// The convenience layer's vocabulary: the messages a plain model reads, the\n// prompt they are rendered from, and the one-purpose agent it fixes.\n// ===========================================================================\n\n/**\n * One message a `defineAgent` `model` receives. Plain data the adapter renders into\n * its provider's shape: the head is the `instructions` (when set) and the\n * run's `input`; then, per model turn, the `assistant` turn followed by the\n * `tool` outcomes that turn asked for. A tool outcome rides as data — the\n * adapter decides how a failure reads to its model. An `assistant` message\n * carries the turn's opaque `provider` slot exactly as the adapter returned it\n * (see `AgentTurn`), present only when the stored turn has one.\n */\nexport type AgentMessage =\n | { readonly role: \"system\"; readonly content: string }\n | { readonly role: \"user\"; readonly content: string }\n | {\n readonly role: \"assistant\";\n readonly content: string;\n readonly toolCalls: readonly ToolCall[];\n readonly provider?: unknown;\n }\n | {\n readonly role: \"tool\";\n readonly callId: string;\n readonly name: string;\n readonly outcome: ToolOutcome<unknown>;\n };\n\n/**\n * The brain-call payload `defineAgent` builds from the durable state — everything\n * `messagesOf` renders, so the prompt is a pure function of the Model and the\n * resilient slice carries exactly what was sent.\n */\nexport interface AgentPrompt<R> {\n readonly instructions: string | null;\n readonly input: string | null;\n readonly conversation: Conversation<R>;\n}\n\n/** The one purpose a `defineAgent` agent runs. */\nexport type LidPurpose = \"act\";\ntype LidOutputs = { readonly [K in LidPurpose]: AgentTurn };\n\n/** The Model a defined agent runs — a hand-wired `createAgent`'s, key for key. */\nexport type DefinedAgentState<T extends AnyToolDef> = AgentState<\n string,\n LidPurpose,\n LidOutputs,\n ToolResult<T>\n>;\n\n/**\n * The Model `run` RESOLVES with — {@link DefinedAgentState} whose `run` slice is\n * narrowed to the ended phases ({@link EndedRun}).\n *\n * `run`'s terminal predicate is `done || cancelled` and its `failed` one rejects,\n * so the never-started `idle` arm is unreachable on the resolved value. Typing\n * the promise as the whole Model published that unreachable arm anyway, and\n * `idle` carries no `runId` — so `(await agent.run(input)).run.runId`, a field\n * every resolved run has, did not typecheck (#155). The narrow is on what `run`\n * can RESOLVE; the `idle` arm is untouched and still carries no `runId`.\n *\n * `DefinedAgentState` itself stays wide, because it is the DURABLE Model: an\n * `init` slice is `idle`, and a `Store<DefinedAgentState<T>>` has to hold one.\n */\nexport type DefinedAgentResolvedState<T extends AnyToolDef> = Omit<\n DefinedAgentState<T>,\n \"run\"\n> & { readonly run: EndedRun<string> };\n\n/** The ctx the tools' handlers read, intersected — what `run` asks for. */\nexport type DefinedAgentCtx<T extends AnyToolDef> = ToolsCtx<T>;\n\n/** The Msg union a defined agent's machine folds. */\nexport type DefinedAgentMsg<T extends AnyToolDef> =\n | AgentMachineMsg<LidPurpose, LidOutputs, ToolResult<T>>\n | WiredToolMsg<T>;\n\n/**\n * The Cmd union a defined agent's machine emits — one interpret cell per member.\n *\n * Snapshotting is fixed OFF (the lid checkpoints through the run's `store`, not\n * the monitored-run cadence), so `snapshot_write` is out of the union.\n * Compaction is fixed ON, which is the SUPERSET of the two machines\n * `defineAgent` builds: with the knob set the `compact_run` cell is the one the\n * lid wires, and without it the reducer provably emits no such Cmd, so the\n * machine carries no cell for it and the union simply has a member nothing\n * reaches. Naming the superset is what lets one type describe both arms — and\n * it is why `with` may wrap `compact_run` on a compacting agent and gets\n * `overlaid`'s \"this machine has none of that cell\" throw on one without.\n */\nexport type DefinedAgentCmd<T extends AnyToolDef> = AgentCmd<\n LidPurpose,\n ToolCmd<T>,\n false,\n true\n>;\n\n/**\n * The interpret table of the machine `defineAgent` wired: one cell per\n * {@link DefinedAgentCmd}, keyed by its `type` — a tool's own Cmd type, the\n * router's `tool_rejected`, and the agent-owned brain call.\n */\nexport type DefinedAgentInterpret<T extends AnyToolDef> = Interpret<\n DefinedAgentMsg<T>,\n DefinedAgentCmd<T>,\n DefinedAgentCtx<T>\n>;\n\n/** The wired machine `defineAgent` builds per `input`. */\nexport type DefinedAgentMachine<T extends AnyToolDef> = Machine<\n DefinedAgentState<T>,\n DefinedAgentMsg<T>,\n DefinedAgentCmd<T>,\n DeadlinesSub,\n DefinedAgentCtx<T>\n>;\n\n/**\n * The machine `defineAgent` builds per `input` beside the handlers it runs\n * under — the interpret table and the `deadline` runner (a machine carries\n * none — #278, #279). It is a `Wired`; feed it to the raw `run`:\n * `run(wired.machine, { ...wired, ctx })`.\n */\nexport type DefinedAgentWired<T extends AnyToolDef> = {\n readonly machine: DefinedAgentMachine<T>;\n readonly interpret: DefinedAgentInterpret<T>;\n readonly subscribe: Subscribe<\n DefinedAgentMsg<T>,\n DeadlinesSub,\n DefinedAgentCtx<T>\n >;\n};\n\n/** `run`'s options for a defined agent's machine. */\ntype RunOptionsOf<T extends AnyToolDef> = Parameters<\n typeof run<\n DefinedAgentState<T>,\n DefinedAgentMsg<T>,\n DefinedAgentCmd<T>,\n DeadlinesSub,\n DefinedAgentCtx<T>,\n AgentEvent<ToolResult<T>>\n >\n>[1];\n\n/**\n * The brain a defined agent runs, in either of its two shapes:\n *\n * - `async (messages) => turn` — the plain port, and the common path.\n * - `async (messages, { onChunk }) => turn` — the same call, plus a side\n * channel it may write token deltas to while the turn is in flight.\n *\n * `defineAgent` takes one field for both and tells them apart by arity\n * (`isStreamingModel`), so there is no config flag saying which you passed and\n * no way for that flag to disagree with the function. Whichever shape you\n * write, the run's Model is the same: the turn it RESOLVES is what the reducer\n * folds, and the deltas end at the `onChunk` run option (see\n * {@link DefinedAgentRunOptions}).\n *\n * Both members are unions of one signature so a model written inline still gets\n * its `messages` parameter typed from the config field.\n */\nexport type DefinedAgentModel =\n | PlainModel<AgentMessage, AgentTurn>\n | StreamingModel<AgentMessage, AgentTurn>;\n\n/**\n * What `defineAgent` takes: the model, the tools and the instructions, plus the\n * four optional guards that stop a run — `maxTurns`, `deadlineMs`,\n * `maxElapsedMs` and `stopWhen` — and the one that keeps a run going, `retry`,\n * the brain call's backoff ladder. Omit every guard and the run is unbounded:\n * it ends only when the model stops asking for tools.\n *\n * Two more knobs bound what a run COSTS rather than whether it ends:\n * `compaction`, which stops the transcript growing, and `toolConcurrency`,\n * which says how many of a turn's tool calls go out at once.\n */\nexport interface DefineAgentConfig<T extends AnyToolDef> {\n /** The brain — either {@link DefinedAgentModel} shape. */\n readonly model: DefinedAgentModel;\n /** The `tool()`s the model may call. */\n readonly tools: readonly T[];\n /**\n * The system prompt — stored on the Model at `init` (ADR 0004) and never\n * re-read, so a resumed run keeps the prompt it started with even across a\n * redeploy that changed this string; to replace a bad prompt already in\n * flight, end that run and start a new one rather than resuming it.\n */\n readonly instructions: string;\n /**\n * Stops a run that keeps going: the maximum number of model round-trips it\n * may take. Once the completed-turn count reaches it the run fails rather\n * than calling the model again. Omit → no limit on turns.\n */\n readonly maxTurns?: number;\n /**\n * Stops a run that stops progressing: milliseconds the run may sit without\n * advancing before it fails. The budget is a no-progress watchdog, not a\n * total wall-clock cap — it restarts each time the run moves. Omit → no\n * watchdog.\n */\n readonly deadlineMs?: number;\n /**\n * Stops a run that keeps going, by the clock: total milliseconds from the\n * run's start it may take before it fails. This is the total wall-clock cap\n * `deadlineMs` is not — the budget never restarts, so a run that keeps\n * progressing is bounded by it where `deadlineMs` would let it run forever,\n * and it counts elapsed time where `maxTurns` counts round-trips. It is read\n * at the turn boundary, so like both of those it stops the run rather than\n * cancelling the work already in flight. Omit → no wall-clock cap.\n *\n * The run's start time is on the durable Model, so a run killed and resumed\n * continues the ORIGINAL budget — the time it spent dead counts against it.\n *\n * The same name on a `DurationRetryPolicy` (`retry`, and a tool's own) is the\n * same idea one altitude down: that one bounds how long ONE call's retry\n * ladder may keep climbing, this one how long the whole run may take.\n */\n readonly maxElapsedMs?: number;\n /**\n * Stops a run on a condition only you can see: a predicate consulted at the\n * turn boundary, after the other three guards have passed, over the run's\n * durable Model. Answer `true` and the run ends there — settled `cancelled`,\n * the same terminal an aborted `signal` reaches, with the transcript intact\n * and no further model call made. Where `maxTurns` and `maxElapsedMs` bound\n * a quantity the agent counts for you and `deadlineMs` watches for a stall,\n * this bounds whatever you name — a token ledger you keep, an external flag,\n * a condition on the turns so far. Omit → no predicate.\n *\n * It must be PURE: the reducer calls it, so a replay hands it the same state\n * and must get the same answer. And it is config rather than Model — a\n * resumed run consults the predicate the config passed to THIS boot, exactly\n * as it uses the `maxTurns` passed to this boot.\n */\n readonly stopWhen?: (state: DefinedAgentState<T>) => boolean;\n /**\n * The backoff ladder a FAILED BRAIN CALL climbs — the same `RetryPolicy`\n * shape `AgentConfigCore.retry` takes, threaded straight to it, so the ladder\n * runs in the resilient slice that already exists and lives on the Model:\n * each failure is recorded there and the next attempt is armed as a timer\n * Sub, which is what makes the wait durable and the attempt count survive a\n * reload.\n *\n * The per-tool knob grows no lid option because a `tool()` is a spec object\n * that declares its own policy (`ToolResilience.retry`). A\n * `defineAgent` `model` is a bare function with no spec object, so the lid is\n * the only declaration site a brain-call policy has.\n *\n * Omit → NO backoff, exactly as before: one throw from `model` ends the run\n * after a single attempt. Nothing is defaulted on your behalf — a silent\n * default would change the failure timing of every existing caller.\n */\n readonly retry?: RetryPolicy;\n /**\n * Observe a tool call that failed, typed against THIS agent's tools: the\n * outcome is `{ kind: \"error\", _tag, …payload, reason }` over\n * `ToolError`'s union — declared tags, `thrown`, `malformed_result`,\n * `unknown_tool`, `malformed_args` — so a `switch` on `_tag` is exhaustive and an\n * unhandled failure mode is a compile error rather than a silent turn (#115).\n * The model still reads `reason` next turn either way — this is the host's\n * channel beside it, never instead of it.\n *\n * Called ONCE per failed call, at the interpret boundary: after the handler\n * settled, before the failure is folded into the conversation. It is awaited,\n * so an async hook holds the settle until it resolves — keep it short, and put\n * anything slow on your own queue.\n *\n * A resume calls it for the calls THIS process runs and no others: an outcome\n * a previous process already folded is in the Model the Store handed back and\n * is never re-interpreted, so a durable run does not re-fire the hook over its\n * history.\n *\n * The hook is CONTAINED, exactly as `onEvent` is: a throw (or a rejected\n * promise) is warned about and the run goes on, so `run`'s contract does not\n * depend on the hook's.\n *\n * Omit → the router is wired unwrapped and nothing observes failures.\n */\n readonly onToolError?: (\n outcome: ToolFailureOf<T>,\n ctx: ToolErrorContext,\n ) => void | Promise<void>;\n /**\n * Bounds a run that keeps going without ever failing: the transcript budget,\n * past which the OLDEST turns are folded into one model-written summary\n * before the next brain call, so a long run's prompt stops growing instead of\n * climbing until the provider rejects it.\n *\n * The knob is a THRESHOLD, not a policy function — see\n * {@link DefineAgentCompaction}. `compaction` is what a run tolerates, and the\n * summarize round-trip that enforces it is wiring, so the lid takes the\n * former and supplies the latter from the `model` it already has.\n *\n * Omit → NO compaction, exactly as before: the transcript grows for as long\n * as the model keeps asking for tools. Nothing is defaulted on your behalf —\n * a silent budget would change the prompt every existing caller sends.\n */\n readonly compaction?: DefineAgentCompaction;\n /**\n * How many of ONE turn's tool calls a transition launches at once. At the\n * default `1` a turn's calls go out one at a time, each waiting for the last\n * to settle; raise it and up to that many are launched together, so they are\n * all in flight in the fan-out ledger rather than queued behind each other.\n * A turn asking for more calls than this runs them in waves.\n *\n * Launched together means overlapping on the clock: a turn of two slow tools\n * costs the slower of them, not their sum. The overlap lives inside the tool\n * Cmds' own handlers and NOT in the kernel — `runInterpret` still interprets\n * a transition's Cmds one after another and never interleaves two handlers,\n * which is ADR 0018's ruling and the reason a replay is unaffected. Settle\n * Msgs fold in Cmd-EMISSION order whichever call finishes first, so raising\n * the knob changes the turn's latency and nothing about its Model.\n *\n * Omit (or `1`) → serial dispatch, exactly as before.\n */\n readonly toolConcurrency?: number;\n}\n\n/**\n * The lid's compaction budget: the two numbers that say when a transcript is\n * too long and how much of it survives the fold. Both are plain counts, so the\n * trigger they build is PURE — a replay re-decides identically, and no clock or\n * token estimate enters the Model (ADR 0004).\n *\n * This is deliberately a threshold rather than the core's `planCompaction`\n * function: a policy function is a second place a lid agent would have to learn\n * the conversation shape, and the lid hides wiring, never state (ADR 0015). A\n * run that needs its own heuristic descends to `createAgent`, whose\n * `CompactionPolicy` this is built from.\n */\nexport interface DefineAgentCompaction {\n /**\n * Fold once the conversation holds at least this many turns, counted BEFORE\n * the brain call about to fire. Must be at least `1`.\n */\n readonly afterTurns: number;\n /**\n * How many of the NEWEST turns survive the fold intact, beside the summary.\n * Everything older becomes the summary's one synthetic head turn. Omit → `0`:\n * the whole transcript folds into the summary.\n *\n * A fold worth fewer than two turns is skipped by the agent itself — one turn\n * replaced by one summary shrinks nothing — so `keepTurns` within one of\n * `afterTurns` is a policy that never fires.\n */\n readonly keepTurns?: number;\n}\n\n/**\n * Which call an `onToolError` failure belongs to: the model's `callId` — the\n * fan-out identity the outcome folds back on — and the tool `name` the model\n * asked for, which for an `unknown_tool` is the name it invented rather than\n * any declared tool.\n */\nexport interface ToolErrorContext {\n readonly callId: string;\n readonly name: string;\n}\n\n/**\n * One lifecycle event a defined agent's run emits — {@link AgentEvent} with the\n * tool results typed against this agent's own tool set.\n */\nexport type DefinedAgentEvent<T extends AnyToolDef> = AgentEvent<ToolResult<T>>;\n\n/**\n * Host wiring for one `run`: the store, the ctx the tools need, a runId, a clock.\n *\n * `ctx` is the plain object the tools' handlers read (ADR 0020). A host with a\n * resource to release wraps `run` in its own `try` / `finally`.\n */\nexport type DefinedAgentRunOptions<T extends AnyToolDef> = CtxArg<\n DefinedAgentCtx<T>\n> & {\n readonly store?: Store<DefinedAgentState<T>>;\n /** The run's identity. Omit → a fresh UUID. */\n readonly runId?: string;\n /** The clock that stamps `at`. Omit → `Date.now`. */\n readonly clock?: () => number;\n /**\n * Observe the run's turn-level lifecycle events — `TurnSettled`,\n * `ToolSettled`, `RunDone` — in the order the kernel settles them. This is\n * the progress seam: without it the only way to see anything mid-run is\n * `machine(input)` plus the raw kernel loop.\n *\n * It forwards the runtime's existing semantic stream (`agentEvents()` /\n * `runtime.on`); it mints no vocabulary of its own, so a consumer folds the\n * same {@link AgentEvent}s a hand-wired `run` would.\n *\n * The listener is CONTAINED: a throw is caught and warned, never allowed to\n * take the run down, and never observable in `run`'s resolution. Only\n * transitions applied by THIS process project events, so a store-backed\n * resume replays nothing that settled before the boot.\n *\n * Omit → no projector is wired and the run behaves exactly as before.\n */\n readonly onEvent?: (event: DefinedAgentEvent<T>) => void;\n /**\n * Observe the token deltas of the turn being produced right now — the\n * granularity below `onEvent`'s. Wired only when the configured `model` is\n * the streaming shape (`async (messages, { onChunk }) => turn`); a plain\n * model has no deltas to give, so passing this beside one is silent.\n *\n * Chunks ride a SIDE CHANNEL, never state. They are not projected off\n * transitions like an {@link AgentEvent} is, because nothing about a chunk is\n * a transition: it is never journaled, never written to the `Store`, and\n * never folded into the Model. That is the whole rule this option obeys — a\n * delta that has not settled is not an outcome, so a run that dies mid-turn\n * loses its chunks and resumes from the last SETTLED turn, and a resumed run\n * re-emits nothing it did not itself re-produce.\n *\n * The listener is CONTAINED exactly as `onEvent`'s is: a throw is caught and\n * warned, never allowed to fail the model call it fired from.\n *\n * Omit → the streaming model is still invoked in its streaming shape, with a\n * sink that drops every chunk.\n */\n readonly onChunk?: (chunk: TurnChunk) => void;\n /**\n * Stop the run from outside — the stop button's seam. On abort the run settles\n * on a CANCELLED terminal Model and `run` RESOLVES with it; it does not reject,\n * and no `DriveFailedError` is thrown. Read the outcome with `status(state)`,\n * which answers `{ kind: \"cancelled\", at }` — distinct from `failed`, because a\n * run someone stopped did not fail.\n *\n * The outcome is durable, so it is also the answer on the next boot: a process\n * killed after an abort resumes reading a run that ENDED, not one to restart.\n * A signal already aborted when `run` is called ends it before the first model\n * call is made.\n *\n * It stops DISPATCH, not the work already in flight — a promise cannot be\n * cancelled, so a tool handler mid-call runs to its own end. Those late results\n * reach no `onEvent`, no `onToolError` and no Model, and they do not hold the\n * runtime's teardown. Propagating the signal INTO handlers is a separate seam\n * this option does not open.\n *\n * Omit → the run has no stop button and every path behaves exactly as before.\n */\n readonly signal?: AbortSignal;\n};\n\n/**\n * One decorator per interpret cell you name: it receives the cell the agent\n * wired (`next`) and returns the cell that runs in its place. Every key is\n * optional and a cell nobody names is passed through by REFERENCE, so an\n * overlay that wraps one tool leaves the others the exact functions\n * `defineAgent` built.\n *\n * The wrapper's signature is the cell's, so calling `next(cmd, ctx, dispatch)`\n * is how the wrapped work happens. A tool cell returns its outcome and the\n * engine mints `<name>_ok` / `<name>_err` from it (ADR 0021), so returning\n * what `next` returned is what keeps the fold, and therefore a replay,\n * identical to the unwrapped run's.\n */\nexport type InterpretOverlay<T extends AnyToolDef> = CellWrappers<\n DefinedAgentInterpret<T>\n>;\n\n/**\n * The decorator table over an interpret table `I`. Written over a bare type\n * parameter because `I[K]` is only indexable when `I` is one: applying the\n * mapped type to `DefinedAgentInterpret<T>` inline leaves TypeScript indexing\n * an unreduced generic mapped type, which it refuses.\n */\ntype CellWrappers<I> = {\n readonly [K in keyof I]?: (next: I[K]) => I[K];\n};\n\n/**\n * What `defineAgent(cfg).with(...)` takes — the one documented wrap point over\n * the machine the lid built.\n */\nexport interface DefinedAgentOverlay<T extends AnyToolDef> {\n readonly interpret: InterpretOverlay<T>;\n}\n\n/** What `defineAgent` returns. */\nexport interface DefinedAgent<T extends AnyToolDef> {\n /**\n * Run `input` to its terminal Model. Resolves on `run.phase: \"done\"`; a\n * failed run rejects with `DriveFailedError` carrying the failed Model.\n *\n * With a `store`, the same call is also the resume: a Model the Store hands\n * back mid-run is booted (`agent_boot`) at its one outstanding effect —\n * same `runId`, no tool re-run — and one already `done` resolves as it is.\n * A fresh start needs an empty Store.\n *\n * It resolves with {@link DefinedAgentResolvedState} — the Model whose `run`\n * slice is narrowed to the ENDED phases, so `(await agent.run(i)).run.runId`\n * reads without a guard against an `idle` arm this promise cannot produce.\n */\n readonly run: (\n input: string,\n ...opts: [Record<never, never>] extends [DefinedAgentCtx<T>]\n ? [opts?: DefinedAgentRunOptions<T>]\n : [opts: DefinedAgentRunOptions<T>]\n ) => Promise<DefinedAgentResolvedState<T>>;\n /**\n * The machine `run` drives for `input` and the interpret table it runs under\n * — the door down to the raw kernel.\n */\n readonly machine: (input: string) => DefinedAgentWired<T>;\n /**\n * The ramp between the lid and `createAgent`: wrap ONE interpret cell of the\n * machine this agent builds and get back a NEW defined agent that runs the\n * wrapped table. The agent it is called on is untouched, and so is every cell\n * the overlay does not name.\n *\n * const traced = agent.with({\n * interpret: {\n * fetch_rate: (next) => async (cmd, ctx, dispatch) => {\n * console.time(cmd.callId);\n * try { return await next(cmd, ctx, dispatch); }\n * finally { console.timeEnd(cmd.callId); }\n * },\n * },\n * });\n *\n * The wrapped cell settles through the SAME typed Cmd→Msg edge as the cell it\n * wraps — it returns whatever `next` returned — so the reducer folds the same\n * Msgs and a replay of a wrapped run is the unwrapped run's replay. That is\n * the whole contract: the door is one over the effect boundary, never over\n * the fold. A cell that must settle DIFFERENTLY is a different machine, and\n * `createAgent` is still where you build one.\n *\n * `with` composes — `agent.with(a).with(b)` puts `b`'s wrapper OUTSIDE `a`'s,\n * so `b` is entered first and `a`'s cell is what its `next` calls. Naming a\n * cell the machine has none of throws at `machine(input)`, where the table it\n * is checked against exists.\n */\n readonly with: (overlay: DefinedAgentOverlay<T>) => DefinedAgent<T>;\n}\n\n// ===========================================================================\n// The defined agent.\n// ===========================================================================\n\n/**\n * Define an agent from a model, the tools it may call and its instructions, and\n * get back `run(input)` — a promise of the finished state — plus `machine(input)`\n * for driving the same run yourself, which is the entry point a newcomer picks,\n * `createAgent` being the layer underneath that you drop to only to walk a stage\n * pipeline of your own.\n *\n * Add `maxTurns`, `deadlineMs`, `maxElapsedMs` or `stopWhen` to bound the run;\n * all four are described on `DefineAgentConfig`. The run's `input` is its single stage, so it is durable\n * beside `instructions`, and the prompt is rendered from those two and the\n * conversation on every model call.\n *\n * One unusual requirement does not cost you the lid: `.with({ interpret })`\n * wraps one interpret cell of the machine this built and hands back another\n * defined agent, so `createAgent` is for a rebuild rather than for a detour.\n */\nexport function defineAgent<T extends AnyToolDef>(\n config: DefineAgentConfig<T>,\n): DefinedAgent<T> {\n const router = toolRouter(config.tools);\n const { onToolError } = config;\n // No hook → the router is the plain one, so an omitted `onToolError` leaves\n // the interpret table the router always built.\n const tools =\n onToolError === undefined ? router : withToolErrorHook(router, onToolError);\n return definedAgent(config, { router, tools }, []);\n}\n\n/** The wiring every agent in one `defineAgent`'s lineage shares. */\ninterface LidWiring<T extends AnyToolDef> {\n readonly router: ToolRouter<T>;\n readonly tools: ToolRouter<T>;\n}\n\n/**\n * The defined agent for one config's wiring and the overlays stacked on it so\n * far. `defineAgent` is this with none; `with` is this with one more, which is\n * why a wrapped agent is a whole agent (`run`, `machine`, `with` again) rather\n * than a second kind of thing, and why the agent it was called on never\n * changes.\n *\n * The wiring is passed IN rather than rebuilt, so a `with` derives an agent that\n * shares the router — and therefore the very interpret cells the overlay does\n * not name.\n */\nfunction definedAgent<T extends AnyToolDef>(\n config: DefineAgentConfig<T>,\n wiring: LidWiring<T>,\n overlays: readonly InterpretOverlay<T>[],\n): DefinedAgent<T> {\n const { router, tools } = wiring;\n const { onToolError } = config;\n const machineWith = (\n input: string,\n onChunk: ((chunk: TurnChunk) => void) | undefined,\n ): DefinedAgentWired<T> => {\n const brain = brainOf(config.model, onChunk);\n // The half of the core config that does not depend on whether compaction is\n // configured. Spread into BOTH arms below rather than mutated into one, so\n // the two `createAgent` calls are provably the same agent apart from the\n // compaction discriminant.\n const core: LidCoreConfig<T> = {\n stages: [input],\n turnOf: () => \"act\" as const,\n schemas: { act: agentTurnSchema },\n model: brain,\n instructions: config.instructions,\n payloadOf: promptOf,\n loadMessages: messagesOf,\n toolOf: tools.toolOf,\n // The per-tool timeout / retry knob (#117). The lid grows no option for\n // it: the policy is declared on the `tool()` that needs it, and the\n // router is what carries it down to the reducer that runs it.\n toolResilienceOf: tools.resilienceOf,\n // The BRAIN-call ladder (#146), which does grow one, because a bare\n // `model` function has nowhere else to declare it. Forwarded only when\n // set, so an omitted lid option leaves `AgentConfigCore.retry` unset\n // and the brain call unbackedoff, byte for byte as before.\n ...(config.retry !== undefined ? { retry: config.retry } : {}),\n // Forwarded only when set, for the same reason: an omitted knob leaves\n // `AgentConfigCore.toolConcurrency` unset and the fan-out at its serial\n // default.\n ...(config.toolConcurrency !== undefined\n ? { toolConcurrency: config.toolConcurrency }\n : {}),\n maxTurns: config.maxTurns,\n deadlineMs: config.deadlineMs,\n maxElapsedMs: config.maxElapsedMs,\n stopWhen: config.stopWhen,\n };\n // `AgentCompactionConfig` is a DISCRIMINATED union — compaction is either\n // structurally absent or a whole policy — and the `compact_run` interpret\n // obligation is derived from which member was passed. So the two arms are\n // written out rather than folded into one spread: a conditional spread would\n // widen the config to a bare optional, which is the very type lie the\n // discriminant exists to refuse.\n const compaction = config.compaction;\n const agent: DefinedAgentWired<T> =\n compaction === undefined\n ? // The one assertion in the pair, and it widens the Cmd union: this\n // machine's `AgentCmd` fixes compaction OFF, `DefinedAgentMachine`\n // names the ON superset, and the gap is the `compact_run` Cmd a\n // policy-less reducer provably never emits. Widening a union nothing\n // can produce is sound. The table beside it is read at that same\n // superset type, and it holds no `compact_run` cell — the Cmd it would\n // serve never fires, and `overlaid` reads the table's own keys, so an\n // overlay naming that cell still gets the \"has none\" throw.\n (createAgent<\n string,\n LidPurpose,\n LidOutputs,\n ToolResult<T>,\n ToolCmd<T>,\n AgentMessage\n >(core).toMachine<DefinedAgentCtx<T>, T>({\n tools,\n }) as unknown as DefinedAgentWired<T>)\n : compactingMachine(core, compaction, brain, tools);\n return overlaid(agent, overlays);\n };\n // The public door down carries no chunk sink: `machine(input)` is handed to\n // the raw kernel by a caller who has no run options to read one from.\n const machine = (input: string): DefinedAgentWired<T> =>\n machineWith(input, undefined);\n const drive: DefinedAgent<T>[\"run\"] = (input, ...[opts = noHost<T>()]) => {\n const { onEvent, onChunk } = opts;\n // No listener → no projector, so an omitted `onEvent` leaves the run the\n // kernel wiring it always had.\n const wired = machineWith(input, onChunk);\n // The `interpret` table is checked where it is built; over the generic `T`\n // TS defers `run`'s conditional `InterpretArg` and cannot relate the two, so\n // the options are read at `run`'s own parameter type.\n const handle = run(wired.machine, {\n ...opts,\n interpret: wired.interpret,\n subscribe: wired.subscribe,\n terminal: isEnded,\n events:\n onEvent === undefined\n ? undefined\n : agentEvents<string, LidPurpose, LidOutputs, ToolResult<T>, T>({\n tools,\n }),\n } as unknown as RunOptionsOf<T>);\n if (onEvent !== undefined) forwardEvents(handle, onEvent);\n if (onToolError !== undefined) {\n forwardLadderErrors(handle, router, onToolError);\n }\n const clock = opts.clock ?? Date.now;\n const begin = (booted: DefinedAgentState<T>) => {\n const at = clock();\n return isMidRun(booted)\n ? agentBootMsg(at)\n : startMsg(opts.runId ?? crypto.randomUUID(), at);\n };\n // Written as two calls rather than one with a conditional spread, for the\n // reason `AgentCompactionConfig`'s two arms are: the cancellation option is a\n // PAIR, and a conditional spread widens it back to two independent optionals\n // — the signal-with-no-cancel the union exists to refuse.\n const signal = opts.signal;\n if (signal === undefined) {\n return ended(driveToDone(handle, begin, isEnded, { failed: isFailed }));\n }\n return ended(\n driveToDone(handle, begin, isEnded, {\n failed: isFailed,\n signal,\n cancel: () => agentCancelMsg(clock()),\n }),\n );\n };\n return {\n machine,\n run: drive,\n with: (overlay) =>\n definedAgent(config, wiring, [...overlays, overlay.interpret]),\n };\n}\n\n/**\n * The machine with each overlay's named cells wrapped, in the order they were\n * stacked — so the LAST `with` is the outermost wrapper and the innermost\n * `next` is always the cell the lid itself wired.\n *\n * A cell nobody names is carried over by REFERENCE, which is what \"unnamed\n * cells untouched\" means literally: the wrapped table holds the same functions\n * for every other key. Only the interpret table is rebuilt — as a new object\n * rather than mutated, because the same `defineAgent` config builds a fresh\n * `Wired` per `input` and per overlay stack. The machine itself carries no\n * handlers (#278), so an overlay never touches it, nor the `subscribe` runner\n * beside it.\n *\n * An unknown key throws HERE rather than at `with`: the table to check a name\n * against is the machine's, and the machine exists only per `input`.\n */\nfunction overlaid<T extends AnyToolDef>(\n wired: DefinedAgentWired<T>,\n overlays: readonly InterpretOverlay<T>[],\n): DefinedAgentWired<T> {\n if (overlays.length === 0) return wired;\n type Cell = (...args: never[]) => Promise<unknown>;\n const cells = { ...(wired.interpret as Record<string, Cell>) };\n for (const overlay of overlays) {\n const wrappers = overlay as unknown as Record<string, (next: Cell) => Cell>;\n for (const [type, wrap] of Object.entries(wrappers)) {\n const cell = cells[type];\n if (cell === undefined) {\n throw new Error(\n `@demlik/tea: defineAgent(...).with named the interpret cell ` +\n `\"${type}\", which this agent's machine has none of. Its cells are: ` +\n `${Object.keys(cells).sort().join(\", \")}.`,\n );\n }\n cells[type] = wrap(cell);\n }\n }\n return { ...wired, interpret: cells as DefinedAgentInterpret<T> };\n}\n\n// ===========================================================================\n// The named parts `defineAgent` composes.\n// ===========================================================================\n\n/**\n * The `ModelPort` `createAgent` is configured with, for either model shape.\n *\n * A plain model is passed through UNTOUCHED — same reference, same one-argument\n * call, so the arity that `isPlainModel` reads (and the misroute error a\n * non-`async` model earns) is exactly what it was before streaming existed. A\n * streaming model is wrapped in an `async` one-argument function that binds this\n * run's sink, which is what makes the sink per-run while `model` stays per-agent.\n *\n * The wrapper resolves whatever the streaming model resolves and adds nothing:\n * the turn still meets `agentTurnSchema` at the same seam, so the settled turn\n * — and therefore the Model — cannot depend on whether anyone watched.\n */\nfunction brainOf(\n model: DefinedAgentModel,\n onChunk: ((chunk: TurnChunk) => void) | undefined,\n): PlainModel<AgentMessage, AgentTurn> {\n if (!isStreamingModel(model)) {\n return model as PlainModel<AgentMessage, AgentTurn>;\n }\n const streaming = model as StreamingModel<AgentMessage, AgentTurn>;\n const stream: ModelStream = {\n onChunk: onChunk === undefined ? dropChunk : contained(\"onChunk\", onChunk),\n };\n return async (messages) => streaming(messages, stream);\n}\n\n/** The sink a streaming model gets when nobody is watching. PURE. */\nfunction dropChunk(): void {}\n\n/**\n * A caller's listener, wrapped so its defects stay its own: a throw is warned\n * about and swallowed rather than propagated into the run that fired it.\n *\n * The run's contract must not depend on the listener's. For `onEvent` the\n * runtime's own fanout is throw-isolated but routes to `OnError`, whose default\n * re-throws on a fresh macrotask; for `onChunk` there is no fanout at all — the\n * sink is called straight from the adapter, so an escaping throw would reject\n * the model call and settle a `resilient_run_err` for a defect in a progress bar.\n */\nfunction contained<E>(what: string, listener: (event: E) => void) {\n return (event: E): void => {\n try {\n listener(event);\n } catch (err) {\n console.warn(`@demlik/tea: a run's ${what} listener threw`, err);\n }\n };\n}\n\n/**\n * The `createAgent` config both of `defineAgent`'s arms share — everything but\n * the compaction discriminant, named so the two arms can be handed one value\n * and provably differ in that field alone.\n */\ntype LidCoreConfig<T extends AnyToolDef> = AgentConfigCore<\n string,\n LidPurpose,\n LidOutputs,\n ToolResult<T>,\n ToolCmd<T>,\n AgentMessage\n>;\n\n/**\n * The compacting arm's machine: the same core config plus the policy, wired to\n * the `compact_run` cell the ON discriminant requires.\n *\n * The one assertion lives here, and it is a GENERICS artifact rather than a\n * claim about the wiring. `toMachine`'s obligation subtracts the router's own\n * Cmds through `Exclude<TC, WiredToolCmd<T>>`, and `WiredToolCmd` is a\n * conditional on `T` — unresolvable while `T` is still a type parameter, so TS\n * cannot see that the router's cells already discharge everything but\n * `compact_run`. At a concrete `T` it reduces and the obligation is exactly the\n * cell supplied. `toMachine` spreads the router's table under this one either\n * way, so nothing here overrides a tool cell.\n */\nfunction compactingMachine<T extends AnyToolDef>(\n core: LidCoreConfig<T>,\n knob: DefineAgentCompaction,\n brain: PlainModel<AgentMessage, AgentTurn>,\n tools: ToolRouter<T>,\n): DefinedAgentWired<T> {\n const agent = createAgent<\n string,\n LidPurpose,\n LidOutputs,\n ToolResult<T>,\n ToolCmd<T>,\n AgentMessage\n >({ ...core, compaction: compactionPolicyOf<ToolResult<T>>(knob) });\n const wiring = {\n tools,\n toolInterpret: { compact_run: summarizeWith(brain) },\n } as Parameters<typeof agent.toMachine<DefinedAgentCtx<T>, T>>[0];\n return agent.toMachine<DefinedAgentCtx<T>, T>(\n wiring,\n ) as unknown as DefinedAgentWired<T>;\n}\n\n/**\n * The system prompt the summarize round-trip runs under. It is the lid's, not\n * the agent's: the agent's own `instructions` tell the model how to do the job,\n * and re-sending them here would ask a summarizer to keep working the task.\n */\nconst SUMMARIZE_INSTRUCTION =\n \"Summarize the conversation so far. Preserve the facts, decisions and tool \" +\n \"results a continuation would need, and drop everything else. Reply with the \" +\n \"summary as your message content and request no tools.\";\n\n/**\n * The core `CompactionPolicy` the lid's threshold knob builds — the whole of the\n * translation from \"how long a transcript I tolerate\" to \"how many of the oldest\n * turns to fold now\".\n *\n * `planCompaction` is PURE and reads only turn counts, so a replay re-decides\n * identically (design D). Below the threshold it returns `0` and the agent fires\n * the brain call it was going to fire, which is what makes an unconfigured — and\n * an under-budget — run byte for byte the run it was before.\n *\n * `payloadOf` renders the FOLDING turns and no others: the summarize call is\n * given exactly the transcript that is about to be dropped, so the summary it\n * writes is a replacement for that text rather than a restatement of the whole\n * conversation.\n */\nfunction compactionPolicyOf<R>(\n knob: DefineAgentCompaction,\n): CompactionPolicy<R, AgentMessage> {\n const keep = knob.keepTurns ?? 0;\n return {\n planCompaction: (conversation) =>\n conversation.turns.length >= knob.afterTurns\n ? Math.max(0, conversation.turns.length - keep)\n : 0,\n payloadOf: (conversation, folding): AgentPrompt<R> => ({\n instructions: SUMMARIZE_INSTRUCTION,\n input: null,\n conversation: {\n ...conversation,\n turns: conversation.turns.slice(0, folding),\n toolRecords: conversation.toolRecords.filter((r) => r.turn < folding),\n },\n }),\n };\n}\n\n/**\n * The `compact_run` interpret cell the lid wires: the summarize I/O, run through\n * the SAME `model` the brain calls, because a lid agent has exactly one model\n * and a second one would be a knob this issue did not add.\n *\n * The summary is the returned turn's `content`. A turn is what a\n * `defineAgent` model resolves, so nothing here asks the adapter for a second\n * output shape — the tool calls such a turn may carry are ignored, since the\n * summarizer is not in the loop that could run them.\n *\n * A throw propagates: the agent's dedicated compaction resilient slice owns the\n * retry / backoff and folds a failure as `compact_err`, which proceeds without\n * compacting rather than failing the run.\n */\nfunction summarizeWith(\n model: PlainModel<AgentMessage, AgentTurn>,\n): (cmd: AgentCompactRunCmd) => Promise<AgentCompactOkMsg> {\n return async (cmd) => {\n const payload = cmd.input.payload as AgentPrompt<unknown>;\n const turn = await model(renderPrompt(payload));\n // `Date.now()` at the settle, exactly as the composed llm-call handler\n // stamps the brain call's own settle Msg.\n return {\n type: MsgType.CompactOk,\n key: COMPACTION_PURPOSE,\n result: {\n key: COMPACTION_PURPOSE,\n purpose: COMPACTION_PURPOSE,\n output: { summary: turn.content },\n },\n at: Date.now(),\n };\n };\n}\n\n/** `payloadOf`: the prompt is the durable state, nothing else. PURE. */\nfunction promptOf<R>(\n stage: string | undefined,\n conversation: Conversation<R>,\n instructions: string | null,\n): AgentPrompt<R> {\n return { instructions, input: stage ?? null, conversation };\n}\n\n/**\n * `loadMessages`: render the call's prompt to the messages the model reads.\n * The payload is what `promptOf` built for this same agent, so the narrowing is\n * an identity — the one place the `unknown` payload is read back typed.\n */\nconst messagesOf: MessageLoader<LidPurpose, AgentMessage> = async (\n call: LlmCall<LidPurpose>,\n) => renderPrompt(call.payload as AgentPrompt<unknown>);\n\n/** The prompt as messages: the head, then each turn with its tool outcomes. PURE. */\nexport function renderPrompt(prompt: AgentPrompt<unknown>): AgentMessage[] {\n const head: AgentMessage[] = [];\n if (prompt.instructions !== null) {\n head.push({ role: \"system\", content: prompt.instructions });\n }\n if (prompt.input !== null) {\n head.push({ role: \"user\", content: prompt.input });\n }\n const { turns, toolRecords } = prompt.conversation;\n const transcript = turns.flatMap<AgentMessage>((turn, i) => [\n assistantOf(turn),\n ...toolRecords\n .filter((r) => r.turn === i)\n .map<AgentMessage>((r) => ({\n role: \"tool\",\n callId: r.call.callId,\n name: r.call.name,\n outcome: r.outcome,\n })),\n ]);\n return [...head, ...transcript];\n}\n\n/**\n * The stored turn as the `assistant` message the model reads back. `provider`\n * rides only when the turn carries one, so a turn persisted before the slot\n * existed renders exactly as it did then. PURE.\n */\nfunction assistantOf(turn: AgentTurn): AgentMessage {\n const { content, toolCalls } = turn;\n return \"provider\" in turn\n ? { role: \"assistant\", content, toolCalls, provider: turn.provider }\n : { role: \"assistant\", content, toolCalls };\n}\n\n/**\n * The options a `run` with no host wiring gets. `opts` may be omitted only when\n * no tool demands ctx — the `run` signature requires it otherwise — so the\n * empty record is a complete options value there, which is what this asserts.\n */\nfunction noHost<T extends AnyToolDef>(): DefinedAgentRunOptions<T> {\n return {} as DefinedAgentRunOptions<T>;\n}\n\n/**\n * Every `AgentEvent` discriminant, so one `on(...)` subscription per type\n * covers the whole union. Subscribing before the drive dispatches is what makes\n * the delivery total: an event of a type nobody is listening for is dropped by\n * the runtime's fanout, not queued.\n */\nconst AGENT_EVENT_TYPES = [\"TurnSettled\", \"ToolSettled\", \"RunDone\"] as const;\n\n/**\n * Forward the runtime's semantic events to the caller's `onEvent`, CONTAINED.\n *\n * `defineAgent` owns the containment (see {@link contained}): a throwing\n * listener is warned about and the run goes on to its terminal Model, so\n * `run`'s contract does not depend on the listener's.\n *\n * Ordering is the kernel's: one handler per type, all attached before the\n * drive's first dispatch, so events arrive in the order the projector emits\n * them.\n */\nfunction forwardEvents<T extends AnyToolDef>(\n handle: BootingRuntime<\n DefinedAgentState<T>,\n AgentMachineMsg<LidPurpose, LidOutputs, ToolResult<T>> | WiredToolMsg<T>,\n DefinedAgentEvent<T>\n >,\n onEvent: (event: DefinedAgentEvent<T>) => void,\n): void {\n const deliver = contained(\"onEvent\", onEvent);\n for (const type of AGENT_EVENT_TYPES) {\n handle.on(type, deliver);\n }\n}\n\n/**\n * Deliver a LADDERED call's one failure to `onToolError` (#117 meeting #115).\n *\n * `withToolErrorHook` below wraps interpret, and that is the right seam for a\n * call nothing else owns — but a tool declaring `timeoutMs` or `retry` settles\n * once per ATTEMPT there, and the attempts a ladder absorbs are not failures the\n * run produced: the model is shown none of them, and neither is the host. The\n * call's real ending is minted by the reducer (a timeout has no handler settle\n * at all — the call is over while its attempt is still running), so it is\n * readable only off the fold.\n *\n * So the two seams SPLIT on one question, `resilienceOf(call) !== null`, and\n * every call is announced by exactly one of them. That is what makes\n * once-per-call structural rather than a filter the caller writes: a laddered\n * call is silent at interpret and announced here, a bare call the other way\n * round, and neither can announce the other's.\n *\n * The cost is that a laddered call's failure is read AFTER its fold rather than\n * before it — there is nothing earlier to read. The two other clauses hold\n * unchanged: once per settled call (`fired`), and never re-announced on resume,\n * because the boot/start transition seeds `fired` with every record the `Store`\n * handed back and folds none of its own.\n */\nfunction forwardLadderErrors<T extends AnyToolDef>(\n handle: BootingRuntime<\n DefinedAgentState<T>,\n AgentMachineMsg<LidPurpose, LidOutputs, ToolResult<T>> | WiredToolMsg<T>,\n DefinedAgentEvent<T>\n >,\n router: ToolRouter<T>,\n onToolError: NonNullable<DefineAgentConfig<T>[\"onToolError\"]>,\n): void {\n const fired = new Set<string>();\n handle.observe((msg, state) => {\n // `agent_start` and `agent_boot` are the run's first transition and fold no\n // tool record of their own, so every record visible under one is history a\n // `Store` handed back. Reading the Msg rather than \"is this the first call\"\n // is what makes that a stated invariant instead of an assumed one.\n const seeding =\n msg.type === MsgType.AgentStart || msg.type === MsgType.AgentBoot;\n for (const record of state.conversation?.toolRecords ?? []) {\n const { outcome, call } = record;\n if (outcome.kind !== \"error\") continue;\n if (fired.has(call.callId)) continue;\n fired.add(call.callId);\n if (seeding) continue;\n // A call no ladder owns was announced at the interpret boundary already.\n if (router.resilienceOf(call) === null) continue;\n void Promise.resolve(\n onToolError(outcome as ToolFailureOf<T>, {\n callId: call.callId,\n name: call.name,\n }),\n ).catch((err: unknown) => {\n console.warn(\"@demlik/tea: a run's onToolError hook threw\", err);\n });\n }\n });\n}\n\n/**\n * The router with the consumer's `onToolError` spliced into every interpret\n * handler — the same router, one seam wider.\n *\n * The interpret boundary is where the hook belongs, and the two timing clauses\n * on `onToolError` are properties of that seam rather than bookkeeping this\n * function does: a handler's outcome is minted through the edge `run` hands\n * on ctx and read back through the router's own `outcomeOf` (so the hook and\n * the conversation see ONE rendering of the failure), and the outcome is\n * returned — for the engine to mint again — only after the hook resolves,\n * which is \"before the fold\"; and interpret runs only for the effects THIS process\n * launches, which is \"not again on resume\". Nothing is folded, counted or\n * remembered here.\n *\n * `tool_rejected` is wrapped like any other handler, so `unknown_tool` and\n * `malformed_args` reach the hook exactly as a tool's own failure does.\n *\n * A LADDERED call is the one thing this seam stays silent about, because here it\n * is one settle per ATTEMPT and the absorbed ones are not failures the run\n * produced. `forwardLadderErrors` above announces those calls off the fold\n * instead; the two seams split on `resilienceOf` and every call belongs to\n * exactly one.\n */\nfunction withToolErrorHook<T extends AnyToolDef>(\n router: ToolRouter<T>,\n onToolError: NonNullable<DefineAgentConfig<T>[\"onToolError\"]>,\n): ToolRouter<T> {\n type Handler = (\n cmd: { readonly type: string },\n ctx: unknown,\n ) => Promise<unknown>;\n const handlers = router.interpret as unknown as Record<string, Handler>;\n const wrapped: Record<string, Handler> = {};\n for (const [type, handler] of Object.entries(handlers)) {\n wrapped[type] = async (cmd, ctx) => {\n const returned = await handler(cmd, ctx);\n // The cell returns an outcome (ADR 0021); minting it here only READS\n // it. The engine mints the returned outcome itself, once, for the fold.\n const msg = cmdEdgeOf(ctx)(cmd, returned);\n if (typeof msg !== \"object\" || msg === null) return returned;\n const settled = router.outcomeOf(msg as { readonly type: string });\n if (settled === null || settled.outcome.kind === \"ok\") return returned;\n // A laddered call is announced off its fold, once, by\n // `forwardLadderErrors` — never per attempt from here.\n if (ownedByLadder(router, cmd, settled.callId)) return returned;\n try {\n await onToolError(settled.outcome as ToolFailureOf<T>, {\n callId: settled.callId,\n name: calledName(cmd),\n });\n } catch (err) {\n console.warn(\"@demlik/tea: a run's onToolError hook threw\", err);\n }\n return returned;\n };\n }\n return {\n ...router,\n interpret: wrapped as unknown as ToolRouter<T>[\"interpret\"],\n };\n}\n\n/**\n * Whether a ladder owns the call this Cmd is an attempt of — the one question\n * the two `onToolError` seams split on. Read off the same `resilienceOf` the\n * reducer runs the ladder from, so the two can never disagree about who\n * announces a call. A `tool_rejected` names no declared tool, so it is never\n * laddered and always announced at the interpret boundary. PURE.\n */\nfunction ownedByLadder<T extends AnyToolDef>(\n router: ToolRouter<T>,\n cmd: { readonly type: string },\n callId: string,\n): boolean {\n return router.resilienceOf({ name: cmd.type, callId, args: {} }) !== null;\n}\n\n/**\n * The tool name a Cmd was built for: its own `type`, except for the router's\n * `tool_rejected`, whose type is the router's and whose rejection carries the\n * name the MODEL asked for — the name a consumer needs to see for an\n * `unknown_tool`. PURE.\n */\nfunction calledName(cmd: { readonly type: string }): string {\n const rejection = (cmd as { readonly error?: { readonly name?: unknown } })\n .error;\n return typeof rejection?.name === \"string\" ? rejection.name : cmd.type;\n}\n\n/** The Msg that sets a run in motion. */\nfunction startMsg(runId: string, at: number) {\n return { type: MsgType.AgentStart, runId, at } as const;\n}\n\n/**\n * Whether the boot State is a run the Store handed back mid-flight — live, or\n * suspended on tools — which `agent_boot` resumes at its one outstanding\n * effect. A `start` here would mint a new `runId` and a fresh conversation\n * over the work already done; that is a restart, and the durable half of\n * `defineAgent` is exactly that it never does one. PURE.\n */\nfunction isMidRun(s: AgentState<string, LidPurpose, LidOutputs, unknown>) {\n const { kind } = status(s);\n return kind === \"running\" || kind === \"suspended\";\n}\n\n/**\n * The drive's terminal predicate — the run ENDED, by finishing or by being\n * cancelled. Both are outcomes the drive resolves on and the Store persists, so\n * both have to read terminal here or an aborted run would wait for a `done` that\n * is never coming. PURE.\n */\nfunction isEnded(s: AgentState<string, LidPurpose, LidOutputs, unknown>) {\n return s.run.phase === \"done\" || s.run.phase === \"cancelled\";\n}\n\n/**\n * The drive's resolved State at the type the drive's own predicates already\n * guarantee. `driveToDone` is typed `Promise<S>` over the machine's whole Model\n * because its terminal test is an opaque `(s) => boolean` it cannot read as a\n * type guard — so the narrowing `isEnded` performs is invisible at the seam and\n * is re-stated here: the promise resolves only where `isEnded` holds (`done` /\n * `cancelled`), and everything `isFailed` marks rejects. This is the ONE place\n * the two are joined, so `run`'s public type carries no `idle` arm and no caller\n * asserts (#155).\n */\nfunction ended<T extends AnyToolDef>(\n drive: Promise<DefinedAgentState<T>>,\n): Promise<DefinedAgentResolvedState<T>> {\n return drive as Promise<DefinedAgentResolvedState<T>>;\n}\n\n/** The drive's failure predicate — either failure channel, via `status`. PURE. */\nfunction isFailed(s: AgentState<string, LidPurpose, LidOutputs, unknown>) {\n return status(s).kind === \"failed\";\n}\n","/**\n * @packageDocumentation\n * The transcript collector — the built-in way to KEEP a run's turns, given that\n * a finished run's Model does not.\n *\n * A run that reaches `phase: \"done\"` clears `conversation` to `null` on\n * purpose: the terminating turn is stamped onto `output` first, so the answer\n * survives, and the history that would otherwise grow without bound in storage\n * kept for its state is dropped (`docs/explanation/durability-model.md`). That\n * policy is not what this module changes. What it changes is that every\n * consumer wanting the history had to hand-write the same fold over `onEvent`.\n *\n * So this is a COLLECTOR over the event stream that already exists, not a knob\n * on the Model. Nothing here is durable, nothing here is written to a `Store`,\n * and a run with a collector attached is byte for byte the run it was without\n * one — the same reason `onChunk` rides a side channel rather than state.\n *\n * const t = transcript<ToolResult<typeof tools>>();\n * const final = await agent.run(input, { store, onEvent: t.onEvent });\n * t.read().turns; // every turn this process settled\n *\n * ## What a resume needs from you\n *\n * Events are projected off the transitions THIS process applies, so a run\n * resumed from a `Store` re-emits nothing the killed process already settled.\n * A collector that only ever listened would therefore hold the tail of a\n * resumed run and call it the whole thing. Hence the seed: hand\n * {@link transcript} the Model the `Store` handed back and it starts from that\n * Model's live conversation, so the resumed collector reads as the whole run\n * rather than its last leg.\n */\n\nimport type { AgentEvent } from \"./machine\";\nimport type { AgentTurn, Conversation } from \"./types\";\n\n/**\n * One tool call the run settled OK, as the transcript keeps it — the `callId`\n * and the result, which is exactly what the `ToolSettled` event carries.\n *\n * A tool that FAILED is absent, and that is the event stream's shape rather\n * than a choice made here: `ToolSettled` is projected off the OK settle alone.\n * Branch on failures through `onToolError`, whose argument is typed per tag.\n */\nexport interface TranscriptToolResult<R> {\n readonly callId: string;\n readonly result: R;\n}\n\n/**\n * Whether the run has finished, and its terminal turn once it has.\n *\n * The two cases are a union rather than a nullable `output` field because\n * `output` is legitimately `null` on a finished run — a `RunDone` with no\n * terminating turn — and a single field would make \"not finished yet\" and\n * \"finished with nothing\" the same reading.\n */\nexport type TranscriptOutcome =\n | { readonly kind: \"running\" }\n | { readonly kind: \"done\"; readonly output: AgentTurn | null };\n\n/** What a collector holds right now — a plain, immutable read. */\nexport interface TranscriptSnapshot<R> {\n /** Every model turn the transcript holds, in order. */\n readonly turns: readonly AgentTurn[];\n /** Every tool call that settled OK, in settle order. */\n readonly tools: readonly TranscriptToolResult<R>[];\n /** Whether `RunDone` has been seen, and the terminal turn if so. */\n readonly outcome: TranscriptOutcome;\n}\n\n/**\n * The Model a resumed collector starts from — structural on purpose, so any\n * agent state (`DefinedAgentState<T>`, `AgentState<…>`) satisfies it without\n * this module importing the lid, and a bare `{ conversation }` object works in\n * a test.\n */\nexport interface TranscriptSeed<R> {\n readonly conversation: Conversation<R> | null;\n}\n\n/**\n * A live transcript: the listener you wire, and the read you take off it.\n *\n * `onEvent` is a bound function, so `{ onEvent: t.onEvent }` is the whole\n * wiring — there is no `this` to lose.\n */\nexport interface Transcript<R> {\n /** Wire this to `run`'s `onEvent`. */\n readonly onEvent: (event: AgentEvent<R>) => void;\n /** The transcript as of now. Each call returns a fresh immutable snapshot. */\n readonly read: () => TranscriptSnapshot<R>;\n}\n\n/**\n * Open a transcript collector over an agent run's event stream.\n *\n * Wire `onEvent` to `run`'s `onEvent` option and `read()` gives you the turns\n * and settled tool results afterwards — the transcript the finished Model no\n * longer carries.\n *\n * Pass `seed` when the run is a RESUME: the Model the `Store` handed back still\n * holds the live conversation the killed process built, and seeding from it is\n * what makes the collector hold the whole run rather than the leg this process\n * ran. One collector per process is the honest unit; a fresh run needs no seed.\n *\n * A seed taken from an already-finished Model contributes nothing, and\n * correctly so: that Model's `conversation` is `null` and its answer is its\n * `output`, which you already hold.\n */\nexport function transcript<R>(seed?: TranscriptSeed<R>): Transcript<R> {\n const turns: AgentTurn[] = [...(seed?.conversation?.turns ?? [])];\n const tools: TranscriptToolResult<R>[] = (\n seed?.conversation?.toolRecords ?? []\n ).flatMap((record) =>\n record.outcome.kind === \"ok\"\n ? [{ callId: record.call.callId, result: record.outcome.result }]\n : [],\n );\n let outcome: TranscriptOutcome = { kind: \"running\" };\n\n return {\n onEvent: (event) => {\n switch (event.type) {\n case \"TurnSettled\":\n turns.push(event.turn);\n return;\n case \"ToolSettled\":\n tools.push({ callId: event.callId, result: event.result });\n return;\n case \"RunDone\":\n outcome = { kind: \"done\", output: event.output };\n return;\n }\n },\n read: () => ({ turns: [...turns], tools: [...tools], outcome }),\n };\n}\n","/**\n * @packageDocumentation\n * @demlik/tea/agent — THE headline Level-3 machine: a durable, crash-recoverable\n * AI agent that runs an ordered stage pipeline, and inside the agentic stage\n * drives the classic loop `llm → tools → fold → llm` until the model stops\n * asking for tools.\n *\n * This generalizes a production audit agent: the domain specifics are stripped,\n * and what remains — the loop, the durability, the boot-reconcile crash\n * recovery, the serial-vs-fanned tool dispatch — is yours. The consumer\n * supplies the only things that are genuinely domain: the tools, the prompts\n * (via the llm-call message loader), the schemas, and the model. `createAgent(config)` returns the uniform handle contract every\n * composition exposes (`init` / verbs returning `readonly [State, Cmd[]]` /\n * `subs`) AND a ready-to-`run` `defineMachine` (`toMachine`) — THE one wired\n * path. (`brainInterpret` and `brain` are the pieces a consumer wiring the\n * verbs by hand reaches for.)\n *\n * ## The composition (three siblings wired into ONE machine)\n *\n * - `../monitored-run` — the OUTER pipeline + lifecycle + safety watchdog.\n * The agent's stages (`plan → act → report`, say) are its stages; the\n * position survives eviction, the no-progress deadline auto-fails a wedged\n * run, and `boot` resumes mid-pipeline. The agent slice OWNS this slice and\n * delegates `start` / `advance` / `progress` / `onDeadline` / `boot` to it.\n * - `../llm-call` — every brain call. One\n * `LlmCall` per turn, structured-output parsed, retry composed in. The agent\n * delegates the resilient slice + verbs, and owns the one Promise handler\n * that invokes the model (`./model`).\n * - `../fan-out` — the tool calls a turn produced. Tools dispatch SERIALLY by\n * default (concurrency 1); fan-out generalizes that to a bounded number\n * LAUNCHED per transition, `config.toolConcurrency`. Above `1` a router's\n * tool cells overlap on the clock while `runInterpret` stays serial — the\n * fan-out is inside the Cmd handler, and its settles fold in emission\n * order (ADR 0018). Each\n * tool is an `of(call)` Cmd the consumer's own interpret performs; results\n * route back through `toolOk` / `toolErr`. When the batch drains, the agent\n * folds the gathered results back into the conversation and fires the next\n * brain call (`fold → llm`).\n *\n * ## The flow loop, as TEA\n *\n * 1. `start` enters the pipeline; the consumer wires the per-stage outstanding\n * effect (often a `call_llm` for the agentic stage) off the current stage.\n * 2. `turn(msg)` folds one model turn:\n * - no tool calls → the loop is done for this stage → `advance` the\n * pipeline (next stage, or finish to `done`).\n * - tool calls → `scatter` them across fan-out (≤ concurrency in flight),\n * emitting the per-tool effect Cmds. The conversation records the model\n * turn; `awaiting` flips to `tools`.\n * 3. `toolOk` / `toolErr` fold each settled tool back, launching the next\n * queued tool. When the batch drains, fold the gathered outcomes into the\n * conversation, bump the turn count (livelock guard), and fire the next\n * brain call — `awaiting` flips back to `llm`.\n * 4. The watchdog bounds a stall and the turn boundary's own stop conditions\n * bound the loop: the deadline fires `failed`, the turn limit fires\n * `failed { turn_limit }`, the wall-clock cap `failed { elapsed_limit }`,\n * and the consumer's `stopWhen` settles the run `cancelled`.\n *\n * ## Boot reconcile (crash recovery)\n *\n * Cold wake re-derives the ONE outstanding effect from `phase × awaiting`: a\n * brain call in flight re-fires `call_llm`; tools in flight re-fire the in-flight\n * tool Cmds. Re-fire is Model-idempotent — had the prior effect's result been\n * processed, the durable Model would already have advanced and boot re-emits the\n * NEXT effect. `boot` re-seeds the watchdog clock to NOW (a cold wake is not a\n * no-progress wedge) via the inherited monitored-run `boot`.\n *\n * ## The two non-negotiables (canon, inherited)\n *\n * - **Durable** — the whole slice is plain data: the monitored-run slice, the\n * resilient (retry) slice, the fan-out ledger, and the conversation are all\n * JSON-serializable. It survives DO eviction / reload.\n * - **Replayable** — every transition is a pure verb returning new state +\n * Cmds; nothing here reads the clock or RNG. Time arrives as an `at`\n * parameter, jitter RNG is injected once at `createAgent`, and the only clock\n * reads live inside the spliced handlers (the effect boundary).\n *\n * ## Typical wiring\n *\n * // Type params: <Stage, Purpose, Outputs, Result, ToolCmd, Msg>. `ToolCmd`\n * // is the discriminated Cmd `toolOf` returns — keep it precise (not the open\n * // `Cmd`) so the wired machine's interpret merge type-checks per key.\n * type RunTool = { readonly type: \"run_tool\" } & ToolCall;\n * const agent = createAgent<Stage, Purpose, Outputs, Result, RunTool, Msg>({\n * stages: [\"plan\", \"act\", \"report\"],\n * // The brain: a plain `async (messages) => turn` (the common path), or the\n * // `(id) => Llm` factory when the model binds the schema itself.\n * model: async (messages) => client.chat(messages),\n * schemas: { plan: planSchema, act: turnSchema, report: reportSchema },\n * turnOf: (stage) => stageToPurpose[stage], // which brain call a stage runs\n * toolOf: (call): RunTool => ({ type: \"run_tool\", ...call }),\n * toolConcurrency: 1, // launched per transition\n * deadlineMs: 10 * 60_000,\n * maxTurns: 60,\n * retry: defaultRetryPolicy,\n * loadMessages,\n * });\n * // The consumer supplies the per-tool (+ snapshot) interpret; the agent owns\n * // the brain interpret and merges them in `toMachine`.\n * const wired = agent.toMachine({ toolInterpret });\n * const runtime = run(wired.machine, { ...wired, ctx, store });\n */\n\nimport {\n type Cmd,\n defineMachine,\n type Interpret,\n type Machine,\n type Reducer,\n type Subscribe,\n} from \"../index\";\nimport { createFanOut, initFanOut } from \"../internal/flow/fan-out\";\nimport {\n createMonitoredRun,\n type MonitoredRunCmd,\n} from \"../internal/flow/monitored-run\";\nimport {\n createLlmCall,\n type LlmCall,\n type LlmOk,\n type LlmRunCmd,\n type ResilientState,\n} from \"../internal/llm-call\";\nimport {\n type DeadlineSub,\n type DeadlinesSub,\n deadlineSub,\n deadlinesSub,\n subscribeDeadline,\n} from \"../internal/resilience/deadline\";\nimport { createResilientCall } from \"../internal/resilience/resilient-call\";\nimport { MsgType } from \"../protocol\";\nimport {\n type AgentCompactErrMsg,\n type AgentCompactOkMsg,\n type AgentCompactRunCmd,\n COMPACTION_PURPOSE,\n type CompactInterpret,\n type CompactionOutputs,\n type CompactionPolicy,\n type CompactionPurpose,\n} from \"./compaction\";\nimport {\n currentStage,\n dedupeByCallId,\n foldSummary,\n freshConversation,\n isSettled,\n requireAwaiting,\n toCompactRunCmd,\n} from \"./internal\";\nimport {\n type AgentCmd,\n type AgentKnob,\n type AgentLlmErrMsg,\n type AgentLlmOkMsg,\n type AgentLlmRunCmd,\n type AgentMachineMsg,\n type AgentTimerMsg,\n mergeInterpret,\n type SnapshotInterpret,\n} from \"./machine\";\nimport { brainHandler } from \"./model\";\nimport {\n type AnyToolDef,\n fanOutInterpret,\n type ToolRouter,\n type ToolsCtx,\n type WiredToolCmd,\n type WiredToolMsg,\n} from \"./tool\";\nimport {\n createToolLadder,\n isToolTimerId,\n type ToolResilienceState,\n type ToolTimerOutcome,\n} from \"./tool-resilience\";\nimport type {\n AgentConfig,\n AgentConfigCore,\n AgentFailure,\n AgentState,\n AgentTurn,\n Conversation,\n ToolCall,\n ToolFailure,\n ToolOutcome,\n} from \"./types\";\n\n// Re-export the concern modules so the public `@demlik/tea/agent` barrel is\n// unchanged after the split into `./types` (domain + conversation + config +\n// state/status), `./compaction` (the #85 seam), and `./machine` (the Cmd/Msg\n// vocabulary + wiring helpers). The reducer core — `createAgent` — stays here.\nexport * from \"./compaction\";\nexport * from \"./define-agent\";\nexport * from \"./machine\";\nexport * from \"./tool\";\nexport * from \"./transcript\";\nexport * from \"./types\";\n\n// ===========================================================================\n// The knob factory.\n// ===========================================================================\n\n/**\n * Assemble an agent from `config` — the model, the stages it walks, and how a\n * tool call is turned into a command — and get back its `init`, verbs and `subs`\n * plus a `toMachine()` that wires all of it into one machine you hand to `run`,\n * which is the layer to reach for only once `defineAgent` cannot express the run\n * you want — a newcomer starts there, not here.\n *\n * Pass `snapshotEvery` to have the run persist itself every N steps, and\n * `compaction` to have long conversations summarized as they grow; each one you\n * pass obliges you to supply the matching handler at `toMachine`, and each one\n * you omit forbids it. `rng` is the determinism seam for the retry backoff —\n * pass a fixed `() => 0` to pin it in tests; omit for `Math.random`.\n *\n * The four overloads exist because the two obligations are derived\n * from the `config` VALUE, never inferred. `{ snapshotEvery: number }` REQUIRES\n * the `snapshot_write` cell, `{ snapshotEvery?: never }` FORBIDS it; `{ compaction:\n * policy }` REQUIRES the `compact_run` cell, `{ compaction?: never }` FORBIDS it.\n * They enumerate the snapshot × compaction grid: overload resolution\n * reads the two fields off `config`, so the right `Snap`/`Compact` pair is fixed\n * even when the call site passes explicit type arguments (TS does not infer\n * trailing type params — a `Cfg`-inference scheme would silently fall back to OFF\n * at every explicit-type-arg call site). The overloads fix both concretely.\n */\nexport function createAgent<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd = Cmd,\n Msg = unknown,\n>(\n config: AgentConfigCore<Stage, P, O, R, TC, Msg> & {\n readonly snapshotEvery: number;\n readonly compaction: CompactionPolicy<R, Msg>;\n },\n): AgentKnob<Stage, P, O, R, TC, true, true>;\nexport function createAgent<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd = Cmd,\n Msg = unknown,\n>(\n config: AgentConfigCore<Stage, P, O, R, TC, Msg> & {\n readonly snapshotEvery: number;\n readonly compaction?: never;\n },\n): AgentKnob<Stage, P, O, R, TC, true, false>;\nexport function createAgent<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd = Cmd,\n Msg = unknown,\n>(\n config: AgentConfigCore<Stage, P, O, R, TC, Msg> & {\n readonly snapshotEvery?: never;\n readonly compaction: CompactionPolicy<R, Msg>;\n },\n): AgentKnob<Stage, P, O, R, TC, false, true>;\nexport function createAgent<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd = Cmd,\n Msg = unknown,\n>(\n config: AgentConfigCore<Stage, P, O, R, TC, Msg> & {\n readonly snapshotEvery?: never;\n readonly compaction?: never;\n },\n): AgentKnob<Stage, P, O, R, TC, false, false>;\nexport function createAgent<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n TC extends Cmd = Cmd,\n Msg = unknown,\n>(\n config: AgentConfig<Stage, P, O, R, TC, Msg>,\n): AgentKnob<Stage, P, O, R, TC, boolean, boolean> {\n const rng = config.rng ?? Math.random;\n // ---- The three composed sub-knobs --------------------------------------\n\n const run = createMonitoredRun<Stage, unknown>({\n ...(config.stages !== undefined ? { stages: config.stages } : {}),\n ...(config.deadlineMs !== undefined\n ? { deadlineMs: config.deadlineMs }\n : {}),\n ...(config.snapshotEvery !== undefined\n ? { snapshotEvery: config.snapshotEvery }\n : {}),\n });\n\n const llm = createLlmCall<P, O>(\n {\n schemas: config.schemas,\n ...(config.retry !== undefined ? { retry: config.retry } : {}),\n },\n rng,\n );\n // The one handler that invokes the model: the config's two ports around the\n // pure `llm` knob, returning the outcome the engine mints into\n // `resilient_run_ok` / `resilient_run_err` (ADR 0021).\n const invokeBrain = brainHandler<P, O, Msg>(llm, {\n model: config.model,\n ...(config.loadMessages !== undefined\n ? { loadMessages: config.loadMessages }\n : {}),\n });\n\n // The DEDICATED compaction round-trip's resilient slice (#85, design B1) — a\n // SECOND resilient-call slice keyed on the reserved `$compact` purpose, so the\n // summarize call inherits the SAME retry/backoff machinery as the brain call\n // WITHOUT sharing its slice (a compaction retry never touches the brain breaker\n // / retry counter). The agent owns the retry ORCHESTRATION (trigger → settle →\n // backoff → re-issue); the consumer's `compact_run` interpret cell owns the\n // summarize I/O (the model round-trip + parse), exactly as the consumer owns\n // tool I/O via `toolOf`. The slice's `input` is the plain `LlmCall<$compact>`\n // request, its `result` the parsed `LlmOk` the consumer's cell returns. Always\n // built; never driven when no policy is configured (the trigger never fires).\n const compactRc = createResilientCall<\n LlmCall<CompactionPurpose>,\n LlmOk<CompactionPurpose, CompactionOutputs>\n >({ ...(config.retry !== undefined ? { retry: config.retry } : {}) }, rng);\n\n // Tools fan out at `toolConcurrency` (default 1 = the seed's serial dispatch).\n // The fan-out item is the `ToolCall`; its identity is `callId`; each launch is\n // the consumer's `toolOf(call)` effect. No `join` — the agent reads completion\n // off `isComplete` at the settle boundary (it must fold + fire the next brain\n // call, not emit a single completion Cmd).\n // `TC` is the fan-out's launch-Cmd type and `never` its join-Cmd type (the\n // agent fires no `join` — it reads completion off `isComplete`), so `scatter`\n // / `itemOk` / `itemErr` return `readonly TC[]` (not the widened `Cmd[]`). The\n // agent's verb tuples stay precisely `AgentCmd<P, TC>` with no widening cast\n // on the launch cmds.\n const fan = createFanOut<ToolCall, ToolOutcome<R>, TC, never>({\n concurrency: config.toolConcurrency ?? 1,\n idOf: (call) => call.callId,\n of: (call) => config.toolOf(call),\n });\n\n // The PER-TOOL timeout / retry ladders (#117) — one more `resilient-call`\n // composition, the third. `fan.of` still names the effect, but a tool that\n // declared a policy does not reach it directly: every launch the fan-out\n // authorizes is routed through `ladder.launch`, which arms the tool's timeout\n // and emits the run Cmd, and every settle is offered to the ladder first. A\n // tool that declared nothing is passed straight through, so the whole feature\n // is inert for an agent that uses none of it.\n const ladder = createToolLadder<TC>(\n config.toolResilienceOf ?? (() => null),\n config.toolOf,\n rng,\n );\n\n type State = AgentState<Stage, P, O, R>;\n\n /** The starting slice — every brick's `init`, no conversation yet. */\n function init(): State {\n return {\n run: run.init(),\n resilience: llm.init(),\n tools: initFanOut<ToolCall, ToolOutcome<R>>(),\n conversation: null,\n compaction: compactRc.init(),\n toolResilience: ladder.init(),\n refusedCalls: [],\n failure: null,\n output: null,\n instructions: config.instructions ?? null,\n };\n }\n\n /** Build the brain-call request for the current stage + conversation. PURE. */\n function brainCall(s: State): LlmCall<P> {\n const stage = currentStage(s);\n const conversation = s.conversation ?? freshConversation<R>();\n // `?? null`: a Model persisted before the slot existed rehydrates without it.\n const instructions = s.instructions ?? null;\n return {\n purpose: config.turnOf(stage),\n model: config.modelId ?? null,\n payload: config.payloadOf\n ? config.payloadOf(stage, conversation, instructions)\n : null,\n };\n }\n\n /**\n * Fire the current stage's brain call: build the request ({@link brainCall}),\n * thread it through the resilient retry layer, and return the resilience-updated\n * state + the llm run Cmds. THE shared epilogue of every verb that (re-)enters\n * the brain path — `start`, `advanceStage`, `settleTool`'s drain, `compactOk`,\n * `compactErr`, `boot` — each concats its OWN leading Cmds onto the returned llm\n * Cmds. PURE — `at` is the only clock.\n */\n function fireBrainCall(\n s: State,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const call = brainCall(s);\n const [resilience, cmds] = llm.attempt(s.resilience, call, at);\n return [{ ...s, resilience }, cmds];\n }\n\n /**\n * Build the compaction summarize request for a conversation + fold count — the\n * `$compact` sibling of {@link brainCall}, so the summarize-request shape lives\n * in ONE spot and both the trigger (`maybeCompact`) and the boot re-fire emit a\n * byte-identical `LlmCall<$compact>`. PURE.\n */\n function compactionCall(\n conv: Conversation<R>,\n folding: number,\n ): LlmCall<CompactionPurpose> {\n const payloadOf = config.compaction?.payloadOf;\n return {\n purpose: COMPACTION_PURPOSE,\n model: config.modelId ?? null,\n payload: payloadOf ? payloadOf(conv, folding) : null,\n };\n }\n\n /** The dedicated compaction round-trip's resilient slice type (#85, design B1). */\n type CompactionSlice = ResilientState<\n LlmCall<CompactionPurpose>,\n LlmOk<CompactionPurpose, CompactionOutputs>\n >;\n\n /**\n * Re-key a compaction verb's `[slice, resilient_run Cmds]` result so the emitted\n * Cmds carry the dedicated `compact_run` discriminant. The one place the\n * `with-resilience` boundary re-key ({@link toCompactRunCmd}) lives.\n */\n function reKeyCompactCmds(\n result: readonly [CompactionSlice, readonly LlmRunCmd<CompactionPurpose>[]],\n ): readonly [CompactionSlice, readonly AgentCompactRunCmd[]] {\n const [slice, cmds] = result;\n return [slice, cmds.map(toCompactRunCmd)];\n }\n\n /**\n * The compaction slice's three cmd-emitting verbs, wrapped so each returns its\n * `resilient_run` Cmds ALREADY re-keyed to the dedicated `compact_run`\n * discriminant. The re-key is an INVARIANT of talking to `compactRc` — its Cmds\n * must route to the compaction interpret cell, never the brain `resilient_run`\n * one — so it lives here ONCE instead of at every call boundary, where a single\n * forgotten `.map` would misroute a compaction run Cmd to the brain cell. PURE —\n * pure delegation + re-key. (`init` / `subs` emit no run Cmds → used on\n * `compactRc` directly.)\n */\n const compact = {\n attempt: (\n slice: CompactionSlice,\n key: CompactionPurpose,\n input: LlmCall<CompactionPurpose>,\n at: number,\n ): readonly [CompactionSlice, readonly AgentCompactRunCmd[]] =>\n reKeyCompactCmds(compactRc.attempt(slice, key, input, at)),\n settle: (\n slice: CompactionSlice,\n msg: Parameters<typeof compactRc.settle>[1],\n ) => {\n const { call, cmds, outcome } = compactRc.settle(slice, msg);\n return { call, cmds: cmds.map(toCompactRunCmd), outcome };\n },\n onTimer: (\n slice: CompactionSlice,\n msg: Parameters<typeof compactRc.onTimer>[1],\n ): readonly [CompactionSlice, readonly AgentCompactRunCmd[]] =>\n reKeyCompactCmds(compactRc.onTimer(slice, msg)),\n };\n\n // === Verb: start =========================================================\n\n /**\n * Start (or restart) the run for `runId` at `at`, entering the agentic loop:\n * seed the pipeline (via monitored-run), seed a fresh conversation, and fire\n * the first brain call. PURE — `at` is the only clock.\n */\n function start(\n s: State,\n runId: string,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const [runSlice] = run.start(s.run, runId, at);\n const conversation = freshConversation<R>();\n const withRun: State = {\n ...s,\n run: runSlice,\n conversation,\n failure: null,\n // A restart clears the prior run's terminal output — `result()` reads\n // `undefined` again until THIS run finishes (#46).\n output: null,\n tools: initFanOut<ToolCall, ToolOutcome<R>>(),\n // A restart also clears any prior compaction slice — a fresh run never\n // inherits the previous run's summarize retry bookkeeping (#85).\n compaction: compactRc.init(),\n // …and the prior run's refusals: those `callId`s belong to a batch this\n // run will never settle, so carrying them would only grow the Model (#145).\n refusedCalls: [],\n };\n return fireBrainCall(withRun, at);\n }\n\n // === Verb: turn ==========================================================\n\n /**\n * Fold ONE model turn (the brain call resolved with an `AgentTurn`). The core\n * of the loop — the seed's `applyAiTurn`, generalized:\n *\n * - empty `toolCalls` → the loop is done for this stage → `advance` the\n * pipeline (next stage seeds a fresh conversation + brain call, or finish\n * to `done`).\n * - non-empty `toolCalls` → `scatter` them across fan-out (≤ concurrency in\n * flight), recording the turn and flipping `awaiting` to `tools`. The\n * returned Cmds are the launched per-tool effects.\n *\n * A no-op when the run is settled or the slice is not awaiting a brain call\n * (stale settle after boot / advance). PURE — `at` is the only clock.\n */\n function turn(\n s: State,\n result: AgentTurn,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const conv = requireAwaiting(s, \"llm\");\n if (conv === null) return [s, []];\n\n const withTurn: Conversation<R> = {\n ...conv,\n turns: [...conv.turns, result],\n };\n\n // ── No tool calls → the stage's loop is done → advance the pipeline. ──\n // `result` is the terminating turn — threaded into `advanceStage` so it can\n // be stamped as the run's `output` when this retire finishes the pipeline.\n if (result.toolCalls.length === 0) {\n return advanceStage({ ...s, conversation: withTurn }, result, at);\n }\n\n // ── Tool calls → scatter across fan-out (serial by default). ──\n // The fan-out item identity IS `callId` (`idOf`). A model that emits the\n // SAME `callId` twice in one turn is a defect: scattering both would launch\n // the consumer's `toolOf(call)` effect twice for one identity (the dup runs\n // TWICE) while a single settle Msg can only close ONE of the two `running`\n // entries — the other stays in flight forever and the batch never drains.\n // Collapse duplicates by `callId` (keep first occurrence) so every distinct\n // tool launches exactly once and each `callId` settles exactly once.\n const batch = dedupeByCallId(result.toolCalls);\n const [tools] = fan.scatter(initFanOut<ToolCall, ToolOutcome<R>>(), batch);\n const nextConv: Conversation<R> = {\n ...withTurn,\n awaiting: { kind: \"tools\", batchTurn: withTurn.turnCount },\n };\n // An advance of the loop is progress — bump the monitored-run watchdog.\n const [runSlice] = run.progress(s.run, undefined, at);\n const [toolResilience, launchCmds] = armLaunch(s, [], tools.running, at);\n return [\n { ...s, run: runSlice, tools, toolResilience, conversation: nextConv },\n launchCmds,\n ];\n }\n\n /**\n * Advance the outer pipeline on a finished stage loop. Retire the current\n * stage (monitored-run `advance`); if the pipeline finished → `done`, else\n * seed a fresh conversation for the next stage and fire its first brain call.\n * Shared by `turn` (empty tool calls) so the loop-end → next-stage move lives\n * in one place. PURE.\n *\n * `terminatingTurn` is the empty-tool model turn that ended the current\n * stage's loop. When THIS retire finishes the whole pipeline (`done`), it is\n * the run's terminal output — stamped on `state.output` so it survives the\n * conversation clear and `runtime.result()` can read it (#46).\n */\n function advanceStage(\n s: State,\n terminatingTurn: AgentTurn,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const [runSlice, runCmds] = run.advance(\n s.run,\n undefined,\n { kind: \"ok\" },\n at,\n );\n // Pipeline finished (or single-shot done) → no further brain call. The\n // terminating turn is the run's output; record it before clearing the\n // conversation so the result survives the retire (the field the deleted\n // `captureLastTurn` host hook used to reconstruct off the stream).\n if (runSlice.phase === \"done\") {\n return [\n { ...s, run: runSlice, conversation: null, output: terminatingTurn },\n runCmds,\n ];\n }\n // Next stage → fresh conversation + its first brain call.\n const conversation = freshConversation<R>();\n const moved: State = {\n ...s,\n run: runSlice,\n conversation,\n tools: initFanOut<ToolCall, ToolOutcome<R>>(),\n };\n const [fired, llmCmds] = fireBrainCall(moved, at);\n return [fired, [...runCmds, ...llmCmds]];\n }\n\n // === Verb: toolOk / toolErr ==============================================\n\n /**\n * Record a tool's success for `callId` and launch the next queued tool to\n * backfill the freed slot (the seed's queue-drain → next-tool). When the batch\n * drains, fold every gathered outcome into the conversation, bump the turn\n * count (livelock guard), and fire the next brain call — `awaiting` flips back\n * to `llm` (\"fold → llm\"). PURE.\n */\n function toolOk(\n s: State,\n callId: string,\n result: R,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const call = inFlight(s, callId);\n // A success ends the ladder for this call: `ladder.ok` drops its entry, and\n // dropping it is what disarms the timeout Sub — so the value settles and no\n // timer survives to fire against a call that is already folded.\n const laddered =\n call === null\n ? s\n : { ...s, toolResilience: ladder.ok(toolSlice(s), call, at) };\n return settleTool(laddered, callId, { kind: \"ok\", result }, at);\n }\n\n /**\n * Record a tool's failure for `callId` — symmetric to `toolOk`. A failed tool\n * still counts toward batch completion (the model sees the error reason and\n * recovers — \"errors are data\"); same fold → llm tail when the batch drains.\n * PURE.\n */\n function toolErr(\n s: State,\n callId: string,\n reported: string | ToolFailure,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n // A bare string is the hand-wired caller's shape and carries no tag — the\n // one untagged arm `ToolFailure`'s optional `_tag` exists for, beside a\n // record a pre-0.13 `Store` hands back.\n const failure: ToolFailure =\n typeof reported === \"string\"\n ? { kind: \"error\", reason: reported }\n : reported;\n const call = inFlight(s, callId);\n if (call === null) return settleTool(s, callId, failure, at);\n // Offer the failure to the ladder FIRST. A `null` verdict means it armed\n // another attempt: the fan-out entry stays `running`, nothing is folded, and\n // the wait is a timer Sub on the Model rather than an `await` inside a\n // handler — which is what makes the ladder survive a process kill. Anything\n // else is the failure the call ends on, ladder-authored or the tool's own —\n // and either way it is the STRUCTURED failure, so the `_tag` #115 keeps\n // survives the ladder instead of being flattened by passing through it.\n const [toolResilience, settled] = ladder.err(\n toolSlice(s),\n call,\n failure,\n at,\n );\n const next: State = { ...s, toolResilience };\n if (settled === null) return [next, []];\n return settleTool(next, callId, settled, at);\n }\n\n /** The in-flight `ToolCall` for `callId`, or `null` if none is running. PURE. */\n function inFlight(s: State, callId: string): ToolCall | null {\n return s.tools.running.find((c) => c.callId === callId) ?? null;\n }\n\n /**\n * The tool-ladder slice, defaulting to empty. The default is the rehydration\n * guard: a Model persisted before this slice existed comes back without the\n * field, and it must read as \"no tool has laddered\" rather than crash. PURE.\n */\n function toolSlice(s: State): ToolResilienceState {\n return s.toolResilience ?? {};\n }\n\n /**\n * The refused-`callId` list, defaulting to empty — the same rehydration guard\n * `toolSlice` carries, for the same reason: a Model persisted before the\n * field existed comes back without it, and it must read as \"nothing refused\n * yet\" rather than crash. PURE.\n */\n function refusedOf(s: State): readonly string[] {\n return s.refusedCalls ?? [];\n }\n\n /**\n * Arm every launch the fan-out just authorized. The fan-out's own launch Cmds\n * are DISCARDED in favour of these: a policied tool's effect must be emitted\n * by its resilient gate (which is what records the attempt and arms the\n * timeout), and a bare tool's is re-emitted here identically. The two lists\n * are the same calls either way — `after \\ before` is exactly what the\n * fan-out moved into `running`. PURE.\n */\n function armLaunch(\n s: State,\n before: readonly ToolCall[],\n after: readonly ToolCall[],\n at: number,\n ): readonly [ToolResilienceState, readonly TC[]] {\n const known = new Set(before.map((c) => c.callId));\n return ladder.launch(\n toolSlice(s),\n after.filter((c) => !known.has(c.callId)),\n at,\n );\n }\n\n /**\n * Shared tool-settle body: route the outcome into fan-out, fold the matching\n * call+outcome onto the conversation, and — if the batch is now complete —\n * fold the turn and fire the next brain call. PURE.\n */\n function settleTool(\n prev: State,\n callId: string,\n outcome: ToolOutcome<R>,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const conv = requireAwaiting(prev, \"tools\");\n if (conv === null) return [prev, []];\n\n // Find the original call (by id) so the folded record carries it. A settle\n // for an unknown / already-settled id is a no-op (fan-out also no-ops it).\n const call = prev.tools.running.find((c) => c.callId === callId);\n if (call === undefined) return [prev, []];\n\n const [tools] =\n outcome.kind === \"ok\"\n ? fan.itemOk(prev.tools, callId, outcome)\n : fan.itemErr(prev.tools, callId, outcome);\n // The freed slot backfills from the queue — those launches are armed exactly\n // like the batch's first ones, so a queued tool gets its timeout too.\n const [toolResilience, launchCmds] = armLaunch(\n prev,\n prev.tools.running,\n tools.running,\n at,\n );\n // A failure IS this call's public outcome: `onToolError` reports it now, so\n // any later success for the same `callId` is a late result of an abandoned\n // attempt and must be silent on every public channel (#145). Recorded here,\n // at the one settle body both the ladder's deadline arm and a tool's own\n // error pass through, so the projector needs no second rule per source.\n const refusedCalls =\n outcome.kind === \"ok\" ? refusedOf(prev) : [...refusedOf(prev), callId];\n const s: State = { ...prev, toolResilience, refusedCalls };\n\n const foldedConv: Conversation<R> = {\n ...conv,\n // Stamp the producing-turn index on the record (#85, A1). At settle time\n // `conv.turnCount` equals the index in `turns` of the turn that scattered\n // this batch (each prior drained batch bumped `turnCount` exactly once, and\n // each tool-bearing turn appended exactly one entry to `turns`), so a record\n // carrying `turn: conv.turnCount` is dropped iff its producing turn is folded\n // (`turn < N`) — the association the fold-back relies on.\n toolRecords: [\n ...conv.toolRecords,\n { call, outcome, turn: conv.turnCount },\n ],\n };\n\n // Batch still draining → record + keep launching the next queued tool.\n if (!fan.isComplete(tools)) {\n const [runSlice] = run.progress(s.run, undefined, at);\n return [\n { ...s, run: runSlice, tools, conversation: foldedConv },\n launchCmds,\n ];\n }\n\n // ── Batch drained → fold the turn → fire the next brain call. ──\n const turnedConv: Conversation<R> = {\n ...foldedConv,\n turnCount: foldedConv.turnCount + 1,\n awaiting: { kind: \"llm\" },\n };\n\n // ── The turn boundary's stop conditions, in order. ──\n const turned: State = { ...s, tools, conversation: turnedConv };\n const stopped = stopConditions(turned, at);\n if (stopped !== null) return stopped;\n\n // The tool ledger resets for the next turn's batch regardless of which\n // effect (compaction or brain call) fires next.\n const drained: State = {\n ...turned,\n tools: initFanOut<ToolCall, ToolOutcome<R>>(),\n };\n\n // ── Compaction trigger (#85, design B1). BEFORE the next brain call, ask\n // the PURE policy how many oldest turns to fold. N > 0 → fire the dedicated\n // compaction round-trip INSTEAD of the brain call and flip awaiting to\n // `compacting`; the fold-back (`compact_ok`) then fires the brain call. The\n // trigger bumps the watchdog (compaction IS liveness, decision C) but does\n // NOT bump `turnCount` — it already bumped once for this drained batch, and\n // compaction is not model reasoning progress, so it never trips `maxTurns`.\n const compacting = maybeCompact(drained, at);\n if (compacting !== null) return compacting;\n\n // ── No compaction → fire the next brain call. ──\n // An advance of the loop is progress — bump the watchdog, then fire.\n const [runSlice] = run.progress(drained.run, undefined, at);\n const [fired, llmCmds] = fireBrainCall({ ...drained, run: runSlice }, at);\n return [fired, [...launchCmds, ...llmCmds]];\n }\n\n /**\n * The compaction trigger (#85, design B1) — PURE. Given the drained-batch\n * state about to fire a brain call, consult `config.compaction.planCompaction`\n * (the consumer's PURE heuristic). Returns:\n *\n * - `null` — no policy, or the policy returned `0`, or there is nothing to\n * fold (`< 2` turns: folding 0 or 1 turns into a summary cannot shrink the\n * transcript, so it is a no-op the trigger skips rather than spend a round\n * trip). The caller fires the brain call as normal.\n * - `[state, cmds]` — fire the dedicated compaction round-trip: flip\n * `awaiting` to `compacting { folding: N }`, bump the watchdog (liveness,\n * decision C — NOT `turnCount`, so `maxTurns` is untouched), and emit the\n * re-keyed `compact_run` Cmd. `compact_ok` folds the summary back; the loop\n * resumes with the next brain call there.\n *\n * `folding` is clamped to `turns.length` so a policy returning a count larger\n * than the transcript folds the WHOLE transcript into one summary (never more).\n * The launched `launchCmds` from the final tool settle are NOT this function's\n * concern — the caller composes them.\n */\n function maybeCompact(\n s: State,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] | null {\n const policy = config.compaction;\n const conv = s.conversation;\n if (policy === undefined || conv === null) return null;\n const requested = policy.planCompaction(conv);\n // Nothing to gain: a fold of 0 or 1 turns cannot shrink the transcript\n // (`turns[0..N]` → one summary turn only shrinks when N >= 2).\n const folding = Math.min(requested, conv.turns.length);\n if (folding < 2) return null;\n\n const compactConv: Conversation<R> = {\n ...conv,\n awaiting: { kind: \"compacting\", folding },\n };\n // Compaction is forward progress (liveness) — bump the watchdog, NOT the\n // turn count (decision C: it is not model reasoning, must not trip maxTurns).\n const [runSlice] = run.progress(s.run, undefined, at);\n const input = compactionCall(conv, folding);\n // The `compact` adapter re-keys the composed `resilient_run` Cmd(s) to the\n // dedicated `compact_run` discriminant so they route to the compaction\n // interpret cell, never the brain `resilient_run` one (the `with-resilience`\n // boundary-re-key pattern).\n const [compaction, cmds] = compact.attempt(\n s.compaction,\n COMPACTION_PURPOSE,\n input,\n at,\n );\n return [\n { ...s, run: runSlice, conversation: compactConv, compaction },\n cmds,\n ];\n }\n\n /**\n * The turn boundary's three stop conditions, consulted in declaration order\n * on the state a drained batch just folded. Returns the terminal result when\n * one trips, or `null` for \"the loop goes on\" — so the caller reads one\n * branch rather than three, and a fourth guard lands here rather than in the\n * middle of the drain.\n *\n * - `maxTurns` → `failure { turn_limit }`. The count the loop keeps.\n * - `maxElapsedMs` → `failure { elapsed_limit }`. `at - run.startedAt`,\n * both of them durable numbers, so the comparison is as\n * replayable as the turn count's — no clock is read\n * here.\n * - `stopWhen` → `cancelled`, the caller's own stop. Not a failure:\n * nothing went wrong, someone asked to stop, which is\n * the same reading an aborted `signal` gets.\n *\n * PURE — `at` is the only clock, and `stopWhen` is required pure by contract.\n */\n function stopConditions(\n s: State,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] | null {\n const turnCount = s.conversation?.turnCount ?? 0;\n if (config.maxTurns !== undefined && turnCount >= config.maxTurns) {\n return [{ ...s, failure: { reason: \"turn_limit\", at } }, []];\n }\n if (\n config.maxElapsedMs !== undefined &&\n at - s.run.startedAt >= config.maxElapsedMs\n ) {\n return [{ ...s, failure: { reason: \"elapsed_limit\", at } }, []];\n }\n if (config.stopWhen?.(s) === true) return cancel(s, at);\n return null;\n }\n\n // === Verb: succeed / fail (brain-call resilient settles) =================\n\n /**\n * Fold a brain-call SUCCESS — the single entry the engine-minted\n * `resilient_run_ok` Msg drives. Two halves, in order:\n *\n * 1. The RETRY layer: `llm.succeed` closes the breaker and DROPS this key's\n * retry counter. This is the half the old detached wiring skipped — the\n * detached handler dispatched the parsed turn directly and never\n * settled the brain call, so `succeed` never ran, the resilient slice\n * stayed stuck `running`, the breaker never closed, and the retry counter\n * ACCUMULATED across the run (a later transient failure would trip\n * `maxAttempts` prematurely). Running it here resets the retry slice every\n * turn — a clean retry slice across the whole run.\n * 2. The LOOP: fold the parsed `AgentTurn` (`msg.value.output`) through\n * `turn`, which scatters this turn's tools (or advances the pipeline on an\n * empty turn). One engine-minted settle Msg now advances BOTH the resilient\n * slice AND the conversation, so the loop actually progresses to a\n * terminal `done`.\n *\n * PURE — `at` is the only clock.\n */\n function succeed(\n s: State,\n msg: AgentLlmOkMsg<P, O>,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n // 1) Advance the retry layer — resets retry[key], closes the breaker.\n const [resilience, retryCmds] = llm.succeed(s.resilience, msg);\n const settled: State = { ...s, resilience };\n // 2) Fold the parsed turn into the loop (scatter tools / advance the stage).\n // `msg.value.output` is `O[P]`, and the `O extends Record<P, AgentTurn>`\n // bound pins every purpose's output to an `AgentTurn` — so it feeds `turn`\n // with NO cast. The rule lives in the type (invariant 8: no `as` past the\n // boundary), not in a doc-comment the compiler cannot enforce.\n const [withTurn, turnCmds] = turn(settled, msg.value.output, at);\n return [withTurn, [...retryCmds, ...turnCmds]];\n }\n\n /**\n * Record a brain-call failure: back off via the inherited retry (re-arming\n * the retry timer), or — when retry is exhausted / absent — the resilient\n * slice settles the call `failed`. The agent also stamps an `llm` failure on\n * its own slice so a consumer can render the terminal cause — the typed\n * `LlmErr` `llm.errOf` reads off the Msg. PURE.\n */\n function fail(\n s: State,\n msg: AgentLlmErrMsg<P>,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const [resilience, cmds] = llm.fail(s.resilience, msg);\n // If the resilient slice settled this call terminally (no retry pending),\n // surface the agent-level llm failure too. A `waiting_retry` phase means a\n // retry is armed → not terminal → leave `failure` untouched.\n const call = resilience.calls[msg.cmd.key];\n const failure: AgentFailure | null =\n call?.phase === \"failed\"\n ? { reason: \"llm\", error: llm.errOf(msg), at }\n : s.failure;\n return [{ ...s, resilience, failure }, cmds];\n }\n\n // === Verb: compactOk / compactErr (compaction resilient settles) =========\n\n /**\n * Fold the compaction SUMMARY back (#85, design A1) — the entry the re-entered\n * `compact_ok` settle Msg drives. Two halves, in order:\n *\n * 1. The RETRY layer: `compactRc.settle` closes the compaction breaker and\n * DROPS the `$compact` retry counter (the same reset the brain `succeed`\n * does, on the dedicated compaction slice).\n * 2. The FOLD-BACK: replace `turns[0..folding]` AND every `toolRecord` whose\n * `turn < folding` with a SINGLE synthetic summary `AgentTurn` (no tool\n * calls, carrying the summary text), then RE-INDEX the surviving records'\n * `turn` so the new head (the summary) is index 0. `turnCount` is\n * UNCHANGED (compaction is not a model round-trip — decision C), and\n * `awaiting` flips back to `llm`. The next brain call fires on the shrunk\n * transcript — the loop the trigger paused resumes here.\n *\n * A no-op if the run is settled or not awaiting compaction (a stale settle).\n * PURE — `at` is the only clock.\n */\n function compactOk(\n s: State,\n key: string,\n msg: AgentCompactOkMsg,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n // 1) Advance the compaction retry layer — resets retry[$compact], closes the\n // compaction breaker. Reuses resilient-call's `settle` on the dedicated\n // slice; the parsed `LlmOk` the `compact_ok` carries is its value.\n const { call: compaction, cmds: retryCmds } = compact.settle(s.compaction, {\n cmd: { key },\n value: msg.result,\n at: msg.at,\n });\n const settledRetry: State = { ...s, compaction };\n\n // Stale settle (the run is settled, or advanced/rebooted past this\n // compaction). The retry slice still resets above; emit only its cmds\n // (settling an `_ok` never emits a run Cmd, so `retryCmds` is empty here).\n const conv = requireAwaiting(settledRetry, \"compacting\");\n if (conv === null) return [settledRetry, retryCmds];\n\n // 2) Fold-back. `folding` is the count the trigger pinned on `awaiting`; the\n // summary turn replaces those oldest turns + their records.\n const folding = conv.awaiting.folding;\n const summaryTurn: AgentTurn = {\n content: msg.result.output.summary,\n toolCalls: [],\n };\n const foldedConv = foldSummary(conv, folding, summaryTurn);\n // Resume the loop: fire the next brain call on the shrunk transcript.\n const [fired, llmCmds] = fireBrainCall(\n { ...settledRetry, conversation: foldedConv },\n at,\n );\n return [fired, [...retryCmds, ...llmCmds]];\n }\n\n /**\n * Record a compaction FAILURE (#85). Back off via the compaction slice's\n * inherited retry (re-arming the `$compact` retry timer), or — when retry is\n * exhausted / absent — PROCEED WITHOUT COMPACTING: flip `awaiting` back to\n * `llm` and fire the brain call on the (un-compacted) transcript. Compaction is\n * an OPTIMIZATION, not correctness: a failed summarize must not wedge or fail\n * the whole run (errors are data). This is the chosen option of design B1's\n * `compact_err` fork — it is strictly weaker than failing the run, and the\n * brain call's OWN resilient retry / the deadline watchdog still bound the\n * un-compacted continuation. A consumer that wants compaction failure to be\n * terminal can detect it on the `compaction` slice's `failed` phase. PURE.\n */\n function compactErr(\n s: State,\n key: string,\n msg: AgentCompactErrMsg,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const {\n call: compaction,\n cmds,\n outcome,\n } = compact.settle(s.compaction, {\n cmd: { key },\n error: msg.error,\n at: msg.at,\n });\n const settledRetry: State = { ...s, compaction };\n\n // A retry is armed (`retrying`) → not terminal → keep awaiting the\n // re-issued compaction call (the re-keyed run Cmd, if any, rides here).\n if (outcome.kind === \"retrying\") {\n return [settledRetry, cmds];\n }\n\n // Stale settle (run settled, or advanced/rebooted past this compaction).\n // Past the `waiting_retry` guard `fail` emits no run Cmd, so `cmds` is empty.\n const conv = requireAwaiting(settledRetry, \"compacting\");\n if (conv === null) return [settledRetry, cmds];\n\n // Exhausted retry (or no retry) → proceed WITHOUT compacting: drop the\n // `compacting` state, fire the next brain call on the un-compacted transcript.\n const resumedConv: Conversation<R> = { ...conv, awaiting: { kind: \"llm\" } };\n const [fired, llmCmds] = fireBrainCall(\n { ...settledRetry, conversation: resumedConv },\n at,\n );\n return [fired, [...cmds, ...llmCmds]];\n }\n\n // === Verb: onTimer =======================================================\n\n /**\n * A timer fired — disambiguated by Sub id across the composed bricks:\n *\n * - a `monitored:safety:*` id → the no-progress watchdog → fail the run via\n * the inherited monitored-run `onDeadline`.\n * - a `resilient:*:$compact` id → a COMPACTION retry/deadline timer →\n * re-run the compaction call via the compaction slice's `onTimer`, re-keying\n * its re-issued `resilient_run` to the dedicated `compact_run` (#85).\n * - any other `resilient:*` id → a brain-call retry timer → re-run the brain\n * call via the inherited llm-call `onTimer`.\n *\n * Each brick `onTimer` / `onDeadline` verb tolerates a stale fire for another's\n * id (it no-ops on a non-matching id), so the routing is by id prefix/suffix.\n * PURE.\n */\n function onTimer(\n s: State,\n msg: AgentTimerMsg,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n if (msg.id.startsWith(\"monitored:\")) {\n const [runSlice] = run.onDeadline(s.run, msg);\n return [{ ...s, run: runSlice }, []];\n }\n // The compaction slice's timers are keyed on the reserved `$compact` purpose\n // (`resilient:retry:$compact` / `resilient:deadline:$compact`), distinct from\n // every brain purpose, so the suffix routes the fire to the right slice.\n if (msg.id.endsWith(`:${COMPACTION_PURPOSE}`)) {\n const [compaction, cmds] = compact.onTimer(s.compaction, msg);\n return [{ ...s, compaction }, cmds];\n }\n // A `$tool:`-keyed id is one of the per-tool ladders (#117): either a retry\n // timer, whose fire IS the next attempt, or a timeout, whose fire ends the\n // call. Both come back as data the reducer folds — the run cmds to re-issue\n // and, for a timeout, the settle order the fan-out then folds like any\n // other failure, so the model reads `timeout` as an ordinary tool error.\n if (isToolTimerId(msg.id)) return toolTimer(s, msg);\n const [resilience, cmds] = llm.onTimer(s.resilience, msg);\n return [{ ...s, resilience }, cmds];\n }\n\n /**\n * Fold one tool-ladder timer fire: apply it to the slice, emit whatever next\n * attempt it authorized, and settle every call it gave up on. A timeout's\n * settle runs through `settleTool`, so a timed-out call drains its batch and\n * fires the next brain call exactly as a handler-reported failure would —\n * there is no second completion path to keep in step. PURE.\n */\n function toolTimer(\n s: State,\n msg: AgentTimerMsg,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const [toolResilience, outcome] = ladder.onTimer(toolSlice(s), msg);\n return applyLadder(s, toolResilience, outcome, msg.atMs);\n }\n\n /**\n * Fold one ladder outcome onto the Model: adopt the new slice, keep the\n * attempts it authorized, and drive every call it gave up on through\n * `settleTool` so a ladder-ended call drains its batch and fires the next brain\n * call exactly as a handler-reported failure would. Shared by the timer fire\n * and the boot path, which produce the same outcome for the same reason — there\n * is no second completion path to keep in step. PURE.\n */\n function applyLadder(\n s: State,\n toolResilience: ToolResilienceState,\n outcome: ToolTimerOutcome<AgentCmd<P, TC>>,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n let next: State = { ...s, toolResilience };\n const cmds: AgentCmd<P, TC>[] = [...outcome.cmds];\n for (const order of outcome.settle) {\n const [settled, more] = settleTool(next, order.callId, order.failure, at);\n next = settled;\n cmds.push(...more);\n }\n return [next, cmds];\n }\n\n // === Verb: boot ==========================================================\n\n /**\n * Resume after a reload (cold wake) — the seed's boot reconcile, generalized.\n * Re-seeds the watchdog clock to `at` (a cold wake is not a no-progress wedge)\n * via monitored-run `boot`, then RE-EMITS the ONE outstanding effect derived\n * from `phase × awaiting`:\n *\n * - awaiting `llm` → re-fire the current stage's brain call (idempotent:\n * had the response been processed, the durable Model would already have\n * advanced + persisted, so boot re-emits the NEXT effect).\n * - awaiting `tools` → re-fire every in-flight tool Cmd (idempotent via\n * `callId` — the consumer's tool runner dedupes a re-issued call).\n * - awaiting `compacting` → re-fire the in-flight compaction call (#85),\n * idempotent at the compaction slice's gate exactly like the brain call.\n * - no conversation (between stages / settled) → no effect.\n *\n * A no-op on a settled run. PURE.\n */\n function boot(\n s: State,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const [runSlice] = run.boot(s.run, at);\n const rebooted: State = { ...s, run: runSlice };\n if (isSettled(rebooted)) return [rebooted, []];\n\n const conv = rebooted.conversation;\n if (conv === null) return [rebooted, []];\n\n if (conv.awaiting.kind === \"llm\") {\n // Re-fire the brain call. The resilient slice already tracks it `running`;\n // re-issuing the same key is idempotent at the gate (re-emits the run Cmd).\n return fireBrainCall(rebooted, at);\n }\n\n if (conv.awaiting.kind === \"compacting\") {\n // Re-fire the in-flight compaction round-trip (#85). The compaction slice\n // already tracks `$compact` running; re-issuing the same key is idempotent\n // at the gate, and the re-emitted `resilient_run` is re-keyed to `compact_run`.\n const input = compactionCall(conv, conv.awaiting.folding);\n const [compaction, cmds] = compact.attempt(\n rebooted.compaction,\n COMPACTION_PURPOSE,\n input,\n at,\n );\n return [{ ...rebooted, compaction }, cmds];\n }\n\n // awaiting tools → re-fire every running tool's effect Cmd, through the\n // ladder. It re-arms each policied call's timeout and — the point of the\n // whole exercise — SKIPS a call the kill caught between two attempts: that\n // one's next attempt is already owed to the retry timer `subs` re-arms off\n // the rehydrated slice, so re-firing here would buy an attempt the budget\n // never granted and reset the count that survived the kill.\n const [toolResilience, outcome] = ladder.boot(\n toolSlice(rebooted),\n rebooted.tools.running,\n at,\n );\n return applyLadder(rebooted, toolResilience, outcome, at);\n }\n\n // === Verb: cancel ========================================================\n\n /**\n * Settle the run `cancelled` at `at` — the fold of an aborted `AbortSignal`.\n * Delegates the phase move to monitored-run and emits NO Cmd, which is the\n * whole of \"stop dispatching new work\": from here `isSettled` holds, so every\n * later Msg — a tool settling, a brain call returning, a retry timer firing —\n * folds to a no-op and issues nothing. The effects already in flight are not\n * recallable (a promise cannot be cancelled); they run to their own end, and\n * the `refusedCalls` discipline (#145) keeps their late results off every\n * public channel.\n *\n * The conversation is left exactly as it stood. Clearing it would destroy the\n * transcript of the work that DID happen before the stop, and a cancelled run\n * is a run someone may still want to read.\n *\n * A no-op on a settled run — monitored-run's own guard — so an abort racing a\n * finish never overwrites the outcome that won. PURE.\n */\n function cancel(\n s: State,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const [runSlice] = run.cancel(s.run, at);\n return [{ ...s, run: runSlice }, []];\n }\n\n // === Subs ================================================================\n\n /**\n * The merged deadline list — the brain-call retry timers (`../llm-call`),\n * the COMPACTION retry timers (the dedicated `$compact` slice, #85), the\n * PER-TOOL retry + timeout timers (the `$tool:`-keyed ladders, #117), and the\n * no-progress safety deadline (`../monitored-run`). All are `DeadlineSub`s\n * told apart by id (the compaction timers are keyed `resilient:*:$compact`,\n * distinct from every brain timer), armed by ONE `deadline` Sub\n * (`deadlinesSub`) and its `subscribeDeadline` runner. PURE.\n */\n function subs(s: State): readonly DeadlineSub[] {\n return [\n ...llm.deadlines(s.resilience),\n ...compactRc.deadlines(s.compaction),\n ...ladder.subs(toolSlice(s)),\n ...run.deadlines(s.run),\n ];\n }\n\n // === Handlers ============================================================\n\n /**\n * The brain-call interpret handler — the `resilient_run` cell `toMachine`\n * wires, built from the config's `model` / `loadMessages` ports (`./model`).\n * It assembles messages, binds the purpose schema, invokes, and RETURNS the\n * outcome `llm.decode` builds: the brain Cmd is `Cmd.define`d, so the engine\n * mints `resilient_run_ok` / `resilient_run_err` from it (ADR 0021), and\n * dispatches them to the reducer's `succeed` / `fail` arms — which advance\n * the inherited retry loop AND fold the parsed turn into the conversation.\n */\n function brainHandlers<Ctx>(): Interpret<\n AgentLlmOkMsg<P, O> | AgentLlmErrMsg<P>,\n AgentLlmRunCmd<P>,\n Ctx\n > {\n return { resilient_run: invokeBrain };\n }\n\n /**\n * Wire the agent into a single runnable `defineMachine`, returned as a\n * `Wired` beside its handlers. The host Msg union is the closed set of verb\n * entry points; `update` routes each to the matching verb, `subs` declares\n * one `deadline` Sub over every brick's deadlines, `subscribe` carries its\n * runner, and `interpret` is the FIXED brain-call handler.\n *\n * The brain call uses the FIXED no-arg handler (`brainHandlers`): it returns\n * the call's outcome, and the engine mints `resilient_run_ok` /\n * `resilient_run_err` from it (ADR 0021). The `resilient_run_ok` arm runs\n * `succeed` (reset retry + close breaker + fold the parsed turn) and the\n * `resilient_run_err` arm runs `fail` (back off via retry, re-arm the timer).\n * This is what drives the loop to a clean terminal `done` with a reset retry\n * slice — fixing the L3 break where the old detached handler dispatched the\n * turn directly, never settled the brain call, and so `succeed` never ran\n * (stuck `running`, accumulating retry).\n *\n * The consumer supplies only the per-tool interpret (the agent owns the brain\n * interpret now; no `ports` to supply — the parsed turn is folded by `succeed`,\n * not by a consumer-built Msg).\n *\n * `HostMsg` is fixed to the agent's own verb-driven Msg union so the machine\n * is self-contained; a consumer needing extra Msgs wires the verbs by hand\n * instead (the knob contract is the escape hatch).\n */\n function toMachine<Ctx = object, T extends AnyToolDef = never>(opts?: {\n /**\n * A `toolRouter` (#56). Its cells join the interpret table, its defs go on\n * `Machine.cmds` (so `run`'s edge parses each `_ok` and stamps `at`), and\n * one reducer cell per settled Msg folds the tool back through `toolOk` /\n * `toolErr` — the router's `toolOf` is the config's, so the consumer wires\n * nothing per tool.\n */\n readonly tools?: ToolRouter<T>;\n /**\n * The consumer's interpret for the non-brain Cmds — the per-tool effect\n * `TC`, plus (ONLY when checkpointing is configured) the monitored-run\n * `snapshot_write` checkpoint cell. The brain `resilient_run` cell the agent\n * owns is merged in below, so the consumer supplies only the rest of the\n * config-derived `AgentCmd<P, TC, Snap>` union.\n *\n * The snapshot obligation is CONFIG-DERIVED (#55): `SnapshotInterpret`\n * resolves to a REQUIRED `snapshot_write` cell when `config.snapshotEvery`\n * is set (a real checkpoint write MUST be wired — never a silent no-op), and\n * to `{ snapshot_write?: never }` (the cell is FORBIDDEN — it can never fire)\n * when checkpointing is off. There is no default no-op: a non-checkpointing\n * consumer cannot even mention `snapshot_write`, and a checkpointing one must.\n */\n readonly toolInterpret?: Interpret<\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n Exclude<TC, WiredToolCmd<T>>,\n Ctx\n > &\n SnapshotInterpret<\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n boolean,\n Ctx\n > &\n CompactInterpret<\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n boolean,\n Ctx\n >;\n }): {\n readonly machine: Machine<\n State,\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n AgentCmd<P, TC, boolean, boolean>,\n DeadlinesSub,\n Ctx & ToolsCtx<T>\n >;\n readonly interpret: Interpret<\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n AgentCmd<P, TC, boolean, boolean>,\n Ctx & ToolsCtx<T>\n >;\n readonly subscribe: Subscribe<\n AgentMachineMsg<P, O, R> | WiredToolMsg<T>,\n DeadlinesSub,\n Ctx & ToolsCtx<T>\n >;\n } {\n type M = AgentMachineMsg<P, O, R> | WiredToolMsg<T>;\n const tools = opts?.tools;\n // The implementation is typed at `Snap = boolean` — the SUPERSET that\n // always includes the monitored-run checkpoint Cmd; the public OVERLOADS\n // narrow it to `true` / `false` and hand the consumer the precise obligation\n // (#55). `NonBrainCmd` is the consumer's per-tool `TC` plus that checkpoint\n // Cmd, and `ACmd` unions it with the brain Cmd — fully concrete (no pending\n // conditional), union-equal to `AgentCmd<P, TC, boolean>`, and built from the\n // SAME pieces `mergeInterpret` joins so the merge result is syntactically\n // `Interpret<M, ACmd, Ctx>` with no `Exclude`/conditional TS refuses to reduce.\n // `NonBrainCmd` is the consumer's half of the merged interpret — the per-tool\n // `TC`, the monitored-run checkpoint Cmd, AND the compaction `compact_run`\n // Cmd (#85). The consumer owns the `compact_run` cell (the summarize I/O,\n // returning `compact_ok` / `compact_err` for re-entry), exactly as it owns the\n // tool cells; the agent owns only the retry ORCHESTRATION (the slice verbs).\n // At `boolean` this is the SUPERSET; the overloads config-derive `compact_run`\n // IN (policy) or OUT (`{ compact_run?: never }`) of the obligation (#55 reuse).\n type NonBrainCmd = TC | MonitoredRunCmd<unknown> | AgentCompactRunCmd;\n type ACmd = AgentLlmRunCmd<P> | NonBrainCmd;\n // The FIXED brain handler returns an outcome; the engine mints the\n // `resilient_run_ok` / `resilient_run_err` Msg from it and dispatches that\n // into `update` (the `resilient_run_*` arms below). It is PRECISELY an `Interpret` over the brain Cmd\n // (`AgentLlmRunCmd<P>`); the consumer's `toolInterpret` is PRECISELY an\n // `Interpret` over the rest of the config-derived union (`TC`, and\n // `snapshot_write` only when snapshotting). `mergeInterpret` joins the two\n // disjoint halves into the full `Interpret<M, ACmd, Ctx>` — each key maps\n // precisely (`resilient_run` → the brain cell, `TC[\"type\"]` / `snapshot_write`\n // → the consumer's cells), with the one sound mapped-type identity isolated in\n // the helper rather than laundered through `as unknown as` here.\n //\n // No no-op `snapshot_write` default: with checkpointing off `SnapCmd` is\n // `never`, so the Cmd is config-derived OUT of `ACmd`, the consumer never\n // wires it, and the monitored-run slice never emits it — the\n // `snapshot_write: async () => undefined` ceremony (and the type lie it\n // masked) is gone (#55).\n //\n // The router's cells (#56) sit under the consumer's: the router owns the\n // tool Cmds' keys (`Exclude<TC, WiredToolCmd<T>>` took them off the consumer's\n // obligation), the consumer owns the rest, so the two never share a key.\n // At `toolConcurrency > 1` the router's cells are the FANNING ones (ADR\n // 0018 option (c)): they launch their tool, return, and settle in\n // Cmd-emission order through `run`'s own edge, so a turn's calls overlap on\n // the clock. At the serial default the cells are the exact functions\n // `toolRouter` built — the knob's own wall-clock promise, and nothing below\n // it changes.\n const toolCellsInterpret =\n tools === undefined\n ? undefined\n : (config.toolConcurrency ?? 1) > 1\n ? fanOutInterpret<T>(tools.interpret)\n : tools.interpret;\n const consumerInterpret = {\n ...toolCellsInterpret,\n ...opts?.toolInterpret,\n } as Interpret<M, NonBrainCmd, Ctx>;\n const interpret: Interpret<M, ACmd, Ctx> = mergeInterpret<\n M,\n NonBrainCmd,\n AgentLlmRunCmd<P>,\n Ctx\n >(consumerInterpret, brainHandlers<Ctx>());\n\n // Type the dispatch table explicitly so each cell gets its narrowed Msg\n // and the Reducer-form overload of `defineMachine` matches cleanly (the\n // agent State is not a discriminated union, so the Transitions overload's\n // `update` field collapses to `never` and would otherwise mask inference).\n // The verbs return `AgentCmd<P, TC>` — the `Snap = true` superset, because\n // they FORWARD whatever monitored-run emits and the verbs are not themselves\n // config-typed. The machine declares the config-derived `ACmd`; the one\n // narrowing (`update` below) is SOUND because a non-snapshotting run's\n // monitored-run slice provably never emits a `snapshot_write` Cmd, so the\n // forwarded array never carries the variant `ACmd` excludes.\n //\n // The router's settled Msgs (#56) fold exactly as `agent_tool_ok` /\n // `agent_tool_err` do — one cell per `<name>_ok` / `<name>_err`, read off\n // the router's defs, each routed through `outcomeOf` so the `_ok` value and\n // the `{ _tag }` failure's `reason` are rendered in ONE place. The record is\n // built per def at runtime, which is why the reducer is assembled as a\n // record and typed at the `M` union below.\n type ToolCell = (\n s: State,\n m: WiredToolMsg<T>,\n ) => readonly [State, readonly AgentCmd<P, TC>[]];\n const foldTool: ToolCell = (s, m) => {\n const settled = tools?.outcomeOf(m);\n if (settled === undefined || settled === null) return [s, []];\n // Through `toolOk` / `toolErr` rather than straight to `settleTool`: those\n // two are where the per-tool timeout / retry ladder (#117) sees the\n // settle, and a router tool declaring `retry` must climb it exactly as a\n // bare one does. `toolErr` takes the WHOLE failure the router built, so\n // the `{ _tag, …payload }` beside the reason (#115) rides through the\n // ladder intact — re-deriving it from a string here is exactly the loss.\n return settled.outcome.kind === \"ok\"\n ? toolOk(s, settled.callId, settled.outcome.result as R, m.at)\n : toolErr(s, settled.callId, settled.outcome, m.at);\n };\n const toolCells: Record<string, ToolCell> = {};\n for (const def of tools?.defs ?? []) {\n toolCells[def.okType] = foldTool;\n toolCells[def.errType] = foldTool;\n }\n const ownUpdate: Reducer<\n State,\n AgentMachineMsg<P, O, R>,\n AgentCmd<P, TC>\n > = {\n [MsgType.AgentStart]: (s, m) => start(s, m.runId, m.at),\n [MsgType.AgentToolOk]: (s, m) => toolOk(s, m.callId, m.result, m.at),\n // `agent_tool_err` is `createAgent`'s own raw settle Msg and its wire\n // shape is a bare `reason` string — a consumer routing their own interpret\n // through it never declared a tag, so the failure it mints carries none.\n [MsgType.AgentToolErr]: (s, m) => toolErr(s, m.callId, m.reason, m.at),\n // The engine-minted brain-call settle Msgs (from `brainHandlers`' outcome):\n // success runs `succeed` (reset retry + fold the turn), failure runs `fail`.\n [MsgType.ResilientOk]: (s, m) => succeed(s, m, m.at),\n [MsgType.ResilientErr]: (s, m) => fail(s, m, m.at),\n // The re-entered compaction settle Msgs (from the consumer's `compact_run`\n // cell, #85): `compact_ok` folds the summary back (drop oldest turns +\n // their records, fire the next brain call), `compact_err` backs off via the\n // compaction retry or proceeds without compacting.\n [MsgType.CompactOk]: (s, m) => compactOk(s, m.key, m, m.at),\n [MsgType.CompactErr]: (s, m) => compactErr(s, m.key, m, m.at),\n deadline_exceeded: (s, m) => onTimer(s, m),\n [MsgType.AgentBoot]: (s, m) => boot(s, m.at),\n [MsgType.AgentCancel]: (s, m) => cancel(s, m.at),\n };\n // `ownUpdate` carries every `AgentMachineMsg` cell (checked above);\n // `toolCells` carries one per router def. The join is `Reducer` over the\n // union `M` — a mapped type over a generic `T` that TS cannot enumerate,\n // so the identity is asserted once here.\n const update = { ...ownUpdate, ...toolCells } as Reducer<\n State,\n M,\n AgentCmd<P, TC>\n >;\n\n // Build the machine as a fully-typed `Machine<...>` const, then pass it\n // through `defineMachine`'s identity. Annotating the const pins the concrete\n // type params here; calling `defineMachine` with explicit type args instead\n // would defer the `Machine` type's conditionals over the generic `TC` and\n // fail the overload.\n //\n // The machine's Cmd type is the config-derived `ACmd`. `update` is the\n // `AgentCmd<P, TC>` superset reducer; narrowing it to `Reducer<State, M,\n // ACmd>` is the SINGLE sound assertion of the snapshot derivation — a\n // non-snapshotting run never emits the `MonitoredRunCmd` variant `ACmd`\n // drops, so the reducer's emitted arrays provably stay within `ACmd[]`. This\n // is the same shape as `mergeInterpret`'s one sound mapped-type identity: the\n // soundness lives in a documented seam, not smuggled at every verb.\n const machine: Machine<State, M, ACmd, DeadlinesSub, Ctx> = {\n init: (loaded) => (loaded !== null ? [loaded, []] : [init(), []]),\n update: update as Reducer<State, M, ACmd>,\n subs: [deadlinesSub(subs)],\n // The brain run Cmd is `Cmd.define`d: listing it is what makes the\n // engine mint `resilient_run_ok` / `resilient_run_err` from the brain\n // handler's outcome. The router's defs ride beside it.\n cmds: [llm.run, ...(tools?.defs ?? [])],\n };\n // The machine carries no handlers (#278, #279): `interpret` and the\n // `deadline` runner ride beside it, for the caller to hand `run`.\n // `interpret` is already checked as `Interpret<M, ACmd, Ctx>` where it is\n // built; each cell's form is conditional on whether its Cmd is\n // `Cmd.define`d (ADR 0021), and over the generic `TC` TS defers that and\n // cannot relate the two mapped types, so the checked table is handed over\n // unrelated here.\n return {\n machine: defineMachine(machine),\n interpret: interpret as never,\n subscribe: { deadline: subscribeDeadline },\n };\n }\n\n return {\n init,\n start,\n turn,\n toolOk,\n toolErr,\n succeed,\n fail,\n compactOk,\n compactErr,\n onTimer,\n boot,\n isSettled,\n currentStage,\n brainCall,\n subs,\n // `toMachine` is THE wired path; `brainInterpret` / `brain` are the two\n // pieces a consumer wiring the verbs by hand needs.\n toMachine,\n brainInterpret: brainHandlers,\n brain: llm.run,\n };\n}\n\n/**\n * Re-export the deadline primitives so consumers (and tests) wire one import:\n * `subscribeDeadline` is the `deadline` runner, `deadlinesSub` a machine's\n * `subs` entry, and `deadlineSub` builds the entry both composed wrappers'\n * `subs` list.\n */\nexport { subscribeDeadline, deadlineSub, deadlinesSub };\nexport type { DeadlineSub, DeadlinesSub };\nexport type {\n EndedRun,\n MonitoredRunCmd,\n RunFailure,\n} from \"../internal/flow/monitored-run\";\nexport type {\n LlmCall,\n LlmErr,\n LlmFailMsg,\n LlmOk,\n LlmRunCmd,\n LlmSucceedMsg,\n Schema,\n} from \"../internal/llm-call\";\nexport type {\n Llm,\n MessageLoader,\n ModelFactory,\n ModelPort,\n PlainModel,\n} from \"./model\";\nexport { PLAIN_MODEL_MISROUTE_REASON, plainModel } from \"./model\";\n"]}