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

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 (102) hide show
  1. package/README.md +46 -16
  2. package/dist/author.d.ts +96 -0
  3. package/dist/author.js +320 -0
  4. package/dist/authoring.js +1 -1
  5. package/dist/cli.js +8 -3
  6. package/dist/code-exec.d.ts +6 -0
  7. package/dist/code-exec.js +126 -0
  8. package/dist/decision-receipts.d.ts +98 -0
  9. package/dist/decision-receipts.js +51 -0
  10. package/dist/dry-run.d.ts +14 -1
  11. package/dist/dry-run.js +39 -13
  12. package/dist/graph.d.ts +83 -0
  13. package/dist/graph.js +231 -0
  14. package/dist/index.d.ts +12 -4
  15. package/dist/index.js +6 -2
  16. package/dist/inspection.js +2 -2
  17. package/dist/job.d.ts +14 -0
  18. package/dist/job.js +5 -0
  19. package/dist/long-timer.d.ts +7 -0
  20. package/dist/long-timer.js +22 -0
  21. package/dist/observer-snapshot.d.ts +3 -0
  22. package/dist/observer-snapshot.js +46 -0
  23. package/dist/predicates.d.ts +4 -0
  24. package/dist/predicates.js +19 -2
  25. package/dist/recovery/binding.d.ts +10 -0
  26. package/dist/recovery/binding.js +43 -0
  27. package/dist/recovery/call-key.d.ts +13 -0
  28. package/dist/recovery/call-key.js +24 -0
  29. package/dist/recovery/canonical-hash.d.ts +7 -0
  30. package/dist/recovery/canonical-hash.js +22 -0
  31. package/dist/recovery/driver.d.ts +208 -0
  32. package/dist/recovery/driver.js +1222 -0
  33. package/dist/recovery/effect-failure.d.ts +34 -0
  34. package/dist/recovery/effect-failure.js +62 -0
  35. package/dist/recovery/errors.d.ts +31 -0
  36. package/dist/recovery/errors.js +51 -0
  37. package/dist/recovery/execution-path.d.ts +53 -0
  38. package/dist/recovery/execution-path.js +167 -0
  39. package/dist/recovery/file-store.d.ts +7 -0
  40. package/dist/recovery/file-store.js +131 -0
  41. package/dist/recovery/frozen-snapshot.d.ts +244 -0
  42. package/dist/recovery/frozen-snapshot.js +171 -0
  43. package/dist/recovery/handoff-block.d.ts +36 -0
  44. package/dist/recovery/handoff-block.js +148 -0
  45. package/dist/recovery/handoff-digest.d.ts +58 -0
  46. package/dist/recovery/handoff-digest.js +195 -0
  47. package/dist/recovery/handoff-files.d.ts +54 -0
  48. package/dist/recovery/handoff-files.js +162 -0
  49. package/dist/recovery/handoff-receipts.d.ts +42 -0
  50. package/dist/recovery/handoff-receipts.js +53 -0
  51. package/dist/recovery/handoff-redact.d.ts +12 -0
  52. package/dist/recovery/handoff-redact.js +44 -0
  53. package/dist/recovery/handoff.d.ts +44 -0
  54. package/dist/recovery/handoff.js +46 -0
  55. package/dist/recovery/index.d.ts +18 -0
  56. package/dist/recovery/index.js +16 -0
  57. package/dist/recovery/item-state.d.ts +48 -0
  58. package/dist/recovery/item-state.js +89 -0
  59. package/dist/recovery/journal.d.ts +28 -0
  60. package/dist/recovery/journal.js +139 -0
  61. package/dist/recovery/memory-store.d.ts +4 -0
  62. package/dist/recovery/memory-store.js +20 -0
  63. package/dist/recovery/store.d.ts +105 -0
  64. package/dist/recovery/store.js +6 -0
  65. package/dist/recovery/testing/conformance.d.ts +4 -0
  66. package/dist/recovery/testing/conformance.js +268 -0
  67. package/dist/recovery/testing/crash-points.d.ts +18 -0
  68. package/dist/recovery/testing/crash-points.js +43 -0
  69. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  70. package/dist/recovery/testing/crash-sweep.js +146 -0
  71. package/dist/recovery/testing/index.d.ts +3 -0
  72. package/dist/recovery/testing/index.js +4 -0
  73. package/dist/recovery/testing/preload.d.ts +1 -0
  74. package/dist/recovery/testing/preload.js +3 -0
  75. package/dist/recovery/transport-facts.d.ts +23 -0
  76. package/dist/recovery/transport-facts.js +46 -0
  77. package/dist/recovery/with-recovery.d.ts +44 -0
  78. package/dist/recovery/with-recovery.js +87 -0
  79. package/dist/system-one.d.ts +17 -1
  80. package/dist/system-one.js +62 -5
  81. package/dist/vocabulary.d.ts +42 -0
  82. package/dist/vocabulary.js +74 -0
  83. package/dist/workflow-shape.d.ts +7 -0
  84. package/dist/workflow-shape.js +85 -62
  85. package/dist/workflow.d.ts +187 -16
  86. package/dist/workflow.js +967 -324
  87. package/package.json +18 -2
  88. package/schema/workflow.schema.json +251 -15
  89. package/skills/author/SKILL.md +122 -0
  90. package/skills/author/examples/evidence-gate.input.json +6 -0
  91. package/skills/author/examples/evidence-gate.json +125 -0
  92. package/skills/author/examples/read-file.input.json +1 -0
  93. package/skills/author/examples/read-file.json +44 -0
  94. package/skills/author/examples/read-source-decision.input.json +4 -0
  95. package/skills/author/examples/read-source-decision.json +37 -0
  96. package/skills/author/examples/release-note.txt +10 -0
  97. package/skills/author/examples/review-release-notes.input.json +6 -0
  98. package/skills/author/examples/review-release-notes.json +123 -0
  99. package/skills/author/references/jev-decisions.md +125 -0
  100. package/skills/author/references/language.md +118 -0
  101. package/skills/author/references/sdk-authoring.md +11 -0
  102. package/skills/author/references/workflow-format.md +137 -0
