@parcha/agentrun-dsl 0.1.0-beta.28 → 0.1.0-beta.280

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 (79) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +22 -17
  3. package/dist/author-references.d.ts +2 -2
  4. package/dist/author-references.js +2 -2
  5. package/dist/author.d.ts +0 -2
  6. package/dist/author.js +12 -7
  7. package/dist/authoring.js +3 -2
  8. package/dist/cli.js +13 -12
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +60 -2
  14. package/dist/decision-receipts.js +13 -3
  15. package/dist/dry-run.d.ts +31 -1
  16. package/dist/dry-run.js +120 -14
  17. package/dist/edit.d.ts +158 -0
  18. package/dist/edit.js +1486 -0
  19. package/dist/evidence.d.ts +19 -0
  20. package/dist/evidence.js +63 -0
  21. package/dist/graph.d.ts +17 -0
  22. package/dist/graph.js +71 -6
  23. package/dist/index.d.ts +17 -12
  24. package/dist/index.js +16 -10
  25. package/dist/inspection.d.ts +5 -0
  26. package/dist/inspection.js +14 -1
  27. package/dist/pattern-screen.d.ts +14 -0
  28. package/dist/pattern-screen.js +451 -0
  29. package/dist/pointer-warning.d.ts +14 -0
  30. package/dist/pointer-warning.js +22 -0
  31. package/dist/predicates.d.ts +32 -2
  32. package/dist/predicates.js +66 -6
  33. package/dist/record.d.ts +4 -0
  34. package/dist/record.js +6 -0
  35. package/dist/recovery/binding.js +2 -1
  36. package/dist/recovery/call-key.d.ts +0 -4
  37. package/dist/recovery/call-key.js +0 -7
  38. package/dist/recovery/driver.d.ts +48 -20
  39. package/dist/recovery/driver.js +150 -41
  40. package/dist/recovery/frozen-snapshot.d.ts +30 -1
  41. package/dist/recovery/frozen-snapshot.js +26 -8
  42. package/dist/recovery/handoff-receipts.d.ts +0 -35
  43. package/dist/recovery/handoff-receipts.js +2 -44
  44. package/dist/recovery/index.d.ts +4 -8
  45. package/dist/recovery/index.js +4 -7
  46. package/dist/recovery/item-state.d.ts +2 -1
  47. package/dist/recovery/item-state.js +7 -13
  48. package/dist/recovery/with-recovery.d.ts +9 -3
  49. package/dist/recovery/with-recovery.js +72 -15
  50. package/dist/submit-envelope.d.ts +2 -1
  51. package/dist/submit-envelope.js +12 -5
  52. package/dist/system-one.d.ts +21 -2
  53. package/dist/system-one.js +96 -18
  54. package/dist/testing/decision-provider.d.ts +32 -0
  55. package/dist/testing/decision-provider.js +183 -0
  56. package/dist/testing/index.d.ts +1 -0
  57. package/dist/testing/index.js +2 -0
  58. package/dist/vocabulary.d.ts +16 -3
  59. package/dist/vocabulary.js +22 -7
  60. package/dist/workflow-shape.js +4 -2
  61. package/dist/workflow.d.ts +131 -15
  62. package/dist/workflow.js +807 -233
  63. package/dist/zod-json-contract.js +6 -8
  64. package/package.json +12 -4
  65. package/schema/workflow.schema.json +346 -1
  66. package/skills/author/references/jev-decisions.md +50 -5
  67. package/skills/author/references/language.md +14 -9
  68. package/dist/recovery/effect-failure.d.ts +0 -34
  69. package/dist/recovery/effect-failure.js +0 -62
  70. package/dist/recovery/handoff-block.d.ts +0 -36
  71. package/dist/recovery/handoff-block.js +0 -148
  72. package/dist/recovery/handoff-digest.d.ts +0 -58
  73. package/dist/recovery/handoff-digest.js +0 -195
  74. package/dist/recovery/handoff-files.d.ts +0 -54
  75. package/dist/recovery/handoff-files.js +0 -162
  76. package/dist/recovery/handoff-redact.d.ts +0 -12
  77. package/dist/recovery/handoff-redact.js +0 -44
  78. package/dist/recovery/handoff.d.ts +0 -44
  79. package/dist/recovery/handoff.js +0 -46
@@ -1,53 +1,11 @@
1
1
  import { canonicalHash } from "./canonical-hash.js";
