@parcha/agentrun-dsl 0.1.0-beta.2 → 0.1.0-beta.200

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 (111) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +172 -22
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +97 -0
  6. package/dist/author.js +329 -0
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +25 -0
  10. package/dist/code-exec.js +180 -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 +159 -0
  14. package/dist/decision-receipts.js +93 -0
  15. package/dist/dry-run.d.ts +45 -2
  16. package/dist/dry-run.js +159 -27
  17. package/dist/edit.d.ts +149 -0
  18. package/dist/edit.js +1415 -0
  19. package/dist/evidence.d.ts +19 -0
  20. package/dist/evidence.js +63 -0
  21. package/dist/graph.d.ts +169 -0
  22. package/dist/graph.js +433 -0
  23. package/dist/index.d.ts +20 -7
  24. package/dist/index.js +17 -7
  25. package/dist/inspection.d.ts +5 -0
  26. package/dist/inspection.js +16 -3
  27. package/dist/job.d.ts +14 -0
  28. package/dist/job.js +5 -0
  29. package/dist/long-timer.d.ts +7 -0
  30. package/dist/long-timer.js +22 -0
  31. package/dist/observer-snapshot.d.ts +3 -0
  32. package/dist/observer-snapshot.js +46 -0
  33. package/dist/pattern-screen.d.ts +14 -0
  34. package/dist/pattern-screen.js +451 -0
  35. package/dist/predicates.d.ts +33 -0
  36. package/dist/predicates.js +81 -5
  37. package/dist/record.d.ts +4 -0
  38. package/dist/record.js +6 -0
  39. package/dist/recovery/binding.d.ts +10 -0
  40. package/dist/recovery/binding.js +44 -0
  41. package/dist/recovery/call-key.d.ts +9 -0
  42. package/dist/recovery/call-key.js +17 -0
  43. package/dist/recovery/canonical-hash.d.ts +7 -0
  44. package/dist/recovery/canonical-hash.js +22 -0
  45. package/dist/recovery/driver.d.ts +245 -0
  46. package/dist/recovery/driver.js +1347 -0
  47. package/dist/recovery/errors.d.ts +31 -0
  48. package/dist/recovery/errors.js +51 -0
  49. package/dist/recovery/execution-path.d.ts +53 -0
  50. package/dist/recovery/execution-path.js +167 -0
  51. package/dist/recovery/file-store.d.ts +7 -0
  52. package/dist/recovery/file-store.js +131 -0
  53. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  54. package/dist/recovery/frozen-snapshot.js +187 -0
  55. package/dist/recovery/handoff-receipts.d.ts +7 -0
  56. package/dist/recovery/handoff-receipts.js +11 -0
  57. package/dist/recovery/index.d.ts +14 -0
  58. package/dist/recovery/index.js +13 -0
  59. package/dist/recovery/item-state.d.ts +48 -0
  60. package/dist/recovery/item-state.js +89 -0
  61. package/dist/recovery/journal.d.ts +28 -0
  62. package/dist/recovery/journal.js +139 -0
  63. package/dist/recovery/memory-store.d.ts +4 -0
  64. package/dist/recovery/memory-store.js +20 -0
  65. package/dist/recovery/store.d.ts +105 -0
  66. package/dist/recovery/store.js +6 -0
  67. package/dist/recovery/testing/conformance.d.ts +4 -0
  68. package/dist/recovery/testing/conformance.js +268 -0
  69. package/dist/recovery/testing/crash-points.d.ts +18 -0
  70. package/dist/recovery/testing/crash-points.js +43 -0
  71. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  72. package/dist/recovery/testing/crash-sweep.js +146 -0
  73. package/dist/recovery/testing/index.d.ts +3 -0
  74. package/dist/recovery/testing/index.js +4 -0
  75. package/dist/recovery/testing/preload.d.ts +1 -0
  76. package/dist/recovery/testing/preload.js +3 -0
  77. package/dist/recovery/transport-facts.d.ts +23 -0
  78. package/dist/recovery/transport-facts.js +46 -0
  79. package/dist/recovery/with-recovery.d.ts +50 -0
  80. package/dist/recovery/with-recovery.js +144 -0
  81. package/dist/submit-envelope.d.ts +9 -0
  82. package/dist/submit-envelope.js +44 -0
  83. package/dist/system-one.d.ts +37 -2
  84. package/dist/system-one.js +146 -11
  85. package/dist/testing/decision-provider.d.ts +32 -0
  86. package/dist/testing/decision-provider.js +183 -0
  87. package/dist/testing/index.d.ts +1 -0
  88. package/dist/testing/index.js +2 -0
  89. package/dist/vocabulary.d.ts +50 -0
  90. package/dist/vocabulary.js +84 -0
  91. package/dist/workflow-shape.d.ts +7 -0
  92. package/dist/workflow-shape.js +119 -69
  93. package/dist/workflow.d.ts +309 -29
  94. package/dist/workflow.js +1664 -487
  95. package/dist/zod-json-contract.js +6 -8
  96. package/package.json +33 -5
  97. package/schema/workflow.schema.json +599 -12
  98. package/skills/author/SKILL.md +125 -0
  99. package/skills/author/examples/evidence-gate.input.json +6 -0
  100. package/skills/author/examples/evidence-gate.json +125 -0
  101. package/skills/author/examples/read-file.input.json +1 -0
  102. package/skills/author/examples/read-file.json +44 -0
  103. package/skills/author/examples/read-source-decision.input.json +4 -0
  104. package/skills/author/examples/read-source-decision.json +37 -0
  105. package/skills/author/examples/release-note.txt +10 -0
  106. package/skills/author/examples/review-release-notes.input.json +6 -0
  107. package/skills/author/examples/review-release-notes.json +123 -0
  108. package/skills/author/references/jev-decisions.md +170 -0
  109. package/skills/author/references/language.md +123 -0
  110. package/skills/author/references/sdk-authoring.md +11 -0
  111. package/skills/author/references/workflow-format.md +137 -0
