@parcha/agentrun-dsl 0.1.0-beta.17 → 0.1.0-beta.171

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 (75) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +153 -16
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +4 -3
  6. package/dist/author.js +20 -11
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +64 -3
  14. package/dist/decision-receipts.js +50 -8
  15. package/dist/dry-run.d.ts +35 -1
  16. package/dist/dry-run.js +131 -25
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +107 -5
  20. package/dist/graph.js +284 -9
  21. package/dist/index.d.ts +17 -12
  22. package/dist/index.js +16 -10
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +14 -1
  25. package/dist/pattern-screen.d.ts +14 -0
  26. package/dist/pattern-screen.js +451 -0
  27. package/dist/predicates.d.ts +29 -0
  28. package/dist/predicates.js +62 -3
  29. package/dist/record.d.ts +4 -0
  30. package/dist/record.js +6 -0
  31. package/dist/recovery/binding.js +2 -1
  32. package/dist/recovery/call-key.d.ts +0 -4
  33. package/dist/recovery/call-key.js +0 -7
  34. package/dist/recovery/driver.d.ts +59 -24
  35. package/dist/recovery/driver.js +251 -73
  36. package/dist/recovery/frozen-snapshot.d.ts +54 -4
  37. package/dist/recovery/frozen-snapshot.js +44 -14
  38. package/dist/recovery/handoff-receipts.d.ts +0 -35
  39. package/dist/recovery/handoff-receipts.js +2 -44
  40. package/dist/recovery/index.d.ts +4 -8
  41. package/dist/recovery/index.js +4 -7
  42. package/dist/recovery/with-recovery.d.ts +9 -3
  43. package/dist/recovery/with-recovery.js +78 -18
  44. package/dist/submit-envelope.d.ts +9 -0
  45. package/dist/submit-envelope.js +44 -0
  46. package/dist/system-one.d.ts +21 -2
  47. package/dist/system-one.js +96 -18
  48. package/dist/testing/decision-provider.d.ts +32 -0
  49. package/dist/testing/decision-provider.js +183 -0
  50. package/dist/testing/index.d.ts +1 -0
  51. package/dist/testing/index.js +2 -0
  52. package/dist/vocabulary.d.ts +11 -3
  53. package/dist/vocabulary.js +19 -9
  54. package/dist/workflow-shape.d.ts +7 -0
  55. package/dist/workflow-shape.js +116 -70
  56. package/dist/workflow.d.ts +171 -19
  57. package/dist/workflow.js +1063 -399
  58. package/dist/zod-json-contract.js +6 -8
  59. package/package.json +12 -4
  60. package/schema/workflow.schema.json +366 -1
  61. package/skills/author/SKILL.md +6 -1
  62. package/skills/author/references/jev-decisions.md +50 -5
  63. package/skills/author/references/language.md +19 -14
  64. package/dist/recovery/effect-failure.d.ts +0 -34
  65. package/dist/recovery/effect-failure.js +0 -62
  66. package/dist/recovery/handoff-block.d.ts +0 -36
  67. package/dist/recovery/handoff-block.js +0 -148
  68. package/dist/recovery/handoff-digest.d.ts +0 -58
  69. package/dist/recovery/handoff-digest.js +0 -195
  70. package/dist/recovery/handoff-files.d.ts +0 -54
  71. package/dist/recovery/handoff-files.js +0 -162
  72. package/dist/recovery/handoff-redact.d.ts +0 -12
  73. package/dist/recovery/handoff-redact.js +0 -44
  74. package/dist/recovery/handoff.d.ts +0 -44
  75. package/dist/recovery/handoff.js +0 -46
@@ -4,18 +4,23 @@
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
6
  import { createHash } from "node:crypto";
7
- import { desugarWorkflow } from "../workflow.js";
7
+ import { desugarWorkflow, isItemFailure } from "../workflow.js";
8
+ import { setLongTimeout } from "../long-timer.js";
9
+ import { isRecord } from "../record.js";
8
10
  import { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, topLevelCompletion } from "./execution-path.js";
9
11
  import { bindingDigests, LEDGER_FORMAT } from "./binding.js";
10
12
  import { canonicalHash as hash } from "./canonical-hash.js";
11
13
  import { RecoveryError } from "./errors.js";
12
14
  import { gatewayIntentOf } from "./handoff-receipts.js";
