@parcha/agentrun-dsl 0.1.0-beta.5 → 0.1.0-beta.50

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 (94) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +167 -23
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +13 -5
  6. package/dist/author.js +38 -19
  7. package/dist/authoring.js +2 -2
  8. package/dist/cli.js +17 -12
  9. package/dist/code-exec.d.ts +6 -0
  10. package/dist/code-exec.js +126 -0
  11. package/dist/decision-provider.d.ts +165 -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 +157 -26
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +62 -0
  19. package/dist/graph.d.ts +169 -0
  20. package/dist/graph.js +433 -0
  21. package/dist/index.d.ts +19 -11
  22. package/dist/index.js +16 -9
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +16 -3
  25. package/dist/job.d.ts +14 -0
  26. package/dist/job.js +5 -0
  27. package/dist/long-timer.d.ts +7 -0
  28. package/dist/long-timer.js +22 -0
  29. package/dist/observer-snapshot.d.ts +3 -0
  30. package/dist/observer-snapshot.js +46 -0
  31. package/dist/predicates.d.ts +32 -0
  32. package/dist/predicates.js +61 -0
  33. package/dist/recovery/binding.d.ts +10 -0
  34. package/dist/recovery/binding.js +43 -0
  35. package/dist/recovery/call-key.d.ts +9 -0
  36. package/dist/recovery/call-key.js +17 -0
  37. package/dist/recovery/canonical-hash.d.ts +7 -0
  38. package/dist/recovery/canonical-hash.js +22 -0
  39. package/dist/recovery/driver.d.ts +235 -0
  40. package/dist/recovery/driver.js +1333 -0
  41. package/dist/recovery/errors.d.ts +31 -0
  42. package/dist/recovery/errors.js +51 -0
  43. package/dist/recovery/execution-path.d.ts +53 -0
  44. package/dist/recovery/execution-path.js +167 -0
  45. package/dist/recovery/file-store.d.ts +7 -0
  46. package/dist/recovery/file-store.js +131 -0
  47. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  48. package/dist/recovery/frozen-snapshot.js +187 -0
  49. package/dist/recovery/handoff-receipts.d.ts +7 -0
  50. package/dist/recovery/handoff-receipts.js +10 -0
  51. package/dist/recovery/index.d.ts +14 -0
  52. package/dist/recovery/index.js +13 -0
  53. package/dist/recovery/item-state.d.ts +48 -0
  54. package/dist/recovery/item-state.js +89 -0
  55. package/dist/recovery/journal.d.ts +28 -0
  56. package/dist/recovery/journal.js +139 -0
  57. package/dist/recovery/memory-store.d.ts +4 -0
  58. package/dist/recovery/memory-store.js +20 -0
  59. package/dist/recovery/store.d.ts +105 -0
  60. package/dist/recovery/store.js +6 -0
  61. package/dist/recovery/testing/conformance.d.ts +4 -0
  62. package/dist/recovery/testing/conformance.js +268 -0
  63. package/dist/recovery/testing/crash-points.d.ts +18 -0
  64. package/dist/recovery/testing/crash-points.js +43 -0
  65. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  66. package/dist/recovery/testing/crash-sweep.js +146 -0
  67. package/dist/recovery/testing/index.d.ts +3 -0
  68. package/dist/recovery/testing/index.js +4 -0
  69. package/dist/recovery/testing/preload.d.ts +1 -0
  70. package/dist/recovery/testing/preload.js +3 -0
  71. package/dist/recovery/transport-facts.d.ts +23 -0
  72. package/dist/recovery/transport-facts.js +46 -0
  73. package/dist/recovery/with-recovery.d.ts +50 -0
  74. package/dist/recovery/with-recovery.js +144 -0
  75. package/dist/submit-envelope.d.ts +9 -0
  76. package/dist/submit-envelope.js +43 -0
  77. package/dist/system-one.d.ts +40 -2
  78. package/dist/system-one.js +132 -12
  79. package/dist/testing/decision-provider.d.ts +32 -0
  80. package/dist/testing/decision-provider.js +183 -0
  81. package/dist/testing/index.d.ts +1 -0
  82. package/dist/testing/index.js +2 -0
  83. package/dist/vocabulary.d.ts +19 -3
  84. package/dist/vocabulary.js +31 -10
  85. package/dist/workflow-shape.d.ts +7 -0
  86. package/dist/workflow-shape.js +115 -69
  87. package/dist/workflow.d.ts +269 -29
  88. package/dist/workflow.js +1453 -439
  89. package/package.json +27 -4
  90. package/schema/workflow.schema.json +497 -12
  91. package/skills/author/SKILL.md +6 -1
  92. package/skills/author/references/jev-decisions.md +69 -12
  93. package/skills/author/references/language.md +28 -20
  94. package/skills/author/references/sdk-authoring.md +2 -0