package/dist/graph.js ADDED
@@ -0,0 +1,231 @@
1
+ // The graph of a workflow document, and what a run has done in it. This module imports nothing, so a reader with no Node
2
+ // (the static viewer inlines it) and the pi session's text view draw the same graph; nothing here validates, runs or
3
+ // reads a store. `workflowGraph` reads the workflow JSON as written; `nodeStatus` reads the driver's record of a run
4
+ // (the `agentrun.driver` frame of the frozen snapshot, and the `agentrun.items` of a keyed-layout run) and says, for
5
+ // each node of that graph, whether it is done, working, failed or not run; `graphNodeOf` names the node an execution path ran
6
+ // at, and the map items and loop iterations around it.
7
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8
+ const pointer = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
9
+ /** The nesting depth `validateWorkflow` and `inspectWorkflow` accept (128 JSON levels): a node nests at least one level deeper than its parent, so every node of such a document is within it. */
10
+ const MAX_DEPTH = 128;
11
+ /** The graph of `workflow`, computed from its JSON alone: nodes in document order (a node, then its descendants), and the
12
+ * edges between them. A value that is not a workflow, or a node the walk does not know, adds nothing and never throws:
13
+ * validation is `validateWorkflow`'s. */
14
+ export function workflowGraph(workflow) {
15
+ const nodes = [];
16
+ const edges = [];
17
+ const visit = (node, path, depth) => {
18
+ if (!isObject(node) || typeof node.node !== "string" || depth > MAX_DEPTH)
19
+ return;
20
+ nodes.push({ path, kind: node.node, label: typeof node.label === "string" ? node.label : node.node,
21
+ ...(node.node === "call" && typeof node.via === "string" ? { via: node.via } : {}) });
22
+ const child = (target, at, kind, from = path) => {
23
+ if (!isObject(target) || typeof target.node !== "string" || depth + 1 > MAX_DEPTH)
24
+ return;
25
+ edges.push({ from, to: at, kind });
26
+ visit(target, at, depth + 1);
27
+ };
28
+ switch (node.node) {
29
+ case "chain":
30
+ if (Array.isArray(node.steps))
31
+ node.steps.forEach((step, index) => child(step, `${path}/steps/${index}`, "next", index === 0 ? path : `${path}/steps/${index - 1}`));
32
+ break;
33
+ case "parallel":
34
+ if (Array.isArray(node.branches))
35
+ node.branches.forEach((branch, index) => child(branch, `${path}/branches/${index}`, "branch"));
36
+ break;
37
+ case "map":
38
+ child(node.body, `${path}/body`, "item");
39
+ break;
40
+ case "loop":
41
+ child(node.body, `${path}/body`, "next");
42
+ break;
43
+ case "route":
44
+ if (isObject(node.branches))
45
+ for (const [name, branch] of Object.entries(node.branches))
46
+ if (isObject(branch))
47
+ child(branch.body, `${path}/branches/${pointer(name)}/body`, "route");
48
+ break;
49
+ case "workflow":
50
+ if (isObject(node.workflow))
51
+ child(node.workflow.root, `${path}/workflow/root`, "child");
52
+ break;
53
+ }
54
+ };
55
+ visit(isObject(workflow) ? workflow.root : undefined, "/root", 0);
56
+ return { nodes, edges };
57
+ }
58
+ /** The execution path an instance of a node ran at, as the node's path in the document: a map's item and a loop's
59
+ * iteration have no node of their own. */
60
+ const definitionPath = (path) => path.replace(/\/items\/\d+\/body/g, "/body").replace(/\/iterations\/\d+(?=\/|$)/g, "");
61
+ const RANK = { working: 1, done: 2, failed: 3 };
62
+ /** For every node of `graph`, the state the record shows. `source` is what the driver kept: its frame and, in the keyed
63
+ * layout, the records of the map items (a run's whole story is the frame and the items together). A source that is not
64
+ * one of those shows no node run. */
65
+ export function nodeStatus(graph, source, options = {}) {
66
+ const instances = new Map();
67
+ const note = (path, state) => {
68
+ if (typeof path !== "string")
69
+ return;
70
+ const held = instances.get(path);
71
+ if (held === undefined || RANK[state] > RANK[held])
72
+ instances.set(path, state);
73
+ };
74
+ const readFrame = (frame) => {
75
+ if (!isObject(frame))
76
+ return;
77
+ if (isObject(frame.inputs))
78
+ for (const path of Object.keys(frame.inputs))
79
+ note(path, "working");
80
+ if (isObject(frame.steps))
81
+ for (const [path, step] of Object.entries(frame.steps)) {
82
+ const status = isObject(step) ? step.status : undefined;
83
+ note(path, status === "failed" ? "failed" : "working");
84
+ }
85
+ if (Array.isArray(frame.done))
86
+ for (const path of frame.done)
87
+ note(path, "done");
88
+ // A map that ended on an item's failure is kept as `partial` (its path and the finished items' results); no step or item says failed.
89
+ if (isObject(frame.partial) && typeof frame.partial.path === "string")
90
+ note(frame.partial.path, "failed");
91
+ };
92
+ const readItem = (item) => {
93
+ if (!isObject(item))
94
+ return;
95
+ readFrame(item.frame);
96
+ if (typeof item.map === "string" && Number.isInteger(item.index)) {
97
+ const body = `${item.map}/items/${item.index}/body`;
98
+ note(body, item.status === "committed" ? "done" : item.status === "failed" ? "failed" : "working");
99
+ }
100
+ };
101
+ const raw = source;
102
+ if (Array.isArray(raw))
103
+ raw.forEach(readItem);
104
+ else if (isObject(raw) && isObject(raw.pin)) {
105
+ readFrame(raw.pin);
106
+ if (Array.isArray(raw.items))
107
+ raw.items.forEach(readItem);
108
+ }
109
+ else
110
+ readFrame(raw);
111
+ // A done mark outranks a working one at the same path (a step's record stays after its node commits); a failure outranks both.
112
+ const byNode = new Map();
113
+ for (const [path, state] of instances) {
114
+ const at = definitionPath(path), list = byNode.get(at) ?? [];
115
+ list.push(state);
116
+ byNode.set(at, list);
117
+ }
118
+ const below = (path) => {
119
+ const found = [];
120
+ for (const [at, list] of byNode)
121
+ if (at.startsWith(`${path}/`))
122
+ found.push(...list);
123
+ return found;
124
+ };
125
+ const out = {};
126
+ for (const node of graph.nodes) {
127
+ const own = byNode.get(node.path) ?? [], inside = below(node.path);
128
+ out[node.path] = own.includes("failed") || inside.includes("failed") ? "failed"
129
+ : own.length && own.every((state) => state === "done") ? "done"
130
+ : own.includes("working") || inside.includes("working") ? "working"
131
+ : inside.length ? "working"
132
+ : own.length ? "working"
133
+ : "not-run";
134
+ }
135
+ // A chain is never recorded as done itself: the driver commits its steps. It is done when its steps all are, which a
136
+ // run that ended on its last step shows. Children are finished before their parents: the nodes are walked from the end.
137
+ for (const node of [...graph.nodes].reverse()) {
138
+ if (node.kind !== "chain" || byNode.has(node.path))
139
+ continue;
140
+ const prefix = `${node.path}/steps/`;
141
+ const steps = graph.nodes.filter((other) => other.path.startsWith(prefix) && /^\d+$/.test(other.path.slice(prefix.length)));
142
+ if (steps.length && steps.every((step) => out[step.path] === "done"))
143
+ out[node.path] = "done";
144
+ }
145
+ // A node inside a map's or a loop's body stands for every item or iteration, and the record names only those that started: it is
146
+ // done only when the map or loop is. Parents come before their descendants in the node list, so the container is settled first.
147
+ // The map or loop an `item` belongs to is the exception, and so is every one that encloses it: that item is the instance, and
148
+ // the source holds nothing of the items around it. A map or loop inside the item still stands for its own items.
149
+ const owner = typeof options.item === "string" ? definitionPath(options.item.replace(/\/(?:items|iterations)\/\d+$/, "")) : undefined;
150
+ const containers = graph.nodes.filter((node) => (node.kind === "map" || node.kind === "loop")
151
+ && !(owner !== undefined && (node.path === owner || owner.startsWith(`${node.path}/body`))));
152
+ for (const node of graph.nodes) {
153
+ if (out[node.path] !== "done")
154
+ continue;
155
+ if (containers.some((container) => node.path.startsWith(`${container.path}/body`) && out[container.path] !== "done"))
156
+ out[node.path] = "working";
157
+ }
158
+ return out;
159
+ }
160
+ /** An item or iteration index as an execution path writes it: a whole number with no sign and no leading zero. */
161
+ const indexOf = (segment) => segment !== undefined && /^(0|[1-9][0-9]*)$/.test(segment) && Number.isSafeInteger(Number(segment)) ? Number(segment) : undefined;
162
+ /** The graph node an execution path ran at. An execution path is the node's JSON Pointer with two runtime segments added:
163
+ * a map's item (`items/<i>` before the map's `body`) and a loop's iteration (`iterations/<i>` before the loop's `body`); the
164
+ * graph has `/body` for both, and the indexes are returned in `at`. The path is read by walking the graph from `/root`, by
165
+ * each node's kind, never by matching its text, so a route branch named `items` or `iterations` is a branch. Undefined for
166
+ * a path the graph does not have, or one that is not an execution path (a map's `body` without an item, an item without
167
+ * its `body`). */
168
+ export function graphNodeOf(graph, executionPath) {
169
+ if (typeof executionPath !== "string")
170
+ return undefined;
171
+ const kinds = new Map(graph.nodes.map((node) => [node.path, node.kind]));
172
+ const parts = executionPath.split("/");
173
+ if (parts[0] !== "" || parts[1] !== "root" || !kinds.has("/root"))
174
+ return undefined;
175
+ let path = "/root";
176
+ const at = [];
177
+ for (let i = 2; i < parts.length;) {
178
+ const [first, second, third] = [parts[i], parts[i + 1], parts[i + 2]];
179
+ let next;
180
+ switch (kinds.get(path)) {
181
+ case "chain":
182
+ if (first === "steps" && indexOf(second) !== undefined) {
183
+ next = `${path}/steps/${second}`;
184
+ i += 2;
185
+ }
186
+ break;
187
+ case "parallel":
188
+ if (first === "branches" && indexOf(second) !== undefined) {
189
+ next = `${path}/branches/${second}`;
190
+ i += 2;
191
+ }
192
+ break;
193
+ case "route":
194
+ // The branch's name, pointer-escaped as in the graph, whatever it is: `items`, `iterations`, `0`, and the empty name a
195
+ // route Jev chooses may give a branch, included.
196
+ if (first === "branches" && second !== undefined && third === "body") {
197
+ next = `${path}/branches/${second}/body`;
198
+ i += 3;
199
+ }
200
+ break;
201
+ case "workflow":
202
+ if (first === "workflow" && second === "root") {
203
+ next = `${path}/workflow/root`;
204
+ i += 2;
205
+ }
206
+ break;
207
+ case "map": {
208
+ const index = indexOf(second);
209
+ if (first === "items" && index !== undefined && third === "body") {
210
+ at.push({ kind: "item", index });
211
+ next = `${path}/body`;
212
+ i += 3;
213
+ }
214
+ break;
215
+ }
216
+ case "loop": {
217
+ const index = indexOf(second);
218
+ if (first === "iterations" && index !== undefined && third === "body") {
219
+ at.push({ kind: "iteration", index });
220
+ next = `${path}/body`;
221
+ i += 3;
222
+ }
223
+ break;
224
+ }
225
+ }
226
+ if (next === undefined || !kinds.has(next))
227
+ return undefined;
228
+ path = next;
229
+ }
230
+ return { path, at };
231
+ }
package/dist/index.d.ts CHANGED
@@ -1,15 +1,23 @@
1
1
  export { defineWorkflow, runTypedWorkflow, WorkflowSchemaConversionError } from "./authoring.js";
