@parcha/agentrun-dsl 0.1.0-beta.192 → 0.1.0-beta.194

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
@@ -188,6 +188,8 @@ The schema helpers resolve the owning workflow's schema catalog; `stageSchemaFor
188
188
 
189
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
190
 
191
+ The same module answers what a property panel asks. `setBranchCriteria(doc, path, branch, criteria)` writes or removes (`undefined`) a judged route branch's criteria. `setSchema(doc, id, schema, scope?)` writes or removes a schema of the document, or of the child workflow of the workflow node at `scope`, and refuses to remove one that `schemaUsers(doc, id, scope?)` says is named: it lists the JSON Pointers of the workflow's `input.schemaId` and `output.schemaId`, each node's `out` and `verify.out`, and each `$ref` to `#/definitions/<id>` in another schema. `namesInScope(doc, path, field?)` lists the names the node at `path` may read, each `{ name, from }` with `from` the path of the node that writes it, `"input"` or `"engine"` (a map body's `item` and `item_index`), by the scope rules `rename` carries a key along; `field` asks for one field where it sees more (a map's `resultPath`, a loop's `until`, `verify`, a pick's or sift's `describe`, a workflow node's `workflow`). It cannot list a key only a code node's returned record writes, nor the keys of an input whose schema lists no properties. `readsOf(doc, path)` lists each `{placeholder}` and state path the node reads as `{ pointer, name }`, the references `rename` carries, and `openPlaceholderAt(text, offset)` finds the `{` open at a cursor and the name typed after it. `freshName(doc, base)` gives `base` or `<base>_<n>`, free in every scope, and `placeholderNode(doc, kind)` the smallest node of a kind that holds no nodes, each required field holding its `FIELD_PLACEHOLDERS` value, which the validator flags until it is filled in.
192
+
191
193
  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.
192
194
 
193
195
  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 CHANGED
@@ -29,7 +29,7 @@ export type DuplicateResult = EditResult & {
29
29
  mentions: string[];
30
30
  };
31
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"];
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", "SCHEMA_NOT_FOUND", "SCHEMA_IN_USE", "SCHEMA_INVALID"];
33
33
  export type EditErrorCode = typeof EDIT_ERROR_CODES[number];
34
34
  /** The one error the operations throw. `path` is the node it is about, in the input document where that node existed
35
35
  * there; `related` names other nodes the error is about: the one holding a taken name, the other writers of a key. */
@@ -39,6 +39,10 @@ export declare class EditError extends Error {
39
39
  readonly related: readonly string[];
40
40
  constructor(code: EditErrorCode, path: string, message: string, related?: readonly string[]);
41
41
  }
42
+ /** The placeholder a required field takes in a new node: a value insert accepts and the validator flags until someone
43
+ * 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
44
+ * `maxIters`, the smallest bound. placeholderNode and wrap fill fields from it. */
45
+ export declare const FIELD_PLACEHOLDERS: Readonly<Record<string, unknown>>;
42
46
  /** The fields setField writes on this node: its kind's (and its route form's) own fields, without `node` and the child
43
47
  * slots. A property panel lists these. */
44
48
  export declare function editableFields(node: WorkflowNodeJson): string[];
@@ -96,3 +100,50 @@ export type RenameKeyOptions = {
96
100
  * map writes its failed items under. Every reference in scope follows it, `<key>$answers` and `<key>$verify` included,
97
101
  * and the code and shell sources in scope that mention the old key are listed in `mentions`, unchanged. */
98
102
  export declare function renameKey(doc: WorkflowDocument, path: string, name: string, options?: RenameKeyOptions): RenameResult;
103
+ /** Write `criteria`, the text Jev reads to choose it, on branch `branch` of the judged route at `path`, in its place;
104
+ * `undefined` removes it. A route by value matches its branches by name and takes no criteria. */
105
+ export declare function setBranchCriteria(doc: WorkflowDocument, path: string, branch: string, criteria: string | undefined): EditResult;
106
+ /** The JSON Pointers of the values that name schema `id` of a scope ("" for the document, or a workflow node's path
107
+ * for its child's schemas): the workflow's `input.schemaId` and `output.schemaId`, a `$ref` from another of its
108
+ * schemas, and the `out` and `verify.out` of its nodes (a workflow node's `out` names its parent's schema). */
109
+ export declare function schemaUsers(doc: WorkflowDocument, id: string, scope?: string): string[];
110
+ /** Write `schema` (copied) as schema `id` of a scope ("" for the document, or a workflow node's path for its child), in
111
+ * its place when it exists; `undefined` removes it, unless something still names it (`schemaUsers`). */
112
+ export declare function setSchema(doc: WorkflowDocument, id: string, schema: Record<string, unknown> | undefined, scope?: string): EditResult;
113
+ /** A name a node may read, and what gives it: the path of the node that writes it, "input" (the workflow's input, or a
114
+ * child's), or "engine" (a map body's `item` and `item_index`). */
115
+ export type NameInScope = {
116
+ name: string;
117
+ from: string;
118
+ };
119
+ /** The names the node at `path` may read, each with what gives it, by the scope rules rename carries a key along: its
120
+ * workflow's input keys, a map body's `item` and `item_index`, and the keys (with their `<key>$answers` and
121
+ * `<key>$verify`) of each node whose write it runs after and sees. With `field`, the names that one field of the node
122
+ * 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
123
+ * keys, `verify` the node's own `as` and `submission`, a pick's or sift's `describe` its own `item` and `item_index`,
124
+ * and a workflow node's `workflow` (its child's `output.path`) the child's state. */
125
+ export declare function namesInScope(doc: WorkflowDocument, path: string, field?: string): NameInScope[];
126
+ /** A reference a node makes: the JSON Pointer of the value it sits in, the name it reads (the head of its path), and
127
+ * `optional` for a whole-string placeholder marked `?` (`"{plan?}"`), which the engine fills with null while unset. */
128
+ export type NodeRead = {
129
+ pointer: string;
130
+ name: string;
131
+ optional?: true;
132
+ };
133
+ /** Each `{placeholder}` and state path the node at `path` reads, in its fields' order: the references rename carries,
134
+ * found by the same walk. A workflow node's include its child's `output.path`, which reads the child's state. */
135
+ export declare function readsOf(doc: WorkflowDocument, path: string): NodeRead[];
136
+ /** The `{placeholder` open at `offset` in `text`: the index of its `{` and the name typed after it up to the cursor, by
137
+ * the placeholder grammar (letters, digits, "_", "." and "$"; a reference may start with `state.`). Undefined when no
138
+ * placeholder's name holds the cursor. The placeholder may already be closed after it. */
139
+ export declare function openPlaceholderAt(text: string, offset: number): {
140
+ start: number;
141
+ prefix: string;
142
+ } | undefined;
143
+ /** `base`, or its stem (`base` without a `_<n>` ending) with the smallest `_<n>` from 2, so that no label, key,
144
+ * reference, input key or word of code of any scope of the document holds it, nor an engine key or a name
145
+ * `Object.prototype` has. `base` is a state key name. */
146
+ export declare function freshName(doc: WorkflowDocument, base: string): string;
147
+ /** The smallest node of `kind` for `doc`: its required fields in the schema's order, a fresh name as its label (and its
148
+ * `as`, where it needs one), and each other field's placeholder. A container is made by wrapping nodes that exist. */
149
+ export declare function placeholderNode(doc: WorkflowDocument, kind: string): WorkflowNodeJson;
package/dist/edit.js CHANGED
@@ -81,6 +81,19 @@
81
81
  // `toString`, `__proto__` and the rest) or `prototype`: rename, renameKey, renameBranch and setField refuse one, and
82
82
  // insert and addBranch refuse a node with one anywhere inside it. A read of such a key that nothing wrote would find
83
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
+ // - namesInScope runs rename's scope rules backwards: a node may read its workflow's input keys, a map body's `item`
91
+ // and `item_index`, and every key whose readers include it, with that key's `<key>$answers` and `<key>$verify`. A
92
+ // map's `resultPath`, a loop's `until`, a `verify` (the node's own `as` and `submission`), a pick's or sift's
93
+ // `describe` (its own `item`) and a child's `output.path` see more than the node's other fields, so namesInScope
94
+ // takes the field. It cannot list a key only a code node's returned record writes, nor the keys of an
95
+ // input whose schema lists no properties; the validator does not flag a read of either.
96
+ // - placeholderNode makes the smallest node of a kind that holds no nodes: wrap makes containers of nodes that exist.
84
97
  import { workflowGraph } from "./graph.js";
85
98
  import { DECISION_NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, NODE_FIELDS, WORKFLOW_NODE_KINDS } from "./vocabulary.js";
86
99
  /** Every code an EditError carries. */
@@ -117,6 +130,12 @@ export const EDIT_ERROR_CODES = [
117
130
  "UNWRAP_INVALID",
118
131
  /** The result would break a rule of the document's structure. */
119
132
  "STRUCTURE_INVALID",
133
+ /** The workflow has no schema with that id. */
134
+ "SCHEMA_NOT_FOUND",
135
+ /** A field or another schema still names the schema being removed. */
136
+ "SCHEMA_IN_USE",
137
+ /** The schema is not a JSON object. */
138
+ "SCHEMA_INVALID",
120
139
  ];
121
140
  /** The one error the operations throw. `path` is the node it is about, in the input document where that node existed
122
141
  * there; `related` names other nodes the error is about: the one holding a taken name, the other writers of a key. */
@@ -166,6 +185,16 @@ const MAX_ROUTE_BRANCHES = 240;
166
185
  const MAX_DEPTH = 128;
167
186
  /** State keys the engine gives a node, which no rename or fresh name may take. */
168
187
  const RESERVED_KEYS = new Set(["item", "item_index", "report_markdown", "artifact", "state", "submission", "$host"]);
188
+ /** The placeholder a required field takes in a new node: a value insert accepts and the validator flags until someone
189
+ * 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
190
+ * `maxIters`, the smallest bound. placeholderNode and wrap fill fields from it. */
191
+ export const FIELD_PLACEHOLDERS = Object.freeze({
192
+ instructions: "", code: "", out: "", type: "", itemsPath: "", describe: "", kind: "", stage: "", summary: "", via: "",
193
+ valuePath: "", state: Object.freeze({}), when: Object.freeze({ predicate: "" }), until: Object.freeze({ predicate: "" }),
194
+ deadline_s: 0, maxIters: 1,
195
+ });
196
+ /** A copy of a field's placeholder, to write into a document. */
197
+ const placeholder = (field) => structuredClone(FIELD_PLACEHOLDERS[field]);
169
198
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
170
199
  const isNode = (value) => isObject(value) && typeof value.node === "string";
171
200
  const isByValue = (node) => node.node === "route" && node.valuePath !== undefined;
@@ -562,31 +591,32 @@ const refusePrototypeName = (name, path) => {
562
591
  if (typeof name === "string" && (name === "prototype" || Object.hasOwn(Object.prototype, name)))
563
592
  throw new EditError("NAME_INVALID", path, `"${name}" is a name an object's prototype has`);
564
593
  };
565
- const renamePath = (path, rename, prefixed) => {
594
+ const renamePath = (path, rename, prefixed, at, optional = false) => {
566
595
  const prefix = prefixed && path.startsWith("state.") ? "state." : "";
567
596
  const [head, ...tail] = path.slice(prefix.length).split(".");
568
- const next = rename(head);
597
+ const next = rename(head, at, optional);
569
598
  return next === head ? path : prefix + [next, ...tail].join(".");
570
599
  };
571
600
  /** A rewrite of `key` to `name` in a path's head, its engine-owned `<key>$...` keys included. */
572
601
  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) => {
602
+ /** A value with each `{placeholder}` in its strings rewritten, the same value when none changes. `at` is the value's
603
+ * pointer from the node. */
604
+ const renamePlaceholders = (value, rename, at) => {
575
605
  if (typeof value === "string") {
576
606
  const whole = WHOLE_PLACEHOLDER.exec(value);
577
607
  if (whole) {
578
- const path = renamePath(whole[1], rename, true);
608
+ const path = renamePath(whole[1], rename, true, at, whole[2] !== undefined);
579
609
  return path === whole[1] ? value : `{${path}${whole[2] ?? ""}}`;
580
610
  }
581
- const next = value.replace(INNER_PLACEHOLDER, (all, path) => { const renamed = renamePath(path, rename, true); return renamed === path ? all : `{${renamed}}`; });
611
+ const next = value.replace(INNER_PLACEHOLDER, (all, path) => { const renamed = renamePath(path, rename, true, at); return renamed === path ? all : `{${renamed}}`; });
582
612
  return next === value ? value : next;
583
613
  }
584
614
  if (Array.isArray(value)) {
585
- const next = value.map((inner) => renamePlaceholders(inner, rename));
615
+ const next = value.map((inner, i) => renamePlaceholders(inner, rename, `${at}/${i}`));
586
616
  return next.some((inner, i) => inner !== value[i]) ? next : value;
587
617
  }
588
618
  if (isObject(value)) {
589
- const next = Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, renamePlaceholders(inner, rename)]));
619
+ const next = Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, renamePlaceholders(inner, rename, `${at}/${escape(key)}`)]));
590
620
  return Object.keys(value).some((key) => next[key] !== value[key]) ? next : value;
