@parcha/agentrun-dsl 0.1.0-beta.3 → 0.1.0-beta.31

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 (103) hide show
  1. package/README.md +165 -21
  2. package/dist/author-references.d.ts +8 -0
  3. package/dist/author-references.js +8 -0
  4. package/dist/author.d.ts +16 -3
  5. package/dist/author.js +40 -16
  6. package/dist/authoring.js +2 -2
  7. package/dist/cli.js +17 -12
  8. package/dist/code-exec.d.ts +6 -0
  9. package/dist/code-exec.js +126 -0
  10. package/dist/decision-provider.d.ts +157 -0
  11. package/dist/decision-provider.js +230 -0
  12. package/dist/decision-receipts.d.ts +143 -0
  13. package/dist/decision-receipts.js +93 -0
  14. package/dist/dry-run.d.ts +14 -1
  15. package/dist/dry-run.js +58 -15
  16. package/dist/graph.d.ts +169 -0
  17. package/dist/graph.js +433 -0
  18. package/dist/index.d.ts +15 -8
  19. package/dist/index.js +8 -4
  20. package/dist/inspection.d.ts +5 -0
  21. package/dist/inspection.js +16 -3
  22. package/dist/job.d.ts +14 -0
  23. package/dist/job.js +5 -0
  24. package/dist/long-timer.d.ts +7 -0
  25. package/dist/long-timer.js +22 -0
  26. package/dist/observer-snapshot.d.ts +3 -0
  27. package/dist/observer-snapshot.js +46 -0
  28. package/dist/predicates.d.ts +10 -0
  29. package/dist/predicates.js +18 -0
  30. package/dist/recovery/binding.d.ts +10 -0
  31. package/dist/recovery/binding.js +43 -0
  32. package/dist/recovery/call-key.d.ts +13 -0
  33. package/dist/recovery/call-key.js +24 -0
  34. package/dist/recovery/canonical-hash.d.ts +7 -0
  35. package/dist/recovery/canonical-hash.js +22 -0
  36. package/dist/recovery/driver.d.ts +238 -0
  37. package/dist/recovery/driver.js +1337 -0
  38. package/dist/recovery/effect-failure.d.ts +34 -0
  39. package/dist/recovery/effect-failure.js +62 -0
  40. package/dist/recovery/errors.d.ts +31 -0
  41. package/dist/recovery/errors.js +51 -0
  42. package/dist/recovery/execution-path.d.ts +53 -0
  43. package/dist/recovery/execution-path.js +167 -0
  44. package/dist/recovery/file-store.d.ts +7 -0
  45. package/dist/recovery/file-store.js +131 -0
  46. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  47. package/dist/recovery/frozen-snapshot.js +187 -0
  48. package/dist/recovery/handoff-block.d.ts +36 -0
  49. package/dist/recovery/handoff-block.js +148 -0
  50. package/dist/recovery/handoff-digest.d.ts +58 -0
  51. package/dist/recovery/handoff-digest.js +195 -0
  52. package/dist/recovery/handoff-files.d.ts +54 -0
  53. package/dist/recovery/handoff-files.js +162 -0
  54. package/dist/recovery/handoff-receipts.d.ts +42 -0
  55. package/dist/recovery/handoff-receipts.js +53 -0
  56. package/dist/recovery/handoff-redact.d.ts +12 -0
  57. package/dist/recovery/handoff-redact.js +44 -0
  58. package/dist/recovery/handoff.d.ts +44 -0
  59. package/dist/recovery/handoff.js +46 -0
  60. package/dist/recovery/index.d.ts +19 -0
  61. package/dist/recovery/index.js +17 -0
  62. package/dist/recovery/item-state.d.ts +48 -0
  63. package/dist/recovery/item-state.js +89 -0
  64. package/dist/recovery/journal.d.ts +28 -0
  65. package/dist/recovery/journal.js +139 -0
  66. package/dist/recovery/memory-store.d.ts +4 -0
  67. package/dist/recovery/memory-store.js +20 -0
  68. package/dist/recovery/store.d.ts +105 -0
  69. package/dist/recovery/store.js +6 -0
  70. package/dist/recovery/testing/conformance.d.ts +4 -0
  71. package/dist/recovery/testing/conformance.js +268 -0
  72. package/dist/recovery/testing/crash-points.d.ts +18 -0
  73. package/dist/recovery/testing/crash-points.js +43 -0
  74. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  75. package/dist/recovery/testing/crash-sweep.js +146 -0
  76. package/dist/recovery/testing/index.d.ts +3 -0
  77. package/dist/recovery/testing/index.js +4 -0
  78. package/dist/recovery/testing/preload.d.ts +1 -0
  79. package/dist/recovery/testing/preload.js +3 -0
  80. package/dist/recovery/transport-facts.d.ts +23 -0
  81. package/dist/recovery/transport-facts.js +46 -0
  82. package/dist/recovery/with-recovery.d.ts +50 -0
  83. package/dist/recovery/with-recovery.js +142 -0
  84. package/dist/submit-envelope.d.ts +9 -0
  85. package/dist/submit-envelope.js +40 -0
  86. package/dist/system-one.d.ts +40 -1
  87. package/dist/system-one.js +141 -5
  88. package/dist/testing/decision-provider.d.ts +32 -0
  89. package/dist/testing/decision-provider.js +183 -0
  90. package/dist/testing/index.d.ts +1 -0
  91. package/dist/testing/index.js +2 -0
  92. package/dist/vocabulary.d.ts +22 -3
  93. package/dist/vocabulary.js +33 -10
  94. package/dist/workflow-shape.d.ts +7 -0
  95. package/dist/workflow-shape.js +115 -67
  96. package/dist/workflow.d.ts +269 -20
  97. package/dist/workflow.js +1251 -341
  98. package/package.json +25 -2
  99. package/schema/workflow.schema.json +506 -12
  100. package/skills/author/SKILL.md +6 -1
  101. package/skills/author/references/jev-decisions.md +58 -6
  102. package/skills/author/references/language.md +28 -19
  103. package/skills/author/references/sdk-authoring.md +2 -0
