@demlik/tea 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.d.ts +14 -13
- package/dist/agent/index.js +6 -6
- package/dist/{chunk-F2US5BW6.js → chunk-22POWGFA.js} +17 -11
- package/dist/chunk-22POWGFA.js.map +1 -0
- package/dist/{chunk-HYDWG35Q.js → chunk-3B5X7SBB.js} +4 -4
- package/dist/{chunk-HYDWG35Q.js.map → chunk-3B5X7SBB.js.map} +1 -1
- package/dist/{chunk-RQULHGYH.js → chunk-66PY5WYF.js} +15 -3
- package/dist/{chunk-RQULHGYH.js.map → chunk-66PY5WYF.js.map} +1 -1
- package/dist/{chunk-AQ6ZIMEA.js → chunk-AYS5N6WY.js} +121 -37
- package/dist/chunk-AYS5N6WY.js.map +1 -0
- package/dist/{chunk-HUKZQX6U.js → chunk-L3TND7LA.js} +3 -3
- package/dist/{chunk-HUKZQX6U.js.map → chunk-L3TND7LA.js.map} +1 -1
- package/dist/{chunk-I5MQMJDW.js → chunk-Q5CQTBFA.js} +3 -3
- package/dist/{chunk-I5MQMJDW.js.map → chunk-Q5CQTBFA.js.map} +1 -1
- package/dist/{chunk-F7FMAWLA.js → chunk-QPEVCJ5Q.js} +3 -3
- package/dist/{chunk-F7FMAWLA.js.map → chunk-QPEVCJ5Q.js.map} +1 -1
- package/dist/{chunk-Z2L3LSNV.js → chunk-TCLBCERH.js} +17 -7
- package/dist/chunk-TCLBCERH.js.map +1 -0
- package/dist/{chunk-BLJ2JQSH.js → chunk-V46HSVCK.js} +3 -3
- package/dist/{chunk-BLJ2JQSH.js.map → chunk-V46HSVCK.js.map} +1 -1
- package/dist/{chunk-LYLTKJWM.js → chunk-VTQI2NHP.js} +3 -3
- package/dist/{chunk-LYLTKJWM.js.map → chunk-VTQI2NHP.js.map} +1 -1
- package/dist/{core-CTzMJ82M.d.ts → core-DnzqWy6u.d.ts} +1 -1
- package/dist/do/index.d.ts +13 -12
- package/dist/do/index.js +7 -7
- package/dist/{durable-effects-B0-qGQDy.d.ts → durable-effects-CWzA-o2B.d.ts} +1 -1
- package/dist/extension/index.d.ts +3 -3
- package/dist/extension/index.js +1 -1
- package/dist/flow/index.d.ts +15 -26
- package/dist/flow/index.js +8 -8
- package/dist/idempotency/index.d.ts +3 -3
- package/dist/idempotency/index.js +2 -2
- package/dist/{index-4vZzljCD.d.ts → index-C2DwkjlP.d.ts} +4 -4
- package/dist/{index-B5BZ-_cT.d.ts → index-CA_7I5g9.d.ts} +277 -87
- package/dist/{index-DJWIER_3.d.ts → index-CSyMYDAB.d.ts} +1 -1
- package/dist/{index-6A7dB8f6.d.ts → index-CuNO9m8i.d.ts} +2 -2
- package/dist/{index-TvRb1KVf.d.ts → index-DrIRb_Ch.d.ts} +1 -1
- package/dist/{index-q0hXFeZ0.d.ts → index-HSYgG2Yt.d.ts} +50 -15
- package/dist/{index-NjrT3fL2.d.ts → index-KXqTRJyb.d.ts} +4 -4
- package/dist/{index-DMCeMPMJ.d.ts → index-ZCMhnVKN.d.ts} +1 -1
- package/dist/index.d.ts +66 -6
- package/dist/index.js +1 -1
- package/dist/jev/index.d.ts +34 -22
- package/dist/jev/index.js +178 -126
- package/dist/jev/index.js.map +1 -1
- package/dist/{machine-CdIcN2Xm.d.ts → machine-DGlPWCWI.d.ts} +34 -26
- package/dist/machine-viz/index.d.ts +1 -1
- package/dist/machine-viz/index.js +1 -1
- package/dist/mem/index.d.ts +2 -2
- package/dist/mem/index.js +1 -1
- package/dist/node/index.d.ts +2 -2
- package/dist/node/index.js +1 -1
- package/dist/paginate/index.d.ts +6 -17
- package/dist/paginate/index.js +4 -4
- package/dist/parity/index.d.ts +3 -3
- package/dist/parity/index.js +2 -2
- package/dist/pbt/index.d.ts +1 -1
- package/dist/pbt/index.js +1 -1
- package/dist/persistence/index.d.ts +5 -5
- package/dist/persistence/index.js +3 -3
- package/dist/protocol-D8VbH-VH.d.ts +54 -0
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +1 -1
- package/dist/resilience/index.d.ts +8 -7
- package/dist/resilience/index.js +5 -5
- package/dist/{runtime-types-LWDoi943.d.ts → runtime-types-CMF13BBh.d.ts} +1 -1
- package/dist/testing/index.d.ts +147 -3
- package/dist/testing/index.js +95 -2
- package/dist/testing/index.js.map +1 -1
- package/dist/timing/index.d.ts +4 -4
- package/dist/timing/index.js +3 -3
- package/dist/{types-DP3f5NIl.d.ts → types-BseNPIhr.d.ts} +1 -1
- package/dist/work-queue/index.d.ts +4 -4
- package/package.json +1 -1
- package/dist/chunk-AQ6ZIMEA.js.map +0 -1
- package/dist/chunk-F2US5BW6.js.map +0 -1
- package/dist/chunk-Z2L3LSNV.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { asRng, recordFailure, shouldRetry, nextDelayMs, initRetry } from './chunk-VBDU4JL6.js';
|
|
2
|
-
import { initCache, set, deadlineSub, get } from './chunk-
|
|
3
|
-
import { Cmd, without, tryInterpret } from './chunk-
|
|
2
|
+
import { deadlineMsgType, subscribeDeadline, initCache, set, deadlineSub, get } from './chunk-22POWGFA.js';
|
|
3
|
+
import { Cmd, liftSlice, without, tryInterpret } from './chunk-66PY5WYF.js';
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
|
|
6
6
|
// src/protocol.ts
|
|
@@ -147,8 +147,9 @@ function remaining(window, nowMs) {
|
|
|
147
147
|
const live = prune(window, nowMs).length;
|
|
148
148
|
return Math.max(0, window.limit - live);
|
|
149
149
|
}
|
|
150
|
-
|
|
151
|
-
|
|
150
|
+
var DEFAULT_RESILIENT_NAME = "resilient";
|
|
151
|
+
function runCmdDef(name = DEFAULT_RESILIENT_NAME) {
|
|
152
|
+
return Cmd.define(`${name}_run`, {
|
|
152
153
|
input: z.custom(),
|
|
153
154
|
ok: z.custom(),
|
|
154
155
|
err: ["port_rejected", "deadline_exceeded"]
|
|
@@ -167,16 +168,23 @@ function charge(budget, at) {
|
|
|
167
168
|
const elapsed = Math.max(0, at - budget.chargingSinceMs);
|
|
168
169
|
return { remainingMs: budget.remainingMs - elapsed, chargingSinceMs: at };
|
|
169
170
|
}
|
|
170
|
-
function retryTimerId(key) {
|
|
171
|
-
return
|
|
171
|
+
function retryTimerId(name, key) {
|
|
172
|
+
return `${name}:retry:${key}`;
|
|
172
173
|
}
|
|
173
|
-
function deadlineTimerId(key) {
|
|
174
|
-
return
|
|
174
|
+
function deadlineTimerId(name, key) {
|
|
175
|
+
return `${name}:deadline:${key}`;
|
|
176
|
+
}
|
|
177
|
+
function deadlineNameOf(name) {
|
|
178
|
+
return name === DEFAULT_RESILIENT_NAME ? void 0 : name;
|
|
175
179
|
}
|
|
176
180
|
function createResilientCall(config, rng = Math.random) {
|
|
181
|
+
const name = config.name ?? DEFAULT_RESILIENT_NAME;
|
|
177
182
|
const cPolicy = circuitPolicy(config);
|
|
178
183
|
const rngBranded = asRng(rng);
|
|
179
|
-
const runCmd = runCmdDef();
|
|
184
|
+
const runCmd = runCmdDef(name);
|
|
185
|
+
const okType = `${name}_ok`;
|
|
186
|
+
const errType = `${name}_err`;
|
|
187
|
+
const deadlineName = deadlineNameOf(name);
|
|
180
188
|
function init() {
|
|
181
189
|
return {
|
|
182
190
|
circuit: initCircuit(),
|
|
@@ -218,7 +226,7 @@ function createResilientCall(config, rng = Math.random) {
|
|
|
218
226
|
phase: "failed",
|
|
219
227
|
error: {
|
|
220
228
|
_tag: "deadline_exceeded",
|
|
221
|
-
id: deadlineTimerId(key),
|
|
229
|
+
id: deadlineTimerId(name, key),
|
|
222
230
|
atMs: at
|
|
223
231
|
}
|
|
224
232
|
}),
|
|
@@ -336,7 +344,7 @@ function createResilientCall(config, rng = Math.random) {
|
|
|
336
344
|
}
|
|
337
345
|
function onTimer(s, msg) {
|
|
338
346
|
for (const [key, call] of Object.entries(s.calls)) {
|
|
339
|
-
if (msg.id === retryTimerId(key)) {
|
|
347
|
+
if (msg.id === retryTimerId(name, key)) {
|
|
340
348
|
if (call.phase !== "waiting_retry") return [s, []];
|
|
341
349
|
return gate(
|
|
342
350
|
s,
|
|
@@ -346,7 +354,7 @@ function createResilientCall(config, rng = Math.random) {
|
|
|
346
354
|
charge(call.budget, msg.atMs)
|
|
347
355
|
);
|
|
348
356
|
}
|
|
349
|
-
if (msg.id === deadlineTimerId(key)) {
|
|
357
|
+
if (msg.id === deadlineTimerId(name, key)) {
|
|
350
358
|
if (call.phase !== "running" && call.phase !== "waiting_retry")
|
|
351
359
|
return [s, []];
|
|
352
360
|
return [
|
|
@@ -368,13 +376,18 @@ function createResilientCall(config, rng = Math.random) {
|
|
|
368
376
|
const out = [];
|
|
369
377
|
for (const [key, call] of Object.entries(s.calls)) {
|
|
370
378
|
if (call.phase === "waiting_retry") {
|
|
371
|
-
out.push(
|
|
379
|
+
out.push(
|
|
380
|
+
deadlineSub(retryTimerId(name, key), call.retryAtMs, {
|
|
381
|
+
name: deadlineName
|
|
382
|
+
})
|
|
383
|
+
);
|
|
372
384
|
}
|
|
373
385
|
if (config.deadline !== void 0 && (call.phase === "running" || call.phase === "waiting_retry") && call.budget.remainingMs > 0) {
|
|
374
386
|
out.push(
|
|
375
387
|
deadlineSub(
|
|
376
|
-
deadlineTimerId(key),
|
|
377
|
-
call.budget.chargingSinceMs + call.budget.remainingMs
|
|
388
|
+
deadlineTimerId(name, key),
|
|
389
|
+
call.budget.chargingSinceMs + call.budget.remainingMs,
|
|
390
|
+
{ name: deadlineName }
|
|
378
391
|
)
|
|
379
392
|
);
|
|
380
393
|
}
|
|
@@ -382,25 +395,29 @@ function createResilientCall(config, rng = Math.random) {
|
|
|
382
395
|
return out;
|
|
383
396
|
}
|
|
384
397
|
function handlers(ports) {
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
};
|
|
398
|
+
const handle = tryInterpret(
|
|
399
|
+
(cmd) => ports.run(cmd.input, cmd.key),
|
|
400
|
+
(result, cmd) => ({
|
|
401
|
+
type: okType,
|
|
402
|
+
key: cmd.key,
|
|
403
|
+
result,
|
|
404
|
+
at: Date.now()
|
|
405
|
+
}),
|
|
406
|
+
(error, cmd) => ({
|
|
407
|
+
type: errType,
|
|
408
|
+
key: cmd.key,
|
|
409
|
+
error,
|
|
410
|
+
at: Date.now()
|
|
411
|
+
})
|
|
412
|
+
);
|
|
413
|
+
return { [runCmd.cmdType]: handle };
|
|
402
414
|
}
|
|
403
415
|
return {
|
|
416
|
+
// The Msg-name family this knob speaks, as a VALUE typed at `N`. `mount`
|
|
417
|
+
// keys its settle cells off this rather than off the `resilient_*`
|
|
418
|
+
// literals, so a named knob mounts into its own cells (#229) and the Cmd,
|
|
419
|
+
// the Msgs, the Sub ids and the mounted cells all derive from one name.
|
|
420
|
+
name,
|
|
404
421
|
init,
|
|
405
422
|
attempt,
|
|
406
423
|
resume,
|
|
@@ -412,10 +429,77 @@ function createResilientCall(config, rng = Math.random) {
|
|
|
412
429
|
handlers
|
|
413
430
|
};
|
|
414
431
|
}
|
|
415
|
-
function liftResilience(state,
|
|
416
|
-
return
|
|
432
|
+
function liftResilience(state, result) {
|
|
433
|
+
return liftSlice("resilience", state, result);
|
|
434
|
+
}
|
|
435
|
+
function mountResilientCall(knob, config) {
|
|
436
|
+
const { slice, attempt, onOk, onErr, onDeadline } = config;
|
|
437
|
+
function put(model, next) {
|
|
438
|
+
return {
|
|
439
|
+
...model,
|
|
440
|
+
...{ [slice]: next }
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
function settle(verb, fold) {
|
|
444
|
+
return (model, msg) => {
|
|
445
|
+
const [next, cmds] = verb(model[slice], msg.key, msg);
|
|
446
|
+
const settled = put(model, next);
|
|
447
|
+
if (fold === void 0) return [settled, cmds];
|
|
448
|
+
const [folded, extra] = fold(settled, msg);
|
|
449
|
+
return [folded, [...cmds, ...extra]];
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
const update = {
|
|
453
|
+
[attempt.on]: (model, msg) => {
|
|
454
|
+
const [next, cmds] = attempt.run(model[slice], msg);
|
|
455
|
+
return [put(model, next), cmds];
|
|
456
|
+
},
|
|
457
|
+
// Keyed off the knob's own name, not the `resilient_*` literals: a knob
|
|
458
|
+
// built with `name: "jev"` emits `jev_ok` / `jev_err`, and a mount that
|
|
459
|
+
// spelled the literals would spread cells nothing ever dispatches to.
|
|
460
|
+
[`${knob.name}_ok`]: settle(
|
|
461
|
+
(s, key, msg) => knob.succeed(s, key, msg),
|
|
462
|
+
onOk
|
|
463
|
+
),
|
|
464
|
+
[`${knob.name}_err`]: settle(
|
|
465
|
+
(s, key, msg) => knob.fail(s, key, msg),
|
|
466
|
+
onErr
|
|
467
|
+
),
|
|
468
|
+
// The one settle path that carries no settle Msg: `onTimer` writes
|
|
469
|
+
// `failed` straight into the slice, so a mounted `onErr` never sees it. The
|
|
470
|
+
// cell reads the transition off the two slices instead of inventing a Msg —
|
|
471
|
+
// whichever key moved INTO `failed` is the call that just died.
|
|
472
|
+
//
|
|
473
|
+
// Keyed off the knob's name for the same reason the two settle cells are
|
|
474
|
+
// (#238): the knob's deadline Sub dispatches `<name>_deadline`, so a cell
|
|
475
|
+
// spelling the bare literal would be one two named knobs both claim — and
|
|
476
|
+
// the second spread into `defineMachine` would silently win.
|
|
477
|
+
[deadlineMsgType(deadlineNameOf(knob.name))]: (model, msg) => {
|
|
478
|
+
const before = model[slice];
|
|
479
|
+
const [next, cmds] = knob.onTimer(before, msg);
|
|
480
|
+
const advanced = put(model, next);
|
|
481
|
+
if (onDeadline === void 0) return [advanced, cmds];
|
|
482
|
+
let folded = advanced;
|
|
483
|
+
const extra = [];
|
|
484
|
+
for (const [key, call] of Object.entries(next.calls)) {
|
|
485
|
+
if (call.phase !== "failed") continue;
|
|
486
|
+
if (before.calls[key]?.phase === "failed") continue;
|
|
487
|
+
const [m, c] = onDeadline(folded, { key, error: call.error, msg });
|
|
488
|
+
folded = m;
|
|
489
|
+
extra.push(...c);
|
|
490
|
+
}
|
|
491
|
+
return [folded, [...cmds, ...extra]];
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
return {
|
|
495
|
+
init: () => ({ [slice]: knob.init() }),
|
|
496
|
+
update,
|
|
497
|
+
subscriptions: (model) => knob.subs(model[slice]),
|
|
498
|
+
subscribe: { deadline: subscribeDeadline },
|
|
499
|
+
interpret: knob.handlers()
|
|
500
|
+
};
|
|
417
501
|
}
|
|
418
502
|
|
|
419
|
-
export { MsgType, canPass, createResilientCall, defaultCircuitPolicy, initBucket, initCircuit, initWindow, liftResilience, onFailure, onSuccess, record, refill, remaining, runCmdDef, tryConsume };
|
|
420
|
-
//# sourceMappingURL=chunk-
|
|
421
|
-
//# sourceMappingURL=chunk-
|
|
503
|
+
export { DEFAULT_RESILIENT_NAME, MsgType, canPass, createResilientCall, defaultCircuitPolicy, initBucket, initCircuit, initWindow, liftResilience, mountResilientCall, onFailure, onSuccess, record, refill, remaining, runCmdDef, tryConsume };
|
|
504
|
+
//# sourceMappingURL=chunk-AYS5N6WY.js.map
|
|
505
|
+
//# sourceMappingURL=chunk-AYS5N6WY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/protocol.ts","../src/internal/resilience/circuit-breaker/index.ts","../src/internal/resilience/rate-limit/index.ts","../src/internal/resilience/resilient-call/index.ts"],"names":[],"mappings":";;;;;;AAmCO,IAAM,OAAA,GAAU;AAAA;AAAA;AAAA,EAGrB,YAAA,EAAc,eAAA;AAAA;AAAA,EAEd,WAAA,EAAa,cAAA;AAAA;AAAA,EAEb,YAAA,EAAc,eAAA;AAAA;AAAA;AAAA,EAId,UAAA,EAAY,aAAA;AAAA;AAAA,EAEZ,WAAA,EAAa,eAAA;AAAA;AAAA,EAEb,YAAA,EAAc,gBAAA;AAAA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AAA,IAAI,MAAA,GAAS,QAAA;AACb,MAAA,MAAM,QAAa,EAAC;AACpB,MAAA,KAAA,MAAW,CAAC,KAAK,IAAI,CAAA,IAAK,OAAO,OAAA,CAAQ,IAAA,CAAK,KAAK,CAAA,EAAG;AACpD,QAAA,IAAI,IAAA,CAAK,UAAU,QAAA,EAAU;AAC7B,QAAA,IAAI,MAAA,CAAO,KAAA,CAAM,GAAG,CAAA,EAAG,UAAU,QAAA,EAAU;AAC3C,QAAA,MAAM,CAAC,CAAA,EAAG,CAAC,CAAA,GAAI,UAAA,CAAW,MAAA,EAAQ,EAAE,GAAA,EAAK,KAAA,EAAO,IAAA,CAAK,KAAA,EAAO,GAAA,EAAK,CAAA;AACjE,QAAA,MAAA,GAAS,CAAA;AACT,QAAA,KAAA,CAAM,IAAA,CAAK,GAAG,CAAC,CAAA;AAAA,MACjB;AACA,MAAA,OAAO,CAAC,MAAA,EAAQ,CAAC,GAAG,IAAA,EAAM,GAAG,KAAK,CAAC,CAAA;AAAA,IACrC;AAAA,GACF;AAcA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,OACH,EAAE,CAAC,KAAK,GAAG,IAAA,CAAK,MAAK,EAAE,CAAA;AAAA,IAG1B,MAAA;AAAA,IACA,eAAe,CAAC,KAAA,KAAU,KAAK,IAAA,CAAK,KAAA,CAAM,KAAK,CAAC,CAAA;AAAA,IAChD,SAAA,EAAW,EAAE,QAAA,EAAU,iBAAA,EAAkB;AAAA,IACzC,SAAA,EAAW,KAAK,QAAA;AAAS,GAC3B;AACF","file":"chunk-AYS5N6WY.js","sourcesContent":["// ===========================================================================\n// Protocol — the ONE typed source of truth for the cross-module Msg/Cmd\n// discriminant strings (issue #60).\n// ===========================================================================\n//\n// The resilient/agent/auth plumbing speaks a small fixed vocabulary of\n// discriminant strings on `{ type: ... }` Msgs and Cmds. Before this module\n// those literals were retyped inline across ~8 modules — `resilient_ok` alone\n// appeared as a hand-written `\"resilient_ok\"` in resilient-call, with-resilience,\n// llm-call, agent, do/host, paginated-walk, reconciler. Adding a variant or\n// renaming one was shotgun surgery with no compiler to catch a missed site.\n//\n// `MsgType` is that vocabulary, declared ONCE `as const`. Each entry is BOTH:\n// - a value — `MsgType.ResilientOk` is the string `\"resilient_ok\"`, used at\n// construction sites (`{ type: MsgType.ResilientOk, ... }`), reducer keys\n// (`[MsgType.ResilientOk]: ...`), and switch labels (`case MsgType.ResilientOk:`).\n// - a type — `typeof MsgType.ResilientOk` is the literal type `\"resilient_ok\"`,\n// used in the `readonly type:` field of every Msg/Cmd interface.\n//\n// Because the value and the type both derive from the single `as const`\n// declaration, a new variant or a rename is a ONE-LINE change here that\n// propagates with full exhaustiveness — not an 8-file edit.\n//\n// This module is BEHAVIOR-PRESERVING: every string is byte-identical to the\n// literal it replaces. It is internal plumbing vocabulary, NOT a public event\n// surface — `resilient_ok` / `agent_tool_ok` stay PRIVATE (the agent's\n// `agentEvents` projector is the ONE place they are read; #47). Centralizing\n// the literal here does NOT re-expose them to consumers.\n\n/**\n * The closed set of cross-module Msg/Cmd discriminant strings. Declared `as\n * const` so each entry is usable as both a value (construction / reducer keys /\n * switch labels) and, via `typeof MsgType.X`, a literal type (`readonly type:`\n * fields). The single source of truth for issue #60.\n */\nexport const MsgType = {\n // --- resilient-call: the run Cmd + its two settle Msgs -------------------\n /** The \"run the port for `key`\" effect Cmd resilient-call emits. */\n ResilientRun: \"resilient_run\",\n /** PRIVATE success settle Msg (read only by `agentEvents`, #47). */\n ResilientOk: \"resilient_ok\",\n /** Failure settle Msg — routed to the `fail` verb (back off via retry). */\n ResilientErr: \"resilient_err\",\n\n // --- agent: the wired machine's own entry-point Msgs ---------------------\n /** Begin a run. */\n AgentStart: \"agent_start\",\n /** PRIVATE tool-fan-out success settle Msg (read only by `agentEvents`, #47). */\n AgentToolOk: \"agent_tool_ok\",\n /** Tool-fan-out failure settle Msg. */\n AgentToolErr: \"agent_tool_err\",\n /**\n * Re-fire the one outstanding effect on rehydrate (the do↔agent seam). Fired\n * by `do/host`'s `autoBoot` via the typed `agentBootMsg` constructor, matched\n * by the agent reducer — see `AgentBootPort` in `../agent`.\n */\n AgentBoot: \"agent_boot\",\n /**\n * Stop the run from outside and settle it `cancelled` — what an `AbortSignal`\n * handed to `driveToDone` / a defined agent's `run` dispatches on abort. A\n * transition, never a throw: the outcome lands in the Model, so a reload reads\n * a run that ended rather than one to resume.\n */\n AgentCancel: \"agent_cancel\",\n\n // --- agent: the context-compaction round-trip (#85) ----------------------\n /**\n * The \"summarize the oldest N turns\" effect Cmd the agent emits when its\n * `CompactionPolicy` asks to compact before a brain call. A DEDICATED\n * round-trip (design B1), distinct from the brain call's `resilient_run`, so\n * compaction is its own honest `Awaiting` state — see `../agent`.\n */\n CompactRun: \"compact_run\",\n /** Compaction round-trip resolved — carries the summary text the fold-back folds. */\n CompactOk: \"compact_ok\",\n /** Compaction round-trip failed (exhausted retry) — surfaced as data, not a stall. */\n CompactErr: \"compact_err\",\n\n // --- token-refresh: the two refresh-result Msgs --------------------------\n /** Refresh port resolved — carries the fresh `Token`. */\n TokenRefreshed: \"token_refreshed\",\n /** Refresh port rejected — carries the rejection (errors are data). */\n TokenRefreshFailed: \"token_refresh_failed\",\n\n // --- authed-call: the 401 trigger ----------------------------------------\n /** The 401 the consumer dispatches when a guarded call comes back unauthorized. */\n Unauthorized: \"unauthorized\",\n} as const;\n\n/** The union of every discriminant string in the protocol. */\nexport type MsgTypeValue = (typeof MsgType)[keyof typeof MsgType];\n","/**\n * @packageDocumentation\n * internal/resilience/circuit-breaker — per-target failure tracking as pure state + ops.\n *\n * Same shape as `../../work-queue/ops.ts`, `../rate-limit/`, and\n * `../../idempotency/`: a state type plus pure transition functions.\n * Host-agnostic by construction — no `Date.now()`, no timers, no I/O. The\n * caller injects the clock (`nowMs`) and wires the result into its own reducer\n * / interpret. This keeps the breaker inside TEA's invariant 2 (transitions are\n * pure: same inputs → same outputs, no `Date.now`) so a consumer can fold it\n * through `update` and exercise it with `replay` / the pbt fold without a fake\n * clock.\n *\n * Every op returns a NEW state value and never mutates its input (invariant 1 —\n * state is a value, not a place). `canPass` returns a `[next, allowed]` tuple so\n * the caller branches on the decision while threading the advanced state forward\n * — same convention as `rate-limit`'s `tryConsume` / `record`. `onSuccess` /\n * `onFailure` are the outcome-recording transitions the caller folds in once the\n * guarded call resolves.\n *\n * ## The phase machine\n *\n * A circuit breaker guards a fallible downstream target (an HTTP backend, a DB,\n * a flaky tool call). Instead of hammering a target that is already failing, it\n * trips OPEN after enough failures and fast-fails subsequent calls for a\n * cooldown, then probes with a few trial calls before fully closing again.\n * Three phases, each carrying ONLY its own data so impossible states are\n * unrepresentable (pattern 11):\n *\n * - **closed** — the healthy steady state. Calls pass through. Carries\n * `failures`: the count of *consecutive* failures since the last success.\n * A success resets it to 0; the `failureThreshold`-th failure trips the\n * breaker OPEN. Only `closed` has a failure counter — `open` and\n * `half_open` don't, because in those phases the count is irrelevant\n * (the breaker has already tripped / is already probing).\n *\n * - **open** — the tripped state. All calls fast-fail (no downstream load).\n * Carries `openedAtMs`: the clock reading at which the breaker tripped.\n * `canPass` compares `nowMs - openedAtMs` against `cooldownMs` to decide\n * when to start probing. Only `open` carries a timestamp — neither other\n * phase is timing anything.\n *\n * - **half_open** — the probing state. A limited number of trial calls are\n * allowed through to test whether the target has recovered. Carries\n * `probes`: the count of probes admitted so far this probing round.\n * `canPass` admits while `probes < halfOpenMaxProbes`, then fast-fails the\n * rest (so a slow target can't be flooded by every queued caller at once).\n * A probe success closes the breaker; a probe failure re-opens it (and\n * resets the cooldown clock). Only `half_open` counts in-flight probes.\n *\n * ### Transition table\n *\n * Rows are the current phase; columns are the event. `→` denotes the next\n * phase; `self` means unchanged. `nowMs` is the injected clock.\n *\n * | from \\ event | onSuccess | onFailure | canPass (→ allowed?) |\n * | ------------ | -------------- | -------------------------------------- | ------------------------------------------------------------------------------------ |\n * | closed | closed(0) | failures+1; trip → open(nowMs) at thr. | self → true (always) |\n * | open | self *(¹)* | self | elapsed ≥ cooldown → half_open(1), true; else self → false |\n * | half_open | → closed(0) | → open(nowMs) (probe failed) | probes < max → half_open(probes+1), true; else self → false |\n *\n * *(¹)* `onSuccess` on `open` \"shouldn't happen\": no call was admitted while\n * open, so no success can be reported for one. We leave the state unchanged\n * rather than throw — the breaker is a coordination aid, not a correctness\n * gate, and a spurious success report (e.g. a late-arriving result from before\n * the trip) must not silently un-trip the breaker. `onFailure` on `open` is\n * likewise a no-op: the breaker is already tripped; the `open` clock is anchored\n * at the trip, not bumped by late failures.\n *\n * ### The probe-admission asymmetry\n *\n * Entering `half_open` happens inside `canPass`, not `onSuccess` / `onFailure`,\n * because the cooldown is a *time* condition and only `canPass` reads the clock\n * against `openedAtMs`. The first `canPass` after the cooldown elapses both\n * transitions the phase AND admits the probe (`[half_open(1), true]`) — one\n * caller drives the recovery attempt. Subsequent `canPass` calls in the same\n * round admit up to `halfOpenMaxProbes` total, then fast-fail until a probe\n * resolves and `onSuccess` / `onFailure` moves the phase out of `half_open`.\n *\n * This module is a textbook three-state machine — a clean `/machine-viz` demo.\n *\n * Internal to the package (`src/internal/resilience/`), not a published\n * subpath (#46); same one-shape-per-module rule as `work-queue`, `rate-limit`,\n * and `idempotency`.\n */\n\n/**\n * Circuit-breaker policy — pure configuration, no mutable state. One policy is\n * shared across all the calls guarded by one logical breaker (often a\n * module-scope const). `CircuitState` carries the mutable counts; this carries\n * the thresholds those counts are compared against.\n */\nexport interface CircuitPolicy {\n /**\n * Consecutive failures in `closed` that trip the breaker `open`. The\n * `failureThreshold`-th failure is the one that trips — with a threshold of\n * 5, the breaker survives 4 failures and opens on the 5th.\n */\n readonly failureThreshold: number;\n /**\n * How long the breaker stays `open` before `canPass` starts admitting\n * probes, in milliseconds. Measured from `openedAtMs`; the cutoff is\n * half-open (`elapsed >= cooldownMs` admits), matching `rate-limit` /\n * `idempotency` window edges — a breaker opened at `t` first probes at\n * `t + cooldownMs`.\n */\n readonly cooldownMs: number;\n /**\n * How many probe calls `half_open` admits before fast-failing the rest of\n * the round. Caps the load on a recovering target — a single slow probe\n * can't be joined by every queued caller. The round ends when a probe\n * resolves: success closes the breaker, failure re-opens it.\n */\n readonly halfOpenMaxProbes: number;\n}\n\n/**\n * Sensible defaults: trip after 5 consecutive failures, cool down for 30s,\n * admit a single probe before deciding. Tuned for guarding a network backend;\n * override per call site rather than mutating this shared const.\n */\nexport const defaultCircuitPolicy: CircuitPolicy = {\n failureThreshold: 5,\n cooldownMs: 30_000,\n halfOpenMaxProbes: 1,\n};\n\n/**\n * The breaker's phase. A discriminated union on `phase` so each phase carries\n * ONLY its own data and impossible combinations are unrepresentable (pattern\n * 11): there is no state with both a failure count AND an open timestamp,\n * because such a state is meaningless. `phase` is the discriminant; every field\n * is `readonly` so the whole value is trivially JSON-serializable into a\n * consumer's `Store<S>` and safe to thread through a pure reducer.\n *\n * - `closed` carries `failures` — consecutive failures since last success.\n * - `open` carries `openedAtMs` — clock reading when it tripped.\n * - `half_open` carries `probes` — probes admitted this round.\n */\nexport type CircuitState =\n | { readonly phase: \"closed\"; readonly failures: number }\n | { readonly phase: \"open\"; readonly openedAtMs: number }\n | { readonly phase: \"half_open\"; readonly probes: number };\n\n/** The starting state: closed with zero recorded failures. */\nexport function initCircuit(): CircuitState {\n return { phase: \"closed\", failures: 0 };\n}\n\n/**\n * Record a successful guarded call. PURE — returns a new state; the input is\n * never mutated.\n *\n * - `closed` → reset `failures` to 0 (a success breaks the consecutive run).\n * - `half_open` → the probe succeeded; the target has recovered → `closed`.\n * - `open` → unchanged. A success \"shouldn't happen\" while open (no call\n * was admitted to produce one); a late/spurious success must\n * not silently un-trip the breaker. See module header note ¹.\n */\nexport function onSuccess(\n state: CircuitState,\n _policy: CircuitPolicy,\n): CircuitState {\n switch (state.phase) {\n case \"closed\":\n // Already closed at 0 → return the same shape (cheap; the consumer's\n // store only re-persists on a real change if it dedupes).\n return state.failures === 0 ? state : { phase: \"closed\", failures: 0 };\n case \"half_open\":\n return { phase: \"closed\", failures: 0 };\n case \"open\":\n return state;\n }\n}\n\n/**\n * Record a failed guarded call. PURE — returns a new state; the input is never\n * mutated. `nowMs` is the injected clock, stamped onto the `open` phase when the\n * breaker trips so `canPass` can measure the cooldown later.\n *\n * - `closed` → `failures + 1`; if that reaches `failureThreshold`, trip to\n * `open(nowMs)`. The threshold-th failure is the one that trips.\n * - `half_open` → the probe failed; the target is still unhealthy →\n * `open(nowMs)`, restarting the cooldown clock so a fresh\n * cooldown elapses before the next probe round.\n * - `open` → unchanged. The breaker is already tripped; the `open` clock\n * is anchored at the original trip, not bumped by late\n * failures. See module header note ¹.\n */\nexport function onFailure(\n state: CircuitState,\n policy: CircuitPolicy,\n nowMs: number,\n): CircuitState {\n switch (state.phase) {\n case \"closed\": {\n const failures = state.failures + 1;\n // `>=` not `===`: a threshold of 0 (or any already-exceeded count from a\n // policy change) trips immediately rather than over-counting forever.\n return failures >= policy.failureThreshold\n ? { phase: \"open\", openedAtMs: nowMs }\n : { phase: \"closed\", failures };\n }\n case \"half_open\":\n // A failed probe re-opens and resets the cooldown clock to nowMs.\n return { phase: \"open\", openedAtMs: nowMs };\n case \"open\":\n return state;\n }\n}\n\n/**\n * Decide whether a call may pass, advancing the phase as a side effect of the\n * decision. PURE — returns `[next, allowed]`; the input is never mutated.\n * Branch on the boolean, thread the state forward regardless:\n *\n * const [c1, allowed] = canPass(state.circuit, policy, nowMs);\n * if (!allowed) return [{ ...state, circuit: c1 }, [fastFailCmd]];\n * return [{ ...state, circuit: c1 }, [doGuardedCallCmd]];\n *\n * - `closed` → `[state, true]` — always passes; failures are recorded by\n * `onFailure` once the call resolves, not gated here.\n * - `open` → if `nowMs - openedAtMs >= cooldownMs` the cooldown has\n * elapsed → enter `half_open` and admit this caller as the\n * first probe: `[half_open(1), true]`. Otherwise still cooling\n * down → `[state, false]` (fast-fail, no downstream load).\n * - `half_open` → admit while `probes < halfOpenMaxProbes`, incrementing the\n * count: `[half_open(probes+1), true]`. Once the cap is hit →\n * `[state, false]` until a probe resolves and `onSuccess` /\n * `onFailure` moves the phase out of `half_open`.\n *\n * Entering `half_open` lives here (not in `onSuccess` / `onFailure`) because the\n * cooldown is a time condition and only `canPass` reads `nowMs` against\n * `openedAtMs`. See the module header's probe-admission note.\n */\nexport function canPass(\n state: CircuitState,\n policy: CircuitPolicy,\n nowMs: number,\n): readonly [CircuitState, boolean] {\n switch (state.phase) {\n case \"closed\":\n return [state, true];\n case \"open\": {\n const elapsed = nowMs - state.openedAtMs;\n // Half-open cutoff: elapsed exactly == cooldownMs admits the first probe,\n // matching the >= edge `rate-limit` / `idempotency` use for their windows.\n if (elapsed >= policy.cooldownMs) {\n return [{ phase: \"half_open\", probes: 1 }, true];\n }\n return [state, false];\n }\n case \"half_open\":\n if (state.probes < policy.halfOpenMaxProbes) {\n return [{ phase: \"half_open\", probes: state.probes + 1 }, true];\n }\n return [state, false];\n }\n}\n","/**\n * internal/resilience/rate-limit — two rate limiters as pure state + ops.\n *\n * Same shape as `../../work-queue/ops.ts`: a state type plus pure\n * transition functions. Host-agnostic by construction — no `Date.now()`, no\n * timers, no I/O. The caller injects the clock (`nowMs`) and wires the result\n * into its own reducer / interpret. This keeps the limiters inside TEA's\n * invariant 2 (transitions are pure: same inputs → same outputs, no `Date.now`)\n * so a consumer can fold them through `update` and exercise them with `replay`\n * / the pbt fold without a fake clock.\n *\n * Every op returns a NEW state value and never mutates its input (invariant 1 —\n * state is a value, not a place). The `tryConsume` / `record` ops return a\n * `[next, ok]` tuple so the caller branches on the decision while threading the\n * advanced state forward; `refill` / `remaining` are read-shaped helpers.\n *\n * Two complementary algorithms, picked by the cost the caller wants to pay:\n *\n * - **Token bucket** — O(1) state (four numbers), smooths bursts against a\n * steady refill rate. Allows a burst up to `capacity`, then throttles to\n * `refillPerSec`. Cheapest; the default choice.\n * - **Sliding window log** — O(limit) state (one timestamp per in-window\n * hit), exact \"no more than `limit` events per `windowMs`\". Pay the memory\n * for precise window edges when a token bucket's continuous refill would\n * let through too many at a boundary.\n *\n * Internal to the package (`src/internal/resilience/`), not a published\n * subpath (#46); same one-shape-per-module rule as `work-queue` and `do`.\n */\n\n// ===========================================================================\n// Token bucket\n// ===========================================================================\n\n/**\n * A token bucket: `tokens` of `capacity` available now, replenished at\n * `refillPerSec` tokens per second. `lastRefillMs` is the clock reading at\n * which `tokens` was last computed — `refill` advances it. All four fields are\n * plain numbers so the whole bucket is trivially JSON-serializable into a\n * consumer's `Store<S>`.\n */\nexport interface TokenBucket {\n readonly tokens: number;\n readonly capacity: number;\n readonly refillPerSec: number;\n readonly lastRefillMs: number;\n}\n\n/**\n * Create a full bucket. Starts at `capacity` tokens (the conventional \"a fresh\n * limiter lets the first burst through\" behavior) and stamps `lastRefillMs`\n * with the caller's clock so the first `refill` measures elapsed time from\n * boot, not from epoch 0.\n */\nexport function initBucket(\n capacity: number,\n refillPerSec: number,\n nowMs: number,\n): TokenBucket {\n return {\n tokens: capacity,\n capacity,\n refillPerSec,\n lastRefillMs: nowMs,\n };\n}\n\n/**\n * Add the tokens accrued since `lastRefillMs`, clamped to `capacity`, and\n * advance `lastRefillMs` to `nowMs`. PURE — returns a new bucket; the input is\n * untouched.\n *\n * A `nowMs` at or before `lastRefillMs` (clock not advanced, or skewed\n * backwards) adds a non-positive amount; `Math.max(0, …)` floors the elapsed\n * term so a backwards clock can never *remove* tokens. `lastRefillMs` still\n * advances to `nowMs` so the bucket tracks the latest reading the caller\n * presented — the next forward step measures from there, not from a stale\n * future timestamp.\n */\nexport function refill(bucket: TokenBucket, nowMs: number): TokenBucket {\n const elapsedSec = Math.max(0, nowMs - bucket.lastRefillMs) / 1000;\n const replenished = bucket.tokens + elapsedSec * bucket.refillPerSec;\n return {\n ...bucket,\n tokens: Math.min(bucket.capacity, replenished),\n lastRefillMs: nowMs,\n };\n}\n\n/**\n * Refill against `nowMs`, then attempt to take `n` tokens (default 1).\n *\n * On success returns `[next, true]` with `n` subtracted; on failure returns\n * `[refilled, false]` — the refilled bucket (so the caller keeps the advanced\n * clock + accrued tokens) with no tokens spent. Branch on the boolean, thread\n * the bucket forward regardless:\n *\n * const [b1, ok] = tryConsume(bucket, nowMs);\n * return ok ? [{ ...state, bucket: b1 }, [doWork]] : [{ ...state, bucket: b1 }, []];\n *\n * PURE — input bucket is never mutated.\n */\nexport function tryConsume(\n bucket: TokenBucket,\n nowMs: number,\n n = 1,\n): readonly [TokenBucket, boolean] {\n const refilled = refill(bucket, nowMs);\n if (refilled.tokens >= n) {\n return [{ ...refilled, tokens: refilled.tokens - n }, true];\n }\n return [refilled, false];\n}\n\n// ===========================================================================\n// Sliding window log\n// ===========================================================================\n\n/**\n * A sliding-window log: the timestamps of every hit still inside the trailing\n * `windowMs`, capped at `limit` events per window. `hits` is `readonly` and\n * kept oldest-first (pruning slices the stale prefix off the front, recording\n * appends to the back), so the array is its own sorted index. Exact at the\n * window edge — unlike a token bucket's continuous refill, a hit leaves the\n * count the instant it ages past `windowMs`.\n */\nexport interface SlidingWindow {\n readonly hits: readonly number[];\n readonly windowMs: number;\n readonly limit: number;\n}\n\n/** Create an empty window. No hits recorded yet. */\nexport function initWindow(windowMs: number, limit: number): SlidingWindow {\n return { hits: [], windowMs, limit };\n}\n\n/**\n * The window-edge rule, in one place: keep only the hits still live at `nowMs`.\n * The cutoff is half-open — a hit exactly `windowMs` old is dropped (`> cutoff`,\n * not `>=`), so a hit recorded at `t` no longer counts at `t + windowMs` and the\n * window's capacity fully recovers `windowMs` after the last hit. `record` (the\n * writer) and `remaining` (the read helper) both prune through here so a change\n * to the edge semantics can't leave the reader disagreeing with the writer.\n */\nfunction prune(window: SlidingWindow, nowMs: number): readonly number[] {\n const cutoff = nowMs - window.windowMs;\n return window.hits.filter((t) => t > cutoff);\n}\n\n/**\n * Prune hits older than `nowMs - windowMs`, then record `nowMs` if there is\n * room. Returns `[next, true]` with the hit appended when `hits.length < limit`\n * after pruning, else `[pruned, false]` — the pruned window (capacity recovers\n * as old hits age out) with nothing appended.\n *\n * The cutoff is half-open (see {@link prune}): a hit exactly `windowMs` old is\n * pruned, so a hit recorded at `t` no longer counts at `t + windowMs`. That\n * makes the window's capacity fully recover `windowMs` after the last hit, the\n * behavior tests pin.\n *\n * PURE — input window is never mutated; `hits` is rebuilt by `filter` +\n * spread.\n */\nexport function record(\n window: SlidingWindow,\n nowMs: number,\n): readonly [SlidingWindow, boolean] {\n const pruned = prune(window, nowMs);\n if (pruned.length < window.limit) {\n return [{ ...window, hits: [...pruned, nowMs] }, true];\n }\n return [{ ...window, hits: pruned }, false];\n}\n\n/**\n * How many more hits `record` would accept at `nowMs` without blocking —\n * `limit` minus the live (post-prune) hit count, floored at 0. Read-only: it\n * prunes a local copy to answer but returns no new window. Use it to render a\n * \"N requests remaining\" affordance without committing a hit.\n */\nexport function remaining(window: SlidingWindow, nowMs: number): number {\n const live = prune(window, nowMs).length;\n return Math.max(0, window.limit - live);\n}\n","/**\n * @packageDocumentation\n *\n * Internal to the package (`src/internal/resilience/`, #46). The published\n * `./resilient-call` door is closed; the consumer-facing shape is the\n * higher-order `withResilience(base, config)` wrapper in `../with-resilience`\n * (TEA-idiomatic: it wraps any existing machine instead of forcing a bespoke\n * embedded slice), and this module is its implementation. The APIs are NOT\n * drop-in; migration map, for the in-tree embedded-slice consumers:\n *\n * - `createResilientCall(config, rng)` + hand-wiring `init` / the verbs /\n * `subs` / `handlers` into your machine → `withResilience(base, { target,\n * ...bricks }, rng)`. Nothing is wired by hand anymore: the wrapper\n * intercepts the `target` base Cmd and routes it through the gate.\n * - `ResilientConfig` bricks (`retry` / `circuit` / `rateLimit` / `cache` /\n * `deadline`) → unchanged; `ResilienceConfig` extends the same knob and\n * adds `target` (required), `keyOf?` (per-call key — was `attempt`'s `key`\n * argument), and `at?` (time-as-data reader — REQUIRED with any\n * time-sensitive brick; `withResilience` throws at construction without it).\n * - The slice at your chosen Model field + `liftResilience` → the wrapper\n * owns `model.$resilience`; there is nothing to lift.\n * - Verbs `attempt` / `succeed` / `fail` / `onTimer` → internal to the\n * wrapper; results route as `$resilience:ok` / `$resilience:err` /\n * `$resilience:timer` Msgs through the merged `update` (the old\n * `resilient_run` / `resilient_ok` / `resilient_err` vocabulary is renamed\n * into the `$resilience:` namespace).\n * - `settleFailed` → NO equivalent. It exists for embedded-slice consumers\n * (`authed-call`, `paginated-walk`) that settle a call without touching the\n * breaker; the wrapper exposes no caller-facing settle verb.\n * - `handlers(ports)` / `subs(state)` / the `subscribeDeadline` re-export →\n * handled by the wrapper; run the returned machine like any other.\n *\n * The in-tree modules that embed the slice (`with-resilience` itself, `agent`,\n * `llm-call`, `authed-call`, `reconciler`, `paginated-walk`) import this module\n * directly — that is its role.\n *\n * internal/resilience/resilient-call — the ROOT composition: a single resilience knob\n * that bundles cache → circuit-breaker → rate-limit → exponential-backoff retry\n * (with a deadline-driven retry timer) around any fallible `(input) => Promise`\n * port.\n *\n * This is `examples/resilient-fetch.ts`'s hand-wired `attempt()` generalized:\n *\n * - It is **keyed**. The example tracked one URL at a time; this tracks N\n * concurrent logical calls, each under a string `key`. The cache, the\n * waiting-retry bookkeeping, and the retry timers are all per-key, while the\n * circuit breaker and token bucket are shared (one downstream target, one\n * breaker / one bucket — the example's implicit single-target assumption\n * made explicit).\n * - It is **config-driven**, not hand-wired. You hand `createResilientCall`\n * a `ResilientConfig` and get back the uniform knob contract every L2\n * composition exposes: `init()`, the four verbs (`attempt` / `succeed` /\n * `fail` / `onTimer`), `subs(state)`, and `handlers(ports)`.\n * - Every brick is **optional**. Omit `cache` and the cache gate disappears\n * (`get` is never consulted); omit `circuit` and every call passes the\n * breaker; omit `rateLimit` and the bucket never throttles; omit `retry`\n * and a failure is terminal (no backoff, no timer); omit `deadline` and no\n * overall time budget is armed. \"Omit a brick → omit its gate\" is the\n * whole config story — there are no other modes.\n *\n * Four later compositions (`llm-call`, `paginated-walk`, `authed-call`,\n * `reconciler`) inherit THIS slice + verb shape, so the contract here is\n * load-bearing: the slice is a flat record of brick states, every verb returns\n * `readonly [State, Cmd[]]`, time is always an `at` / `now` parameter, and the\n * RNG used for jitter is injected on the config (never read inside a verb).\n *\n * ## The two non-negotiables (canon)\n *\n * - **Durable** — the slice is a plain-data Model field (brick states are all\n * JSON-serializable), so it survives DO eviction / reload.\n * - **Replayable** — every transition is a verb returning new state + Cmds;\n * `replay` reconstructs it exactly. Nothing here closes over time or RNG.\n *\n * ## Where the clock / RNG live\n *\n * Inside the verbs: nowhere. Time arrives as `at` on `attempt` / `onTimer` and\n * is carried on the result / timer Msgs the consumer dispatches. Jitter RNG is\n * injected once at `createResilientCall(config, rng)` and threaded into\n * `nextDelayMs` at the verb boundary — deterministic in tests, `Math.random`\n * by default. The ONLY clock read is `Date.now()` inside the `handlers` port\n * (the effect boundary), exactly as `resilient-fetch.ts` stamps its result Msgs.\n *\n * That same `at` is what makes a DURATION-bounded retry budget reachable here:\n * `recordFailure` / `shouldRetry` are fed the failure's observation instant,\n * so `config.retry` accepts any `AnyRetryPolicy` — a count, a wall-clock outage\n * budget (`maxElapsedMs`), or explicit `unbounded: true` — with no new argument\n * on any verb and no clock read inside one.\n *\n * ## Typical wiring\n *\n * const rc = createResilientCall<string, Result>({\n * cache: { ttlMs: 60_000 },\n * circuit: { threshold: 5, cooldownMs: 30_000 },\n * rateLimit: { capacity: 10, refillPerSec: 5 },\n * retry: defaultRetryPolicy,\n * deadline: { ms: 5_000 },\n * });\n *\n * // `mountResilientCall` pre-assembles the wiring; the one cell it cannot\n * // write is `attempt`, whose arguments only the consumer's Msg knows. This\n * // knob's `handlers` takes ports, so it is bound before the mount reads it —\n * // `../../jev/ask` and `../../llm-call` expose a nullary `handlers()` and\n * // are passed straight in.\n * const mounted = mountResilientCall({\n * ...rc,\n * handlers: () => rc.handlers({ run: ctx.call }),\n * }, {\n * slice: \"resilience\",\n * attempt: {\n * on: \"fetch\",\n * run: (slice, m: Fetch) => rc.attempt(slice, m.key, m.input, m.at),\n * },\n * onOk: (model, m) => [{ ...model, result: m.result }, []],\n * });\n *\n * // in the machine:\n * init: () => [{ ...mounted.init(), result: null }, []],\n * update: { ...mounted.update },\n * subscriptions: mounted.subscriptions,\n * subscribe: mounted.subscribe,\n * interpret: mounted.interpret,\n *\n * The six verbs stay exported and callable by hand for a consumer that wants a\n * cell the mount cannot express (ADR 0015's escape hatch): `rc.succeed(...)`,\n * `rc.fail(...)`, `rc.onTimer(...)` and `liftResilience` splice exactly as\n * before.\n *\n * ## Naming a knob, when a machine mounts more than one\n *\n * Every knob above speaks `resilient_run` / `resilient_ok` / `resilient_err`,\n * so TWO of them in one machine meet in one `resilient_ok` cell whose `result`\n * is the union of both payloads — discriminated by hand on `key`, which the\n * type checker cannot grade. `config.name` renames the whole family, Cmd and\n * both settle Msgs together:\n *\n * const jev = createResilientCall<JevRequest, JevOk, \"jev\">({ name: \"jev\" });\n * const llm = createResilientCall<LlmCall, LlmOk, \"llm\">({ name: \"llm\" });\n *\n * update: {\n * jev_ok: (s, m) => …, // m.result is JevOk — no `key` switch\n * llm_ok: (s, m) => …, // m.result is LlmOk\n * }\n *\n * The name leads the retry / deadline Sub ids too (`jev:retry:<key>`), because\n * Subs reconcile by id and two knobs would otherwise share one timer per key.\n * `N` is not inferable from `I` / `R`, so an opted-in knob spells all three\n * type arguments; `config.name` is typed at `N`, so value and type cannot\n * drift. Omit `name` and every one of those strings is `resilient*` exactly as\n * it has always been — no existing machine changes.\n *\n * `mountResilientCall` reads the same name off the knob, so a mounted named\n * knob's settle cells are `jev_ok` / `jev_err` too — the mount never spells the\n * `resilient_*` literals, and two named knobs mounted into one machine spread\n * into four distinct cells.\n */\n\nimport { z } from \"zod\";\nimport { liftSlice } from \"../../../compose\";\nimport { Cmd, type CmdOf, type NoCtx, tryInterpret } from \"../../../index\";\nimport type { MsgType } from \"../../../protocol\";\nimport { without } from \"../../../pure/core\";\nimport {\n type AnyRetryPolicy,\n asRng,\n initRetry,\n nextDelayMs,\n type RetryState,\n recordFailure,\n shouldRetry,\n} from \"../../../retry-backoff\";\nimport {\n get as cacheGet,\n set as cacheSet,\n initCache,\n type TtlCache,\n} from \"../cache\";\nimport {\n type CircuitState,\n canPass,\n initCircuit,\n onFailure,\n onSuccess,\n} from \"../circuit-breaker\";\nimport {\n type DeadlineExceeded,\n type DeadlineSub,\n deadlineMsgType,\n deadlineSub,\n subscribeDeadline,\n} from \"../deadline\";\nimport { initBucket, type TokenBucket, tryConsume } from \"../rate-limit\";\n\n// ===========================================================================\n// Config — the knob. Every brick optional; omit a brick → omit its gate.\n// ===========================================================================\n\n/** Circuit-breaker knob — only the two numbers a consumer ever tunes. */\nexport interface CircuitConfig {\n /** Consecutive failures that trip the breaker open. */\n readonly threshold: number;\n /** How long the breaker stays open before admitting a probe, in ms. */\n readonly cooldownMs: number;\n /**\n * Probes admitted in `half_open` before fast-failing the rest of the round.\n * Defaults to 1 (a single probe decides recovery) — matches the circuit-\n * breaker module's `defaultCircuitPolicy`.\n */\n readonly halfOpenMaxProbes?: number;\n}\n\n/** Token-bucket rate-limit knob. */\nexport interface RateLimitConfig {\n /** Burst size — the bucket starts full at `capacity`. */\n readonly capacity: number;\n /** Steady-state refill rate, tokens per second. */\n readonly refillPerSec: number;\n}\n\n/** Per-entry TTL cache knob. */\nexport interface CacheConfig {\n /** How long a cached success stays fresh, in ms. */\n readonly ttlMs: number;\n}\n\n/**\n * Overall deadline knob — a budget of IN-PROCESS time per in-flight call.\n *\n * The budget is charged in elapsed time this process actually observed, not by\n * a position on the host's wall clock. Time in which no process exists — a DO\n * eviction, a crash between attempts, a redeploy — is NOT charged: `resume`\n * re-anchors every live call's charging clock, so downtime lands outside every\n * segment. A timeout therefore means \"the tool took too long\", never \"the host\n * was away too long\" (#144).\n */\nexport interface DeadlineConfig {\n /** Budget of in-process time from the moment a call starts, in ms. */\n readonly ms: number;\n}\n\n// ===========================================================================\n// The Msg-name family — one `name` derives the Cmd and both settle Msgs.\n// ===========================================================================\n\n/**\n * The family every unnamed knob speaks: `resilient_run` / `resilient_ok` /\n * `resilient_err`. Identical to the `MsgType.Resilient*` literals, which stay\n * the vocabulary of every knob that passes no name.\n */\nexport const DEFAULT_RESILIENT_NAME = \"resilient\";\nexport type DefaultResilientName = typeof DEFAULT_RESILIENT_NAME;\n\n// The default family IS the protocol's `MsgType.Resilient*` vocabulary, not a\n// parallel spelling of it. These three lines fail to compile the moment the two\n// drift, which is the only thing keeping \"omit the name and nothing changes\"\n// true for every machine wired before the name existed.\nconst _runIsProtocol: typeof MsgType.ResilientRun =\n `${DEFAULT_RESILIENT_NAME}_run` as const;\nconst _okIsProtocol: typeof MsgType.ResilientOk =\n `${DEFAULT_RESILIENT_NAME}_ok` as const;\nconst _errIsProtocol: typeof MsgType.ResilientErr =\n `${DEFAULT_RESILIENT_NAME}_err` as const;\nvoid [_runIsProtocol, _okIsProtocol, _errIsProtocol];\n\n/** The run Cmd's `type` for the `N` family. */\nexport type ResilientRunType<N extends string> = `${N}_run`;\n/** The success settle Msg's `type` for the `N` family. */\nexport type ResilientOkType<N extends string> = `${N}_ok`;\n/** The failure settle Msg's `type` for the `N` family. */\nexport type ResilientErrType<N extends string> = `${N}_err`;\n\n/**\n * The resilience knob. EVERY field is optional: omit a brick and its gate is\n * skipped entirely (the slice still carries a default brick state so the shape\n * stays uniform across configs, but the gate is never consulted). An empty\n * config `{}` is a valid pass-through — a bare effect with no resilience at all.\n *\n * `N` is the knob's Msg-name family (see {@link ResilientName}); it is carried on\n * the config so the run Cmd and the two settle Msgs are named from ONE place.\n */\nexport interface ResilientConfig<N extends string = DefaultResilientName> {\n /**\n * What this knob's Cmd and settle Msgs are called: `<name>_run`, `<name>_ok`,\n * `<name>_err`. Omit it and the family is `resilient` — `resilient_run` /\n * `resilient_ok` / `resilient_err`, exactly as before this parameter existed.\n *\n * Name a knob when a machine mounts more than one of the resilient family.\n * Two unnamed knobs meet in ONE `resilient_ok` cell whose payload is the union\n * of both results, and the consumer discriminates by hand on `key` — which the\n * type checker cannot see. Under distinct names each knob settles into its own\n * cell, already narrowed to its own payload.\n *\n * The name is a value AND a type: the settle Msg types are generic in `N`, and\n * `N` is not inferable from `I` / `R`, so an opted-in knob spells all three\n * type arguments — `createResilientCall<In, Out, \"jev\">({ name: \"jev\", … })`.\n * The `name` field is typed at `N`, so the two cannot drift apart.\n */\n readonly name?: N;\n /**\n * The backoff brick. Omit and a failure is terminal (no backoff, no timer).\n *\n * Any bound the `../retry-backoff` union admits: a count (`RetryPolicy`), a\n * wall-clock outage budget (`DurationRetryPolicy`), or explicit\n * `unbounded: true`. A duration bound needs no extra wiring: every path that\n * records a failure already holds the instant it was observed as DATA —\n * `fail`'s `msg.at` (stamped at the interpret boundary) and `gate`'s `at`\n * (the caller's `attempt` / the retry timer's `atMs`) — so the streak clock\n * is fed from a Msg, never from a `Date.now()` inside a verb (invariant 2).\n */\n readonly retry?: AnyRetryPolicy;\n readonly circuit?: CircuitConfig;\n readonly rateLimit?: RateLimitConfig;\n readonly cache?: CacheConfig;\n readonly deadline?: DeadlineConfig;\n}\n\n// ===========================================================================\n// Slice — the Model field this knob owns. A flat record of brick states.\n// ===========================================================================\n\n/**\n * What is left of one call's deadline budget, and where the currently open\n * charging segment starts. Plain data, so it persists with the rest of the slice\n * — but the DURABLE fact is `remainingMs`, a duration, never an instant.\n *\n * The accounting has one rule, applied at every transition that carries a clock\n * (`attempt`'s `at`, a settle Msg's `at`, a timer's `atMs`): charge the segment\n * that just closed and open a new one at the same instant —\n * `remainingMs -= at - chargingSinceMs; chargingSinceMs = at`. See {@link charge}.\n *\n * `chargingSinceMs` is an IN-PROCESS anchor, not a persisted deadline. It is\n * meaningful only while the process that wrote it is alive, and `resume` re-bases\n * it on every live call before anything reads it after a reload — which is what\n * keeps downtime out of the budget. Nothing derives a timeout from it across a\n * resume; the only durable answer to \"how much budget is left\" is `remainingMs`.\n *\n * `remainingMs` is `0` when the `deadline` brick is absent, which is also the\n * \"no cap armed\" reading `subs` uses — a call with a real budget always has\n * `remainingMs > 0`, because `gate` settles a call whose budget reached zero\n * rather than letting it enter `running`.\n */\nexport interface CallBudget {\n /** In-process ms left when the open segment started. `0` = no deadline brick. */\n readonly remainingMs: number;\n /** The instant the open segment started, on the clock of the process that opened it. */\n readonly chargingSinceMs: number;\n}\n\n/**\n * Per-key call phase. `key` indexes a logical call; several can be in flight at\n * once (the generalization of the example's single `url`). Discriminated on\n * `phase` so each phase carries only its own data (pattern 11):\n *\n * - `idle` — never attempted, or fully settled and forgotten.\n * - `running` — the effect Cmd is out; awaiting `succeed` / `fail`.\n * Carries the deadline budget ({@link CallBudget}) and the\n * last `input` so a retry can re-issue it.\n * - `waiting_retry` — a transient failure backed off; the retry timer is armed\n * for `retryAtMs`. Carries `input` for the re-attempt, and\n * the same budget — backoff is in-process time, so it is\n * charged like an attempt.\n * - `circuit_open` — the breaker fast-failed this attempt. Terminal for this\n * call until the consumer re-attempts after cooldown.\n * - `succeeded` — settled OK. `result` is the value the port produced.\n * - `failed` — settled Err (out of retries, or no retry brick). `error`\n * carries the last failure.\n */\nexport type CallPhase<I, R> =\n | { readonly phase: \"idle\" }\n | {\n readonly phase: \"running\";\n readonly input: I;\n readonly budget: CallBudget;\n }\n | {\n readonly phase: \"waiting_retry\";\n readonly input: I;\n readonly retryAtMs: number;\n readonly budget: CallBudget;\n }\n | { readonly phase: \"circuit_open\" }\n | { readonly phase: \"succeeded\"; readonly result: R }\n | { readonly phase: \"failed\"; readonly error: unknown };\n\n/**\n * The slice. `circuit` / `bucket` are SHARED across keys (one downstream target\n * → one breaker, one bucket). `retry` and `cache` are PER KEY (each logical call\n * has its own backoff count + cached result), as is the per-call `CallPhase`.\n * Every field is plain data → the whole slice serializes into a `Store<S>`.\n *\n * `retry` / `cache` keep a default brick value even when the corresponding\n * config brick is omitted, so the slice shape is identical regardless of which\n * bricks the consumer enabled — the verbs simply never consult the unused brick.\n */\nexport interface ResilientState<I, R> {\n readonly circuit: CircuitState;\n readonly bucket: TokenBucket;\n /**\n * Per-key backoff counter. Entries minted by `backoff` are `TimedRetryState`s\n * (they carry the streak's `firstFailureAtMs`, since every failure path holds\n * the observation instant); the field is typed at the `RetryState` supertype\n * because a key that has never failed has no streak, and a slice persisted\n * before the origin existed rehydrates without one. Still plain data.\n */\n readonly retry: Readonly<Record<string, RetryState>>;\n readonly cache: TtlCache<R>;\n readonly calls: Readonly<Record<string, CallPhase<I, R>>>;\n}\n\n// ===========================================================================\n// Cmds + Msgs the knob speaks. Generic over the port input `I`.\n// ===========================================================================\n\n/**\n * The one effect this knob emits: \"run the port for `key` with `input`\". The\n * consumer's `handlers(ports)` interprets it; it carries no closure — `input`\n * is plain data (invariant 3).\n */\nexport function runCmdDef<I, R, N extends string = DefaultResilientName>(\n name: N = DEFAULT_RESILIENT_NAME as N,\n) {\n return Cmd.define(`${name}_run` as ResilientRunType<N>, {\n input: z.custom<{ readonly key: string; readonly input: I }>(),\n ok: z.custom<R>(),\n err: [\"port_rejected\", \"deadline_exceeded\"],\n });\n}\nexport type RunCmdDef<\n I,\n R,\n N extends string = DefaultResilientName,\n> = ReturnType<typeof runCmdDef<I, R, N>>;\nexport type RunCmd<I, N extends string = DefaultResilientName> = CmdOf<\n RunCmdDef<I, unknown, N>\n>;\n\n/**\n * Settle Msgs the `handlers` port dispatches back. `at` is stamped at the\n * boundary. Both are generic in the knob's name family `N`, so two knobs named\n * apart land in two `update` cells whose payloads are already narrowed — the\n * `key` switch a single shared cell forces is gone.\n */\nexport type SucceedMsg<R, N extends string = DefaultResilientName> = {\n readonly type: ResilientOkType<N>;\n readonly key: string;\n readonly result: R;\n readonly at: number;\n};\nexport type FailMsg<N extends string = DefaultResilientName> = {\n readonly type: ResilientErrType<N>;\n readonly key: string;\n readonly error: unknown;\n readonly at: number;\n};\n\n/**\n * The deadline Msg tag this knob's timers dispatch, derived from its name the\n * same way `<name>_ok` / `<name>_err` are. The DEFAULT family keeps the bare\n * `\"deadline_exceeded\"` literal — that is the tag every machine wired before\n * the name existed already handles, and `mountResilientCall` still returns a\n * `deadline_exceeded` cell for an unnamed knob.\n */\nexport type ResilientDeadlineType<N extends string = DefaultResilientName> =\n N extends DefaultResilientName ? \"deadline_exceeded\" : `${N}_deadline`;\n\n/**\n * The name the deadline Sub carries for the `N` family — `undefined` for the\n * default family (no name at all, so the bare literal is dispatched), the name\n * itself otherwise. One conditional, so the value and {@link\n * ResilientDeadlineType} can never disagree about which family is unnamed.\n */\nexport type DeadlineNameOf<N extends string = DefaultResilientName> =\n N extends DefaultResilientName ? undefined : N;\n\n/**\n * The retry / deadline timer Msg — a `DeadlineExceeded` whose tag is this\n * knob's ({@link ResilientDeadlineType}), keyed by the call `key` through the\n * Sub `id`. Bare `ResilientTimerMsg` is the default family's, so it is the same\n * `DeadlineExceeded` it has always been.\n */\nexport type ResilientTimerMsg<N extends string = DefaultResilientName> =\n DeadlineExceeded<DeadlineNameOf<N>>;\n\n/**\n * The plain-data error a deadline-failed call settles with. A `{_tag, ...}`\n * sentinel — NEVER a `new Error(...)` — so the slice stays JSON-serializable\n * (Error objects round-trip to `{}` and carry a stack trace, both of which break\n * the slice's durability invariant). `id` / `atMs` echo the timer that fired so\n * a consumer can attribute the failure to its deadline.\n */\nexport type DeadlineExceededError = {\n readonly _tag: \"deadline_exceeded\";\n readonly id: string;\n readonly atMs: number;\n};\n\n/**\n * What `handlers(ports)` returns: the interpret cell for this knob's run Cmd,\n * under that Cmd's own name. A named knob contributes `<name>_run`, so two\n * knobs' handler records merge into one `interpret` without either shadowing\n * the other.\n */\nexport type ResilientHandlers<I, R, N extends string = DefaultResilientName> = {\n readonly [K in ResilientRunType<N>]: (\n cmd: RunCmd<I, N>,\n ctx: NoCtx,\n ) => Promise<SucceedMsg<R, N> | FailMsg<N>>;\n};\n\n/** Ports the consumer supplies to `handlers`. */\nexport interface ResilientPorts<I, R> {\n /** The fallible work this knob wraps. Throws on failure → routed to `fail`. */\n readonly run: (input: I, key: string) => Promise<R>;\n}\n\n// ===========================================================================\n// Internal brick-policy derivation — config → the L1 policy shapes.\n// ===========================================================================\n\n// A circuit policy is only built when the brick is configured; absence is\n// represented as `null` so the gate can short-circuit to \"always pass\".\nfunction circuitPolicy(config: ResilientConfig<string>) {\n if (config.circuit === undefined) return null;\n return {\n failureThreshold: config.circuit.threshold,\n cooldownMs: config.circuit.cooldownMs,\n halfOpenMaxProbes: config.circuit.halfOpenMaxProbes ?? 1,\n };\n}\n\n/**\n * Close the open charging segment at `at` and open the next one there: the ONE\n * place a {@link CallBudget} is debited. Every caller holds `at` as data (a\n * verb's argument, a Msg's stamp), so the budget advances without any verb\n * reading a clock. PURE.\n *\n * A budget with no deadline brick (`remainingMs` 0) is left alone — there is\n * nothing to spend, and debiting it would push it negative and read as \"spent\".\n * `at` before the anchor cannot happen on a monotonic feed, but a clamped charge\n * keeps a skewed one from CREDITING budget back.\n */\nfunction charge(budget: CallBudget, at: number): CallBudget {\n if (budget.remainingMs <= 0) return { ...budget, chargingSinceMs: at };\n const elapsed = Math.max(0, at - budget.chargingSinceMs);\n return { remainingMs: budget.remainingMs - elapsed, chargingSinceMs: at };\n}\n\n// Sub-id families. Each call's retry timer is a deadline keyed by `key`, so a\n// machine running many concurrent calls reconciles each independently. The\n// knob's `name` leads the id for the same reason it leads the Msg types: Subs\n// reconcile by id, so two knobs sharing a key would otherwise share one timer.\n// The default `resilient` name reproduces the ids exactly as they have always\n// read.\nfunction retryTimerId(name: string, key: string): string {\n return `${name}:retry:${key}`;\n}\nfunction deadlineTimerId(name: string, key: string): string {\n return `${name}:deadline:${key}`;\n}\n\n/**\n * The deadline Sub's `name` for a knob's family — the value side of\n * {@link DeadlineNameOf}. The default family maps to `undefined` (no name),\n * which is what keeps an unnamed knob dispatching the bare `deadline_exceeded`\n * literal rather than a `resilient_deadline` nobody is wired for.\n */\nfunction deadlineNameOf<N extends string>(name: N): DeadlineNameOf<N> {\n return (\n name === DEFAULT_RESILIENT_NAME ? undefined : name\n ) as DeadlineNameOf<N>;\n}\n\n// ===========================================================================\n// The knob factory.\n// ===========================================================================\n\n/**\n * Build a resilient-call knob from `config`. `rng` is injected for retry\n * jitter — pass a fixed `() => 0.5` in tests to pin backoff; defaults to\n * `Math.random` (read at the verb boundary, never inside a brick op). It is\n * curried onto the factory rather than threaded through every verb so callers\n * spell the determinism choice once.\n *\n * Returns the uniform L2 knob contract. `I` is the port input type, `R` the\n * port result type. Consumers outside the package reach this through\n * `withResilience` (`../with-resilience`) — see the migration map at the top\n * of this module.\n */\nexport function createResilientCall<\n I,\n R,\n N extends string = DefaultResilientName,\n>(config: ResilientConfig<N>, rng: () => number = Math.random) {\n const name = config.name ?? (DEFAULT_RESILIENT_NAME as N);\n const cPolicy = circuitPolicy(config);\n // Re-affirm the `[0, 1)` contract at the seam where the injected generator\n // feeds the backoff math (brand from `../retry-backoff`). The factory's\n // public param stays a plain `() => number` so transitive callers are\n // unchanged; `asRng` is the single point it's branded for `nextDelayMs`.\n const rngBranded = asRng(rng);\n const runCmd = runCmdDef<I, R, N>(name);\n // The two settle names, derived once from the same `name` the Cmd def is\n // built from — so the Cmd and the Msgs it settles into can never disagree.\n const okType = `${name}_ok` as ResilientOkType<N>;\n const errType = `${name}_err` as ResilientErrType<N>;\n // The name the deadline Sub carries, which is what fixes the Msg tag it\n // dispatches. `undefined` for the DEFAULT family: an unnamed knob must keep\n // dispatching the bare `deadline_exceeded` literal every existing machine is\n // wired against, so the default is not merely spelled the same — it is the\n // absence of a name, exactly as before this parameter existed.\n const deadlineName = deadlineNameOf(name);\n\n /** The starting slice. Bricks not in `config` still get a default value. */\n function init(): ResilientState<I, R> {\n return {\n circuit: initCircuit(),\n // The bucket carries a default value even without the rateLimit brick so\n // the slice shape is uniform, but the rate-limit GATE is skipped entirely\n // when the brick is absent (see `gate`) — the bucket is simply never\n // consulted. A `0/0` placeholder bucket would be touched by `tryConsume`;\n // a `1-cap` default is harmless because the gate never calls it.\n bucket: config.rateLimit\n ? initBucket(\n config.rateLimit.capacity,\n config.rateLimit.refillPerSec,\n 0,\n )\n : initBucket(1, 1, 0),\n retry: {},\n cache: initCache<R>(),\n calls: {},\n };\n }\n\n /** Read this key's retry state, defaulting to a fresh one. */\n function retryOf(s: ResilientState<I, R>, key: string): RetryState {\n return s.retry[key] ?? initRetry();\n }\n\n /** A fresh full budget for a call starting at `at` (`remainingMs` 0 = no cap). */\n function freshBudget(at: number): CallBudget {\n return {\n remainingMs: config.deadline ? config.deadline.ms : 0,\n chargingSinceMs: at,\n };\n }\n\n /**\n * The budget a call already live under `key` carries forward, charged up to\n * `at`; a fresh full budget when the key has no live call. This is what makes a\n * re-attempt share ONE budget with the attempts before it rather than buying a\n * new one — the in-process invariant the deadline brick has always had.\n */\n function budgetFor(\n s: ResilientState<I, R>,\n key: string,\n at: number,\n ): CallBudget {\n const call = s.calls[key];\n if (call?.phase === \"running\" || call?.phase === \"waiting_retry\") {\n return charge(call.budget, at);\n }\n return freshBudget(at);\n }\n\n /**\n * The shared decision: budget → cache → rate-limit → circuit gate, then either\n * emit the effect or schedule a retry. `budget` is threaded so a re-attempt\n * (from `onTimer`) keeps the ORIGINAL overall budget rather than restarting it.\n * PURE — `at` is the only clock; `rng` is the injected jitter source.\n *\n * ## Why the budget is checked BEFORE the effect is emitted\n *\n * The check is step 0 and it settles rather than dispatches. A call whose\n * budget is spent must not reach the port at all: the port is a real side\n * effect, and re-issuing an attempt only to settle `deadline_exceeded` when it\n * returns spends that effect for an answer nobody reads. This is exactly the\n * resume path's shape — a process that comes back to a spent budget settles\n * here, with zero further port calls (#144).\n *\n * Used by both `attempt` (fresh call) and `onTimer` (retry timer fired) so\n * the gate logic lives in exactly one place — the example's shared `attempt`\n * helper, lifted to a keyed knob.\n *\n * ## Why rate-limit is gated BEFORE the circuit probe\n *\n * The circuit-breaker's `canPass` is not a passive read: in `half_open` it\n * *consumes* a probe slot (advancing `probes`), and the consumed slot is only\n * released when a probe RESOLVES via `onSuccess` / `onFailure`. So a probe\n * slot may only be taken when this attempt is actually going to reach the\n * backend (i.e. emit the `resilient_run` Cmd). The rate-limit gate can reject\n * an attempt and return a backoff WITHOUT any Cmd — no backend call, so no\n * settle Msg ever comes back. If the circuit probe were consumed first, that\n * rate-limited attempt would burn the half-open probe budget on a call that\n * never happened, wedging the breaker `half_open` at its probe cap forever\n * (nothing moves it out of `half_open` but a resolved probe). Running the\n * rate-limit gate first means the circuit probe is consumed ONLY on the path\n * that emits the effect.\n */\n function gate(\n s: ResilientState<I, R>,\n key: string,\n input: I,\n at: number,\n budget: CallBudget,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N>[]] {\n // 0) Budget gate. Skipped without the deadline brick (`remainingMs` stays 0\n // and never moves). A spent budget settles here — before the cache read, the\n // token spend and the circuit probe, none of which a dead call should touch.\n if (config.deadline !== undefined && budget.remainingMs <= 0) {\n return [\n setCall(s, key, {\n phase: \"failed\",\n error: {\n _tag: \"deadline_exceeded\",\n id: deadlineTimerId(name, key),\n atMs: at,\n } satisfies DeadlineExceededError,\n }),\n [],\n ];\n }\n\n // 1) Serve from cache if fresh — no effect at all. Skipped when no cache brick.\n if (config.cache !== undefined) {\n const cached = cacheGet(s.cache, key, at);\n if (cached !== undefined) {\n return [setCall(s, key, { phase: \"succeeded\", result: cached }), []];\n }\n }\n\n // 2) Rate-limit gate FIRST — it may reject with no Cmd, so it must run\n // before any circuit probe is consumed (see header note). Skipped entirely\n // when no rateLimit brick — the bucket is never consulted, so the default\n // placeholder bucket stays untouched.\n let bucket = s.bucket;\n if (config.rateLimit !== undefined) {\n const [next, hasToken] = tryConsume(bucket, at);\n bucket = next;\n if (!hasToken) {\n // Rate-limited: treat as a transient failure and back off via retry.\n // The circuit is untouched — no probe is spent on a call that never ran.\n return backoff(\n { ...s, bucket },\n key,\n input,\n \"rate_limited\",\n at,\n budget,\n );\n }\n }\n\n // 3) Circuit-breaker gate. `null` policy → no breaker → always pass. Reached\n // only once a token is secured, so a half-open probe is consumed exclusively\n // on the path that emits the effect below.\n let circuit = s.circuit;\n if (cPolicy !== null) {\n const [next, ok] = canPass(circuit, cPolicy, at);\n circuit = next;\n if (!ok) {\n return [\n { ...setCall(s, key, { phase: \"circuit_open\" }), bucket, circuit },\n [],\n ];\n }\n }\n\n // 4) All gates passed — emit the effect as data.\n return [\n {\n ...setCall(s, key, { phase: \"running\", input, budget }),\n circuit,\n bucket,\n },\n [runCmd({ key, input })],\n ];\n }\n\n /**\n * Back off after a transient failure: record it, and if `retry` permits\n * another attempt, enter `waiting_retry` with the retry timer armed; else\n * settle `failed`. When no `retry` brick is configured the call fails on the\n * first failure (no backoff, no timer). PURE.\n *\n * `at` is both the backoff anchor AND the streak clock: it is passed to\n * `recordFailure` (which starts `firstFailureAtMs` on the streak's first\n * failure and preserves it on every later one) and to `shouldRetry`, so a\n * `DurationRetryPolicy` on `config.retry` is honoured with no extra wiring.\n * A success drops `retry[key]` entirely, which drops the origin with it —\n * only an unbroken run of failures grows toward a duration budget.\n */\n function backoff(\n s: ResilientState<I, R>,\n key: string,\n input: I,\n error: unknown,\n at: number,\n budget: CallBudget,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N>[]] {\n if (config.retry === undefined) {\n return [setCall(s, key, { phase: \"failed\", error }), []];\n }\n const retry = recordFailure(retryOf(s, key), error, at);\n const withRetry = { ...s, retry: { ...s.retry, [key]: retry } };\n if (!shouldRetry(retry, config.retry, at)) {\n return [setCall(withRetry, key, { phase: \"failed\", error }), []];\n }\n const retryAtMs = at + nextDelayMs(retry, config.retry, rngBranded);\n return [\n setCall(withRetry, key, {\n phase: \"waiting_retry\",\n input,\n retryAtMs,\n budget,\n }),\n [],\n ];\n }\n\n // Set the phase for one key, leaving every other field untouched.\n function setCall(\n s: ResilientState<I, R>,\n key: string,\n phase: CallPhase<I, R>,\n ): ResilientState<I, R> {\n return { ...s, calls: { ...s.calls, [key]: phase } };\n }\n\n // === Verb: attempt =======================================================\n\n /**\n * Start (or restart) the call for `key` with `input` at time `at`. Runs the\n * cache → circuit → rate-limit gate and either emits the `resilient_run`\n * effect, schedules a retry, fast-fails (circuit open), or serves the cache.\n * PURE.\n *\n * A key already live keeps the budget it is under (charged up to `at`) rather\n * than being handed a fresh one, so re-issuing an in-flight call — the boot\n * path's move — cannot silently extend its deadline. Only a key with no live\n * call starts a full budget.\n */\n function attempt(\n s: ResilientState<I, R>,\n key: string,\n input: I,\n at: number,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N>[]] {\n return gate(s, key, input, at, budgetFor(s, key, at));\n }\n\n // === Verb: resume ========================================================\n\n /**\n * Re-anchor every live call's charging clock to `at`: the verb a host calls\n * once on the boot path, before any Sub is armed or any attempt re-issued.\n *\n * This is what keeps DOWNTIME out of the budget. `chargingSinceMs` is an\n * instant on the clock of the process that wrote it; after an eviction, a crash\n * or a redeploy, the gap between it and now is time in which no attempt ran and\n * no port was called, so charging it would time a call out on the host's\n * absence rather than on the tool's slowness. `remainingMs` — the durable half\n * of the budget — is left exactly as the last live transition set it. PURE.\n */\n function resume(s: ResilientState<I, R>, at: number): ResilientState<I, R> {\n const calls: Record<string, CallPhase<I, R>> = { ...s.calls };\n for (const [key, call] of Object.entries(calls)) {\n if (call.phase !== \"running\" && call.phase !== \"waiting_retry\") continue;\n calls[key] = {\n ...call,\n budget: { ...call.budget, chargingSinceMs: at },\n };\n }\n return { ...s, calls };\n }\n\n // === Verb: succeed =======================================================\n\n /**\n * Record a success for `key`: close the breaker, fill the cache (if a cache\n * brick exists), reset this key's retry count, and settle `succeeded`. PURE —\n * `msg.at` is the cache write clock.\n */\n function succeed(\n s: ResilientState<I, R>,\n key: string,\n msg: SucceedMsg<R, N>,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N>[]] {\n const circuit =\n cPolicy !== null ? onSuccess(s.circuit, cPolicy) : s.circuit;\n const cache =\n config.cache !== undefined\n ? cacheSet(s.cache, key, msg.result, msg.at, config.cache.ttlMs)\n : s.cache;\n // Drop this key's retry counter — a success ends the retry run.\n const retry = without(s.retry, key);\n return [\n {\n ...setCall(s, key, { phase: \"succeeded\", result: msg.result }),\n circuit,\n cache,\n retry,\n },\n [],\n ];\n }\n\n // === Verb: fail ==========================================================\n\n /**\n * Record a failure for `key`: trip the breaker (it may open), then back off —\n * schedule a retry if `retry` permits, else settle `failed`. PURE — `msg.at`\n * stamps the breaker trip + the retry delay base. Re-issues from the call's\n * remembered `input` and carries the original budget forward, charged up to\n * `msg.at` — the attempt that just failed spent in-process time, and a retry\n * ladder shares ONE budget across its attempts rather than getting a fresh one\n * per attempt.\n */\n function fail(\n s: ResilientState<I, R>,\n key: string,\n msg: FailMsg<N>,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N>[]] {\n const circuit =\n cPolicy !== null ? onFailure(s.circuit, cPolicy, msg.at) : s.circuit;\n const withCircuit = { ...s, circuit };\n const call = s.calls[key];\n const input = call?.phase === \"running\" ? call.input : undefined;\n const budget = budgetFor(s, key, msg.at);\n // No remembered input (e.g. a stray fail for a key not running) → just\n // settle failed after tripping the breaker; nothing to re-issue.\n if (input === undefined) {\n return [\n setCall(withCircuit, key, { phase: \"failed\", error: msg.error }),\n [],\n ];\n }\n return backoff(withCircuit, key, input, msg.error, msg.at, budget);\n }\n\n // === Verb: settleFailed ==================================================\n\n /**\n * Settle `key` to terminal `failed` with `error` WITHOUT touching the circuit\n * breaker or this key's retry counter. PURE.\n *\n * This is the verb for a failure that is NOT a downstream-health signal: the\n * call must end now, but the breaker must not trip and the backoff run must\n * not advance. `fail` is the opposite — it records the failure against the\n * breaker (it may open) and feeds the retry policy (it may back off). Use\n * `settleFailed` when the *reason* the call cannot proceed has nothing to do\n * with downstream health:\n *\n * - `authed-call` settles a 401 it cannot fix (e.g. the refresh budget is\n * spent): a bad token is the caller's problem, not the backend's —\n * tripping the breaker on it would punish a healthy target, and backing\n * off would just retry a request that will 401 again.\n * - `paginated-walk` settles a terminal walk error (e.g. a malformed page\n * the consumer rejects) that should stop the walk without poisoning the\n * shared breaker the next page fetch passes through.\n *\n * Because it leaves `circuit` and `retry[key]` untouched, the breaker keeps\n * its health view of the actual backend and a later `attempt` for this key\n * starts a fresh retry run. Both sibling knobs previously hand-rolled this by\n * splicing `calls` directly; this verb gives them one named, tested entry\n * point so the slice's settle invariants live in exactly one place.\n */\n function settleFailed(\n s: ResilientState<I, R>,\n key: string,\n error: unknown,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N>[]] {\n return [setCall(s, key, { phase: \"failed\", error }), []];\n }\n\n // === Verb: onTimer =======================================================\n\n /**\n * A timer fired for some key. Two kinds, disambiguated by the Sub id:\n *\n * - retry timer → re-run the gate for that key's remembered input,\n * re-checking the circuit + bucket at THIS time.\n * - deadline timer → the overall budget elapsed → settle `failed` with a\n * deadline error, no matter the current phase.\n *\n * A timer for a key no longer `waiting_retry` (retry) / no longer in flight\n * (deadline) is a no-op — the reconcile pass races the result; the verb must\n * tolerate a stale fire. PURE.\n */\n function onTimer(\n s: ResilientState<I, R>,\n msg: ResilientTimerMsg,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N>[]] {\n for (const [key, call] of Object.entries(s.calls)) {\n if (msg.id === retryTimerId(name, key)) {\n if (call.phase !== \"waiting_retry\") return [s, []];\n // The backoff wait was in-process time, so it is charged before the gate\n // reads the budget — and the gate settles rather than dispatching when\n // that leaves nothing, which is how a resumed ladder ends without one\n // more port call.\n return gate(\n s,\n key,\n call.input,\n msg.atMs,\n charge(call.budget, msg.atMs),\n );\n }\n if (msg.id === deadlineTimerId(name, key)) {\n // Deadline only fires for a still-active call. A settled call has no\n // armed deadline Sub, but tolerate a stale fire defensively.\n if (call.phase !== \"running\" && call.phase !== \"waiting_retry\")\n return [s, []];\n // Plain-data sentinel, NOT a `new Error(...)`: an Error object is not\n // JSON-serializable (it round-trips to `{}`) and captures a stack trace,\n // both of which break the slice's durability invariant once it is\n // persisted into a `Store<S>` and reloaded. A `{_tag, ...}` record keeps\n // the slice round-trip-equal under JSON.parse(JSON.stringify(...)).\n return [\n setCall(s, key, {\n phase: \"failed\",\n error: {\n _tag: \"deadline_exceeded\",\n id: msg.id,\n atMs: msg.atMs,\n } satisfies DeadlineExceededError,\n }),\n [],\n ];\n }\n }\n return [s, []];\n }\n\n // === Subs ================================================================\n\n /**\n * Pre-wired subscriptions: a retry timer for every `waiting_retry` call, and\n * (when the `deadline` brick is configured) an overall deadline timer for\n * every still-active call. Both are `DeadlineSub`s reconciled by id, so a\n * phase change cancels the matching timer automatically — no manual\n * `clearTimeout`. Wire `subscribe: { deadline: subscribeDeadline }`.\n */\n function subs(\n s: ResilientState<I, R>,\n ): readonly DeadlineSub<DeadlineNameOf<N>>[] {\n const out: DeadlineSub<DeadlineNameOf<N>>[] = [];\n for (const [key, call] of Object.entries(s.calls)) {\n if (call.phase === \"waiting_retry\") {\n out.push(\n deadlineSub(retryTimerId(name, key), call.retryAtMs, {\n name: deadlineName,\n }),\n );\n }\n if (\n config.deadline !== undefined &&\n (call.phase === \"running\" || call.phase === \"waiting_retry\") &&\n call.budget.remainingMs > 0\n ) {\n // The absolute instant the timer arms at is DERIVED here, from the open\n // segment's anchor plus what is left — it is never persisted, so a slice\n // that came back from storage arms off the anchor `resume` just re-based\n // rather than off a stamp the downtime ran past.\n out.push(\n deadlineSub(\n deadlineTimerId(name, key),\n call.budget.chargingSinceMs + call.budget.remainingMs,\n { name: deadlineName },\n ),\n );\n }\n }\n return out;\n }\n\n // === Handlers ============================================================\n\n /**\n * Pre-wired interpret handler for `resilient_run`. Wraps the consumer's\n * `run` port via `tryInterpret` (Railway): success → `resilient_ok`, failure\n * → `resilient_err`, each stamped with `Date.now()` at the effect boundary —\n * the ONE permitted clock read (interpret is impure; the reducer never reads\n * the clock). Assign to the machine's `interpret`:\n *\n * interpret: rc.handlers({ run: (input, key) => ctx.callBackend(input) })\n */\n function handlers(ports: ResilientPorts<I, R>): ResilientHandlers<I, R, N> {\n const handle = tryInterpret<\n RunCmd<I, N>,\n R,\n SucceedMsg<R, N> | FailMsg<N>,\n // The work fn reads nothing from ctx — it forwards `cmd.input` to the\n // consumer-supplied `run` port. `NoCtx` (not `unknown`) marks this as a\n // DELIBERATE context-free seam, so callers see intent, not looseness.\n NoCtx\n >(\n (cmd) => ports.run(cmd.input, cmd.key),\n (result, cmd): SucceedMsg<R, N> => ({\n type: okType,\n key: cmd.key,\n result,\n at: Date.now(),\n }),\n (error, cmd): FailMsg<N> => ({\n type: errType,\n key: cmd.key,\n error,\n at: Date.now(),\n }),\n );\n // The key is `${name}_run`, a template-literal type TS cannot see through\n // in an object literal; the mapped return type above is the declaration\n // that carries it to the caller.\n return { [runCmd.cmdType]: handle } as ResilientHandlers<I, R, N>;\n }\n\n return {\n // The Msg-name family this knob speaks, as a VALUE typed at `N`. `mount`\n // keys its settle cells off this rather than off the `resilient_*`\n // literals, so a named knob mounts into its own cells (#229) and the Cmd,\n // the Msgs, the Sub ids and the mounted cells all derive from one name.\n name,\n init,\n attempt,\n resume,\n succeed,\n fail,\n settleFailed,\n onTimer,\n subs,\n handlers,\n };\n}\n\n/**\n * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the\n * slice lives at `state.resilience`. A convenience for the common single-slice\n * host; consumers with a differently-named field spread by hand. Pure — a thin\n * record rebuild, no clock / RNG. Under `withResilience` the wrapper owns\n * `model.$resilience`, so there is nothing to lift; this is for the embedded\n * slice consumers only.\n *\n * The record rebuild itself is `liftSlice` from the root door (#231) — this\n * stays as the named, pre-keyed convenience for the `state.resilience` field,\n * unchanged in name, signature and subpath.\n */\nexport function liftResilience<\n S extends { resilience: ResilientState<I, R> },\n I,\n R,\n C extends Cmd,\n>(\n state: S,\n result: readonly [ResilientState<I, R>, readonly C[]],\n): readonly [S, readonly C[]] {\n return liftSlice(\"resilience\", state, result);\n}\n\n// ===========================================================================\n// mount — the eight hand-spliced wiring points, pre-assembled.\n// ===========================================================================\n\n/** What every verb of a knob in this family hands back. */\nexport type Settle<I, R> = readonly [\n ResilientState<I, R>,\n readonly RunCmd<I>[],\n];\n\n/**\n * The part of a resilient-call knob {@link mountResilientCall} needs. This knob\n * satisfies it, and so does every knob that delegates these verbs to it —\n * `internal/jev/ask` and `internal/llm-call` both do, which is why the mount is\n * written against the shape rather than against either door.\n *\n * `OkMsg` / `ErrMsg` are parameters rather than {@link SucceedMsg} /\n * {@link FailMsg} because an inheriting knob narrows them: jev-ask's `fail`\n * takes a `JevFailMsg` whose `error` is a typed `JevAskErr`, and a mount that\n * fixed the supertype would hand that verb a widened Msg.\n */\nexport interface MountableKnob<\n I,\n R,\n OkMsg,\n ErrMsg,\n Handlers,\n N extends string = DefaultResilientName,\n> {\n /**\n * The Msg-name family this knob settles into — `<name>_ok` / `<name>_err`\n * (#229). The mount reads it rather than assuming `resilient_*`, so a named\n * knob mounts into the cells it actually emits; an unnamed one is\n * `resilient`, so nothing a machine already spread changes.\n */\n readonly name: N;\n init(): ResilientState<I, R>;\n succeed(s: ResilientState<I, R>, key: string, msg: OkMsg): Settle<I, R>;\n fail(s: ResilientState<I, R>, key: string, msg: ErrMsg): Settle<I, R>;\n onTimer(s: ResilientState<I, R>, msg: ResilientTimerMsg<N>): Settle<I, R>;\n subs(s: ResilientState<I, R>): readonly DeadlineSub<DeadlineNameOf<N>>[];\n handlers(): Handlers;\n}\n\n/**\n * The consumer's half of a settle cell: fold the settled answer into the\n * machine's own Model.\n *\n * It is handed the Model the inherited verb ALREADY settled — the slice at\n * `slice` is the post-`succeed` / post-`fail` one — so the ordering that wedges\n * a call at `running` is not something this callback can express. It returns\n * the repo's universal cell shape so a fold that needs to chain an effect\n * (book the answer, then write it somewhere) returns that Cmd like any other\n * reducer cell would.\n */\nexport type SettleFold<Model, M, C extends Cmd> = (\n model: Model,\n msg: M,\n) => readonly [Model, readonly C[]];\n\n/** One cell of the update fragment {@link mountResilientCall} returns. */\nexport type MountedCell<Model, M, I, C extends Cmd> = (\n model: Model,\n msg: M,\n) => readonly [Model, readonly (RunCmd<I> | C)[]];\n\n/**\n * What to mount, and where. `slice` names the Model field the knob's state\n * lives on — a plain, readable field, per\n * [ADR 0015](../../../../.decisions/0015-hide-the-wiring-never-the-state.md):\n * the mount absorbs the assembly and hides none of the durable state.\n */\nexport interface MountConfig<\n Model,\n Slice extends string,\n I,\n R,\n AttemptType extends string,\n AttemptMsg,\n OkMsg,\n ErrMsg,\n C extends Cmd,\n N extends string = DefaultResilientName,\n> {\n /** The Model field carrying the knob's slice. */\n readonly slice: Slice;\n /**\n * The cell that starts a call. Its shape is the one wiring point the mount\n * cannot supply: each door's `attempt` takes its own arguments (jev-ask reads\n * a key, a state and an instant; llm-call reads a request), and only the\n * consumer knows which Msg field carries each. `run` is that one line.\n */\n readonly attempt: {\n /** The Msg type that starts a call — the key the cell lands on. */\n readonly on: AttemptType;\n readonly run: (\n slice: ResilientState<I, R>,\n msg: AttemptMsg,\n ) => Settle<I, R>;\n };\n /** Fold a settled success into the Model. Omit and only the slice advances. */\n readonly onOk?: SettleFold<Model, OkMsg, C>;\n /** Fold a settled failure into the Model. Omit and only the slice advances. */\n readonly onErr?: SettleFold<Model, ErrMsg, C>;\n /**\n * Fold a call the TIMER settled into the Model. This is the third failure\n * class, and it never reaches {@link MountConfig.onErr}: a deadline fire\n * settles `failed` inside the slice and emits no settle Msg, so without this\n * callback a call that dies on its budget advances the slice and folds\n * nothing — the shape that used to be a documented caveat.\n *\n * It runs once per call the knob's deadline cell moved INTO `failed`:\n * the deadline fire itself, and the resumed retry whose gate found the\n * budget spent. A plain backoff tick, a stale fire and an already-`failed`\n * call fold nothing. `error` is the slice's own settled error — a\n * {@link DeadlineExceededError} on the deadline path.\n *\n * Omit and only the slice advances, exactly as the other two do.\n */\n readonly onDeadline?: SettleFold<Model, DeadlineSettled<N>, C>;\n}\n\n/**\n * What {@link MountConfig.onDeadline} is handed: the one call the timer cell\n * just settled `failed`, named by its `key`, carrying the error the slice\n * settled with and the timer Msg that produced it. It is not a Msg the reducer\n * ever sees — no settle Msg exists for this failure class, which is the whole\n * reason the callback is here.\n */\nexport interface DeadlineSettled<N extends string = DefaultResilientName> {\n /** The call key that settled. */\n readonly key: string;\n /** The error now on the slice — a {@link DeadlineExceededError} on the deadline path. */\n readonly error: unknown;\n /**\n * The timer Msg whose fire settled it — this knob's own tag, so a fold on a\n * knob named `jev` is handed a `jev_deadline` and one on an unnamed knob a\n * `deadline_exceeded`.\n */\n readonly msg: ResilientTimerMsg<N>;\n}\n\n/**\n * The four fragments a consumer spreads into `defineMachine`. Together with\n * `init` they are the eight wiring points; none of them is optional at the type\n * level, so a consumer that mounts cannot omit `subscribe` (a backed-off retry\n * that never fires) or re-implement `interpret` as a dispatching handler.\n */\nexport interface MountedResilientCall<\n Model,\n Slice extends string,\n I,\n R,\n AttemptType extends string,\n AttemptMsg,\n OkMsg,\n ErrMsg,\n C extends Cmd,\n Handlers,\n N extends string = DefaultResilientName,\n> {\n /** The starting slice under its field name — spread into the machine's `init`. */\n init(): { readonly [K in Slice]: ResilientState<I, R> };\n /**\n * The three settle cells plus the attempt cell, to spread into `update`.\n *\n * The two settle keys are the knob's OWN Msg names (#229), so a knob built as\n * `name: \"jev\"` mounts into `jev_ok` / `jev_err` and two named knobs in one\n * machine spread into four distinct cells instead of colliding on one. An\n * unnamed knob is `resilient`, so the keys read `resilient_ok` /\n * `resilient_err` exactly as they always have.\n *\n * The deadline cell is keyed the same way (#238). A knob's deadline Sub\n * carries its name, so a knob built as `name: \"jev\"` dispatches\n * `jev_deadline` and mounts into a `jev_deadline` cell; an unnamed knob still\n * dispatches and mounts `deadline_exceeded`. Before that, both mounts wrote\n * the one unqualified `deadline_exceeded` key and the last spread silently\n * dropped the other knob's deadline fold. The cell folds through\n * {@link MountConfig.onDeadline}, since a call the timer settles emits no\n * settle Msg and so reaches no `onErr`.\n */\n readonly update: Readonly<\n Record<AttemptType, MountedCell<Model, AttemptMsg, I, C>>\n > & {\n readonly [K in ResilientOkType<N>]: MountedCell<Model, OkMsg, I, C>;\n } & {\n readonly [K in ResilientErrType<N>]: MountedCell<Model, ErrMsg, I, C>;\n } & {\n readonly [K in ResilientDeadlineType<N>]: MountedCell<\n Model,\n ResilientTimerMsg<N>,\n I,\n C\n >;\n };\n subscriptions(model: Model): readonly DeadlineSub<DeadlineNameOf<N>>[];\n readonly subscribe: { readonly deadline: typeof subscribeDeadline };\n readonly interpret: Handlers;\n}\n\n/**\n * Pre-assemble a resilient-call knob into the fragments a machine definition\n * spreads, so mounting one is a spread instead of eight hand-spliced points.\n *\n * The three points that used to fail only at runtime are gone at the type\n * level rather than documented:\n *\n * - The settle cells run the inherited `succeed` / `fail` verb and hand the\n * already-settled Model to {@link SettleFold}. There is no cell for a\n * consumer to write in the wrong order.\n * - `interpret` is `knob.handlers()` — the form that RETURNS the settle Msg\n * so it re-enters the reducer. A consumer that spreads the fragment cannot\n * substitute a dispatching handler for it.\n * - `subscribe` carries `subscribeDeadline`, so the retry timer is armed by\n * construction rather than by remembering.\n *\n * A deadline-exceeded call settles inside the slice and emits no settle Msg, so\n * it reaches no `onErr`. {@link MountConfig.onDeadline} is that failure class's\n * fold — omit it and the slice still advances, exactly as omitting `onErr`\n * does.\n *\n * Nothing is taken away. The slice stays a plain field at `slice` that the\n * consumer reads, `replay` sees and the journal prints, and every verb the\n * fragments call is still exported and callable by hand — a consumer that\n * wants a settle cell this shape cannot express writes that one cell itself and\n * spreads the rest. PURE: a record of closures over `knob` and `config`, no\n * clock and no RNG.\n */\nexport function mountResilientCall<\n Slice extends string,\n I,\n R,\n Model extends { readonly [K in Slice]: ResilientState<I, R> },\n AttemptType extends string,\n AttemptMsg,\n OkMsg extends { readonly key: string },\n ErrMsg extends { readonly key: string },\n Handlers,\n C extends Cmd = never,\n N extends string = DefaultResilientName,\n>(\n knob: MountableKnob<I, R, OkMsg, ErrMsg, Handlers, N>,\n config: MountConfig<\n Model,\n Slice,\n I,\n R,\n AttemptType,\n AttemptMsg,\n OkMsg,\n ErrMsg,\n C,\n N\n >,\n): MountedResilientCall<\n Model,\n Slice,\n I,\n R,\n AttemptType,\n AttemptMsg,\n OkMsg,\n ErrMsg,\n C,\n Handlers,\n N\n> {\n const { slice, attempt, onOk, onErr, onDeadline } = config;\n\n // A computed key of a generic literal type widens to a string index\n // signature, which is the one place this file asserts: the assertion says\n // only what `Slice extends string` already pins.\n function put(model: Model, next: ResilientState<I, R>): Model {\n return {\n ...model,\n ...({ [slice]: next } as { readonly [K in Slice]: ResilientState<I, R> }),\n };\n }\n\n // The settle shape both `resilient_ok` and `resilient_err` have: inherited\n // verb, then the consumer's fold over the Model it settled.\n function settle<M extends { readonly key: string }>(\n verb: (s: ResilientState<I, R>, key: string, msg: M) => Settle<I, R>,\n fold: SettleFold<Model, M, C> | undefined,\n ): MountedCell<Model, M, I, C> {\n return (model, msg) => {\n const [next, cmds] = verb(model[slice], msg.key, msg);\n const settled = put(model, next);\n if (fold === undefined) return [settled, cmds];\n const [folded, extra] = fold(settled, msg);\n return [folded, [...cmds, ...extra]];\n };\n }\n\n const update = {\n [attempt.on]: (model: Model, msg: AttemptMsg) => {\n const [next, cmds] = attempt.run(model[slice], msg);\n return [put(model, next), cmds] as const;\n },\n // Keyed off the knob's own name, not the `resilient_*` literals: a knob\n // built with `name: \"jev\"` emits `jev_ok` / `jev_err`, and a mount that\n // spelled the literals would spread cells nothing ever dispatches to.\n [`${knob.name}_ok`]: settle<OkMsg>(\n (s, key, msg) => knob.succeed(s, key, msg),\n onOk,\n ),\n [`${knob.name}_err`]: settle<ErrMsg>(\n (s, key, msg) => knob.fail(s, key, msg),\n onErr,\n ),\n // The one settle path that carries no settle Msg: `onTimer` writes\n // `failed` straight into the slice, so a mounted `onErr` never sees it. The\n // cell reads the transition off the two slices instead of inventing a Msg —\n // whichever key moved INTO `failed` is the call that just died.\n //\n // Keyed off the knob's name for the same reason the two settle cells are\n // (#238): the knob's deadline Sub dispatches `<name>_deadline`, so a cell\n // spelling the bare literal would be one two named knobs both claim — and\n // the second spread into `defineMachine` would silently win.\n [deadlineMsgType(deadlineNameOf(knob.name))]: (\n model: Model,\n msg: ResilientTimerMsg<N>,\n ) => {\n const before = model[slice];\n const [next, cmds] = knob.onTimer(before, msg);\n const advanced = put(model, next);\n if (onDeadline === undefined) return [advanced, cmds] as const;\n let folded = advanced;\n const extra: C[] = [];\n for (const [key, call] of Object.entries(next.calls)) {\n if (call.phase !== \"failed\") continue;\n if (before.calls[key]?.phase === \"failed\") continue;\n const [m, c] = onDeadline(folded, { key, error: call.error, msg });\n folded = m;\n extra.push(...c);\n }\n return [folded, [...cmds, ...extra]] as const;\n },\n } as MountedResilientCall<\n Model,\n Slice,\n I,\n R,\n AttemptType,\n AttemptMsg,\n OkMsg,\n ErrMsg,\n C,\n Handlers,\n N\n >[\"update\"];\n\n return {\n init: () =>\n ({ [slice]: knob.init() }) as {\n readonly [K in Slice]: ResilientState<I, R>;\n },\n update,\n subscriptions: (model) => knob.subs(model[slice]),\n subscribe: { deadline: subscribeDeadline },\n interpret: knob.handlers(),\n };\n}\n\n/**\n * Re-export the deadline Sub primitives so consumers (and tests) wire one\n * import: `subscribeDeadline` is the `subscribe` cell, `deadlineSub` builds the\n * Sub literal this knob's `subs` emits.\n */\nexport { subscribeDeadline, deadlineSub };\nexport type { DeadlineSub, DeadlineExceeded };\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Cmd, tryInterpret } from './chunk-
|
|
1
|
+
import { Cmd, tryInterpret } from './chunk-66PY5WYF.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
|
|
4
4
|
var DEFAULT_SNAPSHOT_KEY = "@@snapshot";
|
|
@@ -93,5 +93,5 @@ function createSnapshot(config) {
|
|
|
93
93
|
}
|
|
94
94
|
|
|
95
95
|
export { createSnapshot, snapshotFailed, snapshotLoad, snapshotLoadFailed, snapshotLoaded, snapshotSaved, snapshotWriteDef };
|
|
96
|
-
//# sourceMappingURL=chunk-
|
|
97
|
-
//# sourceMappingURL=chunk-
|
|
96
|
+
//# sourceMappingURL=chunk-L3TND7LA.js.map
|
|
97
|
+
//# sourceMappingURL=chunk-L3TND7LA.js.map
|