@parcha/agentrun-dsl 0.1.0-beta.2 → 0.1.0-beta.200

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +172 -22
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +97 -0
  6. package/dist/author.js +329 -0
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +25 -0
  10. package/dist/code-exec.js +180 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +159 -0
  14. package/dist/decision-receipts.js +93 -0
  15. package/dist/dry-run.d.ts +45 -2
  16. package/dist/dry-run.js +159 -27
  17. package/dist/edit.d.ts +149 -0
  18. package/dist/edit.js +1415 -0
  19. package/dist/evidence.d.ts +19 -0
  20. package/dist/evidence.js +63 -0
  21. package/dist/graph.d.ts +169 -0
  22. package/dist/graph.js +433 -0
  23. package/dist/index.d.ts +20 -7
  24. package/dist/index.js +17 -7
  25. package/dist/inspection.d.ts +5 -0
  26. package/dist/inspection.js +16 -3
  27. package/dist/job.d.ts +14 -0
  28. package/dist/job.js +5 -0
  29. package/dist/long-timer.d.ts +7 -0
  30. package/dist/long-timer.js +22 -0
  31. package/dist/observer-snapshot.d.ts +3 -0
  32. package/dist/observer-snapshot.js +46 -0
  33. package/dist/pattern-screen.d.ts +14 -0
  34. package/dist/pattern-screen.js +451 -0
  35. package/dist/predicates.d.ts +33 -0
  36. package/dist/predicates.js +81 -5
  37. package/dist/record.d.ts +4 -0
  38. package/dist/record.js +6 -0
  39. package/dist/recovery/binding.d.ts +10 -0
  40. package/dist/recovery/binding.js +44 -0
  41. package/dist/recovery/call-key.d.ts +9 -0
  42. package/dist/recovery/call-key.js +17 -0
  43. package/dist/recovery/canonical-hash.d.ts +7 -0
  44. package/dist/recovery/canonical-hash.js +22 -0
  45. package/dist/recovery/driver.d.ts +245 -0
  46. package/dist/recovery/driver.js +1347 -0
  47. package/dist/recovery/errors.d.ts +31 -0
  48. package/dist/recovery/errors.js +51 -0
  49. package/dist/recovery/execution-path.d.ts +53 -0
  50. package/dist/recovery/execution-path.js +167 -0
  51. package/dist/recovery/file-store.d.ts +7 -0
  52. package/dist/recovery/file-store.js +131 -0
  53. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  54. package/dist/recovery/frozen-snapshot.js +187 -0
  55. package/dist/recovery/handoff-receipts.d.ts +7 -0
  56. package/dist/recovery/handoff-receipts.js +11 -0
  57. package/dist/recovery/index.d.ts +14 -0
  58. package/dist/recovery/index.js +13 -0
  59. package/dist/recovery/item-state.d.ts +48 -0
  60. package/dist/recovery/item-state.js +89 -0
  61. package/dist/recovery/journal.d.ts +28 -0
  62. package/dist/recovery/journal.js +139 -0
  63. package/dist/recovery/memory-store.d.ts +4 -0
  64. package/dist/recovery/memory-store.js +20 -0
  65. package/dist/recovery/store.d.ts +105 -0
  66. package/dist/recovery/store.js +6 -0
  67. package/dist/recovery/testing/conformance.d.ts +4 -0
  68. package/dist/recovery/testing/conformance.js +268 -0
  69. package/dist/recovery/testing/crash-points.d.ts +18 -0
  70. package/dist/recovery/testing/crash-points.js +43 -0
  71. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  72. package/dist/recovery/testing/crash-sweep.js +146 -0
  73. package/dist/recovery/testing/index.d.ts +3 -0
  74. package/dist/recovery/testing/index.js +4 -0
  75. package/dist/recovery/testing/preload.d.ts +1 -0
  76. package/dist/recovery/testing/preload.js +3 -0
  77. package/dist/recovery/transport-facts.d.ts +23 -0
  78. package/dist/recovery/transport-facts.js +46 -0
  79. package/dist/recovery/with-recovery.d.ts +50 -0
  80. package/dist/recovery/with-recovery.js +144 -0
  81. package/dist/submit-envelope.d.ts +9 -0
  82. package/dist/submit-envelope.js +44 -0
  83. package/dist/system-one.d.ts +37 -2
  84. package/dist/system-one.js +146 -11
  85. package/dist/testing/decision-provider.d.ts +32 -0
  86. package/dist/testing/decision-provider.js +183 -0
  87. package/dist/testing/index.d.ts +1 -0
  88. package/dist/testing/index.js +2 -0
  89. package/dist/vocabulary.d.ts +50 -0
  90. package/dist/vocabulary.js +84 -0
  91. package/dist/workflow-shape.d.ts +7 -0
  92. package/dist/workflow-shape.js +119 -69
  93. package/dist/workflow.d.ts +309 -29
  94. package/dist/workflow.js +1664 -487
  95. package/dist/zod-json-contract.js +6 -8
  96. package/package.json +33 -5
  97. package/schema/workflow.schema.json +599 -12
  98. package/skills/author/SKILL.md +125 -0
  99. package/skills/author/examples/evidence-gate.input.json +6 -0
  100. package/skills/author/examples/evidence-gate.json +125 -0
  101. package/skills/author/examples/read-file.input.json +1 -0
  102. package/skills/author/examples/read-file.json +44 -0
  103. package/skills/author/examples/read-source-decision.input.json +4 -0
  104. package/skills/author/examples/read-source-decision.json +37 -0
  105. package/skills/author/examples/release-note.txt +10 -0
  106. package/skills/author/examples/review-release-notes.input.json +6 -0
  107. package/skills/author/examples/review-release-notes.json +123 -0
  108. package/skills/author/references/jev-decisions.md +170 -0
  109. package/skills/author/references/language.md +123 -0
  110. package/skills/author/references/sdk-authoring.md +11 -0
  111. package/skills/author/references/workflow-format.md +137 -0
