@parcha/agentrun-dsl 0.1.0-beta.29 → 0.1.0-beta.291

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 (69) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +11 -7
  3. package/dist/author-references.d.ts +2 -2
  4. package/dist/author-references.js +2 -2
  5. package/dist/author.d.ts +0 -2
  6. package/dist/author.js +7 -6
  7. package/dist/authoring.js +3 -2
  8. package/dist/cli.js +2 -1
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +11 -2
  12. package/dist/decision-provider.js +12 -4
  13. package/dist/decision-receipts.d.ts +24 -3
  14. package/dist/decision-receipts.js +2 -0
  15. package/dist/dry-run.d.ts +31 -1
  16. package/dist/dry-run.js +103 -14
  17. package/dist/edit.d.ts +158 -0
  18. package/dist/edit.js +1486 -0
  19. package/dist/evidence.d.ts +19 -0
  20. package/dist/evidence.js +63 -0
  21. package/dist/index.d.ts +12 -9
  22. package/dist/index.js +14 -9
  23. package/dist/pattern-screen.d.ts +14 -0
  24. package/dist/pattern-screen.js +451 -0
  25. package/dist/pointer-warning.d.ts +14 -0
  26. package/dist/pointer-warning.js +22 -0
  27. package/dist/predicates.d.ts +23 -3
  28. package/dist/predicates.js +48 -6
  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 +20 -14
  35. package/dist/recovery/driver.js +48 -26
  36. package/dist/recovery/frozen-snapshot.js +8 -8
  37. package/dist/recovery/handoff-receipts.d.ts +0 -35
  38. package/dist/recovery/handoff-receipts.js +2 -44
  39. package/dist/recovery/index.d.ts +2 -7
  40. package/dist/recovery/index.js +2 -6
  41. package/dist/recovery/item-state.d.ts +2 -1
  42. package/dist/recovery/item-state.js +7 -13
  43. package/dist/recovery/with-recovery.js +4 -2
  44. package/dist/submit-envelope.d.ts +1 -1
  45. package/dist/submit-envelope.js +11 -7
  46. package/dist/system-one.d.ts +0 -4
  47. package/dist/system-one.js +7 -8
  48. package/dist/vocabulary.d.ts +7 -2
  49. package/dist/vocabulary.js +7 -1
  50. package/dist/workflow-shape.js +4 -2
  51. package/dist/workflow.d.ts +64 -13
  52. package/dist/workflow.js +511 -204
  53. package/dist/zod-json-contract.js +6 -8
  54. package/package.json +7 -3
  55. package/schema/workflow.schema.json +93 -0
  56. package/skills/author/references/jev-decisions.md +10 -5
  57. package/skills/author/references/language.md +5 -4
  58. package/dist/recovery/effect-failure.d.ts +0 -34
  59. package/dist/recovery/effect-failure.js +0 -62
  60. package/dist/recovery/handoff-block.d.ts +0 -36
  61. package/dist/recovery/handoff-block.js +0 -148
  62. package/dist/recovery/handoff-digest.d.ts +0 -58
  63. package/dist/recovery/handoff-digest.js +0 -195
  64. package/dist/recovery/handoff-files.d.ts +0 -54
  65. package/dist/recovery/handoff-files.js +0 -162
  66. package/dist/recovery/handoff-redact.d.ts +0 -12
  67. package/dist/recovery/handoff-redact.js +0 -44
  68. package/dist/recovery/handoff.d.ts +0 -44
  69. package/dist/recovery/handoff.js +0 -46
package/dist/author.js CHANGED
@@ -6,6 +6,8 @@ import { join, resolve } from "node:path";
6
6
  import { validateWorkflow } from "./workflow.js";
7
7
  import { SYSTEM_ONE_LIMITS } from "./system-one.js";
8
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("|");
@@ -19,6 +21,7 @@ const PREDICATE_SHAPES = {
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",
21
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\``,
22
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",
23
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)",
24
27
  };
@@ -34,12 +37,12 @@ Deliver the complete JSON document the way your host asks; never deliver prose,
34
37
  ## Document
35
38
 
