@parcha/agentrun-dsl 0.1.0-beta.8 → 0.1.0-beta.80

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 (93) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +156 -16
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +13 -5
  6. package/dist/author.js +31 -16
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/decision-provider.d.ts +166 -0
  10. package/dist/decision-provider.js +238 -0
  11. package/dist/decision-receipts.d.ts +159 -0
  12. package/dist/decision-receipts.js +93 -0
  13. package/dist/dry-run.d.ts +41 -1
  14. package/dist/dry-run.js +158 -27
  15. package/dist/evidence.d.ts +19 -0
  16. package/dist/evidence.js +63 -0
  17. package/dist/graph.d.ts +169 -0
  18. package/dist/graph.js +433 -0
  19. package/dist/index.d.ts +18 -10
  20. package/dist/index.js +15 -8
  21. package/dist/inspection.d.ts +5 -0
  22. package/dist/inspection.js +16 -3
  23. package/dist/job.d.ts +14 -0
  24. package/dist/job.js +5 -0
  25. package/dist/observer-snapshot.d.ts +3 -0
  26. package/dist/observer-snapshot.js +46 -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.d.ts +10 -0
  32. package/dist/recovery/binding.js +44 -0
  33. package/dist/recovery/call-key.d.ts +9 -0
  34. package/dist/recovery/call-key.js +17 -0
  35. package/dist/recovery/canonical-hash.d.ts +7 -0
  36. package/dist/recovery/canonical-hash.js +22 -0
  37. package/dist/recovery/driver.d.ts +235 -0
  38. package/dist/recovery/driver.js +1333 -0
  39. package/dist/recovery/errors.d.ts +31 -0
  40. package/dist/recovery/errors.js +51 -0
  41. package/dist/recovery/execution-path.d.ts +53 -0
  42. package/dist/recovery/execution-path.js +167 -0
  43. package/dist/recovery/file-store.d.ts +7 -0
  44. package/dist/recovery/file-store.js +131 -0
  45. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  46. package/dist/recovery/frozen-snapshot.js +187 -0
  47. package/dist/recovery/handoff-receipts.d.ts +7 -0
  48. package/dist/recovery/handoff-receipts.js +11 -0
  49. package/dist/recovery/index.d.ts +14 -0
  50. package/dist/recovery/index.js +13 -0
  51. package/dist/recovery/item-state.d.ts +48 -0
  52. package/dist/recovery/item-state.js +89 -0
  53. package/dist/recovery/journal.d.ts +28 -0
  54. package/dist/recovery/journal.js +139 -0
  55. package/dist/recovery/memory-store.d.ts +4 -0
  56. package/dist/recovery/memory-store.js +20 -0
  57. package/dist/recovery/store.d.ts +105 -0
  58. package/dist/recovery/store.js +6 -0
  59. package/dist/recovery/testing/conformance.d.ts +4 -0
  60. package/dist/recovery/testing/conformance.js +268 -0
  61. package/dist/recovery/testing/crash-points.d.ts +18 -0
  62. package/dist/recovery/testing/crash-points.js +43 -0
  63. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  64. package/dist/recovery/testing/crash-sweep.js +146 -0
  65. package/dist/recovery/testing/index.d.ts +3 -0
  66. package/dist/recovery/testing/index.js +4 -0
  67. package/dist/recovery/testing/preload.d.ts +1 -0
  68. package/dist/recovery/testing/preload.js +3 -0
  69. package/dist/recovery/transport-facts.d.ts +23 -0
  70. package/dist/recovery/transport-facts.js +46 -0
  71. package/dist/recovery/with-recovery.d.ts +50 -0
  72. package/dist/recovery/with-recovery.js +144 -0
  73. package/dist/submit-envelope.d.ts +9 -0
  74. package/dist/submit-envelope.js +44 -0
  75. package/dist/system-one.d.ts +37 -2
  76. package/dist/system-one.js +137 -17
  77. package/dist/testing/decision-provider.d.ts +32 -0
  78. package/dist/testing/decision-provider.js +183 -0
  79. package/dist/testing/index.d.ts +1 -0
  80. package/dist/testing/index.js +2 -0
  81. package/dist/vocabulary.d.ts +11 -3
  82. package/dist/vocabulary.js +19 -9
  83. package/dist/workflow-shape.d.ts +7 -0
  84. package/dist/workflow-shape.js +116 -70
  85. package/dist/workflow.d.ts +228 -24
  86. package/dist/workflow.js +1411 -448
  87. package/dist/zod-json-contract.js +6 -8
  88. package/package.json +27 -4
  89. package/schema/workflow.schema.json +463 -3
  90. package/skills/author/SKILL.md +6 -1
  91. package/skills/author/references/jev-decisions.md +69 -12
  92. package/skills/author/references/language.md +21 -15
  93. package/skills/author/references/sdk-authoring.md +2 -0