@@ -0,0 +1,159 @@
1
+ import type { CostBasis, DecisionEvidence } from "./decision-provider.js";
2
+ import { type ConfidenceSource, type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
3
+ export declare const DECISION_RECEIPT_VERSION = 1;
4
+ /** The escalation kind of a decision its provider refused: the run ends `escalated` at stage "decision", for a person. */
5
+ export declare const DECISION_REFUSED = "decision_refused";
6
+ /** The escalation kind of a run whose decision was asked by an earlier process and never answered there: it is routed to
7
+ * review instead of being asked, and paid for, again. Its stage is `decision`. */
8
+ export declare const DECISION_INTERRUPTED = "decision_interrupted";
9
+ /** The most of the state a receipt keeps, as UTF-8 JSON bytes: a larger state is kept as the first this many bytes of its
10
+ * JSON text, with `state_truncated: true`. */
11
+ export declare const DECISION_STATE_MAX_BYTES: number;
12
+ /** The most of a request's error a receipt keeps, in characters; a longer one is kept to it with `error_truncated`. */
13
+ export declare const DECISION_ERROR_MAX: number;
14
+ /** An image a request carried, as its receipt names it: the token the request used, the reference the host loaded, and
15
+ * the image's SHA-256, type and size (never the bytes). The digest fields are null when the image was never loaded (a
16
+ * request that failed before its images were read). */
17
+ export type DecisionImageDigest = {
18
+ token: string;
19
+ ref: string;
20
+ sha256: string | null;
21
+ mime: string | null;
22
+ bytes: number | null;
23
+ };
24
+ /** A state value a provider cut to fit its model's context before it sent the request: where it sits in the state (a JSON
25
+ * Pointer, RFC 6901), and its UTF-8 bytes as asked and as sent (its start and the provider's cut mark). */
26
+ export type DecisionStateCut = {
27
+ path: string;
28
+ bytes: number;
29
+ sent_bytes: number;
30
+ };
31
+ /** The state a provider sent when it sent other than it was asked (values cut to fit its context), and the values it cut. */
32
+ export type DecisionStateSent = {
33
+ state: unknown;
34
+ cut: DecisionStateCut[];
35
+ };
36
+ /** The typed questions the interpreter asks: the five question nodes and predicates, and a generative
37
+ * node's `verify` clause. */
38
+ export type DecisionKind = "judge" | "pick" | "sift" | "route" | "ask" | "verify";
39
+ /** How answers become the action, with every threshold applied. */
40
+ export type DecisionRule =
41
+ /** judge: each question's decoded value (a choice, a yes/no at 0.5, a rounded score). */
42
+ {
43
+ kind: "judge";
44
+ }
45
+ /** pick: the chosen option names an item by its position, or none. */
46
+ | {
47
+ kind: "pick";
48
+ options: string[];
49
+ none: string | null;
50
+ }
51
+ /** route: the chosen branch, or the unsure branch when the choice's confidence is below `gte`. The chosen
52
+ * branch names one of `branches`; `unsure`, when set, judges its confidence against `gte`. `branches` is
53
+ * absent on a rule recorded before it was added, and such a rule skips the branch-membership check. */
54
+ | {
55
+ kind: "route";
56
+ branches?: string[];
57
+ unsure: {
58
+ gte: number;
59
+ branch: string;
60
+ } | null;
61
+ }
62
+ /** sift: an item of this request is kept when its `keep` measure meets `gte`; every item without a keep
63
+ * rule. `items` counts this request's items; the action names them by their position in the request. */
64
+ | {
65
+ kind: "sift";
66
+ items: number;
67
+ ids: string[];
68
+ keep: {
69
+ id: string;
70
+ measure: "confidence" | "value";
71
+ gte: number;
72
+ } | null;
73
+ }
74
+ /** ask: the predicate holds when the yes-probability meets `gte`. */
75
+ | {
76
+ kind: "ask";
77
+ gte: number;
78
+ }
79
+ /** verify: a yes/no question fails when its yes-probability is below its threshold (null: not judged).
80
+ * A failed question the submission holds is doubted; a failed one it lacks is unmet. */
81
+ | {
82
+ kind: "verify";
83
+ thresholds: Record<string, number | null>;
84
+ present: string[];
85
+ };
86
+ export type DecisionReceipt = {
87
+ v: typeof DECISION_RECEIPT_VERSION;
88
+ /** The request's identity: where it sits in the run (execution path, kind, position among its node's
89
+ * requests) and what it asked (questions and state). The same request asked again has the same id. */
90
+ id: string;
91
+ /** When the receipt was made, ISO 8601. */
92
+ at: string;
93
+ /** The label the request carried, a child workflow's prefix included. */
94
+ node: string;
95
+ kind: DecisionKind;
96
+ /** The map item the request ran for, by index; null outside a map. */
97
+ item: number | null;
98
+ execution_path: string;
99
+ /** This request among the requests its node makes at this path. A sift over the host's limits sends
100
+ * `count` requests, and `items` lists the positions in the sifted list this one covers, in the order it
101
+ * asked about them. A verify clause's nth review has index n - 1 and `count` is the most it may ask.
102
+ * Every other kind asks once. */
103
+ request: {
104
+ index: number;
105
+ count: number;
106
+ items?: number[];
107
+ };
108
+ /** `answered`: the answers came back and decided `action`. `failed`: the judge rejected, or its answers
109
+ * were refused. `cancelled`: the request's signal was aborted before it settled, so whether it was
110
+ * served is not known. */
111
+ status: "answered" | "failed" | "cancelled";
112
+ /** SHA-256 of the canonical JSON of the state the judge was asked with: part of the request's identity (`id`). What
113
+ * the provider sent is `state` and `request_sha256`, which differ when it cut values to fit (`state_cut`). */
114
+ state_sha256: string;
115
+ questions: Record<string, SystemOneQuestion>;
116
+ /** What came back, as it came back; empty when nothing did. */
117
+ answers: Record<string, SystemOneAnswer>;
118
+ /** Null unless `status` is `answered`. */
119
+ rule: DecisionRule | null;
120
+ /** What the answers decide under `rule`; null unless `status` is `answered`. */
121
+ action: unknown;
122
+ model: string | null;
123
+ usage: {
124
+ input_tokens: number;
125
+ output_tokens: number;
126
+ } | null;
127
+ cost_usd: number | null;
128
+ request_sha256: string | null;
129
+ /** Wall time of the judge call, in milliseconds. */
130
+ latency_ms: number;
131
+ /** The questions whose answer came back as a refusal, when any did. A refusal decodes to no value: the request is
132
+ * `failed` and the run escalates (DECISION_REFUSED), except a route with an `unsure` branch, which takes that branch. */
133
+ refused?: string[];
134
+ /** For each choice and score answer, whether its confidence is the provider's own or was derived from its
135
+ * probabilities; present when the judge said. */
136
+ confidence_source?: Record<string, ConfidenceSource>;
137
+ /** The provider that answered, when the host's judge names it or the node pins it. */
138
+ provider?: string;
139
+ /** The sources the provider grounded its answers in, unless the node said `evidence: "off"`; absent when it gave none. */
140
+ evidence?: DecisionEvidence[];
141
+ /** How `cost_usd` was reached (reported by the provider, estimated by the host, unknown), when the judge said. */
142
+ cost_basis?: CostBasis;
143
+ /** The images the request carried, by digest; absent when it carried none. */
144
+ images?: DecisionImageDigest[];
145
+ /** The state the judge saw, as its provider sent it (with any value it cut, cut): the value itself, or, past
146
+ * `DECISION_STATE_MAX_BYTES` of JSON, the first that many bytes of its JSON text (a string) with `state_truncated: true`.
147
+ * Absent on a receipt recorded before it was kept. */
148
+ state?: unknown;
149
+ state_truncated?: boolean;
150
+ /** The state values the provider cut to fit its model's context before sending; absent when it sent the state as asked. */
151
+ state_cut?: DecisionStateCut[];
152
+ /** The request's error, whole up to `DECISION_ERROR_MAX` characters: a host redacts it before it cuts it for a person.
153
+ * A longer one is kept to that many with `error_truncated: true`; one recorded before was cut at 2000. */
154
+ error?: string;
155
+ error_truncated?: boolean;
156
+ };
157
+ /** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
158
+ * receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
159
+ export declare function rederiveDecision(receipt: Pick<DecisionReceipt, "rule" | "answers" | "questions">): unknown;
@@ -0,0 +1,93 @@
1
+ import { answerConfidence, answersToValue } from "./system-one.js";
2
+ export const DECISION_RECEIPT_VERSION = 1;
3
+ /** The escalation kind of a decision its provider refused: the run ends `escalated` at stage "decision", for a person. */
4
+ export const DECISION_REFUSED = "decision_refused";
5
+ /** The escalation kind of a run whose decision was asked by an earlier process and never answered there: it is routed to
6
+ * review instead of being asked, and paid for, again. Its stage is `decision`. */
7
+ export const DECISION_INTERRUPTED = "decision_interrupted";
8
+ /** The most of the state a receipt keeps, as UTF-8 JSON bytes: a larger state is kept as the first this many bytes of its
9
+ * JSON text, with `state_truncated: true`. */
10
+ export const DECISION_STATE_MAX_BYTES = 64 * 1024;
11
+ /** The most of a request's error a receipt keeps, in characters; a longer one is kept to it with `error_truncated`. */
12
+ export const DECISION_ERROR_MAX = 64 * 1024;
13
+ /** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
14
+ * receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
15
+ export function rederiveDecision(receipt) {
16
+ const rule = receipt.rule;
17
+ const answers = receipt.answers;
18
+ if (!rule)
19
+ return null;
20
+ switch (rule.kind) {
21
+ case "judge": return answersToValue(receipt.answers, receipt.questions);
22
+ case "pick": {
23
+ // An answered pick carries its pick answer; a receipt without one decided nothing.
24
+ const answer = answers.pick;
25
+ if (!answer || typeof answer !== "object")
26
+ return null;
27
+ const choice = answer.choice;
28
+ // The choice must be a string that names an option, or the none option. Anything else (no string
29
+ // choice, or a choice in neither set) is a malformed answer, never a fail-open {index: -1}.
30
+ if (typeof choice !== "string")
31
+ return null;
32
+ const none = rule.none !== null && choice === rule.none;
33
+ if (!none && !rule.options.includes(choice))
34
+ return null;
35
+ return { index: none ? null : rule.options.indexOf(choice), none };
36
+ }
37
+ case "route": {
38
+ // An answered route carries its branch answer; a receipt without one decided nothing.
39
+ const answer = answers.branch;
40
+ if (!answer || typeof answer !== "object")
41
+ return null;
42
+ // A refused route has no branch of its own: it took the unsure branch, and without one it decided nothing.
43
+ if (answer.type === "refusal")
44
+ return rule.unsure ? { branch: null, taken: rule.unsure.branch, unsure: true, refused: true } : null;
45
+ const branch = answer.choice;
46
+ // The chosen branch must be a string; when the rule carries `branches` (recorded since this check was
47
+ // added) it must name one of them. A rule recorded before `branches` skips the membership check, so an
48
+ // older route receipt re-derives as it did before, never throwing on a missing field.
49
+ if (typeof branch !== "string" || (rule.branches && !rule.branches.includes(branch)))
50
+ return null;
51
+ // When unsure is set, judging SURE/UNSURE needs a finite numeric confidence. A missing or non-numeric
52
+ // confidence must not compare false and re-derive as SURE (a fail-open onto the chosen branch).
53
+ if (rule.unsure && !(typeof answer.confidence === "number" && Number.isFinite(answer.confidence)))
54
+ return null;
55
+ const unsure = Boolean(rule.unsure && answer.confidence < rule.unsure.gte);
56
+ return { branch, taken: unsure ? rule.unsure.branch : branch, unsure };
57
+ }
58
+ case "sift": {
59
+ const kept = [];
60
+ for (let i = 0; i < rule.items; i += 1) {
61
+ if (!rule.keep) {
62
+ kept.push(i);
63
+ continue;
64
+ }
65
+ const answer = answers[`${i}.${rule.keep.id}`];
66
+ const measure = !answer ? NaN : rule.keep.measure === "confidence" ? answerConfidence(answer) : answer.type === "noul" ? answer.noul : answer.type === "score" ? answer.score : NaN;
67
+ if (Number.isFinite(measure) && measure >= rule.keep.gte)
68
+ kept.push(i);
69
+ }
70
+ return { kept };
71
+ }
72
+ case "ask": return { holds: Number(answers.holds?.noul) >= rule.gte };
73
+ case "verify": {
74
+ const doubted = [];
75
+ const unmet = [];
76
+ for (const [id, threshold] of Object.entries(rule.thresholds)) {
77
+ if (threshold === null)
78
+ continue;
79
+ // A field with a threshold needs its yes/no answer; a receipt missing one, or holding another shape, decided
80
+ // nothing (null), never a fail-open "accepted".
81
+ const answer = answers[id];
82
+ // The answer must be a noul with a finite numeric probability. A noul-typed answer whose noul is
83
+ // absent or not a finite number would compare NaN < threshold (false), reading as supported: a
84
+ // fail-open one level down. It decided nothing.
85
+ if (answer?.type !== "noul" || typeof answer.noul !== "number" || !Number.isFinite(answer.noul))
86
+ return null;
87
+ if (answer.noul < threshold)
88
+ (rule.present.includes(id) ? doubted : unmet).push(id);
89
+ }
90
+ return { accepted: doubted.length === 0 && unmet.length === 0, doubted, unmet };
91
+ }
92
+ }
93
+ }
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
- export declare function synthesizeInstance(schema: unknown, definitions?: Record<string, unknown>, depth?: number): unknown;
14
+ /** What one dry run may synthesize in all, across its input and every step's answer (DryRunOptions.budget), and what one
15
+ * synthesizeInstance call may when none is given: values (each array item, object, string, number...) and string
16
+ * characters. Synthesis counts each before it makes it and throws SynthesisTooLarge past either, so a schema that asks
17
+ * for a huge value (nested arrays of a large minItems, a long minLength) never allocates past the budget. */
18
+ export type SynthesisBudget = {
19
+ values: number;
20
+ chars: number;
21
+ };
22
+ /** The default: a million values and 16 million characters, far past what a real workflow's dry run builds (a few
23
+ * thousand values at most), and well within a host's memory (a few hundred MB at worst). */
24
+ export declare const SYNTHESIS_BUDGET: Readonly<SynthesisBudget>;
25
+ /** The schema asked synthesis for more than its budget: the dry run ends not run, saying so. */
26
+ export declare class SynthesisTooLarge extends Error {
27
+ name: string;
28
+ }
29
+ /** A value of `schema` (its `$ref`s read from `definitions`), synthesized within `budget` (SYNTHESIS_BUDGET when none):
30
+ * past it, SynthesisTooLarge. */
31
+ export declare function synthesizeInstance(schema: unknown, definitions?: Record<string, unknown>, depth?: number, budget?: Partial<SynthesisBudget>): unknown;
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,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) {
@@ -116,9 +169,9 @@ function unsupportedConstructs(schema, path, found, depth = 0) {
116
169
  return found;
117
170
  }
118
171
  export async function dryRunWorkflow(workflow, opts = {}) {
119
- const valid = validateWorkflow(workflow, opts.input === undefined ? undefined : { input: opts.input });
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,53 +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,
276
+ ...(runCode ? { runCode: async (...args) => { await step(); return runCode(...args); } } : {}),
162
277
  onEvent: (event) => { if (typeof event.label === "string")
163
278
  currentLabel = event.label; },
164
279
  runNode: async ({ schema, review }) => {
165
- const candidate = synthesizeInstance(schema, schema.definitions ?? workflow.schemas);
280
+ await step();
281
+ const candidate = synthesized(() => synthesize(schema, schema.definitions ?? workflow.schemas, 0, spend));
166
282
  if (review)
167
283
  await review(candidate);
168
284
  return candidate;
169
285
  },
170
- 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
+ },
171
296
  syntheticEffects: true,
172
- runEffect: async ({ node, schema }) => node.via === "shell"
173
- ? { code: 0, stdout: "{}", stderr: "", truncated: false }
174
- : 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
+ },
175
304
  });
176
305
  if (result.status === "escalated") {
177
306
  // 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`] };
307
+ return { ok: true, status: "not_run", skipped: [`escalated:${result.escalation.kind}@${result.escalation.stage} on synthetic values`] };
179
308
  }
180
- return { ok: true };
309
+ opts.onOutput?.(result.output);
310
+ return { ok: true, status: "passed" };
181
311
  }
182
312
  catch (error) {
313
+ if (stopped)
314
+ return { ok: true, status: "not_run", skipped: [stopped] };
183
315
  if (error instanceof WorkflowOutputInvalidError) {
184
- return { ok: false, problems: error.problems, stage: error.stage };
316
+ return { ok: false, status: "failed", problems: error.problems, stage: error.stage };
185
317
  }
186
318
  if (error instanceof WorkflowInputInvalidError)
187
- return { ok: false, problems: [error.message] };
319
+ return { ok: false, status: "failed", problems: [error.message] };
188
320
  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 };
321
+ return { ok: false, status: "failed", problems: [`deterministic path threw over schema-conforming inputs${currentLabel ? ` (at "${currentLabel}")` : ""}: ${message.slice(0, 1200)}`], stage: currentLabel || undefined };
190
322
  }
191
323
  }