@parcha/agentrun-dsl 0.1.0-beta.20 → 0.1.0-beta.200

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 (76) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +141 -21
  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 +19 -10
  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 +1415 -0
  19. package/dist/evidence.d.ts +19 -0
  20. package/dist/evidence.js +63 -0
  21. package/dist/graph.d.ts +91 -5
  22. package/dist/graph.js +212 -10
  23. package/dist/index.d.ts +17 -12
  24. package/dist/index.js +16 -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/predicates.d.ts +29 -0
  30. package/dist/predicates.js +62 -3
  31. package/dist/record.d.ts +4 -0
  32. package/dist/record.js +6 -0
  33. package/dist/recovery/binding.js +2 -1
  34. package/dist/recovery/call-key.d.ts +0 -4
  35. package/dist/recovery/call-key.js +0 -7
  36. package/dist/recovery/driver.d.ts +61 -24
  37. package/dist/recovery/driver.js +193 -68
  38. package/dist/recovery/frozen-snapshot.d.ts +33 -3
  39. package/dist/recovery/frozen-snapshot.js +28 -12
  40. package/dist/recovery/handoff-receipts.d.ts +0 -35
  41. package/dist/recovery/handoff-receipts.js +2 -44
  42. package/dist/recovery/index.d.ts +4 -8
  43. package/dist/recovery/index.js +4 -7
  44. package/dist/recovery/with-recovery.d.ts +9 -3
  45. package/dist/recovery/with-recovery.js +72 -15
  46. package/dist/submit-envelope.d.ts +9 -0
  47. package/dist/submit-envelope.js +44 -0
  48. package/dist/system-one.d.ts +21 -2
  49. package/dist/system-one.js +96 -18
  50. package/dist/testing/decision-provider.d.ts +32 -0
  51. package/dist/testing/decision-provider.js +183 -0
  52. package/dist/testing/index.d.ts +1 -0
  53. package/dist/testing/index.js +2 -0
  54. package/dist/vocabulary.d.ts +11 -3
  55. package/dist/vocabulary.js +18 -8
  56. package/dist/workflow-shape.js +34 -7
  57. package/dist/workflow.d.ts +128 -19
  58. package/dist/workflow.js +772 -238
  59. package/dist/zod-json-contract.js +6 -8
  60. package/package.json +16 -4
  61. package/schema/workflow.schema.json +352 -1
  62. package/skills/author/SKILL.md +4 -1
  63. package/skills/author/references/jev-decisions.md +50 -5
  64. package/skills/author/references/language.md +17 -12
  65. package/dist/recovery/effect-failure.d.ts +0 -34
  66. package/dist/recovery/effect-failure.js +0 -62
  67. package/dist/recovery/handoff-block.d.ts +0 -36
  68. package/dist/recovery/handoff-block.js +0 -148
  69. package/dist/recovery/handoff-digest.d.ts +0 -58
  70. package/dist/recovery/handoff-digest.js +0 -195
  71. package/dist/recovery/handoff-files.d.ts +0 -54
  72. package/dist/recovery/handoff-files.js +0 -162
  73. package/dist/recovery/handoff-redact.d.ts +0 -12
  74. package/dist/recovery/handoff-redact.js +0 -44
  75. package/dist/recovery/handoff.d.ts +0 -44
  76. package/dist/recovery/handoff.js +0 -46