13
- import { validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, stateDelta, applyStateDelta } from "./frozen-snapshot.js";
14
- const failure = (code, message) => new RecoveryError(message, code);
15
+ import { validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, failure, SHA256 as SHA, FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, stateDelta, applyStateDelta, isItemOutcome, DECISION_REQUEST } from "./frozen-snapshot.js";
15
16
  /** The branch a route runs for its answer, as the interpreter takes it: the node's `unsure` branch when
16
- * the answer's confidence is below `unsure.gte`, else the choice the answer names. */
17
+ * the answer's confidence is below `unsure.gte`, else the choice the answer names. A refused answer chose no branch:
18
+ * with an `unsure` branch the route took it (choice null, refused); without one the run escalated, and there is no
19
+ * decision (null). */
17
20
  export function routeTaken(node, answers) {
18
21
  const answer = answers?.branch;
22
+ if (answer?.type === "refusal")
23
+ return node.unsure ? { branch: node.unsure.branch, choice: null, unsure: true, refused: true } : null;
19
24
  const choice = String(answer?.choice ?? "");
20
25
  const unsure = Boolean(node.unsure && typeof answer?.confidence === "number" && answer.confidence < node.unsure.gte);
21
26
  return { branch: unsure ? node.unsure.branch : choice, choice, unsure };
@@ -168,8 +173,11 @@ export async function openRecovery(store, workflow, options) {
168
173
  const driver = options.key;
169
174
  const controller = new AbortController();
170
175
  let fatal;
171
- /** A pause or cancel was applied: its commit still lands, and nothing after it. */
176
+ /** A pause or cancel was applied: its commit is still made, and no admission after it. */
172
177
  let stopping = false;
178
+ /** A commit the store refused after a pause or cancel was applied (the stop's own, say): the stop is not durable, the
179
+ * journal still reads as it did, and the host hears it from `flush` and `close`. */
180
+ let refusedAfterStop;
173
181
  const journal = await store.open(bound);
174
182
  /** Whether the store keeps parts beside the state: the keyed layout needs both reads. */
175
183
  const keyed = typeof journal.items === "function" && typeof journal.stateOf === "function";
@@ -203,7 +211,7 @@ export async function openRecovery(store, workflow, options) {
203
211
  /** A state the run references by digest, read back and checked against it. */
204
212
  const stateBy = async (sha256) => {
205
213
  const state = await journal.stateOf(sha256);
206
- if (!state || typeof state !== "object" || Array.isArray(state) || hash(state) !== sha256)
214
+ if (!isRecord(state) || hash(state) !== sha256)
207
215
  throw invalid(`The state ${sha256} the run references is missing or changed`);
208
216
  writtenStates.add(sha256);
209
217
  digests.set(state, sha256);
@@ -217,8 +225,6 @@ export async function openRecovery(store, workflow, options) {
217
225
  writtenStates.add(sha256);
218
226
  return value;
219
227
  };
220
- const SHA = /^[a-f0-9]{64}$/;
221
- const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
222
228
  const validEntry = (entry) => isRecord(entry) && Number.isSafeInteger(entry.length) && entry.length >= 0
223
229
  && Number.isSafeInteger(entry.items) && entry.items >= 0 && typeof entry.base === "string" && SHA.test(entry.base);
224
230
  /** The path of map item `index` of the map at `mapPath`: the prefix the interpreter gives every path inside it. */
@@ -245,13 +251,24 @@ export async function openRecovery(store, workflow, options) {
245
251
  const record = item;
246
252
  const valid = record.driver === driver && record.map === mapPath && record.index === index && record.base === entry.base && Number.isSafeInteger(record.revision)
247
253
  && ["running", "committed", "failed"].includes(record.status) && isRecord(record.frame) && Array.isArray(record.frame.done)
254
+ && (record.frame.decisions === undefined || isRecord(record.frame.decisions))
248
255
  && [record.frame.states, record.frame.chains, record.frame.loops, record.frame.routes, record.frame.inputs, record.frame.steps, record.clocks, record.files, record.unknownResponses, record.maps].every(isRecord)
249
- && Array.isArray(record.effects) && record.effects.every((id) => typeof id === "string");
256
+ && Array.isArray(record.effects) && record.effects.every((id) => typeof id === "string")
257
+ // An item that ended on its failure, and only one, holds how it ended; its map collects its items' failures.
258
+ && (record.status === "failed"
259
+ ? isItemOutcome(record.outcome) && nodeAt(view, mapPath)?.onItemFailure === "collect"
260
+ : record.outcome === undefined);
250
261
  if (!valid)
251
262
  throw invalid(`The record of map item ${path} is not one this run wrote`);
263
+ if (record.outcome)
264
+ (frame.failures ??= {})[path] = { ...record.outcome };
252
265
  lastItems.set(path, JSON.stringify({ ...record, revision: 0 }));
253
266
  frame.done.push(...record.frame.done);
254
267
  Object.assign(frame.steps, record.frame.steps);
268
+ if (record.frame.decisions) {
269
+ frame.decisions ??= {};
270
+ Object.assign(frame.decisions, record.frame.decisions);
271
+ }
255
272
  Object.assign(snapshot.clocks, record.clocks);
256
273
  for (const [name, sha256] of Object.entries(record.files)) {
257
274
  // A committed item keeps the record it last wrote, so a file a later step wrote again holds an older hash there.
@@ -430,6 +447,18 @@ export async function openRecovery(store, workflow, options) {
430
447
  build.record.frame[table][at] = value;
431
448
  }
432
449
  }
450
+ // A map item's decision requests are kept in its record, as its steps are; a frame with none writes no table.
451
+ for (const [at, requests] of Object.entries(frame.decisions ?? {})) {
452
+ const build = own(at);
453
+ if (build === undefined) {
454
+ pin.decisions ??= {};
455
+ pin.decisions[at] = requests;
456
+ }
457
+ else if (build) {
458
+ build.record.frame.decisions ??= {};
459
+ build.record.frame.decisions[at] = requests;
460
+ }
461
+ }
433
462
  const clocks = {};
434
463
  for (const [key, value] of Object.entries(snapshot.clocks)) {
435
464
  const build = own(clockPath(key));
@@ -454,6 +483,14 @@ export async function openRecovery(store, workflow, options) {
454
483
  else if (build)
455
484
  build.record.unknownResponses[id] = value;
456
485
  }
486
+ // An item that ended on its failure keeps it in its own record.
487
+ for (const [item, outcome] of Object.entries(frame.failures ?? {})) {
488
+ const build = own(`${item}/body`);
489
+ if (build === undefined)
490
+ (pin.failures ??= {})[item] = outcome;
491
+ else if (build)
492
+ build.record.outcome = outcome;
493
+ }
457
494
  for (const id of new Set([...journal.effects().map((effect) => effect.id), ...queued, ...(admitting === undefined ? [] : [admitting])])) {
458
495
  const build = own(frozenEffectPath(id)?.path);
459
496
  if (build)
@@ -488,7 +525,7 @@ export async function openRecovery(store, workflow, options) {
488
525
  };
489
526
  const items = {};
490
527
  for (const build of builds.values()) {
491
- build.record.status = finished(build.path) ? "committed" : "running";
528
+ build.record.status = build.record.outcome ? "failed" : finished(build.path) ? "committed" : "running";
492
529
  const text = JSON.stringify(build.record);
493
530
  if (lastItems.get(build.path) !== text) {
494
531
  lastItems.set(build.path, text);
@@ -506,7 +543,7 @@ export async function openRecovery(store, workflow, options) {
506
543
  const frame = snapshot.pin;
507
544
  const done = new Set(frame.done);
508
545
  const paths = [...frame.done, ...Object.keys(frame.states), ...Object.keys(frame.chains), ...Object.keys(frame.inputs), ...Object.keys(frame.steps),
509
- ...Object.keys(frame.loops), ...Object.keys(frame.routes)];
546
+ ...Object.keys(frame.loops), ...Object.keys(frame.routes), ...Object.keys(frame.decisions ?? {}), ...Object.keys(frame.failures ?? {}).map((item) => `${item}/body`)];
510
547
  return paths.every((path) => { const at = mapItemOf(path); return !at || done.has(at.map) || Boolean(maps.get(at.map)?.baseState); });
511
548
  };
512
549
  /** One write of the driver's state, in the layout this open keeps. */
@@ -525,14 +562,19 @@ export async function openRecovery(store, workflow, options) {
525
562
  const persist = (write) => {
526
563
  const next = chain.then(() => { if (fatal && !stopping)
527
564
  throw fatal; return write(); });
528
- chain = next.catch((error) => { if (!fatal) {
529
- fatal = error;
530
- controller.abort(error);
531
- } });
565
+ chain = next.catch((error) => {
566
+ if (!fatal) {
567
+ fatal = error;
568
+ controller.abort(error);
569
+ }
570
+ else if (stopping && refusedAfterStop === undefined)
571
+ refusedAfterStop = error;
572
+ });
532
573
  return next;
533
574
  };
534
- /** Every commit the driver started has landed; a failed one is thrown. */
535
- const flush = async () => { await chain; if (fatal && !stopping)
575
+ /** Every commit the driver started has landed; a failed one is thrown, a pause's or a cancel's own commit included. */
576
+ const flush = async () => { await chain; if (refusedAfterStop !== undefined)
577
+ throw refusedAfterStop; if (fatal && !stopping)
536
578
  throw fatal; };
537
579
  try {
538
580
  // A driver an earlier process bound, with no checkpoint, is a run killed between its binding and its first
@@ -544,7 +586,7 @@ export async function openRecovery(store, workflow, options) {
544
586
  const known = [FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4];
545
587
  const found = stored?.schema;
546
588
  const version = typeof found === "string" ? /^agentrun\.frozen_run\.v(\d+)$/.exec(found)?.[1] : undefined;
547
- if (version !== undefined && !known.includes(found) && Number(version) > 4) {
589
+ if (version !== undefined && Number(version) > 4) {
548
590
  throw Object.assign(new RecoveryError(`This run is stored as ${found}, newer than this build knows (${known.join(", ")}); open it with a build that knows it`, "RECOVERY_SCHEMA_NEWER"), { found, known });
549
591
  }
550
592
  // The keyed layout is sticky: a run stored in it stays in it. A run stored whole, or a new one, takes it when the
@@ -674,9 +716,8 @@ export async function openRecovery(store, workflow, options) {
674
716
  }
675
717
  wake();
676
718
  };
677
- const fileHashes = (names) => reader.hashes(names);
678
719
  const verifyFiles = (files) => {
679
- if (hash(fileHashes(Object.keys(files))) !== hash(files))
720
+ if (hash(reader.hashes(Object.keys(files))) !== hash(files))
680
721
  throw failure("FROZEN_ARTIFACT_INVALID", "Committed artifact bytes changed; effect will not be repeated");
681
722
  };
682
723
  /** An effect-level clock is set once and kept across resume: a poll window or an attempt deadline
@@ -710,6 +751,14 @@ export async function openRecovery(store, workflow, options) {
710
751
  throw pathFault(at, "The interpreter named a path this run's document does not hold");
711
752
  return at;
712
753
  };
754
+ /** Where a decision's requests are kept: its own node, or the loop whose `until` the interpreter asks at
755
+ * `<loop>/iterations/<n>`, the one path a question is asked at that no node holds. Any other path is refused. */
756
+ const decisionPlace = (at, doc) => {
757
+ const loop = typeof at === "string" ? /^(.+)\/iterations\/(?:0|[1-9][0-9]*)$/.exec(at)?.[1] : undefined;
758
+ if (loop !== undefined && nodeAt(doc, loop)?.node === "loop")
759
+ return loop;
760
+ return placed(at, doc);
761
+ };
713
762
  /** The committed state a resume at `at` is answered from: its own, or the frontier of a chain it sits
714
763
  * in when the frontier lies past it. A chain threads one state, so every step before its frontier,
715
764
  * and everything inside those steps, is answered with the frontier's. */
@@ -724,7 +773,10 @@ export async function openRecovery(store, workflow, options) {
724
773
  return undefined;
725
774
  };
726
775
  /** Drops what no resume can ask for again: the states, chain frontiers, loop counts, route decisions
727
- * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them. */
776
+ * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them; decision
777
+ * requests stay, as what the run asked and paid for; and so do
778
+ * failed items, as committed paths do: a map that commits in the write that moves its run writes its items' records
779
+ * then, a failed one's with its outcome. */
728
780
  const prune = (frame, gone) => {
729
781
  for (const table of [frame.states, frame.chains, frame.loops, frame.routes, frame.inputs]) {
730
782
  for (const key of Object.keys(table))
@@ -732,6 +784,24 @@ export async function openRecovery(store, workflow, options) {
732
784
  delete table[key];
733
785
  }
734
786
  };
787
+ /** Whether `at` lies in an item of a map that collects its items' failures, at any depth. */
788
+ const collectedAt = (at, doc) => {
789
+ for (let item = mapItemOf(at); item; item = mapItemOf(item.map)) {
790
+ const map = nodeAt(doc, item.map);
791
+ if (map?.node === "map" && map.onItemFailure === "collect")
792
+ return true;
793
+ }
794
+ return false;
795
+ };
796
+ /** The item of a map that collects its items' failures whose body is at `at`, or a fault. */
797
+ const collectingItem = (at, doc) => {
798
+ const item = mapItemOf(at);
799
+ const map = item && nodeAt(doc, item.map);
800
+ if (!item || `${item.item}/body` !== at || map?.node !== "map" || map.onItemFailure !== "collect") {
801
+ throw pathFault(at, "Only the body of an item of a map that collects its items' failures ends on a failure");
802
+ }
803
+ return item;
804
+ };
735
805
  const recovery = {
736
806
  // Every store key below is the interpreter's execution path, so a composed graph (a loop, a route, a
737
807
  // map whose body is structure, a nested child) resumes where it stopped.
@@ -789,7 +859,7 @@ export async function openRecovery(store, workflow, options) {
789
859
  if (step && (frame.chains[step.chain]?.index ?? -1) >= step.index)
790
860
  throw pathFault(at, "A chain step committed behind its chain's frontier");
791
861
  if (node.node === "artifact" && node.path)
792
- keepFiles(fileHashes([node.path]), at);
862
+ keepFiles(reader.hashes([node.path]), at);
793
863
  frame.done.push(at);
794
864
  done.add(at);
795
865
  // A map that committed, alone or inside what committed, has its results in the state: what it had finished
@@ -820,6 +890,35 @@ export async function openRecovery(store, workflow, options) {
820
890
  await save();
821
891
  await flush();
822
892
  },
893
+ async failItem(_node, row, executionPath) {
894
+ // Finished work commits while a pause waits for an effect in flight; it starts nothing.
895
+ guard();
896
+ const { frame, doc } = active();
897
+ const at = placed(executionPath, doc);
898
+ const { item } = collectingItem(at, doc);
899
+ if (frame.failures?.[item])
900
+ throw pathFault(at, "An item ends on its failure once");
901
+ // An effect the item admitted and never completed may have happened: that is uncertainty, reconciled before the
902
+ // run goes on, and never an item failure. A call that threw is one: the driver never certifies a thrown dispatch.
903
+ const uncertain = journal.effects().find((effect) => effect.status === "unknown" && isWithin(frozenEffectPath(effect.id)?.path ?? "", item));
904
+ if (uncertain)
905
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${uncertain.id}: an item whose effect's outcome is unknown does not end on its failure`);
906
+ // What the item had in progress is no one's now: nothing in it is asked for again. Its committed paths, step
907
+ // records and effects stay, as a finished item's do.
908
+ prune(frame, key => isWithin(key, item));
909
+ (frame.failures ??= {})[item] = { code: row.code, label: row.label, message: row.message };
910
+ await save();
911
+ await flush();
912
+ },
913
+ async itemFailure(_node, executionPath) {
914
+ guard();
915
+ const { frame, doc } = active();
916
+ const at = placed(executionPath, doc);
917
+ const { item, index } = collectingItem(at, doc);
918
+ const held = frame.failures?.[item];
919
+ // The row as the item's own process wrote it, key for key.
920
+ return held ? { item_index: index, label: held.label, code: held.code, message: held.message } : undefined;
921
+ },
823
922
  pollStartedAt(node, _item, executionPath) {
824
923
  guard();
825
924
  const { tag, doc } = active();
@@ -834,8 +933,9 @@ export async function openRecovery(store, workflow, options) {
834
933
  // The wait's clock is durable before the wait starts, so a process that dies inside it resumes the same wait.
835
934
  await flush();
836
935
  await new Promise((resolve, reject) => {
837
- const onAbort = () => { clearTimeout(wait); reject(controller.signal.reason); };
838
- const wait = setTimeout(() => { controller.signal.removeEventListener("abort", onAbort); resolve(); }, Math.max(0, until - Date.now()));
936
+ const onAbort = () => { wait.clear(); reject(controller.signal.reason); };
937
+ // setLongTimeout: a wait past Node's 2^31-1 ms timer limit waits instead of firing at once.
938
+ const wait = setLongTimeout(() => { controller.signal.removeEventListener("abort", onAbort); resolve(); }, until - Date.now());
839
939
  controller.signal.addEventListener("abort", onAbort, { once: true });
840
940
  });
841
941
  guard();
@@ -916,7 +1016,7 @@ export async function openRecovery(store, workflow, options) {
916
1016
  stepAdmitted(executionPath) { const { frame, at } = llmStep(executionPath); return frame.steps[at] !== undefined; },
917
1017
  /** The current attempt did not submit: its session closes with its spend kept.
918
1018
  * The step is `closed` until a retry is admitted, or `failed` when no attempt remains. */
919
- stepAttemptFailed(executionPath, final = false) {
1019
+ stepAttemptFailed(executionPath, final = false, error) {
920
1020
  guard();
921
1021
  const { frame, tag, at } = llmStep(executionPath);
922
1022
  const step = frame.steps[at];
@@ -925,7 +1025,11 @@ export async function openRecovery(store, workflow, options) {
925
1025
  const id = sessionOf(tag, at, step);
926
1026
  if (options.closeStepSession)
927
1027
  void persist(() => options.closeStepSession(id)).catch(() => undefined);
928
- closeFrozenStepAttempt(step, final);
1028
+ // An item failure that fails a step in an item of a map that collects them is kept with the step: the item's own
1029
+ // commit comes after this one, and a process that resumes between the two ends the item on the same failure.
1030
+ const kept = error instanceof Error && isItemFailure(error) && collectedAt(at, view)
1031
+ ? { code: String(error.code), message: String(error.message || error).slice(0, 300) } : undefined;
1032
+ closeFrozenStepAttempt(step, final, kept);
929
1033
  save();
930
1034
  },
931
1035
  /** The step delivered its record; the row and the step record agree before the step commit. */
@@ -957,15 +1061,17 @@ export async function openRecovery(store, workflow, options) {
957
1061
  await flush();
958
1062
  },
959
1063
  /** A question's metered spend, committed with the driver's state so a resume that skips the
960
- * finished question still reports it; an unpriced answer (`null`) adds nothing. A route's answer is its decision: it commits in the same save, once per route path, and a resume
961
- * inside the branch follows it instead of asking again. */
1064
+ * finished question still reports it. A priced answer adds to `questionSpendUsd`; an answer with no
1065
+ * price (`null`, or a cost that is not a non-negative finite number) is counted in
1066
+ * `unpricedQuestionCount` instead, so the run's spend is read as incomplete and never as a bare total
1067
+ * that silently omits it: an unknown cost is never zero. A route's answer is its decision: it commits
1068
+ * in the same save, once per route path, and a resume inside the branch follows it instead of asking
1069
+ * again; its price, priced or not, is recorded the same way. */
962
1070
  recordQuestionSpend(usd, route) {
963
1071
  guard();
964
- let changed = false;
965
- if (usd !== null && Number.isFinite(usd) && usd >= 0) {
966
- snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
967
- changed = true;
968
- }
1072
+ // A route's checks run before any state is touched, so a refused call (not a route, or a route already
1073
+ // decided) leaves the snapshot clean: the next save never carries a half-recorded answer forward.
1074
+ let decision;
969
1075
  if (route) {
970
1076
  const { frame, doc } = active();
971
1077
  const at = placed(route.executionPath, doc);
@@ -974,11 +1080,18 @@ export async function openRecovery(store, workflow, options) {
974
1080
  throw pathFault(at, "Only a route's answer is a decision");
975
1081
  if (frame.routes[at])
976
1082
  throw pathFault(at, "A route is decided once");
977
- frame.routes[at] = { label: route.label, ...routeTaken(node, route.result.answers), request_sha256: typeof route.result.request_sha256 === "string" ? route.result.request_sha256 : null, result: route.result, receipts: route.receipts };
978
- changed = true;
1083
+ // A refused route with no unsure branch took no branch: its answer is spent, and there is no decision.
1084
+ const taken = routeTaken(node, route.result.answers);
1085
+ if (taken)
1086
+ decision = { at, row: { label: route.label, ...taken, request_sha256: typeof route.result.request_sha256 === "string" ? route.result.request_sha256 : null, result: route.result, receipts: route.receipts } };
979
1087
  }
980
- if (changed)
981
- save();
1088
+ if (usd !== null && Number.isFinite(usd) && usd >= 0)
1089
+ snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
1090
+ else
1091
+ snapshot.unpricedQuestionCount = (snapshot.unpricedQuestionCount ?? 0) + 1;
1092
+ if (decision)
1093
+ active().frame.routes[decision.at] = decision.row;
1094
+ save();
982
1095
  },
983
1096
  /** The host has written what it keeps of the route at `executionPath`: its decision no longer carries the
984
1097
  * receipts a resume would write. */
@@ -992,10 +1105,72 @@ export async function openRecovery(store, workflow, options) {
992
1105
  save();
993
1106
  },
994
1107
  /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
1108
+ /** Moves the poll window of the call node at `executionPath` back by `ms`, the time its host held the call (a pause
1109
+ * for a raise of the run's spend cap, which no deadline is for), durably: a later open reads the moved window, and
1110
+ * the next effect's check (wrapEffect) and the interpreter's poll start (pollStartedAt) take it. A node with no poll
1111
+ * window started, or no time held, moves nothing. `hold` names the hold (the host's id for it): one hold moves the
1112
+ * window once, however often a resume reports it again. */
1113
+ holdPoll(executionPath, ms, hold) {
1114
+ const { tag, doc } = active();
1115
+ const at = placed(executionPath, doc);
1116
+ const key = `poll:${tag}:${at}`;
1117
+ const once = `hold:${tag}:${at}:${hold}`;
1118
+ if (snapshot.clocks[key] === undefined || snapshot.clocks[once] !== undefined || !(Number.isFinite(ms) && ms > 0))
1119
+ return;
1120
+ snapshot.clocks[key] += ms;
1121
+ snapshot.clocks[once] = ms;
1122
+ void save();
1123
+ },
995
1124
  routeDecision(executionPath) {
996
1125
  const { frame, doc } = active();
997
1126
  return frame.routes[placed(executionPath, doc)];
998
1127
  },
1128
+ /** Every decision request this run committed, by decision id. */
1129
+ decisionRequests() {
1130
+ const { frame } = active();
1131
+ return structuredClone(Object.assign({}, ...Object.values(frame.decisions ?? {})));
1132
+ },
1133
+ /** Admits a decision's request before the host's judge is asked, in the driver's next commit, which the caller
1134
+ * awaits: a new request, or the next attempt of one that failed in its own process (undefined). A request found
1135
+ * in any other status was asked by an earlier process and is returned as it stands; the caller does not ask again.
1136
+ * An admitted request is in flight until `decisionSettled`: a pause waits for it, as for an effect. */
1137
+ admitDecision(executionPath, request) {
1138
+ guard();
1139
+ const { frame, doc } = active();
1140
+ const at = decisionPlace(executionPath, doc);
1141
+ frame.decisions ??= {};
1142
+ frame.decisions[at] ??= {};
1143
+ const requests = frame.decisions[at];
1144
+ const known = requests[request.decision_id];
1145
+ if (known && known.status !== "failed")
1146
+ return structuredClone(known);
1147
+ requests[request.decision_id] = { record: DECISION_REQUEST, ...request, attempt: (known?.attempt ?? 0) + 1, status: "requested" };
1148
+ inFlight += 1;
1149
+ save();
1150
+ return undefined;
1151
+ },
1152
+ /** A request `admitDecision` admitted is no longer in flight. */
1153
+ decisionSettled() { settled(); },
1154
+ /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
1155
+ * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
1156
+ * It never applies a stop: a request the run asked ends whatever stops the run. */
1157
+ decisionEnded(executionPath, decisionId, status, cost_usd, alongside) {
1158
+ if (fatal)
1159
+ throw fatal;
1160
+ const { frame, doc } = active();
1161
+ const request = frame.decisions?.[decisionPlace(executionPath, doc)]?.[decisionId];
1162
+ if (!request)
1163
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The decision ${decisionId} ends without its request`);
1164
+ if (request.status !== "requested")
1165
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The decision ${decisionId} ends once`);
1166
+ Object.assign(request, { status, cost_usd });
1167
+ try {
1168
+ alongside?.();
1169
+ }
1170
+ finally {
1171
+ save();
1172
+ }
1173
+ },
999
1174
  /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
1000
1175
  * as an escalation commit before anything acts on it. A later open gets the same row and the same
1001
1176
  * continuation identity, whatever fires again. */
@@ -1018,31 +1193,10 @@ export async function openRecovery(store, workflow, options) {
1018
1193
  return snapshot.escalation;
1019
1194
  },
1020
1195
  escalation() { return snapshot.escalation; },
1196
+ /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
1197
+ pinJson() { return JSON.stringify(snapshot.pin); },
1021
1198
  /** How many effects the driver admitted. */
1022
1199
  effectCalls() { return journal.effects().length; },
1023
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
1024
- * read and its identity. */
1025
- async annotateHandoff(detail) {
1026
- await persist(() => journal.note("inherited", detail));
1027
- },
1028
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
1029
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
1030
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
1031
- * continuation binds on, does not change. */
1032
- async handoff(spend) {
1033
- guard();
1034
- const row = snapshot.escalation;
1035
- if (!row)
1036
- throw failure("FROZEN_CHECKPOINT_INVALID", "A handoff follows an escalation; none is recorded");
1037
- if (row.cost_usd === spend.cost_usd && row.turns === spend.turns && row.effect_calls === spend.effect_calls)
1038
- return row;
1039
- const detail = { escalation_revision: row.revision, previous_cost_usd: row.cost_usd,
1040
- cost_usd: spend.cost_usd, turns: spend.turns, effect_calls: spend.effect_calls };
1041
- Object.assign(row, spend);
1042
- const write = writeOf();
1043
- await persist(() => journal.save(write.state, { kind: "handoff", detail }, write.parts));
1044
- return row;
1045
- },
1046
1200
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
1047
1201
  * items produced under the map's key: what an escalation on a failure carries. */
1048
1202
  lastState() {
@@ -1094,12 +1248,16 @@ export async function openRecovery(store, workflow, options) {
1094
1248
  // From its admission the effect is in flight: a pause waits for it to complete and commit, so the admission is
1095
1249
  // never left without its dispatch.
1096
1250
  inFlight += 1;
1251
+ let deadlineTimer;
1097
1252
  try {
1098
1253
  // The driver's state and the admission are one transaction.
1099
1254
  const admission = writeOf(id);
1100
1255
  const admitted = await persist(() => journal.admit(id, String(params.node.label), argsHash, admission.state, driver, external, params.input ?? null, admission.parts, admission.owner));
1101
1256
  if (admitted !== "new")
1102
1257
  throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id} before dispatch`);
1258
+ // The admission durable before the dispatch, where the host's store needs a barrier for it (afterAdmit).
1259
+ if (options.afterAdmit)
1260
+ await persist(options.afterAdmit);
1103
1261
  // What landed while the admission was being committed still counts: after a cancel, the caller's own
1104
1262
  // cancellation or the effect's deadline, the effect stays admitted and unknown and the adapter is never called.
1105
1263
  // A pause lets it dispatch and complete.
@@ -1108,7 +1266,15 @@ export async function openRecovery(store, workflow, options) {
1108
1266
  throw params.signal.reason;
1109
1267
  if (Date.now() >= deadline)
1110
1268
  throw failure("FROZEN_EFFECT_DEADLINE", "Effect exceeded its own deadline");
1111
- const signal = AbortSignal.any([params.signal, controller.signal, AbortSignal.timeout(Math.max(1, deadline - Date.now()))]);
1269
+ // The deadline is the clock the driver kept, so a fraction of a millisecond, or a delay past Node's 2^31-1 ms timer
1270
+ // limit, waits out its time; it aborts with the TimeoutError AbortSignal.timeout gives, which a host reads as a deadline.
1271
+ const timeout = new AbortController();
1272
+ deadlineTimer = setLongTimeout(() => timeout.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError")), deadline - Date.now());
1273
+ const signal = AbortSignal.any([params.signal, controller.signal, timeout.signal]);
1274
+ // Clear the deadline timer the moment the effect is aborted (a cancel, a pause, or the deadline itself): a
1275
+ // `runEffect` that ignores its signal and stays pending would otherwise leave this process alive until the
1276
+ // deadline — hours or days out — because the `finally` runs only when the dispatch settles.
1277
+ signal.addEventListener("abort", () => deadlineTimer?.clear(), { once: true });
1112
1278
  // A thrown/aborted call remains UNKNOWN, including transient failures: no blind retry. Each outside call the effect
1113
1279
  // makes is kept on its record as it ends, on the driver's commit chain, so a process killed mid-effect keeps the
1114
1280
  // calls it made and a commit that fails is the run's failure, which aborts the effect at once.
@@ -1118,21 +1284,28 @@ export async function openRecovery(store, workflow, options) {
1118
1284
  try {
1119
1285
  value = await run({ ...params, signal, call: keep, effect: { id, argsHash } });
1120
1286
  }
1287
+ catch (error) {
1288
+ // The host's one signal that it cannot know the outcome: what it observed is kept for the operator, without
1289
+ // certifying completion. Any other throw leaves the effect unknown too, with nothing observed.
1290
+ if (error instanceof RecoveryError && error.code === "FROZEN_EFFECT_UNKNOWN") {
1291
+ if (calls.length)
1292
+ await flush();
1293
+ if (error.cause !== undefined) {
1294
+ (snapshot.unknownResponses ??= {})[id] = error.cause;
1295
+ await save();
1296
+ await flush();
1297
+ }
1298
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id}: the host reported an unknown outcome`);
1299
+ }
1300
+ throw error;
1301
+ }
1121
1302
  finally {
1122
1303
  if (calls.length)
1123
1304
  await flush();
1124
1305
  }
1125
1306
  if (signal.aborted)
1126
1307
  throw signal.reason;
1127
- const returned = value;
1128
- if (returned?.outcome === "unknown" || returned?.effect_status === "unknown"
1129
- || returned?.details?.outcome === "unknown" || returned?.details?.effect_status === "unknown") {
1130
- (snapshot.unknownResponses ??= {})[id] = value;
1131
- await save(); // Preserve the observation without certifying completion.
1132
- await flush();
1133
- throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id}: tool returned an unknown outcome`);
1134
- }
1135
- const files = fileHashes(params.produces);
1308
+ const files = reader.hashes(params.produces);
1136
1309
  // A tool effect's receipt names the external call it paid for (the tool and its arguments),
1137
1310
  // so a continuation that inherits the receipt can answer the same call from it. Any other
1138
1311
  // effect keeps its arguments beside its result.
@@ -1143,13 +1316,18 @@ export async function openRecovery(store, workflow, options) {
1143
1316
  return value;
1144
1317
  }
1145
1318
  finally {
1319
+ deadlineTimer?.clear();
1146
1320
  settled();
1147
1321
  }
1148
1322
  };
1149
1323
  },
1150
- /** Every commit the driver started has landed; a failed one is thrown. */
1324
+ /** Every commit the driver started has landed; a failed one is thrown, a pause's or a cancel's own commit included. */
1151
1325
  flush,
1152
- /** Let go of the run once every commit the driver started has landed. */
1153
- async close() { await chain; await journal.close(); },
1326
+ /** Let go of the run once every commit the driver started has landed. A commit the store refused after a pause or
1327
+ * cancel is thrown once the journal is released: the stop is not durable, and the host must not take the run as
1328
+ * stopped. It is thrown even when a later stop's commit lands, since a later commit does not carry every record the
1329
+ * refused one held. A run's own failed commit is the run's failure and is not thrown again here. */
1330
+ async close() { await chain; await journal.close(); if (refusedAfterStop !== undefined)
1331
+ throw refusedAfterStop; },
1154
1332
  };
1155
1333
  }