36
39
  A workflow is {"v":2,"name","schemas","input"?,"output","root"}.
37
- - ${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.
38
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.
39
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.
40
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.
41
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")}.
42
- - ${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.
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.
43
46
 
44
47
  ## Node kinds
45
48
 
@@ -88,7 +91,7 @@ Typed questions answered by the host's judge in one request each: no tools, no s
88
91
  ### Control nodes
89
92
 
90
93
  - ${code("chain")}: non-empty ${code("steps")}, run in order.
91
- - ${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.
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.
92
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.
93
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.
94
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.
@@ -152,7 +155,7 @@ export function renderAuthorContract(options = {}) {
152
155
  export function authorContract(options = {}) {
153
156
  return renderAuthorContract(options).text;
154
157
  }
155
- const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
158
+ const record = (value) => isRecord(value) ? value : undefined;
156
159
  /** Author policy over a candidate, checked before validation so a refused candidate never evaluates code. */
157
160
  export function candidatePolicyErrors(candidate, options) {
158
161
  const errors = [];
@@ -309,8 +312,6 @@ export async function authorWorkflow(options) {
309
312
  throw error;
310
313
  }
311
314
  }
312
- /** The packaged author skill's name, as a skill-loading host registers it. */
313
- export const AUTHOR_SKILL_NAME = "agentrun-author";
314
315
  const skillRoot = new URL("../skills/author/", import.meta.url);
315
316
  /** The absolute directory of the packaged author skill (the one holding SKILL.md). */
316
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
  }
@@ -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")
package/dist/cli.js CHANGED
@@ -6,6 +6,7 @@ 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
12
  agentrun-dsl demo [--scenario billing|technical|ambiguous] [--json]
@@ -109,7 +110,7 @@ async function main(args) {
109
110
  catch (error) {
110
111
  throw new Error(`Cannot read input JSON file "${positional[1]}": ${error instanceof Error ? error.message : String(error)}`);
111
112
  }
112
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
113
+ if (!isRecord(parsed))
113
114
  throw new Error("Input JSON must be an object.");
114
115
  input = parsed;
115
116
  }
@@ -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
+ }
@@ -1,4 +1,5 @@
1
1
  import { type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
2
+ import type { DecisionStateSent } from "./decision-receipts.js";
2
3
  import type { WorkflowDeps } from "./workflow.js";
3
4
  type RunJudge = NonNullable<WorkflowDeps["runJudge"]>;
4
5
  type JudgeParams = Parameters<RunJudge>[0];
@@ -86,11 +87,15 @@ export interface DecisionOutcome {
86
87
  cost_usd: number | null;
87
88
  cost_basis: CostBasis;
88
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;
89
93
  }
90
94
  /** `outcome_unknown`: the request was sent and its outcome is not known (a 408, a 5xx, a connection lost after
91
95
  * sending). It may have been answered and billed, so it is not sent again; the run escalates the decision as
92
- * interrupted. */
93
- export type DecisionProviderErrorCode = "configuration" | "auth" | "rate_limited" | "timeout" | "aborted" | "invalid_request" | "invalid_response" | "http" | "connection" | "outcome_unknown";
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";
94
99
  /** A provider's failure. Its message names what failed, never a key, a header, a request or response body. */
95
100
  export declare class DecisionProviderError extends Error {
96
101
  readonly code: DecisionProviderErrorCode;
@@ -106,6 +111,9 @@ export declare class DecisionProviderError extends Error {
106
111
  * judgeFromProviders keeps its code under a node's timeoutMs, where any other cut is taken for a request that may
107
112
  * have been billed. Absent when it may have been sent; `attempts` alone never says so. */
108
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;
109
117
  constructor(code: DecisionProviderErrorCode, message: string, details?: {
110
118
  status?: number;
111
119
  attempts?: number;
@@ -113,6 +121,7 @@ export declare class DecisionProviderError extends Error {
113
121
  costUsd?: number | null;
114
122
  costBasis?: CostBasis;
115
123
  unsent?: boolean;
124
+ stateSent?: DecisionStateSent;
116
125
  cause?: unknown;
117
126
  });
118
127
  }
@@ -2,6 +2,7 @@
2
2
  // and without an agent harness, and judgeFromProvider makes one the interpreter's runJudge. Jev is one provider and a
3
3
  // third-party API another; each passes the conformance suite in `@parcha/agentrun-dsl/testing`.
4
4
  import { createHash } from "node:crypto";
5
+ import { evidenceOf } from "./evidence.js";
5
6
  import { completeConfidence, validateAnswers } from "./system-one.js";
6
7
  /** 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
7
8
  * when the bytes are neither or the header is cut short. A provider with a size cap checks it before a paid call. */
@@ -49,6 +50,9 @@ export class DecisionProviderError extends Error {
49
50
  * judgeFromProviders keeps its code under a node's timeoutMs, where any other cut is taken for a request that may
50
51
  * have been billed. Absent when it may have been sent; `attempts` alone never says so. */
51
52
  unsent;
53
+ /** The state the request held as the provider prepared it, when it cut values to fit (DecisionOutcome.state_sent): the
54
+ * failed decision's receipt records it. */
55
+ stateSent;
52
56
  constructor(code, message, details = {}) {
53
57
  super(message, details.cause !== undefined ? { cause: details.cause } : undefined);
54
58
  this.code = code;
@@ -64,6 +68,8 @@ export class DecisionProviderError extends Error {
64
68
  this.costBasis = details.costBasis;
65
69
  if (details.unsent === true)
66
70
  this.unsent = true;
71
+ if (details.stateSent !== undefined)
72
+ this.stateSent = details.stateSent;
67
73
  }
68
74
  }
69
75
  /** What a provider's error books for its request: one sent whose outcome was lost (`outcome_unknown`), or one answered
@@ -181,12 +187,13 @@ export function judgeFromProvider(provider, options = {}) {
181
187
  catch (error) {
182
188
  // The provider answered, so the request was paid for: the rejection carries its cost, or null when it reported none.
183
189
  const cost = typeof outcome.cost_usd === "number" && Number.isFinite(outcome.cost_usd) ? outcome.cost_usd : null;
184
- throw new DecisionProviderError("invalid_response", `${provider.id} answered with ${error.message.replace(/^System One /, "")}`, { costUsd: cost, costBasis: cost === null ? "unknown" : outcome.cost_basis });
190
+ throw new DecisionProviderError("invalid_response", `${provider.id} answered with ${error.message.replace(/^System One /, "")}`, { costUsd: cost, costBasis: cost === null ? "unknown" : outcome.cost_basis, ...(outcome.state_sent ? { stateSent: outcome.state_sent } : {}) });
185
191
  }
186
192
  const result = {
187
193
  answers, model: outcome.model, usage: outcome.usage, cost_usd: outcome.cost_usd, cost_basis: outcome.cost_basis,
188
- evidence: outcome.evidence, provider_request_id: outcome.provider_request_id, confidence_source,
189
- ...(digests ? { images: digests } : {}),
194
+ // Every provider's evidence, a third party's too, through the one sanitizer (evidence.ts).
195
+ evidence: evidenceOf(outcome.evidence), provider_request_id: outcome.provider_request_id, confidence_source,
196
+ ...(digests ? { images: digests } : {}), ...(outcome.state_sent ? { state_sent: outcome.state_sent } : {}),
190
197
  };
191
198
  return result;
192
199
  };
@@ -217,7 +224,8 @@ export function judgeFromProviders(options) {
217
224
  catch (error) {
218
225
  if (cut.signal.aborted && error instanceof DecisionProviderError && !cutBeforeSending.has(error) && error.unsent !== true && (error.code === "aborted" || error.code === "timeout")) {
219
226
  throw new DecisionProviderError("outcome_unknown", `${id}: cut by the node's timeoutMs (${node} ms) after it may have been sent`, {
220
- attempts: error.attempts, ...(error.costUsd !== undefined ? { costUsd: error.costUsd } : {}), ...(error.costBasis !== undefined ? { costBasis: error.costBasis } : {}), cause: error
227
+ attempts: error.attempts, ...(error.costUsd !== undefined ? { costUsd: error.costUsd } : {}), ...(error.costBasis !== undefined ? { costBasis: error.costBasis } : {}),
228
+ ...(error.stateSent !== undefined ? { stateSent: error.stateSent } : {}), cause: error
221
229
  });
222
230
  }
223
231
  throw error;
@@ -9,6 +9,8 @@ export declare const DECISION_INTERRUPTED = "decision_interrupted";
9
9
  /** The most of the state a receipt keeps, as UTF-8 JSON bytes: a larger state is kept as the first this many bytes of its
10
10
  * JSON text, with `state_truncated: true`. */
11
11
  export declare const DECISION_STATE_MAX_BYTES: number;
12
+ /** The most of a request's error a receipt keeps, in characters; a longer one is kept to it with `error_truncated`. */
13
+ export declare const DECISION_ERROR_MAX: number;
12
14
  /** An image a request carried, as its receipt names it: the token the request used, the reference the host loaded, and
13
15
  * the image's SHA-256, type and size (never the bytes). The digest fields are null when the image was never loaded (a
14
16
  * request that failed before its images were read). */
@@ -19,6 +21,18 @@ export type DecisionImageDigest = {
19
21
  mime: string | null;
20
22
  bytes: number | null;
21
23
  };
24
+ /** A state value a provider cut to fit its model's context before it sent the request: where it sits in the state (a JSON
25
+ * Pointer, RFC 6901), and its UTF-8 bytes as asked and as sent (its start and the provider's cut mark). */
26
+ export type DecisionStateCut = {
27
+ path: string;
28
+ bytes: number;
29
+ sent_bytes: number;
30
+ };
31
+ /** The state a provider sent when it sent other than it was asked (values cut to fit its context), and the values it cut. */
32
+ export type DecisionStateSent = {
33
+ state: unknown;
34
+ cut: DecisionStateCut[];
35
+ };
22
36
  /** The typed questions the interpreter asks: the five question nodes and predicates, and a generative
23
37
  * node's `verify` clause. */
24
38
  export type DecisionKind = "judge" | "pick" | "sift" | "route" | "ask" | "verify";
@@ -95,7 +109,8 @@ export type DecisionReceipt = {
95
109
  * were refused. `cancelled`: the request's signal was aborted before it settled, so whether it was
96
110
  * served is not known. */
97
111
  status: "answered" | "failed" | "cancelled";
98
- /** SHA-256 of the canonical JSON of the state the judge was given. */
112
+ /** SHA-256 of the canonical JSON of the state the judge was asked with: part of the request's identity (`id`). What
113
+ * the provider sent is `state` and `request_sha256`, which differ when it cut values to fit (`state_cut`). */
99
114
  state_sha256: string;
100
115
  questions: Record<string, SystemOneQuestion>;
101
116
  /** What came back, as it came back; empty when nothing did. */
@@ -127,11 +142,17 @@ export type DecisionReceipt = {
127
142
  cost_basis?: CostBasis;
128
143
  /** The images the request carried, by digest; absent when it carried none. */
129
144
  images?: DecisionImageDigest[];
130
- /** The state the judge saw: the value itself, or, past `DECISION_STATE_MAX_BYTES` of JSON, the first that many bytes of
131
- * its JSON text (a string) with `state_truncated: true`. Absent on a receipt recorded before it was kept. */
145
+ /** The state the judge saw, as its provider sent it (with any value it cut, cut): the value itself, or, past
146
+ * `DECISION_STATE_MAX_BYTES` of JSON, the first that many bytes of its JSON text (a string) with `state_truncated: true`.
147
+ * Absent on a receipt recorded before it was kept. */
132
148
  state?: unknown;
133
149
  state_truncated?: boolean;
150
+ /** The state values the provider cut to fit its model's context before sending; absent when it sent the state as asked. */
151
+ state_cut?: DecisionStateCut[];
152
+ /** The request's error, whole up to `DECISION_ERROR_MAX` characters: a host redacts it before it cuts it for a person.
153
+ * A longer one is kept to that many with `error_truncated: true`; one recorded before was cut at 2000. */
134
154
  error?: string;
155
+ error_truncated?: boolean;
135
156
  };
136
157
  /** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
137
158
  * receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
@@ -8,6 +8,8 @@ export const DECISION_INTERRUPTED = "decision_interrupted";
8
8
  /** The most of the state a receipt keeps, as UTF-8 JSON bytes: a larger state is kept as the first this many bytes of its
9
9
  * JSON text, with `state_truncated: true`. */
10
10
  export const DECISION_STATE_MAX_BYTES = 64 * 1024;
11
+ /** The most of a request's error a receipt keeps, in characters; a longer one is kept to it with `error_truncated`. */
12
+ export const DECISION_ERROR_MAX = 64 * 1024;
11
13
  /** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
12
14
  * receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
13
15
  export function rederiveDecision(receipt) {
package/dist/dry-run.d.ts CHANGED
@@ -11,7 +11,24 @@ export type DryRunResult = {
11
11
  problems: string[];
12
12
  stage?: string;
13
13
  };
14
- export declare function synthesizeInstance(schema: unknown, definitions?: Record<string, unknown>, depth?: number): unknown;
14
+ /** What one dry run may synthesize in all, across its input and every step's answer (DryRunOptions.budget), and what one
15
+ * synthesizeInstance call may when none is given: values (each array item, object, string, number...) and string
16
+ * characters. Synthesis counts each before it makes it and throws SynthesisTooLarge past either, so a schema that asks
17
+ * for a huge value (nested arrays of a large minItems, a long minLength) never allocates past the budget. */
18
+ export type SynthesisBudget = {
19
+ values: number;
20
+ chars: number;
21
+ };
22
+ /** The default: a million values and 16 million characters, far past what a real workflow's dry run builds (a few
23
+ * thousand values at most), and well within a host's memory (a few hundred MB at worst). */
24
+ export declare const SYNTHESIS_BUDGET: Readonly<SynthesisBudget>;
25
+ /** The schema asked synthesis for more than its budget: the dry run ends not run, saying so. */
26
+ export declare class SynthesisTooLarge extends Error {
27
+ name: string;
28
+ }
29
+ /** A value of `schema` (its `$ref`s read from `definitions`), synthesized within `budget` (SYNTHESIS_BUDGET when none):
30
+ * past it, SynthesisTooLarge. */
31
+ export declare function synthesizeInstance(schema: unknown, definitions?: Record<string, unknown>, depth?: number, budget?: Partial<SynthesisBudget>): unknown;
15
32
  export type DryRunOptions = {
16
33
  sop?: string;
17
34
  probeContext?: {
@@ -28,5 +45,18 @@ export type DryRunOptions = {
28
45
  * stops, as not run: synthetic answers can keep a loop going to its bound, and a map over a long list. 10,000 by
29
46
  * default. */
30
47
  maxSteps?: number;
48
+ /** What the whole dry run may synthesize (SynthesisBudget): its input and every step's answer together. Past it the dry
49
+ * run stops, as not run ("the schema is too large to synthesize"). SYNTHESIS_BUDGET by default. */
50
+ budget?: Partial<SynthesisBudget>;
51
+ /** The longest the dry run may take by the clock (ms): past it, it stops at its next node or step, as not run. Read
52
+ * from the clock at each, never from a timer, so a dry run that never yields still stops. 60,000 by default. */
53
+ deadlineMs?: number;
54
+ /** The most node visits (a loop's body each iteration, a map's body for each item, any node run), whether or not they
55
+ * ask anything, before the dry run stops, as not run: a loop whose body asks nothing is no step, so maxSteps alone
56
+ * never ends it. Ten times maxSteps by default. */
57
+ maxVisits?: number;
58
+ /** Handed the workflow's output when the dry run passed (on synthetic values): what a host holds to a shape of its own
59
+ * (the answer it serves) before it calls the draft good. The result keeps its shape either way. */
60
+ onOutput?: (output: unknown) => void;
31
61
  };
32
62
  export declare function dryRunWorkflow(workflow: Workflow, opts?: DryRunOptions): Promise<DryRunResult>;