package/dist/author.d.ts CHANGED
@@ -39,7 +39,8 @@ export declare function authorContract(options?: {
39
39
  export interface CandidatePolicyOptions {
40
40
  /** Authoritative rubric text by section name. Every generative node must name every section. */
41
41
  rubricSections?: Record<string, string>;
42
- /** Admits code, call and artifact nodes. */
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). */
43
44
  allowExecutableCandidates?: boolean;
44
45
  /** Direct tool calls admitted without executable authorization. */
45
46
  allowedEffectTools?: readonly string[];
@@ -47,9 +48,16 @@ export interface CandidatePolicyOptions {
47
48
  }
48
49
  /** Author policy over a candidate, checked before validation so a refused candidate never evaluates code. */
49
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
+ }
50
57
  /** The interpreter's view of a workflow written in a host's vocabulary: an artifact of a declared prose output
51
- * type becomes the report writer it is. Validate and run this view; retain and digest the authored bytes. */
52
- export declare function applyHostOutputTypes(candidate: Workflow, host: AuthorHostAddendum | undefined): Workflow;
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;
53
61
  export interface AuthorWorkflowOptions {
54
62
  request: string;
55
63
  outputDir: string;
@@ -59,6 +67,8 @@ export interface AuthorWorkflowOptions {
59
67
  /** Keys available to a candidate without an input schema; defaults to the host's initial state keys. */
60
68
  inputKeys?: string[];
61
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). */
62
72
  allowExecutableCandidates?: boolean;
63
73
  maxCandidates?: number;
64
74
  /** Host acceptance over a structurally valid candidate, in the interpreter's view (`applyHostOutputTypes`):
@@ -79,8 +89,6 @@ export interface AuthoredWorkflow {
79
89
  /** Author one workflow and retain every candidate with its review in a new directory under `outputDir`.
80
90
  * Policy, validation and host acceptance review each submission; a rejection returns to the same session. */
81
91
  export declare function authorWorkflow(options: AuthorWorkflowOptions): Promise<AuthoredWorkflow>;
82
- /** The packaged author skill's name, as a skill-loading host registers it. */
83
- export declare const AUTHOR_SKILL_NAME = "agentrun-author";
84
92
  /** The absolute directory of the packaged author skill (the one holding SKILL.md). */
85
93
  export declare function authorSkillDirectory(): string;
86
94
  /** A reference shipped with the author skill, for hosts without file-reading tools. */
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() {
@@ -36,8 +41,8 @@ A workflow is {"v":2,"name","schemas","input"?,"output","root"}.
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")}.
@@ -77,14 +82,16 @@ Typed questions answered by the host's judge in one request each: no tools, no s
77
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.
78
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")}.
79
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}.
80
- - ${code("sift")}: ${code("itemsPath")}, ${code("out")} (a question schema asked of every item in one request) 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
- - ${code("route")}: a non-empty ${code("state")} map, ${code("instructions")} (the one question) and 2 to ${SYSTEM_ONE_LIMITS.maxChoiceOptions} named ${code("branches")}, each {criteria?, body}. ${code("unsure")} {branch: one of the branches, gte: a number in (0, 1]} takes that branch when the choice's confidence is below ${code("gte")}. ${code("as")} records the choice.
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.
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.
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. ${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.
@@ -111,6 +118,7 @@ ${predicateLines()}
111
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.
112
119
  - Acceptance checks are the host's. Never change a check, fixture or threshold to pass.
113
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.
114
122
 
115
123
  ## Example
116
124
 
@@ -147,7 +155,7 @@ export function renderAuthorContract(options = {}) {
147
155
  export function authorContract(options = {}) {
148
156
  return renderAuthorContract(options).text;
149
157
  }
150
- const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
158
+ const record = (value) => isRecord(value) ? value : undefined;
151
159
  /** Author policy over a candidate, checked before validation so a refused candidate never evaluates code. */
152
160
  export function candidatePolicyErrors(candidate, options) {
153
161
  const errors = [];
@@ -166,7 +174,9 @@ export function candidatePolicyErrors(candidate, options) {
166
174
  // `budget` on an agent is accepted for older documents and never read: an author writes budget_usd.
167
175
  if (kind === "agent" && Object.hasOwn(node, "budget"))
168
176
  errors.push(`${String(node.label ?? kind)}: budget is not read; declare budget_usd, the dollars the node asks to spend`);
169
- if (sections.length && JUDGMENT_NODE_KINDS.includes(String(kind)))
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)
170
180
  errors.push(`${String(kind)} cannot carry supplied SOP sections; use an LLM node with sopSection`);
171
181
  const llm = GENERATIVE_NODE_KINDS.includes(String(kind));
172
182
  const predicate = kind === "loop" ? record(node.until) : kind === "escalate" ? record(node.when) : undefined;
@@ -210,15 +220,18 @@ export function candidatePolicyErrors(candidate, options) {
210
220
  return errors;
211
221
  }
212
222
  /** The interpreter's view of a workflow written in a host's vocabulary: an artifact of a declared prose output
213
- * type becomes the report writer it is. Validate and run this view; retain and digest the authored bytes. */
214
- export function applyHostOutputTypes(candidate, host) {
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 = {}) {
215
226
  const prose = new Set(Object.entries(host?.outputTypes ?? {}).filter(([, spec]) => spec.kind === "prose").map(([type]) => type));
216
227
  if (!prose.size)
217
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;
218
231
  const visit = (node) => {
219
232
  if (!node || typeof node !== "object")
220
233
  return node;
221
- if (node.node === "artifact" && prose.has(node.type))
234
+ if (node.node === "artifact" && prose.has(nameOf(node.type)))
222
235
  return { ...node, type: "report" };
223
236
  if (node.node === "chain")
224
237
  return { ...node, steps: (node.steps || []).map(visit) };
@@ -228,6 +241,8 @@ export function applyHostOutputTypes(candidate, host) {
228
241
  return { ...node, body: visit(node.body) };
229
242
  if (node.node === "route")
230
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.
231
246
  return node;
232
247
  };
233
248
  return { ...candidate, root: visit(candidate.root) };
@@ -265,7 +280,9 @@ export async function authorWorkflow(options) {
265
280
  const errors = candidatePolicyErrors(value, options);
266
281
  if (!errors.length) {
267
282
  try {
268
- 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 });
269
286
  if (!verdict.ok)
270
287
  errors.push(...verdict.errors);
271
288
  }
@@ -295,8 +312,6 @@ export async function authorWorkflow(options) {
295
312
  throw error;
296
313
  }
297
314
  }
298
- /** The packaged author skill's name, as a skill-loading host registers it. */
299
- export const AUTHOR_SKILL_NAME = "agentrun-author";
300
315
  const skillRoot = new URL("../skills/author/", import.meta.url);
301
316
  /** The absolute directory of the packaged author skill (the one holding SKILL.md). */
302
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, {});
@@ -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 {};