@parcha/agentrun-dsl 0.1.0-beta.17 → 0.1.0-beta.171

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +153 -16
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +4 -3
  6. package/dist/author.js +20 -11
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +64 -3
  14. package/dist/decision-receipts.js +50 -8
  15. package/dist/dry-run.d.ts +35 -1
  16. package/dist/dry-run.js +131 -25
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +107 -5
  20. package/dist/graph.js +284 -9
  21. package/dist/index.d.ts +17 -12
  22. package/dist/index.js +16 -10
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +14 -1
  25. package/dist/pattern-screen.d.ts +14 -0
  26. package/dist/pattern-screen.js +451 -0
  27. package/dist/predicates.d.ts +29 -0
  28. package/dist/predicates.js +62 -3
  29. package/dist/record.d.ts +4 -0
  30. package/dist/record.js +6 -0
  31. package/dist/recovery/binding.js +2 -1
  32. package/dist/recovery/call-key.d.ts +0 -4
  33. package/dist/recovery/call-key.js +0 -7
  34. package/dist/recovery/driver.d.ts +59 -24
  35. package/dist/recovery/driver.js +251 -73
  36. package/dist/recovery/frozen-snapshot.d.ts +54 -4
  37. package/dist/recovery/frozen-snapshot.js +44 -14
  38. package/dist/recovery/handoff-receipts.d.ts +0 -35
  39. package/dist/recovery/handoff-receipts.js +2 -44
  40. package/dist/recovery/index.d.ts +4 -8
  41. package/dist/recovery/index.js +4 -7
  42. package/dist/recovery/with-recovery.d.ts +9 -3
  43. package/dist/recovery/with-recovery.js +78 -18
  44. package/dist/submit-envelope.d.ts +9 -0
  45. package/dist/submit-envelope.js +44 -0
  46. package/dist/system-one.d.ts +21 -2
  47. package/dist/system-one.js +96 -18
  48. package/dist/testing/decision-provider.d.ts +32 -0
  49. package/dist/testing/decision-provider.js +183 -0
  50. package/dist/testing/index.d.ts +1 -0
  51. package/dist/testing/index.js +2 -0
  52. package/dist/vocabulary.d.ts +11 -3
  53. package/dist/vocabulary.js +19 -9
  54. package/dist/workflow-shape.d.ts +7 -0
  55. package/dist/workflow-shape.js +116 -70
  56. package/dist/workflow.d.ts +171 -19
  57. package/dist/workflow.js +1063 -399
  58. package/dist/zod-json-contract.js +6 -8
  59. package/package.json +12 -4
  60. package/schema/workflow.schema.json +366 -1
  61. package/skills/author/SKILL.md +6 -1
  62. package/skills/author/references/jev-decisions.md +50 -5
  63. package/skills/author/references/language.md +19 -14
  64. package/dist/recovery/effect-failure.d.ts +0 -34
  65. package/dist/recovery/effect-failure.js +0 -62
  66. package/dist/recovery/handoff-block.d.ts +0 -36
  67. package/dist/recovery/handoff-block.js +0 -148
  68. package/dist/recovery/handoff-digest.d.ts +0 -58
  69. package/dist/recovery/handoff-digest.js +0 -195
  70. package/dist/recovery/handoff-files.d.ts +0 -54
  71. package/dist/recovery/handoff-files.js +0 -162
  72. package/dist/recovery/handoff-redact.d.ts +0 -12
  73. package/dist/recovery/handoff-redact.js +0 -44
  74. package/dist/recovery/handoff.d.ts +0 -44
  75. package/dist/recovery/handoff.js +0 -46
@@ -1,4 +1,6 @@
1
+ import { RecoveryError } from "./errors.js";
1
2
  import { type PartialSlot, type Sha256, type StateDelta } from "./item-state.js";
3
+ export declare const failure: (code: string, message: string) => RecoveryError;
2
4
  export declare const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
3
5
  /** The keyed layout: what lies in a map item is kept in that item's record beside the state, and a state the driver
4
6
  * references is kept once by its digest, so no record rewritten at a commit grows with a map's items. */