package/dist/index.js CHANGED
@@ -1,15 +1,19 @@
1
1
  export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
2
- export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, } from "./workflow.js";
2
+ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, } from "./workflow.js";
3
+ export { defineJob } from "./job.js";
4
+ export { DECISION_RECEIPT_VERSION, DECISION_INTERRUPTED, DECISION_REFUSED, DECISION_STATE_MAX_BYTES, rederiveDecision } from "./decision-receipts.js";
3
5
  export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
4
- export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, } from "./system-one.js";
6
+ export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, deriveConfidence, completeConfidence, refusedQuestions, } from "./system-one.js";
7
+ export { judgeFromProvider, judgeFromProviders, checkCapabilities, DecisionProviderError, imageDimensions } from "./decision-provider.js";
5
8
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
6
9
  export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA,
7
10
  // Document helpers a host facade needs to speak about a workflow without re-implementing the walk.
8
11
  childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
9
12
  // Host-side data helpers the interpreter itself uses: the same normalization and reference shaping.
10
13
  buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
11
- export { compileTransform, compileTransformSyntax } from "./code-exec.js";
14
+ export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
12
15
  export { resolveSchemaForWorkflow } from "./schema-references.js";
16
+ export { submitParameters } from "./submit-envelope.js";
13
17
  export { getPath, predicateMatches } from "./predicates.js";
14
18
  export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
15
- export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
19
+ export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, FIELD_TYPES, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
@@ -11,6 +11,11 @@ export type WorkflowInspectionNode = {
11
11
  /** Effective selection from completed map-item state; absent means whole item state. */
12
12
  resultPath?: string;
13
13
  childWorkflow?: string;
14
+ /** A decision node's (or an `ask` predicate's) provider and pinned model, when it names them, and the tokens of the
15
+ * images it sends. */
16
+ provider?: string;
17
+ model?: string;
18
+ images?: string[];
14
19
  };
