@parcha/agentrun-dsl 0.1.0-beta.4 → 0.1.0-beta.40
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/README.md +167 -23
- package/dist/author-references.d.ts +8 -0
- package/dist/author-references.js +8 -0
- package/dist/author.d.ts +13 -5
- package/dist/author.js +47 -18
- package/dist/authoring.js +2 -2
- package/dist/cli.js +17 -12
- package/dist/code-exec.d.ts +6 -0
- package/dist/code-exec.js +126 -0
- package/dist/decision-provider.d.ts +165 -0
- package/dist/decision-provider.js +238 -0
- package/dist/decision-receipts.d.ts +159 -0
- package/dist/decision-receipts.js +93 -0
- package/dist/dry-run.d.ts +45 -2
- package/dist/dry-run.js +159 -26
- package/dist/evidence.d.ts +19 -0
- package/dist/evidence.js +62 -0
- package/dist/graph.d.ts +169 -0
- package/dist/graph.js +433 -0
- package/dist/index.d.ts +19 -11
- package/dist/index.js +14 -9
- package/dist/inspection.d.ts +5 -0
- package/dist/inspection.js +16 -3
- package/dist/job.d.ts +14 -0
- package/dist/job.js +5 -0
- package/dist/long-timer.d.ts +7 -0
- package/dist/long-timer.js +22 -0
- package/dist/observer-snapshot.d.ts +3 -0
- package/dist/observer-snapshot.js +46 -0
- package/dist/predicates.d.ts +32 -0
- package/dist/predicates.js +61 -0
- package/dist/recovery/binding.d.ts +10 -0
- package/dist/recovery/binding.js +43 -0
- package/dist/recovery/call-key.d.ts +9 -0
- package/dist/recovery/call-key.js +17 -0
- package/dist/recovery/canonical-hash.d.ts +7 -0
- package/dist/recovery/canonical-hash.js +22 -0
- package/dist/recovery/driver.d.ts +235 -0
- package/dist/recovery/driver.js +1333 -0
- package/dist/recovery/errors.d.ts +31 -0
- package/dist/recovery/errors.js +51 -0
- package/dist/recovery/execution-path.d.ts +53 -0
- package/dist/recovery/execution-path.js +167 -0
- package/dist/recovery/file-store.d.ts +7 -0
- package/dist/recovery/file-store.js +131 -0
- package/dist/recovery/frozen-snapshot.d.ts +274 -0
- package/dist/recovery/frozen-snapshot.js +187 -0
- package/dist/recovery/handoff-receipts.d.ts +7 -0
- package/dist/recovery/handoff-receipts.js +10 -0
- package/dist/recovery/index.d.ts +14 -0
- package/dist/recovery/index.js +13 -0
- package/dist/recovery/item-state.d.ts +48 -0
- package/dist/recovery/item-state.js +89 -0
- package/dist/recovery/journal.d.ts +28 -0
- package/dist/recovery/journal.js +139 -0
- package/dist/recovery/memory-store.d.ts +4 -0
- package/dist/recovery/memory-store.js +20 -0
- package/dist/recovery/store.d.ts +105 -0
- package/dist/recovery/store.js +6 -0
- package/dist/recovery/testing/conformance.d.ts +4 -0
- package/dist/recovery/testing/conformance.js +268 -0
- package/dist/recovery/testing/crash-points.d.ts +18 -0
- package/dist/recovery/testing/crash-points.js +43 -0
- package/dist/recovery/testing/crash-sweep.d.ts +65 -0
- package/dist/recovery/testing/crash-sweep.js +146 -0
- package/dist/recovery/testing/index.d.ts +3 -0
- package/dist/recovery/testing/index.js +4 -0
- package/dist/recovery/testing/preload.d.ts +1 -0
- package/dist/recovery/testing/preload.js +3 -0
- package/dist/recovery/transport-facts.d.ts +23 -0
- package/dist/recovery/transport-facts.js +46 -0
- package/dist/recovery/with-recovery.d.ts +50 -0
- package/dist/recovery/with-recovery.js +144 -0
- package/dist/submit-envelope.d.ts +9 -0
- package/dist/submit-envelope.js +40 -0
- package/dist/system-one.d.ts +40 -2
- package/dist/system-one.js +141 -6
- package/dist/testing/decision-provider.d.ts +32 -0
- package/dist/testing/decision-provider.js +183 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.js +2 -0
- package/dist/vocabulary.d.ts +31 -3
- package/dist/vocabulary.js +46 -14
- package/dist/workflow-shape.d.ts +7 -0
- package/dist/workflow-shape.js +112 -68
- package/dist/workflow.d.ts +362 -29
- package/dist/workflow.js +1844 -430
- package/package.json +27 -4
- package/schema/workflow.schema.json +551 -12
- package/skills/author/SKILL.md +6 -1
- package/skills/author/references/jev-decisions.md +69 -12
- package/skills/author/references/language.md +41 -24
- package/skills/author/references/sdk-authoring.md +2 -0
package/dist/dry-run.d.ts
CHANGED
|
@@ -1,13 +1,34 @@
|
|
|
1
|
-
import { type Workflow } from "./workflow.js";
|
|
1
|
+
import { type Workflow, type WorkflowDeps } from "./workflow.js";
|
|
2
|
+
/** `ok` keeps its meaning: false only when a check failed. `status` says whether every check ran: `passed`, `not_run`
|
|
3
|
+
* (a check stood down; `skipped` says which and why, so this is not proof the graph was exercised) or `failed`. */
|
|
2
4
|
export type DryRunResult = {
|
|
3
5
|
ok: true;
|
|
6
|
+
status: "passed" | "not_run";
|
|
4
7
|
skipped?: string[];
|
|
5
8
|
} | {
|
|
6
9
|
ok: false;
|
|
10
|
+
status: "failed";
|
|
7
11
|
problems: string[];
|
|
8
12
|
stage?: string;
|
|
9
13
|
};
|
|
10
|
-
|
|
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;
|
|
11
32
|
export type DryRunOptions = {
|
|
12
33
|
sop?: string;
|
|
13
34
|
probeContext?: {
|
|
@@ -15,5 +36,27 @@ export type DryRunOptions = {
|
|
|
15
36
|
references_parsed?: Record<string, unknown>;
|
|
16
37
|
};
|
|
17
38
|
input?: Record<string, unknown>;
|
|
39
|
+
/** The host's executor for `code` nodes (WorkflowDeps.runCode). Present, the dry run validates
|
|
40
|
+
* with executeCode:false and hands every code node to it, so no code body runs in this process. */
|
|
41
|
+
runCode?: WorkflowDeps["runCode"];
|
|
42
|
+
/** Ends the dry run: it stops at its next step, as not run. */
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
/** The most synthetic steps (an agent's or a judge's answer, an effect, a code node the host runs) before the dry run
|
|
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
|
|
46
|
+
* default. */
|
|
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;
|
|
18
61
|
};
|
|
19
62
|
export declare function dryRunWorkflow(workflow: Workflow, opts?: DryRunOptions): Promise<DryRunResult>;
|
package/dist/dry-run.js
CHANGED
|
@@ -2,29 +2,74 @@ 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
|
-
|
|
5
|
+
/** A provider for every id the workflow names, and a default: the dry run answers each decision itself, so a node's
|
|
6
|
+
* provider and timeoutMs hold it to no host's providers. */
|
|
7
|
+
function syntheticProviders(workflow) {
|
|
8
|
+
const ids = new Set(["dry-run"]);
|
|
9
|
+
JSON.stringify(workflow, (key, value) => { if (key === "provider" && typeof value === "string")
|
|
10
|
+
ids.add(value); return value; });
|
|
11
|
+
const capabilities = { types: ["noul", "choice", "score", "box"], inputs: ["text", "json", "image", "pdf", "url"], evidence: "citations",
|
|
12
|
+
probability: "none", grounding: false, replay: "deduped", maxQuestions: null, maxStateBytes: null };
|
|
13
|
+
const provider = (id) => ({ id, needs: [], capabilities, decide: async () => { throw new Error("A dry run answers its decisions itself."); } });
|
|
14
|
+
return { providers: Object.fromEntries([...ids].map((id) => [id, provider(id)])), default: "dry-run" };
|
|
15
|
+
}
|
|
16
|
+
/** The default: a million values and 16 million characters, far past what a real workflow's dry run builds (a few
|
|
17
|
+
* thousand values at most), and well within a host's memory (a few hundred MB at worst). */
|
|
18
|
+
export const SYNTHESIS_BUDGET = { values: 1_000_000, chars: 16_000_000 };
|
|
19
|
+
/** The schema asked synthesis for more than its budget: the dry run ends not run, saying so. */
|
|
20
|
+
export class SynthesisTooLarge extends Error {
|
|
21
|
+
name = "SynthesisTooLarge";
|
|
22
|
+
}
|
|
23
|
+
/** A budget's limits, each field the default unless given as a number (a field given as undefined keeps the default). */
|
|
24
|
+
const spendOf = (limit = {}) => ({
|
|
25
|
+
values: 0,
|
|
26
|
+
chars: 0,
|
|
27
|
+
limit: { values: typeof limit.values === "number" ? limit.values : SYNTHESIS_BUDGET.values, chars: typeof limit.chars === "number" ? limit.chars : SYNTHESIS_BUDGET.chars },
|
|
28
|
+
});
|
|
29
|
+
/** A literal's characters as the value it is (a const, an enum's first): its serialized size. */
|
|
30
|
+
const literalChars = (value) => JSON.stringify(value)?.length ?? 0;
|
|
31
|
+
function charge(spend, values, chars) {
|
|
32
|
+
spend.values += values;
|
|
33
|
+
spend.chars += chars;
|
|
34
|
+
if (spend.values > spend.limit.values || spend.chars > spend.limit.chars) {
|
|
35
|
+
throw new SynthesisTooLarge(`the schema is too large to synthesize: past ${spend.limit.values} values or ${spend.limit.chars} characters`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** A value of `schema` (its `$ref`s read from `definitions`), synthesized within `budget` (SYNTHESIS_BUDGET when none):
|
|
39
|
+
* past it, SynthesisTooLarge. */
|
|
40
|
+
export function synthesizeInstance(schema, definitions = {}, depth = 0, budget = SYNTHESIS_BUDGET) {
|
|
41
|
+
return synthesize(schema, definitions, depth, spendOf(budget));
|
|
42
|
+
}
|
|
43
|
+
function synthesize(schema, definitions, depth, spend) {
|
|
44
|
+
// 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
|
|
45
|
+
// of its own): past the budget it throws, having built no more than the budget.
|
|
6
46
|
if (depth > 12 || !schema || typeof schema !== "object")
|
|
7
|
-
return null;
|
|
47
|
+
return (charge(spend, 1, 0), null);
|
|
8
48
|
const spec = schema;
|
|
9
49
|
if (typeof spec.$ref === "string") {
|
|
10
50
|
const match = /^#\/definitions\/(.+)$/.exec(spec.$ref);
|
|
11
|
-
return match && definitions[match[1]] ?
|
|
51
|
+
return match && definitions[match[1]] ? synthesize(definitions[match[1]], definitions, depth + 1, spend) : (charge(spend, 1, 0), null);
|
|
12
52
|
}
|
|
53
|
+
// A literal is charged its serialized size: one written long in the schema does not escape the character budget.
|
|
13
54
|
if (spec.const !== undefined)
|
|
14
|
-
return spec.const;
|
|
55
|
+
return (charge(spend, 1, literalChars(spec.const)), spec.const);
|
|
15
56
|
if (Array.isArray(spec.enum) && spec.enum.length)
|
|
16
|
-
return spec.enum[0];
|
|
57
|
+
return (charge(spend, 1, literalChars(spec.enum[0])), spec.enum[0]);
|
|
17
58
|
if (Array.isArray(spec.anyOf) && spec.anyOf.length) {
|
|
18
59
|
const branch = spec.anyOf.find((candidate) => candidate?.type !== "null") ?? spec.anyOf[0];
|
|
19
|
-
return
|
|
60
|
+
return synthesize(branch, definitions, depth + 1, spend);
|
|
20
61
|
}
|
|
21
62
|
if (Array.isArray(spec.oneOf) && spec.oneOf.length)
|
|
22
|
-
return
|
|
63
|
+
return synthesize(spec.oneOf[0], definitions, depth + 1, spend);
|
|
64
|
+
// The one value made below.
|
|
65
|
+
charge(spend, 1, 0);
|
|
23
66
|
const type = Array.isArray(spec.type) ? spec.type[0] : spec.type;
|
|
24
67
|
if (type === "object" || (!type && spec.properties)) {
|
|
25
68
|
const out = Object.create(null);
|
|
26
69
|
for (const [key, property] of Object.entries(spec.properties || {})) {
|
|
27
|
-
|
|
70
|
+
// Its name is built into every value made under it, and serialized with it: charged before it is added.
|
|
71
|
+
charge(spend, 0, key.length);
|
|
72
|
+
out[key] = synthesize(property, definitions, depth + 1, spend);
|
|
28
73
|
}
|
|
29
74
|
return { ...out };
|
|
30
75
|
}
|
|
@@ -34,12 +79,17 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
|
|
|
34
79
|
const min = Number.isInteger(spec.minItems) ? spec.minItems : 1;
|
|
35
80
|
if (!spec.items)
|
|
36
81
|
return [];
|
|
37
|
-
|
|
82
|
+
// Each item is at least one value: a length past what the budget has left is refused before the array is made.
|
|
83
|
+
const length = Math.max(1, min);
|
|
84
|
+
if (length > spend.limit.values - spend.values)
|
|
85
|
+
charge(spend, length, 0);
|
|
86
|
+
return Array.from({ length }, () => synthesize(spec.items, definitions, depth + 1, spend));
|
|
38
87
|
}
|
|
39
88
|
if (type === "string") {
|
|
40
89
|
if (spec.maxLength === 0)
|
|
41
90
|
return "";
|
|
42
91
|
const min = Number.isInteger(spec.minLength) ? spec.minLength : 1;
|
|
92
|
+
charge(spend, 0, Math.max(1, min));
|
|
43
93
|
return "x".repeat(Math.max(1, min));
|
|
44
94
|
}
|
|
45
95
|
if (type === "integer") {
|
|
@@ -79,6 +129,8 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
|
|
|
79
129
|
return false;
|
|
80
130
|
if (type === "null")
|
|
81
131
|
return null;
|
|
132
|
+
// A schema synthesis cannot read: one character.
|
|
133
|
+
charge(spend, 0, 1);
|
|
82
134
|
return "x";
|
|
83
135
|
}
|
|
84
136
|
function unsupportedConstructs(schema, path, found, depth = 0) {
|
|
@@ -116,9 +168,9 @@ function unsupportedConstructs(schema, path, found, depth = 0) {
|
|
|
116
168
|
return found;
|
|
117
169
|
}
|
|
118
170
|
export async function dryRunWorkflow(workflow, opts = {}) {
|
|
119
|
-
const valid = validateWorkflow(workflow, opts.input === undefined ?
|
|
171
|
+
const valid = validateWorkflow(workflow, { ...(opts.input === undefined ? {} : { input: opts.input }), ...(opts.runCode ? { executeCode: false } : {}) });
|
|
120
172
|
if (!valid.ok)
|
|
121
|
-
return { ok: false, problems: [new WorkflowInvalidError(String(workflow?.name), valid.errors).message] };
|
|
173
|
+
return { ok: false, status: "failed", problems: [new WorkflowInvalidError(String(workflow?.name), valid.errors, valid.issues).message] };
|
|
122
174
|
const skipped = [];
|
|
123
175
|
const scanSchemas = (plan) => {
|
|
124
176
|
for (const [id, schema] of Object.entries(plan.schemas || {}))
|
|
@@ -139,53 +191,134 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
139
191
|
};
|
|
140
192
|
scanSchemas(workflow);
|
|
141
193
|
if (skipped.length)
|
|
142
|
-
return { ok: true, skipped };
|
|
194
|
+
return { ok: true, status: "not_run", skipped };
|
|
195
|
+
// One budget for everything this dry run synthesizes.
|
|
196
|
+
const spend = spendOf(opts.budget);
|
|
143
197
|
let input = opts.input ?? {};
|
|
144
198
|
if (opts.input === undefined && workflow.input) {
|
|
145
199
|
const schema = resolveSchemaForWorkflow(workflow, workflow.schemas[workflow.input.schemaId]);
|
|
146
|
-
|
|
200
|
+
let generated;
|
|
201
|
+
try {
|
|
202
|
+
generated = synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend);
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
if (error instanceof SynthesisTooLarge)
|
|
206
|
+
return { ok: true, status: "not_run", skipped: [error.message] };
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
147
209
|
if (!generated || typeof generated !== "object" || Array.isArray(generated) || !Compile(schema).Check(generated)) {
|
|
148
|
-
return { ok: true, skipped: ["Could not synthesize a valid input object. Supply input explicitly to dryRunWorkflow or the dry-run CLI."] };
|
|
210
|
+
return { ok: true, status: "not_run", skipped: ["Could not synthesize a valid input object. Supply input explicitly to dryRunWorkflow or the dry-run CLI."] };
|
|
149
211
|
}
|
|
150
212
|
input = generated;
|
|
151
213
|
}
|
|
152
214
|
if (opts.probeContext && !Object.prototype.hasOwnProperty.call(input, "context")) {
|
|
153
215
|
input = { ...input, context: {
|
|
154
|
-
references: opts.probeContext
|
|
155
|
-
references_parsed: opts.probeContext
|
|
216
|
+
references: opts.probeContext.references ?? {},
|
|
217
|
+
references_parsed: opts.probeContext.references_parsed ?? {},
|
|
156
218
|
} };
|
|
157
219
|
}
|
|
158
220
|
let currentLabel = "";
|
|
221
|
+
// Every synthetic step counts, and every 64th yields to the event loop, so the host can take a stop meanwhile.
|
|
222
|
+
const maxSteps = opts.maxSteps ?? 10_000;
|
|
223
|
+
let steps = 0;
|
|
224
|
+
// Why the dry run stopped early, kept here: the interpreter may wrap what an adapter throws.
|
|
225
|
+
let stopped;
|
|
226
|
+
const stop = (reason) => { stopped ??= reason; throw new Error(stopped); };
|
|
227
|
+
/** A step's synthetic answer within the run's budget: past it, the dry run stops (the interpreter may wrap the throw). */
|
|
228
|
+
const synthesized = (make) => {
|
|
229
|
+
try {
|
|
230
|
+
return make();
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
if (error instanceof SynthesisTooLarge)
|
|
234
|
+
stop(error.message);
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
const deadlineMs = opts.deadlineMs ?? 60_000;
|
|
239
|
+
const deadline = Date.now() + deadlineMs;
|
|
240
|
+
const maxVisits = opts.maxVisits ?? maxSteps * 10;
|
|
241
|
+
let visits = 0;
|
|
242
|
+
const pastDeadline = () => {
|
|
243
|
+
if (Date.now() > deadline)
|
|
244
|
+
stop(`The dry run stopped past its ${deadlineMs} ms deadline.`);
|
|
245
|
+
};
|
|
246
|
+
/** A node's visit (a loop's body each iteration, a map's body for each item), counted against maxVisits and the
|
|
247
|
+
* deadline, so a loop whose body asks nothing (no step) still ends. Synchronous: it reads the clock, never a timer, so
|
|
248
|
+
* a run that never yields still stops. */
|
|
249
|
+
const visit = () => {
|
|
250
|
+
if (opts.signal?.aborted)
|
|
251
|
+
stop("The dry run was stopped before it finished.");
|
|
252
|
+
visits += 1;
|
|
253
|
+
if (visits > maxVisits)
|
|
254
|
+
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.`);
|
|
255
|
+
pastDeadline();
|
|
256
|
+
};
|
|
257
|
+
const step = async () => {
|
|
258
|
+
if (opts.signal?.aborted)
|
|
259
|
+
stop("The dry run was stopped before it finished.");
|
|
260
|
+
steps += 1;
|
|
261
|
+
if (steps > maxSteps)
|
|
262
|
+
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.`);
|
|
263
|
+
pastDeadline();
|
|
264
|
+
if (steps % 64 === 0) {
|
|
265
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
266
|
+
if (opts.signal?.aborted)
|
|
267
|
+
stop("The dry run was stopped before it finished.");
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
const runCode = opts.runCode;
|
|
159
271
|
try {
|
|
160
272
|
const result = await runWorkflow(workflow, input, {
|
|
273
|
+
onVisit: () => visit(),
|
|
161
274
|
sop: opts.sop,
|
|
275
|
+
...(runCode ? { runCode: async (...args) => { await step(); return runCode(...args); } } : {}),
|
|
162
276
|
onEvent: (event) => { if (typeof event.label === "string")
|
|
163
277
|
currentLabel = event.label; },
|
|
164
278
|
runNode: async ({ schema, review }) => {
|
|
165
|
-
|
|
279
|
+
await step();
|
|
280
|
+
const candidate = synthesized(() => synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend));
|
|
166
281
|
if (review)
|
|
167
282
|
await review(candidate);
|
|
168
283
|
return candidate;
|
|
169
284
|
},
|
|
170
|
-
|
|
285
|
+
// A node that requires evidence gets a placeholder, as a provider that gives evidence would answer it.
|
|
286
|
+
runJudge: async ({ questions, evidence }) => {
|
|
287
|
+
await step();
|
|
288
|
+
// Its answers are synthetic values like any step's: each charged its serialized size against the run's budget (a
|
|
289
|
+
// choice's first option may be a long string, and a map collects one per item).
|
|
290
|
+
const answers = synthesizeAnswers(questions);
|
|
291
|
+
synthesized(() => charge(spend, Object.keys(answers).length, literalChars(answers)));
|
|
292
|
+
return { answers, model: "synthetic", usage: null, cost_usd: null, request_sha256: "",
|
|
293
|
+
...(evidence === "required" ? { evidence: [{ url: "https://example.invalid/dry-run", title: null, excerpts: [], scope: "dry_run" }] } : {}) };
|
|
294
|
+
},
|
|
295
|
+
// A guard never hands back on synthetic values: the dry run proves the path, not the step's answer.
|
|
296
|
+
guardStep: async () => ({ p: 1 }),
|
|
171
297
|
syntheticEffects: true,
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
298
|
+
decisionProviders: syntheticProviders(workflow),
|
|
299
|
+
runEffect: async ({ node, schema }) => {
|
|
300
|
+
await step();
|
|
301
|
+
return node.via === "shell"
|
|
302
|
+
? { code: 0, stdout: "{}", stderr: "", truncated: false }
|
|
303
|
+
: synthesized(() => synthesize(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {}, 0, spend));
|
|
304
|
+
},
|
|
175
305
|
});
|
|
176
306
|
if (result.status === "escalated") {
|
|
177
307
|
// Synthetic values tripping an escalate predicate proves nothing about real cases.
|
|
178
|
-
return { ok: true, skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
|
|
308
|
+
return { ok: true, status: "not_run", skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
|
|
179
309
|
}
|
|
180
|
-
|
|
310
|
+
opts.onOutput?.(result.output);
|
|
311
|
+
return { ok: true, status: "passed" };
|
|
181
312
|
}
|
|
182
313
|
catch (error) {
|
|
314
|
+
if (stopped)
|
|
315
|
+
return { ok: true, status: "not_run", skipped: [stopped] };
|
|
183
316
|
if (error instanceof WorkflowOutputInvalidError) {
|
|
184
|
-
return { ok: false, problems: error.problems, stage: error.stage };
|
|
317
|
+
return { ok: false, status: "failed", problems: error.problems, stage: error.stage };
|
|
185
318
|
}
|
|
186
319
|
if (error instanceof WorkflowInputInvalidError)
|
|
187
|
-
return { ok: false, problems: [error.message] };
|
|
320
|
+
return { ok: false, status: "failed", problems: [error.message] };
|
|
188
321
|
const message = error instanceof Error ? error.message : String(error);
|
|
189
|
-
return { ok: false, problems: [`deterministic path threw over schema-conforming inputs${currentLabel ? ` (at "${currentLabel}")` : ""}: ${message.slice(0, 1200)}`], stage: currentLabel || undefined };
|
|
322
|
+
return { ok: false, status: "failed", problems: [`deterministic path threw over schema-conforming inputs${currentLabel ? ` (at "${currentLabel}")` : ""}: ${message.slice(0, 1200)}`], stage: currentLabel || undefined };
|
|
190
323
|
}
|
|
191
324
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { DecisionEvidence } from "./decision-provider.js";
|
|
2
|
+
/** The longest title an item keeps, in code points. */
|
|
3
|
+
export declare const EVIDENCE_TITLE_MAX = 300;
|
|
4
|
+
/** The longest passage an item keeps, in code points. */
|
|
5
|
+
export declare const EVIDENCE_EXCERPT_MAX = 4096;
|
|
6
|
+
/** The most passages one item keeps. */
|
|
7
|
+
export declare const EVIDENCE_EXCERPTS_PER_ITEM = 5;
|
|
8
|
+
/** The most items a decision's evidence keeps. */
|
|
9
|
+
export declare const EVIDENCE_ITEMS_MAX = 20;
|
|
10
|
+
/** The most code points of titles and passages a decision's evidence keeps, all items together. */
|
|
11
|
+
export declare const EVIDENCE_TEXT_MAX: number;
|
|
12
|
+
/** What a caller keeps of each citation: `excerpts: false` keeps none of its passages. */
|
|
13
|
+
export type EvidenceOptions = {
|
|
14
|
+
excerpts?: boolean;
|
|
15
|
+
};
|
|
16
|
+
/** Raw citations as a decision's evidence. Items in order, each kept or dropped by its URL, its text plain and cut, until
|
|
17
|
+
* the item count or the code-point budget is reached. With `excerpts: false` no item keeps a passage. Idempotent: clean
|
|
18
|
+
* evidence comes back as it went in. */
|
|
19
|
+
export declare function evidenceOf(raw: unknown, { excerpts: withExcerpts }?: EvidenceOptions): DecisionEvidence[];
|
package/dist/evidence.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** The longest title an item keeps, in code points. */
|
|
2
|
+
export const EVIDENCE_TITLE_MAX = 300;
|
|
3
|
+
/** The longest passage an item keeps, in code points. */
|
|
4
|
+
export const EVIDENCE_EXCERPT_MAX = 4096;
|
|
5
|
+
/** The most passages one item keeps. */
|
|
6
|
+
export const EVIDENCE_EXCERPTS_PER_ITEM = 5;
|
|
7
|
+
/** The most items a decision's evidence keeps. */
|
|
8
|
+
export const EVIDENCE_ITEMS_MAX = 20;
|
|
9
|
+
/** The most code points of titles and passages a decision's evidence keeps, all items together. */
|
|
10
|
+
export const EVIDENCE_TEXT_MAX = 32 * 1024;
|
|
11
|
+
/** The longest `scope` an item keeps, in code points. */
|
|
12
|
+
const SCOPE_MAX = 64;
|
|
13
|
+
// C0 controls but tab, newline and return; DEL and the C1 controls; the Unicode direction marks, overrides and isolates.
|
|
14
|
+
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f--]/g;
|
|
15
|
+
const codePoints = (text) => Array.from(text).length;
|
|
16
|
+
/** `text` with its control characters gone, cut to `max` code points (an ellipsis marking a cut). */
|
|
17
|
+
function plain(text, max) {
|
|
18
|
+
const clean = text.replace(CONTROL, "");
|
|
19
|
+
const chars = Array.from(clean);
|
|
20
|
+
return chars.length <= max ? clean : `${chars.slice(0, Math.max(0, max - 1)).join("")}…`;
|
|
21
|
+
}
|
|
22
|
+
/** The URL as the parser normalizes it, if it is http(s) with no user or password; else undefined, and its item is dropped. */
|
|
23
|
+
function webUrl(url) {
|
|
24
|
+
if (typeof url !== "string")
|
|
25
|
+
return undefined;
|
|
26
|
+
const parsed = URL.parse(url);
|
|
27
|
+
if (!parsed || (parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password)
|
|
28
|
+
return undefined;
|
|
29
|
+
return parsed.href;
|
|
30
|
+
}
|
|
31
|
+
/** Raw citations as a decision's evidence. Items in order, each kept or dropped by its URL, its text plain and cut, until
|
|
32
|
+
* the item count or the code-point budget is reached. With `excerpts: false` no item keeps a passage. Idempotent: clean
|
|
33
|
+
* evidence comes back as it went in. */
|
|
34
|
+
export function evidenceOf(raw, { excerpts: withExcerpts = true } = {}) {
|
|
35
|
+
const kept = [];
|
|
36
|
+
let left = EVIDENCE_TEXT_MAX;
|
|
37
|
+
for (const item of Array.isArray(raw) ? raw : []) {
|
|
38
|
+
if (kept.length >= EVIDENCE_ITEMS_MAX || left <= 0)
|
|
39
|
+
break;
|
|
40
|
+
if (!item || typeof item !== "object" || Array.isArray(item))
|
|
41
|
+
continue;
|
|
42
|
+
const { url: rawUrl, title: rawTitle, excerpts: rawExcerpts, scope: rawScope } = item;
|
|
43
|
+
const url = webUrl(rawUrl);
|
|
44
|
+
if (!url)
|
|
45
|
+
continue;
|
|
46
|
+
const title = typeof rawTitle === "string" ? plain(rawTitle, Math.min(EVIDENCE_TITLE_MAX, left)) : null;
|
|
47
|
+
left -= title === null ? 0 : codePoints(title);
|
|
48
|
+
const excerpts = [];
|
|
49
|
+
for (const excerpt of withExcerpts && Array.isArray(rawExcerpts) ? rawExcerpts : []) {
|
|
50
|
+
if (excerpts.length >= EVIDENCE_EXCERPTS_PER_ITEM || left <= 0)
|
|
51
|
+
break;
|
|
52
|
+
if (typeof excerpt !== "string")
|
|
53
|
+
continue;
|
|
54
|
+
const text = plain(excerpt, Math.min(EVIDENCE_EXCERPT_MAX, left));
|
|
55
|
+
excerpts.push(text);
|
|
56
|
+
left -= codePoints(text);
|
|
57
|
+
}
|
|
58
|
+
const scope = typeof rawScope === "string" && rawScope ? plain(rawScope, SCOPE_MAX) : "call";
|
|
59
|
+
kept.push({ url, title, excerpts, scope });
|
|
60
|
+
}
|
|
61
|
+
return kept;
|
|
62
|
+
}
|
package/dist/graph.d.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/** One node of the workflow as written. `path` is a JSON Pointer (RFC 6901) into the document: `/root` is the root,
|
|
2
|
+
* `/root/steps/1` a chain's second step, `/root/branches/<name>/body` a route's branch, `/root/body` a map's or a
|
|
3
|
+
* loop's body, `/root/workflow/root` a child workflow's root: the pointers `inspectWorkflow` and a validation issue
|
|
4
|
+
* use for the same node. `label` is the node's label, or its kind when it has none. `via` is a `call` node's transport.
|
|
5
|
+
* `changeCheck` detects a change to the node's own fields from one graph to another: 8 hex digits, the FNV-1a hash of
|
|
6
|
+
* the canonical JSON (keys sorted) of the node with its children left out as the walk leaves them out (a chain's steps,
|
|
7
|
+
* a parallel's branches, a map's or a loop's body, each route branch's body, a child workflow's root). A route's branch
|
|
8
|
+
* names are its own fields, since they decide which branch runs, so a route that gains or loses a branch is rewritten. It
|
|
9
|
+
* is not an identity and not a saved revision's sha256: two nodes with the same check are not the same node, and a check
|
|
10
|
+
* that stayed only means no change was seen. A graph built by hand may leave it out. */
|
|
11
|
+
export type GraphNode = {
|
|
12
|
+
path: string;
|
|
13
|
+
kind: string;
|
|
14
|
+
label: string;
|
|
15
|
+
via?: string;
|
|
16
|
+
changeCheck?: string;
|
|
17
|
+
} & GraphDecision;
|
|
18
|
+
/** One typed question a decision node asks, as a viewer shows it: its id, its type (`unknown` when its schema is not a
|
|
19
|
+
* question the reader recognizes), its instructions, and a choice's options. */
|
|
20
|
+
export type GraphQuestion = {
|
|
21
|
+
id: string;
|
|
22
|
+
type: "noul" | "choice" | "score" | "unknown";
|
|
23
|
+
instructions: string;
|
|
24
|
+
options?: string[];
|
|
25
|
+
};
|
|
26
|
+
/** What a decision node (judge, pick, sift, a judged route, or a loop or escalate whose predicate is `ask`) says about
|
|
27
|
+
* its decision, read from the document: the provider and model it names (absent when it names none), its questions, and
|
|
28
|
+
* the tokens of the images it sends. A graph of another node carries none of these. */
|
|
29
|
+
export type GraphDecision = {
|
|
30
|
+
provider?: string;
|
|
31
|
+
model?: string;
|
|
32
|
+
questions?: GraphQuestion[];
|
|
33
|
+
images?: string[];
|
|
34
|
+
};
|
|
35
|
+
/** How control reaches `to` from `from`.
|
|
36
|
+
* - `next`: a chain enters its first step and each step is followed by the next; a loop enters its body, which runs again
|
|
37
|
+
* until the loop ends.
|
|
38
|
+
* - `branch`: a parallel node starts each of its branches.
|
|
39
|
+
* - `route`: a route node takes one of its branches (the branch's name is the last pointer segment before `/body`).
|
|
40
|
+
* - `item`: a map runs its body once for each item.
|
|
41
|
+
* - `child`: a workflow node runs the child workflow's root. */
|
|
42
|
+
export type GraphEdgeKind = "next" | "branch" | "route" | "item" | "child";
|
|
43
|
+
export type GraphEdge = {
|
|
44
|
+
from: string;
|
|
45
|
+
to: string;
|
|
46
|
+
kind: GraphEdgeKind;
|
|
47
|
+
};
|
|
48
|
+
export type WorkflowGraph = {
|
|
49
|
+
nodes: GraphNode[];
|
|
50
|
+
edges: GraphEdge[];
|
|
51
|
+
};
|
|
52
|
+
/** The graph of `workflow`, computed from its JSON alone: nodes in document order (a node, then its descendants), and the
|
|
53
|
+
* edges between them. A value that is not a workflow, or a node the walk does not know, adds nothing and never throws:
|
|
54
|
+
* validation is `validateWorkflow`'s. */
|
|
55
|
+
export declare function workflowGraph(workflow: unknown): WorkflowGraph;
|
|
56
|
+
/** What a run has done at a node. A node inside a map's or a loop's body stands for every item or iteration, and the record names
|
|
57
|
+
* only those that started, so it is `done` only once the map or loop is: until then it is `working`, and a done node never
|
|
58
|
+
* goes back. A container (chain, parallel, map, loop, route, workflow) is `working` while some of
|
|
59
|
+
* its descendants are, or some are done and it is not; a node a run never reached, a branch a route did not take among
|
|
60
|
+
* them, is `not-run`. `escalated` is where the run ended on an escalation: the escalate node that fired and each container
|
|
61
|
+
* on its path. It is read from the run's terminal result, never from the frame, which holds no mark for that node. */
|
|
62
|
+
export type NodeState = "done" | "working" | "failed" | "not-run" | "escalated";
|
|
63
|
+
type Frame = {
|
|
64
|
+
done?: unknown;
|
|
65
|
+
steps?: unknown;
|
|
66
|
+
inputs?: unknown;
|
|
67
|
+
partial?: unknown;
|
|
68
|
+
};
|
|
69
|
+
/** The part of an `agentrun.items` value the status reads: the map item's `status` and its frame. */
|
|
70
|
+
export type ItemRecordLike = {
|
|
71
|
+
map?: unknown;
|
|
72
|
+
index?: unknown;
|
|
73
|
+
status?: unknown;
|
|
74
|
+
frame?: Frame;
|
|
75
|
+
};
|
|
76
|
+
/** The part of a run's terminal result the status reads: its `status` and, for an escalation, the execution path of the
|
|
77
|
+
* node it stopped at (`escalation.executionPath`, as `runWorkflow` returns it). */
|
|
78
|
+
export type TerminalResultLike = {
|
|
79
|
+
status?: unknown;
|
|
80
|
+
escalation?: {
|
|
81
|
+
executionPath?: unknown;
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
/** What `nodeStatus` reads: a driver frame (the `pin` of a frozen snapshot: `done`, `steps`, `inputs`), a frozen snapshot
|
|
85
|
+
* (its `pin`), or the map items' records, alone or together with the driver's record (`{ pin, items }`), and with it the
|
|
86
|
+
* run's terminal `result` once the run has ended. */
|
|
87
|
+
export type StatusSource = Frame | {
|
|
88
|
+
pin: Frame;
|
|
89
|
+
items?: readonly ItemRecordLike[];
|
|
90
|
+
result?: TerminalResultLike | null;
|
|
91
|
+
} | readonly ItemRecordLike[];
|
|
92
|
+
/** `item`: the source is one map item's (or loop iteration's) record, read on its own, and this is its execution path
|
|
93
|
+
* (`<map path>/items/<index>`, `<loop path>/iterations/<index>`). That item is then the instance, not one of many: its body is done
|
|
94
|
+
* when the item is, whether or not the map is. A map or loop inside the item still stands for all of its own items. */
|
|
95
|
+
export type StatusOptions = {
|
|
96
|
+
item?: string;
|
|
97
|
+
};
|
|
98
|
+
/** For every node of `graph`, the state the record shows. `source` is what the driver kept: its frame and, in the keyed
|
|
99
|
+
* layout, the records of the map items (a run's whole story is the frame and the items together). A source that is not
|
|
100
|
+
* one of those shows no node run. With the run's terminal `result`, an escalation that names a node of the graph marks
|
|
101
|
+
* that node and every container on its path `escalated`, and the maps and loops on that path have ended, so what finished
|
|
102
|
+
* inside them is done; without one, or when it names no node of the graph, nothing else changes. */
|
|
103
|
+
export declare function nodeStatus(graph: WorkflowGraph, source: StatusSource, options?: StatusOptions): Record<string, NodeState>;
|
|
104
|
+
/** Where an execution path is in the graph: the node it ran at (`path`, a node of the graph) and the map items and loop
|
|
105
|
+
* iterations it ran in, outermost first. */
|
|
106
|
+
export type GraphNodeAt = {
|
|
107
|
+
path: string;
|
|
108
|
+
at: {
|
|
109
|
+
kind: "item" | "iteration";
|
|
110
|
+
index: number;
|
|
111
|
+
}[];
|
|
112
|
+
};
|
|
113
|
+
/** The graph node an execution path ran at. An execution path is the node's JSON Pointer with two runtime segments added:
|
|
114
|
+
* a map's item (`items/<i>` before the map's `body`) and a loop's iteration (`iterations/<i>` before the loop's `body`); the
|
|
115
|
+
* graph has `/body` for both, and the indexes are returned in `at`. The path is read by walking the graph from `/root`, by
|
|
116
|
+
* each node's kind, never by matching its text, so a route branch named `items` or `iterations` is a branch. Undefined for
|
|
117
|
+
* a path the graph does not have, or one that is not an execution path (a map's `body` without an item, an item without
|
|
118
|
+
* its `body`). */
|
|
119
|
+
export declare function graphNodeOf(graph: WorkflowGraph, executionPath: string): GraphNodeAt | undefined;
|
|
120
|
+
/** A node as `graphDiff` reports it: its path in the graph it is in, its kind and its label. */
|
|
121
|
+
export type GraphDiffNode = {
|
|
122
|
+
path: string;
|
|
123
|
+
kind: string;
|
|
124
|
+
label: string;
|
|
125
|
+
};
|
|
126
|
+
/** What changed from one graph to the next. `added` holds nodes of `next` only (paths in `next`), `removed` nodes of `prev`
|
|
127
|
+
* only (paths in `prev`); `changed` the same node at the same path with a new kind or label; `moved` the same node at a
|
|
128
|
+
* new path; `rewritten` the same node, its kind and label as they were, with other own fields changed (its `changeCheck`
|
|
129
|
+
* differs: new instructions, a new budget), at its path in each graph; `edges.added` edges of `next` only and
|
|
130
|
+
* `edges.removed` edges of `prev` only, each in its own graph's paths. */
|
|
131
|
+
export type GraphDiff = {
|
|
132
|
+
added: GraphDiffNode[];
|
|
133
|
+
removed: GraphDiffNode[];
|
|
134
|
+
changed: {
|
|
135
|
+
prev: string;
|
|
136
|
+
next: string;
|
|
137
|
+
was: {
|
|
138
|
+
kind: string;
|
|
139
|
+
label: string;
|
|
140
|
+
};
|
|
141
|
+
now: {
|
|
142
|
+
kind: string;
|
|
143
|
+
label: string;
|
|
144
|
+
};
|
|
145
|
+
}[];
|
|
146
|
+
moved: {
|
|
147
|
+
prev: string;
|
|
148
|
+
next: string;
|
|
149
|
+
}[];
|
|
150
|
+
rewritten: {
|
|
151
|
+
prev: string;
|
|
152
|
+
next: string;
|
|
153
|
+
kind: string;
|
|
154
|
+
label: string;
|
|
155
|
+
}[];
|
|
156
|
+
edges: {
|
|
157
|
+
added: GraphEdge[];
|
|
158
|
+
removed: GraphEdge[];
|
|
159
|
+
};
|
|
160
|
+
};
|
|
161
|
+
/** What changed between two graphs of a workflow, such as two saved revisions of one. A node is the same in both when its
|
|
162
|
+
* `(kind, label)` is unique in each graph, wherever it is: a step inserted before others is one `added` node and the rest
|
|
163
|
+
* `moved`, never a run of changes. A node whose `(kind, label)` repeats in either graph, or is in one only, is the same
|
|
164
|
+
* as the other graph's node at its path, unless that node is already matched by its identity; with a new kind or label
|
|
165
|
+
* it is `changed`. A matched node with its kind and label as they were and another `changeCheck` is `rewritten`; a node
|
|
166
|
+
* without a check in either graph is never reported rewritten. An edge is the same when both its ends are the same nodes
|
|
167
|
+
* and its kind is the same. Every list is in its graph's node or edge order. */
|
|
168
|
+
export declare function graphDiff(prev: WorkflowGraph, next: WorkflowGraph): GraphDiff;
|
|
169
|
+
export {};
|