@parcha/agentrun-dsl 0.1.0-beta.15 → 0.1.0-beta.152

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 (75) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +153 -16
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +4 -3
  6. package/dist/author.js +20 -11
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -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 +64 -3
  14. package/dist/decision-receipts.js +50 -8
  15. package/dist/dry-run.d.ts +35 -1
  16. package/dist/dry-run.js +131 -25
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +107 -5
  20. package/dist/graph.js +284 -9
  21. package/dist/index.d.ts +17 -12
  22. package/dist/index.js +16 -10
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +14 -1
  25. package/dist/pattern-screen.d.ts +14 -0
  26. package/dist/pattern-screen.js +451 -0
  27. package/dist/predicates.d.ts +29 -0
  28. package/dist/predicates.js +62 -3
  29. package/dist/record.d.ts +4 -0
  30. package/dist/record.js +6 -0
  31. package/dist/recovery/binding.js +2 -1
  32. package/dist/recovery/call-key.d.ts +0 -4
  33. package/dist/recovery/call-key.js +0 -7
  34. package/dist/recovery/driver.d.ts +59 -24
  35. package/dist/recovery/driver.js +251 -73
  36. package/dist/recovery/frozen-snapshot.d.ts +54 -4
  37. package/dist/recovery/frozen-snapshot.js +44 -14
  38. package/dist/recovery/handoff-receipts.d.ts +0 -35
  39. package/dist/recovery/handoff-receipts.js +2 -44
  40. package/dist/recovery/index.d.ts +4 -8
  41. package/dist/recovery/index.js +4 -7
  42. package/dist/recovery/with-recovery.d.ts +9 -3
  43. package/dist/recovery/with-recovery.js +78 -18
  44. package/dist/submit-envelope.d.ts +9 -0
  45. package/dist/submit-envelope.js +44 -0
  46. package/dist/system-one.d.ts +21 -2
  47. package/dist/system-one.js +96 -18
  48. package/dist/testing/decision-provider.d.ts +32 -0
  49. package/dist/testing/decision-provider.js +183 -0
  50. package/dist/testing/index.d.ts +1 -0
  51. package/dist/testing/index.js +2 -0
  52. package/dist/vocabulary.d.ts +11 -3
  53. package/dist/vocabulary.js +19 -9
  54. package/dist/workflow-shape.d.ts +7 -0
  55. package/dist/workflow-shape.js +116 -70
  56. package/dist/workflow.d.ts +171 -19
  57. package/dist/workflow.js +1063 -399
  58. package/dist/zod-json-contract.js +6 -8
  59. package/package.json +12 -4
  60. package/schema/workflow.schema.json +366 -1
  61. package/skills/author/SKILL.md +6 -1
  62. package/skills/author/references/jev-decisions.md +50 -5
  63. package/skills/author/references/language.md +19 -14
  64. package/dist/recovery/effect-failure.d.ts +0 -34
  65. package/dist/recovery/effect-failure.js +0 -62
  66. package/dist/recovery/handoff-block.d.ts +0 -36
  67. package/dist/recovery/handoff-block.js +0 -148
  68. package/dist/recovery/handoff-digest.d.ts +0 -58
  69. package/dist/recovery/handoff-digest.js +0 -195
  70. package/dist/recovery/handoff-files.d.ts +0 -54
  71. package/dist/recovery/handoff-files.js +0 -162
  72. package/dist/recovery/handoff-redact.d.ts +0 -12
  73. package/dist/recovery/handoff-redact.js +0 -44
  74. package/dist/recovery/handoff.d.ts +0 -44
  75. package/dist/recovery/handoff.js +0 -46
package/dist/author.js CHANGED
@@ -5,7 +5,9 @@ import { fileURLToPath } from "node:url";
5
5
  import { join, resolve } from "node:path";
6
6
  import { validateWorkflow } from "./workflow.js";
7
7
  import { SYSTEM_ONE_LIMITS } from "./system-one.js";