15
20
  export type WorkflowInspection = {
16
21
  name: string;
@@ -1,5 +1,17 @@
1
- import { workflowDocumentError, workflowSha256 } from "./workflow.js";
1
+ import { routesByValue, workflowDocumentError, workflowSha256 } from "./workflow.js";
2
2
  import { workflowShapeErrors } from "./workflow-shape.js";
3
+ /** What a decision node, or a loop's or escalate's `ask` predicate, names of its provider, model and images. */
4
+ function decisionFields(node) {
5
+ const source = node.node === "loop" ? node.until : node.node === "escalate" ? node.when
6
+ : ["judge", "pick", "sift"].includes(node.node) || node.node === "route" && !routesByValue(node) ? node : undefined;
7
+ if (!source || ((node.node === "loop" || node.node === "escalate") && source.predicate !== "ask"))
8
+ return {};
9
+ const { provider, model, images } = source;
10
+ return {
11
+ ...(typeof provider === "string" ? { provider } : {}), ...(typeof model === "string" ? { model } : {}),
12
+ ...(images && typeof images === "object" && Object.keys(images).length ? { images: Object.keys(images) } : {}),
13
+ };
14
+ }
3
15
  const pointer = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
4
16
  /** Inspect a workflow's structure without running authored code, adapters, or schema probes.
5
17
  * The input must be plain JSON data. This is a review aid, not execution admission: use
@@ -26,11 +38,12 @@ export function inspectWorkflow(value) {
26
38
  ...("out" in node && node.out && node.node !== "sift" ? { outputSchema: node.out } : {}),
27
39
  ...(node.node === "map" && (node.resultPath || "as" in node.body && node.body.as)
28
40
  ? { resultPath: node.resultPath || node.body.as } : {}),
29
- ...(node.node === "workflow" ? { childWorkflow: node.workflow.name } : {}), });
41
+ ...(node.node === "workflow" ? { childWorkflow: node.workflow.name } : {}),
42
+ ...decisionFields(node), });
30
43
  if (["agent", "decide", "extract", "report"].includes(node.node) ||
31
44
  node.node === "artifact" && ["markdown", "report"].includes(node.type))
32
45
  adapters.add("runNode");
33
- if (["judge", "pick", "sift", "route"].includes(node.node) ||
46
+ if (["judge", "pick", "sift"].includes(node.node) || node.node === "route" && !routesByValue(node) ||
34
47
  "verify" in node && node.verify || node.node === "loop" && node.until.predicate === "ask" ||
35
48
  node.node === "escalate" && node.when.predicate === "ask")
36
49
  adapters.add("runJudge");
package/dist/job.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { Workflow } from "./workflow.js";
2
+ /** A unit of work a host runs: the workflow, the input it runs on, and the files it starts with (by path, as bytes). */
3
+ export type Job = {
4
+ workflow: Workflow;
5
+ input: Record<string, unknown>;
6
+ files?: Record<string, Uint8Array>;
7
+ };
8
+ /** Returns `job` itself. It checks the job's shape and keeps the workflow's literal type, so a job written beside a workflow
9
+ * declared `as const satisfies Workflow` still names the workflow's literal values. */
10
+ export declare function defineJob<const W extends Workflow>(job: {
11
+ workflow: W;
12
+ input: Record<string, unknown>;
13
+ files?: Record<string, Uint8Array>;
14
+ }): typeof job;
package/dist/job.js ADDED
@@ -0,0 +1,5 @@
1
+ /** Returns `job` itself. It checks the job's shape and keeps the workflow's literal type, so a job written beside a workflow
2
+ * declared `as const satisfies Workflow` still names the workflow's literal values. */
3
+ export function defineJob(job) {
4
+ return job;
5
+ }
@@ -0,0 +1,7 @@
1
+ export declare const MAX_TIMER_DELAY_MS: number;
2
+ export type LongTimer = {
3
+ clear(): void;
4
+ };
5
+ /** Schedule `fn` after `ms`, re-arming in <= MAX_TIMER_DELAY_MS chunks so a delay past Node's timer
6
+ * limit still fires on time instead of overflowing. `clear()` cancels the pending chunk. */
7
+ export declare function setLongTimeout(fn: () => void, ms: number): LongTimer;
@@ -0,0 +1,22 @@
1
+ // Node's timers accept a delay of at most 2^31-1 ms (~24.8 days); a larger delay silently overflows
2
+ // to a near-immediate fire with a TimeoutOverflowWarning. A workflow's deadline_s, poll.deadline_s,
3
+ // poll.interval_s and retry.backoff_s carry no upper ceiling, so a delay derived from them can exceed
4
+ // that. `setLongTimeout` re-arms in <= MAX_TIMER_DELAY_MS chunks, so the callback fires at the
5
+ // intended time however far out it is, and returns a handle that clears whichever chunk is pending.
6
+ export const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
7
+ /** Schedule `fn` after `ms`, re-arming in <= MAX_TIMER_DELAY_MS chunks so a delay past Node's timer
8
+ * limit still fires on time instead of overflowing. `clear()` cancels the pending chunk. */
9
+ export function setLongTimeout(fn, ms) {
10
+ let remaining = Number.isFinite(ms) ? Math.max(0, ms) : MAX_TIMER_DELAY_MS;
11
+ let handle;
12
+ const tick = () => {
13
+ if (remaining <= MAX_TIMER_DELAY_MS) {
14
+ handle = setTimeout(fn, remaining);
15
+ return;
16
+ }
17
+ remaining -= MAX_TIMER_DELAY_MS;
18
+ handle = setTimeout(tick, MAX_TIMER_DELAY_MS);
19
+ };
20
+ tick();
21
+ return { clear() { clearTimeout(handle); } };
22
+ }
@@ -0,0 +1,3 @@
1
+ /** Copy observation data without reading accessors or sharing mutable data objects.
2
+ * Keep invalid JSON shapes visible so required host trace validation can reject them. */
3
+ export declare function observerSnapshot<T>(value: T): T;
@@ -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,15 @@ 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
+ } | NotPredicate;
37
+ /** Holds when `of` does not. `of` is mechanical: a judged question never sits inside a negation. */
38
+ export type NotPredicate = {
39
+ predicate: "not";
40
+ of: AcceptPredicate;
31
41
  };
