@parcha/agentrun-dsl 0.1.0-beta.186 → 0.1.0-beta.188

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.
package/README.md CHANGED
@@ -186,6 +186,8 @@ The schema helpers resolve the owning workflow's schema catalog; `stageSchemaFor
186
186
 
187
187
  `@parcha/agentrun-dsl/graph` imports nothing, so a static viewer bundles it and a reader with no Node runs it. `workflowGraph(workflow)` returns `{ nodes, edges }` for a workflow document, computed from its JSON alone: a node is `{ path, kind, label, via? }` with `path` a JSON Pointer into the document as written (`/root/steps/1`, `/root/branches/<name>/body`, `/root/body` for a map's or a loop's body, `/root/workflow/root` for a child; the pointers `inspectWorkflow` and a validation issue use), and an edge is `{ from, to, kind }` with `kind` one of `next` (a chain's steps in order, a loop into its body), `branch` (a parallel node's branches), `route` (a route's branches), `item` (a map into its body) and `child` (a workflow node into its child's root). `nodeStatus(graph, source)` says, for each node, `done`, `working`, `failed` or `not-run`, read from what the recovery driver kept: its frame (the `pin` of the frozen snapshot), the map items' records (`agentrun.items`, keyed layout), or both as `{ pin, items }`. A run's map item or loop iteration has no node of its own: its instances count toward the body's node, and a node inside a map's or loop's body is done only once the map or loop is. Once the run has ended, pass its terminal result as `{ pin, items, result }`: an escalation (`result.status` `escalated`, with `result.escalation.executionPath` as `runWorkflow` returns it) marks the escalate node that fired and every container on its path `escalated`, since the frame holds no mark for that node, and a map or loop on that path has ended, so what finished inside it is done. Without a result the status is what it was. To read one item's record on its own, pass `{ item: "<map path>/items/<index>" }` as a third argument: that item is then the instance, and its body is done when the item is. `graphNodeOf(graph, executionPath)` names the node an execution path (an event's or a record's) ran at: `{ path, at }`, where `path` is the node's pointer and `at` lists the map items (`{ kind: "item", index }`) and loop iterations (`{ kind: "iteration", index }`) it ran in, outermost first. An execution path is the node's pointer with `items/<i>` before a map's `body` and `iterations/<i>` before a loop's; the path is read by walking the graph by node kind, so a route branch named `items` stays a branch, and a path the graph does not have is `undefined`. `graphDiff(prev, next)` says what changed between two graphs of a workflow, such as two saved revisions of one: `{ added, removed, changed, moved, edges: { added, removed } }`. A node is the same in both when its `(kind, label)` is unique in each graph, so a step inserted before others is one `added` node (its path in `next`) and the steps after it `moved` (`{ prev, next }` paths), never a run of changes; a node whose `(kind, label)` repeats, or is in one graph only, is matched by its path, and the same path with a new kind or label is `changed` (`{ prev, next, was, now }`, `was` and `now` each `{ kind, label }`). `removed` holds nodes of `prev` only, at their paths there; `rewritten` holds matched nodes whose kind and label stayed but whose own fields changed (new instructions, a new budget: `{ prev, next, kind, label }`); `edges.added` and `edges.removed` hold the edges of one graph only, each in its own graph's paths. Each graph node carries a `changeCheck` for this: 8 hex digits, the FNV-1a hash of the node's own fields as canonical JSON, its children left out as the walk leaves them out. It detects a change; it is not an identity, and not a saved revision's sha256. The pi session's text view draws the same graph.
188
188
 
