@demlik/tea 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/dist/agent/index.d.ts +5 -5
- package/dist/agent/index.js +10 -10
- package/dist/authed-call/index.d.ts +3 -3
- package/dist/authed-call/index.js +7 -7
- package/dist/await-terminal/index.d.ts +2 -2
- package/dist/await-terminal/index.js +3 -2
- package/dist/await-terminal/index.js.map +1 -1
- package/dist/batch-window/index.d.ts +4 -4
- package/dist/batch-window/index.js +3 -3
- package/dist/cache/index.d.ts +2 -2
- package/dist/cache/index.js +4 -4
- package/dist/{chunk-TWDHNIY6.js → chunk-2KBEIGYP.js} +3 -3
- package/dist/{chunk-TWDHNIY6.js.map → chunk-2KBEIGYP.js.map} +1 -1
- package/dist/{chunk-LYLDCIPH.js → chunk-2UGTDYOK.js} +32 -25
- package/dist/chunk-2UGTDYOK.js.map +1 -0
- package/dist/{chunk-LJJV6ZD5.js → chunk-66S2KEQQ.js} +4 -4
- package/dist/{chunk-LJJV6ZD5.js.map → chunk-66S2KEQQ.js.map} +1 -1
- package/dist/{chunk-2AHAR7CX.js → chunk-A7USKARI.js} +3 -3
- package/dist/{chunk-2AHAR7CX.js.map → chunk-A7USKARI.js.map} +1 -1
- package/dist/{chunk-RMX4EOQK.js → chunk-ASX7PL2K.js} +3 -3
- package/dist/{chunk-RMX4EOQK.js.map → chunk-ASX7PL2K.js.map} +1 -1
- package/dist/{chunk-JFFVBEDI.js → chunk-AZ3NHUPD.js} +3 -3
- package/dist/{chunk-JFFVBEDI.js.map → chunk-AZ3NHUPD.js.map} +1 -1
- package/dist/{chunk-7FYQGDMF.js → chunk-AZZLE7XR.js} +3 -3
- package/dist/{chunk-7FYQGDMF.js.map → chunk-AZZLE7XR.js.map} +1 -1
- package/dist/{chunk-B5RAZVXW.js → chunk-EC6FO42Q.js} +6 -6
- package/dist/{chunk-B5RAZVXW.js.map → chunk-EC6FO42Q.js.map} +1 -1
- package/dist/{chunk-FCKP6N7Y.js → chunk-ERYY5P6W.js} +3 -3
- package/dist/{chunk-FCKP6N7Y.js.map → chunk-ERYY5P6W.js.map} +1 -1
- package/dist/{chunk-ET6QQNSQ.js → chunk-IVHQCVFX.js} +3 -3
- package/dist/{chunk-ET6QQNSQ.js.map → chunk-IVHQCVFX.js.map} +1 -1
- package/dist/{chunk-PBDYW2TU.js → chunk-O7ED34JH.js} +16 -3
- package/dist/chunk-O7ED34JH.js.map +1 -0
- package/dist/{chunk-SSHDBOXF.js → chunk-S6Y3RNX4.js} +4 -4
- package/dist/{chunk-SSHDBOXF.js.map → chunk-S6Y3RNX4.js.map} +1 -1
- package/dist/{chunk-5W7CNAHB.js → chunk-UV7VCTNC.js} +7 -7
- package/dist/{chunk-5W7CNAHB.js.map → chunk-UV7VCTNC.js.map} +1 -1
- package/dist/{chunk-2KNLKQVN.js → chunk-WF46FABO.js} +3 -3
- package/dist/{chunk-2KNLKQVN.js.map → chunk-WF46FABO.js.map} +1 -1
- package/dist/{chunk-SPWVPIFQ.js → chunk-XMHZ44QC.js} +4 -4
- package/dist/{chunk-SPWVPIFQ.js.map → chunk-XMHZ44QC.js.map} +1 -1
- package/dist/{chunk-JXYYRKD6.js → chunk-XOAP3LOT.js} +3 -3
- package/dist/{chunk-JXYYRKD6.js.map → chunk-XOAP3LOT.js.map} +1 -1
- package/dist/{chunk-D4NJBQAH.js → chunk-ZH454CR5.js} +97 -24
- package/dist/chunk-ZH454CR5.js.map +1 -0
- package/dist/{core-42kapW0n.d.ts → core-JPHsMZVB.d.ts} +9 -6
- package/dist/deadline/index.d.ts +2 -2
- package/dist/deadline/index.js +3 -3
- package/dist/do/index.d.ts +9 -9
- package/dist/do/index.js +10 -10
- package/dist/do/index.js.map +1 -1
- package/dist/{durable-effects-CFRngTNA.d.ts → durable-effects-MRnCBCxV.d.ts} +2 -2
- package/dist/extension/index.d.ts +2 -2
- package/dist/extension/index.js +3 -3
- package/dist/extension/react.js +3 -3
- package/dist/extension/subs/index.d.ts +2 -2
- package/dist/extension/test-utils.d.ts +1 -1
- package/dist/extension/test-utils.js.map +1 -1
- package/dist/fan-out/index.d.ts +2 -2
- package/dist/idempotent-intake/index.d.ts +2 -2
- package/dist/index.d.ts +18 -4
- package/dist/index.js +2 -2
- package/dist/llm-call/index.d.ts +3 -3
- package/dist/llm-call/index.js +7 -7
- package/dist/{machine-B_BF4jij.d.ts → machine-nGXCMyHn.d.ts} +3 -3
- package/dist/machine-viz/index.d.ts +1 -1
- package/dist/machine-viz/index.js +2 -2
- package/dist/mem/index.d.ts +2 -2
- package/dist/monitored-run/index.d.ts +4 -4
- package/dist/monitored-run/index.js +5 -5
- package/dist/node/index.d.ts +2 -2
- package/dist/paginated-walk/index.d.ts +3 -3
- package/dist/paginated-walk/index.js +7 -7
- package/dist/parity/index.d.ts +2 -2
- package/dist/parity/index.js +3 -3
- package/dist/pbt/arbitraries/index.d.ts +3 -3
- package/dist/pbt/arbitraries/index.js +1 -1
- package/dist/pbt/index.d.ts +1 -1
- package/dist/pbt/index.js +4 -4
- package/dist/pbt/runners/index.d.ts +1 -1
- package/dist/pbt/runners/index.js +3 -3
- package/dist/poller/index.d.ts +3 -3
- package/dist/poller/index.js +3 -3
- package/dist/prediction/index.d.ts +1 -1
- package/dist/prediction/index.js +2 -2
- package/dist/pure/index.d.ts +1 -1
- package/dist/pure/index.js +2 -2
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +2 -2
- package/dist/reconciler/index.d.ts +3 -3
- package/dist/reconciler/index.js +7 -7
- package/dist/recorder/index.d.ts +2 -2
- package/dist/resilient-call/index.d.ts +2 -2
- package/dist/resilient-call/index.js +6 -6
- package/dist/retry-to-success/index.js +2 -0
- package/dist/retry-to-success/index.js.map +1 -1
- package/dist/{runtime-types-CukV8kMX.d.ts → runtime-types-BbBq4LWo.d.ts} +50 -5
- package/dist/saga/index.d.ts +2 -2
- package/dist/snapshot/index.d.ts +1 -1
- package/dist/snapshot/index.js +3 -3
- package/dist/subs/index.d.ts +16 -9
- package/dist/subs/index.js +3 -3
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +2 -2
- package/dist/throttled-input/index.d.ts +2 -2
- package/dist/throttled-input/index.js +6 -6
- package/dist/token-refresh/index.d.ts +1 -1
- package/dist/token-refresh/index.js +3 -3
- package/dist/trace-replay/index.d.ts +2 -2
- package/dist/trace-replay/index.js +3 -3
- package/dist/{types-KbL3W1mj.d.ts → types-BMZ7IMrd.d.ts} +1 -1
- package/dist/with-deadline/index.d.ts +1 -1
- package/dist/with-deadline/index.js +2 -2
- package/dist/with-resilience/index.d.ts +2 -2
- package/dist/with-resilience/index.js +6 -6
- package/dist/with-telemetry/index.d.ts +1 -1
- package/dist/with-telemetry/index.js +2 -2
- package/dist/work-queue/adapter.d.ts +2 -2
- package/dist/work-queue/index.d.ts +3 -3
- package/dist/work-queue/index.js.map +1 -1
- package/dist/work-queue/ops.d.ts +2 -2
- package/dist/workflow/index.d.ts +3 -3
- package/package.json +12 -4
- package/dist/chunk-D4NJBQAH.js.map +0 -1
- package/dist/chunk-LYLDCIPH.js.map +0 -1
- package/dist/chunk-PBDYW2TU.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { detectUpdateForm, foldUpdates, structuralHash, applyCellChecked } from './chunk-
|
|
1
|
+
import { detectUpdateForm, foldUpdates, depsInactive, structuralHash, applyCellChecked } from './chunk-O7ED34JH.js';
|
|
2
2
|
import { Result } from 'better-result';
|
|
3
3
|
|
|
4
4
|
// src/observability.ts
|
|
@@ -62,6 +62,7 @@ var QuiescenceTimeoutError = class extends Error {
|
|
|
62
62
|
);
|
|
63
63
|
this.iterations = iterations;
|
|
64
64
|
}
|
|
65
|
+
iterations;
|
|
65
66
|
name = "QuiescenceTimeoutError";
|
|
66
67
|
_tag = "QuiescenceTimeoutError";
|
|
67
68
|
};
|
|
@@ -74,9 +75,34 @@ var RuntimeDiscardedError = class extends RuntimeDiscardNotice {
|
|
|
74
75
|
);
|
|
75
76
|
this.pendingCmds = pendingCmds;
|
|
76
77
|
}
|
|
78
|
+
pendingCmds;
|
|
77
79
|
name = "RuntimeDiscardedError";
|
|
78
80
|
_tag = "RuntimeDiscardedError";
|
|
79
81
|
};
|
|
82
|
+
var IdentityDropNotice = class extends RuntimeDiscardNotice {
|
|
83
|
+
constructor(msgType) {
|
|
84
|
+
super(
|
|
85
|
+
`@demlik/tea: Msg "${msgType}" was addressed to a different instance than this state owns and was dropped before \`update\` ran \u2014 the machine's \`identity\` filter working as declared. If this Msg was meant for THIS instance, its \`ofMsg\` projection disagrees with \`ofState\`; if the instance is being reused across runs, route the message to the run that owns it.`
|
|
86
|
+
);
|
|
87
|
+
this.msgType = msgType;
|
|
88
|
+
}
|
|
89
|
+
msgType;
|
|
90
|
+
name = "IdentityDropNotice";
|
|
91
|
+
_tag = "IdentityDropNotice";
|
|
92
|
+
};
|
|
93
|
+
var DisposeTimeoutNotice = class extends RuntimeDiscardNotice {
|
|
94
|
+
constructor(pendingDisposals, timeoutMs) {
|
|
95
|
+
super(
|
|
96
|
+
`@demlik/tea: stop() gave up waiting for ${pendingDisposals} async teardown(s) after ${timeoutMs}ms \u2014 the resources they release may still be open. Make \`release\` / the Sub cleanup settle (bound its own IO), or raise run({ disposeTimeoutMs }).`
|
|
97
|
+
);
|
|
98
|
+
this.pendingDisposals = pendingDisposals;
|
|
99
|
+
this.timeoutMs = timeoutMs;
|
|
100
|
+
}
|
|
101
|
+
pendingDisposals;
|
|
102
|
+
timeoutMs;
|
|
103
|
+
name = "DisposeTimeoutNotice";
|
|
104
|
+
_tag = "DisposeTimeoutNotice";
|
|
105
|
+
};
|
|
80
106
|
var DispatchDiscardedError = class extends RuntimeDiscardNotice {
|
|
81
107
|
constructor(msgType) {
|
|
82
108
|
super(
|
|
@@ -84,6 +110,7 @@ var DispatchDiscardedError = class extends RuntimeDiscardNotice {
|
|
|
84
110
|
);
|
|
85
111
|
this.msgType = msgType;
|
|
86
112
|
}
|
|
113
|
+
msgType;
|
|
87
114
|
name = "DispatchDiscardedError";
|
|
88
115
|
_tag = "DispatchDiscardedError";
|
|
89
116
|
};
|
|
@@ -146,7 +173,8 @@ function replay(machine, opts) {
|
|
|
146
173
|
if (machine.subs) {
|
|
147
174
|
for (const [index, entry] of machine.subs.entries()) {
|
|
148
175
|
const deps = entry.deps(state);
|
|
149
|
-
if (
|
|
176
|
+
if (!depsInactive(deps))
|
|
177
|
+
depSubs.push({ index, id: structuralHash(deps) });
|
|
150
178
|
}
|
|
151
179
|
}
|
|
152
180
|
return { state, cmds, subs, depSubs };
|
|
@@ -193,6 +221,7 @@ function run(machine, opts) {
|
|
|
193
221
|
const { store } = opts;
|
|
194
222
|
const ctx = opts.ctx ?? {};
|
|
195
223
|
const idleCap = opts.__idleCap ?? 1e5;
|
|
224
|
+
const disposeTimeoutMs = opts.disposeTimeoutMs ?? 5e3;
|
|
196
225
|
const projectEvents = opts.events ?? (() => []);
|
|
197
226
|
const isTerminal = opts.terminal ?? (() => false);
|
|
198
227
|
const onError = opts.onError ?? defaultOnError;
|
|
@@ -238,19 +267,50 @@ function run(machine, opts) {
|
|
|
238
267
|
const cleanup = subRegistry.get(id);
|
|
239
268
|
if (cleanup === void 0) continue;
|
|
240
269
|
try {
|
|
241
|
-
cleanup();
|
|
270
|
+
trackDisposal(cleanup());
|
|
242
271
|
} catch (err) {
|
|
243
272
|
reportError(err, { phase: "sub-cleanup" });
|
|
244
273
|
}
|
|
245
274
|
subRegistry.delete(id);
|
|
246
275
|
}
|
|
247
276
|
}
|
|
277
|
+
const pendingDisposals = /* @__PURE__ */ new Set();
|
|
278
|
+
function trackDisposal(result) {
|
|
279
|
+
if (!(result instanceof Promise)) return;
|
|
280
|
+
const settling = result.catch((err) => {
|
|
281
|
+
reportError(err, { phase: "sub-cleanup" });
|
|
282
|
+
}).finally(() => {
|
|
283
|
+
pendingDisposals.delete(settling);
|
|
284
|
+
});
|
|
285
|
+
pendingDisposals.add(settling);
|
|
286
|
+
}
|
|
287
|
+
async function drainDisposals() {
|
|
288
|
+
if (pendingDisposals.size === 0) return;
|
|
289
|
+
const outstanding = [...pendingDisposals];
|
|
290
|
+
let timer;
|
|
291
|
+
try {
|
|
292
|
+
const outcome = await Promise.race([
|
|
293
|
+
Promise.all(outstanding).then(() => "settled"),
|
|
294
|
+
new Promise((resolve) => {
|
|
295
|
+
timer = setTimeout(() => resolve("timeout"), disposeTimeoutMs);
|
|
296
|
+
})
|
|
297
|
+
]);
|
|
298
|
+
if (outcome === "timeout") {
|
|
299
|
+
reportError(
|
|
300
|
+
new DisposeTimeoutNotice(outstanding.length, disposeTimeoutMs),
|
|
301
|
+
{ phase: "discard" }
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
} finally {
|
|
305
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
248
308
|
function disposeDepSubs(indices) {
|
|
249
309
|
for (const index of indices) {
|
|
250
310
|
const running = depSubRegistry.get(index);
|
|
251
311
|
if (running === void 0) continue;
|
|
252
312
|
try {
|
|
253
|
-
running.dispose();
|
|
313
|
+
trackDisposal(running.dispose());
|
|
254
314
|
} catch (err) {
|
|
255
315
|
reportError(err, { phase: "sub-cleanup" });
|
|
256
316
|
}
|
|
@@ -262,19 +322,26 @@ function run(machine, opts) {
|
|
|
262
322
|
const subs = machine.subs;
|
|
263
323
|
if (!subs) return firstError;
|
|
264
324
|
for (const [i, entry] of subs.entries()) {
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
325
|
+
let deps;
|
|
326
|
+
let id;
|
|
327
|
+
try {
|
|
328
|
+
deps = entry.deps(state);
|
|
329
|
+
if (depsInactive(deps)) {
|
|
330
|
+
disposeDepSubs([i]);
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
id = structuralHash(deps);
|
|
334
|
+
} catch (err) {
|
|
335
|
+
if (firstError === null) firstError = err;
|
|
268
336
|
continue;
|
|
269
337
|
}
|
|
270
|
-
const id = structuralHash(deps);
|
|
271
338
|
const running = depSubRegistry.get(i);
|
|
272
339
|
if (running !== void 0 && running.runningId === id) {
|
|
273
340
|
continue;
|
|
274
341
|
}
|
|
275
342
|
disposeDepSubs([i]);
|
|
276
343
|
try {
|
|
277
|
-
const dispose = entry.source(state,
|
|
344
|
+
const dispose = entry.source(state, dispatchUnawaited, ctx);
|
|
278
345
|
depSubRegistry.set(i, { runningId: id, dispose });
|
|
279
346
|
} catch (err) {
|
|
280
347
|
if (firstError === null) firstError = err;
|
|
@@ -311,7 +378,7 @@ function run(machine, opts) {
|
|
|
311
378
|
const cleanup = handler(
|
|
312
379
|
sub,
|
|
313
380
|
ctx,
|
|
314
|
-
|
|
381
|
+
dispatchUnawaited
|
|
315
382
|
);
|
|
316
383
|
subRegistry.set(sub.id, cleanup);
|
|
317
384
|
} catch (err) {
|
|
@@ -321,7 +388,7 @@ function run(machine, opts) {
|
|
|
321
388
|
if (firstStartError !== null) throw firstStartError;
|
|
322
389
|
}
|
|
323
390
|
const interpretMap = machine.interpret ?? {};
|
|
324
|
-
const
|
|
391
|
+
const dispatchUnawaited = (msg) => {
|
|
325
392
|
enqueueDispatch(msg).catch(reportUndelivered);
|
|
326
393
|
};
|
|
327
394
|
function reportUndelivered(error) {
|
|
@@ -343,7 +410,7 @@ function run(machine, opts) {
|
|
|
343
410
|
handler(
|
|
344
411
|
cmd,
|
|
345
412
|
augmentedCtx,
|
|
346
|
-
|
|
413
|
+
dispatchUnawaited
|
|
347
414
|
)
|
|
348
415
|
);
|
|
349
416
|
if (follow !== void 0 && follow !== null) {
|
|
@@ -398,22 +465,27 @@ function run(machine, opts) {
|
|
|
398
465
|
fireEvents(msg);
|
|
399
466
|
settleDoneWaiters();
|
|
400
467
|
}
|
|
468
|
+
function isMisaddressed(msg, current) {
|
|
469
|
+
if (machine.identity === void 0) return false;
|
|
470
|
+
const addressed = machine.identity.ofMsg(msg);
|
|
471
|
+
if (addressed === void 0) return false;
|
|
472
|
+
const own = machine.identity.ofState(current);
|
|
473
|
+
if (own === void 0) return false;
|
|
474
|
+
return structuralHash(addressed) !== structuralHash(own);
|
|
475
|
+
}
|
|
401
476
|
async function stepDispatch(msg) {
|
|
402
477
|
if (state === void 0) {
|
|
403
478
|
throw new Error("@demlik/tea: runtime not booted");
|
|
404
479
|
}
|
|
405
|
-
if (machine.identity !== void 0) {
|
|
406
|
-
const addressed = machine.identity.ofMsg(msg);
|
|
407
|
-
if (addressed !== void 0) {
|
|
408
|
-
const own = machine.identity.ofState(state);
|
|
409
|
-
if (own !== void 0 && structuralHash(addressed) !== structuralHash(own)) {
|
|
410
|
-
return;
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
480
|
let next;
|
|
415
481
|
let cmds;
|
|
416
482
|
try {
|
|
483
|
+
if (isMisaddressed(msg, state)) {
|
|
484
|
+
reportError(new IdentityDropNotice(msg.type), {
|
|
485
|
+
phase: "identity-drop"
|
|
486
|
+
});
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
417
489
|
[next, cmds] = applyCellChecked(machine, state, msg);
|
|
418
490
|
} catch (reduceError) {
|
|
419
491
|
reportError(reduceError, { phase: "reduce" });
|
|
@@ -576,6 +648,7 @@ function run(machine, opts) {
|
|
|
576
648
|
gate = "closed";
|
|
577
649
|
stopSubs([...subRegistry.keys()]);
|
|
578
650
|
disposeDepSubs([...depSubRegistry.keys()]);
|
|
651
|
+
await drainDisposals();
|
|
579
652
|
if (store && state !== void 0 && bootError === null) {
|
|
580
653
|
try {
|
|
581
654
|
await store.save(state);
|
|
@@ -588,6 +661,6 @@ function run(machine, opts) {
|
|
|
588
661
|
return runtime;
|
|
589
662
|
}
|
|
590
663
|
|
|
591
|
-
export { DispatchDiscardedError, PortNameCollisionError, QuiescenceTimeoutError, RuntimeDiscardNotice, RuntimeDiscardedError, SubIdCollisionError, __resetPortRegistry, absurd, asReducer, defineMachine, definePort, historyTracker, noop, replay, run, schemaMigrate, tryInterpret, wrapDetached };
|
|
592
|
-
//# sourceMappingURL=chunk-
|
|
593
|
-
//# sourceMappingURL=chunk-
|
|
664
|
+
export { DispatchDiscardedError, DisposeTimeoutNotice, IdentityDropNotice, PortNameCollisionError, QuiescenceTimeoutError, RuntimeDiscardNotice, RuntimeDiscardedError, SubIdCollisionError, __resetPortRegistry, absurd, asReducer, defineMachine, definePort, historyTracker, noop, replay, run, schemaMigrate, tryInterpret, wrapDetached };
|
|
665
|
+
//# sourceMappingURL=chunk-ZH454CR5.js.map
|
|
666
|
+
//# sourceMappingURL=chunk-ZH454CR5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/observability.ts","../src/runtime-types.ts","../src/run.ts"],"names":["opts"],"mappings":";;;;AAsDO,SAAS,cAAA,CACd,SACA,IAAA,EACsB;AACtB,EAAA,MAAM,SAAwC,EAAC;AAC/C,EAAA,IAAI,OAAA,GAAU,KAAA;AAEd,EAAA,MAAM,IAAA,GAAO,CAAC,KAAA,KAA6C;AACzD,IAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AACjB,IAAA,IAAI,MAAA,CAAO,MAAA,GAAS,IAAA,EAAM,MAAA,CAAO,KAAA,EAAM;AAAA,EACzC,CAAA;AAMA,EAAA,MAAM,SAAA,GACJ,IAAA,IAAQ,CAAA,GACJ,MAAY;AAAA,EAAC,CAAA,GACb,OAAA,CAAQ,OAAA,CAAQ,CAAC,KAAK,KAAA,KAAU;AAC9B,IAAA,IAAA,CAAK,EAAE,GAAA,EAAK,KAAA,EAAO,CAAA;AAAA,EACrB,CAAC,CAAA;AACP,EAAA,MAAM,MAAA,GACJ,IAAA,IAAQ,CAAA,GACJ,MAAY;AAAA,EAAC,CAAA,GACb,OAAA,CAAQ,MAAA,CAAO,CAAC,KAAA,KAAU;AACxB,IAAA,IAAA,CAAK,EAAE,GAAA,EAAK,IAAA,EAAM,KAAA,EAAO,CAAA;AAAA,EAC3B,CAAC,CAAA;AAEP,EAA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,KAAA,EAAO,WAAA,EAAa,CAAA;AAAA,QAC3C;AAAA,MACF;AAAA,IACF;AAAA,GACF;AAEA,EAAA,OAAO,OAAA;AACT","file":"chunk-ZH454CR5.js","sourcesContent":["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 * @demlik/tea runtime interface surface + pure helpers — the public types,\n * interfaces, and construction/composition helpers the runtime (`./run`)\n * implements against: `Store`, the error-sink and supervision contracts, the\n * `RuntimeRef` / `BootingRuntime` / `Runtime` handle hierarchy, `definePort`, the\n * identity-typed constructors `defineMachine` / `asReducer`, and the pure tools\n * `replay` (compose without running) and `tryInterpret` (Railway).\n */\n\nimport { Result } from \"better-result\";\nimport type {\n InterpretDetached,\n Machine,\n Port,\n PortEmitter,\n Reducer,\n Sub,\n Transitions,\n} from \"./pure/core\";\nimport {\n type Cmd,\n depsInactive,\n detectUpdateForm,\n foldUpdates,\n structuralHash,\n} from \"./pure/core\";\n\n// The nominal brand minted ONLY through the validated construction path\n// (`asReducer` / `defineMachine`). A raw record of handlers is a structural\n// `Reducer<S, M, C>`; a branded one has passed through the single minting\n// boundary. The brand is an *optional* phantom so the structural annotation form\n// (`const update: Reducer<...> = { ... }`) keeps accepting plain object literals\n// — the guard that rejects an async reducer is `SyncReturn`'s non-thenable\n// return, enforced on every cell.\ndeclare const ReducerBrand: unique symbol;\n\n// A `Reducer` (or `Transitions`) minted through `asReducer` / `defineMachine`.\n// Carries the phantom brand; otherwise identical to its structural counterpart.\nexport type Branded<T> = T & { readonly [ReducerBrand]: true };\n\n/**\n * Compile-time exhaustiveness assertion for default branches of switches over\n * discriminated unions narrowed by hand (Sub handlers, message-bridge\n * dispatchers, port fanouts) — TS narrows the operand to `never` only if every\n * variant is covered, so adding one produces a compile error at the `absurd(x)`\n * site. Strengthens invariant 7 (identity is explicit).\n *\n * @example\n * switch (msg.type) {\n * case \"a\": return ...;\n * case \"b\": return ...;\n * default: return absurd(msg); // compile error if a \"c\" is added\n * }\n */\nexport function absurd(x: never): never {\n throw new Error(`unreachable: ${JSON.stringify(x)}`);\n}\n\n// The explicit \"this cell ignores this msg\" helper. Naming the no-op forces the\n// author to *decide* \"this cell does nothing\" (a real decision), distinct from\n// \"I forgot to write this cell\" (which the mapped type rejects); an implicit\n// wildcard would silently swallow a future Msg variant that should be handled.\n// Assignable to any Transitions cell regardless of S/M/C concrete types.\nexport const noop = <S, M, C extends Cmd>(\n state: S,\n _msg: M,\n): readonly [S, readonly C[]] => [state, []];\n\n// Module-level registry — process-scope, identity-by-name. The runtime witness\n// that every port name in this process is unique. Cleared only by the test-only\n// `__resetPortRegistry()` helper.\nconst definedPortNames = new Set<string>();\n\n/**\n * Thrown by `definePort` when a name has already been registered in the current\n * process. Symmetric with `SubIdCollisionError` (thrown by `reconcileSubs`) —\n * both mechanize invariant 7 (identity is explicit) at the runtime layer the\n * type system cannot reach (string names compared at runtime).\n */\nexport class PortNameCollisionError extends Error {\n override readonly name = \"PortNameCollisionError\";\n readonly _tag = \"PortNameCollisionError\" as const;\n constructor(portName: string) {\n super(\n `definePort: a port named \"${portName}\" was already defined. ` +\n `Each definePort call must use a unique name. ` +\n `If two modules need the same port, export it from one module and import it.`,\n );\n }\n}\n\n/**\n * Thrown by `reconcileSubs` when, within ONE desired subscription set, two subs\n * share an `id` but declare different `type`s — a silent bug class the type\n * system cannot reach (ids are strings compared at runtime). The symmetric twin\n * of `PortNameCollisionError`: both mechanize invariant 7 (identity is explicit)\n * at the runtime layer. Same id across transitions is the no-churn case and does\n * NOT throw; only a within-set type conflict does.\n */\nexport class SubIdCollisionError extends Error {\n override readonly name = \"SubIdCollisionError\";\n readonly _tag = \"SubIdCollisionError\" as const;\n constructor(id: string, declaredType: string, conflictingType: string) {\n super(\n `@demlik/tea: Sub.id collision: id=\"${id}\" declared as ` +\n `type=\"${declaredType}\" and type=\"${conflictingType}\"`,\n );\n }\n}\n\n/**\n * Test-only escape hatch — clears the module-level port-name registry so the\n * collision assert in `definePort` doesn't false-positive across vitest's\n * non-isolated runs. Production code MUST NOT call this.\n *\n * @internal test-only\n */\nexport function __resetPortRegistry(): void {\n definedPortNames.clear();\n}\n\n/**\n * Which otherwise-unattributable runtime path produced an error. Every fanout is\n * throw-isolated so one bad consumer never strands its siblings, and the\n * isolated throw routes to the `OnError` sink rather than a bare `console.error`.\n *\n * - `\"follow-up\"` — a follow-up Msg an interpret handler returned rejected when\n * re-dispatched (the original dispatcher already resolved, so no caller).\n * A rejection caused by `stop()`'s own teardown is NOT this phase — see\n * `\"discard\"`.\n * - `\"stop-save\"` — the final `store.save(state)` inside `stop()` threw\n * (`stop()` resolves regardless, so without the sink this was silent loss).\n * - `\"reduce\"` — the pure `update` (reducer) threw synchronously; the configured\n * `Supervision` strategy decides what happens next, but the throw is surfaced\n * here as data first.\n * - `\"listener\"` — a `runtime.subscribe(...)` listener threw during fanout.\n * - `\"observer\"` — a `runtime.observe(...)` observer threw during fanout.\n * - `\"event\"` — the `events` projector or an `on(type, ...)` handler threw.\n * - `\"boot\"` — an `onBoot` handler threw (boot fanout, or a late registration).\n * - `\"port-emit\"` — a `subscribePort` listener threw during a port emission.\n * - `\"sub-cleanup\"` — a subscription's cleanup threw (reconcile-removal or\n * `stop()` teardown).\n * - `\"discard\"` — work lost to a teardown the host asked for. Two witnesses,\n * both carrying a `RuntimeDiscardNotice`: `stop()` was called while interpret\n * handlers were still awaiting (`RuntimeDiscardedError`), and a Msg that\n * arrived DURING `stop()`'s drain and so could not be delivered\n * (`DispatchDiscardedError`), and teardown work that did not settle inside\n * `disposeTimeoutMs` (`DisposeTimeoutNotice`). The one phase that is a\n * LIFECYCLE report rather than a failure: legal, merely lossy.\n * - `\"identity-drop\"` — the `Identity` filter dropped a message addressed to a\n * different instance (`IdentityDropNotice`). Its own phase rather than\n * `\"discard\"`: the loss is the FILTER WORKING, not a teardown, and a host\n * routing it (a metric, a 409 back to the caller) wants it apart from\n * unmount-time noise. Warn-only, like every `RuntimeDiscardNotice`.\n *\n * The phase never decides fatality — the ERROR CLASS does (`RuntimeDiscardNotice`\n * warns, everything else rethrows). A phase is attached by the report site, so a\n * consumer sink that throws while handling a `\"discard\"` report inherits that\n * phase; keying the warn-only path on it would make the sink's own defect vanish.\n */\nexport type RuntimeErrorPhase =\n | \"follow-up\"\n | \"stop-save\"\n | \"reduce\"\n | \"listener\"\n | \"observer\"\n | \"event\"\n | \"boot\"\n | \"port-emit\"\n | \"sub-cleanup\"\n | \"discard\"\n | \"identity-drop\";\n\n/** Context handed to an `OnError` sink alongside the error itself. */\nexport interface RuntimeErrorContext {\n readonly phase: RuntimeErrorPhase;\n}\n\n/**\n * Sink for runtime failures that have no caller to reject at. Configured via\n * `run(machine, { onError })`. Should be total — a throw inside the sink is\n * itself surfaced via the default sink, so it can never re-introduce a silent\n * failure.\n */\nexport type OnError = (error: unknown, context: RuntimeErrorContext) => void;\n\n// === Supervision: declared policy for a reducer throw ===\n//\n// A throw inside the pure `update` is a synchronous throw (the reentrancy brand\n// makes a reducer provably synchronous), catchable in the dispatch loop — the\n// seam Akka supervisor strategies / Erlang-OTP supervision trees occupy: \"let it\n// crash\" becomes CONFIG. Every strategy routes the failure to `onError` with\n// `phase: \"reduce\"` FIRST (invariant 6), then differs in what happens next:\n//\n// - `stop` — halt (SAFE DEFAULT). State is NOT advanced; the dispatch\n// promise rejects; every subsequent dispatch rejects. Never a\n// silent resume.\n// - `escalate`— surface + propagate: the dispatch promise rejects so the\n// failure bubbles to a parent supervisor. The runtime stays live.\n// - `restart` — re-init from a host-provided last-known-good state and keep\n// folding. The core owns no snapshot logic — the host supplies\n// `rehydrate()`, the core installs its result and continues.\n\n/** The three declared reducer-throw supervision strategies. */\nexport type SupervisionStrategy = \"stop\" | \"escalate\" | \"restart\";\n\n/**\n * Declared supervision policy for a reducer (`update`) throw, at\n * `run(machine, { supervision })`. The bare-string shorthands (`\"stop\"` /\n * `\"escalate\"`) are accepted for the two strategies that need no host data;\n * `restart` MUST be the object form because it carries the `rehydrate` callback,\n * which MUST return a valid `S` synchronously (the reducer is synchronous, so\n * recovery is too — no suspension across the single-writer slot).\n */\nexport type Supervision<S, M extends { type: string }> =\n | \"stop\"\n | \"escalate\"\n | { readonly strategy: \"stop\" }\n | { readonly strategy: \"escalate\" }\n | {\n readonly strategy: \"restart\";\n /**\n * Host-provided rehydration to last-known-good state. Invoked when the\n * reducer throws; its return value becomes the new state and the transition\n * continues from there. Receives the pre-throw `state`, the `msg` that\n * triggered the throw, and the thrown `error` so the host can route by\n * cause.\n */\n readonly rehydrate: (state: S, msg: M, error: unknown) => S;\n };\n\n/**\n * Raised by `idle()` when the quiescence wait hits its iteration cap without the\n * dispatch tail stabilizing — `idle()` REJECTS rather than silently resolving,\n * so a livelocking machine surfaces instead of masquerading as quiescent.\n * Mechanizes invariant 6 at the runtime layer, the role `PortNameCollisionError`\n * plays for invariant 7.\n */\nexport class QuiescenceTimeoutError extends Error {\n override readonly name = \"QuiescenceTimeoutError\";\n readonly _tag = \"QuiescenceTimeoutError\" as const;\n constructor(public readonly iterations: number) {\n super(\n `@demlik/tea: idle() did not reach quiescence after ${iterations} ` +\n `iterations — the dispatch tail kept advancing. The machine is ` +\n `likely livelocking (an interpret handler enqueues a follow-up Msg ` +\n `that enqueues another, without end). Bound the follow-up chain in ` +\n `the reducer, or stop the runtime.`,\n );\n }\n}\n\n/**\n * Base of the LOSSY-BUT-LEGAL teardown facts: work the host discarded by letting\n * go of a runtime that still had something outstanding. Reported under\n * `phase: \"discard\"`, never raised.\n *\n * It exists so \"is this fatal?\" has ONE definition — `error instanceof\n * RuntimeDiscardNotice` — that the default sink can ask about any error from any\n * site. The phase cannot answer it: a report site attaches the phase, so a\n * consumer sink that throws while handling a `\"discard\"` report carries that\n * phase into the sink-failure path, and a phase-keyed warn branch would swallow\n * the sink's own defect. Sub-classing is how a new teardown fact opts into the\n * warn-only treatment; nothing else can.\n */\nexport abstract class RuntimeDiscardNotice extends Error {}\n\n/**\n * Reported to the `OnError` sink under `phase: \"discard\"` when `stop()` is\n * called while `interpret` handlers are still awaiting. The host is dropping\n * its only handle on that work: `stop()` drains the tail, but the listeners,\n * observers and event handlers that would have consumed the resulting\n * transitions are gone, so the Cmds' results reach nobody.\n *\n * The motivating shape is `@demlik/tea/react`'s `useMachine`, which memoizes on\n * `[machine, ctx, store]` — a ctx re-derived mid-flight replaces the runtime,\n * and the in-flight mutation's response arrives for a runtime the UI no longer\n * renders, silently rewinding the visible state. Never a throw: tearing a\n * runtime down mid-flight is legal (a navigation does it every time), so this\n * is surfaced as data, not raised. Mechanizes invariant 6 (no silent failures)\n * at the teardown seam, the role `QuiescenceTimeoutError` plays for `idle()`.\n */\nexport class RuntimeDiscardedError extends RuntimeDiscardNotice {\n override readonly name = \"RuntimeDiscardedError\";\n readonly _tag = \"RuntimeDiscardedError\" as const;\n constructor(public readonly pendingCmds: number) {\n super(\n `@demlik/tea: runtime stopped with ${pendingCmds} Cmd(s) in flight — ` +\n `their results will reach no listener. In React this is usually a ` +\n `ctx-identity change rebuilding useMachine's runtime mid-flight: ` +\n `stabilize the ctx (useMemo / useState) so the runtime outlives the ` +\n `Cmds it started. An intentional teardown (unmount, navigation) can ` +\n `silence this with a run({ onError }) sink that ignores ` +\n `phase: \"discard\".`,\n );\n }\n}\n\n/**\n * Reported to the `OnError` sink under `phase: \"identity-drop\"` when the\n * `Identity` filter drops a message addressed to a different instance.\n *\n * The drop itself is the feature — it is what lets a reducer stop repeating\n * `if (msg.runId !== state.runId) return`. What was missing is that it was\n * INVISIBLE: the dispatch resolved exactly like an applied one, so a reusable\n * Durable Object serving run A and then run B lost every run-B message and\n * reported success to each caller. The comment claiming \"the one observable\n * enforcement point\" described this notice before it existed.\n *\n * Never fatal (`RuntimeDiscardNotice`): a mis-addressed message is a normal\n * consequence of instance reuse, not a defect. A host that wants to act on it\n * — a metric, a 409 to the caller, a re-route — reads `phase: \"identity-drop\"`\n * in its own sink.\n */\nexport class IdentityDropNotice extends RuntimeDiscardNotice {\n override readonly name = \"IdentityDropNotice\";\n readonly _tag = \"IdentityDropNotice\" as const;\n constructor(public readonly msgType: string) {\n super(\n `@demlik/tea: Msg \"${msgType}\" was addressed to a different instance ` +\n `than this state owns and was dropped before \\`update\\` ran — the ` +\n `machine's \\`identity\\` filter working as declared. If this Msg was ` +\n `meant for THIS instance, its \\`ofMsg\\` projection disagrees with ` +\n `\\`ofState\\`; if the instance is being reused across runs, route the ` +\n `message to the run that owns it.`,\n );\n }\n}\n\n/**\n * Reported to the `OnError` sink under `phase: \"discard\"` when `stop()`'s wait\n * for async teardown work hits `disposeTimeoutMs`.\n *\n * `stop()` awaits the disposals it started so `await runtime.stop()` can mean\n * \"safe to evict\". A `release` that never settles must not turn that guarantee\n * into a host that never shuts down, so the wait is bounded and expiry is\n * REPORTED rather than silently tolerated — the resource is genuinely still\n * open at that point, and only the host can decide what that costs.\n */\nexport class DisposeTimeoutNotice extends RuntimeDiscardNotice {\n override readonly name = \"DisposeTimeoutNotice\";\n readonly _tag = \"DisposeTimeoutNotice\" as const;\n constructor(\n public readonly pendingDisposals: number,\n public readonly timeoutMs: number,\n ) {\n super(\n `@demlik/tea: stop() gave up waiting for ${pendingDisposals} async ` +\n `teardown(s) after ${timeoutMs}ms — the resources they release may ` +\n `still be open. Make \\`release\\` / the Sub cleanup settle (bound its ` +\n `own IO), or raise run({ disposeTimeoutMs }).`,\n );\n }\n}\n\n/**\n * The rejection of a dispatch that arrived DURING `stop()`'s drain — an in-flight\n * interpret handler's follow-up Msg, a detached handler's terminal Msg, or a Sub\n * that is still live because subs are torn down only after the drain. The stop\n * barrier is absolute (the Msg is refused, never folded), so this names the loss.\n *\n * It is the SECOND witness of `RuntimeDiscardedError`'s fact, and it is why the\n * drain window is a distinct runtime state rather than a plain `stopped` flag:\n * a Msg refused inside the window was discarded BY the teardown, while the same\n * refusal after `stop()` has returned is a consumer dispatching into a runtime it\n * already retired — a real error, and still loud (`phase: \"follow-up\"`, or the\n * caller's own rejection). The distinction is the state at refusal time, never\n * the message text.\n */\nexport class DispatchDiscardedError extends RuntimeDiscardNotice {\n override readonly name = \"DispatchDiscardedError\";\n readonly _tag = \"DispatchDiscardedError\" as const;\n constructor(public readonly msgType: string) {\n super(\n `@demlik/tea: Msg \"${msgType}\" arrived while the runtime was stopping ` +\n `and was discarded — stop() refuses new work so the drain terminates. ` +\n `It is the result of a Cmd that outlived its runtime; keep the runtime ` +\n `alive until the Cmd settles (in React: stabilize useMachine's ctx) if ` +\n `the transition matters.`,\n );\n }\n}\n\n/**\n * Define a typed port. `name` is metadata (devtools / debug logs); port identity\n * is by reference. Each definePort call must use a unique `name` — a second call\n * with the same name throws `PortNameCollisionError`. Use ports for \"data leaving\n * the runtime selectively\" (cursor announcements, DOM-mutation broadcasts,\n * telemetry) that should NOT be folded into State. Strengthens invariant 7.\n */\nexport function definePort<T>(name: string): Port<T> {\n // HMR skip — Vite / dev servers re-import the module on hot reload, which\n // would otherwise false-positive on every definePort across reloads. The\n // try/catch is load-bearing for service-worker bundles: Vite polyfills\n // `import.meta.url` via `document.baseURI`, which throws ReferenceError in\n // an MV3 service worker. A throw here would abort SW install (Chrome\n // surfaces it as \"registration failed status 15\"). Catching it = \"no HMR\n // detected\" = the collision check applies, which is the correct SW\n // behavior (SWs reload via chrome.runtime.reload, not module HMR).\n let isHmr = false;\n try {\n const meta = import.meta as { hot?: unknown };\n isHmr = meta?.hot !== undefined && meta?.hot !== null;\n } catch {\n isHmr = false;\n }\n if (!isHmr && definedPortNames.has(name)) {\n throw new PortNameCollisionError(name);\n }\n definedPortNames.add(name);\n return { __brand: \"port\", name } as Port<T>;\n}\n\n// === Store: pluggable persistence adapter ===\n//\n// `load()` returns `unknown` because storage genuinely doesn't know `S` —\n// chrome.storage returns whatever JSON lives at the key, DurableObjectStorage\n// returns whatever bytes were serialized. Casting raw storage to `S` at the\n// adapter boundary is the exact `as S` move forbidden by invariant 8\n// everywhere else in the substrate. `load()` returning `unknown` makes the\n// substrate stop pretending.\n//\n// `migrate(raw)` is the boundary parse. Returns `S` on a recognized shape —\n// the substrate passes it to `init` as `loaded`. Returns `null` on any\n// unrecognized shape — the substrate passes `null` to `init`, fresh-boot\n// path. Must NOT throw: if a future shape is unrecognizable, returning\n// `null` boots clean from a known-good path. Throwing here would\n// indistinguishably collapse \"storage corruption\" and \"schema migration not\n// yet written\" — both are runtime decisions, not panics.\n//\n// Strengthens invariant 8 (the boundary parses; the core trusts) — the\n// substrate now enforces the parse instead of relying on every adapter\n// remembering to.\nexport interface Store<S> {\n load(): Promise<unknown>;\n save(state: S): Promise<void>;\n migrate(raw: unknown): S | null;\n}\n\n// === Schema-derived migrate: single-source the durable State ===\n//\n// The boundary parse `migrate(raw)` is two jobs glued together:\n// 1. STRUCTURAL VALIDATION — \"is this the current shape?\" 100% derivable\n// from the State type, pure boilerplate, the part that drifts when a\n// field is added to a variant but the hand-written parser isn't updated.\n// 2. VERSION MIGRATION — \"upgrade an OLD shape to the current one\" (default a\n// missing field, drop a dead one, remap a removed enum). Genuine logic.\n// Encodes decisions about how past rows map forward. NOT derivable.\n//\n// `schemaMigrate` derives job 1 from a schema and isolates job 2 in a thin,\n// explicit `upcast` run BEFORE the parse. When the State type is itself\n// `Schema<S>`-inferred (`type S = SchemaOutput<typeof schema>`), the type and\n// the validator are the SAME declaration — you cannot add a field to the type\n// without it being in the schema, so the parse always enforces the current\n// shape. The `as S` an adapter would otherwise write on `safeParse().data` is\n// deleted: the schema's output IS `S`.\n//\n// The kernel stays library-agnostic — `Schema<S>` is the minimal Standard-\n// Schema-shaped surface (`safeParse`) that both zod 3 and zod 4 satisfy. No\n// validator is imported here; the consumer supplies one.\n//\n// Strengthens invariant 8 (the boundary parses; the core trusts) and invariant\n// 1 (state is a value — one declaration sources both type and parser).\nexport interface Schema<S> {\n safeParse(raw: unknown): { success: true; data: S } | { success: false };\n}\n\n/**\n * Build a `Store.migrate` from a schema (job 1) and an optional thin `upcast`\n * (job 2). `upcast` maps a recognized-but-OLD raw shape forward into the shape\n * the schema validates; it defaults to identity (no version migration yet).\n *\n * Never throws — a shape the schema rejects returns `null`, the substrate's\n * fresh-boot path, per the `Store.migrate` contract. An `upcast` that itself\n * throws on a corrupt blob is caught and collapses to `null` (same posture).\n */\nexport function schemaMigrate<S>(\n schema: Schema<S>,\n upcast: (raw: unknown) => unknown = (raw) => raw,\n): (raw: unknown) => S | null {\n return (raw: unknown): S | null => {\n let migrated: unknown;\n try {\n migrated = upcast(raw);\n } catch {\n return null;\n }\n const parsed = schema.safeParse(migrated);\n return parsed.success ? parsed.data : null;\n };\n}\n\n// === DispatchSettle: how far a dispatch awaits ===\n//\n// The default is the SAFE one, `\"quiescent\"` — `dispatch` resolves only once the\n// entire transitive follow-up chain has drained (the same drain `idle()`\n// performs). Were the default one transition, an `interpret` follow-up Msg would\n// enqueue a fresh transition fire-and-forget relative to the original\n// `dispatch`, resolving \"early\". The rare single-step case opts in with `\"once\"`\n// (or the `dispatchOnce` convenience).\nexport type DispatchSettle = \"quiescent\" | \"once\";\n\n// === RuntimeRef<M>: typed sibling-runtime handle ===\n//\n// Exposes only the inbox of a Runtime — `dispatch` / `dispatchOnce`. Use it as\n// the field type when one runtime holds a *sibling* (composition by reduction\n// across orthogonal lifecycles — invariant 5): the holder learns the Msg shape\n// it can send, nothing about the referenced runtime's State/Cmd/Sub/Ctx/\n// observers/Port fanout. `Runtime<S, M>` extends `RuntimeRef<M>` structurally.\nexport interface RuntimeRef<M extends { type: string }> {\n /**\n * Put a Msg in the runtime's inbox and resolve once processed. Runs to\n * QUIESCENCE by default: settles only after the dispatched Msg AND every\n * transitive interpret follow-up has drained. Pass `{ settle: \"once\" }` (or\n * call `dispatchOnce`) for the single-step case.\n *\n * Rejection ordering: the ONE dispatched transition's own failure surfaces\n * first, here. If it succeeds but the follow-up chain never stabilizes, the\n * quiescent drain rejects with `QuiescenceTimeoutError`. Follow-up Msg\n * rejections themselves route to the `onError` sink, never here.\n */\n dispatch(msg: M, opts?: { readonly settle?: DispatchSettle }): Promise<void>;\n /**\n * Dispatch `msg` and resolve after exactly ONE transition's effects settle,\n * WITHOUT draining the follow-up chain — equivalent to\n * `dispatch(msg, { settle: \"once\" })`. Prefer plain `dispatch` unless you will\n * `await runtime.idle()` yourself; the un-awaited follow-up chain is the\n * footgun the quiescent default removed.\n */\n dispatchOnce(msg: M): Promise<void>;\n}\n\n// === BootingRuntime: handle returned SYNCHRONOUSLY from run() ===\n//\n// `run()` returns a `BootingRuntime<S, M>` the instant it is called, while boot\n// is still in flight. It exposes exactly the surface TOTAL before boot: queue a\n// dispatch, subscribe, observe, wire a Port, stop. What you may NOT do is read\n// State (`getState`) or wait for quiescence (`idle`) — those need the initial\n// State to exist, and are the difference between a BootingRuntime and a\n// `Runtime`, enforced at the type level so \"read State before boot\" is a COMPILE\n// error, not a runtime throw.\n//\n// `subscribe` is the React-shaped change notifier (zero-arg, paired with\n// `getState()`). `observe` is the devtools-shaped trace hook — `(msg, state)`\n// for every APPLIED transition; boot is delivered via `onBoot` instead, so\n// `observe`'s `msg` is total (never `null`). `on(type, handler)` is the SEMANTIC\n// event channel: only the public, `type`-narrowed events a machine projects,\n// never its PRIVATE Msg vocabulary. `E` defaults to `never` (no projector → `on`\n// uncallable).\nexport interface BootingRuntime<\n S,\n M extends { type: string },\n E extends { type: string } = never,\n> extends RuntimeRef<M> {\n dispatch(msg: M, opts?: { readonly settle?: DispatchSettle }): Promise<void>;\n dispatchOnce(msg: M): Promise<void>;\n subscribe(listener: () => void): () => void;\n observe(observer: (msg: M, state: S) => void): () => void;\n /**\n * Subscribe to the INITIAL State — the boot transition. Fires exactly once:\n * immediately if boot already completed (so a late subscriber never misses\n * it), otherwise on the boot fanout. Returns a cleanup (a no-op once fired).\n */\n onBoot(handler: (state: S) => void): () => void;\n /**\n * Subscribe to a SEMANTIC event of `type`. The handler receives exactly the\n * `E` member whose `type` matches `K`, so a consumer never touches another\n * event's shape and never references the machine's PRIVATE Msg names. Multiple\n * handlers per type; fanout is synchronous and throw-isolated. Fires only when\n * the machine's `events` projector (wired on `run`) emits that type.\n */\n on<K extends E[\"type\"]>(\n type: K,\n handler: (event: Extract<E, { type: K }>) => void,\n ): () => void;\n /**\n * Subscribe to a typed Port. Multiple listeners per port; fanout is synchronous\n * and isolated. Ports are for \"data leaving the runtime selectively\" (see\n * `definePort`) — distinct from `observe` (every transition) and State.\n */\n subscribePort<T>(port: Port<T>, listener: (value: T) => void): () => void;\n /**\n * Emit a value on a Port from OUTSIDE an interpret handler — same synchronous\n * fanout as `ctx.emit`. The canonical use is `observe`-driven emission (one\n * runtime publishing a state-derived signal another subscribes to via\n * `subscribePort`) without spawning a \"tell the outside world\" Cmd per\n * transition.\n */\n emitPort<T>(port: Port<T>, value: T): void;\n /**\n * Resolves to the booted `Runtime<S, M>` after boot completes (or rejects with\n * the boot error). This is the ONLY way to obtain a `Runtime` — and a\n * `Runtime` is the only handle whose `getState()` is total. Awaiting `ready` is\n * the single gate between \"boot in flight\" and \"State exists\":\n *\n * ```ts\n * const runtime = await run(machine, opts).ready;\n * runtime.getState(); // total — never throws-before-boot\n * ```\n *\n * Idempotent — the same settled promise, resolving to the same `Runtime`, comes\n * back on every read. Expresses canon §2.3 (boot is a named, awaitable moment).\n */\n ready: Promise<Runtime<S, M, E>>;\n stop(): Promise<void>;\n}\n\n// === Runtime: the BOOTED handle `ready` resolves to ===\n//\n// A `BootingRuntime<S, M>` whose boot has completed. It adds the two members\n// only meaningful once the initial State exists — `getState()` (total) and\n// `idle()` (quiescence) — and narrows `ready` to resolve to itself. You never\n// construct one directly; you obtain it via `await bootingRuntime.ready`, which\n// makes \"read State before boot\" unrepresentable rather than merely discouraged.\nexport interface Runtime<\n S,\n M extends { type: string },\n E extends { type: string } = never,\n> extends BootingRuntime<S, M, E> {\n /**\n * The current State. TOTAL — never throws. Obtaining a `Runtime` requires\n * awaiting `ready`, which only resolves AFTER boot has run `init` and set the\n * initial State.\n */\n getState(): S;\n /** Resolves to this same `Runtime` once boot completes. Idempotent. */\n ready: Promise<Runtime<S, M, E>>;\n /**\n * Resolves once the runtime has reached QUIESCENCE — every dispatched Msg AND\n * every transitive interpret follow-up has been processed, with no further step\n * pending on the tail. Since plain `dispatch` already runs to quiescence, this\n * is mainly for follow-ups left by a `dispatchOnce` single step, or a chain\n * kicked off by a Sub / boot `init` cmds with no `dispatch` to await.\n *\n * Idempotent and re-entrant-safe. Tail rejections are NOT surfaced here (a\n * failing dispatch surfaces on its OWN promise; follow-up rejections route to\n * `onError`). The one rejection `idle()` produces is `QuiescenceTimeoutError`\n * on hitting the iteration cap — so a livelock stays distinguishable from a\n * genuine quiesce (invariant 6). A poll is still correct when waiting on an\n * EXTERNAL event the runtime cannot enqueue itself.\n */\n idle(): Promise<void>;\n /**\n * The terminal State of the run, or `undefined` while in flight — \"terminal\"\n * per the `terminal` predicate passed to `run()` (no predicate → never\n * terminal → always `undefined`). The first-class result read: the run's\n * product off the State the machine already owns, NOT scraped off the `observe`\n * firehose by matching an internal Msg name. Total — never throws.\n */\n result(): S | undefined;\n /**\n * Resolves with the terminal State the first time the run reaches one (per the\n * `terminal` predicate). If ALREADY terminal, resolves immediately; otherwise\n * on the transition that first makes `terminal` hold. The awaitable companion\n * to `result()`. With no predicate this never resolves. Idempotent and\n * multi-caller safe.\n */\n done(): Promise<S>;\n}\n\n// === defineMachine: identity-typed pass-through ===\n//\n// Overloads enforce exactly one `update` shape per call so consumers see a\n// concrete type, not the internal union. Runtime is identity — `run` branches on\n// the structural shape of `update` (Reducer = record of functions; Transitions =\n// record of records) when dispatching, so overload resolution picks the right\n// branch by value shape. Strengthens invariant 2 (record forms have no\n// fall-through default) and invariant 7 (the variant set is load-bearing).\n\n// Transitions-form overload — 2D table keyed by State.type then Msg.type.\n// Declared FIRST (most specific). The S constraint is a conditional (`S extends\n// { type: string } ? Transitions<...> : never`) not a generic-parameter\n// constraint, so `S` stays unconstrained at the signature and the public\n// `Parameters<typeof defineMachine<NonDiscriminatedS, ...>>` pattern skips this\n// overload (update becomes `never`) instead of failing.\nexport function defineMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n m: Omit<Machine<S, M, C, U, Ctx>, \"update\"> & {\n // `[S]` tuple-wrap disables distributive conditional behavior — see\n // the comment on `Machine.update` for why distribution is wrong here.\n update: [S] extends [{ type: string }] ? Transitions<S, M, C> : never;\n },\n): Machine<S, M, C, U, Ctx>;\n// Reducer-form overload — flat record keyed by Msg.type.\nexport function defineMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n m: Omit<Machine<S, M, C, U, Ctx>, \"update\"> & {\n update: Reducer<S, M, C>;\n },\n): Machine<S, M, C, U, Ctx>;\n// Implementation signature — accepts both via the union on `Machine.update`.\nexport function defineMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(m: Machine<S, M, C, U, Ctx>): Machine<S, M, C, U, Ctx> {\n // Tag the update form ONCE, here at the typed construction boundary, so no\n // downstream reader re-derives it structurally. Non-enumerable so it does not\n // serialize, show up in `Object.keys`, or collide with a Msg.type key.\n // Idempotent under re-wrap (`defineMachine(defineMachine(m))`).\n if (m.__form === undefined) {\n Object.defineProperty(m, \"__form\", {\n value: detectUpdateForm(m.update as object),\n enumerable: false,\n writable: false,\n configurable: true,\n });\n }\n return m;\n}\n\n// === asReducer: the validated minting path for a reducer ===\n//\n// Turns a raw record of handlers into a branded `Reducer<S, M, C>`. The\n// parameter type's every cell returns the non-thenable `SyncReturn<S, C>`, so\n// the reentrancy guard fires HERE, at construction: an `async` cell returns\n// `Promise<...>`, not assignable to `SyncReturn`, and `tsc` rejects it. PURE —\n// identity at runtime (the brand is phantom). `defineMachine` brands its\n// `update` internally the same way, so this exists for the standalone `const\n// update = asReducer<...>({ ... })` form.\nexport function asReducer<S, M extends { type: string }, C extends Cmd>(\n reducer: Reducer<S, M, C>,\n): Branded<Reducer<S, M, C>> {\n return reducer as Branded<Reducer<S, M, C>>;\n}\n\n// === CtxArg<Ctx>: the `ctx` field of `run`'s opts, conditionally optional ===\n//\n// A PURE machine reads nothing from `ctx` (its `Ctx` is `NoCtx` /\n// `Record<string, never>` / `unknown`); forcing `ctx: {}` is ceremony for a\n// value the type already pins as empty. So `ctx` is CONDITIONALLY optional: when\n// `{}` satisfies `Ctx` it may be OMITTED (defaulted to `{}`), so a pure reducer\n// runs as `run(machine)`; when `Ctx` carries a field a handler reads, `ctx` stays\n// REQUIRED. `[Record<never, never>] extends [Ctx]` reads as \"is `{}` assignable\n// to `Ctx`\" — true for the context-free shapes, false for `{ db: … }`; the\n// tuple-wrap disables distributive conditional behavior.\nexport type CtxArg<Ctx> = [Record<never, never>] extends [Ctx]\n ? { ctx?: Ctx }\n : { ctx: Ctx };\n\n// === replay: pure unit-test helper ===\n//\n// Composes `init(loaded ?? null, ctx)` then `update(state, msg)` for each msg.\n// Returns the final state plus the cmds that *would* have been emitted and the\n// subs that *would* have been desired at the final state. It does NOT call any\n// `interpret[type]` handler, does NOT touch `Store`, and does NOT start any\n// subscription. `subscriptions` IS called to derive `subs` — that lets tests\n// assert what would be wired up without actually wiring it.\n//\n// Dep-keyed Subs are reported in `depSubs`: for each `machine.subs` entry\n// active at the FINAL state (its `deps` non-null), the entry's `index` and the\n// derived `id` (`structuralHash(deps)`) — so a test can assert \"the deadline +\n// checkpoint + bridge dep-subs are armed in `running`\" without wiring any\n// source. Same intent as `subs` for the manual path: assert the desired set\n// purely. `source` is NEVER called (replay starts no subscription).\nexport function replay<\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 opts: { msgs: readonly M[]; ctx: Ctx; loaded?: S | null },\n): {\n state: S;\n cmds: C[];\n subs: U[];\n depSubs: { index: number; id: string }[];\n} {\n // Coerce undefined → null so `replay` with `loaded: undefined` calls\n // `init(null, ctx)`.\n const loaded = opts.loaded ?? null;\n const [initialState, initCmds] = machine.init(loaded, opts.ctx);\n\n if (loaded !== null && initCmds.length > 0) {\n throw new Error(\n \"TEA contract violation: machine.init must return [state, []] (no Cmds) \" +\n \"when `loaded` is non-null. Init's rehydrate branch is a pure state \" +\n \"passthrough — the migration/parse boundary, not the boot-effect hook.\\n\\n\" +\n \"Routes for boot effects:\\n\" +\n \" - Stateless infrastructure (e.g. chrome.alarms ensure) → host module \" +\n \"top level, outside TEA.\\n\" +\n \" - State-conditional resume (e.g. re-attach a session) → a `boot` Msg \" +\n \"dispatched once from the host after `run(...)` returns, handled in update.\\n\\n\" +\n \"See .patterns/tea/tea-invariants.md (Invariant 2).\",\n );\n }\n\n // `replay` and `foldMsgs` share ONE internal fold (`foldUpdates`), keyed on\n // `formOf` — the same reader `run` uses — so all three agree on the\n // reducer-vs-transitions form by construction.\n const { state, cmds: foldedCmds } = foldUpdates<S, M, C>(\n machine,\n initialState,\n opts.msgs,\n );\n const cmds: C[] = [...initCmds, ...foldedCmds];\n\n const subs: U[] = machine.subscriptions\n ? [...machine.subscriptions(state)]\n : [];\n\n // The dep-keyed desired set at the final state — `deps` only, never `source`.\n const depSubs: { index: number; id: string }[] = [];\n if (machine.subs) {\n for (const [index, entry] of machine.subs.entries()) {\n const deps = entry.deps(state);\n // Same gate the runtime reconciles on (`depsInactive`), not a second\n // spelling of it — a `deps` returning `undefined` means inactive here too.\n if (!depsInactive(deps))\n depSubs.push({ index, id: structuralHash(deps) });\n }\n }\n\n return { state, cmds, subs, depSubs };\n}\n\n// === wrapDetached: the typed Cmd→Msg edge for a detached interpret handler ===\n//\n// Adapts an `InterpretDetached<C, Allowed, Ctx>` — a handler that detaches its\n// long-running work (`ctx.waitUntil(...)`) and fires its TERMINAL Msg through\n// the kernel-injected `dispatch` — into a plain `Interpret` cell that drops into\n// the `interpret` dictionary unchanged. The point is the NARROWING: `Allowed`\n// is the subset of the Msg union this Cmd is permitted to produce, and the\n// `dispatch` the handler sees is typed `(msg: Allowed) => void`. A wrong /\n// typo'd terminal Msg from the detached site then fails to compile (rung 2),\n// where today it reaches for a host-wired `ctx.dispatch` typed to the full\n// union and compiles silently (rung 5 — the allowed set on a comment).\n//\n// `Allowed extends M` is the constraint that makes this SOUND at the kernel:\n// the kernel injects the WIDE `dispatch: (msg: M) => void`, the handler only\n// ever calls it with `Allowed` values (its own narrowed signature enforces\n// that), and every `Allowed` is a valid `M`. So passing the wide dispatch into\n// the narrow-expecting handler is type-correct in one direction (the values the\n// handler produces are all `M`) — the narrowing constrains the AUTHOR, not the\n// kernel. No `as` on data: the only widen is the function reference itself\n// (`dispatch` accepting `M` is usable where one accepting `Allowed` is wanted\n// because `Allowed extends M` — contravariant parameter, sound here because the\n// handler never sees a non-`Allowed` value), expressed by the explicit\n// `Allowed`/`M` generic relation, not a cast.\n//\n// Opt-in / additive: a leaf handler that resolves on its own keeps returning\n// `Promise<M | void>` and never touches `wrapDetached`. Only the detached sites\n// adopt it. The wrapped result is structurally a plain cell, so the `interpret`\n// map type is unchanged.\n//\n// Strengthens invariant 3 (effects are data — the detached effect's terminal\n// result feeds back as a Msg, now a TYPED edge) and invariant 7 (identity is\n// explicit — a Cmd's allowed result-Msg set is load-bearing at the type level).\nexport function wrapDetached<\n C extends Cmd,\n M extends { type: string },\n Allowed extends M,\n Ctx,\n>(\n handler: InterpretDetached<C, Allowed, Ctx>,\n): (\n cmd: C,\n ctx: Ctx & PortEmitter,\n dispatch?: (msg: M) => void,\n) => Promise<void> {\n // The injected `dispatch` accepts the full `M`. The handler's signature only\n // lets it call `dispatch` with `Allowed` (⊆ M) values, so handing it the\n // wide fn is sound: `(msg: M) => void` is callable wherever\n // `(msg: Allowed) => void` is wanted, and every value the handler passes is a\n // valid `M`. No data cast — the relation is carried by `Allowed extends M`.\n //\n // `dispatch` is OPTIONAL on the signature to match the `Interpret` cell type\n // (additive — see `Interpret`). The kernel ALWAYS passes it from\n // `runInterpret`; a detached handler invoked WITHOUT a dispatch (only a\n // mis-wired direct caller could do this) has no way to fire its terminal Msg,\n // so we fail loudly (rung 4) rather than silently dropping the seam's result.\n return (cmd, ctx, dispatch) => {\n if (dispatch === undefined) {\n throw new Error(\n \"@demlik/tea: a wrapDetached handler was invoked without the injected dispatch. \" +\n \"The kernel always supplies it; call the handler through the runtime, not directly.\",\n );\n }\n return handler(cmd, ctx, dispatch);\n };\n}\n\n// === tryInterpret: Railway sugar over `Result.tryPromise` ===\n//\n// Wraps a fallible `(cmd, ctx) => Promise<Ok>` into a handler for\n// `interpret[type]`: on success resolves `onOk(value, cmd)`, on rejection\n// `onErr(error, cmd)`. It NEVER rejects (assuming `onOk`/`onErr` are total).\n//\n// We use the `{try, catch: (e) => e}` form (not the one-arg thunk) so the\n// original error passes through untouched — the one-arg form wraps errors in\n// `UnhandledException`, which would break `instanceof` checks inside `onErr`.\nexport function tryInterpret<C extends Cmd, Ok, M, Ctx>(\n work: (cmd: C, ctx: Ctx) => Promise<Ok>,\n onOk: (value: Ok, cmd: C) => M,\n onErr: (error: unknown, cmd: C) => M,\n): (cmd: C, ctx: Ctx) => Promise<M> {\n return async (cmd, ctx) => {\n const result = await Result.tryPromise({\n try: () => work(cmd, ctx),\n catch: (error: unknown): unknown => error,\n });\n return result.match({\n ok: (value) => onOk(value, cmd),\n err: (error) => onErr(error, cmd),\n });\n };\n}\n","/**\n * @demlik/tea runtime — `run`: boot + the serial dispatch loop. The pure helpers\n * that compose against a machine without running it (`replay`, `tryInterpret`)\n * live in `./runtime-types`.\n */\n\nimport type {\n Dispose,\n Interpret,\n Machine,\n Port,\n PortEmitter,\n Sub,\n} from \"./pure/core\";\nimport {\n applyCellChecked,\n type Cmd,\n depsInactive,\n structuralHash,\n} from \"./pure/core\";\nimport type {\n BootingRuntime,\n CtxArg,\n DispatchSettle,\n OnError,\n Runtime,\n RuntimeErrorContext,\n RuntimeErrorPhase,\n Store,\n Supervision,\n} from \"./runtime-types\";\nimport {\n DispatchDiscardedError,\n DisposeTimeoutNotice,\n IdentityDropNotice,\n QuiescenceTimeoutError,\n RuntimeDiscardedError,\n RuntimeDiscardNotice,\n SubIdCollisionError,\n} from \"./runtime-types\";\n\n// Default `onError` sink: re-throw on a fresh macrotask so the failure reaches\n// the host's global error handler instead of vanishing — surface, not swallow\n// (invariant 6).\n//\n// A `RuntimeDiscardNotice` is NOT a failure of the runtime's own contract — a\n// host tearing a runtime down with Cmds in flight (a React ctx-identity change,\n// a navigation) is legal, merely lossy. Rethrowing it would make every\n// unmount-during-fetch an uncaught error for consumers who never configured a\n// sink, so the default WARNS: loud enough that the silent discard #365 describes\n// cannot happen again, never fatal. A configured `onError` sees `\"discard\"` like\n// any other phase and can route or ignore it.\n//\n// The branch keys on the ERROR CLASS, never on `context.phase`: the phase is\n// attached by the report site, and `reportError` hands a THROWING consumer sink's\n// own error back here with the phase it was handling — so a phase-keyed branch\n// would warn away a broken sink and re-create the very silent failure this\n// mechanism exists to remove. The class is the one thing a sink's own defect\n// cannot forge.\nfunction defaultOnError(error: unknown, _context: RuntimeErrorContext): void {\n if (error instanceof RuntimeDiscardNotice) {\n console.warn(error);\n return;\n }\n setTimeout(() => {\n throw error;\n }, 0);\n}\n\n// Normalize `Supervision` (bare string or object) so the dispatch loop branches\n// on `.strategy` once. Default `stop`. Derived from `Supervision` — the object\n// arms are exactly its non-string members, so the restart `rehydrate` payload\n// has a single source of truth.\ntype NormalizedSupervision<S, M extends { type: string }> = Extract<\n Supervision<S, M>,\n object\n>;\n\nfunction normalizeSupervision<S, M extends { type: string }>(\n supervision: Supervision<S, M> | undefined,\n): NormalizedSupervision<S, M> {\n if (supervision === undefined) return { strategy: \"stop\" };\n if (typeof supervision === \"string\") return { strategy: supervision };\n return supervision;\n}\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. A throw in any\n// effect phase leaves the persisted state ahead of the host's belief about\n// what executed — the Railway discipline (`tryInterpret` in handlers) makes\n// that 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 opts: CtxArg<Ctx> & {\n store?: Store<S>;\n onError?: OnError;\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 * 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 const { store } = opts;\n // `ctx` is conditionally optional (see `CtxArg`); default the nullish case to\n // `{}` so the augmented-ctx spread and `init(loaded, ctx)` get a value.\n const ctx = (opts.ctx ?? {}) as Ctx;\n const idleCap = opts.__idleCap ?? 100_000;\n const disposeTimeoutMs = opts.disposeTimeoutMs ?? 5_000;\n // No projector → `E = never` and `on` is uncallable.\n const projectEvents: (msg: M, state: S) => readonly E[] =\n opts.events ?? (() => []);\n // No predicate → never terminal (`result()` always `undefined`).\n const isTerminal: (state: S) => boolean = opts.terminal ?? (() => false);\n // Absent sink → `defaultOnError` (invariant 6).\n const onError: OnError = opts.onError ?? defaultOnError;\n // A throwing sink routes THAT throw through `defaultOnError` so it can't\n // re-create a silent failure. It arrives with the context the sink was\n // handling, so `defaultOnError` must not decide fatality from the phase — the\n // sink's own error is not the runtime's teardown notice, whatever phase it\n // inherits.\n const reportError = (error: unknown, context: RuntimeErrorContext): void => {\n try {\n onError(error, context);\n } catch (sinkError) {\n defaultOnError(sinkError, context);\n }\n };\n\n // Throw-isolated fanout: run `fn` for every item, routing any throw to the\n // sink under `phase` so one bad consumer never strands its siblings\n // (invariant 6). The single home for that isolation discipline — every\n // synchronous listener/observer/handler fanout goes through here.\n function fanout<T>(\n items: Iterable<T>,\n phase: RuntimeErrorPhase,\n fn: (item: T) => void,\n ): void {\n for (const item of items) {\n try {\n fn(item);\n } catch (err) {\n reportError(err, { phase });\n }\n }\n }\n const supervision = normalizeSupervision<S, M>(opts.supervision);\n\n // `state` is late-initialized inside the boot step (the head of the tail).\n let state: S | undefined;\n let bootError: unknown = null;\n // The dispatch gate. It only ever ADVANCES — `\"open\"` → `\"draining\"` →\n // `\"closed\"` — so the discard window can never re-open under a second `stop()`.\n //\n // \"open\" — normal operation; `enqueueDispatch` accepts.\n // \"draining\" — inside `stop()`, before the tail has settled. New work is\n // still refused (the stop barrier is absolute, and refusing is\n // what makes the drain terminate), but a Msg refused HERE was\n // discarded BY the teardown: it is an in-flight Cmd's follow-up,\n // a detached handler's terminal Msg, or a Sub that is still live\n // because subs are torn down only after the drain. So the\n // rejection is a `DispatchDiscardedError` and it reports under\n // `phase: \"discard\"` — lossy, legal, warn-only.\n // \"closed\" — halted: a `stop` supervision halt, or `stop()` has returned.\n // A dispatch refused here is a consumer using a runtime it\n // already retired — a real error, and it stays loud.\n let gate: \"open\" | \"draining\" | \"closed\" = \"open\";\n // Interpret handlers currently awaiting — \"how many Cmds are in flight?\".\n // Maintained in `runInterpret` (its only writer) and read by `stop()` to make\n // a mid-flight teardown LOUD instead of silent (issue #365). Not a second\n // representation of the serial `tail`: the tail is a promise chain, which\n // cannot be asked synchronously whether it has outstanding work.\n let inFlightCmds = 0;\n\n const subRegistry = new Map<string, Dispose>();\n // Dep-keyed Sub registry. One slot per `machine.subs[i]`, keyed by the entry's\n // array index (its stable identity across reconciles — a dep-keyed Sub has no\n // author-supplied id). `runningId` is the `structuralHash(deps)` of the live\n // source; an absent slot means the entry is currently inactive (its `deps`\n // returned null). The same dispose-on-change / dispose-on-null machinery the\n // manual Sub path uses, with the id DERIVED instead of author-supplied.\n const depSubRegistry = new Map<\n number,\n { runningId: string; dispose: Dispose }\n >();\n const listeners = new Set<() => void>();\n // Observers get (msg, state) for every APPLIED transition (boot goes via `onBoot`).\n const observers = new Set<(msg: M, state: S) => void>();\n // `booted` lets an `onBoot` handler registered AFTER boot fire immediately.\n const bootHandlers = new Set<(state: S) => void>();\n let booted = false;\n // Keyed by event `type`, stored monomorphically (per-type safety at `on`).\n const eventHandlers = new Map<string, Set<(event: E) => void>>();\n // `done()` waiters — the first terminal transition drains them.\n const doneWaiters = new Set<(state: S) => void>();\n\n // Keyed by Port reference (identity is by-reference per Elm); per-port type\n // safety is enforced at the call sites.\n const portRegistry = new Map<Port<unknown>, Set<(value: unknown) => void>>();\n\n // `emit` injected onto ctx: synchronous fanout, no-op on no subscribers,\n // listener throws isolated + routed to the sink (invariant 6).\n function portEmit<T>(port: Port<T>, value: T): void {\n const subscribers = portRegistry.get(port as Port<unknown>);\n if (!subscribers || subscribers.size === 0) return;\n fanout(subscribers, \"port-emit\", (listener) => listener(value));\n }\n\n // Spread into a fresh object so handlers get a Ctx & PortEmitter without\n // mutating the caller's ctx (which may be shared across runtimes / tests).\n const augmentedCtx: Ctx & PortEmitter = { ...ctx, emit: portEmit };\n\n // Every step chains onto `tail` — the single concurrency gate.\n let tail: Promise<void> = Promise.resolve();\n\n // Tear down each named sub: run its cleanup (throws isolated + routed to the\n // sink under `\"sub-cleanup\"`), then drop it from the registry regardless of a\n // cleanup throw. The single home for the cleanup-and-delete discipline shared\n // by `reconcileSubs`'s removal pass and `stop()`.\n function stopSubs(ids: Iterable<string>): void {\n for (const id of ids) {\n const cleanup = subRegistry.get(id);\n if (cleanup === undefined) continue;\n try {\n trackDisposal(cleanup());\n } catch (err) {\n reportError(err, { phase: \"sub-cleanup\" });\n }\n subRegistry.delete(id);\n }\n }\n\n // Teardown work that returned a Promise and has not settled. A cleanup /\n // `Dispose` may be async (`defineManagedResource`'s `release` is typed\n // `void | Promise<void>` precisely so a flush can be awaited), and the\n // reconcile pass CANNOT await it — reconcile runs inside the synchronous\n // transition path (invariant 2). So every async disposal is remembered here\n // the moment it starts, wherever it started, and `stop()` drains the set\n // before resolving: `await runtime.stop()` then means \"teardown is done\", which\n // is the only reading a host evicting an isolate can act on.\n //\n // The rejection is attached HERE, once, so a failing teardown reaches the sink\n // under `\"sub-cleanup\"` (the same phase a synchronous cleanup throw uses)\n // instead of a `console.warn` at each battery, and can never become an\n // unhandled rejection.\n const pendingDisposals = new Set<Promise<void>>();\n\n function trackDisposal(result: void | Promise<void>): void {\n if (!(result instanceof Promise)) return;\n const settling: Promise<void> = result\n .catch((err) => {\n reportError(err, { phase: \"sub-cleanup\" });\n })\n .finally(() => {\n pendingDisposals.delete(settling);\n });\n pendingDisposals.add(settling);\n }\n\n /**\n * Wait for the disposals started so far, bounded by `disposeTimeoutMs`. On\n * expiry report a `DisposeTimeoutNotice` and return anyway — `stop()` resolves\n * regardless (contract), and a release that never settles must not become a\n * host that never shuts down. Warn-only, like every `RuntimeDiscardNotice`:\n * the host asked for this teardown, the loss is legal, and it is now visible.\n */\n async function drainDisposals(): Promise<void> {\n if (pendingDisposals.size === 0) return;\n const outstanding = [...pendingDisposals];\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const outcome = await Promise.race([\n Promise.all(outstanding).then(() => \"settled\" as const),\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), disposeTimeoutMs);\n }),\n ]);\n if (outcome === \"timeout\") {\n reportError(\n new DisposeTimeoutNotice(outstanding.length, disposeTimeoutMs),\n { phase: \"discard\" },\n );\n }\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n // Dispose each named dep-keyed slot: run its `Dispose` (throws isolated +\n // routed to the sink under `\"sub-cleanup\"`, exactly as `stopSubs` does for the\n // manual path), then drop the slot regardless of a throw. The single home for\n // the dispose-and-delete discipline shared by `reconcileDepSubs`'s teardown /\n // re-arm passes and `stop()`.\n function disposeDepSubs(indices: Iterable<number>): void {\n for (const index of indices) {\n const running = depSubRegistry.get(index);\n if (running === undefined) continue;\n try {\n trackDisposal(running.dispose());\n } catch (err) {\n reportError(err, { phase: \"sub-cleanup\" });\n }\n depSubRegistry.delete(index);\n }\n }\n\n /**\n * Reconcile the dep-keyed Subs (`machine.subs`) against `state`. Runs as the\n * first pass of `reconcileSubs`, sharing the dispose-on-change /\n * dispose-on-null machinery with the manual Sub path. For each entry:\n *\n * - `deps(state)` is nullish (`depsInactive`) → the Sub is inactive in this\n * state; dispose it if it was running.\n * - otherwise → `id = structuralHash(deps)`; if no source is running for\n * this entry, or the running id differs (re-arm), dispose the old source\n * and run `source(state, dispatch, ctx)` to open a fresh one (the entry\n * re-derives its own typed slice from `state`).\n * - Unchanged id → leave the source running (the no-churn case).\n *\n * Throws are collected and returned rather than thrown here (same contract as\n * the manual path) so one bad entry doesn't strand the others. That covers\n * `deps` and the hash, not just `source`: `deps` is user code on exactly the\n * same footing, and an unguarded throw there stranded every LATER entry AND\n * the manual `subscriptions` aggregate, which is only reached after this loop.\n * A machine that declares no `subs` returns immediately — the pass is inert.\n */\n function reconcileDepSubs(): unknown {\n let firstError: unknown = null;\n const subs = machine.subs;\n if (!subs) return firstError;\n for (const [i, entry] of subs.entries()) {\n // `deps` + `structuralHash` in ONE guarded step: both are pure user-data\n // reads whose failure means \"this entry's slice is unknowable\", and the\n // recovery is identical — remember the error, leave the slot untouched,\n // keep reconciling the siblings.\n let deps: unknown;\n let id: string;\n try {\n deps = entry.deps(state as S);\n if (depsInactive(deps)) {\n // Inactive in this state — tear down if running.\n disposeDepSubs([i]);\n continue;\n }\n id = structuralHash(deps);\n } catch (err) {\n if (firstError === null) firstError = err;\n continue;\n }\n\n const running = depSubRegistry.get(i);\n if (running !== undefined && running.runningId === id) {\n // No-churn case: same deps → leave the source running.\n continue;\n }\n // Re-arm (id changed) or first arm — dispose the stale source first.\n disposeDepSubs([i]);\n try {\n // `dispatchUnawaited`, never the raw `enqueueDispatch`: a source's\n // dispatch has no caller to reject at, and the gate rejects during\n // teardown — handing it the raw promise-returning form turned every\n // Sub that fired while `stop()` drained into an unhandled rejection\n // that bypassed `onError` entirely.\n const dispose = entry.source(state as S, dispatchUnawaited, ctx);\n depSubRegistry.set(i, { runningId: id, dispose });\n } catch (err) {\n if (firstError === null) firstError = err;\n // Do NOT register; continue so other dep-keyed sources still arm.\n }\n }\n return firstError;\n }\n\n /**\n * Reconcile subscriptions against `state`, after every save. Same id old+new →\n * leave running; removed id → cleanup (throws isolated, routed to the sink);\n * new id → start (throw remembered and re-thrown after the loop so all other\n * new subs still register).\n */\n function reconcileSubs(): void {\n // Dep-keyed pass FIRST, then the manual aggregate — ONE reconcile pass over\n // both paths. Its start error is remembered (it happened first) and thrown\n // after the manual pass so a bad dep-keyed source never strands the manual\n // subs, and vice versa.\n const depError = reconcileDepSubs();\n if (!machine.subscriptions) {\n if (depError !== null) throw depError;\n return;\n }\n const desired = machine.subscriptions(state as S);\n const desiredIds = new Set<string>();\n\n // Collision assert: within one desired set, two subs sharing an id but\n // declaring different types is a silent bug class. (Same id across\n // transitions is the no-churn case and MUST NOT throw.)\n const desiredTypeById = new Map<string, string>();\n for (const sub of desired) {\n const existing = desiredTypeById.get(sub.id);\n if (existing !== undefined && existing !== sub.type) {\n throw new SubIdCollisionError(sub.id, existing, sub.type);\n }\n desiredTypeById.set(sub.id, sub.type);\n }\n\n // Removals first — anything in the registry not in `desired` should stop.\n for (const sub of desired) desiredIds.add(sub.id);\n stopSubs([...subRegistry.keys()].filter((id) => !desiredIds.has(id)));\n\n // Additions — anything in `desired` not in the registry should start.\n let firstStartError: unknown = depError;\n for (const sub of desired) {\n if (subRegistry.has(sub.id)) continue;\n const handler = machine.subscribe?.[sub.type as U[\"type\"]];\n if (!handler) {\n // No handler for this sub type — programmer error; skip.\n continue;\n }\n try {\n // Same reasoning as the dep-keyed source above: a subscribe handler's\n // dispatch is unawaited by construction, so it gets the wrapped form.\n const cleanup = handler(\n sub as Extract<U, { type: U[\"type\"] }>,\n ctx,\n dispatchUnawaited,\n );\n subRegistry.set(sub.id, cleanup);\n } catch (err) {\n if (firstStartError === null) firstStartError = err;\n // Do NOT register; continue to next sub so other starts still run.\n }\n }\n if (firstStartError !== null) throw firstStartError;\n }\n\n // `interpret` is optional when `C extends Cmd<never>`; default a missing map to\n // `{}` — the per-cmd `if (!handler) continue` preserves invariant-6 forward\n // progress for a miswired consumer.\n const interpretMap: Interpret<M, C, Ctx> =\n (machine as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n\n // The ONE `(msg) => void` handed to every producer that cannot await its own\n // dispatch: a detached interpret handler's `ctx.waitUntil(...)` tail, a\n // dep-keyed Sub's `source`, a `subscribe[type]` handler. Same serial-tail\n // enqueue every other dispatch uses (`enqueueDispatch` chains on `tail`),\n // wrapped so the rejection — which has no caller, the original dispatcher\n // having already resolved — routes to the sink with the phase DERIVED from\n // the error class (`reportUndelivered`).\n //\n // Handing any of those sites the raw `enqueueDispatch` is the defect this\n // shape exists to prevent: its promise REJECTS whenever the gate is shut, so\n // a Sub that fires during `stop()`'s drain produced an unhandled rejection\n // that reached the host's global handler while `onError` saw nothing. A\n // handler authored via `wrapDetached` receives a NARROWED view of this fn\n // (only its declared result-Msg set); a plain leaf handler ignores it.\n const dispatchUnawaited = (msg: M): void => {\n enqueueDispatch(msg).catch(reportUndelivered);\n };\n\n /**\n * Report a re-dispatch that nobody can await. The phase is DERIVED from the\n * rejection the gate produced, so the two call sites cannot drift: a\n * `DispatchDiscardedError` means the teardown refused the Msg (`\"discard\"` —\n * warn-only), anything else is a genuine failure of the follow-up itself\n * (`\"follow-up\"` — the default sink rethrows it).\n */\n function reportUndelivered(error: unknown): void {\n reportError(error, {\n phase: error instanceof DispatchDiscardedError ? \"discard\" : \"follow-up\",\n });\n }\n\n /**\n * Count an interpret handler's work as in flight for exactly the lifetime of\n * its promise. The ONE writer of `inFlightCmds`, so \"how many Cmds are\n * outstanding?\" has a single definition; `finally`-balanced, so a rejecting\n * handler can never strand the count above zero. A handler that throws\n * SYNCHRONOUSLY never reaches here, which is correct — it was never in\n * flight.\n */\n function trackInFlight<T>(work: T | Promise<T>): Promise<T> {\n inFlightCmds++;\n return Promise.resolve(work).finally(() => {\n inFlightCmds--;\n });\n }\n\n /**\n * Run `interpret` for each emitted cmd. A returned follow-up Msg is enqueued\n * onto the tail (NOT dispatched re-entrantly). The first error stops further\n * handlers in this transition.\n */\n async function runInterpret(cmds: readonly C[]): Promise<void> {\n for (const cmd of cmds) {\n const handler = interpretMap[cmd.type as C[\"type\"]];\n if (!handler) continue;\n const follow = await trackInFlight(\n handler(\n cmd as Extract<C, { type: C[\"type\"] }>,\n augmentedCtx,\n dispatchUnawaited,\n ),\n );\n if (follow !== undefined && follow !== null) {\n // The follow-up's rejection has no caller (the original dispatcher\n // resolved), so route it to the sink (invariant 6); name a failure Msg\n // via `tryInterpret` to fold it back into state.\n enqueueDispatch(follow as M).catch(reportUndelivered);\n }\n }\n }\n\n // Throws isolated so one bad listener does not strand the others.\n function fireListeners(): void {\n fanout(listeners, \"listener\", (listener) => listener());\n }\n\n // After `fireListeners` so observers see what subscribers see. APPLIED\n // transitions only — `msg` is total (boot routes to `fireBoot`).\n function fireObservers(msg: M): void {\n if (observers.size === 0 || state === undefined) return;\n const snapshot = state;\n fanout(observers, \"observer\", (observer) => observer(msg, snapshot));\n }\n\n // Project the transition to semantic events and fan each to its `on(...)`\n // handlers; a throw in the projector OR a handler is isolated.\n function fireEvents(msg: M): void {\n if (eventHandlers.size === 0 || state === undefined) return;\n let events: readonly E[];\n try {\n events = projectEvents(msg, state);\n } catch (err) {\n reportError(err, { phase: \"event\" });\n return;\n }\n for (const event of events) {\n const bucket = eventHandlers.get(event.type);\n if (bucket === undefined) continue;\n fanout(bucket, \"event\", (handler) => handler(event));\n }\n }\n\n // Fire every `onBoot` handler with the initial State ONCE and flip `booted`.\n function fireBoot(): void {\n booted = true;\n if (bootHandlers.size === 0 || state === undefined) return;\n const snapshot = state;\n fanout(bootHandlers, \"boot\", (handler) => handler(snapshot));\n }\n\n // Resolve every parked `done()` waiter iff the just-folded State is terminal —\n // so `done()` settles on the same transition `result()` first returns it.\n function settleDoneWaiters(): void {\n if (doneWaiters.size === 0 || state === undefined) return;\n if (!isTerminal(state)) return;\n const snapshot = state;\n const parked = [...doneWaiters];\n doneWaiters.clear();\n for (const resolve of parked) resolve(snapshot);\n }\n\n // The post-transition commit tail: install state, then save → reconcile subs →\n // interpret → fire fanout → settle done-waiters. Save-before-effects is the\n // hard ordering; tests pin it. The normal transition and the `restart`\n // supervision branch both end here.\n async function commit(next: S, msg: M, cmds: readonly C[]): Promise<void> {\n state = next;\n if (store) await store.save(next);\n reconcileSubs();\n await runInterpret(cmds);\n fireListeners();\n fireObservers(msg);\n fireEvents(msg);\n settleDoneWaiters();\n }\n\n /**\n * Instance-identity filter: is this message addressed to a DIFFERENT instance\n * than the one this state owns? When the machine declares an `identity`, a\n * `true` here drops the message before `update` runs, so the reducer never\n * sees a foreign-instance message and no cell needs a\n * `msg.runId !== state.runId` guard.\n *\n * A message with no identity (`ofMsg` → undefined) is identity-agnostic and\n * always proceeds. `ofState` → undefined means this instance has no identity\n * to defend yet (an `idle` state before any run is established), so an\n * addressed message there is identity-ESTABLISHING, not foreign. Drop only\n * when both identities are present and differ.\n *\n * Pure and synchronous; a throw is the caller's to supervise (see\n * `stepDispatch`).\n */\n function isMisaddressed(msg: M, current: S): boolean {\n if (machine.identity === undefined) return false;\n const addressed = machine.identity.ofMsg(msg);\n if (addressed === undefined) return false;\n const own = machine.identity.ofState(current);\n if (own === undefined) return false;\n return structuralHash(addressed) !== structuralHash(own);\n }\n\n /**\n * One full transition: update → save → reconcile subs → interpret → fire.\n * Save-before-effects is the hard ordering; tests pin it. A `save` throw\n * propagates after the in-memory `state` is advanced; reconcile/interpret\n * throws after `save` has succeeded.\n */\n async function stepDispatch(msg: M): Promise<void> {\n if (state === undefined) {\n throw new Error(\"@demlik/tea: runtime not booted\");\n }\n // The identity filter and the reducer are ONE synchronous user-code step,\n // and they are protected as one. The projections used to run above this\n // `try`, so a throwing `ofMsg` / `ofState` was neither reported nor\n // supervised while an identical throw one line later was both — and since\n // `structuralHash` throws on a bigint or a non-plain value, a snowflake-style\n // run id put EVERY dispatch on that unprotected path.\n //\n // The reentrancy brand guarantees this whole step cannot suspend, so a throw\n // here is clean with `state` still pre-transition; it routes to the declared\n // supervision strategy under `phase: \"reduce\"` — the transition's own\n // synchronous code failed, whichever half of it that was. Folding goes\n // through `applyCellChecked` — the single dev-checked\n // reducer-vs-transitions primitive `foldUpdates` also folds through (see\n // `pure/core.ts`).\n let next: S;\n let cmds: readonly C[];\n try {\n if (isMisaddressed(msg, state)) {\n // The drop advances nothing: no save, no reconcile, no interpret, no\n // listener/observer/event fire, no done-waiter settle — and it RESOLVES\n // the dispatch, because a mis-addressed message is not the caller's\n // error. That is exactly why it must be reported: without this the\n // caller cannot tell \"applied\" from \"silently discarded\", and a reusable\n // Durable Object serving run A then run B lost run B while reporting\n // success. `IdentityDropNotice` is a `RuntimeDiscardNotice` — warn by\n // default, never fatal (invariant 6: the enforcement point is\n // observable, which is what makes it ONE point).\n reportError(new IdentityDropNotice(msg.type), {\n phase: \"identity-drop\",\n });\n return;\n }\n [next, cmds] = applyCellChecked<S, M, C>(machine, state, msg);\n } catch (reduceError) {\n // Invariant 6 — surface the failure as data FIRST, for every strategy.\n reportError(reduceError, { phase: \"reduce\" });\n switch (supervision.strategy) {\n case \"restart\": {\n // Host supplies last-known-good state; core installs it and KEEPS\n // FOLDING from there with no cmds (the throwing reduce produced none).\n // A throw inside `rehydrate` is NOT caught — it surfaces to the caller.\n await commit(supervision.rehydrate(state, msg, reduceError), msg, []);\n return;\n }\n case \"escalate\":\n // Surface + propagate; the runtime stays live for a parent supervisor.\n throw reduceError;\n default:\n // `stop` (safe default): halt. State is NOT advanced; propagate so THIS\n // dispatch also rejects — the halt is observable, never a silent resume.\n gate = \"closed\";\n throw reduceError;\n }\n }\n await commit(next, msg, cmds);\n }\n\n // Boot has two phases. With NO store, `loaded = null` without an await — run\n // `init(null, ctx)` IMMEDIATELY so `getState()` is observable synchronously\n // (what `useSyncExternalStore` consumers need to render the first commit\n // without a flicker). The async remainder runs in `stepBootEffects` as the\n // first tail entry. With a store we cannot `init` synchronously (we'd invent a\n // loaded value), so the full path runs there; `store.load` throws propagate\n // via the boot promise.\n let pendingInitCmds: readonly C[] = [];\n if (!store) {\n const [initialState, initCmds] = machine.init(null, ctx);\n state = initialState;\n pendingInitCmds = initCmds;\n }\n\n async function stepBootEffects(): Promise<void> {\n if (store) {\n // Boundary parse (invariant 8): `store.load()` returns `unknown`;\n // `store.migrate(raw)` is the required parse — `S` on recognized shape,\n // `null` on unrecognized (boots fresh). `migrate` MUST NOT throw; if it\n // does we surface via the boot promise (same as a `load` throw).\n const raw = await store.load();\n const parsed = store.migrate(raw);\n const [initialState, initCmds] = machine.init(parsed, ctx);\n state = initialState;\n pendingInitCmds = initCmds;\n await store.save(state);\n }\n reconcileSubs();\n await runInterpret(pendingInitCmds);\n fireListeners();\n // Boot has no applied Msg — deliver the initial State via `onBoot`, not\n // `observe`, and project no semantic event.\n fireBoot();\n // A rehydrated boot can land terminal — settle any pre-boot `done()` waiter.\n settleDoneWaiters();\n }\n\n /**\n * Enqueue a dispatch on the tail — the single gate re-entrant interpret /\n * subscribe calls also go through. Rejects when the gate is not open (with a\n * `DispatchDiscardedError` while `stop()` drains, a plain stopped Error once it\n * has), boot failed, or the reducer / save / sub start / interpret throws.\n */\n function enqueueDispatch(msg: M): Promise<void> {\n if (gate !== \"open\") {\n // The gate's state at refusal time IS the classification — the report\n // sites read the error class, never the message.\n return Promise.reject(\n gate === \"draining\"\n ? new DispatchDiscardedError(msg.type)\n : new Error(\"@demlik/tea: runtime stopped\"),\n );\n }\n const next = tail.then(() => {\n if (bootError !== null) throw bootError;\n return stepDispatch(msg);\n });\n // Swallow the rejection on the tail so one failing dispatch does NOT poison\n // every subsequent one. The original `next` still rejects for the caller.\n tail = next.catch(() => {});\n return next;\n }\n\n /**\n * Drain the serial tail to quiescence. Every interpret follow-up calls\n * `enqueueDispatch`, which reassigns `tail` SYNCHRONOUSLY before the parent\n * step resolves, so awaiting the current `tail` and re-reading it catches every\n * transitively enqueued follow-up; loop until the reference is stable. Bounded\n * by `idleCap` — on cap REJECT with `QuiescenceTimeoutError` (never a silent\n * resolve), keeping a livelock distinguishable from quiescence (invariant 6).\n */\n async function drainToQuiescence(): Promise<void> {\n for (let i = 0; i < idleCap; i++) {\n const observed = tail;\n await observed;\n if (tail === observed) return;\n }\n throw new QuiescenceTimeoutError(idleCap);\n }\n\n /**\n * The public `dispatch`: run-to-quiescence by default. Await the Msg's OWN\n * transition first (so a reducer / save / interpret throw on THIS Msg surfaces\n * before any drain), then — unless `{ settle: \"once\" }` — drain the transitive\n * follow-up chain.\n */\n async function dispatchToQuiescence(\n msg: M,\n opts?: { readonly settle?: DispatchSettle },\n ): Promise<void> {\n await enqueueDispatch(msg);\n if (opts?.settle === \"once\") return;\n await drainToQuiescence();\n }\n\n // `bootPromise` is the un-swallowed promise `runtime.ready` chains off (so\n // callers see the boot error directly); `tail` gets the swallowed branch so a\n // boot failure does NOT poison every subsequent dispatch's chain (each surfaces\n // `bootError` in `enqueueDispatch`).\n const bootPromise = stepBootEffects();\n tail = bootPromise.catch((err) => {\n bootError = err;\n });\n\n // `ready` chains off `bootPromise` so a failed boot never hands out a `Runtime`\n // (keeping `getState()` total). The `runtime` forward reference resolves at\n // `.then` time, after the literal below initializes. Idempotent.\n const readyPromise: Promise<Runtime<S, M, E>> = bootPromise.then(\n () => runtime,\n );\n\n const runtime: Runtime<S, M, E> = {\n dispatch: dispatchToQuiescence,\n dispatchOnce: enqueueDispatch,\n getState(): S {\n // TOTAL. A `Runtime` is only obtainable by awaiting `ready`, which resolves\n // AFTER boot set `state`; a failed boot rejects `ready`, so no `Runtime` is\n // handed out then. The cast encodes that invariant.\n return state as S;\n },\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n observe(observer: (msg: M, state: S) => void): () => void {\n observers.add(observer);\n return () => {\n observers.delete(observer);\n };\n },\n onBoot(handler: (state: S) => void): () => void {\n // Already booted → fire immediately (cleanup is a no-op) so a late\n // subscriber never misses the one-shot boot.\n if (booted && state !== undefined) {\n const snapshot = state;\n fanout([handler], \"boot\", (h) => h(snapshot));\n return () => {};\n }\n bootHandlers.add(handler);\n return () => {\n bootHandlers.delete(handler);\n };\n },\n on<K extends E[\"type\"]>(\n type: K,\n handler: (event: Extract<E, { type: K }>) => void,\n ): () => void {\n // Monomorphic registry; per-type narrowing lives at THIS call site, and\n // `fireEvents` only routes an event to its own bucket, so the erased call\n // is sound.\n let bucket = eventHandlers.get(type);\n if (bucket === undefined) {\n bucket = new Set<(event: E) => void>();\n eventHandlers.set(type, bucket);\n }\n const erased = handler as (event: E) => void;\n bucket.add(erased);\n return () => {\n const set = eventHandlers.get(type);\n if (set === undefined) return;\n set.delete(erased);\n if (set.size === 0) eventHandlers.delete(type);\n };\n },\n subscribePort<T>(port: Port<T>, listener: (value: T) => void): () => void {\n const key = port as Port<unknown>;\n let bucket = portRegistry.get(key);\n if (!bucket) {\n bucket = new Set<(value: unknown) => void>();\n portRegistry.set(key, bucket);\n }\n // Bucket stores `(value: unknown) => void`; per-port type safety at this site.\n const erased = listener as (value: unknown) => void;\n bucket.add(erased);\n return () => {\n const set = portRegistry.get(key);\n if (!set) return;\n set.delete(erased);\n if (set.size === 0) portRegistry.delete(key);\n };\n },\n emitPort<T>(port: Port<T>, value: T): void {\n // Lets `observe`-driven Port emission work without a per-transition Cmd.\n portEmit(port, value);\n },\n ready: readyPromise,\n idle(): Promise<void> {\n return drainToQuiescence();\n },\n result(): S | undefined {\n // TOTAL. No predicate → `isTerminal` is `() => false`, so a non-terminating\n // machine reads `undefined` forever.\n const current = state as S;\n return isTerminal(current) ? current : undefined;\n },\n done(): Promise<S> {\n // Already terminal → resolve at once (never parks, so it can't miss the\n // terminal transition). Otherwise park a resolver for `settleDoneWaiters`.\n const current = state as S;\n if (isTerminal(current)) return Promise.resolve(current);\n return new Promise<S>((resolve) => {\n doneWaiters.add(resolve);\n });\n },\n async stop(): Promise<void> {\n // Open the discard window unless the gate is already `\"closed\"` (a\n // supervision halt, or a redundant second `stop()`): the gate only\n // advances, so a Msg refused after a halt or after `stop()` returned stays\n // a loud error rather than being re-labelled a teardown discard.\n if (gate === \"open\") gate = \"draining\";\n // Report BEFORE the drain: after `await tail` the count is zero by\n // construction, and the fact worth surfacing is what was outstanding at\n // the moment the host let go. `stop()` drains, but every consumer of the\n // resulting transitions (listeners, observers, event handlers) is being\n // torn down with it, so those Cmds' results reach nobody (issue #365).\n if (inFlightCmds > 0) {\n reportError(new RuntimeDiscardedError(inFlightCmds), {\n phase: \"discard\",\n });\n }\n // Drain in-flight work. Tail rejections were swallowed at enqueue time, so\n // this await always resolves. The drain TERMINATES because the gate refuses\n // the follow-ups those handlers return — allowing them in instead would let\n // a handler chain extend the tail without end.\n await tail;\n // The barrier is now absolute: everything that was in flight has settled,\n // so a dispatch from here on is a consumer using a retired runtime.\n gate = \"closed\";\n // Run every active sub cleanup; throws isolated and routed to the sink.\n stopSubs([...subRegistry.keys()]);\n // Dispose every live dep-keyed source too (same throw-isolation).\n disposeDepSubs([...depSubRegistry.keys()]);\n // …then WAIT for the teardown work that is still settling — the ones\n // above, plus any async cleanup a mid-run reconcile started. `stop()`\n // resolving has to mean \"teardown is done\", or a host doing\n // `await stop(); env.evict()` drops the isolate mid-release and re-creates\n // the exact leak the managed-resource battery exists to prevent. Bounded\n // by `disposeTimeoutMs` so a release that never settles cannot hold the\n // host open (see `drainDisposals`).\n await drainDisposals();\n // Flush final state. A save throw here does not reject `stop()` (contract:\n // resolves regardless) but IS loss of the last write, so route it to the\n // sink rather than swallowing it (invariant 6).\n if (store && state !== undefined && bootError === null) {\n try {\n await store.save(state);\n } catch (error) {\n reportError(error, { phase: \"stop-save\" });\n }\n }\n },\n };\n\n return runtime;\n}\n"]}
|
|
@@ -117,16 +117,19 @@ type Sub<T extends string = string> = {
|
|
|
117
117
|
readonly id: SubId;
|
|
118
118
|
readonly type: T;
|
|
119
119
|
};
|
|
120
|
-
type Dispose = () => void
|
|
120
|
+
type Dispose = () => void | Promise<void>;
|
|
121
121
|
declare function structuralHash(deps: unknown): string;
|
|
122
122
|
interface DepKeyedSub<S, M, Ctx = unknown> {
|
|
123
123
|
/**
|
|
124
|
-
* The slice of state this Sub depends on. `null` ⇒ the Sub is
|
|
125
|
-
* this state (the substrate disposes it if it was running)
|
|
124
|
+
* The slice of state this Sub depends on. `null` OR `undefined` ⇒ the Sub is
|
|
125
|
+
* inactive in this state (the substrate disposes it if it was running) — see
|
|
126
|
+
* `depsInactive`, so `(s) => s.optionalRunId` gates correctly. Otherwise the
|
|
126
127
|
* Sub is active, keyed on `structuralHash(deps)`.
|
|
127
128
|
*
|
|
128
129
|
* Pure (invariant 2). Plain JSON-compatible data only (invariant 1) — the
|
|
129
|
-
* structural hash walks it deterministically
|
|
130
|
+
* structural hash walks it deterministically and THROWS on a `Date`, `Map`,
|
|
131
|
+
* `Set`, `Error` or class instance rather than collapsing them all onto one
|
|
132
|
+
* id. Project such a value first (`startedAt.toISOString()`).
|
|
130
133
|
*/
|
|
131
134
|
readonly deps: (state: S) => unknown;
|
|
132
135
|
/**
|
|
@@ -195,7 +198,7 @@ type Subscribe<M extends {
|
|
|
195
198
|
}, U extends Sub, Ctx> = {
|
|
196
199
|
[K in U["type"]]: (sub: Extract<U, {
|
|
197
200
|
type: K;
|
|
198
|
-
}>, ctx: Ctx, dispatch: (msg: M) => void) =>
|
|
201
|
+
}>, ctx: Ctx, dispatch: (msg: M) => void) => Dispose;
|
|
199
202
|
};
|
|
200
203
|
type Machine<S, M extends {
|
|
201
204
|
type: string;
|
|
@@ -284,4 +287,4 @@ declare function foldMsgs<S, M extends {
|
|
|
284
287
|
type: string;
|
|
285
288
|
}, C extends Cmd, U extends Sub, Ctx>(machine: Machine<S, M, C, U, Ctx>, base: S, msgs: readonly M[]): S;
|
|
286
289
|
|
|
287
|
-
export { Cmd as C, type DepKeyedSub as D, type
|
|
290
|
+
export { Cmd as C, type DepKeyedSub as D, type Interpret as I, type Machine as M, NoCellError as N, type PortEmitter as P, type Reducer as R, type Sub as S, type Transitions as T, type UpdateForm as U, type Port as a, type SubId as b, type InterpretDetached as c, type ContextFree as d, type Dispose as e, type Identity as f, type NoCtx as g, type Subscribe as h, type SyncReturn as i, applyCell as j, detectUpdateForm as k, foldMsgs as l, formOf as m, msgKeysOf as n, subId as o, structuralHash as s };
|
package/dist/deadline/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as Sub,
|
|
2
|
-
import { S as SubscribeHandler } from '../types-
|
|
1
|
+
import { S as Sub, b as SubId } from '../core-JPHsMZVB.js';
|
|
2
|
+
import { S as SubscribeHandler } from '../types-BMZ7IMrd.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* @demlik/tea/deadline — a one-shot Sub that fires when an ABSOLUTE wall-clock
|
package/dist/deadline/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { deadlineExceeded, deadlineSub, setTimeoutArmTimer, subscribeDeadline, subscribeWith } from '../chunk-
|
|
1
|
+
export { deadlineExceeded, deadlineSub, setTimeoutArmTimer, subscribeDeadline, subscribeWith } from '../chunk-ASX7PL2K.js';
|
|
2
2
|
import '../chunk-2YFLOCWX.js';
|
|
3
|
-
import '../chunk-
|
|
4
|
-
import '../chunk-
|
|
3
|
+
import '../chunk-ZH454CR5.js';
|
|
4
|
+
import '../chunk-O7ED34JH.js';
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
6
6
|
//# sourceMappingURL=index.js.map
|
package/dist/do/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { S as Store, R as Runtime, B as BootingRuntime } from '../runtime-types-
|
|
2
|
-
import { P as PendingEffectsRecorder, b as EffectOwed, a as EffectConfirmed } from '../durable-effects-
|
|
3
|
-
export { D as DeliveryId, E as EffectLedgerEvent, O as OwedEffect,
|
|
1
|
+
import { S as Store, R as Runtime, B as BootingRuntime } from '../runtime-types-BbBq4LWo.js';
|
|
2
|
+
import { P as PendingEffectsRecorder, b as EffectOwed, a as EffectConfirmed } from '../durable-effects-MRnCBCxV.js';
|
|
3
|
+
export { D as DeliveryId, E as EffectLedgerEvent, O as OwedEffect, c as PendingEffectsLedger, d as applyEffectEvent, e as emptyLedger, f as foldLedger, i as isOwed, p as pendingEffectsLedger, s as survivingEffects } from '../durable-effects-MRnCBCxV.js';
|
|
4
4
|
import { RetryPolicy, Rng } from '../retry-backoff/index.js';
|
|
5
|
-
import { C as Cmd, S as Sub, M as Machine } from '../core-
|
|
6
|
-
import {
|
|
5
|
+
import { C as Cmd, S as Sub, M as Machine } from '../core-JPHsMZVB.js';
|
|
6
|
+
import { k as AgentEvent, A as AgentTurn, s as AgentState, p as AgentMachineMsg, t as AgentStatus } from '../machine-nGXCMyHn.js';
|
|
7
7
|
import '../llm-call/index.js';
|
|
8
8
|
import '../resilient-call/index.js';
|
|
9
9
|
import '../cache/index.js';
|
|
10
|
-
import '../types-
|
|
10
|
+
import '../types-BMZ7IMrd.js';
|
|
11
11
|
import '../circuit-breaker/index.js';
|
|
12
12
|
import '../deadline/index.js';
|
|
13
13
|
import '../protocol-B5YmJr0d.js';
|
|
@@ -42,7 +42,7 @@ import '../fan-out/index.js';
|
|
|
42
42
|
* The rule in one line: **pull when the client drives a cold-between-steps
|
|
43
43
|
* control loop; push when the DO drives unsolicited fan-out.** A hibernating
|
|
44
44
|
* agent whose only traffic is "run the next tool" wants pull — that is the case
|
|
45
|
-
*
|
|
45
|
+
* a production consumer adopted this carrier for.
|
|
46
46
|
*
|
|
47
47
|
* ## Why pull is hibernation-correct
|
|
48
48
|
*
|
|
@@ -134,7 +134,7 @@ type StepResponse<I, O> = {
|
|
|
134
134
|
};
|
|
135
135
|
/**
|
|
136
136
|
* The NOT-READY arm — the run is computing OUT-OF-BAND under a defer-resume host
|
|
137
|
-
* (
|
|
137
|
+
* (a production incident: a non-blocking pull carrier must
|
|
138
138
|
* answer a pull with an explicit "computing, poll again" instead of holding the
|
|
139
139
|
* request across a multi-second step). The held `/step` request returns this
|
|
140
140
|
* IMMEDIATELY instead of inline-awaiting `engine.resume`; the hands re-poll
|
|
@@ -242,7 +242,7 @@ interface StepHostConfig {
|
|
|
242
242
|
}
|
|
243
243
|
/**
|
|
244
244
|
* The DEFER-RESUME hook — the opt-in seam that drives `engine.resume` OUT of the
|
|
245
|
-
* held `/step` request. A non-blocking host (
|
|
245
|
+
* held `/step` request. A non-blocking host (a non-blocking production audit carrier)
|
|
246
246
|
* cannot inline-await a multi-second step inside the held request, so instead of
|
|
247
247
|
* `stepHost` calling `engine.resume` inline it hands the posted result to this
|
|
248
248
|
* hook to SETTLE-AND-ENQUEUE (record it durably, schedule the compute in a
|