@parcha/agentrun-dsl 0.1.0-beta.32 → 0.1.0-beta.321

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 (67) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +13 -7
  3. package/dist/author-references.d.ts +2 -2
  4. package/dist/author-references.js +2 -2
  5. package/dist/author.d.ts +0 -2
  6. package/dist/author.js +7 -6
  7. package/dist/authoring.js +3 -2
  8. package/dist/cli.js +2 -1
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +11 -2
  12. package/dist/decision-provider.js +9 -3
  13. package/dist/decision-receipts.d.ts +19 -3
  14. package/dist/dry-run.d.ts +31 -1
  15. package/dist/dry-run.js +103 -14
  16. package/dist/edit.d.ts +158 -0
  17. package/dist/edit.js +1486 -0
  18. package/dist/evidence.js +2 -1
  19. package/dist/index.d.ts +10 -8
  20. package/dist/index.js +12 -8
  21. package/dist/pattern-screen.d.ts +14 -0
  22. package/dist/pattern-screen.js +451 -0
  23. package/dist/pointer-warning.d.ts +14 -0
  24. package/dist/pointer-warning.js +22 -0
  25. package/dist/predicates.d.ts +23 -3
  26. package/dist/predicates.js +48 -6
  27. package/dist/record.d.ts +4 -0
  28. package/dist/record.js +6 -0
  29. package/dist/recovery/binding.js +2 -1
  30. package/dist/recovery/call-key.d.ts +0 -4
  31. package/dist/recovery/call-key.js +0 -7
  32. package/dist/recovery/driver.d.ts +9 -14
  33. package/dist/recovery/driver.js +29 -26
  34. package/dist/recovery/frozen-snapshot.js +8 -8
  35. package/dist/recovery/handoff-receipts.d.ts +0 -35
  36. package/dist/recovery/handoff-receipts.js +2 -44
  37. package/dist/recovery/index.d.ts +2 -7
  38. package/dist/recovery/index.js +2 -6
  39. package/dist/recovery/item-state.d.ts +2 -1
  40. package/dist/recovery/item-state.js +7 -13
  41. package/dist/recovery/with-recovery.js +4 -2
  42. package/dist/submit-envelope.d.ts +1 -1
  43. package/dist/submit-envelope.js +11 -7
  44. package/dist/system-one.d.ts +0 -4
  45. package/dist/system-one.js +7 -8
  46. package/dist/vocabulary.d.ts +7 -2
  47. package/dist/vocabulary.js +7 -1
  48. package/dist/workflow-shape.js +4 -2
  49. package/dist/workflow.d.ts +58 -13
  50. package/dist/workflow.js +399 -180
  51. package/dist/zod-json-contract.js +6 -8
  52. package/package.json +18 -2
  53. package/schema/workflow.schema.json +93 -0
  54. package/skills/author/references/jev-decisions.md +10 -5
  55. package/skills/author/references/language.md +5 -4
  56. package/dist/recovery/effect-failure.d.ts +0 -34
  57. package/dist/recovery/effect-failure.js +0 -62
  58. package/dist/recovery/handoff-block.d.ts +0 -36
  59. package/dist/recovery/handoff-block.js +0 -148
  60. package/dist/recovery/handoff-digest.d.ts +0 -58
  61. package/dist/recovery/handoff-digest.js +0 -195
  62. package/dist/recovery/handoff-files.d.ts +0 -54
  63. package/dist/recovery/handoff-files.js +0 -162
  64. package/dist/recovery/handoff-redact.d.ts +0 -12
  65. package/dist/recovery/handoff-redact.js +0 -44
  66. package/dist/recovery/handoff.d.ts +0 -44
  67. package/dist/recovery/handoff.js +0 -46
