@parcha/agentrun-dsl 0.1.0-beta.13 → 0.1.0-beta.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +155 -16
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +4 -3
  6. package/dist/author.js +20 -11
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +64 -3
  14. package/dist/decision-receipts.js +50 -8
  15. package/dist/dry-run.d.ts +41 -1
  16. package/dist/dry-run.js +158 -27
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +169 -0
  20. package/dist/graph.js +433 -0
  21. package/dist/index.d.ts +19 -12
  22. package/dist/index.js +17 -10
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +14 -1
  25. package/dist/job.d.ts +14 -0
  26. package/dist/job.js +5 -0
  27. package/dist/pattern-screen.d.ts +14 -0
  28. package/dist/pattern-screen.js +451 -0
  29. package/dist/predicates.d.ts +29 -0
  30. package/dist/predicates.js +62 -3
  31. package/dist/record.d.ts +4 -0
  32. package/dist/record.js +6 -0
  33. package/dist/recovery/binding.js +2 -1
  34. package/dist/recovery/call-key.d.ts +0 -4
  35. package/dist/recovery/call-key.js +0 -7
  36. package/dist/recovery/canonical-hash.d.ts +1 -1
  37. package/dist/recovery/canonical-hash.js +3 -3
  38. package/dist/recovery/driver.d.ts +79 -24
  39. package/dist/recovery/driver.js +634 -78
  40. package/dist/recovery/execution-path.d.ts +8 -0
  41. package/dist/recovery/execution-path.js +14 -0
  42. package/dist/recovery/frozen-snapshot.d.ts +128 -3
  43. package/dist/recovery/frozen-snapshot.js +63 -12
  44. package/dist/recovery/handoff-receipts.d.ts +0 -35
  45. package/dist/recovery/handoff-receipts.js +2 -44
  46. package/dist/recovery/index.d.ts +6 -10
  47. package/dist/recovery/index.js +5 -8
  48. package/dist/recovery/item-state.d.ts +48 -0
  49. package/dist/recovery/item-state.js +89 -0
  50. package/dist/recovery/journal.d.ts +6 -3
  51. package/dist/recovery/journal.js +20 -8
  52. package/dist/recovery/store.d.ts +33 -9
  53. package/dist/recovery/testing/conformance.js +55 -0
  54. package/dist/recovery/with-recovery.d.ts +9 -3
  55. package/dist/recovery/with-recovery.js +78 -18
  56. package/dist/submit-envelope.d.ts +9 -0
  57. package/dist/submit-envelope.js +44 -0
  58. package/dist/system-one.d.ts +37 -2
  59. package/dist/system-one.js +112 -18
  60. package/dist/testing/decision-provider.d.ts +32 -0
  61. package/dist/testing/decision-provider.js +183 -0
  62. package/dist/testing/index.d.ts +1 -0
  63. package/dist/testing/index.js +2 -0
  64. package/dist/vocabulary.d.ts +11 -3
  65. package/dist/vocabulary.js +19 -9
  66. package/dist/workflow-shape.d.ts +7 -0
  67. package/dist/workflow-shape.js +116 -70
  68. package/dist/workflow.d.ts +173 -18
  69. package/dist/workflow.js +1103 -398
  70. package/dist/zod-json-contract.js +6 -8
  71. package/package.json +19 -4
  72. package/schema/workflow.schema.json +366 -1
  73. package/skills/author/SKILL.md +6 -1
  74. package/skills/author/references/jev-decisions.md +50 -5
  75. package/skills/author/references/language.md +19 -14
  76. package/skills/author/references/sdk-authoring.md +2 -0
  77. package/dist/recovery/effect-failure.d.ts +0 -34
  78. package/dist/recovery/effect-failure.js +0 -62
  79. package/dist/recovery/handoff-block.d.ts +0 -36
  80. package/dist/recovery/handoff-block.js +0 -148
  81. package/dist/recovery/handoff-digest.d.ts +0 -58
  82. package/dist/recovery/handoff-digest.js +0 -195
  83. package/dist/recovery/handoff-files.d.ts +0 -54
  84. package/dist/recovery/handoff-files.js +0 -162
  85. package/dist/recovery/handoff-redact.d.ts +0 -12
  86. package/dist/recovery/handoff-redact.js +0 -44
  87. package/dist/recovery/handoff.d.ts +0 -44
  88. 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
- export function synthesizeInstance(schema, definitions = {}, depth = 0) {
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]] ? synthesizeInstance(definitions[match[1]], definitions, depth + 1) : null;
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 synthesizeInstance(branch, definitions, depth + 1);
61
+ return synthesize(branch, definitions, depth + 1, spend);
20
62
  }