2
2
  export type { StandardJSONSchema, AuthoringSchema, TypedWorkflow, TypedWorkflowRunResult, WorkflowInput, WorkflowOutput, } from "./authoring.js";
3
- export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, } from "./workflow.js";
4
- export type { Workflow, WorkflowNode, WorkflowDeps, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CallRetryClass, CallPredicate, PollClause, ModelTier, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, MechanicalPredicate, Predicate, } from "./workflow.js";
3
+ export { runWorkflow, validateWorkflow, workflowSha256, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError, WorkflowCodeError, WorkflowStateError, WorkflowVerificationError, WorkflowDecisionRecordError, EffectFailure, EffectDeadlineExceededError, EffectOutcomeUnknownError, EscalationSignal, routesByValue, isItemFailure, } from "./workflow.js";
4
+ export { defineJob } from "./job.js";
5
+ export type { Job } from "./job.js";
6
+ export { DECISION_RECEIPT_VERSION, rederiveDecision } from "./decision-receipts.js";
7
+ export type { DecisionKind, DecisionReceipt, DecisionRule } from "./decision-receipts.js";
8
+ export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, MapItemFailure, DecisionExchange, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, MechanicalPredicate, Predicate, ValidationCode, ValidationIssue, } from "./workflow.js";
5
9
  export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