package/dist/edit.js ADDED
@@ -0,0 +1,1486 @@
1
+ // Edits to a workflow document, each a pure function from one document to the next, so a visual editor, a CLI and a
2
+ // server can share them and the JSON stays the source of truth. A node is named by its JSON Pointer, the path
3
+ // `workflowGraph` gives it. This module imports only the graph and the vocabulary, which import nothing, so a browser
4
+ // bundles it.
5
+ //
6
+ // Every operation takes the document and returns `{ doc, moved, added, removed, changed }`. It never mutates its input,
7
+ // and a subtree it did not touch is shared with the input, so it keeps its bytes. `moved` maps each node whose path
8
+ // changed, in the input's document order; `added` and `removed` list the nodes that exist only after or only before;
9
+ // `changed` lists the nodes whose own fields changed (their `changeCheck` in `workflowGraph`).
10
+ //
11
+ // An operation that would break the document's structure throws one `EditError` and writes nothing. That covers a
12
+ // placement the schema forbids, a node of no known kind, a missing required field, and a container left without its
13
+ // children. Each error carries a code from `EDIT_ERROR_CODES` and the path it is about, in the input's coordinates
14
+ // where the node existed there. An edit to a document that is already broken is allowed, as long as it adds no new
15
+ // break.
16
+ //
17
+ // The checks here are structural. Whether a reference is produced upstream, a field is well typed or a placeholder
18
+ // is filled in is the validator's call: it draws its issues on nodes at these same paths.
19
+ //
20
+ // Choices made where the semantics are the product's to decide; each takes the conservative option:
21
+ // - insert into a slot that holds one node (a map's or a loop's body, a route branch, a child workflow's root, the
22
+ // document's root) makes a chain of the two: index 0 puts the new node first, 1 puts it last. An empty slot takes the
23
+ // node itself.
24
+ // - remove never collapses a chain of one step into that step, and never removes the last step, a parallel's
25
+ // second-to-last branch, a route's second-to-last branch or a body.
26
+ // - move counts `index` in the document as given: the drop point a canvas shows between two steps.
27
+ // - duplicate puts the copy right after the node, in a chain if the node sits alone in its slot. Every node of the
28
+ // copy gets a fresh label. Every key the copy writes (`as`, `failedAs`, or the label of an agent, decide, extract or
29
+ // code node with no `as`) gets a fresh name, off every name its scope uses (a copied child workflow's own input keys
30
+ // included), and the copy's own references to those keys follow them, a copied route's branches and a copied
31
+ // verifier's state included (both read the node's own `as`). Code is copied as it is, so a copied code node writes
32
+ // the same record keys as its source: duplicating a code branch of a parallel gives two branches that write one key,
33
+ // which the run refuses. A copied code node with no `as` writes a result other than a record under its fresh label,
34
+ // and the copy's reads of the old label follow that label; when its code returns a record that names the old label,
35
+ // those reads find nothing. So duplicate returns `mentions` as rename does: the code and shell sources of the copy
36
+ // that mention a key the copy was given a fresh name for (or one of its `<key>$...` keys) by its old name.
37
+ // - wrap takes one node, or consecutive steps or branches of one container, and fills the new container's fields
38
+ // with placeholders the validator flags:
39
+ // - map: `itemsPath: ""` and a fresh `as`;
40
+ // - loop: `until: { predicate: "" }` and `maxIters: 1`;
41
+ // - route: by value, with `valuePath: ""`, the wrapped nodes in branch `match`, and a no-op branch `skip` that
42
+ // `otherwise` names.
43
+ // A parallel takes at least two nodes, one per branch.
44
+ // - unwrap puts a container's children where it was: a chain's steps or a parallel's branches spliced into the
45
+ // enclosing chain, or the body of a map or a loop. A route needs the name of the branch to keep, and its other
46
+ // branches go. A child workflow is never unwrapped, since it runs on its own state, and neither is a map whose body
47
+ // reads `item` or `item_index`, nor a route whose kept branch reads the route's `as`. A nested map's body (the body
48
+ // itself a map included) and a pick's or sift's `describe` read their own `item`, not the outer map's; the rest of
49
+ // `describe` reads the state like any field.
50
+ // - removeBranch keeps a branch that `otherwise` or `unsure` names. renameBranch carries `otherwise` and `unsure`, but
51
+ // not a value elsewhere that compares against the old name.
52
+ // - setField writes exactly the field it names, as given. It refuses the kind, a child slot (use the tree
53
+ // operations), a field the node's kind or route form does not have, and the removal of a required field. Setting a
54
+ // label this way carries nothing; rename does.
55
+ // - rename changes a node's label. When that label is the key the node writes (an agent, decide, extract or code node
56
+ // with no `as`; a code node writes there when its code returns something other than a record), every reference in
57
+ // scope follows it: the `{placeholders}` in state maps, call args, input, env and
58
+ // produces, a child workflow's input, `escalate.summary`, and pick and sift `describe` (all but its own `item`),
59
+ // plus the state paths in itemsPath, valuePath, resultPath, requires and predicates (`path`, `key`, quote_missing's
60
+ // `pages`, under `not` too), and the workflow's `output.path`.
61
+ // - In scope means the nodes that run after the write and see it: later steps of the enclosing chains, and the
62
+ // whole body of an enclosing loop (a later pass reads what an earlier one wrote) with its `until`. Scope ends at
63
+ // the nearest enclosing map (whose `resultPath` reads the item's state) or child workflow (whose `output.path`
64
+ // reads it). A sibling branch of a parallel or a route does not see the write.
65
+ // - Instructions are literal and never rewritten. Code is never rewritten either: the code and shell sources in
66
+ // scope that mention the old key (or one of its `<key>$...` keys) are listed in `mentions`, for the caller to
67
+ // show. So is a renamed code node's own code when it names the old key: a record it returns with that key still
68
+ // writes the old name. The validator does not see a read inside code, so that list is the only warning.
69
+ // - rename refuses a name another node's label or key holds in its workflow, or that a reference (as `<name>$...`
70
+ // too), an input or a code source in scope already uses. A label in another workflow (a sibling child's) is free. No label holds "/" (a run names a child's steps `<child>/<step>`). It also refuses to rename a key another node in scope or the input also writes, since it
71
+ // can't tell whose readers are whose.
72
+ // - renameKey renames the key a node writes: its `as` when it has one (any kind, a map's and a decision node's
73
+ // included), else its label when that is the key, where it gives the document rename gives; with
74
+ // `{ field: "failedAs" }`, a map's `failedAs`. The references in scope follow it as they follow rename,
75
+ // `<key>$answers` and `<key>$verify` included, and so do the reads a node makes of its own `as`: a route's branches
76
+ // (the route writes its choice before they run) and a verifier's state. It takes a name of letters, digits and "_",
77
+ // refuses names and keys as rename does (all but the node's own label, which its key may take), and refuses a node
78
+ // that writes no such key: a chain, parallel, loop, escalate, report or artifact, or a node with no `failedAs` when
79
+ // that is the field.
80
+ // - No edit gives a label, an `as`, a `failedAs` or a route branch a name `Object.prototype` has (`constructor`,
81
+ // `toString`, `__proto__` and the rest) or `prototype`: rename, renameKey, renameBranch and setField refuse one, and
82
+ // insert and addBranch refuse a node with one anywhere inside it. A read of such a key that nothing wrote would find
83
+ // the prototype's value. An edit to a field's current value stays no change.
84
+ // - setBranchCriteria writes a judged route branch's criteria; a route by value matches its branches by name and takes
85
+ // none.
86
+ // - setSchema writes or removes a schema of the document, or of a child workflow (named by its workflow node's path).
87
+ // It refuses to remove a schema something names (schemaUsers lists them: the workflow's `input.schemaId` and
88
+ // `output.schemaId`, a node's `out` and `verify.out`, and a `$ref` to `#/definitions/<id>` in another schema), and it
89
+ // never renames one.
90
+ // - setWorkflowField writes the document's own `input` or `output` as given, and removes the input but never the
91
+ // output. outputNames lists what the output's `path` may read: the input keys and the keys written outside any map
92
+ // body or child workflow.
93
+ // - namesInScope runs rename's scope rules backwards: a node may read its workflow's input keys, a map body's `item`
94
+ // and `item_index`, and every key whose readers include it, with that key's `<key>$answers` and `<key>$verify`. A
95
+ // map's `resultPath`, a loop's `until`, a `verify` (the node's own `as` and `submission`), a pick's or sift's
96
+ // `describe` (its own `item`) and a child's `output.path` see more than the node's other fields, so namesInScope
97
+ // takes the field. It cannot list a key only a code node's returned record writes, nor the keys of an
98
+ // input whose schema lists no properties; the validator does not flag a read of either.
99
+ // - placeholderNode makes the smallest node of a kind that holds no nodes: wrap makes containers of nodes that exist.
100
+ import { workflowGraph } from "./graph.js";
101
+ import { DECISION_NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, isPrototypeName, NODE_FIELDS, PROSE_ARTIFACT_TYPES, WORKFLOW_NODE_KINDS } from "./vocabulary.js";
102
+ /** Every code an EditError carries. */
103
+ export const EDIT_ERROR_CODES = [
104
+ /** The document is not an object. */
105
+ "DOCUMENT_INVALID",
106
+ /** No node sits at the path. */
107
+ "PATH_NOT_FOUND",
108
+ /** The parent has no such slot, or the node is not a container the operation works on. */
109
+ "SLOT_INVALID",
110
+ /** The index is not a whole number within the slot. */
111
+ "INDEX_OUT_OF_RANGE",
112
+ /** The node is not a node of a known kind with its required fields and only its own fields. */
113
+ "NODE_INVALID",
114
+ /** setField, rename or renameKey named a field the node may not have written that way, or that it lacks. */
115
+ "FIELD_INVALID",
116
+ /** The name is empty, holds a "$", is no state key where the name is one, or is a name an object's prototype has. */
117
+ "NAME_INVALID",
118
+ /** Another node's label or key already holds the name, or a reference, input or code source uses it. */
119
+ "NAME_TAKEN",
120
+ /** Another node or the input writes the key being renamed. */
121
+ "NAME_SHARED",
122
+ /** No branch has that name or index. */
123
+ "BRANCH_NOT_FOUND",
124
+ /** A branch already has that name. */
125
+ "BRANCH_TAKEN",
126
+ /** `otherwise` or `unsure` names the branch. */
127
+ "BRANCH_IN_USE",
128
+ /** The move puts a node inside itself. */
129
+ "MOVE_INTO_SELF",
130
+ /** The nodes to wrap are none, repeated, not consecutive siblings, too few for the container, or the kind is no container. */
131
+ "WRAP_INVALID",
132
+ /** The node is not a container that can be unwrapped there. */
133
+ "UNWRAP_INVALID",
134
+ /** The result would break a rule of the document's structure. */
135
+ "STRUCTURE_INVALID",
136
+ /** The workflow has no schema with that id. */
137
+ "SCHEMA_NOT_FOUND",
138
+ /** A field or another schema still names the schema being removed. */
139
+ "SCHEMA_IN_USE",
140
+ /** The schema is not a JSON object. */
141
+ "SCHEMA_INVALID",
142
+ ];
143
+ /** The one error the operations throw. `path` is the node it is about, in the input document where that node existed
144
+ * there; `related` names other nodes the error is about: the one holding a taken name, the other writers of a key. */
145
+ export class EditError extends Error {
146
+ code;
147
+ path;
148
+ related;
149
+ constructor(code, path, message, related = []) {
150
+ super(message);
151
+ this.name = "EditError";
152
+ this.code = code;
153
+ this.path = path;
154
+ this.related = related;
155
+ }
156
+ }
157
+ // ---- the vocabulary, as the edits read it ---------------------------------------------------------------------------
158
+ const KINDS = new Set(WORKFLOW_NODE_KINDS);
159
+ /** The fields of each kind that hold its children, which only the tree operations write. */
160
+ const SLOT_FIELDS = { chain: ["steps"], parallel: ["branches"], map: ["body"], loop: ["body"], route: ["branches"], workflow: ["workflow"] };
161
+ /** Fields only one form of route has: a route Jev chooses, or a route by value. */
162
+ const JUDGED_ROUTE_ONLY = ["state", "instructions", "unsure", ...DECISION_NODE_FIELDS];
163
+ const BY_VALUE_ROUTE_ONLY = ["valuePath", "otherwise"];
164
+ /** The schema's required fields of each kind, and of each form of route. */
165
+ const REQUIRED = {
166
+ chain: ["node", "steps"],
167
+ code: ["node", "label", "code"],
168
+ agent: ["node", "label", "instructions", "out"],
169
+ decide: ["node", "label", "instructions", "out"],
170
+ extract: ["node", "label", "instructions", "out"],
171
+ report: ["node", "label", "instructions"],
172
+ artifact: ["node", "label", "type"],
173
+ map: ["node", "label", "itemsPath", "body", "as"],
174
+ parallel: ["node", "label", "branches"],
175
+ loop: ["node", "label", "body", "until", "maxIters"],
176
+ escalate: ["node", "label", "when", "kind", "stage", "summary"],
177
+ call: ["node", "label", "via", "as", "deadline_s"],
178
+ workflow: ["node", "label", "workflow", "input", "out", "as"],
179
+ judge: ["node", "label", "state", "out", "as"],
180
+ pick: ["node", "label", "itemsPath", "describe", "instructions", "as"],
181
+ sift: ["node", "label", "itemsPath", "out", "as"],
182
+ route: ["node", "label", "state", "instructions", "branches"],
183
+ "route by value": ["node", "label", "valuePath", "branches"],
184
+ };
185
+ /** A judged route takes at most this many branches (System One's choice limit). */
186
+ const MAX_ROUTE_BRANCHES = 240;
187
+ /** The nesting depth `workflowGraph` walks. */
188
+ const MAX_DEPTH = 128;
189
+ /** State keys the engine gives a node, which no rename or fresh name may take. */
190
+ const RESERVED_KEYS = new Set(["item", "item_index", "report_markdown", "artifact", "state", "submission", "$host"]);
191
+ /** The placeholder a required field takes in a new node: a value insert accepts and the validator flags until someone
192
+ * fills it in (an empty text, an empty state map, a predicate with no name, a deadline of 0 seconds), or, for a loop's
193
+ * `maxIters`, the smallest bound. placeholderNode and wrap fill fields from it. */
194
+ export const FIELD_PLACEHOLDERS = Object.freeze({
195
+ instructions: "", code: "", out: "", type: "", itemsPath: "", describe: "", kind: "", stage: "", summary: "", via: "",
196
+ valuePath: "", state: Object.freeze({}), when: Object.freeze({ predicate: "" }), until: Object.freeze({ predicate: "" }),
197
+ deadline_s: 0, maxIters: 1,
198
+ });
199
+ /** A copy of a field's placeholder, to write into a document. */
200
+ const placeholder = (field) => structuredClone(FIELD_PLACEHOLDERS[field]);
201
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
202
+ const isNode = (value) => isObject(value) && typeof value.node === "string";
203
+ const isByValue = (node) => node.node === "route" && node.valuePath !== undefined;
204
+ /** The fields the node's kind (and its route form) accepts, `node` and the child slots included. */
205
+ const fieldsOf = (node) => {
206
+ const kind = String(node.node);
207
+ if (!KINDS.has(kind))
208
+ return [];
209
+ const own = [...NODE_FIELDS[kind], ...HOST_NODE_FIELDS];
210
+ if (kind !== "route")
211
+ return own;
212
+ const other = isByValue(node) ? JUDGED_ROUTE_ONLY : BY_VALUE_ROUTE_ONLY;
213
+ return own.filter((field) => !other.includes(field));
214
+ };
215
+ /** The fields setField writes on this node: its kind's (and its route form's) own fields, without `node` and the child
216
+ * slots. A property panel lists these. */
217
+ export function editableFields(node) {
218
+ if (!isObject(node))
219
+ return [];
220
+ const slots = SLOT_FIELDS[String(node.node)] ?? [];
221
+ return fieldsOf(node).filter((field) => field !== "node" && !slots.includes(field));
222
+ }
223
+ /** The fields the schema requires of this node's kind (and its route form), `node` included. */
224
+ export function requiredFields(node) {
225
+ if (!isObject(node) || !KINDS.has(String(node.node)))
226
+ return [];
227
+ return [...REQUIRED[isByValue(node) ? "route by value" : String(node.node)]];
228
+ }
229
+ // ---- pointers and the walk ------------------------------------------------------------------------------------------
230
+ const escape = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
231
+ const unescape = (part) => part.replace(/~1/g, "/").replace(/~0/g, "~");
232
+ /** Every node of the document, in the order and at the paths `workflowGraph` gives them. */
233
+ function entriesOf(doc) {
234
+ const out = [];
235
+ const visit = (node, at, depth) => {
236
+ if (!isNode(node) || depth > MAX_DEPTH)
237
+ return;
238
+ out.push({ ...at, node });
239
+ if (depth + 1 > MAX_DEPTH)
240
+ return;
241
+ const { path, keys, scope } = at;
242
+ const child = (value, slot, index, many, tail, inner = scope) => visit(value, { path: `${path}/${many ? `${slot}/${index}` : slot}`, parentPath: path, slot, index, many, keys: [...keys, ...tail], scope: inner }, depth + 1);
243
+ switch (node.node) {
244
+ case "chain":
245
+ if (Array.isArray(node.steps))
246
+ node.steps.forEach((step, index) => child(step, "steps", index, true, ["steps", String(index)]));
247
+ break;
248
+ case "parallel":
249
+ if (Array.isArray(node.branches))
250
+ node.branches.forEach((branch, index) => child(branch, "branches", index, true, ["branches", String(index)]));
251
+ break;
252
+ case "map":
253
+ case "loop":
254
+ child(node.body, "body", 0, false, ["body"]);
255
+ break;
256
+ case "route":
257
+ if (isObject(node.branches))
258
+ for (const [name, branch] of Object.entries(node.branches)) {
259
+ if (isObject(branch))
260
+ child(branch.body, `branches/${escape(name)}/body`, 0, false, ["branches", name, "body"]);
261
+ }
262
+ break;
263
+ case "workflow":
264
+ if (isObject(node.workflow))
265
+ child(node.workflow.root, "workflow/root", 0, false, ["workflow", "root"], path);
266
+ break;
267
+ }
268
+ };
269
+ visit(doc.root, { path: "/root", parentPath: "", slot: "root", index: 0, many: false, keys: ["root"], scope: "" }, 0);
270
+ return out;
271
+ }
272
+ /** Where the node at `path` sits: its parent's path, the slot it is in, and its index there (0 in a slot that holds one
273
+ * node). Undefined when no node sits there. */
274
+ export function locate(doc, path) {
275
+ if (!isObject(doc))
276
+ return undefined;
277
+ const entry = entriesOf(doc).find((candidate) => candidate.path === path);
278
+ return entry && { parentPath: entry.parentPath, slot: entry.slot, index: entry.index };
279
+ }
280
+ // ---- copy on write ----------------------------------------------------------------------------------------------------
281
+ const DELETE = Symbol("delete");
282
+ /** One operation's copies: each copied object remembers the object it was copied from, so the result can say which
283
+ * node of the input each node of the output is. */
284
+ class Draft {
285
+ from = new WeakMap();
286
+ copy(value) {
287
+ const copied = (Array.isArray(value) ? value.slice() : { ...value });
288
+ this.from.set(copied, this.source(value));
289
+ return copied;
290
+ }
291
+ source(value) {
292
+ let at = value;
293
+ for (let next = this.from.get(at); next !== undefined; next = this.from.get(at))
294
+ at = next;
295
+ return at;
296
+ }
297
+ /** `doc` with the value at `keys` replaced by `fn` of it (a key deleted when `fn` returns DELETE), each object on the
298
+ * way copied and every other value shared. */
299
+ update(doc, keys, fn) {
300
+ const go = (value, i) => {
301
+ if (i === keys.length)
302
+ return fn(value);
303
+ if (!isObject(value) && !Array.isArray(value))
304
+ throw new Error(`edit: no container at ${keys.slice(0, i).join("/")}`);
305
+ const copied = this.copy(value);
306
+ const inner = go(value[keys[i]], i + 1);
307
+ if (inner === DELETE)
308
+ delete copied[keys[i]];
309
+ else
310
+ copied[keys[i]] = inner;
311
+ return copied;
312
+ };
313
+ return go(doc, 0);
314
+ }
315
+ /** `update`, where `fn` revises the node at `keys`: what it returns is that node, edited, not a new one. */
316
+ revise(doc, keys, fn) {
317
+ return this.update(doc, keys, (value) => {
318
+ const next = fn(value);
319
+ if (next !== value && isObject(value))
320
+ this.from.set(next, this.source(value));
321
+ return next;
322
+ });
323
+ }
324
+ }
325
+ /** A JSON value copied, so the document never shares an object with its caller. */
326
+ const clone = (value) => {
327
+ if (Array.isArray(value))
328
+ return value.map(clone);
329
+ if (isObject(value))
330
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, clone(inner)]));
331
+ return value;
332
+ };
333
+ /** How many reports and artifacts sit in the node, as the validator counts them: never inside a child workflow. */
334
+ const terminals = (node) => {
335
+ if (!isNode(node))
336
+ return 0;
337
+ switch (node.node) {
338
+ case "report":
339
+ case "artifact": return 1;
340
+ case "chain": return Array.isArray(node.steps) ? node.steps.reduce((n, step) => n + terminals(step), 0) : 0;
341
+ case "parallel": return Array.isArray(node.branches) ? node.branches.reduce((n, branch) => n + terminals(branch), 0) : 0;
342
+ case "map":
343
+ case "loop": return terminals(node.body);
344
+ case "route": return isObject(node.branches) ? Object.values(node.branches).reduce((n, branch) => n + (isObject(branch) ? terminals(branch.body) : 0), 0) : 0;
345
+ default: return 0;
346
+ }
347
+ };
348
+ /** The document's structural breaks, in document order and then the document's own. They mirror the validator's rules
349
+ * on where a node may sit and what it must hold: a known kind, only its kind's fields, the schema's required fields,
350
+ * steps, branches and bodies present and enough of them, a report or artifact only as the root chain's last step.
351
+ * The validator's other structural rules (a model node's `out` naming `report_markdown`, the depth bound) and every
352
+ * value's type are its own to check. */
353
+ function problemsOf(doc) {
354
+ const out = [];
355
+ const add = (at, rule, code, message) => { out.push({ at, rule, code, message }); };
356
+ const visit = (value, path, holder, slot, depth) => {
357
+ if (!isNode(value)) {
358
+ add(holder, `slot:${slot}`, "STRUCTURE_INVALID", `${path}: no node here; the ${slot === "root" ? "document" : "slot"} needs one`);
359
+ return;
360
+ }
361
+ if (depth > MAX_DEPTH)
362
+ return;
363
+ const kind = String(value.node);
364
+ if (!KINDS.has(kind)) {
365
+ add(path, "kind", "NODE_INVALID", `${path}: unknown node kind "${kind}"`);
366
+ return;
367
+ }
368
+ const allowed = new Set([...fieldsOf(value), ...(IGNORED_NODE_FIELDS[kind] ?? [])]);
369
+ for (const key of Object.keys(value))
370
+ if (!allowed.has(key))
371
+ add(path, `key:${key}`, "NODE_INVALID", `${path}: a ${isByValue(value) ? "route by value" : kind} node has no field "${key}"`);
372
+ const slots = SLOT_FIELDS[kind] ?? [];
373
+ for (const field of requiredFields(value))
374
+ if (!slots.includes(field) && value[field] === undefined)
375
+ add(path, `required:${field}`, "NODE_INVALID", `${path}: a ${kind} node needs "${field}"`);
376
+ const inside = (rule, where) => add(path, rule, "STRUCTURE_INVALID", `${path}: a report or artifact cannot sit inside ${where}; the workflow renders its terminal once, as the root chain's last step`);
377
+ switch (kind) {
378
+ case "chain":
379
+ if (!Array.isArray(value.steps)) {
380
+ add(path, "slot:steps", "STRUCTURE_INVALID", `${path}: a chain needs steps`);
381
+ break;
382
+ }
383
+ if (!value.steps.length)
384
+ add(path, "chain-empty", "STRUCTURE_INVALID", `${path}: a chain needs at least one step`);
385
+ value.steps.forEach((step, index) => visit(step, `${path}/steps/${index}`, path, "steps", depth + 1));
386
+ break;
387
+ case "parallel":
388
+ if (!Array.isArray(value.branches)) {
389
+ add(path, "slot:branches", "STRUCTURE_INVALID", `${path}: a parallel needs branches`);
390
+ break;
391
+ }
392
+ if (value.branches.length < 2)
393
+ add(path, "parallel-few", "STRUCTURE_INVALID", `${path}: a parallel needs at least two branches`);
394
+ value.branches.forEach((branch, index) => visit(branch, `${path}/branches/${index}`, path, "branches", depth + 1));
395
+ if (terminals(value))
396
+ inside("terminal-inside", "a parallel branch");
397
+ break;
398
+ case "map":
399
+ case "loop":
400
+ visit(value.body, `${path}/body`, path, "body", depth + 1);
401
+ if (terminals(value.body))
402
+ inside("terminal-inside", `a ${kind} body`);
403
+ break;
404
+ case "route": {
405
+ if (!isObject(value.branches)) {
406
+ add(path, "slot:branches", "STRUCTURE_INVALID", `${path}: a route needs branches`);
407
+ break;
408
+ }
409
+ const names = Object.keys(value.branches);
410
+ if (names.length < 2)
411
+ add(path, "route-few", "STRUCTURE_INVALID", `${path}: a route needs at least two branches`);
412
+ if (!isByValue(value) && names.length > MAX_ROUTE_BRANCHES)
413
+ add(path, "route-many", "STRUCTURE_INVALID", `${path}: a route Jev chooses takes at most ${MAX_ROUTE_BRANCHES} branches`);
414
+ for (const name of names) {
415
+ const branch = value.branches[name];
416
+ if (!isObject(branch))
417
+ add(path, "slot:branch", "STRUCTURE_INVALID", `${path}: branch "${name}" needs a body`);
418
+ else
419
+ visit(branch.body, `${path}/branches/${escape(name)}/body`, path, "branch", depth + 1);
420
+ }
421
+ if (terminals(value))
422
+ inside("terminal-inside", "a route branch");
423
+ break;
424
+ }
425
+ case "workflow": {
426
+ const child = value.workflow;
427
+ const root = isObject(child) ? child.root : undefined;
428
+ if (!isNode(root) || (root.node === "chain" && (!Array.isArray(root.steps) || !root.steps.length)))
429
+ add(path, "child-root", "STRUCTURE_INVALID", `${path}: the child workflow needs a root node`);
430
+ if (isNode(root)) {
431
+ visit(root, `${path}/workflow/root`, path, "workflow/root", depth + 1);
432
+ if (terminals(root))
433
+ inside("terminal-inside", "a child workflow; the parent owns the terminal");
434
+ }
435
+ break;
436
+ }
437
+ }
438
+ };
439
+ visit(doc.root, "/root", "", "root", 0);
440
+ const total = terminals(doc.root);
441
+ if (total > 1)
442
+ add("", "terminals", "STRUCTURE_INVALID", "/root: a workflow has at most one terminal node (report or artifact)");
443
+ else if (total === 1) {
444
+ const root = doc.root;
445
+ const last = root.node === "chain" && Array.isArray(root.steps) ? root.steps[root.steps.length - 1] : root;
446
+ if (!isNode(last) || (last.node !== "report" && last.node !== "artifact"))
447
+ add("", "terminal-last", "STRUCTURE_INVALID", "/root: the terminal node (report or artifact) must be the last step of the root chain");
448
+ }
449
+ return out;
450
+ }
451
+ /** The result of an operation from `before` to `after`: which node of the input each node of the output is (by the
452
+ * object it was copied from), and the structure checked. A break `after` has that `before` did not throws. */
453
+ function finish(draft, before, after) {
454
+ const old = entriesOf(before), now = entriesOf(after);
455
+ const placements = new Map();
456
+ for (const entry of old)
457
+ placements.set(entry.node, [...(placements.get(entry.node) ?? []), entry.path]);
458
+ const prevOf = new Map(), nextOf = new Map();
459
+ for (const entry of now) {
460
+ const candidates = (placements.get(draft.source(entry.node)) ?? []).filter((path) => !nextOf.has(path));
461
+ const from = candidates.includes(entry.path) ? entry.path : candidates[0];
462
+ if (from !== undefined) {
463
+ prevOf.set(entry.path, from);
464
+ nextOf.set(from, entry.path);
465
+ }
466
+ }
467
+ const moved = new Map();
468
+ for (const entry of old) {
469
+ const to = nextOf.get(entry.path);
470
+ if (to !== undefined && to !== entry.path)
471
+ moved.set(entry.path, to);
472
+ }
473
+ const checks = new Map(workflowGraph(before).nodes.map((node) => [node.path, node.changeCheck]));
474
+ const result = {
475
+ doc: after,
476
+ moved,
477
+ added: now.filter((entry) => !prevOf.has(entry.path)).map((entry) => entry.path),
478
+ removed: old.filter((entry) => !nextOf.has(entry.path)).map((entry) => entry.path),
479
+ changed: workflowGraph(after).nodes.filter((node) => prevOf.has(node.path) && checks.get(prevOf.get(node.path)) !== node.changeCheck).map((node) => node.path),
480
+ };
481
+ // The breaks the input had, at the paths their nodes now have; a break with more instances after is new.
482
+ const had = new Map();
483
+ for (const problem of problemsOf(before)) {
484
+ if (problem.at !== "" && !nextOf.has(problem.at))
485
+ continue;
486
+ const key = `${problem.at === "" ? "" : nextOf.get(problem.at)}|${problem.rule}`;
487
+ had.set(key, (had.get(key) ?? 0) + 1);
488
+ }
489
+ for (const problem of problemsOf(after)) {
490
+ const key = `${problem.at}|${problem.rule}`;
491
+ const left = had.get(key) ?? 0;
492
+ if (left > 0) {
493
+ had.set(key, left - 1);
494
+ continue;
495
+ }
496
+ throw new EditError(problem.code, problem.at === "" ? "/root" : prevOf.get(problem.at) ?? problem.at, problem.message);
497
+ }
498
+ return result;
499
+ }
500
+ // ---- shared steps ------------------------------------------------------------------------------------------------------
501
+ const documentOf = (doc) => {
502
+ if (!isObject(doc))
503
+ throw new EditError("DOCUMENT_INVALID", "", "the document is not a workflow object");
504
+ return doc;
505
+ };
506
+ const find = (entries, path) => {
507
+ const entry = entries.find((candidate) => candidate.path === path);
508
+ if (!entry)
509
+ throw new EditError("PATH_NOT_FOUND", String(path), `no node at ${String(path)}`);
510
+ return entry;
511
+ };
512
+ const nodeOf = (value, path) => {
513
+ if (!isNode(value) || !KINDS.has(String(value.node)))
514
+ throw new EditError("NODE_INVALID", path, `the value is not a node of a known kind: ${JSON.stringify(isObject(value) ? value.node : value)}`);
515
+ for (const { node } of entriesOf({ root: value })) {
516
+ for (const name of [node.label, node.as, node.failedAs])
517
+ refusePrototypeName(name, path);
518
+ if (node.node === "route" && isObject(node.branches))
519
+ for (const name of Object.keys(node.branches))
520
+ refusePrototypeName(name, path);
521
+ refuseSlashLabel(node.label, path);
522
+ }
523
+ return value;
524
+ };
525
+ function slotAt(doc, entries, parentPath, slot) {
526
+ const at = (keys, many) => {
527
+ const value = keys.reduce((inner, key) => isObject(inner) || Array.isArray(inner) ? inner[key] : undefined, doc);
528
+ return { path: `${parentPath}/${slot}`, parentPath, slot, many, keys, size: many ? (Array.isArray(value) ? value.length : 0) : value === undefined ? 0 : 1 };
529
+ };
530
+ if (parentPath === "") {
531
+ if (slot !== "root")
532
+ throw new EditError("SLOT_INVALID", "", `the document holds its root at "root", not "${String(slot)}"`);
533
+ return at(["root"], false);
534
+ }
535
+ const parent = find(entries, parentPath);
536
+ const kind = parent.node.node;
537
+ if (kind === "chain" && slot === "steps")
538
+ return at([...parent.keys, "steps"], true);
539
+ if (kind === "parallel" && slot === "branches")
540
+ return at([...parent.keys, "branches"], true);
541
+ if ((kind === "map" || kind === "loop") && slot === "body")
542
+ return at([...parent.keys, "body"], false);
543
+ if (kind === "workflow" && slot === "workflow/root" && isObject(parent.node.workflow))
544
+ return at([...parent.keys, "workflow", "root"], false);
545
+ const branch = kind === "route" && typeof slot === "string" ? /^branches\/([^/]*)\/body$/.exec(slot) : null;
546
+ if (branch && isObject(parent.node.branches) && Object.hasOwn(parent.node.branches, unescape(branch[1])) && isObject(parent.node.branches[unescape(branch[1])])) {
547
+ return at([...parent.keys, "branches", unescape(branch[1]), "body"], false);
548
+ }
549
+ throw new EditError("SLOT_INVALID", parentPath, `a ${String(kind)} node at ${parentPath} has no slot "${String(slot)}"`);
550
+ }
551
+ const checkIndex = (slot, index) => {
552
+ const most = slot.many ? slot.size : slot.size === 0 ? 0 : 1;
553
+ if (!Number.isInteger(index) || index < 0 || index > most)
554
+ throw new EditError("INDEX_OUT_OF_RANGE", slot.parentPath, `index ${index} is outside ${slot.path} (0 to ${most})`);
555
+ };
556
+ /** `doc` with `node` placed in `slot` at `index`: into the array, into the empty slot, or in a new chain with the slot's
557
+ * one node. */
558
+ function place(draft, doc, slot, index, node) {
559
+ checkIndex(slot, index);
560
+ if (slot.many)
561
+ return draft.update(doc, slot.keys, (value) => {
562
+ const list = Array.isArray(value) ? value : [];
563
+ return [...list.slice(0, index), node, ...list.slice(index)];
564
+ });
565
+ return draft.update(doc, slot.keys, (value) => value === undefined ? node : { node: "chain", steps: index === 0 ? [node, value] : [value, node] });
566
+ }
567
+ /** `doc` without the node `entry` names: spliced out of its array, or its slot emptied. */
568
+ const takeOut = (draft, doc, entry) => entry.many
569
+ ? draft.update(doc, entry.keys.slice(0, -1), (value) => value.filter((_, index) => index !== entry.index))
570
+ : draft.update(doc, entry.keys, () => DELETE);
571
+ /** Replace the node `entry` names by `nodes`: spliced into its array, or, in a slot that holds one, the one node. */
572
+ const putInstead = (draft, doc, entry, nodes, count = 1) => entry.many
573
+ ? draft.update(doc, entry.keys.slice(0, -1), (value) => { const list = value; return [...list.slice(0, entry.index), ...nodes, ...list.slice(entry.index + count)]; })
574
+ : draft.update(doc, entry.keys, () => nodes.length === 1 ? nodes[0] : { node: "chain", steps: nodes });
575
+ // ---- names, keys and references ---------------------------------------------------------------------------------------
576
+ const KEY_NAME = /^[A-Za-z0-9_]+$/;
577
+ const WHOLE_PLACEHOLDER = /^\{([a-zA-Z0-9_.$]+)(\?)?\}$/;
578
+ const INNER_PLACEHOLDER = /\{([a-zA-Z0-9_.$]+)\}/g;
579
+ /** Whether a node writes state under its label: an agent, decide, extract or code node with no `as`. A code node writes
580
+ * there when its code returns something other than a record; a record's own keys are its code's. */
581
+ const labelIsKey = (node) => (node.node === "agent" || node.node === "decide" || node.node === "extract" || node.node === "code") && node.as === undefined;
582
+ /** The state keys a node writes, as its fields name them (the keys of a record a code node returns are its code's). */
583
+ const keysWritten = (node) => [
584
+ ...(typeof node.as === "string" ? [node.as] : []),
585
+ ...(labelIsKey(node) && typeof node.label === "string" ? [node.label] : []),
586
+ ...(typeof node.failedAs === "string" ? [node.failedAs] : []),
587
+ ];
588
+ /** The literal sources of a code node or a call: never interpolated, never rewritten. */
589
+ const sourcesOf = (node) => (node.node === "code" || node.node === "call" ? ["code", "command"] : []).flatMap((field) => typeof node[field] === "string" ? [node[field]] : []);
590
+ /** Whether `text` names `word` as a whole word, or one of its engine-owned `<word>$...` keys. */
591
+ const mentions = (text, word) => new RegExp(`(^|[^A-Za-z0-9_$])${word.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}($|[^A-Za-z0-9_])`).test(text);
592
+ /** Refuse a name `Object.prototype` has (`constructor`, `toString`, `__proto__` and the rest), or `prototype`, as a
593
+ * label, an `as`, a `failedAs` or a route branch (vocabulary.ts isPrototypeName, the validator's rule too). */
594
+ const refusePrototypeName = (name, path) => {
595
+ if (typeof name === "string" && isPrototypeName(name))
596
+ throw new EditError("NAME_INVALID", path, `"${name}" is a name an object's prototype has`);
597
+ };
598
+ /** Refuse a label holding "/": a run names a child workflow's steps `<child>/<step>`, so a label `a/b` beside a child
599
+ * `a`'s step `b` would name two nodes (the validator's rule too). */
600
+ const refuseSlashLabel = (name, path) => {
601
+ if (typeof name === "string" && name.includes("/"))
602
+ throw new EditError("NAME_INVALID", path, `a label holds no "/", which a run names a child workflow's steps with (<child>/<step>): ${JSON.stringify(name)}`);
603
+ };
604
+ const renamePath = (path, rename, prefixed, at, optional = false) => {
605
+ const prefix = prefixed && path.startsWith("state.") ? "state." : "";
606
+ const [head, ...tail] = path.slice(prefix.length).split(".");
607
+ const next = rename(head, at, optional);
608
+ return next === head ? path : prefix + [next, ...tail].join(".");
609
+ };
610
+ /** A rewrite of `key` to `name` in a path's head, its engine-owned `<key>$...` keys included. */
611
+ const renameHead = (key, name) => (head) => head === key ? name : head.startsWith(`${key}$`) ? name + head.slice(key.length) : head;
612
+ /** A value with each `{placeholder}` in its strings rewritten, the same value when none changes. `at` is the value's
613
+ * pointer from the node. */
614
+ const renamePlaceholders = (value, rename, at) => {
615
+ if (typeof value === "string") {
616
+ const whole = WHOLE_PLACEHOLDER.exec(value);
617
+ if (whole) {
618
+ const path = renamePath(whole[1], rename, true, at, whole[2] !== undefined);
619
+ return path === whole[1] ? value : `{${path}${whole[2] ?? ""}}`;
620
+ }
621
+ const next = value.replace(INNER_PLACEHOLDER, (all, path) => { const renamed = renamePath(path, rename, true, at); return renamed === path ? all : `{${renamed}}`; });
622
+ return next === value ? value : next;
623
+ }
624
+ if (Array.isArray(value)) {
625
+ const next = value.map((inner, i) => renamePlaceholders(inner, rename, `${at}/${i}`));
626
+ return next.some((inner, i) => inner !== value[i]) ? next : value;
627
+ }
628
+ if (isObject(value)) {
629
+ const next = Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, renamePlaceholders(inner, rename, `${at}/${escape(key)}`)]));
630
+ return Object.keys(value).some((key) => next[key] !== value[key]) ? next : value;
631
+ }
632
+ return value;
633
+ };
634
+ /** A predicate with the state paths it reads (`path`, `key`, quote_missing's `pages`, and those of a `not`'s `of`) and
635
+ * the placeholders of its `ask` (`state`, `images`) rewritten. A quote_missing `field` names a field of each quote's
636
+ * record, not a state path. */
637
+ const renamePredicate = (value, rename, at) => {
638
+ if (!isObject(value))
639
+ return value;
640
+ const next = { ...value };
641
+ if (typeof value.path === "string")
642
+ next.path = renamePath(value.path, rename, false, `${at}/path`);
643
+ if (typeof value.key === "string")
644
+ next.key = renamePath(value.key, rename, false, `${at}/key`);
645
+ if (Array.isArray(value.pages)) {
646
+ const pages = value.pages.map((page, i) => typeof page === "string" ? renamePath(page, rename, false, `${at}/pages/${i}`) : page);
647
+ if (pages.some((page, i) => page !== value.pages[i]))
648
+ next.pages = pages;
649
+ }
650
+ if (value.state !== undefined)
651
+ next.state = renamePlaceholders(value.state, rename, `${at}/state`);
652
+ if (value.images !== undefined)
653
+ next.images = renamePlaceholders(value.images, rename, `${at}/images`);
654
+ if (value.of !== undefined)
655
+ next.of = renamePredicate(value.of, rename, `${at}/of`);
656
+ return Object.keys(value).some((key) => next[key] !== value[key]) ? next : value;
657
+ };
658
+ /** The keys a pick's or sift's describe gives its own candidate. */
659
+ const OWN_ITEM = new Set(["item", "item_index"]);
660
+ /** The node with each state reference of `mode` rewritten; the same node when none changes. Each reference is visited
661
+ * once, with the pointer, from the node, of the value it sits in. */
662
+ function renameReads(node, mode, rename) {
663
+ const next = { ...node };
664
+ const field = (name, fn) => { if (node[name] !== undefined)
665
+ next[name] = fn(node[name], `/${name}`); };
666
+ const path = (value, at) => typeof value === "string" ? renamePath(value, rename, false, at) : value;
667
+ const paths = (value, at) => {
668
+ if (!Array.isArray(value))
669
+ return value;
670
+ const renamed = value.map((inner, i) => path(inner, `${at}/${i}`));
671
+ return renamed.some((inner, i) => inner !== value[i]) ? renamed : value;
672
+ };
673
+ if (mode === "resultPath")
674
+ field("resultPath", path);
675
+ else if (mode === "until")
676
+ field("until", (value, at) => renamePredicate(value, rename, at));
677
+ else if (mode === "verify")
678
+ field("verify", (value, at) => isObject(value) ? renamePredicate({ ...value }, rename, at) : value);
679
+ else if (mode === "childOutput")
680
+ field("workflow", (child, at) => {
681
+ if (!isObject(child) || !isObject(child.output) || typeof child.output.path !== "string")
682
+ return child;
683
+ const renamed = path(child.output.path, `${at}/output/path`);
684
+ return renamed === child.output.path ? child : { ...child, output: { ...child.output, path: renamed } };
685
+ });
686
+ else {
687
+ for (const name of ["state", "images", "args", "env", "produces", "summary"])
688
+ field(name, (value, at) => renamePlaceholders(value, rename, at));
689
+ // A pick's or sift's describe reads the state, and its own candidate as `item` and `item_index`, which are no state's.
690
+ field("describe", (value, at) => renamePlaceholders(value, (head, inner) => OWN_ITEM.has(head) ? head : rename(head, inner), at));
691
+ if (node.node === "workflow" || node.node === "call")
692
+ field("input", (value, at) => renamePlaceholders(value, rename, at));
693
+ field("verify", (value, at) => isObject(value) ? renamePredicate({ ...value }, rename, at) : value);
694
+ for (const name of ["itemsPath", "valuePath", "resultPath"])
695
+ field(name, path);
696
+ field("requires", paths);
697
+ for (const name of ["until", "when"])
698
+ field(name, (value, at) => renamePredicate(value, rename, at));
699
+ }
700
+ return Object.keys(node).some((key) => next[key] !== node[key]) ? next : node;
701
+ }
702
+ /** The heads of the state paths a node's own fields read; a pick's or sift's describe counts all but its own item. */
703
+ function headsRead(node) {
704
+ const heads = new Set();
705
+ renameReads(node, "own", (head) => { heads.add(head); return head; });
706
+ return heads;
707
+ }
708
+ /** Each entry's path and place in its list, built once per list: namesInScope asks readersOf about every writer. */
709
+ const indexes = new WeakMap();
710
+ const indexOf = (entries) => {
711
+ let index = indexes.get(entries);
712
+ if (!index) {
713
+ index = { byPath: new Map(entries.map((entry) => [entry.path, entry])), place: new Map(entries.map((entry, i) => [entry, i])) };
714
+ indexes.set(entries, index);
715
+ }
716
+ return index;
717
+ };
718
+ /** The nodes that read what the node at `writer` writes, each with how much of it reads, and whether the document's
719
+ * `output.path` does. When the key is the writer's own `as` (`viaAs`), the writer reads it too: a route writes its
720
+ * choice before its branches run, and a verifier sees the submission under the node's `as`. */
721
+ function readersOf(entries, writer, viaAs = false) {
722
+ const { byPath, place } = indexOf(entries);
723
+ const readers = [];
724
+ // entriesOf lists a node's subtree right after it, so the subtree ends at the first entry outside it.
725
+ const subtree = (root) => {
726
+ for (let i = place.get(root) ?? entries.length; i < entries.length; i += 1) {
727
+ const entry = entries[i];
728
+ if (entry.path !== root.path && !entry.path.startsWith(`${root.path}/`))
729
+ break;
730
+ if (entry.scope === root.scope)
731
+ readers.push({ entry, mode: "own" });
732
+ }
733
+ };
734
+ if (viaAs && writer.node.node === "route")
735
+ for (const body of entries)
736
+ if (body.parentPath === writer.path)
737
+ subtree(body);
738
+ if (viaAs && writer.node.verify !== undefined)
739
+ readers.push({ entry: writer, mode: "verify" });
740
+ for (let at = writer;;) {
741
+ const parent = byPath.get(at.parentPath);
742
+ if (!parent)
743
+ return { readers, output: true };
744
+ switch (parent.node.node) {
745
+ case "chain":
746
+ for (const step of entries)
747
+ if (step.parentPath === parent.path && step.many && step.index > at.index)
748
+ subtree(step);
749
+ break;
750
+ case "map":
751
+ readers.push({ entry: parent, mode: "resultPath" });
752
+ return { readers, output: false };
753
+ case "loop": {
754
+ // A later pass reads what an earlier one wrote: the whole body is in scope, the writer and the steps before it too.
755
+ const body = entries.find((entry) => entry.parentPath === parent.path && entry.slot === "body");
756
+ if (body)
757
+ subtree(body);
758
+ readers.push({ entry: parent, mode: "until" });
759
+ break;
760
+ }
761
+ case "workflow":
762
+ readers.push({ entry: parent, mode: "childOutput" });
763
+ return { readers, output: false };
764
+ }
765
+ at = parent;
766
+ }
767
+ }
768
+ /** The workflow object a scope reads: the document, or a workflow node's child. */
769
+ const workflowOf = (doc, entries, scope) => {
770
+ if (scope === "")
771
+ return doc;
772
+ const owner = entries.find((entry) => entry.path === scope)?.node.workflow;
773
+ return isObject(owner) ? owner : {};
774
+ };
775
+ /** The keys a scope starts with: its input schema's properties and, for a child, the keys its input maps. */
776
+ const inputKeys = (doc, entries, scope) => {
777
+ const workflow = workflowOf(doc, entries, scope);
778
+ const id = isObject(workflow.input) ? workflow.input.schemaId : undefined;
779
+ const schema = typeof id === "string" && isObject(workflow.schemas) && Object.hasOwn(workflow.schemas, id) ? workflow.schemas[id] : undefined;
780
+ const keys = new Set(isObject(schema) && isObject(schema.properties) ? Object.keys(schema.properties) : []);
781
+ const owner = entries.find((entry) => entry.path === scope)?.node;
782
+ if (owner && isObject(owner.input))
783
+ for (const key of Object.keys(owner.input))
784
+ keys.add(key);
785
+ return keys;
786
+ };
787
+ /** Every name a key of the scope could clash with: the scope's labels (all but `self`'s), keys written, input keys, the
788
+ * heads of references and of the output path, the words of code and shell sources (the key a `<key>$...` head or word
789
+ * names included), and the engine's own keys. Another workflow's labels are not among them: a child runs on state of
790
+ * its own, and a run names its steps `<child>/<step>`. */
791
+ const namesUsed = (doc, entries, scope, self) => {
792
+ const used = new Set([...RESERVED_KEYS, ...inputKeys(doc, entries, scope)]);
793
+ for (const entry of entries) {
794
+ if (entry.scope !== scope)
795
+ continue;
796
+ if (typeof entry.node.label === "string" && entry !== self)
797
+ used.add(entry.node.label);
798
+ for (const key of keysWritten(entry.node))
799
+ used.add(key);
800
+ for (const head of headsRead(entry.node))
801
+ used.add(head).add(head.split("$")[0]);
802
+ for (const source of sourcesOf(entry.node))
803
+ for (const word of source.match(/[A-Za-z0-9_$]+/g) ?? [])
804
+ used.add(word).add(word.split("$")[0]);
805
+ }
806
+ const output = workflowOf(doc, entries, scope).output;
807
+ if (isObject(output) && typeof output.path === "string")
808
+ used.add(output.path.split(".")[0]).add(output.path.split(".")[0].split("$")[0]);
809
+ return used;
810
+ };
811
+ /** A name no name in `used` has, added to it: `base` itself when free, else its stem with the smallest `_<n>` from 2. */
812
+ const fresh = (base, used) => {
813
+ const stem = base.replace(/_\d+$/, "") || "node";
814
+ if (!used.has(stem) && stem === base && !RESERVED_KEYS.has(stem) && !isPrototypeName(stem)) {
815
+ used.add(stem);
816
+ return stem;
817
+ }
818
+ for (let n = 2;; n += 1) {
819
+ const name = `${stem}_${n}`;
820
+ if (!used.has(name)) {
821
+ used.add(name);
822
+ return name;
823
+ }
824
+ }
825
+ };
826
+ /** Rewrite, in `doc`, the reads of `key` by the readers of each writer: in each reader's fields, and the document's
827
+ * `output.path` when it reads. Returns the next document and the readers whose code mentions the key. */
828
+ function carry(draft, doc, entries, writers, rename, key, within, asKey) {
829
+ const seen = new Set();
830
+ const found = [];
831
+ let next = doc;
832
+ let output = false;
833
+ const inside = (path) => within === undefined || path === within || path.startsWith(`${within}/`);
834
+ for (const writer of writers) {
835
+ const scope = readersOf(entries, writer, asKey !== undefined && writer.node.as === asKey);
836
+ output ||= scope.output && within === undefined;
837
+ for (const { entry, mode } of scope.readers) {
838
+ if (!inside(entry.path) || seen.has(`${entry.path}|${mode}`))
839
+ continue;
840
+ seen.add(`${entry.path}|${mode}`);
841
+ if (mode === "own" && sourcesOf(entry.node).some((source) => mentions(source, key)) && !found.includes(entry.path))
842
+ found.push(entry.path);
843
+ next = draft.revise(next, entry.keys, (node) => renameReads(node, mode, rename));
844
+ }
845
+ }
846
+ if (output && isObject(doc.output) && typeof doc.output.path === "string") {
847
+ const path = renamePath(doc.output.path, rename, false, "/output/path");
848
+ if (path !== doc.output.path)
849
+ next = draft.update(next, ["output", "path"], () => path);
850
+ }
851
+ return { doc: next, mentions: found };
852
+ }
853
+ // ---- the operations ---------------------------------------------------------------------------------------------------
854
+ /** Put `node` (copied) into `slot` of the node at `parentPath`, at `index`. In a chain's steps or a parallel's branches
855
+ * the index is a position, 0 to the count. A slot that holds one node takes index 0 when empty; when it holds a node,
856
+ * 0 puts the new one first and 1 puts it last, in a new chain of the two. */
857
+ export function insert(doc, parentPath, slot, index, node) {
858
+ const before = documentOf(doc);
859
+ const added = nodeOf(node, `${parentPath}/${slot}`);
860
+ const draft = new Draft();
861
+ return finish(draft, before, place(draft, before, slotAt(before, entriesOf(before), parentPath, slot), index, clone(added)));
862
+ }
863
+ /** Take out the node at `path`, and everything inside it. */
864
+ export function remove(doc, path) {
865
+ const before = documentOf(doc);
866
+ const draft = new Draft();
867
+ return finish(draft, before, takeOut(draft, before, find(entriesOf(before), path)));
868
+ }
869
+ /** Move the node at `fromPath` into `slot` of the node at `toParentPath`, at `index`, counted in the document as given:
870
+ * the drop point a canvas shows. A node never moves inside itself. */
871
+ export function move(doc, fromPath, toParentPath, slot, index) {
872
+ const before = documentOf(doc);
873
+ const entries = entriesOf(before);
874
+ const from = find(entries, fromPath);
875
+ if (toParentPath === fromPath || toParentPath.startsWith(`${fromPath}/`))
876
+ throw new EditError("MOVE_INTO_SELF", fromPath, `${fromPath} cannot move inside itself (${toParentPath})`);
877
+ const target = slotAt(before, entries, toParentPath, slot);
878
+ checkIndex(target, index);
879
+ // Taking the node out shifts the later items of its array down by one: the target's parent and, in the same array, its index.
880
+ const holder = `${from.parentPath}/${from.slot}`;
881
+ const shift = (path) => {
882
+ if (!from.many || !path.startsWith(`${holder}/`))
883
+ return path;
884
+ const [at, ...rest] = path.slice(holder.length + 1).split("/");
885
+ return Number(at) > from.index ? [holder, String(Number(at) - 1), ...rest].join("/") : path;
886
+ };
887
+ const sameArray = from.many && target.many && target.path === holder;
888
+ const draft = new Draft();
889
+ const without = takeOut(draft, before, from);
890
+ const parent = shift(toParentPath);
891
+ return finish(draft, before, place(draft, without, slotAt(without, entriesOf(without), parent, slot), sameArray && from.index < index ? index - 1 : index, from.node));
892
+ }
893
+ /** Put a copy of the node at `path` right after it: the next step or branch, or, in a slot that holds one node, the
894
+ * second step of a new chain. Every node of the copy gets a fresh label, every key it writes a fresh name, and its own
895
+ * references follow its keys; the copy's code and shell sources that mention an old key are listed in `mentions`. */
896
+ export function duplicate(doc, path) {
897
+ const before = documentOf(doc);
898
+ const entries = entriesOf(before);
899
+ const source = find(entries, path);
900
+ // The copy as a document of its own: its nodes named afresh, then its reads of its own keys carried.
901
+ const scratch = new Draft();
902
+ let copy = { root: clone(source.node) };
903
+ const labels = new Set(entries.flatMap((entry) => typeof entry.node.label === "string" ? [entry.node.label] : []));
904
+ const names = new Set([...labels, ...namesUsed(before, entries, source.scope)]);
905
+ const renamed = new Map();
906
+ const inCopy = entriesOf(copy);
907
+ // A copied child workflow's keys also stay off the names its own scope uses: the keys its input gives it, first.
908
+ const childNames = new Map();
909
+ for (const entry of inCopy)
910
+ if (entry.scope !== "" && !childNames.has(entry.scope))
911
+ childNames.set(entry.scope, namesUsed(copy, inCopy, entry.scope));
912
+ for (const entry of inCopy) {
913
+ const key = (old, base = old) => {
914
+ const scope = renamed.get(entry.scope) ?? new Map();
915
+ renamed.set(entry.scope, scope);
916
+ if (!scope.has(old)) {
917
+ const name = fresh(base, entry.scope === "" ? names : new Set([...names, ...childNames.get(entry.scope)]));
918
+ names.add(name);
919
+ scope.set(old, name);
920
+ }
921
+ return scope.get(old);
922
+ };
923
+ copy = scratch.update(copy, entry.keys, (value) => {
924
+ const node = { ...value };
925
+ if (typeof node.label === "string") {
926
+ // A label stored with "/" (refuseSlashLabel) is copied with "_" for it, numbered as a copy (`read/write` gives
927
+ // `read_write_2`), so the copy is one a save takes and the original keeps the name it would be renamed to.
928
+ const base = node.label.replace(/\//g, "_");
929
+ if (base !== node.label) {
930
+ labels.add(base);
931
+ names.add(base);
932
+ }
933
+ node.label = labelIsKey(node) ? key(node.label, base) : fresh(base, labels);
934
+ }
935
+ if (typeof node.label === "string") {
936
+ labels.add(node.label);
937
+ names.add(node.label);
938
+ }
939
+ if (typeof node.as === "string")
940
+ node.as = key(node.as);
941
+ if (typeof node.failedAs === "string")
942
+ node.failedAs = key(node.failedAs);
943
+ return node;
944
+ });
945
+ }
946
+ for (const [scope, keys] of renamed)
947
+ for (const [old, name] of keys) {
948
+ const at = entriesOf(copy);
949
+ const writers = at.filter((entry) => entry.scope === scope && keysWritten(entry.node).includes(name));
950
+ copy = carry(scratch, copy, at, writers, renameHead(old, name), old, "/root", name).doc;
951
+ }
952
+ // Code is copied as it is, so the copy's code that names a key it writes afresh still names the old key. The copy's
953
+ // nodes are placed as they are, so they are found in the result by identity.
954
+ const named = new Set(entriesOf(copy).filter((entry) => {
955
+ const old = [...(renamed.get(entry.scope)?.keys() ?? [])];
956
+ return sourcesOf(entry.node).some((source) => old.some((key) => mentions(source, key)));
957
+ }).map((entry) => entry.node));
958
+ const draft = new Draft();
959
+ const target = slotAt(before, entries, source.parentPath, source.slot);
960
+ const result = finish(draft, before, place(draft, before, target, source.many ? source.index + 1 : 1, copy.root));
961
+ return { ...result, mentions: entriesOf(result.doc).filter((entry) => named.has(entry.node)).map((entry) => entry.path) };
962
+ }
963
+ /** Put the nodes at `paths` (one node, or consecutive steps or branches of one container, in any order) into a new
964
+ * container of `kind`, where the first of them was. A map's, loop's or route's body is the one node or a chain of
965
+ * them; a parallel takes each as a branch. The new container's fields are placeholders the validator flags. */
966
+ export function wrap(doc, paths, kind) {
967
+ const before = documentOf(doc);
968
+ if (!["map", "loop", "route", "parallel", "chain"].includes(kind))
969
+ throw new EditError("WRAP_INVALID", paths?.[0] ?? "", `"${String(kind)}" is not a container wrap makes`);
970
+ if (!Array.isArray(paths) || !paths.length)
971
+ throw new EditError("WRAP_INVALID", "", "wrap needs at least one node");
972
+ const entries = entriesOf(before);
973
+ const picked = paths.map((path) => find(entries, path)).sort((a, b) => a.index - b.index);
974
+ if (new Set(paths).size !== paths.length)
975
+ throw new EditError("WRAP_INVALID", paths[0], "a node is named twice");
976
+ const first = picked[0];
977
+ if (picked.length > 1 && !picked.every((entry, i) => entry.many && entry.parentPath === first.parentPath && entry.slot === first.slot && entry.index === first.index + i)) {
978
+ throw new EditError("WRAP_INVALID", first.path, "the nodes to wrap must be consecutive steps or branches of one container");
979
+ }
980
+ if (kind === "parallel" && picked.length < 2)
981
+ throw new EditError("WRAP_INVALID", first.path, "a parallel needs at least two nodes, one per branch");
982
+ const nodes = picked.map((entry) => entry.node);
983
+ const body = nodes.length === 1 ? nodes[0] : { node: "chain", steps: nodes };
984
+ const labels = new Set(entries.flatMap((entry) => typeof entry.node.label === "string" ? [entry.node.label] : []));
985
+ const names = new Set([...labels, ...namesUsed(before, entries, first.scope)]);
986
+ const label = kind === "chain" ? "" : fresh(kind, labels);
987
+ if (label)
988
+ names.add(label);
989
+ const container = kind === "chain" ? { node: "chain", steps: nodes }
990
+ : kind === "parallel" ? { node: "parallel", label, branches: nodes }
991
+ : kind === "map" ? { node: "map", label, itemsPath: placeholder("itemsPath"), as: fresh("results", names), body }
992
+ : kind === "loop" ? { node: "loop", label, body, until: placeholder("until"), maxIters: placeholder("maxIters") }
993
+ : { node: "route", label, valuePath: placeholder("valuePath"), branches: { match: { body }, skip: { body: { node: "code", label: fresh("skip", names), code: "s => ({})" } } }, otherwise: "skip" };
994
+ const draft = new Draft();
995
+ return finish(draft, before, putInstead(draft, before, first, [container], picked.length));
996
+ }
997
+ /** Whether the subtree at `body` reads one of `keys` (a key, or a key with a "$" suffix): a reference in its fields, or
998
+ * a word of its code. With `maps`, a nested map's body is left out: its `item` is that map's own. */
999
+ const bodyReads = (entries, owner, body, keys, maps) => {
1000
+ const under = (path, root) => path === root || path.startsWith(`${root}/`);
1001
+ // A nested map, the body itself included, reads its own item in its body; its own fields still read the outer one.
1002
+ const nested = maps ? entries.filter((entry) => entry.node.node === "map" && under(entry.path, body)).map((entry) => `${entry.path}/body`) : [];
1003
+ const reads = (head) => keys.some((key) => head === key || head.startsWith(`${key}$`));
1004
+ return entries.some((entry) => entry.scope === owner.scope && under(entry.path, body) && !nested.some((inner) => under(entry.path, inner))
1005
+ && ([...headsRead(entry.node)].some(reads) || sourcesOf(entry.node).some((source) => keys.some((key) => mentions(source, key)))));
1006
+ };
1007
+ /** Put the children of the container at `path` where it was: a chain's steps or a parallel's branches, the body of a
1008
+ * map or a loop, or the body of the route branch `branch` names. Into a chain they are spliced; a parallel's branches
1009
+ * join an enclosing parallel; a slot that holds one node takes one child, or a chain of a parallel's branches. */
1010
+ export function unwrap(doc, path, branch) {
1011
+ const before = documentOf(doc);
1012
+ const entries = entriesOf(before);
1013
+ const entry = find(entries, path);
1014
+ const node = entry.node;
1015
+ const kind = String(node.node);
1016
+ if (branch !== undefined && kind !== "route")
1017
+ throw new EditError("UNWRAP_INVALID", path, `a ${kind} has no branch to keep`);
1018
+ let children;
1019
+ switch (kind) {
1020
+ case "chain":
1021
+ children = Array.isArray(node.steps) ? node.steps : [];
1022
+ break;
1023
+ case "parallel":
1024
+ children = Array.isArray(node.branches) ? node.branches : [];
1025
+ break;
1026
+ case "map":
1027
+ if (bodyReads(entries, entry, `${path}/body`, ["item", "item_index"], true))
1028
+ throw new EditError("UNWRAP_INVALID", path, `the body of ${path} reads the map's item; it cannot run outside the map`);
1029
+ children = [node.body];
1030
+ break;
1031
+ case "loop":
1032
+ children = [node.body];
1033
+ break;
1034
+ case "route":
1035
+ if (branch === undefined)
1036
+ throw new EditError("UNWRAP_INVALID", path, `name the branch of ${path} to keep`);
1037
+ if (!isObject(node.branches) || !Object.hasOwn(node.branches, branch) || !isObject(node.branches[branch]))
1038
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${branch}"`);
1039
+ if (typeof node.as === "string" && bodyReads(entries, entry, `${path}/branches/${escape(branch)}/body`, [node.as], false))
1040
+ throw new EditError("UNWRAP_INVALID", path, `branch "${branch}" of ${path} reads the route's choice ("${node.as}"); it cannot run outside the route`);
1041
+ children = [node.branches[branch].body];
1042
+ break;
1043
+ default: throw new EditError("UNWRAP_INVALID", path, kind === "workflow" ? `${path} runs a child workflow on its own state; it is not unwrapped` : `a ${kind} node holds no nodes to unwrap`);
1044
+ }
1045
+ if (!children.length || !children.every(isNode))
1046
+ throw new EditError("UNWRAP_INVALID", path, `${path} holds no nodes to unwrap`);
1047
+ const nodes = children;
1048
+ const intoParallel = entry.many && entry.slot === "branches";
1049
+ if (intoParallel && kind !== "parallel" && nodes.length > 1)
1050
+ throw new EditError("UNWRAP_INVALID", path, `${path} is a parallel's branch; its ${nodes.length} steps cannot each become one`);
1051
+ if (!entry.many && kind === "chain" && nodes.length > 1)
1052
+ throw new EditError("UNWRAP_INVALID", path, `${path} is the one node of its slot; its steps have nowhere else to go`);
1053
+ const draft = new Draft();
1054
+ return finish(draft, before, putInstead(draft, before, entry, nodes));
1055
+ }
1056
+ /** Add a branch to the parallel or route at `path`: `node` (copied) last among a parallel's branches, or as the body of
1057
+ * a new route branch `name`, after the others. */
1058
+ export function addBranch(doc, path, node, name) {
1059
+ const before = documentOf(doc);
1060
+ const entry = find(entriesOf(before), path);
1061
+ const added = clone(nodeOf(node, path));
1062
+ const draft = new Draft();
1063
+ if (entry.node.node === "parallel") {
1064
+ if (name !== undefined)
1065
+ throw new EditError("NAME_INVALID", path, "a parallel's branches have no names");
1066
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => [...(Array.isArray(value) ? value : []), added]));
1067
+ }
1068
+ if (entry.node.node !== "route")
1069
+ throw new EditError("SLOT_INVALID", path, `a ${String(entry.node.node)} node has no branches`);
1070
+ if (typeof name !== "string" || !name.trim())
1071
+ throw new EditError("NAME_INVALID", path, "a route branch needs a name");
1072
+ refusePrototypeName(name, path);
1073
+ if (isObject(entry.node.branches) && Object.hasOwn(entry.node.branches, name))
1074
+ throw new EditError("BRANCH_TAKEN", path, `${path} already has a branch "${name}"`);
1075
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => Object.fromEntries([...Object.entries(isObject(value) ? value : {}), [name, { body: added }]])));
1076
+ }
1077
+ /** Take out a branch of the parallel or route at `path`: a parallel's by its index, a route's by its name. */
1078
+ export function removeBranch(doc, path, branch) {
1079
+ const before = documentOf(doc);
1080
+ const entry = find(entriesOf(before), path);
1081
+ const node = entry.node;
1082
+ const draft = new Draft();
1083
+ if (node.node === "parallel") {
1084
+ if (!Array.isArray(node.branches) || !Number.isInteger(branch) || branch < 0 || branch >= node.branches.length)
1085
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch ${String(branch)}`);
1086
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => value.filter((_, index) => index !== branch)));
1087
+ }
1088
+ if (node.node !== "route")
1089
+ throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no branches`);
1090
+ if (typeof branch !== "string" || !isObject(node.branches) || !Object.hasOwn(node.branches, branch))
1091
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(branch)}"`);
1092
+ if (node.otherwise === branch || (isObject(node.unsure) && node.unsure.branch === branch))
1093
+ throw new EditError("BRANCH_IN_USE", path, `${node.otherwise === branch ? "otherwise" : "unsure"} names branch "${branch}" of ${path}`);
1094
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => Object.fromEntries(Object.entries(value).filter(([key]) => key !== branch))));
1095
+ }
1096
+ /** Rename branch `from` of the route at `path` to `to`, in its place among the others; `otherwise` and `unsure` follow. */
1097
+ export function renameBranch(doc, path, from, to) {
1098
+ const before = documentOf(doc);
1099
+ const entry = find(entriesOf(before), path);
1100
+ const node = entry.node;
1101
+ if (node.node !== "route")
1102
+ throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no named branches`);
1103
+ if (!isObject(node.branches) || typeof from !== "string" || !Object.hasOwn(node.branches, from))
1104
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(from)}"`);
1105
+ if (typeof to !== "string" || !to.trim())
1106
+ throw new EditError("NAME_INVALID", path, "a route branch needs a name");
1107
+ const draft = new Draft();
1108
+ if (to === from)
1109
+ return finish(draft, before, before);
1110
+ refusePrototypeName(to, path);
1111
+ if (Object.hasOwn(node.branches, to))
1112
+ throw new EditError("BRANCH_TAKEN", path, `${path} already has a branch "${to}"`);
1113
+ return finish(draft, before, draft.revise(before, entry.keys, (value) => {
1114
+ const route = { ...value };
1115
+ route.branches = Object.fromEntries(Object.entries(route.branches).map(([key, inner]) => [key === from ? to : key, inner]));
1116
+ if (route.otherwise === from)
1117
+ route.otherwise = to;
1118
+ if (isObject(route.unsure) && route.unsure.branch === from)
1119
+ route.unsure = { ...route.unsure, branch: to };
1120
+ return route;
1121
+ }));
1122
+ }
1123
+ /** Write `value` (copied) at the field of the node at `path`, in its place; `undefined` removes an optional field. */
1124
+ export function setField(doc, path, field, value) {
1125
+ const before = documentOf(doc);
1126
+ const entry = find(entriesOf(before), path);
1127
+ const kind = String(entry.node.node);
1128
+ if (field === "node")
1129
+ throw new EditError("FIELD_INVALID", path, "a node's kind is fixed; insert a node of the other kind instead");
1130
+ if ((SLOT_FIELDS[kind] ?? []).includes(field))
1131
+ throw new EditError("FIELD_INVALID", path, `"${field}" holds the ${kind}'s children; insert, remove, move and the branch operations write it`);
1132
+ if (!editableFields(entry.node).includes(field))
1133
+ throw new EditError("FIELD_INVALID", path, `a ${isByValue(entry.node) ? "route by value" : kind} node has no field "${field}"`);
1134
+ if (value === undefined && requiredFields(entry.node).includes(field))
1135
+ throw new EditError("FIELD_INVALID", path, `a ${kind} node needs "${field}"; it cannot be removed`);
1136
+ // Writing the value the field already holds is no change, whatever the name.
1137
+ if ((field === "label" || field === "as" || field === "failedAs") && value !== entry.node[field])
1138
+ refusePrototypeName(value, path);
1139
+ if (field === "label" && value !== entry.node.label)
1140
+ refuseSlashLabel(value, path);
1141
+ const draft = new Draft();
1142
+ return finish(draft, before, draft.update(before, [...entry.keys, field], () => value === undefined ? DELETE : clone(value)));
1143
+ }
1144
+ /** Another node of `entry`'s workflow labelled `name`. A label is unique in its workflow: a child workflow's labels are
1145
+ * its own (a run names its steps `<child>/<step>`). */
1146
+ const labelHolder = (entries, entry, name) => entries.find((other) => other !== entry && other.scope === entry.scope && other.node.label === name);
1147
+ /** Refuse a key another node of the scope or the scope's input also writes: a rename cannot tell whose readers are whose. */
1148
+ const checkUnshared = (doc, entries, entry, key) => {
1149
+ const others = entries.filter((other) => other !== entry && other.scope === entry.scope && keysWritten(other.node).includes(key));
1150
+ if (others.length || inputKeys(doc, entries, entry.scope).has(key)) {
1151
+ throw new EditError("NAME_SHARED", entry.path, `"${key}" is also written by ${others.length ? others.map((other) => other.path).join(", ") : "the workflow's input"}; a rename cannot tell whose readers are whose`, others.map((other) => other.path));
1152
+ }
1153
+ };
1154
+ /** Rename the label of the node at `path`. When the label is the key the node writes (an agent, decide, extract or code
1155
+ * node with no `as`), every reference in scope follows it, and the code and shell sources in scope that mention the old
1156
+ * key are listed in `mentions`, unchanged: a code node's own code included, when it names the key. */
1157
+ export function rename(doc, path, name) {
1158
+ const before = documentOf(doc);
1159
+ const entries = entriesOf(before);
1160
+ const entry = find(entries, path);
1161
+ const node = entry.node;
1162
+ if (!editableFields(node).includes("label"))
1163
+ throw new EditError("FIELD_INVALID", path, `a ${String(node.node)} node has no label`);
1164
+ const draft = new Draft();
1165
+ if (name === node.label)
1166
+ return { ...finish(draft, before, before), mentions: [] };
1167
+ if (typeof name !== "string" || !name.trim() || name.includes("$"))
1168
+ throw new EditError("NAME_INVALID", path, `a label is a non-empty name with no "$": ${JSON.stringify(name)}`);
1169
+ refusePrototypeName(name, path);
1170
+ refuseSlashLabel(name, path);
1171
+ const keyed = labelIsKey(node) && typeof node.label === "string";
1172
+ if (keyed && !KEY_NAME.test(name))
1173
+ throw new EditError("NAME_INVALID", path, `the label of ${path} is the key it writes, so it takes letters, digits and "_" only: ${JSON.stringify(name)}`);
1174
+ const holder = labelHolder(entries, entry, name);
1175
+ if (holder)
1176
+ throw new EditError("NAME_TAKEN", path, `${holder.path} is labelled "${name}"`, [holder.path]);
1177
+ const relabel = () => draft.update(before, [...entry.keys, "label"], () => name);
1178
+ if (!keyed)
1179
+ return { ...finish(draft, before, relabel()), mentions: [] };
1180
+ const key = node.label;
1181
+ if (namesUsed(before, entries, entry.scope).has(name))
1182
+ throw new EditError("NAME_TAKEN", path, `"${name}" is already a key, a reference, an input or a word of code in this workflow`);
1183
+ checkUnshared(before, entries, entry, key);
1184
+ const carried = carry(draft, relabel(), entries, [entry], renameHead(key, name), key);
1185
+ // A code node whose record names its own label still writes that key, under the old name: the caller must see it. In
1186
+ // a loop, the node reads its own key and carry has listed it already.
1187
+ const own = sourcesOf(node).some((source) => mentions(source, key)) && !carried.mentions.includes(path) ? [path] : [];
1188
+ return { ...finish(draft, before, carried.doc), mentions: [...own, ...carried.mentions] };
1189
+ }
1190
+ /** Rename the state key the node at `path` writes: its `as` when it has one, else its label when the label is the key
1191
+ * (an agent, decide, extract or code node with no `as`, where this is `rename`); or, with `field: "failedAs"`, the key a
1192
+ * map writes its failed items under. Every reference in scope follows it, `<key>$answers` and `<key>$verify` included,
1193
+ * and the code and shell sources in scope that mention the old key are listed in `mentions`, unchanged. */
1194
+ export function renameKey(doc, path, name, options = {}) {
1195
+ const before = documentOf(doc);
1196
+ const entries = entriesOf(before);
1197
+ const entry = find(entries, path);
1198
+ const node = entry.node;
1199
+ const field = options?.field ?? "as";
1200
+ if (field !== "as" && field !== "failedAs")
1201
+ throw new EditError("FIELD_INVALID", path, `renameKey renames "as" or "failedAs", not ${JSON.stringify(field)}`);
1202
+ if (typeof node[field] !== "string") {
1203
+ if (field === "as" && labelIsKey(node) && typeof node.label === "string")
1204
+ return rename(before, path, name);
1205
+ throw new EditError("FIELD_INVALID", path, field === "as"
1206
+ ? `a ${String(node.node)} node ${node.as === undefined ? "with no as " : ""}writes no key of its own to rename`
1207
+ : `a ${String(node.node)} node with no failedAs has no failedAs to rename`);
1208
+ }
1209
+ const draft = new Draft();
1210
+ const key = node[field];
1211
+ if (name === key)
1212
+ return { ...finish(draft, before, before), mentions: [] };
1213
+ if (typeof name !== "string" || !KEY_NAME.test(name))
1214
+ throw new EditError("NAME_INVALID", path, `a state key takes letters, digits and "_" only: ${JSON.stringify(name)}`);
1215
+ refusePrototypeName(name, path);
1216
+ // The node's own label is a name, not a key: its key may take it.
1217
+ const holder = labelHolder(entries, entry, name);
1218
+ if (holder)
1219
+ throw new EditError("NAME_TAKEN", path, `${holder.path} is labelled "${name}"`, [holder.path]);
1220
+ if (namesUsed(before, entries, entry.scope, entry).has(name))
1221
+ throw new EditError("NAME_TAKEN", path, `"${name}" is already a key, a reference, an input or a word of code in this workflow`);
1222
+ checkUnshared(before, entries, entry, key);
1223
+ const carried = carry(draft, draft.update(before, [...entry.keys, field], () => name), entries, [entry], renameHead(key, name), key, undefined, field === "as" ? key : undefined);
1224
+ return { ...finish(draft, before, carried.doc), mentions: carried.mentions };
1225
+ }
1226
+ // ---- what an editor's property panel reads and writes --------------------------------------------------------------
1227
+ /** Write `criteria`, the text Jev reads to choose it, on branch `branch` of the judged route at `path`, in its place;
1228
+ * `undefined` removes it. A route by value matches its branches by name and takes no criteria. */
1229
+ export function setBranchCriteria(doc, path, branch, criteria) {
1230
+ const before = documentOf(doc);
1231
+ const entry = find(entriesOf(before), path);
1232
+ const node = entry.node;
1233
+ if (node.node !== "route")
1234
+ throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no branches`);
1235
+ if (isByValue(node))
1236
+ throw new EditError("FIELD_INVALID", path, `${path} is a route by value: it matches its branches by name and takes no criteria`);
1237
+ if (!isObject(node.branches) || typeof branch !== "string" || !Object.hasOwn(node.branches, branch) || !isObject(node.branches[branch]))
1238
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(branch)}"`);
1239
+ if (criteria !== undefined && typeof criteria !== "string")
1240
+ throw new EditError("FIELD_INVALID", path, `a branch's criteria are a text: ${JSON.stringify(criteria)}`);
1241
+ const draft = new Draft();
1242
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches", branch, "criteria"], () => criteria === undefined ? DELETE : criteria));
1243
+ }
1244
+ /** The workflow a scope names: the document for "", or the child of the workflow node at that path. */
1245
+ const scopeOf = (doc, entries, scope) => {
1246
+ if (scope === "")
1247
+ return { workflow: doc, pointer: "", keys: [] };
1248
+ const entry = find(entries, scope);
1249
+ if (entry.node.node !== "workflow" || !isObject(entry.node.workflow))
1250
+ throw new EditError("SLOT_INVALID", scope, `a ${String(entry.node.node)} node holds no child workflow`);
1251
+ return { workflow: entry.node.workflow, pointer: `${scope}/workflow`, keys: [...entry.keys, "workflow"] };
1252
+ };
1253
+ /** The pointers, in `schema` (at `pointer`), of each `$ref` that names the workflow schema `id`: `#/definitions/<id>`.
1254
+ * One under the schema's own `definitions` counts too: the validator resolves it there only when the schema is the
1255
+ * one a field names, not when another schema's `$ref` reaches it. */
1256
+ const refsTo = (schema, id, pointer) => {
1257
+ const out = [];
1258
+ const visit = (value, at) => {
1259
+ if (Array.isArray(value))
1260
+ value.forEach((inner, i) => visit(inner, `${at}/${i}`));
1261
+ else if (isObject(value))
1262
+ for (const [key, inner] of Object.entries(value)) {
1263
+ if (key === "$ref" && inner === `#/definitions/${id}`)
1264
+ out.push(`${at}/${escape(key)}`);
1265
+ else
1266
+ visit(inner, `${at}/${escape(key)}`);
1267
+ }
1268
+ };
1269
+ visit(schema, pointer);
1270
+ return out;
1271
+ };
1272
+ /** The JSON Pointers of the values that name schema `id` of a scope ("" for the document, or a workflow node's path
1273
+ * for its child's schemas): the workflow's `input.schemaId` and `output.schemaId`, a `$ref` from another of its
1274
+ * schemas, and the `out` and `verify.out` of its nodes (a workflow node's `out` names its parent's schema). */
1275
+ export function schemaUsers(doc, id, scope = "") {
1276
+ const before = documentOf(doc);
1277
+ const entries = entriesOf(before);
1278
+ const { workflow, pointer } = scopeOf(before, entries, scope);
1279
+ const out = [];
1280
+ if (isObject(workflow.input) && workflow.input.schemaId === id)
1281
+ out.push(`${pointer}/input/schemaId`);
1282
+ if (isObject(workflow.output) && workflow.output.schemaId === id)
1283
+ out.push(`${pointer}/output/schemaId`);
1284
+ if (isObject(workflow.schemas))
1285
+ for (const [name, schema] of Object.entries(workflow.schemas))
1286
+ if (name !== id)
1287
+ out.push(...refsTo(schema, id, `${pointer}/schemas/${escape(name)}`));
1288
+ for (const entry of entries) {
1289
+ if (entry.scope !== scope)
1290
+ continue;
1291
+ if (entry.node.out === id)
1292
+ out.push(`${entry.path}/out`);
1293
+ if (isObject(entry.node.verify) && entry.node.verify.out === id)
1294
+ out.push(`${entry.path}/verify/out`);
1295
+ }
1296
+ return out;
1297
+ }
1298
+ /** Write `schema` (copied) as schema `id` of a scope ("" for the document, or a workflow node's path for its child), in
1299
+ * its place when it exists; `undefined` removes it, unless something still names it (`schemaUsers`). */
1300
+ export function setSchema(doc, id, schema, scope = "") {
1301
+ const before = documentOf(doc);
1302
+ const entries = entriesOf(before);
1303
+ const { workflow, keys } = scopeOf(before, entries, scope);
1304
+ if (typeof id !== "string" || !id.trim() || id === "__proto__")
1305
+ throw new EditError("NAME_INVALID", scope, `a schema id is a non-empty name other than "__proto__": ${JSON.stringify(id)}`);
1306
+ const schemas = isObject(workflow.schemas) ? workflow.schemas : undefined;
1307
+ const draft = new Draft();
1308
+ if (schema === undefined) {
1309
+ if (!schemas || !Object.hasOwn(schemas, id))
1310
+ throw new EditError("SCHEMA_NOT_FOUND", scope, `${scope || "the document"} has no schema "${id}"`);
1311
+ const users = schemaUsers(before, id, scope);
1312
+ if (users.length)
1313
+ throw new EditError("SCHEMA_IN_USE", scope, `schema "${id}" is named by ${users.join(", ")}`, users);
1314
+ return finish(draft, before, draft.update(before, [...keys, "schemas", id], () => DELETE));
1315
+ }
1316
+ if (!isObject(schema))
1317
+ throw new EditError("SCHEMA_INVALID", scope, `a schema is a JSON object: ${JSON.stringify(schema)}`);
1318
+ if (!schemas)
1319
+ return finish(draft, before, draft.update(before, [...keys, "schemas"], () => ({ [id]: clone(schema) })));
1320
+ return finish(draft, before, draft.update(before, [...keys, "schemas", id], () => clone(schema)));
1321
+ }
1322
+ /** Write the document's own `input` or `output` (copied): `{ schemaId }`, naming one of its schemas, and for the output
1323
+ * an optional `path`, the state path its value is read from when the run ends. `undefined` removes the input; a workflow
1324
+ * always has its output. Whether the schema exists and something sets the path is the validator's call. */
1325
+ export function setWorkflowField(doc, field, value) {
1326
+ const before = documentOf(doc);
1327
+ if (field !== "input" && field !== "output")
1328
+ throw new EditError("FIELD_INVALID", "", `a workflow's own field edited here is input or output: ${JSON.stringify(field)}`);
1329
+ const draft = new Draft();
1330
+ if (value === undefined) {
1331
+ if (field === "output")
1332
+ throw new EditError("FIELD_INVALID", "/output", "a workflow needs its output");
1333
+ return finish(draft, before, draft.update(before, ["input"], () => DELETE));
1334
+ }
1335
+ if (!isObject(value) || typeof value.schemaId !== "string" || !value.schemaId.trim())
1336
+ throw new EditError("FIELD_INVALID", `/${field}`, `a workflow's ${field} names a schema: ${JSON.stringify(value)}`);
1337
+ if (field === "output" && value.path !== undefined && typeof value.path !== "string")
1338
+ throw new EditError("FIELD_INVALID", "/output", `the output's path is a state path: ${JSON.stringify(value.path)}`);
1339
+ return finish(draft, before, draft.update(before, [field], () => clone(value)));
1340
+ }
1341
+ /** The engine-owned keys a node writes beside `key`: a judge's, a pick's or a judged route's answers under
1342
+ * `<as>$answers`, and a verified node's verdict under `<key>$verify`. */
1343
+ const sidecarsOf = (node, key) => [
1344
+ ...(key === node.as && (node.node === "judge" || node.node === "pick" || (node.node === "route" && !isByValue(node))) ? [`${key}$answers`] : []),
1345
+ ...(node.verify !== undefined && key !== node.failedAs ? [`${key}$verify`] : []),
1346
+ ];
1347
+ /** Whether the node sits in a map's body, in its own scope: it reads that map's `item` and `item_index`. */
1348
+ const inMapBody = (entries, target) => {
1349
+ const byPath = new Map(entries.map((entry) => [entry.path, entry]));
1350
+ for (let at = target;;) {
1351
+ const parent = byPath.get(at.parentPath);
1352
+ if (!parent || parent.scope !== target.scope)
1353
+ return false;
1354
+ if (parent.node.node === "map" && at.slot === "body")
1355
+ return true;
1356
+ at = parent;
1357
+ }
1358
+ };
1359
+ /** The names the node at `path` may read, each with what gives it, by the scope rules rename carries a key along: its
1360
+ * workflow's input keys, a map body's `item` and `item_index`, and the keys (with their `<key>$answers` and
1361
+ * `<key>$verify`) of each node whose write it runs after and sees. With `field`, the names that one field of the node
1362
+ * reads, where it sees more than the rest: a map's `resultPath` its body's keys and item, a loop's `until` its body's
1363
+ * keys, `verify` the node's own `as` and `submission`, a pick's or sift's `describe` its own `item` and `item_index`,
1364
+ * and a workflow node's `workflow` (its child's `output.path`) the child's state. */
1365
+ export function namesInScope(doc, path, field) {
1366
+ const before = documentOf(doc);
1367
+ const entries = entriesOf(before);
1368
+ const target = find(entries, path);
1369
+ const child = field === "workflow" && target.node.node === "workflow";
1370
+ const out = [];
1371
+ const seen = new Set();
1372
+ const add = (name, from) => { const key = JSON.stringify([name, from]); if (!seen.has(key)) {
1373
+ seen.add(key);
1374
+ out.push({ name, from });
1375
+ } };
1376
+ for (const key of inputKeys(before, entries, child ? target.path : target.scope))
1377
+ add(key, "input");
1378
+ // A map's body, and its resultPath, read the item; so does a pick's or sift's describe, its own candidate. A verifier
1379
+ // reads the node's result as `submission` too.
1380
+ const item = inMapBody(entries, target) || (field === "resultPath" && target.node.node === "map") || (field === "describe" && (target.node.node === "pick" || target.node.node === "sift"));
1381
+ if (!child && item)
1382
+ for (const key of OWN_ITEM)
1383
+ add(key, "engine");
1384
+ if (field === "verify" && target.node.verify !== undefined)
1385
+ add("submission", "engine");
1386
+ const modes = child ? ["childOutput"] : ["own", ...(field === "resultPath" || field === "until" || field === "verify" ? [field] : [])];
1387
+ const reads = (readers) => readers.some(({ entry, mode }) => entry === target && modes.includes(mode));
1388
+ for (const writer of entries) {
1389
+ const keys = keysWritten(writer.node);
1390
+ if (!keys.length)
1391
+ continue;
1392
+ // A key a node writes reaches its readers. Its own `as` also reaches a route's branches, which run after the route
1393
+ // wrote its choice and answers, and the node's verifier, which runs before its verdict is written.
1394
+ if (reads(readersOf(entries, writer).readers)) {
1395
+ for (const key of keys)
1396
+ for (const name of [key, ...sidecarsOf(writer.node, key)])
1397
+ add(name, writer.path);
1398
+ }
1399
+ else if (typeof writer.node.as === "string" && reads(readersOf(entries, writer, true).readers))
1400
+ for (const name of [writer.node.as, ...(writer.node.node === "route" ? sidecarsOf(writer.node, writer.node.as) : [])])
1401
+ add(name, writer.path);
1402
+ }
1403
+ return out;
1404
+ }
1405
+ /** The names the document's `output.path` may read, each with what gives it, as namesInScope gives a node's: its input
1406
+ * keys, and the keys (with their `<key>$answers` and `<key>$verify`) of each node whose write is in the state when the
1407
+ * run ends, which no key written in a map's body or a child workflow is. A terminal's fixed key is one: a report's, or
1408
+ * a prose artifact's (which runs as a report), `report_markdown`, and a file artifact's `artifact`. */
1409
+ export function outputNames(doc) {
1410
+ const before = documentOf(doc);
1411
+ const entries = entriesOf(before);
1412
+ const out = [];
1413
+ const seen = new Set();
1414
+ const add = (name, from) => { const key = JSON.stringify([name, from]); if (!seen.has(key)) {
1415
+ seen.add(key);
1416
+ out.push({ name, from });
1417
+ } };
1418
+ for (const key of inputKeys(before, entries, ""))
1419
+ add(key, "input");
1420
+ const terminalKeys = (node) => node.node === "report" || (node.node === "artifact" && PROSE_ARTIFACT_TYPES.includes(node.type)) ? ["report_markdown"] : node.node === "artifact" ? ["artifact"] : [];
1421
+ for (const writer of entries) {
1422
+ const names = [...keysWritten(writer.node).flatMap((key) => [key, ...sidecarsOf(writer.node, key)]), ...terminalKeys(writer.node)];
1423
+ if (names.length && readersOf(entries, writer).output)
1424
+ for (const name of names)
1425
+ add(name, writer.path);
1426
+ }
1427
+ return out;
1428
+ }
1429
+ /** Each `{placeholder}` and state path the node at `path` reads, in its fields' order: the references rename carries,
1430
+ * found by the same walk. A workflow node's include its child's `output.path`, which reads the child's state. */
1431
+ export function readsOf(doc, path) {
1432
+ const before = documentOf(doc);
1433
+ const entry = find(entriesOf(before), path);
1434
+ const out = [];
1435
+ const collect = (head, at, optional) => { out.push({ pointer: `${path}${at}`, name: head, ...(optional ? { optional: true } : {}) }); return head; };
1436
+ renameReads(entry.node, "own", collect);
1437
+ if (entry.node.node === "workflow")
1438
+ renameReads(entry.node, "childOutput", collect);
1439
+ return out;
1440
+ }
1441
+ /** The `{placeholder` open at `offset` in `text`: the index of its `{` and the name typed after it up to the cursor, by
1442
+ * the placeholder grammar (letters, digits, "_", "." and "$"; a reference may start with `state.`). Undefined when no
1443
+ * placeholder's name holds the cursor. The placeholder may already be closed after it. */
1444
+ export function openPlaceholderAt(text, offset) {
1445
+ if (typeof text !== "string" || !Number.isInteger(offset) || offset < 0 || offset > text.length)
1446
+ return undefined;
1447
+ let start = offset;
1448
+ while (start > 0 && /[A-Za-z0-9_.$]/.test(text[start - 1]))
1449
+ start -= 1;
1450
+ if (start === 0 || text[start - 1] !== "{")
1451
+ return undefined;
1452
+ return { start: start - 1, prefix: text.slice(start, offset) };
1453
+ }
1454
+ /** `base`, or its stem (`base` without a `_<n>` ending) with the smallest `_<n>` from 2, so that no label, key,
1455
+ * reference, input key or word of code of any scope of the document holds it (a child workflow's that holds no node
1456
+ * yet among them), nor an engine key or a name `Object.prototype` has. `base` is a state key name. */
1457
+ export function freshName(doc, base) {
1458
+ const before = documentOf(doc);
1459
+ if (typeof base !== "string" || !KEY_NAME.test(base))
1460
+ throw new EditError("NAME_INVALID", "", `a name takes letters, digits and "_" only: ${JSON.stringify(base)}`);
1461
+ const entries = entriesOf(before);
1462
+ const used = new Set();
1463
+ // Each workflow node's path is a scope, its child's first node not yet inserted included: that node is named here.
1464
+ const scopes = ["", ...entries.filter((entry) => entry.node.node === "workflow").map((entry) => entry.path)];
1465
+ for (const scope of scopes)
1466
+ for (const name of namesUsed(before, entries, scope))
1467
+ used.add(name);
1468
+ // `base` itself when free, numbered or not, and no reserved name (vocabulary.ts isPrototypeName, the validator's rule);
1469
+ // `fresh` alone numbers a numbered base from its stem even when it is free.
1470
+ if (!used.has(base) && !RESERVED_KEYS.has(base) && !isPrototypeName(base))
1471
+ return base;
1472
+ return fresh(base, used);
1473
+ }
1474
+ /** The smallest node of `kind` for `doc`: its required fields in the schema's order, a fresh name as its label (and its
1475
+ * `as`, where it needs one), and each other field's placeholder. A container is made by wrapping nodes that exist. */
1476
+ export function placeholderNode(doc, kind) {
1477
+ if (typeof kind !== "string" || !KINDS.has(kind))
1478
+ throw new EditError("NODE_INVALID", "", `no node kind "${String(kind)}"`);
1479
+ if (SLOT_FIELDS[kind])
1480
+ throw new EditError("NODE_INVALID", "", `a ${kind} holds nodes; wrap makes one of nodes that exist`);
1481
+ const name = freshName(doc, kind);
1482
+ const node = {};
1483
+ for (const field of requiredFields({ node: kind }))
1484
+ node[field] = field === "node" ? kind : field === "label" || field === "as" ? name : placeholder(field);
1485
+ return node;
1486
+ }