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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +167 -23
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +13 -5
  6. package/dist/author.js +38 -19
  7. package/dist/authoring.js +2 -2
  8. package/dist/cli.js +17 -12
  9. package/dist/code-exec.d.ts +6 -0
  10. package/dist/code-exec.js +126 -0
  11. package/dist/decision-provider.d.ts +165 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +159 -0
  14. package/dist/decision-receipts.js +93 -0
  15. package/dist/dry-run.d.ts +45 -2
  16. package/dist/dry-run.js +157 -26
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +62 -0
  19. package/dist/graph.d.ts +169 -0
  20. package/dist/graph.js +433 -0
  21. package/dist/index.d.ts +19 -11
  22. package/dist/index.js +16 -9
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +16 -3
  25. package/dist/job.d.ts +14 -0
  26. package/dist/job.js +5 -0
  27. package/dist/long-timer.d.ts +7 -0
  28. package/dist/long-timer.js +22 -0
  29. package/dist/observer-snapshot.d.ts +3 -0
  30. package/dist/observer-snapshot.js +46 -0
  31. package/dist/predicates.d.ts +32 -0
  32. package/dist/predicates.js +61 -0
  33. package/dist/recovery/binding.d.ts +10 -0
  34. package/dist/recovery/binding.js +43 -0
  35. package/dist/recovery/call-key.d.ts +9 -0
  36. package/dist/recovery/call-key.js +17 -0
  37. package/dist/recovery/canonical-hash.d.ts +7 -0
  38. package/dist/recovery/canonical-hash.js +22 -0
  39. package/dist/recovery/driver.d.ts +235 -0
  40. package/dist/recovery/driver.js +1333 -0
  41. package/dist/recovery/errors.d.ts +31 -0
  42. package/dist/recovery/errors.js +51 -0
  43. package/dist/recovery/execution-path.d.ts +53 -0
  44. package/dist/recovery/execution-path.js +167 -0
  45. package/dist/recovery/file-store.d.ts +7 -0
  46. package/dist/recovery/file-store.js +131 -0
  47. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  48. package/dist/recovery/frozen-snapshot.js +187 -0
  49. package/dist/recovery/handoff-receipts.d.ts +7 -0
  50. package/dist/recovery/handoff-receipts.js +10 -0
  51. package/dist/recovery/index.d.ts +14 -0
  52. package/dist/recovery/index.js +13 -0
  53. package/dist/recovery/item-state.d.ts +48 -0
  54. package/dist/recovery/item-state.js +89 -0
  55. package/dist/recovery/journal.d.ts +28 -0
  56. package/dist/recovery/journal.js +139 -0
  57. package/dist/recovery/memory-store.d.ts +4 -0
  58. package/dist/recovery/memory-store.js +20 -0
  59. package/dist/recovery/store.d.ts +105 -0
  60. package/dist/recovery/store.js +6 -0
  61. package/dist/recovery/testing/conformance.d.ts +4 -0
  62. package/dist/recovery/testing/conformance.js +268 -0
  63. package/dist/recovery/testing/crash-points.d.ts +18 -0
  64. package/dist/recovery/testing/crash-points.js +43 -0
  65. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  66. package/dist/recovery/testing/crash-sweep.js +146 -0
  67. package/dist/recovery/testing/index.d.ts +3 -0
  68. package/dist/recovery/testing/index.js +4 -0
  69. package/dist/recovery/testing/preload.d.ts +1 -0
  70. package/dist/recovery/testing/preload.js +3 -0
  71. package/dist/recovery/transport-facts.d.ts +23 -0
  72. package/dist/recovery/transport-facts.js +46 -0
  73. package/dist/recovery/with-recovery.d.ts +50 -0
  74. package/dist/recovery/with-recovery.js +144 -0
  75. package/dist/submit-envelope.d.ts +9 -0
  76. package/dist/submit-envelope.js +43 -0
  77. package/dist/system-one.d.ts +40 -2
  78. package/dist/system-one.js +132 -12
  79. package/dist/testing/decision-provider.d.ts +32 -0
  80. package/dist/testing/decision-provider.js +183 -0
  81. package/dist/testing/index.d.ts +1 -0
  82. package/dist/testing/index.js +2 -0
  83. package/dist/vocabulary.d.ts +19 -3
  84. package/dist/vocabulary.js +31 -10
  85. package/dist/workflow-shape.d.ts +7 -0
  86. package/dist/workflow-shape.js +115 -69
  87. package/dist/workflow.d.ts +269 -29
  88. package/dist/workflow.js +1453 -439
  89. package/package.json +27 -4
  90. package/schema/workflow.schema.json +497 -12
  91. package/skills/author/SKILL.md +6 -1
  92. package/skills/author/references/jev-decisions.md +69 -12
  93. package/skills/author/references/language.md +28 -20
  94. package/skills/author/references/sdk-authoring.md +2 -0