591
621
  }
592
622
  return value;
@@ -594,57 +624,68 @@ const renamePlaceholders = (value, rename) => {
594
624
  /** A predicate with the state paths it reads (`path`, `key`, quote_missing's `pages`, and those of a `not`'s `of`) and
595
625
  * the placeholders of its `ask` (`state`, `images`) rewritten. A quote_missing `field` names a field of each quote's
596
626
  * record, not a state path. */
597
- const renamePredicate = (value, rename) => {
627
+ const renamePredicate = (value, rename, at) => {
598
628
  if (!isObject(value))
599
629
  return value;
600
630
  const next = { ...value };
601
631
  if (typeof value.path === "string")
602
- next.path = renamePath(value.path, rename, false);
632
+ next.path = renamePath(value.path, rename, false, `${at}/path`);
603
633
  if (typeof value.key === "string")
604
- next.key = renamePath(value.key, rename, false);
634
+ next.key = renamePath(value.key, rename, false, `${at}/key`);
605
635
  if (Array.isArray(value.pages)) {
606
- const pages = value.pages.map((page) => typeof page === "string" ? renamePath(page, rename, false) : page);
636
+ const pages = value.pages.map((page, i) => typeof page === "string" ? renamePath(page, rename, false, `${at}/pages/${i}`) : page);
607
637
  if (pages.some((page, i) => page !== value.pages[i]))
608
638
  next.pages = pages;
609
639
  }
610
640
  if (value.state !== undefined)
611
- next.state = renamePlaceholders(value.state, rename);
641
+ next.state = renamePlaceholders(value.state, rename, `${at}/state`);
612
642
  if (value.images !== undefined)
613
- next.images = renamePlaceholders(value.images, rename);
643
+ next.images = renamePlaceholders(value.images, rename, `${at}/images`);
614
644
  if (value.of !== undefined)
615
- next.of = renamePredicate(value.of, rename);
645
+ next.of = renamePredicate(value.of, rename, `${at}/of`);
616
646
  return Object.keys(value).some((key) => next[key] !== value[key]) ? next : value;
617
647
  };
618
648
  /** The keys a pick's or sift's describe gives its own candidate. */
619
649
  const OWN_ITEM = new Set(["item", "item_index"]);
620
- /** The node with each state reference of `mode` rewritten; the same node when none changes. */
650
+ /** The node with each state reference of `mode` rewritten; the same node when none changes. Each reference is visited
651
+ * once, with the pointer, from the node, of the value it sits in. */
621
652
  function renameReads(node, mode, rename) {
622
653
  const next = { ...node };
623
654
  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;
655
+ next[name] = fn(node[name], `/${name}`); };
656
+ const path = (value, at) => typeof value === "string" ? renamePath(value, rename, false, at) : value;
657
+ const paths = (value, at) => {
658
+ if (!Array.isArray(value))
659
+ return value;
660
+ const renamed = value.map((inner, i) => path(inner, `${at}/${i}`));
661
+ return renamed.some((inner, i) => inner !== value[i]) ? renamed : value;
662
+ };
626
663
  if (mode === "resultPath")
627
664
  field("resultPath", path);
628
665
  else if (mode === "until")
629
- field("until", (value) => renamePredicate(value, rename));
666
+ field("until", (value, at) => renamePredicate(value, rename, at));
630
667
  else if (mode === "verify")
631
- field("verify", (value) => isObject(value) ? renamePredicate({ ...value }, rename) : value);
668
+ field("verify", (value, at) => isObject(value) ? renamePredicate({ ...value }, rename, at) : value);
632
669
  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);
670
+ field("workflow", (child, at) => {
671
+ if (!isObject(child) || !isObject(child.output) || typeof child.output.path !== "string")
672
+ return child;
673
+ const renamed = path(child.output.path, `${at}/output/path`);
674
+ return renamed === child.output.path ? child : { ...child, output: { ...child.output, path: renamed } };
675
+ });
635
676
  else {
636
677
  for (const name of ["state", "images", "args", "env", "produces", "summary"])
637
- field(name, (value) => renamePlaceholders(value, rename));
678
+ field(name, (value, at) => renamePlaceholders(value, rename, at));
638
679
  // 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)));
680
+ field("describe", (value, at) => renamePlaceholders(value, (head, inner) => OWN_ITEM.has(head) ? head : rename(head, inner), at));
640
681
  if (node.node === "workflow" || node.node === "call")
641
- field("input", (value) => renamePlaceholders(value, rename));
642
- field("verify", (value) => isObject(value) ? renamePredicate({ ...value }, rename) : value);
682
+ field("input", (value, at) => renamePlaceholders(value, rename, at));
683
+ field("verify", (value, at) => isObject(value) ? renamePredicate({ ...value }, rename, at) : value);
643
684
  for (const name of ["itemsPath", "valuePath", "resultPath"])
644
685
  field(name, path);
645
- field("requires", (value) => Array.isArray(value) && value.some((inner) => path(inner) !== inner) ? value.map(path) : value);
686
+ field("requires", paths);
646
687
  for (const name of ["until", "when"])
647
- field(name, (value) => renamePredicate(value, rename));
688
+ field(name, (value, at) => renamePredicate(value, rename, at));
648
689
  }
649
690
  return Object.keys(node).some((key) => next[key] !== node[key]) ? next : node;
650
691
  }
