@demlik/tea 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +30 -7
  2. package/dist/agent/index.d.ts +49 -37
  3. package/dist/agent/index.js +12 -8
  4. package/dist/chunk-4LPY67E4.js +18 -0
  5. package/dist/chunk-4LPY67E4.js.map +1 -0
  6. package/dist/chunk-5XU6ZJO2.js +533 -0
  7. package/dist/chunk-5XU6ZJO2.js.map +1 -0
  8. package/dist/{chunk-AYS5N6WY.js → chunk-6NG4V5SB.js} +62 -172
  9. package/dist/chunk-6NG4V5SB.js.map +1 -0
  10. package/dist/{chunk-3B5X7SBB.js → chunk-7MGXQZPW.js} +11 -9
  11. package/dist/chunk-7MGXQZPW.js.map +1 -0
  12. package/dist/{chunk-V46HSVCK.js → chunk-BCTEOVOU.js} +3 -3
  13. package/dist/{chunk-V46HSVCK.js.map → chunk-BCTEOVOU.js.map} +1 -1
  14. package/dist/chunk-CH5KTOEZ.js +710 -0
  15. package/dist/chunk-CH5KTOEZ.js.map +1 -0
  16. package/dist/chunk-CIHSHLQX.js +64 -0
  17. package/dist/chunk-CIHSHLQX.js.map +1 -0
  18. package/dist/{chunk-TCLBCERH.js → chunk-EHUDXAKC.js} +238 -212
  19. package/dist/chunk-EHUDXAKC.js.map +1 -0
  20. package/dist/chunk-GOX2CYIM.js +380 -0
  21. package/dist/chunk-GOX2CYIM.js.map +1 -0
  22. package/dist/{chunk-22POWGFA.js → chunk-IVJP3GKJ.js} +46 -20
  23. package/dist/chunk-IVJP3GKJ.js.map +1 -0
  24. package/dist/{chunk-QPEVCJ5Q.js → chunk-MVZS5FDM.js} +13 -6
  25. package/dist/chunk-MVZS5FDM.js.map +1 -0
  26. package/dist/{chunk-VTQI2NHP.js → chunk-MYNLY3HP.js} +9 -8
  27. package/dist/chunk-MYNLY3HP.js.map +1 -0
  28. package/dist/{chunk-Q5CQTBFA.js → chunk-NSIAORRY.js} +20 -30
  29. package/dist/chunk-NSIAORRY.js.map +1 -0
  30. package/dist/{chunk-MYXFNWAJ.js → chunk-QNGYQMZB.js} +4 -4
  31. package/dist/chunk-QNGYQMZB.js.map +1 -0
  32. package/dist/chunk-WT5PBPLB.js +98 -0
  33. package/dist/chunk-WT5PBPLB.js.map +1 -0
  34. package/dist/{core-DnzqWy6u.d.ts → core-BbgtiXdg.d.ts} +231 -139
  35. package/dist/do/index.d.ts +37 -33
  36. package/dist/do/index.js +21 -14
  37. package/dist/do/index.js.map +1 -1
  38. package/dist/{durable-effects-CWzA-o2B.d.ts → durable-effects-7MTK_jnj.d.ts} +1 -1
  39. package/dist/effect/index.d.ts +151 -0
  40. package/dist/effect/index.js +98 -0
  41. package/dist/effect/index.js.map +1 -0
  42. package/dist/extension/index.d.ts +6 -7
  43. package/dist/extension/index.js +3 -2
  44. package/dist/extension/index.js.map +1 -1
  45. package/dist/flow/index.d.ts +68 -59
  46. package/dist/flow/index.js +32 -27
  47. package/dist/flow/index.js.map +1 -1
  48. package/dist/idempotency/index.d.ts +6 -7
  49. package/dist/idempotency/index.js +4 -2
  50. package/dist/{index-CSyMYDAB.d.ts → index-7vV8xmsD.d.ts} +1 -1
  51. package/dist/{index-KXqTRJyb.d.ts → index-Bz5Rh9Ga.d.ts} +19 -96
  52. package/dist/index-CjFDUBeq.d.ts +207 -0
  53. package/dist/{index-CuNO9m8i.d.ts → index-CkFYA9Y6.d.ts} +14 -16
  54. package/dist/{index-CA_7I5g9.d.ts → index-Cou86-GX.d.ts} +137 -246
  55. package/dist/{index-DrIRb_Ch.d.ts → index-DU6JpQ8G.d.ts} +1 -1
  56. package/dist/{index-HSYgG2Yt.d.ts → index-Xufl55W8.d.ts} +247 -211
  57. package/dist/{index-C2DwkjlP.d.ts → index-_dOR3xqA.d.ts} +57 -45
  58. package/dist/index.d.ts +121 -385
  59. package/dist/index.js +2 -1
  60. package/dist/jev/index.d.ts +133 -97
  61. package/dist/jev/index.js +205 -161
  62. package/dist/jev/index.js.map +1 -1
  63. package/dist/{machine-DGlPWCWI.d.ts → machine-BQzTV8On.d.ts} +171 -288
  64. package/dist/machine-viz/index.d.ts +5 -5
  65. package/dist/machine-viz/index.js +8 -4
  66. package/dist/machine-viz/index.js.map +1 -1
  67. package/dist/mem/index.d.ts +3 -4
  68. package/dist/mem/index.js +2 -1
  69. package/dist/mem/index.js.map +1 -1
  70. package/dist/node/index.d.ts +119 -78
  71. package/dist/node/index.js +52 -38
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/paginate/index.d.ts +27 -22
  74. package/dist/paginate/index.js +6 -4
  75. package/dist/parity/index.d.ts +4 -5
  76. package/dist/parity/index.js +3 -2
  77. package/dist/parity/index.js.map +1 -1
  78. package/dist/pbt/index.d.ts +2 -2
  79. package/dist/pbt/index.js +2 -1
  80. package/dist/pbt/index.js.map +1 -1
  81. package/dist/persistence/index.d.ts +6 -7
  82. package/dist/persistence/index.js +5 -3
  83. package/dist/promise/index.d.ts +186 -0
  84. package/dist/promise/index.js +5 -0
  85. package/dist/promise/index.js.map +1 -0
  86. package/dist/{protocol-D8VbH-VH.d.ts → protocol-ClRZBhHQ.d.ts} +7 -8
  87. package/dist/react/index.d.ts +36 -17
  88. package/dist/react/index.js +27 -4
  89. package/dist/react/index.js.map +1 -1
  90. package/dist/resilience/index.d.ts +63 -456
  91. package/dist/resilience/index.js +37 -483
  92. package/dist/resilience/index.js.map +1 -1
  93. package/dist/{runtime-types-CMF13BBh.d.ts → runtime-types-CiVpC0HN.d.ts} +131 -388
  94. package/dist/testing/index.d.ts +22 -16
  95. package/dist/testing/index.js +15 -7
  96. package/dist/testing/index.js.map +1 -1
  97. package/dist/timing/index.d.ts +25 -22
  98. package/dist/timing/index.js +4 -3
  99. package/dist/timing/index.js.map +1 -1
  100. package/dist/{types-BseNPIhr.d.ts → types-LxZxGYda.d.ts} +2 -2
  101. package/dist/work-queue/index.d.ts +5 -6
  102. package/package.json +18 -5
  103. package/dist/chunk-22POWGFA.js.map +0 -1
  104. package/dist/chunk-3B5X7SBB.js.map +0 -1
  105. package/dist/chunk-66PY5WYF.js +0 -1816
  106. package/dist/chunk-66PY5WYF.js.map +0 -1
  107. package/dist/chunk-AYS5N6WY.js.map +0 -1
  108. package/dist/chunk-L3TND7LA.js +0 -97
  109. package/dist/chunk-L3TND7LA.js.map +0 -1
  110. package/dist/chunk-MYXFNWAJ.js.map +0 -1
  111. package/dist/chunk-Q5CQTBFA.js.map +0 -1
  112. package/dist/chunk-QPEVCJ5Q.js.map +0 -1
  113. package/dist/chunk-TCLBCERH.js.map +0 -1
  114. package/dist/chunk-VTQI2NHP.js.map +0 -1
  115. package/dist/index-ZCMhnVKN.d.ts +0 -272