@@ -0,0 +1,50 @@
1
+ import { type WorkflowDeps } from "../workflow.js";
2
+ import type { openRecovery, RecoveryEffectParams } from "./driver.js";
3
+ import { DECISION_INTERRUPTED } from "../decision-receipts.js";
4
+ export { DECISION_INTERRUPTED };
5
+ /** A recovery driver, as `openRecovery` returns it. */
6
+ export type RecoveryDriver = Awaited<ReturnType<typeof openRecovery>>;
7
+ /** The attempt of an LLM step a node runner is asked to run, as the driver admitted it. One attempt is one session:
8
+ * a runner that keeps what an attempt delivered keys it by `sessionId`. */
9
+ export type RecoveryStep = {
10
+ sessionId: string;
11
+ attempt: number;
12
+ earlierSessionIds: readonly string[];
13
+ };
14
+ /** What a host's node runner receives under the driver: the interpreter's parameters, and the attempt it runs. A
15
+ * runner marks a failure no second attempt should follow (one that ended on a bound of its own) with `final: true`
16
+ * on what it throws. */
17
+ export type RecoveryNodeParams = Parameters<NonNullable<WorkflowDeps["runNode"]>>[0] & {
18
+ step?: RecoveryStep;
19
+ };
20
+ /** The host's adapters as `withRecovery` takes them: the interpreter's, with the two that learn more under the driver. */
21
+ export type RecoveryAdapters = Omit<WorkflowDeps, "runEffect" | "runNode"> & {
22
+ runEffect?: (params: RecoveryEffectParams) => Promise<unknown>;
23
+ runNode?: (params: RecoveryNodeParams) => Promise<unknown>;
24
+ };
25
+ export type WithRecoveryOptions = {
26
+ /** The node runner keeps what each attempt delivered: asked again for a `sessionId` whose record it holds, it
27
+ * returns that record without running anything. A step found delivered is then asked of it again as the same
28
+ * attempt, and nothing is spent. Absent, such a step has spent its attempt.
29
+ * A record the interpreter refuses is therefore returned, and refused, again at every later open: the step neither
30
+ * advances nor spends, and the run fails the same way each time until the host ends it (an escalation, a new run). */
31
+ durableNodes?: boolean;
32
+ };
33
+ /** The dependencies to run a workflow with under `driver`. The interpreter's `recovery` hooks cover nodes; three
34
+ * things they have no slot for are applied to the host's adapters here:
35
+ * - `runEffect`: each effect is admitted before it is dispatched, a completed one is answered from its receipt, and
36
+ * one admitted and never completed is refused;
37
+ * - `runJudge`: each request is committed (`decision.request`) before the judge is asked, and ends with one outcome:
38
+ * answered, or failed in its own process (asked again as its next attempt). A later open that finds it asked and
39
+ * never answered (the process died, or a cancel cut the call) books it once at an unknown cost and ends the run
40
+ * escalated (`decision_interrupted`) instead of asking again. A route's answer is committed as its decision before
41
+ * any branch step runs, and a resume inside the branch follows it without asking again; every answer's spend is
42
+ * committed with the driver's state;
43
+ * - `runNode`: an LLM step's record is committed before the step runs, with two attempts, each handed to the
44
+ * runner as its `step`. A failed attempt is followed at once by the second, unless the runner marked the
45
+ * failure final; a step that spent both is refused at every later open. A process that dies inside a step spends
46
+ * no attempt. A step that delivered a submission and whose node never committed (the interpreter refused it, or
47
+ * the process died first) is answered again from the runner's own record under `durableNodes`, and has spent its
48
+ * attempt otherwise.
49
+ * The run stops through the driver's signal, together with the host's own. */
50
+ export declare function withRecovery(driver: RecoveryDriver, deps: RecoveryAdapters, options?: WithRecoveryOptions): WorkflowDeps;
@@ -0,0 +1,144 @@
1
+ import { chargedCost, DecisionProviderError } from "../decision-provider.js";
2
+ import { validateAnswers } from "../system-one.js";
3
+ import { EscalationSignal } from "../workflow.js";
4
+ import { canonicalHash } from "./canonical-hash.js";
5
+ import { DECISION_INTERRUPTED } from "../decision-receipts.js";
6
+ export { DECISION_INTERRUPTED };
7
+ /** The dependencies to run a workflow with under `driver`. The interpreter's `recovery` hooks cover nodes; three
8
+ * things they have no slot for are applied to the host's adapters here:
9
+ * - `runEffect`: each effect is admitted before it is dispatched, a completed one is answered from its receipt, and
10
+ * one admitted and never completed is refused;
11
+ * - `runJudge`: each request is committed (`decision.request`) before the judge is asked, and ends with one outcome:
12
+ * answered, or failed in its own process (asked again as its next attempt). A later open that finds it asked and
13
+ * never answered (the process died, or a cancel cut the call) books it once at an unknown cost and ends the run
14
+ * escalated (`decision_interrupted`) instead of asking again. A route's answer is committed as its decision before
15
+ * any branch step runs, and a resume inside the branch follows it without asking again; every answer's spend is
16
+ * committed with the driver's state;
17
+ * - `runNode`: an LLM step's record is committed before the step runs, with two attempts, each handed to the
18
+ * runner as its `step`. A failed attempt is followed at once by the second, unless the runner marked the
19
+ * failure final; a step that spent both is refused at every later open. A process that dies inside a step spends
20
+ * no attempt. A step that delivered a submission and whose node never committed (the interpreter refused it, or
21
+ * the process died first) is answered again from the runner's own record under `durableNodes`, and has spent its
22
+ * attempt otherwise.
23
+ * The run stops through the driver's signal, together with the host's own. */
24
+ export function withRecovery(driver, deps, options = {}) {
25
+ const { runEffect, runJudge, runNode } = deps;
26
+ return {
27
+ ...deps,
28
+ recovery: driver.recovery,
29
+ signal: deps.signal ? AbortSignal.any([deps.signal, driver.signal]) : driver.signal,
30
+ runEffect: runEffect && driver.wrapEffect(runEffect),
31
+ runJudge: runJudge && (async (params) => {
32
+ const decided = params.kind === "route" ? driver.routeDecision(params.executionPath) : undefined;
33
+ if (decided)
34
+ return decided.result;
35
+ await driver.seam();
36
+ const decisionId = params.decisionId ?? canonicalHash(["decision-request", params.executionPath, params.kind, params.questions, params.state]);
37
+ const open = driver.admitDecision(params.executionPath, { decision_id: decisionId, kind: params.kind, label: params.label, model: params.model ?? null,
38
+ request_sha256: canonicalHash({ kind: params.kind, label: params.label, state: params.state, questions: params.questions }) });
39
+ if (open) {
40
+ // An earlier process asked and its answer never reached a receipt: never asked again, booked once at an unknown
41
+ // cost, and the run goes to review. The unknown cost is counted with the outcome in one commit, the way the
42
+ // answered and failed paths commit theirs, so the run's spend reads incomplete and never omits it.
43
+ if (open.status === "requested")
44
+ driver.decisionEnded(params.executionPath, decisionId, "interrupted", null, () => driver.recordQuestionSpend(null));
45
+ await driver.flush();
46
+ throw new EscalationSignal({ kind: DECISION_INTERRUPTED, stage: "decision", executionPath: params.executionPath, label: params.label, state: driver.lastState(),
47
+ summary: `The decision "${params.label}" was asked by an earlier process and its answer never reached a receipt; it is not asked again.` });
48
+ }
49
+ try {
50
+ // The request is durable before the judge is asked.
51
+ await driver.flush();
52
+ let result;
53
+ try {
54
+ result = await runJudge(params);
55
+ }
56
+ catch (error) {
57
+ // A request sent whose outcome was lost may have been answered and billed: it is interrupted, never asked again,
58
+ // and its estimate (or an unknown cost, which makes the spend read incomplete) is booked with that outcome.
59
+ const charge = chargedCost(error);
60
+ if (error instanceof DecisionProviderError && error.code === "outcome_unknown") {
61
+ driver.decisionEnded(params.executionPath, decisionId, "interrupted", charge ?? null, () => driver.recordQuestionSpend(charge ?? null));
62
+ throw error;
63
+ }
64
+ // An answer rejected after it was paid for failed, and its cost (or an unknown one) is booked with that outcome:
65
+ // the next process asks again.
66
+ if (charge !== undefined) {
67
+ driver.decisionEnded(params.executionPath, decisionId, "failed", charge, () => driver.recordQuestionSpend(charge));
68
+ throw error;
69
+ }
70
+ // A cut call (a cancel, the run's failure) has no outcome: a later open finds it asked and unanswered. A call
71
+ // that ended on its own failed, and the next process asks again; so does one that never left (`unsent`, a host's
72
+ // refusal before it sent anything), whatever stopped the run meanwhile: nothing went out to answer.
73
+ const unsent = error instanceof DecisionProviderError && error.unsent === true;
74
+ if (unsent || (!driver.signal.aborted && !params.signal?.aborted))
75
+ driver.decisionEnded(params.executionPath, decisionId, "failed", null);
76
+ throw error;
77
+ }
78
+ const cost = typeof result.cost_usd === "number" && Number.isFinite(result.cost_usd) ? result.cost_usd : null;
79
+ // An answer the interpreter would refuse is spent at its price and is never a decision: the question is
80
+ // asked again by the next process.
81
+ try {
82
+ validateAnswers(params.questions, result.answers);
83
+ }
84
+ catch (error) {
85
+ driver.decisionEnded(params.executionPath, decisionId, "failed", cost, () => driver.recordQuestionSpend(cost));
86
+ throw error;
87
+ }
88
+ // The outcome, the spend and a route's decision are one commit.
89
+ driver.decisionEnded(params.executionPath, decisionId, "answered", cost, () => driver.recordQuestionSpend(cost, params.kind === "route"
90
+ ? { executionPath: params.executionPath, label: params.label, result: result, receipts: null } : undefined));
91
+ // The decision is durable before the interpreter acts on the answer, and a stop taken meanwhile ends the run here.
92
+ await driver.flush();
93
+ driver.checkStop();
94
+ return result;
95
+ }
96
+ finally {
97
+ driver.decisionSettled();
98
+ }
99
+ }),
100
+ runNode: runNode && (async (params) => {
101
+ const admit = () => driver.stepSession(params.executionPath, params.label, { attemptsAllowed: 2 });
102
+ let admission = admit();
103
+ for (;;) {
104
+ // An attempt that delivered a submission is asked for again only when its node never committed. A runner that
105
+ // keeps what it delivered answers it again below, as the same attempt; with any other runner it is spent.
106
+ if (admission.status === "submitted" && !options.durableNodes) {
107
+ driver.stepAttemptFailed(params.executionPath);
108
+ admission = admit();
109
+ }
110
+ // A step that failed on an item failure is refused with it, so the item it lies in ends on the same failure.
111
+ if (admission.status === "failed") {
112
+ throw admission.failure ? Object.assign(new Error(admission.failure.message), { code: admission.failure.code, itemFailure: true })
113
+ : new Error(`${params.label} failed after ${admission.attemptsAllowed} attempts`);
114
+ }
115
+ // The step's record is durable before the attempt runs. A stop or a caller's cancellation that landed
116
+ // meanwhile ends the step here: the runner is not called, and no attempt is spent. A pause waiting for an
117
+ // effect in flight holds the step here until it is taken.
118
+ await driver.flush();
119
+ await driver.seam();
120
+ if (params.signal?.aborted)
121
+ throw params.signal.reason;
122
+ try {
123
+ const submission = await runNode({ ...params, step: { sessionId: admission.sessionId, attempt: admission.attempt, earlierSessionIds: admission.earlierSessionIds } });
124
+ driver.stepSubmitted(params.executionPath);
125
+ return submission;
126
+ }
127
+ catch (error) {
128
+ // A stop the driver took, or a sibling's failure, ends the step where it is: no attempt is spent.
129
+ if (driver.signal.aborted || params.signal?.aborted)
130
+ throw error;
131
+ // A failure the runner marked final (an attempt that ended on a bound of its own) gets no second attempt: it
132
+ // would spend the same again.
133
+ const final = error?.final === true;
134
+ driver.stepAttemptFailed(params.executionPath, final, error);
135
+ if (final)
136
+ throw error;
137
+ admission = admit();
138
+ if (admission.status !== "running")
139
+ throw error;
140
+ }
141
+ }
142
+ }),
143
+ };
144
+ }
@@ -0,0 +1,9 @@
1
+ /** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
2
+ * `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
3
+ * is not an object schema), and embedding it moves the document root its local pointers resolve
4
+ * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
5
+ * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
6
+ * delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
7
+ * every harness. A keyword the host alone reads (`criteria`, any `x-` one) is left out of every schema in it, never a property or
8
+ * definition of that name; the submission is still checked against the node's schema as written. */
9
+ export declare function submitParameters(schema: unknown): Record<string, unknown>;
@@ -0,0 +1,43 @@
1
+ // Keywords that may sit on a schema but are not JSON Schema, read by the host alone: the DSL's `criteria` (System One's
2
+ // question keyword) and every `x-` annotation (AgentRun's `x-carried`, the fields of an agent's answer its next run reads
3
+ // back, which a learned workflow's output node can copy from the agent's output schema). Google's OpenAPI-subset
4
+ // `parameters` refuses a field it does not know. The model never sees them.
5
+ const hostOnlyKeyword = (key) => key === "criteria" || key.startsWith("x-");
6
+ /** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
7
+ * `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
8
+ * is not an object schema), and embedding it moves the document root its local pointers resolve
9
+ * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
10
+ * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
11
+ * delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
12
+ * every harness. A keyword the host alone reads (`criteria`, any `x-` one) is left out of every schema in it, never a property or
13
+ * definition of that name; the submission is still checked against the node's schema as written. */
14
+ export function submitParameters(schema) {
15
+ const maps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
16
+ const singles = new Set(["additionalProperties", "unevaluatedProperties", "propertyNames", "items", "additionalItems", "contains", "unevaluatedItems", "not", "if", "then", "else", "contentSchema"]);
17
+ const arrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
18
+ const relocate = (node, resourceScope = false) => {
19
+ if (!node || typeof node !== "object" || Array.isArray(node))
20
+ return structuredClone(node);
21
+ // $id establishes a separate schema resource: its local references do not move.
22
+ resourceScope ||= typeof node.$id === "string" && node.$id !== "";
23
+ const child = (value) => relocate(value, resourceScope);
24
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !hostOnlyKeyword(key)).map(([key, value]) => {
25
+ if (!resourceScope && key === "$ref" && typeof value === "string" && (value === "#" || value.startsWith("#/"))) {
26
+ return [key, `#/properties/value${value.slice(1)}`];
27
+ }
28
+ if (maps.has(key) && value && typeof value === "object" && !Array.isArray(value)) {
29
+ return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, child(value)]))];
30
+ }
31
+ if (arrays.has(key) && Array.isArray(value))
32
+ return [key, value.map(child)];
33
+ if (singles.has(key))
34
+ return [key, Array.isArray(value) ? value.map(child) : child(value)];
35
+ if (key === "dependencies" && value && typeof value === "object" && !Array.isArray(value)) {
36
+ return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, Array.isArray(value) ? structuredClone(value) : child(value)]))];
37
+ }
38
+ // Annotations and literal values are data, not schemas (including a literal $ref).
39
+ return [key, structuredClone(value)];
40
+ }));
41
+ };
42
+ return { type: "object", properties: { value: relocate(schema) }, required: ["value"], additionalProperties: false };
43
+ }
@@ -13,6 +13,18 @@ export type SystemOneQuestion = {
13
13
  type: "score";
14
14
  instructions: string;
15
15
  criteria: string[];
16
+ }
17
+ /** Locates what its instructions describe in the request's image. A host-side question: no workflow node declares one, and it needs an image sent with the request. */
18
+ | {
19
+ type: "box";
20
+ instructions: string;
21
+ };
22
+ /** A box's edges as fractions of the image's height (`top`, `bottom`) and width (`left`, `right`), from the top left corner. */
23
+ export type SystemOneBox = {
24
+ top: number;
25
+ bottom: number;
26
+ left: number;
27
+ right: number;
16
28
  };