@@ -654,16 +695,31 @@ function headsRead(node) {
654
695
  renameReads(node, "own", (head) => { heads.add(head); return head; });
655
696
  return heads;
656
697
  }
698
+ /** Each entry's path and place in its list, built once per list: namesInScope asks readersOf about every writer. */
699
+ const indexes = new WeakMap();
700
+ const indexOf = (entries) => {
701
+ let index = indexes.get(entries);
702
+ if (!index) {
703
+ index = { byPath: new Map(entries.map((entry) => [entry.path, entry])), place: new Map(entries.map((entry, i) => [entry, i])) };
704
+ indexes.set(entries, index);
705
+ }
706
+ return index;
707
+ };
657
708
  /** The nodes that read what the node at `writer` writes, each with how much of it reads, and whether the document's
658
709
  * `output.path` does. When the key is the writer's own `as` (`viaAs`), the writer reads it too: a route writes its
659
710
  * choice before its branches run, and a verifier sees the submission under the node's `as`. */
660
711
  function readersOf(entries, writer, viaAs = false) {
661
- const byPath = new Map(entries.map((entry) => [entry.path, entry]));
712
+ const { byPath, place } = indexOf(entries);
662
713
  const readers = [];
714
+ // entriesOf lists a node's subtree right after it, so the subtree ends at the first entry outside it.
663
715
  const subtree = (root) => {
664
- for (const entry of entries)
665
- if (entry.scope === root.scope && (entry.path === root.path || entry.path.startsWith(`${root.path}/`)))
716
+ for (let i = place.get(root) ?? entries.length; i < entries.length; i += 1) {
717
+ const entry = entries[i];
718
+ if (entry.path !== root.path && !entry.path.startsWith(`${root.path}/`))
719
+ break;
720
+ if (entry.scope === root.scope)
666
721
  readers.push({ entry, mode: "own" });
722
+ }
667
723
  };
668
724
  if (viaAs && writer.node.node === "route")
669
725
  for (const body of entries)
@@ -777,7 +833,7 @@ function carry(draft, doc, entries, writers, rename, key, within, asKey) {
777
833
  }
778
834
  }