@@ -1,58 +1,8 @@
1
1
  import { asRng, recordFailure, shouldRetry, nextDelayMs, initRetry } from './chunk-VBDU4JL6.js';
2
- import { deadlineMsgType, subscribeDeadline, initCache, set, deadlineSub, get } from './chunk-22POWGFA.js';
3
- import { Cmd, liftSlice, without, tryInterpret } from './chunk-66PY5WYF.js';
4
- import { z } from 'zod';
5
-
6
- // src/protocol.ts
7
- var MsgType = {
8
- // --- resilient-call: the run Cmd + its two settle Msgs -------------------
9
- /** The "run the port for `key`" effect Cmd resilient-call emits. */
10
- ResilientRun: "resilient_run",
11
- /** PRIVATE success settle Msg (read only by `agentEvents`, #47). */
12
- ResilientOk: "resilient_ok",
13
- /** Failure settle Msg — routed to the `fail` verb (back off via retry). */
14
- ResilientErr: "resilient_err",
15
- // --- agent: the wired machine's own entry-point Msgs ---------------------
16
- /** Begin a run. */
17
- AgentStart: "agent_start",
18
- /** PRIVATE tool-fan-out success settle Msg (read only by `agentEvents`, #47). */
19
- AgentToolOk: "agent_tool_ok",
20
- /** Tool-fan-out failure settle Msg. */
21
- AgentToolErr: "agent_tool_err",
22
- /**
23
- * Re-fire the one outstanding effect on rehydrate (the do↔agent seam). Fired
24
- * by `do/host`'s `autoBoot` via the typed `agentBootMsg` constructor, matched
25
- * by the agent reducer — see `AgentBootPort` in `../agent`.
26
- */
27
- AgentBoot: "agent_boot",
28
- /**
29
- * Stop the run from outside and settle it `cancelled` — what an `AbortSignal`
30
- * handed to `driveToDone` / a defined agent's `run` dispatches on abort. A
31
- * transition, never a throw: the outcome lands in the Model, so a reload reads
32
- * a run that ended rather than one to resume.
33
- */
34
- AgentCancel: "agent_cancel",
35
- // --- agent: the context-compaction round-trip (#85) ----------------------
36
- /**
37
- * The "summarize the oldest N turns" effect Cmd the agent emits when its
38
- * `CompactionPolicy` asks to compact before a brain call. A DEDICATED
39
- * round-trip (design B1), distinct from the brain call's `resilient_run`, so
40
- * compaction is its own honest `Awaiting` state — see `../agent`.
41
- */
42
- CompactRun: "compact_run",
43
- /** Compaction round-trip resolved — carries the summary text the fold-back folds. */
44
- CompactOk: "compact_ok",
45
- /** Compaction round-trip failed (exhausted retry) — surfaced as data, not a stall. */
46
- CompactErr: "compact_err",
47
- // --- token-refresh: the two refresh-result Msgs --------------------------
48
- /** Refresh port resolved — carries the fresh `Token`. */
49
- TokenRefreshed: "token_refreshed",
50
- /** Refresh port rejected — carries the rejection (errors are data). */
51
- TokenRefreshFailed: "token_refresh_failed",
52
- // --- authed-call: the 401 trigger ----------------------------------------
53
- /** The 401 the consumer dispatches when a guarded call comes back unauthorized. */
54
- Unauthorized: "unauthorized"
55
- };
2
+ import { unchecked } from './chunk-4LPY67E4.js';
3
+ import { initCache, deadlineSub, nextTimer, get, set } from './chunk-IVJP3GKJ.js';
4
+ import { liftSlice } from './chunk-GOX2CYIM.js';
5
+ import { Cmd, without } from './chunk-CH5KTOEZ.js';
56
6
 
