@parcha/agentrun-dsl 0.1.0-beta.16 → 0.1.0-beta.161

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 (75) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +153 -16
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +4 -3
  6. package/dist/author.js +20 -11
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +64 -3
  14. package/dist/decision-receipts.js +50 -8
  15. package/dist/dry-run.d.ts +35 -1
  16. package/dist/dry-run.js +131 -25
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +107 -5
  20. package/dist/graph.js +284 -9
  21. package/dist/index.d.ts +17 -12
  22. package/dist/index.js +16 -10
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +14 -1
  25. package/dist/pattern-screen.d.ts +14 -0
  26. package/dist/pattern-screen.js +451 -0
  27. package/dist/predicates.d.ts +29 -0
  28. package/dist/predicates.js +62 -3
  29. package/dist/record.d.ts +4 -0
  30. package/dist/record.js +6 -0
  31. package/dist/recovery/binding.js +2 -1
  32. package/dist/recovery/call-key.d.ts +0 -4
  33. package/dist/recovery/call-key.js +0 -7
  34. package/dist/recovery/driver.d.ts +59 -24
  35. package/dist/recovery/driver.js +251 -73
  36. package/dist/recovery/frozen-snapshot.d.ts +54 -4
  37. package/dist/recovery/frozen-snapshot.js +44 -14
  38. package/dist/recovery/handoff-receipts.d.ts +0 -35
  39. package/dist/recovery/handoff-receipts.js +2 -44
  40. package/dist/recovery/index.d.ts +4 -8
  41. package/dist/recovery/index.js +4 -7
  42. package/dist/recovery/with-recovery.d.ts +9 -3
  43. package/dist/recovery/with-recovery.js +78 -18
  44. package/dist/submit-envelope.d.ts +9 -0
  45. package/dist/submit-envelope.js +44 -0
  46. package/dist/system-one.d.ts +21 -2
  47. package/dist/system-one.js +96 -18
  48. package/dist/testing/decision-provider.d.ts +32 -0
  49. package/dist/testing/decision-provider.js +183 -0
  50. package/dist/testing/index.d.ts +1 -0
  51. package/dist/testing/index.js +2 -0
  52. package/dist/vocabulary.d.ts +11 -3
  53. package/dist/vocabulary.js +19 -9
  54. package/dist/workflow-shape.d.ts +7 -0
  55. package/dist/workflow-shape.js +116 -70
  56. package/dist/workflow.d.ts +171 -19
  57. package/dist/workflow.js +1063 -399
  58. package/dist/zod-json-contract.js +6 -8
  59. package/package.json +12 -4
  60. package/schema/workflow.schema.json +366 -1
  61. package/skills/author/SKILL.md +6 -1
  62. package/skills/author/references/jev-decisions.md +50 -5
  63. package/skills/author/references/language.md +19 -14
  64. package/dist/recovery/effect-failure.d.ts +0 -34
  65. package/dist/recovery/effect-failure.js +0 -62
  66. package/dist/recovery/handoff-block.d.ts +0 -36
  67. package/dist/recovery/handoff-block.js +0 -148
  68. package/dist/recovery/handoff-digest.d.ts +0 -58
  69. package/dist/recovery/handoff-digest.js +0 -195
  70. package/dist/recovery/handoff-files.d.ts +0 -54
  71. package/dist/recovery/handoff-files.js +0 -162
  72. package/dist/recovery/handoff-redact.d.ts +0 -12
  73. package/dist/recovery/handoff-redact.js +0 -44
  74. package/dist/recovery/handoff.d.ts +0 -44
  75. package/dist/recovery/handoff.js +0 -46
@@ -44,6 +44,10 @@ export type SystemOneAnswer = {
44
44
  type: "box";
45
45
  box: SystemOneBox;
46
46
  confidence: number | null;
47
+ }
48
+ /** The provider declined to answer this question. It is never decoded as a value. */
49
+ | {
50
+ type: "refusal";
47
51
  };