6
10
  export type { DryRunOptions, DryRunResult } from "./dry-run.js";
7
11
  export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, } from "./system-one.js";
8
- export type { SystemOneQuestion, SystemOneAnswer, SystemOneResult, SystemOneRetryClass, SystemOneResponseReason, CompiledQuestions, AnswersSidecar, } from "./system-one.js";
12
+ export type { SystemOneQuestion, SystemOneAnswer, SystemOneBox, SystemOneResult, SystemOneRetryClass, SystemOneResponseReason, CompiledQuestions, AnswersSidecar, } from "./system-one.js";
9
13
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
10
14
  export type { WorkflowInspection, WorkflowInspectionNode } from "./inspection.js";
11
15
  export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA, childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY, buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
12
- export { compileTransform, compileTransformSyntax } from "./code-exec.js";
16
+ export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
13
17
  export { resolveSchemaForWorkflow } from "./schema-references.js";
14
18
  export { getPath, predicateMatches } from "./predicates.js";
15
19
  export type { StopPredicate, AcceptPredicate } from "./predicates.js";
20
+ export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
21
+ export type { AuthorHostAddendum, CandidatePolicyOptions, AuthorWorkflowOptions, AuthoredWorkflow, HostOutputTypeOptions } from "./author.js";
22
+ export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
23
+ export type { WorkflowNodeKind, WorkflowPredicateName } from "./vocabulary.js";
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
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, rederiveDecision } from "./decision-receipts.js";
3
5
  export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
