@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
@@ -0,0 +1,169 @@
1
+ /** One node of the workflow as written. `path` is a JSON Pointer (RFC 6901) into the document: `/root` is the root,
2
+ * `/root/steps/1` a chain's second step, `/root/branches/<name>/body` a route's branch, `/root/body` a map's or a
3
+ * loop's body, `/root/workflow/root` a child workflow's root: the pointers `inspectWorkflow` and a validation issue
4
+ * use for the same node. `label` is the node's label, or its kind when it has none. `via` is a `call` node's transport.
5
+ * `changeCheck` detects a change to the node's own fields from one graph to another: 8 hex digits, the FNV-1a hash of
6
+ * the canonical JSON (keys sorted) of the node with its children left out as the walk leaves them out (a chain's steps,
7
+ * a parallel's branches, a map's or a loop's body, each route branch's body, a child workflow's root). A route's branch
8
+ * names are its own fields, since they decide which branch runs, so a route that gains or loses a branch is rewritten. It
9
+ * is not an identity and not a saved revision's sha256: two nodes with the same check are not the same node, and a check
10
+ * that stayed only means no change was seen. A graph built by hand may leave it out. */
11
+ export type GraphNode = {
12
+ path: string;
13
+ kind: string;
14
+ label: string;
15
+ via?: string;
16
+ changeCheck?: string;
17
+ } & GraphDecision;
18
+ /** One typed question a decision node asks, as a viewer shows it: its id, its type (`unknown` when its schema is not a
19
+ * question the reader recognizes), its instructions, and a choice's options. */
20
+ export type GraphQuestion = {
21
+ id: string;
22
+ type: "noul" | "choice" | "score" | "unknown";
23
+ instructions: string;
24
+ options?: string[];
25
+ };
26
+ /** What a decision node (judge, pick, sift, a judged route, or a loop or escalate whose predicate is `ask`) says about
27
+ * its decision, read from the document: the provider and model it names (absent when it names none), its questions, and
28
+ * the tokens of the images it sends. A graph of another node carries none of these. */
29
+ export type GraphDecision = {
30
+ provider?: string;
31
+ model?: string;
32
+ questions?: GraphQuestion[];
33
+ images?: string[];
34
+ };
35
+ /** How control reaches `to` from `from`.
36
+ * - `next`: a chain enters its first step and each step is followed by the next; a loop enters its body, which runs again
37
+ * until the loop ends.
38
+ * - `branch`: a parallel node starts each of its branches.
39
+ * - `route`: a route node takes one of its branches (the branch's name is the last pointer segment before `/body`).
40
+ * - `item`: a map runs its body once for each item.
41
+ * - `child`: a workflow node runs the child workflow's root. */
42
+ export type GraphEdgeKind = "next" | "branch" | "route" | "item" | "child";
43
+ export type GraphEdge = {
44
+ from: string;
45
+ to: string;
46
+ kind: GraphEdgeKind;
47
+ };
48
+ export type WorkflowGraph = {
49
+ nodes: GraphNode[];
50
+ edges: GraphEdge[];
51
+ };
52
+ /** The graph of `workflow`, computed from its JSON alone: nodes in document order (a node, then its descendants), and the
53
+ * edges between them. A value that is not a workflow, or a node the walk does not know, adds nothing and never throws:
54
+ * validation is `validateWorkflow`'s. */
55
+ export declare function workflowGraph(workflow: unknown): WorkflowGraph;
56
+ /** What a run has done at a node. A node inside a map's or a loop's body stands for every item or iteration, and the record names
57
+ * only those that started, so it is `done` only once the map or loop is: until then it is `working`, and a done node never
58
+ * goes back. A container (chain, parallel, map, loop, route, workflow) is `working` while some of
59
+ * its descendants are, or some are done and it is not; a node a run never reached, a branch a route did not take among
60
+ * them, is `not-run`. `escalated` is where the run ended on an escalation: the escalate node that fired and each container
61
+ * on its path. It is read from the run's terminal result, never from the frame, which holds no mark for that node. */
62
+ export type NodeState = "done" | "working" | "failed" | "not-run" | "escalated";
63
+ type Frame = {
64
+ done?: unknown;
65
+ steps?: unknown;
66
+ inputs?: unknown;
67
+ partial?: unknown;
68
+ };
69
+ /** The part of an `agentrun.items` value the status reads: the map item's `status` and its frame. */
70
+ export type ItemRecordLike = {
71
+ map?: unknown;
72
+ index?: unknown;
73
+ status?: unknown;
74
+ frame?: Frame;
75
+ };
76
+ /** The part of a run's terminal result the status reads: its `status` and, for an escalation, the execution path of the
77
+ * node it stopped at (`escalation.executionPath`, as `runWorkflow` returns it). */
78
+ export type TerminalResultLike = {
79
+ status?: unknown;
80
+ escalation?: {
81
+ executionPath?: unknown;
82
+ };
83
+ };
84
+ /** What `nodeStatus` reads: a driver frame (the `pin` of a frozen snapshot: `done`, `steps`, `inputs`), a frozen snapshot
85
+ * (its `pin`), or the map items' records, alone or together with the driver's record (`{ pin, items }`), and with it the
86
+ * run's terminal `result` once the run has ended. */
87
+ export type StatusSource = Frame | {
88
+ pin: Frame;
89
+ items?: readonly ItemRecordLike[];
90
+ result?: TerminalResultLike | null;
91
+ } | readonly ItemRecordLike[];
92
+ /** `item`: the source is one map item's (or loop iteration's) record, read on its own, and this is its execution path
93
+ * (`<map path>/items/<index>`, `<loop path>/iterations/<index>`). That item is then the instance, not one of many: its body is done
94
+ * when the item is, whether or not the map is. A map or loop inside the item still stands for all of its own items. */
95
+ export type StatusOptions = {
96
+ item?: string;
97
+ };
98
+ /** For every node of `graph`, the state the record shows. `source` is what the driver kept: its frame and, in the keyed
99
+ * layout, the records of the map items (a run's whole story is the frame and the items together). A source that is not
100
+ * one of those shows no node run. With the run's terminal `result`, an escalation that names a node of the graph marks
101
+ * that node and every container on its path `escalated`, and the maps and loops on that path have ended, so what finished
102
+ * inside them is done; without one, or when it names no node of the graph, nothing else changes. */
103
+ export declare function nodeStatus(graph: WorkflowGraph, source: StatusSource, options?: StatusOptions): Record<string, NodeState>;
104
+ /** Where an execution path is in the graph: the node it ran at (`path`, a node of the graph) and the map items and loop
105
+ * iterations it ran in, outermost first. */
106
+ export type GraphNodeAt = {
107
+ path: string;
108
+ at: {
109
+ kind: "item" | "iteration";
110
+ index: number;
111
+ }[];
112
+ };
113
+ /** The graph node an execution path ran at. An execution path is the node's JSON Pointer with two runtime segments added:
114
+ * a map's item (`items/<i>` before the map's `body`) and a loop's iteration (`iterations/<i>` before the loop's `body`); the
115
+ * graph has `/body` for both, and the indexes are returned in `at`. The path is read by walking the graph from `/root`, by
116
+ * each node's kind, never by matching its text, so a route branch named `items` or `iterations` is a branch. Undefined for
117
+ * 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
118
+ * its `body`). */
119
+ export declare function graphNodeOf(graph: WorkflowGraph, executionPath: string): GraphNodeAt | undefined;
120
+ /** A node as `graphDiff` reports it: its path in the graph it is in, its kind and its label. */
121
+ export type GraphDiffNode = {
122
+ path: string;
123
+ kind: string;
124
+ label: string;
125
+ };
126
+ /** What changed from one graph to the next. `added` holds nodes of `next` only (paths in `next`), `removed` nodes of `prev`
127
+ * only (paths in `prev`); `changed` the same node at the same path with a new kind or label; `moved` the same node at a
128
+ * new path; `rewritten` the same node, its kind and label as they were, with other own fields changed (its `changeCheck`
129
+ * differs: new instructions, a new budget), at its path in each graph; `edges.added` edges of `next` only and
130
+ * `edges.removed` edges of `prev` only, each in its own graph's paths. */
131
+ export type GraphDiff = {
132
+ added: GraphDiffNode[];
133
+ removed: GraphDiffNode[];
134
+ changed: {
135
+ prev: string;
136
+ next: string;
137
+ was: {
138
+ kind: string;
139
+ label: string;
140
+ };
141
+ now: {
142
+ kind: string;
143
+ label: string;
144
+ };
145
+ }[];
146
+ moved: {
147
+ prev: string;
148
+ next: string;
149
+ }[];
150
+ rewritten: {
151
+ prev: string;
152
+ next: string;
153
+ kind: string;
154
+ label: string;
155
+ }[];
156
+ edges: {
157
+ added: GraphEdge[];
158
+ removed: GraphEdge[];
159
+ };
160
+ };
161
+ /** What changed between two graphs of a workflow, such as two saved revisions of one. A node is the same in both when its
162
+ * `(kind, label)` is unique in each graph, wherever it is: a step inserted before others is one `added` node and the rest
163
+ * `moved`, never a run of changes. A node whose `(kind, label)` repeats in either graph, or is in one only, is the same
164
+ * as the other graph's node at its path, unless that node is already matched by its identity; with a new kind or label
165
+ * it is `changed`. A matched node with its kind and label as they were and another `changeCheck` is `rewritten`; a node
166
+ * without a check in either graph is never reported rewritten. An edge is the same when both its ends are the same nodes
167
+ * and its kind is the same. Every list is in its graph's node or edge order. */
168
+ export declare function graphDiff(prev: WorkflowGraph, next: WorkflowGraph): GraphDiff;
169
+ export {};
package/dist/graph.js ADDED
@@ -0,0 +1,433 @@
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, or, given the run's terminal result, where an
6
+ // escalation stopped it; `graphNodeOf` names the node an execution path ran
7
+ // at, and the map items and loop iterations around it; `graphDiff` says what changed between two graphs of a workflow.
8
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9
+ const pointer = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
10
+ /** 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. */
11
+ const MAX_DEPTH = 128;
12
+ /** A value as canonical JSON: object keys sorted, undefined members left out, other values as JSON writes them. Deeper
13
+ * than `MAX_DEPTH` a value is written as one marker, so a value that is not JSON (a cycle) still ends. A leaf JSON
14
+ * cannot encode (a bigint, a symbol) is written as a marker of its type, so changeCheck is total: `workflowGraph` never
15
+ * throws on a node the validator accepts, and such a leaf still changes the check when it changes value. */
16
+ const leaf = (value) => {
17
+ try {
18
+ return JSON.stringify(value) ?? "null";
19
+ }
20
+ catch {
21
+ return JSON.stringify(`[${typeof value}:${String(value)}]`);
22
+ }
23
+ };
24
+ const canonicalJson = (value, depth = 0) => {
25
+ if (depth > MAX_DEPTH)
26
+ return '"…"';
27
+ if (Array.isArray(value))
28
+ return `[${value.map((item) => canonicalJson(item, depth + 1)).join(",")}]`;
29
+ if (isObject(value))
30
+ return `{${Object.keys(value).filter((key) => value[key] !== undefined).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key], depth + 1)}`).join(",")}}`;
31
+ return leaf(value);
32
+ };
33
+ /** FNV-1a (32 bits) over the UTF-16 code units of `text`, as 8 hex digits. */
34
+ const fnv1a = (text) => {
35
+ let hash = 0x811c9dc5;
36
+ for (let i = 0; i < text.length; i += 1)
37
+ hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193);
38
+ return (hash >>> 0).toString(16).padStart(8, "0");
39
+ };
40
+ const without = (value, key) => Object.fromEntries(Object.entries(value).filter(([name]) => name !== key));
41
+ /** A node's own fields: the node with the children the walk visits left out. */
42
+ const ownFields = (node) => {
43
+ switch (node.node) {
44
+ case "chain": return without(node, "steps");
45
+ case "parallel": return without(node, "branches");
46
+ case "map":
47
+ case "loop": return without(node, "body");
48
+ case "route": return isObject(node.branches)
49
+ ? { ...node, branches: Object.fromEntries(Object.entries(node.branches).map(([name, branch]) => [name, isObject(branch) ? without(branch, "body") : branch])) }
50
+ : node;
51
+ case "workflow": return isObject(node.workflow) ? { ...node, workflow: without(node.workflow, "root") } : node;
52
+ default: return node;
53
+ }
54
+ };
55
+ /** The graph of `workflow`, computed from its JSON alone: nodes in document order (a node, then its descendants), and the
56
+ * edges between them. A value that is not a workflow, or a node the walk does not know, adds nothing and never throws:
57
+ * validation is `validateWorkflow`'s. */
58
+ export function workflowGraph(workflow) {
59
+ const nodes = [];
60
+ const edges = [];
61
+ const visit = (node, path, depth, schemas) => {
62
+ if (!isObject(node) || typeof node.node !== "string" || depth > MAX_DEPTH)
63
+ return;
64
+ nodes.push({ path, kind: node.node, label: typeof node.label === "string" ? node.label : node.node,
65
+ ...(node.node === "call" && typeof node.via === "string" ? { via: node.via } : {}), changeCheck: fnv1a(canonicalJson(ownFields(node))),
66
+ ...decisionOf(node, schemas) });
67
+ const child = (target, at, kind, from = path, inner = schemas) => {
68
+ if (!isObject(target) || typeof target.node !== "string" || depth + 1 > MAX_DEPTH)
69
+ return;
70
+ edges.push({ from, to: at, kind });
71
+ visit(target, at, depth + 1, inner);
72
+ };
73
+ switch (node.node) {
74
+ case "chain":
75
+ if (Array.isArray(node.steps))
76
+ node.steps.forEach((step, index) => child(step, `${path}/steps/${index}`, "next", index === 0 ? path : `${path}/steps/${index - 1}`));
77
+ break;
78
+ case "parallel":
79
+ if (Array.isArray(node.branches))
80
+ node.branches.forEach((branch, index) => child(branch, `${path}/branches/${index}`, "branch"));
81
+ break;
82
+ case "map":
83
+ child(node.body, `${path}/body`, "item");
84
+ break;
85
+ case "loop":
86
+ child(node.body, `${path}/body`, "next");
87
+ break;
88
+ case "route":
89
+ if (isObject(node.branches))
90
+ for (const [name, branch] of Object.entries(node.branches))
91
+ if (isObject(branch))
92
+ child(branch.body, `${path}/branches/${pointer(name)}/body`, "route");
93
+ break;
94
+ case "workflow":
95
+ if (isObject(node.workflow))
96
+ child(node.workflow.root, `${path}/workflow/root`, "child", path, isObject(node.workflow.schemas) ? node.workflow.schemas : {});
97
+ break;
98
+ }
99
+ };
100
+ visit(isObject(workflow) ? workflow.root : undefined, "/root", 0, isObject(workflow) && isObject(workflow.schemas) ? workflow.schemas : {});
101
+ return { nodes, edges };
102
+ }
103
+ /** The questions of a question schema (`out` of a judge or sift): a flat object whose properties are the questions, a
104
+ * string enum a choice, a boolean a noul, an integer a score; a local `#/definitions/<id>` reference is followed. */
105
+ const schemaQuestions = (schemaId, schemas) => {
106
+ const root = typeof schemaId === "string" && Object.hasOwn(schemas, schemaId) ? schemas[schemaId] : undefined;
107
+ const resolve = (spec) => {
108
+ for (let hops = 0; isObject(spec) && typeof spec.$ref === "string" && hops < 8; hops += 1) {
109
+ const id = /^#\/definitions\/(.+)$/.exec(spec.$ref)?.[1];
110
+ const inline = isObject(root) && isObject(root.definitions) ? root.definitions : {};
111
+ spec = id === undefined ? undefined : Object.hasOwn(inline, id) ? inline[id] : Object.hasOwn(schemas, id) ? schemas[id] : undefined;
112
+ }
113
+ return spec;
114
+ };
115
+ const object = resolve(root);
116
+ if (!isObject(object) || !isObject(object.properties))
117
+ return [];
118
+ return Object.entries(object.properties).map(([id, raw]) => {
119
+ const spec = resolve(raw);
120
+ const instructions = isObject(spec) && typeof spec.description === "string" ? spec.description : "";
121
+ const types = isObject(spec) ? (Array.isArray(spec.type) ? spec.type : [spec.type]).filter((type) => type !== "null") : [];
122
+ if (isObject(spec) && Array.isArray(spec.enum))
123
+ return { id, type: "choice", instructions, options: spec.enum.map(String) };
124
+ if (types.length === 1 && types[0] === "boolean")
125
+ return { id, type: "noul", instructions };
126
+ if (types.length === 1 && types[0] === "integer")
127
+ return { id, type: "score", instructions };
128
+ return { id, type: "unknown", instructions };
129
+ });
130
+ };
131
+ /** A decision node's provider, model, questions and image tokens, as written. */
132
+ const decisionOf = (node, schemas) => {
133
+ let source = node;
134
+ let questions;
135
+ const text = (value) => typeof value === "string" ? value : "";
136
+ switch (node.node) {
137
+ case "judge":
138
+ case "sift":
139
+ questions = schemaQuestions(node.out, schemas);
140
+ break;
141
+ case "pick":
142
+ questions = [{ id: "pick", type: "choice", instructions: text(node.instructions) }];
143
+ break;
144
+ case "route":
145
+ if (node.valuePath !== undefined)
146
+ return {};
147
+ questions = [{ id: "branch", type: "choice", instructions: text(node.instructions), options: isObject(node.branches) ? Object.keys(node.branches) : [] }];
148
+ break;
149
+ case "loop":
150
+ case "escalate": {
151
+ const predicate = node.node === "loop" ? node.until : node.when;
152
+ if (!isObject(predicate) || predicate.predicate !== "ask")
153
+ return {};
154
+ source = predicate;
155
+ questions = [{ id: "holds", type: "noul", instructions: text(predicate.instructions) }];
156
+ break;
157
+ }
158
+ default: return {};
159
+ }
160
+ return {
161
+ ...(typeof source.provider === "string" ? { provider: source.provider } : {}),
162
+ ...(typeof source.model === "string" ? { model: source.model } : {}),
163
+ questions,
164
+ ...(isObject(source.images) && Object.keys(source.images).length ? { images: Object.keys(source.images) } : {}),
165
+ };
166
+ };
167
+ /** 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
168
+ * iteration have no node of their own. */
169
+ const definitionPath = (path) => path.replace(/\/items\/\d+\/body/g, "/body").replace(/\/iterations\/\d+(?=\/|$)/g, "");
170
+ const RANK = { working: 1, done: 2, failed: 3 };
171
+ /** For every node of `graph`, the state the record shows. `source` is what the driver kept: its frame and, in the keyed
172
+ * layout, the records of the map items (a run's whole story is the frame and the items together). A source that is not
173
+ * one of those shows no node run. With the run's terminal `result`, an escalation that names a node of the graph marks
174
+ * that node and every container on its path `escalated`, and the maps and loops on that path have ended, so what finished
175
+ * inside them is done; without one, or when it names no node of the graph, nothing else changes. */
176
+ export function nodeStatus(graph, source, options = {}) {
177
+ const instances = new Map();
178
+ const note = (path, state) => {
179
+ if (typeof path !== "string")
180
+ return;
181
+ const held = instances.get(path);
182
+ if (held === undefined || RANK[state] > RANK[held])
183
+ instances.set(path, state);
184
+ };
185
+ const readFrame = (frame) => {
186
+ if (!isObject(frame))
187
+ return;
188
+ if (isObject(frame.inputs))
189
+ for (const path of Object.keys(frame.inputs))
190
+ note(path, "working");
191
+ if (isObject(frame.steps))
192
+ for (const [path, step] of Object.entries(frame.steps)) {
193
+ const status = isObject(step) ? step.status : undefined;
194
+ note(path, status === "failed" ? "failed" : "working");
195
+ }
196
+ if (Array.isArray(frame.done))
197
+ for (const path of frame.done)
198
+ note(path, "done");
199
+ // 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.
200
+ if (isObject(frame.partial) && typeof frame.partial.path === "string")
201
+ note(frame.partial.path, "failed");
202
+ };
203
+ const readItem = (item) => {
204
+ if (!isObject(item))
205
+ return;
206
+ readFrame(item.frame);
207
+ if (typeof item.map === "string" && Number.isInteger(item.index)) {
208
+ const body = `${item.map}/items/${item.index}/body`;
209
+ note(body, item.status === "committed" ? "done" : item.status === "failed" ? "failed" : "working");
210
+ }
211
+ };
212
+ const raw = source;
213
+ if (Array.isArray(raw))
214
+ raw.forEach(readItem);
215
+ else if (isObject(raw) && isObject(raw.pin)) {
216
+ readFrame(raw.pin);
217
+ if (Array.isArray(raw.items))
218
+ raw.items.forEach(readItem);
219
+ }
220
+ else
221
+ readFrame(raw);
222
+ // The node a run's escalation ended at, from its terminal result: by its execution path, as the node it ran as.
223
+ const result = isObject(raw) && isObject(raw.pin) && isObject(raw.result) ? raw.result : undefined;
224
+ const escalation = result?.status === "escalated" && isObject(result.escalation) ? result.escalation : undefined;
225
+ const escalatedExecPath = typeof escalation?.executionPath === "string" ? escalation.executionPath : undefined;
226
+ // When one map item or loop iteration is read on its own (`options.item`), the escalation belongs to this view only if
227
+ // it fired inside that same instance: another item's escalation, reduced to the shared body, must not mark this one's
228
+ // body escalated. The item index is in the raw execution path, which `definitionPath` then strips.
229
+ const itemScope = typeof options.item === "string" ? options.item.replace(/\/$/, "") : undefined;
230
+ const inThisItem = escalatedExecPath !== undefined
231
+ && (itemScope === undefined || escalatedExecPath === itemScope || escalatedExecPath.startsWith(`${itemScope}/`));
232
+ const stoppedAt = escalatedExecPath !== undefined && inThisItem ? definitionPath(escalatedExecPath) : undefined;
233
+ const ended = stoppedAt !== undefined && graph.nodes.some((node) => node.path === stoppedAt) ? stoppedAt : undefined;
234
+ const onPath = (path) => ended !== undefined && (path === ended || ended.startsWith(`${path}/`));
235
+ // A done mark outranks a working one at the same path (a step's record stays after its node commits); a failure outranks both.
236
+ const byNode = new Map();
237
+ for (const [path, state] of instances) {
238
+ const at = definitionPath(path), list = byNode.get(at) ?? [];
239
+ list.push(state);
240
+ byNode.set(at, list);
241
+ }
242
+ const below = (path) => {
243
+ const found = [];
244
+ for (const [at, list] of byNode)
245
+ if (at.startsWith(`${path}/`))
246
+ found.push(...list);
247
+ return found;
248
+ };
249
+ const out = {};
250
+ for (const node of graph.nodes) {
251
+ const own = byNode.get(node.path) ?? [], inside = below(node.path);
252
+ out[node.path] = own.includes("failed") || inside.includes("failed") ? "failed"
253
+ : own.length && own.every((state) => state === "done") ? "done"
254
+ : own.includes("working") || inside.includes("working") ? "working"
255
+ : inside.length ? "working"
256
+ : own.length ? "working"
257
+ : "not-run";
258
+ }
259
+ // A chain is never recorded as done itself: the driver commits its steps. It is done when its steps all are, which a
260
+ // run that ended on its last step shows. Children are finished before their parents: the nodes are walked from the end.
261
+ for (const node of [...graph.nodes].reverse()) {
262
+ if (node.kind !== "chain" || byNode.has(node.path))
263
+ continue;
264
+ const prefix = `${node.path}/steps/`;
265
+ const steps = graph.nodes.filter((other) => other.path.startsWith(prefix) && /^\d+$/.test(other.path.slice(prefix.length)));
266
+ if (steps.length && steps.every((step) => out[step.path] === "done"))
267
+ out[node.path] = "done";
268
+ }
269
+ // 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
270
+ // done only when the map or loop is. Parents come before their descendants in the node list, so the container is settled first.
271
+ // 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
272
+ // the source holds nothing of the items around it. A map or loop inside the item still stands for its own items.
273
+ const owner = typeof options.item === "string" ? definitionPath(options.item.replace(/\/(?:items|iterations)\/\d+$/, "")) : undefined;
274
+ // A map or loop on an escalation's path has ended: no other item or iteration will run, so what finished inside it is done.
275
+ const containers = graph.nodes.filter((node) => (node.kind === "map" || node.kind === "loop") && !onPath(node.path)
276
+ && !(owner !== undefined && (node.path === owner || owner.startsWith(`${node.path}/body`))));
277
+ for (const node of graph.nodes) {
278
+ if (out[node.path] !== "done")
279
+ continue;
280
+ if (containers.some((container) => node.path.startsWith(`${container.path}/body`) && out[container.path] !== "done"))
281
+ out[node.path] = "working";
282
+ }
283
+ // The run ended at the escalate node that fired, and in each container on its path; a failure recorded below a container
284
+ // still shows.
285
+ for (const node of graph.nodes)
286
+ if (onPath(node.path) && (node.path === ended || out[node.path] !== "failed"))
287
+ out[node.path] = "escalated";
288
+ return out;
289
+ }
290
+ /** An item or iteration index as an execution path writes it: a whole number with no sign and no leading zero. */
291
+ const indexOf = (segment) => segment !== undefined && /^(0|[1-9][0-9]*)$/.test(segment) && Number.isSafeInteger(Number(segment)) ? Number(segment) : undefined;
292
+ /** The graph node an execution path ran at. An execution path is the node's JSON Pointer with two runtime segments added:
293
+ * a map's item (`items/<i>` before the map's `body`) and a loop's iteration (`iterations/<i>` before the loop's `body`); the
294
+ * graph has `/body` for both, and the indexes are returned in `at`. The path is read by walking the graph from `/root`, by
295
+ * each node's kind, never by matching its text, so a route branch named `items` or `iterations` is a branch. Undefined for
296
+ * 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
297
+ * its `body`). */
298
+ export function graphNodeOf(graph, executionPath) {
299
+ if (typeof executionPath !== "string")
300
+ return undefined;
301
+ const kinds = new Map(graph.nodes.map((node) => [node.path, node.kind]));
302
+ const parts = executionPath.split("/");
303
+ if (parts[0] !== "" || parts[1] !== "root" || !kinds.has("/root"))
304
+ return undefined;
305
+ let path = "/root";
306
+ const at = [];
307
+ for (let i = 2; i < parts.length;) {
308
+ const [first, second, third] = [parts[i], parts[i + 1], parts[i + 2]];
309
+ let next;
310
+ switch (kinds.get(path)) {
311
+ case "chain":
312
+ if (first === "steps" && indexOf(second) !== undefined) {
313
+ next = `${path}/steps/${second}`;
314
+ i += 2;
315
+ }
316
+ break;
317
+ case "parallel":
318
+ if (first === "branches" && indexOf(second) !== undefined) {
319
+ next = `${path}/branches/${second}`;
320
+ i += 2;
321
+ }
322
+ break;
323
+ case "route":
324
+ // The branch's name, pointer-escaped as in the graph, whatever it is: `items`, `iterations`, `0`, and the empty name a
325
+ // route Jev chooses may give a branch, included.
326
+ if (first === "branches" && second !== undefined && third === "body") {
327
+ next = `${path}/branches/${second}/body`;
328
+ i += 3;
329
+ }
330
+ break;
331
+ case "workflow":
332
+ if (first === "workflow" && second === "root") {
333
+ next = `${path}/workflow/root`;
334
+ i += 2;
335
+ }
336
+ break;
337
+ case "map": {
338
+ const index = indexOf(second);
339
+ if (first === "items" && index !== undefined && third === "body") {
340
+ at.push({ kind: "item", index });
341
+ next = `${path}/body`;
342
+ i += 3;
343
+ }
344
+ break;
345
+ }
346
+ case "loop": {
347
+ const index = indexOf(second);
348
+ if (first === "iterations" && index !== undefined && third === "body") {
349
+ at.push({ kind: "iteration", index });
350
+ next = `${path}/body`;
351
+ i += 3;
352
+ }
353
+ break;
354
+ }
355
+ }
356
+ if (next === undefined || !kinds.has(next))
357
+ return undefined;
358
+ path = next;
359
+ }
360
+ return { path, at };
361
+ }
362
+ /** What changed between two graphs of a workflow, such as two saved revisions of one. A node is the same in both when its
363
+ * `(kind, label)` is unique in each graph, wherever it is: a step inserted before others is one `added` node and the rest
364
+ * `moved`, never a run of changes. A node whose `(kind, label)` repeats in either graph, or is in one only, is the same
365
+ * as the other graph's node at its path, unless that node is already matched by its identity; with a new kind or label
366
+ * it is `changed`. A matched node with its kind and label as they were and another `changeCheck` is `rewritten`; a node
367
+ * without a check in either graph is never reported rewritten. An edge is the same when both its ends are the same nodes
368
+ * and its kind is the same. Every list is in its graph's node or edge order. */
369
+ export function graphDiff(prev, next) {
370
+ const identity = (node) => JSON.stringify([node.kind, node.label]);
371
+ const counts = (graph) => {
372
+ const count = new Map();
373
+ for (const node of graph.nodes)
374
+ count.set(identity(node), (count.get(identity(node)) ?? 0) + 1);
375
+ return count;
376
+ };
377
+ const [inPrev, inNext] = [counts(prev), counts(next)];
378
+ const unique = (node) => inPrev.get(identity(node)) === 1 && inNext.get(identity(node)) === 1;
379
+ // The matched nodes, each way: a path of `next` to its node's path in `prev`, and back.
380
+ const prevOf = new Map();
381
+ const nextOf = new Map();
382
+ const match = (from, to) => { prevOf.set(to, from); nextOf.set(from, to); };
383
+ const uniqueInPrev = new Map(prev.nodes.filter(unique).map((node) => [identity(node), node.path]));
384
+ for (const node of next.nodes) {
385
+ const at = unique(node) ? uniqueInPrev.get(identity(node)) : undefined;
386
+ if (at !== undefined)
387
+ match(at, node.path);
388
+ }
389
+ const prevAt = new Map(prev.nodes.map((node) => [node.path, node]));
390
+ const changed = [];
391
+ for (const node of next.nodes) {
392
+ const old = prevAt.get(node.path);
393
+ if (prevOf.has(node.path) || old === undefined || nextOf.has(old.path))
394
+ continue;
395
+ match(old.path, node.path);
396
+ if (old.kind !== node.kind || old.label !== node.label) {
397
+ changed.push({ prev: old.path, next: node.path, was: { kind: old.kind, label: old.label }, now: { kind: node.kind, label: node.label } });
398
+ }
399
+ }
400
+ const rewritten = [];
401
+ for (const node of next.nodes) {
402
+ const from = prevOf.get(node.path);
403
+ const old = from === undefined ? undefined : prevAt.get(from);
404
+ if (old === undefined || old.kind !== node.kind || old.label !== node.label)
405
+ continue;
406
+ if (old.changeCheck !== undefined && node.changeCheck !== undefined && old.changeCheck !== node.changeCheck) {
407
+ rewritten.push({ prev: old.path, next: node.path, kind: node.kind, label: node.label });
408
+ }
409
+ }
410
+ const reported = ({ path, kind, label }) => ({ path, kind, label });
411
+ const edgeKey = (from, to, kind) => JSON.stringify([from, to, kind]);
412
+ const prevEdges = new Set(prev.edges.map((edge) => edgeKey(edge.from, edge.to, edge.kind)));
413
+ const nextEdges = new Set(next.edges.map((edge) => edgeKey(edge.from, edge.to, edge.kind)));
414
+ // Whether the other graph has this edge: both its ends matched there, joined by an edge of the same kind.
415
+ const theirs = (edge, map, edges) => {
416
+ const [from, to] = [map.get(edge.from), map.get(edge.to)];
417
+ return from !== undefined && to !== undefined && edges.has(edgeKey(from, to, edge.kind));
418
+ };
419
+ return {
420
+ added: next.nodes.filter((node) => !prevOf.has(node.path)).map(reported),
421
+ removed: prev.nodes.filter((node) => !nextOf.has(node.path)).map(reported),
422
+ changed,
423
+ moved: next.nodes.flatMap((node) => {
424
+ const from = prevOf.get(node.path);
425
+ return from !== undefined && from !== node.path ? [{ prev: from, next: node.path }] : [];
426
+ }),
427
+ rewritten,
428
+ edges: {
429
+ added: next.edges.filter((edge) => !theirs(edge, prevOf, prevEdges)).map(({ from, to, kind }) => ({ from, to, kind })),
430
+ removed: prev.edges.filter((edge) => !theirs(edge, nextOf, nextEdges)).map(({ from, to, kind }) => ({ from, to, kind })),
431
+ },
432
+ };
433
+ }
package/dist/index.d.ts CHANGED
@@ -1,19 +1,26 @@
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, DECISION_INTERRUPTED, DECISION_REFUSED, DECISION_STATE_MAX_BYTES, rederiveDecision } from "./decision-receipts.js";
7
+ export type { DecisionImageDigest, 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, DecisionEvidenceMode, DecisionImages, MechanicalPredicate, Predicate, ValidationCode, ValidationIssue, ValidateWorkflowOptions, } from "./workflow.js";
5
9
  export { dryRunWorkflow, synthesizeInstance } from "./dry-run.js";