32
42
  export declare const MECHANICAL_PREDICATE_NAMES: ReadonlySet<string>;
33
43
  /** Resolve a dotted state path the one way every reader does: a record by key, an array by a
@@ -24,6 +24,19 @@ 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
+ }
27
40
  export function predicateMatches(predicate, value) {
28
41
  switch (predicate.predicate) {
29
42
  case "field_equals":
@@ -54,6 +67,11 @@ export function predicateMatches(predicate, value) {
54
67
  return false;
55
68
  return predicate.predicate === "gte" ? target >= predicate.n : target < predicate.n;
56
69
  }
70
+ case "field_type":
71
+ return hasType(getPath(value, predicate.path), predicate.type);
72
+ case "not":
73
+ // A judged `of` reaches the default case below and throws: validation refuses it first.
74
+ return !predicateMatches(predicate.of, value);
57
75
  default:
58
76
  throw new Error(`agentrun: unsupported predicate "${String(predicate?.predicate ?? "")}" — fail closed, never silently false`);
59
77
  }
@@ -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,13 @@
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;
10
+ /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
11
+ * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
12
+ * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
13
+ export declare function heldCallKey(callId: string, holds: (rawKey: string) => boolean): string;
@@ -0,0 +1,24 @@
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
+ }
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
+ }
@@ -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,238 @@
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
+ /** Settles effects a killed process left unknown, through the driver's own open of the run (one generation per process).
52
+ * `openRecovery` calls it once, after the open and before anything resumes, when the journal holds an effect that was
53
+ * 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)`
54
+ * 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
55
+ * the call the host's door answered, as a handoff reads it. `receipt.calls` are the outside calls the host MADE or FOUND APPLIED
56
+ * while settling it, records of the shape `{ outcome: "applied" | "failed" | "unknown", ... }`, so that the effect's `calls` lists
57
+ * every applied call exactly once. They are kept on the effect before it completes, after the calls an earlier process kept, as a
58
+ * 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
59
+ * lookup, an answer the host kept) reports `{ outcome: "applied" }` when the calls the effect holds include no applied entry,
60
+ * and adds none when its applied call is already there. A settle that made no call and found none applied reports none. The
61
+ * effect is then answered from that result and not
62
+ * dispatched again. One it leaves unknown is refused at resume (`FROZEN_EFFECT_UNKNOWN`). A throw fails the open with
63
+ * `RECOVERY_RECONCILE_FAILED`, keeping the cause, before any effect is dispatched. */
64
+ reconcile?: (unknown: RecoveryEffect[], complete: (id: string, value: unknown, receipt?: {
65
+ intent?: {
66
+ tool: string;
67
+ args?: unknown;
68
+ };
69
+ calls?: unknown[];
70
+ }) => Promise<void>) => Promise<void>;
71
+ /** How a new run, or one stored whole, is kept. `"v3"` (the default in this release) keeps the driver's whole state in
72
+ * one record, rewritten at every commit, so a map's commits grow with the square of its items. `"v4"`, the keyed
73
+ * layout, keeps what lies in each map item in that item's record and each state the driver references once by its
74
+ * digest (a failed map's finished results too), so a commit writes what it changed: a run stored whole moves to it at
75
+ * its first commit. After that move, the checkpoint bases of the driver's record keep the ids of the effects admitted
76
+ * before it: a cost bounded by the work done before the move, which later commits do not grow; each commit after the
77
+ * move costs the same however many items the map has. Only a store that
78
+ * keeps parts (its opened journal has `items` and `stateOf`) can hold it; on any other the driver keeps `"v3"` and says
79
+ * why once per open, in a `layout` note. A run stored in the keyed layout stays in it whatever this says, and a driver
80
+ * that knows only `"v3"` refuses to open it (`FROZEN_CHECKPOINT_INVALID`). Release 0.1.0-beta.13 and earlier fail their
81
+ * 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
82
+ * then fails on this release too, with no call repeated and nothing corrupted. So opt in only when no process on an
83
+ * earlier release can open the run. A build from this release on leaves a run stored in a schema newer than it knows
84
+ * pending (`RECOVERY_SCHEMA_NEWER`), for a build that knows it. */
85
+ layout?: "v3" | "v4";
86
+ };
87
+ /** What a host's effect adapter receives under the driver: the interpreter's parameters, `call`, which keeps each
88
+ * outside call the effect makes on its record as the call ends, and `effect`, the admitted effect: its journal id and
89
+ * the hash of its arguments, as the journal stores them and the same in every process of the run. A host that keeps
90
+ * what an outside call answered under them can settle an effect whose call was cut with `journal.complete`.
91
+ *
92
+ * What the adapter returns is the effect's result, whatever its fields. An adapter that cannot know whether the outside
93
+ * call happened throws: a `RecoveryError` with code `FROZEN_EFFECT_UNKNOWN`, its `cause` what it observed (kept for the
94
+ * operator in the checkpoint's `unknownResponses`), or an `EffectOutcomeUnknownError`. The effect then stays unknown,
95
+ * is never dispatched again, and the run resumes only once the host reconciles it, as after any call that throws. */
96
+ export type RecoveryEffectParams = Parameters<NonNullable<WorkflowDeps["runEffect"]>>[0] & {
97
+ call?: (record: unknown) => void;
98
+ effect?: {
99
+ id: string;
100
+ argsHash: string;
101
+ };
102
+ };
103
+ /** Opens the durable state of one run of `workflow` in `store` and takes ownership of it. Execution remains in the
104
+ * interpreter: the workflow runs with the returned driver's hooks, and `close` lets go of the run. */
105
+ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, options: RecoveryOptions): Promise<{
106
+ recovery: {
107
+ supportsExecutionPaths?: boolean;
108
+ resume: (node: WorkflowNode, state: Record<string, unknown>, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<Record<string, unknown> | undefined>;
109
+ commit: (node: WorkflowNode, state: Record<string, unknown>, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<void>;
110
+ pollStartedAt: (node: import("../workflow.js").CallNode, item?: import("../workflow.js").MapItem, executionPath?: string) => number;
111
+ wait: (node: import("../workflow.js").CallNode, ms: number, item?: import("../workflow.js").MapItem, executionPath?: string) => Promise<void>;
112
+ fail?: (node: WorkflowNode, results: unknown[], error: unknown, executionPath?: string) => Promise<void>;
113
+ failItem?: (node: WorkflowNode, failure: import("../workflow.js").MapItemFailure, executionPath?: string) => Promise<void>;
114
+ itemFailure?: (node: WorkflowNode, executionPath?: string) => Promise<import("../workflow.js").MapItemFailure | undefined>;
115
+ decision?: (id: string) => Promise<import("../decision-receipts.js").DecisionReceipt | undefined>;
116
+ };
117
+ signal: AbortSignal;
118
+ resumed: boolean;
119
+ /** This process's generation of the run: a request this process makes is named with it, so a
120
+ * process that asks again never reuses an earlier process's invocation. */
121
+ readonly generation: number;
122
+ /** A refusal found before any step, or null: the host escalates it before any step runs. */
123
+ preStepRefusal: {
124
+ code: string;
125
+ kind: string;
126
+ message: string;
127
+ label: string;
128
+ } | null;
129
+ /** How this open keeps the run: the layout's schema, and why it is not the keyed one the host asked for. */
130
+ readonly layout: {
131
+ schema: typeof FROZEN_SNAPSHOT_SCHEMA | typeof FROZEN_SNAPSHOT_SCHEMA_V4;
132
+ reason?: string;
133
+ };
134
+ binding: string;
135
+ /** The run's key: what its step sessions and effects are named under. */
136
+ driverId: string;
137
+ /** The host hands the driver its stop here. A cancel stops the driver at once, and its steps and effects through
138
+ * its signal. A pause refuses new work at once and is taken when no effect is in flight: an effect already
139
+ * dispatched completes and commits its receipt first, so a paused run resumes without a reconciliation. */
140
+ stop: (stop: RecoveryStop) => void;
141
+ /** The driver's stop check, for a branch that hands off without entering the interpreter: a pause or cancel the
142
+ * driver took stops the run here, before anything resumes. */
143
+ checkStop(): void;
144
+ /** A seam for new work: it waits while a pause waits for an effect in flight, then applies any stop taken. */
145
+ seam: () => Promise<void>;
146
+ /** An LLM step's execution record, admitted before it dispatches. The first call fixes the label
147
+ * the interpreter names it by (a child's step under its invocation) and the retry limit; a resume
148
+ * at this path gets the same record, so its session is found again. A closed attempt advances to a new
149
+ * session identity here, and only here; a failed step never gets another. */
150
+ stepSession(executionPath: unknown, label: string, admission?: {
151
+ attemptsAllowed: number;
152
+ }): StepRecord & {
153
+ stepId: string;
154
+ sessionId: string;
155
+ earlierSessionIds: string[];
156
+ };
157
+ /** Whether the step already has an execution record: a resumed step was admitted in an earlier
158
+ * process and is continued, never refused again. */
159
+ stepAdmitted(executionPath: unknown): boolean;
160
+ /** The current attempt did not submit: its session closes with its spend kept.
161
+ * The step is `closed` until a retry is admitted, or `failed` when no attempt remains. */
162
+ stepAttemptFailed(executionPath: unknown, final?: boolean, error?: unknown): void;
163
+ /** The step delivered its record; the row and the step record agree before the step commit. */
164
+ stepSubmitted(executionPath: unknown): void;
165
+ /** The short identity of an admitted LLM step (a digest of its frame and path), for the escalation
166
+ * row when it fails; null for a path that ran no LLM step. */
167
+ stepId(executionPath: unknown): string | null;
168
+ /** Spend outside any question or session, committed with the driver's state the moment it is priced, so the run's
169
+ * recorded spend holds it. It may be called inside a tool, so it never applies a stop; a failed commit is the run's
170
+ * persistence failure. */
171
+ charge(usd: number): Promise<void>;
172
+ /** A question's metered spend, committed with the driver's state so a resume that skips the
173
+ * finished question still reports it. A priced answer adds to `questionSpendUsd`; an answer with no
174
+ * price (`null`, or a cost that is not a non-negative finite number) is counted in
175
+ * `unpricedQuestionCount` instead, so the run's spend is read as incomplete and never as a bare total
176
+ * that silently omits it: an unknown cost is never zero. A route's answer is its decision: it commits
177
+ * in the same save, once per route path, and a resume inside the branch follows it instead of asking
178
+ * again; its price, priced or not, is recorded the same way. */
179
+ recordQuestionSpend(usd: number | null, route?: {
180
+ executionPath: unknown;
181
+ label: string;
182
+ result: Record<string, unknown>;
183
+ receipts: QuestionReceipts | null;
184
+ }): void;
185
+ /** The host has written what it keeps of the route at `executionPath`: its decision no longer carries the
186
+ * receipts a resume would write. */
187
+ routeReceipted(executionPath: unknown): void;
188
+ /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
189
+ routeDecision(executionPath: unknown): RouteDecision | undefined;
190
+ /** Every decision request this run committed, by decision id. */
191
+ decisionRequests(): Record<string, DecisionRequest>;
192
+ /** Admits a decision's request before the host's judge is asked, in the driver's next commit, which the caller
193
+ * awaits: a new request, or the next attempt of one that failed in its own process (undefined). A request found
194
+ * in any other status was asked by an earlier process and is returned as it stands; the caller does not ask again.
195
+ * An admitted request is in flight until `decisionSettled`: a pause waits for it, as for an effect. */
196
+ admitDecision(executionPath: unknown, request: Pick<DecisionRequest, "decision_id" | "kind" | "label" | "model" | "request_sha256">): DecisionRequest | undefined;
197
+ /** A request `admitDecision` admitted is no longer in flight. */
198
+ decisionSettled(): void;
199
+ /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
200
+ * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
201
+ * It never applies a stop: a request the run asked ends whatever stops the run. */
202
+ decisionEnded(executionPath: unknown, decisionId: string, status: "answered" | "failed" | "interrupted", cost_usd: number | null, alongside?: () => void): void;
203
+ /** The escalation that ended this run (a gate that fired, or an LLM step that failed), written once
204
+ * as an escalation commit before anything acts on it. A later open gets the same row and the same
205
+ * continuation identity, whatever fires again. */
206
+ escalate(row: Omit<EscalationRow, "tail" | "revision">): Promise<EscalationRow>;
207
+ escalation(): EscalationRow | undefined;
208
+ /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
209
+ pinJson(): string;
210
+ /** How many effects the driver admitted. */
211
+ effectCalls(): number;
212
+ /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
213
+ * read and its identity. */
214
+ annotateHandoff(detail: {
215
+ escalation_revision: number;
216
+ tail: string;
217
+ inherit: string;
218
+ block_chars: number;
219
+ digest_chars: number;
220
+ }): Promise<void>;
221
+ /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
222
+ * the escalation commit, so the row the continuation reads the spend from is brought current here,
223
+ * by one `handoff` commit that names the escalation. The escalation's revision, what the
224
+ * continuation binds on, does not change. */
225
+ handoff(spend: Pick<EscalationRow, "cost_usd" | "turns" | "effect_calls">): Promise<EscalationRow>;
226
+ /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
227
+ * items produced under the map's key: what an escalation on a failure carries. */
228
+ lastState(): Record<string, unknown>;
229
+ readonly started: boolean;
230
+ wrapEffect(run: (params: RecoveryEffectParams) => Promise<unknown>): NonNullable<WorkflowDeps["runEffect"]>;
231
+ /** Every commit the driver started has landed; a failed one is thrown, a pause's or a cancel's own commit included. */
232
+ flush: () => Promise<void>;
233
+ /** Let go of the run once every commit the driver started has landed. A commit the store refused after a pause or
234
+ * cancel is thrown once the journal is released: the stop is not durable, and the host must not take the run as
235
+ * stopped. It is thrown even when a later stop's commit lands, since a later commit does not carry every record the
236
+ * refused one held. A run's own failed commit is the run's failure and is not thrown again here. */
237
+ close(): Promise<void>;
238
+ }>;