@@ -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)`
@@ -84,7 +92,12 @@ export type RecoveryOptions = {
84
92
  /** What a host's effect adapter receives under the driver: the interpreter's parameters, `call`, which keeps each
85
93
  * outside call the effect makes on its record as the call ends, and `effect`, the admitted effect: its journal id and
86
94
  * the hash of its arguments, as the journal stores them and the same in every process of the run. A host that keeps
87
- * what an outside call answered under them can settle an effect whose call was cut with `journal.complete`. */
95
+ * what an outside call answered under them can settle an effect whose call was cut with `journal.complete`.
96
+ *
97
+ * What the adapter returns is the effect's result, whatever its fields. An adapter that cannot know whether the outside
98
+ * call happened throws: a `RecoveryError` with code `FROZEN_EFFECT_UNKNOWN`, its `cause` what it observed (kept for the
99
+ * operator in the checkpoint's `unknownResponses`), or an `EffectOutcomeUnknownError`. The effect then stays unknown,
100
+ * is never dispatched again, and the run resumes only once the host reconciles it, as after any call that throws. */
88
101
  export type RecoveryEffectParams = Parameters<NonNullable<WorkflowDeps["runEffect"]>>[0] & {
89
102
  call?: (record: unknown) => void;
90
103
  effect?: {
@@ -103,7 +116,13 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
103
116
  wait: (node: import("../workflow.js").CallNode, ms: number, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<void>;
104
117
  fail?: (node: WorkflowNode, results: unknown[], error: unknown, executionPath?: string) => Promise<void>;
105
118
  failItem?: (node: WorkflowNode, failure: import("../workflow.js").MapItemFailure, executionPath?: string) => Promise<void>;
106
- itemFailure?: (node: WorkflowNode, executionPath?: string) => Promise<import("../workflow.js").MapItemFailure | undefined>;
119
+ itemFailure?: (node: WorkflowNode, executionPath
120
+ /** One write in the keyed layout: the driver's record without what lies in map items, the records of the items that
121
+ * changed, and the states first referenced now. `admitting` is an effect admitted in this write; `owner` the item that
122
+ * lists it. */
123
+ ? /** One write in the keyed layout: the driver's record without what lies in map items, the records of the items that
124
+ * changed, and the states first referenced now. `admitting` is an effect admitted in this write; `owner` the item that
125
+ * lists it. */: string) => Promise<import("../workflow.js").MapItemFailure | undefined>;
107
126
  decision?: (id: string) => Promise<import("../decision-receipts.js").DecisionReceipt | undefined>;
108
127
  };
109
128
  signal: AbortSignal;
@@ -162,8 +181,12 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
162
181
  * persistence failure. */
163
182
  charge(usd: number): Promise<void>;
164
183
  /** A question's metered spend, committed with the driver's state so a resume that skips the
165
- * 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
166
- * inside the branch follows it instead of asking again. */
184
+ * finished question still reports it. A priced answer adds to `questionSpendUsd`; an answer with no
185
+ * price (`null`, or a cost that is not a non-negative finite number) is counted in
186
+ * `unpricedQuestionCount` instead, so the run's spend is read as incomplete and never as a bare total
187
+ * that silently omits it: an unknown cost is never zero. A route's answer is its decision: it commits
188
+ * in the same save, once per route path, and a resume inside the branch follows it instead of asking
189
+ * again; its price, priced or not, is recorded the same way. */
167
190
  recordQuestionSpend(usd: number | null, route?: {
168
191
  executionPath: unknown;
169
192
  label: string;
@@ -174,35 +197,49 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
174
197
  * receipts a resume would write. */
175
198
  routeReceipted(executionPath: unknown): void;
176
199
  /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
200
+ /** Moves the poll window of the call node at `executionPath` back by `ms`, the time its host held the call (a pause
201
+ * for a raise of the run's spend cap, which no deadline is for), durably: a later open reads the moved window, and
202
+ * the next effect's check (wrapEffect) and the interpreter's poll start (pollStartedAt) take it. A node with no poll
203
+ * window started, or no time held, moves nothing. `hold` names the hold (the host's id for it): one hold moves the
204
+ * window once, however often a resume reports it again. */
205
+ holdPoll(executionPath: unknown, ms: number, hold: string): void;
177
206
  routeDecision(executionPath: unknown): RouteDecision | undefined;
207
+ /** Every decision request this run committed, by decision id. */
208
+ decisionRequests(): Record<string, DecisionRequest>;
209
+ /** Admits a decision's request before the host's judge is asked, in the driver's next commit, which the caller
210
+ * awaits: a new request, or the next attempt of one that failed in its own process (undefined). A request found
211
+ * in any other status was asked by an earlier process and is returned as it stands; the caller does not ask again.
212
+ * An admitted request is in flight until `decisionSettled`: a pause waits for it, as for an effect. */
213
+ admitDecision(executionPath: unknown, request: Pick<DecisionRequest, "decision_id" | "kind" | "label" | "model" | "request_sha256">): DecisionRequest | undefined;
214
+ /** A request `admitDecision` admitted is no longer in flight. */
215
+ decisionSettled(): void;
216
+ /** Work the host does for a running step outside the driver's records (a model node's request to its model), in
217
+ * flight until the returned release: a pause waits for it, as for an effect, and is taken once it is released. A stop
218
+ * already taken refuses it. Released once; a second release does nothing. */
219
+ hold(): () => void;
220
+ /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
221
+ * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
222
+ * It never applies a stop: a request the run asked ends whatever stops the run. */
223
+ decisionEnded(executionPath: unknown, decisionId: string, status: "answered" | "failed" | "interrupted", cost_usd: number | null, alongside?: () => void): void;
178
224
  /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
179
225
  * as an escalation commit before anything acts on it. A later open gets the same row and the same
180
226
  * continuation identity, whatever fires again. */
181
227
  escalate(row: Omit<EscalationRow, "tail" | "revision">): Promise<EscalationRow>;
182
228
  escalation(): EscalationRow | undefined;
229
+ /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
230
+ pinJson(): string;
183
231
  /** How many effects the driver admitted. */
184
232
  effectCalls(): number;
185
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
186
- * read and its identity. */
187
- annotateHandoff(detail: {
188
- escalation_revision: number;
189
- tail: string;
190
- inherit: string;
191
- block_chars: number;
192
- digest_chars: number;
193
- }): Promise<void>;
194
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
195
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
196
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
197
- * continuation binds on, does not change. */
198
- handoff(spend: Pick<EscalationRow, "cost_usd" | "turns" | "effect_calls">): Promise<EscalationRow>;
199
233
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
200
234
  * items produced under the map's key: what an escalation on a failure carries. */
201
235
  lastState(): Record<string, unknown>;
202
236
  readonly started: boolean;
203
237
  wrapEffect(run: (params: RecoveryEffectParams) => Promise<unknown>): NonNullable<WorkflowDeps["runEffect"]>;
204
- /** Every commit the driver started has landed; a failed one is thrown. */
238
+ /** Every commit the driver started has landed; a failed one is thrown, a pause's or a cancel's own commit included. */
205
239
  flush: () => Promise<void>;
206
- /** Let go of the run once every commit the driver started has landed. */
240
+ /** Let go of the run once every commit the driver started has landed. A commit the store refused after a pause or
241
+ * cancel is thrown once the journal is released: the stop is not durable, and the host must not take the run as
242
+ * stopped. It is thrown even when a later stop's commit lands, since a later commit does not carry every record the
243
+ * refused one held. A run's own failed commit is the run's failure and is not thrown again here. */
207
244
  close(): Promise<void>;
208
245
  }>;
@@ -5,17 +5,22 @@ import fs from "node:fs";
5
5
  import path from "node:path";
6
6
  import { createHash } from "node:crypto";
7
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, isItemOutcome } 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,6 +251,7 @@ 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
256
  && Array.isArray(record.effects) && record.effects.every((id) => typeof id === "string")
250
257
  // An item that ended on its failure, and only one, holds how it ended; its map collects its items' failures.
@@ -258,6 +265,10 @@ export async function openRecovery(store, workflow, options) {
258
265
  lastItems.set(path, JSON.stringify({ ...record, revision: 0 }));
259
266
  frame.done.push(...record.frame.done);
260
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
+ }
261
272
  Object.assign(snapshot.clocks, record.clocks);
262
273
  for (const [name, sha256] of Object.entries(record.files)) {
263
274
  // A committed item keeps the record it last wrote, so a file a later step wrote again holds an older hash there.
@@ -436,6 +447,18 @@ export async function openRecovery(store, workflow, options) {
436
447
  build.record.frame[table][at] = value;
437
448
  }
438
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
+ }
439
462
  const clocks = {};
440
463
  for (const [key, value] of Object.entries(snapshot.clocks)) {
441
464
  const build = own(clockPath(key));
@@ -520,7 +543,7 @@ export async function openRecovery(store, workflow, options) {
520
543
  const frame = snapshot.pin;
521
544
  const done = new Set(frame.done);
522
545
  const paths = [...frame.done, ...Object.keys(frame.states), ...Object.keys(frame.chains), ...Object.keys(frame.inputs), ...Object.keys(frame.steps),
523
- ...Object.keys(frame.loops), ...Object.keys(frame.routes), ...Object.keys(frame.failures ?? {}).map((item) => `${item}/body`)];
546
+ ...Object.keys(frame.loops), ...Object.keys(frame.routes), ...Object.keys(frame.decisions ?? {}), ...Object.keys(frame.failures ?? {}).map((item) => `${item}/body`)];
524
547
  return paths.every((path) => { const at = mapItemOf(path); return !at || done.has(at.map) || Boolean(maps.get(at.map)?.baseState); });
525
548
  };
526
549
  /** One write of the driver's state, in the layout this open keeps. */
@@ -539,14 +562,19 @@ export async function openRecovery(store, workflow, options) {
539
562
  const persist = (write) => {
540
563
  const next = chain.then(() => { if (fatal && !stopping)
541
564
  throw fatal; return write(); });
542
- chain = next.catch((error) => { if (!fatal) {
543
- fatal = error;
544
- controller.abort(error);
545
- } });
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
+ });
546
573
  return next;
547
574
  };
548
- /** Every commit the driver started has landed; a failed one is thrown. */
549
- 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)
550
578
  throw fatal; };
551
579
  try {
552
580
  // A driver an earlier process bound, with no checkpoint, is a run killed between its binding and its first
@@ -558,7 +586,7 @@ export async function openRecovery(store, workflow, options) {
558
586
  const known = [FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4];
559
587
  const found = stored?.schema;
560
588
  const version = typeof found === "string" ? /^agentrun\.frozen_run\.v(\d+)$/.exec(found)?.[1] : undefined;
561
- if (version !== undefined && !known.includes(found) && Number(version) > 4) {
589
+ if (version !== undefined && Number(version) > 4) {
562
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 });
563
591
  }
564
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
@@ -688,9 +716,8 @@ export async function openRecovery(store, workflow, options) {
688
716
  }
689
717
  wake();
690
718
  };
691
- const fileHashes = (names) => reader.hashes(names);
692
719
  const verifyFiles = (files) => {
693
- if (hash(fileHashes(Object.keys(files))) !== hash(files))
720
+ if (hash(reader.hashes(Object.keys(files))) !== hash(files))
694
721
  throw failure("FROZEN_ARTIFACT_INVALID", "Committed artifact bytes changed; effect will not be repeated");
695
722
  };
696
723
  /** An effect-level clock is set once and kept across resume: a poll window or an attempt deadline
@@ -724,6 +751,14 @@ export async function openRecovery(store, workflow, options) {
724
751
  throw pathFault(at, "The interpreter named a path this run's document does not hold");
725
752
  return at;
726
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
+ };
727
762
  /** The committed state a resume at `at` is answered from: its own, or the frontier of a chain it sits
728
763
  * in when the frontier lies past it. A chain threads one state, so every step before its frontier,
729
764
  * and everything inside those steps, is answered with the frontier's. */
@@ -738,7 +773,8 @@ export async function openRecovery(store, workflow, options) {
738
773
  return undefined;
739
774
  };
740
775
  /** Drops what no resume can ask for again: the states, chain frontiers, loop counts, route decisions
741
- * and start bindings of the paths `gone` names. Step records stay: a host reads its sessions from them; and so do
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
742
778
  * failed items, as committed paths do: a map that commits in the write that moves its run writes its items' records
743
779
  * then, a failed one's with its outcome. */
744
780
  const prune = (frame, gone) => {
@@ -823,7 +859,7 @@ export async function openRecovery(store, workflow, options) {
823
859
  if (step && (frame.chains[step.chain]?.index ?? -1) >= step.index)
824
860
  throw pathFault(at, "A chain step committed behind its chain's frontier");
825
861
  if (node.node === "artifact" && node.path)
826
- keepFiles(fileHashes([node.path]), at);
862
+ keepFiles(reader.hashes([node.path]), at);
827
863
  frame.done.push(at);
828
864
  done.add(at);
829
865
  // A map that committed, alone or inside what committed, has its results in the state: what it had finished
@@ -897,8 +933,9 @@ export async function openRecovery(store, workflow, options) {
897
933
  // The wait's clock is durable before the wait starts, so a process that dies inside it resumes the same wait.
898
934
  await flush();
899
935
  await new Promise((resolve, reject) => {
900
- const onAbort = () => { clearTimeout(wait); reject(controller.signal.reason); };
901
- 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());
902
939
  controller.signal.addEventListener("abort", onAbort, { once: true });
903
940
  });
904
941
  guard();
@@ -1024,15 +1061,17 @@ export async function openRecovery(store, workflow, options) {
1024
1061
  await flush();
1025
1062
  },
1026
1063
  /** A question's metered spend, committed with the driver's state so a resume that skips the
1027
- * 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
1028
- * 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. */
1029
1070
  recordQuestionSpend(usd, route) {
1030
1071
  guard();
1031
- let changed = false;
1032
- if (usd !== null && Number.isFinite(usd) && usd >= 0) {
1033
- snapshot.questionSpendUsd = +((snapshot.questionSpendUsd ?? 0) + usd).toFixed(8);
1034
- changed = true;
1035
- }
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;
1036
1075
  if (route) {
1037
1076
  const { frame, doc } = active();
1038
1077
  const at = placed(route.executionPath, doc);
@@ -1041,11 +1080,18 @@ export async function openRecovery(store, workflow, options) {
1041
1080
  throw pathFault(at, "Only a route's answer is a decision");
1042
1081
  if (frame.routes[at])
1043
1082
  throw pathFault(at, "A route is decided once");
1044
- 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 };
1045
- 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 } };
1046
1087
  }
1047
- if (changed)
1048
- 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();
1049
1095
  },
1050
1096
  /** The host has written what it keeps of the route at `executionPath`: its decision no longer carries the
1051
1097
  * receipts a resume would write. */
@@ -1059,10 +1105,86 @@ export async function openRecovery(store, workflow, options) {
1059
1105
  save();
1060
1106
  },
1061
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
+ },
1062
1124
  routeDecision(executionPath) {
1063
1125
  const { frame, doc } = active();
1064
1126
  return frame.routes[placed(executionPath, doc)];
1065
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
+ /** Work the host does for a running step outside the driver's records (a model node's request to its model), in
1155
+ * flight until the returned release: a pause waits for it, as for an effect, and is taken once it is released. A stop
1156
+ * already taken refuses it. Released once; a second release does nothing. */
1157
+ hold() {
1158
+ guard();
1159
+ inFlight += 1;
1160
+ let released = false;
1161
+ return () => {
1162
+ if (released)
1163
+ return;
1164
+ released = true;
1165
+ settled();
1166
+ };
1167
+ },
1168
+ /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
1169
+ * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
1170
+ * It never applies a stop: a request the run asked ends whatever stops the run. */
1171
+ decisionEnded(executionPath, decisionId, status, cost_usd, alongside) {
1172
+ if (fatal)
1173
+ throw fatal;
1174
+ const { frame, doc } = active();
1175
+ const request = frame.decisions?.[decisionPlace(executionPath, doc)]?.[decisionId];
1176
+ if (!request)
1177
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The decision ${decisionId} ends without its request`);
1178
+ if (request.status !== "requested")
1179
+ throw failure("FROZEN_CHECKPOINT_INVALID", `The decision ${decisionId} ends once`);
1180
+ Object.assign(request, { status, cost_usd });
1181
+ try {
1182
+ alongside?.();
1183
+ }
1184
+ finally {
1185
+ save();
1186
+ }
1187
+ },
1066
1188
  /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
