@demlik/tea 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +3 -2
  2. package/dist/agent/index.d.ts +182 -35
  3. package/dist/agent/index.js +11 -11
  4. package/dist/{chunk-KWNCM6XM.js → chunk-AHW2CLPT.js} +65 -18
  5. package/dist/chunk-AHW2CLPT.js.map +1 -0
  6. package/dist/{chunk-K4ETBNKS.js → chunk-AIIXV4XB.js} +38 -9
  7. package/dist/chunk-AIIXV4XB.js.map +1 -0
  8. package/dist/{chunk-LYVOGOBC.js → chunk-BRX3243I.js} +3 -3
  9. package/dist/{chunk-LYVOGOBC.js.map → chunk-BRX3243I.js.map} +1 -1
  10. package/dist/{chunk-GWWCCSDH.js → chunk-C3G2QFEZ.js} +4 -4
  11. package/dist/{chunk-GWWCCSDH.js.map → chunk-C3G2QFEZ.js.map} +1 -1
  12. package/dist/{chunk-C4U5D5HP.js → chunk-FNGZMVIT.js} +3 -3
  13. package/dist/chunk-FNGZMVIT.js.map +1 -0
  14. package/dist/{chunk-QWIPH4YH.js → chunk-H2ELKHI6.js} +16 -6
  15. package/dist/chunk-H2ELKHI6.js.map +1 -0
  16. package/dist/chunk-H3MWNH7A.js +119 -0
  17. package/dist/chunk-H3MWNH7A.js.map +1 -0
  18. package/dist/chunk-I7E7AD2S.js +213 -0
  19. package/dist/chunk-I7E7AD2S.js.map +1 -0
  20. package/dist/{chunk-OYR7ENKU.js → chunk-IHUNKHDX.js} +3 -3
  21. package/dist/{chunk-OYR7ENKU.js.map → chunk-IHUNKHDX.js.map} +1 -1
  22. package/dist/chunk-JVE2LBFJ.js +21 -0
  23. package/dist/chunk-JVE2LBFJ.js.map +1 -0
  24. package/dist/chunk-JVKU2UQC.js +34 -0
  25. package/dist/chunk-JVKU2UQC.js.map +1 -0
  26. package/dist/{chunk-OPH6Y4UT.js → chunk-JYNYG5SF.js} +4 -4
  27. package/dist/{chunk-OPH6Y4UT.js.map → chunk-JYNYG5SF.js.map} +1 -1
  28. package/dist/{chunk-XBZQT2TD.js → chunk-PCJA2HTZ.js} +437 -162
  29. package/dist/chunk-PCJA2HTZ.js.map +1 -0
  30. package/dist/{chunk-DFUEAA6L.js → chunk-PQSDUX6B.js} +3 -3
  31. package/dist/{chunk-DFUEAA6L.js.map → chunk-PQSDUX6B.js.map} +1 -1
  32. package/dist/{chunk-6XBEYZME.js → chunk-WTSOW2MD.js} +5 -5
  33. package/dist/{chunk-6XBEYZME.js.map → chunk-WTSOW2MD.js.map} +1 -1
  34. package/dist/{chunk-4PXNZ5UY.js → chunk-XVIKSRCK.js} +4 -4
  35. package/dist/{chunk-4PXNZ5UY.js.map → chunk-XVIKSRCK.js.map} +1 -1
  36. package/dist/{chunk-4NTCPTNQ.js → chunk-YIMOFXST.js} +3 -3
  37. package/dist/{chunk-4NTCPTNQ.js.map → chunk-YIMOFXST.js.map} +1 -1
  38. package/dist/{core-rDbOaJTN.d.ts → core-Ce9ncpuv.d.ts} +5 -4
  39. package/dist/do/index.d.ts +140 -64
  40. package/dist/do/index.js +17 -18
  41. package/dist/do/index.js.map +1 -1
  42. package/dist/drive-loop-CsUsW3Wo.d.ts +127 -0
  43. package/dist/{durable-effects-CNaw97Be.d.ts → durable-effects-BmUrRA-h.d.ts} +1 -1
  44. package/dist/effect/index.d.ts +6 -150
  45. package/dist/effect/index.js +4 -96
  46. package/dist/effect/index.js.map +1 -1
  47. package/dist/extension/index.d.ts +7 -5
  48. package/dist/extension/index.js +2 -3
  49. package/dist/extension/index.js.map +1 -1
  50. package/dist/flow/index.d.ts +13 -13
  51. package/dist/flow/index.js +13 -12
  52. package/dist/flow/index.js.map +1 -1
  53. package/dist/idempotency/index.d.ts +3 -3
  54. package/dist/idempotency/index.js +4 -4
  55. package/dist/{index-q1PoukOZ.d.ts → index-2kNxy6az.d.ts} +2 -2
  56. package/dist/{index-B_BxplWi.d.ts → index-B1Wzarkl.d.ts} +1 -1
  57. package/dist/{index-Cberb5Rr.d.ts → index-Bf9_bNql.d.ts} +2 -2
  58. package/dist/index-BnsAqn0-.d.ts +286 -0
  59. package/dist/{index-Cx0F2M34.d.ts → index-Ce5GYAuI.d.ts} +2 -2
  60. package/dist/{index-CWmsXNdX.d.ts → index-D8sYVzCI.d.ts} +1 -1
  61. package/dist/{index-CcrKLtse.d.ts → index-DWdg7R1l.d.ts} +1 -1
  62. package/dist/{index-BOrsbdAf.d.ts → index-Dy3379ve.d.ts} +5 -5
  63. package/dist/{index-DaX_P35Q.d.ts → index-e36uEyl4.d.ts} +3 -3
  64. package/dist/index.d.ts +109 -36
  65. package/dist/index.js +2 -2
  66. package/dist/jev/index.d.ts +8 -8
  67. package/dist/jev/index.js +6 -7
  68. package/dist/jev/index.js.map +1 -1
  69. package/dist/{machine-BcfCFMYF.d.ts → machine-CuojfZup.d.ts} +353 -57
  70. package/dist/machine-viz/index.d.ts +1 -1
  71. package/dist/machine-viz/index.js +2 -2
  72. package/dist/mem/index.d.ts +6 -6
  73. package/dist/mem/index.js +6 -2
  74. package/dist/mem/index.js.map +1 -1
  75. package/dist/node/index.d.ts +16 -10
  76. package/dist/node/index.js +22 -3
  77. package/dist/node/index.js.map +1 -1
  78. package/dist/otel/index.d.ts +161 -0
  79. package/dist/otel/index.js +403 -0
  80. package/dist/otel/index.js.map +1 -0
  81. package/dist/paginate/index.d.ts +4 -4
  82. package/dist/paginate/index.js +5 -5
  83. package/dist/parity/index.d.ts +3 -3
  84. package/dist/parity/index.js +3 -3
  85. package/dist/pbt/index.d.ts +166 -53
  86. package/dist/pbt/index.js +2 -2
  87. package/dist/pbt/index.js.map +1 -1
  88. package/dist/persistence/index.d.ts +5 -5
  89. package/dist/persistence/index.js +5 -5
  90. package/dist/promise/index.d.ts +2 -2
  91. package/dist/promise/index.js +4 -3
  92. package/dist/react/index.d.ts +2 -2
  93. package/dist/resilience/index.d.ts +13 -9
  94. package/dist/resilience/index.js +5 -5
  95. package/dist/resilience/index.js.map +1 -1
  96. package/dist/{runtime-types-B62Ucnxr.d.ts → runtime-types-BKg2CGMx.d.ts} +88 -14
  97. package/dist/testing/effect/index.d.ts +65 -0
  98. package/dist/testing/effect/index.js +148 -0
  99. package/dist/testing/effect/index.js.map +1 -0
  100. package/dist/testing/index.d.ts +12 -158
  101. package/dist/testing/index.js +4 -130
  102. package/dist/testing/index.js.map +1 -1
  103. package/dist/testing/promise/index.d.ts +41 -0
  104. package/dist/testing/promise/index.js +37 -0
  105. package/dist/testing/promise/index.js.map +1 -0
  106. package/dist/timing/index.d.ts +4 -4
  107. package/dist/timing/index.js +4 -4
  108. package/dist/{types-DPm5YCDQ.d.ts → types-SzNSHKlV.d.ts} +1 -1
  109. package/dist/work-queue/index.d.ts +4 -4
  110. package/dist/work-queue/index.js +4 -3
  111. package/dist/work-queue/index.js.map +1 -1
  112. package/package.json +25 -13
  113. package/dist/chunk-C4U5D5HP.js.map +0 -1
  114. package/dist/chunk-G5E74IJB.js +0 -8
  115. package/dist/chunk-G5E74IJB.js.map +0 -1
  116. package/dist/chunk-K4ETBNKS.js.map +0 -1
  117. package/dist/chunk-KWNCM6XM.js.map +0 -1
  118. package/dist/chunk-QWIPH4YH.js.map +0 -1
  119. package/dist/chunk-XBZQT2TD.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/compose/index.ts","../src/observability.ts","../src/internal/prediction/index.ts","../src/subs/types.ts","../src/subs/define-listener.ts","../src/subs/from-broadcast-channel.ts","../src/subs/from-event-source.ts","../src/subs/from-event-target.ts","../src/subs/from-interval.ts","../src/subs/from-port.ts","../src/subs/from-reconnecting-web-socket.ts","../src/subs/from-timeout.ts","../src/subs/from-web-socket.ts","../src/subs/managed-resource.ts","../src/subs/transport.ts"],"names":[],"mappings":";;;AAsCO,SAAS,UACd,GAAA,EACA,KAAA,EACA,CAAC,KAAA,EAAO,IAAI,CAAA,EACgB;AAI5B,EAAA,OAAO,CAAC,EAAE,GAAG,KAAA,E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,SAAA,CAAU,GAAG,CAAC,CAAA;AACjC,MAAA,IAAI,MAAM,MAAA,EAAW;AAGnB,QAAA,OAAA,CAAQ,IAAA;AAAA,UACN,CAAA,eAAA,EAAkB,KAAK,IAAI,CAAA,+CAAA,CAAA;AAAA,UAC3B,UAAU,GAAG;AAAA,SACf;AACA,QAAA;AAAA,MACF;AACA,MAAA,CAAA,CAAE,IAAA,CAAK,IAAA,CAAK,iBAAA,CAAkB,QAAQ,CAAC,CAAA;AAAA,IACzC;AAAA,GACF;AACF","file":"chunk-FNGZMVIT.js","sourcesContent":["/**\n * @packageDocumentation\n * The composition seam — the layer between a battery and a door.\n *\n * A battery is pure state plus verbs over that state. A door holds several\n * batteries side by side in one Model. Everything between those two facts was,\n * until now, hand-written at every consumer: the one-key record rebuild that\n * threads a verb's `[slice, cmds]` result back into the host state, and the\n * statement order that decides which slice wins a derived read.\n *\n * Two helpers cover it, and neither is an optics kit. {@link liftSlice} is the\n * record rebuild with the key checked by the type system; {@link readInOrder}\n * turns a read's precedence from statement order into a value you can name,\n * export and assert on. ADR 0001 (no off-the-shelf resilience) and ADR 0014\n * (Effect's types, never its runtime values) between them settle why this is\n * forty lines here rather than a dependency.\n *\n * `docs/how-to/compose-two-battery-slices.md` wires both end to end over a\n * two-battery door, and its `ts` blocks are compiled and run as\n * `src/docs/how-to/compose-slices.test.ts`.\n *\n * Both are pure: no clock, no RNG, no storage, nothing captured. A `liftSlice`\n * result is a fresh record and a Cmd array, so ADR 0014's journal/hash promise\n * over a reducer's return value is untouched.\n */\n\n/**\n * Lift a battery verb's result into the host state that carries its slice.\n *\n * `liftSlice(\"resilience\", state, knob.attempt(state.resilience, …))` is the\n * `{ ...state, resilience: slice }` every consumer writes by hand, with the key\n * checked: `key` must be a key of `S`, and the slice the verb returned must be\n * assignable to the type that key carries — so naming the wrong field, or\n * threading one battery's slice into another's key, is a compile error rather\n * than a state shape nothing reads correctly.\n *\n * PURE — a fresh record and the verb's own Cmds, unchanged.\n */\nexport function liftSlice<S, K extends keyof S, C>(\n key: K,\n state: S,\n [slice, cmds]: readonly [S[K], readonly C[]],\n): readonly [S, readonly C[]] {\n // A computed-key spread widens to `S & { [k in K]: S[K] }` in TS's own\n // arithmetic, which is `S` by construction; the assertion states that rather\n // than re-deriving it. The runtime shape is exactly `S`'s.\n return [{ ...state, [key]: slice } as S, cmds];\n}\n\n/**\n * One step of a composed read: the slice it consults, under the name that slice\n * goes by. `read` returns `undefined` for \"this slice has nothing to say\",\n * which is what hands the read on to the next step.\n */\nexport interface ReadStep<In, Out> {\n /** The slice this step consults — `\"cache\"`, `\"failed\"`, `\"inFlight\"`. */\n readonly name: string;\n /** What this slice says about `input`, or `undefined` to defer. */\n readonly read: (input: In) => Out | undefined;\n}\n\n/**\n * Run a composed read through `order` and return the first answer any step\n * gives, or `absent` when every one defers.\n *\n * The point is that `order` is a VALUE. A derived read over three battery\n * slices otherwise states its precedence as the order of three `if` statements,\n * where it is invisible to the type system, unnameable in a test and one\n * innocent-looking reshuffle away from being wrong — which is exactly the\n * defect that escaped `classify-batch`'s per-battery test suites. Written as\n * data, the precedence can be exported, printed and asserted on directly.\n *\n * PURE — it evaluates `read` in order and stores nothing.\n */\nexport function readInOrder<In, Out>(\n input: In,\n order: readonly ReadStep<In, Out>[],\n absent: Out,\n): Out {\n for (const step of order) {\n const answer = step.read(input);\n if (answer !== undefined) return answer;\n }\n return absent;\n}\n","import type { BootingRuntime } from \"./runtime-types\";\n\n// === historyTracker: composable observability helper ===\n//\n// A bounded ring buffer of recent `(msg, state)` transitions, built on the\n// Runtime's public `observe` API. The substrate itself stays minimal — it has\n// no notion of history, no opt to enable one, no method on the Runtime\n// interface to read one. Anything that wants \"recent transitions\" composes via\n// this helper.\n//\n// Why not put this on the Runtime interface as `runtime.history()`? Because\n// history is derivable. Putting it on the Runtime privileges one use case\n// (debug inspectors) at the substrate level and grows the interface for\n// everyone; the composition shape stays out of the dispatch loop entirely, so\n// the substrate's hot path pays no cost for a feature it doesn't need.\n\nexport interface HistoryTracker<S, M extends { type: string }> {\n /**\n * Snapshot of recorded transitions, oldest first. Each entry is\n * `{ msg, state }`: `msg` is `null` for the boot transition (recorded via\n * `onBoot`) and the applied Msg for every other (recorded via `observe`).\n *\n * Returns a shallow copy: the array is fresh on every call (callers may\n * iterate, slice, or replay without affecting the tracker's buffer).\n * Entry values are references to the originals (TEA states/msgs are\n * conventionally immutable; do not mutate them if your S/M is not).\n */\n snapshot(): readonly { readonly msg: M | null; readonly state: S }[];\n /**\n * Detach the underlying observer. After `stop()`:\n * - No new transitions are recorded.\n * - `snapshot()` continues to work and returns the buffer's contents\n * at the moment of stop (useful for post-hoc inspection in tests).\n * - The tracker holds no references that would prevent GC of the\n * `runtime` argument other than the entries already buffered.\n *\n * Idempotent — subsequent calls are no-ops.\n */\n stop(): void;\n}\n\n/**\n * Create a bounded history tracker over a Runtime. The tracker subscribes to\n * the runtime via `observe(...)` and retains the last `size` `(msg, state)`\n * transitions in a FIFO ring buffer.\n *\n * @param runtime Any `BootingRuntime<S, M>` (a full `Runtime` satisfies it).\n * The tracker uses only `observe`, which is total before boot —\n * attach it to the synchronous `run()` handle to record the\n * boot transition.\n * @param size Buffer cap. `size <= 0` produces an inert no-op tracker:\n * no observer is attached to the runtime, `snapshot()` is\n * always `[]`, and `stop()` is a no-op.\n */\nexport function historyTracker<S, M extends { type: string }>(\n runtime: BootingRuntime<S, M>,\n size: number,\n): HistoryTracker<S, M> {\n const buffer: { msg: M | null; state: S }[] = [];\n let stopped = false;\n\n const push = (entry: { msg: M | null; state: S }): void => {\n buffer.push(entry);\n if (buffer.length > size) buffer.shift();\n };\n\n // The boot transition (the `{ msg: null, state }` head entry) arrives via\n // `onBoot`; applied transitions arrive via `observe` with a total `msg`. The\n // public snapshot shape (`msg: M | null`) is unchanged — boot is still\n // `msg: null`.\n const unobserve =\n size <= 0\n ? (): void => {}\n : runtime.observe((msg, state) => {\n push({ msg, state });\n });\n const unboot =\n size <= 0\n ? (): void => {}\n : runtime.onBoot((state) => {\n push({ msg: null, state });\n });\n\n return {\n snapshot() {\n // Shallow copy — callers may freely iterate or mutate the returned\n // array. Entry values are references; see HistoryTracker docs.\n return buffer.slice();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n unobserve();\n unboot();\n },\n };\n}\n","/**\n * internal/prediction — the client-prediction ack primitive (epic #186, facet 2).\n * Internal since #49 — not published on any subpath of its own; the\n * client-safe barrel `src/pure/` re-exports the public surface, and the root\n * `@demlik/tea` door publishes it.\n *\n * The contract the Gambetta/Valve authoritative-server netcode loop needs:\n * **command-seq-in → last-applied-seq-out.** A client tags each predicted\n * command/`Msg` with a monotonic `seq`; the authoritative side replies with the\n * `lastAppliedSeq` it has processed. `partitionByAck` then splits the client's\n * pending buffer into the inputs the server has ACKED (`seq <= lastAppliedSeq`)\n * and those still PENDING (`seq > lastAppliedSeq`) — the un-acked tail the\n * reconciliation pass (#214) replays over the authoritative snapshot via\n * `foldMsgs` (#211, the client-safe barrel `src/pure/`).\n *\n * Deliberately **Model-shape-agnostic** (ADR 0006): the ack is a standalone\n * value, NOT a field this module requires on the consumer's `State`. It\n * generalizes the `lastAckedSeq`-on-the-Model + `seq`-threaded-through-the-Msg\n * pattern vortex hand-rolled (epic #186). It is a LEAF module — pure and\n * runtime-free, importing nothing from the tea core or host, so it can never\n * drag `run`/the host into a client bundle.\n *\n * This is the read/ack side of the primitive; `tagSeq`/`nextSeq` are the write\n * side, letting a client mint monotonic seqs from its pending buffer alone —\n * again with no counter field on the Model.\n *\n * `reconcile` (the read side's payoff, #214) composes this ack partition with\n * the pure fold seam `foldMsgs` to perform the whole Gambetta/Valve\n * reconciliation step in one call. The `foldMsgs` import is the ONLY dependency\n * this leaf takes, and it reaches into the pure-core leaf (`../pure/core`) — NOT\n * the runtime root — so the module stays runtime-free and the client-safe\n * import-graph guard (ADR 0006, #213) still holds.\n */\n\nimport type { Cmd, Machine, Sub } from \"../../pure/core\";\nimport { foldMsgs } from \"../../pure/core\";\n\n/**\n * A monotonic, non-negative sequence number tagging one client-predicted\n * command. Monotonicity is the client's contract (mint successive seqs with\n * `nextSeq`); this module only ever *compares* seqs.\n */\nexport type Seq = number;\n\n/** A command (or `Msg`) tagged with the `seq` the client assigned it. */\nexport interface SeqTagged<T> {\n readonly seq: Seq;\n readonly value: T;\n}\n\n/** Tag a command/`Msg` with its sequence number. */\nexport const tagSeq = <T>(seq: Seq, value: T): SeqTagged<T> => ({ seq, value });\n\n/**\n * The authoritative side's acknowledgement: the highest `seq` it has applied.\n * Everything with `seq <= lastAppliedSeq` is settled; everything above is still\n * in flight. This *is* the whole \"ack from the authoritative side\" — a value\n * the consumer carries however it likes (a wire field, a message payload),\n * never a shape this module imposes on the Model.\n */\nexport interface Ack {\n readonly lastAppliedSeq: Seq;\n}\n\n/** Construct an `Ack` for a last-applied sequence number. */\nexport const ack = (lastAppliedSeq: Seq): Ack => ({ lastAppliedSeq });\n\n/**\n * The \"nothing applied yet\" cursor — the ack value for a server that has applied\n * no client input at all. Because `nextSeq` mints **0-based** seqs and\n * `partitionByAck` acks **inclusively** (`seq <= lastAppliedSeq`), the pre-first\n * cursor must sit strictly *below* seq 0: `lastAppliedSeq = 0` would falsely ack\n * the seq-0 input before the server ever saw it. `-1` is \"before any seq\", and\n * `partitionByAck(buffer, NO_ACK)` therefore leaves the whole buffer PENDING.\n *\n * This names the boundary value on the seam so no consumer has to re-discover it\n * as a magic number: it is the primitive's own design (0-based mint + inclusive\n * partition) that creates the trap, so it is the primitive's job to name the\n * escape. Pair with {@link initAck} when an {@link Ack} is wanted instead of the\n * bare `Seq`.\n */\nexport const NO_ACK: Seq = -1;\n\n/**\n * The `Ack` for a server that has applied nothing yet — `ack(NO_ACK)`. The `Ack`\n * counterpart to the {@link NO_ACK} `Seq` sentinel, for a consumer that carries\n * an `Ack` rather than a bare `lastAppliedSeq`.\n */\nexport const initAck = (): Ack => ack(NO_ACK);\n\n/** The result of splitting a seq-tagged buffer against an ack. */\nexport interface AckPartition<T> {\n /** Inputs the authoritative side has applied (`seq <= lastAppliedSeq`). */\n readonly acked: readonly SeqTagged<T>[];\n /** Inputs still in flight / un-acked (`seq > lastAppliedSeq`) — the replay tail. */\n readonly pending: readonly SeqTagged<T>[];\n}\n\n/**\n * Partition a buffer of seq-tagged commands into ACKED and PENDING against the\n * authoritative `lastAppliedSeq`. Pure and total: every item lands in exactly\n * one bucket, input order is preserved within each bucket, and the boundary\n * `seq == lastAppliedSeq` is ACKED (inclusive `<=`). Routing is by `seq` value,\n * not buffer position, so an out-of-order or duplicate-seq buffer partitions\n * correctly. Accepts either an {@link Ack} or a bare `lastAppliedSeq` number, so\n * a caller passes whichever it holds.\n */\nexport const partitionByAck = <T>(\n buffer: readonly SeqTagged<T>[],\n ackOrSeq: Ack | Seq,\n): AckPartition<T> => {\n const lastAppliedSeq =\n typeof ackOrSeq === \"number\" ? ackOrSeq : ackOrSeq.lastAppliedSeq;\n const acked: SeqTagged<T>[] = [];\n const pending: SeqTagged<T>[] = [];\n for (const item of buffer) {\n if (item.seq <= lastAppliedSeq) {\n acked.push(item);\n } else {\n pending.push(item);\n }\n }\n return { acked, pending };\n};\n\n/**\n * The next sequence number to assign: one past the highest `seq` in the buffer,\n * or `0` for an empty buffer. Lets a client mint monotonic seqs from its pending\n * buffer alone — no counter field on the Model — and is tolerant of an unordered\n * buffer (it takes the max, not the last element).\n */\nexport const nextSeq = <T>(buffer: readonly SeqTagged<T>[]): Seq =>\n buffer.reduce((max, item) => (item.seq > max ? item.seq : max), -1) + 1;\n\n/**\n * The client prediction/reconciliation helper — the Gambetta/Valve\n * authoritative-server loop's reconcile step, generalized.\n *\n * Given the latest `authoritativeState` from the server, the server's\n * `lastAppliedSeq` ack, and the client's `pending` buffer of seq-tagged inputs,\n * it returns the corrected predicted state: drop the inputs the server has\n * already applied (`seq <= lastAppliedSeq`) and replay ONLY the un-acked tail\n * (`seq > lastAppliedSeq`) over the authoritative snapshot.\n *\n * It is **composed, not re-derived** (ADR 0006): the drop is {@link partitionByAck}\n * (the ack primitive, #212) and the replay is `foldMsgs` (the pure fold seam,\n * #211) — there is no second copy of the partition logic and no second copy of\n * the fold. `lastAppliedSeq` accepts either an {@link Ack} or a bare `Seq`, so a\n * caller passes whichever it holds, matching `partitionByAck`.\n *\n * Pure and host-agnostic: it takes the `machine` (which `foldMsgs` needs to\n * dispatch `update`) but touches no `Store`, `interpret`, or subscription, and\n * imports nothing from the runtime — so it ships through the client-safe\n * umbrella without dragging `run` into a client bundle.\n */\nexport function reconcile<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n authoritativeState: S,\n lastAppliedSeq: Ack | Seq,\n pending: readonly SeqTagged<M>[],\n): S {\n const { pending: unacked } = partitionByAck(pending, lastAppliedSeq);\n return foldMsgs(\n machine,\n authoritativeState,\n unacked.map((tagged) => tagged.value),\n );\n}\n","// ---------------------------------------------------------------------------\n// SubscribeHandler<S, M, Ctx> — the structural shape of one sub runner: one\n// entry of the `subscribe` table handed to `run`. Pulled out as a named type\n// so factory return types in this subpath can match the engine's `Subscribe`\n// entry without re-deriving it from the mapped type.\n//\n// The machine declares a Sub as data in `subs`; a factory in this subpath\n// returns the runner for that Sub's type, which the caller hands to `run`:\n//\n// subs: [{ type: \"audit-idle\", deps: (s) => (s.watching ? {} : null) }],\n// // …\n// run(machine, {\n// subscribe: {\n// \"audit-idle\": fromPort(\n// (ctx) => ctx.auditRuntime,\n// auditIdlePort,\n// (idle) => ({ type: \"audit:idle\", idle }),\n// ),\n// },\n// });\n//\n// The factory absorbs the lifecycle (subscribe + cleanup); the caller keeps\n// the intent (which port, which msg). A runner reads its data off `sub.deps`.\n// Strengthens invariant 9 (the surface for cross-cutting Sub topologies is\n// named, small, and exported from one subpath instead of redrawn at every\n// call site).\n// ---------------------------------------------------------------------------\n\nimport type { Dispose, Sub } from \"../index\";\n\nexport type SubscribeHandler<S extends Sub, M, Ctx> = (\n sub: S,\n ctx: Ctx,\n dispatch: (msg: M) => void,\n) => Dispose;\n\n// ---------------------------------------------------------------------------\n// dispatchIfPresent — the null-drop dispatch idiom every Sub factory in this\n// subpath (and the chrome/node factories) shares. A factory's callback maps a\n// platform event to `M | null`; `null` is the explicit \"drop this emission\"\n// signal — the event fired but the caller decided it isn't interesting given\n// current state, so no dispatch is made and the listener stays armed. Hoisted\n// here so the one drop-on-null rule lives once instead of re-inlined as\n// `const msg = fn(...); if (msg !== null) dispatch(msg);` at every listener.\n// ---------------------------------------------------------------------------\n\nexport function dispatchIfPresent<M>(\n dispatch: (msg: M) => void,\n msg: M | null,\n): void {\n if (msg !== null) dispatch(msg);\n}\n","// ---------------------------------------------------------------------------\n// defineListener — listener-as-resource. The kernel primitive that turns an\n// imperative `add`/`remove` listener pair into a substrate-owned Sub whose\n// cleanup is MANDATORY and DERIVED — a forgotten or no-op disposer is\n// unrepresentable.\n//\n// The leak it kills: every author who wires a raw listener hand-rolls the SAME\n// skeleton —\n//\n// return (sub, _ctx, dispatch) => {\n// const listener = (e) => { const m = msgFn(e, sub); if (m !== null) dispatch(m); };\n// target.addListener(listener);\n// return () => target.removeListener(listener); // ← author-driven\n// };\n//\n// — and each re-write can SILENTLY LEAK two ways the type system never sees:\n//\n// 1. The disposer is a no-op (`return () => {}`) — the listener stays armed\n// forever. Nothing forces the returned cleanup to undo the add.\n// 2. The disposer calls `remove` with a DIFFERENT function than `add`\n// received (a fresh closure, a re-bound `this`) — the original listener\n// is never removed; it leaks while a phantom remove succeeds silently.\n//\n// `fromBroadcastChannel`, `fromEventTarget`, and every host-side bridge\n// hand-roll this skeleton today. They happen to be correct — but the\n// correctness is convention (rung 5), not structure. `defineListener` moves it\n// to rung 1: the listener the substrate builds is the SAME reference handed to\n// both `add` and `remove`, and the cleanup IS `() => remove(thatListener, ...)`.\n// You cannot write a no-op disposer because you do not write the disposer at\n// all.\n//\n// Shape:\n//\n// // Args is the tuple chrome invokes the listener with — here a single\n// // [Alarm]. The substrate builds ONE listener of this exact native shape.\n// const fromChromeAlarm = defineListener<[chrome.alarms.Alarm], S>({\n// add: (l) => chrome.alarms.onAlarm.addListener(l),\n// remove: (l) => chrome.alarms.onAlarm.removeListener(l),\n// });\n//\n// // ...then in the `subscribe` table handed to `run`, supply the Msg projection:\n// subscribe: { tick: fromChromeAlarm<M>((sub, alarm) => ({ type: \"tick\", ... })) }\n//\n// - `add`/`remove` receive `(listener, sub, ctx)`. The `listener` is the\n// EXACT function the substrate built; pass it straight to the platform's\n// addListener/removeListener — NO wrapper. A wrapper inside `add` would\n// break reference identity (the platform stores the wrapper, but the\n// substrate hands `remove` the unwrapped listener → silent leak). Carrying\n// the platform's native `Args` tuple on the listener is what lets it be\n// registered directly. `sub`/`ctx` let the target be pulled from `ctx` or\n// keyed on the `sub` (the `getTarget()`-from-ctx shape fromPort needs).\n//\n// - `msgFn(sub, ...args) => M | null` — the universal drop-on-null filter\n// every factory in this subpath carries. `null` drops the dispatch; the\n// listener stays armed. `sub` is first (always present); the platform args\n// follow in their native order.\n//\n// Generalizes the `from*` pattern: a closure-owned disposer makes a forgotten\n// cleanup a syntax error, and this brings it to every host/satellite.\n//\n// Strengthens invariant 4 (external events enter as Subs; the lifecycle —\n// add on subscribe, remove on cleanup — is owned by the substrate, never the\n// author) and invariant 6 (no silent looseness: a leaked listener is a silent\n// failure, and this primitive removes the way to write one).\n// ---------------------------------------------------------------------------\n\nimport type { Sub } from \"../index\";\nimport { dispatchIfPresent, type SubscribeHandler } from \"./types\";\n\n/**\n * The imperative listener target, expressed as the `add`/`remove` pair the\n * substrate pairs into a reconciled resource. Both halves receive the SAME\n * `listener` reference — the substrate builds it once — so `remove` can never\n * be handed a different function than `add` saw.\n *\n * `add`/`remove` also receive `(sub, ctx)` so the target may be resolved from\n * `ctx` (a runtime, a port, a DOM node looked up lazily) or keyed on the Sub\n * (an alarm name, a channel name). Resolving the target inside `add` and\n * closing over nothing but the listener keeps a target swap from leaking the\n * old target's listener — same rationale as `fromEventTarget`'s captured\n * target.\n *\n * `Args` is the tuple the platform invokes the listener with — `[Alarm]` for\n * `chrome.alarms.onAlarm`, `[message, sender, sendResponse]` for\n * `chrome.runtime.onMessage`, `[changes, areaName]` for\n * `chrome.storage.onChanged`. The substrate builds ONE function of this exact\n * shape and threads the IDENTICAL reference to both `add` and `remove` — so a\n * platform that matches `removeListener` by reference (every chrome surface)\n * removes exactly what it added. A consumer that wrapped the listener inside\n * `add` would break reference identity (leak #2 above); carrying the native\n * `Args` on the listener itself removes the need for any wrapper.\n */\nexport interface ListenerTarget<\n Args extends readonly unknown[],\n S extends Sub,\n Ctx,\n> {\n add: (listener: (...args: Args) => void, sub: S, ctx: Ctx) => void;\n remove: (listener: (...args: Args) => void, sub: S, ctx: Ctx) => void;\n}\n\n/**\n * Build a listener-backed Sub factory whose cleanup is mandatory and derived.\n *\n * `Args`, `S`, `Ctx` are fixed when the target is defined — they describe the\n * one listener topology this factory owns (the platform arg tuple, which Sub\n * shape it filters on, what context resolves it). `M` is supplied at the\n * runner because the same listener feeds different Msgs in different\n * machines. Pinning `S` here (rather than at the `msgFn` step) lets\n * `add`/`remove` read the concrete Sub's deps — `sub.deps.alarmName`,\n * `sub.deps.channel` — with NO cast at the substrate edge: the narrowing\n * happens in author-land where the Sub shape is in scope.\n *\n * The returned function is a `SubscribeHandler` factory in the exact shape of\n * every other Sub factory in `src/subs/`: supply the `msgFn` projection, get a\n * `(sub, ctx, dispatch) => cleanup` runner for the `subscribe` table `run`\n * takes.\n * The cleanup the author NEVER writes is `() => remove(listener, sub, ctx)`,\n * with `listener` the identical reference passed to `add`.\n */\nexport function defineListener<\n Args extends readonly unknown[],\n S extends Sub = Sub,\n Ctx = unknown,\n>(\n target: ListenerTarget<Args, S, Ctx>,\n): <M>(\n msgFn: (sub: S, ...args: Args) => M | null,\n) => SubscribeHandler<S, M, Ctx> {\n return <M>(\n msgFn: (sub: S, ...args: Args) => M | null,\n ): SubscribeHandler<S, M, Ctx> => {\n return (sub, ctx, dispatch) => {\n const listener = (...args: Args): void => {\n dispatchIfPresent(dispatch, msgFn(sub, ...args));\n };\n // ONE listener, identical reference to both halves — chrome's\n // removeListener matches by reference, so this removes exactly what\n // add registered. No wrapper, no WeakMap, no reference drift.\n target.add(listener, sub, ctx);\n return () => {\n target.remove(listener, sub, ctx);\n };\n };\n };\n}\n","// ---------------------------------------------------------------------------\n// fromBroadcastChannel — universal `BroadcastChannel`-shaped Sub factory.\n//\n// `BroadcastChannel` is a same-origin pub/sub primitive available in\n// every modern browser context (window, worker, service worker) AND in\n// Cloudflare Workers (with origin scoped to the worker isolate). The\n// constructor opens the channel; the `message` event fires whenever\n// another participant on the same channel name posts a message; the\n// `close()` method releases the OS resource.\n//\n// The factory reads `channelName` off the Sub's `deps` (not the closure)\n// so the same factory instance handles every BroadcastChannel Sub in a\n// machine — one Sub per channel, sharing the factory's lifecycle code.\n// A renamed channel is a changed deps value, so a new id: the engine\n// closes the old channel and opens the new one.\n//\n// `msgFn` returns `M | null` — same drop-on-null pattern as\n// `fromEventTarget`. The MessageEvent's `data` is `unknown` from the\n// platform's perspective; the caller decides whether the payload is a\n// recognizable shape, and returns `null` to drop unknown messages\n// without polluting the reducer with parse-discard cells.\n//\n// Cleanup calls `channel.close()`, which removes the listener AND\n// releases the channel reference — `removeEventListener` alone would\n// leak the BroadcastChannel handle. The pair is intentional.\n// ---------------------------------------------------------------------------\n\nimport type { Sub } from \"../index\";\nimport type {\n MinimalBroadcastChannelCtor,\n MinimalMessageEvent,\n} from \"./platform\";\nimport { dispatchIfPresent, type SubscribeHandler } from \"./types\";\n\ntype BroadcastSubData = { readonly channelName: string };\n\ndeclare const BroadcastChannel: MinimalBroadcastChannelCtor;\n\nexport function fromBroadcastChannel<\n S extends Sub<string, BroadcastSubData>,\n M,\n>(\n msgFn: (event: MinimalMessageEvent, sub: S) => M | null,\n): SubscribeHandler<S, M, unknown> {\n return (sub, _ctx, dispatch) => {\n const channel = new BroadcastChannel(sub.deps.channelName);\n const listener = (event: MinimalMessageEvent): void => {\n dispatchIfPresent(dispatch, msgFn(event, sub));\n };\n channel.addEventListener(\"message\", listener);\n return () => {\n channel.removeEventListener(\"message\", listener);\n channel.close();\n };\n };\n}\n","// ---------------------------------------------------------------------------\n// fromEventSource — universal `EventSource` (server-sent events) Sub\n// factory.\n//\n// SSE is the asymmetric streaming protocol used by the agent log /\n// audit log pipelines: HTTP-shaped open, server pushes events forever,\n// client receives until close. `EventSource` is the standard browser\n// API; the constructor opens the connection, `message` fires per\n// server-pushed event, `error` fires on disconnect or non-2xx, `open`\n// fires once on initial handshake, `close()` tears the connection\n// down.\n//\n// Three callbacks because three observable events ARE three concerns\n// the caller routinely cares about:\n//\n// - `onMessage(data, sub)` — required. The SSE payload's `data` field\n// is `string` from the platform; the caller decides parse + Msg\n// shape. Returns `M | null`; null drops the dispatch.\n//\n// - `onError(event, sub)` — optional. SSE's `error` event fires both\n// on transient network drops (the browser auto-reconnects) AND on\n// permanent failures. Most consumers want to surface ONE of these\n// as a Msg (e.g. \"stream-disconnected\") without folding both into\n// `onMessage`'s discriminant. Omitting the callback drops error\n// events silently.\n//\n// - `onOpen(sub)` — optional. The connection's initial handshake\n// succeeded. Useful for \"show 'connected' indicator\" Msgs. Omitting\n// drops open events silently. NOT fired on auto-reconnect by every\n// browser implementation — treat the event as best-effort.\n//\n// `url` lives in the Sub's `deps` (`EventSourceSubData`). A changed url\n// is a changed deps value, so a new id: the engine closes the old\n// connection and opens one to the new url.\n//\n// Cleanup is `close()` + `removeEventListener` for all three —\n// belt-and-suspenders against EventSource implementations that\n// dispatch events into already-closed sources.\n// ---------------------------------------------------------------------------\n\nimport type { Sub } from \"../index\";\nimport type {\n MinimalEvent,\n MinimalEventSourceCtor,\n MinimalMessageEvent,\n} from \"./platform\";\nimport { dispatchIfPresent, type SubscribeHandler } from \"./types\";\n\ntype EventSourceSubData = { readonly url: string };\n\ndeclare const EventSource: MinimalEventSourceCtor;\n\nexport interface EventSourceFactoryOpts<S, M> {\n onMessage: (data: string, sub: S) => M | null;\n onError?: (event: MinimalEvent, sub: S) => M | null;\n onOpen?: (sub: S) => M | null;\n}\n\nexport function fromEventSource<S extends Sub<string, EventSourceSubData>, M>(\n opts: EventSourceFactoryOpts<S, M>,\n): SubscribeHandler<S, M, unknown> {\n return (sub, _ctx, dispatch) => {\n const source = new EventSource(sub.deps.url);\n\n const messageListener = (event: MinimalMessageEvent): void => {\n // The SSE `data` payload is a string per the platform contract.\n // Cast at the boundary: callers express `(data: string) => M | null`\n // and never see `unknown` flowing in from the platform global.\n dispatchIfPresent(dispatch, opts.onMessage(event.data as string, sub));\n };\n source.addEventListener(\"message\", messageListener);\n\n const onError = opts.onError;\n const errorListener = onError\n ? (event: MinimalEvent): void => {\n dispatchIfPresent(dispatch, onError(event, sub));\n }\n : undefined;\n if (errorListener) source.addEventListener(\"error\", errorListener);\n\n const onOpen = opts.onOpen;\n const openListener = onOpen\n ? (): void => {\n dispatchIfPresent(dispatch, onOpen(sub));\n }\n : undefined;\n if (openListener) source.addEventListener(\"open\", openListener);\n\n return () => {\n source.removeEventListener(\"message\", messageListener);\n if (errorListener) source.removeEventListener(\"error\", errorListener);\n if (openListener) source.removeEventListener(\"open\", openListener);\n source.close();\n };\n };\n}\n","// ---------------------------------------------------------------------------\n// fromEventTarget — universal addEventListener/removeEventListener Sub\n// factory over any `EventTarget` (DOM nodes, `window`, `document`,\n// `BroadcastChannel`, `MessagePort`, `Worker`, `ServiceWorker`, etc.).\n//\n// Two non-obvious shape choices:\n//\n// - `getTarget: () => EventTarget` is a thunk, not a direct value. The\n// factory MUST work in environments where the target is not available\n// at module-load time — service workers run before any `document`\n// exists; some targets are constructed lazily from `ctx`. Deferring\n// the lookup to subscribe time also means a state-driven swap of the\n// target needs only a changed `deps` value (a restart); the factory\n// pulls the current target on subscribe.\n//\n// - `msgFn` may return `null` — that emission is *dropped*. The event\n// fired, the factory called `msgFn`, but the caller decided \"this\n// event is not interesting given current state.\" No dispatch is made;\n// the listener stays armed for the next event. This is the explicit\n// filter point at the Sub boundary — the alternative (filtering inside\n// the reducer via a noop cell) costs a transition + reconcile pass per\n// filtered event.\n//\n// Cleanup uses the SAME `getTarget()` instance captured at subscribe time\n// so a target swap mid-Sub doesn't leak the listener on the old target.\n// We close over the resolved target rather than calling `getTarget()`\n// again at cleanup — the alternative (re-resolving) is the cause of\n// silent listener leaks in long-lived runtimes.\n// ---------------------------------------------------------------------------\n\nimport type { Sub } from \"../index\";\nimport type { MinimalEvent, MinimalEventTarget } from \"./platform\";\nimport { dispatchIfPresent, type SubscribeHandler } from \"./types\";\n\nexport function fromEventTarget<S extends Sub, M>(\n getTarget: () => MinimalEventTarget,\n eventName: string,\n msgFn: (event: MinimalEvent, sub: S) => M | null,\n): SubscribeHandler<S, M, unknown> {\n return (sub, _ctx, dispatch) => {\n const target = getTarget();\n const listener = (event: MinimalEvent): void => {\n dispatchIfPresent(dispatch, msgFn(event, sub));\n };\n target.addEventListener(eventName, listener);\n return () => {\n target.removeEventListener(eventName, listener);\n };\n };\n}\n","// ---------------------------------------------------------------------------\n// fromInterval — universal `setInterval`-shaped Sub factory.\n//\n// The recurring shape at every runner that wraps a periodic timer is the\n// same five lines: `setInterval` the dispatch, return a `clearInterval`\n// cleanup. The factory absorbs both halves of the lifecycle (subscribe +\n// cleanup); the caller keeps the intent — which Sub type, which Msg to\n// dispatch.\n//\n// Timing data (`intervalMs`) lives in the Sub's `deps`, not in the closure.\n// The engine derives the Sub's id from its deps, so a `deps` that returns\n// `{ intervalMs: 30_000 }` in one state and `{ intervalMs: 60_000 }` later is\n// a new id: the engine stops the old interval and starts one at the new\n// period. An unchanged deps value leaves the running interval alone.\n//\n// Strengthens invariant 9 (named, small surface) and invariant 2 (the Sub\n// carries the data; the lifecycle is in the factory; the reducer never\n// sees the timer).\n// ---------------------------------------------------------------------------\n\nimport type { Sub } from \"../index\";\nimport type { SubscribeHandler } from \"./types\";\n\ntype IntervalSubData = { readonly intervalMs: number };\n\nexport function fromInterval<S extends Sub<string, IntervalSubData>, M>(\n msgFn: (sub: S) => M,\n): SubscribeHandler<S, M, unknown> {\n return (sub, _ctx, dispatch) => {\n const handle = setInterval(() => {\n dispatch(msgFn(sub));\n }, sub.deps.intervalMs);\n return () => {\n clearInterval(handle);\n };\n };\n}\n","// ---------------------------------------------------------------------------\n// fromPort — universal `Runtime.subscribePort`-shaped Sub factory.\n//\n// The canonical cross-runtime coordination pattern in @demlik/tea: one\n// runtime emits to a typed Port; another runtime's machine declares an\n// `audit-idle`-shaped Sub whose runner attaches to the publisher's Port.\n// The recurring 4-line shape at every such runner:\n//\n// \"audit-idle\": (_sub, ctx, dispatch) =>\n// ctx.auditRuntime.subscribePort(auditIdlePort, (value) => {\n// dispatch(buildMsg(value));\n// });\n//\n// The factory absorbs the cleanup-returning subscribePort call AND the\n// dispatch-on-emit wiring. The caller keeps the three pieces of intent:\n//\n// 1. `selectRuntime(ctx)` — which sibling Runtime publishes the Port.\n// This is a selector (not a direct ctx.auditRuntime reference) so\n// the factory does NOT pin the ctx shape — any machine whose ctx\n// exposes some Runtime<...> reference is compatible by selecting it.\n// A direct `Runtime` parameter would have made the factory shape\n// depend on having that Runtime in scope at machine-definition\n// time, which is a worse match for the \"ctx is the boundary\"\n// contract this substrate already commits to.\n//\n// 2. `port: Port<T>` — the typed channel itself. Identity is by\n// reference (the substrate enforces unique names at definePort\n// time); pass the same `Port<T>` value the publisher emits to.\n//\n// 3. `msgFn(value, sub) => M | null` — the value-to-Msg mapping, with\n// drop-on-null semantics matching every other factory in this\n// subpath. The published value's type `T` flows through to `msgFn`'s\n// first param so the caller never re-asserts the payload shape.\n//\n// Strengthens invariant 9 (the cross-runtime Port topology is named at\n// one factory site instead of redrawn at every runner).\n// ---------------------------------------------------------------------------\n\nimport type { Port, Runtime, Sub } from \"../index\";\nimport { dispatchIfPresent, type SubscribeHandler } from \"./types\";\n\n// `RS` / `RM` carry the sibling Runtime's concrete State and Msg through the\n// selector: a caller that selects a `Runtime<AuditState, AuditMsg>` keeps that\n// type at the seam instead of collapsing it to `Runtime<unknown, {type:string}>`.\n// They default to the prior broad pair so existing call sites that select a\n// less-specific Runtime still compile — the factory still only ever calls\n// `subscribePort`, so it does not read RS/RM, but the boundary no longer\n// hardcodes the widest type when the caller knows a narrower one.\nexport function fromPort<\n S extends Sub,\n M,\n Ctx,\n T,\n RS = unknown,\n RM extends { type: string } = { type: string },\n>(\n selectRuntime: (ctx: Ctx) => Runtime<RS, RM>,\n port: Port<T>,\n msgFn: (value: T, sub: S) => M | null,\n): SubscribeHandler<S, M, Ctx> {\n return (sub, ctx, dispatch) => {\n const runtime = selectRuntime(ctx);\n return runtime.subscribePort(port, (value) => {\n dispatchIfPresent(dispatch, msgFn(value, sub));\n });\n };\n}\n","// ---------------------------------------------------------------------------\n// fromReconnectingWebSocket — a `WebSocket` Sub factory that survives drops.\n//\n// `fromWebSocket` is the SSE-sibling ONE-SHOT factory: its cleanup `close()`s\n// the socket and it never re-opens on an unexpected drop (issue #188). That is\n// the right shape for a connection the caller manages, but any tea client over\n// an unreliable transport — games, presence, collab — needs the connection to\n// recover transparently, without a page reload. Rather than re-roll a backoff\n// loop in every consumer (vortex's `ReconnectingSocket` is the proven shape,\n// services/vortex/src/reconnecting-socket.ts), this is the reconnecting variant\n// folded into the substrate's Sub surface.\n//\n// The reconnect contract, mirroring vortex's wrapper:\n//\n// - On an UNEXPECTED close (`onclose` the substrate didn't initiate) it\n// re-opens after a CAPPED exponential backoff: `min(base * 2^attempt, max)`.\n// A successful handshake resets `attempt` to 0, so the next drop retries\n// fast again.\n//\n// - A CALLER-INITIATED close (the Sub's cleanup, e.g. the machine\n// transitioned the Sub away) suppresses reconnect: handlers are detached\n// BEFORE `close(1000)` so the teardown can't fire `onClose` or schedule a\n// reconnect. After cleanup the factory never re-opens.\n//\n// - `connect` and `schedule` are INJECTABLE (defaulting to the global\n// `WebSocket` and `setTimeout`/`clearTimeout`), the test seam that lets the\n// reconnect/backoff behavior be unit-tested with a fake socket + a manual\n// clock — no DOM, no real network, no timers — exactly as vortex's wrapper\n// is tested.\n//\n// Callback contract (same `M | null` \"null drops the dispatch\" shape as\n// `fromWebSocket`, plus one reconnect-specific hook):\n//\n// - `onMessage(data, sub)` — required. Raw `unknown` frame; the caller parses.\n// - `onOpen(sub)` — optional. Fires on EVERY successful handshake — the first\n// open AND every reconnect — so a \"connected\" indicator stays accurate.\n// - `onError(event, sub)` — optional. The `error` event; `close` still drives\n// the reconnect (one path), so this is purely a notification.\n// - `onClose(code, reason, sub)` — optional. Fires on every close the\n// substrate observes (a drop that will be retried, too) — NOT on the\n// caller's own teardown, whose handlers are detached first.\n// - `onReconnect(attempt, sub)` — optional. Fires when a RE-open (any open\n// after the first) succeeds, carrying the 1-based reconnect count. This is\n// the resync hook: the place to dispatch a \"re-fetch the authoritative\n// snapshot, discard predicted state\" Msg after the transport recovered.\n//\n// Like `fromWebSocket`, `wsUrl` lives in the Sub's `deps` (`WebSocketSubData`).\n// A changed url is a new id, so the engine tears this runner down (no\n// reconnect) and starts a fresh one against the new endpoint.\n// ---------------------------------------------------------------------------\n\nimport type { Sub } from \"../index\";\nimport type { WebSocketSubData } from \"./from-web-socket\";\nimport type {\n MinimalEvent,\n MinimalWebSocket,\n MinimalWebSocketCtor,\n} from \"./platform\";\nimport { dispatchIfPresent, type SubscribeHandler } from \"./types\";\n\ndeclare const WebSocket: MinimalWebSocketCtor;\n\n/** Cancels a scheduled reconnect timer (the inverse of `schedule`). */\nexport type CancelTimer = () => void;\n\nexport interface ReconnectingWebSocketFactoryOpts<S, M> {\n onMessage: (data: unknown, sub: S) => M | null;\n onOpen?: (sub: S) => M | null;\n onError?: (event: MinimalEvent, sub: S) => M | null;\n onClose?: (code: number, reason: string, sub: S) => M | null;\n /**\n * Fires when a reconnection (any open after the first) succeeds, carrying the\n * 1-based reconnect count — the resync hook. Omitting drops reconnect events\n * silently.\n */\n onReconnect?: (attempt: number, sub: S) => M | null;\n /** First backoff delay in ms (doubles each failed attempt). Default 250. */\n backoffBaseMs?: number;\n /** Backoff ceiling in ms. Default 5000. */\n backoffMaxMs?: number;\n /** Inject the socket constructor (defaults to the global `WebSocket`); the test seam. */\n connect?: (url: string) => MinimalWebSocket;\n /** Inject the timer (defaults to `setTimeout`/`clearTimeout`); the test seam. */\n schedule?: (fn: () => void, ms: number) => CancelTimer;\n}\n\nconst defaultConnect = (url: string): MinimalWebSocket => new WebSocket(url);\n\nconst defaultSchedule = (fn: () => void, ms: number): CancelTimer => {\n const handle = setTimeout(fn, ms);\n return () => clearTimeout(handle);\n};\n\nexport function fromReconnectingWebSocket<\n S extends Sub<string, WebSocketSubData>,\n M,\n>(\n opts: ReconnectingWebSocketFactoryOpts<S, M>,\n): SubscribeHandler<S, M, unknown> {\n const backoffBaseMs = opts.backoffBaseMs ?? 250;\n const backoffMaxMs = opts.backoffMaxMs ?? 5000;\n const connect = opts.connect ?? defaultConnect;\n const schedule = opts.schedule ?? defaultSchedule;\n\n const { onMessage, onOpen, onError, onClose, onReconnect } = opts;\n\n return (sub, _ctx, dispatch) => {\n let ws: MinimalWebSocket | null = null;\n let attempt = 0;\n let opened = false;\n let closedByCaller = false;\n let cancelReconnect: CancelTimer | null = null;\n\n const emit = (msg: M | null): void => dispatchIfPresent(dispatch, msg);\n\n const handleClose = (code: number, reason: string): void => {\n ws = null;\n if (onClose) emit(onClose(code, reason, sub));\n // A teardown the substrate initiated detaches handlers first, so this\n // path only runs for an UNEXPECTED close — reconnect with capped backoff.\n if (closedByCaller) return;\n const delay = Math.min(backoffBaseMs * 2 ** attempt, backoffMaxMs);\n attempt += 1;\n cancelReconnect = schedule(() => {\n cancelReconnect = null;\n if (!closedByCaller) open();\n }, delay);\n };\n\n function open(): void {\n const socket = connect(sub.deps.wsUrl);\n ws = socket;\n\n socket.onopen = (): void => {\n // `opened` BEFORE this open marks it a reconnect; `attempt` is the\n // pending count for the drop that triggered it (1-based once we reset).\n const reconnected = opened;\n const reconnectCount = attempt;\n attempt = 0;\n opened = true;\n if (onOpen) emit(onOpen(sub));\n if (reconnected && onReconnect) emit(onReconnect(reconnectCount, sub));\n };\n\n socket.onmessage = (event): void => {\n emit(onMessage(event.data, sub));\n };\n\n // `error` precedes `close`; let `close` drive the reconnect so there is\n // one path. The handler is still wired (as a no-op when the caller didn't\n // supply `onError`) so a platform error event has a sink.\n socket.onerror = onError\n ? (event): void => emit(onError(event, sub))\n : (): void => {};\n\n socket.onclose = (event): void => {\n handleClose(event.code, event.reason);\n };\n }\n\n open();\n\n return () => {\n // Deliberate teardown: cancel any pending reconnect, detach handlers so\n // the cleanup `close()` can't fire `onClose` or schedule a reconnect,\n // then close the live socket. After this the factory never re-opens.\n closedByCaller = true;\n if (cancelReconnect !== null) {\n cancelReconnect();\n cancelReconnect = null;\n }\n const socket = ws;\n ws = null;\n if (socket !== null) {\n socket.onopen = null;\n socket.onmessage = null;\n socket.onerror = null;\n socket.onclose = null;\n // 1000 = \"normal closure\" per RFC 6455 §7.4.1.\n socket.close(1000);\n }\n };\n };\n}\n","// ---------------------------------------------------------------------------\n// fromTimeout — universal `setTimeout`-shaped Sub factory.\n//\n// Same lifecycle shape as `fromInterval` minus the recurrence: the\n// scheduled callback fires once, the cleanup is `clearTimeout`. For the\n// common case — fire one Msg after a delay — the engine's built-in `timer`\n// Sub (`{ type: \"timer\", deps: (s) => cond ? { ms, msg } : null }`) needs no\n// runner at all; reach for this factory when the Msg is built from the Sub\n// rather than carried in its deps. Two observable consequences worth pinning:\n//\n// 1. The timer fires once per start. It does NOT re-arm while the Sub\n// stays on with the same deps — the engine leaves an unchanged Sub\n// running, and the handle is exhausted. A changed deps value (a new\n// `delayMs`, or any other field) is a new id, so the engine stops this\n// runner and starts a fresh one: that is how to re-arm.\n//\n// 2. Cleanup before the timer fires cancels the pending dispatch. This\n// is the \"cancel on state exit\" pattern: gate the Sub's `deps` on the\n// state where the timeout should be armed. When the state leaves it,\n// `deps` goes null, the engine stops the Sub, and the factory's\n// cleanup fires before the timer does.\n// ---------------------------------------------------------------------------\n\nimport type { Sub } from \"../index\";\nimport type { SubscribeHandler } from \"./types\";\n\ntype TimeoutSubData = { readonly delayMs: number };\n\nexport function fromTimeout<S extends Sub<string, TimeoutSubData>, M>(\n msgFn: (sub: S) => M,\n): SubscribeHandler<S, M, unknown> {\n return (sub, _ctx, dispatch) => {\n const handle = setTimeout(() => {\n dispatch(msgFn(sub));\n }, sub.deps.delayMs);\n return () => {\n clearTimeout(handle);\n };\n };\n}\n","// ---------------------------------------------------------------------------\n// fromWebSocket — universal `WebSocket` Sub factory. The symmetric sibling\n// of `fromEventSource`.\n//\n// WebSocket is the bidirectional streaming protocol used wherever the\n// server pushes events AND the client pushes commands on the same\n// connection. The constructor opens the connection, `onopen` fires once\n// on handshake, `onmessage` fires per server-pushed frame, `onerror`\n// fires on transient or permanent failure, `onclose` fires once on\n// teardown carrying `code` + `reason`. `close(code)` initiates a clean\n// shutdown from the client side.\n//\n// Four callbacks because four observable events ARE four concerns the\n// caller routinely cares about. `wsUrl` lives in the Sub's `deps`\n// (`WebSocketSubData`) — a changed `wsUrl` is a new id, so the engine closes\n// the old socket and opens one to the new url, as with `fromEventSource`.\n//\n// - `onMessage(data, sub)` — required. The platform delivers `data` as\n// `string | Blob | ArrayBuffer` depending on `binaryType` and the\n// server's frame type. The factory does NOT bake in a parse contract:\n// the callback receives the raw `unknown` and decides parse + Msg\n// shape. Returns `M | null`; null drops the dispatch.\n//\n// - `onOpen(sub)` — optional. Connection handshake succeeded. Useful\n// for \"show 'connected' indicator\" Msgs. Omitting drops open events\n// silently.\n//\n// - `onError(event, sub)` — optional. WebSocket's `error` event fires\n// on transient drops AND permanent failures; like SSE, most consumers\n// want one Msg (\"connection-errored\") without folding both into\n// `onMessage`'s discriminant. Omitting drops error events silently.\n//\n// - `onClose(code, reason, sub)` — optional. The connection is gone.\n// `code` is the WebSocket close code (1000 = clean, 1006 = abnormal,\n// etc.). `reason` is the server-supplied string (often empty).\n// Omitting drops close events silently.\n//\n// Cleanup is `close(1000)` — the IANA-registered clean-shutdown code.\n// The factory intentionally does NOT bake in registry semantics (e.g.\n// the extension's `ctx.wsRegistry` so `interpret.send_ws` can reach the\n// live socket): that's consumer glue. A consumer that needs the live\n// socket for outbound sends wires it from inside the subscribe handler\n// or keeps a hand-written Sub alongside this factory.\n// ---------------------------------------------------------------------------\n\nimport type { Sub } from \"../index\";\nimport type {\n MinimalCloseEvent,\n MinimalEvent,\n MinimalMessageEvent,\n MinimalWebSocketCtor,\n} from \"./platform\";\nimport { dispatchIfPresent, type SubscribeHandler } from \"./types\";\n\nexport type WebSocketSubData = { readonly wsUrl: string };\n\ndeclare const WebSocket: MinimalWebSocketCtor;\n\nexport interface WebSocketFactoryOpts<S, M> {\n onMessage: (data: unknown, sub: S) => M | null;\n onOpen?: (sub: S) => M | null;\n onError?: (event: MinimalEvent, sub: S) => M | null;\n onClose?: (code: number, reason: string, sub: S) => M | null;\n}\n\nexport function fromWebSocket<S extends Sub<string, WebSocketSubData>, M>(\n opts: WebSocketFactoryOpts<S, M>,\n): SubscribeHandler<S, M, unknown> {\n return (sub, _ctx, dispatch) => {\n const ws = new WebSocket(sub.deps.wsUrl);\n\n ws.onmessage = (event: MinimalMessageEvent): void => {\n // The platform delivers `data` as `unknown` — the factory hands it\n // through untouched and the caller chooses the parse strategy.\n dispatchIfPresent(dispatch, opts.onMessage(event.data, sub));\n };\n\n const onOpen = opts.onOpen;\n if (onOpen) {\n ws.onopen = (): void => {\n dispatchIfPresent(dispatch, onOpen(sub));\n };\n }\n\n const onError = opts.onError;\n if (onError) {\n ws.onerror = (event: MinimalEvent): void => {\n dispatchIfPresent(dispatch, onError(event, sub));\n };\n }\n\n const onClose = opts.onClose;\n if (onClose) {\n ws.onclose = (event: MinimalCloseEvent): void => {\n dispatchIfPresent(dispatch, onClose(event.code, event.reason, sub));\n };\n }\n\n return () => {\n // Detach the lifecycle handlers BEFORE close() so the consumer's\n // `onClose` Msg isn't fired from a teardown the substrate initiated.\n // Mirrors fromEventSource's removeEventListener pass.\n ws.onmessage = null;\n ws.onopen = null;\n ws.onerror = null;\n ws.onclose = null;\n // 1000 = \"normal closure\" per RFC 6455 §7.4.1.\n ws.close(1000);\n };\n };\n}\n","// ---------------------------------------------------------------------------\n// defineManagedResource — a Model-gated resource with a MANDATORY release.\n//\n// foldkit's ManagedResource, ported. The recurring shape: a resource whose\n// lifetime is \"while the machine is in phase X, hold Y open; on leaving X,\n// tear Y down\" — a checkpoint store, a span, a lease, a pooled connection.\n// Rule 9 says that is a Sub the substrate reconciles, NOT a start/end Cmd\n// pair hand-driven across cells. Hand-driving leaks: every transition cell\n// has to remember to end-then-start, and one missed cell leaks the resource\n// forever (the checkpoint-namespace leak this battery was built to kill).\n//\n// The author writes three things — `{ name, acquire, release }` — and gets\n// back a `.depKeyed(when)` entry for the machine's `subs` plus a `.subscribe`\n// runner for the `subscribe` table handed to `run`. The battery's `name` IS\n// its Sub type, so two managed resources in one machine are two Sub types,\n// each with its own runner — no router. The engine's reconcile does the rest:\n// - `when(state)` turns non-null → runner runs → `acquire(key, ctx)`.\n// - `when(state)` goes null → cleanup runs → `release(handle)`.\n// - the key changes (a new id) → old cleanup (release) + new acquire.\n// Same reconcile mechanism `fromTransport` rides for open/close — no new\n// kernel hook.\n//\n// THE ACQUIRE-AS-SUCCESS-VALUE DISCIPLINE\n// ----------------------------------------\n// `release` receives ONLY what `acquire` returned (the Handle). Nothing else\n// is in scope. So:\n// - An `acquire` that throws never produces a Handle, so `release` is never\n// called with a half-built resource — an interrupted acquire can't dangle.\n// - Whatever `release` needs to tear down must be captured INTO the Handle\n// by `acquire`. The Handle is the closure over the live resource.\n// `release` is NOT optional in the type. A managed resource without a teardown\n// is just a Cmd (Rule 5); the whole point of this battery is the guaranteed\n// teardown, so the type forces the author to write one.\n//\n// NEUTRAL MECHANISM — no policy. The battery knows `acquire`, `release`,\n// `name`, `key`. It does not know what a checkpoint, a span, or a socket is.\n// Could a reasonable machine want the opposite of any choice here? The only\n// choices are \"release is mandatory\" (yes — that's the contract) and \"release\n// runs on disappear OR key-change\" (yes — that's reconcile semantics, shared\n// with every other Sub). No Cloudflare, no audit domain.\n//\n// Strengthens invariant 4 (external lifecycle owned by the substrate — the\n// acquire/release pair rides the reconcile pass, never hand-driven by a cell)\n// and invariant 6 (no silent looseness — every live resource is a running Sub,\n// visible in `replay(...).subs`).\n// ---------------------------------------------------------------------------\n\nimport type { DepKeyedSub, Dispose, Sub } from \"../index\";\nimport { structuralHash } from \"../index\";\n\n/**\n * The running Sub of a managed resource named `N`: its `deps` is the lifetime\n * key. The consumer's Sub union (`types.sub`) includes it directly.\n */\nexport type ManagedResourceSub<N extends string, TKey> = Sub<N, TKey>;\n\nexport interface DefineManagedResourceOpts<\n N extends string,\n TKey,\n Handle,\n Ctx,\n> {\n /**\n * A short, stable name — and the resource's Sub `type`. The machine's\n * `subscribe` table holds this battery's runner under it, so it must be\n * unique among the machine's Sub types.\n */\n readonly name: N;\n\n /**\n * Build the resource. Runs when the resource's `deps` turns non-null.\n * The returned Handle is the ONLY thing `release` receives — capture\n * everything teardown needs into it. If `acquire` throws, the engine does\n * NOT register the Sub and `release` is never called (no dangling\n * half-built resource).\n */\n readonly acquire: (key: TKey, ctx: Ctx) => Handle;\n\n /**\n * Tear the resource down. Runs when the key goes null (phase exited) or\n * changes. MANDATORY — the guaranteed teardown is the reason this battery\n * exists.\n *\n * May be sync or async, and an async one is really awaited: the promise is\n * returned to the substrate, which tracks it and drains it inside `stop()`\n * (bounded by `run({ disposeTimeoutMs })`). So `await runtime.stop()` means\n * the release finished — the reading a host evicting an isolate acts on.\n * MID-RUN teardown (a phase exit, a key change) is still fire-and-forget\n * (Rule 2): the reconcile pass is synchronous by construction, so it starts\n * the release and moves on. A rejection is never a Msg — it reaches the\n * runtime's `onError` sink under `phase: \"sub-cleanup\"`.\n */\n readonly release: (handle: Handle) => void | Promise<void>;\n}\n\n/**\n * What the battery returns: a `.depKeyed(when)` entry for the machine's\n * `subs`, the `.subscribe` runner for the `subscribe` table handed to `run`,\n * and a `.get(key)` accessor so Cmd handlers can reach the live Handle while\n * the resource is held.\n */\nexport interface ManagedResourceBattery<N extends string, TKey, Handle, Ctx> {\n /** The battery's Sub type — its `name`. */\n readonly type: N;\n\n /**\n * The `subs` entry. `when(state)` returns the resource's KEY when it should\n * be held, or `null` when it should be torn down. The key is the Sub's\n * `deps`, so the engine derives the id from it: an unchanged key leaves the\n * resource alone, a changed key releases the old one and acquires anew.\n * Plain JSON-compatible data only — the id hash throws on anything else.\n */\n readonly depKeyed: <S>(\n when: (state: S) => TKey | null,\n ) => DepKeyedSub<S, ManagedResourceSub<N, TKey>>;\n\n /**\n * The runner for this battery's Sub type — hand it to `run` as\n * `subscribe: { [battery.type]: battery.subscribe }`. Runs `acquire` on\n * start, holds the Handle in the battery's handle table, and returns a\n * cleanup that runs `release` (and forgets the Handle) on stop.\n */\n readonly subscribe: (\n sub: ManagedResourceSub<N, TKey>,\n ctx: Ctx,\n // The managed resource dispatches no Msgs — acquire/release are pure\n // lifecycle. `dispatch` is accepted to match the runner shape and is\n // intentionally unused.\n dispatch: (msg: never) => void,\n ) => Dispose;\n\n /**\n * Accessor for the live Handle, keyed on `key` (the author's key, never the\n * derived Sub id). Returns `undefined` when the resource is not currently\n * held — the caller decides whether that is an error. A Cmd handler wires\n * its `ctx.getX(key)` through this, so the handler reads the SAME owner the\n * reconciler holds, never a hand-built duplicate.\n */\n readonly get: (key: TKey) => Handle | undefined;\n}\n\n/**\n * Build the battery. One call per managed resource at the machine's host\n * file.\n *\n * @example\n * ```ts\n * import {\n * defineMachine,\n * defineManagedResource,\n * type Interpret,\n * type ManagedResourceSub,\n * type Reducer,\n * } from \"@demlik/tea\";\n * import { run } from \"@demlik/tea/promise\";\n *\n * type RunId = string;\n * type State = { type: \"idle\" } | { type: \"running\"; runId: RunId };\n * type Msg = { type: \"start\"; runId: RunId } | { type: \"stop\" };\n * type Cmd = { type: \"start_graph\"; runId: RunId };\n * interface Ctx { readonly storage: Storage; readonly bucket: string }\n * declare class CheckpointSaver {\n * constructor(opts: { storage: Storage; bucket: string; runId: RunId });\n * save(step: string): Promise<void>;\n * clear(): Promise<void>;\n * }\n * declare const update: Reducer<State, Msg, Cmd>;\n * declare const ctx: Ctx;\n *\n * const checkpointStore = defineManagedResource<\"checkpoint\", RunId, CheckpointSaver, Ctx>({\n * name: \"checkpoint\",\n * acquire: (runId, ctx) =>\n * new CheckpointSaver({ storage: ctx.storage, bucket: ctx.bucket, runId }),\n * release: (saver) => saver.clear(),\n * });\n *\n * // In the machine:\n * const machine = defineMachine({\n * types: {\n * model: {} as State,\n * msg: {} as Msg,\n * cmd: {} as Cmd,\n * sub: {} as ManagedResourceSub<\"checkpoint\", RunId>,\n * ctx: {} as Ctx,\n * },\n * init: (loaded) => [loaded ?? { type: \"idle\" }, []],\n * update,\n * subs: [\n * checkpointStore.depKeyed((s: State) =>\n * s.type === \"running\" ? s.runId : null,\n * ),\n * ],\n * });\n *\n * // In interpret (read the live handle the reconciler holds):\n * const interpret: Interpret<Msg, Cmd, Ctx> = {\n * start_graph: async (cmd) => {\n * const saver = checkpointStore.get(cmd.runId); // same owner, no rebuild\n * await saver?.save(\"started\");\n * },\n * };\n *\n * // At run:\n * run(machine, { ctx, interpret, subscribe: { checkpoint: checkpointStore.subscribe } });\n * ```\n */\nexport function defineManagedResource<N extends string, TKey, Handle, Ctx>(\n opts: DefineManagedResourceOpts<N, TKey, Handle, Ctx>,\n): ManagedResourceBattery<N, TKey, Handle, Ctx> {\n // Handle table — one live resource per key. Lives in this closure for the\n // lifetime of the battery (the machine's lifetime). Interpret-local; never\n // crosses into reducer state. Same shape as `fromTransport`'s `live` map.\n // Keyed by the author's key, because `get` is called with that key and the\n // caller cannot know the derived Sub id.\n const held = new Map<string, Handle>();\n\n // Single-sourced on the kernel's `structuralHash`: `\"1\"` (string) and `1`\n // (number) render distinctly, so a key collision can't return/release the\n // wrong held handle; non-JSON keys throw loudly instead of silently returning\n // undefined.\n const keyString = (k: TKey): string => structuralHash(k);\n\n const subscribe = (\n sub: ManagedResourceSub<N, TKey>,\n ctx: Ctx,\n _dispatch: (msg: never) => void,\n ): Dispose => {\n // Acquire. A throw here propagates out of the reconcile pass (the engine\n // records it and re-throws after the diff) and the Sub is NOT registered\n // — so no cleanup runs and `held` stays clean. The\n // acquire-as-success-value discipline: no Handle, no release.\n const handle = opts.acquire(sub.deps, ctx);\n const k = keyString(sub.deps);\n held.set(k, handle);\n\n // Cleanup runs when the key goes null or changes. Forget the Handle first\n // so a concurrent `get` after teardown begins sees `undefined`, then\n // release.\n //\n // An async `release` is RETURNED, not swallowed: the substrate tracks the\n // promise and `stop()` awaits it (bounded), so `await runtime.stop()` means\n // the release finished. Attaching a `.catch` here and returning `void` was\n // the defect — a host doing `await stop(); env.evict()` dropped the isolate\n // mid-release, which is the leak this battery exists to prevent, moved to\n // shutdown. A rejection now reaches the runtime's `onError` under\n // `phase: \"sub-cleanup\"` instead of a `console.warn` nobody configured.\n return () => {\n held.delete(k);\n return opts.release(handle);\n };\n };\n\n return {\n type: opts.name,\n depKeyed: <S>(\n when: (state: S) => TKey | null,\n ): DepKeyedSub<S, ManagedResourceSub<N, TKey>> => ({\n type: opts.name,\n deps: when,\n }),\n subscribe,\n get: (key) => held.get(keyString(key)),\n };\n}\n","// ---------------------------------------------------------------------------\n// fromTransport — the SEAM battery.\n//\n// At every seam between two TEA-shaped processes (a DO ↔ its hands container,\n// a SW background ↔ a content script, a parent ↔ a child runtime), there is\n// the SAME hand-rolled boilerplate:\n//\n// 1. The inbound message stream — a Sub keyed on a phase, opened when the\n// machine enters the phase, closed when the machine leaves it.\n// 2. A transport-close detector — when the underlying channel drops, a\n// single Msg is dispatched (`*_lost`). NOT a Sub the consumer\n// re-publishes; the lifetime IS the inbound Sub's lifetime.\n// 3. The outbound side — a Cmd whose handler hands a value to the live\n// transport, looked up by an interpret-local handle table keyed on the\n// phase's run-identity.\n//\n// Every hand-rolled seam (`hands-inbound.ts`, `forwardOutbound`, the\n// `client_disconnected` Msg arm, the WS handle map) is the same three\n// pieces with different vocabularies. The battery bakes those three in.\n//\n// What the author writes:\n//\n// 1. The vocabulary (Inbound / Outbound types).\n// 2. ONE call: `fromTransport({ name, openTransport, parseInbound, ... })`.\n//\n// What the author NEVER writes again:\n//\n// - The runner, the `cleanup` Promise dance.\n// - The transport-close → `*_lost` Msg wiring.\n// - The \"find the live socket from inside an interpret handler\" lookup.\n// - The keepalive / heartbeat / sequence-number ceremony (none of those\n// belong in the machine — that's Rule 9: lifetime-bound resources are\n// Subs, not state-machine cells).\n//\n// The seam's `name` IS its Sub type, so two seams in one machine (`hands` +\n// `worker`) are two Sub types with two runners — they never collide.\n//\n// Host-pluggable: the battery takes a `TransportFactory`, not a concrete\n// WebSocket. A Durable Object passes a workerd `WebSocket` adapter; a worker\n// thread can pass a `MessagePort` adapter; an in-process test can pass a\n// stub. Same battery; three different hosts.\n//\n// Distinct from `fromWebSocket` / `fromReconnectingWebSocket` in this same\n// subpath, which own a CONCRETE `WebSocket` and are inbound-only. This battery\n// is transport-agnostic and duplex: it also owns the outbound handle table, so\n// a Cmd handler can reach the live channel without a hand-written registry.\n//\n// Strengthens invariant 4 (external events / observation enter as Subs;\n// lifecycle owned by the substrate — the inbound stream, the close\n// detection, AND the outbound handle are all owned by the battery's Sub\n// lifecycle, not hand-driven by the consumer's cells).\n// ---------------------------------------------------------------------------\n\nimport type { DepKeyedSub, Dispose, Sub } from \"../index\";\nimport { structuralHash } from \"../index\";\n\n/**\n * Duplex transport. The host (DO, worker thread, in-process bus) constructs\n * one from whatever the platform offers. `fromTransport` does not know what\n * a WebSocket is — it knows `send`, `onMessage`, `onClose`.\n */\nexport interface Transport {\n /** Send a string frame. Best-effort; failures are logged at the boundary. */\n send(data: string): void;\n /**\n * Subscribe to inbound frames. Returns a cleanup that removes the listener.\n * The battery wires this in its runner; cleanup runs when the seam's key\n * goes null or changes.\n */\n onMessage(listener: (data: string) => void): () => void;\n /**\n * Subscribe to a one-shot close. Returns a cleanup that removes the\n * listener. The battery dispatches `lostMsg` on close.\n */\n onClose(listener: () => void): () => void;\n /** Close the underlying channel cleanly. Called by the Sub cleanup. */\n close(): void;\n}\n\n/**\n * Factory the consumer wires to a platform-specific transport. The battery\n * passes the seam's key (`runId`, or whatever identity is on the phase) so\n * per-run transports can be addressed.\n */\nexport type TransportFactory<K> = (key: K) => Transport;\n\n/**\n * The running Sub of a seam named `N`: its `deps` is the seam key. The\n * consumer's Sub union (`types.sub`) includes it directly.\n */\nexport type TransportSub<N extends string, TKey> = Sub<N, TKey>;\n\nexport interface FromTransportOpts<\n N extends string,\n TKey,\n Inbound,\n Outbound,\n M,\n Ctx,\n> {\n /**\n * A short, stable name for this seam — and its Sub `type`. The machine's\n * `subscribe` table holds the seam's runner under it, so it must be unique\n * among the machine's Sub types.\n */\n readonly name: N;\n\n /**\n * Build the transport. The battery owns the lifetime; the factory is the\n * platform-specific constructor (`new WebSocket(...)` adapter on a DO,\n * `MessagePort` adapter in a worker, in-memory stub in tests).\n */\n readonly openTransport: (key: TKey, ctx: Ctx) => Transport;\n\n /**\n * Parse one inbound frame. The battery hands `unknown` through (boundary\n * parse is the consumer's responsibility per invariant 8). Returning\n * `null` drops the frame silently — useful for frames the seam doesn't\n * recognize at this layer (e.g. transport-level keepalive).\n */\n readonly parseInbound: (raw: string, key: TKey) => Inbound | null;\n\n /**\n * Map a parsed inbound to a domain Msg. Returning `null` drops the\n * dispatch (e.g. a transport-level pong that doesn't change domain state).\n */\n readonly onInbound: (inbound: Inbound, key: TKey) => M | null;\n\n /**\n * The Msg dispatched when the transport closes (peer gone, network\n * dropped, normal close). ONE Msg arm, not a Sub, not a heartbeat-derived\n * deadline — the transport's own close signal is the truth.\n */\n readonly lostMsg: (key: TKey) => M;\n\n /**\n * Serialize an outbound. Called by the Cmd handler the battery wires.\n * Pure data → string at the seam boundary.\n */\n readonly serializeOutbound: (outbound: Outbound) => string;\n}\n\n/**\n * What the battery returns: a `.depKeyed(when)` entry for the machine's\n * `subs`, the `.subscribe` runner for the `subscribe` table handed to `run`,\n * and a `send(key, outbound)` helper the consumer's Cmd handler calls.\n */\nexport interface TransportBattery<N extends string, TKey, Outbound, M, Ctx> {\n /** The seam's Sub type — its `name`. */\n readonly type: N;\n\n /**\n * The `subs` entry. `when(state)` returns the seam's KEY when it should be\n * open, or `null` when it should be torn down. The key is the Sub's `deps`,\n * so the engine derives the id from it: an unchanged key leaves the seam\n * open, a changed key closes it and opens a fresh one. Plain\n * JSON-compatible data only — the id hash throws on anything else.\n */\n readonly depKeyed: <S>(\n when: (state: S) => TKey | null,\n ) => DepKeyedSub<S, TransportSub<N, TKey>>;\n\n /**\n * The runner for this seam's Sub type — hand it to `run` as\n * `subscribe: { [seam.type]: seam.subscribe }`. Wires inbound + close in\n * one shot and publishes the live transport to the outbound handle table.\n */\n readonly subscribe: (\n sub: TransportSub<N, TKey>,\n ctx: Ctx,\n dispatch: (msg: M) => void,\n ) => Dispose;\n\n /**\n * Outbound send, addressed by the seam's key (never the derived Sub id,\n * which the caller cannot know). The Cmd handler calls this; the battery's\n * handle table (built when the runner started) routes to the live\n * transport. If the seam is closed (no running Sub), the send is dropped\n * honestly (logged, not thrown — the reducer already moved past caring,\n * same shape as Rule 2 fire-and-forget Cmds).\n */\n readonly send: (key: TKey, outbound: Outbound) => void;\n}\n\n/**\n * Build the battery. One call per seam at the machine's host file.\n *\n * @example\n * ```ts\n * import {\n * defineMachine,\n * fromTransport,\n * type Interpret,\n * type Reducer,\n * type Transport,\n * type TransportSub,\n * } from \"@demlik/tea\";\n * import { run } from \"@demlik/tea/promise\";\n *\n * type RunId = string;\n * type HandsInbound = { kind: \"said\"; text: string };\n * type HandsOutbound = { kind: \"do\"; action: string };\n * type State = { type: \"idle\" } | { type: \"auditing\"; runId: RunId };\n * type Msg =\n * | { type: \"hands_said\"; runId: RunId; inbound: HandsInbound }\n * | { type: \"hands_lost\"; runId: RunId };\n * type Cmd = { type: \"send_hands\"; runId: RunId; outbound: HandsOutbound };\n * interface Ctx { readonly openHandsWs: (runId: RunId) => Transport }\n * declare function parseHandsInbound(json: unknown): HandsInbound | null;\n * declare const update: Reducer<State, Msg, Cmd>;\n * declare const ctx: Ctx;\n *\n * const handsSeam = fromTransport<\"hands\", RunId, HandsInbound, HandsOutbound, Msg, Ctx>({\n * name: \"hands\",\n * openTransport: (runId, ctx) => ctx.openHandsWs(runId),\n * parseInbound: (raw) => parseHandsInbound(JSON.parse(raw)),\n * onInbound: (inbound, runId) => ({ type: \"hands_said\", runId, inbound }),\n * lostMsg: (runId) => ({ type: \"hands_lost\", runId }),\n * serializeOutbound: (out) => JSON.stringify(out),\n * });\n *\n * // In the machine:\n * const machine = defineMachine({\n * types: {\n * model: {} as State,\n * msg: {} as Msg,\n * cmd: {} as Cmd,\n * sub: {} as TransportSub<\"hands\", RunId>,\n * ctx: {} as Ctx,\n * },\n * init: (loaded) => [loaded ?? { type: \"idle\" }, []],\n * update,\n * subs: [\n * handsSeam.depKeyed((s: State) =>\n * s.type === \"auditing\" ? s.runId : null,\n * ),\n * ],\n * });\n *\n * // In interpret:\n * const interpret: Interpret<Msg, Cmd, Ctx> = {\n * send_hands: async (cmd) => { handsSeam.send(cmd.runId, cmd.outbound); },\n * };\n *\n * // At run:\n * run(machine, { ctx, interpret, subscribe: { hands: handsSeam.subscribe } });\n * ```\n */\nexport function fromTransport<\n N extends string,\n TKey,\n Inbound,\n Outbound,\n M,\n Ctx,\n>(\n opts: FromTransportOpts<N, TKey, Inbound, Outbound, M, Ctx>,\n): TransportBattery<N, TKey, Outbound, M, Ctx> {\n // Handle table — one live transport per key. Lives in this closure for the\n // lifetime of the battery (i.e. the machine's lifetime). Interpret-local;\n // never crosses into reducer state. The same shape as a brain's\n // `pending: Map<callId, deferred>`: imperative handles in a Map keyed on\n // run-identity, not on durable state — and on the author's key, not the\n // derived Sub id, because `send` is addressed by that key.\n const live = new Map<string, Transport>();\n\n // Single-sourced on the kernel's `structuralHash`: `\"1\"` (string) and `1`\n // (number) render distinctly, so a key collision can't mis-route an outbound\n // send or overwrite the wrong live transport; non-JSON keys throw loudly.\n const keyString = (k: TKey): string => structuralHash(k);\n\n const subscribe = (\n sub: TransportSub<N, TKey>,\n ctx: Ctx,\n dispatch: (msg: M) => void,\n ): Dispose => {\n const key = sub.deps;\n // Open the transport. The battery owns the lifetime.\n const t = opts.openTransport(key, ctx);\n const k = keyString(key);\n\n // ACQUIRE-AS-SUCCESS-VALUE: wire EVERYTHING first, publish to the handle\n // table last. An adapter over an already-CLOSING socket throws while\n // wiring; when `live.set` ran first, that left the transport in the table\n // with NO sub registered — so no cleanup ever ran, `send` wrote into a\n // half-wired seam with no inbound listener, and every subsequent reconcile\n // opened another one: an unbounded leak from one recoverable throw. On the\n // way out we undo exactly what we did (drop the listeners, close the\n // transport) and rethrow, so the substrate records the failure and the\n // battery holds nothing. Same discipline `defineManagedResource` states in\n // its own header — no Handle, no release.\n let offMessage: (() => void) | undefined;\n let offClose: (() => void) | undefined;\n try {\n // Wire inbound. Parse boundary lives here per invariant 8.\n offMessage = t.onMessage((raw) => {\n const parsed = opts.parseInbound(raw, key);\n if (parsed === null) return;\n const msg = opts.onInbound(parsed, key);\n if (msg === null) return;\n dispatch(msg);\n });\n\n // Wire close. ONE Msg arm — `*_lost`. No heartbeat, no sequence\n // numbers, no \"is the peer still alive\" derivation: the transport's\n // own close IS the liveness signal.\n offClose = t.onClose(() => {\n dispatch(opts.lostMsg(key));\n });\n } catch (err) {\n offMessage?.();\n offClose?.();\n try {\n t.close();\n } catch (closeErr) {\n // Boundary log: the wiring failure is the fact worth surfacing, and it\n // is about to be rethrown. A close that also fails must not replace it.\n console.warn(\n `[fromTransport:${opts.name}] close during failed wiring failed`,\n closeErr,\n );\n }\n throw err;\n }\n\n live.set(k, t);\n\n // Cleanup runs when the seam's key goes null or changes.\n return () => {\n offMessage?.();\n offClose?.();\n live.delete(k);\n try {\n t.close();\n } catch (err) {\n // Boundary log: cleanup-time close failures are fire-and-forget\n // (Rule 2). The reducer is already past caring.\n console.warn(`[fromTransport:${opts.name}] close failed`, err);\n }\n };\n };\n\n return {\n type: opts.name,\n\n depKeyed: <S>(\n when: (state: S) => TKey | null,\n ): DepKeyedSub<S, TransportSub<N, TKey>> => ({\n type: opts.name,\n deps: when,\n }),\n\n subscribe,\n\n send: (key, outbound) => {\n const t = live.get(keyString(key));\n if (t === undefined) {\n // Honest drop. The reducer's Cmd burst can race a `*_lost`\n // transition; the Cmd is fire-and-forget at that point.\n console.warn(\n `[fromTransport:${opts.name}] send dropped — no live transport for key`,\n keyString(key),\n );\n return;\n }\n t.send(opts.serializeOutbound(outbound));\n },\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { startLoop, builtinExtensions, liveWork } from './chunk-KWNCM6XM.js';
2
- import { subEntriesOf, applyCell, DriveFailedError, DriveStalledError } from './chunk-K4ETBNKS.js';
1
+ import { startLoop, builtinExtensions, liveWork } from './chunk-AHW2CLPT.js';
2
+ import { subEntriesOf, applyCell, DriveFailedError, DriveStalledError } from './chunk-AIIXV4XB.js';
3
3
 
4
4
  // src/promise/builtin-runners.ts
5
5
  function timer(sub, _ctx, dispatch) {
@@ -13,11 +13,16 @@ function run(machine, opts) {
13
13
  const interpretMap = opts.interpret ?? {};
14
14
  const subscribeTable = opts.subscribe;
15
15
  const builtins = builtinRunners;
16
+ function runnerFor(type) {
17
+ const runner = subscribeTable?.[type] ?? builtins[type];
18
+ if (runner === void 0) return void 0;
19
+ return (sub, ctx, dispatch) => runner(sub, ctx, dispatch);
20
+ }
16
21
  const handle = startLoop({
17
22
  init: machine.init,
18
23
  reduce: (state, msg) => applyCell(machine, state, msg),
19
24
  subs: subEntriesOf(machine),
20
- runnerFor: (type) => subscribeTable?.[type] ?? builtins[type],
25
+ runnerFor,
21
26
  handlerFor: (type) => interpretMap[type],
22
27
  store: opts.store,
23
28
  // `ctx` is conditionally optional (see `CtxArg`); default the nullish case
@@ -26,7 +31,12 @@ function run(machine, opts) {
26
31
  onError: opts.onError,
27
32
  disposeTimeoutMs: opts.disposeTimeoutMs ?? 5e3,
28
33
  idleCap: opts.__idleCap ?? 1e5,
29
- extensions: builtinExtensions(machine, opts)
34
+ extensions: builtinExtensions(machine, opts),
35
+ // Deferred: a runner that throws during a storeless boot fails before
36
+ // `startLoop` has returned the handle.
37
+ stopOnSubFailure: () => {
38
+ queueMicrotask(() => void handle.stop());
39
+ }
30
40
  });
31
41
  return handle;
32
42
  }
@@ -94,5 +104,5 @@ async function driveToDone(handle, start, isTerminal, opts = {}) {
94
104
  }
95
105
 
96
106
  export { driveToDone, run };
97
- //# sourceMappingURL=chunk-QWIPH4YH.js.map
98
- //# sourceMappingURL=chunk-QWIPH4YH.js.map
107
+ //# sourceMappingURL=chunk-H2ELKHI6.js.map
108
+ //# sourceMappingURL=chunk-H2ELKHI6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/promise/builtin-runners.ts","../src/promise/run.ts"],"names":[],"mappings":";;;;AAaA,SAAS,KAAA,CACP,GAAA,EACA,IAAA,EACA,QAAA,EACS;AACT,EAAA,MAAM,MAAA,GAAS,UAAA,CAAW,MAAM,QAAA,CAAS,GAAA,CAAI,KAAK,GAAG,CAAA,EAAG,GAAA,CAAI,IAAA,CAAK,EAAE,CAAA;AACnE,EAAA,OAAO,MAAM,aAAa,MAAM,CAAA;AAClC;AAGO,IAAM,cAAA,GAAiB,EAAE,KAAA,EAAM;;;AC4B/B,SAAS,GAAA,CAQd,SAMA,IAAA,EAyDyB;AAIzB,EAAA,MAAM,YAAA,GAAiB,IAAA,CACpB,SAAA,IAAa,EAAC;AAOjB,EAAA,MAAM,iBAAkB,IAAA,CAAiC,SAAA;AAGzD,EAAA,MAAM,QAAA,GAAW,cAAA;AAOjB,EAAA,SAAS,UAAU,IAAA,EAA8C;AAC/D,IAAA,MAAM,MAAA,GAAS,cAAA,GAAiB,IAAI,CAAA,IAAK,SAAS,IAAI,CAAA;AACtD,IAAA,IAAI,MAAA,KAAW,QAAW,OAAO,MAAA;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ACpB;AACF","file":"chunk-H2ELKHI6.js","sourcesContent":["/**\n * The Promise engine's built-in sub runners (#270 R1.1). A machine declares a\n * built-in Sub by type alone — `{ type: \"timer\", deps: (s) => ({ ms, msg }) }`\n * — and `run` starts it with the runner here unless `subscribe` names one of\n * the same type, which replaces it (#270 R2.1).\n */\n\nimport type { BuiltinSubType, Dispose, TimerSub } from \"../pure/core\";\n\n/**\n * `timer`: dispatch `deps.msg` once, `deps.ms` after the Sub starts. The engine\n * restarts it when `ms` or `msg` changes and clears it when the Sub stops.\n */\nfunction timer<M>(\n sub: TimerSub<M>,\n _ctx: unknown,\n dispatch: (msg: M) => void,\n): Dispose {\n const handle = setTimeout(() => dispatch(sub.deps.msg), sub.deps.ms);\n return () => clearTimeout(handle);\n}\n\n/** Every built-in runner, keyed by the Sub type it runs. */\nexport const builtinRunners = { timer } as const satisfies Record<\n BuiltinSubType,\n unknown\n>;\n","/**\n * @demlik/tea runtime — `run`: boot a machine and drive its serial dispatch loop\n * on Promises; `driveToDone`: run one to its terminal State.\n *\n * `run` is assembly. The loop itself is `src/internal/engine/loop.ts` — a small\n * core with no special case for any built-in, shared with the Effect engine —\n * and every built-in is an extension of it (`src/internal/engine/builtins.ts`),\n * built from `run`'s options in the order both engines share.\n */\n\nimport { builtinExtensions } from \"../internal/engine/builtins\";\nimport {\n type LiveWorkProbe,\n type LoopHandler,\n type LoopRunner,\n liveWork,\n startLoop,\n} from \"../internal/engine/loop\";\nimport type {\n Dispose,\n Interpret,\n Machine,\n RunHandlers,\n Sub,\n} from \"../pure/core\";\nimport { applyCell, type Cmd, subEntriesOf } from \"../pure/core\";\nimport type {\n BootingRuntime,\n CtxArg,\n OnError,\n Store,\n Supervision,\n TelemetrySink,\n} from \"../runtime-types\";\nimport { DriveFailedError, DriveStalledError } from \"../runtime-types\";\nimport { builtinRunners } from \"./builtin-runners\";\n\n// === run ===\n//\n// Returns a `BootingRuntime<S, M>` synchronously; boot runs as the FIRST entry\n// on the serial dispatch tail, awaited implicitly by every public method.\n//\n// Save-then-effects ordering is structural: every transition mutates state,\n// awaits `store.save(newState)`, then reconciles subscriptions, then runs\n// `interpret` for emitted cmds, then fires external listeners. The listeners\n// fire even when a Cmd handler throws: the dispatch rejects with the handler's\n// error, and every listener, observer, `on` handler and `done()` waiter still\n// hears the State that was installed and saved (#311). A throw in any effect\n// phase leaves the persisted state ahead of the host's belief about what\n// executed — the Railway discipline (`tryInterpret` in handlers) makes that\n// safe in practice.\nexport function run<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n E extends { type: string } = never,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n // `ctx` is a plain object (ADR 0020): tea does no dependency injection, so\n // a handler's services are whatever the host put on it. The Cmd handlers\n // arrive here, beside the machine and never on it (#251 R1.1). `NoInfer`\n // keeps them a check against the machine's `M` / `C` rather than a second\n // inference site that could widen either.\n opts: CtxArg<Ctx> &\n NoInfer<RunHandlers<M, C, U, Ctx>> & {\n store?: Store<S>;\n onError?: OnError;\n /**\n * The clock that stamps `at` on a `Cmd.define`d effect's settled Msg at\n * the interpret edge, and on each `telemetry` event. Defaults to\n * `Date.now`. Inject a fixed one for a deterministic run; a `replay` log\n * carries its own `at`s and never reads this.\n */\n clock?: () => number;\n /**\n * The SEMANTIC event projector. Maps one APPLIED transition `(msg, state)`\n * to zero-or-more public events of `E`; `[]` skips the transition. Maps the\n * machine's PRIVATE Msg vocabulary to NAMED events — the private names never\n * reach `on`'s `E` surface. Omit → `E = never` and `on` is uncallable. PURE.\n */\n events?: (msg: M, state: S) => readonly E[];\n /**\n * Declared policy for a reducer (`update`) throw. Always surfaced via\n * `onError` (`phase: \"reduce\"`); the strategy decides what the runtime does\n * next. Defaults to `\"stop\"`. See `Supervision`.\n */\n supervision?: Supervision<S, M>;\n /**\n * The run-terminality predicate — makes the run's outcome first-class. Fed to\n * `Runtime.result()` and `Runtime.done()`. PURE. Omit → never terminal.\n */\n terminal?: (state: S) => boolean;\n /**\n * A sink handed `{ seq, msgType, at }` for every applied transition —\n * the observe-only telemetry `withTelemetry` used to add by wrapping the\n * machine (#268). Fire-and-forget; see {@link TelemetrySink}.\n */\n telemetry?: TelemetrySink;\n /**\n * How long `stop()` waits for teardown work that returned a Promise (an\n * async `release` in `defineManagedResource`, an async Sub cleanup) before\n * giving up on it. Defaults to 5_000ms.\n *\n * `stop()` awaits those disposals so a host doing\n * `await runtime.stop(); env.evict()` cannot drop the isolate mid-release —\n * the leak the managed-resource battery exists to prevent, relocated to\n * shutdown. The bound is what keeps a release that never settles from\n * hanging the host: on expiry `stop()` reports a `DisposeTimeoutNotice`\n * (warn-only, like every `RuntimeDiscardNotice`) and resolves anyway,\n * because `stop()` resolving is a contract.\n */\n disposeTimeoutMs?: number;\n /**\n * Iteration cap for `idle()`'s quiescence wait. Defaults to 100_000. Test\n * seam only. Production code must not set it.\n *\n * @internal test-only\n */\n __idleCap?: number;\n },\n): BootingRuntime<S, M, E> {\n // `interpret` is optional when `C extends Cmd<never>`; default a missing map\n // to `{}` — a Cmd with no handler is skipped, invariant 6's forward progress\n // for a miswired consumer.\n const interpretMap = ((opts as { interpret?: Interpret<M, C, Ctx> })\n .interpret ?? {}) as Readonly<Record<string, LoopHandler<M> | undefined>>;\n\n // The runner for a Sub type: the one handed to `run` in `subscribe`, else\n // the engine's built-in of that name (#270 — a user entry overrides a\n // built-in). Looked up per start rather than merged once, so a handler table\n // that resolves its cells lazily (`/react` reads the latest render's) is\n // honoured.\n const subscribeTable = (opts as { subscribe?: unknown }).subscribe as\n | Readonly<Record<string, UserRunner<Ctx, M> | undefined>>\n | undefined;\n const builtins = builtinRunners as Readonly<\n Record<string, UserRunner<Ctx, M> | undefined>\n >;\n\n // A Promise runner has no failure channel of its own: the one failure the\n // engine sees is a throw while it starts, which the loop turns into a stopped\n // run (#309). So the runner is called with the three arguments it declares.\n function runnerFor(type: string): LoopRunner<Ctx, M> | undefined {\n const runner = subscribeTable?.[type] ?? builtins[type];\n if (runner === undefined) return undefined;\n return (sub, ctx, dispatch) => runner(sub, ctx, dispatch);\n }\n\n const handle = startLoop<S, M, C, Ctx>({\n init: machine.init,\n reduce: (state, msg) => applyCell<S, M, C>(machine, state, msg),\n subs: subEntriesOf<S>(machine),\n runnerFor,\n handlerFor: (type) => interpretMap[type],\n store: opts.store,\n // `ctx` is conditionally optional (see `CtxArg`); default the nullish case\n // to `{}` so the handler ctx and `init(loaded, ctx)` get a value.\n ctx: (opts.ctx ?? {}) as Ctx,\n onError: opts.onError,\n disposeTimeoutMs: opts.disposeTimeoutMs ?? 5_000,\n idleCap: opts.__idleCap ?? 100_000,\n extensions: builtinExtensions<S, M, C, E>(machine, opts),\n // Deferred: a runner that throws during a storeless boot fails before\n // `startLoop` has returned the handle.\n stopOnSubFailure: () => {\n queueMicrotask(() => void handle.stop());\n },\n });\n return handle as unknown as BootingRuntime<S, M, E> & LiveWorkProbe;\n}\n\n/** A runner as a caller hands it to `run` in `subscribe`. */\ntype UserRunner<Ctx, M> = (\n sub: Sub,\n ctx: Ctx,\n dispatch: (msg: M) => void,\n) => Dispose;\n\n/**\n * Is the runtime provably out of ways to transition on its own? True only when\n * the handle carries the `liveWork` read and it counts zero live Subs and zero\n * in-flight Cmds. A handle without the read (a wrapper that rebuilt the object\n * without spreading it) cannot be proven stalled, so the drive keeps waiting —\n * the pre-#68 contract, never a false stall.\n */\nfunction isStalled(runtime: object): boolean {\n const probe = (runtime as Partial<LiveWorkProbe>)[liveWork];\n if (probe === undefined) return false;\n const live = probe();\n return live.subs === 0 && live.cmds === 0;\n}\n\n/**\n * The outside-in stop, as a PAIR. A signal is only cancellation if something can\n * turn \"aborted\" into a transition this machine understands, and the kernel has\n * no built-in cancel Msg any more than it has a built-in terminal set — so the\n * `signal` and the `cancel` that reads it are one option, present together or\n * absent together. A discriminated union rather than two optional fields, on the\n * same reasoning as `AgentCompactionConfig`: a signal with no `cancel` is a stop\n * button wired to nothing, and that is a state worth making unrepresentable\n * rather than checking for.\n */\ntype DriveCancellation<S, M> =\n | {\n readonly signal?: undefined;\n readonly cancel?: undefined;\n }\n | {\n /**\n * Abort the run through this signal. On abort the drive dispatches\n * `cancel`'s Msg and resolves on the State that lands — it does NOT reject,\n * and a cancellation is never a `DriveFailedError`. Already aborted when\n * the drive is called → the cancel Msg goes in place of `start`, so the\n * run ends without the start's effects ever firing.\n */\n readonly signal: AbortSignal;\n /**\n * The Msg that settles this machine as cancelled, chosen off the current\n * State exactly as `start` is. PURE. It must land a State `isTerminal`\n * holds for — the drive resolves on the terminal predicate, not on the\n * abort — and that State should be DURABLE, or a reload resumes the run\n * its caller stopped.\n */\n readonly cancel: (state: S) => M;\n };\n\n/** Options for `driveToDone`. */\nexport type DriveToDoneOptions<\n S,\n M extends { type: string } = never,\n> = DriveCancellation<S, M> & {\n /**\n * Marks a terminal State as a FAILURE. A State this holds for ends the drive\n * like any terminal one — the runtime is stopped — but the drive REJECTS with\n * `DriveFailedError` carrying it instead of resolving. A failed State is\n * terminal by definition; it need not also satisfy `isTerminal`. Omit → the\n * drive never rejects on State, only on a runtime error.\n */\n readonly failed?: (state: S) => boolean;\n};\n\n/**\n * Drive a machine from `start` to its terminal State in one call, then tear the\n * runtime down. The one-shot shape every \"run this machine to done\" test and\n * caller boundary otherwise hand-wires as six steps — `await ready`, `observe`,\n * park a promise, `dispatch(start)`, `getState()`, `stop()` — with the observer\n * leak and the forgotten `stop` those six steps invite.\n *\n * Takes the handle `run()` returns (a `Runtime` extends it, so a booted one is\n * accepted too), awaits `ready`, dispatches `start`, and resolves with the first\n * State for which `isTerminal` holds. A machine that boots already terminal (a\n * rehydrated finished run) resolves on its boot State and `start` is never\n * dispatched — a finished run has nothing to set in motion. `start` may be a\n * function of the boot State instead of a Msg: a machine rehydrated MID-run\n * needs its resume Msg, not its start Msg, and only the boot State says which\n * (the agent's `agent_boot` vs `agent_start` is the case in point). The\n * observer is detached and `stop()` awaited on EVERY exit: resolve, `failed`,\n * a stall, a boot or dispatch throw, the quiescence cap.\n *\n * Rejections are typed, never silent:\n * - `DriveFailedError<S>` when `opts.failed` marks the final State — the State\n * rides on `error.state`.\n * - `DriveStalledError<S>` when `start`'s follow-up chain quiesces on a State\n * that is neither terminal nor `failed` and the runtime has no live Sub and\n * no Cmd in flight — nothing inside it can deliver another transition, so\n * waiting would be a hang with the runtime leaked. The stalled State rides\n * on `error.state`. A machine that CAN still move is not stalled: a live Sub\n * that delivers the terminal Msg after the dispatch\n * quiesces keeps the drive waiting, and it resolves on that State. What the\n * runtime cannot see — a dispatch from outside it after quiescence — does\n * not count as live; a machine that depends on one declares it as a Sub.\n * - `QuiescenceTimeoutError` when `start`'s follow-up chain never settles —\n * the SAME cap `dispatch` and `idle()` already reject on (invariant 6), not a\n * second clock. A livelocking machine surfaces as its own failure class.\n * - the boot error, or whatever `dispatch(start)` rejects with, otherwise.\n *\n * `isTerminal` is caller-supplied, exactly as `run()`'s `terminal` option is —\n * the kernel has no built-in terminal-set concept and this does not add one.\n *\n * Cancellation is the same story: `{ signal, cancel }` stops the drive from\n * outside, and it settles the run rather than escaping it. On abort the drive\n * dispatches `cancel`'s Msg and RESOLVES on the terminal State that transition\n * lands — no rejection, no `DriveFailedError`, no `AbortError`. That is the whole\n * point of routing a stop through the Model: the outcome is durable, so a killed\n * process resumes reading a run that ended instead of restarting one someone\n * stopped. A cancel that THROWS is the one abort that rejects: it lands\n * no State, so its error is what the drive has to report — and that holds\n * whether the `cancel` function throws synchronously or the fold it produced\n * throws later, since both leave the run with no State to settle on. A State the\n * caller's `failed` predicate marks rejects on an abort exit exactly as it does\n * anywhere else. In-flight effects are not recalled — a promise cannot be cancelled —\n * so they settle to their own end and `stop()` drains them as it always did;\n * keeping their results off the public channels is the machine's own business.\n * Omit the pair and every path here behaves exactly as it did before.\n *\n * @param handle the handle `run(machine, opts)` returned.\n * @param start the Msg that sets the run in motion, or a function choosing\n * it off the boot State. PURE.\n * @param isTerminal the terminal predicate over the machine's State. PURE.\n * @param opts an optional `failed` predicate and an optional\n * `{ signal, cancel }` pair (see {@link DriveToDoneOptions}).\n */\nexport async function driveToDone<\n S,\n M extends { type: string },\n E extends { type: string } = never,\n>(\n handle: BootingRuntime<S, M, E>,\n start: M | ((booted: S) => M),\n isTerminal: (state: S) => boolean,\n opts: DriveToDoneOptions<S, M> = {},\n): Promise<S> {\n const failed = opts.failed ?? (() => false);\n const settles = (state: S): boolean => isTerminal(state) || failed(state);\n let detach: (() => void) | undefined;\n let unlisten: (() => void) | undefined;\n try {\n const runtime = await handle.ready;\n // A run that rehydrated already terminal has nothing to start: resolve on\n // the boot State without dispatching, so `start`'s Cmds are never left in\n // flight for `stop()` to discard. Read BEFORE the signal so a run that\n // already ended keeps the outcome it ended on — an abort arriving after the\n // fact does not restate a finished run as cancelled.\n const booted = runtime.getState();\n // The one exit check every branch below shares: a State the caller's\n // `failed` predicate marks rejects, wherever the drive reached it.\n const outcome = (state: S): S => {\n if (failed(state)) throw new DriveFailedError(state);\n return state;\n };\n if (settles(booted)) return outcome(booted);\n // Attach BEFORE dispatching so a terminal transition landing inside the\n // start dispatch is caught.\n const terminal = new Promise<S>((resolve) => {\n detach = runtime.observe((_msg, state) => {\n if (settles(state)) resolve(state);\n });\n });\n // An abort mid-run enqueues the cancel Msg on the SAME serial tail every\n // other dispatch uses, so it lands between transitions rather than inside\n // one. Work already enqueued when the abort arrives still folds; work the\n // machine would have enqueued after it does not, because the cancelled State\n // is terminal and its verbs stop emitting. `dispatchOnce` (not `dispatch`)\n // because the cancel has no follow-up chain to drain. Its rejection is NOT\n // swallowed: only the cancel fold can land the terminal State on an abort,\n // so a cancel that throws leaves `terminal` with nothing to resolve it and\n // the drive would park forever (#170). `cancelFailed` carries that rejection\n // into whichever race the branch below awaits.\n let cancelFailed: Promise<never> | undefined;\n if (opts.signal !== undefined) {\n const { signal, cancel } = opts;\n let onCancelError!: (error: unknown) => void;\n cancelFailed = new Promise<never>((_resolve, reject) => {\n onCancelError = reject;\n });\n // The try covers the SYNCHRONOUS call site too, not just the dispatch it\n // returns: a caller-supplied `cancel` that throws before it ever produces\n // a Msg would otherwise escape this listener, and a listener's throw goes\n // nowhere — no caller frame to catch it, `terminal` still unresolved, the\n // drive parked exactly as #170 described (#174). Both throws are the same\n // fact — the cancel fold could not land a State — so both take the one\n // route out through `onCancelError`.\n const onAbort = () => {\n try {\n runtime.dispatchOnce(cancel(runtime.getState())).catch(onCancelError);\n } catch (error) {\n onCancelError(error);\n }\n };\n // Already aborted → cancel INSTEAD of starting, so `start`'s effects (a\n // model call, for the agent) never fire at all.\n if (signal.aborted) {\n onAbort();\n return outcome(await Promise.race([terminal, cancelFailed]));\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n unlisten = () => signal.removeEventListener(\"abort\", onAbort);\n }\n // The race lets a dispatch rejection (reducer / interpret throw, the\n // quiescence cap) surface here instead of floating as an unhandled rejection\n // while the terminal await parks forever.\n const msg = typeof start === \"function\" ? start(booted) : start;\n const started = runtime.dispatch(msg).then(() => {\n // Quiesced. A settling State already went through the observer, so\n // `terminal` is resolved; otherwise the wait is legitimate only while the\n // runtime itself can still transition. With no live Sub and no Cmd in\n // flight nothing is coming, and the wait becomes the hang #68 names.\n const parked = runtime.getState();\n if (!settles(parked) && isStalled(runtime)) {\n throw new DriveStalledError(parked);\n }\n return terminal;\n });\n // `cancelFailed` rides the race for the mid-run abort: `started` cannot\n // carry the cancel's rejection, having usually resolved long before the\n // abort arrives.\n const racers: Promise<S>[] = [terminal, started];\n if (cancelFailed !== undefined) racers.push(cancelFailed);\n return outcome(await Promise.race(racers));\n } finally {\n detach?.();\n // The abort listener outlives this call unless it is removed: a signal a\n // caller reuses across runs would otherwise accumulate one dispatch per run\n // it has already finished.\n unlisten?.();\n // `stop()` resolves by contract, so awaiting it here cannot mask the error\n // a rejecting branch above is carrying.\n await handle.stop();\n }\n}\n"]}
@@ -0,0 +1,119 @@
1
+ import { bindMachine } from './chunk-JVKU2UQC.js';
2
+ import { cmdContractOver, followUps, subEntriesOf, desiredSub } from './chunk-AIIXV4XB.js';
3
+
4
+ // src/testing/drive-loop.ts
5
+ var DEFAULT_MAX_ROUNDS = 100;
6
+ var DriveRoundsExceededError = class extends Error {
7
+ constructor(maxRounds, rounds, trace) {
8
+ super(
9
+ `@demlik/tea: drive did not settle within ${maxRounds} round(s) \u2014 the machine was still emitting work at round ${rounds}. The partial trace (${trace.length} entr${trace.length === 1 ? "y" : "ies"}) is on the error's \`trace\` field.`
10
+ );
11
+ this.maxRounds = maxRounds;
12
+ this.rounds = rounds;
13
+ this.trace = trace;
14
+ }
15
+ maxRounds;
16
+ rounds;
17
+ trace;
18
+ name = "DriveRoundsExceededError";
19
+ _tag = "DriveRoundsExceededError";
20
+ };
21
+ var DriveNoHandlerError = class extends Error {
22
+ constructor(cmdType, trace) {
23
+ super(
24
+ `@demlik/tea: drive found no interpret handler for Cmd type "${cmdType}" \u2014 the handlers record must answer every Cmd the machine emits.`
25
+ );
26
+ this.cmdType = cmdType;
27
+ this.trace = trace;
28
+ }
29
+ cmdType;
30
+ trace;
31
+ name = "DriveNoHandlerError";
32
+ _tag = "DriveNoHandlerError";
33
+ };
34
+ var TRACE_KEY = "driveTrace";
35
+ function annotateTrace(err, trace) {
36
+ if (typeof err !== "object" || err === null) return;
37
+ Object.defineProperty(err, TRACE_KEY, {
38
+ value: [...trace],
39
+ enumerable: false,
40
+ configurable: true,
41
+ writable: true
42
+ });
43
+ }
44
+ function driveTraceOf(err) {
45
+ if (typeof err !== "object" || err === null) return void 0;
46
+ const carried = err[TRACE_KEY];
47
+ return Array.isArray(carried) ? carried : void 0;
48
+ }
49
+ function driveContractOf(machine, clock) {
50
+ return cmdContractOver(machine.cmds ?? [], clock);
51
+ }
52
+ async function driveLoop(machine, initial, msg, ctx, maxRounds, engine) {
53
+ const bound = bindMachine(machine, ctx);
54
+ const { contract, cellFor, subs } = engine;
55
+ const trace = [];
56
+ let state = initial;
57
+ let pending = [msg];
58
+ let round = 0;
59
+ try {
60
+ subs?.reconcile(state);
61
+ while (pending.length > 0) {
62
+ round += 1;
63
+ if (round > maxRounds) {
64
+ throw new DriveRoundsExceededError(maxRounds, round, trace);
65
+ }
66
+ const folding = pending;
67
+ pending = [];
68
+ const emitted = [];
69
+ for (const next of folding) {
70
+ trace.push({ kind: "msg", msg: next });
71
+ const [advanced, cmds] = bound.step(state, next);
72
+ state = advanced;
73
+ emitted.push(...cmds);
74
+ subs?.reconcile(state);
75
+ }
76
+ for (const cmd of emitted) {
77
+ trace.push({ kind: "cmd", cmd });
78
+ const cell = cellFor(cmd.type);
79
+ if (cell === void 0) {
80
+ throw new DriveNoHandlerError(cmd.type, trace);
81
+ }
82
+ let refused;
83
+ const dispatch = (fired) => {
84
+ try {
85
+ contract.checkDispatch(cmd, fired);
86
+ } catch (error) {
87
+ refused ??= { error };
88
+ return;
89
+ }
90
+ pending.push(fired);
91
+ };
92
+ const settled = contract.settle(cmd, await cell(cmd, dispatch));
93
+ if (refused !== void 0) throw refused.error;
94
+ pending.push(...followUps(settled));
95
+ }
96
+ if (pending.length === 0 && subs !== void 0) {
97
+ pending = [...await subs.next() ?? []];
98
+ }
99
+ }
100
+ } catch (err) {
101
+ annotateTrace(err, trace);
102
+ throw err;
103
+ } finally {
104
+ await subs?.close();
105
+ }
106
+ return { state, trace };
107
+ }
108
+ function desiredSubs(machine, state) {
109
+ const desired = /* @__PURE__ */ new Map();
110
+ for (const entry of subEntriesOf(machine)) {
111
+ const sub = desiredSub(entry, state);
112
+ if (sub !== null) desired.set(sub.id, sub);
113
+ }
114
+ return desired;
115
+ }
116
+
117
+ export { DEFAULT_MAX_ROUNDS, DriveNoHandlerError, DriveRoundsExceededError, annotateTrace, desiredSubs, driveContractOf, driveLoop, driveTraceOf };
118
+ //# sourceMappingURL=chunk-H3MWNH7A.js.map
119
+ //# sourceMappingURL=chunk-H3MWNH7A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing/drive-loop.ts"],"names":[],"mappings":";;;;AAmDO,IAAM,kBAAA,GAAqB;AAq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AAK,IAAA,KAAS,KAAA,CAAA,EAAW;AAC9C,QAAA,OAAA,GAAU,CAAC,GAAK,MAAM,KAAK,IAAA,EAAK,IAAM,EAAG,CAAA;AAAA,MAC3C;AAAA,IACF;AAAA,EACF,SAAS,GAAA,EAAK;AAGZ,IAAA,aAAA,CAAc,KAAK,KAAK,CAAA;AACxB,IAAA,MAAM,GAAA;AAAA,EACR,CAAA,SAAE;AACA,IAAA,MAAM,MAAM,KAAA,EAAM;AAAA,EACpB;AAEA,EAAA,OAAO,EAAE,OAAO,KAAA,EAAM;AACxB;AAGO,SAAS,WAAA,CACd,SACA,KAAA,EAC0B;AAC1B,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAiB;AACrC,EAAA,KAAA,MAAW,KAAA,IAAS,YAAA,CAAgB,OAAO,CAAA,EAAG;AAC5C,IAAA,MAAM,GAAA,GAAM,UAAA,CAAW,KAAA,EAAO,KAAK,CAAA;AACnC,IAAA,IAAI,QAAQ,IAAA,EAAM,OAAA,CAAQ,GAAA,CAAI,GAAA,CAAI,IAAI,GAAG,CAAA;AAAA,EAC3C;AACA,EAAA,OAAO,OAAA;AACT","file":"chunk-H3MWNH7A.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The round loop both `drive`s run — `@demlik/tea/testing/promise` and\n// `@demlik/tea/testing/effect` — said once, so the two cannot drift.\n//\n// `bindMachine` hands back the Cmds a fold emitted and stops there; performing\n// them is the caller's. So every consumer test that exercises a Cmd-emitting\n// machine hand-writes the same fixture: step the Msg, await the real interpret\n// handler over each emitted Cmd, feed the settle Msg back, repeat until quiet,\n// with a hand-picked guard bound in the loop header. `drive` is that fixture as\n// one call, and this file is its loop. It composes `bindMachine`'s synchronous\n// 2-arg `step` and adds NO second reducer path.\n//\n// What differs per engine is only how one Cmd is performed and whether Subs\n// run, so an engine hands this loop a `cellFor` lookup and, optionally, a\n// `subs` driver. Everything else — the rounds, the trace, the `maxRounds`\n// bound, the `Cmd.define` edge and its dispatch check (#304) — is here.\n//\n// **It returns the history, not just the endpoint.** `{ state, trace }`, where\n// `trace` is every Msg folded and every Cmd dispatched in order, lets a test\n// assert on the SEQUENCE as well as the settled state, and the same trace's\n// Msgs replayed through `replay` from the same initial state reproduce the\n// returned state exactly.\n//\n// **Exhausting `maxRounds` fails the drive.** A driver that quietly returns a\n// half-driven state lets a test assert green on a machine that never settled.\n//\n// Strengthens invariant 9 (the testing surface is named and small).\n// ---------------------------------------------------------------------------\n\nimport {\n type AnyCmdDef,\n type Cmd,\n type CmdContract,\n cmdContractOver,\n desiredSub,\n followUps,\n type Machine,\n type Sub,\n subEntriesOf,\n} from \"../pure/core\";\nimport type { CtxArg } from \"../runtime-types\";\nimport { bindMachine } from \"./bind-machine\";\n\n/**\n * The default round bound when `opts.maxRounds` is omitted: **100**.\n *\n * A round is one drain of the pending Msgs plus one drain of the Cmds those\n * folds emitted, so a settling machine costs a handful; 100 is loose enough\n * that a legitimate retry ladder finishes inside it and tight enough that a\n * genuine cycle stops rather than hangs.\n */\nexport const DEFAULT_MAX_ROUNDS = 100;\n\n/**\n * One entry of a driven run's history, in dispatch order.\n *\n * - `msg` — a Msg folded through the machine's reducer. The seed Msg is the\n * first entry of every trace; every later one is a settle Msg a handler\n * returned (or fired through its injected `dispatch`), or a Msg a running\n * Sub emitted.\n * - `cmd` — a Cmd handed to an interpret handler. It is recorded BEFORE the\n * handler runs, so a trace recovered from a failed handler names the Cmd\n * that failed as its last entry.\n */\nexport type DriveTraceEntry<M, C> =\n | { readonly kind: \"msg\"; readonly msg: M }\n | { readonly kind: \"cmd\"; readonly cmd: C };\n\n/** What a settled `drive` hands back. */\nexport interface DriveResult<S, M, C> {\n /** The state after the machine went quiet — no Msg pending, no Cmd unperformed. */\n readonly state: S;\n /**\n * Every Msg folded and every Cmd dispatched, in order. Filtering it to its\n * `msg` entries and replaying those through `replay` from the same initial\n * state reproduces {@link DriveResult.state}.\n */\n readonly trace: readonly DriveTraceEntry<M, C>[];\n}\n\n/**\n * `drive`'s `ctx` field. `CtxArg` widened by exactly one case: a machine\n * declaring `ctx: undefined` in its `types` block — the pure shape every\n * how-to on this package writes — may omit it too. `CtxArg` alone keeps `ctx`\n * REQUIRED there, because `{}` is not assignable to `undefined`, which would\n * make the common pure call site spell `{ ctx: undefined }` to say nothing.\n * A machine whose `Ctx` carries a field a handler reads still requires it.\n */\nexport type DriveCtxArg<Ctx> = [undefined] extends [Ctx]\n ? { readonly ctx?: Ctx }\n : CtxArg<Ctx>;\n\n/**\n * The options both `drive`s take. `ctx` is conditionally optional (see\n * {@link DriveCtxArg}).\n */\nexport type DriveOptions<Ctx> = DriveCtxArg<Ctx> & {\n /**\n * The round bound. Exceeding it fails the drive with\n * {@link DriveRoundsExceededError}; `drive` never returns a half-driven\n * state. Defaults to {@link DEFAULT_MAX_ROUNDS} (100).\n */\n readonly maxRounds?: number;\n /**\n * The clock that stamps `at` on a `Cmd.define`d Cmd's minted `_ok` / `_err`\n * Msg — the one `run` takes. Defaults to `Date.now`; pin it for a test that\n * asserts on `at`.\n */\n readonly clock?: () => number;\n};\n\n/**\n * Raised when a driven machine is still emitting work after `maxRounds` rounds.\n * Follows the tea error dialect (`override readonly name`) and carries a `_tag`\n * discriminant, so a test branches on it by `instanceof` or on the tag.\n *\n * It carries the round count it stopped at and the PARTIAL trace up to that\n * point, which is what a test needs to see the cycle — the bound alone says\n * only that one exists.\n */\nexport class DriveRoundsExceededError<M, C> extends Error {\n override readonly name = \"DriveRoundsExceededError\";\n readonly _tag = \"DriveRoundsExceededError\" as const;\n constructor(\n /** The bound that was exceeded. */\n public readonly maxRounds: number,\n /** The round the driver stopped at — always `maxRounds + 1`. */\n public readonly rounds: number,\n /** Every Msg folded and Cmd dispatched before the driver gave up. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive did not settle within ${maxRounds} round(s) — the ` +\n `machine was still emitting work at round ${rounds}. The partial ` +\n `trace (${trace.length} entr${trace.length === 1 ? \"y\" : \"ies\"}) is ` +\n `on the error's \\`trace\\` field.`,\n );\n }\n}\n\n/**\n * Raised when a Cmd reaches `drive` with no handler for its `type` in the\n * handler record. The record's mapped type makes that a compile error at a\n * well-typed call site; this is the runtime arm for a handler record assembled\n * dynamically or cast.\n */\nexport class DriveNoHandlerError<M, C> extends Error {\n override readonly name = \"DriveNoHandlerError\";\n readonly _tag = \"DriveNoHandlerError\" as const;\n constructor(\n /** The Cmd `type` nothing in the handler record answered. */\n public readonly cmdType: string,\n /** Every Msg folded and Cmd dispatched before the miss. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive found no interpret handler for Cmd type ` +\n `\"${cmdType}\" — the handlers record must answer every Cmd the ` +\n `machine emits.`,\n );\n }\n}\n\n/** The key `drive` hangs a partial trace off a failure under. */\nconst TRACE_KEY = \"driveTrace\";\n\n/**\n * Hang `trace` off `err` on a non-enumerable property, so {@link driveTraceOf}\n * reads it back without changing how the error prints or serializes. A\n * non-object failure carries nothing.\n */\nexport function annotateTrace(err: unknown, trace: readonly unknown[]): void {\n if (typeof err !== \"object\" || err === null) return;\n Object.defineProperty(err, TRACE_KEY, {\n value: [...trace],\n enumerable: false,\n configurable: true,\n writable: true,\n });\n}\n\n/**\n * Read back the partial trace `drive` attached to an error a handler failed\n * with. Returns `undefined` for anything `drive` did not annotate.\n *\n * A failing handler's error leaves `drive` UNSWALLOWED — same value, same\n * `instanceof`, same `_tag` — so a test that already branches on the handler's\n * own error type keeps doing so. The trace rides along on a non-enumerable\n * property so it is recoverable without changing how the error prints or\n * serializes.\n */\nexport function driveTraceOf<M, C>(\n err: unknown,\n): readonly DriveTraceEntry<M, C>[] | undefined {\n if (typeof err !== \"object\" || err === null) return undefined;\n const carried = (err as Record<string, unknown>)[TRACE_KEY];\n return Array.isArray(carried)\n ? (carried as readonly DriveTraceEntry<M, C>[])\n : undefined;\n}\n\n// === The loop ===\n\n/**\n * Perform one Cmd and resolve with the handler's raw return, before the\n * `Cmd.define` edge reads it. The `dispatch` it is handed is already checked\n * (#304).\n */\nexport type DriveCell<M, C> = (\n cmd: C,\n dispatch: (msg: M) => void,\n) => Promise<unknown>;\n\n/** The Subs a drive runs, as the loop sees them. */\nexport interface DriveSubs<S, M> {\n /**\n * Start every Sub `state` wants that is not running, and stop every running\n * one it no longer wants — the engine's reconcile, after each fold.\n */\n readonly reconcile: (state: S) => void;\n /**\n * Wait for the next Msgs a running Sub emits. Resolves with every Msg\n * buffered by then, or with `undefined` once no Sub is left running; rejects\n * when a Sub failed.\n */\n readonly next: () => Promise<readonly M[] | undefined>;\n /** Stop every Sub still running. */\n readonly close: () => Promise<void>;\n}\n\n/** What one engine hands the shared loop. */\nexport interface DriveEngine<S, M, C> {\n /**\n * The edge and dispatch check over the machine's `Cmd.define` list. The\n * engine builds it (see {@link driveContractOf}) so a handler that settles\n * through `cmdEdgeOf(ctx)` mints into the same record the check reads.\n */\n readonly contract: CmdContract;\n /** The cell that performs a Cmd of `type`, or `undefined` when none does. */\n readonly cellFor: (type: string) => DriveCell<M, C> | undefined;\n /** The Subs to run beside the Cmds; an engine that runs none omits it. */\n readonly subs?: DriveSubs<S, M>;\n}\n\n/** The contract both `drive`s hold a machine's Cmds to (ADR 0021). */\nexport function driveContractOf(\n machine: { readonly cmds?: readonly AnyCmdDef[] },\n clock: () => number,\n): CmdContract {\n return cmdContractOver(machine.cmds ?? [], clock);\n}\n\n/**\n * Drive `machine` from `initial` through `msg`, performing every emitted Cmd\n * through `engine.cellFor`, until the machine goes quiet.\n *\n * One round is: fold every pending Msg, then perform every Cmd those folds\n * emitted, in order. A Msg a cell returns or dispatches is pending for the next\n * round. When nothing is pending and Subs are running, the loop waits for the\n * next Msgs they emit; it settles once no Msg is pending, no Cmd is unperformed\n * and no Sub is left running.\n *\n * Every error that leaves the loop carries the partial trace (see\n * {@link driveTraceOf}).\n */\nexport async function driveLoop<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n initial: S,\n msg: M,\n ctx: Ctx,\n maxRounds: number,\n engine: DriveEngine<S, M, C>,\n): Promise<DriveResult<S, M, C>> {\n const bound = bindMachine(machine, ctx);\n const { contract, cellFor, subs } = engine;\n\n const trace: DriveTraceEntry<M, C>[] = [];\n let state = initial;\n let pending: M[] = [msg];\n let round = 0;\n\n try {\n subs?.reconcile(state);\n while (pending.length > 0) {\n round += 1;\n if (round > maxRounds) {\n throw new DriveRoundsExceededError<M, C>(maxRounds, round, trace);\n }\n\n // Drain the round's Msgs first, THEN its Cmds. Swapping the buffer before\n // the fold is what keeps a settle Msg out of the round that produced it.\n const folding = pending;\n pending = [];\n const emitted: C[] = [];\n for (const next of folding) {\n trace.push({ kind: \"msg\", msg: next });\n const [advanced, cmds] = bound.step(state, next);\n state = advanced;\n emitted.push(...cmds);\n subs?.reconcile(state);\n }\n\n for (const cmd of emitted) {\n trace.push({ kind: \"cmd\", cmd });\n const cell = cellFor(cmd.type);\n if (cell === undefined) {\n throw new DriveNoHandlerError<M, C>(cmd.type, trace);\n }\n // The dispatch half of ADR 0021, as the engine applies it (#304): a\n // `Cmd.define`d handler may not send a `_ok` / `_err` it built itself.\n // That Msg is dropped, never folded, and the refusal fails the drive\n // once the cell settles, so a handler that catches it cannot hide it.\n let refused: { readonly error: unknown } | undefined;\n const dispatch = (fired: M): void => {\n try {\n contract.checkDispatch(cmd, fired);\n } catch (error) {\n refused ??= { error };\n return;\n }\n pending.push(fired);\n };\n const settled = contract.settle(cmd, await cell(cmd, dispatch));\n if (refused !== undefined) throw refused.error;\n // A returned list lands in order, as `run`'s loop enqueues it.\n pending.push(...followUps<M>(settled));\n }\n\n if (pending.length === 0 && subs !== undefined) {\n pending = [...((await subs.next()) ?? [])];\n }\n }\n } catch (err) {\n // Unswallowed: the failure's own value is what leaves the loop, so a\n // test's `instanceof` / `_tag` branch still lands.\n annotateTrace(err, trace);\n throw err;\n } finally {\n await subs?.close();\n }\n\n return { state, trace };\n}\n\n/** The Subs `machine` wants at `state`, keyed by the id the engines derive. */\nexport function desiredSubs<S>(\n machine: { readonly subs?: ReadonlyArray<unknown> },\n state: S,\n): ReadonlyMap<string, Sub> {\n const desired = new Map<string, Sub>();\n for (const entry of subEntriesOf<S>(machine)) {\n const sub = desiredSub(entry, state);\n if (sub !== null) desired.set(sub.id, sub);\n }\n return desired;\n}\n"]}