2
- /** A tool value that is itself a returned failure: an error envelope (`ok: false`, `isError: true`, `outcome: "error"`) as
3
- * an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
4
- * never prose. */
5
- export function returnedFailure(value) {
6
- const failed = (parsed) => Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed) && (parsed.ok === false || parsed.isError === true || parsed.outcome === "error"));
7
- if (typeof value !== "string")
8
- return failed(value);
9
- // The envelope may be the whole text (pretty-printed or not) or one line of it with guidance appended; each
10
- // candidate is parsed structurally, never matched as prose.
11
- for (const candidate of [value.trim(), ...value.split("\n").map((line) => line.trim())]) {
12
- if (!candidate.startsWith("{"))
13
- continue;
14
- try {
15
- if (failed(JSON.parse(candidate)))
16
- return true;
17
- }
18
- catch { /* not this candidate */ }
19
- }
20
- return false;
21
- }
22
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
23
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
24
- * failure. */
25
- export function inheritableReceipts(effects) {
26
- return effects.filter((e) => e.status === "completed" && e.result && typeof e.result === "object" && e.result.intent && typeof e.result.intent.tool === "string" && !returnedFailure(e.result.value))
27
- .map((e) => {
28
- const receipt = e.result;
29
- // Keyed as a continuation's own call is: a node that reached the gateway through the fetch wrapper paid for the tool the wrapper names.
30
- const { tool, argsHash } = gatewayIntentOf(receipt.intent.tool, receipt.intent.args ?? {});
31
- return { id: e.id, name: e.name, tool, argsHash, result: receipt.value, session: e.session };
32
- });
33
- }
34
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
35
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
36
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
37
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
38
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
39
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
40
- * has none, and is matched by name and hash only. */
41
- export function inheritableUnknowns(effects) {
42
- return effects.filter((e) => e.status === "unknown").map((e) => ({ id: e.id, name: e.name, argsHash: e.argsHash, session: e.session,
43
- ...(e.intent ? { intent: { tool: e.intent.tool, argsHash: e.intent.argsHash } } : {}) }));
44
- }
2
+ import { isRecord } from "../record.js";
45
3
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
46
4
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
47
5
  * The same key is computed for an effect from its receipt's intent. */
48
6
  export function gatewayIntentOf(name, args) {
49
7
  const a = args;
50
- if (name === "fetch" && a && typeof a === "object" && typeof a.tool === "string" && a.args && typeof a.args === "object" && !Array.isArray(a.args))
8
+ if (name === "fetch" && a && typeof a === "object" && typeof a.tool === "string" && isRecord(a.args))
51
9
  return { tool: a.tool, argsHash: canonicalHash(a.args) };
52
10
  return { tool: name, argsHash: canonicalHash(args ?? {}) };
53
11
  }
@@ -1,18 +1,14 @@
1
1
  export type { RecoveryBinding, RecoveryEffect, RecoveryIntent, RecoveryItem, RecoveryJournal, RecoveryNote, RecoveryParts, RecoveryStore } from "./store.js";
2
2
  export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles, type RecoveryEffectParams, type RecoveryFiles, type RecoveryOptions, type RecoveryStop } from "./driver.js";
3
- export { withRecovery, type RecoveryAdapters, type RecoveryDriver, type RecoveryNodeParams, type RecoveryStep, type WithRecoveryOptions } from "./with-recovery.js";
3
+ export { DECISION_REFUSED } from "../decision-receipts.js";
4
+ export { withRecovery, DECISION_INTERRUPTED, type RecoveryAdapters, type RecoveryDriver, type RecoveryNodeParams, type RecoveryStep, type WithRecoveryOptions } from "./with-recovery.js";
4
5
  export { memoryStore } from "./memory-store.js";
5
6
  export { fileStore } from "./file-store.js";
6
7
  export { openJournal, type JournalBackend, type JournalRecord } from "./journal.js";
7
8
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
8
9
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
9
10
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
10
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
11
- export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
11
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
12
+ export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, frozenStepId, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type DecisionRequest, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
12
13
  export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
13
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
14
14
  export { effectRetryClass, transportFactOf, type TransportFact } from "./transport-facts.js";
15
- export { buildHandoff, handoffFirstTurn, type Handoff, type HandoffOptions } from "./handoff.js";
16
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
17
- export { inputProvenance, judgedRecords, type InputProvenance } from "./handoff-files.js";
18
- export { type InheritedSession, type InheritedEffect, type TranscriptMessage } from "./handoff-digest.js";
@@ -1,16 +1,13 @@
1
1
  export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles } from "./driver.js";
2
- export { withRecovery } from "./with-recovery.js";
2
+ export { DECISION_REFUSED } from "../decision-receipts.js";
3
+ export { withRecovery, DECISION_INTERRUPTED } from "./with-recovery.js";
3
4
  export { memoryStore } from "./memory-store.js";
4
5
  export { fileStore } from "./file-store.js";
5
6
  export { openJournal } from "./journal.js";