4
6
  export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, } from "./system-one.js";
5
7
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
@@ -8,6 +10,8 @@ export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSch
8
10
  childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
9
11
  // Host-side data helpers the interpreter itself uses: the same normalization and reference shaping.
10
12
  buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
11
- export { compileTransform, compileTransformSyntax } from "./code-exec.js";
13
+ export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
12
14
  export { resolveSchemaForWorkflow } from "./schema-references.js";
13
15
  export { getPath, predicateMatches } from "./predicates.js";
16
+ export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
17
+ export { WORKFLOW_NODE_KINDS, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, MECHANICAL_PREDICATES, WORKFLOW_PREDICATES, PREDICATE_FIELDS, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, } from "./vocabulary.js";
@@ -1,4 +1,4 @@
1
- import { workflowDocumentError, workflowSha256 } from "./workflow.js";
1
+ import { routesByValue, workflowDocumentError, workflowSha256 } from "./workflow.js";
2
2
  import { workflowShapeErrors } from "./workflow-shape.js";
3
3
  const pointer = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
4
4
  /** Inspect a workflow's structure without running authored code, adapters, or schema probes.
@@ -30,7 +30,7 @@ export function inspectWorkflow(value) {
30
30
  if (["agent", "decide", "extract", "report"].includes(node.node) ||
31
31
  node.node === "artifact" && ["markdown", "report"].includes(node.type))
32
32
  adapters.add("runNode");
33
- if (["judge", "pick", "sift", "route"].includes(node.node) ||
33
+ if (["judge", "pick", "sift"].includes(node.node) || node.node === "route" && !routesByValue(node) ||
34
34
  "verify" in node && node.verify || node.node === "loop" && node.until.predicate === "ask" ||
35
35
  node.node === "escalate" && node.when.predicate === "ask")
36
36
  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
+ }
@@ -30,5 +30,9 @@ export type AcceptPredicate = StopPredicate | {
30
30
  values: Array<string | number | boolean>;
31
31
  };
32
32
  export declare const MECHANICAL_PREDICATE_NAMES: ReadonlySet<string>;
33
+ /** Resolve a dotted state path the one way every reader does: a record by key, an array by a
34
+ * non-negative integer index, anything else (a string, a number, a missing value) to undefined.
35
+ * `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
36
+ * path that names a value for one names it for all. */
33
37
  export declare function getPath(value: unknown, key: string): unknown;
