@parcha/agentrun-dsl 0.1.0-beta.27 → 0.1.0-beta.270

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 (80) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +22 -17
  3. package/dist/author-references.d.ts +3 -3
  4. package/dist/author-references.js +3 -3
  5. package/dist/author.d.ts +0 -2
  6. package/dist/author.js +13 -8
  7. package/dist/authoring.js +3 -2
  8. package/dist/cli.js +13 -12
  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 +60 -2
  14. package/dist/decision-receipts.js +13 -3
  15. package/dist/dry-run.d.ts +31 -1
  16. package/dist/dry-run.js +120 -14
  17. package/dist/edit.d.ts +158 -0
  18. package/dist/edit.js +1486 -0
  19. package/dist/evidence.d.ts +19 -0
  20. package/dist/evidence.js +63 -0
  21. package/dist/graph.d.ts +17 -0
  22. package/dist/graph.js +71 -6
  23. package/dist/index.d.ts +18 -12
  24. package/dist/index.js +17 -10
  25. package/dist/inspection.d.ts +5 -0
  26. package/dist/inspection.js +14 -1
  27. package/dist/pattern-screen.d.ts +14 -0
  28. package/dist/pattern-screen.js +451 -0
  29. package/dist/pointer-warning.d.ts +14 -0
  30. package/dist/pointer-warning.js +22 -0
  31. package/dist/predicates.d.ts +32 -2
  32. package/dist/predicates.js +66 -6
  33. package/dist/record.d.ts +4 -0
  34. package/dist/record.js +6 -0
  35. package/dist/recovery/binding.js +2 -1
  36. package/dist/recovery/call-key.d.ts +0 -4
  37. package/dist/recovery/call-key.js +0 -7
  38. package/dist/recovery/driver.d.ts +43 -20
  39. package/dist/recovery/driver.js +140 -41
  40. package/dist/recovery/frozen-snapshot.d.ts +30 -1
  41. package/dist/recovery/frozen-snapshot.js +26 -8
  42. package/dist/recovery/handoff-receipts.d.ts +0 -35
  43. package/dist/recovery/handoff-receipts.js +2 -44
  44. package/dist/recovery/index.d.ts +4 -8
  45. package/dist/recovery/index.js +4 -7
  46. package/dist/recovery/item-state.d.ts +2 -1
  47. package/dist/recovery/item-state.js +7 -13
  48. package/dist/recovery/with-recovery.d.ts +9 -3
  49. package/dist/recovery/with-recovery.js +72 -15
  50. package/dist/submit-envelope.d.ts +9 -0
  51. package/dist/submit-envelope.js +44 -0
  52. package/dist/system-one.d.ts +21 -2
  53. package/dist/system-one.js +96 -18
  54. package/dist/testing/decision-provider.d.ts +32 -0
  55. package/dist/testing/decision-provider.js +183 -0
  56. package/dist/testing/index.d.ts +1 -0
  57. package/dist/testing/index.js +2 -0
  58. package/dist/vocabulary.d.ts +16 -3
  59. package/dist/vocabulary.js +23 -8
  60. package/dist/workflow-shape.js +4 -2
  61. package/dist/workflow.d.ts +144 -18
  62. package/dist/workflow.js +871 -247
  63. package/dist/zod-json-contract.js +6 -8
  64. package/package.json +12 -4
  65. package/schema/workflow.schema.json +352 -1
  66. package/skills/author/SKILL.md +4 -1
  67. package/skills/author/references/jev-decisions.md +50 -5
  68. package/skills/author/references/language.md +16 -11
  69. package/dist/recovery/effect-failure.d.ts +0 -34
  70. package/dist/recovery/effect-failure.js +0 -62
  71. package/dist/recovery/handoff-block.d.ts +0 -36
  72. package/dist/recovery/handoff-block.js +0 -148
  73. package/dist/recovery/handoff-digest.d.ts +0 -58
  74. package/dist/recovery/handoff-digest.js +0 -195
  75. package/dist/recovery/handoff-files.d.ts +0 -54
  76. package/dist/recovery/handoff-files.js +0 -162
  77. package/dist/recovery/handoff-redact.d.ts +0 -12
  78. package/dist/recovery/handoff-redact.js +0 -44
  79. package/dist/recovery/handoff.d.ts +0 -44
  80. package/dist/recovery/handoff.js +0 -46