779
835
  if (output && isObject(doc.output) && typeof doc.output.path === "string") {
780
- const path = renamePath(doc.output.path, rename, false);
836
+ const path = renamePath(doc.output.path, rename, false, "/output/path");
781
837
  if (path !== doc.output.path)
782
838
  next = draft.update(next, ["output", "path"], () => path);
783
839
  }
@@ -913,9 +969,9 @@ export function wrap(doc, paths, kind) {
913
969
  names.add(label);
914
970
  const container = kind === "chain" ? { node: "chain", steps: nodes }
915
971
  : 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" };
972
+ : kind === "map" ? { node: "map", label, itemsPath: placeholder("itemsPath"), as: fresh("results", names), body }
973
+ : kind === "loop" ? { node: "loop", label, body, until: placeholder("until"), maxIters: placeholder("maxIters") }
974
+ : { node: "route", label, valuePath: placeholder("valuePath"), branches: { match: { body }, skip: { body: { node: "code", label: fresh("skip", names), code: "s => ({})" } } }, otherwise: "skip" };
919
975
  const draft = new Draft();
920
976
  return finish(draft, before, putInstead(draft, before, first, [container], picked.length));
921
977
  }
@@ -1142,3 +1198,218 @@ export function renameKey(doc, path, name, options = {}) {
1142
1198
  const carried = carry(draft, draft.update(before, [...entry.keys, field], () => name), entries, [entry], renameHead(key, name), key, undefined, field === "as" ? key : undefined);
1143
1199
  return { ...finish(draft, before, carried.doc), mentions: carried.mentions };
1144
1200
  }