189
+ `@parcha/agentrun-dsl/edit` edits a workflow document as JSON, one pure function per edit, for a visual editor, a CLI or a server. It imports only the graph and the node vocabulary, so a browser bundles it, and it names a node by its graph path. `insert(doc, parentPath, slot, index, node)`, `remove(doc, path)`, `move(doc, fromPath, toParentPath, slot, index)`, `duplicate(doc, path)`, `wrap(doc, paths, kind)` (in a map, loop, route, parallel or chain), `unwrap(doc, path, branch?)`, `addBranch(doc, path, node, name?)`, `removeBranch(doc, path, branch)`, `renameBranch(doc, path, from, to)`, `setField(doc, path, field, value)`, `rename(doc, path, name)` and `renameKey(doc, path, name, options?)` each return `{ doc, moved, added, removed, changed }`. `doc` is the next document: the input is never mutated, and every subtree the edit did not touch is shared with it, byte for byte. `moved` maps each node whose path changed, old path to new; `added` and `removed` list the nodes only one of the two documents has; `changed` lists the nodes whose own fields changed. A slot is where a child sits under its parent: `steps`, `branches`, `body`, `branches/<name>/body`, `workflow/root`, or `root` under the parent path `""`; `locate(doc, path)` says which one holds a node, and `move` counts its index in the document as given, the drop point between two steps. An edit that would break the document's structure (a report inside a map, a chain with no steps, a parallel with one branch, a node of no known kind or without a required field) throws an `EditError` with a `code` from `EDIT_ERROR_CODES` and the `path` it is about, and writes nothing. Whether each reference is produced and each field filled in is still `validateWorkflow`'s to say: `wrap` gives its new container placeholders the validator flags on it (an empty `itemsPath`, `valuePath` or `until` predicate). `rename` changes a label. When the label is the key the node writes (an agent, decide, extract or code node with no `as`; a code node writes there when its code returns something other than a record), every `{placeholder}` and state path that reads the key in scope follows it, and the code and shell sources that mention it, or one of its `<key>$...` keys, are listed in `mentions`, unchanged. A renamed code node's own code is listed too when it names the key, since a record it returns with that key still writes the old name. `renameKey` renames the key a node writes the same way: its `as` when it has one, any kind's, else its label when that is the key, where it gives the document `rename` gives; `{ field: "failedAs" }` renames a map's `failedAs` instead. No edit gives a label, an `as`, a `failedAs` or a route branch a name `Object.prototype` has (`constructor`, `toString`, `__proto__` and the rest) or `prototype`: `rename`, `renameKey`, `renameBranch` and `setField` refuse one, and `insert` and `addBranch` refuse a node with one anywhere inside it. `renameBranch` carries the route's `otherwise` and `unsure`, but not a value elsewhere that compares against the old branch name (a `field_equals` on the route's `as`, or the value a route by value reads), which the caller must change. `duplicate` copies code as it is, so a copied code node writes the same record keys as its source: duplicating a code branch of a parallel gives two branches that write one key, which the run refuses. The copy's reads of a copied code node's label follow its fresh label, so when that code returns a record naming the old label, those reads find nothing; `duplicate` lists the copy's code and shell sources that mention a key it renamed in `mentions`, as `rename` does. `editableFields(node)` and `requiredFields(node)` are the schema's fields for a node, as `setField` writes them.
190
+
189
191
  The separate `@parcha/agentrun-dsl/demo` entrypoint provides the support-triage example. `@parcha/agentrun-dsl/schema` provides the generated workflow JSON Schema, a JSON file: import it with `import schema from '@parcha/agentrun-dsl/schema' with { type: 'json' };` (a plain `import` throws `ERR_IMPORT_ATTRIBUTE_MISSING`), or load it with `require('@parcha/agentrun-dsl/schema')` in CommonJS.
190
192
 
191
193
  Children can contain maps, loops, routes, parallel branches and other children, and appear inside those structures. Their input/state and schema catalogs stay isolated; terminal report/artifact delivery remains parent-owned. New composed structures require path-aware recovery stores when recovery is enabled. `executionPath` is supplied to adapters, events and checkpoint/recovery hooks. Existing host validators and durable-cursor limits remain authoritative.
package/dist/edit.d.ts ADDED
@@ -0,0 +1,98 @@
1
+ /** A workflow document as JSON: an object whose `root` is a node. */
2
+ export type WorkflowDocument = Record<string, unknown>;
3
+ /** A node as JSON: an object whose `node` is its kind. */
4
+ export type WorkflowNodeJson = Record<string, unknown>;
5
+ /** Where a child sits under its parent node: the pointer segments from the parent to it. A chain's `steps` and a
6
+ * parallel's `branches` hold many, by index; a map's or a loop's `body`, a route branch's `branches/<name>/body` (the
7
+ * name pointer-escaped, as in a graph path) and a child workflow's `workflow/root` hold one. The document holds its
8
+ * root at `root`, under the parent path `""`. */
9
+ export type Slot = "root" | "steps" | "branches" | "body" | "workflow/root" | `branches/${string}/body`;
10
+ /** What an operation returns: the next document and what happened to the nodes of the one it was given. */
11
+ export type EditResult = {
12
+ doc: WorkflowDocument;
13
+ /** Each node whose path changed, from its path before to its path after, in the input's document order. */
14
+ moved: Map<string, string>;
15
+ /** The paths, in the result, of the nodes the input did not have. */
16
+ added: string[];
17
+ /** The paths, in the input, of the nodes the result does not have. */
18
+ removed: string[];
19
+ /** The paths, in the result, of the nodes that were kept with their own fields changed. */
20
+ changed: string[];
21
+ };
22
+ /** What rename returns: an EditResult, and the code and shell sources in scope that mention the old key. */
23
+ export type RenameResult = EditResult & {
24
+ mentions: string[];
25
+ };
26
+ /** What duplicate returns: an EditResult, and the paths, in the result, of the copy's code and shell sources that
27
+ * mention a key the copy writes under a fresh name, by its old name. */
28
+ export type DuplicateResult = EditResult & {
29
+ mentions: string[];
30
+ };
31
+ /** Every code an EditError carries. */
32
+ export declare const EDIT_ERROR_CODES: readonly ["DOCUMENT_INVALID", "PATH_NOT_FOUND", "SLOT_INVALID", "INDEX_OUT_OF_RANGE", "NODE_INVALID", "FIELD_INVALID", "NAME_INVALID", "NAME_TAKEN", "NAME_SHARED", "BRANCH_NOT_FOUND", "BRANCH_TAKEN", "BRANCH_IN_USE", "MOVE_INTO_SELF", "WRAP_INVALID", "UNWRAP_INVALID", "STRUCTURE_INVALID"];
33
+ export type EditErrorCode = typeof EDIT_ERROR_CODES[number];
34
+ /** The one error the operations throw. `path` is the node it is about, in the input document where that node existed
35
+ * there; `related` names other nodes the error is about: the one holding a taken name, the other writers of a key. */
36
+ export declare class EditError extends Error {
37
+ readonly code: EditErrorCode;
38
+ readonly path: string;
39
+ readonly related: readonly string[];
40
+ constructor(code: EditErrorCode, path: string, message: string, related?: readonly string[]);
41
+ }
42
+ /** The fields setField writes on this node: its kind's (and its route form's) own fields, without `node` and the child
43
+ * slots. A property panel lists these. */
44
+ export declare function editableFields(node: WorkflowNodeJson): string[];
45
+ /** The fields the schema requires of this node's kind (and its route form), `node` included. */
46
+ export declare function requiredFields(node: WorkflowNodeJson): string[];
47
+ /** 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
48
+ * node). Undefined when no node sits there. */
49
+ export declare function locate(doc: WorkflowDocument, path: string): {
50
+ parentPath: string;
51
+ slot: Slot;
52
+ index: number;
53
+ } | undefined;
54
+ /** Put `node` (copied) into `slot` of the node at `parentPath`, at `index`. In a chain's steps or a parallel's branches
55
+ * 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,
56
+ * 0 puts the new one first and 1 puts it last, in a new chain of the two. */
57
+ export declare function insert(doc: WorkflowDocument, parentPath: string, slot: Slot, index: number, node: WorkflowNodeJson): EditResult;
58
+ /** Take out the node at `path`, and everything inside it. */
59
+ export declare function remove(doc: WorkflowDocument, path: string): EditResult;
60
+ /** Move the node at `fromPath` into `slot` of the node at `toParentPath`, at `index`, counted in the document as given:
61
+ * the drop point a canvas shows. A node never moves inside itself. */
62
+ export declare function move(doc: WorkflowDocument, fromPath: string, toParentPath: string, slot: Slot, index: number): EditResult;
63
+ /** 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
64
+ * 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
65
+ * references follow its keys; the copy's code and shell sources that mention an old key are listed in `mentions`. */
66
+ export declare function duplicate(doc: WorkflowDocument, path: string): DuplicateResult;
67
+ /** The containers wrap makes. */
68
+ export type WrapKind = "map" | "loop" | "route" | "parallel" | "chain";
69
+ /** Put the nodes at `paths` (one node, or consecutive steps or branches of one container, in any order) into a new
70
+ * 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
71
+ * them; a parallel takes each as a branch. The new container's fields are placeholders the validator flags. */
72
+ export declare function wrap(doc: WorkflowDocument, paths: readonly string[], kind: WrapKind): EditResult;
73
+ /** Put the children of the container at `path` where it was: a chain's steps or a parallel's branches, the body of a
74
+ * map or a loop, or the body of the route branch `branch` names. Into a chain they are spliced; a parallel's branches
75
+ * join an enclosing parallel; a slot that holds one node takes one child, or a chain of a parallel's branches. */
76
+ export declare function unwrap(doc: WorkflowDocument, path: string, branch?: string): EditResult;
77
+ /** Add a branch to the parallel or route at `path`: `node` (copied) last among a parallel's branches, or as the body of
78
+ * a new route branch `name`, after the others. */
79
+ export declare function addBranch(doc: WorkflowDocument, path: string, node: WorkflowNodeJson, name?: string): EditResult;
80
+ /** Take out a branch of the parallel or route at `path`: a parallel's by its index, a route's by its name. */
81
+ export declare function removeBranch(doc: WorkflowDocument, path: string, branch: string | number): EditResult;
82
+ /** Rename branch `from` of the route at `path` to `to`, in its place among the others; `otherwise` and `unsure` follow. */
83
+ export declare function renameBranch(doc: WorkflowDocument, path: string, from: string, to: string): EditResult;
84
+ /** Write `value` (copied) at the field of the node at `path`, in its place; `undefined` removes an optional field. */
85
+ export declare function setField(doc: WorkflowDocument, path: string, field: string, value: unknown): EditResult;
86
+ /** Rename the label of the node at `path`. When the label is the key the node writes (an agent, decide, extract or code
87
+ * node with no `as`), every reference in scope follows it, and the code and shell sources in scope that mention the old
88
+ * key are listed in `mentions`, unchanged: a code node's own code included, when it names the key. */
89
+ export declare function rename(doc: WorkflowDocument, path: string, name: string): RenameResult;
90
+ /** Which key renameKey renames: the node's `as` (the default), or a map's `failedAs`. */
91
+ export type RenameKeyOptions = {
92
+ field?: "as" | "failedAs";
93
+ };
94
+ /** Rename the state key the node at `path` writes: its `as` when it has one, else its label when the label is the key
95
+ * (an agent, decide, extract or code node with no `as`, where this is `rename`); or, with `field: "failedAs"`, the key a
96
+ * map writes its failed items under. Every reference in scope follows it, `<key>$answers` and `<key>$verify` included,
97
+ * and the code and shell sources in scope that mention the old key are listed in `mentions`, unchanged. */
98
+ export declare function renameKey(doc: WorkflowDocument, path: string, name: string, options?: RenameKeyOptions): RenameResult;
package/dist/edit.js ADDED
@@ -0,0 +1,1144 @@
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, or that a reference (as `<name>$...` too), an input
70
+ // or a code source in scope already uses. 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
+ import { workflowGraph } from "./graph.js";
85
+ import { DECISION_NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, NODE_FIELDS, WORKFLOW_NODE_KINDS } from "./vocabulary.js";
86
+ /** Every code an EditError carries. */
87
+ export const EDIT_ERROR_CODES = [
88
+ /** The document is not an object. */
89
+ "DOCUMENT_INVALID",
90
+ /** No node sits at the path. */
91
+ "PATH_NOT_FOUND",
92
+ /** The parent has no such slot, or the node is not a container the operation works on. */
93
+ "SLOT_INVALID",
94
+ /** The index is not a whole number within the slot. */
95
+ "INDEX_OUT_OF_RANGE",
96
+ /** The node is not a node of a known kind with its required fields and only its own fields. */
97
+ "NODE_INVALID",
98
+ /** setField, rename or renameKey named a field the node may not have written that way, or that it lacks. */
99
+ "FIELD_INVALID",
100
+ /** The name is empty, holds a "$", is no state key where the name is one, or is a name an object's prototype has. */
101
+ "NAME_INVALID",
102
+ /** Another node's label or key already holds the name, or a reference, input or code source uses it. */
103
+ "NAME_TAKEN",
104
+ /** Another node or the input writes the key being renamed. */
105
+ "NAME_SHARED",
106
+ /** No branch has that name or index. */
107
+ "BRANCH_NOT_FOUND",
108
+ /** A branch already has that name. */
109
+ "BRANCH_TAKEN",
110
+ /** `otherwise` or `unsure` names the branch. */
111
+ "BRANCH_IN_USE",
112
+ /** The move puts a node inside itself. */
113
+ "MOVE_INTO_SELF",
114
+ /** The nodes to wrap are none, repeated, not consecutive siblings, too few for the container, or the kind is no container. */
115
+ "WRAP_INVALID",
116
+ /** The node is not a container that can be unwrapped there. */
117
+ "UNWRAP_INVALID",
118
+ /** The result would break a rule of the document's structure. */
119
+ "STRUCTURE_INVALID",
120
+ ];
121
+ /** The one error the operations throw. `path` is the node it is about, in the input document where that node existed
122
+ * there; `related` names other nodes the error is about: the one holding a taken name, the other writers of a key. */
123
+ export class EditError extends Error {
124
+ code;
125
+ path;
126
+ related;
127
+ constructor(code, path, message, related = []) {
128
+ super(message);
129
+ this.name = "EditError";
130
+ this.code = code;
131
+ this.path = path;
132
+ this.related = related;
133
+ }
134
+ }
135
+ // ---- the vocabulary, as the edits read it ---------------------------------------------------------------------------
136
+ const KINDS = new Set(WORKFLOW_NODE_KINDS);
137
+ /** The fields of each kind that hold its children, which only the tree operations write. */
138
+ const SLOT_FIELDS = { chain: ["steps"], parallel: ["branches"], map: ["body"], loop: ["body"], route: ["branches"], workflow: ["workflow"] };
139
+ /** Fields only one form of route has: a route Jev chooses, or a route by value. */
140
+ const JUDGED_ROUTE_ONLY = ["state", "instructions", "unsure", ...DECISION_NODE_FIELDS];
141
+ const BY_VALUE_ROUTE_ONLY = ["valuePath", "otherwise"];
142
+ /** The schema's required fields of each kind, and of each form of route. */
143
+ const REQUIRED = {
144
+ chain: ["node", "steps"],
145
+ code: ["node", "label", "code"],
146
+ agent: ["node", "label", "instructions", "out"],
147
+ decide: ["node", "label", "instructions", "out"],
148
+ extract: ["node", "label", "instructions", "out"],
149
+ report: ["node", "label", "instructions"],
150
+ artifact: ["node", "label", "type"],
151
+ map: ["node", "label", "itemsPath", "body", "as"],
152
+ parallel: ["node", "label", "branches"],
153
+ loop: ["node", "label", "body", "until", "maxIters"],
154
+ escalate: ["node", "label", "when", "kind", "stage", "summary"],
155
+ call: ["node", "label", "via", "as", "deadline_s"],
156
+ workflow: ["node", "label", "workflow", "input", "out", "as"],
157
+ judge: ["node", "label", "state", "out", "as"],
158
+ pick: ["node", "label", "itemsPath", "describe", "instructions", "as"],
159
+ sift: ["node", "label", "itemsPath", "out", "as"],
160
+ route: ["node", "label", "state", "instructions", "branches"],
161
+ "route by value": ["node", "label", "valuePath", "branches"],
162
+ };
163
+ /** A judged route takes at most this many branches (System One's choice limit). */
164
+ const MAX_ROUTE_BRANCHES = 240;
165
+ /** The nesting depth `workflowGraph` walks. */
166
+ const MAX_DEPTH = 128;
167
+ /** State keys the engine gives a node, which no rename or fresh name may take. */
168
+ const RESERVED_KEYS = new Set(["item", "item_index", "report_markdown", "artifact", "state", "submission", "$host"]);
169
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
170
+ const isNode = (value) => isObject(value) && typeof value.node === "string";
171
+ const isByValue = (node) => node.node === "route" && node.valuePath !== undefined;
172
+ /** The fields the node's kind (and its route form) accepts, `node` and the child slots included. */
173
+ const fieldsOf = (node) => {
174
+ const kind = String(node.node);
175
+ if (!KINDS.has(kind))
176
+ return [];
177
+ const own = [...NODE_FIELDS[kind], ...HOST_NODE_FIELDS];
178
+ if (kind !== "route")
179
+ return own;
180
+ const other = isByValue(node) ? JUDGED_ROUTE_ONLY : BY_VALUE_ROUTE_ONLY;
181
+ return own.filter((field) => !other.includes(field));
182
+ };
183
+ /** The fields setField writes on this node: its kind's (and its route form's) own fields, without `node` and the child
184
+ * slots. A property panel lists these. */
185
+ export function editableFields(node) {
186
+ if (!isObject(node))
187
+ return [];
188
+ const slots = SLOT_FIELDS[String(node.node)] ?? [];
189
+ return fieldsOf(node).filter((field) => field !== "node" && !slots.includes(field));
190
+ }
191
+ /** The fields the schema requires of this node's kind (and its route form), `node` included. */
192
+ export function requiredFields(node) {
193
+ if (!isObject(node) || !KINDS.has(String(node.node)))
194
+ return [];
195
+ return [...REQUIRED[isByValue(node) ? "route by value" : String(node.node)]];
196
+ }
197
+ // ---- pointers and the walk ------------------------------------------------------------------------------------------
198
+ const escape = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
199
+ const unescape = (part) => part.replace(/~1/g, "/").replace(/~0/g, "~");
200
+ /** Every node of the document, in the order and at the paths `workflowGraph` gives them. */
201
+ function entriesOf(doc) {
202
+ const out = [];
203
+ const visit = (node, at, depth) => {
204
+ if (!isNode(node) || depth > MAX_DEPTH)
205
+ return;
206
+ out.push({ ...at, node });
207
+ if (depth + 1 > MAX_DEPTH)
208
+ return;
209
+ const { path, keys, scope } = at;
210
+ 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);
211
+ switch (node.node) {
212
+ case "chain":
213
+ if (Array.isArray(node.steps))
214
+ node.steps.forEach((step, index) => child(step, "steps", index, true, ["steps", String(index)]));
215
+ break;
216
+ case "parallel":
217
+ if (Array.isArray(node.branches))
218
+ node.branches.forEach((branch, index) => child(branch, "branches", index, true, ["branches", String(index)]));
219
+ break;
220
+ case "map":
221
+ case "loop":
222
+ child(node.body, "body", 0, false, ["body"]);
223
+ break;
224
+ case "route":
225
+ if (isObject(node.branches))
226
+ for (const [name, branch] of Object.entries(node.branches)) {
227
+ if (isObject(branch))
228
+ child(branch.body, `branches/${escape(name)}/body`, 0, false, ["branches", name, "body"]);
229
+ }
230
+ break;
231
+ case "workflow":
232
+ if (isObject(node.workflow))
233
+ child(node.workflow.root, "workflow/root", 0, false, ["workflow", "root"], path);
234
+ break;
235
+ }
236
+ };
237
+ visit(doc.root, { path: "/root", parentPath: "", slot: "root", index: 0, many: false, keys: ["root"], scope: "" }, 0);
238
+ return out;
239
+ }
240
+ /** 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
241
+ * node). Undefined when no node sits there. */
242
+ export function locate(doc, path) {
243
+ if (!isObject(doc))
244
+ return undefined;
245
+ const entry = entriesOf(doc).find((candidate) => candidate.path === path);
246
+ return entry && { parentPath: entry.parentPath, slot: entry.slot, index: entry.index };
247
+ }
248
+ // ---- copy on write ----------------------------------------------------------------------------------------------------
249
+ const DELETE = Symbol("delete");
250
+ /** One operation's copies: each copied object remembers the object it was copied from, so the result can say which
251
+ * node of the input each node of the output is. */
252
+ class Draft {
253
+ from = new WeakMap();
254
+ copy(value) {
255
+ const copied = (Array.isArray(value) ? value.slice() : { ...value });
256
+ this.from.set(copied, this.source(value));
257
+ return copied;
258
+ }
259
+ source(value) {
260
+ let at = value;
261
+ for (let next = this.from.get(at); next !== undefined; next = this.from.get(at))
262
+ at = next;
263
+ return at;
264
+ }
265
+ /** `doc` with the value at `keys` replaced by `fn` of it (a key deleted when `fn` returns DELETE), each object on the
266
+ * way copied and every other value shared. */
267
+ update(doc, keys, fn) {
268
+ const go = (value, i) => {
269
+ if (i === keys.length)
270
+ return fn(value);
271
+ if (!isObject(value) && !Array.isArray(value))
272
+ throw new Error(`edit: no container at ${keys.slice(0, i).join("/")}`);
273
+ const copied = this.copy(value);
274
+ const inner = go(value[keys[i]], i + 1);
275
+ if (inner === DELETE)
276
+ delete copied[keys[i]];
277
+ else
278
+ copied[keys[i]] = inner;
279
+ return copied;
280
+ };
281
+ return go(doc, 0);
282
+ }
283
+ /** `update`, where `fn` revises the node at `keys`: what it returns is that node, edited, not a new one. */
284
+ revise(doc, keys, fn) {
285
+ return this.update(doc, keys, (value) => {
286
+ const next = fn(value);
287
+ if (next !== value && isObject(value))
288
+ this.from.set(next, this.source(value));
289
+ return next;
290
+ });
291
+ }
292
+ }
293
+ /** A JSON value copied, so the document never shares an object with its caller. */
294
+ const clone = (value) => {
295
+ if (Array.isArray(value))
296
+ return value.map(clone);
297
+ if (isObject(value))
298
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, clone(inner)]));
299
+ return value;
300
+ };
301
+ /** How many reports and artifacts sit in the node, as the validator counts them: never inside a child workflow. */
302
+ const terminals = (node) => {
303
+ if (!isNode(node))
304
+ return 0;
305
+ switch (node.node) {
306
+ case "report":
307
+ case "artifact": return 1;
308
+ case "chain": return Array.isArray(node.steps) ? node.steps.reduce((n, step) => n + terminals(step), 0) : 0;
309
+ case "parallel": return Array.isArray(node.branches) ? node.branches.reduce((n, branch) => n + terminals(branch), 0) : 0;
310
+ case "map":
311
+ case "loop": return terminals(node.body);
312
+ case "route": return isObject(node.branches) ? Object.values(node.branches).reduce((n, branch) => n + (isObject(branch) ? terminals(branch.body) : 0), 0) : 0;
313
+ default: return 0;
314
+ }
315
+ };
316
+ /** The document's structural breaks, in document order and then the document's own. They mirror the validator's rules
317
+ * on where a node may sit and what it must hold: a known kind, only its kind's fields, the schema's required fields,
318
+ * steps, branches and bodies present and enough of them, a report or artifact only as the root chain's last step.
319
+ * The validator's other structural rules (a model node's `out` naming `report_markdown`, the depth bound) and every
320
+ * value's type are its own to check. */
321
+ function problemsOf(doc) {
322
+ const out = [];
323
+ const add = (at, rule, code, message) => { out.push({ at, rule, code, message }); };
324
+ const visit = (value, path, holder, slot, depth) => {
325
+ if (!isNode(value)) {
326
+ add(holder, `slot:${slot}`, "STRUCTURE_INVALID", `${path}: no node here; the ${slot === "root" ? "document" : "slot"} needs one`);
327
+ return;
328
+ }
329
+ if (depth > MAX_DEPTH)
330
+ return;
331
+ const kind = String(value.node);
332
+ if (!KINDS.has(kind)) {
333
+ add(path, "kind", "NODE_INVALID", `${path}: unknown node kind "${kind}"`);
334
+ return;
335
+ }
336
+ const allowed = new Set([...fieldsOf(value), ...(IGNORED_NODE_FIELDS[kind] ?? [])]);
337
+ for (const key of Object.keys(value))
338
+ if (!allowed.has(key))
339
+ add(path, `key:${key}`, "NODE_INVALID", `${path}: a ${isByValue(value) ? "route by value" : kind} node has no field "${key}"`);
340
+ const slots = SLOT_FIELDS[kind] ?? [];
341
+ for (const field of requiredFields(value))
342
+ if (!slots.includes(field) && value[field] === undefined)
343
+ add(path, `required:${field}`, "NODE_INVALID", `${path}: a ${kind} node needs "${field}"`);
344
+ 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`);
345
+ switch (kind) {
346
+ case "chain":
347
+ if (!Array.isArray(value.steps)) {
348
+ add(path, "slot:steps", "STRUCTURE_INVALID", `${path}: a chain needs steps`);
349
+ break;
350
+ }
351
+ if (!value.steps.length)
352
+ add(path, "chain-empty", "STRUCTURE_INVALID", `${path}: a chain needs at least one step`);
353
+ value.steps.forEach((step, index) => visit(step, `${path}/steps/${index}`, path, "steps", depth + 1));
354
+ break;
355
+ case "parallel":
356
+ if (!Array.isArray(value.branches)) {
357
+ add(path, "slot:branches", "STRUCTURE_INVALID", `${path}: a parallel needs branches`);
358
+ break;
359
+ }
360
+ if (value.branches.length < 2)
361
+ add(path, "parallel-few", "STRUCTURE_INVALID", `${path}: a parallel needs at least two branches`);
362
+ value.branches.forEach((branch, index) => visit(branch, `${path}/branches/${index}`, path, "branches", depth + 1));
363
+ if (terminals(value))
364
+ inside("terminal-inside", "a parallel branch");
365
+ break;
366
+ case "map":
367
+ case "loop":
368
+ visit(value.body, `${path}/body`, path, "body", depth + 1);
369
+ if (terminals(value.body))
370
+ inside("terminal-inside", `a ${kind} body`);
371
+ break;
372
+ case "route": {
373
+ if (!isObject(value.branches)) {
374
+ add(path, "slot:branches", "STRUCTURE_INVALID", `${path}: a route needs branches`);
375
+ break;
376
+ }
377
+ const names = Object.keys(value.branches);
378
+ if (names.length < 2)
379
+ add(path, "route-few", "STRUCTURE_INVALID", `${path}: a route needs at least two branches`);
380
+ if (!isByValue(value) && names.length > MAX_ROUTE_BRANCHES)
381
+ add(path, "route-many", "STRUCTURE_INVALID", `${path}: a route Jev chooses takes at most ${MAX_ROUTE_BRANCHES} branches`);
382
+ for (const name of names) {
383
+ const branch = value.branches[name];
384
+ if (!isObject(branch))
385
+ add(path, "slot:branch", "STRUCTURE_INVALID", `${path}: branch "${name}" needs a body`);
386
+ else
387
+ visit(branch.body, `${path}/branches/${escape(name)}/body`, path, "branch", depth + 1);
388
+ }
389
+ if (terminals(value))
390
+ inside("terminal-inside", "a route branch");
391
+ break;
392
+ }
393
+ case "workflow": {
394
+ const child = value.workflow;
395
+ const root = isObject(child) ? child.root : undefined;
396
+ if (!isNode(root) || (root.node === "chain" && (!Array.isArray(root.steps) || !root.steps.length)))
397
+ add(path, "child-root", "STRUCTURE_INVALID", `${path}: the child workflow needs a root node`);
398
+ if (isNode(root)) {
399
+ visit(root, `${path}/workflow/root`, path, "workflow/root", depth + 1);
400
+ if (terminals(root))
401
+ inside("terminal-inside", "a child workflow; the parent owns the terminal");
402
+ }
403
+ break;
404
+ }
405
+ }
406
+ };
407
+ visit(doc.root, "/root", "", "root", 0);
408
+ const total = terminals(doc.root);
409
+ if (total > 1)
410
+ add("", "terminals", "STRUCTURE_INVALID", "/root: a workflow has at most one terminal node (report or artifact)");
411
+ else if (total === 1) {
412
+ const root = doc.root;
413
+ const last = root.node === "chain" && Array.isArray(root.steps) ? root.steps[root.steps.length - 1] : root;
414
+ if (!isNode(last) || (last.node !== "report" && last.node !== "artifact"))
415
+ add("", "terminal-last", "STRUCTURE_INVALID", "/root: the terminal node (report or artifact) must be the last step of the root chain");
416
+ }
417
+ return out;
418
+ }
419
+ /** The result of an operation from `before` to `after`: which node of the input each node of the output is (by the
420
+ * object it was copied from), and the structure checked. A break `after` has that `before` did not throws. */
421
+ function finish(draft, before, after) {
422
+ const old = entriesOf(before), now = entriesOf(after);
423
+ const placements = new Map();
424
+ for (const entry of old)
425
+ placements.set(entry.node, [...(placements.get(entry.node) ?? []), entry.path]);
426
+ const prevOf = new Map(), nextOf = new Map();
427
+ for (const entry of now) {
428
+ const candidates = (placements.get(draft.source(entry.node)) ?? []).filter((path) => !nextOf.has(path));
429
+ const from = candidates.includes(entry.path) ? entry.path : candidates[0];
430
+ if (from !== undefined) {
431
+ prevOf.set(entry.path, from);
432
+ nextOf.set(from, entry.path);
433
+ }
434
+ }
435
+ const moved = new Map();
436
+ for (const entry of old) {
437
+ const to = nextOf.get(entry.path);
438
+ if (to !== undefined && to !== entry.path)
439
+ moved.set(entry.path, to);
440
+ }
441
+ const checks = new Map(workflowGraph(before).nodes.map((node) => [node.path, node.changeCheck]));
442
+ const result = {
443
+ doc: after,
444
+ moved,
445
+ added: now.filter((entry) => !prevOf.has(entry.path)).map((entry) => entry.path),
446
+ removed: old.filter((entry) => !nextOf.has(entry.path)).map((entry) => entry.path),
447
+ changed: workflowGraph(after).nodes.filter((node) => prevOf.has(node.path) && checks.get(prevOf.get(node.path)) !== node.changeCheck).map((node) => node.path),
448
+ };
449
+ // The breaks the input had, at the paths their nodes now have; a break with more instances after is new.
450
+ const had = new Map();
451
+ for (const problem of problemsOf(before)) {
452
+ if (problem.at !== "" && !nextOf.has(problem.at))
453
+ continue;
454
+ const key = `${problem.at === "" ? "" : nextOf.get(problem.at)}|${problem.rule}`;
455
+ had.set(key, (had.get(key) ?? 0) + 1);
456
+ }
457
+ for (const problem of problemsOf(after)) {
458
+ const key = `${problem.at}|${problem.rule}`;
459
+ const left = had.get(key) ?? 0;
460
+ if (left > 0) {
461
+ had.set(key, left - 1);
462
+ continue;
463
+ }
464
+ throw new EditError(problem.code, problem.at === "" ? "/root" : prevOf.get(problem.at) ?? problem.at, problem.message);
465
+ }
466
+ return result;
467
+ }
468
+ // ---- shared steps ------------------------------------------------------------------------------------------------------
469
+ const documentOf = (doc) => {
470
+ if (!isObject(doc))
471
+ throw new EditError("DOCUMENT_INVALID", "", "the document is not a workflow object");
472
+ return doc;
473
+ };
474
+ const find = (entries, path) => {
475
+ const entry = entries.find((candidate) => candidate.path === path);
476
+ if (!entry)
477
+ throw new EditError("PATH_NOT_FOUND", String(path), `no node at ${String(path)}`);
478
+ return entry;
479
+ };
480
+ const nodeOf = (value, path) => {
481
+ if (!isNode(value) || !KINDS.has(String(value.node)))
482
+ throw new EditError("NODE_INVALID", path, `the value is not a node of a known kind: ${JSON.stringify(isObject(value) ? value.node : value)}`);
483
+ for (const { node } of entriesOf({ root: value })) {
484
+ for (const name of [node.label, node.as, node.failedAs])
485
+ refusePrototypeName(name, path);
486
+ if (node.node === "route" && isObject(node.branches))
487
+ for (const name of Object.keys(node.branches))
488
+ refusePrototypeName(name, path);
489
+ }
490
+ return value;
491
+ };
492
+ function slotAt(doc, entries, parentPath, slot) {
493
+ const at = (keys, many) => {
494
+ const value = keys.reduce((inner, key) => isObject(inner) || Array.isArray(inner) ? inner[key] : undefined, doc);
495
+ return { path: `${parentPath}/${slot}`, parentPath, slot, many, keys, size: many ? (Array.isArray(value) ? value.length : 0) : value === undefined ? 0 : 1 };
496
+ };
497
+ if (parentPath === "") {
498
+ if (slot !== "root")
499
+ throw new EditError("SLOT_INVALID", "", `the document holds its root at "root", not "${String(slot)}"`);
500
+ return at(["root"], false);
501
+ }
502
+ const parent = find(entries, parentPath);
503
+ const kind = parent.node.node;
504
+ if (kind === "chain" && slot === "steps")
505
+ return at([...parent.keys, "steps"], true);
506
+ if (kind === "parallel" && slot === "branches")
507
+ return at([...parent.keys, "branches"], true);
508
+ if ((kind === "map" || kind === "loop") && slot === "body")
509
+ return at([...parent.keys, "body"], false);
510
+ if (kind === "workflow" && slot === "workflow/root" && isObject(parent.node.workflow))
511
+ return at([...parent.keys, "workflow", "root"], false);
512
+ const branch = kind === "route" && typeof slot === "string" ? /^branches\/([^/]*)\/body$/.exec(slot) : null;
513
+ if (branch && isObject(parent.node.branches) && Object.hasOwn(parent.node.branches, unescape(branch[1])) && isObject(parent.node.branches[unescape(branch[1])])) {
514
+ return at([...parent.keys, "branches", unescape(branch[1]), "body"], false);
515
+ }
516
+ throw new EditError("SLOT_INVALID", parentPath, `a ${String(kind)} node at ${parentPath} has no slot "${String(slot)}"`);
517
+ }
518
+ const checkIndex = (slot, index) => {
519
+ const most = slot.many ? slot.size : slot.size === 0 ? 0 : 1;
520
+ if (!Number.isInteger(index) || index < 0 || index > most)
521
+ throw new EditError("INDEX_OUT_OF_RANGE", slot.parentPath, `index ${index} is outside ${slot.path} (0 to ${most})`);
522
+ };
523
+ /** `doc` with `node` placed in `slot` at `index`: into the array, into the empty slot, or in a new chain with the slot's
524
+ * one node. */
525
+ function place(draft, doc, slot, index, node) {
526
+ checkIndex(slot, index);
527
+ if (slot.many)
528
+ return draft.update(doc, slot.keys, (value) => {
529
+ const list = Array.isArray(value) ? value : [];
530
+ return [...list.slice(0, index), node, ...list.slice(index)];
531
+ });
532
+ return draft.update(doc, slot.keys, (value) => value === undefined ? node : { node: "chain", steps: index === 0 ? [node, value] : [value, node] });
533
+ }
534
+ /** `doc` without the node `entry` names: spliced out of its array, or its slot emptied. */
535
+ const takeOut = (draft, doc, entry) => entry.many
536
+ ? draft.update(doc, entry.keys.slice(0, -1), (value) => value.filter((_, index) => index !== entry.index))
537
+ : draft.update(doc, entry.keys, () => DELETE);
538
+ /** Replace the node `entry` names by `nodes`: spliced into its array, or, in a slot that holds one, the one node. */
539
+ const putInstead = (draft, doc, entry, nodes, count = 1) => entry.many
540
+ ? draft.update(doc, entry.keys.slice(0, -1), (value) => { const list = value; return [...list.slice(0, entry.index), ...nodes, ...list.slice(entry.index + count)]; })
541
+ : draft.update(doc, entry.keys, () => nodes.length === 1 ? nodes[0] : { node: "chain", steps: nodes });
542
+ // ---- names, keys and references ---------------------------------------------------------------------------------------
543
+ const KEY_NAME = /^[A-Za-z0-9_]+$/;
544
+ const WHOLE_PLACEHOLDER = /^\{([a-zA-Z0-9_.$]+)(\?)?\}$/;
545
+ const INNER_PLACEHOLDER = /\{([a-zA-Z0-9_.$]+)\}/g;
546
+ /** Whether a node writes state under its label: an agent, decide, extract or code node with no `as`. A code node writes
547
+ * there when its code returns something other than a record; a record's own keys are its code's. */
548
+ const labelIsKey = (node) => (node.node === "agent" || node.node === "decide" || node.node === "extract" || node.node === "code") && node.as === undefined;
549
+ /** The state keys a node writes, as its fields name them (the keys of a record a code node returns are its code's). */
550
+ const keysWritten = (node) => [
551
+ ...(typeof node.as === "string" ? [node.as] : []),
552
+ ...(labelIsKey(node) && typeof node.label === "string" ? [node.label] : []),
553
+ ...(typeof node.failedAs === "string" ? [node.failedAs] : []),
554
+ ];
555
+ /** The literal sources of a code node or a call: never interpolated, never rewritten. */
556
+ const sourcesOf = (node) => (node.node === "code" || node.node === "call" ? ["code", "command"] : []).flatMap((field) => typeof node[field] === "string" ? [node[field]] : []);
557
+ /** Whether `text` names `word` as a whole word, or one of its engine-owned `<word>$...` keys. */
558
+ const mentions = (text, word) => new RegExp(`(^|[^A-Za-z0-9_$])${word.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}($|[^A-Za-z0-9_])`).test(text);
559
+ /** Refuse a name `Object.prototype` has (`constructor`, `toString`, `__proto__` and the rest), or `prototype`, as a
560
+ * label, an `as`, a `failedAs` or a route branch: a read of one that nothing wrote would find the prototype's value. */
561
+ const refusePrototypeName = (name, path) => {
562
+ if (typeof name === "string" && (name === "prototype" || Object.hasOwn(Object.prototype, name)))
563
+ throw new EditError("NAME_INVALID", path, `"${name}" is a name an object's prototype has`);
564
+ };
565
+ const renamePath = (path, rename, prefixed) => {
566
+ const prefix = prefixed && path.startsWith("state.") ? "state." : "";
567
+ const [head, ...tail] = path.slice(prefix.length).split(".");
568
+ const next = rename(head);
569
+ return next === head ? path : prefix + [next, ...tail].join(".");
570
+ };
571
+ /** A rewrite of `key` to `name` in a path's head, its engine-owned `<key>$...` keys included. */
572
+ const renameHead = (key, name) => (head) => head === key ? name : head.startsWith(`${key}$`) ? name + head.slice(key.length) : head;
573
+ /** A value with each `{placeholder}` in its strings rewritten, the same value when none changes. */
574
+ const renamePlaceholders = (value, rename) => {
575
+ if (typeof value === "string") {
576
+ const whole = WHOLE_PLACEHOLDER.exec(value);
577
+ if (whole) {
578
+ const path = renamePath(whole[1], rename, true);
579
+ return path === whole[1] ? value : `{${path}${whole[2] ?? ""}}`;
580
+ }
581
+ const next = value.replace(INNER_PLACEHOLDER, (all, path) => { const renamed = renamePath(path, rename, true); return renamed === path ? all : `{${renamed}}`; });
582
+ return next === value ? value : next;
583
+ }
584
+ if (Array.isArray(value)) {
585
+ const next = value.map((inner) => renamePlaceholders(inner, rename));
586
+ return next.some((inner, i) => inner !== value[i]) ? next : value;
587
+ }
588
+ if (isObject(value)) {
589
+ const next = Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, renamePlaceholders(inner, rename)]));
590
+ return Object.keys(value).some((key) => next[key] !== value[key]) ? next : value;
591
+ }
592
+ return value;
593
+ };
594
+ /** A predicate with the state paths it reads (`path`, `key`, quote_missing's `pages`, and those of a `not`'s `of`) and
595
+ * the placeholders of its `ask` (`state`, `images`) rewritten. A quote_missing `field` names a field of each quote's
596
+ * record, not a state path. */
597
+ const renamePredicate = (value, rename) => {
598
+ if (!isObject(value))
599
+ return value;
600
+ const next = { ...value };
601
+ if (typeof value.path === "string")
602
+ next.path = renamePath(value.path, rename, false);
603
+ if (typeof value.key === "string")
604
+ next.key = renamePath(value.key, rename, false);
605
+ if (Array.isArray(value.pages)) {
606
+ const pages = value.pages.map((page) => typeof page === "string" ? renamePath(page, rename, false) : page);
607
+ if (pages.some((page, i) => page !== value.pages[i]))
608
+ next.pages = pages;
609
+ }
610
+ if (value.state !== undefined)
611
+ next.state = renamePlaceholders(value.state, rename);
612
+ if (value.images !== undefined)
613
+ next.images = renamePlaceholders(value.images, rename);
614
+ if (value.of !== undefined)
615
+ next.of = renamePredicate(value.of, rename);
616
+ return Object.keys(value).some((key) => next[key] !== value[key]) ? next : value;
617
+ };
618
+ /** The keys a pick's or sift's describe gives its own candidate. */
619
+ const OWN_ITEM = new Set(["item", "item_index"]);
620
+ /** The node with each state reference of `mode` rewritten; the same node when none changes. */
621
+ function renameReads(node, mode, rename) {
622
+ const next = { ...node };
623
+ const field = (name, fn) => { if (node[name] !== undefined)
624
+ next[name] = fn(node[name]); };
625
+ const path = (value) => typeof value === "string" ? renamePath(value, rename, false) : value;
626
+ if (mode === "resultPath")
627
+ field("resultPath", path);
628
+ else if (mode === "until")
629
+ field("until", (value) => renamePredicate(value, rename));
630
+ else if (mode === "verify")
631
+ field("verify", (value) => isObject(value) ? renamePredicate({ ...value }, rename) : value);
632
+ else if (mode === "childOutput")
633
+ field("workflow", (child) => isObject(child) && isObject(child.output) && typeof child.output.path === "string" && path(child.output.path) !== child.output.path
634
+ ? { ...child, output: { ...child.output, path: path(child.output.path) } } : child);
635
+ else {
636
+ for (const name of ["state", "images", "args", "env", "produces", "summary"])
637
+ field(name, (value) => renamePlaceholders(value, rename));
638
+ // A pick's or sift's describe reads the state, and its own candidate as `item` and `item_index`, which are no state's.
639
+ field("describe", (value) => renamePlaceholders(value, (head) => OWN_ITEM.has(head) ? head : rename(head)));
640
+ if (node.node === "workflow" || node.node === "call")
641
+ field("input", (value) => renamePlaceholders(value, rename));
642
+ field("verify", (value) => isObject(value) ? renamePredicate({ ...value }, rename) : value);
643
+ for (const name of ["itemsPath", "valuePath", "resultPath"])
644
+ field(name, path);
645
+ field("requires", (value) => Array.isArray(value) && value.some((inner) => path(inner) !== inner) ? value.map(path) : value);
646
+ for (const name of ["until", "when"])
647
+ field(name, (value) => renamePredicate(value, rename));
648
+ }
649
+ return Object.keys(node).some((key) => next[key] !== node[key]) ? next : node;
650
+ }
651
+ /** 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. */
652
+ function headsRead(node) {
653
+ const heads = new Set();
654
+ renameReads(node, "own", (head) => { heads.add(head); return head; });
655
+ return heads;
656
+ }
657
+ /** The nodes that read what the node at `writer` writes, each with how much of it reads, and whether the document's
658
+ * `output.path` does. When the key is the writer's own `as` (`viaAs`), the writer reads it too: a route writes its
659
+ * choice before its branches run, and a verifier sees the submission under the node's `as`. */
660
+ function readersOf(entries, writer, viaAs = false) {
661
+ const byPath = new Map(entries.map((entry) => [entry.path, entry]));
662
+ const readers = [];
663
+ const subtree = (root) => {
664
+ for (const entry of entries)
665
+ if (entry.scope === root.scope && (entry.path === root.path || entry.path.startsWith(`${root.path}/`)))
666
+ readers.push({ entry, mode: "own" });
667
+ };
668
+ if (viaAs && writer.node.node === "route")
669
+ for (const body of entries)
670
+ if (body.parentPath === writer.path)
671
+ subtree(body);
672
+ if (viaAs && writer.node.verify !== undefined)
673
+ readers.push({ entry: writer, mode: "verify" });
674
+ for (let at = writer;;) {
675
+ const parent = byPath.get(at.parentPath);
676
+ if (!parent)
677
+ return { readers, output: true };
678
+ switch (parent.node.node) {
679
+ case "chain":
680
+ for (const step of entries)
681
+ if (step.parentPath === parent.path && step.many && step.index > at.index)
682
+ subtree(step);
683
+ break;
684
+ case "map":
685
+ readers.push({ entry: parent, mode: "resultPath" });
686
+ return { readers, output: false };
687
+ case "loop": {
688
+ // A later pass reads what an earlier one wrote: the whole body is in scope, the writer and the steps before it too.
689
+ const body = entries.find((entry) => entry.parentPath === parent.path && entry.slot === "body");
690
+ if (body)
691
+ subtree(body);
692
+ readers.push({ entry: parent, mode: "until" });
693
+ break;
694
+ }
695
+ case "workflow":
696
+ readers.push({ entry: parent, mode: "childOutput" });
697
+ return { readers, output: false };
698
+ }
699
+ at = parent;
700
+ }
701
+ }
702
+ /** The workflow object a scope reads: the document, or a workflow node's child. */
703
+ const workflowOf = (doc, entries, scope) => {
704
+ if (scope === "")
705
+ return doc;
706
+ const owner = entries.find((entry) => entry.path === scope)?.node.workflow;
707
+ return isObject(owner) ? owner : {};
708
+ };
709
+ /** The keys a scope starts with: its input schema's properties and, for a child, the keys its input maps. */
710
+ const inputKeys = (doc, entries, scope) => {
711
+ const workflow = workflowOf(doc, entries, scope);
712
+ const id = isObject(workflow.input) ? workflow.input.schemaId : undefined;
713
+ const schema = typeof id === "string" && isObject(workflow.schemas) && Object.hasOwn(workflow.schemas, id) ? workflow.schemas[id] : undefined;
714
+ const keys = new Set(isObject(schema) && isObject(schema.properties) ? Object.keys(schema.properties) : []);
715
+ const owner = entries.find((entry) => entry.path === scope)?.node;
716
+ if (owner && isObject(owner.input))
717
+ for (const key of Object.keys(owner.input))
718
+ keys.add(key);
719
+ return keys;
720
+ };
721
+ /** Every name a key of the scope could clash with: labels (all but `self`'s), keys written, input keys, the heads of
722
+ * references and of the output path, the words of code and shell sources (the key a `<key>$...` head or word names
723
+ * included), and the engine's own keys. */
724
+ const namesUsed = (doc, entries, scope, self) => {
725
+ const used = new Set([...RESERVED_KEYS, ...inputKeys(doc, entries, scope)]);
726
+ for (const entry of entries) {
727
+ if (typeof entry.node.label === "string" && entry !== self)
728
+ used.add(entry.node.label);
729
+ if (entry.scope !== scope)
730
+ continue;
731
+ for (const key of keysWritten(entry.node))
732
+ used.add(key);
733
+ for (const head of headsRead(entry.node))
734
+ used.add(head).add(head.split("$")[0]);
735
+ for (const source of sourcesOf(entry.node))
736
+ for (const word of source.match(/[A-Za-z0-9_$]+/g) ?? [])
737
+ used.add(word).add(word.split("$")[0]);
738
+ }
739
+ const output = workflowOf(doc, entries, scope).output;
740
+ if (isObject(output) && typeof output.path === "string")
741
+ used.add(output.path.split(".")[0]).add(output.path.split(".")[0].split("$")[0]);
742
+ return used;
743
+ };
744
+ /** A name no name in `used` has, added to it: `base` itself when free, else its stem with the smallest `_<n>` from 2. */
745
+ const fresh = (base, used) => {
746
+ const stem = base.replace(/_\d+$/, "") || "node";
747
+ if (!used.has(stem) && stem === base && !RESERVED_KEYS.has(stem)) {
748
+ used.add(stem);
749
+ return stem;
750
+ }
751
+ for (let n = 2;; n += 1) {
752
+ const name = `${stem}_${n}`;
753
+ if (!used.has(name)) {
754
+ used.add(name);
755
+ return name;
756
+ }
757
+ }
758
+ };
759
+ /** Rewrite, in `doc`, the reads of `key` by the readers of each writer: in each reader's fields, and the document's
760
+ * `output.path` when it reads. Returns the next document and the readers whose code mentions the key. */
761
+ function carry(draft, doc, entries, writers, rename, key, within, asKey) {
762
+ const seen = new Set();
763
+ const found = [];
764
+ let next = doc;
765
+ let output = false;
766
+ const inside = (path) => within === undefined || path === within || path.startsWith(`${within}/`);
767
+ for (const writer of writers) {
768
+ const scope = readersOf(entries, writer, asKey !== undefined && writer.node.as === asKey);
769
+ output ||= scope.output && within === undefined;
770
+ for (const { entry, mode } of scope.readers) {
771
+ if (!inside(entry.path) || seen.has(`${entry.path}|${mode}`))
772
+ continue;
773
+ seen.add(`${entry.path}|${mode}`);
774
+ if (mode === "own" && sourcesOf(entry.node).some((source) => mentions(source, key)) && !found.includes(entry.path))
775
+ found.push(entry.path);
776
+ next = draft.revise(next, entry.keys, (node) => renameReads(node, mode, rename));
777
+ }
778
+ }
779
+ if (output && isObject(doc.output) && typeof doc.output.path === "string") {
780
+ const path = renamePath(doc.output.path, rename, false);
781
+ if (path !== doc.output.path)
782
+ next = draft.update(next, ["output", "path"], () => path);
783
+ }
784
+ return { doc: next, mentions: found };
785
+ }
786
+ // ---- the operations ---------------------------------------------------------------------------------------------------
787
+ /** Put `node` (copied) into `slot` of the node at `parentPath`, at `index`. In a chain's steps or a parallel's branches
788
+ * 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,
789
+ * 0 puts the new one first and 1 puts it last, in a new chain of the two. */
790
+ export function insert(doc, parentPath, slot, index, node) {
791
+ const before = documentOf(doc);
792
+ const added = nodeOf(node, `${parentPath}/${slot}`);
793
+ const draft = new Draft();
794
+ return finish(draft, before, place(draft, before, slotAt(before, entriesOf(before), parentPath, slot), index, clone(added)));
795
+ }
796
+ /** Take out the node at `path`, and everything inside it. */
797
+ export function remove(doc, path) {
798
+ const before = documentOf(doc);
799
+ const draft = new Draft();
800
+ return finish(draft, before, takeOut(draft, before, find(entriesOf(before), path)));
801
+ }
802
+ /** Move the node at `fromPath` into `slot` of the node at `toParentPath`, at `index`, counted in the document as given:
803
+ * the drop point a canvas shows. A node never moves inside itself. */
804
+ export function move(doc, fromPath, toParentPath, slot, index) {
805
+ const before = documentOf(doc);
806
+ const entries = entriesOf(before);
807
+ const from = find(entries, fromPath);
808
+ if (toParentPath === fromPath || toParentPath.startsWith(`${fromPath}/`))
809
+ throw new EditError("MOVE_INTO_SELF", fromPath, `${fromPath} cannot move inside itself (${toParentPath})`);
810
+ const target = slotAt(before, entries, toParentPath, slot);
811
+ checkIndex(target, index);
812
+ // 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.
813
+ const holder = `${from.parentPath}/${from.slot}`;
814
+ const shift = (path) => {
815
+ if (!from.many || !path.startsWith(`${holder}/`))
816
+ return path;
817
+ const [at, ...rest] = path.slice(holder.length + 1).split("/");
818
+ return Number(at) > from.index ? [holder, String(Number(at) - 1), ...rest].join("/") : path;
819
+ };
820
+ const sameArray = from.many && target.many && target.path === holder;
821
+ const draft = new Draft();
822
+ const without = takeOut(draft, before, from);
823
+ const parent = shift(toParentPath);
824
+ return finish(draft, before, place(draft, without, slotAt(without, entriesOf(without), parent, slot), sameArray && from.index < index ? index - 1 : index, from.node));
825
+ }
826
+ /** 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
827
+ * 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
828
+ * references follow its keys; the copy's code and shell sources that mention an old key are listed in `mentions`. */
829
+ export function duplicate(doc, path) {
830
+ const before = documentOf(doc);
831
+ const entries = entriesOf(before);
832
+ const source = find(entries, path);
833
+ // The copy as a document of its own: its nodes named afresh, then its reads of its own keys carried.
834
+ const scratch = new Draft();
835
+ let copy = { root: clone(source.node) };
836
+ const labels = new Set(entries.flatMap((entry) => typeof entry.node.label === "string" ? [entry.node.label] : []));
837
+ const names = new Set([...labels, ...namesUsed(before, entries, source.scope)]);
838
+ const renamed = new Map();
839
+ const inCopy = entriesOf(copy);
840
+ // A copied child workflow's keys also stay off the names its own scope uses: the keys its input gives it, first.
841
+ const childNames = new Map();
842
+ for (const entry of inCopy)
843
+ if (entry.scope !== "" && !childNames.has(entry.scope))
844
+ childNames.set(entry.scope, namesUsed(copy, inCopy, entry.scope));
845
+ for (const entry of inCopy) {
846
+ const key = (old) => {
847
+ const scope = renamed.get(entry.scope) ?? new Map();
848
+ renamed.set(entry.scope, scope);
849
+ if (!scope.has(old)) {
850
+ const name = fresh(old, entry.scope === "" ? names : new Set([...names, ...childNames.get(entry.scope)]));
851
+ names.add(name);
852
+ scope.set(old, name);
853
+ }
854
+ return scope.get(old);
855
+ };
856
+ copy = scratch.update(copy, entry.keys, (value) => {
857
+ const node = { ...value };
858
+ if (typeof node.label === "string")
859
+ node.label = labelIsKey(node) ? key(node.label) : fresh(node.label, labels);
860
+ if (typeof node.label === "string") {
861
+ labels.add(node.label);
862
+ names.add(node.label);
863
+ }
864
+ if (typeof node.as === "string")
865
+ node.as = key(node.as);
866
+ if (typeof node.failedAs === "string")
867
+ node.failedAs = key(node.failedAs);
868
+ return node;
869
+ });
870
+ }
871
+ for (const [scope, keys] of renamed)
872
+ for (const [old, name] of keys) {
873
+ const at = entriesOf(copy);
874
+ const writers = at.filter((entry) => entry.scope === scope && keysWritten(entry.node).includes(name));
875
+ copy = carry(scratch, copy, at, writers, renameHead(old, name), old, "/root", name).doc;
876
+ }
877
+ // 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
878
+ // nodes are placed as they are, so they are found in the result by identity.
879
+ const named = new Set(entriesOf(copy).filter((entry) => {
880
+ const old = [...(renamed.get(entry.scope)?.keys() ?? [])];
881
+ return sourcesOf(entry.node).some((source) => old.some((key) => mentions(source, key)));
882
+ }).map((entry) => entry.node));
883
+ const draft = new Draft();
884
+ const target = slotAt(before, entries, source.parentPath, source.slot);
885
+ const result = finish(draft, before, place(draft, before, target, source.many ? source.index + 1 : 1, copy.root));
886
+ return { ...result, mentions: entriesOf(result.doc).filter((entry) => named.has(entry.node)).map((entry) => entry.path) };
887
+ }
888
+ /** Put the nodes at `paths` (one node, or consecutive steps or branches of one container, in any order) into a new
889
+ * 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
890
+ * them; a parallel takes each as a branch. The new container's fields are placeholders the validator flags. */
891
+ export function wrap(doc, paths, kind) {
892
+ const before = documentOf(doc);
893
+ if (!["map", "loop", "route", "parallel", "chain"].includes(kind))
894
+ throw new EditError("WRAP_INVALID", paths?.[0] ?? "", `"${String(kind)}" is not a container wrap makes`);
895
+ if (!Array.isArray(paths) || !paths.length)
896
+ throw new EditError("WRAP_INVALID", "", "wrap needs at least one node");
897
+ const entries = entriesOf(before);
898
+ const picked = paths.map((path) => find(entries, path)).sort((a, b) => a.index - b.index);
899
+ if (new Set(paths).size !== paths.length)
900
+ throw new EditError("WRAP_INVALID", paths[0], "a node is named twice");
901
+ const first = picked[0];
902
+ if (picked.length > 1 && !picked.every((entry, i) => entry.many && entry.parentPath === first.parentPath && entry.slot === first.slot && entry.index === first.index + i)) {
903
+ throw new EditError("WRAP_INVALID", first.path, "the nodes to wrap must be consecutive steps or branches of one container");
904
+ }
905
+ if (kind === "parallel" && picked.length < 2)
906
+ throw new EditError("WRAP_INVALID", first.path, "a parallel needs at least two nodes, one per branch");
907
+ const nodes = picked.map((entry) => entry.node);
908
+ const body = nodes.length === 1 ? nodes[0] : { node: "chain", steps: nodes };
909
+ const labels = new Set(entries.flatMap((entry) => typeof entry.node.label === "string" ? [entry.node.label] : []));
910
+ const names = new Set([...labels, ...namesUsed(before, entries, first.scope)]);
911
+ const label = kind === "chain" ? "" : fresh(kind, labels);
912
+ if (label)
913
+ names.add(label);
914
+ const container = kind === "chain" ? { node: "chain", steps: nodes }
915
+ : kind === "parallel" ? { node: "parallel", label, branches: nodes }
916
+ : kind === "map" ? { node: "map", label, itemsPath: "", as: fresh("results", names), body }
917
+ : kind === "loop" ? { node: "loop", label, body, until: { predicate: "" }, maxIters: 1 }
918
+ : { node: "route", label, valuePath: "", branches: { match: { body }, skip: { body: { node: "code", label: fresh("skip", names), code: "s => ({})" } } }, otherwise: "skip" };
919
+ const draft = new Draft();
920
+ return finish(draft, before, putInstead(draft, before, first, [container], picked.length));
921
+ }
922
+ /** Whether the subtree at `body` reads one of `keys` (a key, or a key with a "$" suffix): a reference in its fields, or
923
+ * a word of its code. With `maps`, a nested map's body is left out: its `item` is that map's own. */
924
+ const bodyReads = (entries, owner, body, keys, maps) => {
925
+ const under = (path, root) => path === root || path.startsWith(`${root}/`);
926
+ // A nested map, the body itself included, reads its own item in its body; its own fields still read the outer one.
927
+ const nested = maps ? entries.filter((entry) => entry.node.node === "map" && under(entry.path, body)).map((entry) => `${entry.path}/body`) : [];
928
+ const reads = (head) => keys.some((key) => head === key || head.startsWith(`${key}$`));
929
+ return entries.some((entry) => entry.scope === owner.scope && under(entry.path, body) && !nested.some((inner) => under(entry.path, inner))
930
+ && ([...headsRead(entry.node)].some(reads) || sourcesOf(entry.node).some((source) => keys.some((key) => mentions(source, key)))));
931
+ };
932
+ /** Put the children of the container at `path` where it was: a chain's steps or a parallel's branches, the body of a
933
+ * map or a loop, or the body of the route branch `branch` names. Into a chain they are spliced; a parallel's branches
934
+ * join an enclosing parallel; a slot that holds one node takes one child, or a chain of a parallel's branches. */
935
+ export function unwrap(doc, path, branch) {
936
+ const before = documentOf(doc);
937
+ const entries = entriesOf(before);
938
+ const entry = find(entries, path);
939
+ const node = entry.node;
940
+ const kind = String(node.node);
941
+ if (branch !== undefined && kind !== "route")
942
+ throw new EditError("UNWRAP_INVALID", path, `a ${kind} has no branch to keep`);
943
+ let children;
944
+ switch (kind) {
945
+ case "chain":
946
+ children = Array.isArray(node.steps) ? node.steps : [];
947
+ break;
948
+ case "parallel":
949
+ children = Array.isArray(node.branches) ? node.branches : [];
950
+ break;
951
+ case "map":
952
+ if (bodyReads(entries, entry, `${path}/body`, ["item", "item_index"], true))
953
+ throw new EditError("UNWRAP_INVALID", path, `the body of ${path} reads the map's item; it cannot run outside the map`);
954
+ children = [node.body];
955
+ break;
956
+ case "loop":
957
+ children = [node.body];
958
+ break;
959
+ case "route":
960
+ if (branch === undefined)
961
+ throw new EditError("UNWRAP_INVALID", path, `name the branch of ${path} to keep`);
962
+ if (!isObject(node.branches) || !Object.hasOwn(node.branches, branch) || !isObject(node.branches[branch]))
963
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${branch}"`);
964
+ if (typeof node.as === "string" && bodyReads(entries, entry, `${path}/branches/${escape(branch)}/body`, [node.as], false))
965
+ throw new EditError("UNWRAP_INVALID", path, `branch "${branch}" of ${path} reads the route's choice ("${node.as}"); it cannot run outside the route`);
966
+ children = [node.branches[branch].body];
967
+ break;
968
+ 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`);
969
+ }
970
+ if (!children.length || !children.every(isNode))
971
+ throw new EditError("UNWRAP_INVALID", path, `${path} holds no nodes to unwrap`);
972
+ const nodes = children;
973
+ const intoParallel = entry.many && entry.slot === "branches";
974
+ if (intoParallel && kind !== "parallel" && nodes.length > 1)
975
+ throw new EditError("UNWRAP_INVALID", path, `${path} is a parallel's branch; its ${nodes.length} steps cannot each become one`);
976
+ if (!entry.many && kind === "chain" && nodes.length > 1)
977
+ throw new EditError("UNWRAP_INVALID", path, `${path} is the one node of its slot; its steps have nowhere else to go`);
978
+ const draft = new Draft();
979
+ return finish(draft, before, putInstead(draft, before, entry, nodes));
980
+ }
981
+ /** Add a branch to the parallel or route at `path`: `node` (copied) last among a parallel's branches, or as the body of
982
+ * a new route branch `name`, after the others. */
983
+ export function addBranch(doc, path, node, name) {
984
+ const before = documentOf(doc);
985
+ const entry = find(entriesOf(before), path);
986
+ const added = clone(nodeOf(node, path));
987
+ const draft = new Draft();
988
+ if (entry.node.node === "parallel") {
989
+ if (name !== undefined)
990
+ throw new EditError("NAME_INVALID", path, "a parallel's branches have no names");
991
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => [...(Array.isArray(value) ? value : []), added]));
992
+ }
993
+ if (entry.node.node !== "route")
994
+ throw new EditError("SLOT_INVALID", path, `a ${String(entry.node.node)} node has no branches`);
995
+ if (typeof name !== "string" || !name.trim())
996
+ throw new EditError("NAME_INVALID", path, "a route branch needs a name");
997
+ refusePrototypeName(name, path);
998
+ if (isObject(entry.node.branches) && Object.hasOwn(entry.node.branches, name))
999
+ throw new EditError("BRANCH_TAKEN", path, `${path} already has a branch "${name}"`);
1000
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => Object.fromEntries([...Object.entries(isObject(value) ? value : {}), [name, { body: added }]])));
1001
+ }
1002
+ /** Take out a branch of the parallel or route at `path`: a parallel's by its index, a route's by its name. */
1003
+ export function removeBranch(doc, path, branch) {
1004
+ const before = documentOf(doc);
1005
+ const entry = find(entriesOf(before), path);
1006
+ const node = entry.node;
1007
+ const draft = new Draft();
1008
+ if (node.node === "parallel") {
1009
+ if (!Array.isArray(node.branches) || !Number.isInteger(branch) || branch < 0 || branch >= node.branches.length)
1010
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch ${String(branch)}`);
1011
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => value.filter((_, index) => index !== branch)));
1012
+ }
1013
+ if (node.node !== "route")
1014
+ throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no branches`);
1015
+ if (typeof branch !== "string" || !isObject(node.branches) || !Object.hasOwn(node.branches, branch))
1016
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(branch)}"`);
1017
+ if (node.otherwise === branch || (isObject(node.unsure) && node.unsure.branch === branch))
1018
+ throw new EditError("BRANCH_IN_USE", path, `${node.otherwise === branch ? "otherwise" : "unsure"} names branch "${branch}" of ${path}`);
1019
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => Object.fromEntries(Object.entries(value).filter(([key]) => key !== branch))));
1020
+ }
1021
+ /** Rename branch `from` of the route at `path` to `to`, in its place among the others; `otherwise` and `unsure` follow. */
1022
+ export function renameBranch(doc, path, from, to) {
1023
+ const before = documentOf(doc);
1024
+ const entry = find(entriesOf(before), path);
1025
+ const node = entry.node;
1026
+ if (node.node !== "route")
1027
+ throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no named branches`);
1028
+ if (!isObject(node.branches) || typeof from !== "string" || !Object.hasOwn(node.branches, from))
1029
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(from)}"`);
1030
+ if (typeof to !== "string" || !to.trim())
1031
+ throw new EditError("NAME_INVALID", path, "a route branch needs a name");
1032
+ const draft = new Draft();
1033
+ if (to === from)
1034
+ return finish(draft, before, before);
1035
+ refusePrototypeName(to, path);
1036
+ if (Object.hasOwn(node.branches, to))
1037
+ throw new EditError("BRANCH_TAKEN", path, `${path} already has a branch "${to}"`);
1038
+ return finish(draft, before, draft.revise(before, entry.keys, (value) => {
1039
+ const route = { ...value };
1040
+ route.branches = Object.fromEntries(Object.entries(route.branches).map(([key, inner]) => [key === from ? to : key, inner]));
1041
+ if (route.otherwise === from)
1042
+ route.otherwise = to;
1043
+ if (isObject(route.unsure) && route.unsure.branch === from)
1044
+ route.unsure = { ...route.unsure, branch: to };
1045
+ return route;
1046
+ }));
1047
+ }
1048
+ /** Write `value` (copied) at the field of the node at `path`, in its place; `undefined` removes an optional field. */
1049
+ export function setField(doc, path, field, value) {
1050
+ const before = documentOf(doc);
1051
+ const entry = find(entriesOf(before), path);
1052
+ const kind = String(entry.node.node);
1053
+ if (field === "node")
1054
+ throw new EditError("FIELD_INVALID", path, "a node's kind is fixed; insert a node of the other kind instead");
1055
+ if ((SLOT_FIELDS[kind] ?? []).includes(field))
1056
+ throw new EditError("FIELD_INVALID", path, `"${field}" holds the ${kind}'s children; insert, remove, move and the branch operations write it`);
1057
+ if (!editableFields(entry.node).includes(field))
1058
+ throw new EditError("FIELD_INVALID", path, `a ${isByValue(entry.node) ? "route by value" : kind} node has no field "${field}"`);
1059
+ if (value === undefined && requiredFields(entry.node).includes(field))
1060
+ throw new EditError("FIELD_INVALID", path, `a ${kind} node needs "${field}"; it cannot be removed`);
1061
+ // Writing the value the field already holds is no change, whatever the name.
1062
+ if ((field === "label" || field === "as" || field === "failedAs") && value !== entry.node[field])
1063
+ refusePrototypeName(value, path);
1064
+ const draft = new Draft();
1065
+ return finish(draft, before, draft.update(before, [...entry.keys, field], () => value === undefined ? DELETE : clone(value)));
1066
+ }
1067
+ /** Refuse a key another node of the scope or the scope's input also writes: a rename cannot tell whose readers are whose. */
1068
+ const checkUnshared = (doc, entries, entry, key) => {
1069
+ const others = entries.filter((other) => other !== entry && other.scope === entry.scope && keysWritten(other.node).includes(key));
1070
+ if (others.length || inputKeys(doc, entries, entry.scope).has(key)) {
1071
+ 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));
1072
+ }
1073
+ };
1074
+ /** Rename the label of the node at `path`. When the label is the key the node writes (an agent, decide, extract or code
1075
+ * node with no `as`), every reference in scope follows it, and the code and shell sources in scope that mention the old
1076
+ * key are listed in `mentions`, unchanged: a code node's own code included, when it names the key. */
1077
+ export function rename(doc, path, name) {
1078
+ const before = documentOf(doc);
1079
+ const entries = entriesOf(before);
1080
+ const entry = find(entries, path);
1081
+ const node = entry.node;
1082
+ if (!editableFields(node).includes("label"))
1083
+ throw new EditError("FIELD_INVALID", path, `a ${String(node.node)} node has no label`);
1084
+ const draft = new Draft();
1085
+ if (name === node.label)
1086
+ return { ...finish(draft, before, before), mentions: [] };
1087
+ if (typeof name !== "string" || !name.trim() || name.includes("$"))
1088
+ throw new EditError("NAME_INVALID", path, `a label is a non-empty name with no "$": ${JSON.stringify(name)}`);
1089
+ refusePrototypeName(name, path);
1090
+ const keyed = labelIsKey(node) && typeof node.label === "string";
1091
+ if (keyed && !KEY_NAME.test(name))
1092
+ 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)}`);
1093
+ const holder = entries.find((other) => other !== entry && other.node.label === name);
1094
+ if (holder)
1095
+ throw new EditError("NAME_TAKEN", path, `${holder.path} is labelled "${name}"`, [holder.path]);
1096
+ const relabel = () => draft.update(before, [...entry.keys, "label"], () => name);
1097
+ if (!keyed)
1098
+ return { ...finish(draft, before, relabel()), mentions: [] };
1099
+ const key = node.label;
1100
+ if (namesUsed(before, entries, entry.scope).has(name))
1101
+ throw new EditError("NAME_TAKEN", path, `"${name}" is already a key, a reference, an input or a word of code in this workflow`);
1102
+ checkUnshared(before, entries, entry, key);
1103
+ const carried = carry(draft, relabel(), entries, [entry], renameHead(key, name), key);
1104
+ // A code node whose record names its own label still writes that key, under the old name: the caller must see it. In
1105
+ // a loop, the node reads its own key and carry has listed it already.
1106
+ const own = sourcesOf(node).some((source) => mentions(source, key)) && !carried.mentions.includes(path) ? [path] : [];
1107
+ return { ...finish(draft, before, carried.doc), mentions: [...own, ...carried.mentions] };
1108
+ }
1109
+ /** Rename the state key the node at `path` writes: its `as` when it has one, else its label when the label is the key
1110
+ * (an agent, decide, extract or code node with no `as`, where this is `rename`); or, with `field: "failedAs"`, the key a
1111
+ * map writes its failed items under. Every reference in scope follows it, `<key>$answers` and `<key>$verify` included,
1112
+ * and the code and shell sources in scope that mention the old key are listed in `mentions`, unchanged. */
1113
+ export function renameKey(doc, path, name, options = {}) {
1114
+ const before = documentOf(doc);
1115
+ const entries = entriesOf(before);
1116
+ const entry = find(entries, path);
1117
+ const node = entry.node;
1118
+ const field = options?.field ?? "as";
1119
+ if (field !== "as" && field !== "failedAs")
1120
+ throw new EditError("FIELD_INVALID", path, `renameKey renames "as" or "failedAs", not ${JSON.stringify(field)}`);
1121
+ if (typeof node[field] !== "string") {
1122
+ if (field === "as" && labelIsKey(node) && typeof node.label === "string")
1123
+ return rename(before, path, name);
1124
+ throw new EditError("FIELD_INVALID", path, field === "as"
1125
+ ? `a ${String(node.node)} node ${node.as === undefined ? "with no as " : ""}writes no key of its own to rename`
1126
+ : `a ${String(node.node)} node with no failedAs has no failedAs to rename`);
1127
+ }
1128
+ const draft = new Draft();
1129
+ const key = node[field];
1130
+ if (name === key)
1131
+ return { ...finish(draft, before, before), mentions: [] };
1132
+ if (typeof name !== "string" || !KEY_NAME.test(name))
1133
+ throw new EditError("NAME_INVALID", path, `a state key takes letters, digits and "_" only: ${JSON.stringify(name)}`);
1134
+ refusePrototypeName(name, path);
1135
+ // The node's own label is a name, not a key: its key may take it.
1136
+ const holder = entries.find((other) => other !== entry && other.node.label === name);
1137
+ if (holder)
1138
+ throw new EditError("NAME_TAKEN", path, `${holder.path} is labelled "${name}"`, [holder.path]);
1139
+ if (namesUsed(before, entries, entry.scope, entry).has(name))
1140
+ throw new EditError("NAME_TAKEN", path, `"${name}" is already a key, a reference, an input or a word of code in this workflow`);
1141
+ checkUnshared(before, entries, entry, key);
1142
+ const carried = carry(draft, draft.update(before, [...entry.keys, field], () => name), entries, [entry], renameHead(key, name), key, undefined, field === "as" ? key : undefined);
1143
+ return { ...finish(draft, before, carried.doc), mentions: carried.mentions };
1144
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-dsl",
3
- "version": "0.1.0-beta.186",
3
+ "version": "0.1.0-beta.188",
4
4
  "description": "Composable, typed workflows for agents",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -16,6 +16,10 @@
16
16
  "types": "./dist/graph.d.ts",
17
17
  "import": "./dist/graph.js"
18
18
  },
19
+ "./edit": {
20
+ "types": "./dist/edit.d.ts",
21
+ "import": "./dist/edit.js"
22
+ },
19
23
  "./demo": {
20
24
  "types": "./dist/demo.d.ts",
21
25
  "import": "./dist/demo.js"