@parcha/agentrun-dsl 0.1.0-beta.18 → 0.1.0-beta.181
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 +153 -16
- package/dist/author-references.d.ts +8 -0
- package/dist/author-references.js +8 -0
- package/dist/author.d.ts +4 -3
- package/dist/author.js +20 -11
- package/dist/authoring.js +5 -4
- package/dist/cli.js +19 -13
- package/dist/code-exec.d.ts +19 -0
- package/dist/code-exec.js +54 -5
- package/dist/decision-provider.d.ts +166 -0
- package/dist/decision-provider.js +238 -0
- package/dist/decision-receipts.d.ts +64 -3
- package/dist/decision-receipts.js +50 -8
- package/dist/dry-run.d.ts +35 -1
- package/dist/dry-run.js +131 -25
- package/dist/evidence.d.ts +19 -0
- package/dist/evidence.js +63 -0
- package/dist/graph.d.ts +107 -5
- package/dist/graph.js +284 -9
- package/dist/index.d.ts +17 -12
- package/dist/index.js +16 -10
- package/dist/inspection.d.ts +5 -0
- package/dist/inspection.js +14 -1
- package/dist/pattern-screen.d.ts +14 -0
- package/dist/pattern-screen.js +451 -0
- package/dist/predicates.d.ts +29 -0
- package/dist/predicates.js +62 -3
- 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 +59 -24
- package/dist/recovery/driver.js +251 -73
- package/dist/recovery/frozen-snapshot.d.ts +54 -4
- package/dist/recovery/frozen-snapshot.js +44 -14
- package/dist/recovery/handoff-receipts.d.ts +0 -35
- package/dist/recovery/handoff-receipts.js +2 -44
- package/dist/recovery/index.d.ts +4 -8
- package/dist/recovery/index.js +4 -7
- package/dist/recovery/with-recovery.d.ts +9 -3
- package/dist/recovery/with-recovery.js +78 -18
- package/dist/submit-envelope.d.ts +9 -0
- package/dist/submit-envelope.js +44 -0
- package/dist/system-one.d.ts +21 -2
- package/dist/system-one.js +96 -18
- 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 +11 -3
- package/dist/vocabulary.js +19 -9
- package/dist/workflow-shape.d.ts +7 -0
- package/dist/workflow-shape.js +116 -70
- package/dist/workflow.d.ts +171 -19
- package/dist/workflow.js +1063 -399
- package/dist/zod-json-contract.js +6 -8
- package/package.json +12 -4
- package/schema/workflow.schema.json +366 -1
- package/skills/author/SKILL.md +6 -1
- package/skills/author/references/jev-decisions.md +50 -5
- package/skills/author/references/language.md +19 -14
- 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/dry-run.js
CHANGED
|
@@ -2,29 +2,75 @@ 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
|
+
import { isRecord } from "./record.js";
|
|
6
|
+
/** A provider for every id the workflow names, and a default: the dry run answers each decision itself, so a node's
|
|
7
|
+
* provider and timeoutMs hold it to no host's providers. */
|
|
8
|
+
function syntheticProviders(workflow) {
|
|
9
|
+
const ids = new Set(["dry-run"]);
|
|
10
|
+
JSON.stringify(workflow, (key, value) => { if (key === "provider" && typeof value === "string")
|
|
11
|
+
ids.add(value); return value; });
|
|
12
|
+
const capabilities = { types: ["noul", "choice", "score", "box"], inputs: ["text", "json", "image", "pdf", "url"], evidence: "citations",
|
|
13
|
+
probability: "none", grounding: false, replay: "deduped", maxQuestions: null, maxStateBytes: null };
|
|
14
|
+
const provider = (id) => ({ id, needs: [], capabilities, decide: async () => { throw new Error("A dry run answers its decisions itself."); } });
|
|
15
|
+
return { providers: Object.fromEntries([...ids].map((id) => [id, provider(id)])), default: "dry-run" };
|
|
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.
|
|
6
47
|
if (depth > 12 || !schema || typeof schema !== "object")
|
|
7
|
-
return null;
|
|
48
|
+
return (charge(spend, 1, 0), null);
|
|
8
49
|
const spec = schema;
|
|
9
50
|
if (typeof spec.$ref === "string") {
|
|
10
51
|
const match = /^#\/definitions\/(.+)$/.exec(spec.$ref);
|
|
11
|
-
return match && definitions[match[1]] ?
|
|
52
|
+
return match && definitions[match[1]] ? synthesize(definitions[match[1]], definitions, depth + 1, spend) : (charge(spend, 1, 0), null);
|
|
12
53
|
}
|
|
54
|
+
// A literal is charged its serialized size: one written long in the schema does not escape the character budget.
|
|
13
55
|
if (spec.const !== undefined)
|
|
14
|
-
return spec.const;
|
|
56
|
+
return (charge(spend, 1, literalChars(spec.const)), spec.const);
|
|
15
57
|
if (Array.isArray(spec.enum) && spec.enum.length)
|
|
16
|
-
return spec.enum[0];
|
|
58
|
+
return (charge(spend, 1, literalChars(spec.enum[0])), spec.enum[0]);
|
|
17
59
|
if (Array.isArray(spec.anyOf) && spec.anyOf.length) {
|
|
18
60
|
const branch = spec.anyOf.find((candidate) => candidate?.type !== "null") ?? spec.anyOf[0];
|
|
19
|
-
return
|
|
61
|
+
return synthesize(branch, definitions, depth + 1, spend);
|
|
20
62
|
}
|
|
21
63
|
if (Array.isArray(spec.oneOf) && spec.oneOf.length)
|
|
22
|
-
return
|
|
64
|
+
return synthesize(spec.oneOf[0], definitions, depth + 1, spend);
|
|
65
|
+
// The one value made below.
|
|
66
|
+
charge(spend, 1, 0);
|
|
23
67
|
const type = Array.isArray(spec.type) ? spec.type[0] : spec.type;
|
|
24
68
|
if (type === "object" || (!type && spec.properties)) {
|
|
25
69
|
const out = Object.create(null);
|
|
26
70
|
for (const [key, property] of Object.entries(spec.properties || {})) {
|
|
27
|
-
|
|
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);
|
|
28
74
|
}
|
|
29
75
|
return { ...out };
|
|
30
76
|
}
|
|
@@ -34,12 +80,17 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
|
|
|
34
80
|
const min = Number.isInteger(spec.minItems) ? spec.minItems : 1;
|
|
35
81
|
if (!spec.items)
|
|
36
82
|
return [];
|
|
37
|
-
|
|
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));
|
|
38
88
|
}
|
|
39
89
|
if (type === "string") {
|
|
40
90
|
if (spec.maxLength === 0)
|
|
41
91
|
return "";
|
|
42
92
|
const min = Number.isInteger(spec.minLength) ? spec.minLength : 1;
|
|
93
|
+
charge(spend, 0, Math.max(1, min));
|
|
43
94
|
return "x".repeat(Math.max(1, min));
|
|
44
95
|
}
|
|
45
96
|
if (type === "integer") {
|
|
@@ -79,6 +130,8 @@ export function synthesizeInstance(schema, definitions = {}, depth = 0) {
|
|
|
79
130
|
return false;
|
|
80
131
|
if (type === "null")
|
|
81
132
|
return null;
|
|
133
|
+
// A schema synthesis cannot read: one character.
|
|
134
|
+
charge(spend, 0, 1);
|
|
82
135
|
return "x";
|
|
83
136
|
}
|
|
84
137
|
function unsupportedConstructs(schema, path, found, depth = 0) {
|
|
@@ -118,7 +171,7 @@ function unsupportedConstructs(schema, path, found, depth = 0) {
|
|
|
118
171
|
export async function dryRunWorkflow(workflow, opts = {}) {
|
|
119
172
|
const valid = validateWorkflow(workflow, { ...(opts.input === undefined ? {} : { input: opts.input }), ...(opts.runCode ? { executeCode: false } : {}) });
|
|
120
173
|
if (!valid.ok)
|
|
121
|
-
return { ok: false, problems: [new WorkflowInvalidError(String(workflow?.name), valid.errors).message] };
|
|
174
|
+
return { ok: false, status: "failed", problems: [new WorkflowInvalidError(String(workflow?.name), valid.errors, valid.issues).message] };
|
|
122
175
|
const skipped = [];
|
|
123
176
|
const scanSchemas = (plan) => {
|
|
124
177
|
for (const [id, schema] of Object.entries(plan.schemas || {}))
|
|
@@ -139,20 +192,30 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
139
192
|
};
|
|
140
193
|
scanSchemas(workflow);
|
|
141
194
|
if (skipped.length)
|
|
142
|
-
return { ok: true, skipped };
|
|
195
|
+
return { ok: true, status: "not_run", skipped };
|
|
196
|
+
// One budget for everything this dry run synthesizes.
|
|
197
|
+
const spend = spendOf(opts.budget);
|
|
143
198
|
let input = opts.input ?? {};
|
|
144
199
|
if (opts.input === undefined && workflow.input) {
|
|
145
200
|
const schema = resolveSchemaForWorkflow(workflow, workflow.schemas[workflow.input.schemaId]);
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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)) {
|
|
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."] };
|
|
149
212
|
}
|
|
150
213
|
input = generated;
|
|
151
214
|
}
|
|
152
215
|
if (opts.probeContext && !Object.prototype.hasOwnProperty.call(input, "context")) {
|
|
153
216
|
input = { ...input, context: {
|
|
154
|
-
references: opts.probeContext
|
|
155
|
-
references_parsed: opts.probeContext
|
|
217
|
+
references: opts.probeContext.references ?? {},
|
|
218
|
+
references_parsed: opts.probeContext.references_parsed ?? {},
|
|
156
219
|
} };
|
|
157
220
|
}
|
|
158
221
|
let currentLabel = "";
|
|
@@ -162,12 +225,43 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
162
225
|
// Why the dry run stopped early, kept here: the interpreter may wrap what an adapter throws.
|
|
163
226
|
let stopped;
|
|
164
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
|
+
};
|
|
165
258
|
const step = async () => {
|
|
166
259
|
if (opts.signal?.aborted)
|
|
167
260
|
stop("The dry run was stopped before it finished.");
|
|
168
261
|
steps += 1;
|
|
169
262
|
if (steps > maxSteps)
|
|
170
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();
|
|
171
265
|
if (steps % 64 === 0) {
|
|
172
266
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
173
267
|
if (opts.signal?.aborted)
|
|
@@ -177,41 +271,53 @@ export async function dryRunWorkflow(workflow, opts = {}) {
|
|
|
177
271
|
const runCode = opts.runCode;
|
|
178
272
|
try {
|
|
179
273
|
const result = await runWorkflow(workflow, input, {
|
|
274
|
+
onVisit: () => visit(),
|
|
180
275
|
sop: opts.sop,
|
|
181
276
|
...(runCode ? { runCode: async (...args) => { await step(); return runCode(...args); } } : {}),
|
|
182
277
|
onEvent: (event) => { if (typeof event.label === "string")
|
|
183
278
|
currentLabel = event.label; },
|
|
184
279
|
runNode: async ({ schema, review }) => {
|
|
185
280
|
await step();
|
|
186
|
-
const candidate =
|
|
281
|
+
const candidate = synthesized(() => synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend));
|
|
187
282
|
if (review)
|
|
188
283
|
await review(candidate);
|
|
189
284
|
return candidate;
|
|
190
285
|
},
|
|
191
|
-
|
|
286
|
+
// A node that requires evidence gets a placeholder, as a provider that gives evidence would answer it.
|
|
287
|
+
runJudge: async ({ questions, evidence }) => {
|
|
288
|
+
await step();
|
|
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: "",
|
|
294
|
+
...(evidence === "required" ? { evidence: [{ url: "https://example.invalid/dry-run", title: null, excerpts: [], scope: "dry_run" }] } : {}) };
|
|
295
|
+
},
|
|
192
296
|
syntheticEffects: true,
|
|
297
|
+
decisionProviders: syntheticProviders(workflow),
|
|
193
298
|
runEffect: async ({ node, schema }) => {
|
|
194
299
|
await step();
|
|
195
300
|
return node.via === "shell"
|
|
196
301
|
? { code: 0, stdout: "{}", stderr: "", truncated: false }
|
|
197
|
-
:
|
|
302
|
+
: synthesized(() => synthesize(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {}, 0, spend));
|
|
198
303
|
},
|
|
199
304
|
});
|
|
200
305
|
if (result.status === "escalated") {
|
|
201
306
|
// Synthetic values tripping an escalate predicate proves nothing about real cases.
|
|
202
|
-
return { ok: true, skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
|
|
307
|
+
return { ok: true, status: "not_run", skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
|
|
203
308
|
}
|
|
204
|
-
|
|
309
|
+
opts.onOutput?.(result.output);
|
|
310
|
+
return { ok: true, status: "passed" };
|
|
205
311
|
}
|
|
206
312
|
catch (error) {
|
|
207
313
|
if (stopped)
|
|
208
|
-
return { ok: true, skipped: [stopped] };
|
|
314
|
+
return { ok: true, status: "not_run", skipped: [stopped] };
|
|
209
315
|
if (error instanceof WorkflowOutputInvalidError) {
|
|
210
|
-
return { ok: false, problems: error.problems, stage: error.stage };
|
|
316
|
+
return { ok: false, status: "failed", problems: error.problems, stage: error.stage };
|
|
211
317
|
}
|
|
212
318
|
if (error instanceof WorkflowInputInvalidError)
|
|
213
|
-
return { ok: false, problems: [error.message] };
|
|
319
|
+
return { ok: false, status: "failed", problems: [error.message] };
|
|
214
320
|
const message = error instanceof Error ? error.message : String(error);
|
|
215
|
-
return { ok: false, problems: [`deterministic path threw over schema-conforming inputs${currentLabel ? ` (at "${currentLabel}")` : ""}: ${message.slice(0, 1200)}`], stage: currentLabel || undefined };
|
|
321
|
+
return { ok: false, status: "failed", problems: [`deterministic path threw over schema-conforming inputs${currentLabel ? ` (at "${currentLabel}")` : ""}: ${message.slice(0, 1200)}`], stage: currentLabel || undefined };
|
|
216
322
|
}
|
|
217
323
|
}
|
|
@@ -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,63 @@
|
|
|
1
|
+
import { isRecord } from "./record.js";
|
|
2
|
+
/** The longest title an item keeps, in code points. */
|
|
3
|
+
export const EVIDENCE_TITLE_MAX = 300;
|
|
4
|
+
/** The longest passage an item keeps, in code points. */
|
|
5
|
+
export const EVIDENCE_EXCERPT_MAX = 4096;
|
|
6
|
+
/** The most passages one item keeps. */
|
|
7
|
+
export const EVIDENCE_EXCERPTS_PER_ITEM = 5;
|
|
8
|
+
/** The most items a decision's evidence keeps. */
|
|
9
|
+
export const EVIDENCE_ITEMS_MAX = 20;
|
|
10
|
+
/** The most code points of titles and passages a decision's evidence keeps, all items together. */
|
|
11
|
+
export const EVIDENCE_TEXT_MAX = 32 * 1024;
|
|
12
|
+
/** The longest `scope` an item keeps, in code points. */
|
|
13
|
+
const SCOPE_MAX = 64;
|
|
14
|
+
// C0 controls but tab, newline and return; DEL and the C1 controls; the Unicode direction marks, overrides and isolates.
|
|
15
|
+
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f--]/g;
|
|
16
|
+
const codePoints = (text) => Array.from(text).length;
|
|
17
|
+
/** `text` with its control characters gone, cut to `max` code points (an ellipsis marking a cut). */
|
|
18
|
+
function plain(text, max) {
|
|
19
|
+
const clean = text.replace(CONTROL, "");
|
|
20
|
+
const chars = Array.from(clean);
|
|
21
|
+
return chars.length <= max ? clean : `${chars.slice(0, Math.max(0, max - 1)).join("")}…`;
|
|
22
|
+
}
|
|
23
|
+
/** The URL as the parser normalizes it, if it is http(s) with no user or password; else undefined, and its item is dropped. */
|
|
24
|
+
function webUrl(url) {
|
|
25
|
+
if (typeof url !== "string")
|
|
26
|
+
return undefined;
|
|
27
|
+
const parsed = URL.parse(url);
|
|
28
|
+
if (!parsed || (parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.username || parsed.password)
|
|
29
|
+
return undefined;
|
|
30
|
+
return parsed.href;
|
|
31
|
+
}
|
|
32
|
+
/** Raw citations as a decision's evidence. Items in order, each kept or dropped by its URL, its text plain and cut, until
|
|
33
|
+
* the item count or the code-point budget is reached. With `excerpts: false` no item keeps a passage. Idempotent: clean
|
|
34
|
+
* evidence comes back as it went in. */
|
|
35
|
+
export function evidenceOf(raw, { excerpts: withExcerpts = true } = {}) {
|
|
36
|
+
const kept = [];
|
|
37
|
+
let left = EVIDENCE_TEXT_MAX;
|
|
38
|
+
for (const item of Array.isArray(raw) ? raw : []) {
|
|
39
|
+
if (kept.length >= EVIDENCE_ITEMS_MAX || left <= 0)
|
|
40
|
+
break;
|
|
41
|
+
if (!isRecord(item))
|
|
42
|
+
continue;
|
|
43
|
+
const { url: rawUrl, title: rawTitle, excerpts: rawExcerpts, scope: rawScope } = item;
|
|
44
|
+
const url = webUrl(rawUrl);
|
|
45
|
+
if (!url)
|
|
46
|
+
continue;
|
|
47
|
+
const title = typeof rawTitle === "string" ? plain(rawTitle, Math.min(EVIDENCE_TITLE_MAX, left)) : null;
|
|
48
|
+
left -= title === null ? 0 : codePoints(title);
|
|
49
|
+
const excerpts = [];
|
|
50
|
+
for (const excerpt of withExcerpts && Array.isArray(rawExcerpts) ? rawExcerpts : []) {
|
|
51
|
+
if (excerpts.length >= EVIDENCE_EXCERPTS_PER_ITEM || left <= 0)
|
|
52
|
+
break;
|
|
53
|
+
if (typeof excerpt !== "string")
|
|
54
|
+
continue;
|
|
55
|
+
const text = plain(excerpt, Math.min(EVIDENCE_EXCERPT_MAX, left));
|
|
56
|
+
excerpts.push(text);
|
|
57
|
+
left -= codePoints(text);
|
|
58
|
+
}
|
|
59
|
+
const scope = typeof rawScope === "string" && rawScope ? plain(rawScope, SCOPE_MAX) : "call";
|
|
60
|
+
kept.push({ url, title, excerpts, scope });
|
|
61
|
+
}
|
|
62
|
+
return kept;
|
|
63
|
+
}
|
package/dist/graph.d.ts
CHANGED
|
@@ -1,12 +1,36 @@
|
|
|
1
1
|
/** One node of the workflow as written. `path` is a JSON Pointer (RFC 6901) into the document: `/root` is the root,
|
|
2
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
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.
|
|
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. */
|
|
5
11
|
export type GraphNode = {
|
|
6
12
|
path: string;
|
|
7
13
|
kind: string;
|
|
8
14
|
label: string;
|
|
9
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[];
|
|
10
34
|
};
|
|
11
35
|
/** How control reaches `to` from `from`.
|
|
12
36
|
* - `next`: a chain enters its first step and each step is followed by the next; a loop enters its body, which runs again
|
|
@@ -33,8 +57,9 @@ export declare function workflowGraph(workflow: unknown): WorkflowGraph;
|
|
|
33
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
|
|
34
58
|
* goes back. A container (chain, parallel, map, loop, route, workflow) is `working` while some of
|
|
35
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
|
|
36
|
-
* them, is `not-run`.
|
|
37
|
-
|
|
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";
|
|
38
63
|
type Frame = {
|
|
39
64
|
done?: unknown;
|
|
40
65
|
steps?: unknown;
|
|
@@ -48,11 +73,21 @@ export type ItemRecordLike = {
|
|
|
48
73
|
status?: unknown;
|
|
49
74
|
frame?: Frame;
|
|
50
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
|
+
};
|
|
51
84
|
/** What `nodeStatus` reads: a driver frame (the `pin` of a frozen snapshot: `done`, `steps`, `inputs`), a frozen snapshot
|
|
52
|
-
* (its `pin`), or the map items' records, alone or together with the driver's record (`{ pin, items }`)
|
|
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. */
|
|
53
87
|
export type StatusSource = Frame | {
|
|
54
88
|
pin: Frame;
|
|
55
89
|
items?: readonly ItemRecordLike[];
|
|
90
|
+
result?: TerminalResultLike | null;
|
|
56
91
|
} | readonly ItemRecordLike[];
|
|
57
92
|
/** `item`: the source is one map item's (or loop iteration's) record, read on its own, and this is its execution path
|
|
58
93
|
* (`<map path>/items/<index>`, `<loop path>/iterations/<index>`). That item is then the instance, not one of many: its body is done
|
|
@@ -62,6 +97,73 @@ export type StatusOptions = {
|
|
|
62
97
|
};
|
|
63
98
|
/** For every node of `graph`, the state the record shows. `source` is what the driver kept: its frame and, in the keyed
|
|
64
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
|
|
65
|
-
* one of those shows no node run.
|
|
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. */
|
|
66
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;
|
|
67
169
|
export {};
|