34
38
  export declare function predicateMatches(predicate: StopPredicate | AcceptPredicate, value: unknown): boolean;
@@ -1,11 +1,28 @@
1
- export const MECHANICAL_PREDICATE_NAMES = new Set(["no_new_items", "field_true", "count_gte", "empty", "field_equals", "in", "gte", "lt"]);
1
+ import { MECHANICAL_PREDICATES } from "./vocabulary.js";
2
+ export const MECHANICAL_PREDICATE_NAMES = new Set(MECHANICAL_PREDICATES);
2
3
  function isRecord(value) {
3
4
  return typeof value === "object" && value !== null && !Array.isArray(value);
4
5
  }
6
+ /** Resolve a dotted state path the one way every reader does: a record by key, an array by a
7
+ * non-negative integer index, anything else (a string, a number, a missing value) to undefined.
8
+ * `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
9
+ * path that names a value for one names it for all. */
5
10
  export function getPath(value, key) {
6
11
  if (!key)
7
12
  return value;
8
- return key.split(".").reduce((current, part) => (isRecord(current) ? current[part] : undefined), value);
13
+ return key.split(".").reduce((current, part) => {
14
+ if (isRecord(current))
15
+ return current[part];
16
+ if (Array.isArray(current)) {
17
+ // Only a position inside the array resolves: a canonical integer below its length. Anything
18
+ // else (a property name, an out-of-range or non-canonical number) is not an element.
19
+ if (!/^(0|[1-9][0-9]*)$/.test(part))
20
+ return undefined;
21
+ const index = Number(part);
22
+ return Number.isSafeInteger(index) && index < current.length ? current[index] : undefined;
23
+ }
24
+ return undefined;
25
+ }, value);
9
26
  }
10
27
  export function predicateMatches(predicate, value) {
11
28
  switch (predicate.predicate) {
@@ -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
+ }