@demlik/tea 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -0
- package/dist/agent/index.d.ts +16 -770
- package/dist/agent/index.js +18 -16
- package/dist/authed-call/index.d.ts +3 -3
- package/dist/authed-call/index.js +22 -36
- package/dist/authed-call/index.js.map +1 -1
- package/dist/await-terminal/index.d.ts +2 -2
- package/dist/await-terminal/index.js +2 -2
- package/dist/batch-window/index.d.ts +3 -3
- package/dist/batch-window/index.js +3 -3
- package/dist/cache/index.d.ts +2 -2
- package/dist/cache/index.js +5 -2
- package/dist/{chunk-3545BOYL.js → chunk-25LBDCBC.js} +6 -5
- package/dist/chunk-25LBDCBC.js.map +1 -0
- package/dist/{chunk-IN33Q4VJ.js → chunk-2KNLKQVN.js} +3 -3
- package/dist/{chunk-IN33Q4VJ.js.map → chunk-2KNLKQVN.js.map} +1 -1
- package/dist/{chunk-MMH7CW5K.js → chunk-BP2R7TPP.js} +216 -157
- package/dist/chunk-BP2R7TPP.js.map +1 -0
- package/dist/chunk-C6QC273X.js +71 -0
- package/dist/chunk-C6QC273X.js.map +1 -0
- package/dist/{chunk-7W4LMPUW.js → chunk-CAXMQJJ3.js} +17 -24
- package/dist/chunk-CAXMQJJ3.js.map +1 -0
- package/dist/{chunk-UV6UWGEO.js → chunk-D736QUGF.js} +6 -5
- package/dist/chunk-D736QUGF.js.map +1 -0
- package/dist/chunk-EWJP3YYP.js +21 -0
- package/dist/chunk-EWJP3YYP.js.map +1 -0
- package/dist/{chunk-TGG26XMK.js → chunk-FV3Z5MBE.js} +10 -5
- package/dist/chunk-FV3Z5MBE.js.map +1 -0
- package/dist/chunk-G5E74IJB.js +8 -0
- package/dist/chunk-G5E74IJB.js.map +1 -0
- package/dist/{chunk-27N2SPTN.js → chunk-IXBKFQH5.js} +12 -11
- package/dist/chunk-IXBKFQH5.js.map +1 -0
- package/dist/{chunk-SQTCS44W.js → chunk-JFFVBEDI.js} +3 -3
- package/dist/{chunk-SQTCS44W.js.map → chunk-JFFVBEDI.js.map} +1 -1
- package/dist/chunk-LYLDCIPH.js +365 -0
- package/dist/chunk-LYLDCIPH.js.map +1 -0
- package/dist/{chunk-HJO6VNQI.js → chunk-MU6MCIAC.js} +3 -3
- package/dist/{chunk-HJO6VNQI.js.map → chunk-MU6MCIAC.js.map} +1 -1
- package/dist/{chunk-UYWUVEP6.js → chunk-MUUROGIH.js} +2 -2
- package/dist/chunk-MUUROGIH.js.map +1 -0
- package/dist/{chunk-EHIX7NYZ.js → chunk-MVY5DAMF.js} +4 -4
- package/dist/{chunk-EHIX7NYZ.js.map → chunk-MVY5DAMF.js.map} +1 -1
- package/dist/{chunk-LP7VQBRG.js → chunk-NPERUUUE.js} +76 -95
- package/dist/chunk-NPERUUUE.js.map +1 -0
- package/dist/{chunk-QLA76GIT.js → chunk-PBDYW2TU.js} +68 -9
- package/dist/chunk-PBDYW2TU.js.map +1 -0
- package/dist/{chunk-5VNWZADP.js → chunk-Q2UM7BXU.js} +18 -7
- package/dist/chunk-Q2UM7BXU.js.map +1 -0
- package/dist/chunk-RMX4EOQK.js +26 -0
- package/dist/chunk-RMX4EOQK.js.map +1 -0
- package/dist/{chunk-2YOE5PIS.js → chunk-S2EGRPCM.js} +8 -6
- package/dist/chunk-S2EGRPCM.js.map +1 -0
- package/dist/{chunk-ON24RKSE.js → chunk-S4O26D7B.js} +7 -14
- package/dist/chunk-S4O26D7B.js.map +1 -0
- package/dist/{chunk-3XJWC7VW.js → chunk-SK5JGUY7.js} +3 -3
- package/dist/{chunk-3XJWC7VW.js.map → chunk-SK5JGUY7.js.map} +1 -1
- package/dist/{chunk-5DEQ5I3U.js → chunk-TPGASTFF.js} +8 -10
- package/dist/chunk-TPGASTFF.js.map +1 -0
- package/dist/{chunk-SC3FAFZN.js → chunk-UF4MZSLT.js} +2 -2
- package/dist/chunk-UF4MZSLT.js.map +1 -0
- package/dist/{chunk-PS23H6KQ.js → chunk-VBUCHVCV.js} +6 -5
- package/dist/chunk-VBUCHVCV.js.map +1 -0
- package/dist/{chunk-S3FQN4SL.js → chunk-WGGAMW7Y.js} +191 -178
- package/dist/chunk-WGGAMW7Y.js.map +1 -0
- package/dist/chunk-ZJ5AOYBH.js +8 -0
- package/dist/chunk-ZJ5AOYBH.js.map +1 -0
- package/dist/{chunk-LEC4U6CX.js → chunk-ZVJZ72HY.js} +3 -3
- package/dist/{chunk-LEC4U6CX.js.map → chunk-ZVJZ72HY.js.map} +1 -1
- package/dist/circuit-breaker/index.d.ts +1 -0
- package/dist/circuit-breaker/index.js +1 -1
- package/dist/{core-BoB6t7dB.d.ts → core-42kapW0n.d.ts} +105 -6
- package/dist/deadline/index.d.ts +77 -11
- package/dist/deadline/index.js +3 -3
- package/dist/devtools/index.js +8 -28
- package/dist/devtools/index.js.map +1 -1
- package/dist/do/index.d.ts +483 -339
- package/dist/do/index.js +244 -214
- package/dist/do/index.js.map +1 -1
- package/dist/{durable-effects-CO9Uh971.d.ts → durable-effects-CFRngTNA.d.ts} +3 -3
- package/dist/extension/index.d.ts +25 -7
- package/dist/extension/index.js +4 -3
- package/dist/extension/index.js.map +1 -1
- package/dist/extension/react.js +4 -3
- package/dist/extension/react.js.map +1 -1
- package/dist/extension/subs/index.d.ts +2 -2
- package/dist/extension/subs/index.js +7 -10
- package/dist/extension/subs/index.js.map +1 -1
- package/dist/fan-out/index.d.ts +10 -10
- package/dist/fan-out/index.js +3 -3
- package/dist/idempotent-intake/index.d.ts +2 -2
- package/dist/idempotent-intake/index.js +3 -3
- package/dist/index.d.ts +50 -472
- package/dist/index.js +2 -2
- package/dist/llm-call/index.d.ts +3 -2
- package/dist/llm-call/index.js +12 -10
- package/dist/machine-B_BF4jij.d.ts +804 -0
- package/dist/machine-viz/index.d.ts +1 -1
- package/dist/machine-viz/index.js +2 -2
- package/dist/mem/index.d.ts +3 -2
- package/dist/mem/index.js.map +1 -1
- package/dist/monitored-run/index.d.ts +54 -30
- package/dist/monitored-run/index.js +7 -7
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.js +2 -3
- package/dist/node/index.js.map +1 -1
- package/dist/paginated-walk/index.d.ts +2 -2
- package/dist/paginated-walk/index.js +11 -10
- package/dist/parity/index.d.ts +6 -5
- package/dist/parity/index.js +5 -4
- package/dist/parity/index.js.map +1 -1
- package/dist/pbt/arbitraries/index.d.ts +1 -1
- package/dist/pbt/index.d.ts +1 -1
- package/dist/pbt/index.js +3 -3
- package/dist/pbt/index.js.map +1 -1
- package/dist/pbt/runners/index.d.ts +1 -1
- package/dist/pbt/runners/index.js +3 -3
- package/dist/poller/index.d.ts +59 -17
- package/dist/poller/index.js +56 -20
- package/dist/poller/index.js.map +1 -1
- package/dist/prediction/index.d.ts +1 -1
- package/dist/prediction/index.js +2 -2
- package/dist/pure/index.d.ts +1 -1
- package/dist/pure/index.js +2 -2
- package/dist/rate-limit/index.d.ts +2 -2
- package/dist/rate-limit/index.js +1 -1
- package/dist/react/index.d.ts +3 -2
- package/dist/react/index.js +2 -2
- package/dist/react/index.js.map +1 -1
- package/dist/reconciler/index.d.ts +2 -2
- package/dist/reconciler/index.js +13 -15
- package/dist/reconciler/index.js.map +1 -1
- package/dist/recorder/index.d.ts +20 -20
- package/dist/recorder/index.js +1 -1
- package/dist/resilient-call/index.d.ts +31 -6
- package/dist/resilient-call/index.js +10 -9
- package/dist/retry-backoff/index.d.ts +191 -14
- package/dist/retry-backoff/index.js +1 -1
- package/dist/retry-to-success/index.js +1 -1
- package/dist/runtime-types-gsog27b6.d.ts +337 -0
- package/dist/saga/index.d.ts +3 -2
- package/dist/saga/index.js +2 -2
- package/dist/saga/index.js.map +1 -1
- package/dist/snapshot/index.d.ts +1 -1
- package/dist/snapshot/index.js +3 -3
- package/dist/subs/index.d.ts +372 -4
- package/dist/subs/index.js +4 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +2 -2
- package/dist/throttled-input/index.d.ts +2 -2
- package/dist/throttled-input/index.js +14 -13
- package/dist/throttled-input/index.js.map +1 -1
- package/dist/token-refresh/index.d.ts +1 -1
- package/dist/token-refresh/index.js +3 -3
- package/dist/trace-replay/index.d.ts +12 -7
- package/dist/trace-replay/index.js +4 -3
- package/dist/{types-B-8bcAp8.d.ts → types-KbL3W1mj.d.ts} +1 -1
- package/dist/with-deadline/index.d.ts +1 -1
- package/dist/with-deadline/index.js +2 -2
- package/dist/with-resilience/index.d.ts +21 -2
- package/dist/with-resilience/index.js +12 -23
- package/dist/with-resilience/index.js.map +1 -1
- package/dist/with-telemetry/index.d.ts +1 -1
- package/dist/with-telemetry/index.js +2 -2
- package/dist/work-queue/adapter.d.ts +2 -2
- package/dist/work-queue/adapter.js +2 -2
- package/dist/work-queue/index.d.ts +3 -2
- package/dist/work-queue/index.js +1 -1
- package/dist/work-queue/index.js.map +1 -1
- package/dist/work-queue/ops.d.ts +2 -2
- package/dist/work-queue/ops.js +1 -1
- package/dist/workflow/index.d.ts +51 -19
- package/dist/workflow/index.js +71 -52
- package/dist/workflow/index.js.map +1 -1
- package/package.json +4 -19
- package/dist/chunk-27N2SPTN.js.map +0 -1
- package/dist/chunk-2YOE5PIS.js.map +0 -1
- package/dist/chunk-3545BOYL.js.map +0 -1
- package/dist/chunk-5DEQ5I3U.js.map +0 -1
- package/dist/chunk-5VNWZADP.js.map +0 -1
- package/dist/chunk-6RGBKODV.js +0 -268
- package/dist/chunk-6RGBKODV.js.map +0 -1
- package/dist/chunk-7W4LMPUW.js.map +0 -1
- package/dist/chunk-DILMKOZ7.js +0 -91
- package/dist/chunk-DILMKOZ7.js.map +0 -1
- package/dist/chunk-K7Q23EQ4.js +0 -20
- package/dist/chunk-K7Q23EQ4.js.map +0 -1
- package/dist/chunk-LP7VQBRG.js.map +0 -1
- package/dist/chunk-MMH7CW5K.js.map +0 -1
- package/dist/chunk-NSDFA6M6.js +0 -198
- package/dist/chunk-NSDFA6M6.js.map +0 -1
- package/dist/chunk-ON24RKSE.js.map +0 -1
- package/dist/chunk-PS23H6KQ.js.map +0 -1
- package/dist/chunk-QLA76GIT.js.map +0 -1
- package/dist/chunk-S3FQN4SL.js.map +0 -1
- package/dist/chunk-SC3FAFZN.js.map +0 -1
- package/dist/chunk-TGG26XMK.js.map +0 -1
- package/dist/chunk-UV6UWGEO.js.map +0 -1
- package/dist/chunk-UYWUVEP6.js.map +0 -1
- package/dist/chunk-VLGARN6H.js +0 -202
- package/dist/chunk-VLGARN6H.js.map +0 -1
- package/dist/raft/demo.d.ts +0 -105
- package/dist/raft/demo.js +0 -172
- package/dist/raft/demo.js.map +0 -1
- package/dist/raft/index.d.ts +0 -548
- package/dist/raft/index.js +0 -7
- package/dist/raft/index.js.map +0 -1
- package/dist/raft/sim.d.ts +0 -222
- package/dist/raft/sim.js +0 -8
- package/dist/raft/sim.js.map +0 -1
- package/dist/raft/timeline.d.ts +0 -46
- package/dist/raft/timeline.js +0 -62
- package/dist/raft/timeline.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
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,KAAA,KAA8B;AACpC,IAAA,IAAI,CAAC,WAAA,CAAY,KAAK,CAAA,EAAG;AACvB,MAAA,MAAM,IAAI,MAAM,kDAAkD,CAAA;AAAA,IACpE;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAmIO,IAAM,kBAAA,GAAwC;AAkB9C,SAAS,oBACd,KAAA,EAC4B;AAC5B,EAA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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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/circuit-breaker/index.ts"],"names":[],"mappings":";AAw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;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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/work-queue/ops.ts"],"names":[],"mappings":";AAuBO,SAAS,SAAA,CACd,KAAA,EACA,KAAA,EACA,GAAA,EACA,EAAA,EAC8C;AAC9C,EAAA,MAAM,IAAA,GAAqB;AAAA,IACzB,EAAA;AAAA,IACA,MAAA,EAAQ,SAAA;AAAA,IACR,KAAA;AAAA,IACA,UAAA,EAAY;AAAA,GACd;AACA,EAAA,OAAO,EAAE,IAAA,EAAM,CAAC,GAAG,KAAA,EAAO,IAAI,GAAG,IAAA,EAAK;AACxC;AAOO,SAAS,WAAA,CACd,OACA,GAAA,EACwD;AACxD,EAAA,MAAM,MAAM,KAAA,CAAM,SAAA,CAAU,CAAC,CAAA,KAAM,CAAA,CAAE,WAAW,SAAS,CAAA;AACzD,EAAA,MAAM,MAAA,GAAS,GAAA,KAAQ,EAAA,GAAK,MAAA,GAAY,MAAM,GAAG,CAAA;AAIjD,EAAA,IAAI,MAAA,KAAW,QAAW,OAAO,IAAA;AACjC,EAAA,MAAM,OAAA,GAAwB;AAAA,IAC5B,GAAG,MAAA;AAAA,IACH,MAAA,EAAQ,SAAA;AAAA,IACR,SAAA,EAAW;AAAA,GACb;AACA,EAAA,MAAM,IAAA,GAAO,MAAM,KAAA,EAAM;AACzB,EAAA,IAAA,CAAK,GAAG,CAAA,GAAI,OAAA;AACZ,EAAA,OAAO,EAAE,MAAM,OAAA,EAAQ;AACzB;AAOO,SAAS,UAAA,CACd,OACA,EAAA,EAC4C;AAC5C,EAAA,MAAM,OAAO,KAAA,CAAM,MAAA,CA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,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,CAAK,MAAA,KAAW,MAAM,MAAA,EAAO;AACvD","file":"chunk-TGG26XMK.js","sourcesContent":["/**\n * Pure queue-lifecycle ops over `QueueItem<I>[]` — the BLESSED delegation\n * surface for this package.\n *\n * Each op is `(queue, ...args) => { next, result? }`. No I/O, no Date.now\n * indirection beyond a plain call site — the adapter in `./index.ts` injects\n * `Store<QueueItem<I>[]>` and orchestrates `load → mutate → save`.\n *\n * Substrate-agnostic by construction: nothing here references chrome.storage,\n * Cloudflare, or any concrete persistence layer. The audit-specific shape\n * (journeyId, projectId, ...) is lifted into the caller's `I` parameter.\n *\n * Importable two ways. The `createQueue(...)` adapter in `./index.ts` binds\n * these ops to a `Store` for in-process use (same one-shape-per-package rule\n * as `@demlik/tea/do`). L2 compositions that own their own Model slice\n * (`monitored-run`, `idempotent-intake`, …) instead reach these ops directly\n * via the `@demlik/tea/work-queue/ops` subpath, so a status flip is delegated\n * here rather than re-rolled per call site.\n */\n\nimport type { QueueItem } from \"./index\";\n\n/** Append a new pending item. Returns the new queue and the created item. */\nexport function enqueueOp<I>(\n queue: readonly QueueItem<I>[],\n input: I,\n now: number,\n id: string,\n): { next: QueueItem<I>[]; item: QueueItem<I> } {\n const item: QueueItem<I> = {\n id,\n status: \"pending\",\n input,\n enqueuedAt: now,\n };\n return { next: [...queue, item], item };\n}\n\n/**\n * Claim the first pending item by flipping it to `running` and stamping\n * `startedAt`. Returns the new queue and the claimed item, or `null` if no\n * pending item exists.\n */\nexport function claimNextOp<I>(\n queue: readonly QueueItem<I>[],\n now: number,\n): { next: QueueItem<I>[]; claimed: QueueItem<I> } | null {\n const idx = queue.findIndex((i) => i.status === \"pending\");\n const target = idx === -1 ? undefined : queue[idx];\n // `target === undefined` collapses \"no pending item\" and the (impossible\n // post-`findIndex`) hole into one early-out, so the element is typed\n // `QueueItem<I>` below without a non-null assertion.\n if (target === undefined) return null;\n const claimed: QueueItem<I> = {\n ...target,\n status: \"running\",\n startedAt: now,\n };\n const next = queue.slice();\n next[idx] = claimed;\n return { next, claimed };\n}\n\n/**\n * Done items leave the queue — completed runs live wherever the caller\n * persists their output. Returns the new queue (or the original reference if\n * no item matched, so the adapter can skip a save).\n */\nexport function markDoneOp<I>(\n queue: readonly QueueItem<I>[],\n id: string,\n): { next: QueueItem<I>[]; changed: boolean } {\n const next = queue.filter((i) => i.id !== id);\n return { next, changed: next.length !== queue.length };\n}\n\n/**\n * Generic single-item status transition. Used by `markFailed`,\n * `markCancelled`, `retryItem`, `bindOutput`. The patch closure receives the\n * matched item and returns its replacement; returning the same reference is\n * fine (the adapter only saves on `changed`).\n */\nexport function patchItemOp<I>(\n queue: readonly QueueItem<I>[],\n id: string,\n patch: (item: QueueItem<I>) => QueueItem<I>,\n): { next: QueueItem<I>[]; changed: boolean } {\n const idx = queue.findIndex((i) => i.id === id);\n const target = idx === -1 ? undefined : queue[idx];\n // `target === undefined` collapses the no-match case and the (impossible\n // post-`findIndex`) hole, narrowing `target` to `QueueItem<I>` for `patch`\n // without a non-null assertion.\n if (target === undefined) return { next: queue.slice(), changed: false };\n const next = queue.slice();\n next[idx] = patch(target);\n return { next, changed: true };\n}\n\n/** Reset every `running` item back to `pending`, clearing `startedAt`. */\nexport function resetRunningOp<I>(queue: readonly QueueItem<I>[]): {\n next: QueueItem<I>[];\n changed: boolean;\n} {\n let changed = false;\n const next = queue.map((i): QueueItem<I> => {\n if (i.status !== \"running\") return i;\n changed = true;\n return { ...i, status: \"pending\", startedAt: undefined };\n });\n return { next, changed };\n}\n\n/** Hard-delete an item regardless of status. */\nexport function removeOp<I>(\n queue: readonly QueueItem<I>[],\n id: string,\n): { next: QueueItem<I>[]; changed: boolean } {\n const next = queue.filter((i) => i.id !== id);\n return { next, changed: next.length !== queue.length };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/fan-out/index.ts"],"names":[],"mappings":";;;AAoMA,SAAS,aAAa,WAAA,EAA6B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ACzD,IAAA,IAAI,MAAA,CAAO,SAAS,MAAA,IAAa,CAAC,SAAS,MAAA,IAAU,UAAA,CAAW,QAAQ,CAAA,EAAG;AACzE,MAAA,MAAM,OAAA,GAAU,QAAA,CAAS,IAAA,CACtB,KAAA,CAAM,QAAA,CAAS,YAAY,CAAA,CAC3B,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM,CAAA;AACtB,MAAA,MAAM,IAAA,GAA0B,EAAE,GAAG,QAAA,EAAU,QAAQ,IAAA,EAAK;AAC5D,MAAA,OAAO,CAAC,MAAM,CAAC,GAAG,YAAY,MAAA,CAAO,IAAA,CAAK,OAAO,CAAC,CAAC,CAAA;AAAA,IACrD;AACA,IAAA,OAAO,CAAC,UAAU,UAAU,CAAA;AAAA,EAC9B;AAaA,EAAA,SAAS,SAAS,KAAA,EAAuB;AACvC,IAAA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOL,cAAA,CACE,MACA,KAAA,EACM;AACN,QAAA,IAAI,CAAC,UAAA,CAAW,KAAK,CAAA,EAAG;AACxB,QAAA,IAAA;AAAA,UACE,KAAA,CAAM,QAAA;AAAA,UACN,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,KAAA,CAAM,YAAY,EAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM;AAAA,SAC1D;AAAA,MACF;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,UAAA;AAAA,IACN,OAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-UV6UWGEO.js","sourcesContent":["/**\n * @demlik/tea/fan-out — scatter-gather over a bounded-concurrency work list.\n *\n * The Level-2 combinator that fans a batch of items out across at most\n * `concurrency` in-flight effects, gathers each item's result (or error), and\n * — once every item has settled — fires an optional `join` over the collected\n * results. It is the \"map a list through an effect, but never run more than N\n * at once\" knob.\n *\n * The recipe (which bricks it composes):\n * - `../work-queue` — fan-out's tracked items ARE work-queue items. Each\n * item carries the same `{ id, status, input }` lifecycle vocabulary\n * (`pending → running → done | failed`). The slice this knob owns is four\n * partitions over that one lifecycle, so the work-queue's status taxonomy\n * is the substrate rather than a parallel invention. We reuse its\n * `QueueItem<I>` / `QueueItemStatus` TYPES and delegate the ledger\n * transitions to its BLESSED pure ops (`@demlik/tea/work-queue/ops`):\n * `scatter` mints each pending record with `enqueueOp`, and `launchUpTo`\n * flips `pending → running` with `claimNextOp` (one positional claim per\n * launch). The lone exception is `settleOne`'s `running → done|failed`\n * flip — it must match \"first id-match that is still `running`\" to settle\n * exactly one of a DUPLICATE id, a status predicate the ops surface can't\n * express, so fan-out owns that one index (see `settleOne`). The async\n * `createQueue(store)` adapter is NOT used here because its `load → mutate\n * → save` reads the clock and lives at an I/O boundary, while a combinator's\n * verbs must be pure (invariant 2) — fan-out reaches the underlying ops\n * directly instead, the same route `monitored-run` / `idempotent-intake`\n * take. The slice lives in the Model instead — durable + replayable, the\n * two non-negotiables every knob preserves.\n *\n * Typical wiring (combinator form — splice the hooks into your machine):\n *\n * const fan = createFanOut<Url, Report>({\n * concurrency: 4,\n * idOf: (url) => url, // stable, pure identity\n * of: (url) => ({ type: \"crawl\", url }), // the per-item effect, as data\n * join: (results) => ({ type: \"report_done\", results }),\n * });\n *\n * // in `update`:\n * start_crawl: (s, m) => { const [fanOut, cmds] = fan.scatter(s.fanOut, m.urls);\n * return [{ ...s, fanOut }, cmds]; },\n * crawl_ok: (s, m) => { const [fanOut, cmds] = fan.itemOk(s.fanOut, m.id, m.report);\n * return [{ ...s, fanOut }, cmds]; },\n * crawl_err: (s, m) => { const [fanOut, cmds] = fan.itemErr(s.fanOut, m.id, m.error);\n * return [{ ...s, fanOut }, cmds]; },\n *\n * Every verb is PURE: it returns a NEW slice plus the Cmds to perform (the\n * `of(item)` effects for newly-launched items, and at most one `join` Cmd when\n * the batch completes). The reducer never reads a clock or RNG — item identity\n * is supplied by the caller's `idOf` so `scatter` is deterministic, and the\n * launch effects are plain data the runtime performs (invariant 3).\n *\n * `handlers(ports)` is the I/O splice: it wires the runtime side that actually\n * runs each launched `of(item)` Cmd. Because `of` already produces a fully\n * caller-defined Cmd, fan-out does NOT own the interpret handler for it — the\n * consumer's own `interpret` performs the effect and routes Ok/Err back to the\n * `itemOk` / `itemErr` verbs (the same shape resilient-fetch uses with\n * `tryInterpret`). `handlers` therefore exposes the one piece fan-out CAN\n * pre-wire generically: emitting the gathered batch onto a typed Port when the\n * batch completes, for consumers that observe completion out-of-band rather\n * than through the `join` Cmd.\n *\n * NOT a substrate primitive: it depends only on `../work-queue`'s pure types +\n * blessed ops and `../index`'s `Cmd` / `Port` types. Consumers reach it via the\n * `@demlik/tea/fan-out` subpath.\n */\n\nimport type { Cmd, Port } from \"../index\";\nimport type { QueueItem, QueueItemStatus } from \"../work-queue\";\nimport { queueAdapter } from \"../work-queue/adapter\";\n\n/**\n * One settled-OK item: the original `input` and the `result` its effect\n * produced. Mirrors the spec slice's `done: {item, result}[]` — `item` is the\n * caller's input value (not the internal `QueueItem` envelope), so a consumer\n * reading `done` gets back exactly what it scattered.\n */\nexport interface FanOutDone<I, R> {\n /** The original scattered input value. */\n readonly item: I;\n /** The result the item's effect produced, routed in via `itemOk`. */\n readonly result: R;\n}\n\n/**\n * One settled-error item: the original `input` and the `error` its effect\n * surfaced. `error` is `unknown` — fan-out carries it forward verbatim (an\n * `Error`, a tagged result, a string) for the consumer's reducer to read,\n * never interpreting it (same discipline as `retry-backoff`'s `lastError`).\n */\nexport interface FanOutFailed<I> {\n /** The original scattered input value. */\n readonly item: I;\n /** The error the item's effect surfaced, routed in via `itemErr`. Carried, never interpreted. */\n readonly error: unknown;\n}\n\n/**\n * The slice this knob owns — four partitions over the work-queue item\n * lifecycle, plus the work-queue records the verbs thread the lifecycle\n * through.\n *\n * Why both the spec's four arrays AND `items`:\n * - The four arrays (`pending` / `running` / `done` / `failed`) are the\n * SPEC's public read surface — what a consumer's view renders and what\n * `isComplete` reads. They hold caller-facing values (`I`, or\n * `FanOutDone` / `FanOutFailed`), not the internal id-bearing envelope.\n * - `items` is the work-queue ledger: one `QueueItem<I>` per scattered item,\n * carrying the stable `id` (from `config.idOf`) that `itemOk` / `itemErr`\n * address and the `status` that decides launch-eligibility. It is the\n * single source of truth; the four arrays are a derived projection kept in\n * lockstep so consumers never re-scan `items` to render a partition.\n *\n * Every field is `readonly` and the whole slice is JSON-serializable (plain\n * arrays + the work-queue's plain `QueueItem` records), so it round-trips\n * through a consumer's `Store<S>` unchanged — durable across DO eviction.\n */\nexport interface FanOutState<I, R> {\n /** Items accepted but not yet launched (queue back-pressure beyond `concurrency`). */\n readonly pending: readonly I[];\n /** Items whose `of(item)` effect is in flight (size never exceeds `concurrency`). */\n readonly running: readonly I[];\n /** Items whose effect resolved OK, with the result it produced. */\n readonly done: readonly FanOutDone<I, R>[];\n /** Items whose effect failed, with the error it surfaced. */\n readonly failed: readonly FanOutFailed<I>[];\n /**\n * The work-queue ledger: one record per scattered item, keyed by the\n * caller's `idOf`. The single source of truth the four arrays project from.\n */\n readonly items: readonly QueueItem<I>[];\n /**\n * Index into `done` where the CURRENT wave's OK results begin. `done` is\n * append-only and accumulates across every wave (so a consumer reading\n * `done` sees the full history), but `join` must fold only the wave that\n * just drained — not the cumulative total. A wave opens when `scatter`\n * enqueues into a slice with nothing in flight; this marks `done.length` at\n * that moment so `join` receives exactly `done.slice(waveDoneFrom)`.\n */\n readonly waveDoneFrom: number;\n /**\n * Index into `failed` where the current wave's failures begin. Symmetric to\n * `waveDoneFrom` — the wave boundary over the failure partition. Carried for\n * a consumer that wants to read only the current wave's failures; `join`\n * itself folds only OK results.\n */\n readonly waveFailedFrom: number;\n /**\n * Whether the current wave has already fired its `join`. `join` fires at most\n * once per wave — set `true` at the completion edge so a stale settle that\n * re-reaches `isComplete` cannot re-fire it. A new `scatter` that opens a wave\n * resets it to `false`.\n */\n readonly joined: boolean;\n}\n\n/**\n * The knob. `concurrency` caps how many `of(item)` effects are in flight at\n * once; `idOf` mints a stable, PURE identity per item (so `scatter` is\n * deterministic and `itemOk` / `itemErr` can address an item by id); `of`\n * turns an item into the launch Cmd; `join` (optional) turns the gathered\n * results into a single completion Cmd fired exactly once when every item has\n * settled.\n *\n * Field optionality follows the resilient-call rule — omit `join`, omit the\n * completion Cmd (a consumer that observes `isComplete` itself, or wires the\n * `handlers` Port, doesn't need one).\n */\nexport interface FanOutConfig<I, R, C extends Cmd, J extends Cmd> {\n /** Max in-flight `of(item)` effects. Clamped to `>= 1` (a 0/negative cap would deadlock). */\n readonly concurrency: number;\n /**\n * Stable, deterministic identity for an item. PURE — no clock, no RNG. The\n * id is what `itemOk` / `itemErr` address, so it must survive a round-trip\n * through the durable slice and match across the launch → settle gap. For\n * value-unique inputs (URLs, ids) this is often the identity function; for\n * structural inputs, a content hash or a caller-assigned key.\n */\n readonly idOf: (item: I) => string;\n /** The per-item effect, as data. Performed by the consumer's own `interpret`. */\n readonly of: (item: I) => C;\n /**\n * Optional: fold the gathered done-results into a single completion Cmd,\n * fired exactly once at the transition that empties `pending` + `running`.\n * Omit to drive completion off `isComplete` (or the `handlers` Port) instead.\n */\n readonly join?: (results: readonly R[]) => J;\n}\n\n/**\n * Clamp the configured concurrency to a usable launch budget. A cap of 0 or\n * negative would launch nothing and the batch would deadlock with items stuck\n * `pending` forever; clamping to 1 degrades gracefully to fully-serial\n * fan-out (still correct, just no parallelism) rather than hanging.\n */\nfunction launchBudget(concurrency: number): number {\n return concurrency < 1 ? 1 : Math.floor(concurrency);\n}\n\n/** The starting slice: nothing scattered yet. */\nexport function initFanOut<I, R>(): FanOutState<I, R> {\n return {\n pending: [],\n running: [],\n done: [],\n failed: [],\n items: [],\n waveDoneFrom: 0,\n waveFailedFrom: 0,\n joined: false,\n };\n}\n\n/**\n * Whether every scattered item has settled (no `pending`, no `running`).\n * Derived — reads the slice, never mutates. The verbs use it to decide when to\n * fire `join`; consumers can read it directly to branch their own phase.\n *\n * An empty fan-out (nothing ever scattered) is NOT complete: completion is \"a\n * non-empty batch fully drained,\" so `isComplete(initFanOut())` is `false` and\n * a `scatter([])` of zero items also reads `false` (there was no batch to\n * complete). This keeps `join` from firing on a degenerate empty scatter.\n */\nexport function isComplete<I, R>(state: FanOutState<I, R>): boolean {\n if (state.items.length === 0) return false;\n return state.pending.length === 0 && state.running.length === 0;\n}\n\n/**\n * Count of items currently in flight. `running.length`, named for the launch\n * arithmetic below (and readable at a call site).\n */\nfunction inFlight<I, R>(state: FanOutState<I, R>): number {\n return state.running.length;\n}\n\n/**\n * Move up to `budget - inFlight` items from `pending` to `running`, emitting\n * `of(item)` for each launched item. PURE — returns the new slice and the\n * launch Cmds. The work-queue `items` ledger flips each launched item's status\n * `pending → running` via the BLESSED `claimNextOp`, in lockstep with the\n * projected arrays.\n *\n * Delegation, not re-rolling: each launch is one `claimNextOp` call — the same\n * `pending → running` transition `@demlik/tea/work-queue` owns. `claimNextOp`\n * flips the FIRST pending ledger record positionally, and fan-out's `pending`\n * array is appended in lockstep with the ledger, so the first `slots` pending\n * inputs map to the first `slots` pending records — claiming one-per-launch\n * settles exactly those. This also makes a DUPLICATE id correct: a positional\n * claim flips ONE record per launch, where a blanket id-set flip would promote\n * every pending record sharing the launched id (over-flipping the ledger past\n * `running.length`). The `at` stamp is `0` — fan-out's verbs are pure and never\n * read a clock; positional order, not the timestamp, drives every decision\n * (same convention as `scatter`'s `enqueuedAt: 0`).\n *\n * Shared by `scatter` (launch on enqueue) and `itemOk` / `itemErr` (launch the\n * next pending item as a slot frees). Factoring it here keeps the concurrency\n * invariant — `running.length <= budget` — in ONE place.\n */\nfunction launchUpTo<I, R, C extends Cmd>(\n state: FanOutState<I, R>,\n config: {\n concurrency: number;\n idOf: (item: I) => string;\n of: (item: I) => C;\n },\n): readonly [FanOutState<I, R>, readonly C[]] {\n const budget = launchBudget(config.concurrency);\n const slots = budget - inFlight(state);\n if (slots <= 0 || state.pending.length === 0) return [state, []];\n\n const toLaunch = state.pending.slice(0, slots);\n const stillPending = state.pending.slice(slots);\n\n // Flip the ledger records `pending → running` one launch at a time via the\n // `QueueAdapter` (positional first-pending claim per call).\n const queue = queueAdapter<I>();\n let items: readonly QueueItem<I>[] = state.items;\n for (let i = 0; i < toLaunch.length; i++) {\n const claimed = queue.claim(items, 0);\n if (claimed === null) break;\n items = claimed.next;\n }\n\n const next: FanOutState<I, R> = {\n ...state,\n pending: stillPending,\n running: [...state.running, ...toLaunch],\n items,\n };\n const cmds = toLaunch.map((item) => config.of(item));\n return [next, cmds];\n}\n\n/**\n * Settle EXACTLY ONE running entry for `id`: remove the first `running` item\n * whose `idOf` matches, and flip the first ledger record for `id` that is still\n * `running` to `status`. Returns the input that was settled plus the new\n * `running` / `items` arrays, or `undefined` if no running item carries that id\n * (a stale / unknown settle Msg → caller treats as a no-op rather than a crash).\n *\n * Why \"exactly one\": when two scattered items share an `idOf` (a duplicate id),\n * the ledger holds two `running` records under the same id and `running` holds\n * two inputs. A settle Msg carries one result, so it must close out exactly one\n * of them — not all matches. A blanket `filter((x) => idOf(x) !== id)` would\n * drop BOTH running entries while recording only ONE result, silently losing a\n * unit of work and corrupting the done/failed partition. find-index + splice\n * removes a single `running` entry; the matching `findIndex` over the ledger\n * flips a single record. The OTHER duplicate stays `running`, awaiting its own\n * settle Msg.\n *\n * This flip is NOT delegated to `patchItemOp`: the blessed op matches the FIRST\n * record by id, but the record fan-out must flip is \"first id-match that is\n * still `running`\" — and after a dup-id's first settle the first id-match is\n * the already-terminal record. The status predicate is load-bearing here and\n * the ops surface can't express it, so fan-out owns this one index. The flipped\n * record is still built the work-queue way (spread + new `status`), and there\n * is no `as` cast: `status` arrives already typed `QueueItemStatus`.\n */\nfunction settleOne<I, R>(\n state: FanOutState<I, R>,\n id: string,\n status: QueueItemStatus,\n idOf: (item: I) => string,\n):\n | { input: I; running: readonly I[]; items: readonly QueueItem<I>[] }\n | undefined {\n const runIdx = state.running.findIndex((item) => idOf(item) === id);\n const input = runIdx === -1 ? undefined : state.running[runIdx];\n // `input === undefined` collapses \"no running entry for this id\" and the\n // (impossible post-`findIndex`) hole into one early-out, narrowing `input`\n // to `I` below without a non-null assertion (the pattern `ops.ts` uses).\n if (input === undefined) return undefined;\n\n const running = [\n ...state.running.slice(0, runIdx),\n ...state.running.slice(runIdx + 1),\n ];\n\n const ledgerIdx = state.items.findIndex(\n (item) => item.id === id && item.status === \"running\",\n );\n const ledger = ledgerIdx === -1 ? undefined : state.items[ledgerIdx];\n // Same early-out: `ledger === undefined` narrows the record to `QueueItem<I>`\n // for the spread below without a non-null assertion.\n const items =\n ledger === undefined\n ? state.items\n : [\n ...state.items.slice(0, ledgerIdx),\n { ...ledger, status },\n ...state.items.slice(ledgerIdx + 1),\n ];\n\n return { input, running, items };\n}\n\n/**\n * Optional Port for observing batch completion out-of-band. When a consumer\n * passes `handlers(ports)` a `complete` Port, the runtime side can emit the\n * gathered results onto it the moment `isComplete` flips true — distinct from\n * the in-band `join` Cmd (which threads back through `update`). Use the Port\n * for \"tell the outside world the batch finished\" without folding a completion\n * signal into the consumer's Msg union.\n */\nexport interface FanOutPorts<R> {\n /** Fires once with every gathered done-result when the batch completes. */\n readonly complete: Port<readonly R[]>;\n}\n\n/**\n * Build the fan-out knob from `config`. Returns the uniform combinator\n * contract: `init` for the owned slice, the three settle verbs + the derived\n * `isComplete`, and `handlers` for the optional out-of-band completion Port.\n *\n * No `subs` — fan-out runs no timers (the spec pins \"Subs: none\"). The\n * per-item effect's lifetime is owned by the consumer's `interpret`, and\n * completion is a pure function of the settle Msgs, so there is nothing\n * continuous to subscribe to.\n */\nexport function createFanOut<I, R, C extends Cmd = Cmd, J extends Cmd = Cmd>(\n config: FanOutConfig<I, R, C, J>,\n) {\n /**\n * Enqueue `items` and launch up to `concurrency` of them. PURE.\n *\n * Each item gets a ledger record (`status: \"pending\"`, its `idOf` id) and is\n * appended to `pending`; `launchUpTo` then promotes as many as the free\n * concurrency budget allows, emitting `of(item)` per launch. The returned\n * Cmds are exactly the launch effects — `scatter` never fires `join` (a batch\n * can't complete on the same transition it starts unless it launches zero\n * effects, which `isComplete`'s empty-batch rule already declines to treat as\n * completion).\n *\n * Each pending ledger record is minted by the blessed `enqueueOp` — the same\n * `pending` append `@demlik/tea/work-queue` owns — rather than re-rolled\n * inline, so the `status: \"pending\"` literal lives in exactly one place (no\n * `as QueueItemStatus` cast here).\n *\n * `enqueuedAt` is stamped `0` rather than read from a clock: fan-out's verbs\n * are pure, and fan-out does not use the timestamp for any decision (ordering\n * is positional via the arrays). A consumer that needs real enqueue times\n * threads them through its own Msg `at` and stores them alongside.\n */\n function scatter(\n state: FanOutState<I, R>,\n items: readonly I[],\n ): readonly [FanOutState<I, R>, readonly C[]] {\n // Append one pending ledger record per item via the `QueueAdapter`.\n // `queue.enqueue` returns `status: \"pending\"` already typed — no cast — and\n // the lifecycle's \"new work is pending\" rule stays in work-queue's hands.\n const queue = queueAdapter<I>();\n let ledger: readonly QueueItem<I>[] = state.items;\n for (const input of items) {\n ledger = queue.enqueue(ledger, input, 0, config.idOf(input)).next;\n }\n // A scatter OPENS A FRESH WAVE when nothing is in flight — either the very\n // first scatter, or a re-scatter after the previous wave fully drained. The\n // wave boundary advances to the current `done` / `failed` length so `join`\n // folds only THIS wave's results, never the cumulative history, and\n // `joined` resets so the new wave can fire its own `join` exactly once.\n //\n // A scatter that adds to a wave still in flight (pending or running\n // non-empty — e.g. enqueuing more work mid-batch) does NOT open a wave:\n // those items join the current wave and settle under its single `join`.\n const opensWave = state.pending.length === 0 && state.running.length === 0;\n\n const enqueued: FanOutState<I, R> = {\n ...state,\n pending: [...state.pending, ...items],\n items: ledger,\n ...(opensWave\n ? {\n waveDoneFrom: state.done.length,\n waveFailedFrom: state.failed.length,\n joined: false,\n }\n : {}),\n };\n return launchUpTo(enqueued, config);\n }\n\n /**\n * Record `id`'s effect as succeeded with `result`, then launch the next\n * pending item to backfill the freed slot. PURE.\n *\n * Moves the item out of `running` into `done` (carrying the original input +\n * its result), flips its ledger record `running → done`, and runs\n * `launchUpTo` to keep the pipeline full. If this transition empties both\n * `pending` and `running` AND a `join` is configured, the returned Cmds also\n * include the single `join(results)` Cmd — fired exactly once at the\n * completion edge.\n *\n * A settle for an unknown / already-settled `id` is a no-op (returns the\n * slice unchanged, no Cmds): the runtime's serial dispatch makes a true\n * double-settle impossible, but a stale Msg after a boot/replay is real, and\n * swallowing it is the safe direction (the result is already recorded).\n */\n function itemOk(\n state: FanOutState<I, R>,\n id: string,\n result: R,\n ): readonly [FanOutState<I, R>, readonly (C | J)[]] {\n const settled = settleOne(state, id, \"done\", config.idOf);\n if (settled === undefined) return [state, []];\n\n const next: FanOutState<I, R> = {\n ...state,\n running: settled.running,\n done: [...state.done, { item: settled.input, result }],\n items: settled.items,\n };\n return finishOrLaunch(next);\n }\n\n /**\n * Record `id`'s effect as failed with `error`, then launch the next pending\n * item to backfill the freed slot. PURE.\n *\n * Symmetric to `itemOk`: moves the item out of `running` into `failed`\n * (carrying the original input + the error), flips its ledger record\n * `running → failed`, backfills via `launchUpTo`, and fires `join` at the\n * completion edge if configured. A failed item still counts toward completion\n * — the batch is \"done\" when every item has settled, success or failure;\n * `join` receives only the OK results (failures are read off `failed`).\n *\n * Same unknown-`id` no-op contract as `itemOk`.\n */\n function itemErr(\n state: FanOutState<I, R>,\n id: string,\n error: unknown,\n ): readonly [FanOutState<I, R>, readonly (C | J)[]] {\n const settled = settleOne(state, id, \"failed\", config.idOf);\n if (settled === undefined) return [state, []];\n\n const next: FanOutState<I, R> = {\n ...state,\n running: settled.running,\n failed: [...state.failed, { item: settled.input, error }],\n items: settled.items,\n };\n return finishOrLaunch(next);\n }\n\n /**\n * Shared tail of `itemOk` / `itemErr`: backfill the freed slot, then — if the\n * CURRENT wave is now complete, a `join` is configured, and this wave has not\n * already joined — append the single completion Cmd and mark the wave joined.\n *\n * Two guards keep `join` firing exactly once per wave:\n * - `isComplete(next)` is the completion edge (the transition that drains\n * the last in-flight item; `launchUpTo` cannot re-fill from an empty\n * `pending`, so `running` stays empty and the edge is reached once).\n * - `!next.joined` makes it idempotent even if a stale settle re-reaches a\n * completed slice, and — critically — combined with the per-wave reset in\n * `scatter` it stops `join` re-firing across waves. Without the wave\n * boundary, `done` is append-only, so a SECOND wave draining would see\n * `isComplete` true and re-fold the WHOLE cumulative `done` (wave 1 +\n * wave 2). The fix folds only `done.slice(waveDoneFrom)` — exactly the\n * results this wave produced.\n */\n function finishOrLaunch(\n settled: FanOutState<I, R>,\n ): readonly [FanOutState<I, R>, readonly (C | J)[]] {\n const [launched, launchCmds] = launchUpTo(settled, config);\n if (config.join !== undefined && !launched.joined && isComplete(launched)) {\n const results = launched.done\n .slice(launched.waveDoneFrom)\n .map((d) => d.result);\n const next: FanOutState<I, R> = { ...launched, joined: true };\n return [next, [...launchCmds, config.join(results)]];\n }\n return [launched, launchCmds];\n }\n\n /**\n * The out-of-band completion splice. Returns an observer-shaped function the\n * consumer calls after every settle: when the batch has just completed it\n * emits the gathered results onto `ports.complete`. This is the Port-side\n * analogue of the `join` Cmd — use it when completion should leave the\n * runtime as a typed signal rather than re-enter `update`.\n *\n * Returns the emit-on-complete callback so the consumer wires it into its own\n * runtime `observe` (e.g. `runtime.observe((_, s) => emit(s.fanOut))`); fan-out\n * stays out of the dispatch loop, matching `historyTracker`'s discipline.\n */\n function handlers(ports: FanOutPorts<R>) {\n return {\n /**\n * Emit the gathered done-results onto `ports.complete` iff `state` is a\n * just-completed batch. Idempotency is the caller's concern (call it once\n * per transition via `observe`); emitting to a Port with no subscribers\n * is a no-op at the runtime, so an extra call is harmless.\n */\n emitOnComplete(\n emit: <T>(port: Port<T>, value: T) => void,\n state: FanOutState<I, R>,\n ): void {\n if (!isComplete(state)) return;\n emit(\n ports.complete,\n state.done.slice(state.waveDoneFrom).map((d) => d.result),\n );\n },\n };\n }\n\n return {\n init: initFanOut<I, R>,\n scatter,\n itemOk,\n itemErr,\n isComplete,\n handlers,\n };\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,GAAA;AAA+C,KACxD,CAAA;AAAA,EACH;AACA,EAAA,OAAO,MAAA;AACT;AAgBA,SAAS,aAAmB,KAAA,EAA4B;AACtD,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,EAAE,IAAA,EAAM,QAAQ,KAAA,EAAO,KAAA,CAAM,MAAA,EAAQ,CAAC,CAAA;AAEhE,EAAA,MAAM,QAAQ,KAAA,CAAM,KAAA;AACpB,EAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAA,EAAA,EAAK;AAC1C,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA;AACxB,IAAA,MAAM,SAAA,GAAY,KAAA,GACd,KAAA,CAAM,CAAC,CAAA,EAAG,KAAA,GACV,CAAA,KAAM,KAAA,CAAM,IAAA,CAAK,MAAA,GAAS,CAAA,GACxB,KAAA,CAAM,UAAA,GACN,IAAA;AACN,IAAA,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,EAAE,IAAA,EAAM,QAAQ,GAAA,EAAK,KAAA,EAAO,SAAA,EAAW,CAAC,CAAA;AAAA,EACpE;AACA,EAAA,OAAO,KAAA,CAAM,KAAK,IAAI,CAAA;AACxB","file":"chunk-UYWUVEP6.js","sourcesContent":["// ---------------------------------------------------------------------------\n// recorder — capture a Runtime's Msg sequence for later replay.\n//\n// `historyTracker` (in ../index) is the exemplar: a BOUNDED, in-memory ring\n// buffer over `runtime.observe`. The recorder is its UNBOUNDED, SERIALIZABLE\n// cousin. Where historyTracker exists to answer \"what were the last N\n// transitions?\", the recorder exists to answer \"reproduce this entire run\n// locally against the current reducer.\"\n//\n// The killer feature this enables: record a prod Msg sequence, dump it as\n// JSONL, ship the file home, and feed it to `../trace-replay`'s `replayTrace`\n// — which folds the SAME msgs through `replay(machine, ...)` and diffs the\n// resulting state against the recorded final state. If they diverge, the\n// reducer changed behavior for that input. Regression-as-a-trace.\n//\n// What `replay` needs to reproduce a run (see `replay` in ../index):\n// - `loaded` — the value `init` was booted with. Captured at the boot\n// observe, where `msg === null` and `state` is the post-init\n// initial state. (We capture the post-init state, not the raw\n// storage value, because replay re-runs `init(loaded, ctx)`\n// itself — and for a faithful re-run we feed it that initial\n// state as `loaded` so `init` returns `[loaded, []]`. This is\n// the rehydrate path, which the substrate guarantees is a pure\n// passthrough; see Invariant 2.)\n// - `msgs` — every non-null msg, in dispatch order.\n// - `ctx` — NOT captured here. Ctx is host wiring (sibling runtimes,\n// clients), supplied fresh at replay time. The trace is the\n// INPUT (loaded + msgs); ctx is the ENVIRONMENT.\n//\n// This module OWNS the `Trace` type. `../trace-replay` imports it.\n// ---------------------------------------------------------------------------\n\nimport type { BootingRuntime } from \"../index\";\n\n/**\n * A recorded run, sufficient to reproduce it via `../trace-replay`.\n *\n * The recorder OWNS this type; `../trace-replay` imports it. It is the wire\n * contract between the two halves of the record/replay feature.\n *\n * @typeParam S - the machine's State type.\n * @typeParam M - the machine's Msg union.\n */\nexport interface Trace<S, M> {\n /**\n * The initial state captured at the boot observe (the transition where\n * `msg === null`). Fed back to replay as `loaded` so `init(loaded, ctx)`\n * reproduces the exact starting point. `null` only if the recorder attached\n * AFTER boot (it missed the boot observe) — replay then re-runs fresh `init`.\n */\n loaded: S | null;\n /** The ordered, non-null msgs as observed. The replay input sequence. */\n msgs: readonly M[];\n /**\n * The last observed state. The oracle: `replayTrace` deep-compares its\n * recomputed final state against this. Equal ⇒ the reducer still produces\n * the same result for this input.\n */\n finalState: S;\n /**\n * Per-transition `(msg, post-state)` pairs, in dispatch order, for human\n * inspection (e.g. \"show me the state after step 3\"). When present, there\n * is exactly one entry per recorded msg and `state` is the POST-transition\n * state for that msg (so `steps[i].msg === msgs[i]` and `steps.at(-1).state`\n * deep-equals `finalState`). NOT required for replay — replay only needs\n * `loaded` + `msgs` + `finalState`.\n *\n * Present iff the recorder was created with `captureSteps: true`, OR the\n * Trace was re-hydrated from JSONL via {@link parseJSONL} (the JSONL format\n * carries per-step state, so the parser populates `steps` whenever a step\n * line had a non-null state). A trace dumped with `captureSteps: false` has\n * `steps === undefined`.\n */\n steps?: readonly { msg: M; state: S }[];\n}\n\n/** Options for {@link recorder}. */\nexport interface RecorderOptions {\n /**\n * Fraction of msgs to record, in `(0, 1]`. Default `1` (record everything).\n *\n * IMPORTANT — sampling breaks replay fidelity. A sampled trace DROPS msgs,\n * so its `msgs` array is no longer the complete input sequence and\n * `replayTrace` will NOT reproduce `finalState`. Sampling exists for\n * VOLUME STATISTICS (how much traffic, msg-type distribution), not for\n * faithful replay. Use the default `1` for any trace you intend to replay.\n *\n * The boot observe (`msg === null`) is ALWAYS recorded regardless of\n * `sampleRate` — `loaded` and `finalState` are anchors, not samples.\n */\n sampleRate?: number;\n /**\n * When `true`, retain a per-transition `(msg, post-state)` pair in\n * {@link Trace.steps} for EVERY recorded transition. Default `false`.\n *\n * Size vs. fidelity — the precise trade-off:\n *\n * - `captureSteps: false` (default) — the MINIMAL replay-faithful trace.\n * The recorder keeps `loaded` (boot state), the ordered `msgs`, and\n * `finalState`. That is exactly what `../trace-replay` needs to refold\n * the run and diff the result. Memory is O(msgs) — one msg ref each, no\n * per-step state snapshot. `dump().steps` is `undefined`; in JSONL,\n * interior step lines carry `state: null` (the post-states were never\n * retained) and only the LAST step line carries `finalState`. A trace\n * dumped this way REPLAYS correctly but cannot answer \"what was the\n * state after step 3?\".\n *\n * - `captureSteps: true` — the FULL-fidelity trace. The recorder also\n * snapshots the post-transition state for every msg, so `dump().steps`\n * holds `{ msg, state }` for every transition (post-state) and\n * `toJSONL()` emits a non-null `state` on every step line. Memory is\n * O(msgs × |state|) — a state ref per transition (refs, not deep\n * copies; TEA states are conventionally immutable, so the runtime's\n * post-transition state object is retained by reference). This is the\n * mode for per-step inspection and for a JSONL file that round-trips\n * `steps` exactly via {@link parseJSONL}.\n *\n * Replay fidelity is identical in both modes — `../trace-replay` reads\n * `loaded` + `msgs` + `finalState` only and never touches `steps`. The\n * choice is purely \"do I also want to inspect intermediate states?\".\n */\n captureSteps?: boolean;\n}\n\n/**\n * A live recorder attached to a Runtime. Mirrors `historyTracker`'s\n * stop/snapshot semantics: `dump()` works at any time (including after\n * `stop()`), `stop()` is idempotent and detaches the observer.\n *\n * @typeParam S - the machine's State type.\n * @typeParam M - the machine's Msg union.\n */\nexport interface Recorder<S, M> {\n /**\n * Snapshot the recording so far as a {@link Trace}. Returns a fresh object\n * with copied arrays on every call (callers may slice/replay without\n * affecting the recorder's buffers). Entry values are references to the\n * originals (TEA states/msgs are conventionally immutable).\n *\n * Throws only if called before the boot observe has fired AND no msgs have\n * been recorded — i.e. there is no `finalState` yet. In practice callers\n * `await runtime.ready` before `dump()`, after which boot has fired.\n */\n dump(): Trace<S, M>;\n /**\n * Serialize the recording as JSONL (one JSON object per line) — a streamable\n * format that appends cleanly and survives truncation (a partial tail line\n * is the only loss). The first line is the boot header\n * `{ kind: \"boot\", state }`; each subsequent line is\n * `{ kind: \"step\", msg, state }` for one recorded transition.\n *\n * Re-hydrate with {@link parseJSONL}.\n *\n * Round-trip fidelity depends on `captureSteps`:\n * - `captureSteps: true` — every step line carries its non-null\n * post-state, so `parseJSONL(rec.toJSONL())` reconstructs `steps`\n * EXACTLY and deep-equals `rec.dump()` (which also has `steps`). Full\n * per-step fidelity round-trips.\n * - `captureSteps: false` (default) — interior step lines carry\n * `state: null` (those post-states were never retained); only the last\n * step line carries `finalState`. `parseJSONL` then populates `steps`\n * with just the entries that had a non-null state (the final one), so\n * the re-hydrated Trace is NOT deep-equal to `rec.dump()` (which has no\n * `steps`). It is still fully replay-faithful: `loaded`, `msgs`, and\n * `finalState` are intact. Record with `captureSteps: true` if you need\n * interior states to survive the round-trip.\n */\n toJSONL(): string;\n /**\n * Detach the underlying observer. After `stop()`:\n * - no new transitions are recorded;\n * - `dump()` / `toJSONL()` keep working against the buffered contents;\n * - the recorder holds no observer reference into the runtime.\n *\n * Idempotent — subsequent calls are no-ops.\n */\n stop(): void;\n}\n\n/**\n * Attach a recorder to a Runtime. Subscribes via `runtime.observe`, capturing\n * the boot state as `loaded` and every subsequent non-null msg in order.\n *\n * One-line creation, mirroring `historyTracker`:\n *\n * const rec = recorder(runtime);\n * // ... drive the runtime ...\n * await runtime.ready; // boot observe has fired\n * const trace = rec.dump(); // { loaded, msgs, finalState }\n *\n * @param runtime - any `BootingRuntime<S, M>` (a full `Runtime` satisfies it).\n * The recorder uses only `observe`, which is total before boot\n * — so you attach it to the synchronous `run()` handle to\n * capture the boot transition as `loaded`.\n * @param opts - see {@link RecorderOptions}. Default records everything,\n * no step retention.\n */\nexport function recorder<S, M extends { type: string }>(\n runtime: BootingRuntime<S, M>,\n opts?: RecorderOptions,\n): Recorder<S, M> {\n // Clamp sampleRate into (0, 1]. A non-positive or NaN rate would record\n // nothing (and break replay anchors); default it to 1 (record all). Rates\n // above 1 are meaningless — clamp to 1.\n const rawRate = opts?.sampleRate;\n const sampleRate =\n rawRate === undefined || Number.isNaN(rawRate) || rawRate <= 0\n ? 1\n : Math.min(rawRate, 1);\n const captureSteps = opts?.captureSteps ?? false;\n\n // `loaded` is the post-init state captured at the boot observe. `undefined`\n // sentinel = boot not yet seen; resolved to `S | null` in dump() (null when\n // the recorder attached after boot and never observed msg === null).\n let loaded: S | undefined;\n let sawBoot = false;\n // The ordered, recorded msgs. Unbounded (the recorder's whole point vs the\n // bounded historyTracker).\n const msgs: M[] = [];\n // Per-step (msg, state) pairs — only populated when captureSteps is on.\n const steps: { msg: M; state: S }[] = [];\n // The last observed state — boot state until the first step, then advances\n // with every recorded OR dropped transition (finalState must reflect the\n // true latest state even under sampling, so it stays a valid replay oracle\n // for the unsampled case and an honest \"where the run ended\" marker).\n let finalState: S | undefined;\n let stopped = false;\n\n // The boot transition — the post-init initial state the old `observe(msg ===\n // null)` arm captured as `loaded` — now arrives via `onBoot` (#47). Always\n // captured (boot is the replay anchor). It is also the first `finalState`\n // until the first applied transition advances it.\n const unboot = runtime.onBoot((state) => {\n finalState = state;\n loaded = state;\n sawBoot = true;\n });\n\n const unobserve = runtime.observe((msg, state) => {\n // finalState tracks the latest state regardless of sampling — it is the\n // run's endpoint, an anchor, not a sample.\n finalState = state;\n\n // Sampling decision. sampleRate === 1 short-circuits to always-record so\n // the common (faithful) path pays no RNG cost. Math.random() < rate keeps\n // a `rate` fraction in expectation.\n if (sampleRate < 1 && Math.random() >= sampleRate) return;\n\n msgs.push(msg);\n if (captureSteps) steps.push({ msg, state });\n });\n\n return {\n dump(): Trace<S, M> {\n if (finalState === undefined) {\n throw new Error(\n \"@demlik/tea/recorder: dump() called before any transition was observed. \" +\n \"Await `runtime.ready` (boot fires the first observe) before dumping.\",\n );\n }\n return {\n // sawBoot ⇒ `loaded` is the captured boot state; otherwise the\n // recorder attached post-boot and replay must re-run fresh init.\n loaded: sawBoot ? (loaded as S) : null,\n msgs: msgs.slice(),\n finalState,\n // Only attach `steps` when captureSteps was requested — keeps the\n // dumped Trace shape honest about what was retained.\n ...(captureSteps ? { steps: steps.slice() } : {}),\n };\n },\n toJSONL(): string {\n if (finalState === undefined) {\n throw new Error(\n \"@demlik/tea/recorder: toJSONL() called before any transition was observed. \" +\n \"Await `runtime.ready` (boot fires the first observe) before serializing.\",\n );\n }\n // Serialize the live snapshot via the shared Trace→JSONL writer so the\n // recorder and the standalone `traceAttachment` path emit byte-identical\n // wire format. `dump()` resolves the captureSteps logic (steps present\n // iff captureSteps was on); `traceToJSONL` then emits a non-null state\n // on every step line when steps exist, or `null` interior + finalState\n // on the last line when they don't. The replay path never reads step\n // states, so the captureSteps:false null-interiors never affect replay.\n return traceToJSONL(this.dump());\n },\n stop(): void {\n if (stopped) return;\n stopped = true;\n unobserve();\n unboot();\n },\n };\n}\n\n/** One line of the JSONL format produced by {@link Recorder.toJSONL}. */\ntype JsonlLine<S, M> =\n | { kind: \"boot\"; state: S | null }\n | { kind: \"step\"; msg: M; state: S | null };\n\n/**\n * Re-hydrate a {@link Trace} from the JSONL produced by\n * {@link Recorder.toJSONL}. The inverse of `toJSONL`, so\n * `parseJSONL(rec.toJSONL())` deep-equals `rec.dump()`.\n *\n * Parsing rules:\n * - The first non-blank line MUST be the boot header `{ kind: \"boot\", state }`.\n * Its `state` becomes `Trace.loaded`.\n * - Each `{ kind: \"step\", msg, state }` line contributes `msg` to\n * `Trace.msgs` and `(msg, state)` to `Trace.steps`.\n * - `Trace.finalState` is the `state` of the LAST step line, or the boot\n * `state` when there are no steps (a boot-only trace).\n *\n * Blank lines are skipped (tolerant of trailing newlines / hand-edited files).\n * A malformed line, a missing/duplicate boot header, or a step with `null`\n * final state throws — the trace is unusable for replay and silent corruption\n * is worse than a loud parse error (errors are data; surface them).\n *\n * @typeParam S - the machine's State type.\n * @typeParam M - the machine's Msg union.\n */\nexport function parseJSONL<S, M>(jsonl: string): Trace<S, M> {\n const rawLines = jsonl.split(\"\\n\");\n let loaded: S | null = null;\n let sawBoot = false;\n const msgs: M[] = [];\n const steps: { msg: M; state: S }[] = [];\n let finalState: S | null = null;\n let finalKnown = false;\n\n for (const [i, rawLine] of rawLines.entries()) {\n const line = rawLine.trim();\n if (line === \"\") continue; // tolerate blank / trailing-newline lines\n\n let parsed: JsonlLine<S, M>;\n try {\n parsed = JSON.parse(line) as JsonlLine<S, M>;\n } catch (err) {\n throw new Error(\n `@demlik/tea/recorder: parseJSONL failed on line ${i + 1}: not valid JSON. ${String(err)}`,\n );\n }\n\n if (parsed.kind === \"boot\") {\n if (sawBoot) {\n throw new Error(\n `@demlik/tea/recorder: parseJSONL saw a second boot header on line ${i + 1}. ` +\n \"A trace has exactly one boot line.\",\n );\n }\n sawBoot = true;\n loaded = parsed.state;\n // The boot state is the finalState until a step supersedes it (boot-only\n // trace case).\n finalState = parsed.state;\n finalKnown = parsed.state !== null;\n } else if (parsed.kind === \"step\") {\n if (!sawBoot) {\n throw new Error(\n `@demlik/tea/recorder: parseJSONL saw a step line before the boot header on line ${i + 1}.`,\n );\n }\n msgs.push(parsed.msg);\n if (parsed.state !== null) {\n steps.push({ msg: parsed.msg, state: parsed.state });\n finalState = parsed.state;\n finalKnown = true;\n }\n } else {\n throw new Error(\n `@demlik/tea/recorder: parseJSONL saw an unknown line kind on line ${i + 1}: ` +\n JSON.stringify((parsed as { kind?: unknown }).kind),\n );\n }\n }\n\n if (!sawBoot) {\n throw new Error(\n \"@demlik/tea/recorder: parseJSONL found no boot header. A trace must start with \" +\n '{ kind: \"boot\", state }.',\n );\n }\n if (!finalKnown || finalState === null) {\n throw new Error(\n \"@demlik/tea/recorder: parseJSONL could not determine finalState — the boot state \" +\n \"was null and no step carried a non-null state. The trace is unusable for replay.\",\n );\n }\n\n return { loaded, msgs, finalState, steps };\n}\n\n// ---------------------------------------------------------------------------\n// Sentry crash→trace adapters — pure, zero-dependency, Sentry-SHAPED.\n//\n// The killer DevX flow: a machine crashes in prod → its recorded Trace rides\n// along on the Sentry event → one click later you `parseJSONL` it and replay\n// the exact run locally against the (possibly fixed) reducer. These two\n// adapters are the bridge from a `Trace` to the two Sentry surfaces that carry\n// it: an Attachment (the full replayable trace) and Breadcrumbs (a human-\n// readable timeline of the msgs that led to the crash).\n//\n// They take NO dependency on `@sentry/*`. They emit PLAIN OBJECTS whose shapes\n// match Sentry's public `Attachment` and `Breadcrumb` types, and the consumer\n// wires them at their own Sentry boundary (browser or node). This keeps the\n// recorder runnable anywhere a machine runs (a Worker, a Node script, a test)\n// and lets the consumer pin whatever Sentry SDK version they already ship.\n// ---------------------------------------------------------------------------\n\n/**\n * A Sentry-shaped attachment carrying the full {@link Trace} as JSONL. The\n * shape matches Sentry's `Attachment` type so the consumer can hand it\n * straight to `addAttachment(...)` without any adaptation.\n *\n * - `filename` — `\"tea-trace.jsonl\"`. The name Sentry shows in the UI and\n * uses for download; `.jsonl` signals the streamable format.\n * - `data` — the trace serialized via {@link Recorder.toJSONL}'s format\n * (re-hydrate downstream with {@link parseJSONL}).\n * - `contentType` — `\"application/x-ndjson\"`, the standard MIME for\n * newline-delimited JSON.\n */\nexport interface TraceAttachment {\n filename: string;\n data: string;\n contentType: string;\n}\n\n/**\n * Serialize a {@link Trace} into a Sentry-shaped attachment so a crash event\n * carries the full, replayable run. Pure — no Sentry import, no I/O. The\n * returned object matches Sentry's `Attachment` shape exactly.\n *\n * The `data` field is JSONL in the same format {@link Recorder.toJSONL}\n * produces, so the home-side flow is `parseJSONL(attachment.data)` →\n * `replayTrace(machine, trace, ctx)`.\n *\n * Consumer wiring (no Sentry import here — the consumer owns the boundary):\n *\n * ```ts\n * import * as Sentry from \"@sentry/browser\"; // or \"@sentry/node\"\n * import { traceAttachment } from \"@demlik/tea/recorder\";\n * Sentry.getCurrentScope().addAttachment(traceAttachment(rec.dump()));\n * ```\n *\n * @typeParam S - the machine's State type.\n * @typeParam M - the machine's Msg union.\n */\nexport function traceAttachment<S, M extends { type: string }>(\n trace: Trace<S, M>,\n): TraceAttachment {\n return {\n filename: \"tea-trace.jsonl\",\n data: traceToJSONL(trace),\n contentType: \"application/x-ndjson\",\n };\n}\n\n/** A Sentry-shaped breadcrumb. Matches the fields of Sentry's `Breadcrumb`. */\nexport interface TraceBreadcrumb {\n category: string;\n type: string;\n level: string;\n message: string;\n data?: Record<string, unknown>;\n}\n\n/** Options for {@link breadcrumbsFromTrace}. */\nexport interface BreadcrumbsOptions<M> {\n /**\n * Max breadcrumbs to emit. Default `100` (Sentry's own default breadcrumb\n * cap). When the trace has more msgs than `limit`, the OLDEST are dropped —\n * the returned list is the newest-last tail, matching how a Sentry\n * breadcrumb ring buffer behaves (the crash context is the recent past).\n */\n limit?: number;\n /**\n * Customize each breadcrumb's `message`. Default uses `msg.type`. Provide a\n * serializer to surface a richer one-liner (e.g. include an id). The msg is\n * ALSO always attached verbatim under `data.msg` regardless of this option,\n * so the structured payload is never lost to the string rendering.\n */\n serialize?: (msg: M) => string;\n}\n\n/**\n * Project a {@link Trace}'s recorded msgs into Sentry-shaped breadcrumbs — a\n * human-readable timeline of \"what happened before the crash\". Pure — no\n * Sentry import, no I/O. Each returned object matches Sentry's `Breadcrumb`\n * shape, so the consumer can loop and call `addBreadcrumb(...)`.\n *\n * One breadcrumb per recorded msg, in dispatch order (NEWEST LAST — Sentry\n * renders breadcrumbs oldest-first and the crash is the most recent event).\n * Each breadcrumb:\n * - `category` — `\"tea\"` (groups them in the Sentry breadcrumb panel).\n * - `type` — `\"default\"` (the generic Sentry breadcrumb type).\n * - `level` — `\"info\"` (msgs are normal flow; the crash is the event).\n * - `message` — `msg.type`, or `serialize(msg)` when provided.\n * - `data.msg` — the full msg object (structured detail kept verbatim).\n *\n * Capped at `opts.limit` (default 100). When the trace has more msgs than the\n * cap, the OLDEST are dropped and the newest `limit` are kept — the recent\n * lead-up to the crash is the useful context.\n *\n * Consumer wiring (no Sentry import here — the consumer owns the boundary):\n *\n * ```ts\n * import * as Sentry from \"@sentry/browser\"; // or \"@sentry/node\"\n * import { breadcrumbsFromTrace } from \"@demlik/tea/recorder\";\n * for (const b of breadcrumbsFromTrace(rec.dump())) Sentry.addBreadcrumb(b);\n * ```\n *\n * @typeParam S - the machine's State type.\n * @typeParam M - the machine's Msg union.\n */\nexport function breadcrumbsFromTrace<S, M extends { type: string }>(\n trace: Trace<S, M>,\n opts?: BreadcrumbsOptions<M>,\n): TraceBreadcrumb[] {\n const rawLimit = opts?.limit;\n // Clamp limit to a non-negative integer. `undefined`/NaN → 100 (Sentry's\n // default). A negative or zero limit yields an empty list (the caller asked\n // for no breadcrumbs); fractional values floor (you can't emit half a crumb).\n const limit =\n rawLimit === undefined || Number.isNaN(rawLimit)\n ? 100\n : Math.max(0, Math.floor(rawLimit));\n const serialize = opts?.serialize;\n\n // Keep the NEWEST `limit` msgs (the recent lead-up to the crash). Slicing\n // from `length - limit` (clamped to 0) preserves dispatch order within the\n // kept window. Note we do NOT use `slice(-limit)`: `slice(-0)` is `slice(0)`\n // (JS treats -0 as 0), which would return the WHOLE array for `limit: 0`.\n const start = Math.max(0, trace.msgs.length - limit);\n const kept = start === 0 ? trace.msgs : trace.msgs.slice(start);\n\n const crumbs: TraceBreadcrumb[] = [];\n for (const msg of kept) {\n crumbs.push({\n category: \"tea\",\n type: \"default\",\n level: \"info\",\n message: serialize ? serialize(msg) : msg.type,\n // Full msg kept verbatim so the structured payload survives even when\n // `message` is a terse one-liner. Cast: a Msg is a `{ type: string }`\n // record, which is a `Record<string, unknown>` for Sentry's `data`.\n data: { msg: msg as unknown as Record<string, unknown> },\n });\n }\n return crumbs;\n}\n\n// ---------------------------------------------------------------------------\n// traceToJSONL — serialize a STANDALONE Trace to JSONL (the dump→file path).\n//\n// `Recorder.toJSONL()` serializes the recorder's live buffers. `traceAttachment`\n// works over a plain `Trace` value (a `dump()` snapshot or a `parseJSONL`\n// result), which has no recorder behind it — so it needs a Trace→JSONL\n// function. This is the same wire format `Recorder.toJSONL` emits and\n// `parseJSONL` reads, so `parseJSONL(traceToJSONL(trace))` round-trips.\n//\n// When `trace.steps` is present (captureSteps was on, or the trace came from\n// parseJSONL), every step line carries its post-state. When absent, interior\n// step states are unknown — emitted as `null`, with `finalState` on the LAST\n// step line (identical to the captureSteps:false path in `Recorder.toJSONL`).\n// ---------------------------------------------------------------------------\nfunction traceToJSONL<S, M>(trace: Trace<S, M>): string {\n const lines: string[] = [];\n lines.push(JSON.stringify({ kind: \"boot\", state: trace.loaded }));\n\n const steps = trace.steps;\n for (let i = 0; i < trace.msgs.length; i++) {\n const msg = trace.msgs[i];\n const stepState = steps\n ? steps[i]?.state\n : i === trace.msgs.length - 1\n ? trace.finalState\n : null;\n lines.push(JSON.stringify({ kind: \"step\", msg, state: stepState }));\n }\n return lines.join(\"\\n\");\n}\n"]}
|