@parcha/agentrun-dsl 0.1.0-beta.23 → 0.1.0-beta.231

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 (80) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +22 -17
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +0 -2
  6. package/dist/author.js +15 -8
  7. package/dist/authoring.js +4 -3
  8. package/dist/cli.js +13 -12
  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 +31 -1
  16. package/dist/dry-run.js +122 -16
  17. package/dist/edit.d.ts +149 -0
  18. package/dist/edit.js +1422 -0
  19. package/dist/evidence.d.ts +19 -0
  20. package/dist/evidence.js +63 -0
  21. package/dist/graph.d.ts +17 -0
  22. package/dist/graph.js +71 -6
  23. package/dist/index.d.ts +18 -12
  24. package/dist/index.js +17 -10
  25. package/dist/inspection.d.ts +5 -0
  26. package/dist/inspection.js +14 -1
  27. package/dist/pattern-screen.d.ts +14 -0
  28. package/dist/pattern-screen.js +451 -0
  29. package/dist/pointer-warning.d.ts +14 -0
  30. package/dist/pointer-warning.js +22 -0
  31. package/dist/predicates.d.ts +32 -2
  32. package/dist/predicates.js +66 -6
  33. package/dist/record.d.ts +4 -0
  34. package/dist/record.js +6 -0
  35. package/dist/recovery/binding.js +2 -1
  36. package/dist/recovery/call-key.d.ts +0 -4
  37. package/dist/recovery/call-key.js +0 -7
  38. package/dist/recovery/driver.d.ts +43 -20
  39. package/dist/recovery/driver.js +144 -48
  40. package/dist/recovery/frozen-snapshot.d.ts +33 -3
  41. package/dist/recovery/frozen-snapshot.js +28 -12
  42. package/dist/recovery/handoff-receipts.d.ts +0 -35
  43. package/dist/recovery/handoff-receipts.js +2 -44
  44. package/dist/recovery/index.d.ts +4 -8
  45. package/dist/recovery/index.js +4 -7
  46. package/dist/recovery/item-state.d.ts +2 -1
  47. package/dist/recovery/item-state.js +7 -13
  48. package/dist/recovery/with-recovery.d.ts +9 -3
  49. package/dist/recovery/with-recovery.js +72 -15
  50. package/dist/submit-envelope.d.ts +9 -0
  51. package/dist/submit-envelope.js +44 -0
  52. package/dist/system-one.d.ts +21 -2
  53. package/dist/system-one.js +96 -18
  54. package/dist/testing/decision-provider.d.ts +32 -0
  55. package/dist/testing/decision-provider.js +183 -0
  56. package/dist/testing/index.d.ts +1 -0
  57. package/dist/testing/index.js +2 -0
  58. package/dist/vocabulary.d.ts +16 -3
  59. package/dist/vocabulary.js +23 -8
  60. package/dist/workflow-shape.js +4 -2
  61. package/dist/workflow.d.ts +145 -19
  62. package/dist/workflow.js +795 -236
  63. package/dist/zod-json-contract.js +6 -8
  64. package/package.json +16 -4
  65. package/schema/workflow.schema.json +352 -1
  66. package/skills/author/SKILL.md +4 -1
  67. package/skills/author/references/jev-decisions.md +50 -5
  68. package/skills/author/references/language.md +16 -11
  69. package/dist/recovery/effect-failure.d.ts +0 -34
  70. package/dist/recovery/effect-failure.js +0 -62
  71. package/dist/recovery/handoff-block.d.ts +0 -36
  72. package/dist/recovery/handoff-block.js +0 -148
  73. package/dist/recovery/handoff-digest.d.ts +0 -58
  74. package/dist/recovery/handoff-digest.js +0 -195
  75. package/dist/recovery/handoff-files.d.ts +0 -54
  76. package/dist/recovery/handoff-files.js +0 -162
  77. package/dist/recovery/handoff-redact.d.ts +0 -12
  78. package/dist/recovery/handoff-redact.js +0 -44
  79. package/dist/recovery/handoff.d.ts +0 -44
  80. package/dist/recovery/handoff.js +0 -46
@@ -7,7 +7,3 @@ export declare const CALL_KEY_BYTES = 256;
7
7
  * call always has the same key, and two different wide ids share a key only on a digest collision.
8
8
  * Only keys use it: what goes back to the provider is always the id it minted. */
9
9
  export declare function callKey(callId: string): string;
10
- /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
11
- * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
12
- * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
13
- export declare function heldCallKey(callId: string, holds: (rawKey: string) => boolean): string;
@@ -15,10 +15,3 @@ export function callKey(callId) {
15
15
  const prefix = callId.slice(0, PREFIX_CHARS).replace(/[^A-Za-z0-9_.-]/g, "_");
16
16
  return `${prefix}~${createHash("sha256").update(callId).digest("hex").slice(0, DIGEST_HEX)}`;
17
17
  }