17
29
  export type SystemOneAnswer = {
18
30
  type: "choice";
@@ -28,6 +40,14 @@ export type SystemOneAnswer = {
28
40
  legend: Record<string, string>;
29
41
  probabilities: Record<string, number>;
30
42
  confidence: number;
43
+ } | {
44
+ type: "box";
45
+ box: SystemOneBox;
46
+ confidence: number | null;
47
+ }
48
+ /** The provider declined to answer this question. It is never decoded as a value. */
49
+ | {
50
+ type: "refusal";
31
51
  };
32
52
  export type SystemOneResult = {
33
53
  answers: Record<string, SystemOneAnswer>;
@@ -45,7 +65,6 @@ export declare const SYSTEM_ONE_LIMITS: {
45
65
  readonly minScoreLevels: 2;
46
66
  readonly maxScoreLevels: 10;
47
67
  };
48
- export declare const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
49
68
  export type CompiledQuestions = Record<string, SystemOneQuestion>;
50
69
  export declare function compileQuestions(schema: Record<string, unknown>, definitions?: Record<string, unknown>): {
51
70
  ok: true;
@@ -65,7 +84,7 @@ export type AnswersSidecar = {
65
84
  export declare function answersSidecar(answers: Record<string, SystemOneAnswer>): AnswersSidecar;
66
85
  export declare function synthesizeAnswers(questions: Record<string, SystemOneQuestion>): Record<string, SystemOneAnswer>;
67
86
  export type SystemOneRetryClass = "http_429" | "http_5xx" | "connection" | "timeout";
68
- declare const responseReasons: readonly ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability", "confidence", "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"];
69
88
  export type SystemOneResponseReason = typeof responseReasons[number];
70
89
  export declare function isSystemOneResponseReason(value: unknown): value is SystemOneResponseReason;
71
90
  export declare class SystemOneError extends Error {
@@ -75,4 +94,23 @@ export declare class SystemOneError extends Error {
75
94
  constructor(message: string, retryClass: SystemOneRetryClass | null, status?: number | undefined, responseReason?: SystemOneResponseReason);
76
95
  }
77
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
+ /** What `answersToValue` throws for a refused answer: the backstop. A decision node never gets this far, since `decide()`
100
+ * escalates the run for review (DECISION_REFUSED) on a refusal first. */
101
+ export declare function refusalError(ids: string[]): SystemOneError;
102
+ /** The confidence TypeSafe documents for Jev (docs.typesafe.ai/confidence), computed from an answer's probabilities: for a
103
+ * 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
104
+ * the probability-weighted distance from the most likely level (the lowest, on a tie) over that distance for an even
105
+ * spread, floored at 0. Null when the probabilities are missing or are not a distribution over the answer's options. */
106
+ export declare function deriveConfidence(answer: unknown): number | null;
107
+ /** Where an answer's confidence came from: the provider's response, or derived from its probabilities. */
108
+ export type ConfidenceSource = "provider" | "derived";
109
+ /** The answers with every choice and score carrying a confidence: the provider's own when it gave one in [0, 1], else
110
+ * one derived from the probabilities (deriveConfidence), else 0, which validation then refuses with the probabilities
111
+ * that left nothing to derive from. `confidence_source` names each choice and score answer's source. */
112
+ export declare function completeConfidence(questions: Record<string, SystemOneQuestion>, answers: Record<string, unknown>): {
113
+ answers: Record<string, unknown>;
114
+ confidence_source: Record<string, ConfidenceSource>;
115
+ };
78
116
  export {};
@@ -1,5 +1,4 @@
1
1
  export const SYSTEM_ONE_LIMITS = { maxChoiceOptions: 240, minScoreLevels: 2, maxScoreLevels: 10 };
2
- export const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
3
2
  const CRITERIA = "criteria";
4
3
  export function compileQuestions(schema, definitions = {}) {
5
4
  const errors = [];
@@ -84,6 +83,9 @@ export function compileQuestions(schema, definitions = {}) {
84
83
  }
85
84
  export function answersToValue(answers, questions) {
86
85
  const out = Object.create(null);
86
+ const refused = refusedQuestions(answers).filter((id) => Object.hasOwn(questions, id));
87
+ if (refused.length)
88
+ throw refusalError(refused);
87
89
  for (const [id, q] of Object.entries(questions)) {
88
90
  const a = answers[id];
89
91
  if (!a)
@@ -94,6 +96,8 @@ export function answersToValue(answers, questions) {
94
96
  out[id] = a.noul >= 0.5;
95
97
  else if (q.type === "score" && a.type === "score")
96
98
  out[id] = Math.max(0, Math.round(a.score));
99
+ else if (q.type === "box" && a.type === "box")
100
+ out[id] = { ...a.box };
97
101
  else
98
102
  throw new Error(`System One answered question "${id}" with type "${a.type}", expected ${q.type}`);
99
103
  }
@@ -102,8 +106,11 @@ export function answersToValue(answers, questions) {
102
106
  export function answerConfidence(answer) {
103
107
  if (!answer || typeof answer !== "object")
104
108
  throw new SystemOneError("System One answer missing for a question that was asked", null);
109
+ if (answer.type === "refusal")
110
+ return 0;
105
111
  if (answer.type === "noul")
106
112
  return Math.abs(answer.noul - 0.5) * 2;
113
+ // A box the provider reported no confidence for counts as none: unknown is never read as sure.
107
114
  return typeof answer.confidence === "number" ? answer.confidence : 0;
108
115
  }
109
116
  export function answersSidecar(answers) {
@@ -124,6 +131,8 @@ export function synthesizeAnswers(questions) {
124
131
  const options = Object.keys(q.criteria);
125
132
  out[id] = { type: "choice", choice: options[0], probabilities: Object.fromEntries(options.map((o) => [o, 1 / options.length])), confidence: 0 };
126
133
  }
134
+ else if (q.type === "box")
135
+ out[id] = { type: "box", box: { top: 0, bottom: 1, left: 0, right: 1 }, confidence: 0 };
127
136
  else if (q.type === "noul")
128
137
  out[id] = { type: "noul", noul: 0.5 };
129
138
  else
@@ -132,7 +141,7 @@ export function synthesizeAnswers(questions) {
132
141
  return { ...out };
133
142
  }
134
143
  const responseReasons = ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability",
135
- "confidence", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range"];
144
+ "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range", "refusal"];
136
145
  export function isSystemOneResponseReason(value) {
137
146
  return typeof value === "string" && responseReasons.includes(value);
138
147
  }
@@ -150,22 +159,56 @@ export class SystemOneError extends Error {
150
159
  }
151
160
  }
152
161
  const unit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
153
- // System One reports probabilities rounded to two places, so the reported sum drifts from 1 by up to
154
- // half a step per option (3 × 0.33 = 0.99; 8 × 0.13 = 1.04). A distribution is accepted when it could
155
- // be that rounding of one summing to 1: a value on the two-place grid may be off by ±0.005 (within
156
- // [0, 1]); any other value is taken as exact. With no grid values this is |sum − 1| ≤ 1e-5, the
157
- // check for full-precision distributions. Answers are accepted as reported, never rescaled.
158
- const ROUNDING_HALF_STEP = 0.005;
159
- const onTwoPlaceGrid = (p) => Math.abs(p * 100 - Math.round(p * 100)) < 1e-9;
162
+ // System One reports probabilities rounded, Jev to two places and some OpenRouter models to four (Cloudflare's clef,
163
+ // live: 0.2967 + 0.6661 + 0.0371 = 0.9999), so the reported sum drifts from 1 by up to half a step per option
164
+ // (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
165
+ // 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
166
+ // lies on; any other value is taken as exact. With no grid values this is |sum − 1| ≤ 1e-5, the check for
167
+ // full-precision distributions. Answers are accepted as reported, never rescaled.
168
+ const roundingHalfStep = (p) => {
169
+ for (const places of [2, 3, 4]) {
170
+ const scale = 10 ** places;
171
+ if (Math.abs(p * scale - Math.round(p * scale)) < 1e-9 * scale / 100)
172
+ return 0.5 / scale;
173
+ }
174
+ return 0;
175
+ };
160
176
  function roundedFromUnitMass(probabilities) {
161
177
  let low = 0, high = 0;
162
178
  for (const p of probabilities) {
163
- const step = onTwoPlaceGrid(p) ? ROUNDING_HALF_STEP : 0;
179
+ const step = roundingHalfStep(p);
164
180
  low += Math.max(0, p - step);
165
181
  high += Math.min(1, p + step);
166
182
  }
167
183
  return low <= 1 + 1e-5 && high >= 1 - 1e-5;
168
184
  }
185
+ // A Score's weighted level drifts the same way. The unrounded probabilities lie within their rounding
186
+ // intervals and sum to 1, so Σ level·p lies between two bounds: start every level at its interval's
187
+ // low end, then give the rest of the unit mass to the lowest levels (the minimum) or the highest (the
188
+ // maximum), each up to its interval's high end. A score on a grid is itself off by up to half its step. The
189
+ // score is accepted when its interval meets [min, max]; with no grid values this is
190
+ // |score − Σ level·p| ≤ 1e-5. A score that is not a number contradicts nothing here and is left to
191
+ // the range check, as before.
192
+ function scoreContradictsDistribution(score, probabilities) {
193
+ const levels = Object.entries(probabilities).map(([level, p]) => {
194
+ const step = roundingHalfStep(p);
195
+ return { level: Number(level), low: Math.max(0, p - step), high: Math.min(1, p + step) };
196
+ }).sort((a, b) => a.level - b.level);
197
+ const floor = levels.reduce((sum, l) => sum + l.level * l.low, 0);
198
+ const spare = Math.max(0, 1 - levels.reduce((sum, l) => sum + l.low, 0));
199
+ const fill = (order) => {
200
+ let rest = spare, weighted = floor;
201
+ for (const l of order) {
202
+ const add = Math.min(rest, l.high - l.low);
203
+ weighted += l.level * add;
204
+ rest -= add;
205
+ }
206
+ return weighted;
207
+ };
208
+ const min = fill(levels), max = fill([...levels].reverse());
209
+ const step = roundingHalfStep(score);
210
+ return score - step > max + 1e-5 || score + step < min - 1e-5;
211
+ }
169
212
  export function validateAnswers(questions, answers) {
170
213
  if (!answers || typeof answers !== "object" || Array.isArray(answers))
171
214
  throw new SystemOneError("System One response carries no answers", null, undefined, "answers_shape");
@@ -176,8 +219,24 @@ export function validateAnswers(questions, answers) {
176
219
  const a = answers[id];
177
220
  if (!a || typeof a !== "object")
178
221
  throw new SystemOneError("System One returned no answer for a question", null, undefined, "answer_shape");
222
+ if (a.type === "refusal") {
223
+ if (Object.keys(a).length !== 1)
224
+ throw new SystemOneError("System One answer: a refusal carries nothing but its type", null, undefined, "answer_shape");
225
+ continue;
226
+ }
179
227
  if (a.type !== q.type)
180
228
  throw new SystemOneError("System One answer type does not match its question", null, undefined, "answer_type");
229
+ if (q.type === "box") {
230
+ const box = a.box;
231
+ if (!box || typeof box !== "object" || Array.isArray(box) || Object.keys(box).length !== 4 || !["top", "bottom", "left", "right"].every(edge => unit(box[edge])))
232
+ throw new SystemOneError("System One answer: a box's edges are not fractions in [0, 1]", null, undefined, "box_coordinates");
233
+ // An edge pair that runs backwards is a box with negative width or height: not a box.
234
+ if (box.top > box.bottom || box.left > box.right)
235
+ throw new SystemOneError("System One answer: a box's top and left edges cannot lie past its bottom and right", null, undefined, "box_coordinates");
236
+ if (!(a.confidence === null || unit(a.confidence)))
237
+ throw new SystemOneError("System One answer: confidence is not in [0, 1]", null, undefined, "confidence");
238
+ continue;
239
+ }
181
240
  if (q.type === "noul") {
182
241
  if (!unit(a.noul))
183
242
  throw new SystemOneError("System One answer: noul is not a probability", null, undefined, "noul_probability");
@@ -196,8 +255,7 @@ export function validateAnswers(questions, answers) {
196
255
  if (q.type === "score") {
197
256
  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))
198
257
  throw new SystemOneError("System One answer: legend must match the score criteria", null, undefined, "score_legend");
199
- const weighted = expectedKeys.reduce((sum, key) => sum + Number(key) * a.probabilities[key], 0);
200
- if (Math.abs(weighted - a.score) > 1e-5)
258
+ if (scoreContradictsDistribution(a.score, a.probabilities))
201
259
  throw new SystemOneError("System One answer: score must match its weighted distribution", null, undefined, "score_consistency");
202
260
  }
203
261
  if (q.type === "choice" && !(typeof a.choice === "string" && Object.prototype.hasOwnProperty.call(q.criteria, a.choice)))
@@ -206,3 +264,65 @@ export function validateAnswers(questions, answers) {
206
264
  throw new SystemOneError("System One answer: score is outside its levels", null, undefined, "score_range");
207
265
  }
208
266
  }
267
+ /** The questions whose answer is a refusal, in answer order. */
268
+ export function refusedQuestions(answers) {
269
+ return Object.entries(answers).filter(([, a]) => isRecord(a) && a.type === "refusal").map(([id]) => id);
270
+ }
271
+ /** What `answersToValue` throws for a refused answer: the backstop. A decision node never gets this far, since `decide()`
272
+ * escalates the run for review (DECISION_REFUSED) on a refusal first. */
273
+ export function refusalError(ids) {
274
+ return new SystemOneError(`System One refused ${ids.length === 1 ? "question" : "questions"} ${ids.map((id) => `"${id}"`).join(", ")}`, null, undefined, "refusal");
275
+ }
276
+ const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
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;