@demlik/tea 0.1.1 → 0.2.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 (150) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +8 -8
  3. package/dist/authed-call/index.d.ts +3 -3
  4. package/dist/authed-call/index.js +5 -5
  5. package/dist/await-terminal/index.d.ts +1 -1
  6. package/dist/await-terminal/index.js +2 -2
  7. package/dist/batch-window/index.d.ts +2 -2
  8. package/dist/batch-window/index.js +4 -4
  9. package/dist/cache/index.d.ts +2 -2
  10. package/dist/{chunk-EIZJTYKR.js → chunk-5KVHID6A.js} +4 -4
  11. package/dist/{chunk-EIZJTYKR.js.map → chunk-5KVHID6A.js.map} +1 -1
  12. package/dist/{chunk-RVJFGRGK.js → chunk-6GIGQT6C.js} +4 -4
  13. package/dist/chunk-6GIGQT6C.js.map +1 -0
  14. package/dist/{chunk-FH5RUIIL.js → chunk-6OUDPSSG.js} +3 -3
  15. package/dist/{chunk-FH5RUIIL.js.map → chunk-6OUDPSSG.js.map} +1 -1
  16. package/dist/{chunk-2WZHS4P2.js → chunk-6VDCTR7N.js} +25 -40
  17. package/dist/chunk-6VDCTR7N.js.map +1 -0
  18. package/dist/{chunk-BNJYE4AU.js → chunk-DYRKDCJI.js} +46 -16
  19. package/dist/chunk-DYRKDCJI.js.map +1 -0
  20. package/dist/{chunk-RGTPPF4U.js → chunk-EGWTT5XJ.js} +3 -3
  21. package/dist/{chunk-RGTPPF4U.js.map → chunk-EGWTT5XJ.js.map} +1 -1
  22. package/dist/{chunk-A56GNPI7.js → chunk-EMJTPHI7.js} +5 -23
  23. package/dist/chunk-EMJTPHI7.js.map +1 -0
  24. package/dist/{chunk-IFBQJYGI.js → chunk-FOGL3TC7.js} +3 -3
  25. package/dist/{chunk-IFBQJYGI.js.map → chunk-FOGL3TC7.js.map} +1 -1
  26. package/dist/{chunk-RVU3RBE6.js → chunk-G2U7DJHL.js} +6 -4
  27. package/dist/chunk-G2U7DJHL.js.map +1 -0
  28. package/dist/{chunk-WUV3PSCZ.js → chunk-HCEVHFJ7.js} +2 -2
  29. package/dist/chunk-HCEVHFJ7.js.map +1 -0
  30. package/dist/{chunk-EDGDR5XX.js → chunk-IK4S5DJN.js} +3 -3
  31. package/dist/{chunk-EDGDR5XX.js.map → chunk-IK4S5DJN.js.map} +1 -1
  32. package/dist/{chunk-EQRUAP2A.js → chunk-J6527VRQ.js} +2 -2
  33. package/dist/chunk-J6527VRQ.js.map +1 -0
  34. package/dist/{chunk-TAO4YOLO.js → chunk-M6UZT7HS.js} +3 -3
  35. package/dist/{chunk-TAO4YOLO.js.map → chunk-M6UZT7HS.js.map} +1 -1
  36. package/dist/{chunk-QGZW4W3E.js → chunk-SKAMZKTE.js} +3 -3
  37. package/dist/{chunk-QGZW4W3E.js.map → chunk-SKAMZKTE.js.map} +1 -1
  38. package/dist/{chunk-TC4HWABA.js → chunk-VFGKTGGC.js} +7 -7
  39. package/dist/{chunk-TC4HWABA.js.map → chunk-VFGKTGGC.js.map} +1 -1
  40. package/dist/{chunk-D5EQDLDV.js → chunk-ZDRN3YCE.js} +4 -4
  41. package/dist/{chunk-D5EQDLDV.js.map → chunk-ZDRN3YCE.js.map} +1 -1
  42. package/dist/{core-CymXZCeY.d.ts → core-BmlJOvxM.d.ts} +20 -1
  43. package/dist/deadline/index.d.ts +2 -2
  44. package/dist/deadline/index.js +3 -3
  45. package/dist/debounce/index.d.ts +6 -0
  46. package/dist/debounce/index.js +1 -1
  47. package/dist/do/index.d.ts +422 -315
  48. package/dist/do/index.js +173 -149
  49. package/dist/do/index.js.map +1 -1
  50. package/dist/{durable-effects-2MDxDs45.d.ts → durable-effects-9LxFpmh3.d.ts} +1 -1
  51. package/dist/extension/index.d.ts +1 -1
  52. package/dist/extension/index.js +3 -3
  53. package/dist/extension/react.js +3 -3
  54. package/dist/extension/subs/index.d.ts +2 -2
  55. package/dist/fan-out/index.d.ts +1 -1
  56. package/dist/idempotent-intake/index.d.ts +1 -1
  57. package/dist/index.d.ts +20 -3
  58. package/dist/index.js +2 -2
  59. package/dist/llm-call/index.d.ts +2 -2
  60. package/dist/llm-call/index.js +5 -5
  61. package/dist/machine-viz/index.d.ts +4 -4
  62. package/dist/machine-viz/index.js +4 -8
  63. package/dist/machine-viz/index.js.map +1 -1
  64. package/dist/mem/index.d.ts +1 -1
  65. package/dist/monitored-run/index.d.ts +2 -2
  66. package/dist/monitored-run/index.js +5 -5
  67. package/dist/node/index.d.ts +1 -1
  68. package/dist/paginated-walk/index.d.ts +2 -2
  69. package/dist/paginated-walk/index.js +5 -5
  70. package/dist/parity/index.d.ts +10 -4
  71. package/dist/parity/index.js +6 -5
  72. package/dist/parity/index.js.map +1 -1
  73. package/dist/pbt/arbitraries/index.d.ts +1 -1
  74. package/dist/pbt/index.d.ts +15 -8
  75. package/dist/pbt/index.js +5 -11
  76. package/dist/pbt/index.js.map +1 -1
  77. package/dist/pbt/runners/index.d.ts +1 -1
  78. package/dist/pbt/runners/index.js +3 -3
  79. package/dist/poller/index.d.ts +2 -2
  80. package/dist/poller/index.js +3 -3
  81. package/dist/prediction/index.d.ts +23 -2
  82. package/dist/prediction/index.js +2 -2
  83. package/dist/pure/index.d.ts +2 -2
  84. package/dist/pure/index.js +2 -2
  85. package/dist/react/index.d.ts +1 -1
  86. package/dist/react/index.js +8 -4
  87. package/dist/react/index.js.map +1 -1
  88. package/dist/reconciler/index.d.ts +2 -2
  89. package/dist/reconciler/index.js +5 -5
  90. package/dist/recorder/index.d.ts +1 -1
  91. package/dist/resilient-call/index.d.ts +45 -2
  92. package/dist/resilient-call/index.js +4 -4
  93. package/dist/retry-to-success/index.d.ts +109 -0
  94. package/dist/retry-to-success/index.js +35 -0
  95. package/dist/retry-to-success/index.js.map +1 -0
  96. package/dist/saga/index.d.ts +14 -1
  97. package/dist/saga/index.js.map +1 -1
  98. package/dist/snapshot/index.d.ts +1 -1
  99. package/dist/snapshot/index.js +3 -3
  100. package/dist/subs/index.d.ts +2 -2
  101. package/dist/testing/index.d.ts +1 -1
  102. package/dist/testing/index.js +2 -2
  103. package/dist/throttle/index.d.ts +9 -0
  104. package/dist/throttle/index.js +1 -1
  105. package/dist/throttled-input/index.d.ts +10 -2
  106. package/dist/throttled-input/index.js +6 -6
  107. package/dist/throttled-input/index.js.map +1 -1
  108. package/dist/token-refresh/index.d.ts +1 -1
  109. package/dist/token-refresh/index.js +3 -3
  110. package/dist/trace-replay/index.d.ts +1 -1
  111. package/dist/trace-replay/index.js +3 -3
  112. package/dist/{types-N9LZbdnr.d.ts → types-BoUWgwSm.d.ts} +1 -1
  113. package/dist/with-deadline/index.d.ts +1 -1
  114. package/dist/with-deadline/index.js +5 -24
  115. package/dist/with-deadline/index.js.map +1 -1
  116. package/dist/with-resilience/index.d.ts +2 -2
  117. package/dist/with-resilience/index.js +13 -36
  118. package/dist/with-resilience/index.js.map +1 -1
  119. package/dist/with-telemetry/index.d.ts +1 -1
  120. package/dist/with-telemetry/index.js +4 -29
  121. package/dist/with-telemetry/index.js.map +1 -1
  122. package/dist/work-queue/adapter.d.ts +1 -1
  123. package/dist/work-queue/index.d.ts +1 -1
  124. package/dist/work-queue/ops.d.ts +1 -1
  125. package/dist/workflow/index.d.ts +16 -10
  126. package/dist/workflow/index.js.map +1 -1
  127. package/package.json +8 -20
  128. package/dist/chunk-2WZHS4P2.js.map +0 -1
  129. package/dist/chunk-7VEG4KHB.js +0 -202
  130. package/dist/chunk-7VEG4KHB.js.map +0 -1
  131. package/dist/chunk-A56GNPI7.js.map +0 -1
  132. package/dist/chunk-BNJYE4AU.js.map +0 -1
  133. package/dist/chunk-EQRUAP2A.js.map +0 -1
  134. package/dist/chunk-RVJFGRGK.js.map +0 -1
  135. package/dist/chunk-RVU3RBE6.js.map +0 -1
  136. package/dist/chunk-WUV3PSCZ.js.map +0 -1
  137. package/dist/chunk-XRXKH7KA.js +0 -268
  138. package/dist/chunk-XRXKH7KA.js.map +0 -1
  139. package/dist/raft/demo.d.ts +0 -105
  140. package/dist/raft/demo.js +0 -172
  141. package/dist/raft/demo.js.map +0 -1
  142. package/dist/raft/index.d.ts +0 -548
  143. package/dist/raft/index.js +0 -7
  144. package/dist/raft/index.js.map +0 -1
  145. package/dist/raft/sim.d.ts +0 -222
  146. package/dist/raft/sim.js +0 -8
  147. package/dist/raft/sim.js.map +0 -1
  148. package/dist/raft/timeline.d.ts +0 -46
  149. package/dist/raft/timeline.js +0 -62
  150. package/dist/raft/timeline.js.map +0 -1