18
- /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
19
- * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
20
- * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
21
- export function heldCallKey(callId, holds) {
22
- const key = callKey(callId);
23
- return key !== callId && holds(callId) ? callId : key;
24
- }
@@ -1,13 +1,16 @@
1
1
  import type { RouteNode, Workflow, WorkflowDeps, WorkflowNode } from "../workflow.js";
2
- import { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, type RouteDecision, type QuestionReceipts, type StepRecord, type EscalationRow } from "./frozen-snapshot.js";
2
+ import { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, type RouteDecision, type QuestionReceipts, type StepRecord, type EscalationRow, type DecisionRequest } from "./frozen-snapshot.js";
3
3
  import type { RecoveryBinding, RecoveryEffect, RecoveryStore } from "./store.js";
4
4
  /** The branch a route runs for its answer, as the interpreter takes it: the node's `unsure` branch when
5
- * the answer's confidence is below `unsure.gte`, else the choice the answer names. */
5
+ * the answer's confidence is below `unsure.gte`, else the choice the answer names. A refused answer chose no branch:
6
+ * with an `unsure` branch the route took it (choice null, refused); without one the run escalated, and there is no
7
+ * decision (null). */
6
8
  export declare function routeTaken(node: RouteNode, answers: unknown): {
7
9
  branch: string;
8
- choice: string;
10
+ choice: string | null;
9
11
  unsure: boolean;
10
- };
12
+ refused?: true;
13
+ } | null;
11
14
  /** The binding of a run of `workflow` under what the host binds beside it. */
12
15
  export declare function recoveryBinding(workflow: Workflow, bind?: Record<string, unknown>): string;
13
16
  /** What a store is opened under for a run of `workflow`: its binding, and the digest of each input the binding
@@ -45,6 +48,11 @@ export type RecoveryOptions = {
45
48
  /** Closes the session of an LLM step's attempt that ended without a submission. It runs on the driver's commit
46
49
  * chain, before the commit that records the attempt as closed; its failure is the run's. */
47
50
  closeStepSession?: (sessionId: string) => Promise<unknown>;
51
+ /** The host's barrier for an effect's admission: called on the driver's commit chain right after the admission's commit
52
+ * and before the effect is dispatched, so a host whose store syncs between commits (a run store at synchronous NORMAL)
53
+ * makes the admission durable first. Its failure is the run's, and the effect, admitted, is never dispatched: it stays
54
+ * unknown, for a reconcile. Absent, nothing runs between the admission and the dispatch. */
55
+ afterAdmit?: () => Promise<void>;
48
56
  /** Settles effects a killed process left unknown, through the driver's own open of the run (one generation per process).
49
57
  * `openRecovery` calls it once, after the open and before anything resumes, when the journal holds an effect that was
50
58
  * admitted and never completed; `unknown` is those effects, with their `intent` and the `args` the call was admitted with (what the host's door is sent; absent on a record written before args were kept). `complete(id, value, receipt)`
@@ -167,8 +175,12 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
167
175
  * persistence failure. */
168
176
  charge(usd: number): Promise<void>;
