@parcha/agentrun-dsl 0.1.0-beta.1 → 0.1.0-beta.100

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 (109) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +173 -20
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +97 -0
  6. package/dist/author.js +329 -0
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +6 -0
  10. package/dist/code-exec.js +126 -0
  11. package/dist/decision-provider.d.ts +166 -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 +159 -27
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +169 -0
  20. package/dist/graph.js +433 -0
  21. package/dist/index.d.ts +20 -6
  22. package/dist/index.js +19 -4
  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/pattern-screen.d.ts +14 -0
  32. package/dist/pattern-screen.js +451 -0
  33. package/dist/predicates.d.ts +33 -0
  34. package/dist/predicates.js +81 -5
  35. package/dist/record.d.ts +4 -0
  36. package/dist/record.js +6 -0
  37. package/dist/recovery/binding.d.ts +10 -0
  38. package/dist/recovery/binding.js +44 -0
  39. package/dist/recovery/call-key.d.ts +9 -0
  40. package/dist/recovery/call-key.js +17 -0
  41. package/dist/recovery/canonical-hash.d.ts +7 -0
  42. package/dist/recovery/canonical-hash.js +22 -0
  43. package/dist/recovery/driver.d.ts +241 -0
  44. package/dist/recovery/driver.js +1333 -0
  45. package/dist/recovery/errors.d.ts +31 -0
  46. package/dist/recovery/errors.js +51 -0
  47. package/dist/recovery/execution-path.d.ts +53 -0
  48. package/dist/recovery/execution-path.js +167 -0
  49. package/dist/recovery/file-store.d.ts +7 -0
  50. package/dist/recovery/file-store.js +131 -0
  51. package/dist/recovery/frozen-snapshot.d.ts +274 -0
  52. package/dist/recovery/frozen-snapshot.js +187 -0
  53. package/dist/recovery/handoff-receipts.d.ts +7 -0
  54. package/dist/recovery/handoff-receipts.js +11 -0
  55. package/dist/recovery/index.d.ts +14 -0
  56. package/dist/recovery/index.js +13 -0
  57. package/dist/recovery/item-state.d.ts +48 -0
  58. package/dist/recovery/item-state.js +89 -0
  59. package/dist/recovery/journal.d.ts +28 -0
  60. package/dist/recovery/journal.js +139 -0
  61. package/dist/recovery/memory-store.d.ts +4 -0
  62. package/dist/recovery/memory-store.js +20 -0
  63. package/dist/recovery/store.d.ts +105 -0
  64. package/dist/recovery/store.js +6 -0
  65. package/dist/recovery/testing/conformance.d.ts +4 -0
  66. package/dist/recovery/testing/conformance.js +268 -0
  67. package/dist/recovery/testing/crash-points.d.ts +18 -0
  68. package/dist/recovery/testing/crash-points.js +43 -0
  69. package/dist/recovery/testing/crash-sweep.d.ts +65 -0
  70. package/dist/recovery/testing/crash-sweep.js +146 -0
  71. package/dist/recovery/testing/index.d.ts +3 -0
  72. package/dist/recovery/testing/index.js +4 -0
  73. package/dist/recovery/testing/preload.d.ts +1 -0
  74. package/dist/recovery/testing/preload.js +3 -0
  75. package/dist/recovery/transport-facts.d.ts +23 -0
  76. package/dist/recovery/transport-facts.js +46 -0
  77. package/dist/recovery/with-recovery.d.ts +50 -0
  78. package/dist/recovery/with-recovery.js +144 -0
  79. package/dist/submit-envelope.d.ts +9 -0
  80. package/dist/submit-envelope.js +44 -0
  81. package/dist/system-one.d.ts +37 -2
  82. package/dist/system-one.js +146 -11
  83. package/dist/testing/decision-provider.d.ts +32 -0
  84. package/dist/testing/decision-provider.js +183 -0
  85. package/dist/testing/index.d.ts +1 -0
  86. package/dist/testing/index.js +2 -0
  87. package/dist/vocabulary.d.ts +50 -0
  88. package/dist/vocabulary.js +84 -0
  89. package/dist/workflow-shape.d.ts +7 -0
  90. package/dist/workflow-shape.js +119 -69
  91. package/dist/workflow.d.ts +356 -29
  92. package/dist/workflow.js +1777 -487
  93. package/dist/zod-json-contract.js +6 -8
  94. package/package.json +29 -5
  95. package/schema/workflow.schema.json +599 -12
  96. package/skills/author/SKILL.md +125 -0
  97. package/skills/author/examples/evidence-gate.input.json +6 -0
  98. package/skills/author/examples/evidence-gate.json +125 -0
  99. package/skills/author/examples/read-file.input.json +1 -0
  100. package/skills/author/examples/read-file.json +44 -0
  101. package/skills/author/examples/read-source-decision.input.json +4 -0
  102. package/skills/author/examples/read-source-decision.json +37 -0
  103. package/skills/author/examples/release-note.txt +10 -0
  104. package/skills/author/examples/review-release-notes.input.json +6 -0
  105. package/skills/author/examples/review-release-notes.json +123 -0
  106. package/skills/author/references/jev-decisions.md +170 -0
  107. package/skills/author/references/language.md +123 -0
  108. package/skills/author/references/sdk-authoring.md +11 -0
  109. package/skills/author/references/workflow-format.md +137 -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,44 @@