1067
1189
  * as an escalation commit before anything acts on it. A later open gets the same row and the same
1068
1190
  * continuation identity, whatever fires again. */
@@ -1085,31 +1207,10 @@ export async function openRecovery(store, workflow, options) {
1085
1207
  return snapshot.escalation;
1086
1208
  },
1087
1209
  escalation() { return snapshot.escalation; },
1210
+ /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
1211
+ pinJson() { return JSON.stringify(snapshot.pin); },
1088
1212
  /** How many effects the driver admitted. */
1089
1213
  effectCalls() { return journal.effects().length; },
1090
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
1091
- * read and its identity. */
1092
- async annotateHandoff(detail) {
1093
- await persist(() => journal.note("inherited", detail));
1094
- },
1095
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
1096
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
1097
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
1098
- * continuation binds on, does not change. */
1099
- async handoff(spend) {
1100
- guard();
1101
- const row = snapshot.escalation;
1102
- if (!row)
1103
- throw failure("FROZEN_CHECKPOINT_INVALID", "A handoff follows an escalation; none is recorded");
1104
- if (row.cost_usd === spend.cost_usd && row.turns === spend.turns && row.effect_calls === spend.effect_calls)
1105
- return row;
1106
- const detail = { escalation_revision: row.revision, previous_cost_usd: row.cost_usd,
1107
- cost_usd: spend.cost_usd, turns: spend.turns, effect_calls: spend.effect_calls };
1108
- Object.assign(row, spend);
1109
- const write = writeOf();
1110
- await persist(() => journal.save(write.state, { kind: "handoff", detail }, write.parts));
1111
- return row;
1112
- },
1113
1214
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
1114
1215
  * items produced under the map's key: what an escalation on a failure carries. */