@@ -1,15 +1,15 @@
1
1
  import { Store, Runtime, BootingRuntime } from '../index.js';
2
- import { P as PendingEffectsRecorder, b as EffectOwed, a as EffectConfirmed } from '../durable-effects-2MDxDs45.js';
3
- export { D as DeliveryId, E as EffectLedgerEvent, O as OwedEffect, d as PendingEffectsLedger, c as applyEffectEvent, e as emptyLedger, f as foldLedger, i as isOwed, p as pendingEffectsLedger, s as survivingEffects } from '../durable-effects-2MDxDs45.js';
2
+ import { P as PendingEffectsRecorder, b as EffectOwed, a as EffectConfirmed } from '../durable-effects-9LxFpmh3.js';
3
+ export { D as DeliveryId, E as EffectLedgerEvent, O as OwedEffect, d as PendingEffectsLedger, c as applyEffectEvent, e as emptyLedger, f as foldLedger, i as isOwed, p as pendingEffectsLedger, s as survivingEffects } from '../durable-effects-9LxFpmh3.js';
4
4
  import { RetryPolicy, Rng } from '../retry-backoff/index.js';
5
- import { C as Cmd, S as Sub, M as Machine } from '../core-CymXZCeY.js';
6
- import { AgentTurn, AgentState, AgentMachineMsg, AgentEvent, AgentStatus } from '../agent/index.js';
5
+ import { C as Cmd, S as Sub, M as Machine } from '../core-BmlJOvxM.js';
6
+ import { AgentEvent, AgentTurn, AgentState, AgentMachineMsg, AgentStatus } from '../agent/index.js';
7
7
  import '../fan-out/index.js';
8
8
  import '../work-queue/index.js';
9
9
  import '../llm-call/index.js';
10
10
  import '../resilient-call/index.js';
11
11
  import '../cache/index.js';
12
- import '../types-N9LZbdnr.js';
12
+ import '../types-BoUWgwSm.js';
13
13
  import '../circuit-breaker/index.js';
14
14
  import '../deadline/index.js';
15
15
  import '../protocol-B5YmJr0d.js';
