@parcha/agentrun-dsl 0.1.0-beta.14 → 0.1.0-beta.140

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 (88) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +155 -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 +41 -1
  16. package/dist/dry-run.js +158 -27
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +169 -0
  20. package/dist/graph.js +433 -0
  21. package/dist/index.d.ts +19 -12
  22. package/dist/index.js +17 -10
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +14 -1
  25. package/dist/job.d.ts +14 -0
  26. package/dist/job.js +5 -0
  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/canonical-hash.d.ts +1 -1
  37. package/dist/recovery/canonical-hash.js +3 -3
  38. package/dist/recovery/driver.d.ts +79 -24
  39. package/dist/recovery/driver.js +634 -78
  40. package/dist/recovery/execution-path.d.ts +8 -0
  41. package/dist/recovery/execution-path.js +14 -0
  42. package/dist/recovery/frozen-snapshot.d.ts +128 -3
  43. package/dist/recovery/frozen-snapshot.js +63 -12
  44. package/dist/recovery/handoff-receipts.d.ts +0 -35
  45. package/dist/recovery/handoff-receipts.js +2 -44
  46. package/dist/recovery/index.d.ts +6 -10
  47. package/dist/recovery/index.js +5 -8
  48. package/dist/recovery/item-state.d.ts +48 -0
  49. package/dist/recovery/item-state.js +89 -0
  50. package/dist/recovery/journal.d.ts +6 -3
  51. package/dist/recovery/journal.js +20 -8
  52. package/dist/recovery/store.d.ts +33 -9
  53. package/dist/recovery/testing/conformance.js +55 -0
  54. package/dist/recovery/with-recovery.d.ts +9 -3
  55. package/dist/recovery/with-recovery.js +78 -18
  56. package/dist/submit-envelope.d.ts +9 -0
  57. package/dist/submit-envelope.js +44 -0
  58. package/dist/system-one.d.ts +37 -2
  59. package/dist/system-one.js +112 -18
  60. package/dist/testing/decision-provider.d.ts +32 -0
  61. package/dist/testing/decision-provider.js +183 -0
  62. package/dist/testing/index.d.ts +1 -0
  63. package/dist/testing/index.js +2 -0
  64. package/dist/vocabulary.d.ts +11 -3
  65. package/dist/vocabulary.js +19 -9
  66. package/dist/workflow-shape.d.ts +7 -0
  67. package/dist/workflow-shape.js +116 -70
  68. package/dist/workflow.d.ts +173 -18
  69. package/dist/workflow.js +1103 -398
  70. package/dist/zod-json-contract.js +6 -8
  71. package/package.json +19 -4
  72. package/schema/workflow.schema.json +366 -1
  73. package/skills/author/SKILL.md +6 -1
  74. package/skills/author/references/jev-decisions.md +50 -5
  75. package/skills/author/references/language.md +19 -14
  76. package/skills/author/references/sdk-authoring.md +2 -0
  77. package/dist/recovery/effect-failure.d.ts +0 -34
  78. package/dist/recovery/effect-failure.js +0 -62
  79. package/dist/recovery/handoff-block.d.ts +0 -36
  80. package/dist/recovery/handoff-block.js +0 -148
  81. package/dist/recovery/handoff-digest.d.ts +0 -58
  82. package/dist/recovery/handoff-digest.js +0 -195
  83. package/dist/recovery/handoff-files.d.ts +0 -54
  84. package/dist/recovery/handoff-files.js +0 -162
  85. package/dist/recovery/handoff-redact.d.ts +0 -12
  86. package/dist/recovery/handoff-redact.js +0 -44
  87. package/dist/recovery/handoff.d.ts +0 -44
  88. package/dist/recovery/handoff.js +0 -46
@@ -32,6 +32,14 @@ export declare function completedIteration(workflow: Workflow, path: string): {
32
32
  loop: string;
33
33
  index: number;
34
34
  } | undefined;
35
+ /** The innermost map item `path` lies in, when it lies in one: the item's own path (`<map>/items/<i>`, a prefix of
36
+ * `path` without the item's `/body`), its map's path and its index. A map's own path lies in the item that holds the
37
+ * map, not in its own items. */
38
+ export declare function mapItemOf(path: string): {
39
+ item: string;
40
+ map: string;
41
+ index: number;
42
+ } | undefined;
35
43
  /** Whether `inner` is `outer` or lies inside it, compared segment by segment. */
36
44
  export declare function isWithin(inner: string, outer: string): boolean;