6
7
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
7
8
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
8
9
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
9
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
10
- export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
10
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
11
+ export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, frozenStepId, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
11
12
  export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
12
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
13
13
  export { effectRetryClass, transportFactOf } from "./transport-facts.js";
14
- export { buildHandoff, handoffFirstTurn } from "./handoff.js";
15
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure } from "./handoff-receipts.js";
16
- export { inputProvenance, judgedRecords } from "./handoff-files.js";
@@ -11,7 +11,8 @@ export type StateDelta = {
11
11
  export type Sha256 = (text: string) => string;
12
12
  /** The JSON a state's digest is taken over: every object's keys sorted. */
13
13
  export declare function canonicalJson(value: unknown): string;
14
- /** `state` against `base`, as a map item keeps it. */
14
+ /** `state` against `base`, as a map item keeps it. Each object is built from its entries (Object.fromEntries), so every
15
+ * key is an own one, `__proto__` too: an assignment of that key would set the object's prototype and drop the key. */
15
16
  export declare function stateDelta(base: State, state: State, sha256: string): StateDelta;
16
17
  /** The state a delta was taken from, in its own key order: the base's keys first (a map item starts from a copy of its
17
18
  * base), then the keys it added. */
@@ -6,26 +6,20 @@ export function canonicalJson(value) {
6
6
  ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
7
7
  }
8
8
  const sameValue = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
9
- /** `state` against `base`, as a map item keeps it. */
9
+ /** `state` against `base`, as a map item keeps it. Each object is built from its entries (Object.fromEntries), so every
10
+ * key is an own one, `__proto__` too: an assignment of that key would set the object's prototype and drop the key. */
10
11
  export function stateDelta(base, state, sha256) {
11
- const set = {};
12
- for (const [key, value] of Object.entries(state))
13
- if (!Object.hasOwn(base, key) || !sameValue(base[key], value))
14
- set[key] = value;
12
+ const set = Object.fromEntries(Object.entries(state).filter(([key, value]) => !Object.hasOwn(base, key) || !sameValue(base[key], value)));
15
13
  return { set, unset: Object.keys(base).filter((key) => !Object.hasOwn(state, key)), sha256 };
16
14
  }
17
15
  /** The state a delta was taken from, in its own key order: the base's keys first (a map item starts from a copy of its
18
16
  * base), then the keys it added. */
19
17
  export function applyStateDelta(base, delta) {
20
18
  const unset = new Set(delta.unset);
21
- const state = {};
22
- for (const key of Object.keys(base))
23
- if (!unset.has(key))
24
- state[key] = Object.hasOwn(delta.set, key) ? delta.set[key] : base[key];
25
- for (const [key, value] of Object.entries(delta.set))
26
- if (!Object.hasOwn(base, key))
27
- state[key] = value;
28
- return state;
19
+ return Object.fromEntries([
20
+ ...Object.keys(base).filter((key) => !unset.has(key)).map((key) => [key, Object.hasOwn(delta.set, key) ? delta.set[key] : base[key]]),
21
+ ...Object.entries(delta.set).filter(([key]) => !Object.hasOwn(base, key)),
22
+ ]);
29
23
  }
30
24
  const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
31
25
  /** A map item's state at `path`, rebuilt as the driver rebuilds it: the `agentrun.states` value its `base` names, with
@@ -1,5 +1,7 @@
1
- import type { WorkflowDeps } from "../workflow.js";
1
+ import { type WorkflowDeps } from "../workflow.js";
2
2
  import type { openRecovery, RecoveryEffectParams } from "./driver.js";
3
+ import { DECISION_INTERRUPTED } from "../decision-receipts.js";
4
+ export { DECISION_INTERRUPTED };
3
5
  /** A recovery driver, as `openRecovery` returns it. */
4
6
  export type RecoveryDriver = Awaited<ReturnType<typeof openRecovery>>;
5
7
  /** The attempt of an LLM step a node runner is asked to run, as the driver admitted it. One attempt is one session:
@@ -32,8 +34,12 @@ export type WithRecoveryOptions = {
32
34
  * things they have no slot for are applied to the host's adapters here:
33
35
  * - `runEffect`: each effect is admitted before it is dispatched, a completed one is answered from its receipt, and
34
36
  * one admitted and never completed is refused;
35
- * - `runJudge`: a route's answer is committed as its decision before any branch step runs, and a resume inside the
36
- * branch follows it without asking again; every answer's spend is committed with the driver's state;
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;
37
43
  * - `runNode`: an LLM step's record is committed before the step runs, with two attempts, each handed to the
38
44
  * runner as its `step`. A failed attempt is followed at once by the second, unless the runner marked the
39
45
  * failure final; a step that spent both is refused at every later open. A process that dies inside a step spends
@@ -1,10 +1,19 @@
1
+ import { chargedCost, DecisionProviderError } from "../decision-provider.js";
1
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 };
2
7
  /** The dependencies to run a workflow with under `driver`. The interpreter's `recovery` hooks cover nodes; three
3
8
  * things they have no slot for are applied to the host's adapters here:
4
9
  * - `runEffect`: each effect is admitted before it is dispatched, a completed one is answered from its receipt, and
5
10
  * one admitted and never completed is refused;
6
- * - `runJudge`: a route's answer is committed as its decision before any branch step runs, and a resume inside the
7
- * branch follows it without asking again; every answer's spend is committed with the driver's state;
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;
8
17
  * - `runNode`: an LLM step's record is committed before the step runs, with two attempts, each handed to the
9
18
  * runner as its `step`. A failed attempt is followed at once by the second, unless the runner marked the
10
19
  * failure final; a step that spent both is refused at every later open. A process that dies inside a step spends
@@ -23,22 +32,70 @@ export function withRecovery(driver, deps, options = {}) {
23
32
  const decided = params.kind === "route" ? driver.routeDecision(params.executionPath) : undefined;
24
33
  if (decided)
25
34
  return decided.result;
26
- const result = await runJudge(params);
27
- const cost = typeof result.cost_usd === "number" && Number.isFinite(result.cost_usd) ? result.cost_usd : null;
28
- // An answer the interpreter would refuse is spent at its price and is never a decision: the question is
29
- // asked again by the next process.
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
+ }
30
49
  try {
31
- validateAnswers(params.questions, result.answers);
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;
32
95
  }
33
- catch (error) {
34
- driver.recordQuestionSpend(cost);
35
- throw error;
96
+ finally {
97
+ driver.decisionSettled();
36
98
  }
37
- driver.recordQuestionSpend(cost, params.kind === "route" ? { executionPath: params.executionPath, label: params.label, result: result, receipts: null } : undefined);
38
- // The decision is durable before the interpreter acts on the answer, and a stop taken meanwhile ends the run here.
39
- await driver.flush();
40
- driver.checkStop();
41
- return result;
42
99
  }),
43
100
  runNode: runNode && (async (params) => {
44
101
  const admit = () => driver.stepSession(params.executionPath, params.label, { attemptsAllowed: 2 });
@@ -4,5 +4,6 @@
4
4
  * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
5
5
  * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
6
6
  * delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
7
- * every harness. */
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. */
8
9
  export declare function submitParameters(schema: unknown): Record<string, unknown>;
@@ -1,32 +1,39 @@
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-");
1
7
  /** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
2
8
  * `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
3
9
  * is not an object schema), and embedding it moves the document root its local pointers resolve
4
10
  * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
5
11
  * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
6
12
  * delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
7
- * every harness. */
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. */
8
15
  export function submitParameters(schema) {
9
16
  const maps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
10
17
  const singles = new Set(["additionalProperties", "unevaluatedProperties", "propertyNames", "items", "additionalItems", "contains", "unevaluatedItems", "not", "if", "then", "else", "contentSchema"]);
11
18
  const arrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
12
19
  const relocate = (node, resourceScope = false) => {
13
- if (!node || typeof node !== "object" || Array.isArray(node))
20
+ if (!isRecord(node))
14
21
  return structuredClone(node);
15
22
  // $id establishes a separate schema resource: its local references do not move.
16
23
  resourceScope ||= typeof node.$id === "string" && node.$id !== "";
17
24
  const child = (value) => relocate(value, resourceScope);
18
- return Object.fromEntries(Object.entries(node).map(([key, value]) => {
25
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !hostOnlyKeyword(key)).map(([key, value]) => {
19
26
  if (!resourceScope && key === "$ref" && typeof value === "string" && (value === "#" || value.startsWith("#/"))) {
20
27
  return [key, `#/properties/value${value.slice(1)}`];
21
28
  }
22
- if (maps.has(key) && value && typeof value === "object" && !Array.isArray(value)) {
29
+ if (maps.has(key) && isRecord(value)) {
23
30
  return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, child(value)]))];
24
31
  }
25
32
  if (arrays.has(key) && Array.isArray(value))
26
33
  return [key, value.map(child)];
27
34
  if (singles.has(key))
28
35
  return [key, Array.isArray(value) ? value.map(child) : child(value)];
29
- if (key === "dependencies" && value && typeof value === "object" && !Array.isArray(value)) {
36
+ if (key === "dependencies" && isRecord(value)) {
30
37
  return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, Array.isArray(value) ? structuredClone(value) : child(value)]))];
31
38
  }
32
39
  // Annotations and literal values are data, not schemas (including a literal $ref).
@@ -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
+ }