1115
1216
  lastState() {
@@ -1161,12 +1262,16 @@ export async function openRecovery(store, workflow, options) {
1161
1262
  // From its admission the effect is in flight: a pause waits for it to complete and commit, so the admission is
1162
1263
  // never left without its dispatch.
1163
1264
  inFlight += 1;
1265
+ let deadlineTimer;
1164
1266
  try {
1165
1267
  // The driver's state and the admission are one transaction.
1166
1268
  const admission = writeOf(id);
1167
1269
  const admitted = await persist(() => journal.admit(id, String(params.node.label), argsHash, admission.state, driver, external, params.input ?? null, admission.parts, admission.owner));
1168
1270
  if (admitted !== "new")
1169
1271
  throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id} before dispatch`);
1272
+ // The admission durable before the dispatch, where the host's store needs a barrier for it (afterAdmit).
1273
+ if (options.afterAdmit)
1274
+ await persist(options.afterAdmit);
1170
1275
  // What landed while the admission was being committed still counts: after a cancel, the caller's own
1171
1276
  // cancellation or the effect's deadline, the effect stays admitted and unknown and the adapter is never called.
1172
1277
  // A pause lets it dispatch and complete.
@@ -1175,7 +1280,15 @@ export async function openRecovery(store, workflow, options) {
1175
1280
  throw params.signal.reason;
1176
1281
  if (Date.now() >= deadline)
1177
1282
  throw failure("FROZEN_EFFECT_DEADLINE", "Effect exceeded its own deadline");
1178
- const signal = AbortSignal.any([params.signal, controller.signal, AbortSignal.timeout(Math.max(1, deadline - Date.now()))]);
1283
+ // 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
1284
+ // limit, waits out its time; it aborts with the TimeoutError AbortSignal.timeout gives, which a host reads as a deadline.
1285
+ const timeout = new AbortController();
1286
+ deadlineTimer = setLongTimeout(() => timeout.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError")), deadline - Date.now());
1287
+ const signal = AbortSignal.any([params.signal, controller.signal, timeout.signal]);
1288
+ // Clear the deadline timer the moment the effect is aborted (a cancel, a pause, or the deadline itself): a
1289
+ // `runEffect` that ignores its signal and stays pending would otherwise leave this process alive until the
1290
+ // deadline — hours or days out — because the `finally` runs only when the dispatch settles.
1291
+ signal.addEventListener("abort", () => deadlineTimer?.clear(), { once: true });
1179
1292
  // A thrown/aborted call remains UNKNOWN, including transient failures: no blind retry. Each outside call the effect
1180
1293
  // makes is kept on its record as it ends, on the driver's commit chain, so a process killed mid-effect keeps the
1181
1294
  // calls it made and a commit that fails is the run's failure, which aborts the effect at once.
@@ -1185,21 +1298,28 @@ export async function openRecovery(store, workflow, options) {
1185
1298
  try {
1186
1299
  value = await run({ ...params, signal, call: keep, effect: { id, argsHash } });
1187
1300
  }
1301
+ catch (error) {
1302
+ // The host's one signal that it cannot know the outcome: what it observed is kept for the operator, without
1303
+ // certifying completion. Any other throw leaves the effect unknown too, with nothing observed.
1304
+ if (error instanceof RecoveryError && error.code === "FROZEN_EFFECT_UNKNOWN") {
1305
+ if (calls.length)
1306
+ await flush();
1307
+ if (error.cause !== undefined) {
1308
+ (snapshot.unknownResponses ??= {})[id] = error.cause;
1309
+ await save();
1310
+ await flush();
1311
+ }
1312
+ throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id}: the host reported an unknown outcome`);
1313
+ }
1314
+ throw error;
1315
+ }
1188
1316
  finally {
1189
1317
  if (calls.length)
1190
1318
  await flush();
1191
1319
  }