37
45
  /** The top-level step whose completion `path`'s commit is, or undefined. A top-level step commits at
@@ -111,6 +111,20 @@ export function completedIteration(workflow, path) {
111
111
  }
112
112
  return node && node.node !== "chain" ? innermost : undefined;
113
113
  }
114
+ /** The innermost map item `path` lies in, when it lies in one: the item's own path (`<map>/items/<i>`, a prefix of
115
+ * `path` without the item's `/body`), its map's path and its index. A map's own path lies in the item that holds the
116
+ * map, not in its own items. */
117
+ export function mapItemOf(path) {
118
+ const segments = pathSegments(path);
119
+ if (!segments)
120
+ return undefined;
121
+ for (let i = segments.length - 3; i >= 1; i -= 1) {
122
+ if (segments[i].segment === "items" && INDEX.test(segments[i + 1].segment) && segments[i + 2].segment === "body") {
123
+ return { item: prefix(path, segments, i + 2), map: prefix(path, segments, i), index: Number(segments[i + 1].segment) };
124
+ }
125
+ }
126
+ return undefined;
127
+ }
114
128
  /** Whether `inner` is `outer` or lies inside it, compared segment by segment. */
115
129
  export function isWithin(inner, outer) {
116
130
  const a = pathSegments(inner);
@@ -1,5 +1,85 @@
1
+ import { RecoveryError } from "./errors.js";
2
+ import { type PartialSlot, type Sha256, type StateDelta } from "./item-state.js";
3
+ export declare const failure: (code: string, message: string) => RecoveryError;
1
4
  export declare const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
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
6
+ * references is kept once by its digest, so no record rewritten at a commit grows with a map's items. */
7
+ export declare const FROZEN_SNAPSHOT_SCHEMA_V4 = "agentrun.frozen_run.v4";
2
8
  type State = Record<string, unknown>;
9
+ export { stateDelta, applyStateDelta, canonicalJson, type StateDelta, type Sha256, type PartialSlot } from "./item-state.js";
10
+ /** A map the run started: how many items it has, how many item records were written (always the first ones: items
11
+ * start in order, and an item has a record from its start), and the digest of its base. */
12
+ export type MapEntry = {
13
+ length: number;
14
+ items: number;
15
+ base: string;
16
+ };
17
+ /** One map item's share of the driver's state (`agentrun.items`), keyed by the item's path. Every path in it lies in
18
+ * this item and in no item nested in it. */
19
+ export type ItemRecord = {
20
+ driver: string;
21
+ map: string;
22
+ index: number;
23
+ base: string;
24
+ /** The journal revision of the commit that wrote this value. */
25
+ revision: number;
26
+ /** `failed`: the item ended on its failure, which `outcome` holds; its map collects its items' failures. */
27
+ status: "running" | "committed" | "failed";
28
+ /** Present exactly when `status` is `failed`. */
29
+ outcome?: ItemOutcome;
30
+ frame: {
31
+ done: string[];
32
+ states: Record<string, StateDelta>;
33
+ chains: PathFrame["chains"];
34
+ loops: PathFrame["loops"];
35
+ routes: PathFrame["routes"];
36
+ inputs: PathFrame["inputs"];
37
+ steps: PathFrame["steps"];
38
+ decisions?: PathFrame["decisions"];
39
+ };
40
+ effects: string[];
41
+ clocks: Record<string, number>;
42
+ files: Record<string, string>;
43
+ unknownResponses: Record<string, unknown>;
44
+ /** Maps started inside this item. */
45
+ maps: Record<string, MapEntry>;
46
+ };
47
+ /** The driver's own record in the keyed layout: the v3 snapshot without what lies in map items, its frame's states by
48
+ * digest, and the maps the run started. */
49
+ export type FrozenSnapshotV4 = Omit<FrozenSnapshot, "schema" | "pin"> & {
50
+ schema: typeof FROZEN_SNAPSHOT_SCHEMA_V4;
51
+ pin: Omit<PathFrame, "states" | "partial"> & {
52
+ states: Record<string, string>;
53
+ partial?: {
54
+ path: string;
55
+ as: string;
56
+ results: string;
57
+ };
58
+ };
59
+ maps: Record<string, MapEntry>;
60
+ };
61
+ /** A map item's state at `path`, rebuilt as the driver rebuilds it (`./item-state.ts`, which imports nothing): the
62
+ * `agentrun.states` value its `base` names, with the item's `set` and `unset` for that path applied, checked against
63
+ * that path's `sha256`. `item` is an `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256. When
64
+ * the base is missing, or a digest differs, it says why and never guesses. `sha256` defaults to Node's. */
65
+ export declare function itemState(item: unknown, states: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>, path: string, options?: {
66
+ sha256?: Sha256;
67
+ }): {
68
+ state: State;
69
+ } | {
70
+ unreadable: string;
71
+ };
72
+ /** A failed map's finished results from the driver state's `pin.partial` (`./item-state.ts`, which imports nothing): in
73
+ * the keyed layout, the list of slots and each result read by digest and checked; a whole-state run's list as it is.
74
+ * Each slot is null (the item never finished), `{ result }`, or `{ unreadable }`, never a guess. `sha256` defaults to
75
+ * Node's. */
76
+ export declare function partialResults(partial: unknown, states: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>, options?: {
77
+ sha256?: Sha256;
78
+ }): {
79
+ slots: PartialSlot[];
80
+ } | {
81
+ unreadable: string;
82
+ };
3
83
  /** What a question's receipts need beyond its answer: the request's producer invocation, its size and its
4
84
  * latency. */
5
85
  export type QuestionReceipts = {
@@ -14,15 +94,37 @@ export type QuestionReceipts = {
14
94
  * is set in the commit that decides and cleared by the save after the host has written what it keeps of the
15
95
  * answer: a resume that finds it set writes them, so a crash between the two never leaves the spend without
16
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. */
17
98
  export type RouteDecision = {
18
99
  label: string;
19
100
  branch: string;
20
- choice: string;
101
+ choice: string | null;
21
102
  unsure: boolean;
103
+ refused?: true;
22
104
  request_sha256: string | null;
23
105
  result: Record<string, unknown>;
24
106
  receipts: QuestionReceipts | null;
25
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";
26
128
  /** What one document's run committed, by execution path. `done` is every committed path in commit
27
129
  * order; `states` keeps the committed state of the paths a resume may still be answered from (a
28
130
  * chain's frontier step, a finished map item or parallel branch whose structure has not committed, a
@@ -43,6 +145,8 @@ export type PathFrame = {
43
145
  routes: Record<string, RouteDecision>;
44
146
  inputs: Record<string, string>;
45
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>>;
46
150
  /** A map that ended on an item's failure: the finished items' results, keyed by the map's `as`, so
47
151
  * the handoff carries the completed child work and a redispatch never loses it. */
48
152
  partial?: {
@@ -50,6 +154,15 @@ export type PathFrame = {
50
154
  as: string;
51
155
  results: unknown[];
52
156
  };
157
+ /** The map items that ended on their failure (`onItemFailure: "collect"`), by the item's path (`<map>/items/<i>`): an
158
+ * item here is answered from its row and its body never runs again. Kept with the run, as committed paths are. */
159
+ failures?: Record<string, ItemOutcome>;
160
+ };
161
+ /** How a map item that ended on its failure ended: the failing node's label, the failure's code and its message. */
162
+ export type ItemOutcome = {
163
+ code: string;
164
+ label: string;
165
+ message: string;
53
166
  };
54
167
  /** The recovery driver's durable state. It lives whole in the journal; each commit replaces it. No run
55
168
  * clock: clocks exist only per effect. */
@@ -65,6 +178,10 @@ export type FrozenSnapshot = {
65
178
  unknownResponses?: Record<string, unknown>;
66
179
  /** Spend by question nodes, which have no session of their own: metered per answer, carried with the frames. */
67
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;
68
185
  /** The durable form of the escalation that ended the run; set once, reused on resume. */
69
186
  escalation?: EscalationRow;
70
187
  };
@@ -73,6 +190,12 @@ export type StepRecord = {
73
190
  attempt: number;
74
191
  attemptsAllowed: number;
75
192
  status: "running" | "closed" | "failed" | "submitted";
193
+ /** The failure that failed the step, when it was an item failure (`isItemFailure`) in an item of a map that collects
194
+ * its items' failures: a later open refuses the step with it, so the item ends on the same failure in every process. */
195
+ failure?: {
196
+ code: string;
197
+ message: string;
198
+ };
76
199
  };
77
200
  export type EscalationRow = {
78
201
  kind: string;
@@ -104,6 +227,9 @@ export type FrozenShape = {
104
227
  resolves: (path: string) => boolean;
105
228
  };
106
229
  export declare const emptyPathFrame: () => PathFrame;
230
+ export declare const SHA256: RegExp;
231
+ /** Whether a value is an item's committed failure: three strings, and nothing else. */
232
+ export declare const isItemOutcome: (value: unknown) => value is ItemOutcome;
107
233
  /** Refuses a saved snapshot the driver could not have produced for this run. */
108
234
  export declare function validateFrozenSnapshot(saved: any, shape: FrozenShape): void;
109
235
  /** The snapshot a driver runs under: the saved one (a paused run resumes running, retired keys
@@ -142,8 +268,7 @@ export declare function admitFrozenStep(steps: Record<string, StepRecord>, path:
142
268
  };
143
269
  /** The current attempt ended without a submission: `closed` until a retry is admitted, or
144
270
  * `failed` when the failure is final or no attempt remains. */
145
- export declare function closeFrozenStepAttempt(step: StepRecord, final: boolean): void;
271
+ export declare function closeFrozenStepAttempt(step: StepRecord, final: boolean, failure?: StepRecord["failure"]): void;
146
272
  /** The run-wide stop the driver applies: the host's pause or cancel it was handed, or null when it keeps
147
273
  * running. A cancelled snapshot stays cancelled. */
148
274
  export declare function frozenStop(status: FrozenSnapshot["status"], requested: "pause" | "cancel" | undefined): "paused" | "cancelled" | null;
149
- export {};
@@ -3,15 +3,55 @@
3
3
  // the path grammar, maps nodes onto these records and owns the store's lifecycle.
4
4
  import { createHash } from "node:crypto";
5
5
  import { RecoveryError } from "./errors.js";
6
- const failure = (code, message) => new RecoveryError(message, code);
6
+ import { itemState as rebuildItemState, partialResults as readPartialResults } from "./item-state.js";
7
+ import { isRecord } from "../record.js";
8
+ export const failure = (code, message) => new RecoveryError(message, code);
7
9
  export const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
10
+ /** The keyed layout: what lies in a map item is kept in that item's record beside the state, and a state the driver
11
+ * references is kept once by its digest, so no record rewritten at a commit grows with a map's items. */
12
+ export const FROZEN_SNAPSHOT_SCHEMA_V4 = "agentrun.frozen_run.v4";
13
+ export { stateDelta, applyStateDelta, canonicalJson } from "./item-state.js";
14
+ /** A map item's state at `path`, rebuilt as the driver rebuilds it (`./item-state.ts`, which imports nothing): the
15
+ * `agentrun.states` value its `base` names, with the item's `set` and `unset` for that path applied, checked against
16
+ * that path's `sha256`. `item` is an `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256. When
17
+ * the base is missing, or a digest differs, it says why and never guesses. `sha256` defaults to Node's. */
18
+ export function itemState(item, states, path, options = {}) {
19
+ return rebuildItemState(item, states, path, { sha256: options.sha256 ?? ((text) => createHash("sha256").update(text).digest("hex")) });
20
+ }
21
+ /** A failed map's finished results from the driver state's `pin.partial` (`./item-state.ts`, which imports nothing): in
22
+ * the keyed layout, the list of slots and each result read by digest and checked; a whole-state run's list as it is.
23
+ * Each slot is null (the item never finished), `{ result }`, or `{ unreadable }`, never a guess. `sha256` defaults to
24
+ * Node's. */
25
+ export function partialResults(partial, states, options = {}) {
26
+ return readPartialResults(partial, states, { sha256: options.sha256 ?? ((text) => createHash("sha256").update(text).digest("hex")) });
27
+ }
28
+ export const DECISION_REQUEST = "decision.request";
8
29
  export const emptyPathFrame = () => ({ input: null, done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {} });
9
- const record = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
10
- const SHA256 = /^[a-f0-9]{64}$/;
30
+ export const SHA256 = /^[a-f0-9]{64}$/;
11
31
  /** `value` as an object whose fields can be read, or null. */
12
- const fields = (value) => record(value) ? value : null;
32
+ const fields = (value) => isRecord(value) ? value : null;
13
33
  const entriesOf = (value) => { const object = fields(value); return object ? Object.entries(object) : null; };
34
+ const isStepFailure = (value) => {
35
+ const at = fields(value);
36
+ return Boolean(at && Object.keys(at).length === 2 && typeof at.code === "string" && typeof at.message === "string");
37
+ };
38
+ /** Whether a value is an item's committed failure: three strings, and nothing else. */
39
+ export const isItemOutcome = (value) => {
40
+ const at = fields(value);
41
+ return Boolean(at && Object.keys(at).length === 3 && typeof at.code === "string" && typeof at.label === "string" && typeof at.message === "string");
42
+ };
14
43
  const nonNegativeInt = (value) => Number.isSafeInteger(value) && value >= 0;
44
+ /** Whether `value` is a decision request the driver wrote under `id`: requested with no spend, or ended with its spend or null. */
45
+ const isDecisionRequest = (id, value) => {
46
+ const at = fields(value);
47
+ if (!at || at.record !== DECISION_REQUEST || at.decision_id !== id || typeof at.kind !== "string" || typeof at.label !== "string")
48
+ return false;
49
+ if (!(at.model === null || typeof at.model === "string") || typeof at.request_sha256 !== "string" || !Number.isSafeInteger(at.attempt) || at.attempt < 1)
50
+ return false;
51
+ if (at.status === "requested")
52
+ return at.cost_usd === undefined;
53
+ return ["answered", "failed", "interrupted"].includes(String(at.status)) && (at.cost_usd === null || (typeof at.cost_usd === "number" && Number.isFinite(at.cost_usd) && at.cost_usd >= 0));
54
+ };
15
55
  /** Whether a saved frame is one the driver could have written for its document. */
16
56
  function validFrame(value, resolves) {
17
57
  const frame = fields(value);
@@ -25,13 +65,20 @@ function validFrame(value, resolves) {
25
65
  return false;
26
66
  const [states, chains, loops, routes, inputs, steps] = [frame.states, frame.chains, frame.loops, frame.routes, frame.inputs, frame.steps].map(entriesOf);
27
67
  const partial = frame.partial === undefined ? undefined : fields(frame.partial);
28
- return Boolean(states && states.every(([path, state]) => done.has(path) && record(state))
68
+ const failures = frame.failures === undefined ? [] : entriesOf(frame.failures);
69
+ const decisions = frame.decisions === undefined ? [] : entriesOf(frame.decisions);
70
+ return Boolean(decisions && decisions.every(([path, requests]) => resolves(path) && (entriesOf(requests)?.every(([id, request]) => isDecisionRequest(id, request)) ?? false))
71
+ && states && states.every(([path, state]) => done.has(path) && isRecord(state))
72
+ && failures && failures.every(([item, outcome]) => /\/items\/(?:0|[1-9]\d*)$/.test(item) && resolves(`${item}/body`) && isItemOutcome(outcome))
29
73
  && chains && chains.every(([, head]) => { const at = fields(head); return Boolean(at && nonNegativeInt(at.index) && typeof at.path === "string" && done.has(at.path)); })
30
74
  && loops && loops.every(([loop, count]) => resolves(loop) && nonNegativeInt(count))
31
75
  && routes && routes.every(([route, decision]) => {
32
76
  const at = fields(decision);
33
77
  const receipts = fields(at?.receipts);
34
- return Boolean(at && resolves(route) && typeof at.label === "string" && typeof at.branch === "string" && ((typeof at.choice === "string" && typeof at.unsure === "boolean") || (at.choice === undefined && at.unsure === undefined)) && record(at.result) && (at.request_sha256 === null || typeof at.request_sha256 === "string")
78
+ return Boolean(at && resolves(route) && typeof at.label === "string" && typeof at.branch === "string"
79
+ // A refused route took its unsure branch and chose none: a named branch, a null choice, never "" for either.
80
+ && (at.refused === undefined ? (typeof at.choice === "string" && typeof at.unsure === "boolean") || (at.choice === undefined && at.unsure === undefined) : at.refused === true && at.branch !== "" && at.choice === null && at.unsure === true)
81
+ && isRecord(at.result) && (at.request_sha256 === null || typeof at.request_sha256 === "string")
35
82
  && (at.receipts === null || (receipts && typeof receipts.invocation === "string" && nonNegativeInt(receipts.request_bytes) && Number.isFinite(receipts.latency_ms))));
36
83
  })
37
84
  && inputs && inputs.every(([path, digest]) => resolves(path) && !done.has(path) && typeof digest === "string" && SHA256.test(digest))
@@ -39,19 +86,21 @@ function validFrame(value, resolves) {
39
86
  const at = fields(step);
40
87
  return Boolean(at && resolves(path) && typeof at.label === "string"
41
88
  && nonNegativeInt(at.attempt) && Number.isSafeInteger(at.attemptsAllowed) && at.attemptsAllowed >= 1
42
- && ["running", "closed", "failed", "submitted"].includes(String(at.status)));
89
+ && ["running", "closed", "failed", "submitted"].includes(String(at.status))
90
+ && (at.failure === undefined || (at.status === "failed" && isStepFailure(at.failure))));
43
91
  })
44
92
  && (partial === undefined || (partial && typeof partial.path === "string" && resolves(partial.path) && typeof partial.as === "string" && Array.isArray(partial.results))));
45
93
  }
46
94
  /** Refuses a saved snapshot the driver could not have produced for this run. */
47
95
  export function validateFrozenSnapshot(saved, shape) {
48
- if (!record(saved) || saved.schema !== FROZEN_SNAPSHOT_SCHEMA || !Number.isFinite(saved.startedAt)
96
+ if (!saved || typeof saved !== "object" || Array.isArray(saved) || saved.schema !== FROZEN_SNAPSHOT_SCHEMA || !Number.isFinite(saved.startedAt)
49
97
  || (saved.questionSpendUsd !== undefined && !(Number.isFinite(saved.questionSpendUsd) && saved.questionSpendUsd >= 0))
98
+ || (saved.unpricedQuestionCount !== undefined && !nonNegativeInt(saved.unpricedQuestionCount))
50
99
  || !["running", "paused", "cancelled"].includes(saved.status)
51
- || !record(saved.clocks) || !Object.values(saved.clocks).every(Number.isFinite)
52
- || !record(saved.files) || !Object.values(saved.files).every(value => typeof value === "string" && SHA256.test(value))
100
+ || !isRecord(saved.clocks) || !Object.values(saved.clocks).every(Number.isFinite)
101
+ || !isRecord(saved.files) || !Object.values(saved.files).every(value => typeof value === "string" && SHA256.test(value))
53
102
  || !validFrame(saved.pin, shape.resolves)
54
- || (saved.escalation !== undefined && (!record(saved.escalation) || typeof saved.escalation.tail !== "string" || typeof saved.escalation.kind !== "string" || !Number.isSafeInteger(saved.escalation.revision)))
103
+ || (saved.escalation !== undefined && (!isRecord(saved.escalation) || typeof saved.escalation.tail !== "string" || typeof saved.escalation.kind !== "string" || !Number.isSafeInteger(saved.escalation.revision)))
55
104
  // A checkpoint that holds a second document's frame is refused: the driver runs one document.
56
105
  || saved.adaptation !== undefined) {
57
106
  throw failure("FROZEN_CHECKPOINT_INVALID", "Invalid frozen recovery checkpoint");
@@ -126,8 +175,10 @@ export function admitFrozenStep(steps, path, label, admission) {
126
175
  }
127
176
  /** The current attempt ended without a submission: `closed` until a retry is admitted, or
128
177
  * `failed` when the failure is final or no attempt remains. */
129
- export function closeFrozenStepAttempt(step, final) {
178
+ export function closeFrozenStepAttempt(step, final, failure) {
130
179
  step.status = final || step.attempt + 1 >= step.attemptsAllowed ? "failed" : "closed";
180
+ if (step.status === "failed" && failure)
181
+ step.failure = { code: failure.code, message: failure.message };
131
182
  }
132
183
  /** The run-wide stop the driver applies: the host's pause or cancel it was handed, or null when it keeps
133
184
  * running. A cancelled snapshot stays cancelled. */
@@ -1,38 +1,3 @@
1
- import type { RecoveryEffect, RecoveryIntent } from "./store.js";
2
- /** A completed tool effect a continuation may answer an exact repeat from: the external call it paid for, and its value. */
3
- export type InheritedReceipt = {
4
- id: string;
5
- name: string;
6
- tool: string;
7
- argsHash: string;
8
- result: unknown;
9
- session: string | null;
10
- };
11
- /** An effect whose outcome is unknown: its call is never dispatched again. `intent` is the external call it was admitted
12
- * for, when its journal recorded one. */
13
- export type InheritedUnknown = {
14
- id: string;
15
- name: string;
16
- argsHash: string;
17
- session: string | null;
18
- intent?: RecoveryIntent;
19
- };
20
- /** A tool value that is itself a returned failure: an error envelope (`ok: false`, `isError: true`, `outcome: "error"`) as
21
- * an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
22
- * never prose. */
23
- export declare function returnedFailure(value: unknown): boolean;
24
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
25
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
26
- * failure. */
27
- export declare function inheritableReceipts(effects: readonly RecoveryEffect[]): InheritedReceipt[];
28
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
29
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
30
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
31
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
32
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
33
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
34
- * has none, and is matched by name and hash only. */
35
- export declare function inheritableUnknowns(effects: readonly RecoveryEffect[]): InheritedUnknown[];
36
1
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
37
2
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
38
3
  * The same key is computed for an effect from its receipt's intent. */
@@ -1,53 +1,11 @@
1
1
  import { canonicalHash } from "./canonical-hash.js";
2
- /** A tool value that is itself a returned failure: an error envelope (`ok: false`, `isError: true`, `outcome: "error"`) as
3
- * an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
4
- * never prose. */
5
- export function returnedFailure(value) {
6
- const failed = (parsed) => Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed) && (parsed.ok === false || parsed.isError === true || parsed.outcome === "error"));
7
- if (typeof value !== "string")
8
- return failed(value);
9
- // The envelope may be the whole text (pretty-printed or not) or one line of it with guidance appended; each
10
- // candidate is parsed structurally, never matched as prose.
11
- for (const candidate of [value.trim(), ...value.split("\n").map((line) => line.trim())]) {
12
- if (!candidate.startsWith("{"))
13
- continue;
14
- try {
15
- if (failed(JSON.parse(candidate)))
16
- return true;
17
- }
18
- catch { /* not this candidate */ }
19
- }
20
- return false;
21
- }
22
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
23
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
24
- * failure. */
25
- export function inheritableReceipts(effects) {
26
- return effects.filter((e) => e.status === "completed" && e.result && typeof e.result === "object" && e.result.intent && typeof e.result.intent.tool === "string" && !returnedFailure(e.result.value))
27
- .map((e) => {
28
- const receipt = e.result;
29
- // Keyed as a continuation's own call is: a node that reached the gateway through the fetch wrapper paid for the tool the wrapper names.
30
- const { tool, argsHash } = gatewayIntentOf(receipt.intent.tool, receipt.intent.args ?? {});
31
- return { id: e.id, name: e.name, tool, argsHash, result: receipt.value, session: e.session };
32
- });
33
- }
34
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
35
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
36
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
37
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
38
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
39
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
40
- * has none, and is matched by name and hash only. */
41
- export function inheritableUnknowns(effects) {
42
- return effects.filter((e) => e.status === "unknown").map((e) => ({ id: e.id, name: e.name, argsHash: e.argsHash, session: e.session,
43
- ...(e.intent ? { intent: { tool: e.intent.tool, argsHash: e.intent.argsHash } } : {}) }));
44
- }
2
+ import { isRecord } from "../record.js";
45
3
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
46
4
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
47
5
  * The same key is computed for an effect from its receipt's intent. */
48
6
  export function gatewayIntentOf(name, args) {
49
7
  const a = args;
50
- if (name === "fetch" && a && typeof a === "object" && typeof a.tool === "string" && a.args && typeof a.args === "object" && !Array.isArray(a.args))
8
+ if (name === "fetch" && a && typeof a === "object" && typeof a.tool === "string" && isRecord(a.args))
51
9
  return { tool: a.tool, argsHash: canonicalHash(a.args) };
52
10
  return { tool: name, argsHash: canonicalHash(args ?? {}) };
53
11
  }
@@ -1,18 +1,14 @@
1
- export type { RecoveryBinding, RecoveryEffect, RecoveryIntent, RecoveryJournal, RecoveryNote, RecoveryStore } from "./store.js";
1
+ export type { RecoveryBinding, RecoveryEffect, RecoveryIntent, RecoveryItem, RecoveryJournal, RecoveryNote, RecoveryParts, RecoveryStore } from "./store.js";
2
2
  export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles, type RecoveryEffectParams, type RecoveryFiles, type RecoveryOptions, type RecoveryStop } from "./driver.js";
3
- export { withRecovery, type RecoveryAdapters, type RecoveryDriver, type RecoveryNodeParams, type RecoveryStep, type WithRecoveryOptions } from "./with-recovery.js";
3
+ export { DECISION_REFUSED } from "../decision-receipts.js";
4
+ export { withRecovery, DECISION_INTERRUPTED, type RecoveryAdapters, type RecoveryDriver, type RecoveryNodeParams, type RecoveryStep, type WithRecoveryOptions } from "./with-recovery.js";
4
5
  export { memoryStore } from "./memory-store.js";
5
6
  export { fileStore } from "./file-store.js";
6
7
  export { openJournal, type JournalBackend, type JournalRecord } from "./journal.js";
7
8
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
8
9
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
9
10
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
10
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
11
- export { FROZEN_SNAPSHOT_SCHEMA, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type PathFrame, type RouteDecision, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
12
- export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
13
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
11
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
12
+ export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, frozenStepId, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type DecisionRequest, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
13
+ export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
14
14
  export { effectRetryClass, transportFactOf, type TransportFact } from "./transport-facts.js";
15
- export { buildHandoff, handoffFirstTurn, type Handoff, type HandoffOptions } from "./handoff.js";
16
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
17
- export { inputProvenance, judgedRecords, type InputProvenance } from "./handoff-files.js";
18
- export { type InheritedSession, type InheritedEffect, type TranscriptMessage } from "./handoff-digest.js";
@@ -1,16 +1,13 @@
1
1
  export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles } from "./driver.js";
2
- export { withRecovery } from "./with-recovery.js";
2
+ export { DECISION_REFUSED } from "../decision-receipts.js";
3
+ export { withRecovery, DECISION_INTERRUPTED } from "./with-recovery.js";
3
4
  export { memoryStore } from "./memory-store.js";
4
5
  export { fileStore } from "./file-store.js";
5
6
  export { openJournal } from "./journal.js";
6
7
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
7
8
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
8
9
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
9
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
10
- export { FROZEN_SNAPSHOT_SCHEMA, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
11
- export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
12
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
10
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
11
+ export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, frozenStepId, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
12
+ export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
13
13
  export { effectRetryClass, transportFactOf } from "./transport-facts.js";
14
- export { buildHandoff, handoffFirstTurn } from "./handoff.js";
15
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure } from "./handoff-receipts.js";
16
- export { inputProvenance, judgedRecords } from "./handoff-files.js";
@@ -0,0 +1,48 @@
1
+ type State = Record<string, unknown>;
2
+ /** A committed state inside a map item, against its map's base (the state the map started from): the keys it sets
3
+ * (new, or holding another value than the base's), the base's keys it lacks, and the digest of the whole state, which
4
+ * a rebuild must reach. */
5
+ export type StateDelta = {
6
+ set: State;
7
+ unset: string[];
8
+ sha256: string;
9
+ };
10
+ /** The hex SHA-256 of a text's UTF-8 bytes, synchronous. */
11
+ export type Sha256 = (text: string) => string;
12
+ /** The JSON a state's digest is taken over: every object's keys sorted. */
13
+ export declare function canonicalJson(value: unknown): string;
14
+ /** `state` against `base`, as a map item keeps it. */
15
+ export declare function stateDelta(base: State, state: State, sha256: string): StateDelta;
16
+ /** The state a delta was taken from, in its own key order: the base's keys first (a map item starts from a copy of its
17
+ * base), then the keys it added. */
18
+ export declare function applyStateDelta(base: State, delta: StateDelta): State;
19
+ /** A map item's state at `path`, rebuilt as the driver rebuilds it: the `agentrun.states` value its `base` names, with
20
+ * the item's `set` and `unset` for that path applied, checked against that path's `sha256`. `item` is an
21
+ * `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256; `sha256` hashes a text's UTF-8 bytes.
22
+ * When the base is missing, or a digest differs, it says why and never guesses. */
23
+ export declare function itemState(item: unknown, states: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>, path: string, { sha256 }: {
24
+ sha256: Sha256;
25
+ }): {
26
+ state: State;
27
+ } | {
28
+ unreadable: string;
29
+ };
30
+ /** A slot of a failed map: `null` for an item that never finished, its result, or why it cannot be read. */
31
+ export type PartialSlot = null | {
32
+ result: unknown;
33
+ } | {
34
+ unreadable: string;
35
+ };
36
+ /** A failed map's finished results, read as the driver reads them: `partial` is the driver state's `pin.partial`. In the
37
+ * keyed layout its `results` is one SHA-256 naming the `agentrun.states` value that lists each slot (null, or the
38
+ * SHA-256 of that item's result); `states` holds `agentrun.states` values by SHA-256, and every digest is checked. A
39
+ * whole-state run's `results` is the list itself. A document that is missing or does not match its digest is
40
+ * unreadable, never guessed: the list as a whole, or one slot. */
41
+ export declare function partialResults(partial: unknown, states: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>, { sha256 }: {
42
+ sha256: Sha256;
43
+ }): {
44
+ slots: PartialSlot[];
45
+ } | {
46
+ unreadable: string;
47
+ };
48
+ export {};