@@ -0,0 +1,238 @@
1
+ // The seam for decision models: a DecisionProvider answers typed questions (noul, choice, score, box) about a state, fast
2
+ // and without an agent harness, and judgeFromProvider makes one the interpreter's runJudge. Jev is one provider and a
3
+ // third-party API another; each passes the conformance suite in `@parcha/agentrun-dsl/testing`.
4
+ import { createHash } from "node:crypto";
5
+ import { evidenceOf } from "./evidence.js";
6
+ import { completeConfidence, validateAnswers } from "./system-one.js";
7
+ /** A PNG's or JPEG's width and height in pixels, read from its header (PNG's IHDR, a JPEG's first frame marker); null
8
+ * when the bytes are neither or the header is cut short. A provider with a size cap checks it before a paid call. */
9
+ export function imageDimensions(bytes) {
10
+ const u16 = (at) => (bytes[at] << 8) | bytes[at + 1];
11
+ const u32 = (at) => ((bytes[at] << 24) >>> 0) + (bytes[at + 1] << 16) + (bytes[at + 2] << 8) + bytes[at + 3];
12
+ if (bytes.length >= 24 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[12] === 0x49 && bytes[13] === 0x48 && bytes[14] === 0x44 && bytes[15] === 0x52) {
13
+ return { width: u32(16), height: u32(20) };
14
+ }
15
+ if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8)
16
+ return null;
17
+ for (let at = 2; at + 3 < bytes.length;) {
18
+ if (bytes[at] !== 0xff)
19
+ return null;
20
+ const marker = bytes[at + 1];
21
+ if (marker === 0xff) {
22
+ at++;
23
+ continue;
24
+ }
25
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {
26
+ at += 2;
27
+ continue;
28
+ }
29
+ // A start-of-frame marker (C0-CF but DHT C4, JPG C8 and DAC CC) holds precision, height, width.
30
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc)
31
+ return at + 8 < bytes.length ? { width: u16(at + 7), height: u16(at + 5) } : null;
32
+ if (marker === 0xd9 || marker === 0xda)
33
+ return null;
34
+ at += 2 + u16(at + 2);
35
+ }
36
+ return null;
37
+ }
38
+ /** A provider's failure. Its message names what failed, never a key, a header, a request or response body. */
39
+ export class DecisionProviderError extends Error {
40
+ code;
41
+ status;
42
+ attempts;
43
+ /** The provider's own reference for the failure, when it gives one. */
44
+ refId;
45
+ /** What a request that was or may have been billed is booked at (`outcome_unknown`, `invalid_response`), with how it was
46
+ * reached; null when unknown. */
47
+ costUsd;
48
+ costBasis;
49
+ /** True when the provider knows the request was never sent (a check before it, cut by the deadline or a cancel):
50
+ * judgeFromProviders keeps its code under a node's timeoutMs, where any other cut is taken for a request that may
51
+ * have been billed. Absent when it may have been sent; `attempts` alone never says so. */
52
+ unsent;
53
+ /** The state the request held as the provider prepared it, when it cut values to fit (DecisionOutcome.state_sent): the
54
+ * failed decision's receipt records it. */
55
+ stateSent;
56
+ constructor(code, message, details = {}) {
57
+ super(message, details.cause !== undefined ? { cause: details.cause } : undefined);
58
+ this.code = code;
59
+ this.name = "DecisionProviderError";
60
+ this.attempts = details.attempts ?? 0;
61
+ if (details.status !== undefined)
62
+ this.status = details.status;
63
+ if (details.refId !== undefined)
64
+ this.refId = details.refId;
65
+ if (details.costUsd !== undefined)
66
+ this.costUsd = details.costUsd;
67
+ if (details.costBasis !== undefined)
68
+ this.costBasis = details.costBasis;
69
+ if (details.unsent === true)
70
+ this.unsent = true;
71
+ if (details.stateSent !== undefined)
72
+ this.stateSent = details.stateSent;
73
+ }
74
+ }
75
+ /** What a provider's error books for its request: one sent whose outcome was lost (`outcome_unknown`), or one answered
76
+ * with what the seam or the provider rejects (`invalid_response`), was or may have been paid for, and is booked at the
77
+ * cost the error carries, null when that is unknown (never 0). Undefined for an error that books nothing. */
78
+ export function chargedCost(error) {
79
+ if (!(error instanceof DecisionProviderError) || (error.code !== "outcome_unknown" && error.code !== "invalid_response"))
80
+ return undefined;
81
+ return typeof error.costUsd === "number" && Number.isFinite(error.costUsd) ? error.costUsd : null;
82
+ }
83
+ /** Refuses, as invalid_request, a request beyond what `capabilities` declares: a question type it does not answer, more
84
+ * questions than it takes, a larger state, or a model it does not serve. A provider calls it before it sends anything. */
85
+ export function checkCapabilities(capabilities, request) {
86
+ if (request.model !== undefined && capabilities.models && !capabilities.models.includes(request.model))
87
+ throw new DecisionProviderError("invalid_request", `The provider does not answer with the model "${request.model}".`);
88
+ const types = Object.values(request.questions).map((question) => question?.type);
89
+ const unknown = types.filter((type) => !capabilities.types.includes(type));
90
+ if (unknown.length)
91
+ throw new DecisionProviderError("invalid_request", `The provider does not answer ${[...new Set(unknown)].map(String).join(", ")} questions.`);
92
+ if (capabilities.maxQuestions !== null && types.length > capabilities.maxQuestions)
93
+ throw new DecisionProviderError("invalid_request", `${types.length} questions exceed the ${capabilities.maxQuestions} one request may hold.`);
94
+ if (capabilities.maxStateBytes !== null) {
95
+ const bytes = Buffer.byteLength(JSON.stringify(request.state ?? null) ?? "null", "utf8");
96
+ if (bytes > capabilities.maxStateBytes)
97
+ throw new DecisionProviderError("invalid_request", `A state of ${bytes} bytes exceeds the ${capabilities.maxStateBytes} one request may hold.`);
98
+ }
99
+ }
100
+ /** `promise`, or `signal`'s reason once it aborts first: a loader that does not watch its signal is cut all the same. */
101
+ function untilAborted(promise, signal) {
102
+ if (signal.aborted) {
103
+ promise.catch(() => { });
104
+ return Promise.reject(signal.reason);
105
+ }
106
+ return new Promise((resolve, reject) => {
107
+ const stop = () => reject(signal.reason);
108
+ signal.addEventListener("abort", stop, { once: true });
109
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
110
+ });
111
+ }
112
+ /** Requests cut while their images loaded: nothing was sent, so judgeFromProviders never takes one for a request that
113
+ * may have been billed. */
114
+ const cutBeforeSending = new WeakSet();
115
+ /** Loads a request's images through the host's `loadImage`, before anything is sent: a provider that takes no image input,
116
+ * a host that cannot load one, or an image that cannot be read is refused, and no request is made. */
117
+ async function loadImages(provider, images, loadImage, signal) {
118
+ if (!provider.capabilities.inputs.includes("image"))
119
+ throw new DecisionProviderError("invalid_request", `The provider ${provider.id} takes no image input, and the request carries ${Object.keys(images).length}.`);
120
+ if (!loadImage)
121
+ throw new DecisionProviderError("configuration", "The request carries images, and this host has no loadImage to read them.");
122
+ const loaded = Object.create(null);
123
+ const digests = [];
124
+ for (const [token, ref] of Object.entries(images)) {
125
+ let image;
126
+ try {
127
+ image = await untilAborted(loadImage(ref, { signal }), signal);
128
+ }
129
+ catch (error) {
130
+ throw new DecisionProviderError("invalid_request", `The image ${token} (${ref}) could not be read: ${String(error?.message ?? error).slice(0, 200)}`);
131
+ }
132
+ if (!(image?.bytes instanceof Uint8Array) || !image.bytes.byteLength || typeof image.mime !== "string")
133
+ throw new DecisionProviderError("invalid_request", `The image ${token} (${ref}) read as no image bytes.`);
134
+ loaded[token] = { bytes: image.bytes, mime: image.mime, ref };
135
+ digests.push({ token, ref, sha256: createHash("sha256").update(image.bytes).digest("hex"), mime: image.mime, bytes: image.bytes.byteLength });
136
+ }
137
+ return { loaded: { ...loaded }, digests };
138
+ }
139
+ /** The interpreter's runJudge, answered by `provider`: the request goes to it with the decision's id, its signal and
140
+ * `deadlineMs`, and with the images it names, loaded through `loadImage` within that deadline (the provider gets what is
141
+ * left of it; a load the deadline cuts is `timeout`, one the signal cuts `aborted`, and neither was sent); a choice or
142
+ * score without a confidence gets one derived, and the result names each one's source and each image's digest. The
143
+ * answers are validated against the questions, and ones that do not match them are invalid_response. */
144
+ export function judgeFromProvider(provider, options = {}) {
145
+ return async (params) => {
146
+ const request = { label: params.label, kind: params.kind, state: params.state, questions: params.questions, ...(params.item ? { item: params.item } : {}), ...(params.executionPath !== undefined ? { executionPath: params.executionPath } : {}), ...(params.model !== undefined ? { model: params.model } : {}) };
147
+ checkCapabilities(provider.capabilities, request);
148
+ let digests;
149
+ const signal = params.signal ?? new AbortController().signal;
150
+ let deadlineMs = options.deadlineMs ?? null;
151
+ if (params.images && Object.keys(params.images).length) {
152
+ // The deadline counts from before the images load, and loading is cut by it as by the run's signal.
153
+ const started = Date.now();
154
+ const loading = deadlineMs !== null ? AbortSignal.any([signal, AbortSignal.timeout(deadlineMs)]) : signal;
155
+ const cutWith = (reason) => {
156
+ const timedOut = reason?.name === "TimeoutError";
157
+ const cut = new DecisionProviderError(timedOut ? "timeout" : "aborted", `${provider.id}: ${timedOut ? "the deadline passed" : "the request was cancelled"} while its images loaded; nothing was sent`, { cause: reason });
158
+ cutBeforeSending.add(cut);
159
+ return cut;
160
+ };
161
+ let images;
162
+ try {
163
+ images = await loadImages(provider, params.images, options.loadImage, loading);
164
+ }
165
+ catch (error) {
166
+ if (!loading.aborted)
167
+ throw error;
168
+ throw cutWith(loading.reason);
169
+ }
170
+ // A load can end past the deadline before its timer fires (a loader's synchronous work, or hashing the last image,
171
+ // holds the thread): it is cut here, before anything is sent, and the provider gets only time that is left.
172
+ const elapsed = Date.now() - started;
173
+ if (loading.aborted)
174
+ throw cutWith(loading.reason);
175
+ if (deadlineMs !== null && elapsed >= deadlineMs)
176
+ throw cutWith(new DOMException("The decision's deadline passed while its images loaded", "TimeoutError"));
177
+ request.images = images.loaded;
178
+ digests = images.digests;
179
+ if (deadlineMs !== null)
180
+ deadlineMs -= elapsed;
181
+ }
182
+ const outcome = await provider.decide(request, { decisionId: params.decisionId ?? "", signal, deadlineMs });
183
+ const { answers, confidence_source } = completeConfidence(params.questions, (outcome.answers ?? {}));
184
+ try {
185
+ validateAnswers(params.questions, answers);
186
+ }
187
+ catch (error) {
188
+ // The provider answered, so the request was paid for: the rejection carries its cost, or null when it reported none.
189
+ const cost = typeof outcome.cost_usd === "number" && Number.isFinite(outcome.cost_usd) ? outcome.cost_usd : null;
190
+ throw new DecisionProviderError("invalid_response", `${provider.id} answered with ${error.message.replace(/^System One /, "")}`, { costUsd: cost, costBasis: cost === null ? "unknown" : outcome.cost_basis, ...(outcome.state_sent ? { stateSent: outcome.state_sent } : {}) });
191
+ }
192
+ const result = {
193
+ answers, model: outcome.model, usage: outcome.usage, cost_usd: outcome.cost_usd, cost_basis: outcome.cost_basis,
194
+ // Every provider's evidence, a third party's too, through the one sanitizer (evidence.ts).
195
+ evidence: evidenceOf(outcome.evidence), provider_request_id: outcome.provider_request_id, confidence_source,
196
+ ...(digests ? { images: digests } : {}), ...(outcome.state_sent ? { state_sent: outcome.state_sent } : {}),
197
+ };
198
+ return result;
199
+ };
200
+ }
201
+ /** The interpreter's runJudge over a host's providers: each request goes to the provider its node names, or to
202
+ * `default`, with the node's pinned model, within the shorter of the node's `timeoutMs` and the provider's own
203
+ * `deadlineMs`: a node only ever shortens it. The node's bound is kept here: when it passes, the call is cut, and a cut
204
+ * call may already have been sent and billed, so it is `outcome_unknown` (the decision escalates as interrupted), never
205
+ * asked again. A call cut while its images load was not sent, and stays `timeout`. The result names the provider that
206
+ * answered. */
207
+ export function judgeFromProviders(options) {
208
+ return async (params) => {
209
+ const id = params.provider ?? options.default;
210
+ const provider = Object.hasOwn(options.providers, id) ? options.providers[id] : undefined;
211
+ if (!provider)
212
+ throw new DecisionProviderError("configuration", `No decision provider "${id}" on this host.`);
213
+ const own = options.deadlineMs ?? null;
214
+ const node = params.timeoutMs ?? null;
215
+ const shorter = node !== null && (own === null || node < own);
216
+ const deadlineMs = shorter ? node : own;
217
+ const cut = new AbortController();
218
+ const timer = shorter ? setTimeout(() => cut.abort(new DOMException("The decision node's timeoutMs passed", "TimeoutError")), node) : undefined;
219
+ const signal = params.signal ? AbortSignal.any([params.signal, cut.signal]) : cut.signal;
220
+ try {
221
+ const result = await judgeFromProvider(provider, { deadlineMs, ...(options.loadImage ? { loadImage: options.loadImage } : {}) })({ ...params, signal });
222
+ return { ...result, provider: id };
223
+ }
224
+ catch (error) {
225
+ if (cut.signal.aborted && error instanceof DecisionProviderError && !cutBeforeSending.has(error) && error.unsent !== true && (error.code === "aborted" || error.code === "timeout")) {
226
+ throw new DecisionProviderError("outcome_unknown", `${id}: cut by the node's timeoutMs (${node} ms) after it may have been sent`, {
227
+ attempts: error.attempts, ...(error.costUsd !== undefined ? { costUsd: error.costUsd } : {}), ...(error.costBasis !== undefined ? { costBasis: error.costBasis } : {}),
228
+ ...(error.stateSent !== undefined ? { stateSent: error.stateSent } : {}), cause: error
229
+ });
230
+ }
231
+ throw error;
232
+ }
233
+ finally {
234
+ if (timer !== undefined)
235
+ clearTimeout(timer);
236
+ }
237
+ };
238
+ }
@@ -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>;