@parcha/agentrun-dsl 0.1.0-beta.5 → 0.1.0-beta.50

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 (94) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +167 -23
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +13 -5
  6. package/dist/author.js +38 -19
  7. package/dist/authoring.js +2 -2
  8. package/dist/cli.js +17 -12
  9. package/dist/code-exec.d.ts +6 -0
  10. package/dist/code-exec.js +126 -0
  11. package/dist/decision-provider.d.ts +165 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +159 -0
  14. package/dist/decision-receipts.js +93 -0
  15. package/dist/dry-run.d.ts +45 -2
  16. package/dist/dry-run.js +157 -26
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +62 -0
  19. package/dist/graph.d.ts +169 -0
  20. package/dist/graph.js +433 -0
  21. package/dist/index.d.ts +19 -11
  22. package/dist/index.js +16 -9
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +16 -3
  25. package/dist/job.d.ts +14 -0
  26. package/dist/job.js +5 -0
  27. package/dist/long-timer.d.ts +7 -0
  28. package/dist/long-timer.js +22 -0
  29. package/dist/observer-snapshot.d.ts +3 -0
  30. package/dist/observer-snapshot.js +46 -0
  31. package/dist/predicates.d.ts +32 -0
  32. package/dist/predicates.js +61 -0
  33. package/dist/recovery/binding.d.ts +10 -0
  34. package/dist/recovery/binding.js +43 -0
  35. package/dist/recovery/call-key.d.ts +9 -0
  36. package/dist/recovery/call-key.js +17 -0
  37. package/dist/recovery/canonical-hash.d.ts +7 -0
  38. package/dist/recovery/canonical-hash.js +22 -0
  39. package/dist/recovery/driver.d.ts +235 -0
  40. package/dist/recovery/driver.js +1333 -0
  41. package/dist/recovery/errors.d.ts +31 -0
  42. package/dist/recovery/errors.js +51 -0
  43. package/dist/recovery/execution-path.d.ts +53 -0
  44. package/dist/recovery/execution-path.js +167 -0
  45. package/dist/recovery/file-store.d.ts +7 -0
  46. package/dist/recovery/file-store.js +131 -0
  47. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  48. package/dist/recovery/frozen-snapshot.js +187 -0
  49. package/dist/recovery/handoff-receipts.d.ts +7 -0
  50. package/dist/recovery/handoff-receipts.js +10 -0
  51. package/dist/recovery/index.d.ts +14 -0
  52. package/dist/recovery/index.js +13 -0
  53. package/dist/recovery/item-state.d.ts +48 -0
  54. package/dist/recovery/item-state.js +89 -0
  55. package/dist/recovery/journal.d.ts +28 -0
  56. package/dist/recovery/journal.js +139 -0
  57. package/dist/recovery/memory-store.d.ts +4 -0
  58. package/dist/recovery/memory-store.js +20 -0
  59. package/dist/recovery/store.d.ts +105 -0
  60. package/dist/recovery/store.js +6 -0
  61. package/dist/recovery/testing/conformance.d.ts +4 -0
  62. package/dist/recovery/testing/conformance.js +268 -0
  63. package/dist/recovery/testing/crash-points.d.ts +18 -0
  64. package/dist/recovery/testing/crash-points.js +43 -0
  65. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  66. package/dist/recovery/testing/crash-sweep.js +146 -0
  67. package/dist/recovery/testing/index.d.ts +3 -0
  68. package/dist/recovery/testing/index.js +4 -0
  69. package/dist/recovery/testing/preload.d.ts +1 -0
  70. package/dist/recovery/testing/preload.js +3 -0
  71. package/dist/recovery/transport-facts.d.ts +23 -0
  72. package/dist/recovery/transport-facts.js +46 -0
  73. package/dist/recovery/with-recovery.d.ts +50 -0
  74. package/dist/recovery/with-recovery.js +144 -0
  75. package/dist/submit-envelope.d.ts +9 -0
  76. package/dist/submit-envelope.js +43 -0
  77. package/dist/system-one.d.ts +40 -2
  78. package/dist/system-one.js +132 -12
  79. package/dist/testing/decision-provider.d.ts +32 -0
  80. package/dist/testing/decision-provider.js +183 -0
  81. package/dist/testing/index.d.ts +1 -0
  82. package/dist/testing/index.js +2 -0
  83. package/dist/vocabulary.d.ts +19 -3
  84. package/dist/vocabulary.js +31 -10
  85. package/dist/workflow-shape.d.ts +7 -0
  86. package/dist/workflow-shape.js +115 -69
  87. package/dist/workflow.d.ts +269 -29
  88. package/dist/workflow.js +1453 -439
  89. package/package.json +27 -4
  90. package/schema/workflow.schema.json +497 -12
  91. package/skills/author/SKILL.md +6 -1
  92. package/skills/author/references/jev-decisions.md +69 -12
  93. package/skills/author/references/language.md +28 -20
  94. package/skills/author/references/sdk-authoring.md +2 -0