1201
+ // ---- what an editor's property panel reads and writes --------------------------------------------------------------
1202
+ /** Write `criteria`, the text Jev reads to choose it, on branch `branch` of the judged route at `path`, in its place;
1203
+ * `undefined` removes it. A route by value matches its branches by name and takes no criteria. */
1204
+ export function setBranchCriteria(doc, path, branch, criteria) {
1205
+ const before = documentOf(doc);
1206
+ const entry = find(entriesOf(before), path);
1207
+ const node = entry.node;
1208
+ if (node.node !== "route")
1209
+ throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no branches`);
1210
+ if (isByValue(node))
1211
+ throw new EditError("FIELD_INVALID", path, `${path} is a route by value: it matches its branches by name and takes no criteria`);
1212
+ if (!isObject(node.branches) || typeof branch !== "string" || !Object.hasOwn(node.branches, branch) || !isObject(node.branches[branch]))
1213
+ throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(branch)}"`);
1214
+ if (criteria !== undefined && typeof criteria !== "string")
1215
+ throw new EditError("FIELD_INVALID", path, `a branch's criteria are a text: ${JSON.stringify(criteria)}`);
1216
+ const draft = new Draft();
1217
+ return finish(draft, before, draft.update(before, [...entry.keys, "branches", branch, "criteria"], () => criteria === undefined ? DELETE : criteria));
1218
+ }
1219
+ /** The workflow a scope names: the document for "", or the child of the workflow node at that path. */
1220
+ const scopeOf = (doc, entries, scope) => {
1221
+ if (scope === "")
1222
+ return { workflow: doc, pointer: "", keys: [] };
1223
+ const entry = find(entries, scope);
1224
+ if (entry.node.node !== "workflow" || !isObject(entry.node.workflow))
1225
+ throw new EditError("SLOT_INVALID", scope, `a ${String(entry.node.node)} node holds no child workflow`);
1226
+ return { workflow: entry.node.workflow, pointer: `${scope}/workflow`, keys: [...entry.keys, "workflow"] };
1227
+ };
1228
+ /** The pointers, in `schema` (at `pointer`), of each `$ref` that names the workflow schema `id`: `#/definitions/<id>`.
1229
+ * One under the schema's own `definitions` counts too: the validator resolves it there only when the schema is the
1230
+ * one a field names, not when another schema's `$ref` reaches it. */
1231
+ const refsTo = (schema, id, pointer) => {
1232
+ const out = [];
1233
+ const visit = (value, at) => {
1234
+ if (Array.isArray(value))
1235
+ value.forEach((inner, i) => visit(inner, `${at}/${i}`));
1236
+ else if (isObject(value))
1237
+ for (const [key, inner] of Object.entries(value)) {
1238
+ if (key === "$ref" && inner === `#/definitions/${id}`)
1239
+ out.push(`${at}/${escape(key)}`);
1240
+ else
1241
+ visit(inner, `${at}/${escape(key)}`);
1242
+ }
1243
+ };
1244
+ visit(schema, pointer);
1245
+ return out;
1246
+ };
1247
+ /** The JSON Pointers of the values that name schema `id` of a scope ("" for the document, or a workflow node's path
1248
+ * for its child's schemas): the workflow's `input.schemaId` and `output.schemaId`, a `$ref` from another of its
1249
+ * schemas, and the `out` and `verify.out` of its nodes (a workflow node's `out` names its parent's schema). */
1250
+ export function schemaUsers(doc, id, scope = "") {
1251
+ const before = documentOf(doc);
1252
+ const entries = entriesOf(before);
1253
+ const { workflow, pointer } = scopeOf(before, entries, scope);
1254
+ const out = [];
1255
+ if (isObject(workflow.input) && workflow.input.schemaId === id)
1256
+ out.push(`${pointer}/input/schemaId`);
1257
+ if (isObject(workflow.output) && workflow.output.schemaId === id)
1258
+ out.push(`${pointer}/output/schemaId`);
1259
+ if (isObject(workflow.schemas))
1260
+ for (const [name, schema] of Object.entries(workflow.schemas))
1261
+ if (name !== id)
1262
+ out.push(...refsTo(schema, id, `${pointer}/schemas/${escape(name)}`));
1263
+ for (const entry of entries) {
1264
+ if (entry.scope !== scope)
1265
+ continue;
1266
+ if (entry.node.out === id)
1267
+ out.push(`${entry.path}/out`);
1268
+ if (isObject(entry.node.verify) && entry.node.verify.out === id)
1269
+ out.push(`${entry.path}/verify/out`);
1270
+ }
1271
+ return out;
1272
+ }
1273
+ /** Write `schema` (copied) as schema `id` of a scope ("" for the document, or a workflow node's path for its child), in
1274
+ * its place when it exists; `undefined` removes it, unless something still names it (`schemaUsers`). */
1275
+ export function setSchema(doc, id, schema, scope = "") {
1276
+ const before = documentOf(doc);
1277
+ const entries = entriesOf(before);
1278
+ const { workflow, keys } = scopeOf(before, entries, scope);
1279
+ if (typeof id !== "string" || !id.trim() || id === "__proto__")
1280
+ throw new EditError("NAME_INVALID", scope, `a schema id is a non-empty name other than "__proto__": ${JSON.stringify(id)}`);
1281
+ const schemas = isObject(workflow.schemas) ? workflow.schemas : undefined;
1282
+ const draft = new Draft();
1283
+ if (schema === undefined) {
1284
+ if (!schemas || !Object.hasOwn(schemas, id))
1285
+ throw new EditError("SCHEMA_NOT_FOUND", scope, `${scope || "the document"} has no schema "${id}"`);
1286
+ const users = schemaUsers(before, id, scope);
1287
+ if (users.length)
1288
+ throw new EditError("SCHEMA_IN_USE", scope, `schema "${id}" is named by ${users.join(", ")}`, users);
1289
+ return finish(draft, before, draft.update(before, [...keys, "schemas", id], () => DELETE));
1290
+ }
1291
+ if (!isObject(schema))
1292
+ throw new EditError("SCHEMA_INVALID", scope, `a schema is a JSON object: ${JSON.stringify(schema)}`);
1293
+ if (!schemas)
1294
+ return finish(draft, before, draft.update(before, [...keys, "schemas"], () => ({ [id]: clone(schema) })));
1295
+ return finish(draft, before, draft.update(before, [...keys, "schemas", id], () => clone(schema)));
1296
+ }
1297
+ /** The engine-owned keys a node writes beside `key`: a judge's, a pick's or a judged route's answers under
1298
+ * `<as>$answers`, and a verified node's verdict under `<key>$verify`. */
1299
+ const sidecarsOf = (node, key) => [
1300
+ ...(key === node.as && (node.node === "judge" || node.node === "pick" || (node.node === "route" && !isByValue(node))) ? [`${key}$answers`] : []),
1301
+ ...(node.verify !== undefined && key !== node.failedAs ? [`${key}$verify`] : []),
1302
+ ];
1303
+ /** Whether the node sits in a map's body, in its own scope: it reads that map's `item` and `item_index`. */
1304
+ const inMapBody = (entries, target) => {
1305
+ const byPath = new Map(entries.map((entry) => [entry.path, entry]));
1306
+ for (let at = target;;) {
1307
+ const parent = byPath.get(at.parentPath);
1308
+ if (!parent || parent.scope !== target.scope)
1309
+ return false;
1310
+ if (parent.node.node === "map" && at.slot === "body")
1311
+ return true;
1312
+ at = parent;
1313
+ }
1314
+ };
1315
+ /** The names the node at `path` may read, each with what gives it, by the scope rules rename carries a key along: its
1316
+ * workflow's input keys, a map body's `item` and `item_index`, and the keys (with their `<key>$answers` and
1317
+ * `<key>$verify`) of each node whose write it runs after and sees. With `field`, the names that one field of the node
1318
+ * 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
1319
+ * keys, `verify` the node's own `as` and `submission`, a pick's or sift's `describe` its own `item` and `item_index`,
1320
+ * and a workflow node's `workflow` (its child's `output.path`) the child's state. */
1321
+ export function namesInScope(doc, path, field) {
1322
+ const before = documentOf(doc);
1323
+ const entries = entriesOf(before);
1324
+ const target = find(entries, path);
1325
+ const child = field === "workflow" && target.node.node === "workflow";
1326
+ const out = [];
1327
+ const seen = new Set();
1328
+ const add = (name, from) => { const key = JSON.stringify([name, from]); if (!seen.has(key)) {
1329
+ seen.add(key);
1330
+ out.push({ name, from });
1331
+ } };
1332
+ for (const key of inputKeys(before, entries, child ? target.path : target.scope))
1333
+ add(key, "input");
1334
+ // A map's body, and its resultPath, read the item; so does a pick's or sift's describe, its own candidate. A verifier
1335
+ // reads the node's result as `submission` too.
1336
+ const item = inMapBody(entries, target) || (field === "resultPath" && target.node.node === "map") || (field === "describe" && (target.node.node === "pick" || target.node.node === "sift"));
1337
+ if (!child && item)
1338
+ for (const key of OWN_ITEM)
1339
+ add(key, "engine");
1340
+ if (field === "verify" && target.node.verify !== undefined)
1341
+ add("submission", "engine");
1342
+ const modes = child ? ["childOutput"] : ["own", ...(field === "resultPath" || field === "until" || field === "verify" ? [field] : [])];
1343
+ const reads = (readers) => readers.some(({ entry, mode }) => entry === target && modes.includes(mode));
1344
+ for (const writer of entries) {
1345
+ const keys = keysWritten(writer.node);
1346
+ if (!keys.length)
1347
+ continue;
1348
+ // A key a node writes reaches its readers. Its own `as` also reaches a route's branches, which run after the route
1349
+ // wrote its choice and answers, and the node's verifier, which runs before its verdict is written.
1350
+ if (reads(readersOf(entries, writer).readers)) {
1351
+ for (const key of keys)
1352
+ for (const name of [key, ...sidecarsOf(writer.node, key)])
1353
+ add(name, writer.path);
1354
+ }
1355
+ else if (typeof writer.node.as === "string" && reads(readersOf(entries, writer, true).readers))
1356
+ for (const name of [writer.node.as, ...(writer.node.node === "route" ? sidecarsOf(writer.node, writer.node.as) : [])])
1357
+ add(name, writer.path);
1358
+ }
1359
+ return out;
1360
+ }
1361
+ /** Each `{placeholder}` and state path the node at `path` reads, in its fields' order: the references rename carries,
1362
+ * found by the same walk. A workflow node's include its child's `output.path`, which reads the child's state. */
1363
+ export function readsOf(doc, path) {
1364
+ const before = documentOf(doc);
1365
+ const entry = find(entriesOf(before), path);
1366
+ const out = [];
1367
+ const collect = (head, at, optional) => { out.push({ pointer: `${path}${at}`, name: head, ...(optional ? { optional: true } : {}) }); return head; };
1368
+ renameReads(entry.node, "own", collect);
1369
+ if (entry.node.node === "workflow")
1370
+ renameReads(entry.node, "childOutput", collect);
1371
+ return out;
1372
+ }
1373
+ /** The `{placeholder` open at `offset` in `text`: the index of its `{` and the name typed after it up to the cursor, by
1374
+ * the placeholder grammar (letters, digits, "_", "." and "$"; a reference may start with `state.`). Undefined when no
1375
+ * placeholder's name holds the cursor. The placeholder may already be closed after it. */
1376
+ export function openPlaceholderAt(text, offset) {
1377
+ if (typeof text !== "string" || !Number.isInteger(offset) || offset < 0 || offset > text.length)
1378
+ return undefined;
1379
+ let start = offset;
1380
+ while (start > 0 && /[A-Za-z0-9_.$]/.test(text[start - 1]))
1381
+ start -= 1;
1382
+ if (start === 0 || text[start - 1] !== "{")
1383
+ return undefined;
1384
+ return { start: start - 1, prefix: text.slice(start, offset) };
1385
+ }
1386
+ /** `base`, or its stem (`base` without a `_<n>` ending) with the smallest `_<n>` from 2, so that no label, key,
1387
+ * reference, input key or word of code of any scope of the document holds it, nor an engine key or a name
1388
+ * `Object.prototype` has. `base` is a state key name. */
1389
+ export function freshName(doc, base) {
1390
+ const before = documentOf(doc);
1391
+ if (typeof base !== "string" || !KEY_NAME.test(base))
1392
+ throw new EditError("NAME_INVALID", "", `a name takes letters, digits and "_" only: ${JSON.stringify(base)}`);
1393
+ const entries = entriesOf(before);
1394
+ const used = new Set([...Object.getOwnPropertyNames(Object.prototype), "prototype"]);
1395
+ for (const scope of new Set(["", ...entries.map((entry) => entry.scope)]))
1396
+ for (const name of namesUsed(before, entries, scope))
1397
+ used.add(name);
1398
+ // `base` itself when free, numbered or not; `fresh` alone numbers a numbered base from its stem even when it is free.
1399
+ if (!used.has(base) && !RESERVED_KEYS.has(base))
1400
+ return base;
1401
+ return fresh(base, used);
1402
+ }
1403
+ /** The smallest node of `kind` for `doc`: its required fields in the schema's order, a fresh name as its label (and its
1404
+ * `as`, where it needs one), and each other field's placeholder. A container is made by wrapping nodes that exist. */
1405
+ export function placeholderNode(doc, kind) {
1406
+ if (typeof kind !== "string" || !KINDS.has(kind))
1407
+ throw new EditError("NODE_INVALID", "", `no node kind "${String(kind)}"`);
1408
+ if (SLOT_FIELDS[kind])
1409
+ throw new EditError("NODE_INVALID", "", `a ${kind} holds nodes; wrap makes one of nodes that exist`);
1410
+ const name = freshName(doc, kind);
1411
+ const node = {};
1412
+ for (const field of requiredFields({ node: kind }))
1413
+ node[field] = field === "node" ? kind : field === "label" || field === "as" ? name : placeholder(field);
1414
+ return node;
1415
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-dsl",
3
- "version": "0.1.0-beta.192",
3
+ "version": "0.1.0-beta.194",
4
4
  "description": "Composable, typed workflows for agents",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",