@parcha/agentrun-dsl 0.1.0-beta.226 → 0.1.0-beta.227
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 +1 -1
- package/dist/edit.js +8 -7
- package/dist/index.d.ts +1 -1
- package/dist/predicates.d.ts +3 -2
- package/dist/predicates.js +4 -3
- package/dist/recovery/driver.js +3 -1
- package/dist/recovery/item-state.d.ts +2 -1
- package/dist/recovery/item-state.js +7 -13
- package/dist/vocabulary.d.ts +5 -0
- package/dist/vocabulary.js +5 -0
- package/dist/workflow.d.ts +14 -0
- package/dist/workflow.js +42 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -186,7 +186,7 @@ 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.
|
|
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; `validateWorkflow` refuses a document written with one (`NODE_FIELD_INVALID`, saying to rename it). With `{ reservedNames: "warn" }`, the check a run makes of a document already stored (`runWorkflow` and `runWorkflowSlice` make it so), each such name is a warning instead, listed in the result's `reserved` (`{ path, field, name }`): the engine reads every label, key, branch and state path as an own key, so a stored document that has one runs as written, and a read of `constructor` that nothing wrote is unset. `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
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 (a child workflow's with no node yet included), 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
192
|
|
package/dist/edit.js
CHANGED
|
@@ -95,7 +95,7 @@
|
|
|
95
95
|
// input whose schema lists no properties; the validator does not flag a read of either.
|
|
96
96
|
// - placeholderNode makes the smallest node of a kind that holds no nodes: wrap makes containers of nodes that exist.
|
|
97
97
|
import { workflowGraph } from "./graph.js";
|
|
98
|
-
import { DECISION_NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, NODE_FIELDS, WORKFLOW_NODE_KINDS } from "./vocabulary.js";
|
|
98
|
+
import { DECISION_NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, isPrototypeName, NODE_FIELDS, WORKFLOW_NODE_KINDS } from "./vocabulary.js";
|
|
99
99
|
/** Every code an EditError carries. */
|
|
100
100
|
export const EDIT_ERROR_CODES = [
|
|
101
101
|
/** The document is not an object. */
|
|
@@ -586,9 +586,9 @@ const sourcesOf = (node) => (node.node === "code" || node.node === "call" ? ["co
|
|
|
586
586
|
/** Whether `text` names `word` as a whole word, or one of its engine-owned `<word>$...` keys. */
|
|
587
587
|
const mentions = (text, word) => new RegExp(`(^|[^A-Za-z0-9_$])${word.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}($|[^A-Za-z0-9_])`).test(text);
|
|
588
588
|
/** Refuse a name `Object.prototype` has (`constructor`, `toString`, `__proto__` and the rest), or `prototype`, as a
|
|
589
|
-
* label, an `as`, a `failedAs` or a route branch
|
|
589
|
+
* label, an `as`, a `failedAs` or a route branch (vocabulary.ts isPrototypeName, the validator's rule too). */
|
|
590
590
|
const refusePrototypeName = (name, path) => {
|
|
591
|
-
if (typeof name === "string" && (name
|
|
591
|
+
if (typeof name === "string" && isPrototypeName(name))
|
|
592
592
|
throw new EditError("NAME_INVALID", path, `"${name}" is a name an object's prototype has`);
|
|
593
593
|
};
|
|
594
594
|
const renamePath = (path, rename, prefixed, at, optional = false) => {
|
|
@@ -801,7 +801,7 @@ const namesUsed = (doc, entries, scope, self) => {
|
|
|
801
801
|
/** A name no name in `used` has, added to it: `base` itself when free, else its stem with the smallest `_<n>` from 2. */
|
|
802
802
|
const fresh = (base, used) => {
|
|
803
803
|
const stem = base.replace(/_\d+$/, "") || "node";
|
|
804
|
-
if (!used.has(stem) && stem === base && !RESERVED_KEYS.has(stem)) {
|
|
804
|
+
if (!used.has(stem) && stem === base && !RESERVED_KEYS.has(stem) && !isPrototypeName(stem)) {
|
|
805
805
|
used.add(stem);
|
|
806
806
|
return stem;
|
|
807
807
|
}
|
|
@@ -1395,14 +1395,15 @@ export function freshName(doc, base) {
|
|
|
1395
1395
|
if (typeof base !== "string" || !KEY_NAME.test(base))
|
|
1396
1396
|
throw new EditError("NAME_INVALID", "", `a name takes letters, digits and "_" only: ${JSON.stringify(base)}`);
|
|
1397
1397
|
const entries = entriesOf(before);
|
|
1398
|
-
const used = new Set(
|
|
1398
|
+
const used = new Set();
|
|
1399
1399
|
// Each workflow node's path is a scope, its child's first node not yet inserted included: that node is named here.
|
|
1400
1400
|
const scopes = ["", ...entries.filter((entry) => entry.node.node === "workflow").map((entry) => entry.path)];
|
|
1401
1401
|
for (const scope of scopes)
|
|
1402
1402
|
for (const name of namesUsed(before, entries, scope))
|
|
1403
1403
|
used.add(name);
|
|
1404
|
-
// `base` itself when free, numbered or not
|
|
1405
|
-
|
|
1404
|
+
// `base` itself when free, numbered or not, and no reserved name (vocabulary.ts isPrototypeName, the validator's rule);
|
|
1405
|
+
// `fresh` alone numbers a numbered base from its stem even when it is free.
|
|
1406
|
+
if (!used.has(base) && !RESERVED_KEYS.has(base) && !isPrototypeName(base))
|
|
1406
1407
|
return base;
|
|
1407
1408
|
return fresh(base, used);
|
|
1408
1409
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export { defineJob } from "./job.js";
|
|
|
5
5
|
export type { Job } from "./job.js";
|
|
6
6
|
export { DECISION_RECEIPT_VERSION, DECISION_INTERRUPTED, DECISION_REFUSED, DECISION_STATE_MAX_BYTES, rederiveDecision } from "./decision-receipts.js";
|
|
7
7
|
export type { DecisionImageDigest, DecisionKind, DecisionReceipt, DecisionRule, DecisionStateCut, DecisionStateSent } from "./decision-receipts.js";
|
|
8
|
-
export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, MapLimits, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, MapItemFailure, DecisionExchange, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, DecisionEvidenceMode, DecisionImages, MechanicalPredicate, Predicate, ValidationCode, ValidationIssue, ValidateWorkflowOptions, } from "./workflow.js";
|
|
8
|
+
export type { Workflow, WorkflowNode, NodeMetadata, WorkflowDeps, MapLimits, WorkflowEvent, WorkflowRunResult, HostPolicy, HostPolicyContext, Escalation, EffectSettlement, MapItem, MapItemFailure, DecisionExchange, LlmNode, JudgeNode, PickNode, SiftNode, RouteNode, RouteByJudgmentNode, RouteByValueNode, WorkflowInvocation, ArtifactNode, ArtifactState, CallNode, CodeNode, CallRetryClass, EffectFailureCode, CallPredicate, PollClause, ModelTier, AgentContext, WorkflowEffort, WorkflowThinking, VerifyClause, AskPredicate, DecisionEvidenceMode, DecisionImages, MechanicalPredicate, Predicate, ReservedName, ValidationCode, ValidationIssue, ValidateWorkflowOptions, } from "./workflow.js";
|
|
9
9
|
export { dryRunWorkflow, SYNTHESIS_BUDGET, SynthesisTooLarge, synthesizeInstance, type SynthesisBudget } from "./dry-run.js";
|
|
10
10
|
export type { DryRunOptions, DryRunResult } from "./dry-run.js";
|
|
11
11
|
export { compileQuestions, validateAnswers, answersToValue, answersSidecar, answerConfidence, synthesizeAnswers, SYSTEM_ONE_LIMITS, SystemOneError, isSystemOneResponseReason, deriveConfidence, completeConfidence, refusedQuestions, } from "./system-one.js";
|
package/dist/predicates.d.ts
CHANGED
|
@@ -49,10 +49,11 @@ export type NotPredicate = {
|
|
|
49
49
|
of: AcceptPredicate;
|
|
50
50
|
};
|
|
51
51
|
export declare const MECHANICAL_PREDICATE_NAMES: ReadonlySet<string>;
|
|
52
|
-
/** Resolve a dotted state path the one way every reader does: a record by key, an array by a
|
|
52
|
+
/** Resolve a dotted state path the one way every reader does: a record by its own key, an array by a
|
|
53
53
|
* non-negative integer index, anything else (a string, a number, a missing value) to undefined.
|
|
54
54
|
* `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
|
|
55
|
-
* path that names a value for one names it for all.
|
|
55
|
+
* path that names a value for one names it for all. A key is the record's own: `constructor` or
|
|
56
|
+
* `toString` that nothing wrote is undefined, never the prototype's. */
|
|
56
57
|
export declare function getPath(value: unknown, key: string): unknown;
|
|
57
58
|
/** A quote shorter than this, normalised, is not checked: too short to say which page it came from. */
|
|
58
59
|
export declare const QUOTE_MIN_CHARS = 8;
|
package/dist/predicates.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { isRecord } from "./record.js";
|
|
2
2
|
import { MECHANICAL_PREDICATES } from "./vocabulary.js";
|
|
3
3
|
export const MECHANICAL_PREDICATE_NAMES = new Set(MECHANICAL_PREDICATES);
|
|
4
|
-
/** Resolve a dotted state path the one way every reader does: a record by key, an array by a
|
|
4
|
+
/** Resolve a dotted state path the one way every reader does: a record by its own key, an array by a
|
|
5
5
|
* non-negative integer index, anything else (a string, a number, a missing value) to undefined.
|
|
6
6
|
* `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
|
|
7
|
-
* path that names a value for one names it for all.
|
|
7
|
+
* path that names a value for one names it for all. A key is the record's own: `constructor` or
|
|
8
|
+
* `toString` that nothing wrote is undefined, never the prototype's. */
|
|
8
9
|
export function getPath(value, key) {
|
|
9
10
|
if (!key)
|
|
10
11
|
return value;
|
|
11
12
|
return key.split(".").reduce((current, part) => {
|
|
12
13
|
if (isRecord(current))
|
|
13
|
-
return current[part];
|
|
14
|
+
return Object.hasOwn(current, part) ? current[part] : undefined;
|
|
14
15
|
if (Array.isArray(current)) {
|
|
15
16
|
// Only a position inside the array resolves: a canonical integer below its length. Anything
|
|
16
17
|
// else (a property name, an out-of-range or non-canonical number) is not an element.
|
package/dist/recovery/driver.js
CHANGED
|
@@ -7,6 +7,7 @@ import { createHash } from "node:crypto";
|
|
|
7
7
|
import { desugarWorkflow, isItemFailure } from "../workflow.js";
|
|
8
8
|
import { setLongTimeout } from "../long-timer.js";
|
|
9
9
|
import { isRecord } from "../record.js";
|
|
10
|
+
import { getPath } from "../predicates.js";
|
|
10
11
|
import { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, topLevelCompletion } from "./execution-path.js";
|
|
11
12
|
import { bindingDigests, LEDGER_FORMAT } from "./binding.js";
|
|
12
13
|
import { canonicalHash as hash } from "./canonical-hash.js";
|
|
@@ -829,7 +830,8 @@ export async function openRecovery(store, workflow, options) {
|
|
|
829
830
|
throw pathFault(at, "A committed path was asked for again after its state was released");
|
|
830
831
|
// A map that starts, or starts again, names the base its items are kept against: the state it starts from.
|
|
831
832
|
if ((layoutV4 || moving) && node.node === "map") {
|
|
832
|
-
|
|
833
|
+
// Read as the interpreter reads it (getPath: own keys, an array by its positions), so both count the same items.
|
|
834
|
+
const list = getPath(state, String(node.itemsPath));
|
|
833
835
|
maps.set(at, { length: Array.isArray(list) ? list.length : 0, items: maps.get(at)?.items ?? 0, base: digestOf(state), baseState: state });
|
|
834
836
|
}
|
|
835
837
|
// A node started in an earlier process starts again from the same state, or not at all. The
|
|
@@ -11,7 +11,8 @@ export type StateDelta = {
|
|
|
11
11
|
export type Sha256 = (text: string) => string;
|
|
12
12
|
/** The JSON a state's digest is taken over: every object's keys sorted. */
|
|
13
13
|
export declare function canonicalJson(value: unknown): string;
|
|
14
|
-
/** `state` against `base`, as a map item keeps it.
|
|
14
|
+
/** `state` against `base`, as a map item keeps it. Each object is built from its entries (Object.fromEntries), so every
|
|
15
|
+
* key is an own one, `__proto__` too: an assignment of that key would set the object's prototype and drop the key. */
|
|
15
16
|
export declare function stateDelta(base: State, state: State, sha256: string): StateDelta;
|
|
16
17
|
/** The state a delta was taken from, in its own key order: the base's keys first (a map item starts from a copy of its
|
|
17
18
|
* base), then the keys it added. */
|
|
@@ -6,26 +6,20 @@ export function canonicalJson(value) {
|
|
|
6
6
|
? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
|
|
7
7
|
}
|
|
8
8
|
const sameValue = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
|
|
9
|
-
/** `state` against `base`, as a map item keeps it.
|
|
9
|
+
/** `state` against `base`, as a map item keeps it. Each object is built from its entries (Object.fromEntries), so every
|
|
10
|
+
* key is an own one, `__proto__` too: an assignment of that key would set the object's prototype and drop the key. */
|
|
10
11
|
export function stateDelta(base, state, sha256) {
|
|
11
|
-
const set =
|
|
12
|
-
for (const [key, value] of Object.entries(state))
|
|
13
|
-
if (!Object.hasOwn(base, key) || !sameValue(base[key], value))
|
|
14
|
-
set[key] = value;
|
|
12
|
+
const set = Object.fromEntries(Object.entries(state).filter(([key, value]) => !Object.hasOwn(base, key) || !sameValue(base[key], value)));
|
|
15
13
|
return { set, unset: Object.keys(base).filter((key) => !Object.hasOwn(state, key)), sha256 };
|
|
16
14
|
}
|
|
17
15
|
/** The state a delta was taken from, in its own key order: the base's keys first (a map item starts from a copy of its
|
|
18
16
|
* base), then the keys it added. */
|
|
19
17
|
export function applyStateDelta(base, delta) {
|
|
20
18
|
const unset = new Set(delta.unset);
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
for (const [key, value] of Object.entries(delta.set))
|
|
26
|
-
if (!Object.hasOwn(base, key))
|
|
27
|
-
state[key] = value;
|
|
28
|
-
return state;
|
|
19
|
+
return Object.fromEntries([
|
|
20
|
+
...Object.keys(base).filter((key) => !unset.has(key)).map((key) => [key, Object.hasOwn(delta.set, key) ? delta.set[key] : base[key]]),
|
|
21
|
+
...Object.entries(delta.set).filter(([key]) => !Object.hasOwn(base, key)),
|
|
22
|
+
]);
|
|
29
23
|
}
|
|
30
24
|
const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
31
25
|
/** A map item's state at `path`, rebuilt as the driver rebuilds it: the `agentrun.states` value its `base` names, with
|
package/dist/vocabulary.d.ts
CHANGED
|
@@ -48,3 +48,8 @@ export declare const CALL_RETRY_CLASSES: readonly ["timeout", "http_5xx", "http_
|
|
|
48
48
|
export declare const EFFECT_FAILURE_CODES: readonly ["effect_timeout", "effect_exit", "effect_transport", "effect_not_granted", "effect_produces_missing", "effect_path_escape", "effect_code_unsafe", "output_invalid", "state_invalid", "effect_unknown_transport"];
|
|
49
49
|
/** Artifact types the engine itself treats as prose (the report writer). Every other type names a file. */
|
|
50
50
|
export declare const PROSE_ARTIFACT_TYPES: readonly ["markdown", "report"];
|
|
51
|
+
/** Whether `name` is one an object's prototype has (`constructor`, `toString`, `__proto__` and the rest of
|
|
52
|
+
* `Object.prototype`'s own names), or `prototype`. As a label, an `as`, a `failedAs` or a route branch, a read of one that
|
|
53
|
+
* nothing wrote would find the prototype's value: the editor refuses to write such a name (edit.ts), and the validator
|
|
54
|
+
* refuses a document that has one (workflow.ts). */
|
|
55
|
+
export declare const isPrototypeName: (name: string) => boolean;
|
package/dist/vocabulary.js
CHANGED
|
@@ -82,3 +82,8 @@ export const EFFECT_FAILURE_CODES = [
|
|
|
82
82
|
];
|
|
83
83
|
/** Artifact types the engine itself treats as prose (the report writer). Every other type names a file. */
|
|
84
84
|
export const PROSE_ARTIFACT_TYPES = ["markdown", "report"];
|
|
85
|
+
/** Whether `name` is one an object's prototype has (`constructor`, `toString`, `__proto__` and the rest of
|
|
86
|
+
* `Object.prototype`'s own names), or `prototype`. As a label, an `as`, a `failedAs` or a route branch, a read of one that
|
|
87
|
+
* nothing wrote would find the prototype's value: the editor refuses to write such a name (edit.ts), and the validator
|
|
88
|
+
* refuses a document that has one (workflow.ts). */
|
|
89
|
+
export const isPrototypeName = (name) => name === "prototype" || Object.hasOwn(Object.prototype, name);
|
package/dist/workflow.d.ts
CHANGED
|
@@ -704,6 +704,13 @@ export type ValidationIssue = {
|
|
|
704
704
|
code: ValidationCode;
|
|
705
705
|
message: string;
|
|
706
706
|
};
|
|
707
|
+
/** A reserved name (vocabulary.ts isPrototypeName: Object.prototype's own names, and "prototype") where a document puts a
|
|
708
|
+
* name: a node's `label`, `as` or `failedAs`, or a route's branch. `path` is the node's JSON Pointer. */
|
|
709
|
+
export type ReservedName = {
|
|
710
|
+
path: string;
|
|
711
|
+
field: "label" | "as" | "failedAs" | "branch";
|
|
712
|
+
name: string;
|
|
713
|
+
};
|
|
707
714
|
/** Whether a workflow can run, checked without running it: `errors` refuse it, `warnings` advise and never refuse.
|
|
708
715
|
* Set `executeCode: false` for untrusted author feedback: check syntax and mechanical contracts without evaluating
|
|
709
716
|
* authored expressions or probing transforms. That is not execution admission; trusted/default validation and runtime
|
|
@@ -725,15 +732,22 @@ export type ValidateWorkflowOptions = {
|
|
|
725
732
|
/** The host's tool names. Given, a node that names a tool outside them (a model or artifact node's `tools`, a call
|
|
726
733
|
* node's `tool`) is refused here. Absent, tool names are not checked until a node runs. */
|
|
727
734
|
tools?: readonly string[];
|
|
735
|
+
/** A reserved name as a label, `as`, `failedAs` or route branch (ReservedName). "refuse" (the default, a save's check):
|
|
736
|
+
* each is a NODE_FIELD_INVALID issue saying to rename it. "warn" (a run's check of a document already stored): none is
|
|
737
|
+
* an issue; each is a warning, and `reserved` lists them in document order. The engine reads every name as an own key,
|
|
738
|
+
* so a stored document that has one runs as written. */
|
|
739
|
+
reservedNames?: "refuse" | "warn";
|
|
728
740
|
};
|
|
729
741
|
export declare function validateWorkflow(workflow: Workflow, opts?: ValidateWorkflowOptions): {
|
|
730
742
|
ok: true;
|
|
731
743
|
warnings?: string[];
|
|
744
|
+
reserved?: ReservedName[];
|
|
732
745
|
} | {
|
|
733
746
|
ok: false;
|
|
734
747
|
errors: string[];
|
|
735
748
|
issues: ValidationIssue[];
|
|
736
749
|
warnings?: string[];
|
|
750
|
+
reserved?: ReservedName[];
|
|
737
751
|
};
|
|
738
752
|
/** The value a `{path}` placeholder reads from state, in interpolation's lookup order: the path as written, else, for a
|
|
739
753
|
* `state.` path, the path after `state.` (so `{state.x}` reads a real `state` key first). undefined when neither
|
package/dist/workflow.js
CHANGED
|
@@ -2,7 +2,7 @@ import { observerSnapshot } from "./observer-snapshot.js";
|
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import { isDeepStrictEqual, types as utilTypes } from "node:util";
|
|
4
4
|
import { predicateMatches, getPath, MECHANICAL_PREDICATE_NAMES, quoteCheck } from "./predicates.js";
|
|
5
|
-
import { DECISION_NODE_FIELDS, DECISION_TIMEOUT_MAX_MS, WORKFLOW_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, WORKFLOW_PREDICATES, FIELD_TYPES, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES } from "./vocabulary.js";
|
|
5
|
+
import { DECISION_NODE_FIELDS, DECISION_TIMEOUT_MAX_MS, WORKFLOW_NODE_KINDS, NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, WORKFLOW_PREDICATES, FIELD_TYPES, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, isPrototypeName } from "./vocabulary.js";
|
|
6
6
|
import { validateAnswers, answerConfidence, answersSidecar, answersToValue, compileQuestions, refusedQuestions, SYSTEM_ONE_LIMITS } from "./system-one.js";
|
|
7
7
|
import { chargedCost, DecisionProviderError } from "./decision-provider.js";
|
|
8
8
|
import { DECISION_ERROR_MAX, DECISION_RECEIPT_VERSION, DECISION_INTERRUPTED, DECISION_REFUSED, DECISION_STATE_MAX_BYTES } from "./decision-receipts.js";
|
|
@@ -460,6 +460,17 @@ export function validateWorkflow(workflow, opts) {
|
|
|
460
460
|
const errors = [];
|
|
461
461
|
const issues = [];
|
|
462
462
|
const fail = (code, path, message) => { errors.push(message); issues.push({ path, code, message }); };
|
|
463
|
+
// Reserved names, refused where they are, or (reservedNames "warn") kept to warn of once the walk is done.
|
|
464
|
+
const warnReserved = opts?.reservedNames === "warn";
|
|
465
|
+
const reserved = [];
|
|
466
|
+
const reservedWords = (field, name) => `${field} "${name}" is a reserved name, one an object's prototype has; rename it`;
|
|
467
|
+
const reservedAt = (at, path, shown, field, name) => {
|
|
468
|
+
const message = `${path} (${shown}): ${reservedWords(field, name)}`;
|
|
469
|
+
if (warnReserved)
|
|
470
|
+
reserved.push({ hit: { path: at, field, name }, message: `${message} on your next save` });
|
|
471
|
+
else
|
|
472
|
+
fail("NODE_FIELD_INVALID", at, message);
|
|
473
|
+
};
|
|
463
474
|
// Each node's walk path (the text its messages begin with) to its JSON Pointer. Desugaring replaces nodes in place, so
|
|
464
475
|
// the pointer names the same node in the document as written.
|
|
465
476
|
const pointers = new Map();
|
|
@@ -952,6 +963,19 @@ export function validateWorkflow(workflow, opts) {
|
|
|
952
963
|
const labelIsKey = (node.node === "agent" || node.node === "decide" || node.node === "extract" || node.node === "code") && node.as === undefined;
|
|
953
964
|
if (labelIsKey && typeof node.label === "string" && holdsDollar(node.label))
|
|
954
965
|
fail("STATE_KEY_RESERVED", ptrOf(path), `${path} (${node.label}): label must not contain "$" — an unaliased ${node.node} node writes under its label, and "$" keys are engine-owned`);
|
|
966
|
+
// No label, `as`, `failedAs` or route branch is a reserved name (vocabulary.ts isPrototypeName), a label that is only a
|
|
967
|
+
// name as well as one that is the node's key: the editor refuses to write one (edit.ts), and so does a save. The
|
|
968
|
+
// engine reads each as an own key, so a document stored with one still runs (reservedNames "warn").
|
|
969
|
+
for (const field of ["label", "as", "failedAs"]) {
|
|
970
|
+
const name = node[field];
|
|
971
|
+
if (typeof name === "string" && isPrototypeName(name))
|
|
972
|
+
reservedAt(ptrOf(path), path, node.label || node.node, field, name);
|
|
973
|
+
}
|
|
974
|
+
if (node.node === "route" && isRecord(node.branches)) {
|
|
975
|
+
for (const name of Object.keys(node.branches))
|
|
976
|
+
if (isPrototypeName(name))
|
|
977
|
+
reservedAt(ptrOf(path), path, node.label || "route", "branch", name);
|
|
978
|
+
}
|
|
955
979
|
// A generative or code node's write key must be a real state key, never blank: the interpreter writes under
|
|
956
980
|
// `as || label` (`as` wins when it is any non-empty string, whitespace included), so a blank or whitespace-only
|
|
957
981
|
// `as`, or a label that is the key and is whitespace-only, would write under a key no other node can name and hide
|
|
@@ -1350,10 +1374,13 @@ export function validateWorkflow(workflow, opts) {
|
|
|
1350
1374
|
fail("STRUCTURE_INVALID", ptrOf(path), `${path} (${label}): a child cannot render a report or deliver an artifact; the parent owns the terminal`);
|
|
1351
1375
|
if (typeof child.input?.schemaId !== "string" || !Object.hasOwn(child.schemas, child.input.schemaId))
|
|
1352
1376
|
fail("WORKFLOW_FIELD_INVALID", `${ptrOf(path)}/workflow`, `${path} (${label}): the child must declare input.schemaId in its own schemas`);
|
|
1353
|
-
const validated = validateWorkflow(child, { executeCode: opts?.executeCode, inputKeys: Object.keys(node.input && typeof node.input === "object" ? node.input : {}), ...(opts?.tools ? { tools: opts.tools } : {}) });
|
|
1377
|
+
const validated = validateWorkflow(child, { executeCode: opts?.executeCode, inputKeys: Object.keys(node.input && typeof node.input === "object" ? node.input : {}), ...(opts?.tools ? { tools: opts.tools } : {}), ...(opts?.reservedNames ? { reservedNames: opts.reservedNames } : {}) });
|
|
1354
1378
|
if (!validated.ok)
|
|
1355
1379
|
for (const issue of validated.issues)
|
|
1356
1380
|
fail(issue.code, `${ptr}/workflow${issue.path}`, `${path} (${label}) child: ${issue.message}`);
|
|
1381
|
+
// Warned (reservedNames "warn"), the child's reserved names are the parent's, at their paths in the parent.
|
|
1382
|
+
for (const hit of validated.reserved ?? [])
|
|
1383
|
+
reserved.push({ hit: { ...hit, path: `${ptr}/workflow${hit.path}` }, message: `${path} (${label}) child: ${hit.path}: ${reservedWords(hit.field, hit.name)} on your next save` });
|
|
1357
1384
|
for (const step of steps)
|
|
1358
1385
|
if (step.node === "call" && Array.isArray(step.produces))
|
|
1359
1386
|
for (const file of step.produces)
|
|
@@ -1595,8 +1622,11 @@ export function validateWorkflow(workflow, opts) {
|
|
|
1595
1622
|
if (!errors.length)
|
|
1596
1623
|
for (const issue of workflowShapeIssues(workflow, true))
|
|
1597
1624
|
fail("SHAPE_INVALID", issue.path, issue.message);
|
|
1598
|
-
|
|
1599
|
-
|
|
1625
|
+
// The warnings in one fixed order: the cost advice, then what the reachability checks found against derived input keys,
|
|
1626
|
+
// then the reserved names (reservedNames "warn"), each in document order.
|
|
1627
|
+
const warnings = [...workflowWarnings(workflow), ...derivedWarnings, ...reserved.map(({ message }) => message)];
|
|
1628
|
+
const named = reserved.length ? { reserved: reserved.map(({ hit }) => hit) } : {};
|
|
1629
|
+
return errors.length ? { ok: false, errors, issues, ...(warnings.length ? { warnings } : {}), ...named } : { ok: true, ...(warnings.length ? { warnings } : {}), ...named };
|
|
1600
1630
|
}
|
|
1601
1631
|
/** The value a `{path}` placeholder reads from state, in interpolation's lookup order: the path as written, else, for a
|
|
1602
1632
|
* `state.` path, the path after `state.` (so `{state.x}` reads a real `state` key first). undefined when neither
|
|
@@ -3134,13 +3164,14 @@ async function runNodeBody(node, state, workflow, deps) {
|
|
|
3134
3164
|
const itemState = snapshotState({ ...state, item: items[i], item_index: i });
|
|
3135
3165
|
const out = await runNodeOnState(node.body, itemState, workflow, itemDeps);
|
|
3136
3166
|
if (node.resultPath !== undefined) {
|
|
3137
|
-
|
|
3167
|
+
// Each key read is the value's own (an array's positions and length among them), never its prototype's.
|
|
3168
|
+
const selected = node.resultPath.split(".").reduce((value, key) => value == null || !Object.hasOwn(Object(value), key) ? undefined : value[key], out);
|
|
3138
3169
|
if (selected === undefined)
|
|
3139
3170
|
throw new WorkflowStateError(`map node "${node.label}": resultPath "${node.resultPath}" is missing from item ${i}`, node.label, node.resultPath, "missing_map_result");
|
|
3140
3171
|
results[i] = structuredClone(selected);
|
|
3141
3172
|
}
|
|
3142
3173
|
else
|
|
3143
|
-
results[i] = node.body.as ? out[node.body.as] : out;
|
|
3174
|
+
results[i] = node.body.as ? (Object.hasOwn(out, node.body.as) ? out[node.body.as] : undefined) : out;
|
|
3144
3175
|
}
|
|
3145
3176
|
catch (error) {
|
|
3146
3177
|
// An item failure ends its item, and a decision that went to review marks it for review; the map's stop and
|
|
@@ -3322,9 +3353,7 @@ async function runNodeBody(node, state, workflow, deps) {
|
|
|
3322
3353
|
case "escalate": {
|
|
3323
3354
|
const evaluated = await evaluatePredicate(node.when, state, deps, { label: node.label, kind: "escalate" }, workflow);
|
|
3324
3355
|
const fired = evaluated.holds;
|
|
3325
|
-
const pathValue = node.when?.path
|
|
3326
|
-
? String(node.when.path).split(".").reduce((acc, key) => (acc == null ? acc : acc[key]), state)
|
|
3327
|
-
: undefined;
|
|
3356
|
+
const pathValue = node.when?.path ? getPath(state, String(node.when.path)) : undefined;
|
|
3328
3357
|
deps.onEvent?.({ type: "escalate.evaluated", label: node.label, detail: { fired, path: node.when?.path ?? null, path_resolved: pathValue !== undefined, ...(evaluated.detail ?? {}) } });
|
|
3329
3358
|
if (fired) {
|
|
3330
3359
|
throw new EscalationSignal({ kind: node.kind, stage: node.stage, summary: interpolate(node.summary, state), state, label: node.label, executionPath: executionPath(deps) });
|
|
@@ -3541,7 +3570,8 @@ export async function runWorkflow(workflow, input, deps) {
|
|
|
3541
3570
|
throw new WorkflowInputInvalidError(String(workflow?.name), ["input must be a JSON object"]);
|
|
3542
3571
|
// A host that executes code nodes itself never has them executed here, not even as validation probes.
|
|
3543
3572
|
const executeCode = deps.runCode ? false : undefined;
|
|
3544
|
-
|
|
3573
|
+
// A run takes a document already stored: a reserved name a save would refuse is a warning here, never a refusal.
|
|
3574
|
+
const valid = validateWorkflow(workflow, { executeCode, reservedNames: "warn" });
|
|
3545
3575
|
if (!valid.ok)
|
|
3546
3576
|
throw new WorkflowInvalidError(String(workflow?.name), valid.errors, valid.issues);
|
|
3547
3577
|
workflow = desugarWorkflow(workflow);
|
|
@@ -3550,7 +3580,7 @@ export async function runWorkflow(workflow, input, deps) {
|
|
|
3550
3580
|
if (!validator.Check(input))
|
|
3551
3581
|
throw new WorkflowInputInvalidError(workflow.name, schemaProblems(validator, input));
|
|
3552
3582
|
}
|
|
3553
|
-
const reachable = validateWorkflow(workflow, { executeCode, inputKeys: Object.keys(input) });
|
|
3583
|
+
const reachable = validateWorkflow(workflow, { executeCode, inputKeys: Object.keys(input), reservedNames: "warn" });
|
|
3554
3584
|
if (!reachable.ok)
|
|
3555
3585
|
throw new WorkflowInvalidError(workflow.name, reachable.errors, reachable.issues);
|
|
3556
3586
|
assertWorkflowCapabilities(workflow.root, deps, workflow);
|
|
@@ -3581,7 +3611,7 @@ export async function runWorkflow(workflow, input, deps) {
|
|
|
3581
3611
|
}
|
|
3582
3612
|
}
|
|
3583
3613
|
export async function runWorkflowSlice(workflow, input, focus, deps) {
|
|
3584
|
-
const valid = validateWorkflow(workflow, { executeCode: deps.runCode ? false : undefined });
|
|
3614
|
+
const valid = validateWorkflow(workflow, { executeCode: deps.runCode ? false : undefined, reservedNames: "warn" });
|
|
3585
3615
|
if (!valid.ok)
|
|
3586
3616
|
throw new WorkflowInvalidError(String(workflow?.name), valid.errors, valid.issues);
|
|
3587
3617
|
const desugared = desugarWorkflow(workflow);
|