@@ -21,7 +23,10 @@ export type ItemRecord = {
21
23
  base: string;
22
24
  /** The journal revision of the commit that wrote this value. */
23
25
  revision: number;
26
+ /** `failed`: the item ended on its failure, which `outcome` holds; its map collects its items' failures. */
24
27
  status: "running" | "committed" | "failed";
28
+ /** Present exactly when `status` is `failed`. */
29
+ outcome?: ItemOutcome;
25
30
  frame: {
26
31
  done: string[];
27
32
  states: Record<string, StateDelta>;
@@ -30,6 +35,7 @@ export type ItemRecord = {
30
35
  routes: PathFrame["routes"];
31
36
  inputs: PathFrame["inputs"];
32
37
  steps: PathFrame["steps"];
38
+ decisions?: PathFrame["decisions"];
33
39
  };
34
40
  effects: string[];
35
41
  clocks: Record<string, number>;
@@ -52,8 +58,6 @@ export type FrozenSnapshotV4 = Omit<FrozenSnapshot, "schema" | "pin"> & {
52
58
  };
53
59
  maps: Record<string, MapEntry>;
54
60
  };
55
- /** Two values a state holds under one key are the same value. A key an item copied from its base holds the base's own
56
- * object, or one with the same JSON. */
57
61
  /** A map item's state at `path`, rebuilt as the driver rebuilds it (`./item-state.ts`, which imports nothing): the
58
62
  * `agentrun.states` value its `base` names, with the item's `set` and `unset` for that path applied, checked against
59
63
  * that path's `sha256`. `item` is an `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256. When
@@ -90,15 +94,37 @@ export type QuestionReceipts = {
90
94
  * is set in the commit that decides and cleared by the save after the host has written what it keeps of the
91
95
  * answer: a resume that finds it set writes them, so a crash between the two never leaves the spend without
92
96
  * its receipts. A host that keeps nothing commits null. */
97
+ /** `choice` is null and `refused` true for a refused answer, which took the route's unsure branch. */
93
98
  export type RouteDecision = {
94
99
  label: string;
95
100
  branch: string;
96
- choice: string;
101
+ choice: string | null;
97
102
  unsure: boolean;
103
+ refused?: true;
98
104
  request_sha256: string | null;
99
105
  result: Record<string, unknown>;
100
106
  receipts: QuestionReceipts | null;
101
107
  };
108
+ /** A decision's request to the host's judge, as the kernel books a paid request: written and committed before the judge
109
+ * is asked (`requested`), with one outcome after. `answered` and `failed` are written by the process that asked;
110
+ * `interrupted` by a later process that found it still `requested`: the answer, if the provider gave one, was lost with
111
+ * the process, so the decision is never asked again and its cost is unknown (null, never 0). A `failed` request is
112
+ * asked again as its next attempt. */
113
+ export type DecisionRequest = {
114
+ record: "decision.request";
115
+ decision_id: string;
116
+ kind: string;
117
+ label: string;
118
+ /** The model the request named, when it named one. */
119
+ model: string | null;
120
+ /** The digest of what the judge was sent: the kind, the label, the state and the questions. */
121
+ request_sha256: string;
122
+ attempt: number;
123
+ status: "requested" | "answered" | "failed" | "interrupted";
124
+ /** The outcome's spend: absent while requested, null when unknown. */
125
+ cost_usd?: number | null;
126
+ };
127
+ export declare const DECISION_REQUEST = "decision.request";
102
128
  /** What one document's run committed, by execution path. `done` is every committed path in commit
103
129
  * order; `states` keeps the committed state of the paths a resume may still be answered from (a
104
130
  * chain's frontier step, a finished map item or parallel branch whose structure has not committed, a
@@ -119,6 +145,8 @@ export type PathFrame = {
119
145
  routes: Record<string, RouteDecision>;
120
146
  inputs: Record<string, string>;
121
147
  steps: Record<string, StepRecord>;
148
+ /** Each decision node's requests to the judge, by decision id. Absent in a frame written before decisions were kept. */
149
+ decisions?: Record<string, Record<string, DecisionRequest>>;
122
150
  /** A map that ended on an item's failure: the finished items' results, keyed by the map's `as`, so
123
151
  * the handoff carries the completed child work and a redispatch never loses it. */
124
152
  partial?: {
@@ -126,6 +154,15 @@ export type PathFrame = {
126
154
  as: string;
127
155
  results: unknown[];
128
156
  };
157
+ /** The map items that ended on their failure (`onItemFailure: "collect"`), by the item's path (`<map>/items/<i>`): an
158
+ * item here is answered from its row and its body never runs again. Kept with the run, as committed paths are. */
159
+ failures?: Record<string, ItemOutcome>;
160
+ };
161
+ /** How a map item that ended on its failure ended: the failing node's label, the failure's code and its message. */
162
+ export type ItemOutcome = {
163
+ code: string;
164
+ label: string;
165
+ message: string;
129
166
  };
130
167
  /** The recovery driver's durable state. It lives whole in the journal; each commit replaces it. No run
131
168
  * clock: clocks exist only per effect. */
@@ -141,6 +178,10 @@ export type FrozenSnapshot = {
141
178
  unknownResponses?: Record<string, unknown>;
142
179
  /** Spend by question nodes, which have no session of their own: metered per answer, carried with the frames. */
143
180
  questionSpendUsd?: number;
181
+ /** How many question answers came back with no price, so their cost is not in `questionSpendUsd`. A run
182
+ * with any makes its spend read as incomplete, never as a bare total that omits them: an unknown cost is
183
+ * never zero. Carried with the frames and committed in the same save as the spend it stands beside. */
184
+ unpricedQuestionCount?: number;
144
185
  /** The durable form of the escalation that ended the run; set once, reused on resume. */
145
186
  escalation?: EscalationRow;
146
187
  };
@@ -149,6 +190,12 @@ export type StepRecord = {
149
190
  attempt: number;
150
191
  attemptsAllowed: number;
151
192
  status: "running" | "closed" | "failed" | "submitted";
193
+ /** The failure that failed the step, when it was an item failure (`isItemFailure`) in an item of a map that collects
194
+ * its items' failures: a later open refuses the step with it, so the item ends on the same failure in every process. */
195
+ failure?: {
196
+ code: string;
197
+ message: string;
198
+ };
152
199
  };
153
200
  export type EscalationRow = {
154
201
  kind: string;
@@ -180,6 +227,9 @@ export type FrozenShape = {
180
227
  resolves: (path: string) => boolean;
181
228
  };
182
229
  export declare const emptyPathFrame: () => PathFrame;
230
+ export declare const SHA256: RegExp;
231
+ /** Whether a value is an item's committed failure: three strings, and nothing else. */
232
+ export declare const isItemOutcome: (value: unknown) => value is ItemOutcome;
183
233
  /** Refuses a saved snapshot the driver could not have produced for this run. */
184
234
  export declare function validateFrozenSnapshot(saved: any, shape: FrozenShape): void;
185
235
  /** The snapshot a driver runs under: the saved one (a paused run resumes running, retired keys
@@ -218,7 +268,7 @@ export declare function admitFrozenStep(steps: Record<string, StepRecord>, path:
218
268
  };
219
269
  /** The current attempt ended without a submission: `closed` until a retry is admitted, or
220
270
  * `failed` when the failure is final or no attempt remains. */
221
- export declare function closeFrozenStepAttempt(step: StepRecord, final: boolean): void;
271
+ export declare function closeFrozenStepAttempt(step: StepRecord, final: boolean, failure?: StepRecord["failure"]): void;
222
272
  /** The run-wide stop the driver applies: the host's pause or cancel it was handed, or null when it keeps
223
273
  * running. A cancelled snapshot stays cancelled. */
224
274
  export declare function frozenStop(status: FrozenSnapshot["status"], requested: "pause" | "cancel" | undefined): "paused" | "cancelled" | null;
@@ -4,14 +4,13 @@
4
4
  import { createHash } from "node:crypto";
5
5
  import { RecoveryError } from "./errors.js";
6
6
  import { itemState as rebuildItemState, partialResults as readPartialResults } from "./item-state.js";
7
- const failure = (code, message) => new RecoveryError(message, code);
7
+ import { isRecord } from "../record.js";
8
+ export const failure = (code, message) => new RecoveryError(message, code);
8
9
  export const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
9
10
  /** The keyed layout: what lies in a map item is kept in that item's record beside the state, and a state the driver
10
11
  * references is kept once by its digest, so no record rewritten at a commit grows with a map's items. */
11
12
  export const FROZEN_SNAPSHOT_SCHEMA_V4 = "agentrun.frozen_run.v4";
12
13
  export { stateDelta, applyStateDelta, canonicalJson } from "./item-state.js";
13
- /** Two values a state holds under one key are the same value. A key an item copied from its base holds the base's own
14
- * object, or one with the same JSON. */
15
14
  /** A map item's state at `path`, rebuilt as the driver rebuilds it (`./item-state.ts`, which imports nothing): the
16
15
  * `agentrun.states` value its `base` names, with the item's `set` and `unset` for that path applied, checked against
17
16
  * that path's `sha256`. `item` is an `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256. When
@@ -26,13 +25,33 @@ export function itemState(item, states, path, options = {}) {
26
25
  export function partialResults(partial, states, options = {}) {
27
26
  return readPartialResults(partial, states, { sha256: options.sha256 ?? ((text) => createHash("sha256").update(text).digest("hex")) });
28
27
  }
28
+ export const DECISION_REQUEST = "decision.request";
29
29
  export const emptyPathFrame = () => ({ input: null, done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {} });
30
- const record = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
31
- const SHA256 = /^[a-f0-9]{64}$/;
30
+ export const SHA256 = /^[a-f0-9]{64}$/;
32
31
  /** `value` as an object whose fields can be read, or null. */
33
- const fields = (value) => record(value) ? value : null;
32
+ const fields = (value) => isRecord(value) ? value : null;
34
33
  const entriesOf = (value) => { const object = fields(value); return object ? Object.entries(object) : null; };
34
+ const isStepFailure = (value) => {
35
+ const at = fields(value);
36
+ return Boolean(at && Object.keys(at).length === 2 && typeof at.code === "string" && typeof at.message === "string");
37
+ };
38
+ /** Whether a value is an item's committed failure: three strings, and nothing else. */
39
+ export const isItemOutcome = (value) => {
40
+ const at = fields(value);
41
+ return Boolean(at && Object.keys(at).length === 3 && typeof at.code === "string" && typeof at.label === "string" && typeof at.message === "string");
42
+ };
35
43
  const nonNegativeInt = (value) => Number.isSafeInteger(value) && value >= 0;
44
+ /** Whether `value` is a decision request the driver wrote under `id`: requested with no spend, or ended with its spend or null. */
45
+ const isDecisionRequest = (id, value) => {
46
+ const at = fields(value);
47
+ if (!at || at.record !== DECISION_REQUEST || at.decision_id !== id || typeof at.kind !== "string" || typeof at.label !== "string")
48
+ return false;
49
+ if (!(at.model === null || typeof at.model === "string") || typeof at.request_sha256 !== "string" || !Number.isSafeInteger(at.attempt) || at.attempt < 1)
50
+ return false;
51
+ if (at.status === "requested")
52
+ return at.cost_usd === undefined;
53
+ return ["answered", "failed", "interrupted"].includes(String(at.status)) && (at.cost_usd === null || (typeof at.cost_usd === "number" && Number.isFinite(at.cost_usd) && at.cost_usd >= 0));
54
+ };
36
55
  /** Whether a saved frame is one the driver could have written for its document. */
37
56
  function validFrame(value, resolves) {
38
57
  const frame = fields(value);
@@ -46,13 +65,20 @@ function validFrame(value, resolves) {
46
65
  return false;
47
66
  const [states, chains, loops, routes, inputs, steps] = [frame.states, frame.chains, frame.loops, frame.routes, frame.inputs, frame.steps].map(entriesOf);
48
67
  const partial = frame.partial === undefined ? undefined : fields(frame.partial);
49
- return Boolean(states && states.every(([path, state]) => done.has(path) && record(state))
68
+ const failures = frame.failures === undefined ? [] : entriesOf(frame.failures);
69
+ const decisions = frame.decisions === undefined ? [] : entriesOf(frame.decisions);
70
+ return Boolean(decisions && decisions.every(([path, requests]) => resolves(path) && (entriesOf(requests)?.every(([id, request]) => isDecisionRequest(id, request)) ?? false))
71
+ && states && states.every(([path, state]) => done.has(path) && isRecord(state))
72
+ && failures && failures.every(([item, outcome]) => /\/items\/(?:0|[1-9]\d*)$/.test(item) && resolves(`${item}/body`) && isItemOutcome(outcome))
50
73
  && chains && chains.every(([, head]) => { const at = fields(head); return Boolean(at && nonNegativeInt(at.index) && typeof at.path === "string" && done.has(at.path)); })
51
74
  && loops && loops.every(([loop, count]) => resolves(loop) && nonNegativeInt(count))
52
75
  && routes && routes.every(([route, decision]) => {
53
76
  const at = fields(decision);
54
77
  const receipts = fields(at?.receipts);
55
- return Boolean(at && resolves(route) && typeof at.label === "string" && typeof at.branch === "string" && ((typeof at.choice === "string" && typeof at.unsure === "boolean") || (at.choice === undefined && at.unsure === undefined)) && record(at.result) && (at.request_sha256 === null || typeof at.request_sha256 === "string")
78
+ return Boolean(at && resolves(route) && typeof at.label === "string" && typeof at.branch === "string"
79
+ // A refused route took its unsure branch and chose none: a named branch, a null choice, never "" for either.
80
+ && (at.refused === undefined ? (typeof at.choice === "string" && typeof at.unsure === "boolean") || (at.choice === undefined && at.unsure === undefined) : at.refused === true && at.branch !== "" && at.choice === null && at.unsure === true)
81
+ && isRecord(at.result) && (at.request_sha256 === null || typeof at.request_sha256 === "string")
56
82
  && (at.receipts === null || (receipts && typeof receipts.invocation === "string" && nonNegativeInt(receipts.request_bytes) && Number.isFinite(receipts.latency_ms))));
57
83
  })
58
84
  && inputs && inputs.every(([path, digest]) => resolves(path) && !done.has(path) && typeof digest === "string" && SHA256.test(digest))
@@ -60,19 +86,21 @@ function validFrame(value, resolves) {
60
86
  const at = fields(step);
61
87
  return Boolean(at && resolves(path) && typeof at.label === "string"
62
88
  && nonNegativeInt(at.attempt) && Number.isSafeInteger(at.attemptsAllowed) && at.attemptsAllowed >= 1
63
- && ["running", "closed", "failed", "submitted"].includes(String(at.status)));
89
+ && ["running", "closed", "failed", "submitted"].includes(String(at.status))
90
+ && (at.failure === undefined || (at.status === "failed" && isStepFailure(at.failure))));
64
91
  })
65
92
  && (partial === undefined || (partial && typeof partial.path === "string" && resolves(partial.path) && typeof partial.as === "string" && Array.isArray(partial.results))));
66
93
  }
67
94
  /** Refuses a saved snapshot the driver could not have produced for this run. */
68
95
  export function validateFrozenSnapshot(saved, shape) {
69
- if (!record(saved) || saved.schema !== FROZEN_SNAPSHOT_SCHEMA || !Number.isFinite(saved.startedAt)
96
+ if (!saved || typeof saved !== "object" || Array.isArray(saved) || saved.schema !== FROZEN_SNAPSHOT_SCHEMA || !Number.isFinite(saved.startedAt)
70
97
  || (saved.questionSpendUsd !== undefined && !(Number.isFinite(saved.questionSpendUsd) && saved.questionSpendUsd >= 0))
98
+ || (saved.unpricedQuestionCount !== undefined && !nonNegativeInt(saved.unpricedQuestionCount))
71
99
  || !["running", "paused", "cancelled"].includes(saved.status)
72
- || !record(saved.clocks) || !Object.values(saved.clocks).every(Number.isFinite)
73
- || !record(saved.files) || !Object.values(saved.files).every(value => typeof value === "string" && SHA256.test(value))
100
+ || !isRecord(saved.clocks) || !Object.values(saved.clocks).every(Number.isFinite)
101
+ || !isRecord(saved.files) || !Object.values(saved.files).every(value => typeof value === "string" && SHA256.test(value))
74
102
  || !validFrame(saved.pin, shape.resolves)
75
- || (saved.escalation !== undefined && (!record(saved.escalation) || typeof saved.escalation.tail !== "string" || typeof saved.escalation.kind !== "string" || !Number.isSafeInteger(saved.escalation.revision)))
103
+ || (saved.escalation !== undefined && (!isRecord(saved.escalation) || typeof saved.escalation.tail !== "string" || typeof saved.escalation.kind !== "string" || !Number.isSafeInteger(saved.escalation.revision)))
76
104
  // A checkpoint that holds a second document's frame is refused: the driver runs one document.
77
105
  || saved.adaptation !== undefined) {
78
106
  throw failure("FROZEN_CHECKPOINT_INVALID", "Invalid frozen recovery checkpoint");
@@ -147,8 +175,10 @@ export function admitFrozenStep(steps, path, label, admission) {
147
175
  }
148
176
  /** The current attempt ended without a submission: `closed` until a retry is admitted, or
149
177
  * `failed` when the failure is final or no attempt remains. */
150
- export function closeFrozenStepAttempt(step, final) {
178
+ export function closeFrozenStepAttempt(step, final, failure) {
151
179
  step.status = final || step.attempt + 1 >= step.attemptsAllowed ? "failed" : "closed";
180
+ if (step.status === "failed" && failure)
181
+ step.failure = { code: failure.code, message: failure.message };
152
182
  }
153
183
  /** The run-wide stop the driver applies: the host's pause or cancel it was handed, or null when it keeps
154
184
  * running. A cancelled snapshot stays cancelled. */
@@ -1,38 +1,3 @@
1
- import type { RecoveryEffect, RecoveryIntent } from "./store.js";
2
- /** A completed tool effect a continuation may answer an exact repeat from: the external call it paid for, and its value. */
3
- export type InheritedReceipt = {
4
- id: string;
5
- name: string;
6
- tool: string;
7
- argsHash: string;
8
- result: unknown;
9
- session: string | null;
10
- };
11
- /** An effect whose outcome is unknown: its call is never dispatched again. `intent` is the external call it was admitted
12
- * for, when its journal recorded one. */
13
- export type InheritedUnknown = {
14
- id: string;
15
- name: string;
16
- argsHash: string;
17
- session: string | null;
18
- intent?: RecoveryIntent;
19
- };
20
- /** A tool value that is itself a returned failure: an error envelope (`ok: false`, `isError: true`, `outcome: "error"`) as
21
- * an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
22
- * never prose. */
23
- export declare function returnedFailure(value: unknown): boolean;
24
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
25
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
26
- * failure. */
27
- export declare function inheritableReceipts(effects: readonly RecoveryEffect[]): InheritedReceipt[];
28
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
29
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
30
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
31
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
32
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
33
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
34
- * has none, and is matched by name and hash only. */
35
- export declare function inheritableUnknowns(effects: readonly RecoveryEffect[]): InheritedUnknown[];
36
1
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
37
2
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
38
3
  * The same key is computed for an effect from its receipt's intent. */
@@ -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";
@@ -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 });
@@ -50,8 +107,11 @@ export function withRecovery(driver, deps, options = {}) {
50
107
  driver.stepAttemptFailed(params.executionPath);
51
108
  admission = admit();
52
109
  }
53
- if (admission.status === "failed")
54
- throw new Error(`${params.label} failed after ${admission.attemptsAllowed} attempts`);
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
+ }
55
115
  // The step's record is durable before the attempt runs. A stop or a caller's cancellation that landed
56
116
  // meanwhile ends the step here: the runner is not called, and no attempt is spent. A pause waiting for an
57
117
  // effect in flight holds the step here until it is taken.
@@ -71,7 +131,7 @@ export function withRecovery(driver, deps, options = {}) {
71
131
  // A failure the runner marked final (an attempt that ended on a bound of its own) gets no second attempt: it
72
132
  // would spend the same again.
73
133
  const final = error?.final === true;
74
- driver.stepAttemptFailed(params.executionPath, final);
134
+ driver.stepAttemptFailed(params.executionPath, final, error);
75
135
  if (final)
76
136
  throw error;
77
137
  admission = admit();
@@ -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
+ }