@@ -0,0 +1,46 @@
1
+ import { isProxy } from "node:util/types";
2
+ /** Copy observation data without reading accessors or sharing mutable data objects.
3
+ * Keep invalid JSON shapes visible so required host trace validation can reject them. */
4
+ export function observerSnapshot(value) {
5
+ const seen = new Map();
6
+ const pending = [];
7
+ const copy = (item) => {
8
+ // A proxy can execute code even when its property descriptors are inspected.
9
+ if (isProxy(item))
10
+ return function unavailable() { };
11
+ if (item === null || typeof item !== "object") {
12
+ // Functions are invalid observation data; an inert function preserves that
13
+ // fact without giving an observer the original callable or its properties.
14
+ return typeof item === "function" ? function unavailable() { } : item;
15
+ }
16
+ const known = seen.get(item);
17
+ if (known)
18
+ return known;
19
+ const prototype = Object.getPrototypeOf(item);
20
+ if (prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null)
21
+ return function unavailable() { };
22
+ const target = Array.isArray(item) ? [] : Object.create(prototype);
23
+ seen.set(item, target);
24
+ pending.push([item, target]);
25
+ return target;
26
+ };
27
+ const result = copy(value);
28
+ while (pending.length) {
29
+ const [source, target] = pending.pop();
30
+ for (const key of Reflect.ownKeys(source)) {
31
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
32
+ if ("value" in descriptor)
33
+ descriptor.value = copy(descriptor.value);
34
+ else {
35
+ // Never invoke authored getters, including during cloning. Their shape
36
+ // remains an accessor so a JSON-validating host still fails closed.
37
+ if (descriptor.get)
38
+ descriptor.get = () => undefined;
39
+ if (descriptor.set)
40
+ descriptor.set = () => { };
41
+ }
42
+ Object.defineProperty(target, key, descriptor);
43
+ }
44
+ }
45
+ return result;
46
+ }
@@ -1,3 +1,4 @@
1
+ import { type FieldType } from "./vocabulary.js";
1
2
  export type StopPredicate = {
2
3
  predicate: "no_new_items";
3
4
  key: string;
@@ -28,6 +29,24 @@ export type AcceptPredicate = StopPredicate | {
28
29
  predicate: "in";
29
30
  path: string;
30
31
  values: Array<string | number | boolean>;
32
+ } | {
33
+ predicate: "field_type";
34
+ path: string;
35
+ type: FieldType;
36
+ } | QuoteMissingPredicate | NotPredicate;
37
+ /** Holds when a quote at `path` is in none of the page text at `pages`. `path` names a quote (a string) or a list of them;
38
+ * with `field`, a list (or one record) of records, each holding its quote at `field`. Each of `pages` names a state value
39
+ * this run wrote, a call's result most often: every string under it is page text. */
40
+ export type QuoteMissingPredicate = {
41
+ predicate: "quote_missing";
42
+ path: string;
43
+ field?: string;
44
+ pages: string[];
45
+ };
46
+ /** Holds when `of` does not. `of` is mechanical: a judged question never sits inside a negation. */
47
+ export type NotPredicate = {
48
+ predicate: "not";
49
+ of: AcceptPredicate;
31
50
  };
32
51
  export declare const MECHANICAL_PREDICATE_NAMES: ReadonlySet<string>;
33
52
  /** Resolve a dotted state path the one way every reader does: a record by key, an array by a
@@ -35,4 +54,17 @@ export declare const MECHANICAL_PREDICATE_NAMES: ReadonlySet<string>;
35
54
  * `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
36
55
  * path that names a value for one names it for all. */
37
56
  export declare function getPath(value: unknown, key: string): unknown;
57
+ /** A quote shorter than this, normalised, is not checked: too short to say which page it came from. */
58
+ export declare const QUOTE_MIN_CHARS = 8;
59
+ /** A quote or a page as quote_missing compares them: lowercase, curly quotes straight, en and em dashes "-", each run of
60
+ * whitespace one space, trimmed. */
61
+ export declare const quoteText: (text: string) => string;
62
+ /** quote_missing's reading of `value`: how many quotes it checked (each at least QUOTE_MIN_CHARS once normalised) and how
63
+ * many of them are in no page. A quote is found when its normalised text is in one page string's (each string under the
64
+ * pages read alone, so no quote runs from one into the next), or when its letters and digits are in that string's; the
65
+ * pages are only what `value` holds, the run's own state. Counts alone: no quote or page text leaves here. */
66
+ export declare function quoteCheck(predicate: QuoteMissingPredicate, value: unknown): {
67
+ checked: number;
68
+ missed: number;
69
+ };
38
70
  export declare function predicateMatches(predicate: StopPredicate | AcceptPredicate, value: unknown): boolean;
@@ -24,6 +24,60 @@ export function getPath(value, key) {
24
24
  return undefined;
25
25
  }, value);
