@parcha/agentrun-dsl 0.1.0-beta.30 → 0.1.0-beta.300
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +2 -0
- package/README.md +11 -7
- package/dist/author-references.d.ts +2 -2
- package/dist/author-references.js +2 -2
- package/dist/author.d.ts +0 -2
- package/dist/author.js +7 -6
- package/dist/authoring.js +3 -2
- package/dist/cli.js +2 -1
- package/dist/code-exec.d.ts +19 -0
- package/dist/code-exec.js +54 -5
- package/dist/decision-provider.d.ts +11 -2
- package/dist/decision-provider.js +12 -4
- package/dist/decision-receipts.d.ts +19 -3
- package/dist/dry-run.d.ts +31 -1
- package/dist/dry-run.js +103 -14
- package/dist/edit.d.ts +158 -0
- package/dist/edit.js +1486 -0
- package/dist/evidence.d.ts +19 -0
- package/dist/evidence.js +63 -0
- package/dist/index.d.ts +12 -9
- package/dist/index.js +14 -9
- package/dist/pattern-screen.d.ts +14 -0
- package/dist/pattern-screen.js +451 -0
- package/dist/pointer-warning.d.ts +14 -0
- package/dist/pointer-warning.js +22 -0
- package/dist/predicates.d.ts +23 -3
- package/dist/predicates.js +48 -6
- package/dist/record.d.ts +4 -0
- package/dist/record.js +6 -0
- package/dist/recovery/binding.js +2 -1
- package/dist/recovery/call-key.d.ts +0 -4
- package/dist/recovery/call-key.js +0 -7
- package/dist/recovery/driver.d.ts +20 -14
- package/dist/recovery/driver.js +48 -26
- package/dist/recovery/frozen-snapshot.js +8 -8
- package/dist/recovery/handoff-receipts.d.ts +0 -35
- package/dist/recovery/handoff-receipts.js +2 -44
- package/dist/recovery/index.d.ts +2 -7
- package/dist/recovery/index.js +2 -6
- package/dist/recovery/item-state.d.ts +2 -1
- package/dist/recovery/item-state.js +7 -13
- package/dist/recovery/with-recovery.js +4 -2
- package/dist/submit-envelope.d.ts +1 -1
- package/dist/submit-envelope.js +11 -7
- package/dist/system-one.d.ts +0 -4
- package/dist/system-one.js +7 -8
- package/dist/vocabulary.d.ts +7 -2
- package/dist/vocabulary.js +7 -1
- package/dist/workflow-shape.js +4 -2
- package/dist/workflow.d.ts +64 -13
- package/dist/workflow.js +506 -202
- package/dist/zod-json-contract.js +6 -8
- package/package.json +7 -3
- package/schema/workflow.schema.json +93 -0
- package/skills/author/references/jev-decisions.md +10 -5
- package/skills/author/references/language.md +5 -4
- package/dist/recovery/effect-failure.d.ts +0 -34
- package/dist/recovery/effect-failure.js +0 -62
- package/dist/recovery/handoff-block.d.ts +0 -36
- package/dist/recovery/handoff-block.js +0 -148
- package/dist/recovery/handoff-digest.d.ts +0 -58
- package/dist/recovery/handoff-digest.js +0 -195
- package/dist/recovery/handoff-files.d.ts +0 -54
- package/dist/recovery/handoff-files.js +0 -162
- package/dist/recovery/handoff-redact.d.ts +0 -12
- package/dist/recovery/handoff-redact.js +0 -44
- package/dist/recovery/handoff.d.ts +0 -44
- 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) =>
|
|
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 (!
|
|
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 (!
|
|
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 (!
|
|
113
|
+
if (!isRecord(parsed))
|
|
113
114
|
throw new Error("Input JSON must be an object.");
|
|
114
115
|
input = parsed;
|
|
115
116
|
}
|
package/dist/code-exec.d.ts
CHANGED
|
@@ -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(
|
|
149
|
+
throw new Error(EMPTY_SOURCE);
|
|
142
150
|
let factory;
|
|
143
151
|
try {
|
|
144
|
-
factory = new Function(...DENIED_GLOBALS,
|
|
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(
|
|
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(
|
|
172
|
+
throw new Error(THENABLE);
|
|
165
173
|
}
|
|
166
174
|
if (result && typeof result.then === "function") {
|
|
167
|
-
throw new Error(
|
|
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
|
-
|
|
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
|
-
|
|
189
|
-
|
|
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 } : {}),
|
|
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;
|
|
@@ -21,6 +21,18 @@ export type DecisionImageDigest = {
|
|
|
21
21
|
mime: string | null;
|
|
22
22
|
bytes: number | null;
|
|
23
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
|
+
};
|
|
24
36
|
/** The typed questions the interpreter asks: the five question nodes and predicates, and a generative
|
|
25
37
|
* node's `verify` clause. */
|
|
26
38
|
export type DecisionKind = "judge" | "pick" | "sift" | "route" | "ask" | "verify";
|
|
@@ -97,7 +109,8 @@ export type DecisionReceipt = {
|
|
|
97
109
|
* were refused. `cancelled`: the request's signal was aborted before it settled, so whether it was
|
|
98
110
|
* served is not known. */
|
|
99
111
|
status: "answered" | "failed" | "cancelled";
|
|
100
|
-
/** SHA-256 of the canonical JSON of the state the judge was
|
|
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`). */
|
|
101
114
|
state_sha256: string;
|
|
102
115
|
questions: Record<string, SystemOneQuestion>;
|
|
103
116
|
/** What came back, as it came back; empty when nothing did. */
|
|
@@ -129,10 +142,13 @@ export type DecisionReceipt = {
|
|
|
129
142
|
cost_basis?: CostBasis;
|
|
130
143
|
/** The images the request carried, by digest; absent when it carried none. */
|
|
131
144
|
images?: DecisionImageDigest[];
|
|
132
|
-
/** The state the judge saw
|
|
133
|
-
* its JSON text (a string) with `state_truncated: true`.
|
|
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. */
|
|
134
148
|
state?: unknown;
|
|
135
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[];
|
|
136
152
|
/** The request's error, whole up to `DECISION_ERROR_MAX` characters: a host redacts it before it cuts it for a person.
|
|
137
153
|
* A longer one is kept to that many with `error_truncated: true`; one recorded before was cut at 2000. */
|
|
138
154
|
error?: string;
|
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
|
-
|
|
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>;
|
package/dist/dry-run.js
CHANGED
|
@@ -2,6 +2,7 @@ import { Compile } from "typebox/compile";
|
|
|
2
2
|
import { runWorkflow, validateWorkflow, WorkflowInvalidError, WorkflowInputInvalidError, WorkflowOutputInvalidError } from "./workflow.js";
|
|
3
3
|
import { resolveSchemaForWorkflow } from "./schema-references.js";
|
|
4
4
|
import { synthesizeAnswers } from "./system-one.js";
|
|
5
|
+
import { isRecord } from "./record.js";
|
|
5
6
|
/** A provider for every id the workflow names, and a default: the dry run answers each decision itself, so a node's
|
|
6
7
|
* provider and timeoutMs hold it to no host's providers. */
|
|
7
8
|
function syntheticProviders(workflow) {
|
|
@@ -13,29 +14,63 @@ function syntheticProviders(workflow) {
|
|
|
13
14
|
const provider = (id) => ({ id, needs: [], capabilities, decide: async () => { throw new Error("A dry run answers its decisions itself."); } });
|
|
14
15
|
return { providers: Object.fromEntries([...ids].map((id) => [id, provider(id)])), default: "dry-run" };
|
|
15
16
|
}
|
|
16
|
-
|
|
17
|
+
/** The default: a million values and 16 million characters, far past what a real workflow's dry run builds (a few
|
|
18
|
+
* thousand values at most), and well within a host's memory (a few hundred MB at worst). */
|
|
19
|
+
export const SYNTHESIS_BUDGET = { values: 1_000_000, chars: 16_000_000 };
|
|
20
|
+
/** The schema asked synthesis for more than its budget: the dry run ends not run, saying so. */
|
|
21
|
+
export class SynthesisTooLarge extends Error {
|
|
22
|
+
name = "SynthesisTooLarge";
|
|
23
|
+
}
|
|
24
|
+
/** A budget's limits, each field the default unless given as a number (a field given as undefined keeps the default). */
|
|
25
|
+
const spendOf = (limit = {}) => ({
|
|
26
|
+
values: 0,
|
|
27
|
+
chars: 0,
|
|
28
|
+
limit: { values: typeof limit.values === "number" ? limit.values : SYNTHESIS_BUDGET.values, chars: typeof limit.chars === "number" ? limit.chars : SYNTHESIS_BUDGET.chars },
|
|
29
|
+
});
|
|
30
|
+
/** A literal's characters as the value it is (a const, an enum's first): its serialized size. */
|
|
31
|
+
const literalChars = (value) => JSON.stringify(value)?.length ?? 0;
|
|
32
|
+
function charge(spend, values, chars) {
|
|
33
|
+
spend.values += values;
|
|
34
|
+
spend.chars += chars;
|
|
35
|
+
if (spend.values > spend.limit.values || spend.chars > spend.limit.chars) {
|
|
36
|
+
throw new SynthesisTooLarge(`the schema is too large to synthesize: past ${spend.limit.values} values or ${spend.limit.chars} characters`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** A value of `schema` (its `$ref`s read from `definitions`), synthesized within `budget` (SYNTHESIS_BUDGET when none):
|
|
40
|
+
* past it, SynthesisTooLarge. */
|
|
41
|
+
export function synthesizeInstance(schema, definitions = {}, depth = 0, budget = SYNTHESIS_BUDGET) {
|
|
42
|
+
return synthesize(schema, definitions, depth, spendOf(budget));
|
|
43
|
+
}
|
|
44
|
+
function synthesize(schema, definitions, depth, spend) {
|
|
45
|
+
// Every value it makes is counted before it is made, once (a $ref, an anyOf or a oneOf is the value it leads to, not one
|
|
46
|
+
// of its own): past the budget it throws, having built no more than the budget.
|
|
17
47
|
if (depth > 12 || !schema || typeof schema !== "object")
|
|
18
|
-
return null;
|
|
48
|
+
return (charge(spend, 1, 0), null);
|
|
19
49
|
const spec = schema;
|
|
20
50
|
if (typeof spec.$ref === "string") {
|
|
21
51
|
const match = /^#\/definitions\/(.+)$/.exec(spec.$ref);
|
|
22
|
-
return match && definitions[match[1]] ?
|
|
52
|
+
return match && definitions[match[1]] ? synthesize(definitions[match[1]], definitions, depth + 1, spend) : (charge(spend, 1, 0), null);
|
|
23
53
|
}
|
|
54
|
+
// A literal is charged its serialized size: one written long in the schema does not escape the character budget.
|
|
24
55
|
if (spec.const !== undefined)
|
|
25
|
-
return spec.const;
|
|
56
|
+
return (charge(spend, 1, literalChars(spec.const)), spec.const);
|
|
26
57
|
if (Array.isArray(spec.enum) && spec.enum.length)
|
|
27
|
-
return spec.enum[0];
|
|
58
|
+
return (charge(spend, 1, literalChars(spec.enum[0])), spec.enum[0]);
|
|
28
59
|
if (Array.isArray(spec.anyOf) && spec.anyOf.length) {
|
|
29
60
|
const branch = spec.anyOf.find((candidate) => candidate?.type !== "null") ?? spec.anyOf[0];
|
|
30
|
-
return
|
|
61
|
+
return synthesize(branch, definitions, depth + 1, spend);
|
|
31
62
|
}
|
|
32
63
|
if (Array.isArray(spec.oneOf) && spec.oneOf.length)
|
|
33
|
-
return
|
|
64
|
+
return synthesize(spec.oneOf[0], definitions, depth + 1, spend);
|
|
65
|
+
// The one value made below.
|
|
66
|
+
charge(spend, 1, 0);
|
|
34
67
|
const type = Array.isArray(spec.type) ? spec.type[0] : spec.type;
|
|
35
68
|
if (type === "object" || (!type && spec.properties)) {
|
|
36
69
|
const out = Object.create(null);
|
|
37
70
|
for (const [key, property] of Object.entries(spec.properties || {})) {
|
|
38
|
-
|
|
71
|
+
// Its name is built into every value made under it, and serialized with it: charged before it is added.
|
|
72
|
+
charge(spend, 0, key.length);
|
|
73
|
+
out[key] = synthesize(property, definitions, depth + 1, spend);
|
|
39
74
|
}
|
|
40
75
|
return { ...out };
|
|
41
76
|
}
|
|
@@ -45,12 +80,17 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
|
|
|
45
80
|
const min = Number.isInteger(spec.minItems) ? spec.minItems : 1;
|
|
46
81
|
if (!spec.items)
|
|
47
82
|
return [];
|
|
48
|
-
|
|
83
|
+
// Each item is at least one value: a length past what the budget has left is refused before the array is made.
|
|
84
|
+
const length = Math.max(1, min);
|
|
85
|
+
if (length > spend.limit.values - spend.values)
|
|
86
|
+
charge(spend, length, 0);
|
|
87
|
+
return Array.from({ length }, () => synthesize(spec.items, definitions, depth + 1, spend));
|
|
49
88
|
}
|
|
50
89
|
if (type === "string") {
|
|
51
90
|
if (spec.maxLength === 0)
|
|
52
91
|
return "";
|
|
53
92
|
const min = Number.isInteger(spec.minLength) ? spec.minLength : 1;
|
|
93
|
+
charge(spend, 0, Math.max(1, min));
|
|
54
94
|
return "x".repeat(Math.max(1, min));
|
|
55
95
|
}
|
|
56
96
|
if (type === "integer") {
|
|
@@ -90,6 +130,8 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
|
|
|
90
130
|
return false;
|
|
91
131
|
if (type === "null")
|
|
92
132
|
return null;
|
|
133
|
+
// A schema synthesis cannot read: one character.
|
|
134
|
+
charge(spend, 0, 1);
|
|
93
135
|
return "x";
|
|
94
136
|
}
|
|
95
137
|
function unsupportedConstructs(schema, path, found, depth = 0) {
|
|
@@ -151,11 +193,21 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
151
193
|
scanSchemas(workflow);
|
|
152
194
|
if (skipped.length)
|
|
153
195
|
return { ok: true, status: "not_run", skipped };
|
|
196
|
+
// One budget for everything this dry run synthesizes.
|
|
197
|
+
const spend = spendOf(opts.budget);
|
|
154
198
|
let input = opts.input ?? {};
|
|
155
199
|
if (opts.input === undefined && workflow.input) {
|
|
156
200
|
const schema = resolveSchemaForWorkflow(workflow, workflow.schemas[workflow.input.schemaId]);
|
|
157
|
-
|
|
158
|
-
|
|
201
|
+
let generated;
|
|
202
|
+
try {
|
|
203
|
+
generated = synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend);
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
if (error instanceof SynthesisTooLarge)
|
|
207
|
+
return { ok: true, status: "not_run", skipped: [error.message] };
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
if (!isRecord(generated) || !Compile(schema).Check(generated)) {
|
|
159
211
|
return { ok: true, status: "not_run", skipped: ["Could not synthesize a valid input object. Supply input explicitly to dryRunWorkflow or the dry-run CLI."] };
|
|
160
212
|
}
|
|
161
213
|
input = generated;
|
|
@@ -173,12 +225,43 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
173
225
|
// Why the dry run stopped early, kept here: the interpreter may wrap what an adapter throws.
|
|
174
226
|
let stopped;
|
|
175
227
|
const stop = (reason) => { stopped ??= reason; throw new Error(stopped); };
|
|
228
|
+
/** A step's synthetic answer within the run's budget: past it, the dry run stops (the interpreter may wrap the throw). */
|
|
229
|
+
const synthesized = (make) => {
|
|
230
|
+
try {
|
|
231
|
+
return make();
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
if (error instanceof SynthesisTooLarge)
|
|
235
|
+
stop(error.message);
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
const deadlineMs = opts.deadlineMs ?? 60_000;
|
|
240
|
+
const deadline = Date.now() + deadlineMs;
|
|
241
|
+
const maxVisits = opts.maxVisits ?? maxSteps * 10;
|
|
242
|
+
let visits = 0;
|
|
243
|
+
const pastDeadline = () => {
|
|
244
|
+
if (Date.now() > deadline)
|
|
245
|
+
stop(`The dry run stopped past its ${deadlineMs} ms deadline.`);
|
|
246
|
+
};
|
|
247
|
+
/** A node's visit (a loop's body each iteration, a map's body for each item), counted against maxVisits and the
|
|
248
|
+
* deadline, so a loop whose body asks nothing (no step) still ends. Synchronous: it reads the clock, never a timer, so
|
|
249
|
+
* a run that never yields still stops. */
|
|
250
|
+
const visit = () => {
|
|
251
|
+
if (opts.signal?.aborted)
|
|
252
|
+
stop("The dry run was stopped before it finished.");
|
|
253
|
+
visits += 1;
|
|
254
|
+
if (visits > maxVisits)
|
|
255
|
+
stop(`The dry run stopped after ${maxVisits} node visits: on synthetic values the workflow's loops or maps go on further, asking nothing. Supply input, or lower a loop's maxIters.`);
|
|
256
|
+
pastDeadline();
|
|
257
|
+
};
|
|
176
258
|
const step = async () => {
|
|
177
259
|
if (opts.signal?.aborted)
|
|
178
260
|
stop("The dry run was stopped before it finished.");
|
|
179
261
|
steps += 1;
|
|
180
262
|
if (steps > maxSteps)
|
|
181
263
|
stop(`The dry run stopped after ${maxSteps} synthetic steps: on synthetic values the workflow's loops or maps go on further. Supply input, or lower a loop's maxIters.`);
|
|
264
|
+
pastDeadline();
|
|
182
265
|
if (steps % 64 === 0) {
|
|
183
266
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
184
267
|
if (opts.signal?.aborted)
|
|
@@ -188,13 +271,14 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
188
271
|
const runCode = opts.runCode;
|
|
189
272
|
try {
|
|
190
273
|
const result = await runWorkflow(workflow, input, {
|
|
274
|
+
onVisit: () => visit(),
|
|
191
275
|
sop: opts.sop,
|
|
192
276
|
...(runCode ? { runCode: async (...args) => { await step(); return runCode(...args); } } : {}),
|
|
193
277
|
onEvent: (event) => { if (typeof event.label === "string")
|
|
194
278
|
currentLabel = event.label; },
|
|
195
279
|
runNode: async ({ schema, review }) => {
|
|
196
280
|
await step();
|
|
197
|
-
const candidate =
|
|
281
|
+
const candidate = synthesized(() => synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend));
|
|
198
282
|
if (review)
|
|
199
283
|
await review(candidate);
|
|
200
284
|
return candidate;
|
|
@@ -202,7 +286,11 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
202
286
|
// A node that requires evidence gets a placeholder, as a provider that gives evidence would answer it.
|
|
203
287
|
runJudge: async ({ questions, evidence }) => {
|
|
204
288
|
await step();
|
|
205
|
-
|
|
289
|
+
// Its answers are synthetic values like any step's: each charged its serialized size against the run's budget (a
|
|
290
|
+
// choice's first option may be a long string, and a map collects one per item).
|
|
291
|
+
const answers = synthesizeAnswers(questions);
|
|
292
|
+
synthesized(() => charge(spend, Object.keys(answers).length, literalChars(answers)));
|
|
293
|
+
return { answers, model: "synthetic", usage: null, cost_usd: null, request_sha256: "",
|
|
206
294
|
...(evidence === "required" ? { evidence: [{ url: "https://example.invalid/dry-run", title: null, excerpts: [], scope: "dry_run" }] } : {}) };
|
|
207
295
|
},
|
|
208
296
|
syntheticEffects: true,
|
|
@@ -211,13 +299,14 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
211
299
|
await step();
|
|
212
300
|
return node.via === "shell"
|
|
213
301
|
? { code: 0, stdout: "{}", stderr: "", truncated: false }
|
|
214
|
-
:
|
|
302
|
+
: synthesized(() => synthesize(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {}, 0, spend));
|
|
215
303
|
},
|
|
216
304
|
});
|
|
217
305
|
if (result.status === "escalated") {
|
|
218
306
|
// Synthetic values tripping an escalate predicate proves nothing about real cases.
|
|
219
307
|
return { ok: true, status: "not_run", skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
|
|
220
308
|
}
|
|
309
|
+
opts.onOutput?.(result.output);
|
|
221
310
|
return { ok: true, status: "passed" };
|
|
222
311
|
}
|
|
223
312
|
catch (error) {
|