@@ -0,0 +1,166 @@
1
+ import { type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
2
+ import type { DecisionStateSent } from "./decision-receipts.js";
3
+ import type { WorkflowDeps } from "./workflow.js";
4
+ type RunJudge = NonNullable<WorkflowDeps["runJudge"]>;
5
+ type JudgeParams = Parameters<RunJudge>[0];
6
+ export type DecisionInput = "text" | "json" | "image" | "pdf" | "url";
7
+ /** What a provider answers, so a workflow or host can tell before it asks. */
8
+ export interface DecisionCapabilities {
9
+ types: SystemOneQuestion["type"][];
10
+ inputs: DecisionInput[];
11
+ /** What grounds the answers: nothing, sources for the whole call, or spans per answer. */
12
+ evidence: "none" | "citations" | "spans";
13
+ /** Where the probabilities come from. Only "calibrated" claims to have been measured against outcomes. */
14
+ probability: "calibrated" | "model" | "self_reported" | "none";
15
+ /** Whether it looks things up on the web. */
16
+ grounding: boolean;
17
+ /** "never": a request is paid once sent, so it is never sent again unasked. The provider retries only a request that
18
+ * provably never reached the service (a connect error before sending) or one refused unanswered with a time to
19
+ * retry (a 429 with Retry-After). A failure after sending (a 408, a 5xx, a lost connection) is `outcome_unknown`,
20
+ * and the decision escalates as interrupted. "deduped": the provider answers a decision id it has seen with the
21
+ * same answer and no new charge. */
22
+ replay: "never" | "deduped";
23
+ /** The most questions one request may hold, or null for no limit. */
24
+ maxQuestions: number | null;
25
+ /** The largest state one request may hold, as UTF-8 JSON bytes, or null for no limit. */
26
+ maxStateBytes: number | null;
27
+ /** The models a node may pin, by name; absent or null, any name goes to the provider. */
28
+ models?: readonly string[] | null;
29
+ }
30
+ /** An image a request carries, loaded by the host: its bytes, its type, and the reference it was loaded from. */
31
+ export interface DecisionImage {
32
+ bytes: Uint8Array;
33
+ mime: string;
34
+ ref: string;
35
+ }
36
+ /** 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
37
+ * when the bytes are neither or the header is cut short. A provider with a size cap checks it before a paid call. */
38
+ export declare function imageDimensions(bytes: Uint8Array): {
39
+ width: number;
40
+ height: number;
41
+ } | null;
42
+ /** How a host reads an image a decision node names: `ref` is the node's resolved reference (a run-relative path). */
43
+ export type LoadImage = (ref: string, ctx: {
44
+ signal: AbortSignal;
45
+ }) => Promise<{
46
+ bytes: Uint8Array;
47
+ mime: string;
48
+ }>;
49
+ export type DecisionRequest = Pick<JudgeParams, "label" | "kind" | "state" | "questions" | "item" | "executionPath" | "model"> & {
50
+ /** The images, by the token the state or a question names each with; only for a provider whose inputs include image. */
51
+ images?: Record<string, DecisionImage>;
52
+ };
53
+ export interface DecisionContext {
54
+ /** The decision receipt's id: the same request asked again has the same id. */
55
+ decisionId: string;
56
+ signal: AbortSignal;
57
+ /** How long the provider has, every attempt included, in milliseconds; null leaves it to the provider. */
58
+ deadlineMs: number | null;
59
+ }
60
+ /** A source an answer rests on. `scope` is "call" when the provider grounds the whole request in it, or the id of the one
61
+ * question it supports. */
62
+ export interface DecisionEvidence {
63
+ url: string;
64
+ title: string | null;
65
+ excerpts: string[];
66
+ scope: string;
67
+ }
68
+ type WithoutConfidence<A> = A extends {
69
+ confidence: unknown;
70
+ } ? Omit<A, "confidence"> & {
71
+ confidence?: number | null;
72
+ } : A;
73
+ /** An answer as a provider gives it: a choice or score may lack a confidence, which judgeFromProvider derives. */
74
+ export type ProviderAnswer = SystemOneAnswer | WithoutConfidence<Extract<SystemOneAnswer, {
75
+ type: "choice" | "score";
76
+ }>>;
77
+ /** How a cost was reached. "unknown" goes with a null cost, never with 0. */
78
+ export type CostBasis = "reported" | "estimate" | "unknown";
79
+ export interface DecisionOutcome {
80
+ answers: Record<string, ProviderAnswer>;
81
+ evidence: DecisionEvidence[];
82
+ model: string | null;
83
+ usage: {
84
+ input_tokens: number;
85
+ output_tokens: number;
86
+ } | null;
87
+ cost_usd: number | null;
88
+ cost_basis: CostBasis;
89
+ provider_request_id: string | null;
90
+ /** The state the provider sent and the values it cut, when it cut any to fit its model's context; absent when it sent
91
+ * the state as asked. The decision's receipt records this state. */
92
+ state_sent?: DecisionStateSent;
93
+ }
94
+ /** `outcome_unknown`: the request was sent and its outcome is not known (a 408, a 5xx, a connection lost after
95
+ * sending). It may have been answered and billed, so it is not sent again; the run escalates the decision as
96
+ * interrupted. `payment_required`: the provider refused the key's account (a 402: out of credit), before any work, so
97
+ * nothing was billed. */
98
+ export type DecisionProviderErrorCode = "configuration" | "auth" | "payment_required" | "rate_limited" | "timeout" | "aborted" | "invalid_request" | "invalid_response" | "http" | "connection" | "outcome_unknown";
99
+ /** A provider's failure. Its message names what failed, never a key, a header, a request or response body. */
100
+ export declare class DecisionProviderError extends Error {
101
+ readonly code: DecisionProviderErrorCode;
102
+ readonly status?: number;
103
+ readonly attempts: number;
104
+ /** The provider's own reference for the failure, when it gives one. */
105
+ readonly refId?: string;
106
+ /** What a request that was or may have been billed is booked at (`outcome_unknown`, `invalid_response`), with how it was
107
+ * reached; null when unknown. */
108
+ readonly costUsd?: number | null;
109
+ readonly costBasis?: CostBasis;
110
+ /** True when the provider knows the request was never sent (a check before it, cut by the deadline or a cancel):
111
+ * judgeFromProviders keeps its code under a node's timeoutMs, where any other cut is taken for a request that may
112
+ * have been billed. Absent when it may have been sent; `attempts` alone never says so. */
113
+ readonly unsent?: true;
114
+ /** The state the request held as the provider prepared it, when it cut values to fit (DecisionOutcome.state_sent): the
115
+ * failed decision's receipt records it. */
116
+ readonly stateSent?: DecisionStateSent;
117
+ constructor(code: DecisionProviderErrorCode, message: string, details?: {
118
+ status?: number;
119
+ attempts?: number;
120
+ refId?: string;
121
+ costUsd?: number | null;
122
+ costBasis?: CostBasis;
123
+ unsent?: boolean;
124
+ stateSent?: DecisionStateSent;
125
+ cause?: unknown;
126
+ });
127
+ }
128
+ export interface DecisionProvider {
129
+ /** "jev", "parallel", "http:<name>" and the like. */
130
+ readonly id: string;
131
+ /** The environment variables it reads its keys from, by name; never their values. */
132
+ readonly needs: readonly string[];
133
+ readonly capabilities: DecisionCapabilities;
134
+ decide(request: DecisionRequest, ctx: DecisionContext): Promise<DecisionOutcome>;
135
+ }
136
+ /** What a provider's error books for its request: one sent whose outcome was lost (`outcome_unknown`), or one answered
137
+ * with what the seam or the provider rejects (`invalid_response`), was or may have been paid for, and is booked at the
138
+ * cost the error carries, null when that is unknown (never 0). Undefined for an error that books nothing. */
139
+ export declare function chargedCost(error: unknown): number | null | undefined;
140
+ /** Refuses, as invalid_request, a request beyond what `capabilities` declares: a question type it does not answer, more
141
+ * questions than it takes, a larger state, or a model it does not serve. A provider calls it before it sends anything. */
142
+ export declare function checkCapabilities(capabilities: DecisionCapabilities, request: Pick<DecisionRequest, "questions" | "state" | "model">): void;
143
+ export interface JudgeFromProviderOptions {
144
+ deadlineMs?: number | null;
145
+ /** Reads the images a node names. A request with images on a host without it is refused as configuration. */
146
+ loadImage?: LoadImage;
147
+ }
148
+ /** The interpreter's runJudge, answered by `provider`: the request goes to it with the decision's id, its signal and
149
+ * `deadlineMs`, and with the images it names, loaded through `loadImage` within that deadline (the provider gets what is
150
+ * left of it; a load the deadline cuts is `timeout`, one the signal cuts `aborted`, and neither was sent); a choice or
151
+ * score without a confidence gets one derived, and the result names each one's source and each image's digest. The
152
+ * answers are validated against the questions, and ones that do not match them are invalid_response. */
153
+ export declare function judgeFromProvider(provider: DecisionProvider, options?: JudgeFromProviderOptions): RunJudge;
154
+ /** The interpreter's runJudge over a host's providers: each request goes to the provider its node names, or to
155
+ * `default`, with the node's pinned model, within the shorter of the node's `timeoutMs` and the provider's own
156
+ * `deadlineMs`: a node only ever shortens it. The node's bound is kept here: when it passes, the call is cut, and a cut
157
+ * call may already have been sent and billed, so it is `outcome_unknown` (the decision escalates as interrupted), never
158
+ * asked again. A call cut while its images load was not sent, and stays `timeout`. The result names the provider that
159
+ * answered. */
160
+ export declare function judgeFromProviders(options: {
161
+ providers: Readonly<Record<string, DecisionProvider>>;
162
+ default: string;
163
+ deadlineMs?: number | null;
164
+ loadImage?: LoadImage;
165
+ }): RunJudge;
166
+ export {};
@@ -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
+ }
@@ -1,5 +1,38 @@
1
- import { type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
1
+ import type { CostBasis, DecisionEvidence } from "./decision-provider.js";
2
+ import { type ConfidenceSource, type SystemOneAnswer, type SystemOneQuestion } from "./system-one.js";
2
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
+ };
3
36
  /** The typed questions the interpreter asks: the five question nodes and predicates, and a generative
4
37
  * node's `verify` clause. */