26
26
  }
27
+ /** Whether a value is of a JSON type. A number is a finite one, and an absent value is of no type. */
28
+ function hasType(value, type) {
29
+ switch (type) {
30
+ case "number": return typeof value === "number" && Number.isFinite(value);
31
+ case "string": return typeof value === "string";
32
+ case "boolean": return typeof value === "boolean";
33
+ case "array": return Array.isArray(value);
34
+ case "object": return isRecord(value);
35
+ case "null": return value === null;
36
+ default:
37
+ throw new Error(`agentrun: unsupported field_type type "${String(type)}" — fail closed, never silently false`);
38
+ }
39
+ }
40
+ /** A quote shorter than this, normalised, is not checked: too short to say which page it came from. */
41
+ export const QUOTE_MIN_CHARS = 8;
42
+ const QUOTE_MARKS = { "‘": "'", "’": "'", "“": "\"", "”": "\"", "–": "-", "—": "-" };
43
+ /** A quote or a page as quote_missing compares them: lowercase, curly quotes straight, en and em dashes "-", each run of
44
+ * whitespace one space, trimmed. */
45
+ export const quoteText = (text) => text.toLowerCase().replace(/[‘’“”–—]/g, (mark) => QUOTE_MARKS[mark]).replace(/\s+/g, " ").trim();
46
+ /** The looser reading: the letters and digits of `text` alone, each run joined by one space. */
47
+ const quoteTokens = (text) => (text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []).join(" ");
48
+ /** How deep under a page path strings are read: past it a value is no page. */
49
+ const PAGE_DEPTH = 64;
50
+ function pageStrings(value, out, depth = 0) {
51
+ if (typeof value === "string")
52
+ out.push(value);
53
+ else if (depth < PAGE_DEPTH && value !== null && typeof value === "object")
54
+ for (const inner of Array.isArray(value) ? value : Object.values(value))
55
+ pageStrings(inner, out, depth + 1);
56
+ }
57
+ function quotesAt(value, field) {
58
+ if (field === undefined)
59
+ return typeof value === "string" ? [value] : Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
60
+ const records = Array.isArray(value) ? value : isRecord(value) ? [value] : [];
61
+ return records.map((record) => getPath(record, field)).filter((quote) => typeof quote === "string");
62
+ }
63
+ /** quote_missing's reading of `value`: how many quotes it checked (each at least QUOTE_MIN_CHARS once normalised) and how
64
+ * many of them are in no page. A quote is found when its normalised text is in one page string's (each string under the
65
+ * pages read alone, so no quote runs from one into the next), or when its letters and digits are in that string's; the
66
+ * pages are only what `value` holds, the run's own state. Counts alone: no quote or page text leaves here. */
67
+ export function quoteCheck(predicate, value) {
68
+ const quotes = quotesAt(getPath(value, predicate.path), predicate.field).map(quoteText).filter((quote) => quote.length >= QUOTE_MIN_CHARS);
69
+ if (!quotes.length)
70
+ return { checked: 0, missed: 0 };
71
+ const strings = [];
72
+ for (const page of predicate.pages)
73
+ pageStrings(getPath(value, page), strings);
74
+ const texts = strings.map((string) => { const text = quoteText(string); return { text, tokens: quoteTokens(text) }; });
75
+ const missed = quotes.filter((quote) => {
76
+ const loose = quoteTokens(quote);
77
+ return !texts.some(({ text, tokens }) => text.includes(quote) || (loose !== "" && tokens.includes(loose)));
78
+ }).length;
79
+ return { checked: quotes.length, missed };
80
+ }
27
81
  export function predicateMatches(predicate, value) {
28
82
  switch (predicate.predicate) {
29
83
  case "field_equals":
@@ -54,6 +108,13 @@ export function predicateMatches(predicate, value) {
54
108
  return false;
55
109
  return predicate.predicate === "gte" ? target >= predicate.n : target < predicate.n;
56
110
  }
111
+ case "field_type":
112
+ return hasType(getPath(value, predicate.path), predicate.type);
113
+ case "quote_missing":
114
+ return quoteCheck(predicate, value).missed > 0;
115
+ case "not":
116
+ // A judged `of` reaches the default case below and throws: validation refuses it first.
117
+ return !predicateMatches(predicate.of, value);
57
118
  default:
58
119
  throw new Error(`agentrun: unsupported predicate "${String(predicate?.predicate ?? "")}" — fail closed, never silently false`);
59
120
  }
@@ -0,0 +1,10 @@
1
+ import { RecoveryError } from "./errors.js";
2
+ /** The digest of each input a binding covers, named by its path: one entry per key of `parts`, and
3
+ * one per key of a part that is itself an object ("config.question", "binding.budget"). Stored beside
4
+ * the binding, they let a mismatch name the inputs that moved instead of only saying one did. */
5
+ export declare function bindingDigests(parts: Record<string, unknown>): Record<string, string>;
6
+ /** Why a store refuses a binding: the inputs whose digests differ from the ones it was bound with. */
7
+ export declare function bindingMismatch(stored: string | null, given: Record<string, string> | undefined): RecoveryError;
8
+ /** The format of what a run's store holds for a resume. Every binding carries it, so a store written under
9
+ * another format is refused, never resumed as if it held the same record. */
10
+ export declare const LEDGER_FORMAT = 3;
@@ -0,0 +1,43 @@
1
+ // A run's binding: what a durable record of the run was opened under. A binding is the hash of the host's inputs; its
2
+ // per-input digests let a refused open name the inputs that moved.
3
+ import { canonicalHash } from "./canonical-hash.js";
4
+ import { RecoveryError } from "./errors.js";
5
+ /** The digest of each input a binding covers, named by its path: one entry per key of `parts`, and
6
+ * one per key of a part that is itself an object ("config.question", "binding.budget"). Stored beside
7
+ * the binding, they let a mismatch name the inputs that moved instead of only saying one did. */
8
+ export function bindingDigests(parts) {
9
+ // An omitted input has no digest, as the binding's own JSON omits it: a change between omitted and
10
+ // null is then named as an input that is new or gone.
11
+ const digests = {};
12
+ for (const [name, value] of Object.entries(parts)) {
13
+ if (value === undefined)
14
+ continue;
15
+ if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length) {
16
+ for (const [key, inner] of Object.entries(value))
17
+ if (inner !== undefined)
18
+ digests[`${name}.${key}`] = canonicalHash(inner);
19
+ }
20
+ else
21
+ digests[name] = canonicalHash(value);
22
+ }
23
+ return digests;
24
+ }
25
+ /** Why a store refuses a binding: the inputs whose digests differ from the ones it was bound with. */
26
+ export function bindingMismatch(stored, given) {
27
+ let recorded = null;
28
+ try {
29
+ recorded = stored ? JSON.parse(stored) : null;
30
+ }
31
+ catch {
32
+ recorded = null;
33
+ }
34
+ if (!recorded || !given) {
35
+ return Object.assign(new RecoveryError(`Run store binding mismatch: ${!recorded ? "the store was bound before its input digests were recorded" : "the opener named no input digests"}, so the input that moved cannot be named`, "RUN_STORE_BINDING_MISMATCH"), { moved: null });
36
+ }
37
+ const moved = [...new Set([...Object.keys(recorded), ...Object.keys(given)])].filter((name) => recorded[name] !== given[name]).sort();
38
+ const described = moved.map((name) => !(name in recorded) ? `${name} (new)` : !(name in given) ? `${name} (gone)` : name);
39
+ return Object.assign(new RecoveryError(`Run store binding mismatch: ${moved.length ? `${described.join(", ")} changed since the run was bound` : "every named input matches, so the change is in how the binding is composed"}`, "RUN_STORE_BINDING_MISMATCH"), { moved });
40
+ }
41
+ /** The format of what a run's store holds for a resume. Every binding carries it, so a store written under
42
+ * another format is refused, never resumed as if it held the same record. */
43
+ export const LEDGER_FORMAT = 3;
@@ -0,0 +1,9 @@
1
+ /** The widest provider tool-call id that is keyed as it is. */
2
+ export declare const CALL_KEY_BYTES = 256;
3
+ /** A host's own key for a provider-minted tool-call id. A provider may fold arbitrary data into
4
+ * its call ids (a reasoning signature, for one), so an id's length is the provider's, not ours: an id
5
+ * within `CALL_KEY_BYTES` is its own key, and a wider one is keyed by its leading characters (made
6
+ * identifier-safe) and a SHA-256 prefix of the whole id. The mapping is deterministic, so the same
7
+ * call always has the same key, and two different wide ids share a key only on a digest collision.
8
+ * Only keys use it: what goes back to the provider is always the id it minted. */
9
+ export declare function callKey(callId: string): string;
@@ -0,0 +1,17 @@
1
+ import { createHash } from "node:crypto";
2
+ /** The widest provider tool-call id that is keyed as it is. */
3
+ export const CALL_KEY_BYTES = 256;
4
+ const PREFIX_CHARS = 64;
5
+ const DIGEST_HEX = 32;
6
+ /** A host's own key for a provider-minted tool-call id. A provider may fold arbitrary data into
7
+ * its call ids (a reasoning signature, for one), so an id's length is the provider's, not ours: an id
8
+ * within `CALL_KEY_BYTES` is its own key, and a wider one is keyed by its leading characters (made
9
+ * identifier-safe) and a SHA-256 prefix of the whole id. The mapping is deterministic, so the same
10
+ * call always has the same key, and two different wide ids share a key only on a digest collision.
11
+ * Only keys use it: what goes back to the provider is always the id it minted. */
12
+ export function callKey(callId) {
13
+ if (Buffer.byteLength(callId) <= CALL_KEY_BYTES)
14
+ return callId;
15
+ const prefix = callId.slice(0, PREFIX_CHARS).replace(/[^A-Za-z0-9_.-]/g, "_");
16
+ return `${prefix}~${createHash("sha256").update(callId).digest("hex").slice(0, DIGEST_HEX)}`;
17
+ }
@@ -0,0 +1,7 @@
1
+ /** SHA-256 of a value's JSON with every object's keys sorted (`canonicalJson`): the identity of a binding, an input,
2
+ * an intent's arguments or a set of file hashes, independent of key order. */
3
+ export declare const canonicalHash: (value: unknown) => string;
4
+ /** SHA-256 of a value serialized with sorted keys: an identity for a contract a host persists. Not interchangeable
5
+ * with canonicalHash: it writes an undefined member as `undefined` and never calls toJSON, and both identities are
6
+ * persisted. */
7
+ export declare function canonicalSha256(value: unknown): string;
@@ -0,0 +1,22 @@
1
+ import { createHash } from "node:crypto";
2
+ import { canonicalJson } from "./item-state.js";
3
+ /** SHA-256 of a value's JSON with every object's keys sorted (`canonicalJson`): the identity of a binding, an input,
4
+ * an intent's arguments or a set of file hashes, independent of key order. */
5
+ export const canonicalHash = (value) => createHash("sha256").update(canonicalJson(value)).digest("hex");
6
+ function canonical(value) {
7
+ if (value === null || typeof value !== "object")
8
+ return JSON.stringify(value);
9
+ if (Array.isArray(value))
10
+ return `[${value.map(canonical).join(",")}]`;
11
+ const object = value;
12
+ return `{${Object.keys(object)
13
+ .sort()
14
+ .map((key) => `${JSON.stringify(key)}:${canonical(object[key])}`)
15
+ .join(",")}}`;
16
+ }
17
+ /** SHA-256 of a value serialized with sorted keys: an identity for a contract a host persists. Not interchangeable
18
+ * with canonicalHash: it writes an undefined member as `undefined` and never calls toJSON, and both identities are
19
+ * persisted. */
20
+ export function canonicalSha256(value) {
21
+ return createHash("sha256").update(canonical(value)).digest("hex");
22
+ }
@@ -0,0 +1,235 @@
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, type DecisionRequest } from "./frozen-snapshot.js";
3
+ import type { RecoveryBinding, RecoveryEffect, RecoveryStore } from "./store.js";
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. 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). */
8
+ export declare function routeTaken(node: RouteNode, answers: unknown): {
9
+ branch: string;
10
+ choice: string | null;
11
+ unsure: boolean;
12
+ refused?: true;
13
+ } | null;
14
+ /** The binding of a run of `workflow` under what the host binds beside it. */
15
+ export declare function recoveryBinding(workflow: Workflow, bind?: Record<string, unknown>): string;
16
+ /** What a store is opened under for a run of `workflow`: its binding, and the digest of each input the binding
17
+ * covers. The driver opens its store under it, and so does an operator who reconciles an effect by hand. */
18
+ export declare function recoveryBound(workflow: Workflow, bind?: Record<string, unknown>): RecoveryBinding;
19
+ /** A host's pause or cancel, and who issued it. */
20
+ export type RecoveryStop = {
21
+ action: "pause" | "cancel";
22
+ source?: string;
23
+ };
24
+ /** How the driver reads the files a workflow declares it writes. */
25
+ export type RecoveryFiles = {
26
+ /** Whether two names are one file. */
27
+ same(a: string, b: string): boolean;
28
+ /** The SHA-256 of each named file, by name. A missing file, or one outside the place files live, is refused
29
+ * with FROZEN_ARTIFACT_INVALID. */
30
+ hashes(names: string[]): Record<string, string>;
31
+ };
32
+ /** The files of a workspace directory: a name is relative to it, and a file that resolves outside it is refused. */
33
+ export declare function workspaceFiles(cwd: string): RecoveryFiles;
34
+ export type RecoveryOptions = {
35
+ /** The run's identity. Its step sessions, its effects' receipts and the continuation of its escalation are named
36
+ * under it, so the same run is opened with the same key in every process. */
37
+ key: string;
38
+ /** What else must not change between two opens of the run, beside the workflow: the host's own inputs. */
39
+ bind?: Record<string, unknown>;
40
+ /** The document the interpreter runs, when the host rewrites the authored one before running it. Execution paths
41
+ * resolve in it; the binding, the labels and the declared files are the authored document's. Absent, the
42
+ * desugared workflow. */
43
+ view?: Workflow;
44
+ /** Files only the host writes. A workflow that declares one of them is refused before any step runs. */
45
+ reservedOutputs?: readonly string[];
46
+ /** The files a workflow declares it writes. Absent, the files of the process's working directory. */
47
+ files?: RecoveryFiles;
48
+ /** Closes the session of an LLM step's attempt that ended without a submission. It runs on the driver's commit
49
+ * chain, before the commit that records the attempt as closed; its failure is the run's. */
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>;
56
+ /** Settles effects a killed process left unknown, through the driver's own open of the run (one generation per process).
57
+ * `openRecovery` calls it once, after the open and before anything resumes, when the journal holds an effect that was
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)`
59
+ * records `value` as the effect's result, as `journal.complete` does with `{ value, files }`, hashing the files the effect declares (a missing one refuses the settlement); `receipt.intent` names
60
+ * the call the host's door answered, as a handoff reads it. `receipt.calls` are the outside calls the host MADE or FOUND APPLIED
61
+ * while settling it, records of the shape `{ outcome: "applied" | "failed" | "unknown", ... }`, so that the effect's `calls` lists
62
+ * every applied call exactly once. They are kept on the effect before it completes, after the calls an earlier process kept, as a
63
+ * dispatch keeps its own. A re-send is a call of this process. A settle from evidence that the call applied (a provider's own
64
+ * lookup, an answer the host kept) reports `{ outcome: "applied" }` when the calls the effect holds include no applied entry,
65
+ * and adds none when its applied call is already there. A settle that made no call and found none applied reports none. The
66
+ * effect is then answered from that result and not
67
+ * dispatched again. One it leaves unknown is refused at resume (`FROZEN_EFFECT_UNKNOWN`). A throw fails the open with
68
+ * `RECOVERY_RECONCILE_FAILED`, keeping the cause, before any effect is dispatched. */
69
+ reconcile?: (unknown: RecoveryEffect[], complete: (id: string, value: unknown, receipt?: {
70
+ intent?: {
71
+ tool: string;
72
+ args?: unknown;
73
+ };
74
+ calls?: unknown[];
75
+ }) => Promise<void>) => Promise<void>;
76
+ /** How a new run, or one stored whole, is kept. `"v3"` (the default in this release) keeps the driver's whole state in
77
+ * one record, rewritten at every commit, so a map's commits grow with the square of its items. `"v4"`, the keyed
78
+ * layout, keeps what lies in each map item in that item's record and each state the driver references once by its
79
+ * digest (a failed map's finished results too), so a commit writes what it changed: a run stored whole moves to it at
80
+ * its first commit. After that move, the checkpoint bases of the driver's record keep the ids of the effects admitted
81
+ * before it: a cost bounded by the work done before the move, which later commits do not grow; each commit after the
82
+ * move costs the same however many items the map has. Only a store that
83
+ * keeps parts (its opened journal has `items` and `stateOf`) can hold it; on any other the driver keeps `"v3"` and says
84
+ * why once per open, in a `layout` note. A run stored in the keyed layout stays in it whatever this says, and a driver
85
+ * that knows only `"v3"` refuses to open it (`FROZEN_CHECKPOINT_INVALID`). Release 0.1.0-beta.13 and earlier fail their
86
+ * own task on a run in the keyed layout and report it refused; that ends the run's agent nodes in flight, and the run
87
+ * then fails on this release too, with no call repeated and nothing corrupted. So opt in only when no process on an
88
+ * earlier release can open the run. A build from this release on leaves a run stored in a schema newer than it knows
89
+ * pending (`RECOVERY_SCHEMA_NEWER`), for a build that knows it. */
90
+ layout?: "v3" | "v4";
91
+ };
92
+ /** What a host's effect adapter receives under the driver: the interpreter's parameters, `call`, which keeps each
93
+ * outside call the effect makes on its record as the call ends, and `effect`, the admitted effect: its journal id and
94
+ * the hash of its arguments, as the journal stores them and the same in every process of the run. A host that keeps
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. */
101
+ export type RecoveryEffectParams = Parameters<NonNullable<WorkflowDeps["runEffect"]>>[0] & {
102
+ call?: (record: unknown) => void;
103
+ effect?: {
104
+ id: string;
105
+ argsHash: string;
106
+ };
107
+ };
108
+ /** Opens the durable state of one run of `workflow` in `store` and takes ownership of it. Execution remains in the
109
+ * interpreter: the workflow runs with the returned driver's hooks, and `close` lets go of the run. */
110
+ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, options: RecoveryOptions): Promise<{
111
+ recovery: {
112
+ supportsExecutionPaths?: boolean;
113
+ resume: (node: WorkflowNode, state: Record<string, unknown>, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<Record<string, unknown> | undefined>;
114
+ commit: (node: WorkflowNode, state: Record<string, unknown>, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<void>;
115
+ pollStartedAt: (node: import("../workflow.js").CallNode, item?: import("../workflow.js").MapItem, executionPath?: string) => number;
116
+ wait: (node: import("../workflow.js").CallNode, ms: number, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<void>;
117
+ fail?: (node: WorkflowNode, results: unknown[], error: unknown, executionPath?: string) => Promise<void>;
118
+ failItem?: (node: WorkflowNode, failure: import("../workflow.js").MapItemFailure, executionPath? /** The host's stop as it was handed over (a cancel outranks a pause), and who issued it. */: string) => Promise<void>;
119
+ itemFailure?: (node: WorkflowNode, executionPath?: string) => Promise<import("../workflow.js").MapItemFailure | undefined>;
120
+ decision?: (id: string) => Promise<import("../decision-receipts.js").DecisionReceipt | undefined>;
121
+ };
122
+ signal: AbortSignal;
123
+ resumed: boolean;
124
+ /** This process's generation of the run: a request this process makes is named with it, so a
125
+ * process that asks again never reuses an earlier process's invocation. */
126
+ readonly generation: number;
127
+ /** A refusal found before any step, or null: the host escalates it before any step runs. */
128
+ preStepRefusal: {
129
+ code: string;
130
+ kind: string;
131
+ message: string;
132
+ label: string;
133
+ } | null;
134
+ /** How this open keeps the run: the layout's schema, and why it is not the keyed one the host asked for. */
135
+ readonly layout: {
136
+ schema: typeof FROZEN_SNAPSHOT_SCHEMA | typeof FROZEN_SNAPSHOT_SCHEMA_V4;
137
+ reason?: string;
138
+ };
139
+ binding: string;
140
+ /** The run's key: what its step sessions and effects are named under. */
141
+ driverId: string;
142
+ /** The host hands the driver its stop here. A cancel stops the driver at once, and its steps and effects through
143
+ * its signal. A pause refuses new work at once and is taken when no effect is in flight: an effect already
144
+ * dispatched completes and commits its receipt first, so a paused run resumes without a reconciliation. */
145
+ stop: (stop: RecoveryStop) => void;
146
+ /** The driver's stop check, for a branch that hands off without entering the interpreter: a pause or cancel the
147
+ * driver took stops the run here, before anything resumes. */
148
+ checkStop(): void;
149
+ /** A seam for new work: it waits while a pause waits for an effect in flight, then applies any stop taken. */
150
+ seam: () => Promise<void>;
151
+ /** An LLM step's execution record, admitted before it dispatches. The first call fixes the label
152
+ * the interpreter names it by (a child's step under its invocation) and the retry limit; a resume
153
+ * at this path gets the same record, so its session is found again. A closed attempt advances to a new
154
+ * session identity here, and only here; a failed step never gets another. */
155
+ stepSession(executionPath: unknown, label: string, admission?: {
156
+ attemptsAllowed: number;
157
+ }): StepRecord & {
158
+ stepId: string;
159
+ sessionId: string;
160
+ earlierSessionIds: string[];
161
+ };
162
+ /** Whether the step already has an execution record: a resumed step was admitted in an earlier
163
+ * process and is continued, never refused again. */
164
+ stepAdmitted(executionPath: unknown): boolean;
165
+ /** The current attempt did not submit: its session closes with its spend kept.
166
+ * The step is `closed` until a retry is admitted, or `failed` when no attempt remains. */
167
+ stepAttemptFailed(executionPath: unknown, final?: boolean, error?: unknown): void;
168
+ /** The step delivered its record; the row and the step record agree before the step commit. */
169
+ stepSubmitted(executionPath: unknown): void;
170
+ /** The short identity of an admitted LLM step (a digest of its frame and path), for the escalation
171
+ * row when it fails; null for a path that ran no LLM step. */
172
+ stepId(executionPath: unknown): string | null;
173
+ /** Spend outside any question or session, committed with the driver's state the moment it is priced, so the run's
174
+ * recorded spend holds it. It may be called inside a tool, so it never applies a stop; a failed commit is the run's
175
+ * persistence failure. */
176
+ charge(usd: number): Promise<void>;
177
+ /** A question's metered spend, committed with the driver's state so a resume that skips the
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. */
184
+ recordQuestionSpend(usd: number | null, route?: {
185
+ executionPath: unknown;
186
+ label: string;
187
+ result: Record<string, unknown>;
188
+ receipts: QuestionReceipts | null;
189
+ }): void;
190
+ /** The host has written what it keeps of the route at `executionPath`: its decision no longer carries the
191
+ * receipts a resume would write. */
192
+ routeReceipted(executionPath: unknown): void;
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;
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
+ /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
211
+ * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
212
+ * It never applies a stop: a request the run asked ends whatever stops the run. */
213
+ decisionEnded(executionPath: unknown, decisionId: string, status: "answered" | "failed" | "interrupted", cost_usd: number | null, alongside?: () => void): void;
214
+ /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
215
+ * as an escalation commit before anything acts on it. A later open gets the same row and the same
216
+ * continuation identity, whatever fires again. */
217
+ escalate(row: Omit<EscalationRow, "tail" | "revision">): Promise<EscalationRow>;
218
+ escalation(): EscalationRow | undefined;
219
+ /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
220
+ pinJson(): string;
221
+ /** How many effects the driver admitted. */
222
+ effectCalls(): number;
223
+ /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
224
+ * items produced under the map's key: what an escalation on a failure carries. */
225
+ lastState(): Record<string, unknown>;
226
+ readonly started: boolean;
227
+ wrapEffect(run: (params: RecoveryEffectParams) => Promise<unknown>): NonNullable<WorkflowDeps["runEffect"]>;
228
+ /** Every commit the driver started has landed; a failed one is thrown, a pause's or a cancel's own commit included. */
229
+ flush: () => Promise<void>;
230
+ /** Let go of the run once every commit the driver started has landed. A commit the store refused after a pause or
231
+ * cancel is thrown once the journal is released: the stop is not durable, and the host must not take the run as
232
+ * stopped. It is thrown even when a later stop's commit lands, since a later commit does not carry every record the
233
+ * refused one held. A run's own failed commit is the run's failure and is not thrown again here. */
234
+ close(): Promise<void>;
235
+ }>;