6
10
  export type { DryRunOptions, DryRunResult } from "./dry-run.js";
7
- 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";
11
+ export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, deriveConfidence, completeConfidence, refusedQuestions, } from "./system-one.js";
12
+ export type { SystemOneQuestion, SystemOneAnswer, SystemOneBox, SystemOneResult, SystemOneRetryClass, SystemOneResponseReason, CompiledQuestions, AnswersSidecar, ConfidenceSource, } from "./system-one.js";
13
+ export { judgeFromProvider, judgeFromProviders, checkCapabilities, DecisionProviderError, imageDimensions } from "./decision-provider.js";
14
+ export type { DecisionProvider, DecisionCapabilities, DecisionInput, DecisionRequest, DecisionContext, DecisionEvidence, DecisionOutcome, ProviderAnswer, CostBasis, DecisionProviderErrorCode, DecisionImage, LoadImage, JudgeFromProviderOptions, } from "./decision-provider.js";
9
15
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
10
16
  export type { WorkflowInspection, WorkflowInspectionNode } from "./inspection.js";
11
17
  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";
18
+ export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
13
19
  export { resolveSchemaForWorkflow } from "./schema-references.js";
20
+ export { submitParameters } from "./submit-envelope.js";
14
21
  export { getPath, predicateMatches } from "./predicates.js";
15
22
  export type { StopPredicate, AcceptPredicate } from "./predicates.js";
16
23
  export { authorContract, renderAuthorContract, renderAuthorHostAddendum, candidatePolicyErrors, applyHostOutputTypes, authorWorkflow, AUTHOR_SKILL_NAME, authorSkillDirectory, loadAuthorReference, loadAuthorSkillBundle, } from "./author.js";
17
- export type { AuthorHostAddendum, CandidatePolicyOptions, AuthorWorkflowOptions, AuthoredWorkflow } from "./author.js";
18
- 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 type { WorkflowNodeKind, WorkflowPredicateName } from "./vocabulary.js";
24
+ export type { AuthorHostAddendum, CandidatePolicyOptions, AuthorWorkflowOptions, AuthoredWorkflow, HostOutputTypeOptions } from "./author.js";
25
+ 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";
26
+ export type { WorkflowNodeKind, WorkflowPredicateName, FieldType } from "./vocabulary.js";