@@ -0,0 +1,97 @@
1
+ import { type Workflow, type WorkflowDeps } from "./workflow.js";
2
+ import { type WorkflowNodeKind } from "./vocabulary.js";
3
+ /** What a host adds to the author contract. It names the host's own vocabulary and rules and never
4
+ * restates or changes the language: the package renders it once, after the language section. */
5
+ export interface AuthorHostAddendum {
6
+ /** The host's name, the addendum's heading. */
7
+ name: string;
8
+ /** The keys the host seeds into the initial state, each with what it holds. Candidates are validated
9
+ * against exactly these keys when they declare no `input` schema. */
10
+ initialState?: Readonly<Record<string, string>>;
11
+ /** The artifact types the host delivers. A prose type is the report writer under the host's name; a file
12
+ * type names a file an earlier shell call produced. Declared, they are the only artifact types admitted. */
13
+ outputTypes?: Readonly<Record<string, {
14
+ kind: "prose" | "file";
15
+ description: string;
16
+ }>>;
17
+ /** The node kinds the host runs. Declared, a candidate using any other kind is refused. */
18
+ nodeKinds?: readonly WorkflowNodeKind[];
19
+ /** The node `metadata` keys an author may set, each with what it holds. Undeclared, an author sets no
20
+ * metadata. The engine never reads them; the host enforces them in its own acceptance checks. */
21
+ metadataKeys?: Readonly<Record<string, string>>;
22
+ /** Host rules, one sentence each. The host enforces them in its own acceptance checks. */
23
+ rules?: readonly string[];
24
+ }
25
+ /** The host section of the contract, or "" without a host. */
26
+ export declare function renderAuthorHostAddendum(host: AuthorHostAddendum | undefined): string;
27
+ /** The rendered author contract and the sha256 of exactly that text. A host records the digest with every
28
+ * candidate it authors, so a workflow names the contract that wrote it. */
29
+ export declare function renderAuthorContract(options?: {
30
+ host?: AuthorHostAddendum;
31
+ }): {
32
+ text: string;
33
+ sha256: string;
34
+ };
35
+ /** The one author contract: the language every host shares, then the host's addendum when one is supplied. */
36
+ export declare function authorContract(options?: {
37
+ host?: AuthorHostAddendum;
38
+ }): string;
39
+ export interface CandidatePolicyOptions {
40
+ /** Authoritative rubric text by section name. Every generative node must name every section. */
41
+ rubricSections?: Record<string, string>;
42
+ /** Admits code, call and artifact nodes. A candidate's code is syntax-checked before acceptance and run only after
43
+ * its host accepts it; in-process code is not a sandbox (see the README's `code` node note). */
44
+ allowExecutableCandidates?: boolean;
45
+ /** Direct tool calls admitted without executable authorization. */
46
+ allowedEffectTools?: readonly string[];
47
+ host?: AuthorHostAddendum;
48
+ }
49
+ /** Author policy over a candidate, checked before validation so a refused candidate never evaluates code. */
50
+ export declare function candidatePolicyErrors(candidate: unknown, options: CandidatePolicyOptions): string[];
51
+ export interface HostOutputTypeOptions {
52
+ /** The host's name for an authored artifact type: an authored spelling (another case, dashes for underscores,
53
+ * an alias) mapped to one of `host.outputTypes`, or null when it names none; its answer decides, so null leaves even
54
+ * an exact name as authored. Absent, a type is matched exactly. */
55
+ normalizeType?: (type: string) => string | null | undefined;
56
+ }
57
+ /** The interpreter's view of a workflow written in a host's vocabulary: an artifact of a declared prose output
58
+ * type becomes the report writer it is. Validate and run this view; retain and digest the authored bytes. With
59
+ * `normalizeType`, an artifact's type is first mapped to the host's name for it. */
60
+ export declare function applyHostOutputTypes(candidate: Workflow, host: AuthorHostAddendum | undefined, options?: HostOutputTypeOptions): Workflow;
61
+ export interface AuthorWorkflowOptions {
62
+ request: string;
63
+ outputDir: string;
64
+ /** The host's generative adapter. The author asks it for one agent session with no tools. */
65
+ runNode: NonNullable<WorkflowDeps["runNode"]>;
66
+ host?: AuthorHostAddendum;
67
+ /** Keys available to a candidate without an input schema; defaults to the host's initial state keys. */
68
+ inputKeys?: string[];
69
+ rubricSections?: Record<string, string>;
70
+ /** Admits code, call and artifact nodes. A candidate's code is syntax-checked before acceptance and run only after
71
+ * its host accepts it; in-process code is not a sandbox (see the README's `code` node note). */
72
+ allowExecutableCandidates?: boolean;
73
+ maxCandidates?: number;
74
+ /** Host acceptance over a structurally valid candidate, in the interpreter's view (`applyHostOutputTypes`):
75
+ * diagnostics, or [] to accept. */
76
+ acceptance?: (candidate: Workflow) => Promise<string[]> | string[];
77
+ signal?: AbortSignal;
78
+ }
79
+ export interface AuthoredWorkflow {
80
+ /** The accepted candidate as authored. A host with prose output types runs `applyHostOutputTypes(workflow, host)`. */
81
+ workflow: Workflow;
82
+ path: string;
83
+ directory: string;
84
+ candidates: number;
85
+ checks: "structural" | "structural-and-host";
86
+ /** sha256 of the exact contract text the session received (`renderAuthorContract`). */
87
+ contractSha256: string;
88
+ }
89
+ /** Author one workflow and retain every candidate with its review in a new directory under `outputDir`.
90
+ * Policy, validation and host acceptance review each submission; a rejection returns to the same session. */
91
+ export declare function authorWorkflow(options: AuthorWorkflowOptions): Promise<AuthoredWorkflow>;
92
+ /** The absolute directory of the packaged author skill (the one holding SKILL.md). */
93
+ export declare function authorSkillDirectory(): string;
94
+ /** A reference shipped with the author skill, for hosts without file-reading tools. */
95
+ export declare function loadAuthorReference(name: "language" | "workflow-format" | "jev-decisions"): string;
96
+ /** The whole skill as one text: SKILL.md, its references and its JSON examples. */
97
+ export declare function loadAuthorSkillBundle(): string;
package/dist/author.js ADDED
@@ -0,0 +1,329 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { readFileSync, readdirSync } from "node:fs";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ import { fileURLToPath } from "node:url";
5
+ import { join, resolve } from "node:path";
6
+ import { validateWorkflow } from "./workflow.js";
7
+ import { SYSTEM_ONE_LIMITS } from "./system-one.js";
8
+ import { WORKFLOW_NODE_KINDS, NODE_FIELDS, WORKFLOW_PREDICATES, PREDICATE_FIELDS, MECHANICAL_PREDICATES, FIELD_TYPES, EFFORT_LEVELS, THINKING_LEVELS, MODEL_TIERS, AGENT_CONTEXTS, CALL_TRANSPORTS, CALL_RETRY_CLASSES, EFFECT_FAILURE_CODES, PROSE_ARTIFACT_TYPES, GENERATIVE_NODE_KINDS, JUDGMENT_NODE_KINDS, } from "./vocabulary.js";
9
+ import { QUOTE_MIN_CHARS } from "./predicates.js";
10
+ import { isRecord } from "./record.js";
11
+ const code = (value) => `\`${value}\``;
12
+ const list = (values) => values.map(code).join(", ");
13
+ const alternatives = (values) => values.join("|");
14
+ const PREDICATE_SHAPES = {
15
+ field_equals: "holds when the value at `path` equals `value` (a string, number or boolean)",
16
+ field_true: "holds when the value at `path` is `true`",
17
+ in: "holds when the value at `path` is one of `values` (a non-empty list of strings, numbers or booleans)",
18
+ count_gte: "holds when the array (or number) at `path` has at least `n` items",
19
+ gte: "holds when the finite number at `path` is at least `n`",
20
+ lt: "holds when the finite number at `path` is below `n`",
21
+ empty: "holds when the value at `path` is an empty array, an empty string, null or absent",
22
+ no_new_items: "takes `key`, not `path`; holds when that state key is an empty array or falsy",
23
+ field_type: `holds when the value at \`path\` is of \`type\`, one of ${FIELD_TYPES.join(", ")}; a number only when finite, and an absent value is of no type`,
24
+ quote_missing: `the quote check, in code: holds when a quote at \`path\` (a string, or a list of them; with \`field\`, a list of records each holding its quote at \`field\`) is in none of the pages at \`pages\` (state paths holding what this run's call steps fetched; every string under each is page text). Both sides are compared lowercased, with curly quotes straight, dashes as "-" and whitespace runs as one space, then once more as their letters and digits alone; a quote under ${QUOTE_MIN_CHARS} characters is not checked. \`{"predicate": "quote_missing", "path": "answer.evidence", "field": "quote", "pages": ["page"]}\` on an escalate hands back an answer quoting text no fetched page holds. Check quotes with it, never with a judge or an \`ask\``,
25
+ not: "holds when `of`, one mechanical predicate (never `ask`), does not; `{\"predicate\": \"not\", \"of\": {\"predicate\": \"field_type\", \"path\": \"score\", \"type\": \"number\"}}` holds when score is absent or not a finite number",
26
+ ask: "a yes/no question for the host's judge: `instructions` is the question, `state` what it sees (default: the whole state), `criteria` optional {true, false} descriptions; holds when the yes-probability is at least `gte` (in (0.5, 1], default 0.6)",
27
+ };
28
+ function nodeFieldLines() {
29
+ return WORKFLOW_NODE_KINDS.map((kind) => `- ${code(kind)}: ${list(NODE_FIELDS[kind].filter((field) => field !== "node"))}`).join("\n");
30
+ }
31
+ function predicateLines() {
32
+ return WORKFLOW_PREDICATES.map((name) => `- ${code(name)} {${PREDICATE_FIELDS[name].join(", ")}}: ${PREDICATE_SHAPES[name]}`).join("\n");
33
+ }
34
+ const LANGUAGE = `You author AgentRun workflows: JSON documents the AgentRun interpreter runs.
35
+ Deliver the complete JSON document the way your host asks; never deliver prose, a file name or a fragment. Make the smallest workflow that satisfies the request. A candidate runs nothing until its host accepts it, and an accepted candidate is not activated by acceptance.
36
+
37
+ ## Document
38
+
39
+ A workflow is {"v":2,"name","schemas","input"?,"output","root"}.
40
+ - ${code("schemas")} maps ids to inline JSON Schema objects. Every schema id a node, ${code("input")} or ${code("output")} names must exist there. Inside a schema, reference a catalog schema or an inline definition only as {"$ref":"#/definitions/<id>"}. A ${code("pattern")} must not backtrack exponentially: no repeat or optional part inside a repeat that can match the same text (${code("(a+)+")}, ${code("(a?a?)+")}, ${code("(\\w+\\s?)*")}), no unbounded repeat of alternatives that start alike (${code("(a|ab)*")}), no backreference; validation refuses one.
41
+ - The input contract: the run starts from the input object and nothing else. ${code("input.schemaId")}, when present, is enforced before the first node. A node may read only input keys and keys an earlier node wrote.
42
+ - ${code("output.schemaId")} validates the final value; ${code("output.path")} selects it from state and must name an input key or a key an earlier node wrote.
43
+ - State is one object. Each step writes its result under one key: its ${code("as")}, or, for an agent, decide, extract or code node without ${code("as")}, its label. A report writes ${code("report_markdown")}. A code node without ${code("as")} that returns an object merges that object's top-level fields instead.
44
+ - Keys that hold a ${code("$")} are engine-owned: ${code("$host")} (host state), ${code("<as>$answers")} (raw judge answers and confidences) and ${code("<as>$verify")} (verifier results). Read them; never write one. No ${code("as")} may hold a ${code("$")}, and neither may the label of an agent, decide, extract or code node without ${code("as")}.
45
+ - ${code("{dot.path}")} placeholders are replaced from state in ${code("state")} maps (including ${code("verify.state")} and ${code("ask.state")}), call ${code("args")}, ${code("input")}, ${code("env")} and ${code("produces")}, a child workflow's ${code("input")}, and ${code("escalate.summary")}; ${code("pick")} and ${code("sift")} ${code("describe")} templates also see ${code("{item...}")}. A placeholder that is the whole string keeps its value's type. Every key a state map, call or child input interpolates must be produced upstream, except through a whole-string placeholder marked optional, such as ${code("\"{draft?}\"")}: it is null while its path is absent (a loop's first pass, before the step that writes it ran), and the path's value once present. Only a whole string may be marked. ${code("instructions")}, ${code("code")} and ${code("command")} are literal and never interpolated.
46
+
47
+ ## Node kinds
48
+
49
+ This is the complete set. Each kind accepts exactly these fields; any other field is an error.
50
+ ${nodeFieldLines()}
51
+
52
+ Every kind also accepts ${code("metadata")}, an object the host owns and the engine never reads; set only the keys the host addendum names.
53
+
54
+ ### Generative nodes: ${GENERATIVE_NODE_KINDS.join(", ")}
55
+
56
+ Each runs one adapter session. A kind is a preset (its duty, default effort and model tier), not a capability limit:
57
+ - ${code("extract")} transcribes facts already present in its input into ${code("out")}: faithfully, null for an absent field, nothing invented, no judgment.
58
+ - ${code("decide")} judges what is already in state.
59
+ - ${code("agent")} gathers new evidence with its tools.
60
+ - ${code("report")} renders the final record as the deliverable prose. It has no ${code("out")} or ${code("as")}: it writes ${code("report_markdown")}.
61
+
62
+ Their fields:
63
+ - ${code("instructions")} (required, non-empty) states the node's duty as literal prose. The node receives ${code("state")} (an interpolated map) or, without it, the accumulated state as its JSON input; refer to keys by name.
64
+ - ${code("out")} names the schema the submission must satisfy; the value lands at ${code("as")}.
65
+ - ${code("requires")} lists state paths that must hold evidence before the node runs, each produced upstream: missing values, null, blank strings, empty arrays and empty objects stop the run; ${code("false")} and ${code("0")} pass.
66
+ - ${code("tools")} names tools the host offers. ${code("[]")} means no tools; omitting ${code("tools")} offers every tool the host allows. Never name a tool the host did not offer.
67
+ - ${code("effort")} is ${alternatives(EFFORT_LEVELS)}; ${code("thinking")} is ${alternatives(THINKING_LEVELS)} (never off); ${code("tier")} is ${alternatives(MODEL_TIERS)}. They are requests to the host: resource ceilings are the host's. A node that names no ${code("thinking")} thinks at medium, unless its host sets another level.
68
+ - An ${code("agent")} node may carry ${code("budget_usd")}, the most it asks to spend in dollars (above 0), which the host caps by what it has left; ${code("max_turns")}, a positive integer, the most turns it asks its host for per attempt, which the host applies within its own cap and refuses above it (the engine enforces nothing, and naming it changes the workflow's digest); and ${code("context")}, ${alternatives(AGENT_CONTEXTS)}: ${code("fresh")} (the default) sees only its instructions and state; ${code("fork")} asks the host to start it from the caller's transcript, which a host refuses where it has none.
69
+ - ${code("sopSection")} names one heading of the host's SOP, or a list of them, as the exact text after "## ". The node receives those sections verbatim.
70
+ - ${code("verify")} reviews a submission before it is accepted: {"out": a question schema with at least one boolean question, "state"?, "maxDrives"?: an integer >= 1 (default 2, no maximum), "override"?: {"below": a number in (0, 1), default 0.3}}. A boolean question named after a submission field doubts that field when its yes-probability is below ${code("override.below")}; any other boolean question is a requirement met at 0.5. A rejected submission returns to the same session with the reasons.
71
+ - When the workflow has a report, no decide or extract ${code("out")} schema carries ${code("report_markdown")}.
72
+
73
+ ### Terminal nodes: report and artifact
74
+
75
+ A workflow has at most one terminal node, a ${code("report")} or an ${code("artifact")}, and it is the last step of the root chain. No terminal node sits inside a map, loop, parallel branch, route branch or child workflow.
76
+ - An ${code("artifact")} of type ${PROSE_ARTIFACT_TYPES.map((type) => code(type)).join(" or ")} is the report writer: give it the report's fields.
77
+ - Any other ${code("artifact")} type names a file: ${code("path")} is the workspace-relative file an earlier shell call declared in ${code("produces")}, and the node has no model fields (${list(["instructions", "state", "sopSection", "tools", "effort", "thinking"])}).
78
+
79
+ ### Judgment nodes: ${JUDGMENT_NODE_KINDS.join(", ")}
80
+
81
+ Typed questions answered by the host's judge in one request each: no tools, no session, no ${code("sopSection")}.
82
+ - A question schema is a flat object. Each property's ${code("description")} is its question. A boolean yields a yes-probability; a string enum (at most ${SYSTEM_ONE_LIMITS.maxChoiceOptions} options, optional per-option ${code("criteria")}) yields a choice; an integer with ${code("criteria")}: [level descriptions] (${SYSTEM_ONE_LIMITS.minScoreLevels} to ${SYSTEM_ONE_LIMITS.maxScoreLevels} levels, minimum 0, maximum the last level index) yields a score. Nothing else is a question.
83
+ - ${code("judge")}: a non-empty ${code("state")} map, ${code("out")} (a question schema) and ${code("as")}. The decoded value lands at ${code("as")}, the raw answers at ${code("<as>$answers")}.
84
+ - ${code("pick")}: ${code("itemsPath")}, ${code("describe")} (the option text per item, such as "{item.name}"), ${code("instructions")} (the one question) and ${code("as")}; ${code("allowNone")} adds a none-of-these option. The result is {index, item, none, option}.
85
+ - ${code("sift")}: ${code("itemsPath")}, ${code("out")} (a question schema asked of every item; the host splits the items across requests when they exceed its limits) and ${code("as")}. ${code("keep")} {path: a question id or <id>.confidence, never a choice, gte?} keeps passing items, in order, at ${code("<as>.items")}.
86
+ - ${code("route")} runs one of 2 or more named ${code("branches")}. Jev chooses: a non-empty ${code("state")} map, ${code("instructions")} (the one question) and up to ${SYSTEM_ONE_LIMITS.maxChoiceOptions} branches, each {criteria?, body}; ${code("unsure")} {branch, gte: a number in (0, 1]} takes that branch when the choice's confidence is below ${code("gte")}. Or the workflow already holds the choice: ${code("valuePath")} names the state string that is the branch, each branch is {body}, no question is asked, and ${code("otherwise")} (a branch) takes a missing or unknown name, which otherwise fails; a non-string fails. ${code("as")} records the choice.
87
+ - A decoded boolean is true at yes-probability 0.5. To hold a different threshold, read ${code("<as>$answers.answers.<id>.noul")} in a code node.
88
+ - ${code("images")} {token: reference} sends images with a decision (judge, pick, sift, a route Jev chooses, ask). Each token, such as "<page1>", must appear literally in the node's ${code("state")} or in a question's text; each reference is written as a state value is, such as "{item.pages.0.image}", and must resolve to an image path the host can read. Only a provider that takes image input answers such a node. Pass images by reference, never their bytes in state.
89
+ - Inside a ${code("map")} with ${code("onItemFailure")} ${code("collect")}, a decision whose provider fails (rate limit, HTTP error, invalid answer, timeout) fails that item, and one sent whose outcome was lost, or one the provider refused, ends the item as a row marked ${code("needs_review")}; the other items go on.
90
+
91
+ ### Control nodes
92
+
93
+ - ${code("chain")}: non-empty ${code("steps")}, run in order.
94
+ - ${code("map")}: ${code("itemsPath")} (an upstream list), ${code("body")} and ${code("as")}. The body sees ${code("item")} and ${code("item_index")}; ${code("maxConcurrency")} is a positive integer (default 4); ${code("resultPath")} selects one path from each completed item's state. Without ${code("resultPath")}, and with no ${code("as")} in the body, each item's result is its whole state, the mapped list included: set ${code("resultPath")} (or an ${code("as")} in the body) for a large map; the validator warns. A map takes at most 10,000 items, and items × the state's JSON size at most 256 Mi characters (each item runs on its own copy of the state); past either it fails before any item runs. ${code("onItemFailure")} is ${code("stop")} (default: the first failing item stops the map and the run) or ${code("collect")}. With ${code("collect")}, an item whose node fails (a call that failed after its retries, an agent that delivered no record, output that does not match its schema, a failed check) ends as {item_index, label, code, message} in the list at ${code("failedAs")}, the other items finish, and ${code("as")} stays aligned with the items: ${code("as[i]")} is item i's result, or ${code("null")} when item i failed. Filter the nulls explicitly if only successes are wanted. Gate on ${code("failedAs")} with ${code("escalate")} or a code node; never let failures pass silently. A crash, a cancel, an ${code("escalate")} inside the item or an effect whose outcome is unknown is never collected.
95
+ - ${code("parallel")}: at least two ${code("branches")}, each starting from the state before the parallel node. Branches write disjoint keys and never read a sibling's writes.
96
+ - ${code("loop")}: ${code("body")}, ${code("until")} (a predicate) and an integer ${code("maxIters")} of at least 1 (no maximum), optionally an integer ${code("expect_iters")} of at least 1 (priced passes). At the bound the state passes through with ${code("until")} unmet; follow the loop with an escalate or gate on that condition.
97
+ - ${code("escalate")}: ${code("when")} (a predicate), and non-empty ${code("kind")}, ${code("stage")} and ${code("summary")}. When the predicate holds the run stops without output and returns the escalation with its interpolated summary.
98
+ - ${code("workflow")}: ${code("label")}, ${code("workflow")} (a complete inline child), ${code("input")} (an object, interpolated, the child's entire initial state), ${code("out")} (a parent schema checked against the child's output) and ${code("as")}. The child declares ${code("input.schemaId")} in its own schemas and contains no report or artifact.
99
+ - ${code("code")}: ${code("code")} is one synchronous function expression such as "(s) => ({ total: s.items.length })". It receives the full state; return new values and never mutate it. ${code("Date")}, ${code("Promise")}, timers, ${code("fetch")}, ${code("require")}, ${code("process")}, ${code("Function")} and ${code("globalThis")} are unavailable. It is trusted host JavaScript, not a sandbox. Use code for typed-state mechanics, never to read meaning from prose.
100
+ - ${code("call")}: one side effect with no model in the loop. ${code("via")} is ${alternatives(CALL_TRANSPORTS)}; ${code("as")} and ${code("deadline_s")} (a finite number greater than 0, no maximum) are required — an unbounded effect is how a stalled provider becomes a stalled job.
101
+ - ${code("via: tool")} takes ${code("tool")} (a host tool address), ${code("args")} (an object) and ${code("out")} (the tool's result schema).
102
+ - ${code("via: executor")} takes ${code("code")} (a body that returns its JSON result and uses only ${code("tools")} and ${code("input")}), ${code("input")} and ${code("out")}.
103
+ - ${code("via: shell")} takes ${code("command")} (literal) and ${code("env")} (UPPER_CASE names to strings, interpolated by value; the way long values reach a command). Its result has the fixed shape {code, stdout, stderr, truncated?}: no ${code("out")}. Only a shell call may declare ${code("produces")} (workspace-relative files, checked after the effect).
104
+ - ${code("retry")} {attempts: an integer >= 1, backoff_s?: a number >= 0, on?: [${[...CALL_RETRY_CLASSES, ...EFFECT_FAILURE_CODES].join(", ")}]}. ${code("where")} accepts only "sandbox".
105
+ - ${code("poll")} {until, fail_when?, interval_s: >= 0.1 (a busy-loop guard), deadline_s: at least the call's deadline_s (no maximum)} repeats the call until ${code("until")} holds on its own result; ${code("fail_when")} fails it at once. Both are mechanical predicates whose paths are relative to the result and lie in its declared shape.
106
+ - Validation and dry runs never perform effects: they synthesize the declared result, and a shell result's stdout is "{}".
107
+
108
+ ## Predicates
109
+
110
+ ${code("loop.until")} and ${code("escalate.when")} take one of these; ${code("poll")} takes only the first ${MECHANICAL_PREDICATES.length}. Each path or key reads a state value an input or an earlier node produced.
111
+ A predicate is one JSON object that names itself in its ${code("predicate")} field beside its own fields, for example ${code('{"predicate": "field_true", "path": "review.approved"}')}.
112
+ ${predicateLines()}
113
+
114
+ ## Authority
115
+
116
+ - Use only tools the host names. Never invent a tool, capability, evidence source or successful check.
117
+ - Code, call and artifact nodes need the host's explicit authorization for executable candidates.
118
+ - When the host supplies rubric sections, they are authoritative source text: every generative node's ${code("sopSection")} lists all of them, a merged judgment inherits the union of its parents' sections, and policy is never paraphrased into instructions. Judgment nodes, ${code("ask")} predicates and ${code("verify")} clauses are then refused until the host reviews a separate question contract.
119
+ - Acceptance checks are the host's. Never change a check, fixture or threshold to pass.
120
+ - Bound loops and parallelism. Uncertainty escalates or takes an explicit fallback such as ${code("route.unsure")} or a threshold gate.
121
+ - Ask Jev only what needs judgment; compute what is certain in code. Once a judge and code have decided, route by ${code("valuePath")}: asking a route again can contradict that decision.
122
+
123
+ ## Example
124
+
125
+ {"v":2,"name":"summarize","schemas":{"Input":{"type":"object","properties":{"text":{"type":"string","minLength":1}},"required":["text"],"additionalProperties":false},"Result":{"type":"object","properties":{"summary":{"type":"string"}},"required":["summary"],"additionalProperties":false}},"input":{"schemaId":"Input"},"output":{"schemaId":"Result","path":"result"},"root":{"node":"extract","label":"summarize","instructions":"Summarize the text field faithfully. Invent nothing.","out":"Result","as":"result","requires":["text"],"tools":[]}}`;
126
+ /** The host section of the contract, or "" without a host. */
127
+ export function renderAuthorHostAddendum(host) {
128
+ if (!host)
129
+ return "";
130
+ const lines = [`## Host: ${host.name}`, "", "These host rules add to the language above; they never change it."];
131
+ if (host.initialState && Object.keys(host.initialState).length) {
132
+ lines.push(`- The run starts with exactly these state keys: ${Object.entries(host.initialState).map(([key, description]) => `${code(key)} (${description})`).join("; ")}. Any other key must be written by a node before it is read.`);
133
+ }
134
+ if (host.outputTypes && Object.keys(host.outputTypes).length) {
135
+ const types = Object.entries(host.outputTypes).map(([type, spec]) => `${code(type)} (${spec.kind === "prose" ? "prose: the report writer, with the report's fields" : `file: ${code("path")} names the file an earlier shell call produced`}; ${spec.description})`);
136
+ lines.push(`- A terminal artifact's ${code("type")} is one of: ${types.join("; ")}.`);
137
+ }
138
+ if (host.metadataKeys && Object.keys(host.metadataKeys).length) {
139
+ lines.push(`- A node's ${code("metadata")} may carry only these keys: ${Object.entries(host.metadataKeys).map(([key, description]) => `${code(key)} (${description})`).join("; ")}.`);
140
+ }
141
+ if (host.nodeKinds)
142
+ lines.push(`- This host runs only these node kinds: ${list(host.nodeKinds)}. Author no other kind.`);
143
+ for (const rule of host.rules ?? [])
144
+ lines.push(`- ${rule}`);
145
+ return lines.join("\n");
146
+ }
147
+ /** The rendered author contract and the sha256 of exactly that text. A host records the digest with every
148
+ * candidate it authors, so a workflow names the contract that wrote it. */
149
+ export function renderAuthorContract(options = {}) {
150
+ const addendum = renderAuthorHostAddendum(options.host);
151
+ const text = addendum ? `${LANGUAGE}\n\n${addendum}` : LANGUAGE;
152
+ return { text, sha256: createHash("sha256").update(text).digest("hex") };
153
+ }
154
+ /** The one author contract: the language every host shares, then the host's addendum when one is supplied. */
155
+ export function authorContract(options = {}) {
156
+ return renderAuthorContract(options).text;
157
+ }
158
+ const record = (value) => isRecord(value) ? value : undefined;
159
+ /** Author policy over a candidate, checked before validation so a refused candidate never evaluates code. */
160
+ export function candidatePolicyErrors(candidate, options) {
161
+ const errors = [];
162
+ const sections = Object.keys(options.rubricSections ?? {});
163
+ const kinds = options.host?.nodeKinds ? new Set(options.host.nodeKinds) : undefined;
164
+ const outputTypes = options.host?.outputTypes;
165
+ const visit = (value) => {
166
+ const node = record(value);
167
+ if (!node)
168
+ return;
169
+ const kind = node.node;
170
+ if (kinds && !kinds.has(String(kind)))
171
+ errors.push(`${String(node.label ?? kind)}: this host does not run ${String(kind)} nodes`);
172
+ if (!options.allowExecutableCandidates && ["code", "call", "artifact"].includes(String(kind)) && !(kind === "call" && node.via === "tool" && typeof node.tool === "string" && options.allowedEffectTools?.includes(node.tool)))
173
+ errors.push(`${kind} requires allowExecutableCandidates`);
174
+ // `budget` on an agent is accepted for older documents and never read: an author writes budget_usd.
175
+ if (kind === "agent" && Object.hasOwn(node, "budget"))
176
+ errors.push(`${String(node.label ?? kind)}: budget is not read; declare budget_usd, the dollars the node asks to spend`);
177
+ // A route by valuePath asks no question, so like code it carries no rubric.
178
+ const asksJev = JUDGMENT_NODE_KINDS.includes(String(kind)) && !(kind === "route" && node.valuePath !== undefined);
179
+ if (sections.length && asksJev)
180
+ errors.push(`${String(kind)} cannot carry supplied SOP sections; use an LLM node with sopSection`);
181
+ const llm = GENERATIVE_NODE_KINDS.includes(String(kind));
182
+ const predicate = kind === "loop" ? record(node.until) : kind === "escalate" ? record(node.when) : undefined;
183
+ if (sections.length && (predicate?.predicate === "ask" || (llm && node.verify !== undefined)))
184
+ errors.push("Semantic predicates and verify clauses require a separately reviewed question contract when rubric sections are supplied");
185
+ const hostType = kind === "artifact" && typeof node.type === "string" && outputTypes && Object.hasOwn(outputTypes, node.type) ? outputTypes[node.type] : undefined;
186
+ if (kind === "artifact" && outputTypes && !hostType)
187
+ errors.push(`${String(node.label ?? kind)}: artifact type ${JSON.stringify(node.type)} is not one of this host's output types`);
188
+ const proseArtifact = kind === "artifact" && (PROSE_ARTIFACT_TYPES.includes(node.type) || hostType?.kind === "prose");
189
+ if (llm || proseArtifact) {
190
+ const included = Array.isArray(node.sopSection) ? node.sopSection : [node.sopSection];
191
+ for (const section of sections)
192
+ if (!included.includes(section))
193
+ errors.push(`${String(node.label)} must include rubric section ${section}`);
194
+ }
195
+ switch (kind) {
196
+ case "chain":
197
+ if (Array.isArray(node.steps))
198
+ node.steps.forEach(visit);
199
+ break;
200
+ case "parallel":
201
+ if (Array.isArray(node.branches))
202
+ node.branches.forEach(visit);
203
+ break;
204
+ case "map":
205
+ case "loop":
206
+ visit(node.body);
207
+ break;
208
+ case "route": {
209
+ const branches = record(node.branches);
210
+ if (branches)
211
+ Object.values(branches).forEach(branch => visit(record(branch)?.body));
212
+ break;
213
+ }
214
+ case "workflow":
215
+ visit(record(node.workflow)?.root);
216
+ break;
217
+ }
218
+ };
219
+ visit(record(candidate)?.root);
220
+ return errors;
221
+ }
222
+ /** The interpreter's view of a workflow written in a host's vocabulary: an artifact of a declared prose output
223
+ * type becomes the report writer it is. Validate and run this view; retain and digest the authored bytes. With
224
+ * `normalizeType`, an artifact's type is first mapped to the host's name for it. */
225
+ export function applyHostOutputTypes(candidate, host, options = {}) {
226
+ const prose = new Set(Object.entries(host?.outputTypes ?? {}).filter(([, spec]) => spec.kind === "prose").map(([type]) => type));
227
+ if (!prose.size)
228
+ return candidate;
229
+ // With a normaliser the host's answer is the name: null or undefined matches no type, the exact one included.
230
+ const nameOf = (type) => typeof type === "string" && options.normalizeType ? options.normalizeType(type) : type;
231
+ const visit = (node) => {
232
+ if (!node || typeof node !== "object")
233
+ return node;
234
+ if (node.node === "artifact" && prose.has(nameOf(node.type)))
235
+ return { ...node, type: "report" };
236
+ if (node.node === "chain")
237
+ return { ...node, steps: (node.steps || []).map(visit) };
238
+ if (node.node === "parallel")
239
+ return { ...node, branches: (node.branches || []).map(visit) };
240
+ if (node.node === "map" || node.node === "loop")
241
+ return { ...node, body: visit(node.body) };
242
+ if (node.node === "route")
243
+ return { ...node, branches: Object.fromEntries(Object.entries(node.branches || {}).map(([name, branch]) => [name, { ...branch, body: visit(branch?.body) }])) };
244
+ // Unlike desugarWorkflow, this does not descend into a child workflow: a child may not hold an artifact node
245
+ // (validateWorkflow rejects it, see containsReportNode), so there is nothing for the prose-type rewrite to reach there.
246
+ return node;
247
+ };
248
+ return { ...candidate, root: visit(candidate.root) };
249
+ }
250
+ /** Author one workflow and retain every candidate with its review in a new directory under `outputDir`.
251
+ * Policy, validation and host acceptance review each submission; a rejection returns to the same session. */
252
+ export async function authorWorkflow(options) {
253
+ if (!options.request.trim())
254
+ throw new Error("Workflow request is required");
255
+ const maxCandidates = options.maxCandidates ?? 4;
256
+ if (!Number.isSafeInteger(maxCandidates) || maxCandidates < 1)
257
+ throw new Error("maxCandidates must be a positive integer");
258
+ const inputKeys = options.inputKeys ?? (options.host?.initialState ? Object.keys(options.host.initialState) : []);
259
+ const contract = renderAuthorContract({ host: options.host });
260
+ const directory = resolve(options.outputDir, `candidate-${randomUUID()}`);
261
+ await mkdir(directory, { recursive: true });
262
+ await writeFile(join(directory, "request.json"), JSON.stringify({ request: options.request, host: options.host?.name ?? null, contractSha256: contract.sha256, inputKeys, rubricSections: options.rubricSections ?? {}, allowExecutableCandidates: options.allowExecutableCandidates ?? false, maxCandidates }, null, 2), { flag: "wx" });
263
+ let candidates = 0;
264
+ let acceptedPath;
265
+ let accepted;
266
+ const checks = options.acceptance ? "structural-and-host" : "structural";
267
+ try {
268
+ await options.runNode({
269
+ kind: "agent", label: "author-workflow", tools: [], signal: options.signal,
270
+ system: [contract.text, "Deliver each candidate as the value of the submit tool. A rejected candidate comes back with its errors; repair it in the same session.", `Executable candidates authorized: ${options.allowExecutableCandidates ?? false}.`, `All supplied rubric sections (authoritative): ${JSON.stringify(options.rubricSections ?? {})}`],
271
+ user: `${options.request}\nAvailable input keys: ${JSON.stringify(inputKeys)}`,
272
+ schema: { type: "object", additionalProperties: true },
273
+ async review(value) {
274
+ candidates++;
275
+ if (candidates > maxCandidates)
276
+ throw new Error(`Candidate limit exceeded: ${maxCandidates}`);
277
+ const number = String(candidates).padStart(3, "0");
278
+ const candidatePath = join(directory, `${number}.json`);
279
+ await writeFile(candidatePath, JSON.stringify(value, null, 2), { flag: "wx" });
280
+ const errors = candidatePolicyErrors(value, options);
281
+ if (!errors.length) {
282
+ try {
283
+ // executeCode: false — a candidate's code is syntax-checked here, never run, so a candidate runs nothing
284
+ // until its host accepts it. Runs and dry runs after acceptance still probe the code.
285
+ const verdict = validateWorkflow(applyHostOutputTypes(value, options.host), { inputKeys, executeCode: false });
286
+ if (!verdict.ok)
287
+ errors.push(...verdict.errors);
288
+ }
289
+ catch (error) {
290
+ errors.push(`Invalid workflow: ${error instanceof Error ? error.message : String(error)}`);
291
+ }
292
+ }
293
+ if (!errors.length && options.acceptance)
294
+ errors.push(...await options.acceptance(applyHostOutputTypes(structuredClone(value), options.host)));
295
+ await writeFile(join(directory, `${number}.review.json`), JSON.stringify({ accepted: !errors.length, checks, errors }, null, 2), { flag: "wx" });
296
+ if (errors.length)
297
+ return { accepted: false, message: errors.join("\n") };
298
+ acceptedPath = candidatePath;
299
+ accepted = structuredClone(value);
300
+ return { accepted: true };
301
+ },
302
+ });
303
+ // The result is the candidate review accepted, never whatever the adapter returns afterwards.
304
+ if (!acceptedPath || !accepted)
305
+ throw new Error("Author returned without a retained accepted candidate");
306
+ const workflow = accepted;
307
+ await writeFile(join(directory, "result.json"), JSON.stringify({ status: "candidate", path: acceptedPath, candidates, contractSha256: contract.sha256 }, null, 2), { flag: "wx" });
308
+ return { workflow, path: acceptedPath, directory, candidates, checks, contractSha256: contract.sha256 };
309
+ }
310
+ catch (error) {
311
+ await writeFile(join(directory, "result.json"), JSON.stringify({ status: "failed", candidates, contractSha256: contract.sha256, message: error instanceof Error ? error.message : String(error) }, null, 2), { flag: "wx" });
312
+ throw error;
313
+ }
314
+ }
315
+ const skillRoot = new URL("../skills/author/", import.meta.url);
316
+ /** The absolute directory of the packaged author skill (the one holding SKILL.md). */
317
+ export function authorSkillDirectory() {
318
+ return fileURLToPath(skillRoot);
319
+ }
320
+ /** A reference shipped with the author skill, for hosts without file-reading tools. */
321
+ export function loadAuthorReference(name) {
322
+ return readFileSync(new URL(`references/${name}.md`, skillRoot), "utf8");
323
+ }
324
+ /** The whole skill as one text: SKILL.md, its references and its JSON examples. */
325
+ export function loadAuthorSkillBundle() {
326
+ const files = ["SKILL.md", "references/language.md", "references/workflow-format.md", "references/jev-decisions.md",
327
+ ...readdirSync(new URL("examples/", skillRoot)).filter(name => name.endsWith(".json")).sort().map(name => `examples/${name}`)];
328
+ return files.map(path => `\n--- ${path} ---\n${readFileSync(new URL(path, skillRoot), "utf8")}`).join("\n");
329
+ }
package/dist/authoring.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { runWorkflow, validateWorkflow, resolveSchemaForWorkflow, WorkflowInvalidError, } from "./workflow.js";
2
2
  import { isDeepStrictEqual, types as utilTypes } from "node:util";