169
177
  /** A question's metered spend, committed with the driver's state so a resume that skips the
170
- * 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
171
- * inside the branch follows it instead of asking again. */
178
+ * finished question still reports it. A priced answer adds to `questionSpendUsd`; an answer with no
179
+ * price (`null`, or a cost that is not a non-negative finite number) is counted in
180
+ * `unpricedQuestionCount` instead, so the run's spend is read as incomplete and never as a bare total
181
+ * that silently omits it: an unknown cost is never zero. A route's answer is its decision: it commits
182
+ * in the same save, once per route path, and a resume inside the branch follows it instead of asking
183
+ * again; its price, priced or not, is recorded the same way. */
172
184
  recordQuestionSpend(usd: number | null, route?: {
173
185
  executionPath: unknown;
174
186
  label: string;
@@ -179,28 +191,39 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
179
191
  * receipts a resume would write. */
180
192
  routeReceipted(executionPath: unknown): void;
181
193
  /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
194
+ /** Moves the poll window of the call node at `executionPath` back by `ms`, the time its host held the call (a pause
195
+ * for a raise of the run's spend cap, which no deadline is for), durably: a later open reads the moved window, and
196
+ * the next effect's check (wrapEffect) and the interpreter's poll start (pollStartedAt) take it. A node with no poll
197
+ * window started, or no time held, moves nothing. `hold` names the hold (the host's id for it): one hold moves the
198
+ * window once, however often a resume reports it again. */
199
+ holdPoll(executionPath: unknown, ms: number, hold: string): void;
182
200
  routeDecision(executionPath: unknown): RouteDecision | undefined;
201
+ /** Every decision request this run committed, by decision id. */
202
+ decisionRequests(): Record<string, DecisionRequest>;
203
+ /** Admits a decision's request before the host's judge is asked, in the driver's next commit, which the caller
204
+ * awaits: a new request, or the next attempt of one that failed in its own process (undefined). A request found
205
+ * in any other status was asked by an earlier process and is returned as it stands; the caller does not ask again.
206
+ * An admitted request is in flight until `decisionSettled`: a pause waits for it, as for an effect. */
207
+ admitDecision(executionPath: unknown, request: Pick<DecisionRequest, "decision_id" | "kind" | "label" | "model" | "request_sha256">): DecisionRequest | undefined;
208
+ /** A request `admitDecision` admitted is no longer in flight. */
209
+ decisionSettled(): void;
210
+ /** Work the host does for a running step outside the driver's records (a model node's request to its model), in
211
+ * flight until the returned release: a pause waits for it, as for an effect, and is taken once it is released. A stop
212
+ * already taken refuses it. Released once; a second release does nothing. */
213
+ hold(): () => void;
214
+ /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
215
+ * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
216
+ * It never applies a stop: a request the run asked ends whatever stops the run. */
217
+ decisionEnded(executionPath: unknown, decisionId: string, status: "answered" | "failed" | "interrupted", cost_usd: number | null, alongside?: () => void): void;
183
218
  /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
184
219
  * as an escalation commit before anything acts on it. A later open gets the same row and the same
185
220
  * continuation identity, whatever fires again. */
186
221
  escalate(row: Omit<EscalationRow, "tail" | "revision">): Promise<EscalationRow>;
187
222
  escalation(): EscalationRow | undefined;
223
+ /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
224
+ pinJson(): string;
188
225
  /** How many effects the driver admitted. */
189
226
  effectCalls(): number;
190
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
191
- * read and its identity. */
192
- annotateHandoff(detail: {
193
- escalation_revision: number;
194
- tail: string;
195
- inherit: string;
196
- block_chars: number;
197
- digest_chars: number;
198
- }): Promise<void>;
199
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
200
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
201
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
202
- * continuation binds on, does not change. */
203
- handoff(spend: Pick<EscalationRow, "cost_usd" | "turns" | "effect_calls">): Promise<EscalationRow>;
204
227
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
205
228
  * items produced under the map's key: what an escalation on a failure carries. */
206
229
  lastState(): Record<string, unknown>;
@@ -6,17 +6,22 @@ import path from "node:path";
6
6
  import { createHash } from "node:crypto";
7
7
  import { desugarWorkflow, isItemFailure } from "../workflow.js";
8
8
  import { setLongTimeout } from "../long-timer.js";
9
+ import { isRecord } from "../record.js";
10
+ import { getPath } from "../predicates.js";
9
11
  import { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, topLevelCompletion } from "./execution-path.js";
10
12
  import { bindingDigests, LEDGER_FORMAT } from "./binding.js";
11
13
  import { canonicalHash as hash } from "./canonical-hash.js";
12
14
  import { RecoveryError } from "./errors.js";
13
15
  import { gatewayIntentOf } from "./handoff-receipts.js";
14
- import { validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, stateDelta, applyStateDelta, isItemOutcome } from "./frozen-snapshot.js";
15
- const failure = (code, message) => new RecoveryError(message, code);
16
+ 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";
16
17
  /** The branch a route runs for its answer, as the interpreter takes it: the node's `unsure` branch when
17
- * the answer's confidence is below `unsure.gte`, else the choice the answer names. */
18
+ * the answer's confidence is below `unsure.gte`, else the choice the answer names. A refused answer chose no branch:
19
+ * with an `unsure` branch the route took it (choice null, refused); without one the run escalated, and there is no
20
+ * decision (null). */
18
21
  export function routeTaken(node, answers) {
19
22
  const answer = answers?.branch;
23
+ if (answer?.type === "refusal")
24
+ return node.unsure ? { branch: node.unsure.branch, choice: null, unsure: true, refused: true } : null;
20
25
  const choice = String(answer?.choice ?? "");
21
26
  const unsure = Boolean(node.unsure && typeof answer?.confidence === "number" && answer.confidence < node.unsure.gte);
22
27
  return { branch: unsure ? node.unsure.branch : choice, choice, unsure };
@@ -207,7 +212,7 @@ export async function openRecovery(store, workflow, options) {
207
212
  /** A state the run references by digest, read back and checked against it. */
208
213
  const stateBy = async (sha256) => {
209
214
  const state = await journal.stateOf(sha256);
210
- if (!state || typeof state !== "object" || Array.isArray(state) || hash(state) !== sha256)
215
+ if (!isRecord(state) || hash(state) !== sha256)
211
216
  throw invalid(`The state ${sha256} the run references is missing or changed`);
212
217
  writtenStates.add(sha256);
213
218
  digests.set(state, sha256);
@@ -221,8 +226,6 @@ export async function openRecovery(store, workflow, options) {
221
226
  writtenStates.add(sha256);
222
227
  return value;
223
228
  };
224
- const SHA = /^[a-f0-9]{64}$/;
225
- const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
226
229
  const validEntry = (entry) => isRecord(entry) && Number.isSafeInteger(entry.length) && entry.length >= 0
227
230
  && Number.isSafeInteger(entry.items) && entry.items >= 0 && typeof entry.base === "string" && SHA.test(entry.base);
228
231
  /** The path of map item `index` of the map at `mapPath`: the prefix the interpreter gives every path inside it. */
@@ -249,6 +252,7 @@ export async function openRecovery(store, workflow, options) {
249
252
  const record = item;
250
253
  const valid = record.driver === driver && record.map === mapPath && record.index === index && record.base === entry.base && Number.isSafeInteger(record.revision)
251
254
  && ["running", "committed", "failed"].includes(record.status) && isRecord(record.frame) && Array.isArray(record.frame.done)
255
+ && (record.frame.decisions === undefined || isRecord(record.frame.decisions))
252
256
  && [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)
253
257
  && Array.isArray(record.effects) && record.effects.every((id) => typeof id === "string")
254
258
  // An item that ended on its failure, and only one, holds how it ended; its map collects its items' failures.
@@ -262,6 +266,10 @@ export async function openRecovery(store, workflow, options) {
262
266
  lastItems.set(path, JSON.stringify({ ...record, revision: 0 }));
263
267
  frame.done.push(...record.frame.done);
264
268
  Object.assign(frame.steps, record.frame.steps);
269
+ if (record.frame.decisions) {
270
+ frame.decisions ??= {};
271
+ Object.assign(frame.decisions, record.frame.decisions);
272
+ }
265
273
  Object.assign(snapshot.clocks, record.clocks);
266
274
  for (const [name, sha256] of Object.entries(record.files)) {
267
275
  // A committed item keeps the record it last wrote, so a file a later step wrote again holds an older hash there.
@@ -440,6 +448,18 @@ export async function openRecovery(store, workflow, options) {
440
448
  build.record.frame[table][at] = value;
441
449
  }
442
450
  }
451
+ // A map item's decision requests are kept in its record, as its steps are; a frame with none writes no table.
452
+ for (const [at, requests] of Object.entries(frame.decisions ?? {})) {
453
+ const build = own(at);
454
+ if (build === undefined) {
455
+ pin.decisions ??= {};
456
+ pin.decisions[at] = requests;
457
+ }
458
+ else if (build) {
459
+ build.record.frame.decisions ??= {};
460
+ build.record.frame.decisions[at] = requests;
461
+ }
462
+ }
443
463
  const clocks = {};
444
464
  for (const [key, value] of Object.entries(snapshot.clocks)) {
445
465
  const build = own(clockPath(key));
@@ -524,7 +544,7 @@ export async function openRecovery(store, workflow, options) {
524
544
  const frame = snapshot.pin;
525
545
  const done = new Set(frame.done);
526
546
  const paths = [...frame.done, ...Object.keys(frame.states), ...Object.keys(frame.chains), ...Object.keys(frame.inputs), ...Object.keys(frame.steps),
527
- ...Object.keys(frame.loops), ...Object.keys(frame.routes), ...Object.keys(frame.failures ?? {}).map((item) => `${item}/body`)];
547
+ ...Object.keys(frame.loops), ...Object.keys(frame.routes), ...Object.keys(frame.decisions ?? {}), ...Object.keys(frame.failures ?? {}).map((item) => `${item}/body`)];
528
548
  return paths.every((path) => { const at = mapItemOf(path); return !at || done.has(at.map) || Boolean(maps.get(at.map)?.baseState); });
529
549
  };
530
550
  /** One write of the driver's state, in the layout this open keeps. */
@@ -567,7 +587,7 @@ export async function openRecovery(store, workflow, options) {
567
587
  const known = [FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4];
568
588
  const found = stored?.schema;
569
589
  const version = typeof found === "string" ? /^agentrun\.frozen_run\.v(\d+)$/.exec(found)?.[1] : undefined;
570
- if (version !== undefined && !known.includes(found) && Number(version) > 4) {
590
+ if (version !== undefined && Number(version) > 4) {
571
591
  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 });
572
592
  }
573
593
  // 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
@@ -697,9 +717,8 @@ export async function openRecovery(store, workflow, options) {
697
717
  }
698
718
  wake();
699
719
  };
700
- const fileHashes = (names) => reader.hashes(names);
701
720
  const verifyFiles = (files) => {
702
- if (hash(fileHashes(Object.keys(files))) !== hash(files))
721
+ if (hash(reader.hashes(Object.keys(files))) !== hash(files))
703
722
  throw failure("FROZEN_ARTIFACT_INVALID", "Committed artifact bytes changed; effect will not be repeated");
704
723
  };
705
724
  /** An effect-level clock is set once and kept across resume: a poll window or an attempt deadline
@@ -733,6 +752,14 @@ export async function openRecovery(store, workflow, options) {
733
752
  throw pathFault(at, "The interpreter named a path this run's document does not hold");
734
753
  return at;
735
754
  };
755
+ /** Where a decision's requests are kept: its own node, or the loop whose `until` the interpreter asks at
756
+ * `<loop>/iterations/<n>`, the one path a question is asked at that no node holds. Any other path is refused. */
757
+ const decisionPlace = (at, doc) => {
758
+ const loop = typeof at === "string" ? /^(.+)\/iterations\/(?:0|[1-9][0-9]*)$/.exec(at)?.[1] : undefined;
759
+ if (loop !== undefined && nodeAt(doc, loop)?.node === "loop")
760
+ return loop;
761
+ return placed(at, doc);
762
+ };
736
763
  /** The committed state a resume at `at` is answered from: its own, or the frontier of a chain it sits
737
764
  * in when the frontier lies past it. A chain threads one state, so every step before its frontier,
738
765
  * and everything inside those steps, is answered with the frontier's. */
@@ -747,7 +774,8 @@ export async function openRecovery(store, workflow, options) {
747
774
  return undefined;
748
775
  };
749
776
  /** Drops what no resume can ask for again: the states, chain frontiers, loop counts, route decisions
750
- * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them; and so do
777
+ * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them; decision
778
+ * requests stay, as what the run asked and paid for; and so do
751
779
  * failed items, as committed paths do: a map that commits in the write that moves its run writes its items' records
752
780
  * then, a failed one's with its outcome. */
753
781
  const prune = (frame, gone) => {
@@ -802,7 +830,8 @@ export async function openRecovery(store, workflow, options) {
802
830
  throw pathFault(at, "A committed path was asked for again after its state was released");
803
831
  // A map that starts, or starts again, names the base its items are kept against: the state it starts from.
804
832
  if ((layoutV4 || moving) && node.node === "map") {
805
- const list = String(node.itemsPath).split(".").reduce((value, key) => value?.[key], state);
833
+ // Read as the interpreter reads it (getPath: own keys, an array by its positions), so both count the same items.
834
+ const list = getPath(state, String(node.itemsPath));
806
835
  maps.set(at, { length: Array.isArray(list) ? list.length : 0, items: maps.get(at)?.items ?? 0, base: digestOf(state), baseState: state });
807
836
  }
808
837
  // A node started in an earlier process starts again from the same state, or not at all. The
@@ -832,7 +861,7 @@ export async function openRecovery(store, workflow, options) {
832
861
  if (step && (frame.chains[step.chain]?.index ?? -1) >= step.index)
833
862
  throw pathFault(at, "A chain step committed behind its chain's frontier");
834
863
  if (node.node === "artifact" && node.path)
835
- keepFiles(fileHashes([node.path]), at);
864
+ keepFiles(reader.hashes([node.path]), at);
836
865
  frame.done.push(at);
837
866
  done.add(at);
838
867
  // A map that committed, alone or inside what committed, has its results in the state: what it had finished
@@ -1034,15 +1063,17 @@ export async function openRecovery(store, workflow, options) {
1034
1063
  await flush();
1035
1064
  },
1036
1065
  /** A question's metered spend, committed with the driver's state so a resume that skips the
1037
- * 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
1038
- * inside the branch follows it instead of asking again. */
1066
+ * finished question still reports it. A priced answer adds to `questionSpendUsd`; an answer with no
1067
+ * price (`null`, or a cost that is not a non-negative finite number) is counted in
1068
+ * `unpricedQuestionCount` instead, so the run's spend is read as incomplete and never as a bare total
1069
+ * that silently omits it: an unknown cost is never zero. A route's answer is its decision: it commits
1070
+ * in the same save, once per route path, and a resume inside the branch follows it instead of asking
1071
+ * again; its price, priced or not, is recorded the same way. */
1039
1072
  recordQuestionSpend(usd, route) {
1040
1073
  guard();
1041
- let changed = false;
1042
- if (usd !== null && Number.isFinite(usd) && usd >= 0) {
1043
- snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
1044
- changed = true;
1045
- }
1074
+ // A route's checks run before any state is touched, so a refused call (not a route, or a route already
1075
+ // decided) leaves the snapshot clean: the next save never carries a half-recorded answer forward.
1076
+ let decision;
1046
1077
  if (route) {
1047
1078
  const { frame, doc } = active();
1048
1079
  const at = placed(route.executionPath, doc);
@@ -1051,11 +1082,18 @@ export async function openRecovery(store, workflow, options) {
1051
1082
  throw pathFault(at, "Only a route's answer is a decision");
1052
1083
  if (frame.routes[at])
1053
1084
  throw pathFault(at, "A route is decided once");
1054
- 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 };
1055
- changed = true;
1085
+ // A refused route with no unsure branch took no branch: its answer is spent, and there is no decision.
1086
+ const taken = routeTaken(node, route.result.answers);
1087
+ if (taken)
1088
+ 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 } };
1056
1089
  }
1057
- if (changed)
1058
- save();
1090
+ if (usd !== null && Number.isFinite(usd) && usd >= 0)
1091
+ snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
1092
+ else
1093
+ snapshot.unpricedQuestionCount = (snapshot.unpricedQuestionCount ?? 0) + 1;
1094
+ if (decision)
1095
+ active().frame.routes[decision.at] = decision.row;
1096
+ save();
1059
1097
  },
1060
1098
  /** The host has written what it keeps of the route at `executionPath`: its decision no longer carries the
1061
1099
  * receipts a resume would write. */
@@ -1069,10 +1107,86 @@ export async function openRecovery(store, workflow, options) {
1069
1107
  save();
1070
1108
  },
1071
1109
  /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
1110
+ /** Moves the poll window of the call node at `executionPath` back by `ms`, the time its host held the call (a pause
1111
+ * for a raise of the run's spend cap, which no deadline is for), durably: a later open reads the moved window, and
1112
+ * the next effect's check (wrapEffect) and the interpreter's poll start (pollStartedAt) take it. A node with no poll
1113
+ * window started, or no time held, moves nothing. `hold` names the hold (the host's id for it): one hold moves the
1114
+ * window once, however often a resume reports it again. */
1115
+ holdPoll(executionPath, ms, hold) {
1116
+ const { tag, doc } = active();
1117
+ const at = placed(executionPath, doc);
1118
+ const key = `poll:${tag}:${at}`;
1119
+ const once = `hold:${tag}:${at}:${hold}`;
1120
+ if (snapshot.clocks[key] === undefined || snapshot.clocks[once] !== undefined || !(Number.isFinite(ms) && ms > 0))
1121
+ return;
1122
+ snapshot.clocks[key] += ms;
1123
+ snapshot.clocks[once] = ms;
1124
+ void save();
1125
+ },
1072
1126
  routeDecision(executionPath) {
1073
1127
  const { frame, doc } = active();
1074
1128
  return frame.routes[placed(executionPath, doc)];
1075
1129
  },
1130
+ /** Every decision request this run committed, by decision id. */
1131
+ decisionRequests() {
1132
+ const { frame } = active();
1133
+ return structuredClone(Object.assign({}, ...Object.values(frame.decisions ?? {})));
1134
+ },
1135
+ /** Admits a decision's request before the host's judge is asked, in the driver's next commit, which the caller
1136
+ * awaits: a new request, or the next attempt of one that failed in its own process (undefined). A request found
1137
+ * in any other status was asked by an earlier process and is returned as it stands; the caller does not ask again.
1138
+ * An admitted request is in flight until `decisionSettled`: a pause waits for it, as for an effect. */
1139
+ admitDecision(executionPath, request) {
1140
+ guard();
1141
+ const { frame, doc } = active();
1142
+ const at = decisionPlace(executionPath, doc);
1143
+ frame.decisions ??= {};
1144
+ frame.decisions[at] ??= {};
1145
+ const requests = frame.decisions[at];
1146
+ const known = requests[request.decision_id];
1147
+ if (known && known.status !== "failed")
1148
+ return structuredClone(known);
1149
+ requests[request.decision_id] = { record: DECISION_REQUEST, ...request, attempt: (known?.attempt ?? 0) + 1, status: "requested" };
1150
+ inFlight += 1;
1151
+ save();
1152
+ return undefined;
1153
+ },
1154
+ /** A request `admitDecision` admitted is no longer in flight. */
1155
+ decisionSettled() { settled(); },
1156
+ /** Work the host does for a running step outside the driver's records (a model node's request to its model), in
1157
+ * flight until the returned release: a pause waits for it, as for an effect, and is taken once it is released. A stop
1158
+ * already taken refuses it. Released once; a second release does nothing. */
1159
+ hold() {
1160
+ guard();
1161
+ inFlight += 1;
1162
+ let released = false;
1163
+ return () => {
1164
+ if (released)
1165
+ return;
1166
+ released = true;
1167
+ settled();
1168
+ };
1169
+ },
1170
+ /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
1171
+ * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
1172
+ * It never applies a stop: a request the run asked ends whatever stops the run. */
1173
+ decisionEnded(executionPath, decisionId, status, cost_usd, alongside) {
1174
+ if (fatal)
1175
+ throw fatal;
1176
+ const { frame, doc } = active();
1177
+ const request = frame.decisions?.[decisionPlace(executionPath, doc)]?.[decisionId];
1178
+ if (!request)
1179
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The decision ${decisionId} ends without its request`);
1180
+ if (request.status !== "requested")
1181
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The decision ${decisionId} ends once`);
1182
+ Object.assign(request, { status, cost_usd });
1183
+ try {
1184
+ alongside?.();
1185
+ }
1186
+ finally {
1187
+ save();
1188
+ }
1189
+ },
1076
1190
  /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
1077
1191
  * as an escalation commit before anything acts on it. A later open gets the same row and the same
1078
1192
  * continuation identity, whatever fires again. */
@@ -1095,31 +1209,10 @@ export async function openRecovery(store, workflow, options) {
1095
1209
  return snapshot.escalation;
1096
1210
  },
1097
1211
  escalation() { return snapshot.escalation; },
1212
+ /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
1213
+ pinJson() { return JSON.stringify(snapshot.pin); },
1098
1214
  /** How many effects the driver admitted. */
1099
1215
  effectCalls() { return journal.effects().length; },
1100
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
1101
- * read and its identity. */
1102
- async annotateHandoff(detail) {
1103
- await persist(() => journal.note("inherited", detail));
1104
- },
1105
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
1106
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
1107
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
1108
- * continuation binds on, does not change. */
1109
- async handoff(spend) {
1110
- guard();
1111
- const row = snapshot.escalation;
1112
- if (!row)
1113
- throw failure("FROZEN_CHECKPOINT_INVALID", "A handoff follows an escalation; none is recorded");
1114
- if (row.cost_usd === spend.cost_usd && row.turns === spend.turns && row.effect_calls === spend.effect_calls)
1115
- return row;
1116
- const detail = { escalation_revision: row.revision, previous_cost_usd: row.cost_usd,
1117
- cost_usd: spend.cost_usd, turns: spend.turns, effect_calls: spend.effect_calls };
1118
- Object.assign(row, spend);
1119
- const write = writeOf();
1120
- await persist(() => journal.save(write.state, { kind: "handoff", detail }, write.parts));
1121
- return row;
1122
- },
1123
1216
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
1124
1217
  * items produced under the map's key: what an escalation on a failure carries. */
1125
1218
  lastState() {
@@ -1178,6 +1271,9 @@ export async function openRecovery(store, workflow, options) {
1178
1271
  const admitted = await persist(() => journal.admit(id, String(params.node.label), argsHash, admission.state, driver, external, params.input ?? null, admission.parts, admission.owner));
1179
1272
  if (admitted !== "new")
1180
1273
  throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id} before dispatch`);
1274
+ // The admission durable before the dispatch, where the host's store needs a barrier for it (afterAdmit).
1275
+ if (options.afterAdmit)
1276
+ await persist(options.afterAdmit);
1181
1277
  // What landed while the admission was being committed still counts: after a cancel, the caller's own
1182
1278
  // cancellation or the effect's deadline, the effect stays admitted and unknown and the adapter is never called.
1183
1279
  // A pause lets it dispatch and complete.
@@ -1225,7 +1321,7 @@ export async function openRecovery(store, workflow, options) {
1225
1321
  }
1226
1322
  if (signal.aborted)
1227
1323
  throw signal.reason;
1228
- const files = fileHashes(params.produces);
1324
+ const files = reader.hashes(params.produces);
1229
1325
  // A tool effect's receipt names the external call it paid for (the tool and its arguments),
1230
1326
  // so a continuation that inherits the receipt can answer the same call from it. Any other
1231
1327
  // effect keeps its arguments beside its result.
@@ -1,4 +1,6 @@
1
+ import { RecoveryError } from "./errors.js";
1
2
  import { type PartialSlot, type Sha256, type StateDelta } from "./item-state.js";
3
+ export declare const failure: (code: string, message: string) => RecoveryError;
2
4
  export declare const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
3
5
  /** The keyed layout: what lies in a map item is kept in that item's record beside the state, and a state the driver
4
6
  * references is kept once by its digest, so no record rewritten at a commit grows with a map's items. */
@@ -33,6 +35,7 @@ export type ItemRecord = {
33
35
  routes: PathFrame["routes"];
34
36
  inputs: PathFrame["inputs"];
35
37
  steps: PathFrame["steps"];
38
+ decisions?: PathFrame["decisions"];
36
39
  };
37
40
  effects: string[];
38
41
  clocks: Record<string, number>;
@@ -55,8 +58,6 @@ export type FrozenSnapshotV4 = Omit<FrozenSnapshot, "schema" | "pin"> & {
55
58
  };
56
59
  maps: Record<string, MapEntry>;
57
60
  };
58
- /** Two values a state holds under one key are the same value. A key an item copied from its base holds the base's own
59
- * object, or one with the same JSON. */
60
61
  /** A map item's state at `path`, rebuilt as the driver rebuilds it (`./item-state.ts`, which imports nothing): the
61
62
  * `agentrun.states` value its `base` names, with the item's `set` and `unset` for that path applied, checked against
62
63
  * that path's `sha256`. `item` is an `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256. When
@@ -93,15 +94,37 @@ export type QuestionReceipts = {
93
94
  * is set in the commit that decides and cleared by the save after the host has written what it keeps of the
94
95
  * answer: a resume that finds it set writes them, so a crash between the two never leaves the spend without
95
96
  * its receipts. A host that keeps nothing commits null. */
97
+ /** `choice` is null and `refused` true for a refused answer, which took the route's unsure branch. */
96
98
  export type RouteDecision = {
97
99
  label: string;
98
100
  branch: string;
99
- choice: string;
101
+ choice: string | null;
100
102
  unsure: boolean;
103
+ refused?: true;
101
104
  request_sha256: string | null;
102
105
  result: Record<string, unknown>;
103
106
  receipts: QuestionReceipts | null;
104
107
  };
108
+ /** A decision's request to the host's judge, as the kernel books a paid request: written and committed before the judge
109
+ * is asked (`requested`), with one outcome after. `answered` and `failed` are written by the process that asked;
110
+ * `interrupted` by a later process that found it still `requested`: the answer, if the provider gave one, was lost with
111
+ * the process, so the decision is never asked again and its cost is unknown (null, never 0). A `failed` request is
112
+ * asked again as its next attempt. */
113
+ export type DecisionRequest = {
114
+ record: "decision.request";
115
+ decision_id: string;
116
+ kind: string;
117
+ label: string;
118
+ /** The model the request named, when it named one. */
119
+ model: string | null;
120
+ /** The digest of what the judge was sent: the kind, the label, the state and the questions. */
121
+ request_sha256: string;
122
+ attempt: number;
123
+ status: "requested" | "answered" | "failed" | "interrupted";
124
+ /** The outcome's spend: absent while requested, null when unknown. */
125
+ cost_usd?: number | null;
126
+ };
127
+ export declare const DECISION_REQUEST = "decision.request";
105
128
  /** What one document's run committed, by execution path. `done` is every committed path in commit
106
129
  * order; `states` keeps the committed state of the paths a resume may still be answered from (a
107
130
  * chain's frontier step, a finished map item or parallel branch whose structure has not committed, a
@@ -122,6 +145,8 @@ export type PathFrame = {
122
145
  routes: Record<string, RouteDecision>;
123
146
  inputs: Record<string, string>;
124
147
  steps: Record<string, StepRecord>;
148
+ /** Each decision node's requests to the judge, by decision id. Absent in a frame written before decisions were kept. */
149
+ decisions?: Record<string, Record<string, DecisionRequest>>;
125
150
  /** A map that ended on an item's failure: the finished items' results, keyed by the map's `as`, so
126
151
  * the handoff carries the completed child work and a redispatch never loses it. */
127
152
  partial?: {
@@ -153,6 +178,10 @@ export type FrozenSnapshot = {
153
178
  unknownResponses?: Record<string, unknown>;
154
179
  /** Spend by question nodes, which have no session of their own: metered per answer, carried with the frames. */
155
180
  questionSpendUsd?: number;
181
+ /** How many question answers came back with no price, so their cost is not in `questionSpendUsd`. A run
182
+ * with any makes its spend read as incomplete, never as a bare total that omits them: an unknown cost is
183
+ * never zero. Carried with the frames and committed in the same save as the spend it stands beside. */
184
+ unpricedQuestionCount?: number;
156
185
  /** The durable form of the escalation that ended the run; set once, reused on resume. */
157
186
  escalation?: EscalationRow;
158
187
  };
@@ -198,6 +227,7 @@ export type FrozenShape = {
198
227
  resolves: (path: string) => boolean;
199
228
  };
200
229
  export declare const emptyPathFrame: () => PathFrame;
230
+ export declare const SHA256: RegExp;
201
231
  /** Whether a value is an item's committed failure: three strings, and nothing else. */
202
232
  export declare const isItemOutcome: (value: unknown) => value is ItemOutcome;
203
233
  /** Refuses a saved snapshot the driver could not have produced for this run. */