21
63
  if (Array.isArray(spec.oneOf) && spec.oneOf.length)
22
- return synthesizeInstance(spec.oneOf[0], definitions, depth + 1);
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
- out[key] = synthesizeInstance(property, definitions, depth + 1);
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
- return Array.from({ length: Math.max(1, min) }, () => synthesizeInstance(spec.items, definitions, depth + 1));
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,54 +192,132 @@ 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
- const generated = synthesizeInstance(schema, schema.definitions ?? workflow.schemas);
147
- 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."] };
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?.references ?? {},
155
- references_parsed: opts.probeContext?.references_parsed ?? {},
217
+ references: opts.probeContext.references ?? {},
218
+ references_parsed: opts.probeContext.references_parsed ?? {},
156
219
  } };
157
220
  }
158
221
  let currentLabel = "";
222
+ // Every synthetic step counts, and every 64th yields to the event loop, so the host can take a stop meanwhile.
223
+ const maxSteps = opts.maxSteps ?? 10_000;
224
+ let steps = 0;
225
+ // Why the dry run stopped early, kept here: the interpreter may wrap what an adapter throws.
226
+ let stopped;
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
+ };
258
+ const step = async () => {
259
+ if (opts.signal?.aborted)
260
+ stop("The dry run was stopped before it finished.");
261
+ steps += 1;
262
+ if (steps > maxSteps)
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();
265
+ if (steps % 64 === 0) {
266
+ await new Promise((resolve) => setTimeout(resolve, 0));
267
+ if (opts.signal?.aborted)
268
+ stop("The dry run was stopped before it finished.");
269
+ }
270
+ };
271
+ const runCode = opts.runCode;
159
272
  try {
160
273
  const result = await runWorkflow(workflow, input, {
274
+ onVisit: () => visit(),
161
275
  sop: opts.sop,
162
- ...(opts.runCode ? { runCode: opts.runCode } : {}),
276
+ ...(runCode ? { runCode: async (...args) => { await step(); return runCode(...args); } } : {}),
163
277
  onEvent: (event) => { if (typeof event.label === "string")
164
278
  currentLabel = event.label; },
165
279
  runNode: async ({ schema, review }) => {
166
- const candidate = synthesizeInstance(schema, schema.definitions ?? workflow.schemas);
280
+ await step();
281
+ const candidate = synthesized(() => synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend));
167
282
  if (review)
168
283
  await review(candidate);
169
284
  return candidate;
170
285
  },
171
- runJudge: async ({ questions }) => ({ answers: synthesizeAnswers(questions), model: "synthetic", usage: null, cost_usd: null, request_sha256: "" }),
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
+ },
172
296
  syntheticEffects: true,
173
- runEffect: async ({ node, schema }) => node.via === "shell"
174
- ? { code: 0, stdout: "{}", stderr: "", truncated: false }
175
- : synthesizeInstance(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {}),
297
+ decisionProviders: syntheticProviders(workflow),
298
+ runEffect: async ({ node, schema }) => {
299
+ await step();
300
+ return node.via === "shell"
301
+ ? { code: 0, stdout: "{}", stderr: "", truncated: false }
302
+ : synthesized(() => synthesize(schema ?? (workflow.schemas || {})[node.out], schema?.definitions ?? workflow.schemas ?? {}, 0, spend));
303
+ },
176
304
  });
177
305
  if (result.status === "escalated") {
178
306
  // Synthetic values tripping an escalate predicate proves nothing about real cases.
179
- 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`] };
180
308
  }
181
- return { ok: true };
309
+ opts.onOutput?.(result.output);
310
+ return { ok: true, status: "passed" };
182
311
  }
183
312
  catch (error) {
313
+ if (stopped)
314
+ return { ok: true, status: "not_run", skipped: [stopped] };
184
315
  if (error instanceof WorkflowOutputInvalidError) {
185
- return { ok: false, problems: error.problems, stage: error.stage };
316
+ return { ok: false, status: "failed", problems: error.problems, stage: error.stage };
186
317
  }
187
318
  if (error instanceof WorkflowInputInvalidError)
188
- return { ok: false, problems: [error.message] };
319
+ return { ok: false, status: "failed", problems: [error.message] };
189
320
  const message = error instanceof Error ? error.message : String(error);
190
- 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 };
191
322
  }
192
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[];
@@ -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
+ }
@@ -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 {};