5
38
  export type DecisionKind = "judge" | "pick" | "sift" | "route" | "ask" | "verify";
@@ -76,7 +109,8 @@ export type DecisionReceipt = {
76
109
  * were refused. `cancelled`: the request's signal was aborted before it settled, so whether it was
77
110
  * served is not known. */
78
111
  status: "answered" | "failed" | "cancelled";
79
- /** SHA-256 of the canonical JSON of the state the judge was given. */
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`). */
80
114
  state_sha256: string;
81
115
  questions: Record<string, SystemOneQuestion>;
82
116
  /** What came back, as it came back; empty when nothing did. */
@@ -94,7 +128,31 @@ export type DecisionReceipt = {
94
128
  request_sha256: string | null;
95
129
  /** Wall time of the judge call, in milliseconds. */
96
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. */
97
154
  error?: string;
155
+ error_truncated?: boolean;
98
156
  };
99
157
  /** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
100
158
  * receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
@@ -1,8 +1,15 @@
1
- // Decision receipts: one record per typed-question request, holding what was asked, what came back, the
2
- // rule that turns those answers into an action (its thresholds included) and the action itself. A receipt
3
- // alone explains a decision: `rederiveDecision` recomputes the action from it without a model call.
4
1
  import { answerConfidence, answersToValue } from "./system-one.js";
5
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;
6
13
  /** The action a receipt's answers and rule determine, recomputed without a model call: for an answered
7
14
  * receipt it equals `receipt.action`. Null for a receipt that decided nothing. */
8
15
  export function rederiveDecision(receipt) {
@@ -32,6 +39,9 @@ export function rederiveDecision(receipt) {
32
39
  const answer = answers.branch;
33
40
  if (!answer || typeof answer !== "object")
34
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;
35
45
  const branch = answer.choice;
36
46
  // The chosen branch must be a string; when the rule carries `branches` (recorded since this check was
37
47
  // added) it must name one of them. A rule recorded before `branches` skips the membership check, so an
package/dist/dry-run.d.ts CHANGED
@@ -11,7 +11,24 @@ export type DryRunResult = {
11
11
  problems: string[];
12
12
  stage?: string;
13
13
  };
14
- 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;
15
32
  export type DryRunOptions = {
16
33
  sop?: string;
17
34
  probeContext?: {
@@ -28,5 +45,18 @@ export type DryRunOptions = {
28
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
29
46
  * default. */
30
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;
31
61
  };
32
62
  export declare function dryRunWorkflow(workflow: Workflow, opts?: DryRunOptions): Promise<DryRunResult>;