@demlik/tea 0.1.0 → 0.1.2
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.
- package/LICENSE +21 -0
- package/dist/agent/index.d.ts +907 -0
- package/dist/agent/index.js +20 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/authed-call/index.d.ts +119 -0
- package/dist/authed-call/index.js +148 -0
- package/dist/authed-call/index.js.map +1 -0
- package/dist/await-terminal/index.d.ts +99 -0
- package/dist/await-terminal/index.js +75 -0
- package/dist/await-terminal/index.js.map +1 -0
- package/dist/batch-window/index.d.ts +259 -0
- package/dist/batch-window/index.js +43 -0
- package/dist/batch-window/index.js.map +1 -0
- package/dist/cache/index.d.ts +2 -2
- package/dist/cache/index.js +2 -50
- package/dist/cache/index.js.map +1 -1
- package/dist/chunk-27N2SPTN.js +222 -0
- package/dist/chunk-27N2SPTN.js.map +1 -0
- package/dist/chunk-2YOE5PIS.js +45 -0
- package/dist/chunk-2YOE5PIS.js.map +1 -0
- package/dist/chunk-3545BOYL.js +65 -0
- package/dist/chunk-3545BOYL.js.map +1 -0
- package/dist/chunk-3XJWC7VW.js +61 -0
- package/dist/chunk-3XJWC7VW.js.map +1 -0
- package/dist/chunk-5DEQ5I3U.js +132 -0
- package/dist/chunk-5DEQ5I3U.js.map +1 -0
- package/dist/chunk-5VNWZADP.js +49 -0
- package/dist/chunk-5VNWZADP.js.map +1 -0
- package/dist/chunk-6RGBKODV.js +268 -0
- package/dist/chunk-6RGBKODV.js.map +1 -0
- package/dist/{chunk-ZRUST6BK.js → chunk-7FYQGDMF.js} +2 -2
- package/dist/chunk-7FYQGDMF.js.map +1 -0
- package/dist/chunk-7W4LMPUW.js +186 -0
- package/dist/chunk-7W4LMPUW.js.map +1 -0
- package/dist/chunk-BYQUGDD3.js +16 -0
- package/dist/chunk-BYQUGDD3.js.map +1 -0
- package/dist/{chunk-PYBQREFU.js → chunk-DILMKOZ7.js} +22 -26
- package/dist/chunk-DILMKOZ7.js.map +1 -0
- package/dist/chunk-EHIX7NYZ.js +93 -0
- package/dist/chunk-EHIX7NYZ.js.map +1 -0
- package/dist/chunk-HCEVHFJ7.js +54 -0
- package/dist/chunk-HCEVHFJ7.js.map +1 -0
- package/dist/chunk-HJO6VNQI.js +15 -0
- package/dist/chunk-HJO6VNQI.js.map +1 -0
- package/dist/chunk-IN33Q4VJ.js +52 -0
- package/dist/chunk-IN33Q4VJ.js.map +1 -0
- package/dist/chunk-J6527VRQ.js +56 -0
- package/dist/chunk-J6527VRQ.js.map +1 -0
- package/dist/chunk-JELSZN25.js +47 -0
- package/dist/chunk-JELSZN25.js.map +1 -0
- package/dist/chunk-K575PT4S.js +58 -0
- package/dist/chunk-K575PT4S.js.map +1 -0
- package/dist/chunk-K7Q23EQ4.js +20 -0
- package/dist/chunk-K7Q23EQ4.js.map +1 -0
- package/dist/chunk-LEC4U6CX.js +91 -0
- package/dist/chunk-LEC4U6CX.js.map +1 -0
- package/dist/{chunk-PYOCUBQJ.js → chunk-LP7VQBRG.js} +22 -15
- package/dist/chunk-LP7VQBRG.js.map +1 -0
- package/dist/{chunk-CMG2KMWX.js → chunk-MMH7CW5K.js} +220 -189
- package/dist/chunk-MMH7CW5K.js.map +1 -0
- package/dist/{chunk-Y5JM3UUH.js → chunk-NSDFA6M6.js} +75 -3
- package/dist/chunk-NSDFA6M6.js.map +1 -0
- package/dist/chunk-ON24RKSE.js +60 -0
- package/dist/chunk-ON24RKSE.js.map +1 -0
- package/dist/chunk-PS23H6KQ.js +87 -0
- package/dist/chunk-PS23H6KQ.js.map +1 -0
- package/dist/chunk-QLA76GIT.js +162 -0
- package/dist/chunk-QLA76GIT.js.map +1 -0
- package/dist/chunk-S3FQN4SL.js +506 -0
- package/dist/chunk-S3FQN4SL.js.map +1 -0
- package/dist/chunk-SC3FAFZN.js +53 -0
- package/dist/chunk-SC3FAFZN.js.map +1 -0
- package/dist/chunk-SINXE47Y.js +55 -0
- package/dist/chunk-SINXE47Y.js.map +1 -0
- package/dist/chunk-SQTCS44W.js +33 -0
- package/dist/chunk-SQTCS44W.js.map +1 -0
- package/dist/chunk-TGG26XMK.js +52 -0
- package/dist/chunk-TGG26XMK.js.map +1 -0
- package/dist/chunk-UV6UWGEO.js +147 -0
- package/dist/chunk-UV6UWGEO.js.map +1 -0
- package/dist/chunk-UYWUVEP6.js +158 -0
- package/dist/chunk-UYWUVEP6.js.map +1 -0
- package/dist/chunk-VLGARN6H.js +202 -0
- package/dist/chunk-VLGARN6H.js.map +1 -0
- package/dist/circuit-breaker/index.js +1 -51
- package/dist/circuit-breaker/index.js.map +1 -1
- package/dist/core-BoB6t7dB.d.ts +188 -0
- package/dist/deadline/index.d.ts +24 -5
- package/dist/deadline/index.js +4 -18
- package/dist/deadline/index.js.map +1 -1
- package/dist/debounce/index.d.ts +6 -0
- package/dist/debounce/index.js +1 -54
- package/dist/debounce/index.js.map +1 -1
- package/dist/devtools/index.d.ts +1 -1
- package/dist/devtools/index.js +18 -6
- package/dist/devtools/index.js.map +1 -1
- package/dist/do/index.d.ts +1723 -92
- package/dist/do/index.js +673 -31
- package/dist/do/index.js.map +1 -1
- package/dist/durable-effects-CO9Uh971.d.ts +180 -0
- package/dist/extension/index.d.ts +31 -13
- package/dist/extension/index.js +5 -3
- package/dist/extension/index.js.map +1 -1
- package/dist/extension/react.js +8 -3
- package/dist/extension/react.js.map +1 -1
- package/dist/extension/subs/index.d.ts +2 -2
- package/dist/extension/subs/index.js.map +1 -1
- package/dist/extension/test-utils.js +11 -3
- package/dist/extension/test-utils.js.map +1 -1
- package/dist/fan-out/index.d.ts +239 -0
- package/dist/fan-out/index.js +5 -0
- package/dist/fan-out/index.js.map +1 -0
- package/dist/idempotency/adapter.d.ts +62 -0
- package/dist/idempotency/adapter.js +4 -0
- package/dist/idempotency/adapter.js.map +1 -0
- package/dist/idempotency/index.js +1 -56
- package/dist/idempotency/index.js.map +1 -1
- package/dist/idempotent-intake/index.d.ts +186 -0
- package/dist/idempotent-intake/index.js +7 -0
- package/dist/idempotent-intake/index.js.map +1 -0
- package/dist/index.d.ts +341 -191
- package/dist/index.js +2 -1
- package/dist/llm-call/index.d.ts +309 -0
- package/dist/llm-call/index.js +14 -0
- package/dist/llm-call/index.js.map +1 -0
- package/dist/machine-viz/index.d.ts +4 -4
- package/dist/machine-viz/index.js +5 -9
- package/dist/machine-viz/index.js.map +1 -1
- package/dist/mem/index.d.ts +1 -0
- package/dist/monitored-run/index.d.ts +253 -0
- package/dist/monitored-run/index.js +10 -0
- package/dist/monitored-run/index.js.map +1 -0
- package/dist/node/index.d.ts +5 -5
- package/dist/node/index.js.map +1 -1
- package/dist/paginated-walk/index.d.ts +234 -0
- package/dist/paginated-walk/index.js +15 -0
- package/dist/paginated-walk/index.js.map +1 -0
- package/dist/paginator/index.d.ts +271 -0
- package/dist/paginator/index.js +3 -0
- package/dist/paginator/index.js.map +1 -0
- package/dist/parity/index.d.ts +92 -0
- package/dist/parity/index.js +78 -0
- package/dist/parity/index.js.map +1 -0
- package/dist/pbt/arbitraries/index.d.ts +1 -1
- package/dist/pbt/arbitraries/index.js +1 -1
- package/dist/pbt/index.d.ts +15 -8
- package/dist/pbt/index.js +6 -11
- package/dist/pbt/index.js.map +1 -1
- package/dist/pbt/runners/index.d.ts +1 -1
- package/dist/pbt/runners/index.js +3 -2
- package/dist/poller/index.d.ts +288 -0
- package/dist/poller/index.js +79 -0
- package/dist/poller/index.js.map +1 -0
- package/dist/prediction/index.d.ts +130 -0
- package/dist/prediction/index.js +4 -0
- package/dist/prediction/index.js.map +1 -0
- package/dist/protocol-B5YmJr0d.d.ts +45 -0
- package/dist/pure/index.d.ts +2 -0
- package/dist/pure/index.js +4 -0
- package/dist/pure/index.js.map +1 -0
- package/dist/raft/demo.d.ts +105 -0
- package/dist/raft/demo.js +172 -0
- package/dist/raft/demo.js.map +1 -0
- package/dist/raft/index.d.ts +548 -0
- package/dist/raft/index.js +7 -0
- package/dist/raft/index.js.map +1 -0
- package/dist/raft/sim.d.ts +222 -0
- package/dist/raft/sim.js +8 -0
- package/dist/raft/sim.js.map +1 -0
- package/dist/raft/timeline.d.ts +46 -0
- package/dist/raft/timeline.js +62 -0
- package/dist/raft/timeline.js.map +1 -0
- package/dist/rate-limit/index.js +1 -43
- package/dist/rate-limit/index.js.map +1 -1
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.js +43 -20
- package/dist/react/index.js.map +1 -1
- package/dist/reconciler/index.d.ts +192 -0
- package/dist/reconciler/index.js +166 -0
- package/dist/reconciler/index.js.map +1 -0
- package/dist/recorder/index.d.ts +7 -3
- package/dist/recorder/index.js +1 -155
- package/dist/recorder/index.js.map +1 -1
- package/dist/resilient-call/index.d.ts +294 -0
- package/dist/resilient-call/index.js +13 -0
- package/dist/resilient-call/index.js.map +1 -0
- package/dist/retry-backoff/index.d.ts +42 -5
- package/dist/retry-backoff/index.js +1 -35
- package/dist/retry-backoff/index.js.map +1 -1
- package/dist/retry-to-success/index.d.ts +109 -0
- package/dist/retry-to-success/index.js +35 -0
- package/dist/retry-to-success/index.js.map +1 -0
- package/dist/saga/index.d.ts +238 -0
- package/dist/saga/index.js +150 -0
- package/dist/saga/index.js.map +1 -0
- package/dist/snapshot/index.d.ts +334 -0
- package/dist/snapshot/index.js +5 -0
- package/dist/snapshot/index.js.map +1 -0
- package/dist/subs/index.d.ts +48 -10
- package/dist/subs/index.js +1 -1
- package/dist/testing/index.d.ts +107 -2
- package/dist/testing/index.js +204 -6
- package/dist/testing/index.js.map +1 -1
- package/dist/throttle/index.d.ts +9 -0
- package/dist/throttle/index.js +1 -52
- package/dist/throttle/index.js.map +1 -1
- package/dist/throttled-input/index.d.ts +380 -0
- package/dist/throttled-input/index.js +88 -0
- package/dist/throttled-input/index.js.map +1 -0
- package/dist/token-refresh/index.d.ts +215 -0
- package/dist/token-refresh/index.js +6 -0
- package/dist/token-refresh/index.js.map +1 -0
- package/dist/trace-replay/index.d.ts +11 -2
- package/dist/trace-replay/index.js +3 -55
- package/dist/trace-replay/index.js.map +1 -1
- package/dist/{types-CwBC5wMn.d.ts → types-B-8bcAp8.d.ts} +1 -1
- package/dist/with-deadline/index.d.ts +196 -0
- package/dist/with-deadline/index.js +111 -0
- package/dist/with-deadline/index.js.map +1 -0
- package/dist/with-resilience/index.d.ts +205 -0
- package/dist/with-resilience/index.js +251 -0
- package/dist/with-resilience/index.js.map +1 -0
- package/dist/with-telemetry/index.d.ts +149 -0
- package/dist/with-telemetry/index.js +70 -0
- package/dist/with-telemetry/index.js.map +1 -0
- package/dist/work-queue/adapter.d.ts +82 -0
- package/dist/work-queue/adapter.js +4 -0
- package/dist/work-queue/adapter.js.map +1 -0
- package/dist/work-queue/index.d.ts +25 -11
- package/dist/work-queue/index.js +1 -46
- package/dist/work-queue/index.js.map +1 -1
- package/dist/work-queue/ops.d.ts +69 -0
- package/dist/work-queue/ops.js +3 -0
- package/dist/work-queue/ops.js.map +1 -0
- package/dist/workflow/index.d.ts +450 -0
- package/dist/workflow/index.js +225 -0
- package/dist/workflow/index.js.map +1 -0
- package/package.json +168 -25
- package/dist/chunk-CMG2KMWX.js.map +0 -1
- package/dist/chunk-PYBQREFU.js.map +0 -1
- package/dist/chunk-PYOCUBQJ.js.map +0 -1
- package/dist/chunk-Y5JM3UUH.js.map +0 -1
- package/dist/chunk-ZRUST6BK.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent/index.ts"],"names":["runSlice","cmds"],"mappings":";;;;;;;;;AA2KO,SAAS,YAAY,KAAA,EAAoC;AAC9D,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,UAAU,OAAO,KAAA;AACxD,EAAA,MAAM,CAAA,GAAI,KAAA;AACV,EAAA,OAAO,OAAO,CAAA,CAAE,OAAA,KAAY,YAAY,KAAA,CAAM,OAAA,CAAQ,EAAE,SAAS,CAAA;AACnE;AAYO,IAAM,eAAA,GAAqC;AAAA,EAChD,KAAA,EAAO,CAAC,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AAA;AAKX,QAAA,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,aAAA,EAAe,MAAM,GAAA,CAAI,MAAA,CAAO,QAAQ,CAAA;AAC5D,QAAA;AAAA,MACF,KAAK,OAAA,CAAQ,WAAA;AAEX,QAAA,MAAA,CAAO,IAAA,CAAK;AAAA,UACV,IAAA,EAAM,aAAA;AAAA,UACN,QAAQ,GAAA,CAAI,MAAA;AAAA,UACZ,QAAQ,GAAA,CAAI;AAAA,SACb,CAAA;AACD,QAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAMF,KAAK,OAAA,CAAQ,UAAA;AAAA,MACb,KAAK,OAAA,CAAQ,YAAA;AAAA,MACb,KAAK,OAAA,CAAQ,YAAA;AAAA,MACb,KAAK,OAAA,CAAQ,SAAA;AAAA,MACb,KAAK,OAAA,CAAQ,UAAA;AAAA,MACb,KAAK,mBAAA;AAAA,MACL,KAAK,OAAA,CAAQ,SAAA;AACX,QAAA;AAAA;AAMJ,IAAA,IAAI,KAAA,CAAM,GAAA,CAAI,KAAA,KAAU,MAAA,EAAQ;AAC9B,MAAA,MAAA,CAAO,KAAK,EAAE,IAAA,EAAM,WAAW,MAAA,EAAQ,KAAA,CAAM,QAAQ,CAAA;AAAA,IACvD;AACA,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AACF;AAkBO,SAAS,cAAA,CAMd,GACA,CAAA,EAC0B;AAC1B,EAAA,OAAO,EAAE,GAAI,CAAA,IAAK,EAAC,EAAI,GAAG,CAAA,EAAE;AAC9B;AAQO,SAAS,SAAA,CAQd,KAAA,EACA,CAAC,KAAA,EAAO,IAAI,CAAA,EACgB;AAC5B,EAAA,OAAO,CAAC,EAAE,GAAG,OAAO,KAAA,EAAO,KAAA,IAAS,IAAI,CAAA;AAC1C","file":"chunk-S3FQN4SL.js","sourcesContent":["/**\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 is the `seed/audit-agent-machine` reducer generalized: the seed's audit /\n * glyph / violation domain specifics are stripped, and what remains — the loop,\n * the durability, the boot-reconcile crash recovery, the serial-vs-fanned tool\n * dispatch — is yours. The consumer supplies the only things that are genuinely\n * domain: the tools, the prompts (via the llm-call message loader), the schemas,\n * and the model. `createAgent(config)` returns the uniform knob 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. (`unsafeDetachedHandlers` is the hand-wiring escape hatch; its name\n * advertises that it does not drive the retry loop — see #54.)\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 (the seed's `call_llm{purpose}`). One\n * `LlmCall` per turn, structured-output parsed, retry composed in. The agent\n * delegates the resilient slice + verbs and reuses the detached handler.\n * - `../fan-out` — the tool calls a turn produced. The seed dispatched tools\n * SERIALLY (concurrency 1); fan-out generalizes that to bounded concurrency\n * `config.toolConcurrency` (default 1 = the seed's serial behavior). 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 (generalized from the seed's `applyAiTurn`)\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 + turn-limit guard bound the loop; the deadline fires\n * `failed`, the turn limit fires `failed { turn_limit }`.\n *\n * ## Boot reconcile (crash recovery — the seed's `outstandingEffect`)\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 * model: (id) => createChatModel(env, id),\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, // serial like the seed (default)\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 machine = agent.toMachine({ toolInterpret });\n * const runtime = run(machine, { ctx, store });\n */\n\nimport { createFanOut, type FanOutState, initFanOut } from \"../fan-out\";\nimport {\n type Cmd,\n defineMachine,\n type Interpret,\n type Machine,\n type Reducer,\n} from \"../index\";\nimport {\n createLlmCall,\n deadlineSub,\n type LlmCall,\n type LlmCallPorts,\n type LlmErr,\n type LlmFailMsg,\n type LlmOk,\n type LlmRunCmd,\n type LlmSucceedMsg,\n type LlmTimerMsg,\n type MessageLoader,\n type ModelFactory,\n type ResilientState,\n type Schema,\n subscribeDeadline,\n} from \"../llm-call\";\nimport {\n createMonitoredRun,\n type DeadlineSub,\n type MonitoredRunCmd,\n type MonitoredRunState,\n type RunFailure,\n} from \"../monitored-run\";\nimport { MsgType } from \"../protocol\";\nimport { createResilientCall } from \"../resilient-call\";\nimport type { RetryPolicy } from \"../retry-backoff\";\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 — the seed's `ToolCall`, stripped\n * of the audit-specific args typing. 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 seed's `AiTurn`, generalized: the narration `content`\n * the model produced and the `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 */\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}\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 two load-bearing fields: `content` is a string,\n * `toolCalls` is an array. PURE — 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 typeof t.content === \"string\" && Array.isArray(t.toolCalls);\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> = {\n parse: (value: unknown): AgentTurn => {\n if (!isAgentTurn(value)) {\n throw new Error(\"structured-output parse failed: not an AgentTurn\");\n }\n return value;\n },\n};\n\n/**\n * One settled tool outcome the consumer routes back into the loop — the seed's\n * `ToolOutcome`. `ok` carries the result the consumer's interpret produced;\n * `error` carries a reason the model sees (so it recovers rather than stalls —\n * \"errors are data\").\n */\nexport type ToolOutcome<R> =\n | { readonly kind: \"ok\"; readonly result: R }\n | { readonly kind: \"error\"; readonly reason: string };\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 (the seed's `Conversation`).\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`, #85). The in-flight\n * fan-out batch exists ONLY in the `tools` variant — \"awaiting llm with tools\n * pending\" is structurally impossible (the seed's 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 — the knob. The domain seams (tools / schemas / model / stages) are\n// required; everything cross-cutting (retry / deadline / concurrency / loader /\n// maxTurns) is optional, per the resilient-call \"omit a brick → omit its gate\".\n// ===========================================================================\n\n/**\n * The agent knob. 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 cell maps to `resilient_run`, the tool cell 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 */\n/**\n * The snapshotting discriminant (#55). 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 cell is\n * REQUIRED (ON) or FORBIDDEN (OFF) instead of defaulting it to a silent 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// Context-compaction seam (#85) — the opt-in transcript snapshot-and-compact\n// policy, shaped exactly like `AgentSnapshotConfig` so a short agent pays\n// nothing and cannot even mention the machinery.\n// ===========================================================================\n\n/**\n * The reserved purpose the compaction round-trip runs under (#85). 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 parse: (value: unknown): CompactionSummary => {\n if (!isCompactionSummary(value)) {\n throw new Error(\n \"structured-output parse failed: not a CompactionSummary\",\n );\n }\n return value;\n },\n};\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 (#85). 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 (#85), shaped exactly like {@link\n * AgentSnapshotConfig}. Compaction is either OFF — `compaction` is structurally\n * absent and the agent never emits a `compact_run` Cmd — or ON, in which case\n * `compaction` is a {@link CompactionPolicy}. A `{ compaction?: never }` member\n * (rather than a bare optional) makes the OFF case load-bearing: it forbids\n * passing `compaction` at all, so `toMachine` config-derives whether the\n * `compact_run` interpret cell is REQUIRED (ON) or FORBIDDEN (OFF) — never a\n * silent no-op cell, the #55 type-lie-killer reused.\n */\nexport type AgentCompactionConfig<R, Msg> =\n | { readonly compaction?: never }\n | { readonly compaction: CompactionPolicy<R, Msg> };\n\n/**\n * The core (non-snapshot, non-compaction) agent knob. 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 */\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 /** DI port — the model factory `(modelId) => Llm`. */\n readonly model: ModelFactory<Msg>;\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 /** Max tools in flight at once. Omit / `1` → serial dispatch (the seed's behavior). */\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 /** Build the per-purpose brain-call payload from the conversation. Omit → `null`. */\n readonly payloadOf?: (\n stage: Stage | undefined,\n conversation: Conversation<R>,\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 (only the deadline watchdog bounds the loop).\n */\n readonly maxTurns?: number;\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 knob — 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 cell.\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 knob 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; deadline / stage failures\n * surface through the monitored-run slice's own `failure`.\n */\nexport type AgentFailure =\n | { readonly reason: \"turn_limit\"; readonly at: number }\n | { readonly reason: \"llm\"; readonly error: unknown; readonly at: number };\n\n/**\n * The agent slice — every composed brick'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 */\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 brick.\n */\n readonly compaction: ResilientState<\n LlmCall<CompactionPurpose>,\n LlmOk<CompactionPurpose, CompactionOutputs>\n >;\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>` knob 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\n// ===========================================================================\n// Lifecycle status — the ONE typed channel callers read instead of re-deriving\n// the private slice shape (issue #49).\n// ===========================================================================\n\n/**\n * The unified terminal failure (issue #49). 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 / `llm` 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?\" (issue #49). 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 * - `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 * - `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 */\nexport type AgentStatus<Stage> =\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\n/**\n * Derive the agent's lifecycle `status` from its durable slice — the pure\n * status function that REPLACES every caller's hand re-derivation of the private\n * shape (issue #49). PURE — reads no clock / RNG, allocates one small record.\n *\n * Ordering is terminal-first so a settled run never reports `running`:\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 === \"failed\"` → `failed`, carrying `run.failure` (deadline /\n * stage). The fallback channel.\n * 3. `run.phase === \"done\"` → `done` with `state.output` (#46).\n * 4. running + conversation + `awaiting.kind === \"tools\"` → `suspended` with\n * the outstanding tool calls (`tools.running`). THE resumability condition.\n * 5. otherwise → `running`.\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 // 2) The monitored-run terminal failure (deadline / stage). `run.failure` is\n // non-null exactly when `phase === \"failed\"` (the run-state invariant), so\n // the `!== null` guard narrows it with no assertion and no fabricated\n // fallback — the unreachable phase-failed-yet-failure-null state falls\n // through rather than inventing a failure to report.\n if (s.run.phase === \"failed\" && s.run.failure !== null) {\n return { kind: \"failed\", failure: s.run.failure };\n }\n // 3) The pipeline finished — the terminal output landed on `state.output`.\n if (s.run.phase === \"done\") {\n return { kind: \"done\", output: s.output };\n }\n // 4) Running + a live conversation awaiting tools → suspended (resumable).\n // The outstanding calls are the in-flight fan-out batch (`tools.running`).\n if (s.conversation !== null && s.conversation.awaiting.kind === \"tools\") {\n return { kind: \"suspended\", pending: s.tools.running };\n }\n // 5) Otherwise the run is live and not awaiting tools.\n return { kind: \"running\" };\n}\n\n// ===========================================================================\n// Cmds + Msgs the knob speaks. Generic over the composed bricks' 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 compaction round-trip's Cmd + settle Msgs (#85, design B1). DEDICATED\n// discriminants (`compact_run` / `compact_ok` / `compact_err`) — re-keyed off\n// the composed resilient call's `resilient_run` / `resilient_ok` / `resilient_err`\n// at the agent boundary (the `with-resilience` re-keying discipline) so the\n// compaction interpret cell is its OWN cell, never the brain `resilient_run` one.\n// ---------------------------------------------------------------------------\n\n/**\n * The \"summarize the oldest N turns\" effect Cmd — the compaction round-trip's\n * carrier (#85). 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 cell, not\n * the brain one. The cell composes the resilient brick (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 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` cell.\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 (#55).\n * - `TC` — the consumer's per-tool effect, mapped to the\n * consumer's own tool interpret cell.\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` (#55).\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` cell\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 cell 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 CONFIG-DERIVED compaction obligation on `toMachine`'s `toolInterpret`\n * (#85), the exact twin of {@link SnapshotInterpret}. Resolves on the `Compact`\n * discriminant the compaction overload of `createAgent` fixes:\n *\n * - compaction ON → a REQUIRED `compact_run` cell\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 cell 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/**\n * The `toMachine` signature, 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` cell via {@link SnapshotInterpret} and the `compact_run` cell\n * via {@link CompactInterpret}, and the machine's Cmd type is the config-derived\n * `AgentCmd<P, TC, Snap, Compact>`.\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>(opts?: {\n readonly toolInterpret?: Interpret<AgentMachineMsg<P, O, R>, TC, Ctx> &\n SnapshotInterpret<AgentMachineMsg<P, O, R>, Snap, Ctx> &\n CompactInterpret<AgentMachineMsg<P, O, R>, Compact, Ctx>;\n}) => Machine<\n AgentState<Stage, P, O, R>,\n AgentMachineMsg<P, O, R>,\n AgentCmd<P, TC, Snap, Compact>,\n DeadlineSub,\n Ctx\n>;\n\n/**\n * The agent knob `createAgent` returns — the uniform verb contract every tea\n * composition exposes, plus the wired `toMachine` and the `unsafeDetachedHandlers`\n * escape hatch. `Snap` flows ONLY into `toMachine`'s `toolInterpret` obligation\n * (the snapshot derivation, #55); every verb is snapshot-agnostic. The model\n * message shape `Msg` does not appear on the knob 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 readonly toolErr: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [callId: string, reason: string, at: number]\n >;\n readonly succeed: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [key: string, msg: AgentLlmOkMsg<P, O>, at: number]\n >;\n readonly fail: AgentVerb1<\n Stage,\n P,\n O,\n R,\n TC,\n [key: string, 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 readonly unsafeDetachedHandlers: <M>(\n ports: AgentPorts<P, O, M>,\n ) => AgentDetachedHandlers<P, M>;\n}\n\n/** A verb taking the state + `Args`, returning the knob'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 / failure settle Msgs, inherited from `../llm-call`. */\nexport type AgentLlmOkMsg<\n P extends string,\n O extends Record<P, unknown>,\n> = LlmSucceedMsg<P, O>;\nexport type AgentLlmErrMsg<P extends string> = LlmFailMsg<P>;\n\n/**\n * The timer Msg (retry + safety deadline) — `DeadlineExceeded`, the shared\n * shape of both bricks' timer Msgs (`LlmTimerMsg` and `MonitoredRunTimerMsg`\n * are both `DeadlineExceeded`). One Msg variant covers both timers; `onTimer`\n * disambiguates by Sub id. This is also the machine Msg the `subscribeDeadline`\n * cell dispatches directly (no wrapping), matching the sibling gold standard.\n */\nexport type AgentTimerMsg = LlmTimerMsg;\n\n/** Ports the consumer supplies to the llm-call handler — re-exported shape. */\nexport type AgentPorts<\n P extends string,\n O extends Record<P, unknown>,\n M,\n> = LlmCallPorts<P, O, M>;\n\n/**\n * The LEGACY detached brain-call handler dictionary `handlers(ports)` returns —\n * the inherited `../llm-call` detached form's exact shape, NOT an `Interpret`.\n * The `resilient_run` cell runs the invoke inside `ctx.waitUntil` and dispatches\n * the consumer's `onOk` / `onErr` Msg directly (returning `void`), so it is a\n * fire-and-forget handler with a structural `{ waitUntil, dispatch }` ctx — it\n * does not re-enter the resilient settle Msg and so does not drive the retry\n * loop. Naming the type precisely (rather than laundering it through\n * `as unknown as Interpret<...>`) keeps `agent.unsafeDetachedHandlers(ports)` honest: the\n * consumer that wires the verbs by hand gets the real detached shape, and its\n * `resilient_run` is callable with a plain Cmd + a `{ waitUntil, dispatch }` ctx\n * with no `as never` at the call site.\n */\nexport type AgentDetachedHandlers<P extends string, M> = {\n readonly resilient_run: (\n cmd: AgentLlmRunCmd<P>,\n ctx: {\n waitUntil(p: Promise<unknown>): void;\n dispatch(msg: M): unknown;\n },\n ) => void;\n};\n\n// ===========================================================================\n// Sub-id helpers — the agent owns no NEW sub ids; it merges the two bricks'.\n// ===========================================================================\n\n// ===========================================================================\n// The knob factory.\n// ===========================================================================\n\n/**\n * Build an agent knob from `config`. The determinism seam — `config.rng`,\n * injected for the inherited brain-call retry jitter — lives as a named field\n * on the config (pass a fixed `() => 0` to pin backoff in tests; omit → defaults\n * to `Math.random`, read only at the resilient-call verb boundary).\n *\n * Returns the uniform knob contract (`init` / verbs / `subs`) plus `toMachine()`\n * — a `defineMachine` wiring all of it into one runnable machine — and the\n * `unsafeDetachedHandlers` hand-wiring escape hatch.\n *\n * `createAgent` is OVERLOADED on TWO independent discriminants — the snapshotting\n * (#55) and the compaction (#85) one — so each `toMachine` obligation is 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 * The four overloads 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, Msg>(\n {\n model: config.model,\n schemas: config.schemas,\n ...(config.retry !== undefined ? { retry: config.retry } : {}),\n ...(config.loadMessages !== undefined\n ? { loadMessages: config.loadMessages }\n : {}),\n },\n rng,\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 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 failure: null,\n output: null,\n };\n }\n\n /** A fresh conversation entering the agentic loop — awaiting the first brain call. */\n function freshConversation(): 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 */\n function dedupeByCallId(calls: readonly ToolCall[]): 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 */\n function foldSummary(\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). */\n function currentStage(s: State): Stage | undefined {\n return s.run.stepStates.find((i) => i.status === \"running\")?.input;\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();\n return {\n purpose: config.turnOf(stage),\n model: config.modelId ?? null,\n payload: config.payloadOf ? config.payloadOf(stage, conversation) : null,\n };\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();\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 };\n const call = brainCall(withRun);\n const [resilience, cmds] = llm.attempt(withRun.resilience, call, at);\n return [{ ...withRun, resilience }, cmds];\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 if (isSettled(s)) return [s, []];\n const conv = s.conversation;\n if (conv === null || conv.awaiting.kind !== \"llm\") 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, launchCmds] = fan.scatter(\n initFanOut<ToolCall, ToolOutcome<R>>(),\n batch,\n );\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 return [{ ...s, run: runSlice, tools, conversation: nextConv }, launchCmds];\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();\n const moved: State = {\n ...s,\n run: runSlice,\n conversation,\n tools: initFanOut<ToolCall, ToolOutcome<R>>(),\n };\n const call = brainCall(moved);\n const [resilience, llmCmds] = llm.attempt(moved.resilience, call, at);\n return [{ ...moved, resilience }, [...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 return settleTool(s, 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 reason: string,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n return settleTool(s, callId, { kind: \"error\", reason }, at);\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 s: State,\n callId: string,\n outcome: ToolOutcome<R>,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n if (isSettled(s)) return [s, []];\n const conv = s.conversation;\n if (conv === null || conv.awaiting.kind !== \"tools\") return [s, []];\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 = s.tools.running.find((c) => c.callId === callId);\n if (call === undefined) return [s, []];\n\n const [tools, launchCmds] =\n outcome.kind === \"ok\"\n ? fan.itemOk(s.tools, callId, outcome)\n : fan.itemErr(s.tools, callId, outcome);\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 // Livelock guard: the bumped turn count crossing maxTurns → terminal fail.\n if (\n config.maxTurns !== undefined &&\n turnedConv.turnCount >= config.maxTurns\n ) {\n return failTurnLimit({ ...s, tools, conversation: turnedConv }, at);\n }\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 ...s,\n tools: initFanOut<ToolCall, ToolOutcome<R>>(),\n conversation: turnedConv,\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: State = { ...drained, run: runSlice };\n const nextCall = brainCall(fired);\n const [resilience, llmCmds] = llm.attempt(fired.resilience, nextCall, at);\n return [{ ...fired, resilience }, [...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: LlmCall<CompactionPurpose> = {\n purpose: COMPACTION_PURPOSE,\n model: config.modelId ?? null,\n payload: policy.payloadOf ? policy.payloadOf(conv, folding) : null,\n };\n const [compaction, runCmds] = compactRc.attempt(\n s.compaction,\n COMPACTION_PURPOSE,\n input,\n at,\n );\n // Re-key the composed `resilient_run` Cmd(s) to the dedicated `compact_run`\n // discriminant so they route to the compaction interpret cell, never the\n // brain `resilient_run` one (the `with-resilience` boundary-re-key pattern).\n const cmds = runCmds.map(toCompactRunCmd);\n return [\n { ...s, run: runSlice, conversation: compactConv, compaction },\n cmds,\n ];\n }\n\n /** Re-key a composed compaction `resilient_run` Cmd to the dedicated `compact_run`. */\n 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 /** Terminal: the livelock guard tripped. Settle the run failed. PURE. */\n function failTurnLimit(\n s: State,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n return [{ ...s, failure: { reason: \"turn_limit\", at } }, []];\n }\n\n // === Verb: succeed / fail (brain-call resilient settles) =================\n\n /**\n * Fold a brain-call SUCCESS — the FIXED single entry the re-entered\n * `resilient_ok` settle 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 * re-entered `resilient_ok`, 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.result.output`) through\n * `turn`, which scatters this turn's tools (or advances the pipeline on an\n * empty turn). One re-entered 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 key: string,\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, key, msg);\n const settled: State = { ...s, resilience };\n // 2) Fold the parsed turn into the loop (scatter tools / advance the stage).\n // `msg.result.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.result.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. PURE.\n */\n function fail(\n s: State,\n key: string,\n msg: AgentLlmErrMsg<P>,\n at: number,\n ): readonly [State, readonly AgentCmd<P, TC>[]] {\n const [resilience, cmds] = llm.fail(s.resilience, key, 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[key];\n const failure: AgentFailure | null =\n call?.phase === \"failed\"\n ? { reason: \"llm\", error: msg.error, 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.succeed` 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 llm-call's `succeed` on the dedicated slice;\n // the enriched `LlmSucceedMsg` is the `compact_ok` payload as-is.\n const [compaction, retryCmds] = compactRc.succeed(s.compaction, key, {\n type: MsgType.ResilientOk,\n key: msg.key,\n result: msg.result,\n at: msg.at,\n });\n const settledRetry: State = { ...s, compaction };\n\n if (isSettled(settledRetry)) return [settledRetry, []];\n const conv = settledRetry.conversation;\n if (conv === null || conv.awaiting.kind !== \"compacting\") {\n // Stale settle (the run advanced/rebooted past this compaction). The retry\n // slice still resets above; emit only its cmds (normally none).\n return [settledRetry, retryCmds.map(toCompactRunCmd)];\n }\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 const fired: State = { ...settledRetry, conversation: foldedConv };\n // Resume the loop: fire the next brain call on the shrunk transcript.\n const nextCall = brainCall(fired);\n const [resilience, llmCmds] = llm.attempt(fired.resilience, nextCall, at);\n return [\n { ...fired, resilience },\n [...retryCmds.map(toCompactRunCmd), ...llmCmds],\n ];\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 [compaction, cmds] = compactRc.fail(s.compaction, key, {\n type: MsgType.ResilientErr,\n key: msg.key,\n error: msg.error,\n at: msg.at,\n });\n const settledRetry: State = { ...s, compaction };\n const call = compaction.calls[key];\n\n // A retry is armed (`waiting_retry`) → not terminal → keep awaiting the\n // re-issued compaction call (the re-keyed run Cmd, if any, rides here).\n if (call?.phase === \"waiting_retry\") {\n return [settledRetry, cmds.map(toCompactRunCmd)];\n }\n\n if (isSettled(settledRetry)) return [settledRetry, []];\n const conv = settledRetry.conversation;\n if (conv === null || conv.awaiting.kind !== \"compacting\") {\n return [settledRetry, cmds.map(toCompactRunCmd)];\n }\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: State = { ...settledRetry, conversation: resumedConv };\n const nextCall = brainCall(fired);\n const [resilience, llmCmds] = llm.attempt(fired.resilience, nextCall, at);\n return [\n { ...fired, resilience },\n [...cmds.map(toCompactRunCmd), ...llmCmds],\n ];\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] = compactRc.onTimer(s.compaction, msg);\n return [{ ...s, compaction }, cmds.map(toCompactRunCmd)];\n }\n const [resilience, cmds] = llm.onTimer(s.resilience, msg);\n return [{ ...s, resilience }, 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 const call = brainCall(rebooted);\n const [resilience, cmds] = llm.attempt(rebooted.resilience, call, at);\n return [{ ...rebooted, resilience }, cmds];\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: LlmCall<CompactionPurpose> = {\n purpose: COMPACTION_PURPOSE,\n model: config.modelId ?? null,\n payload: config.compaction?.payloadOf\n ? config.compaction.payloadOf(conv, conv.awaiting.folding)\n : null,\n };\n const [compaction, cmds] = compactRc.attempt(\n rebooted.compaction,\n COMPACTION_PURPOSE,\n input,\n at,\n );\n return [{ ...rebooted, compaction }, cmds.map(toCompactRunCmd)];\n }\n\n // awaiting tools → re-fire every running tool's effect Cmd.\n const cmds = rebooted.tools.running.map((call) => config.toolOf(call));\n return [rebooted, cmds];\n }\n\n // === Derived ============================================================\n\n /** True iff the run is in a terminal state (monitored-run done/failed, or agent failure). */\n function isSettled(s: State): boolean {\n return (\n s.run.phase === \"done\" || s.run.phase === \"failed\" || s.failure !== null\n );\n }\n\n // === Subs ================================================================\n\n /**\n * The merged subscription set — the brain-call retry timers (`../llm-call`),\n * the COMPACTION retry timers (the dedicated `$compact` slice, #85), and the\n * no-progress safety deadline (`../monitored-run`). All are `DeadlineSub`s\n * reconciled by id (the compaction timers are keyed `resilient:*:$compact`,\n * distinct from every brain timer), wired with one `subscribe: { deadline:\n * subscribeDeadline }` cell. PURE.\n */\n function subs(s: State): readonly DeadlineSub[] {\n return [\n ...llm.subs(s.resilience),\n ...compactRc.subs(s.compaction),\n ...run.subs(s.run),\n ];\n }\n\n // === Handlers ============================================================\n\n /**\n * The brain-call interpret handler — DETACHED, inherited from `../llm-call`.\n * It assembles messages, binds the purpose schema, invokes (retry composed),\n * parses, and dispatches the consumer's `onOk` / `onErr` Msg (carrying the\n * parsed `AgentTurn` for `onOk`).\n *\n * UNSAFE — kept ONLY as a deliberate escape hatch for the consumer that wires\n * the verbs by hand and wants the fire-and-forget dispatch shape. It does NOT\n * drive the inherited retry loop (it never re-enters the `resilient_ok` settle\n * Msg, so `succeed` / `fail` never run — the breaker never closes, the retry\n * counter never resets). The `unsafe` prefix is the warning the name carries:\n * `toMachine` is THE wired path (it uses the FIXED `brainHandlers` below, which\n * returns the settle Msg for re-entry and drives the loop correctly), and this\n * detached form is named `unsafeDetachedHandlers` so the broken-by-design\n * behaviour is visible at the call site, not buried in a doc-comment a consumer\n * meets only after autocomplete already offered it. A consumer reaches for it\n * only when it has accepted owning the retry wiring itself. See llm-call's\n * `handlers` doc (the same retry-loop gap).\n *\n * Returns the inherited detached shape verbatim (`AgentDetachedHandlers`) — a\n * fire-and-forget `resilient_run` cell, NOT an `Interpret` (it returns `void`\n * and takes the structural `{ waitUntil, dispatch }` ctx the detached form\n * runs the invoke against). The type is named precisely so no cast launders a\n * `void`-returning cell into the re-entry `Interpret` contract.\n *\n * The per-tool effects are NOT handled here — `config.toolOf` produces a Cmd\n * the consumer's OWN interpret performs (the agent never owns the tool I/O;\n * the seed's `send_tool_call` handler is the consumer's), routing Ok/Err back\n * to `toolOk` / `toolErr`. This matches fan-out's \"the consumer owns `of`'s\n * interpret\" discipline.\n */\n function unsafeDetachedHandlers<M>(\n ports: AgentPorts<P, O, M>,\n ): AgentDetachedHandlers<P, M> {\n return llm.handlers(ports);\n }\n\n /**\n * The FIXED brain-call interpret handler — the no-arg `../llm-call` form that\n * RETURNS the enriched resilient settle Msg (`resilient_ok` carrying the\n * parsed `LlmOk`, or `resilient_err` carrying the typed `LlmErr`). The\n * substrate enqueues an interpret handler's returned Msg as a FOLLOW-UP\n * (re-entry) onto the dispatch tail, so the machine's `resilient_ok` /\n * `resilient_err` reducer arms run `succeed` / `fail`, advancing the inherited\n * retry loop (succeed/fail → backoff → onTimer → re-issue) AND folding the\n * parsed turn into the conversation. This is the wiring that lets the loop\n * reach a clean terminal `done` with a reset retry slice — the headline L3 fix.\n */\n function brainHandlers<Ctx>(): Interpret<\n LlmSucceedMsg<P, O> | LlmFailMsg<P>,\n AgentLlmRunCmd<P>,\n Ctx\n > {\n // `llm.handlers()` is `{ resilient_run: (cmd: LlmRunCmd<P>) => Promise<\n // LlmSucceedMsg<P,O> | LlmFailMsg<P>> }`. That is structurally an\n // `Interpret` over the single `resilient_run` Cmd: the cell may ignore the\n // `ctx` param (a handler taking fewer args is assignable), and its returned\n // settle Msg is the exact `M` subset. No cast — the precise type holds.\n return llm.handlers();\n }\n\n /**\n * Wire the agent into a single runnable `defineMachine`. The host Msg union is\n * the closed set of verb entry points; `update` routes each to the matching\n * verb, `subscriptions` merges the two bricks' subs, `subscribe` wires the one\n * deadline cell, and `interpret` is the FIXED brain-call handler.\n *\n * The brain call uses the FIXED no-arg `../llm-call` handler (`brainHandlers`):\n * its returned `resilient_ok` / `resilient_err` settle Msg RE-ENTERS the\n * reducer, where the `resilient_ok` arm runs `succeed` (reset retry + close\n * breaker + fold the parsed turn) and the `resilient_err` arm runs `fail`\n * (back off via retry, re-arm the timer). This is what drives the loop to a\n * clean terminal `done` with a reset retry slice — fixing the L3 break where\n * the old detached handler dispatched the turn directly, never re-entered the\n * settle Msg, and so `succeed` never ran (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>(opts?: {\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<AgentMachineMsg<P, O, R>, TC, Ctx> &\n SnapshotInterpret<AgentMachineMsg<P, O, R>, boolean, Ctx> &\n CompactInterpret<AgentMachineMsg<P, O, R>, boolean, Ctx>;\n }): Machine<\n State,\n AgentMachineMsg<P, O, R>,\n AgentCmd<P, TC, boolean, boolean>,\n DeadlineSub,\n Ctx\n > {\n type M = AgentMachineMsg<P, O, R>;\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 the settle Msg for re-entry; the substrate\n // enqueues it as a follow-up dispatched back into `update` (the `resilient_*`\n // 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 const consumerInterpret = (opts?.toolInterpret ?? {}) as Interpret<\n M,\n NonBrainCmd,\n Ctx\n >;\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 const update: Reducer<State, M, AgentCmd<P, TC>> = {\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 [MsgType.AgentToolErr]: (s, m) => toolErr(s, m.callId, m.reason, m.at),\n // The re-entered brain-call settle Msgs (from `brainHandlers`): success\n // runs `succeed` (reset retry + fold the turn), failure runs `fail`.\n [MsgType.ResilientOk]: (s, m) => succeed(s, m.key, m, m.at),\n [MsgType.ResilientErr]: (s, m) => fail(s, m.key, 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 };\n\n // Build the machine as a fully-typed `Machine<...>` const, then pass it\n // through `defineMachine`'s identity. Annotating the const resolves the\n // `Machine` type's conditional `interpret` requirement against the concrete\n // type params here; calling `defineMachine` with explicit type args instead\n // would defer that conditional over the generic `TC` and 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, DeadlineSub, Ctx> = {\n init: (loaded) => (loaded !== null ? [loaded, []] : [init(), []]),\n update: update as Reducer<State, M, ACmd>,\n subscriptions: (s) => subs(s),\n subscribe: { deadline: subscribeDeadline },\n interpret,\n };\n return defineMachine(machine);\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. `unsafeDetachedHandlers` is the\n // hand-wiring escape hatch — named to advertise the retry-loop gap so it is\n // never mistaken for the loop driver (#54).\n toMachine,\n unsafeDetachedHandlers,\n };\n}\n\n// ===========================================================================\n// AgentBootPort — the typed do↔agent boot seam (issue #60).\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 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_ok` / `resilient_err`) RE-ENTER from the FIXED `brainHandlers`\n * (the substrate enqueues an interpret handler's returned Msg as a follow-up),\n * driving `succeed` / `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 re-entered `resilient_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 re-entering `resilient_ok`,\n * so `succeed` never runs and the resilient slice stays `running` (#54). The\n * `turn` verb remains on the knob 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 RE-ENTER straight from `brainHandlers` (no\n // wrapping) — `resilient_ok` runs `succeed` (reset retry + fold the turn),\n // `resilient_err` runs `fail` (back off via retry). This is the inherited\n // llm-call settle shape, dispatched verbatim by the substrate's re-entry.\n | AgentLlmOkMsg<P, O>\n | AgentLlmErrMsg<P>\n // The compaction settle Msgs RE-ENTER from the compaction interpret cell\n // (#85) — `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 cell boundary.\n | AgentCompactOkMsg\n | AgentCompactErrMsg\n // The timer Msg is `DeadlineExceeded` itself (not wrapped) so the\n // `subscribeDeadline` cell dispatches it straight into `update`, exactly as\n // the resilient-call / llm-call / monitored-run gold standards wire it.\n | AgentTimerMsg\n | AgentBootMsg;\n\n// ===========================================================================\n// AgentEvent — the SEMANTIC lifecycle event stream (issue #47).\n// ===========================================================================\n\n/**\n * The agent's PUBLIC lifecycle events — the semantic stream a consumer\n * subscribes to via `runtime.on(type, …)` (#47). 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_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 (#47) — 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_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_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 * 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 */\nexport function agentEvents<\n Stage,\n P extends string,\n O extends Record<P, AgentTurn>,\n R,\n>(): (\n msg: AgentMachineMsg<P, O, R>,\n state: AgentState<Stage, P, O, R>,\n) => readonly AgentEvent<R>[] {\n return (msg, state) => {\n const events: AgentEvent<R>[] = [];\n switch (msg.type) {\n case MsgType.ResilientOk:\n // The PRIVATE brain-call settle Msg → the public TurnSettled. Its\n // `result.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.result.output });\n break;\n case MsgType.AgentToolOk:\n // The PRIVATE tool-fan-out settle Msg → the public ToolSettled.\n events.push({\n type: \"ToolSettled\",\n callId: msg.callId,\n result: msg.result,\n });\n break;\n // start / boot / timer / the *_err arms / the compaction settles carry no\n // public event — return []. (No `default`: the switch is exhaustive over\n // the Msg discriminant, so a new Msg variant forces a decision here at\n // compile time.) Compaction is an internal optimization, not a semantic\n // lifecycle moment a UI folds — its settles are deliberately silent here.\n case MsgType.AgentStart:\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 // 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/**\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 a knob 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/**\n * Re-export the deadline Sub primitives so consumers (and tests) wire one\n * import: `subscribeDeadline` is the `subscribe` cell, `deadlineSub` builds the\n * Sub literal both composed bricks' `subs` emit.\n */\nexport { subscribeDeadline, deadlineSub };\nexport type {\n DeadlineSub,\n LlmCall,\n LlmErr,\n LlmOk,\n LlmRunCmd,\n LlmSucceedMsg,\n LlmFailMsg,\n Schema,\n ModelFactory,\n MessageLoader,\n // The monitored-run checkpoint Cmd is part of the public `AgentCmd` surface —\n // a consumer wiring `toMachine`'s `toolInterpret` for a snapshotting agent\n // needs it to type the `snapshot_write` cell.\n MonitoredRunCmd,\n // `RunFailure` is half of the unified `AgentTerminalFailure` (#49) — a\n // consumer narrowing `status(s).failure` needs to name the monitored-run\n // failure channel.\n RunFailure,\n};\n"]}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// src/circuit-breaker/index.ts
|
|
2
|
+
var defaultCircuitPolicy = {
|
|
3
|
+
failureThreshold: 5,
|
|
4
|
+
cooldownMs: 3e4,
|
|
5
|
+
halfOpenMaxProbes: 1
|
|
6
|
+
};
|
|
7
|
+
function initCircuit() {
|
|
8
|
+
return { phase: "closed", failures: 0 };
|
|
9
|
+
}
|
|
10
|
+
function onSuccess(state, _policy) {
|
|
11
|
+
switch (state.phase) {
|
|
12
|
+
case "closed":
|
|
13
|
+
return state.failures === 0 ? state : { phase: "closed", failures: 0 };
|
|
14
|
+
case "half_open":
|
|
15
|
+
return { phase: "closed", failures: 0 };
|
|
16
|
+
case "open":
|
|
17
|
+
return state;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function onFailure(state, policy, nowMs) {
|
|
21
|
+
switch (state.phase) {
|
|
22
|
+
case "closed": {
|
|
23
|
+
const failures = state.failures + 1;
|
|
24
|
+
return failures >= policy.failureThreshold ? { phase: "open", openedAtMs: nowMs } : { phase: "closed", failures };
|
|
25
|
+
}
|
|
26
|
+
case "half_open":
|
|
27
|
+
return { phase: "open", openedAtMs: nowMs };
|
|
28
|
+
case "open":
|
|
29
|
+
return state;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function canPass(state, policy, nowMs) {
|
|
33
|
+
switch (state.phase) {
|
|
34
|
+
case "closed":
|
|
35
|
+
return [state, true];
|
|
36
|
+
case "open": {
|
|
37
|
+
const elapsed = nowMs - state.openedAtMs;
|
|
38
|
+
if (elapsed >= policy.cooldownMs) {
|
|
39
|
+
return [{ phase: "half_open", probes: 1 }, true];
|
|
40
|
+
}
|
|
41
|
+
return [state, false];
|
|
42
|
+
}
|
|
43
|
+
case "half_open":
|
|
44
|
+
if (state.probes < policy.halfOpenMaxProbes) {
|
|
45
|
+
return [{ phase: "half_open", probes: state.probes + 1 }, true];
|
|
46
|
+
}
|
|
47
|
+
return [state, false];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export { canPass, defaultCircuitPolicy, initCircuit, onFailure, onSuccess };
|
|
52
|
+
//# sourceMappingURL=chunk-SC3FAFZN.js.map
|
|
53
|
+
//# sourceMappingURL=chunk-SC3FAFZN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/circuit-breaker/index.ts"],"names":[],"mappings":";AAwHO,IAAM,oBAAA,GAAsC;AAAA,EACjD,gBAAA,EAAkB,CAAA;AAAA,EAClB,UAAA,EAAY,GAAA;AAAA,EACZ,iBAAA,EAAmB;AACrB;AAoBO,SAAS,WAAA,GAA4B;AAC1C,EAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,QAAA,EAAU,CAAA,EAAE;AACxC;AAYO,SAAS,SAAA,CACd,OACA,OAAA,EACc;AACd,EAAA,QAAQ,MAAM,KAAA;AAAO,IACnB,KAAK,QAAA;AAGH,MAAA,OAAO,KAAA,CAAM,aAAa,CAAA,GAAI,KAAA,GAAQ,EAAE,KAAA,EAAO,QAAA,EAAU,UAAU,CAAA,EAAE;AAAA,IACvE,KAAK,WAAA;AACH,MAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,QAAA,EAAU,CAAA,EAAE;AAAA,IACxC,KAAK,MAAA;AACH,MAAA,OAAO,KAAA;AAAA;AAEb;AAgBO,SAAS,SAAA,CACd,KAAA,EACA,MAAA,EACA,KAAA,EACc;AACd,EAAA,QAAQ,MAAM,KAAA;AAAO,IACnB,KAAK,QAAA,EAAU;AACb,MAAA,MAAM,QAAA,GAAW,MAAM,QAAA,GAAW,CAAA;AAGlC,MAAA,OAAO,QAAA,IAAY,MAAA,CAAO,gBAAA,GACtB,EAAE,KAAA,EAAO,MAAA,EAAQ,UAAA,EAAY,KAAA,EAAM,GACnC,EAAE,KAAA,EAAO,QAAA,EAAU,QAAA,EAAS;AAAA,IAClC;AAAA,IACA,KAAK,WAAA;AAEH,MAAA,OAAO,EAAE,KAAA,EAAO,MAAA,EAAQ,UAAA,EAAY,KAAA,EAAM;AAAA,IAC5C,KAAK,MAAA;AACH,MAAA,OAAO,KAAA;AAAA;AAEb;AA0BO,SAAS,OAAA,CACd,KAAA,EACA,MAAA,EACA,KAAA,EACkC;AAClC,EAAA,QAAQ,MAAM,KAAA;AAAO,IACnB,KAAK,QAAA;AACH,MAAA,OAAO,CAAC,OAAO,IAAI,CAAA;AAAA,IACrB,KAAK,MAAA,EAAQ;AACX,MAAA,MAAM,OAAA,GAAU,QAAQ,KAAA,CAAM,UAAA;AAG9B,MAAA,IAAI,OAAA,IAAW,OAAO,UAAA,EAAY;AAChC,QAAA,OAAO,CAAC,EAAE,KAAA,EAAO,aAAa,MAAA,EAAQ,CAAA,IAAK,IAAI,CAAA;AAAA,MACjD;AACA,MAAA,OAAO,CAAC,OAAO,KAAK,CAAA;AAAA,IACtB;AAAA,IACA,KAAK,WAAA;AACH,MAAA,IAAI,KAAA,CAAM,MAAA,GAAS,MAAA,CAAO,iBAAA,EAAmB;AAC3C,QAAA,OAAO,CAAC,EAAE,KAAA,EAAO,WAAA,EAAa,QAAQ,KAAA,CAAM,MAAA,GAAS,CAAA,EAAE,EAAG,IAAI,CAAA;AAAA,MAChE;AACA,MAAA,OAAO,CAAC,OAAO,KAAK,CAAA;AAAA;AAE1B","file":"chunk-SC3FAFZN.js","sourcesContent":["/**\n * @demlik/tea/circuit-breaker — per-target failure tracking as pure state + ops.\n *\n * Same shape as `@demlik/tea/work-queue`'s `ops.ts`, `@demlik/tea/rate-limit`,\n * and `@demlik/tea/idempotency`: a state type plus pure transition functions.\n * Host-agnostic by construction — no `Date.now()`, no timers, no I/O. The\n * caller injects the clock (`nowMs`) and wires the result into its own reducer\n * / interpret. This keeps the breaker inside TEA's invariant 2 (transitions are\n * pure: same inputs → same outputs, no `Date.now`) so a consumer can fold it\n * through `update` and exercise it with `replay` / the pbt fold without a fake\n * clock.\n *\n * Every op returns a NEW state value and never mutates its input (invariant 1 —\n * state is a value, not a place). `canPass` returns a `[next, allowed]` tuple so\n * the caller branches on the decision while threading the advanced state forward\n * — same convention as `rate-limit`'s `tryConsume` / `record`. `onSuccess` /\n * `onFailure` are the outcome-recording transitions the caller folds in once the\n * guarded call resolves.\n *\n * ## The phase machine\n *\n * A circuit breaker guards a fallible downstream target (an HTTP backend, a DB,\n * a flaky tool call). Instead of hammering a target that is already failing, it\n * trips OPEN after enough failures and fast-fails subsequent calls for a\n * cooldown, then probes with a few trial calls before fully closing again.\n * Three phases, each carrying ONLY its own data so impossible states are\n * unrepresentable (pattern 11):\n *\n * - **closed** — the healthy steady state. Calls pass through. Carries\n * `failures`: the count of *consecutive* failures since the last success.\n * A success resets it to 0; the `failureThreshold`-th failure trips the\n * breaker OPEN. Only `closed` has a failure counter — `open` and\n * `half_open` don't, because in those phases the count is irrelevant\n * (the breaker has already tripped / is already probing).\n *\n * - **open** — the tripped state. All calls fast-fail (no downstream load).\n * Carries `openedAtMs`: the clock reading at which the breaker tripped.\n * `canPass` compares `nowMs - openedAtMs` against `cooldownMs` to decide\n * when to start probing. Only `open` carries a timestamp — neither other\n * phase is timing anything.\n *\n * - **half_open** — the probing state. A limited number of trial calls are\n * allowed through to test whether the target has recovered. Carries\n * `probes`: the count of probes admitted so far this probing round.\n * `canPass` admits while `probes < halfOpenMaxProbes`, then fast-fails the\n * rest (so a slow target can't be flooded by every queued caller at once).\n * A probe success closes the breaker; a probe failure re-opens it (and\n * resets the cooldown clock). Only `half_open` counts in-flight probes.\n *\n * ### Transition table\n *\n * Rows are the current phase; columns are the event. `→` denotes the next\n * phase; `self` means unchanged. `nowMs` is the injected clock.\n *\n * | from \\ event | onSuccess | onFailure | canPass (→ allowed?) |\n * | ------------ | -------------- | -------------------------------------- | ------------------------------------------------------------------------------------ |\n * | closed | closed(0) | failures+1; trip → open(nowMs) at thr. | self → true (always) |\n * | open | self *(¹)* | self | elapsed ≥ cooldown → half_open(1), true; else self → false |\n * | half_open | → closed(0) | → open(nowMs) (probe failed) | probes < max → half_open(probes+1), true; else self → false |\n *\n * *(¹)* `onSuccess` on `open` \"shouldn't happen\": no call was admitted while\n * open, so no success can be reported for one. We leave the state unchanged\n * rather than throw — the breaker is a coordination aid, not a correctness\n * gate, and a spurious success report (e.g. a late-arriving result from before\n * the trip) must not silently un-trip the breaker. `onFailure` on `open` is\n * likewise a no-op: the breaker is already tripped; the `open` clock is anchored\n * at the trip, not bumped by late failures.\n *\n * ### The probe-admission asymmetry\n *\n * Entering `half_open` happens inside `canPass`, not `onSuccess` / `onFailure`,\n * because the cooldown is a *time* condition and only `canPass` reads the clock\n * against `openedAtMs`. The first `canPass` after the cooldown elapses both\n * transitions the phase AND admits the probe (`[half_open(1), true]`) — one\n * caller drives the recovery attempt. Subsequent `canPass` calls in the same\n * round admit up to `halfOpenMaxProbes` total, then fast-fail until a probe\n * resolves and `onSuccess` / `onFailure` moves the phase out of `half_open`.\n *\n * This module is a textbook three-state machine — a clean `/machine-viz` demo.\n *\n * NOT exported from the package root — reached via the\n * `@demlik/tea/circuit-breaker` subpath, same one-shape-per-package rule as\n * `work-queue`, `rate-limit`, and `idempotency`.\n */\n\n/**\n * Circuit-breaker policy — pure configuration, no mutable state. One policy is\n * shared across all the calls guarded by one logical breaker (often a\n * module-scope const). `CircuitState` carries the mutable counts; this carries\n * the thresholds those counts are compared against.\n */\nexport interface CircuitPolicy {\n /**\n * Consecutive failures in `closed` that trip the breaker `open`. The\n * `failureThreshold`-th failure is the one that trips — with a threshold of\n * 5, the breaker survives 4 failures and opens on the 5th.\n */\n readonly failureThreshold: number;\n /**\n * How long the breaker stays `open` before `canPass` starts admitting\n * probes, in milliseconds. Measured from `openedAtMs`; the cutoff is\n * half-open (`elapsed >= cooldownMs` admits), matching `rate-limit` /\n * `idempotency` window edges — a breaker opened at `t` first probes at\n * `t + cooldownMs`.\n */\n readonly cooldownMs: number;\n /**\n * How many probe calls `half_open` admits before fast-failing the rest of\n * the round. Caps the load on a recovering target — a single slow probe\n * can't be joined by every queued caller. The round ends when a probe\n * resolves: success closes the breaker, failure re-opens it.\n */\n readonly halfOpenMaxProbes: number;\n}\n\n/**\n * Sensible defaults: trip after 5 consecutive failures, cool down for 30s,\n * admit a single probe before deciding. Tuned for guarding a network backend;\n * override per call site rather than mutating this shared const.\n */\nexport const defaultCircuitPolicy: CircuitPolicy = {\n failureThreshold: 5,\n cooldownMs: 30_000,\n halfOpenMaxProbes: 1,\n};\n\n/**\n * The breaker's phase. A discriminated union on `phase` so each phase carries\n * ONLY its own data and impossible combinations are unrepresentable (pattern\n * 11): there is no state with both a failure count AND an open timestamp,\n * because such a state is meaningless. `phase` is the discriminant; every field\n * is `readonly` so the whole value is trivially JSON-serializable into a\n * consumer's `Store<S>` and safe to thread through a pure reducer.\n *\n * - `closed` carries `failures` — consecutive failures since last success.\n * - `open` carries `openedAtMs` — clock reading when it tripped.\n * - `half_open` carries `probes` — probes admitted this round.\n */\nexport type CircuitState =\n | { readonly phase: \"closed\"; readonly failures: number }\n | { readonly phase: \"open\"; readonly openedAtMs: number }\n | { readonly phase: \"half_open\"; readonly probes: number };\n\n/** The starting state: closed with zero recorded failures. */\nexport function initCircuit(): CircuitState {\n return { phase: \"closed\", failures: 0 };\n}\n\n/**\n * Record a successful guarded call. PURE — returns a new state; the input is\n * never mutated.\n *\n * - `closed` → reset `failures` to 0 (a success breaks the consecutive run).\n * - `half_open` → the probe succeeded; the target has recovered → `closed`.\n * - `open` → unchanged. A success \"shouldn't happen\" while open (no call\n * was admitted to produce one); a late/spurious success must\n * not silently un-trip the breaker. See module header note ¹.\n */\nexport function onSuccess(\n state: CircuitState,\n _policy: CircuitPolicy,\n): CircuitState {\n switch (state.phase) {\n case \"closed\":\n // Already closed at 0 → return the same shape (cheap; the consumer's\n // store only re-persists on a real change if it dedupes).\n return state.failures === 0 ? state : { phase: \"closed\", failures: 0 };\n case \"half_open\":\n return { phase: \"closed\", failures: 0 };\n case \"open\":\n return state;\n }\n}\n\n/**\n * Record a failed guarded call. PURE — returns a new state; the input is never\n * mutated. `nowMs` is the injected clock, stamped onto the `open` phase when the\n * breaker trips so `canPass` can measure the cooldown later.\n *\n * - `closed` → `failures + 1`; if that reaches `failureThreshold`, trip to\n * `open(nowMs)`. The threshold-th failure is the one that trips.\n * - `half_open` → the probe failed; the target is still unhealthy →\n * `open(nowMs)`, restarting the cooldown clock so a fresh\n * cooldown elapses before the next probe round.\n * - `open` → unchanged. The breaker is already tripped; the `open` clock\n * is anchored at the original trip, not bumped by late\n * failures. See module header note ¹.\n */\nexport function onFailure(\n state: CircuitState,\n policy: CircuitPolicy,\n nowMs: number,\n): CircuitState {\n switch (state.phase) {\n case \"closed\": {\n const failures = state.failures + 1;\n // `>=` not `===`: a threshold of 0 (or any already-exceeded count from a\n // policy change) trips immediately rather than over-counting forever.\n return failures >= policy.failureThreshold\n ? { phase: \"open\", openedAtMs: nowMs }\n : { phase: \"closed\", failures };\n }\n case \"half_open\":\n // A failed probe re-opens and resets the cooldown clock to nowMs.\n return { phase: \"open\", openedAtMs: nowMs };\n case \"open\":\n return state;\n }\n}\n\n/**\n * Decide whether a call may pass, advancing the phase as a side effect of the\n * decision. PURE — returns `[next, allowed]`; the input is never mutated.\n * Branch on the boolean, thread the state forward regardless:\n *\n * const [c1, allowed] = canPass(state.circuit, policy, nowMs);\n * if (!allowed) return [{ ...state, circuit: c1 }, [fastFailCmd]];\n * return [{ ...state, circuit: c1 }, [doGuardedCallCmd]];\n *\n * - `closed` → `[state, true]` — always passes; failures are recorded by\n * `onFailure` once the call resolves, not gated here.\n * - `open` → if `nowMs - openedAtMs >= cooldownMs` the cooldown has\n * elapsed → enter `half_open` and admit this caller as the\n * first probe: `[half_open(1), true]`. Otherwise still cooling\n * down → `[state, false]` (fast-fail, no downstream load).\n * - `half_open` → admit while `probes < halfOpenMaxProbes`, incrementing the\n * count: `[half_open(probes+1), true]`. Once the cap is hit →\n * `[state, false]` until a probe resolves and `onSuccess` /\n * `onFailure` moves the phase out of `half_open`.\n *\n * Entering `half_open` lives here (not in `onSuccess` / `onFailure`) because the\n * cooldown is a time condition and only `canPass` reads `nowMs` against\n * `openedAtMs`. See the module header's probe-admission note.\n */\nexport function canPass(\n state: CircuitState,\n policy: CircuitPolicy,\n nowMs: number,\n): readonly [CircuitState, boolean] {\n switch (state.phase) {\n case \"closed\":\n return [state, true];\n case \"open\": {\n const elapsed = nowMs - state.openedAtMs;\n // Half-open cutoff: elapsed exactly == cooldownMs admits the first probe,\n // matching the >= edge `rate-limit` / `idempotency` use for their windows.\n if (elapsed >= policy.cooldownMs) {\n return [{ phase: \"half_open\", probes: 1 }, true];\n }\n return [state, false];\n }\n case \"half_open\":\n if (state.probes < policy.halfOpenMaxProbes) {\n return [{ phase: \"half_open\", probes: state.probes + 1 }, true];\n }\n return [state, false];\n }\n}\n"]}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// src/paginator/index.ts
|
|
2
|
+
var defaultPaginatorPolicy = {
|
|
3
|
+
firstCursor: 0,
|
|
4
|
+
highWaterMark: 1e3
|
|
5
|
+
};
|
|
6
|
+
function initPaginator() {
|
|
7
|
+
return { phase: "idle", seen: 0, pages: 0 };
|
|
8
|
+
}
|
|
9
|
+
function start(state, policy) {
|
|
10
|
+
if (state.phase !== "idle") return state;
|
|
11
|
+
return {
|
|
12
|
+
phase: "fetching",
|
|
13
|
+
cursor: policy.firstCursor,
|
|
14
|
+
seen: state.seen,
|
|
15
|
+
pages: state.pages
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function recordPage(state, count, next, policy) {
|
|
19
|
+
if (state.phase !== "fetching") return state;
|
|
20
|
+
const safeCount = Number.isFinite(count) ? Math.max(0, count) : 0;
|
|
21
|
+
const seen = state.seen + safeCount;
|
|
22
|
+
const pages = state.pages + 1;
|
|
23
|
+
if (next == null) {
|
|
24
|
+
return { phase: "done", seen, pages };
|
|
25
|
+
}
|
|
26
|
+
if (policy.highWaterMark > 0 && seen >= policy.highWaterMark) {
|
|
27
|
+
return { phase: "paused", cursor: next, seen, pages };
|
|
28
|
+
}
|
|
29
|
+
return { phase: "fetching", cursor: next, seen, pages };
|
|
30
|
+
}
|
|
31
|
+
function drain(state, n) {
|
|
32
|
+
if (n <= 0) return state;
|
|
33
|
+
const seen = Math.max(0, state.seen - n);
|
|
34
|
+
if (seen === state.seen) return state;
|
|
35
|
+
return { ...state, seen };
|
|
36
|
+
}
|
|
37
|
+
function resume(state, policy) {
|
|
38
|
+
if (state.phase !== "paused") return state;
|
|
39
|
+
if (state.seen < policy.highWaterMark) {
|
|
40
|
+
return {
|
|
41
|
+
phase: "fetching",
|
|
42
|
+
cursor: state.cursor,
|
|
43
|
+
seen: state.seen,
|
|
44
|
+
pages: state.pages
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return state;
|
|
48
|
+
}
|
|
49
|
+
function isDone(state) {
|
|
50
|
+
return state.phase === "done";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export { defaultPaginatorPolicy, drain, initPaginator, isDone, recordPage, resume, start };
|
|
54
|
+
//# sourceMappingURL=chunk-SINXE47Y.js.map
|
|
55
|
+
//# sourceMappingURL=chunk-SINXE47Y.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/paginator/index.ts"],"names":[],"mappings":";AAmJO,IAAM,sBAAA,GAAkD;AAAA,EAC7D,WAAA,EAAa,CAAA;AAAA,EACb,aAAA,EAAe;AACjB;AAqCO,SAAS,aAAA,GAAgD;AAC9D,EAAA,OAAO,EAAE,KAAA,EAAO,MAAA,EAAQ,IAAA,EAAM,CAAA,EAAG,OAAO,CAAA,EAAE;AAC5C;AAWO,SAAS,KAAA,CACd,OACA,MAAA,EACwB;AACxB,EAAA,IAAI,KAAA,C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AChC,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,IAAA,EAAK;AAC1B;AAoBO,SAAS,MAAA,CACd,OACA,MAAA,EACwB;AACxB,EAAA,IAAI,KAAA,CAAM,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AACrC,EAAA,IAAI,KAAA,CAAM,IAAA,GAAO,MAAA,CAAO,aAAA,EAAe;AACrC,IAAA,OAAO;AAAA,MACL,KAAA,EAAO,UAAA;AAAA,MACP,QAAQ,KAAA,CAAM,MAAA;AAAA,MACd,MAAM,KAAA,CAAM,IAAA;AAAA,MACZ,OAAO,KAAA,CAAM;AAAA,KACf;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAQO,SAAS,OAAe,KAAA,EAAwC;AACrE,EAAA,OAAO,MAAM,KAAA,KAAU,MAAA;AACzB","file":"chunk-SINXE47Y.js","sourcesContent":["/**\n * @demlik/tea/paginator — the cursor/offset/page-token walk loop as pure\n * state + ops.\n *\n * Same shape as `@demlik/tea/retry-backoff`, `@demlik/tea/circuit-breaker`,\n * and `@demlik/tea/rate-limit`: a state type plus pure transition functions,\n * host-agnostic by construction. Nothing here reads the clock, the RNG, or any\n * I/O on its own behalf — the consumer fetches a page out-of-band and folds the\n * *result* back in through `recordPage`. That keeps every function inside TEA's\n * invariant 2 (transitions are pure: same inputs → same outputs) so a consumer\n * can thread the walk through `update` and exercise it with `replay` / the pbt\n * fold without a fake network.\n *\n * Every op returns a NEW state value and never mutates its input (invariant 1 —\n * state is a value, not a place). All fields are `readonly` and plain data, so\n * the whole walk is trivially JSON-serializable into a consumer's `Store<S>`\n * and survives a Durable-Object eviction / reload mid-walk: the cursor lives in\n * the Model, not a closure (the durability + replay non-negotiables every TEA\n * knob preserves).\n *\n * ## The cursor is opaque, and the consumer advances it\n *\n * A paginated API hands back a *next cursor* however it likes: an offset\n * (`?offset=40`), a page token (`?pageToken=ey…`), a \"next\" URL, or `null` at\n * the end. This module is generic in `Cursor` and never inspects it — it only\n * carries it forward. The consumer (who alone knows the API's shape) reads the\n * next cursor off the just-fetched page and passes it to `recordPage`:\n *\n * const next = page.nextPageToken ?? null; // consumer-specific extraction\n * const walk = recordPage(state.walk, page.items.length, next);\n *\n * Passing `next: null` (or a missing `undefined` cursor — the op compares with\n * loose `== null`) means \"the API said there is no next page\" → the walk\n * finishes (`done`). Passing a `Cursor` means \"fetch this one next\" → the walk\n * either keeps `fetching` or `pauses` for backpressure (below). Decoupling the\n * extraction from the op is the same discipline `circuit-breaker` uses for the\n * clock: the impure / domain-specific bit (`nextCursor(page)`) lives at the\n * call site; the op stays a pure fold over the extracted value.\n *\n * ## The phase machine\n *\n * Four phases, each a discriminated-union arm carrying ONLY the data that phase\n * needs so impossible states are unrepresentable (pattern 11):\n *\n * - **idle** — created, not started. No cursor is armed yet; `start` arms the\n * first one. Carries the running `seen` / `pages` counters (both 0 here, but\n * present on every phase so a consumer reads them uniformly).\n *\n * - **fetching** — a page request for `cursor` is outstanding. The walk sits\n * here while the consumer's fetch is in flight; `recordPage` resolves it.\n * Carries the `cursor` being fetched so a post-eviction resume re-issues the\n * SAME request (idempotent retry) rather than skipping a page.\n *\n * - **paused** — backpressure tripped. The API still has more pages (a non-null\n * next cursor), but `seen` has reached `highWaterMark` and the consumer has\n * not drained yet. Carries the `cursor` to resume from. No fetch is\n * outstanding — the loop is deliberately idle until `resume`. This is the\n * valve that stops a fast producer (the API) from outrunning a slow consumer\n * (whatever processes each page) and blowing memory.\n *\n * - **done** — the API returned a null next cursor; the walk is exhausted. A\n * terminal phase: `start` / `recordPage` / `resume` are all no-ops on it\n * (idempotent completion — a late duplicate result can't un-finish a walk).\n *\n * ### Transition table\n *\n * Rows are the current phase; columns are the op. `→` denotes the next phase;\n * `self` means unchanged (a no-op for that (phase × op) pair). `next` is the\n * cursor the consumer extracted from the page; `hwm` is `highWaterMark`.\n *\n * | from \\ op | start | recordPage(count, next) | resume |\n * | ----------- | -------------- | -------------------------------------------------------------------- | ------------------------------ |\n * | idle | → fetching(c0) | self *(¹)* | self |\n * | fetching | self | seen=max(0,seen+count), pages+=1; next==null → done; seen≥hwm → paused(next); else → fetching(next) | self |\n * | paused | self | self *(¹)* | seen<hwm → fetching(cursor) *(²)* |\n * | done | self | self | self |\n *\n * *(¹)* `recordPage` only makes sense while `fetching` (a page was outstanding).\n * On any other phase it is a no-op: a result that arrives when no fetch was in\n * flight (a late duplicate, a double-dispatch) must not advance the cursor or\n * double-count `seen`. The walk is a coordination aid, not a correctness gate —\n * it absorbs the stray rather than corrupting the count.\n *\n * *(²)* `resume` re-arms the paused cursor ONLY once `seen` has dropped below\n * `highWaterMark` (the consumer drained, lowering `seen` via `drain`). Calling\n * `resume` while still over the mark is a no-op — the valve stays shut until\n * there is real headroom, so a consumer that resumes optimistically can't\n * defeat the backpressure. Resuming a walk that isn't `paused` is likewise a\n * no-op.\n *\n * ## Backpressure\n *\n * `seen` is the count of items the API has produced that the consumer has not\n * yet acknowledged as processed. `recordPage` adds each page's item count to it;\n * `drain(n)` subtracts what the consumer finished. When `seen` reaches\n * `highWaterMark`, `recordPage` parks the walk in `paused` instead of issuing\n * the next fetch — the producer stops until `drain` + `resume` re-open the\n * valve. A `highWaterMark` of `0` (or any non-positive value) disables\n * backpressure: the comparison `seen >= hwm` is satisfied vacuously only when\n * `hwm <= 0` would pause immediately, so we treat `hwm <= 0` as \"unbounded\" and\n * never pause. The walk then runs flat-out, `fetching → fetching` until `done`.\n *\n * NOT exported from the package root — reached via the `@demlik/tea/paginator`\n * subpath, same one-shape-per-package rule as `work-queue`, `retry-backoff`,\n * `circuit-breaker`, and `rate-limit`. It is the L1 escape hatch the\n * `paginated-walk` composition builds its walk loop on.\n */\n\n/**\n * Paginator policy — pure configuration, no mutable state. One policy is shared\n * across the whole walk (often a module-scope const). `PaginatorState` carries\n * the cursor + counters; this carries the knobs they're compared against.\n *\n * Generic in `Cursor` so `firstCursor` matches whatever the API's cursor shape\n * is — an offset `number`, a page-token `string`, a `{ after: string }` record,\n * etc. The module never inspects the cursor; the type just threads through.\n */\nexport interface PaginatorPolicy<Cursor> {\n /**\n * The cursor the walk fetches first, armed by `start`. For an offset API this\n * is typically `0`; for a token API, `null`-or-empty-meaning-\"first page\" is\n * the API's call, so pass whatever sentinel the API treats as page one.\n */\n readonly firstCursor: Cursor;\n /**\n * Backpressure threshold: the number of un-drained items at which the walk\n * pauses instead of fetching the next page. `recordPage` parks in `paused`\n * once `seen >= highWaterMark`; `drain` + `resume` re-open the valve.\n *\n * A non-positive value (`<= 0`) disables backpressure — the walk never pauses\n * and runs `fetching → fetching` until the API exhausts. Use that when the\n * consumer processes each page synchronously inside `recordPage` and there is\n * nothing to back up.\n */\n readonly highWaterMark: number;\n}\n\n/**\n * Sensible defaults: start from a numeric offset of `0`, pause after 1000\n * un-drained items. Tuned for an offset-paginated REST API whose consumer\n * processes pages asynchronously; override per call site (especially\n * `firstCursor`, which is API-specific) rather than mutating this shared const.\n *\n * Typed as `PaginatorPolicy<number>` because the only honest default cursor is\n * the numeric offset `0`; a token-based API supplies its own `firstCursor` and\n * its own `PaginatorPolicy<string>`.\n */\nexport const defaultPaginatorPolicy: PaginatorPolicy<number> = {\n firstCursor: 0,\n highWaterMark: 1000,\n};\n\n/**\n * The walk's phase. A discriminated union on `phase` so each phase carries ONLY\n * its own data and impossible combinations are unrepresentable (pattern 11):\n * there is no `done` state that still holds a pending cursor, no `idle` state\n * mid-fetch. Every field is `readonly` so the whole value is trivially\n * JSON-serializable into a consumer's `Store<S>` and safe to thread through a\n * pure reducer / a Durable-Object reload.\n *\n * Two counters ride on every phase so a consumer reads them uniformly without\n * narrowing first:\n * - `seen` — items produced by the API but not yet drained (backpressure gauge).\n * - `pages` — total pages recorded so far (progress / observability).\n *\n * - `idle` — not started; `start` arms `firstCursor`.\n * - `fetching` — a page request for `cursor` is outstanding.\n * - `paused` — backpressure tripped; `cursor` is the page to resume from.\n * - `done` — API exhausted (null next cursor); terminal.\n */\nexport type PaginatorState<Cursor> =\n | { readonly phase: \"idle\"; readonly seen: number; readonly pages: number }\n | {\n readonly phase: \"fetching\";\n readonly cursor: Cursor;\n readonly seen: number;\n readonly pages: number;\n }\n | {\n readonly phase: \"paused\";\n readonly cursor: Cursor;\n readonly seen: number;\n readonly pages: number;\n }\n | { readonly phase: \"done\"; readonly seen: number; readonly pages: number };\n\n/** The starting state: idle, nothing seen, no pages recorded. */\nexport function initPaginator<Cursor>(): PaginatorState<Cursor> {\n return { phase: \"idle\", seen: 0, pages: 0 };\n}\n\n/**\n * Arm the first fetch. PURE — returns a new state; the input is never mutated.\n *\n * - `idle` → `fetching(firstCursor)`. This is the only phase `start` acts on.\n * - any other phase → unchanged. Re-arming a walk that has already begun (or\n * finished) would skip back to page one and double-count; a stray `start`\n * after launch is absorbed, not honored. Use `initPaginator()` to begin a\n * genuinely fresh walk.\n */\nexport function start<Cursor>(\n state: PaginatorState<Cursor>,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"idle\") return state;\n return {\n phase: \"fetching\",\n cursor: policy.firstCursor,\n seen: state.seen,\n pages: state.pages,\n };\n}\n\n/**\n * Record the result of the outstanding fetch and decide what comes next. PURE —\n * returns a new state; the input is never mutated.\n *\n * `count` is how many items the just-fetched page yielded (added to `seen` for\n * backpressure accounting). `next` is the cursor the consumer extracted from the\n * page — a `Cursor` to fetch next, or `null`/`undefined` (a missing optional\n * cursor field) if the API signalled the end.\n *\n * - `fetching` → `seen = max(0, seen + count)`, `pages += 1`, then branch on\n * `next`:\n * - `next == null` → `done` (API exhausted; loose-null so a\n * missing/`undefined` cursor also finishes).\n * - `seen >= highWaterMark` → `paused(next)` (backpressure; `hwm <= 0`\n * disables this branch — see policy docs).\n * - otherwise → `fetching(next)` (keep walking).\n * - any other phase → unchanged. A result with no fetch outstanding (a late\n * duplicate, a double-dispatch) must not advance the cursor or double-count;\n * it is absorbed. See the module header's note ¹.\n *\n * `count` is floored into the gauge: a non-finite `count` (`NaN`/`Infinity`) is\n * treated as `0`, and the additive sum is clamped at `0`. A record can only hold\n * or raise `seen`; only `drain` lowers it. This keeps a stray negative or\n * non-finite count from poisoning the `seen >= highWaterMark` comparison and\n * silently defeating backpressure.\n *\n * The new `seen` total — not the pre-page value — is what the backpressure check\n * reads, so a single page large enough to cross the mark pauses immediately\n * rather than fetching one more first.\n */\nexport function recordPage<Cursor>(\n state: PaginatorState<Cursor>,\n count: number,\n next: Cursor | null | undefined,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"fetching\") return state;\n // A page's item count must be a finite, non-negative addition to `seen`. A\n // negative count would drive `seen` down (a record can never lower the gauge —\n // only `drain` does) and a non-finite count (`NaN` / `Infinity`) would poison\n // every later `seen >= highWaterMark` comparison, permanently defeating\n // backpressure (NaN compares false, so the valve never trips). Floor the\n // CONTRIBUTION (not just the sum) at 0: clamp a non-finite count to 0\n // (mirroring retry-backoff's `Number.isNaN` discipline at backoffDelay ~:119)\n // and a negative count to 0. Flooring the contribution — rather than the sum —\n // is what makes a record strictly monotonic: `Math.max(0, seen + count)` only\n // catches a count that drags the *sum* below zero, so a small negative count\n // (e.g. `seen=10, count=-3 → 7`) would still silently lower the gauge and\n // break \"only `drain` lowers `seen`\". Clamping `count` first guarantees the\n // additive step can only hold or raise the gauge.\n const safeCount = Number.isFinite(count) ? Math.max(0, count) : 0;\n const seen = state.seen + safeCount;\n const pages = state.pages + 1;\n // Loose `== null` so a *missing* next cursor (`undefined`, common for an\n // optional API field the consumer extracted as `page.nextPageToken`) finishes\n // the walk exactly like an explicit `null`. Strict `=== null` would route an\n // `undefined` cursor into the fetching/paused branch and carry a cursor-less\n // (malformed) state forward.\n if (next == null) {\n return { phase: \"done\", seen, pages };\n }\n // `hwm <= 0` disables backpressure entirely (unbounded walk); only a positive\n // mark can park the loop. `seen >= hwm` is the half-open edge — reaching the\n // mark exactly pauses, matching the `>=` window edges `rate-limit` /\n // `circuit-breaker` use.\n if (policy.highWaterMark > 0 && seen >= policy.highWaterMark) {\n return { phase: \"paused\", cursor: next, seen, pages };\n }\n return { phase: \"fetching\", cursor: next, seen, pages };\n}\n\n/**\n * Acknowledge that the consumer finished processing `n` items, lowering the\n * backpressure gauge. PURE — returns a new state; the input is never mutated.\n *\n * Subtracts `n` from `seen`, floored at 0 (a consumer that over-acks, or acks a\n * page recorded before a reload, can never drive `seen` negative). `n <= 0` is a\n * no-op on the count. `drain` does NOT change the phase — it only frees\n * headroom; `resume` is the separate, explicit decision to re-issue a fetch once\n * the headroom exists. Splitting \"I drained\" from \"I want to continue\" lets a\n * consumer drain in several steps and resume once.\n *\n * Works on every phase: a consumer may drain while still `fetching` (the gauge\n * just drops, no pause was reached) or while `paused` (freeing room for a later\n * `resume`). On `done` the gauge can still be drained for accurate final\n * accounting, though it no longer gates anything.\n */\nexport function drain<Cursor>(\n state: PaginatorState<Cursor>,\n n: number,\n): PaginatorState<Cursor> {\n if (n <= 0) return state;\n const seen = Math.max(0, state.seen - n);\n if (seen === state.seen) return state;\n return { ...state, seen };\n}\n\n/**\n * Re-open the backpressure valve after a `drain`. PURE — returns a new state;\n * the input is never mutated.\n *\n * - `paused` AND `seen < highWaterMark` → `fetching(cursor)`: the consumer has\n * drained below the mark, so re-issue the parked fetch.\n * - `paused` but `seen >= highWaterMark` → unchanged. There is still no\n * headroom; the valve stays shut until a `drain` lowers `seen`. A consumer\n * that resumes optimistically can't defeat the backpressure. (When `hwm <=\n * 0` backpressure is disabled, so the walk never reaches `paused` and this\n * branch is unreachable — but the guard reads `< hwm` consistently, and a\n * non-positive `hwm` makes `seen < hwm` false for any non-negative `seen`,\n * correctly refusing to resume a state that should never have paused.)\n * - any other phase → unchanged. Resuming a walk that isn't paused (idle,\n * fetching, done) is a no-op.\n *\n * See the module header's note ².\n */\nexport function resume<Cursor>(\n state: PaginatorState<Cursor>,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"paused\") return state;\n if (state.seen < policy.highWaterMark) {\n return {\n phase: \"fetching\",\n cursor: state.cursor,\n seen: state.seen,\n pages: state.pages,\n };\n }\n return state;\n}\n\n/**\n * Whether the walk has finished (the API returned a null next cursor). PURE,\n * read-only. A derived predicate so a consumer's reducer can branch\n * (`if (isDone(walk)) return [doneState, [joinCmd]]`) without re-checking the\n * `phase` discriminant by hand at every call site.\n */\nexport function isDone<Cursor>(state: PaginatorState<Cursor>): boolean {\n return state.phase === \"done\";\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { foldMsgs } from './chunk-QLA76GIT.js';
|
|
2
|
+
|
|
3
|
+
// src/prediction/index.ts
|
|
4
|
+
var tagSeq = (seq, value) => ({ seq, value });
|
|
5
|
+
var ack = (lastAppliedSeq) => ({ lastAppliedSeq });
|
|
6
|
+
var NO_ACK = -1;
|
|
7
|
+
var initAck = () => ack(NO_ACK);
|
|
8
|
+
var partitionByAck = (buffer, ackOrSeq) => {
|
|
9
|
+
const lastAppliedSeq = typeof ackOrSeq === "number" ? ackOrSeq : ackOrSeq.lastAppliedSeq;
|
|
10
|
+
const acked = [];
|
|
11
|
+
const pending = [];
|
|
12
|
+
for (const item of buffer) {
|
|
13
|
+
if (item.seq <= lastAppliedSeq) {
|
|
14
|
+
acked.push(item);
|
|
15
|
+
} else {
|
|
16
|
+
pending.push(item);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return { acked, pending };
|
|
20
|
+
};
|
|
21
|
+
var nextSeq = (buffer) => buffer.reduce((max, item) => item.seq > max ? item.seq : max, -1) + 1;
|
|
22
|
+
function reconcile(machine, authoritativeState, lastAppliedSeq, pending) {
|
|
23
|
+
const { pending: unacked } = partitionByAck(pending, lastAppliedSeq);
|
|
24
|
+
return foldMsgs(
|
|
25
|
+
machine,
|
|
26
|
+
authoritativeState,
|
|
27
|
+
unacked.map((tagged) => tagged.value)
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export { NO_ACK, ack, initAck, nextSeq, partitionByAck, reconcile, tag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OAAA;AAAA,IACA,kBAAA;AAAA,IACA,OAAA,CAAQ,GAAA,CAAI,CAAC,MAAA,KAAW,OAAO,KAAK;AAAA,GACtC;AACF","file":"chunk-SQTCS44W.js","sourcesContent":["/**\n * @demlik/tea/prediction — the client-prediction ack primitive (epic #186, facet 2).\n *\n * The contract the Gambetta/Valve authoritative-server netcode loop needs:\n * **command-seq-in → last-applied-seq-out.** A client tags each predicted\n * command/`Msg` with a monotonic `seq`; the authoritative side replies with the\n * `lastAppliedSeq` it has processed. `partitionByAck` then splits the client's\n * pending buffer into the inputs the server has ACKED (`seq <= lastAppliedSeq`)\n * and those still PENDING (`seq > lastAppliedSeq`) — the un-acked tail the\n * reconciliation pass (#214) replays over the authoritative snapshot via\n * `foldMsgs` (#211, `@demlik/tea/pure`).\n *\n * Deliberately **Model-shape-agnostic** (ADR 0006): the ack is a standalone\n * value, NOT a field this module requires on the consumer's `State`. It\n * generalizes the `lastAckedSeq`-on-the-Model + `seq`-threaded-through-the-Msg\n * pattern vortex hand-rolled (epic #186). It is a LEAF module — pure and\n * runtime-free, importing nothing from the tea core or host, so it can never\n * drag `run`/the host into a client bundle.\n *\n * This is the read/ack side of the primitive; `tagSeq`/`nextSeq` are the write\n * side, letting a client mint monotonic seqs from its pending buffer alone —\n * again with no counter field on the Model.\n *\n * `reconcile` (the read side's payoff, #214) composes this ack partition with\n * the pure fold seam `foldMsgs` (#211) to perform the whole Gambetta/Valve\n * reconciliation step in one call. The `foldMsgs` import is the ONLY dependency\n * this leaf takes, and it reaches into the pure-core leaf (`../pure/core`) — NOT\n * the runtime root — so the module stays runtime-free and the `@demlik/tea/pure`\n * import-graph guard (ADR 0006, #213) still holds.\n */\n\nimport type { Cmd, Machine, Sub } from \"../pure/core\";\nimport { foldMsgs } from \"../pure/core\";\n\n/**\n * A monotonic, non-negative sequence number tagging one client-predicted\n * command. Monotonicity is the client's contract (mint successive seqs with\n * `nextSeq`); this module only ever *compares* seqs.\n */\nexport type Seq = number;\n\n/** A command (or `Msg`) tagged with the `seq` the client assigned it. */\nexport interface SeqTagged<T> {\n readonly seq: Seq;\n readonly value: T;\n}\n\n/** Tag a command/`Msg` with its sequence number. */\nexport const tagSeq = <T>(seq: Seq, value: T): SeqTagged<T> => ({ seq, value });\n\n/**\n * The authoritative side's acknowledgement: the highest `seq` it has applied.\n * Everything with `seq <= lastAppliedSeq` is settled; everything above is still\n * in flight. This *is* the whole \"ack from the authoritative side\" — a value\n * the consumer carries however it likes (a wire field, a message payload),\n * never a shape this module imposes on the Model.\n */\nexport interface Ack {\n readonly lastAppliedSeq: Seq;\n}\n\n/** Construct an `Ack` for a last-applied sequence number. */\nexport const ack = (lastAppliedSeq: Seq): Ack => ({ lastAppliedSeq });\n\n/**\n * The \"nothing applied yet\" cursor — the ack value for a server that has applied\n * no client input at all. Because `nextSeq` mints **0-based** seqs and\n * `partitionByAck` acks **inclusively** (`seq <= lastAppliedSeq`), the pre-first\n * cursor must sit strictly *below* seq 0: `lastAppliedSeq = 0` would falsely ack\n * the seq-0 input before the server ever saw it. `-1` is \"before any seq\", and\n * `partitionByAck(buffer, NO_ACK)` therefore leaves the whole buffer PENDING.\n *\n * This names the boundary value on the seam so no consumer has to re-discover it\n * as a magic number: it is the primitive's own design (0-based mint + inclusive\n * partition) that creates the trap, so it is the primitive's job to name the\n * escape. Pair with {@link initAck} when an {@link Ack} is wanted instead of the\n * bare `Seq`.\n */\nexport const NO_ACK: Seq = -1;\n\n/**\n * The `Ack` for a server that has applied nothing yet — `ack(NO_ACK)`. The `Ack`\n * counterpart to the {@link NO_ACK} `Seq` sentinel, for a consumer that carries\n * an `Ack` rather than a bare `lastAppliedSeq`.\n */\nexport const initAck = (): Ack => ack(NO_ACK);\n\n/** The result of splitting a seq-tagged buffer against an ack. */\nexport interface AckPartition<T> {\n /** Inputs the authoritative side has applied (`seq <= lastAppliedSeq`). */\n readonly acked: readonly SeqTagged<T>[];\n /** Inputs still in flight / un-acked (`seq > lastAppliedSeq`) — the replay tail. */\n readonly pending: readonly SeqTagged<T>[];\n}\n\n/**\n * Partition a buffer of seq-tagged commands into ACKED and PENDING against the\n * authoritative `lastAppliedSeq`. Pure and total: every item lands in exactly\n * one bucket, input order is preserved within each bucket, and the boundary\n * `seq == lastAppliedSeq` is ACKED (inclusive `<=`). Routing is by `seq` value,\n * not buffer position, so an out-of-order or duplicate-seq buffer partitions\n * correctly. Accepts either an {@link Ack} or a bare `lastAppliedSeq` number, so\n * a caller passes whichever it holds.\n */\nexport const partitionByAck = <T>(\n buffer: readonly SeqTagged<T>[],\n ackOrSeq: Ack | Seq,\n): AckPartition<T> => {\n const lastAppliedSeq =\n typeof ackOrSeq === \"number\" ? ackOrSeq : ackOrSeq.lastAppliedSeq;\n const acked: SeqTagged<T>[] = [];\n const pending: SeqTagged<T>[] = [];\n for (const item of buffer) {\n if (item.seq <= lastAppliedSeq) {\n acked.push(item);\n } else {\n pending.push(item);\n }\n }\n return { acked, pending };\n};\n\n/**\n * The next sequence number to assign: one past the highest `seq` in the buffer,\n * or `0` for an empty buffer. Lets a client mint monotonic seqs from its pending\n * buffer alone — no counter field on the Model — and is tolerant of an unordered\n * buffer (it takes the max, not the last element).\n */\nexport const nextSeq = <T>(buffer: readonly SeqTagged<T>[]): Seq =>\n buffer.reduce((max, item) => (item.seq > max ? item.seq : max), -1) + 1;\n\n/**\n * The client prediction/reconciliation helper — the Gambetta/Valve\n * authoritative-server loop's reconcile step, generalized (#214, epic #186).\n *\n * Given the latest `authoritativeState` from the server, the server's\n * `lastAppliedSeq` ack, and the client's `pending` buffer of seq-tagged inputs,\n * it returns the corrected predicted state: drop the inputs the server has\n * already applied (`seq <= lastAppliedSeq`) and replay ONLY the un-acked tail\n * (`seq > lastAppliedSeq`) over the authoritative snapshot.\n *\n * It is **composed, not re-derived** (ADR 0006): the drop is {@link partitionByAck}\n * (the ack primitive, #212) and the replay is `foldMsgs` (the pure fold seam,\n * #211) — there is no second copy of the partition logic and no second copy of\n * the fold. `lastAppliedSeq` accepts either an {@link Ack} or a bare `Seq`, so a\n * caller passes whichever it holds, matching `partitionByAck`.\n *\n * Pure and host-agnostic: it takes the `machine` (which `foldMsgs` needs to\n * dispatch `update`) but touches no `Store`, `interpret`, or subscription, and\n * imports nothing from the runtime — so it ships on `@demlik/tea/prediction`\n * and the client-safe `@demlik/tea/pure` umbrella without dragging `run` into a\n * client bundle.\n */\nexport function reconcile<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n authoritativeState: S,\n lastAppliedSeq: Ack | Seq,\n pending: readonly SeqTagged<M>[],\n): S {\n const { pending: unacked } = partitionByAck(pending, lastAppliedSeq);\n return foldMsgs(\n machine,\n authoritativeState,\n unacked.map((tagged) => tagged.value),\n );\n}\n"]}
|