57
7
  // src/internal/resilience/circuit-breaker/index.ts
58
8
  var defaultCircuitPolicy = {
@@ -147,11 +97,13 @@ function remaining(window, nowMs) {
147
97
  const live = prune(window, nowMs).length;
148
98
  return Math.max(0, window.limit - live);
149
99
  }
100
+
101
+ // src/internal/resilience/resilient-call/index.ts
150
102
  var DEFAULT_RESILIENT_NAME = "resilient";
151
103
  function runCmdDef(name = DEFAULT_RESILIENT_NAME) {
152
104
  return Cmd.define(`${name}_run`, {
153
- input: z.custom(),
154
- ok: z.custom(),
105
+ input: unchecked(),
106
+ ok: unchecked(),
155
107
  err: ["port_rejected", "deadline_exceeded"]
156
108
  });
157
109
  }
@@ -182,8 +134,6 @@ function createResilientCall(config, rng = Math.random) {
182
134
  const cPolicy = circuitPolicy(config);
183
135
  const rngBranded = asRng(rng);
184
136
  const runCmd = runCmdDef(name);
185
- const okType = `${name}_ok`;
186
- const errType = `${name}_err`;
187
137
  const deadlineName = deadlineNameOf(name);
188
138
  function init() {
189
139
  return {
@@ -200,9 +150,13 @@ function createResilientCall(config, rng = Math.random) {
200
150
  ) : initBucket(1, 1, 0),
201
151
  retry: {},
202
152
  cache: initCache(),
203
- calls: {}
153
+ calls: {},
154
+ clockMs: 0
204
155
  };
205
156
  }
157
+ function tick(s, at) {
158
+ return s.clockMs === at ? s : { ...s, clockMs: at };
159
+ }
206
160
  function retryOf(s, key) {
207
161
  return s.retry[key] ?? initRetry();
208
162
  }
@@ -298,7 +252,7 @@ function createResilientCall(config, rng = Math.random) {
298
252
  return { ...s, calls: { ...s.calls, [key]: phase } };
299
253
  }
300
254
  function attempt(s, key, input, at) {
301
- return gate(s, key, input, at, budgetFor(s, key, at));
255
+ return gate(tick(s, at), key, input, at, budgetFor(s, key, at));
302
256
  }
303
257
  function resume(s, at) {
304
258
  const calls = { ...s.calls };
@@ -309,23 +263,22 @@ function createResilientCall(config, rng = Math.random) {
309
263
  budget: { ...call.budget, chargingSinceMs: at }
310
264
  };
311
265
  }
312
- return { ...s, calls };
266
+ return { ...s, calls, clockMs: at };
313
267
  }
314
- function succeed(s, key, msg) {
268
+ function recordOk(s, msg) {
269
+ const { key } = msg.cmd;
315
270
  const circuit = cPolicy !== null ? onSuccess(s.circuit) : s.circuit;
316
- const cache = config.cache !== void 0 ? set(s.cache, key, msg.result, msg.at, config.cache.ttlMs) : s.cache;
271
+ const cache = config.cache !== void 0 ? set(s.cache, key, msg.value, msg.at, config.cache.ttlMs) : s.cache;
317
272
  const retry = without(s.retry, key);
318
- return [
319
- {
320
- ...setCall(s, key, { phase: "succeeded", result: msg.result }),
321
- circuit,
322
- cache,
323
- retry
324
- },
325
- []
326
- ];
273
+ return {
274
+ ...setCall(s, key, { phase: "succeeded", result: msg.value }),
275
+ circuit,
276
+ cache,
277
+ retry
278
+ };
327
279
  }
328
- function fail(s, key, msg) {
280
+ function recordErr(s, msg) {
281
+ const { key } = msg.cmd;
329
282
  const circuit = cPolicy !== null ? onFailure(s.circuit, cPolicy, msg.at) : s.circuit;
330
283
  const withCircuit = { ...s, circuit };
331
284
  const call = s.calls[key];
@@ -339,10 +292,30 @@ function createResilientCall(config, rng = Math.random) {
339
292
  }
340
293
  return backoff(withCircuit, key, input, msg.error, msg.at, budget);
341
294
  }
342
- function settleFailed(s, key, error) {
343
- return [setCall(s, key, { phase: "failed", error }), []];
295
+ function isOk(msg) {
296
+ return "value" in msg;
297
+ }
298
+ function settle(s, msg) {
299
+ const now = tick(s, msg.at);
300
+ if (isOk(msg)) {
301
+ return {
302
+ call: recordOk(now, msg),
303
+ cmds: [],
304
+ outcome: { kind: "done", value: msg.value }
305
+ };
306
+ }
307
+ const [call, cmds] = recordErr(now, msg);
308
+ return {
309
+ call,
310
+ cmds,
311
+ outcome: call.calls[msg.cmd.key]?.phase === "waiting_retry" ? { kind: "retrying" } : { kind: "failed", error: msg.error }
312
+ };
313
+ }
314
+ function settleFailed(s, key, error, at) {
315
+ return [setCall(tick(s, at), key, { phase: "failed", error }), []];
344
316
  }
345
- function onTimer(s, msg) {
317
+ function onTimer(slice, msg) {
318
+ const s = tick(slice, msg.atMs);
346
319
  for (const [key, call] of Object.entries(s.calls)) {
347
320
  if (msg.id === retryTimerId(name, key)) {
348
321
  if (call.phase !== "waiting_retry") return [s, []];
@@ -372,7 +345,7 @@ function createResilientCall(config, rng = Math.random) {
372
345
  }
373
346
  return [s, []];
374
347
  }
375
- function subs(s) {
348
+ function deadlines(s) {
376
349
  const out = [];
377
350
  for (const [key, call] of Object.entries(s.calls)) {
378
351
  if (call.phase === "waiting_retry") {
@@ -394,112 +367,29 @@ function createResilientCall(config, rng = Math.random) {
394
367
  }
395
368
  return out;
396
369
  }
397
- function handlers(ports) {
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 };
370
+ function timer(s) {
371
+ return nextTimer(deadlines(s), s.clockMs);
414
372
  }
415
373
  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.
374
+ // The Msg-name family this knob speaks, as a VALUE typed at `N`: the Cmd,
375
+ // the settle Msgs and the timer ids all derive from it.
420
376
  name,
377
+ /** The `Cmd.define`d run Cmd; list it in the machine's `cmds`. */
378
+ run: runCmd,
421
379
  init,
422
380
  attempt,
423
381
  resume,
424
- succeed,
425
- fail,
382
+ settle,
426
383
  settleFailed,
427
384
  onTimer,
428
- subs,
429
- handlers
385
+ deadlines,
386
+ timer
430
387
  };
431
388
  }
432
389
  function liftResilience(state, result) {
433
390
  return liftSlice("resilience", state, result);
434
391
  }
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
- };
501
- }
502
392
 
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
393
+ export { DEFAULT_RESILIENT_NAME, canPass, createResilientCall, defaultCircuitPolicy, initBucket, initCircuit, initWindow, liftResilience, onFailure, onSuccess, record, refill, remaining, runCmdDef, tryConsume };
394
+ //# sourceMappingURL=chunk-6NG4V5SB.js.map
395
+ //# sourceMappingURL=chunk-6NG4V5SB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/resilience/circuit-breaker/index.ts","../src/internal/resilience/rate-limit/index.ts","../src/internal/resilience/resilient-call/index.ts"],"names":[],"mappings":";;;;;;;AAyHO,IAAM,oBAAA,GAAsC;AAAA,EACjD,gBAAA,EAAkB,CAAA;AAAA,EAClB,UAAA,EAAY,GAAA;AAAA,EACZ,iBAAA,EAAmB;AACrB;AAoBO,SAAS,WAAA,GAA4B;AAC1C,EAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,QAAA,EAAU,CAAA,EAAE;AACxC;AAYO,SAAS,SAAA,CACd,OACA,OAAA,EACc;AACd,EAAA,QAAQ,MAAM,KAAA;AAAO,IACnB,KAAK,QAAA;AAGH,MAAA,OAAO,KAAA,CAAM,aAAa,CAAA,GAAI,KAAA,GAAQ,EAAE,KAAA,EAAO,QAAA,EAAU,UAAU,CAAA,EAAE;AAAA,IACvE,KAAK,WAAA;AACH,MAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,QAAA,EAAU,CAAA,EAAE;AAAA,IACxC,KAAK,MAAA;AACH,MAAA,OAAO,KAAA;AAAA;AAEb;AAgBO,SAAS,SAAA,CACd,KAAA,EACA,MAAA,EACA,KAAA,EACc;AACd,EAAA,QAAQ,MAAM,KAAA;AAAO,IACnB,KAAK,QAAA,EAAU;AACb,MAAA,MAAM,QAAA,GAAW,MAAM,QAAA,GAAW,CAAA;AAGlC,MAAA,OA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A,EAAG;AACjD,MAAA,IAAI,IAAA,CAAK,UAAU,eAAA,EAAiB;AAClC,QAAA,GAAA,CAAI,IAAA;AAAA,UACF,YAAY,YAAA,CAAa,IAAA,EAAM,GAAG,CAAA,EAAG,KAAK,SAAA,EAAW;AAAA,YACnD,IAAA,EAAM;AAAA,WACP;AAAA,SACH;AAAA,MACF;AACA,MAAA,IACE,MAAA,CAAO,QAAA,KAAa,MAAA,KACnB,IAAA,CAAK,KAAA,KAAU,SAAA,IAAa,IAAA,CAAK,KAAA,KAAU,eAAA,CAAA,IAC5C,IAAA,CAAK,MAAA,CAAO,WAAA,GAAc,CAAA,EAC1B;AAKA,QAAA,GAAA,CAAI,IAAA;AAAA,UACF,WAAA;AAAA,YACE,eAAA,CAAgB,MAAM,GAAG,CAAA;AAAA,YACzB,IAAA,CAAK,MAAA,CAAO,eAAA,GAAkB,IAAA,CAAK,MAAA,CAAO,WAAA;AAAA,YAC1C,EAAE,MAAM,YAAA;AAAa;AACvB,SACF;AAAA,MACF;AAAA,IACF;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AAcA,EAAA,SAAS,MACP,CAAA,EACwC;AACxC,IAAA,OAAO,SAAA,CAAU,SAAA,CAAU,CAAC,CAAA,EAAG,EAAE,OAAO,CAAA;AAAA,EAC1C;AAEA,EAAA,OAAO;AAAA;AAAA;AAAA,IAGL,IAAA;AAAA;AAAA,IAEA,GAAA,EAAK,MAAA;AAAA,IACL,IAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,YAAA;AAAA,IACA,OAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;AACF;AAYO,SAAS,cAAA,CAMd,OACA,MAAA,EAC4B;AAC5B,EAAA,OAAO,SAAA,CAAU,YAAA,EAAc,KAAA,EAAO,MAAM,CAAA;AAC9C","file":"chunk-6NG4V5SB.js","sourcesContent":["/**\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); consumers reach it\n * through `@demlik/tea/resilience`.\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 one fallible piece of work.\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**. You hand `createResilientCall` a\n * `ResilientConfig` and get back plain functions: `init()`, the verbs\n * (`attempt` / `settle` / `onTimer` / `resume` / `settleFailed`), the\n * `deadlines(state)` list and the `timer(state)` that arms it, and `run` —\n * the `Cmd.define`d Cmd the knob emits. You call them from your own\n * `update` (ADR 0022); nothing mounts or wraps your machine.\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 * ## The work runs in your handler (ADR 0021)\n *\n * The knob ships no engine code. Its one effect is the `run` Cmd\n * (`<name>_run`), built with `Cmd.define`, and you interpret it in your\n * engine's own style. The handler returns an outcome and the engine mints\n * `<name>_run_ok` / `<name>_run_err`, which `settle` reads:\n *\n * interpret: {\n * resilient_run: async (cmd, { ok, err }) => {\n * try { return ok(await fetchUser(cmd.input)); }\n * catch (cause) { return err({ _tag: \"port_rejected\", cause }); }\n * },\n * }\n *\n * A failure the handler does not return as a declared tag (a throw, an\n * undeclared tag) is a contract breach: it goes to the error sink and never\n * reaches `settle`, so it is never retried.\n *\n * ## Where the clock / RNG live\n *\n * Inside the verbs: nowhere. Time arrives as `at` on `attempt` / `resume` /\n * `settleFailed`, as the `at` the engine stamps on a settled Msg, and as `atMs`\n * on a timer Msg. Jitter RNG is injected once at\n * `createResilientCall(config, rng)` and threaded into `nextDelayMs` at the\n * verb boundary — deterministic in tests, `Math.random` by default.\n *\n * Every clocked verb also records its instant on the slice (`clockMs`). That is\n * what lets `timer(state)` hand the built-in `timer` Sub a RELATIVE countdown to\n * the soonest deadline without reading a clock: the Sub's deps change whenever\n * the slice's clock moves, so the engine restarts the countdown from that\n * instant.\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 * // One helper of your own folds the outcome into your Model. The value is\n * // only reachable through `r.outcome`, so the slice has always settled first.\n * function onSettle(s: Model, r: ReturnType<typeof rc.settle>) {\n * const next = { ...s, resilience: r.call };\n * switch (r.outcome.kind) {\n * case \"done\": return [{ ...next, result: r.outcome.value }, r.cmds] as const;\n * case \"failed\": return [next, r.cmds] as const;\n * case \"retrying\": return [next, r.cmds] as const;\n * }\n * }\n *\n * // in the machine:\n * update: {\n * fetch: (s, m) => liftResilience(s, rc.attempt(s.resilience, m.key, m.input, m.at)),\n * resilient_run_ok: (s, m) => onSettle(s, rc.settle(s.resilience, m)),\n * resilient_run_err: (s, m) => onSettle(s, rc.settle(s.resilience, m)),\n * deadline_exceeded: (s, m) => liftResilience(s, rc.onTimer(s.resilience, m)),\n * },\n * subs: [{ type: \"timer\", deps: (s) => rc.timer(s.resilience) }],\n *\n * `timer` is the engine's built-in Sub, so `run` needs no `subscribe` for it.\n * `docs/how-to/hand-wire-a-resilient-call.md` walks the whole machine.\n *\n * ## Naming a knob, when a machine holds more than one\n *\n * Every knob above speaks `resilient_run` / `resilient_run_ok` /\n * `resilient_run_err`, so TWO of them in one machine meet in one\n * `resilient_run_ok` cell whose `value` is the union of both payloads —\n * discriminated by hand on `cmd.key`, which the type checker cannot grade.\n * `config.name` renames the whole family, Cmd and 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_run_ok: (s, m) => …, // m.value is JevOk — no `key` switch\n * llm_run_ok: (s, m) => …, // m.value is LlmOk\n * }\n *\n * The name leads the retry / deadline ids too (`jev:retry:<key>`), because a\n * fired timer is routed by its id and two knobs would otherwise answer each\n * other's timer on a shared key, and it names the timer Msg (`jev_deadline`).\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*`.\n */\n\nimport { liftSlice } from \"../../../compose\";\nimport {\n Cmd,\n type CmdOf,\n type MalformedResult,\n type TaggedError,\n type TimerDeps,\n} 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 { unchecked } from \"../../schema\";\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 deadlineSub,\n nextTimer,\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_run_ok` /\n * `resilient_run_err`. Identical to the `MsgType.Resilient*` literals, which\n * stay 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}_run_ok` as const;\nconst _errIsProtocol: typeof MsgType.ResilientErr =\n `${DEFAULT_RESILIENT_NAME}_run_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 — minted by the engine. */\nexport type ResilientOkType<N extends string> = `${N}_run_ok`;\n/** The failure settle Msg's `type` for the `N` family — minted by the engine. */\nexport type ResilientErrType<N extends string> = `${N}_run_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`, and the\n * `<name>_run_ok` / `<name>_run_err` the engine mints from the run handler's\n * outcome. Omit it and the family is `resilient` — `resilient_run` /\n * `resilient_run_ok` / `resilient_run_err`.\n *\n * Name a knob when a machine holds more than one of the resilient family.\n * Two unnamed knobs meet in ONE `resilient_run_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 * `settle`'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 `settle`.\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 * The instant of the latest clocked transition this slice saw — the `at` of\n * the last `attempt` / `resume` / `settleFailed`, settled Msg or timer fire.\n * `timer` counts the soonest deadline down from it, so the built-in `timer`\n * Sub gets a relative `ms` without anything reading a clock. `0` until the\n * first clocked transition.\n */\n readonly clockMs: number;\n}\n\n// ===========================================================================\n// Cmds + Msgs the knob speaks. Generic over the port input `I`.\n// ===========================================================================\n\n/**\n * The failures a run handler may return (ADR 0021). `port_rejected` is the\n * work failing — carry the cause beside the tag (`err({ _tag: \"port_rejected\",\n * cause })`); `deadline_exceeded` is a handler that timed the work out itself.\n * Either one settles as `<name>_run_err` and feeds the retry / breaker. Any\n * other failure is a contract breach and goes to the error sink.\n */\nexport type RunErr = TaggedError<\"port_rejected\" | \"deadline_exceeded\">;\n\n/**\n * The one effect this knob emits: \"run the work for `key` with `input`\". It is\n * `Cmd.define`d, so the handler you write for it returns an outcome and the\n * engine mints `<name>_run_ok` / `<name>_run_err` (ADR 0021). It carries no\n * closure — `input` 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: unchecked<{ readonly key: string; readonly input: I }>(),\n ok: unchecked<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>>;\n/**\n * The run Cmd value. `R` is its settle value — `unknown` reads any knob's run\n * Cmd; the knob's own verbs emit it at their `R`, which is what lets a machine\n * list `cmds: [rc.run]` and take the verbs' Cmds as its own.\n */\nexport type RunCmd<\n I,\n N extends string = DefaultResilientName,\n R = unknown,\n> = CmdOf<RunCmdDef<I, R, N>>;\n\n/**\n * The settle Msgs the engine mints from a run handler's outcome:\n * `<name>_run_ok` carrying the handler's `value`, `<name>_run_err` carrying its\n * declared `error`. Each carries the run Cmd it settles (`cmd.key` names the\n * call) and the `at` the engine stamped. Both are generic in the knob's name\n * family `N`, so two knobs named apart land in two `update` cells whose\n * payloads are already narrowed.\n *\n * They are the `SettledOk` / `SettledErr` pair `Cmd.define` mints, spelled out\n * so a helper that folds the error into a richer type of its own (llm-call's\n * `LlmErr`, jev-ask's `JevAskErr`) can hand `settle` its Msg with `E` widened.\n */\nexport type SucceedMsg<\n R,\n N extends string = DefaultResilientName,\n I = unknown,\n> = {\n readonly type: ResilientOkType<N>;\n readonly cmd: RunCmd<I, N>;\n readonly value: R;\n readonly at: number;\n};\nexport type FailMsg<\n N extends string = DefaultResilientName,\n I = unknown,\n E = RunErr | MalformedResult,\n> = {\n readonly type: ResilientErrType<N>;\n readonly cmd: RunCmd<I, N>;\n readonly error: E;\n readonly at: number;\n};\n\n/**\n * What `settle` reads off a settled Msg: the call's `key` (on `cmd`), the\n * engine's `at`, and the handler's `value` or `error`. {@link SucceedMsg} and\n * {@link FailMsg} are both one of these, so an engine-minted Msg passes\n * straight in; a helper that settles from its own data (a fallback answer, a\n * compaction summary) builds the record without inventing a whole run Cmd.\n */\nexport type SettleMsg<R, N extends string = DefaultResilientName> =\n | {\n readonly type?: ResilientOkType<N>;\n readonly cmd: { readonly key: string };\n readonly value: R;\n readonly at: number;\n }\n | {\n readonly type?: ResilientErrType<N>;\n readonly cmd: { readonly key: string };\n readonly error: unknown;\n readonly at: number;\n };\n\n/**\n * How a settled call ended — the third thing `settle` hands back, and the only\n * place the port's value can be read from.\n *\n * - `done` — the port answered; `value` is its result.\n * - `failed` — no retry is left (or no retry brick); `error` is the last\n * failure.\n * - `retrying` — backed off; the retry timer is armed and the call is still\n * live.\n */\nexport type SettleOutcome<R> =\n | { readonly kind: \"done\"; readonly value: R }\n | { readonly kind: \"failed\"; readonly error: unknown }\n | { readonly kind: \"retrying\" };\n\n/**\n * What `settle` returns: the settled slice, the Cmds it emitted, and the\n * {@link SettleOutcome}. One record, so the slice update and the result read\n * cannot be split apart in a hand-wired `update` cell.\n */\nexport interface SettleResult<I, R, N extends string = DefaultResilientName> {\n readonly call: ResilientState<I, R>;\n readonly cmds: readonly RunCmd<I, N, R>[];\n readonly outcome: SettleOutcome<R>;\n}\n\n/**\n * The deadline Msg tag this knob's timers dispatch, derived from its name the\n * same way the settle Msgs are. The DEFAULT family keeps the bare\n * `\"deadline_exceeded\"` literal.\n */\nexport type ResilientDeadlineType<N extends string = DefaultResilientName> =\n N extends DefaultResilientName ? \"deadline_exceeded\" : `${N}_deadline`;\n\n/**\n * The name a deadline 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// 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// Deadline-id families. Each call's retry timer is a deadline keyed by `key`, so\n// a machine running many concurrent calls arms and routes each independently.\n// The knob's `name` leads the id for the same reason it leads the Msg types: a\n// fired timer is routed by its id, so two knobs sharing a key would otherwise\n// answer each other's 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 plain functions and the run Cmd def (ADR 0022) — see the module doc\n * for the wiring. `I` is the work's input type, `R` its result type.\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 name each deadline 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 clockMs: 0,\n };\n }\n\n /** Record `at` as the latest instant this slice saw (see `clockMs`). */\n function tick(s: ResilientState<I, R>, at: number): ResilientState<I, R> {\n return s.clockMs === at ? s : { ...s, clockMs: at };\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, R>[]] {\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, R>[]] {\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, R>[]] {\n return gate(tick(s, at), 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, clockMs: at };\n }\n\n // === The two record steps `settle` is built from ==========================\n\n /**\n * Record a success for `msg.key`: close the breaker, fill the cache (if a\n * cache brick exists), reset this key's retry count, and settle `succeeded`.\n * PURE — `msg.at` is the cache write clock. Private: {@link settle} is the\n * verb.\n */\n function recordOk(\n s: ResilientState<I, R>,\n msg: Extract<SettleMsg<R, N>, { readonly value: R }>,\n ): ResilientState<I, R> {\n const { key } = msg.cmd;\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.value, 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 ...setCall(s, key, { phase: \"succeeded\", result: msg.value }),\n circuit,\n cache,\n retry,\n };\n }\n\n /**\n * Record a failure for `msg.key`: trip the breaker (it may open), then back\n * off — schedule a retry if `retry` permits, else settle `failed`. PURE —\n * `msg.at` stamps the breaker trip + the retry delay base. Re-issues from the\n * call's remembered `input` and carries the original budget forward, charged\n * up to `msg.at` — the attempt that just failed spent in-process time, and a\n * retry ladder shares ONE budget across its attempts rather than getting a\n * fresh one per attempt. Private: {@link settle} is the verb.\n */\n function recordErr(\n s: ResilientState<I, R>,\n msg: Extract<SettleMsg<R, N>, { readonly error: unknown }>,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N, R>[]] {\n const { key } = msg.cmd;\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 function isOk(\n msg: SettleMsg<R, N>,\n ): msg is Extract<SettleMsg<R, N>, { readonly value: R }> {\n return \"value\" in msg;\n }\n\n // === Verb: settle ========================================================\n\n /**\n * Settle the call a `<name>_run_ok` / `<name>_run_err` Msg answers, keyed off\n * `msg.cmd.key`, and say how it ended. PURE.\n *\n * A success closes the breaker, fills the cache and ends the retry run; the\n * outcome is `done` with the handler's value. A failure trips the breaker and\n * backs off: `retrying` while the retry policy allows another attempt, and\n * `failed` with the error once it does not. A `retrying` call waits on the\n * retry timer `timer` arms; its fire re-issues the run Cmd through `onTimer`.\n *\n * The settled slice, its Cmds and the outcome come back together, and the\n * result value is reachable ONLY through `outcome`. So a hand-wired settle\n * cell cannot fold the answer into its Model before the slice has settled —\n * the order that used to leave a call stuck at `running` cannot be written.\n */\n function settle(\n s: ResilientState<I, R>,\n msg: SettleMsg<R, N>,\n ): SettleResult<I, R, N> {\n const now = tick(s, msg.at);\n if (isOk(msg)) {\n return {\n call: recordOk(now, msg),\n cmds: [],\n outcome: { kind: \"done\", value: msg.value },\n };\n }\n const [call, cmds] = recordErr(now, msg);\n return {\n call,\n cmds,\n outcome:\n call.calls[msg.cmd.key]?.phase === \"waiting_retry\"\n ? { kind: \"retrying\" }\n : { kind: \"failed\", error: msg.error },\n };\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. `settle` on an `_err` Msg is the opposite — it records the\n * failure against the breaker (it may open) and feeds the retry policy (it\n * 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 * `at` is the instant the caller decided it — recorded as the slice's clock,\n * since ending a call can change which deadline `timer` counts down to.\n */\n function settleFailed(\n s: ResilientState<I, R>,\n key: string,\n error: unknown,\n at: number,\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N, R>[]] {\n return [setCall(tick(s, at), 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) leaves the calls alone — the reconcile pass races the result;\n * the verb must tolerate a stale fire. Every fire records `msg.atMs` as the\n * slice's clock, so `timer` re-arms from it. PURE.\n */\n function onTimer(\n slice: ResilientState<I, R>,\n msg: { readonly id: string; readonly atMs: number },\n ): readonly [ResilientState<I, R>, readonly RunCmd<I, N, R>[]] {\n const s = tick(slice, msg.atMs);\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 // === Timers ==============================================================\n\n /**\n * The deadlines this slice is waiting on: a retry timer for every\n * `waiting_retry` call, and (when the `deadline` brick is configured) an\n * overall deadline timer for every still-active call. Each is an absolute\n * instant; `timer` arms the soonest. PURE.\n */\n function deadlines(\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 /**\n * The built-in `timer` Sub's deps for this slice: the soonest of\n * {@link deadlines}, counted down from the slice's `clockMs`, or `null` when\n * nothing is waiting. Declare it in the machine and `run` needs no runner:\n *\n * subs: [{ type: \"timer\", deps: (s) => rc.timer(s.call) }]\n *\n * Its fire is this knob's timer Msg (`deadline_exceeded`, or\n * `<name>_deadline` for a named knob); route it to `onTimer`. A phase change\n * drops the matching deadline, and the new deps restart the countdown — no\n * manual `clearTimeout`. PURE.\n */\n function timer(\n s: ResilientState<I, R>,\n ): TimerDeps<ResilientTimerMsg<N>> | null {\n return nextTimer(deadlines(s), s.clockMs);\n }\n\n return {\n // The Msg-name family this knob speaks, as a VALUE typed at `N`: the Cmd,\n // the settle Msgs and the timer ids all derive from it.\n name,\n /** The `Cmd.define`d run Cmd; list it in the machine's `cmds`. */\n run: runCmd,\n init,\n attempt,\n resume,\n settle,\n settleFailed,\n onTimer,\n deadlines,\n timer,\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.\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"]}
@@ -1,6 +1,6 @@
1
+ import { createSnapshot } from './chunk-CIHSHLQX.js';
1
2
  import { queueAdapter } from './chunk-TXN2KFHF.js';
2
- import { createSnapshot } from './chunk-L3TND7LA.js';
3
- import { deadlineSub } from './chunk-22POWGFA.js';
3
+ import { deadlineSub, nextTimer } from './chunk-IVJP3GKJ.js';
4
4
 
5
5
  // src/internal/flow/monitored-run/index.ts
6
6
  function safetyTimerId(runId, progressSeq) {
@@ -155,7 +155,7 @@ function createMonitoredRun(config = {}) {
155
155
  };
156
156
  return [reseeded, []];
157
157
  }
158
- function subs(s) {
158
+ function deadlines(s) {
159
159
  if (config.deadlineMs === void 0) return [];
160
160
  if (s.phase !== "running" && s.phase !== "stale") return [];
161
161
  return [
@@ -165,8 +165,8 @@ function createMonitoredRun(config = {}) {
165
165
  )
166
166
  ];
167
167
  }
168
- function handlers(ports) {
169
- return activeSnap.handlers({ store: ports.store });
168
+ function timer(s) {
169
+ return nextTimer(deadlines(s), s.lastProgressAt);
170
170
  }
171
171
  function confirmSnapshot(s, msg) {
172
172
  if (snap === null) return s;
@@ -174,6 +174,8 @@ function createMonitoredRun(config = {}) {
174
174
  return { ...s, snapshot: confirmed };
175
175
  }
176
176
  return {
177
+ /** The `snapshot_write` Cmd def — list it in `cmds` when checkpointing. */
178
+ checkpoint: activeSnap.write,
177
179
  init,
178
180
  start,
179
181
  progress,
@@ -183,8 +185,8 @@ function createMonitoredRun(config = {}) {
183
185
  onDeadline,
184
186
  boot,
185
187
  confirmSnapshot,
186
- subs,
187
- handlers
188
+ deadlines,
189
+ timer
188
190
  };
189
191
  }
190
192
  function liftRun(state, [slice, cmds]) {
@@ -192,5 +194,5 @@ function liftRun(state, [slice, cmds]) {
192
194
  }
193
195
 
194
196
  export { createMonitoredRun, liftRun };
195
- //# sourceMappingURL=chunk-3B5X7SBB.js.map
196
- //# sourceMappingURL=chunk-3B5X7SBB.js.map
197
+ //# sourceMappingURL=chunk-7MGXQZPW.js.map
198
+ //# sourceMappingURL=chunk-7MGXQZPW.js.map