48
52
  export type SystemOneResult = {
49
53
  answers: Record<string, SystemOneAnswer>;
@@ -61,7 +65,6 @@ export declare const SYSTEM_ONE_LIMITS: {
61
65
  readonly minScoreLevels: 2;
62
66
  readonly maxScoreLevels: 10;
63
67
  };
64
- export declare const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
65
68
  export type CompiledQuestions = Record<string, SystemOneQuestion>;
66
69
  export declare function compileQuestions(schema: Record<string, unknown>, definitions?: Record<string, unknown>): {
67
70
  ok: true;
@@ -81,7 +84,7 @@ export type AnswersSidecar = {
81
84
  export declare function answersSidecar(answers: Record<string, SystemOneAnswer>): AnswersSidecar;
82
85
  export declare function synthesizeAnswers(questions: Record<string, SystemOneQuestion>): Record<string, SystemOneAnswer>;
83
86
  export type SystemOneRetryClass = "http_429" | "http_5xx" | "connection" | "timeout";
84
- declare const responseReasons: readonly ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability", "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range"];
87
+ declare const responseReasons: readonly ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability", "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range", "refusal"];
85
88
  export type SystemOneResponseReason = typeof responseReasons[number];
86
89
  export declare function isSystemOneResponseReason(value: unknown): value is SystemOneResponseReason;
87
90
  export declare class SystemOneError extends Error {
@@ -91,4 +94,20 @@ export declare class SystemOneError extends Error {
91
94
  constructor(message: string, retryClass: SystemOneRetryClass | null, status?: number | undefined, responseReason?: SystemOneResponseReason);
92
95
  }
93
96
  export declare function validateAnswers(questions: Record<string, SystemOneQuestion>, answers: unknown): asserts answers is Record<string, SystemOneAnswer>;
97
+ /** The questions whose answer is a refusal, in answer order. */
98
+ export declare function refusedQuestions(answers: Record<string, unknown>): string[];
99
+ /** The confidence TypeSafe documents for Jev (docs.typesafe.ai/confidence), computed from an answer's probabilities: for a
100
+ * choice of n options, (p - 1/n) / (1 - 1/n) for the chosen option's p, floored at 0; for a score of n levels, 1 minus
101
+ * the probability-weighted distance from the most likely level (the lowest, on a tie) over that distance for an even
102
+ * spread, floored at 0. Null when the probabilities are missing or are not a distribution over the answer's options. */
103
+ export declare function deriveConfidence(answer: unknown): number | null;
104
+ /** Where an answer's confidence came from: the provider's response, or derived from its probabilities. */
105
+ export type ConfidenceSource = "provider" | "derived";
106
+ /** The answers with every choice and score carrying a confidence: the provider's own when it gave one in [0, 1], else
107
+ * one derived from the probabilities (deriveConfidence), else 0, which validation then refuses with the probabilities
108
+ * that left nothing to derive from. `confidence_source` names each choice and score answer's source. */
109
+ export declare function completeConfidence(questions: Record<string, SystemOneQuestion>, answers: Record<string, unknown>): {
110
+ answers: Record<string, unknown>;
111
+ confidence_source: Record<string, ConfidenceSource>;
112
+ };
94
113
  export {};
@@ -1,5 +1,5 @@
1
+ import { isRecord } from "./record.js";
1
2
  export const SYSTEM_ONE_LIMITS = { maxChoiceOptions: 240, minScoreLevels: 2, maxScoreLevels: 10 };
2
- export const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
3
3
  const CRITERIA = "criteria";
4
4
  export function compileQuestions(schema, definitions = {}) {
5
5
  const errors = [];
@@ -45,10 +45,10 @@ export function compileQuestions(schema, definitions = {}) {
45
45
  }
46
46
  const map = Object.create(null);
47
47
  for (const option of spec.enum) {
48
- const text = criteria && typeof criteria === "object" && !Array.isArray(criteria) ? criteria[option] : undefined;
48
+ const text = isRecord(criteria) ? criteria[option] : undefined;
49
49
  map[option] = typeof text === "string" && text.trim() ? text.trim() : null;
50
50
  }
51
- if (criteria && typeof criteria === "object" && !Array.isArray(criteria)) {
51
+ if (isRecord(criteria)) {
52
52
  const unknown = Object.keys(criteria).filter((k) => !spec.enum.includes(k));
53
53
  if (unknown.length)
54
54
  errors.push(`property "${id}": criteria name options the enum does not have: ${unknown.join(", ")}`);
@@ -57,7 +57,7 @@ export function compileQuestions(schema, definitions = {}) {
57
57
  continue;
58
58
  }
59
59
  if (types.length === 1 && types[0] === "boolean") {
60
- const c = criteria && typeof criteria === "object" && !Array.isArray(criteria) ? criteria : undefined;
60
+ const c = isRecord(criteria) ? criteria : undefined;
61
61
  questions[id] = { type: "noul", instructions, ...(c ? { criteria: { ...(typeof c.true === "string" ? { true: c.true } : {}), ...(typeof c.false === "string" ? { false: c.false } : {}) } } : {}) };
62
62
  continue;
63
63
  }
@@ -84,6 +84,9 @@ export function compileQuestions(schema, definitions = {}) {
84
84
  }
85
85
  export function answersToValue(answers, questions) {
86
86
  const out = Object.create(null);
87
+ const refused = refusedQuestions(answers).filter((id) => Object.hasOwn(questions, id));
88
+ if (refused.length)
89
+ throw refusalError(refused);
87
90
  for (const [id, q] of Object.entries(questions)) {
88
91
  const a = answers[id];
89
92
  if (!a)
@@ -104,6 +107,8 @@ export function answersToValue(answers, questions) {
104
107
  export function answerConfidence(answer) {
105
108
  if (!answer || typeof answer !== "object")
106
109
  throw new SystemOneError("System One answer missing for a question that was asked", null);
110
+ if (answer.type === "refusal")
111
+ return 0;
107
112
  if (answer.type === "noul")
108
113
  return Math.abs(answer.noul - 0.5) * 2;
109
114
  // A box the provider reported no confidence for counts as none: unknown is never read as sure.
@@ -137,7 +142,7 @@ export function synthesizeAnswers(questions) {
137
142
  return { ...out };
138
143
  }
139
144
  const responseReasons = ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability",
140
- "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range"];
145
+ "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range", "refusal"];
141
146
  export function isSystemOneResponseReason(value) {
142
147
  return typeof value === "string" && responseReasons.includes(value);
143
148
  }
@@ -155,17 +160,24 @@ export class SystemOneError extends Error {
155
160
  }
156
161
  }
157
162
  const unit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
158
- // System One reports probabilities rounded to two places, so the reported sum drifts from 1 by up to
159
- // half a step per option (3 × 0.33 = 0.99; 8 × 0.13 = 1.04). A distribution is accepted when it could
160
- // be that rounding of one summing to 1: a value on the two-place grid may be off by ±0.005 (within
161
- // [0, 1]); any other value is taken as exact. With no grid values this is |sum − 1| ≤ 1e-5, the
162
- // check for full-precision distributions. Answers are accepted as reported, never rescaled.
163
- const ROUNDING_HALF_STEP = 0.005;
164
- const onTwoPlaceGrid = (p) => Math.abs(p * 100 - Math.round(p * 100)) < 1e-9;
163
+ // System One reports probabilities rounded, Jev to two places and some OpenRouter models to four (Cloudflare's clef,
164
+ // live: 0.2967 + 0.6661 + 0.0371 = 0.9999), so the reported sum drifts from 1 by up to half a step per option
165
+ // (3 × 0.33 = 0.99; 8 × 0.13 = 1.04). A distribution is accepted when it could be that rounding of one summing to 1: a
166
+ // value on the two-, three- or four-place grid may be off by half that grid's step (within [0, 1]), the coarsest grid it
167
+ // lies on; any other value is taken as exact. With no grid values this is |sum − 1| ≤ 1e-5, the check for
168
+ // full-precision distributions. Answers are accepted as reported, never rescaled.
169
+ const roundingHalfStep = (p) => {
170
+ for (const places of [2, 3, 4]) {
171
+ const scale = 10 ** places;
172
+ if (Math.abs(p * scale - Math.round(p * scale)) < 1e-9 * scale / 100)
173
+ return 0.5 / scale;
174
+ }
175
+ return 0;
176
+ };
165
177
  function roundedFromUnitMass(probabilities) {
166
178
  let low = 0, high = 0;
167
179
  for (const p of probabilities) {
168
- const step = onTwoPlaceGrid(p) ? ROUNDING_HALF_STEP : 0;
180
+ const step = roundingHalfStep(p);
169
181
  low += Math.max(0, p - step);
170
182
  high += Math.min(1, p + step);
171
183
  }
@@ -174,13 +186,13 @@ function roundedFromUnitMass(probabilities) {
174
186
  // A Score's weighted level drifts the same way. The unrounded probabilities lie within their rounding
175
187
  // intervals and sum to 1, so Σ level·p lies between two bounds: start every level at its interval's
176
188
  // low end, then give the rest of the unit mass to the lowest levels (the minimum) or the highest (the
177
- // maximum), each up to its interval's high end. A score on the grid is itself off by up to 0.005. The
189
+ // maximum), each up to its interval's high end. A score on a grid is itself off by up to half its step. The
178
190
  // score is accepted when its interval meets [min, max]; with no grid values this is
179
191
  // |score − Σ level·p| ≤ 1e-5. A score that is not a number contradicts nothing here and is left to
180
192
  // the range check, as before.
181
193
  function scoreContradictsDistribution(score, probabilities) {
182
194
  const levels = Object.entries(probabilities).map(([level, p]) => {
183
- const step = onTwoPlaceGrid(p) ? ROUNDING_HALF_STEP : 0;
195
+ const step = roundingHalfStep(p);
184
196
  return { level: Number(level), low: Math.max(0, p - step), high: Math.min(1, p + step) };
185
197
  }).sort((a, b) => a.level - b.level);
186
198
  const floor = levels.reduce((sum, l) => sum + l.level * l.low, 0);
@@ -195,11 +207,11 @@ function scoreContradictsDistribution(score, probabilities) {
195
207
  return weighted;
196
208
  };
197
209
  const min = fill(levels), max = fill([...levels].reverse());
198
- const step = onTwoPlaceGrid(score) ? ROUNDING_HALF_STEP : 0;
210
+ const step = roundingHalfStep(score);
199
211
  return score - step > max + 1e-5 || score + step < min - 1e-5;
200
212
  }
201
213
  export function validateAnswers(questions, answers) {
202
- if (!answers || typeof answers !== "object" || Array.isArray(answers))
214
+ if (!isRecord(answers))
203
215
  throw new SystemOneError("System One response carries no answers", null, undefined, "answers_shape");
204
216
  const answerKeys = Object.keys(answers);
205
217
  if (answerKeys.length !== Object.keys(questions).length || answerKeys.some(id => !Object.hasOwn(questions, id)))
@@ -208,6 +220,11 @@ export function validateAnswers(questions, answers) {
208
220
  const a = answers[id];
209
221
  if (!a || typeof a !== "object")
210
222
  throw new SystemOneError("System One returned no answer for a question", null, undefined, "answer_shape");
223
+ if (a.type === "refusal") {
224
+ if (Object.keys(a).length !== 1)
225
+ throw new SystemOneError("System One answer: a refusal carries nothing but its type", null, undefined, "answer_shape");
226
+ continue;
227
+ }
211
228
  if (a.type !== q.type)
212
229
  throw new SystemOneError("System One answer type does not match its question", null, undefined, "answer_type");
213
230
  if (q.type === "box") {
@@ -237,7 +254,7 @@ export function validateAnswers(questions, answers) {
237
254
  if (!roundedFromUnitMass(Object.values(a.probabilities)))
238
255
  throw new SystemOneError("System One answer: probabilities must sum to 1", null, undefined, "probability_mass");
239
256
  if (q.type === "score") {
240
- if (!a.legend || typeof a.legend !== "object" || Array.isArray(a.legend) || Object.keys(a.legend).length !== expectedKeys.length || q.criteria.some((text, index) => a.legend[String(index)] !== text))
257
+ if (!isRecord(a.legend) || Object.keys(a.legend).length !== expectedKeys.length || q.criteria.some((text, index) => a.legend[String(index)] !== text))
241
258
  throw new SystemOneError("System One answer: legend must match the score criteria", null, undefined, "score_legend");
242
259
  if (scoreContradictsDistribution(a.score, a.probabilities))
243
260
  throw new SystemOneError("System One answer: score must match its weighted distribution", null, undefined, "score_consistency");
@@ -248,3 +265,64 @@ export function validateAnswers(questions, answers) {
248
265
  throw new SystemOneError("System One answer: score is outside its levels", null, undefined, "score_range");
249
266
  }
250
267
  }
268
+ /** The questions whose answer is a refusal, in answer order. */
269
+ export function refusedQuestions(answers) {
270
+ return Object.entries(answers).filter(([, a]) => isRecord(a) && a.type === "refusal").map(([id]) => id);
271
+ }
272
+ /** What `answersToValue` throws for a refused answer: the backstop. A decision node never gets this far, since `decide()`
273
+ * escalates the run for review (DECISION_REFUSED) on a refusal first. */
274
+ function refusalError(ids) {
275
+ return new SystemOneError(`System One refused ${ids.length === 1 ? "question" : "questions"} ${ids.map((id) => `"${id}"`).join(", ")}`, null, undefined, "refusal");
276
+ }
277
+ /** The confidence TypeSafe documents for Jev (docs.typesafe.ai/confidence), computed from an answer's probabilities: for a
278
+ * choice of n options, (p - 1/n) / (1 - 1/n) for the chosen option's p, floored at 0; for a score of n levels, 1 minus
279
+ * the probability-weighted distance from the most likely level (the lowest, on a tie) over that distance for an even
280
+ * spread, floored at 0. Null when the probabilities are missing or are not a distribution over the answer's options. */
281
+ export function deriveConfidence(answer) {
282
+ if (!isRecord(answer) || !isRecord(answer.probabilities))
283
+ return null;
284
+ const probabilities = answer.probabilities;
285
+ const values = Object.values(probabilities);
286
+ const n = values.length;
287
+ if (n < 2 || !values.every(unit))
288
+ return null;
289
+ if (answer.type === "choice") {
290
+ if (typeof answer.choice !== "string" || !Object.hasOwn(probabilities, answer.choice))
291
+ return null;
292
+ return Math.min(1, Math.max(0, (probabilities[answer.choice] - 1 / n) / (1 - 1 / n)));
293
+ }
294
+ if (answer.type === "score") {
295
+ const levels = Array.from({ length: n }, (_, i) => probabilities[String(i)]);
296
+ if (!levels.every(unit))
297
+ return null;
298
+ const p = levels;
299
+ const mode = p.indexOf(Math.max(...p));
300
+ const spread = p.reduce((sum, pi, i) => sum + pi * Math.abs(i - mode), 0);
301
+ const even = p.reduce((sum, _, i) => sum + Math.abs(i - (n - 1) / 2), 0) / n;
302
+ return Math.min(1, Math.max(0, 1 - spread / even));
303
+ }
304
+ return null;
305
+ }
306
+ /** The answers with every choice and score carrying a confidence: the provider's own when it gave one in [0, 1], else
307
+ * one derived from the probabilities (deriveConfidence), else 0, which validation then refuses with the probabilities
308
+ * that left nothing to derive from. `confidence_source` names each choice and score answer's source. */
309
+ export function completeConfidence(questions, answers) {
310
+ // Null-prototype records: a question may be named __proto__, which on a plain object would set its prototype.
311
+ const out = Object.create(null);
312
+ const confidence_source = Object.create(null);
313
+ for (const [id, answer] of Object.entries(answers)) {
314
+ const asked = Object.hasOwn(questions, id) ? questions[id] : undefined;
315
+ if (!isRecord(answer) || (answer.type !== "choice" && answer.type !== "score") || asked?.type !== answer.type) {
316
+ out[id] = answer;
317
+ continue;
318
+ }
319
+ if (unit(answer.confidence)) {
320
+ out[id] = answer;
321
+ confidence_source[id] = "provider";
322
+ continue;
323
+ }
324
+ out[id] = { ...answer, confidence: deriveConfidence(answer) ?? 0 };
325
+ confidence_source[id] = "derived";
326
+ }
327
+ return { answers: { ...out }, confidence_source: { ...confidence_source } };
328
+ }
@@ -0,0 +1,32 @@
1
+ import { type DecisionEvidence, type DecisionProvider } from "../decision-provider.js";
2
+ /** What the kit's fake transport answers one call with. An `answer` carries answers in the DSL's shape (and, for a
3
+ * provider with evidence, sources), which the kit sends in the provider's own wire format. `lost` is a connection that
4
+ * drops after the request was sent: whether it was served is not known. */
5
+ export type KitReply = {
6
+ kind: "answer";
7
+ answers: Record<string, unknown>;
8
+ evidence?: DecisionEvidence[];
9
+ } | {
10
+ kind: "status";
11
+ status: number;
12
+ } | {
13
+ kind: "malformed";
14
+ } | {
15
+ kind: "lost";
16
+ } | {
17
+ kind: "hang";
18
+ };
19
+ export interface DecisionProviderKit {
20
+ /** A new provider under test whose transport answers each call with the next of `replies` (the last repeats), and
21
+ * the number of calls its transport has taken. Retry delays should be short: the suite waits for them. */
22
+ build(replies: KitReply[]): {
23
+ provider: DecisionProvider;
24
+ calls(): number;
25
+ };
26
+ /** The key the kit configures the provider with: it must never appear in a result or an error. */
27
+ canary: string;
28
+ /** Whether the provider's wire format can carry a refusal. */
29
+ refuses: boolean;
30
+ }
31
+ /** Registers the suite as `node:test` tests named under `name`. */
32
+ export declare function registerDecisionProviderConformance(name: string, kit: DecisionProviderKit): void;
@@ -0,0 +1,183 @@
1
+ // The DecisionProvider conformance suite: what a provider must hold for a decision workflow to rest on it. A provider
2
+ // package registers it in its own tests with a kit that builds the provider over a fake transport.
3
+ import assert from "node:assert/strict";
4
+ import { test } from "node:test";
5
+ import { DecisionProviderError } from "../decision-provider.js";
6
+ import { completeConfidence, validateAnswers } from "../system-one.js";
7
+ const QUESTIONS = {
8
+ holds: { type: "noul", instructions: "Does the statement hold?" },
9
+ pick: { type: "choice", instructions: "Which option fits?", criteria: { first: "the first", second: "the second" } },
10
+ level: { type: "score", instructions: "How strong is it?", criteria: ["weak", "middling", "strong"] },
11
+ };
12
+ const ANSWERS = {
13
+ holds: { type: "noul", noul: 0.8 },
14
+ pick: { type: "choice", choice: "first", probabilities: { first: 0.75, second: 0.25 }, confidence: 0.5 },
15
+ level: { type: "score", score: 1.5, legend: { 0: "weak", 1: "middling", 2: "strong" }, probabilities: { 0: 0, 1: 0.5, 2: 0.5 }, confidence: 0.25 },
16
+ };
17
+ const EVIDENCE = [{ url: "https://example.org/a", title: "A source", excerpts: ["a passage"], scope: "call" }];
18
+ const BASES = ["reported", "estimate", "unknown"];
19
+ /** The smallest PNG: a 1x1 transparent pixel. */
20
+ const PNG = Uint8Array.from(Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", "base64"));
21
+ /** Registers the suite as `node:test` tests named under `name`. */
22
+ export function registerDecisionProviderConformance(name, kit) {
23
+ const it = (title, body, options = {}) => test(`${name}: ${title}`, { skip: options.skip ?? false, timeout: 20_000 }, body);
24
+ /** The questions of each type the provider answers, with answers to them. */
25
+ const asked = (provider) => {
26
+ const ids = Object.keys(QUESTIONS).filter((id) => provider.capabilities.types.includes(QUESTIONS[id].type));
27
+ return { questions: Object.fromEntries(ids.map((id) => [id, QUESTIONS[id]])), answers: Object.fromEntries(ids.map((id) => [id, structuredClone(ANSWERS[id])])) };
28
+ };
29
+ const request = (questions, state = { case: "conformance" }) => ({ label: "conformance", kind: "judge", state, questions });
30
+ const ctx = (over = {}) => ({ decisionId: "conformance-decision", signal: over.signal ?? new AbortController().signal, deadlineMs: over.deadlineMs === undefined ? 5_000 : over.deadlineMs });
31
+ /** One decision on a provider whose transport gives `replies`. */
32
+ const decideOn = async (replies, questions, context = ctx()) => {
33
+ const { provider } = kit.build(replies);
34
+ return provider.decide(request(questions ?? asked(provider).questions), context);
35
+ };
36
+ const answerReply = (provider, extra = {}) => ({ kind: "answer", answers: asked(provider).answers, ...extra });
37
+ const probe = () => kit.build([{ kind: "hang" }]).provider;
38
+ /** `promise`, or a failure once `ms` pass: the referenced timer also keeps the process up while a request hangs. */
39
+ const within = (ms, promise) => {
40
+ let timer;
41
+ const late = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`still pending after ${ms} ms`)), ms); });
42
+ return Promise.race([promise, late]).finally(() => clearTimeout(timer));
43
+ };
44
+ const failsWith = (expected) => (error) => {
45
+ assert.ok(error instanceof DecisionProviderError, `a provider fails with a DecisionProviderError, got ${String(error)}`);
46
+ assert.equal(error.code, expected);
47
+ return true;
48
+ };
49
+ it("it answers exactly the questions asked, each in its declared type", async () => {
50
+ const { questions } = asked(probe());
51
+ const outcome = await decideOn([answerReply(probe())]);
52
+ assert.deepEqual(Object.keys(outcome.answers).sort(), Object.keys(questions).sort());
53
+ const { answers } = completeConfidence(questions, outcome.answers);
54
+ validateAnswers(questions, answers);
55
+ });
56
+ it("an answer to a question not asked, or none for one asked, is invalid_response", async () => {
57
+ const { answers } = asked(probe());
58
+ await assert.rejects(decideOn([{ kind: "answer", answers: { ...answers, unasked: { type: "noul", noul: 0.5 } } }]), failsWith("invalid_response"));
59
+ const [first, ...rest] = Object.keys(answers);
60
+ assert.ok(first && rest.length, "the provider answers at least two of noul, choice and score");
61
+ await assert.rejects(decideOn([{ kind: "answer", answers: Object.fromEntries(rest.map((id) => [id, answers[id]])) }]), failsWith("invalid_response"));
62
+ });
63
+ it("a cost it does not know is null, never 0, and cost_basis says how it was reached", async () => {
64
+ const outcome = await decideOn([answerReply(probe())]);
65
+ assert.ok(BASES.includes(outcome.cost_basis), `cost_basis is one of ${BASES.join(", ")}, got ${String(outcome.cost_basis)}`);
66
+ assert.equal(outcome.cost_usd === null, outcome.cost_basis === "unknown", `an unknown cost is null and a known one is not: ${outcome.cost_usd} (${outcome.cost_basis})`);
67
+ if (outcome.cost_usd !== null)
68
+ assert.ok(Number.isFinite(outcome.cost_usd) && outcome.cost_usd >= 0);
69
+ if (outcome.usage !== null)
70
+ assert.ok(Number.isSafeInteger(outcome.usage.input_tokens) && Number.isSafeInteger(outcome.usage.output_tokens));
71
+ });
72
+ it("401 and 403 are auth errors", async () => {
73
+ await assert.rejects(decideOn([{ kind: "status", status: 401 }]), failsWith("auth"));
74
+ await assert.rejects(decideOn([{ kind: "status", status: 403 }]), failsWith("auth"));
75
+ });
76
+ it("422 is invalid_request", async () => {
77
+ await assert.rejects(decideOn([{ kind: "status", status: 422 }]), failsWith("invalid_request"));
78
+ });
79
+ it("429 is rate_limited once its retries are spent", async () => {
80
+ await assert.rejects(decideOn([{ kind: "status", status: 429 }]), failsWith("rate_limited"));
81
+ });
82
+ it("a 5xx is outcome_unknown for a provider that cannot replay, and an http error for one that dedupes", async () => {
83
+ const code = probe().capabilities.replay === "never" ? "outcome_unknown" : "http";
84
+ for (const status of [500, 503])
85
+ await assert.rejects(decideOn([{ kind: "status", status }]), failsWith(code));
86
+ });
87
+ it("a provider that cannot replay never retries a failure after the request was sent", async () => {
88
+ if (probe().capabilities.replay !== "never")
89
+ return;
90
+ for (const reply of [{ kind: "status", status: 500 }, { kind: "status", status: 503 }, { kind: "status", status: 408 }, { kind: "lost" }]) {
91
+ const { provider, calls } = kit.build([reply, answerReply(probe())]);
92
+ await assert.rejects(provider.decide(request(asked(provider).questions), ctx()), failsWith("outcome_unknown"));
93
+ assert.equal(calls(), 1, `${JSON.stringify(reply)} was sent ${calls()} times`);
94
+ }
95
+ });
96
+ it("a malformed body is invalid_response", async () => {
97
+ await assert.rejects(decideOn([{ kind: "malformed" }]), failsWith("invalid_response"));
98
+ });
99
+ it("an abort stops a request in flight as aborted", async () => {
100
+ const controller = new AbortController();
101
+ setTimeout(() => controller.abort(), 20);
102
+ await assert.rejects(within(2_000, decideOn([{ kind: "hang" }], undefined, ctx({ signal: controller.signal, deadlineMs: 10_000 }))), failsWith("aborted"));
103
+ });
104
+ it("a request in flight past its deadline is outcome_unknown for a provider that cannot replay, and timeout for one that dedupes", async () => {
105
+ const code = probe().capabilities.replay === "never" ? "outcome_unknown" : "timeout";
106
+ await assert.rejects(within(3_000, decideOn([{ kind: "hang" }], undefined, ctx({ deadlineMs: 50 }))), failsWith(code));
107
+ });
108
+ it("no key appears in a result or an error", async () => {
109
+ const seen = [JSON.stringify(await decideOn([answerReply(probe(), { evidence: EVIDENCE })]))];
110
+ for (const reply of [{ kind: "status", status: 401 }, { kind: "status", status: 422 }, { kind: "status", status: 429 }, { kind: "status", status: 500 }, { kind: "malformed" }]) {
111
+ try {
112
+ await decideOn([reply]);
113
+ seen.push("no error");
114
+ }
115
+ catch (error) {
116
+ seen.push(String(error), error?.stack ?? "", JSON.stringify(error));
117
+ }
118
+ }
119
+ for (const text of seen)
120
+ assert.ok(!text.includes(kit.canary), "the key appears in what the provider returned or threw");
121
+ });
122
+ it("a request beyond its declared capabilities is refused before anything is sent", async () => {
123
+ const { provider, calls } = kit.build([answerReply(probe())]);
124
+ const { maxQuestions, maxStateBytes, types } = provider.capabilities;
125
+ const over = [];
126
+ if (maxQuestions !== null)
127
+ over.push(request(Object.fromEntries(Array.from({ length: maxQuestions + 1 }, (_, i) => [`q${i}`, { type: "noul", instructions: `Question ${i}?` }]))));
128
+ if (!types.includes("box"))
129
+ over.push(request({ spot: { type: "box", instructions: "Where is it?" } }));
130
+ if (maxStateBytes !== null)
131
+ over.push(request(asked(provider).questions, { text: "x".repeat(maxStateBytes + 1) }));
132
+ if (provider.capabilities.models)
133
+ over.push({ ...request(asked(provider).questions), model: "a-model-it-does-not-declare" });
134
+ for (const each of over)
135
+ await assert.rejects(provider.decide(each, ctx()), failsWith("invalid_request"));
136
+ assert.equal(calls(), 0, "nothing was sent");
137
+ });
138
+ it("a refusal comes back as a refusal", async () => {
139
+ const { answers } = asked(probe());
140
+ const outcome = await decideOn([{ kind: "answer", answers: { ...answers, holds: { type: "refusal" } } }]);
141
+ assert.deepEqual(outcome.answers.holds, { type: "refusal" });
142
+ }, { skip: kit.refuses ? false : "the provider's wire format carries no refusal" });
143
+ it("evidence is a list of sources, and the request id a string or null", async () => {
144
+ const provider = probe();
145
+ const outcome = await decideOn([answerReply(provider, { evidence: EVIDENCE })]);
146
+ assert.ok(Array.isArray(outcome.evidence), "evidence is a list");
147
+ for (const source of outcome.evidence) {
148
+ assert.equal(typeof source.url, "string");
149
+ assert.ok(source.title === null || typeof source.title === "string");
150
+ assert.ok(Array.isArray(source.excerpts) && source.excerpts.every((excerpt) => typeof excerpt === "string"));
151
+ assert.equal(typeof source.scope, "string");
152
+ }
153
+ if (provider.capabilities.evidence === "none")
154
+ assert.equal(outcome.evidence.length, 0, "a provider with no evidence returns none");
155
+ else
156
+ assert.ok(outcome.evidence.length > 0, "a provider with evidence returns the sources it was given");
157
+ assert.ok(outcome.provider_request_id === null || typeof outcome.provider_request_id === "string");
158
+ });
159
+ it("it declares only what the seam can send: noul, choice and score questions, from text, JSON, a URL or an image", async () => {
160
+ // A box question has no node that asks it, and the seam carries no PDF: a provider that declares either cannot be
161
+ // asked for it through judgeFromProvider.
162
+ const { capabilities } = probe();
163
+ for (const type of capabilities.types)
164
+ assert.ok(["noul", "choice", "score"].includes(type), `it declares ${type} questions, which the seam cannot send`);
165
+ for (const input of capabilities.inputs)
166
+ assert.ok(["text", "json", "url", "image"].includes(input), `it declares ${input} input, which the seam cannot carry`);
167
+ });
168
+ it("a provider that takes images answers a request that carries one, named in its state", async () => {
169
+ const { questions, answers } = asked(probe());
170
+ const { provider, calls } = kit.build([{ kind: "answer", answers }]);
171
+ const images = { "<page>": { bytes: PNG, mime: "image/png", ref: "pages/conformance/1.png" } };
172
+ const outcome = await provider.decide({ ...request(questions, { page: "<page>", note: "the page is <page>" }), images }, ctx());
173
+ assert.deepEqual(Object.keys(outcome.answers).sort(), Object.keys(questions).sort());
174
+ assert.equal(calls(), 1);
175
+ }, { skip: kit.build([{ kind: "hang" }]).provider.capabilities.inputs.includes("image") ? false : "the provider takes no image input" });
176
+ it("needs names environment variables, never their values", async () => {
177
+ const { needs } = probe();
178
+ for (const variable of needs) {
179
+ assert.match(variable, /^[A-Z][A-Z0-9_]*$/);
180
+ assert.ok(!variable.includes(kit.canary));
181
+ }
182
+ });
183
+ }
@@ -0,0 +1 @@
1
+ export { registerDecisionProviderConformance, type DecisionProviderKit, type KitReply } from "./decision-provider.js";
@@ -0,0 +1,2 @@
1
+ // Test kits a host or provider package registers in its own tests.
2
+ export { registerDecisionProviderConformance } from "./decision-provider.js";
@@ -2,6 +2,11 @@ export declare const WORKFLOW_NODE_KINDS: readonly ["chain", "code", "agent", "d
2
2
  export type WorkflowNodeKind = typeof WORKFLOW_NODE_KINDS[number];
3
3
  /** Generative kinds: one adapter session each, answering against a schema. */
4
4
  export declare const GENERATIVE_NODE_KINDS: readonly ["agent", "decide", "extract", "report"];
5
+ /** What a decision node or an `ask` predicate may say about its provider: which one, a pinned model, the evidence it
6
+ * needs, its own time bound, and the images it sends (token -> image reference). */
7
+ export declare const DECISION_NODE_FIELDS: readonly ["provider", "model", "evidence", "timeoutMs", "images"];
8
+ /** The longest a decision node may give its provider, in milliseconds. A node only ever shortens its provider's own deadline. */
9
+ export declare const DECISION_TIMEOUT_MAX_MS = 120000;
5
10
  /** Typed-question kinds: one judge request each, no tools and no session. */
6
11
  export declare const JUDGMENT_NODE_KINDS: readonly ["judge", "pick", "sift", "route"];
7
12
  /** The fields each node kind accepts. Any other key is an authoring error. */
@@ -15,15 +20,18 @@ export declare const HOST_NODE_FIELDS: readonly ["metadata"];
15
20
  export declare const IGNORED_NODE_FIELDS: {
16
21
  readonly [Kind in WorkflowNodeKind]?: readonly string[];
17
22
  };
18
- /** Predicates that read a state value. `poll` accepts only these. */
19
- export declare const MECHANICAL_PREDICATES: readonly ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items"];
23
+ /** Predicates that read a state value. `poll` accepts only these, and `not` holds only one of these. */
24
+ export declare const MECHANICAL_PREDICATES: readonly ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items", "field_type", "quote_missing", "not"];
20
25
  /** Every predicate `loop.until` and `escalate.when` accept: the mechanical set plus `ask`, a yes/no judge question. */
21
- export declare const WORKFLOW_PREDICATES: readonly ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items", "ask"];
26
+ export declare const WORKFLOW_PREDICATES: readonly ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items", "field_type", "quote_missing", "not", "ask"];
22
27
  export type WorkflowPredicateName = typeof WORKFLOW_PREDICATES[number];
23
28
  /** The fields each predicate takes. */
24
29
  export declare const PREDICATE_FIELDS: {
25
30
  readonly [Name in WorkflowPredicateName]: readonly string[];
26
31
  };
32
+ /** The JSON types `field_type` names. A number is a finite one: NaN and the infinities are no JSON value. */
33
+ export declare const FIELD_TYPES: readonly ["number", "string", "boolean", "array", "object", "null"];
34
+ export type FieldType = typeof FIELD_TYPES[number];
27
35
  export declare const EFFORT_LEVELS: readonly ["minimal", "low", "medium", "high"];
28
36
  /** There is no "off": every generative node thinks. */
29
37
  export declare const THINKING_LEVELS: readonly ["low", "medium", "high"];
@@ -6,6 +6,11 @@ export const WORKFLOW_NODE_KINDS = [
6
6
  ];
7
7
  /** Generative kinds: one adapter session each, answering against a schema. */
8
8
  export const GENERATIVE_NODE_KINDS = ["agent", "decide", "extract", "report"];
9
+ /** What a decision node or an `ask` predicate may say about its provider: which one, a pinned model, the evidence it
10
+ * needs, its own time bound, and the images it sends (token -> image reference). */
11
+ export const DECISION_NODE_FIELDS = ["provider", "model", "evidence", "timeoutMs", "images"];
12
+ /** The longest a decision node may give its provider, in milliseconds. A node only ever shortens its provider's own deadline. */
13
+ export const DECISION_TIMEOUT_MAX_MS = 120_000;
9
14
  /** Typed-question kinds: one judge request each, no tools and no session. */
10
15
  export const JUDGMENT_NODE_KINDS = ["judge", "pick", "sift", "route"];
11
16
  const GENERATIVE_FIELDS = ["node", "label", "state", "instructions", "sopSection", "out", "as", "requires", "tools", "effort", "thinking", "verify", "tier"];
@@ -13,21 +18,21 @@ const GENERATIVE_FIELDS = ["node", "label", "state", "instructions", "sopSection
13
18
  export const NODE_FIELDS = {
14
19
  chain: ["node", "steps"],
15
20
  code: ["node", "label", "code", "as"],
16
- agent: [...GENERATIVE_FIELDS, "budget_usd", "context"],
21
+ agent: [...GENERATIVE_FIELDS, "budget_usd", "max_turns", "context"],
17
22
  decide: GENERATIVE_FIELDS,
18
23
  extract: GENERATIVE_FIELDS,
19
24
  report: ["node", "label", "state", "instructions", "sopSection", "requires", "tools", "effort", "thinking"],
20
25
  artifact: ["node", "label", "state", "type", "path", "instructions", "sopSection", "requires", "tools", "effort", "thinking"],
21
- map: ["node", "label", "itemsPath", "body", "as", "resultPath", "maxConcurrency"],
26
+ map: ["node", "label", "itemsPath", "body", "as", "resultPath", "maxConcurrency", "onItemFailure", "failedAs"],
22
27
  parallel: ["node", "label", "branches"],
23
28
  loop: ["node", "label", "body", "until", "maxIters", "expect_iters"],
24
29
  escalate: ["node", "label", "when", "kind", "stage", "summary"],
25
30
  call: ["node", "label", "via", "tool", "args", "code", "input", "command", "env", "where", "out", "as", "produces", "deadline_s", "retry", "poll", "requires"],
26
31
  workflow: ["node", "label", "workflow", "input", "out", "as"],
27
- judge: ["node", "label", "state", "out", "as", "requires"],
28
- pick: ["node", "label", "itemsPath", "describe", "instructions", "state", "allowNone", "as", "requires"],
29
- sift: ["node", "label", "itemsPath", "describe", "state", "out", "as", "keep", "requires"],
30
- route: ["node", "label", "state", "instructions", "branches", "unsure", "valuePath", "otherwise", "as", "requires"],
32
+ judge: ["node", "label", "state", "out", "as", "requires", ...DECISION_NODE_FIELDS],
33
+ pick: ["node", "label", "itemsPath", "describe", "instructions", "state", "allowNone", "as", "requires", ...DECISION_NODE_FIELDS],
34
+ sift: ["node", "label", "itemsPath", "describe", "state", "out", "as", "keep", "requires", ...DECISION_NODE_FIELDS],
35
+ route: ["node", "label", "state", "instructions", "branches", "unsure", "valuePath", "otherwise", "as", "requires", ...DECISION_NODE_FIELDS],
31
36
  };
32
37
  /** Fields every node kind accepts in addition to its own. `metadata` is the host's: an optional object of
33
38
  * host markers the engine admits, carries and hashes with the document, and never reads. */
@@ -37,8 +42,8 @@ export const IGNORED_NODE_FIELDS = {
37
42
  agent: ["budget"],
38
43
  decide: ["samples", "voteField"],
39
44
  };
40
- /** Predicates that read a state value. `poll` accepts only these. */
41
- export const MECHANICAL_PREDICATES = ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items"];
45
+ /** Predicates that read a state value. `poll` accepts only these, and `not` holds only one of these. */
46
+ export const MECHANICAL_PREDICATES = ["field_equals", "field_true", "in", "count_gte", "gte", "lt", "empty", "no_new_items", "field_type", "quote_missing", "not"];
42
47
  /** Every predicate `loop.until` and `escalate.when` accept: the mechanical set plus `ask`, a yes/no judge question. */
43
48
  export const WORKFLOW_PREDICATES = [...MECHANICAL_PREDICATES, "ask"];
44
49
  /** The fields each predicate takes. */
@@ -51,8 +56,13 @@ export const PREDICATE_FIELDS = {
51
56
  lt: ["path", "n"],
52
57
  empty: ["path"],
53
58
  no_new_items: ["key"],
54
- ask: ["instructions", "state", "criteria", "gte"],
59
+ field_type: ["path", "type"],
60
+ quote_missing: ["path", "field", "pages"],
61
+ not: ["of"],
62
+ ask: ["instructions", "state", "criteria", "gte", ...DECISION_NODE_FIELDS],
55
63
  };
64
+ /** The JSON types `field_type` names. A number is a finite one: NaN and the infinities are no JSON value. */
65
+ export const FIELD_TYPES = ["number", "string", "boolean", "array", "object", "null"];
56
66
  export const EFFORT_LEVELS = ["minimal", "low", "medium", "high"];
57
67
  /** There is no "off": every generative node thinks. */
58
68
  export const THINKING_LEVELS = ["low", "medium", "high"];
@@ -1 +1,8 @@
1
+ /** A shape problem: its message, and a JSON Pointer to the value it is about (to the nearest value the document has, when
2
+ * the one the rule names is missing). */
3
+ export type ShapeIssue = {
4
+ path: string;
5
+ message: string;
6
+ };
1
7
  export declare function workflowShapeErrors(value: unknown, complete?: boolean): string[];
8
+ export declare function workflowShapeIssues(value: unknown, complete?: boolean): ShapeIssue[];