1
+ import { isRecord } from "./record.js";
2
+ // Keywords that may sit on a schema but are not JSON Schema, read by the host alone: the DSL's `criteria` (System One's
3
+ // question keyword) and every `x-` annotation (AgentRun's `x-carried`, the fields of an agent's answer its next run reads
4
+ // back, which a learned workflow's output node can copy from the agent's output schema). Google's OpenAPI-subset
5
+ // `parameters` refuses a field it does not know. The model never sees them.
6
+ const hostOnlyKeyword = (key) => key === "criteria" || key.startsWith("x-");
7
+ /** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
8
+ * `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
9
+ * is not an object schema), and embedding it moves the document root its local pointers resolve
10
+ * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
11
+ * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
12
+ * delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
13
+ * every harness. A keyword the host alone reads (`criteria`, any `x-` one) is left out of every schema in it, never a property or
14
+ * definition of that name; the submission is still checked against the node's schema as written. */
15
+ export function submitParameters(schema) {
16
+ const maps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
17
+ const singles = new Set(["additionalProperties", "unevaluatedProperties", "propertyNames", "items", "additionalItems", "contains", "unevaluatedItems", "not", "if", "then", "else", "contentSchema"]);
18
+ const arrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
19
+ const relocate = (node, resourceScope = false) => {
20
+ if (!isRecord(node))
21
+ return structuredClone(node);
22
+ // $id establishes a separate schema resource: its local references do not move.
23
+ resourceScope ||= typeof node.$id === "string" && node.$id !== "";
24
+ const child = (value) => relocate(value, resourceScope);
25
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !hostOnlyKeyword(key)).map(([key, value]) => {
26
+ if (!resourceScope && key === "$ref" && typeof value === "string" && (value === "#" || value.startsWith("#/"))) {
27
+ return [key, `#/properties/value${value.slice(1)}`];
28
+ }
29
+ if (maps.has(key) && isRecord(value)) {
30
+ return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, child(value)]))];
31
+ }
32
+ if (arrays.has(key) && Array.isArray(value))
33
+ return [key, value.map(child)];
34
+ if (singles.has(key))
35
+ return [key, Array.isArray(value) ? value.map(child) : child(value)];
36
+ if (key === "dependencies" && isRecord(value)) {
37
+ return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, Array.isArray(value) ? structuredClone(value) : child(value)]))];
38
+ }
39
+ // Annotations and literal values are data, not schemas (including a literal $ref).
40
+ return [key, structuredClone(value)];
41
+ }));
42
+ };
43
+ return { type: "object", properties: { value: relocate(schema) }, required: ["value"], additionalProperties: false };
44
+ }
@@ -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,20 @@ 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
+ /** 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
+ };
78
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)
@@ -94,6 +97,8 @@ export function answersToValue(answers, questions) {
94
97
  out[id] = a.noul >= 0.5;
95
98
  else if (q.type === "score" && a.type === "score")
96
99
  out[id] = Math.max(0, Math.round(a.score));
100
+ else if (q.type === "box" && a.type === "box")
101
+ out[id] = { ...a.box };
97
102
  else
98
103
  throw new Error(`System One answered question "${id}" with type "${a.type}", expected ${q.type}`);
99
104
  }
@@ -102,8 +107,11 @@ export function answersToValue(answers, questions) {
102
107
  export function answerConfidence(answer) {
103
108
  if (!answer || typeof answer !== "object")
104
109
  throw new SystemOneError("System One answer missing for a question that was asked", null);
110
+ if (answer.type === "refusal")
111
+ return 0;
105
112
  if (answer.type === "noul")
106
113
  return Math.abs(answer.noul - 0.5) * 2;
114
+ // A box the provider reported no confidence for counts as none: unknown is never read as sure.
107
115
  return typeof answer.confidence === "number" ? answer.confidence : 0;
108
116
  }
109
117
  export function answersSidecar(answers) {
@@ -124,6 +132,8 @@ export function synthesizeAnswers(questions) {
124
132
  const options = Object.keys(q.criteria);
125
133
  out[id] = { type: "choice", choice: options[0], probabilities: Object.fromEntries(options.map((o) => [o, 1 / options.length])), confidence: 0 };
126
134
  }
135
+ else if (q.type === "box")
136
+ out[id] = { type: "box", box: { top: 0, bottom: 1, left: 0, right: 1 }, confidence: 0 };
127
137
  else if (q.type === "noul")
128
138
  out[id] = { type: "noul", noul: 0.5 };
129
139
  else
@@ -132,7 +142,7 @@ export function synthesizeAnswers(questions) {
132
142
  return { ...out };
133
143
  }
134
144
  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"];
145
+ "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range", "refusal"];
136
146
  export function isSystemOneResponseReason(value) {
137
147
  return typeof value === "string" && responseReasons.includes(value);
138
148
  }
@@ -150,8 +160,58 @@ export class SystemOneError extends Error {
150
160
  }
151
161
  }
152
162
  const unit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
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
+ };
177
+ function roundedFromUnitMass(probabilities) {
178
+ let low = 0, high = 0;
179
+ for (const p of probabilities) {
180
+ const step = roundingHalfStep(p);
181
+ low += Math.max(0, p - step);
182
+ high += Math.min(1, p + step);
183
+ }
184
+ return low <= 1 + 1e-5 && high >= 1 - 1e-5;
185
+ }
186
+ // A Score's weighted level drifts the same way. The unrounded probabilities lie within their rounding
187
+ // intervals and sum to 1, so Σ level·p lies between two bounds: start every level at its interval's
188
+ // low end, then give the rest of the unit mass to the lowest levels (the minimum) or the highest (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
190
+ // score is accepted when its interval meets [min, max]; with no grid values this is
191
+ // |score − Σ level·p| ≤ 1e-5. A score that is not a number contradicts nothing here and is left to
192
+ // the range check, as before.
193
+ function scoreContradictsDistribution(score, probabilities) {
194
+ const levels = Object.entries(probabilities).map(([level, p]) => {
195
+ const step = roundingHalfStep(p);
196
+ return { level: Number(level), low: Math.max(0, p - step), high: Math.min(1, p + step) };
197
+ }).sort((a, b) => a.level - b.level);
198
+ const floor = levels.reduce((sum, l) => sum + l.level * l.low, 0);
199
+ const spare = Math.max(0, 1 - levels.reduce((sum, l) => sum + l.low, 0));
200
+ const fill = (order) => {
201
+ let rest = spare, weighted = floor;
202
+ for (const l of order) {
203
+ const add = Math.min(rest, l.high - l.low);
204
+ weighted += l.level * add;
205
+ rest -= add;
206
+ }
207
+ return weighted;
208
+ };
209
+ const min = fill(levels), max = fill([...levels].reverse());
210
+ const step = roundingHalfStep(score);
211
+ return score - step > max + 1e-5 || score + step < min - 1e-5;
212
+ }
153
213
  export function validateAnswers(questions, answers) {
154
- if (!answers || typeof answers !== "object" || Array.isArray(answers))
214
+ if (!isRecord(answers))
155
215
  throw new SystemOneError("System One response carries no answers", null, undefined, "answers_shape");
156
216
  const answerKeys = Object.keys(answers);
157
217
  if (answerKeys.length !== Object.keys(questions).length || answerKeys.some(id => !Object.hasOwn(questions, id)))
@@ -160,8 +220,24 @@ export function validateAnswers(questions, answers) {
160
220
  const a = answers[id];
161
221
  if (!a || typeof a !== "object")
162
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
+ }
163
228
  if (a.type !== q.type)
164
229
  throw new SystemOneError("System One answer type does not match its question", null, undefined, "answer_type");
230
+ if (q.type === "box") {
231
+ const box = a.box;
232
+ if (!box || typeof box !== "object" || Array.isArray(box) || Object.keys(box).length !== 4 || !["top", "bottom", "left", "right"].every(edge => unit(box[edge])))
233
+ throw new SystemOneError("System One answer: a box's edges are not fractions in [0, 1]", null, undefined, "box_coordinates");
234
+ // An edge pair that runs backwards is a box with negative width or height: not a box.
235
+ if (box.top > box.bottom || box.left > box.right)
236
+ throw new SystemOneError("System One answer: a box's top and left edges cannot lie past its bottom and right", null, undefined, "box_coordinates");
237
+ if (!(a.confidence === null || unit(a.confidence)))
238
+ throw new SystemOneError("System One answer: confidence is not in [0, 1]", null, undefined, "confidence");
239
+ continue;
240
+ }
165
241
  if (q.type === "noul") {
166
242
  if (!unit(a.noul))
167
243
  throw new SystemOneError("System One answer: noul is not a probability", null, undefined, "noul_probability");
@@ -175,14 +251,12 @@ export function validateAnswers(questions, answers) {
175
251
  const probabilityKeys = Object.keys(a.probabilities);
176
252
  if (Array.isArray(a.probabilities) || probabilityKeys.length !== expectedKeys.length || expectedKeys.some(key => !Object.hasOwn(a.probabilities, key)))
177
253
  throw new SystemOneError("System One answer: probabilities must contain exactly the declared options", null, undefined, "probability_keys");
178
- const mass = Object.values(a.probabilities).reduce((sum, p) => sum + p, 0);
179
- if (Math.abs(mass - 1) > 1e-5)
254
+ if (!roundedFromUnitMass(Object.values(a.probabilities)))
180
255
  throw new SystemOneError("System One answer: probabilities must sum to 1", null, undefined, "probability_mass");
181
256
  if (q.type === "score") {
182
- 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))
183
258
  throw new SystemOneError("System One answer: legend must match the score criteria", null, undefined, "score_legend");
184
- const weighted = expectedKeys.reduce((sum, key) => sum + Number(key) * a.probabilities[key], 0);
185
- if (Math.abs(weighted - a.score) > 1e-5)
259
+ if (scoreContradictsDistribution(a.score, a.probabilities))
186
260
  throw new SystemOneError("System One answer: score must match its weighted distribution", null, undefined, "score_consistency");
187
261
  }
188
262
  if (q.type === "choice" && !(typeof a.choice === "string" && Object.prototype.hasOwnProperty.call(q.criteria, a.choice)))
@@ -191,3 +265,64 @@ export function validateAnswers(questions, answers) {
191
265
  throw new SystemOneError("System One answer: score is outside its levels", null, undefined, "score_range");
192
266
  }
193
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;