1192
1320
  if (signal.aborted)
1193
1321
  throw signal.reason;
1194
- const returned = value;
1195
- if (returned?.outcome === "unknown" || returned?.effect_status === "unknown"
1196
- || returned?.details?.outcome === "unknown" || returned?.details?.effect_status === "unknown") {
1197
- (snapshot.unknownResponses ??= {})[id] = value;
1198
- await save(); // Preserve the observation without certifying completion.
1199
- await flush();
1200
- throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id}: tool returned an unknown outcome`);
1201
- }
1202
- const files = fileHashes(params.produces);
1322
+ const files = reader.hashes(params.produces);
1203
1323
  // A tool effect's receipt names the external call it paid for (the tool and its arguments),
1204
1324
  // so a continuation that inherits the receipt can answer the same call from it. Any other
1205
1325
  // effect keeps its arguments beside its result.
@@ -1210,13 +1330,18 @@ export async function openRecovery(store, workflow, options) {
1210
1330
  return value;
1211
1331
  }
1212
1332
  finally {
1333
+ deadlineTimer?.clear();
1213
1334
  settled();
1214
1335
  }
1215
1336
  };
1216
1337
  },
1217
- /** Every commit the driver started has landed; a failed one is thrown. */
1338
+ /** Every commit the driver started has landed; a failed one is thrown, a pause's or a cancel's own commit included. */
1218
1339
  flush,
1219
- /** Let go of the run once every commit the driver started has landed. */
1220
- async close() { await chain; await journal.close(); },
1340
+ /** Let go of the run once every commit the driver started has landed. A commit the store refused after a pause or
1341
+ * cancel is thrown once the journal is released: the stop is not durable, and the host must not take the run as
1342
+ * stopped. It is thrown even when a later stop's commit lands, since a later commit does not carry every record the
1343
+ * refused one held. A run's own failed commit is the run's failure and is not thrown again here. */
1344
+ async close() { await chain; await journal.close(); if (refusedAfterStop !== undefined)
1345
+ throw refusedAfterStop; },
1221
1346
  };
1222
1347
  }