@parcha/agentrun-dsl 0.1.0-beta.26 → 0.1.0-beta.260

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 +8 -0
  4. package/dist/author-references.js +8 -0
  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 +64 -3
  14. package/dist/decision-receipts.js +50 -8
  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 +16 -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
package/dist/cli.js CHANGED
@@ -6,14 +6,15 @@ import { runWorkflow, validateWorkflow } from "./workflow.js";
6
6
  import { dryRunWorkflow } from "./dry-run.js";
7
7
  import { demoScenarios, runTriageDemo, supportTriage } from "./demo.js";
8
8
  import { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
9
+ import { isRecord } from "./record.js";
9
10
  const help = `AgentRun DSL — build, test, and run agent workflows
10
11
 
11
- agentrun demo [--scenario billing|technical|ambiguous] [--json]
12
- agentrun example [file.json] Write the demo workflow (never overwrite)
13
- agentrun inspect workflow.json [--json] Show structure without executing code
14
- agentrun validate workflow.json [input.json] --trusted
15
- agentrun dry-run workflow.json [input.json] --trusted [--strict]
16
- agentrun run workflow.json input.json --trusted
12
+ agentrun-dsl demo [--scenario billing|technical|ambiguous] [--json]
13
+ agentrun-dsl example [file.json] Write the demo workflow (never overwrite)
14
+ agentrun-dsl inspect workflow.json [--json] Show structure without executing code
15
+ agentrun-dsl validate workflow.json [input.json] --trusted
16
+ agentrun-dsl dry-run workflow.json [input.json] --trusted [--strict]
17
+ agentrun-dsl run workflow.json input.json --trusted
17
18
 
18
19
  demo runs the real interpreter with scripted judgments, without a key or network.
19
20
  run supports deterministic workflows; use the JavaScript API to supply agent,
@@ -35,7 +36,7 @@ async function main(args) {
35
36
  let scenario = "billing";
36
37
  let scenarioProvided = false;
37
38
  let json = false;
38
- const usage = "Usage: agentrun demo [--scenario billing|technical|ambiguous] [--json]";
39
+ const usage = "Usage: agentrun-dsl demo [--scenario billing|technical|ambiguous] [--json]";
39
40
  for (let i = 1; i < args.length; i++) {
40
41
  const arg = args[i];
41
42
  if (arg === "--json") {
@@ -79,24 +80,24 @@ async function main(args) {
79
80
  if (command === "inspect") {
80
81
  const positional = args.slice(1).filter(arg => arg !== "--json");
81
82
  if (positional.length !== 1 || positional[0].startsWith("--"))
82
- throw new Error("Usage: agentrun inspect workflow.json [--json]");
83
+ throw new Error("Usage: agentrun-dsl inspect workflow.json [--json]");
83
84
  const inspection = inspectWorkflow(JSON.parse(await readFile(resolve(positional[0]), "utf8")));
84
85
  console.log(args.includes("--json") ? JSON.stringify(inspection, null, 2) : formatWorkflowTree(inspection));
85
86
  return;
86
87
  }
87
88
  if (!["validate", "dry-run", "run"].includes(command))
88
- throw new Error(`Unknown command "${command}". Use agentrun --help.`);
89
+ throw new Error(`Unknown command "${command}". Use agentrun-dsl --help.`);
89
90
  if (!args.includes("--trusted"))
90
91
  throw new Error("Pass --trusted only after reviewing the workflow. Authored JavaScript may execute, including during validation.");
91
92
  const strict = command === "dry-run" && args.includes("--strict");
92
93
  const positional = args.slice(1).filter(arg => arg !== "--trusted" && !(strict && arg === "--strict"));
93
94
  const unknown = positional.find(arg => arg.startsWith("--"));
94
95
  if (unknown)
95
- throw new Error(`Unknown option "${unknown}". Use agentrun --help.`);
96
+ throw new Error(`Unknown option "${unknown}". Use agentrun-dsl --help.`);
96
97
  if (!positional[0])
97
98
  throw new Error("Provide a workflow JSON file.");
98
99
  if (positional.length > 2)
99
- throw new Error(`Usage: agentrun ${command} workflow.json ${command === "run" ? "input.json" : "[input.json]"} --trusted${command === "dry-run" ? " [--strict]" : ""}`);
100
+ throw new Error(`Usage: agentrun-dsl ${command} workflow.json ${command === "run" ? "input.json" : "[input.json]"} --trusted${command === "dry-run" ? " [--strict]" : ""}`);
100
101
  if (command === "run" && !positional[1])
101
102
  throw new Error("Provide an input JSON file.");
102
103
  const workflow = JSON.parse(await readFile(resolve(positional[0]), "utf8"));
@@ -109,7 +110,7 @@ async function main(args) {
109
110
  catch (error) {
110
111
  throw new Error(`Cannot read input JSON file "${positional[1]}": ${error instanceof Error ? error.message : String(error)}`);
111
112
  }
112
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
113
+ if (!isRecord(parsed))
113
114
  throw new Error("Input JSON must be an object.");
114
115
  input = parsed;
115
116
  }
@@ -8,3 +8,22 @@ export declare function deniedGlobalReferences(src: string): string[];
8
8
  * Syntax validity does not prove that the expression produces a function or a valid patch. */
9
9
  export declare function compileTransformSyntax(src: string): void;
10
10
  export declare function compileTransform(src: string): (value: any, ctx?: any) => any;
11
+ /** What a code node's script answers (transformScript): the function's value (`undefined: true` for undefined, which
12
+ * JSON has no word for), or the error it threw, in compileTransform's words. */
13
+ export type TransformOutcome = {
14
+ readonly ok: true;
15
+ readonly value?: unknown;
16
+ readonly undefined?: true;
17
+ } | {
18
+ readonly ok: false;
19
+ readonly error: string;
20
+ };
21
+ /**
22
+ * A code node as one script for a JavaScript engine of the host's own, for a host that runs code nodes in an isolated
23
+ * engine (a WebAssembly one) rather than in its own process. The script is a function expression: called with one
24
+ * string, the JSON of `{ state, ctx }`, it builds the function exactly as compileTransform does (the same factory text,
25
+ * denied globals and synchronous checks), calls it once, and returns one string, the JSON of a TransformOutcome. A value
26
+ * JSON can't carry (a BigInt, a cycle, or a function or symbol, which JSON would drop without a word) is an error. It
27
+ * uses only the language itself: no module, no host object, nothing in or out but the two strings.
28
+ */
29
+ export declare function transformScript(src: string): string;
package/dist/code-exec.js CHANGED
@@ -136,12 +136,20 @@ export function deniedGlobalReferences(src) {
136
136
  }
137
137
  return DENIED_GLOBALS.filter((name) => found.has(name));
138
138
  }
139
+ const EMPTY_SOURCE = "code transform source must be a non-empty string";
140
+ const ASYNC_FUNCTION = "code transforms are synchronous; async functions are not supported";
141
+ const THENABLE = "code transforms are synchronous; returned a Promise or thenable";
142
+ /** The start of the error a code node's program gives for a value JSON would drop silently (a function, a symbol). */
143
+ const NOT_JSON = "a code node must return JSON data, and its value holds a ";
144
+ /** The factory's body: `src` evaluated once, strict, under the denied globals' parameters. Both compileTransform and
145
+ * transformScript build their function from this one text, so a code node means the same wherever it runs. */
146
+ const factoryBody = (src) => `"use strict";\nconst __fn = (${src});\nif (typeof __fn !== "function") throw new Error("code must evaluate to a single (value) => value function");\nreturn __fn;`;
139
147
  function createTransformFactory(src) {
140
148
  if (typeof src !== "string" || !src.trim())
141
- throw new Error("code transform source must be a non-empty string");
149
+ throw new Error(EMPTY_SOURCE);
142
150
  let factory;
143
151
  try {
144
- factory = new Function(...DENIED_GLOBALS, `"use strict";\nconst __fn = (${src});\nif (typeof __fn !== "function") throw new Error("code must evaluate to a single (value) => value function");\nreturn __fn;`);
152
+ factory = new Function(...DENIED_GLOBALS, factoryBody(src));
145
153
  }
146
154
  catch (e) {
147
155
  throw new Error(`code transform failed to compile: ${e?.message || e}`);
@@ -156,16 +164,57 @@ export function compileTransformSyntax(src) {
156
164
  export function compileTransform(src) {
157
165
  const fn = createTransformFactory(src)(...DENIED_GLOBALS.map(() => undefined));
158
166
  if (isAsyncFunction(fn))
159
- throw new Error("code transforms are synchronous; async functions are not supported");
167
+ throw new Error(ASYNC_FUNCTION);
160
168
  return (value, ctx) => {
161
169
  const result = fn(value, ctx);
162
170
  if (isPromise(result)) {
163
171
  void Promise.prototype.then.call(result, undefined, () => { });
164
- throw new Error("code transforms are synchronous; returned a Promise or thenable");
172
+ throw new Error(THENABLE);
165
173
  }
166
174
  if (result && typeof result.then === "function") {
167
- throw new Error("code transforms are synchronous; returned a Promise or thenable");
175
+ throw new Error(THENABLE);
168
176
  }
169
177
  return result;
170
178
  };
171
179
  }
180
+ /**
181
+ * A code node as one script for a JavaScript engine of the host's own, for a host that runs code nodes in an isolated
182
+ * engine (a WebAssembly one) rather than in its own process. The script is a function expression: called with one
183
+ * string, the JSON of `{ state, ctx }`, it builds the function exactly as compileTransform does (the same factory text,
184
+ * denied globals and synchronous checks), calls it once, and returns one string, the JSON of a TransformOutcome. A value
185
+ * JSON can't carry (a BigInt, a cycle, or a function or symbol, which JSON would drop without a word) is an error. It
186
+ * uses only the language itself: no module, no host object, nothing in or out but the two strings.
187
+ */
188
+ export function transformScript(src) {
189
+ if (typeof src !== "string" || !src.trim())
190
+ throw new Error(EMPTY_SOURCE);
191
+ const text = JSON.stringify;
192
+ return [
193
+ `(function (input) {`,
194
+ ` "use strict";`,
195
+ ` var DENIED = ${text(DENIED_GLOBALS)};`,
196
+ ` var MakeFunction = Function, OwnPromise = Promise, stringify = JSON.stringify, parse = JSON.parse;`,
197
+ ` var AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;`,
198
+ ` var AsyncGeneratorFunction = Object.getPrototypeOf(async function* () {}).constructor;`,
199
+ ` try {`,
200
+ ` var given = parse(input);`,
201
+ ` var factory;`,
202
+ ` try { factory = MakeFunction.apply(null, DENIED.concat([${text(factoryBody(src))}])); }`,
203
+ ` catch (e) { throw new Error("code transform failed to compile: " + ((e && e.message) || e)); }`,
204
+ ` var fn = factory.apply(null, DENIED.map(function () { return undefined; }));`,
205
+ ` if (fn instanceof AsyncFunction || fn instanceof AsyncGeneratorFunction) throw new Error(${text(ASYNC_FUNCTION)});`,
206
+ ` var result = fn(given.state, given.ctx);`,
207
+ ` if (result instanceof OwnPromise) { OwnPromise.prototype.then.call(result, undefined, function () {}); throw new Error(${text(THENABLE)}); }`,
208
+ ` if (result && typeof result.then === "function") throw new Error(${text(THENABLE)});`,
209
+ ` var kept = result === undefined ? { ok: true, undefined: true } : { ok: true, value: result };`,
210
+ ` return stringify(kept, function (key, value) {`,
211
+ ` if (typeof value !== "function" && typeof value !== "symbol") return value;`,
212
+ ` var where = this === kept && key === "value" ? "" : " at " + stringify(key);`,
213
+ ` throw new Error(${text(NOT_JSON)} + typeof value + where);`,
214
+ ` });`,
215
+ ` } catch (e) {`,
216
+ ` return stringify({ ok: false, error: String(e && e.message !== undefined ? e.message : e) });`,
217
+ ` }`,
218
+ `})`,
219
+ ].join("\n");
220
+ }
@@ -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
+ }