3
3
  import { assertZodJsonContract } from "./zod-json-contract.js";
4
+ import { isRecord } from "./record.js";
4
5
  const authoredWorkflows = new WeakSet();
5
6
  export class WorkflowSchemaConversionError extends Error {
6
7
  schemaId;
@@ -39,7 +40,7 @@ export function defineWorkflow(definition) {
39
40
  }
40
41
  }
41
42
  }
42
- if (!schema || typeof schema !== "object" || Array.isArray(schema))
43
+ if (!isRecord(schema))
43
44
  throw new Error("expected a JSON Schema object");
44
45
  Object.defineProperty(schemas, id, { value: cloneJson(schema), enumerable: true, writable: true, configurable: true });
45
46
  }
@@ -57,7 +58,7 @@ export function defineWorkflow(definition) {
57
58
  });
58
59
  const result = validateWorkflow(document);
59
60
  if (!result.ok)
60
- throw new WorkflowInvalidError(document.name, result.errors);
61
+ throw new WorkflowInvalidError(document.name, result.errors, result.issues);
61
62
  const inputSchema = resolveSchemaForWorkflow(document, document.schemas[definition.input]);
62
63
  if (!objectContract(inputSchema)) {
63
64
  throw new WorkflowSchemaConversionError(definition.input, new Error("workflow input must be constrained to JSON objects; declare type: object or object-only schema alternatives"));
@@ -67,7 +68,7 @@ export function defineWorkflow(definition) {
67
68
  return document;
68
69
  }
69
70
  function objectContract(value) {
70
- if (!value || typeof value !== "object" || Array.isArray(value))
71
+ if (!isRecord(value))
71
72
  return false;
72
73
  const schema = value;
73
74
  if (schema.type === "object" || Array.isArray(schema.type) && schema.type.length === 1 && schema.type[0] === "object")
@@ -98,7 +99,7 @@ function copyJson(value, ancestors, budget, depth) {
98
99
  return value;
99
100
  if (typeof value === "number" && Number.isFinite(value))
100
101
  return value;
101
- if (typeof value !== "object" || value === null)
102
+ if (typeof value !== "object")
102
103
  throw new Error("workflow documents must contain only finite JSON values");
103
104
  if (utilTypes.isProxy(value))
104
105
  throw new Error("workflow documents must not contain proxies");
package/dist/cli.js CHANGED
@@ -6,14 +6,15 @@ import { runWorkflow, validateWorkflow } from "./workflow.js";
6
6
  import { dryRunWorkflow } from "./dry-run.js";
7
7
  import { demoScenarios, runTriageDemo, supportTriage } from "./demo.js";
8
8
  import { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
9
+ import { isRecord } from "./record.js";
9
10
  const help = `AgentRun DSL — build, test, and run agent workflows
10
11
 
11
- agentrun demo [--scenario billing|technical|ambiguous] [--json]
12
- agentrun example [file.json] Write the demo workflow (never overwrite)
13
- agentrun inspect workflow.json [--json] Show structure without executing code
14
- agentrun validate workflow.json [input.json] --trusted
15
- agentrun dry-run workflow.json [input.json] --trusted
16
- agentrun run workflow.json input.json --trusted
12
+ agentrun-dsl demo [--scenario billing|technical|ambiguous] [--json]
13
+ agentrun-dsl example [file.json] Write the demo workflow (never overwrite)
14
+ agentrun-dsl inspect workflow.json [--json] Show structure without executing code
15
+ agentrun-dsl validate workflow.json [input.json] --trusted
16
+ agentrun-dsl dry-run workflow.json [input.json] --trusted [--strict]
17
+ agentrun-dsl run workflow.json input.json --trusted
17
18
 
18
19
  demo runs the real interpreter with scripted judgments, without a key or network.
19
20
  run supports deterministic workflows; use the JavaScript API to supply agent,
@@ -22,6 +23,8 @@ during validation and running. Only use workflows you trust; this is not a sandb
22
23
  validate checks a supplied input against the workflow's input contract.
23
24
  dry-run uses supplied input, or synthesizes it from the declared input schema.
24
25
  Without an input schema, dry-run starts with an empty input object.
26
+ dry-run exits 1 when a check fails. A check that could not run (status not_run, the
27
+ reasons under skipped) exits 0 unless --strict is given, which makes it exit 3.
25
28
  `;
26
29
  async function main(args) {
27
30
  const [command] = args;
@@ -33,7 +36,7 @@ async function main(args) {
33
36
  let scenario = "billing";
34
37
  let scenarioProvided = false;
35
38
  let json = false;
36
- const usage = "Usage: agentrun demo [--scenario billing|technical|ambiguous] [--json]";
39
+ const usage = "Usage: agentrun-dsl demo [--scenario billing|technical|ambiguous] [--json]";
37
40
  for (let i = 1; i < args.length; i++) {
38
41
  const arg = args[i];
39
42
  if (arg === "--json") {
@@ -77,23 +80,24 @@ async function main(args) {
77
80
  if (command === "inspect") {
78
81
  const positional = args.slice(1).filter(arg => arg !== "--json");
79
82
  if (positional.length !== 1 || positional[0].startsWith("--"))
80
- throw new Error("Usage: agentrun inspect workflow.json [--json]");
83
+ throw new Error("Usage: agentrun-dsl inspect workflow.json [--json]");
81
84
  const inspection = inspectWorkflow(JSON.parse(await readFile(resolve(positional[0]), "utf8")));
82
85
  console.log(args.includes("--json") ? JSON.stringify(inspection, null, 2) : formatWorkflowTree(inspection));
83
86
  return;
84
87
  }
85
88
  if (!["validate", "dry-run", "run"].includes(command))
86
- throw new Error(`Unknown command "${command}". Use agentrun --help.`);
89
+ throw new Error(`Unknown command "${command}". Use agentrun-dsl --help.`);
87
90
  if (!args.includes("--trusted"))
88
91
  throw new Error("Pass --trusted only after reviewing the workflow. Authored JavaScript may execute, including during validation.");
89
- const positional = args.slice(1).filter(arg => arg !== "--trusted");
92
+ const strict = command === "dry-run" && args.includes("--strict");
93
+ const positional = args.slice(1).filter(arg => arg !== "--trusted" && !(strict && arg === "--strict"));
90
94
  const unknown = positional.find(arg => arg.startsWith("--"));
91
95
  if (unknown)
92
- throw new Error(`Unknown option "${unknown}". Use agentrun --help.`);
96
+ throw new Error(`Unknown option "${unknown}". Use agentrun-dsl --help.`);
93
97
  if (!positional[0])
94
98
  throw new Error("Provide a workflow JSON file.");
95
99
  if (positional.length > 2)
96
- throw new Error(`Usage: agentrun ${command} workflow.json ${command === "run" ? "input.json" : "[input.json]"} --trusted`);
100
+ throw new Error(`Usage: agentrun-dsl ${command} workflow.json ${command === "run" ? "input.json" : "[input.json]"} --trusted${command === "dry-run" ? " [--strict]" : ""}`);
97
101
  if (command === "run" && !positional[1])
98
102
  throw new Error("Provide an input JSON file.");
99
103
  const workflow = JSON.parse(await readFile(resolve(positional[0]), "utf8"));
@@ -106,7 +110,7 @@ async function main(args) {
106
110
  catch (error) {
107
111
  throw new Error(`Cannot read input JSON file "${positional[1]}": ${error instanceof Error ? error.message : String(error)}`);
108
112
  }
109
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
113
+ if (!isRecord(parsed))
110
114
  throw new Error("Input JSON must be an object.");
111
115
  input = parsed;
112
116
  }
@@ -121,6 +125,8 @@ async function main(args) {
121
125
  console.log(JSON.stringify(result, null, 2));
122
126
  if (!result.ok)
123
127
  process.exitCode = 1;
128
+ else if (strict && result.status === "not_run")
129
+ process.exitCode = 3;
124
130
  }
125
131
  else {
126
132
  const result = await runWorkflow(workflow, input, {});
@@ -1,4 +1,29 @@
1
+ /** The denied globals a transform's source names, in DENIED_GLOBALS order: a lexical scan of the source
2
+ * that skips comments, string and template text and regular-expression literals, and ignores a name
3
+ * read as a property (after `.` or `?.`). A name used as an object key or a local binding is still
4
+ * named: the lint refuses rather than guesses. It is a lint for untrusted authors, never a boundary:
5
+ * a host that runs such code isolates it (deps.runCode). */
6
+ export declare function deniedGlobalReferences(src: string): string[];
1
7
  /** Parse the same expression as trusted execution, without evaluating it or calling its body.
2
8
  * Syntax validity does not prove that the expression produces a function or a valid patch. */
3
9
  export declare function compileTransformSyntax(src: string): void;
4
10
  export declare function compileTransform(src: string): (value: any, ctx?: any) => any;
11
+ /** What a code node's script answers (transformScript): the function's value (`undefined: true` for undefined, which
12
+ * JSON has no word for), or the error it threw, in compileTransform's words. */
13
+ export type TransformOutcome = {
14
+ readonly ok: true;
15
+ readonly value?: unknown;
16
+ readonly undefined?: true;
17
+ } | {
18
+ readonly ok: false;
19
+ readonly error: string;
20
+ };
21
+ /**
22
+ * A code node as one script for a JavaScript engine of the host's own, for a host that runs code nodes in an isolated
23
+ * engine (a WebAssembly one) rather than in its own process. The script is a function expression: called with one
24
+ * string, the JSON of `{ state, ctx }`, it builds the function exactly as compileTransform does (the same factory text,
25
+ * denied globals and synchronous checks), calls it once, and returns one string, the JSON of a TransformOutcome. A value
26
+ * JSON can't carry (a BigInt, a cycle, or a function or symbol, which JSON would drop without a word) is an error. It
27
+ * uses only the language itself: no module, no host object, nothing in or out but the two strings.
28
+ */
29
+ export declare function transformScript(src: string): string;