@@ -117,6 +117,13 @@ interface NextStep<I> {
117
117
  * A `/step` response — a discriminated union on `done`:
118
118
  * - `{ done: false, step }` — execute `step`, POST its result, ask again.
119
119
  * - `{ done: true, output }` — the run is terminal; `output` is its result.
120
+ *
121
+ * This is the ORIGINAL 2-arm INLINE contract, kept byte-identical: a host that
122
+ * resolves each step inside the held request returns exactly these two shapes.
123
+ * The not-ready arm ({@link StepWorking}) is a SEPARATE, opt-in type reachable
124
+ * only through the defer-resume hook — see {@link DeferredStepResponse}. Keeping
125
+ * `StepResponse` a strict subset is what makes inline adopters unaffected: their
126
+ * `if (r.done) … else r.step` narrowing never sees a third member.
120
127
  */
121
128
  type StepResponse<I, O> = {
122
129
  readonly done: false;
@@ -125,6 +132,37 @@ type StepResponse<I, O> = {
125
132
  readonly done: true;
126
133
  readonly output: O;
127
134
  };
135
+ /**
136
+ * The NOT-READY arm — the run is computing OUT-OF-BAND under a defer-resume host
137
+ * (Binclusive ADR 0035 / prod incident #1873: a non-blocking pull carrier must
138
+ * answer a pull with an explicit "computing, poll again" instead of holding the
139
+ * request across a multi-second step). The held `/step` request returns this
140
+ * IMMEDIATELY instead of inline-awaiting `engine.resume`; the hands re-poll
141
+ * (optionally after `retryAfterMs`) until the deferred compute lands in the
142
+ * durable checkpoint and a real {@link StepResponse} step/done arm is returned.
143
+ *
144
+ * It is a first-class discriminated member (`working: true`), NOT a hollow
145
+ * `{ done: false }` with an absent/stale `step` — the not-ready state is made
146
+ * representable so it can never be confused with a real pending step.
147
+ */
148
+ interface StepWorking {
149
+ readonly done: false;
150
+ readonly working: true;
151
+ /**
152
+ * Advisory earliest re-poll delay as a hint to the hands (ms to wait before
153
+ * the next pull). Purely advisory — a host may omit it and the hands fall back
154
+ * to their own backoff curve.
155
+ */
156
+ readonly retryAfterMs?: number;
157
+ }
158
+ /**
159
+ * The 3-arm response a DEFER-RESUME host returns — the inline {@link StepResponse}
160
+ * arms PLUS {@link StepWorking}. A superset of `StepResponse`, so a 2-arm value is
161
+ * assignable to it (the widening is safe for existing transports); discriminate
162
+ * with `if (r.done)` for terminal, then `"working" in r` for the not-ready arm,
163
+ * else the step arm.
164
+ */
165
+ type DeferredStepResponse<I, O> = StepResponse<I, O> | StepWorking;
128
166
  /**
129
167
  * Mint a fresh per-run capability token: 32 random bytes, hex-encoded. Uses the
130
168
  * Web Crypto `crypto.getRandomValues` available in the Workers runtime (and in
@@ -173,7 +211,8 @@ interface StepEngine<R, I, O> {
173
211
  /**
174
212
  * Settle the posted tool result into the run, then RESUME from the durable
175
213
  * checkpoint: dispatch the settle and run to DISPATCH-QUIESCENCE (e.g.
176
- * `dispatchToIdle(runtime, settleMsg)`). Called at most once per distinct
214
+ * `await runtime.dispatch(settleMsg)` — dispatch drains the follow-up chain
215
+ * by default, #50). Called at most once per distinct
177
216
  * `callId` — `stepHost` dedupes re-POSTs via `idempotent-intake` BEFORE
178
217
  * calling this, so the side effect runs exactly once. On the first request
179
218
  * (`posted === null`) `stepHost` skips settle and calls {@link nextStep}
@@ -201,6 +240,51 @@ interface StepHostConfig {
201
240
  */
202
241
  readonly giveUpAfterMs?: number;
203
242
  }
243
+ /**
244
+ * The DEFER-RESUME hook — the opt-in seam that drives `engine.resume` OUT of the
245
+ * held `/step` request. A non-blocking host (Binclusive audit carrier, ADR 0035)
246
+ * cannot inline-await a multi-second step inside the held request, so instead of
247
+ * `stepHost` calling `engine.resume` inline it hands the posted result to this
248
+ * hook to SETTLE-AND-ENQUEUE (record it durably, schedule the compute in a
249
+ * returning activation) and returns the {@link StepWorking} arm PROMPTLY. A later
250
+ * pull re-reads the durable next-step once {@link DeferResumeHook.settled} reports
251
+ * the enqueued compute has landed.
252
+ *
253
+ * Providing this hook is what flips `stepHost` from the 2-arm inline contract to
254
+ * the 3-arm deferred contract — see the `stepHost` overloads. Omit it and the
255
+ * host stays byte-identical inline.
256
+ */
257
+ interface DeferResumeHook<R> {
258
+ /**
259
+ * SETTLE-AND-ENQUEUE the posted result to resume OUT of the held request:
260
+ * durably record it and schedule the compute (e.g. `ctx.storage.setAlarm` or a
261
+ * queue) so a returning activation runs `engine.resume`. MUST return promptly —
262
+ * it never awaits the step compute. Called at most once per distinct `callId`
263
+ * (`stepHost` dedupes re-POSTs through `idempotent-intake` first), so a re-POST
264
+ * of the same step does not re-enqueue.
265
+ */
266
+ enqueue(runId: string, posted: StepResult<R>): void | Promise<void>;
267
+ /**
268
+ * Has the enqueued resume for `callId` COMPLETED and been written to the
269
+ * durable checkpoint? `false` ⇒ the held request returns {@link StepWorking}
270
+ * (poll again); `true` ⇒ `stepHost` reads the next step / terminal output off
271
+ * the now-advanced checkpoint, exactly as the inline path does.
272
+ */
273
+ settled(runId: string, callId: string): boolean | Promise<boolean>;
274
+ /**
275
+ * Optional advisory re-poll delay (ms) surfaced on the {@link StepWorking} arm
276
+ * so the hands can back off to the host's expected step latency.
277
+ */
278
+ retryAfterMs?: number;
279
+ }
280
+ /**
281
+ * `StepHostConfig` with the defer-resume hook engaged — the presence of
282
+ * `deferResume` is the type-level switch that selects the 3-arm response (see the
283
+ * `stepHost` overloads). Extends the inline config, so the alarm tuning is shared.
284
+ */
285
+ interface DeferStepHostConfig<R> extends StepHostConfig {
286
+ readonly deferResume: DeferResumeHook<R>;
287
+ }
204
288
  /**
205
289
  * A structured `/step` outcome `stepHost` returns — the response body plus the
206
290
  * HTTP status the consumer's route should send. Kept transport-agnostic (no
@@ -215,6 +299,21 @@ type StepOutcome<I, O> = {
215
299
  readonly error: string;
216
300
  };
217
301
  };
302
+ /**
303
+ * The `/step` outcome a DEFER-RESUME host returns — like {@link StepOutcome} but
304
+ * its 200 body is the 3-arm {@link DeferredStepResponse} (it can carry the
305
+ * not-ready arm). Returned only from the `deferResume` overload of `stepHost`;
306
+ * the inline overload keeps the narrower {@link StepOutcome}.
307
+ */
308
+ type DeferredStepOutcome<I, O> = {
309
+ readonly status: 200;
310
+ readonly body: DeferredStepResponse<I, O>;
311
+ } | {
312
+ readonly status: 401 | 404;
313
+ readonly body: {
314
+ readonly error: string;
315
+ };
316
+ };
218
317
  /**
219
318
  * Build the `/step` handler for a DO that drives one or more runs over the pull
220
319
  * carrier. Returns `handle(request, now)` — call it from the DO's `/step`
@@ -232,11 +331,20 @@ type StepOutcome<I, O> = {
232
331
  * @param engine the run-specific operations
233
332
  * @param config alarm tuning
234
333
  */
334
+ declare function stepHost<R, I, O>(ctx: StepCtx, engine: StepEngine<R, I, O>, config: DeferStepHostConfig<R>): {
335
+ handle(request: StepRequest<R>, now: number): Promise<DeferredStepOutcome<I, O>>;
336
+ };
235
337
  declare function stepHost<R, I, O>(ctx: StepCtx, engine: StepEngine<R, I, O>, config?: StepHostConfig): {
236
338
  handle(request: StepRequest<R>, now: number): Promise<StepOutcome<I, O>>;
237
339
  };
238
- /** The `/step` transport the hands POST through (injected; faked in tests). */
239
- type StepTransport<R, I, O> = (request: StepRequest<R>) => Promise<StepResponse<I, O>>;
340
+ /**
341
+ * The `/step` transport the hands POST through (injected; faked in tests).
342
+ * Returns the 3-arm {@link DeferredStepResponse} — a defer-resume host may answer
343
+ * with the not-ready arm, which {@link runStepLoop} re-polls. An inline host's
344
+ * 2-arm transport (`=> Promise<StepResponse>`) is assignable here (the narrower
345
+ * return widens), so existing inline adopters are unaffected.
346
+ */
347
+ type StepTransport<R, I, O> = (request: StepRequest<R>) => Promise<DeferredStepResponse<I, O>>;
240
348
  /** Execute one tool call and produce its result (the consumer's hands). */
241
349
  type ExecuteStep<I, R> = (step: NextStep<I>) => Promise<R> | R;
242
350
  /** Tuning for {@link runStepLoop}. */
@@ -283,6 +391,11 @@ type StepLoopOutcome<O> = {
283
391
  * not re-executed; its prior result is re-POSTed. Closes the "the host
284
392
  * re-handed the same step after a duplicate settle" path (the host side is
285
393
  * idempotent; the hands match it).
394
+ * - **not-ready re-poll** — a {@link StepWorking} arm (a defer-resume host
395
+ * computing the step out-of-band) is not a step: the loop re-POSTs the SAME
396
+ * `posted` after a backoff (honoring the host's advisory `retryAfterMs`),
397
+ * until a real step / done arrives. Bounded only by the absolute deadline —
398
+ * an inline host never returns this arm, so its drive is unchanged.
286
399
  */
287
400
  declare function runStepLoop<R, I, O>(token: string, runId: string, transport: StepTransport<R, I, O>, execute: ExecuteStep<I, R>, config: RunStepLoopConfig): Promise<StepLoopOutcome<O>>;
288
401
 
@@ -827,35 +940,253 @@ declare function rebuildProjection<Model, Msg extends {
827
940
  }[]): ProjectionRunner<Model, Msg, View>;
828
941
 
829
942
  /**
830
- * @demlik/tea/do — the minimum-viable Durable-Object HOST for a `@demlik/tea`
831
- * `createAgent` runtime.
943
+ * The runtime→SSE plumbing — the hub, its projection expression, and the
944
+ * semantic-event adapter. See `./host` for the transport-model rationale.
945
+ */
946
+
947
+ /**
948
+ * A set of SSE sinks plus the plumbing to fan an event out to all of them and
949
+ * to open a `text/event-stream` Response wired to a fresh sink.
950
+ *
951
+ * The consumer:
952
+ * 1. holds one `SseHub<E>` per DO,
953
+ * 2. calls `hub.emit(event)` from its Msg→event mapping (driven off
954
+ * `runtime.observe`), and
955
+ * 3. returns `hub.open()` from the `/sse` route.
956
+ *
957
+ * `register(sink)` exists for tests: subscribe a sink directly and observe the
958
+ * exact event sequence a live client would receive (a live `text/event-stream`
959
+ * fights vitest-pool-workers teardown). Deletes the consumer's `sseSinks` set,
960
+ * `openSse`, `emitSse`, and `onSseEvent`.
961
+ */
962
+ interface SseHub<E> {
963
+ emit(event: E): void;
964
+ open(): Response;
965
+ register(sink: (event: E) => void): () => void;
966
+ }
967
+ /** Build an SSE hub for event type `E` (the consumer's domain event shape). */
968
+ declare function sseHub<E>(): SseHub<E>;
969
+ /**
970
+ * Express an {@link SseHub} as a {@link Projection}. The projection's view is
971
+ * the latest emitted SSE event (or `null` before the first); `apply` maps each
972
+ * write-model update to an event via `toEvent` and emits it through `hub.emit`,
973
+ * so the SSE stream is driven by the SAME hub `sseHub()` returns — no API
974
+ * change for the `/sse` route (`hub.open()`) or any existing caller.
975
+ *
976
+ * - `toEvent(msg, model)` returns the SSE event for this update, or `null` to
977
+ * skip it (the view stays, nothing is emitted).
978
+ * - `name`/`key` default to `"sse"`/`"main"`; override for a second SSE view.
979
+ *
980
+ * @example
981
+ * const hub = sseHub<MyEvent>();
982
+ * const registry = projectionRegistry<MyState, MyMsg>();
983
+ * registry.register(sseProjection(hub, (msg) =>
984
+ * msg?.type === "turn_done" ? { kind: "turn", ... } : null,
985
+ * ));
986
+ * driveProjections(registry, runtime); // SSE is now one projection
987
+ * // /sse route unchanged:
988
+ * return hub.open();
989
+ */
990
+ declare function sseProjection<Model, Msg extends {
991
+ type: string;
992
+ }, E>(hub: SseHub<E>, toEvent: (msg: Msg | null, model: Model) => E | null, id?: {
993
+ name?: string;
994
+ key?: string;
995
+ }): Projection<Model, Msg, E | null>;
996
+ /**
997
+ * Wire an {@link SseHub} to a runtime's semantic {@link AgentEvent} stream (#47).
998
+ * For each event `type` the runtime can emit, subscribes via `runtime.on` and
999
+ * pushes `toFrame(event)` at the hub (returning `null` skips that event). The
1000
+ * runtime MUST have been built with `run(machine, { events: agentEvents() })`,
1001
+ * which is what makes `on` deliver the `AgentEvent`s. Returns a cleanup that
1002
+ * detaches every subscription.
1003
+ *
1004
+ * This is the runtime→SSE adapter expressed over the typed event channel: no
1005
+ * `observe` firehose, no private-Msg coupling. `hub.open()` and every existing
1006
+ * `sseHub` caller are unchanged — only the SOURCE of `hub.emit` moves from a
1007
+ * hand-rolled Msg switch to `on`.
832
1008
  *
833
- * `doStore` (in `./index`) is the durability half. This file is the rest of the
834
- * boilerplate a DO consumer hand-rolls every time it drives a tea agent over a
835
- * remote transport: the deferred-tool gateway, auto-boot on rehydrate, the
836
- * command-runner WS accept, the runtime→SSE plumbing, and a clean read of a
837
- * run's terminal output. Each export below names exactly the hand-rolled piece
838
- * it deletes from the consumer.
1009
+ * @example
1010
+ * const hub = sseHub<MyFrame>();
1011
+ * const runtime = await run(machine, { ctx, events: agentEvents() }).ready;
1012
+ * const off = sseFromAgentEvents(runtime, hub, (e) =>
1013
+ * e.type === "RunDone" ? { kind: "done", output: e.output } : null,
1014
+ * );
1015
+ * // /sse route unchanged:
1016
+ * return hub.open();
1017
+ */
1018
+ declare function sseFromAgentEvents<R, Frame>(runtime: {
1019
+ on<K extends AgentEvent<R>["type"]>(type: K, handler: (event: Extract<AgentEvent<R>, {
1020
+ type: K;
1021
+ }>) => void): () => void;
1022
+ }, hub: SseHub<Frame>, toFrame: (event: AgentEvent<R>) => Frame | null): () => void;
1023
+
1024
+ /**
1025
+ * `createAgentHost` — the runtime+events+autoBoot assembly + the test seam,
1026
+ * ONCE (issue #53). The facade over the concern modules: the deferred gateway
1027
+ * (`./deferred-gateway`), the WS carrier (`./command-socket`), the SSE plumbing
1028
+ * (`./sse`), and the cold-wake resume (`./resume`). See `./host` for the
1029
+ * transport-model rationale.
1030
+ */
1031
+
1032
+ /**
1033
+ * What the consumer supplies to {@link createAgentHost} — the domain mappings,
1034
+ * nothing of the wiring. `Stage`/`P`/`O`/`R` are the agent slice's type
1035
+ * parameters (the consumer names them once); `Frame` is its SSE event shape.
1036
+ * `C`/`U`/`Ctx` are the machine's own Cmd/Sub/Ctx — inferred from
1037
+ * `buildMachine` at the `createAgentHost` call site (never name them by hand;
1038
+ * an erased `any` here cost consumers all checking on this layer — #278).
1039
+ */
1040
+ interface AgentHostConfig<Stage, P extends string, O extends Record<P, AgentTurn>, R, Frame, C extends Cmd = Cmd, U extends Sub = Sub, Ctx = unknown> {
1041
+ /**
1042
+ * Build the wired agent machine. Called once per host build (per activation),
1043
+ * AFTER the previous runtime — if any — was torn down. The consumer wires its
1044
+ * per-tool interpret here (`agent.toMachine({ toolInterpret })`).
1045
+ */
1046
+ readonly buildMachine: () => Machine<AgentState<Stage, P, O, R>, AgentMachineMsg<P, O, R>, C, U, Ctx>;
1047
+ /** The durable `Store` for the agent slice (typically `doStore(storage, parse)`). */
1048
+ readonly store: Store<AgentState<Stage, P, O, R>>;
1049
+ /** The Ctx the machine threads to its interpret cells — checked against `buildMachine`'s. */
1050
+ readonly ctx: Ctx;
1051
+ /**
1052
+ * The run-terminality predicate (#46) — what makes `result()` first-class.
1053
+ * Defaults to the agent's own terminal phases (`done` / `failed`).
1054
+ */
1055
+ readonly terminal?: (state: AgentState<Stage, P, O, R>) => boolean;
1056
+ /**
1057
+ * Map one semantic {@link AgentEvent} to the consumer's SSE frame, or `null`
1058
+ * to skip it. This is the ONLY place the consumer touches the SSE seam — the
1059
+ * host owns the subscription wiring (`sseFromAgentEvents`) and the hub.
1060
+ */
1061
+ readonly toSseFrame: (event: AgentEvent<R>) => Frame | null;
1062
+ /** Clock injected for `autoBoot` (the host's only boot clock read). */
1063
+ readonly now?: () => number;
1064
+ }
1065
+ /**
1066
+ * The assembled host: the runtime cell + the SSE hub + the framework test seam,
1067
+ * owned ONCE. A DO holds one `AgentHost` and delegates to it; its own surface
1068
+ * shrinks to the domain (the gateway, the WS bridge, the command-send mapping).
839
1069
  *
840
- * ## The transport model: ONE Sub type, gateway-bridged I/O
1070
+ * @typeParam Stage Pipeline stage type.
1071
+ * @typeParam P Brain-call purposes.
1072
+ * @typeParam O Per-purpose outputs (bound to {@link AgentTurn}).
1073
+ * @typeParam R Tool result type.
1074
+ * @typeParam Frame The consumer's SSE event shape.
1075
+ */
1076
+ interface AgentHost<Stage, P extends string, O extends Record<P, AgentTurn>, R, Frame> {
1077
+ /**
1078
+ * Get (or build) the booted runtime. Build-once-boot-once: the first call
1079
+ * builds the machine, wires SSE off the semantic event stream, awaits the boot
1080
+ * gate, runs the `autoBoot` re-fire for a rehydrated suspended run, and caches
1081
+ * the booted `Runtime`; subsequent calls return the cached handle. The single
1082
+ * assembly every consumer used to hand-roll in `getRuntime()`.
1083
+ */
1084
+ runtime(): Promise<Runtime<AgentState<Stage, P, O, R>, AgentMachineMsg<P, O, R>, AgentEvent<R>>>;
1085
+ /**
1086
+ * The agent's lifecycle status (#49) — the ONE typed channel a consumer reads
1087
+ * instead of re-deriving `run.phase` / `awaiting` by hand. Ensures the runtime
1088
+ * is built + boot-reconciled first. Replaces the per-consumer `isSuspended` /
1089
+ * `runPhase` test methods (read `status().kind`).
1090
+ */
1091
+ status(): Promise<AgentStatus<Stage>>;
1092
+ /**
1093
+ * The run's terminal State (#46), or `undefined` while in flight. Read the
1094
+ * run's product off it (e.g. `result()?.output`). Replaces the per-consumer
1095
+ * `verdict` plumbing's source. Ensures the runtime is built first.
1096
+ */
1097
+ result(): Promise<AgentState<Stage, P, O, R> | undefined>;
1098
+ /**
1099
+ * The SSE hub — the route (`host.sse.open()`) AND the test seam
1100
+ * (`host.sse.register(sink)`). The host drives `hub.emit` off the semantic
1101
+ * event stream; the consumer never touches it except to open / register.
1102
+ */
1103
+ readonly sse: SseHub<Frame>;
1104
+ /**
1105
+ * Tear down the cached runtime (drain its tail via `stop()`, drop the handle)
1106
+ * so the next `runtime()` rebuilds from storage. The framework `settle` test
1107
+ * seam, owned once.
1108
+ */
1109
+ reset(): Promise<void>;
1110
+ }
1111
+ /**
1112
+ * Build an {@link AgentHost} from the consumer's domain mappings. Owns the
1113
+ * runtime+events+autoBoot assembly and the framework test seam — the wiring
1114
+ * issue #53 had every consumer re-write.
841
1115
  *
842
- * `createAgent().toMachine()` fixes the machine's Sub type to `DeadlineSub` —
843
- * the agent owns the retry + watchdog timers and nothing else. That is the
844
- * WHOLE Sub model for a DO-hosted agent, and it is coherent because the
845
- * transport deliberately does NOT live in the Sub system:
1116
+ * @example
1117
+ * const host = createAgentHost<Stage, Purpose, Outputs, ClientResult, SseEvent>({
1118
+ * buildMachine: () => agent.toMachine<Ctx>({ toolInterpret }),
1119
+ * store: doStore(storage, parse),
1120
+ * ctx,
1121
+ * toSseFrame: (e) =>
1122
+ * e.type === "ToolSettled" ? { kind: "result", ...} :
1123
+ * e.type === "TurnSettled" && e.turn.toolCalls.length === 0
1124
+ * ? { kind: "verdict", verdict: e.turn.content } :
1125
+ * e.type === "RunDone" ? { kind: "phase", phase: "done" } : null,
1126
+ * });
1127
+ * // route: return host.sse.open();
1128
+ * // start: await (await host.runtime()).dispatch({ type: "agent_start", ... });
1129
+ * // test: (await host.status()).kind === "suspended"
1130
+ */
1131
+ declare function createAgentHost<Stage, P extends string, O extends Record<P, AgentTurn>, R, Frame, C extends Cmd = Cmd, U extends Sub = Sub, Ctx = unknown>(config: AgentHostConfig<Stage, P, O, R, Frame, C, U, Ctx>): AgentHost<Stage, P, O, R, Frame>;
1132
+
1133
+ /**
1134
+ * The command-runner WebSocket host + broadcast — the WS half of the
1135
+ * `@demlik/tea/do` transport, in both the resident (`acceptCommandSocket`) and
1136
+ * hibernation-aware (`acceptDurableCommandSocket`) forms. See `./host` for the
1137
+ * transport-model rationale (ONE Sub type, gateway-bridged I/O).
1138
+ */
1139
+ /**
1140
+ * Accept a command-runner WebSocket on the DO's `fetch`. Adds the server end to
1141
+ * `clients`, wires `message` → `onFrame(data)` (string frames only) and
1142
+ * `close` → deregister, and returns the 101 upgrade Response.
846
1143
  *
847
- * - Inbound WebSocket frames are bridged straight into `gateway.settle(...)`
848
- * from the DO's `webSocketMessage` lifecycle method — a direct dispatch,
849
- * not a Sub.
850
- * - The per-tool deadline is a `setTimeout` inside the gateway — a timer, not
851
- * a DO alarm.
1144
+ * The consumer's `onFrame` parses the frame and calls `gateway.settle(callId,
1145
+ * result)` — the inbound bridge. Deletes the consumer's `acceptClient` method.
1146
+ */
1147
+ declare function acceptCommandSocket(clients: Set<WebSocket>, onFrame: (data: string) => void): Response;
1148
+ /**
1149
+ * Broadcast a JSON frame to every connected command-runner socket. A dead
1150
+ * socket is skipped (dropped on its own `close` event). Lifts the consumer's
1151
+ * fan-out loop in `sendCommand`.
1152
+ */
1153
+ declare function broadcast(clients: Set<WebSocket>, frame: unknown): void;
1154
+ /**
1155
+ * The slice of `DurableObjectState` the durable carrier needs: the Hibernation
1156
+ * API accept + the registry of hibernatable sockets. A real `DurableObjectState`
1157
+ * satisfies this structurally; a test supplies a fake (no live Workers runtime
1158
+ * needed to exercise the accept/registry seam).
1159
+ */
1160
+ interface HibernatableCtx {
1161
+ acceptWebSocket(ws: WebSocket): void;
1162
+ getWebSockets(): WebSocket[];
1163
+ }
1164
+ /**
1165
+ * Accept a command-runner WebSocket using the Cloudflare **Hibernation API** so
1166
+ * the socket survives DO eviction. Unlike {@link acceptCommandSocket}, this does
1167
+ * NOT attach an isolate-resident `message` listener (that listener is what dies
1168
+ * on eviction) — instead `ctx.acceptWebSocket(server)` hands the socket to the
1169
+ * runtime, which re-creates the DO and calls its `webSocketMessage(ws, data)`
1170
+ * lifecycle method on the next inbound frame. The consumer routes that method to
1171
+ * its `onFrame` (which calls `carrier.settle(callId, result)`).
852
1172
  *
853
- * The deferred-tool gateway owns each tool round-trip as a Promise the interpret
854
- * cell awaits; the transport bridges results into `dispatch` from outside the
855
- * Sub system. The agent's Sub type stays exactly `DeadlineSub` — there is no
856
- * competing DO-native Sub variant to union in, and the host needs none. This is
857
- * the single transport model for `@demlik/tea/do` (#52); see
858
- * `.patterns/tea/durable-actors.md` for the host-layer north star.
1173
+ * Returns the 101 upgrade Response. There is no `clients` registry to keep — the
1174
+ * live sockets are `ctx.getWebSockets()` (see {@link broadcastHibernatable}),
1175
+ * which the runtime repopulates after a wake.
1176
+ */
1177
+ declare function acceptDurableCommandSocket(ctx: HibernatableCtx): Response;
1178
+ /**
1179
+ * Broadcast a JSON frame to every hibernatable command-runner socket. The live
1180
+ * set is read from `ctx.getWebSockets()` (the runtime repopulates it after a
1181
+ * wake), NOT a resident `Set<WebSocket>` — so it is correct immediately after an
1182
+ * eviction, before any other lifecycle method has run. A dead socket is skipped.
1183
+ */
1184
+ declare function broadcastHibernatable(ctx: HibernatableCtx, frame: unknown): void;
1185
+
1186
+ /**
1187
+ * The deferred-tool gateway + its durable wrappers — the Promise-owning half of
1188
+ * the `@demlik/tea/do` transport. See `./host` for the transport-model
1189
+ * rationale (ONE Sub type, gateway-bridged I/O).
859
1190
  */
860
1191
 
861
1192
  /**
@@ -931,7 +1262,64 @@ declare function durableDeferredGateway<R>(inner: DeferredGateway<R>, recorder:
931
1262
  recordConfirmed(callId: string, event: EffectConfirmed): void;
932
1263
  }): DurableDeferredGateway<R>;
933
1264
  /**
934
- * The typed cold-wake resume port `bootResume` fires through — the agent's
1265
+ * The durable command carrier — a {@link DurableDeferredGateway} whose every
1266
+ * tool round-trip is also a durable owed effect.
1267
+ *
1268
+ * A consumer's tool interpret cell still calls `carrier.await(callId, send,
1269
+ * deadlineMs)` and awaits the Promise (mapping Ok/Err to `agent_tool_ok` /
1270
+ * `agent_tool_err`) — the SAME fast path as the volatile gateway. The addition
1271
+ * is durability: `await` hands the consumer an `effect_owed` event (via
1272
+ * `recordOwed`) to PERSIST before the send, and `settle`/`fail` hand it an
1273
+ * `effect_confirmed` (via `recordConfirmed`) to persist. On the next activation
1274
+ * the consumer reads its persisted ledger events back and calls
1275
+ * `reissueSurvivingEffects` (see `./resume`) to re-fire the survivors.
1276
+ *
1277
+ * It extends `DurableDeferredGateway` (so it is a drop-in for the gateway the
1278
+ * interpret cell already awaits) and exposes the underlying `recorder` for a
1279
+ * host that wants to read `surviving()` directly.
1280
+ */
1281
+ interface DurableCommandCarrier<R> extends DeferredGateway<R> {
1282
+ /** The ledger recorder backing this carrier (for `surviving()` introspection). */
1283
+ readonly recorder: PendingEffectsRecorder<{
1284
+ callId: string;
1285
+ }>;
1286
+ }
1287
+ /**
1288
+ * Build a durable command carrier over a (volatile) `DeferredGateway<R>` and a
1289
+ * `PendingEffectsRecorder`. Thin assembly over {@link durableDeferredGateway}:
1290
+ * it names the #91 piece — "the command carrier whose round-trips survive
1291
+ * eviction" — and keeps the recorder reachable for the activation-time re-emit.
1292
+ *
1293
+ * - `inner` — the volatile gateway whose in-isolate Promise the interpret cell
1294
+ * awaits (typically `deferredGateway<R>()`).
1295
+ * - `recorder` — the durable-effects recorder (typically
1296
+ * `pendingEffectsLedger({ events, lastId })` rehydrated from the persisted
1297
+ * log on a wake, or a fresh `pendingEffectsLedger()` on a cold boot).
1298
+ * - `hooks.recordOwed` / `hooks.recordConfirmed` — the persist callbacks the
1299
+ * consumer points at its event log (so the ledger survives eviction).
1300
+ *
1301
+ * The carrier never persists anything itself (it does not own the consumer's
1302
+ * log) — it hands the consumer the events, faithful to "persist the intent
1303
+ * before deliver".
1304
+ */
1305
+ declare function durableCommandCarrier<R>(inner: DeferredGateway<R>, recorder: PendingEffectsRecorder<{
1306
+ callId: string;
1307
+ }>, hooks: {
1308
+ recordOwed(callId: string, event: EffectOwed<{
1309
+ callId: string;
1310
+ }>): void;
1311
+ recordConfirmed(callId: string, event: EffectConfirmed): void;
1312
+ }): DurableCommandCarrier<R>;
1313
+
1314
+ /**
1315
+ * Cold-wake resume — the boot/hibernation re-fire path: the generalized
1316
+ * `bootResume` port, its agent specialization `autoBoot`, and the wake-time
1317
+ * re-emit of surviving tool round-trips. See `./host` for the transport-model
1318
+ * rationale.
1319
+ */
1320
+
1321
+ /**
1322
+ * The typed cold-wake resume port `bootResume` fires through — the agent's
935
1323
  * `AgentBootPort` (issue #60) generalized to any DO-hosted machine (issue #231).
936
1324
  *
937
1325
  * - `isResumable(state)` — true iff the rehydrated State is mid-loop and needs a
@@ -987,101 +1375,6 @@ declare function agentIsResumable<Stage, P extends string, O extends Record<P, u
987
1375
  declare function autoBoot<Stage, P extends string, O extends Record<P, unknown>, R, E extends {
988
1376
  type: string;
989
1377
  } = never>(booting: BootingRuntime<AgentState<Stage, P, O, R>, AgentMachineMsg<P, O, R>, E>, now?: () => number): Promise<void>;
990
- /**
991
- * Accept a command-runner WebSocket on the DO's `fetch`. Adds the server end to
992
- * `clients`, wires `message` → `onFrame(data)` (string frames only) and
993
- * `close` → deregister, and returns the 101 upgrade Response.
994
- *
995
- * The consumer's `onFrame` parses the frame and calls `gateway.settle(callId,
996
- * result)` — the inbound bridge. Deletes the consumer's `acceptClient` method.
997
- */
998
- declare function acceptCommandSocket(clients: Set<WebSocket>, onFrame: (data: string) => void): Response;
999
- /**
1000
- * Broadcast a JSON frame to every connected command-runner socket. A dead
1001
- * socket is skipped (dropped on its own `close` event). Lifts the consumer's
1002
- * fan-out loop in `sendCommand`.
1003
- */
1004
- declare function broadcast(clients: Set<WebSocket>, frame: unknown): void;
1005
- /**
1006
- * The slice of `DurableObjectState` the durable carrier needs: the Hibernation
1007
- * API accept + the registry of hibernatable sockets. A real `DurableObjectState`
1008
- * satisfies this structurally; a test supplies a fake (no live Workers runtime
1009
- * needed to exercise the accept/registry seam).
1010
- */
1011
- interface HibernatableCtx {
1012
- acceptWebSocket(ws: WebSocket): void;
1013
- getWebSockets(): WebSocket[];
1014
- }
1015
- /**
1016
- * Accept a command-runner WebSocket using the Cloudflare **Hibernation API** so
1017
- * the socket survives DO eviction. Unlike {@link acceptCommandSocket}, this does
1018
- * NOT attach an isolate-resident `message` listener (that listener is what dies
1019
- * on eviction) — instead `ctx.acceptWebSocket(server)` hands the socket to the
1020
- * runtime, which re-creates the DO and calls its `webSocketMessage(ws, data)`
1021
- * lifecycle method on the next inbound frame. The consumer routes that method to
1022
- * its `onFrame` (which calls `carrier.settle(callId, result)`).
1023
- *
1024
- * Returns the 101 upgrade Response. There is no `clients` registry to keep — the
1025
- * live sockets are `ctx.getWebSockets()` (see {@link broadcastHibernatable}),
1026
- * which the runtime repopulates after a wake.
1027
- */
1028
- declare function acceptDurableCommandSocket(ctx: HibernatableCtx): Response;
1029
- /**
1030
- * Broadcast a JSON frame to every hibernatable command-runner socket. The live
1031
- * set is read from `ctx.getWebSockets()` (the runtime repopulates it after a
1032
- * wake), NOT a resident `Set<WebSocket>` — so it is correct immediately after an
1033
- * eviction, before any other lifecycle method has run. A dead socket is skipped.
1034
- */
1035
- declare function broadcastHibernatable(ctx: HibernatableCtx, frame: unknown): void;
1036
- /**
1037
- * The durable command carrier — a {@link DurableDeferredGateway} whose every
1038
- * tool round-trip is also a durable owed effect.
1039
- *
1040
- * A consumer's tool interpret cell still calls `carrier.await(callId, send,
1041
- * deadlineMs)` and awaits the Promise (mapping Ok/Err to `agent_tool_ok` /
1042
- * `agent_tool_err`) — the SAME fast path as the volatile gateway. The addition
1043
- * is durability: `await` hands the consumer an `effect_owed` event (via
1044
- * `recordOwed`) to PERSIST before the send, and `settle`/`fail` hand it an
1045
- * `effect_confirmed` (via `recordConfirmed`) to persist. On the next activation
1046
- * the consumer reads its persisted ledger events back and calls
1047
- * {@link reissueSurvivingEffects} to re-fire the survivors.
1048
- *
1049
- * It extends `DurableDeferredGateway` (so it is a drop-in for the gateway the
1050
- * interpret cell already awaits) and exposes the underlying `recorder` for a
1051
- * host that wants to read `surviving()` directly.
1052
- */
1053
- interface DurableCommandCarrier<R> extends DeferredGateway<R> {
1054
- /** The ledger recorder backing this carrier (for `surviving()` introspection). */
1055
- readonly recorder: PendingEffectsRecorder<{
1056
- callId: string;
1057
- }>;
1058
- }
1059
- /**
1060
- * Build a durable command carrier over a (volatile) `DeferredGateway<R>` and a
1061
- * `PendingEffectsRecorder`. Thin assembly over {@link durableDeferredGateway}:
1062
- * it names the #91 piece — "the command carrier whose round-trips survive
1063
- * eviction" — and keeps the recorder reachable for the activation-time re-emit.
1064
- *
1065
- * - `inner` — the volatile gateway whose in-isolate Promise the interpret cell
1066
- * awaits (typically `deferredGateway<R>()`).
1067
- * - `recorder` — the durable-effects recorder (typically
1068
- * `pendingEffectsLedger({ events, lastId })` rehydrated from the persisted
1069
- * log on a wake, or a fresh `pendingEffectsLedger()` on a cold boot).
1070
- * - `hooks.recordOwed` / `hooks.recordConfirmed` — the persist callbacks the
1071
- * consumer points at its event log (so the ledger survives eviction).
1072
- *
1073
- * The carrier never persists anything itself (it does not own the consumer's
1074
- * log) — it hands the consumer the events, faithful to "persist the intent
1075
- * before deliver".
1076
- */
1077
- declare function durableCommandCarrier<R>(inner: DeferredGateway<R>, recorder: PendingEffectsRecorder<{
1078
- callId: string;
1079
- }>, hooks: {
1080
- recordOwed(callId: string, event: EffectOwed<{
1081
- callId: string;
1082
- }>): void;
1083
- recordConfirmed(callId: string, event: EffectConfirmed): void;
1084
- }): DurableCommandCarrier<R>;
1085
1378
  /**
1086
1379
  * RE-EMIT ON ACTIVATION (the #91 wake path). Given a durable carrier whose
1087
1380
  * recorder was rehydrated from the persisted ledger events (e.g.
@@ -1111,192 +1404,6 @@ declare function durableCommandCarrier<R>(inner: DeferredGateway<R>, recorder: P
1111
1404
  * they restore a suspended run's full in-flight state after a wake.
1112
1405
  */
1113
1406
  declare function reissueSurvivingEffects<R>(carrier: DurableCommandCarrier<R>, reissue: (callId: string) => void): readonly string[];
1114
- /**
1115
- * A set of SSE sinks plus the plumbing to fan an event out to all of them and
1116
- * to open a `text/event-stream` Response wired to a fresh sink.
1117
- *
1118
- * The consumer:
1119
- * 1. holds one `SseHub<E>` per DO,
1120
- * 2. calls `hub.emit(event)` from its Msg→event mapping (driven off
1121
- * `runtime.observe`), and
1122
- * 3. returns `hub.open()` from the `/sse` route.
1123
- *
1124
- * `register(sink)` exists for tests: subscribe a sink directly and observe the
1125
- * exact event sequence a live client would receive (a live `text/event-stream`
1126
- * fights vitest-pool-workers teardown). Deletes the consumer's `sseSinks` set,
1127
- * `openSse`, `emitSse`, and `onSseEvent`.
1128
- */
1129
- interface SseHub<E> {
1130
- emit(event: E): void;
1131
- open(): Response;
1132
- register(sink: (event: E) => void): () => void;
1133
- }
1134
- /** Build an SSE hub for event type `E` (the consumer's domain event shape). */
1135
- declare function sseHub<E>(): SseHub<E>;
1136
- /**
1137
- * Express an {@link SseHub} as a {@link Projection}. The projection's view is
1138
- * the latest emitted SSE event (or `null` before the first); `apply` maps each
1139
- * write-model update to an event via `toEvent` and emits it through `hub.emit`,
1140
- * so the SSE stream is driven by the SAME hub `sseHub()` returns — no API
1141
- * change for the `/sse` route (`hub.open()`) or any existing caller.
1142
- *
1143
- * - `toEvent(msg, model)` returns the SSE event for this update, or `null` to
1144
- * skip it (the view stays, nothing is emitted).
1145
- * - `name`/`key` default to `"sse"`/`"main"`; override for a second SSE view.
1146
- *
1147
- * @example
1148
- * const hub = sseHub<MyEvent>();
1149
- * const registry = projectionRegistry<MyState, MyMsg>();
1150
- * registry.register(sseProjection(hub, (msg) =>
1151
- * msg?.type === "turn_done" ? { kind: "turn", ... } : null,
1152
- * ));
1153
- * driveProjections(registry, runtime); // SSE is now one projection
1154
- * // /sse route unchanged:
1155
- * return hub.open();
1156
- */
1157
- declare function sseProjection<Model, Msg extends {
1158
- type: string;
1159
- }, E>(hub: SseHub<E>, toEvent: (msg: Msg | null, model: Model) => E | null, id?: {
1160
- name?: string;
1161
- key?: string;
1162
- }): Projection<Model, Msg, E | null>;
1163
- /**
1164
- * Wire an {@link SseHub} to a runtime's semantic {@link AgentEvent} stream (#47).
1165
- * For each event `type` the runtime can emit, subscribes via `runtime.on` and
1166
- * pushes `toFrame(event)` at the hub (returning `null` skips that event). The
1167
- * runtime MUST have been built with `run(machine, { events: agentEvents() })`,
1168
- * which is what makes `on` deliver the `AgentEvent`s. Returns a cleanup that
1169
- * detaches every subscription.
1170
- *
1171
- * This is the runtime→SSE adapter expressed over the typed event channel: no
1172
- * `observe` firehose, no private-Msg coupling. `hub.open()` and every existing
1173
- * `sseHub` caller are unchanged — only the SOURCE of `hub.emit` moves from a
1174
- * hand-rolled Msg switch to `on`.
1175
- *
1176
- * @example
1177
- * const hub = sseHub<MyFrame>();
1178
- * const runtime = await run(machine, { ctx, events: agentEvents() }).ready;
1179
- * const off = sseFromAgentEvents(runtime, hub, (e) =>
1180
- * e.type === "RunDone" ? { kind: "done", output: e.output } : null,
1181
- * );
1182
- * // /sse route unchanged:
1183
- * return hub.open();
1184
- */
1185
- declare function sseFromAgentEvents<R, Frame>(runtime: {
1186
- on<K extends AgentEvent<R>["type"]>(type: K, handler: (event: Extract<AgentEvent<R>, {
1187
- type: K;
1188
- }>) => void): () => void;
1189
- }, hub: SseHub<Frame>, toFrame: (event: AgentEvent<R>) => Frame | null): () => void;
1190
- /**
1191
- * Dispatch `msg` and resolve only once the runtime has drained every follow-up
1192
- * Msg the transition (transitively) enqueued — run-to-quiescence. Sugar over
1193
- * `await runtime.dispatch(msg); await runtime.idle();`.
1194
- *
1195
- * Replaces the consumer's / test's `until(() => cond)` poll after a `dispatch`
1196
- * for the common "dispatch, then let the loop settle" case. (A poll is still
1197
- * the right tool when waiting on an EXTERNAL event — e.g. a WS reply — that the
1198
- * runtime cannot enqueue itself.)
1199
- */
1200
- declare function dispatchToIdle<M extends {
1201
- type: string;
1202
- }>(runtime: Runtime<unknown, M>, msg: M): Promise<void>;
1203
- /**
1204
- * What the consumer supplies to {@link createAgentHost} — the domain mappings,
1205
- * nothing of the wiring. `Stage`/`P`/`O`/`R` are the agent slice's type
1206
- * parameters (the consumer names them once); `Frame` is its SSE event shape.
1207
- */
1208
- interface AgentHostConfig<Stage, P extends string, O extends Record<P, AgentTurn>, R, Frame> {
1209
- /**
1210
- * Build the wired agent machine. Called once per host build (per activation),
1211
- * AFTER the previous runtime — if any — was torn down. The consumer wires its
1212
- * per-tool interpret here (`agent.toMachine({ toolInterpret })`).
1213
- */
1214
- readonly buildMachine: () => Machine<AgentState<Stage, P, O, R>, AgentMachineMsg<P, O, R>, any, any, any>;
1215
- /** The durable `Store` for the agent slice (typically `doStore(storage, parse)`). */
1216
- readonly store: Store<AgentState<Stage, P, O, R>>;
1217
- /** The Ctx the machine threads to its interpret cells. */
1218
- readonly ctx: unknown;
1219
- /**
1220
- * The run-terminality predicate (#46) — what makes `result()` first-class.
1221
- * Defaults to the agent's own terminal phases (`done` / `failed`).
1222
- */
1223
- readonly terminal?: (state: AgentState<Stage, P, O, R>) => boolean;
1224
- /**
1225
- * Map one semantic {@link AgentEvent} to the consumer's SSE frame, or `null`
1226
- * to skip it. This is the ONLY place the consumer touches the SSE seam — the
1227
- * host owns the subscription wiring (`sseFromAgentEvents`) and the hub.
1228
- */
1229
- readonly toSseFrame: (event: AgentEvent<R>) => Frame | null;
1230
- /** Clock injected for `autoBoot` (the host's only boot clock read). */
1231
- readonly now?: () => number;
1232
- }
1233
- /**
1234
- * The assembled host: the runtime cell + the SSE hub + the framework test seam,
1235
- * owned ONCE. A DO holds one `AgentHost` and delegates to it; its own surface
1236
- * shrinks to the domain (the gateway, the WS bridge, the command-send mapping).
1237
- *
1238
- * @typeParam Stage Pipeline stage type.
1239
- * @typeParam P Brain-call purposes.
1240
- * @typeParam O Per-purpose outputs (bound to {@link AgentTurn}).
1241
- * @typeParam R Tool result type.
1242
- * @typeParam Frame The consumer's SSE event shape.
1243
- */
1244
- interface AgentHost<Stage, P extends string, O extends Record<P, AgentTurn>, R, Frame> {
1245
- /**
1246
- * Get (or build) the booted runtime. Build-once-boot-once: the first call
1247
- * builds the machine, wires SSE off the semantic event stream, awaits the boot
1248
- * gate, runs the `autoBoot` re-fire for a rehydrated suspended run, and caches
1249
- * the booted `Runtime`; subsequent calls return the cached handle. The single
1250
- * assembly every consumer used to hand-roll in `getRuntime()`.
1251
- */
1252
- runtime(): Promise<Runtime<AgentState<Stage, P, O, R>, AgentMachineMsg<P, O, R>, AgentEvent<R>>>;
1253
- /**
1254
- * The agent's lifecycle status (#49) — the ONE typed channel a consumer reads
1255
- * instead of re-deriving `run.phase` / `awaiting` by hand. Ensures the runtime
1256
- * is built + boot-reconciled first. Replaces the per-consumer `isSuspended` /
1257
- * `runPhase` test methods (read `status().kind`).
1258
- */
1259
- status(): Promise<AgentStatus<Stage>>;
1260
- /**
1261
- * The run's terminal State (#46), or `undefined` while in flight. Read the
1262
- * run's product off it (e.g. `result()?.output`). Replaces the per-consumer
1263
- * `verdict` plumbing's source. Ensures the runtime is built first.
1264
- */
1265
- result(): Promise<AgentState<Stage, P, O, R> | undefined>;
1266
- /**
1267
- * The SSE hub — the route (`host.sse.open()`) AND the test seam
1268
- * (`host.sse.register(sink)`). The host drives `hub.emit` off the semantic
1269
- * event stream; the consumer never touches it except to open / register.
1270
- */
1271
- readonly sse: SseHub<Frame>;
1272
- /**
1273
- * Tear down the cached runtime (drain its tail via `stop()`, drop the handle)
1274
- * so the next `runtime()` rebuilds from storage. The framework `settle` test
1275
- * seam, owned once.
1276
- */
1277
- reset(): Promise<void>;
1278
- }
1279
- /**
1280
- * Build an {@link AgentHost} from the consumer's domain mappings. Owns the
1281
- * runtime+events+autoBoot assembly and the framework test seam — the wiring
1282
- * issue #53 had every consumer re-write.
1283
- *
1284
- * @example
1285
- * const host = createAgentHost<Stage, Purpose, Outputs, ClientResult, SseEvent>({
1286
- * buildMachine: () => agent.toMachine<Ctx>({ toolInterpret }),
1287
- * store: doStore(storage, parse),
1288
- * ctx,
1289
- * toSseFrame: (e) =>
1290
- * e.type === "ToolSettled" ? { kind: "result", ...} :
1291
- * e.type === "TurnSettled" && e.turn.toolCalls.length === 0
1292
- * ? { kind: "verdict", verdict: e.turn.content } :
1293
- * e.type === "RunDone" ? { kind: "phase", phase: "done" } : null,
1294
- * });
1295
- * // route: return host.sse.open();
1296
- * // start: await (await host.runtime()).dispatch({ type: "agent_start", ... });
1297
- * // test: (await host.status()).kind === "suspended"
1298
- */
1299
- declare function createAgentHost<Stage, P extends string, O extends Record<P, AgentTurn>, R, Frame>(config: AgentHostConfig<Stage, P, O, R, Frame>): AgentHost<Stage, P, O, R, Frame>;
1300
1407
 
1301
1408
  /**
1302
1409
  * @demlik/tea/do — the idempotent-effect brick (the receiver/effect-side dedup).
@@ -1772,4 +1879,4 @@ interface DoStoreOptions<S> {
1772
1879
  */
1773
1880
  declare function doStore<S>(storage: DurableObjectStorage, parse: (raw: unknown) => S | null, keyOrOptions?: string | DoStoreOptions<S>): Store<S>;
1774
1881
 
1775
- export { type AgentHost, type AgentHostConfig, type AlarmStorage, type AppliedEffects, type AppliedEffectsEvent, type AppliedEffectsGuard, type AttachableSocket, type BroadcastOptions, type BroadcastReport, type DeferredGateway, type DoStoreOptions, type DurableCommandCarrier, type DurableTimer, type DurableTimerConfig, type EffectApplied, EffectConfirmed, type EffectForgotten, type EffectKey, EffectOwed, type EventLogRange, type EventSourcedOptions, type EventSourcedStore, type ExecuteStep, type HibernatableCtx, type IdempotentEffect, type IdempotentOutcome, type NextStep, PendingEffectsRecorder, type PersistedEvent, type PresenceCtx, type PresenceSocket, type PresenceUpgrade, type Projection, type ProjectionId, type ProjectionRegistry, type ProjectionRunner, type ProjectionUpdate, type RegisterOptions, type ResumePort, type RunStepLoopConfig, type SseHub, type StepCtx, type StepEngine, type StepHostConfig, type StepLoopOutcome, type StepOutcome, type StepRequest, type StepResponse, type StepResult, type StepTransport, WS_READY_STATE_OPEN, acceptCommandSocket, acceptDurableCommandSocket, acceptPresenceSocket, agentIsResumable, appliedEffects, applyAppliedEvent, autoBoot, bootResume, broadcast, broadcastFrame, broadcastHibernatable, constantTimeEqual, createAgentHost, deferredGateway, dispatchToIdle, doEventSourcedStore, doStore, driveProjections, durableCommandCarrier, durableDeferredGateway, durableTimer, emptyApplied, foldApplied, idempotentEffect, isApplied, mintRunToken, presenceCount, projectionIdString, projectionRegistry, rebuildProjection, registerHibernatableSocket, reissueSurvivingEffects, runProjection, runStepLoop, sseFromAgentEvents, sseHub, sseProjection, stepHost };
1882
+ export { type AgentHost, type AgentHostConfig, type AlarmStorage, type AppliedEffects, type AppliedEffectsEvent, type AppliedEffectsGuard, type AttachableSocket, type BroadcastOptions, type BroadcastReport, type DeferResumeHook, type DeferStepHostConfig, type DeferredGateway, type DeferredStepOutcome, type DeferredStepResponse, type DoStoreOptions, type DurableCommandCarrier, type DurableTimer, type DurableTimerConfig, type EffectApplied, EffectConfirmed, type EffectForgotten, type EffectKey, EffectOwed, type EventLogRange, type EventSourcedOptions, type EventSourcedStore, type ExecuteStep, type HibernatableCtx, type IdempotentEffect, type IdempotentOutcome, type NextStep, PendingEffectsRecorder, type PersistedEvent, type PresenceCtx, type PresenceSocket, type PresenceUpgrade, type Projection, type ProjectionId, type ProjectionRegistry, type ProjectionRunner, type ProjectionUpdate, type RegisterOptions, type ResumePort, type RunStepLoopConfig, type SseHub, type StepCtx, type StepEngine, type StepHostConfig, type StepLoopOutcome, type StepOutcome, type StepRequest, type StepResponse, type StepResult, type StepTransport, type StepWorking, WS_READY_STATE_OPEN, acceptCommandSocket, acceptDurableCommandSocket, acceptPresenceSocket, agentIsResumable, appliedEffects, applyAppliedEvent, autoBoot, bootResume, broadcast, broadcastFrame, broadcastHibernatable, constantTimeEqual, createAgentHost, deferredGateway, doEventSourcedStore, doStore, driveProjections, durableCommandCarrier, durableDeferredGateway, durableTimer, emptyApplied, foldApplied, idempotentEffect, isApplied, mintRunToken, presenceCount, projectionIdString, projectionRegistry, rebuildProjection, registerHibernatableSocket, reissueSurvivingEffects, runProjection, runStepLoop, sseFromAgentEvents, sseHub, sseProjection, stepHost };