8
- import { WORKFLOW_NODE_KINDS, NODE_FIELDS, WORKFLOW_PREDICATES, PREDICATE_FIELDS, MECHANICAL_PREDICATES, 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";
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";
9
11
  const code = (value) => `\`${value}\``;
10
12
  const list = (values) => values.map(code).join(", ");
11
13
  const alternatives = (values) => values.join("|");
@@ -18,6 +20,9 @@ const PREDICATE_SHAPES = {
18
20
  lt: "holds when the finite number at `path` is below `n`",
19
21
  empty: "holds when the value at `path` is an empty array, an empty string, null or absent",
20
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",
21
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)",
22
27
  };
23
28
  function nodeFieldLines() {
@@ -32,12 +37,12 @@ Deliver the complete JSON document the way your host asks; never deliver prose,
32
37
  ## Document
33
38
 
34
39
  A workflow is {"v":2,"name","schemas","input"?,"output","root"}.
35
- - ${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>"}.
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.
36
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.
37
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.
38
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.
39
- - Keys that begin with ${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 begin with ${code("$")}, and neither may the label of an agent, decide, extract or code node without ${code("as")}.
40
- - ${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. ${code("instructions")}, ${code("code")} and ${code("command")} are literal and never interpolated.
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.
41
46
 
42
47
  ## Node kinds
43
48
 
@@ -59,8 +64,8 @@ Their fields:
59
64
  - ${code("out")} names the schema the submission must satisfy; the value lands at ${code("as")}.
60
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.
61
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.
62
- - ${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.
63
- - 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, 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.
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.
64
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.
65
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.
66
71
  - When the workflow has a report, no decide or extract ${code("out")} schema carries ${code("report_markdown")}.
@@ -80,11 +85,13 @@ Typed questions answered by the host's judge in one request each: no tools, no s
80
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")}.
81
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.
82
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.
83
90
 
84
91
  ### Control nodes
85
92
 
86
93
  - ${code("chain")}: non-empty ${code("steps")}, run in order.
87
- - ${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.
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.
88
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.
89
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.
90
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.
@@ -148,7 +155,7 @@ export function renderAuthorContract(options = {}) {
148
155
  export function authorContract(options = {}) {
149
156
  return renderAuthorContract(options).text;
150
157
  }
151
- const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
158
+ const record = (value) => isRecord(value) ? value : undefined;
152
159
  /** Author policy over a candidate, checked before validation so a refused candidate never evaluates code. */
153
160
  export function candidatePolicyErrors(candidate, options) {
154
161
  const errors = [];
@@ -234,6 +241,8 @@ export function applyHostOutputTypes(candidate, host, options = {}) {
234
241
  return { ...node, body: visit(node.body) };
235
242
  if (node.node === "route")
236
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.
237
246
  return node;
238
247
  };
239
248
  return { ...candidate, root: visit(candidate.root) };
@@ -271,7 +280,9 @@ export async function authorWorkflow(options) {
271
280
  const errors = candidatePolicyErrors(value, options);
272
281
  if (!errors.length) {
273
282
  try {
274
- const verdict = validateWorkflow(applyHostOutputTypes(value, options.host), { inputKeys });
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 });
275
286
  if (!verdict.ok)
276
287
  errors.push(...verdict.errors);
277
288
  }
@@ -301,8 +312,6 @@ export async function authorWorkflow(options) {
301
312
  throw error;
302
313
  }
303
314
  }
304
- /** The packaged author skill's name, as a skill-loading host registers it. */
305
- export const AUTHOR_SKILL_NAME = "agentrun-author";
306
315
  const skillRoot = new URL("../skills/author/", import.meta.url);
307
316
  /** The absolute directory of the packaged author skill (the one holding SKILL.md). */
308
317
  export function authorSkillDirectory() {
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, {});
@@ -8,3 +8,22 @@ export declare function deniedGlobalReferences(src: string): string[];
8
8
  * Syntax validity does not prove that the expression produces a function or a valid patch. */
9
9
  export declare function compileTransformSyntax(src: string): void;
10
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;
package/dist/code-exec.js CHANGED
@@ -136,12 +136,20 @@ export function deniedGlobalReferences(src) {
136
136
  }
137
137
  return DENIED_GLOBALS.filter((name) => found.has(name));
138
138
  }
139
+ const EMPTY_SOURCE = "code transform source must be a non-empty string";
140
+ const ASYNC_FUNCTION = "code transforms are synchronous; async functions are not supported";
141
+ const THENABLE = "code transforms are synchronous; returned a Promise or thenable";
142
+ /** The start of the error a code node's program gives for a value JSON would drop silently (a function, a symbol). */
143
+ const NOT_JSON = "a code node must return JSON data, and its value holds a ";
144
+ /** The factory's body: `src` evaluated once, strict, under the denied globals' parameters. Both compileTransform and
145
+ * transformScript build their function from this one text, so a code node means the same wherever it runs. */
146
+ const factoryBody = (src) => `"use strict";\nconst __fn = (${src});\nif (typeof __fn !== "function") throw new Error("code must evaluate to a single (value) => value function");\nreturn __fn;`;
139
147
  function createTransformFactory(src) {
140
148
  if (typeof src !== "string" || !src.trim())
141
- throw new Error("code transform source must be a non-empty string");
149
+ throw new Error(EMPTY_SOURCE);
142
150
  let factory;
143
151
  try {
144
- factory = new Function(...DENIED_GLOBALS, `"use strict";\nconst __fn = (${src});\nif (typeof __fn !== "function") throw new Error("code must evaluate to a single (value) => value function");\nreturn __fn;`);
152
+ factory = new Function(...DENIED_GLOBALS, factoryBody(src));
145
153
  }
146
154
  catch (e) {
147
155
  throw new Error(`code transform failed to compile: ${e?.message || e}`);
@@ -156,16 +164,57 @@ export function compileTransformSyntax(src) {
156
164
  export function compileTransform(src) {
157
165
  const fn = createTransformFactory(src)(...DENIED_GLOBALS.map(() => undefined));
158
166
  if (isAsyncFunction(fn))
159
- throw new Error("code transforms are synchronous; async functions are not supported");
167
+ throw new Error(ASYNC_FUNCTION);
160
168
  return (value, ctx) => {
161
169
  const result = fn(value, ctx);
162
170
  if (isPromise(result)) {
163
171
  void Promise.prototype.then.call(result, undefined, () => { });
164
- throw new Error("code transforms are synchronous; returned a Promise or thenable");
172
+ throw new Error(THENABLE);
165
173
  }
166
174
  if (result && typeof result.then === "function") {
167
- throw new Error("code transforms are synchronous; returned a Promise or thenable");
175
+ throw new Error(THENABLE);
168
176
  }
169
177
  return result;
170
178
  };
171
179
  }
180
+ /**
181
+ * 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
182
+ * engine (a WebAssembly one) rather than in its own process. The script is a function expression: called with one
183
+ * string, the JSON of `{ state, ctx }`, it builds the function exactly as compileTransform does (the same factory text,
184
+ * denied globals and synchronous checks), calls it once, and returns one string, the JSON of a TransformOutcome. A value
185
+ * JSON can't carry (a BigInt, a cycle, or a function or symbol, which JSON would drop without a word) is an error. It
186
+ * uses only the language itself: no module, no host object, nothing in or out but the two strings.
187
+ */
188
+ export function transformScript(src) {
189
+ if (typeof src !== "string" || !src.trim())
190
+ throw new Error(EMPTY_SOURCE);
191
+ const text = JSON.stringify;
192
+ return [
193
+ `(function (input) {`,
194
+ ` "use strict";`,
195
+ ` var DENIED = ${text(DENIED_GLOBALS)};`,
196
+ ` var MakeFunction = Function, OwnPromise = Promise, stringify = JSON.stringify, parse = JSON.parse;`,
197
+ ` var AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;`,
198
+ ` var AsyncGeneratorFunction = Object.getPrototypeOf(async function* () {}).constructor;`,
199
+ ` try {`,
200
+ ` var given = parse(input);`,
201
+ ` var factory;`,
202
+ ` try { factory = MakeFunction.apply(null, DENIED.concat([${text(factoryBody(src))}])); }`,
203
+ ` catch (e) { throw new Error("code transform failed to compile: " + ((e && e.message) || e)); }`,
204
+ ` var fn = factory.apply(null, DENIED.map(function () { return undefined; }));`,
205
+ ` if (fn instanceof AsyncFunction || fn instanceof AsyncGeneratorFunction) throw new Error(${text(ASYNC_FUNCTION)});`,
206
+ ` var result = fn(given.state, given.ctx);`,
207
+ ` if (result instanceof OwnPromise) { OwnPromise.prototype.then.call(result, undefined, function () {}); throw new Error(${text(THENABLE)}); }`,
208
+ ` if (result && typeof result.then === "function") throw new Error(${text(THENABLE)});`,
209
+ ` var kept = result === undefined ? { ok: true, undefined: true } : { ok: true, value: result };`,
210
+ ` return stringify(kept, function (key, value) {`,
211
+ ` if (typeof value !== "function" && typeof value !== "symbol") return value;`,
212
+ ` var where = this === kept && key === "value" ? "" : " at " + stringify(key);`,
213
+ ` throw new Error(${text(NOT_JSON)} + typeof value + where);`,
214
+ ` });`,
215
+ ` } catch (e) {`,
216
+ ` return stringify({ ok: false, error: String(e && e.message !== undefined ? e.message : e) });`,
217
+ ` }`,
218
+ `})`,
219
+ ].join("\n");
220
+ }
@@ -0,0 +1,166 @@
1
+ import { type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
2
+ import type { DecisionStateSent } from "./decision-receipts.js";
3
+ import type { WorkflowDeps } from "./workflow.js";
4
+ type RunJudge = NonNullable<WorkflowDeps["runJudge"]>;
5
+ type JudgeParams = Parameters<RunJudge>[0];
6
+ export type DecisionInput = "text" | "json" | "image" | "pdf" | "url";
7
+ /** What a provider answers, so a workflow or host can tell before it asks. */
8
+ export interface DecisionCapabilities {
9
+ types: SystemOneQuestion["type"][];
10
+ inputs: DecisionInput[];
11
+ /** What grounds the answers: nothing, sources for the whole call, or spans per answer. */
12
+ evidence: "none" | "citations" | "spans";
13
+ /** Where the probabilities come from. Only "calibrated" claims to have been measured against outcomes. */
14
+ probability: "calibrated" | "model" | "self_reported" | "none";
15
+ /** Whether it looks things up on the web. */
16
+ grounding: boolean;
17
+ /** "never": a request is paid once sent, so it is never sent again unasked. The provider retries only a request that
18
+ * provably never reached the service (a connect error before sending) or one refused unanswered with a time to
19
+ * retry (a 429 with Retry-After). A failure after sending (a 408, a 5xx, a lost connection) is `outcome_unknown`,
20
+ * and the decision escalates as interrupted. "deduped": the provider answers a decision id it has seen with the
21
+ * same answer and no new charge. */
22
+ replay: "never" | "deduped";
23
+ /** The most questions one request may hold, or null for no limit. */
24
+ maxQuestions: number | null;
25
+ /** The largest state one request may hold, as UTF-8 JSON bytes, or null for no limit. */
26
+ maxStateBytes: number | null;
27
+ /** The models a node may pin, by name; absent or null, any name goes to the provider. */
28
+ models?: readonly string[] | null;
29
+ }
30
+ /** An image a request carries, loaded by the host: its bytes, its type, and the reference it was loaded from. */
31
+ export interface DecisionImage {
32
+ bytes: Uint8Array;
33
+ mime: string;
34
+ ref: string;
35
+ }
36
+ /** A PNG's or JPEG's width and height in pixels, read from its header (PNG's IHDR, a JPEG's first frame marker); null
37
+ * when the bytes are neither or the header is cut short. A provider with a size cap checks it before a paid call. */
38
+ export declare function imageDimensions(bytes: Uint8Array): {
39
+ width: number;
40
+ height: number;
41
+ } | null;
42
+ /** How a host reads an image a decision node names: `ref` is the node's resolved reference (a run-relative path). */
43
+ export type LoadImage = (ref: string, ctx: {
44
+ signal: AbortSignal;
45
+ }) => Promise<{
46
+ bytes: Uint8Array;
47
+ mime: string;
48
+ }>;
49
+ export type DecisionRequest = Pick<JudgeParams, "label" | "kind" | "state" | "questions" | "item" | "executionPath" | "model"> & {
50
+ /** The images, by the token the state or a question names each with; only for a provider whose inputs include image. */
51
+ images?: Record<string, DecisionImage>;
52
+ };
53
+ export interface DecisionContext {
54
+ /** The decision receipt's id: the same request asked again has the same id. */
55
+ decisionId: string;
56
+ signal: AbortSignal;
57
+ /** How long the provider has, every attempt included, in milliseconds; null leaves it to the provider. */
58
+ deadlineMs: number | null;
59
+ }
60
+ /** A source an answer rests on. `scope` is "call" when the provider grounds the whole request in it, or the id of the one
61
+ * question it supports. */
62
+ export interface DecisionEvidence {
63
+ url: string;
64
+ title: string | null;
65
+ excerpts: string[];
66
+ scope: string;
67
+ }
68
+ type WithoutConfidence<A> = A extends {
69
+ confidence: unknown;
70
+ } ? Omit<A, "confidence"> & {
71
+ confidence?: number | null;
72
+ } : A;
73
+ /** An answer as a provider gives it: a choice or score may lack a confidence, which judgeFromProvider derives. */
74
+ export type ProviderAnswer = SystemOneAnswer | WithoutConfidence<Extract<SystemOneAnswer, {
75
+ type: "choice" | "score";
76
+ }>>;
77
+ /** How a cost was reached. "unknown" goes with a null cost, never with 0. */
78
+ export type CostBasis = "reported" | "estimate" | "unknown";
79
+ export interface DecisionOutcome {
80
+ answers: Record<string, ProviderAnswer>;
81
+ evidence: DecisionEvidence[];
82
+ model: string | null;
83
+ usage: {
84
+ input_tokens: number;
85
+ output_tokens: number;
86
+ } | null;
87
+ cost_usd: number | null;
88
+ cost_basis: CostBasis;
89
+ provider_request_id: string | null;
90
+ /** The state the provider sent and the values it cut, when it cut any to fit its model's context; absent when it sent
91
+ * the state as asked. The decision's receipt records this state. */
92
+ state_sent?: DecisionStateSent;
93
+ }
94
+ /** `outcome_unknown`: the request was sent and its outcome is not known (a 408, a 5xx, a connection lost after
95
+ * sending). It may have been answered and billed, so it is not sent again; the run escalates the decision as
96
+ * interrupted. `payment_required`: the provider refused the key's account (a 402: out of credit), before any work, so
97
+ * nothing was billed. */
98
+ export type DecisionProviderErrorCode = "configuration" | "auth" | "payment_required" | "rate_limited" | "timeout" | "aborted" | "invalid_request" | "invalid_response" | "http" | "connection" | "outcome_unknown";
99
+ /** A provider's failure. Its message names what failed, never a key, a header, a request or response body. */
100
+ export declare class DecisionProviderError extends Error {
101
+ readonly code: DecisionProviderErrorCode;
102
+ readonly status?: number;
103
+ readonly attempts: number;
104
+ /** The provider's own reference for the failure, when it gives one. */
105
+ readonly refId?: string;
106
+ /** What a request that was or may have been billed is booked at (`outcome_unknown`, `invalid_response`), with how it was
107
+ * reached; null when unknown. */
108
+ readonly costUsd?: number | null;
109
+ readonly costBasis?: CostBasis;
110
+ /** True when the provider knows the request was never sent (a check before it, cut by the deadline or a cancel):
111
+ * judgeFromProviders keeps its code under a node's timeoutMs, where any other cut is taken for a request that may
112
+ * have been billed. Absent when it may have been sent; `attempts` alone never says so. */
113
+ readonly unsent?: true;
114
+ /** The state the request held as the provider prepared it, when it cut values to fit (DecisionOutcome.state_sent): the
115
+ * failed decision's receipt records it. */
116
+ readonly stateSent?: DecisionStateSent;
117
+ constructor(code: DecisionProviderErrorCode, message: string, details?: {
118
+ status?: number;
119
+ attempts?: number;
120
+ refId?: string;
121
+ costUsd?: number | null;
122
+ costBasis?: CostBasis;
123
+ unsent?: boolean;
124
+ stateSent?: DecisionStateSent;
125
+ cause?: unknown;
126
+ });
127
+ }
128
+ export interface DecisionProvider {
129
+ /** "jev", "parallel", "http:<name>" and the like. */
130
+ readonly id: string;
131
+ /** The environment variables it reads its keys from, by name; never their values. */
132
+ readonly needs: readonly string[];
133
+ readonly capabilities: DecisionCapabilities;
134
+ decide(request: DecisionRequest, ctx: DecisionContext): Promise<DecisionOutcome>;
135
+ }
136
+ /** What a provider's error books for its request: one sent whose outcome was lost (`outcome_unknown`), or one answered
137
+ * with what the seam or the provider rejects (`invalid_response`), was or may have been paid for, and is booked at the
138
+ * cost the error carries, null when that is unknown (never 0). Undefined for an error that books nothing. */
139
+ export declare function chargedCost(error: unknown): number | null | undefined;
140
+ /** Refuses, as invalid_request, a request beyond what `capabilities` declares: a question type it does not answer, more
141
+ * questions than it takes, a larger state, or a model it does not serve. A provider calls it before it sends anything. */
142
+ export declare function checkCapabilities(capabilities: DecisionCapabilities, request: Pick<DecisionRequest, "questions" | "state" | "model">): void;
143
+ export interface JudgeFromProviderOptions {
144
+ deadlineMs?: number | null;
145
+ /** Reads the images a node names. A request with images on a host without it is refused as configuration. */
146
+ loadImage?: LoadImage;
147
+ }
148
+ /** The interpreter's runJudge, answered by `provider`: the request goes to it with the decision's id, its signal and
149
+ * `deadlineMs`, and with the images it names, loaded through `loadImage` within that deadline (the provider gets what is
150
+ * left of it; a load the deadline cuts is `timeout`, one the signal cuts `aborted`, and neither was sent); a choice or
151
+ * score without a confidence gets one derived, and the result names each one's source and each image's digest. The
152
+ * answers are validated against the questions, and ones that do not match them are invalid_response. */
153
+ export declare function judgeFromProvider(provider: DecisionProvider, options?: JudgeFromProviderOptions): RunJudge;
154
+ /** The interpreter's runJudge over a host's providers: each request goes to the provider its node names, or to
155
+ * `default`, with the node's pinned model, within the shorter of the node's `timeoutMs` and the provider's own
156
+ * `deadlineMs`: a node only ever shortens it. The node's bound is kept here: when it passes, the call is cut, and a cut
157
+ * call may already have been sent and billed, so it is `outcome_unknown` (the decision escalates as interrupted), never
158
+ * asked again. A call cut while its images load was not sent, and stays `timeout`. The result names the provider that
159
+ * answered. */
160
+ export declare function judgeFromProviders(options: {
161
+ providers: Readonly<Record<string, DecisionProvider>>;
162
+ default: string;
163
+ deadlineMs?: number | null;
164
+ loadImage?: LoadImage;
165
+ }): RunJudge;
166
+ export {};