@tangle-network/agent-runtime 6.0.1 → 6.0.3

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 (83) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/{activation-BRfZOfwb.js → activation-DNqjZEo7.js} +4 -4
  3. package/dist/{activation-BRfZOfwb.js.map → activation-DNqjZEo7.js.map} +1 -1
  4. package/dist/agent.js +4 -4
  5. package/dist/{bundle-vFFiCigS.js → bundle-BET6gl5r.js} +2 -2
  6. package/dist/{bundle-vFFiCigS.js.map → bundle-BET6gl5r.js.map} +1 -1
  7. package/dist/candidate-execution/index.js +4 -4
  8. package/dist/{coordination-manager-RSJg5GmY.js → coordination-manager-CYElgkMI.js} +7 -6
  9. package/dist/{coordination-manager-RSJg5GmY.js.map → coordination-manager-CYElgkMI.js.map} +1 -1
  10. package/dist/{coordination-map-routing-DVjW5Gx0.js → coordination-map-routing-CKRNZSaV.js} +2 -2
  11. package/dist/{coordination-map-routing-DVjW5Gx0.js.map → coordination-map-routing-CKRNZSaV.js.map} +1 -1
  12. package/dist/{delegate-C0cprMUN.js → delegate-dW2jsqFF.js} +2 -2
  13. package/dist/{delegate-C0cprMUN.js.map → delegate-dW2jsqFF.js.map} +1 -1
  14. package/dist/durable.js +12 -11
  15. package/dist/durable.js.map +1 -1
  16. package/dist/failure-cause-BzjUUsRz.js +3208 -0
  17. package/dist/failure-cause-BzjUUsRz.js.map +1 -0
  18. package/dist/{graph-cEg-gquv.js → graph-A7AvOP1I.js} +7 -6
  19. package/dist/{graph-cEg-gquv.js.map → graph-A7AvOP1I.js.map} +1 -1
  20. package/dist/{graph-registry-C-hjRx2t.js → graph-registry-C4ASeL2P.js} +1 -1
  21. package/dist/{graph-registry-B25FxBZN.js → graph-registry-DbCwfHMY.js} +3 -3
  22. package/dist/{graph-registry-B25FxBZN.js.map → graph-registry-DbCwfHMY.js.map} +1 -1
  23. package/dist/{improve-DNl4_6lP.js → improve-4qJclc9J.js} +10 -8
  24. package/dist/{improve-DNl4_6lP.js.map → improve-4qJclc9J.js.map} +1 -1
  25. package/dist/index.js +13 -11
  26. package/dist/index.js.map +1 -1
  27. package/dist/intelligence.js +8 -8
  28. package/dist/jsonl-file-BeUa5EDx.js +232 -0
  29. package/dist/jsonl-file-BeUa5EDx.js.map +1 -0
  30. package/dist/kernel.js +14 -13
  31. package/dist/{loop-runner-DQJjowz0.js → loop-runner-DZxVXLLU.js} +2 -2
  32. package/dist/{loop-runner-DQJjowz0.js.map → loop-runner-DZxVXLLU.js.map} +1 -1
  33. package/dist/loop-runner-bin.js +1 -1
  34. package/dist/mcp/bin.js +3 -3
  35. package/dist/mcp/index.js +7 -7
  36. package/dist/mcp/memory-bin.js +1 -1
  37. package/dist/{prepare-B6SQA12v.js → prepare-O1HbzOqs.js} +4 -3
  38. package/dist/{prepare-B6SQA12v.js.map → prepare-O1HbzOqs.js.map} +1 -1
  39. package/dist/{profile-DN8Dw2Kp.js → profile-DcRoyryP.js} +2 -2
  40. package/dist/{profile-DN8Dw2Kp.js.map → profile-DcRoyryP.js.map} +1 -1
  41. package/dist/{provision-supervisor-CtAaJCUa.js → provision-supervisor-CBeTMpMY.js} +7 -6
  42. package/dist/{provision-supervisor-CtAaJCUa.js.map → provision-supervisor-CBeTMpMY.js.map} +1 -1
  43. package/dist/{run-cancellation-BCuu6khW.js → run-cancellation-ZmRSYLu5.js} +4 -3
  44. package/dist/{run-cancellation-BCuu6khW.js.map → run-cancellation-ZmRSYLu5.js.map} +1 -1
  45. package/dist/{run-state-ByHiAjUs.js → run-state-Dn2AIE5m.js} +6 -6
  46. package/dist/{run-state-ByHiAjUs.js.map → run-state-Dn2AIE5m.js.map} +1 -1
  47. package/dist/{runtime-9EYvBcHG.js → runtime-D5eL70Is.js} +20 -17
  48. package/dist/{runtime-9EYvBcHG.js.map → runtime-D5eL70Is.js.map} +1 -1
  49. package/dist/{scope-DzhBJrRN.js → scope-DSm2RW5I.js} +9 -3204
  50. package/dist/scope-DSm2RW5I.js.map +1 -0
  51. package/dist/{search-executor-BJRNavck.js → search-executor-1qaSeY70.js} +6 -4
  52. package/dist/{search-executor-BJRNavck.js.map → search-executor-1qaSeY70.js.map} +1 -1
  53. package/dist/{server-DH0P6OY_.js → server-Dp4JKuTZ.js} +5 -5
  54. package/dist/{server-DH0P6OY_.js.map → server-Dp4JKuTZ.js.map} +1 -1
  55. package/dist/{settle-record-BSDDf9Z4.js → settle-record-DTh0cvF-.js} +2 -2
  56. package/dist/{settle-record-BSDDf9Z4.js.map → settle-record-DTh0cvF-.js.map} +1 -1
  57. package/dist/snapshot-Cgj2Wzi6.js +210 -0
  58. package/dist/snapshot-Cgj2Wzi6.js.map +1 -0
  59. package/dist/{structural-rollout-DgvJLTO0.js → structural-rollout-BwyAIuww.js} +6 -4
  60. package/dist/{structural-rollout-DgvJLTO0.js.map → structural-rollout-BwyAIuww.js.map} +1 -1
  61. package/dist/{supervise-Cqhkb2Oj.js → supervise-C2Do7hEd.js} +11 -10
  62. package/dist/{supervise-Cqhkb2Oj.js.map → supervise-C2Do7hEd.js.map} +1 -1
  63. package/dist/{supervision-discovery-DI5GIFBJ.js → supervision-discovery-BNChDps7.js} +5 -4
  64. package/dist/{supervision-discovery-DI5GIFBJ.js.map → supervision-discovery-BNChDps7.js.map} +1 -1
  65. package/dist/{supervisor-B6sl14OR.js → supervisor-jXN2xXiU.js} +8 -5
  66. package/dist/{supervisor-B6sl14OR.js.map → supervisor-jXN2xXiU.js.map} +1 -1
  67. package/dist/testing.js +13 -13
  68. package/dist/{tool-server-CZWd_Opp.js → tool-server-B9q2dtnW.js} +11 -8
  69. package/dist/tool-server-B9q2dtnW.js.map +1 -0
  70. package/dist/{top-web-DGoXGxH8.js → top-web-CQNkrh_j.js} +7 -6
  71. package/dist/{top-web-DGoXGxH8.js.map → top-web-CQNkrh_j.js.map} +1 -1
  72. package/dist/tui/bin.js +3 -3
  73. package/dist/tui/index.js +2 -2
  74. package/dist/util-C_cdPNC4.js +653 -0
  75. package/dist/util-C_cdPNC4.js.map +1 -0
  76. package/dist/{workspace-streams-BqNM06y4.js → workspace-streams-uB9rRbms.js} +3 -652
  77. package/dist/workspace-streams-uB9rRbms.js.map +1 -0
  78. package/package.json +3 -3
  79. package/dist/jsonl-file-CeVYTIQJ.js +0 -439
  80. package/dist/jsonl-file-CeVYTIQJ.js.map +0 -1
  81. package/dist/scope-DzhBJrRN.js.map +0 -1
  82. package/dist/tool-server-CZWd_Opp.js.map +0 -1
  83. package/dist/workspace-streams-BqNM06y4.js.map +0 -1
@@ -0,0 +1,3208 @@
1
+ import { m as ValidationError, r as BackendTransportError, t as AgentEvalError } from "./errors-AzSuGI23.js";
2
+ import { A as withBudgetResources, C as unreportedSpend, D as addResourceSpend, E as zeroTokenUsage, O as assertResources, T as zeroSpend, i as chargedTokens, l as fnv1a32Hex, m as promptCacheTokenClasses, n as addSpend, o as cloneTokenUsage, r as addTokenUsage, u as hasCompleteCacheBreakdown } from "./util-C_cdPNC4.js";
3
+ import { a as errMessage, i as causeChain, n as detachedSnapshot, s as errorProperty } from "./snapshot-Cgj2Wzi6.js";
4
+ import { AgentTurnResultSchema, CanonicalStreamEventSchema, RuntimeEventEnvelopeSchema } from "@tangle-network/agent-interface";
5
+ import { isRecord } from "@tangle-network/agent-core";
6
+ import { collectAgentFinalMessageText, collectAgentResponseText } from "@tangle-network/sandbox";
7
+ import { z } from "zod";
8
+ import { AgentTurnFailureSchema } from "@tangle-network/agent-interface/environment-provider";
9
+ import { createHash } from "node:crypto";
10
+ import { setImmediate } from "node:timers/promises";
11
+ import { LedgerCanonicalizationError, canonicalString, jsonDocument, merkleLeafHash, merkleRoot, merkleSalt } from "@tangle-network/agent-eval/ledger-core";
12
+ // src/record-value.ts
13
+ function recordValue(value) {
14
+ return isRecord(value) ? value : void 0;
15
+ }
16
+ // src/runtime/harness-usage.ts
17
+ /**
18
+ * Read and validate one codex `turn.completed` usage record.
19
+ *
20
+ * Every counter must be a non-negative safe integer. Two cross-field invariants hold, and they are
21
+ * what states that the two named counters are SUBSETS of their totals rather than additions to
22
+ * them: `cached_input_tokens <= input_tokens` and `reasoning_output_tokens <= output_tokens`.
23
+ * Measured against the codex CLI: a turn reporting `output_tokens 1523` with
24
+ * `reasoning_output_tokens 1516` answered with about seven tokens of text.
25
+ *
26
+ * `label` names the surface the record came from, so one message serves both readers.
27
+ * Throws `ValidationError` on any violation.
28
+ */
29
+ function parseCodexUsageRecord(usage, label) {
30
+ const record = recordValue(usage);
31
+ if (record === void 0) throw new ValidationError(`${label}: usage must be an object, received ${describe(usage)}`);
32
+ const inputTokens = naturalNumber(record.input_tokens, "input_tokens", label);
33
+ const cachedInputTokens = naturalNumber(record.cached_input_tokens, "cached_input_tokens", label);
34
+ const outputTokens = naturalNumber(record.output_tokens, "output_tokens", label);
35
+ const reasoningOutputTokens = naturalNumber(record.reasoning_output_tokens, "reasoning_output_tokens", label);
36
+ const cacheWriteInputTokens = record.cache_write_input_tokens === void 0 ? void 0 : naturalNumber(record.cache_write_input_tokens, "cache_write_input_tokens", label);
37
+ if (cachedInputTokens > inputTokens) throw new ValidationError(`${label}: cached_input_tokens exceeds input_tokens`);
38
+ if (reasoningOutputTokens > outputTokens) throw new ValidationError(`${label}: reasoning_output_tokens exceeds output_tokens`);
39
+ return {
40
+ inputTokens,
41
+ cachedInputTokens,
42
+ outputTokens,
43
+ reasoningOutputTokens,
44
+ ...cacheWriteInputTokens === void 0 ? {} : { cacheWriteInputTokens }
45
+ };
46
+ }
47
+ /** Names the wire record every codex decode error is reported against. */
48
+ const codexUsageContext = "codex turn.completed";
49
+ /**
50
+ * codex reports the tokens of a turn inside its own `turn.completed` event, which rides the
51
+ * transport either as `{ type: 'raw', data: { type: 'turn.completed', usage: { … } } }` or as
52
+ * the provider-normalized Interface envelope `{ type: 'raw', data: { type: 'raw', event: {
53
+ * type: 'turn.completed', usage: { … } } } }`. It emits no canonical usage event, so this adapter
54
+ * is a codex worker's only usage source.
55
+ *
56
+ * The record is read by `parseCodexUsageRecord`, the same reader `runLocalHarness` uses on the
57
+ * codex CLI's own stdout, so both surfaces hold one field policy and both cross-field invariants.
58
+ *
59
+ * A `turn.completed` that carries a `usage` member the reader cannot read is a `ValidationError`
60
+ * naming the field. A `turn.completed` with no `usage` member reports no usage at all, which
61
+ * leaves the turn's tokens unknown rather than zero.
62
+ */
63
+ const decodeCodexTurnUsage = (event) => {
64
+ if (String(event.type ?? "") !== "raw") return void 0;
65
+ const envelope = recordValue(event.data);
66
+ const data = envelope?.type === "raw" && recordValue(envelope.event) !== void 0 ? recordValue(envelope.event) : envelope;
67
+ if (data === void 0 || data.type !== "turn.completed" || data.usage === void 0) return;
68
+ const record = parseCodexUsageRecord(data.usage, codexUsageContext);
69
+ return {
70
+ harness: "codex",
71
+ input: record.inputTokens,
72
+ output: record.outputTokens,
73
+ cachedInput: record.cachedInputTokens,
74
+ reasoningOutput: record.reasoningOutputTokens,
75
+ ...record.cacheWriteInputTokens === void 0 ? {} : { cacheWriteInput: record.cacheWriteInputTokens }
76
+ };
77
+ };
78
+ /** Claude's adapter forwards one delta per response snapshot, keyed and deduplicated there. */
79
+ const decodeClaudeAssistantUsage = (event) => {
80
+ if (String(event.type ?? "") !== "raw") return void 0;
81
+ const envelope = recordValue(event.data);
82
+ const data = envelope?.type === "raw" && recordValue(envelope.event) !== void 0 ? recordValue(envelope.event) : envelope;
83
+ if (data?.type !== "assistant.usage") return void 0;
84
+ if (typeof data.message_id !== "string" || data.message_id.length === 0) throw new ValidationError("claude assistant.usage: missing response identity");
85
+ const usage = recordValue(data.usage);
86
+ if (!usage) throw new ValidationError("claude assistant.usage: usage must be an object");
87
+ const fresh = naturalNumber(usage.input_tokens, "input_tokens", "claude assistant.usage");
88
+ const cachedInput = naturalNumber(usage.cache_read_input_tokens, "cache_read_input_tokens", "claude assistant.usage");
89
+ const cacheWriteInput = naturalNumber(usage.cache_creation_input_tokens, "cache_creation_input_tokens", "claude assistant.usage");
90
+ const output = naturalNumber(usage.output_tokens, "output_tokens", "claude assistant.usage");
91
+ const input = fresh + cachedInput + cacheWriteInput;
92
+ if (!Number.isSafeInteger(input)) throw new ValidationError("claude assistant.usage: total input tokens exceed a safe integer");
93
+ return {
94
+ harness: "claude-code",
95
+ input,
96
+ output,
97
+ cachedInput,
98
+ cacheWriteInput
99
+ };
100
+ };
101
+ /**
102
+ * The harness → usage-decoder registry. Add a harness by adding one entry.
103
+ *
104
+ * Keyed by `HarnessType`, the vocabulary the `harness` argument is drawn from, so a key no caller
105
+ * can produce does not compile. A harness absent from this registry reports usage through the
106
+ * canonical events or not at all.
107
+ */
108
+ const harnessUsageDecoders = {
109
+ codex: decodeCodexTurnUsage,
110
+ "claude-code": decodeClaudeAssistantUsage
111
+ };
112
+ /**
113
+ * Decode a sandbox event with one harness's adapter, or `undefined` when the event carries no
114
+ * harness-native usage.
115
+ *
116
+ * A NAMED harness reads with that harness's adapter only, and a named harness with no adapter
117
+ * reports nothing. It never falls through to another harness's adapter: a different harness's
118
+ * `turn.completed` decoded as codex would either drop the counters codex does not name or fail on
119
+ * a field codex requires, and both answers would be about the wrong harness. The composite over
120
+ * every registered adapter runs only when the caller cannot name the harness.
121
+ *
122
+ * Throws `ValidationError` when an adapter recognizes the event as its harness's usage carrier and
123
+ * cannot read the numbers.
124
+ */
125
+ function decodeHarnessUsage(event, harness) {
126
+ if (!event || typeof event !== "object") return void 0;
127
+ if (harness !== void 0) return harnessUsageDecoders[harness]?.(event);
128
+ for (const decode of new Set(Object.values(harnessUsageDecoders))) {
129
+ const usage = decode(event);
130
+ if (usage !== void 0) return usage;
131
+ }
132
+ }
133
+ function naturalNumber(value, field, label) {
134
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new ValidationError(`${label}: usage.${field} must be a non-negative safe integer, received ${describe(value)}`);
135
+ return value;
136
+ }
137
+ function describe(value) {
138
+ if (value === null) return "null";
139
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
140
+ if (typeof value === "string") return JSON.stringify(value);
141
+ if (Array.isArray(value)) return "an array";
142
+ return typeof value;
143
+ }
144
+ // src/runtime/sandbox-events.ts
145
+ /**
146
+ * Forward a sandbox event to an optional observer without letting observer
147
+ * behavior affect the run. The observer receives a defensive copy, synchronous
148
+ * throws are swallowed, and returned promises are deliberately not awaited.
149
+ */
150
+ function notifySandboxEventObserver(event, observer, meta) {
151
+ if (!observer) return;
152
+ try {
153
+ const result = observer(cloneEventForObserver(event), meta);
154
+ if (result && typeof result.then === "function") result.then(void 0, () => {});
155
+ } catch {}
156
+ }
157
+ function cloneEventForObserver(event) {
158
+ try {
159
+ return structuredClone(event);
160
+ } catch {
161
+ return copyPlainSpine(event, /* @__PURE__ */ new WeakMap());
162
+ }
163
+ }
164
+ function copyPlainSpine(value, seen) {
165
+ if (value === null || typeof value !== "object") return value;
166
+ const existing = seen.get(value);
167
+ if (existing !== void 0) return existing;
168
+ if (Array.isArray(value)) {
169
+ const copy = [];
170
+ seen.set(value, copy);
171
+ for (const item of value) copy.push(copyPlainSpine(item, seen));
172
+ return copy;
173
+ }
174
+ const proto = Object.getPrototypeOf(value);
175
+ if (proto !== Object.prototype && proto !== null) return {};
176
+ const copy = {};
177
+ seen.set(value, copy);
178
+ for (const [key, child] of Object.entries(value)) copy[key] = copyPlainSpine(child, seen);
179
+ return copy;
180
+ }
181
+ /**
182
+ * Read the served execution identity off one Sandbox event: the platform reports `effectiveBackend`
183
+ * on `execution.started` and again on the terminal event. Absence stays unknown — a request is
184
+ * not a receipt, so nothing here may be inferred from what was asked for.
185
+ */
186
+ function sandboxEventServedBackend(event) {
187
+ const served = recordValue(recordValue(event?.data)?.effectiveBackend);
188
+ const named = [
189
+ "provider",
190
+ "model",
191
+ "source"
192
+ ].flatMap((key) => {
193
+ const value = firstString(served?.[key]);
194
+ return value === void 0 ? [] : [[key, value]];
195
+ });
196
+ if (!named.some(([key]) => key !== "source")) return void 0;
197
+ return Object.fromEntries(named);
198
+ }
199
+ /**
200
+ * Fail the execution when the platform reports serving a model other than the exact one asked for.
201
+ * Measured motive (agent-runtime#892): 6 of 6 boxes declaring `zai-coding-plan/glm-5.2` reported
202
+ * `deepseek/deepseek-v4-flash` (`source: "environment"`) while the materialization receipt recorded
203
+ * the declared model as known; only reading the report back detects the substitution.
204
+ * Silent when the platform reports no served model: unobserved stays unobserved.
205
+ */
206
+ function assertSandboxServedModel(event, expected) {
207
+ const wanted = expected?.model?.trim();
208
+ const served = wanted ? sandboxEventServedBackend(event) : void 0;
209
+ if (!wanted || served?.model === void 0) return;
210
+ if (sameModelId(served.model, wanted, [served.provider, expected?.provider])) return;
211
+ const attribution = Object.entries({
212
+ provider: served.provider,
213
+ source: served.source
214
+ }).flatMap(([key, value]) => value === void 0 ? [] : [`${key} ${JSON.stringify(value)}`]);
215
+ const detail = attribution.length > 0 ? ` (${attribution.join(", ")})` : "";
216
+ throw new Error(`sandbox served model ${JSON.stringify(served.model)}${detail} instead of the exact profile model ${JSON.stringify(wanted)}`);
217
+ }
218
+ /**
219
+ * Do two model ids name the same model, allowing for routing prefixes?
220
+ *
221
+ * Either side may spell the model bare (`glm-5.2`), provider-qualified
222
+ * (`zai-coding-plan/glm-5.2`), or route-qualified, and the platform reports the provider in its
223
+ * own field rather than always in the id. So the comparison drops any known provider prefix and
224
+ * then accepts a `/`-boundary suffix match: a longer route to the SAME leaf model is a routing
225
+ * difference, not a substitution.
226
+ *
227
+ * What it deliberately does NOT absorb is a different leaf: `glm-5.2` against `glm-5.3` stays a
228
+ * mismatch, which is the substitution measured directly against the provider API (a request for
229
+ * `glm-5.2` was served `glm-5.3`). A version suffix is the whole difference between two
230
+ * instruments, so nothing here may treat it as noise.
231
+ */
232
+ function sameModelId(served, wanted, providers) {
233
+ const a = stripProviderPrefix(served, providers);
234
+ const b = stripProviderPrefix(wanted, providers);
235
+ return a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`);
236
+ }
237
+ function stripProviderPrefix(id, providers) {
238
+ let out = id.trim().toLowerCase();
239
+ for (const provider of providers) {
240
+ const prefix = provider?.trim().toLowerCase();
241
+ if (prefix && out.startsWith(`${prefix}/`)) out = out.slice(prefix.length + 1);
242
+ }
243
+ return out;
244
+ }
245
+ function firstString(...values) {
246
+ return values.find((value) => typeof value === "string" && value.length > 0);
247
+ }
248
+ const terminalTypes = /* @__PURE__ */ new Set([
249
+ "message.completed",
250
+ "result",
251
+ "final",
252
+ "done"
253
+ ]);
254
+ /** True for an event type that ends a sandbox turn. */
255
+ function isSandboxTerminalEvent(type) {
256
+ return terminalTypes.has(type);
257
+ }
258
+ /**
259
+ * Which member of a terminal event's `data` carries its usage receipt.
260
+ *
261
+ * The one place the terminal types legitimately differ, stated rather than implied by two lists:
262
+ * sandbox 0.4.0's `done` reports under `tokenUsage` with the cost at the top level, every other
263
+ * terminal type reports under `usage`.
264
+ */
265
+ function sandboxTerminalUsageField(type) {
266
+ return type === "done" ? "tokenUsage" : "usage";
267
+ }
268
+ /**
269
+ * Extract a `RuntimeStreamEvent`-shaped `llm_call` from a sandbox event when
270
+ * the event carries usage/cost data. Returns `undefined` for non-cost events
271
+ * so the kernel can iterate the full stream without branching.
272
+ *
273
+ * Pure by contract: it never throws on a failed run. The terminal truth
274
+ * boundary is the public Sandbox outcome tracker, applied after the complete
275
+ * stream. Post-hoc readers — {@link sumSandboxUsage}, the
276
+ * analyst trace store, the chat projection — must stay able to read a failed
277
+ * turn's events, which is when reading them matters most.
278
+ *
279
+ * Canonical cost-carrying types observed in the wild:
280
+ * - `llm_call` — `data: { model, tokensIn, tokensOut, costUsd, ... }`
281
+ * - `message.completed` / `result` — `data: { usage: { inputTokens,
282
+ * outputTokens, totalCostUsd? } }`
283
+ * - `cost.usage` / `usage` — same shape under a dedicated type
284
+ *
285
+ * Numeric coercion is strict: `Number.isFinite` gates every accumulator write
286
+ * so a sentinel `NaN` from a misbehaving backend cannot poison the ledger.
287
+ */
288
+ function extractLlmCallEvent(event, agentRunName) {
289
+ const data = canonicalUsageData(event);
290
+ return data === void 0 ? void 0 : buildLlmCall(data, agentRunName);
291
+ }
292
+ function canonicalUsageData(event) {
293
+ if (!event || typeof event !== "object") return void 0;
294
+ const type = String(event.type ?? "");
295
+ const data = event.data && typeof event.data === "object" ? event.data : {};
296
+ if (type === "llm_call" || type === "cost.usage" || type === "usage") return usageReceiptData(data, recordValue(data.usage));
297
+ if (type === "error" || isSandboxTerminalEvent(type)) {
298
+ const field = type === "error" ? "tokenUsage" : sandboxTerminalUsageField(type);
299
+ return usageReceiptData(data, recordValue(data[field]) ?? recordValue(data[field === "usage" ? "tokenUsage" : "usage"]));
300
+ }
301
+ }
302
+ /** A {@link SandboxUsageLedger} for one worker. Pass the worker's harness to decode with that
303
+ * harness's adapter; omit it to try every registered adapter. */
304
+ function createSandboxUsageLedger(harness) {
305
+ let held = [];
306
+ let sawCanonical = false;
307
+ const credited = {};
308
+ const receipts = /* @__PURE__ */ new Map();
309
+ const settledTokens = zeroTokenUsage();
310
+ let turnTokens = zeroTokenUsage();
311
+ let turnUsageUnknown = false;
312
+ let settledUsage;
313
+ return {
314
+ settledUsage: () => settledUsage === void 0 ? void 0 : { ...settledUsage },
315
+ tokenUsage() {
316
+ const total = cloneTokenUsage(settledTokens);
317
+ addTokenUsage(total, turnTokens);
318
+ return total;
319
+ },
320
+ observe(event, agentRunName) {
321
+ const call = extractLlmCallEvent(event, agentRunName);
322
+ if (call) {
323
+ sawCanonical = true;
324
+ const receipt = creditCanonicalUsage(event, call, credited, receipts, (receipt, mode) => {
325
+ refineCanonicalTokens(turnTokens, call, receipt, mode);
326
+ });
327
+ if (receipt?.tokensKnown === false) {
328
+ turnTokens.tokensKnown = false;
329
+ turnUsageUnknown = true;
330
+ }
331
+ return receipt;
332
+ }
333
+ let usage;
334
+ try {
335
+ usage = decodeHarnessUsage(event, harness);
336
+ } catch (err) {
337
+ turnUsageUnknown = true;
338
+ return {
339
+ type: "llm_call",
340
+ model: agentRunName,
341
+ tokensKnown: false,
342
+ usdKnown: false,
343
+ tokensUnknownReason: err instanceof Error ? err.message : String(err)
344
+ };
345
+ }
346
+ if (usage) held.push(usage);
347
+ },
348
+ settleTurn(agentRunName) {
349
+ const reports = held;
350
+ const canonical = sawCanonical;
351
+ held = [];
352
+ sawCanonical = false;
353
+ const receipt = !canonical && reports.length > 0 ? harnessUsageLlmCall(reports, agentRunName) : void 0;
354
+ if (receipt) creditCanonicalUsage({
355
+ type: "llm_call",
356
+ data: {}
357
+ }, receipt, credited, receipts, (credit, mode) => refineCanonicalTokens(turnTokens, receipt, credit, mode));
358
+ settledUsage = !turnUsageUnknown && credited.tokensIn !== void 0 && credited.tokensOut !== void 0 ? {
359
+ inputTokens: credited.tokensIn,
360
+ outputTokens: credited.tokensOut,
361
+ ...credited.totalTokens === void 0 ? {} : { totalTokens: credited.totalTokens },
362
+ ...credited.reasoningTokens === void 0 ? {} : { reasoningTokens: credited.reasoningTokens },
363
+ ...credited["promptCache.readTokens"] === void 0 ? {} : { cacheReadInputTokens: credited["promptCache.readTokens"] },
364
+ ...credited["promptCache.writeTokens"] === void 0 ? {} : { cacheCreationInputTokens: credited["promptCache.writeTokens"] },
365
+ ...credited.costUsd === void 0 ? {} : { cost: credited.costUsd }
366
+ } : void 0;
367
+ for (const key of Object.keys(credited)) delete credited[key];
368
+ receipts.clear();
369
+ addTokenUsage(settledTokens, turnTokens);
370
+ turnTokens = zeroTokenUsage();
371
+ turnUsageUnknown = false;
372
+ return receipt;
373
+ }
374
+ };
375
+ }
376
+ /** Shared receipt semantics; an undeclared nonterminal observation is not a cumulative total. */
377
+ function canonicalSandboxUsageMode(event) {
378
+ const declaredMode = recordValue(event.data)?.usageMode;
379
+ return declaredMode === "delta" || declaredMode === "cumulative" ? declaredMode : declaredMode === void 0 && event.type === "llm_call" ? "delta" : declaredMode === void 0 && (event.type === "error" || isSandboxTerminalEvent(String(event.type))) ? "cumulative" : void 0;
380
+ }
381
+ /** Terminal totals replace already credited usage; only per-call receipts add to it. */
382
+ function creditCanonicalUsage(event, call, credited, receipts, onCredit) {
383
+ const mode = canonicalSandboxUsageMode(event);
384
+ const result = { ...call };
385
+ const data = recordValue(event.data) ?? {};
386
+ const usageData = canonicalUsageData(event) ?? {};
387
+ const supplemental = Object.fromEntries(["totalTokens", "reasoningTokens"].flatMap((key) => {
388
+ const value = usageData[key];
389
+ return value === void 0 ? [] : [[key, typeof value === "number" && Number.isFinite(value) ? value : null]];
390
+ }));
391
+ const explicitTokensUnknown = [
392
+ data,
393
+ recordValue(data.usage),
394
+ recordValue(data.tokenUsage)
395
+ ].some((receipt) => ["tokensKnown", "tokens_known"].some((key) => receipt?.[key] !== void 0 && receipt[key] !== true));
396
+ if (call.tokensIn === void 0 && call.tokensOut === void 0 && !call.tokensUnknownReason && !explicitTokensUnknown) delete result.tokensKnown;
397
+ let reason = mode === void 0 ? "usage receipt has no declared delta or cumulative semantics" : void 0;
398
+ if (event.id) {
399
+ const signature = JSON.stringify({
400
+ mode,
401
+ call,
402
+ supplemental
403
+ });
404
+ const previous = receipts.get(event.id);
405
+ if (previous === signature) return void 0;
406
+ if (previous !== void 0) return {
407
+ type: "llm_call",
408
+ model: call.model,
409
+ tokensKnown: false,
410
+ usdKnown: false,
411
+ tokensUnknownReason: `usage receipt ${event.id} changed after it was credited`
412
+ };
413
+ receipts.set(event.id, signature);
414
+ }
415
+ const credit = (key, value) => {
416
+ const previous = credited[key] ?? 0;
417
+ if (!Number.isFinite(value) || value < 0) {
418
+ reason = `usage receipt has an invalid ${key}`;
419
+ return 0;
420
+ }
421
+ if (mode === "delta") {
422
+ credited[key] = previous + value;
423
+ return value;
424
+ }
425
+ if (value < previous) reason = `cumulative usage ${key} is below already credited usage`;
426
+ credited[key] = Math.max(previous, value);
427
+ return Math.max(0, value - previous);
428
+ };
429
+ for (const key of [
430
+ "tokensIn",
431
+ "tokensOut",
432
+ "costUsd",
433
+ "estimatedCostUsd"
434
+ ]) if (call[key] !== void 0) result[key] = credit(key, call[key]);
435
+ for (const [key, value] of Object.entries(supplemental)) if (typeof value !== "number") reason = `usage receipt has an invalid ${key}`;
436
+ else credit(key, value);
437
+ if (call.promptCache) result.promptCache = Object.fromEntries(Object.entries(call.promptCache).map(([key, value]) => [key, typeof value === "number" ? credit(`promptCache.${key}`, value) : value]));
438
+ if (reason !== void 0) {
439
+ result.usdKnown = false;
440
+ if (call.tokensIn !== void 0 || call.tokensOut !== void 0) {
441
+ result.tokensKnown = false;
442
+ result.tokensUnknownReason = reason;
443
+ }
444
+ }
445
+ onCredit(result, mode);
446
+ return result;
447
+ }
448
+ /** Cache partitions belong to the original receipt, not the smaller incremental charge. */
449
+ function refineCanonicalTokens(tokens, call, receipt, mode) {
450
+ const input = receipt.tokensIn ?? 0;
451
+ const output = receipt.tokensOut ?? 0;
452
+ const cache = promptCacheTokenClasses(call.tokensIn, call.promptCache);
453
+ if (mode !== "cumulative") {
454
+ addTokenUsage(tokens, {
455
+ input,
456
+ output,
457
+ ...cache
458
+ });
459
+ return;
460
+ }
461
+ tokens.input += input;
462
+ tokens.output += output;
463
+ if (cache.freshInput !== void 0 && call.tokensIn === tokens.input && receipt.tokensKnown !== false) {
464
+ tokens.freshInput = cache.freshInput;
465
+ tokens.cacheRead = cache.cacheRead;
466
+ tokens.cacheWrite = cache.cacheWrite;
467
+ delete tokens.cacheBreakdownKnown;
468
+ return;
469
+ }
470
+ if (cache.cacheRead !== void 0) tokens.cacheRead = Math.max(tokens.cacheRead ?? 0, cache.cacheRead);
471
+ if (cache.cacheWrite !== void 0) tokens.cacheWrite = Math.max(tokens.cacheWrite ?? 0, cache.cacheWrite);
472
+ if ((tokens.freshInput ?? 0) + (tokens.cacheRead ?? 0) + (tokens.cacheWrite ?? 0) > tokens.input) {
473
+ delete tokens.freshInput;
474
+ delete tokens.cacheRead;
475
+ delete tokens.cacheWrite;
476
+ }
477
+ if (input > 0 || cache.cacheBreakdownKnown === false) tokens.cacheBreakdownKnown = false;
478
+ }
479
+ /**
480
+ * Fold harness-native usage reports into the canonical `llm_call` the accounting paths read.
481
+ *
482
+ * Every counter a `HarnessUsage` carries beside `input` and `output` CLASSIFIES one of those two
483
+ * totals, so none of them is added to the total it describes:
484
+ *
485
+ * - the prompt-cache counters classify `input` and ride `promptCache`, the convention the
486
+ * terminal `tokenUsage` branch above already follows and `promptCacheTokenClasses` folds,
487
+ * where `freshInput = input - cacheRead - cacheWrite`;
488
+ * - `reasoningOutput` classifies `output`. Codex counts its reasoning tokens INSIDE
489
+ * `output_tokens` — a turn reporting `output_tokens 1523` with `reasoning_output_tokens 1516`
490
+ * answered with about seven tokens of text — and `parseCodexUsageRecord` holds that as an
491
+ * invariant. The canonical `llm_call` carries no reasoning class, so the count is not
492
+ * forwarded to {@link buildLlmCall}. Canonical output totals already include reasoning.
493
+ *
494
+ * A counter no report carried stays absent, because a zero would claim the provider measured none.
495
+ */
496
+ function harnessUsageLlmCall(reports, agentRunName) {
497
+ let inputTokens = 0;
498
+ let outputTokens = 0;
499
+ let readTokens;
500
+ let writeTokens;
501
+ for (const report of reports) {
502
+ inputTokens += report.input;
503
+ outputTokens += report.output;
504
+ if (report.cachedInput !== void 0) readTokens = (readTokens ?? 0) + report.cachedInput;
505
+ if (report.cacheWriteInput !== void 0) writeTokens = (writeTokens ?? 0) + report.cacheWriteInput;
506
+ }
507
+ const promptCache = {};
508
+ if (readTokens !== void 0) promptCache.readTokens = readTokens;
509
+ if (writeTokens !== void 0) promptCache.writeTokens = writeTokens;
510
+ return buildLlmCall({
511
+ inputTokens,
512
+ outputTokens,
513
+ ...Object.keys(promptCache).length > 0 ? { promptCache } : {}
514
+ }, agentRunName);
515
+ }
516
+ /**
517
+ * Sum the token usage + USD cost of a sandbox turn's events — the one honest way to meter an
518
+ * `openSandboxRun` cell. Folds a {@link SandboxUsageLedger} over the stream, so it reads usage off
519
+ * EVERY backend event shape — the canonical events plus a harness that reports usage only in its
520
+ * own event — and a `runProfileMatrix` dispatch can report it to `ctx.cost`:
521
+ *
522
+ * receipt: (turn) => {
523
+ * const u = sumSandboxUsage(turn.events)
524
+ * return { model, inputTokens: u.input, outputTokens: u.output,
525
+ * ...(u.tokensKnown === false ? { usageUnknown: true } : {}),
526
+ * ...(u.usdKnown !== false && u.costUsd > 0 ? { actualCostUsd: u.costUsd } : {}),
527
+ * ...(u.usdKnown === false ? { costUnknown: true } : {}),
528
+ * ...(u.estimatedCostUsd !== undefined ? { estimatedCostUsd: u.estimatedCostUsd } : {}) }
529
+ * }
530
+ *
531
+ * Without this a cell reads `{tokens:0, cost:0}` and the backend-integrity guard correctly aborts the
532
+ * matrix as a stub. `agentRunName` is the fallback model label for cost-only events (default `'agent'`).
533
+ *
534
+ * Pure by contract, like the ledger it folds: it never throws. A harness receipt the ledger cannot
535
+ * read leaves the result at `tokensKnown: false` with `tokensUnknownReason` carrying the decode
536
+ * message — an unreadable receipt is a different fact from a turn that reported no usage, and a
537
+ * post-hoc reader that threw would lose the whole failed turn it exists to report.
538
+ */
539
+ function sumSandboxUsage(events, agentRunName = "agent") {
540
+ let input = 0;
541
+ let output = 0;
542
+ let costUsd = 0;
543
+ let estimatedCostUsd = 0;
544
+ let sawEstimate = false;
545
+ let sawCall = false;
546
+ let sawTokenReceipt = false;
547
+ let tokensKnown = true;
548
+ let usdKnown = true;
549
+ let unreadable;
550
+ const ledger = createSandboxUsageLedger();
551
+ const credit = (call) => {
552
+ sawCall = true;
553
+ sawTokenReceipt ||= call.tokensIn !== void 0 || call.tokensOut !== void 0;
554
+ input += call.tokensIn ?? 0;
555
+ output += call.tokensOut ?? 0;
556
+ costUsd += call.costUsd ?? 0;
557
+ if (call.tokensKnown === false) tokensKnown = false;
558
+ if (call.usdKnown === false) usdKnown = false;
559
+ unreadable ??= call.tokensUnknownReason;
560
+ if (call.estimatedCostUsd !== void 0) {
561
+ estimatedCostUsd += call.estimatedCostUsd;
562
+ sawEstimate = true;
563
+ }
564
+ };
565
+ for (const ev of events) {
566
+ const call = ledger.observe(ev, agentRunName);
567
+ if (call) credit(call);
568
+ }
569
+ const harnessCall = ledger.settleTurn(agentRunName);
570
+ if (harnessCall) credit(harnessCall);
571
+ return {
572
+ input,
573
+ output,
574
+ costUsd,
575
+ ...sawTokenReceipt && tokensKnown ? {} : { tokensKnown: false },
576
+ ...sawCall && usdKnown ? {} : { usdKnown: false },
577
+ ...sawEstimate ? { estimatedCostUsd } : {},
578
+ ...unreadable === void 0 ? {} : { tokensUnknownReason: unreadable }
579
+ };
580
+ }
581
+ function usageReceiptData(envelope, usage = {}) {
582
+ const merged = {
583
+ ...usage,
584
+ ...envelope
585
+ };
586
+ for (const aliases of [
587
+ [
588
+ "tokensIn",
589
+ "inputTokens",
590
+ "prompt_tokens"
591
+ ],
592
+ [
593
+ "tokensOut",
594
+ "outputTokens",
595
+ "completion_tokens"
596
+ ],
597
+ [
598
+ "costUsd",
599
+ "totalCostUsd",
600
+ "cost_usd",
601
+ "cost"
602
+ ],
603
+ ["costProvenance", "cost_provenance"]
604
+ ]) {
605
+ const key = aliases.find((alias) => envelope[alias] !== void 0);
606
+ if (key === void 0) continue;
607
+ for (const alias of aliases) delete merged[alias];
608
+ merged[key] = envelope[key];
609
+ }
610
+ for (const aliases of [["tokensKnown", "tokens_known"], [
611
+ "costKnown",
612
+ "cost_known",
613
+ "usdKnown",
614
+ "usd_known"
615
+ ]]) {
616
+ const values = [usage, envelope].flatMap((receipt) => aliases.map((key) => receipt[key]).filter((value) => value !== void 0));
617
+ if (values.length > 0) merged[aliases[0]] = values.every((value) => value === true);
618
+ }
619
+ return merged;
620
+ }
621
+ function buildLlmCall(data, agentRunName) {
622
+ const tokensIn = pickFiniteNumber(data, [
623
+ "tokensIn",
624
+ "inputTokens",
625
+ "prompt_tokens"
626
+ ]);
627
+ const outputTokens = pickFiniteNumber(data, [
628
+ "tokensOut",
629
+ "outputTokens",
630
+ "completion_tokens"
631
+ ]);
632
+ const reasoningTokens = pickFiniteNumber(data, ["reasoningTokens"]);
633
+ const tokensOut = outputTokens ?? reasoningTokens;
634
+ const reportedCostUsd = pickFiniteNumber(data, [
635
+ "costUsd",
636
+ "totalCostUsd",
637
+ "cost_usd",
638
+ "cost"
639
+ ]);
640
+ const explicitTokensKnown = data.tokensKnown ?? data.tokens_known;
641
+ const explicitCostKnown = data.costKnown ?? data.cost_known ?? data.usdKnown ?? data.usd_known;
642
+ const costProvenance = data.costProvenance ?? data.cost_provenance;
643
+ const explicitEstimate = pickFiniteNumber(data, ["estimatedCostUsd", "estimated_cost_usd"]);
644
+ const catalogEstimate = costProvenance === "catalog-estimate" ? explicitEstimate ?? reportedCostUsd : explicitEstimate;
645
+ const costUsd = costProvenance === "catalog-estimate" ? void 0 : reportedCostUsd;
646
+ const promptCache = readPromptCacheUsage(data);
647
+ const tokensKnown = explicitTokensKnown !== false && tokensIn !== void 0 && outputTokens !== void 0;
648
+ const usdKnown = explicitCostKnown !== false && costUsd !== void 0 && (costProvenance === void 0 || costProvenance === "provider-receipt" || costProvenance === "billing-receipt");
649
+ const tools = readOfferedTools(data.tools);
650
+ if (tokensIn === void 0 && tokensOut === void 0 && costUsd === void 0 && catalogEstimate === void 0 && promptCache === void 0 && tools === void 0 && explicitTokensKnown !== false && explicitCostKnown !== false) return;
651
+ const event = {
652
+ type: "llm_call",
653
+ model: typeof data.model === "string" && data.model.length > 0 ? data.model : agentRunName
654
+ };
655
+ if (tokensIn !== void 0) event.tokensIn = tokensIn;
656
+ if (tokensOut !== void 0) event.tokensOut = tokensOut;
657
+ if (!tokensKnown) event.tokensKnown = false;
658
+ if (costUsd !== void 0) event.costUsd = costUsd;
659
+ if (!usdKnown) event.usdKnown = false;
660
+ if (catalogEstimate !== void 0) event.estimatedCostUsd = catalogEstimate;
661
+ if (promptCache !== void 0) event.promptCache = promptCache;
662
+ if (tools !== void 0) event.tools = tools;
663
+ return event;
664
+ }
665
+ /** `data.tools`, when it is a non-empty array of non-empty tool-name strings. Anything else
666
+ * (absent, empty, wrong element type) is treated as "the producer did not report its offered
667
+ * set" — never a placeholder empty list, which would read as "offered zero tools" downstream. */
668
+ function readOfferedTools(value) {
669
+ if (!Array.isArray(value) || value.length === 0) return void 0;
670
+ const names = value.filter((v) => typeof v === "string" && v.length > 0);
671
+ return names.length === value.length ? names : void 0;
672
+ }
673
+ /**
674
+ * Every wire spelling of a prompt-cache READ counter, in precedence order: the canonical name
675
+ * first, then the spellings observed on the paths that reach this extractor — the sandbox terminal
676
+ * `tokenUsage` record, the cli-bridge OpenAI-compatible usage object (which normalizes every
677
+ * backend to Anthropic's `cache_read_input_tokens`), Anthropic verbatim, OpenAI's
678
+ * `prompt_tokens_details.cached_tokens`, and DeepSeek's `prompt_cache_hit_tokens`.
679
+ */
680
+ const PROMPT_CACHE_READ_KEYS = [
681
+ "readTokens",
682
+ "read_tokens",
683
+ "cacheReadInputTokens",
684
+ "cache_read_input_tokens",
685
+ "cacheRead",
686
+ "cache_read",
687
+ "cachedInputTokens",
688
+ "cachedTokens",
689
+ "cached_tokens",
690
+ "prompt_cache_hit_tokens"
691
+ ];
692
+ /**
693
+ * Every wire spelling of a prompt-cache WRITE counter. OpenAI reports no write counter at all, so
694
+ * an OpenAI-shaped usage record matches nothing here and the write stays absent — which is the
695
+ * point: absent is not zero.
696
+ */
697
+ const PROMPT_CACHE_WRITE_KEYS = [
698
+ "writeTokens",
699
+ "write_tokens",
700
+ "cacheWriteInputTokens",
701
+ "cache_write_input_tokens",
702
+ "cacheCreationInputTokens",
703
+ "cache_creation_input_tokens",
704
+ "cacheWrite",
705
+ "cache_write"
706
+ ];
707
+ const PROMPT_CACHE_MISS_KEYS = [
708
+ "missTokens",
709
+ "miss_tokens",
710
+ "prompt_cache_miss_tokens"
711
+ ];
712
+ const PROMPT_CACHE_SAVINGS_KEYS = ["readSavingsUsd", "read_savings_usd"];
713
+ /**
714
+ * Read the provider's own prompt-cache accounting off one usage-bearing event payload, in the
715
+ * `PromptCacheUsage` vocabulary the router, driver, and chat-client paths already speak.
716
+ *
717
+ * Two sources, one record. A payload that already carries a `promptCache` / `prompt_cache` object
718
+ * is forwarded VERBATIM — those fields are the provider's own report, and an unrecognized one must
719
+ * stay visible rather than be bucketed away. On top of that, flat provider counters are translated
720
+ * to the canonical names, filling only the names the verbatim object did not already define.
721
+ *
722
+ * A counter the payload does not carry is left out. Defaulting it to zero would assert the provider
723
+ * measured no cache, which is a different fact from a provider that reported nothing — and it is
724
+ * the fact the budget reads to decide whether its charge is a measurement or a bound.
725
+ */
726
+ function readPromptCacheUsage(data) {
727
+ const declared = finiteMetadata(data.promptCache ?? data.prompt_cache);
728
+ const nested = recordValue(data.promptCache) ?? recordValue(data.prompt_cache);
729
+ const sources = [
730
+ nested,
731
+ data,
732
+ recordValue(data.prompt_tokens_details)
733
+ ].filter((s) => s !== void 0);
734
+ const canonical = {};
735
+ const readTokens = pickTokenCount(sources, PROMPT_CACHE_READ_KEYS);
736
+ const writeTokens = pickTokenCount(sources, PROMPT_CACHE_WRITE_KEYS);
737
+ const missTokens = pickTokenCount(sources, PROMPT_CACHE_MISS_KEYS);
738
+ const readSavingsUsd = pickNonNegativeNumber(sources, PROMPT_CACHE_SAVINGS_KEYS);
739
+ const status = nested !== void 0 && typeof nested.status === "string" ? nested.status : void 0;
740
+ if (readTokens !== void 0) canonical.readTokens = readTokens;
741
+ if (writeTokens !== void 0) canonical.writeTokens = writeTokens;
742
+ if (missTokens !== void 0) canonical.missTokens = missTokens;
743
+ if (readSavingsUsd !== void 0) canonical.readSavingsUsd = readSavingsUsd;
744
+ if (status !== void 0) canonical.status = status;
745
+ const merged = {
746
+ ...canonical,
747
+ ...declared
748
+ };
749
+ return Object.keys(merged).length > 0 ? merged : void 0;
750
+ }
751
+ function pickTokenCount(sources, keys) {
752
+ for (const key of keys) for (const source of sources) {
753
+ const value = source[key];
754
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return value;
755
+ }
756
+ }
757
+ function pickNonNegativeNumber(sources, keys) {
758
+ for (const key of keys) for (const source of sources) {
759
+ const value = source[key];
760
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
761
+ }
762
+ }
763
+ function finiteMetadata(value) {
764
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
765
+ const result = {};
766
+ for (const [key, entry] of Object.entries(value)) if (typeof entry === "number" && Number.isFinite(entry) || typeof entry === "string") result[key] = entry;
767
+ return Object.keys(result).length > 0 ? result : void 0;
768
+ }
769
+ function pickFiniteNumber(data, keys) {
770
+ for (const key of keys) {
771
+ const value = data[key];
772
+ if (typeof value === "number" && Number.isFinite(value)) return value;
773
+ }
774
+ }
775
+ /**
776
+ * Collect one turn's events, keeping only the newest snapshot of each streamed text or
777
+ * reasoning part.
778
+ *
779
+ * opencode sends `message.part.updated` once per token, and every frame carries the part's
780
+ * whole cumulative text, so keeping every frame holds O(L²) bytes per turn: two concurrent
781
+ * audit workflows took the platform API from 459 MB to an OOM at 1.95 GB in 11 minutes.
782
+ * A snapshot (a frame whose part carries `text`) whose text extends the previous snapshot
783
+ * of the same part replaces it and moves to the newest position, which is the rule the
784
+ * Sandbox SDK's text collectors already apply, so the collected text is unchanged. The kept
785
+ * frame drops its `delta`, because its text already holds every earlier increment and a
786
+ * reader that joins `delta ?? part.text` across frames would otherwise read only the last
787
+ * one. Delta-only frames and every other event are kept as they arrived.
788
+ */
789
+ function createSandboxTurnEventCollector() {
790
+ const slots = [];
791
+ const snapshots = /* @__PURE__ */ new Map();
792
+ return {
793
+ push(event) {
794
+ const snapshot = partSnapshot(event);
795
+ if (!snapshot) {
796
+ slots.push(event);
797
+ return;
798
+ }
799
+ const previous = snapshots.get(snapshot.key);
800
+ const extends_ = previous !== void 0 && snapshot.text.startsWith(previous.text);
801
+ if (extends_) slots[previous.at] = void 0;
802
+ snapshots.set(snapshot.key, {
803
+ at: slots.length,
804
+ text: snapshot.text
805
+ });
806
+ slots.push(extends_ ? withoutDelta(event) : event);
807
+ },
808
+ events() {
809
+ return slots.filter((event) => event !== void 0);
810
+ }
811
+ };
812
+ }
813
+ function partSnapshot(event) {
814
+ if (event?.type !== "message.part.updated") return void 0;
815
+ const data = asRecord(event.data);
816
+ const part = asRecord(data?.part) ?? asRecord(asRecord(data?.properties)?.part);
817
+ if (!part || typeof part.id !== "string") return void 0;
818
+ if (part.type !== "text" && part.type !== "reasoning" && part.type !== "thinking") return void 0;
819
+ const text = typeof part.text === "string" ? part.text : typeof part.content === "string" ? part.content : void 0;
820
+ return text === void 0 ? void 0 : {
821
+ key: `${part.type}:${part.id}`,
822
+ text
823
+ };
824
+ }
825
+ function withoutDelta(event) {
826
+ const data = asRecord(event.data);
827
+ if (!data || !("delta" in data)) return event;
828
+ const { delta: _delta, ...rest } = data;
829
+ return {
830
+ ...event,
831
+ data: rest
832
+ };
833
+ }
834
+ function asRecord(value) {
835
+ return value !== null && typeof value === "object" ? value : void 0;
836
+ }
837
+ // src/runtime/timestamps.ts
838
+ const validTimestamp = "2026-01-01T00:00:00.000Z";
839
+ /** Validate a timestamp with the public runtime envelope contract. */
840
+ function assertRuntimeTimestamp(value, label) {
841
+ try {
842
+ RuntimeEventEnvelopeSchema.parse({
843
+ runId: "runtime",
844
+ eventId: "event",
845
+ sequence: 0,
846
+ occurredAt: value,
847
+ receivedAt: validTimestamp,
848
+ event: {
849
+ type: "status",
850
+ status: "processing"
851
+ }
852
+ });
853
+ } catch (error) {
854
+ throw new Error(`${label} must be a valid ISO timestamp`, { cause: error });
855
+ }
856
+ }
857
+ // src/runtime/sandbox-transport-events.ts
858
+ /** Canonical Sandbox/provider wire-envelope decoding and transport identity. */
859
+ const CANONICAL_STREAM_EVENT_TYPES = /* @__PURE__ */ new Set([
860
+ "child-task",
861
+ "message.part.updated",
862
+ "tool-heartbeat",
863
+ "tool-slow",
864
+ "model-processing",
865
+ "status",
866
+ "warning",
867
+ "raw",
868
+ "session.updated",
869
+ "interaction",
870
+ "interaction.cancel",
871
+ "plan.submitted"
872
+ ]);
873
+ /** Decode one known Agent Interface event from a Sandbox event. */
874
+ function canonicalStreamEventFromSandboxEvent(event) {
875
+ if (!event || typeof event !== "object") return void 0;
876
+ const type = String(event.type ?? "");
877
+ const data = event.data && typeof event.data === "object" ? event.data : {};
878
+ const normalized = data.normalized;
879
+ if (normalized === void 0 && !CANONICAL_STREAM_EVENT_TYPES.has(type)) return void 0;
880
+ return parseCanonicalTransportEvent(type, data, normalized, "sandbox");
881
+ }
882
+ /**
883
+ * Transport type whose payload is the harness's OWN event, passed through verbatim.
884
+ *
885
+ * A `raw` payload names a harness-native type from a vocabulary the canonical schema does not
886
+ * define (codex emits `thread.started` / `turn.started` / `turn.completed`). The transport type is
887
+ * therefore the only canonical statement such an event makes, and its payload must never be read
888
+ * as a canonical type: the mismatch guard below exists to catch a producer that MISLABELS a
889
+ * canonical event, which a harness-native payload cannot do. A payload that does satisfy the
890
+ * canonical `raw` shape (`backend` + `event`) still parses; anything else is not a canonical
891
+ * event, and the caller reads it off the transport event instead.
892
+ */
893
+ const harnessNativePayloadType = "raw";
894
+ /** Parse canonical payload fields without treating transport identity as event data. */
895
+ function parseCanonicalTransportEvent(type, data, normalized, source) {
896
+ if (!isRecord(data)) throw new Error(`${source} emitted a canonical event without an object payload`);
897
+ const outerType = String(type ?? "");
898
+ const harnessNative = outerType === harnessNativePayloadType;
899
+ if (normalized !== void 0) {
900
+ if (!harnessNative && typeof normalized === "object" && normalized !== null && "type" in normalized && typeof normalized.type === "string" && normalized.type !== outerType) throw new Error(`${source} canonical event type "${normalized.type}" does not match transport type "${outerType}"`);
901
+ const candidate = CanonicalStreamEventSchema.safeParse(normalized);
902
+ if (!candidate.success) {
903
+ if (harnessNative) return void 0;
904
+ throw new Error(`${source} emitted an invalid normalized canonical event`, { cause: candidate.error });
905
+ }
906
+ return candidate.data;
907
+ }
908
+ const { type: embeddedType, eventId: _eventId, cursor: _cursor, sequence: _sequence, occurredAt: _occurredAt, normalized: _normalized, ...payload } = data;
909
+ if (!harnessNative && embeddedType !== void 0 && embeddedType !== outerType) throw new Error(`${source} canonical event type "${String(embeddedType)}" does not match transport type "${outerType}"`);
910
+ const candidate = CanonicalStreamEventSchema.safeParse({
911
+ ...payload,
912
+ type: outerType
913
+ });
914
+ return candidate.success ? candidate.data : void 0;
915
+ }
916
+ /** Extract shared event identity without privileging one provider wire shape. */
917
+ function extractTransportEventIdentity(event) {
918
+ const record = isRecord(event) ? event : {};
919
+ const data = isRecord(record.data) ? record.data : {};
920
+ const providerEvent = isRecord(record.providerEvent) ? record.providerEvent : {};
921
+ const providerData = isRecord(providerEvent.data) ? providerEvent.data : {};
922
+ const eventId = canonicalEventId(record, data, providerEvent, providerData);
923
+ const cursor = stableString(record.cursor ?? data.cursor ?? providerEvent.cursor ?? providerData.cursor);
924
+ const sequence = optionalSequence(record.sequence ?? data.sequence ?? providerEvent.sequence ?? providerData.sequence);
925
+ const occurredAt = optionalTimestamp(record.occurredAt ?? data.occurredAt ?? providerEvent.occurredAt ?? providerData.occurredAt);
926
+ return {
927
+ ...eventId === void 0 ? {} : { eventId },
928
+ ...cursor === void 0 ? {} : { cursor },
929
+ ...sequence === void 0 ? {} : { sequence },
930
+ ...occurredAt === void 0 ? {} : { occurredAt }
931
+ };
932
+ }
933
+ function canonicalEventId(record, data, providerEvent, providerData) {
934
+ const present = [
935
+ ["data.eventId", data.eventId],
936
+ ["providerEvent.eventId", providerEvent.eventId],
937
+ ["providerData.eventId", providerData.eventId],
938
+ ["record.eventId", record.eventId]
939
+ ].filter(([, value]) => value !== void 0);
940
+ if (present.length === 0) return stableString(record.id ?? providerEvent.id);
941
+ const normalized = present.map(([source, value]) => {
942
+ const eventId = stableString(value);
943
+ if (eventId === void 0) throw new Error(`transport event ${source} must be a stable string`);
944
+ return {
945
+ source,
946
+ eventId
947
+ };
948
+ });
949
+ const first = normalized[0];
950
+ if (normalized.some((candidate) => candidate.eventId !== first.eventId)) throw new Error("transport event canonical identities disagree");
951
+ return first.eventId;
952
+ }
953
+ function stableString(value) {
954
+ return typeof value === "string" && value.length > 0 && value.trim() === value ? value : void 0;
955
+ }
956
+ function finiteNonNegativeInteger(value) {
957
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
958
+ }
959
+ function optionalSequence(value) {
960
+ if (value === void 0) return void 0;
961
+ if (finiteNonNegativeInteger(value) === void 0) throw new Error("transport event sequence must be a non-negative safe integer");
962
+ return value;
963
+ }
964
+ function optionalTimestamp(value) {
965
+ if (value === void 0) return void 0;
966
+ assertRuntimeTimestamp(value, "occurredAt");
967
+ return value;
968
+ }
969
+ // src/runtime/sandbox-executor-output.ts
970
+ /** Streamed and terminal Sandbox executor output, using one tool-part projector. */
971
+ /**
972
+ * Fresh per-turn {@link SandboxToolPartState} for {@link mapSandboxToolEvent} — an
973
+ * empty call-status map so each turn projects tool frames independently.
974
+ *
975
+ * @experimental
976
+ */
977
+ function createSandboxToolPartState() {
978
+ return {
979
+ statusByCall: /* @__PURE__ */ new Map(),
980
+ seq: 0
981
+ };
982
+ }
983
+ /** Statuses that settle one tool call as a failure. A failed tool call stays a tool result:
984
+ * the run's terminal state comes from the public Sandbox outcome tracker, never from here. */
985
+ const TERMINAL_FAILURE = /^(error|errored|failed|failure|cancelled|canceled|timeout|timed_out)$/i;
986
+ /**
987
+ * Project one `SandboxEvent` onto the `tool_call` / `tool_result` variants of
988
+ * `RuntimeStreamEvent` — the tool-part projection `mapSandboxEvent`
989
+ * deliberately does NOT perform. Opt-in and additive: `mapSandboxEvent`'s
990
+ * default vocabulary (text/reasoning deltas + `llm_call`) is unchanged;
991
+ * consumers that need the tool surface (chat UIs rendering tool activity)
992
+ * compose this projector alongside it — `streamAgentTurn` does exactly that
993
+ * under its `preserveToolParts` option.
994
+ *
995
+ * Handled shapes (observed on the opencode / claude-code sandbox backends):
996
+ * - `message.part.updated` with `part.type === 'tool'` — stateful: a
997
+ * `tool_call` on the call id's first frame (args from `state.input` or
998
+ * `state.metadata.input`), a `tool_result` when the status transitions to
999
+ * `completed` (result from `state.output` / `metadata.output`) or to a
1000
+ * terminal failure (result is `{ error, status, output? }` — the error
1001
+ * surfaced in-band, never dropped).
1002
+ * - bare `tool*` event types (`tool.call`, `tool_result`, …) — stateless:
1003
+ * `*result*` types project to `tool_result`, the rest to `tool_call`.
1004
+ * - codex `raw` events whose inner `item.started` / `item.updated` /
1005
+ * `item.completed` carries a command, MCP, collaboration, web search or
1006
+ * file change item — stateful on the item id, like a tool part. Other raw
1007
+ * events, including opencode's raw `tool_use` echoes, project nothing.
1008
+ *
1009
+ * Returns `[]` for every non-tool event.
1010
+ *
1011
+ * @experimental
1012
+ */
1013
+ function mapSandboxToolEvent(event, state) {
1014
+ if (!event || typeof event !== "object") return [];
1015
+ const type = String(event.type ?? "");
1016
+ const data = event.data && typeof event.data === "object" ? event.data : {};
1017
+ if (type === "message.part.updated") {
1018
+ const part = data.part && typeof data.part === "object" ? data.part : {};
1019
+ if (String(part.type ?? "") !== "tool") return [];
1020
+ return projectToolPart(part, state, typeof event.id === "string" ? event.id : void 0);
1021
+ }
1022
+ if (type === "raw") return projectCodexItem(data, state);
1023
+ if (CANONICAL_STREAM_EVENT_TYPES.has(type)) return [];
1024
+ if (type.includes("tool")) {
1025
+ const callId = pickString(data, [
1026
+ "toolCallId",
1027
+ "tool_use_id",
1028
+ "id"
1029
+ ]) ?? (typeof event.id === "string" ? event.id : void 0) ?? `sandbox-tool-${++state.seq}`;
1030
+ const toolName = pickString(data, [
1031
+ "name",
1032
+ "toolName",
1033
+ "tool"
1034
+ ]) ?? "sandbox_tool";
1035
+ if (type.includes("result")) return [{
1036
+ type: "tool_result",
1037
+ toolName,
1038
+ toolCallId: callId,
1039
+ result: data.output ?? data.result ?? data.content ?? data
1040
+ }];
1041
+ return [{
1042
+ type: "tool_call",
1043
+ toolName,
1044
+ toolCallId: callId,
1045
+ args: data.input ?? data.args ?? {}
1046
+ }];
1047
+ }
1048
+ return [];
1049
+ }
1050
+ function projectToolPart(part, state, eventId) {
1051
+ const callId = pickString(part, [
1052
+ "callID",
1053
+ "callId",
1054
+ "toolCallId",
1055
+ "id"
1056
+ ]) ?? eventId ?? `sandbox-tool-${++state.seq}`;
1057
+ const toolName = pickString(part, [
1058
+ "tool",
1059
+ "toolName",
1060
+ "name"
1061
+ ]) ?? "sandbox_tool";
1062
+ const toolState = part.state && typeof part.state === "object" ? part.state : {};
1063
+ const metadata = toolState.metadata && typeof toolState.metadata === "object" ? toolState.metadata : {};
1064
+ const status = pickString(toolState, ["status"]) ?? "updated";
1065
+ const previous = state.statusByCall.get(callId);
1066
+ if (previous === "completed" || previous !== void 0 && TERMINAL_FAILURE.test(previous)) return [];
1067
+ const out = [];
1068
+ if (previous === void 0) out.push({
1069
+ type: "tool_call",
1070
+ toolName,
1071
+ toolCallId: callId,
1072
+ args: toolState.input ?? metadata.input ?? {}
1073
+ });
1074
+ state.statusByCall.set(callId, status);
1075
+ if (status === "completed") out.push({
1076
+ type: "tool_result",
1077
+ toolName,
1078
+ toolCallId: callId,
1079
+ result: toolState.output ?? metadata.output ?? ""
1080
+ });
1081
+ else if (TERMINAL_FAILURE.test(status)) {
1082
+ const message = pickString(toolState, ["error", "message"]) ?? pickString(metadata, ["error", "message"]) ?? `sandbox tool ended with status ${status}`;
1083
+ const output = toolState.output ?? metadata.output;
1084
+ out.push({
1085
+ type: "tool_result",
1086
+ toolName,
1087
+ toolCallId: callId,
1088
+ result: {
1089
+ error: message,
1090
+ status,
1091
+ ...output !== void 0 ? { output } : {}
1092
+ }
1093
+ });
1094
+ }
1095
+ return out;
1096
+ }
1097
+ /** Codex item types that are tool calls. Reasoning, messages and todo lists are not. */
1098
+ const CODEX_TOOL_ITEMS = /* @__PURE__ */ new Set([
1099
+ "command_execution",
1100
+ "mcp_tool_call",
1101
+ "collab_tool_call",
1102
+ "web_search",
1103
+ "file_change"
1104
+ ]);
1105
+ /** Item fields that describe the call's progress or outcome rather than what it was asked to do. */
1106
+ const CODEX_ITEM_OUTCOME_FIELDS = /* @__PURE__ */ new Set([
1107
+ "id",
1108
+ "type",
1109
+ "status",
1110
+ "result",
1111
+ "error",
1112
+ "aggregated_output",
1113
+ "exit_code"
1114
+ ]);
1115
+ /**
1116
+ * Project a codex `item.started` / `item.updated` / `item.completed` tool item through the same
1117
+ * per-call state as a tool part, keyed on the item id: one `tool_call` on its first frame and one
1118
+ * `tool_result` when it completes. Tool names follow Eval's codex intake: `server/tool` for MCP.
1119
+ */
1120
+ function projectCodexItem(data, state) {
1121
+ if (data.backend !== "codex" || !data.event || typeof data.event !== "object") return [];
1122
+ const inner = data.event;
1123
+ const phase = inner.type;
1124
+ if (phase !== "item.started" && phase !== "item.updated" && phase !== "item.completed") return [];
1125
+ if (!inner.item || typeof inner.item !== "object") return [];
1126
+ const item = inner.item;
1127
+ const itemType = pickString(item, ["type"]);
1128
+ if (itemType === void 0 || !CODEX_TOOL_ITEMS.has(itemType)) return [];
1129
+ const error = item.error && typeof item.error === "object" ? pickString(item.error, ["message"]) ?? `${itemType} failed` : void 0;
1130
+ const failed = item.status === "failed" || error !== void 0 || itemType === "command_execution" && typeof item.exit_code === "number" && item.exit_code !== 0;
1131
+ const status = phase !== "item.completed" ? "running" : failed ? "failed" : "completed";
1132
+ const input = Object.fromEntries(Object.entries(item).filter(([key]) => !CODEX_ITEM_OUTCOME_FIELDS.has(key)));
1133
+ const output = item.result ?? item.aggregated_output ?? item.changes;
1134
+ return projectToolPart({
1135
+ ...typeof item.id === "string" ? { callID: item.id } : {},
1136
+ tool: codexToolName(itemType, item),
1137
+ state: {
1138
+ status,
1139
+ input,
1140
+ ...output === void 0 || output === null ? {} : { output },
1141
+ ...status === "failed" ? { error: error ?? `${itemType} failed` } : {}
1142
+ }
1143
+ }, state, void 0);
1144
+ }
1145
+ function codexToolName(itemType, item) {
1146
+ if (itemType === "mcp_tool_call") {
1147
+ const name = [pickString(item, ["server"]), pickString(item, ["tool"])].filter((part) => part !== void 0).join("/");
1148
+ return name === "" ? "mcp" : name;
1149
+ }
1150
+ if (itemType === "collab_tool_call") return pickString(item, ["tool"]) ?? "subagent";
1151
+ if (itemType === "web_search" || itemType === "file_change") return itemType;
1152
+ return pickString(item, ["name"]) ?? itemType;
1153
+ }
1154
+ function pickString(data, keys) {
1155
+ for (const key of keys) {
1156
+ const value = data[key];
1157
+ if (typeof value === "string" && value.length > 0) return value;
1158
+ }
1159
+ }
1160
+ /**
1161
+ * Project one `SandboxEvent` onto the `RuntimeStreamEvent` chat-UX vocabulary,
1162
+ * for runtimes that bridge a sandbox `streamPrompt` into the
1163
+ * `AgentRuntime.act` streaming contract. Returns `undefined` for events that
1164
+ * have no faithful projection — the raw stream is preserved separately for the
1165
+ * `OutputAdapter`, so an unmapped event never loses data.
1166
+ *
1167
+ * Mapped (the task-optional incremental variants — no synthesized task
1168
+ * lifecycle, no guessed tool-part shapes):
1169
+ * - `message.part.updated` text part → `text_delta`
1170
+ * - `message.part.updated` reasoning/thinking part → `reasoning_delta`
1171
+ * - cost-bearing events → `llm_call` (shared with the ledger extractor)
1172
+ *
1173
+ * Tool parts are deliberately NOT mapped here (unchanged default) — compose
1174
+ * {@link mapSandboxToolEvent} alongside when a consumer needs them.
1175
+ *
1176
+ * The opencode backend emits incremental text as
1177
+ * `{ type: 'message.part.updated', data: { part: { type, text }, delta } }`;
1178
+ * `delta` is the increment, `part.text` the running accumulation.
1179
+ */
1180
+ function mapSandboxEvent(event, opts = {}) {
1181
+ if (!event || typeof event !== "object") return void 0;
1182
+ const type = String(event.type ?? "");
1183
+ const data = event.data && typeof event.data === "object" ? event.data : {};
1184
+ if (type === "message.part.updated") {
1185
+ const part = data.part && typeof data.part === "object" ? data.part : {};
1186
+ const partType = String(part.type ?? "");
1187
+ const text = (typeof data.delta === "string" ? data.delta : void 0) ?? (typeof part.text === "string" ? part.text : void 0);
1188
+ if (text === void 0) return void 0;
1189
+ if (partType === "text") return {
1190
+ type: "text_delta",
1191
+ text
1192
+ };
1193
+ if (partType === "reasoning" || partType === "thinking") return {
1194
+ type: "reasoning_delta",
1195
+ text
1196
+ };
1197
+ return;
1198
+ }
1199
+ return extractLlmCallEvent(event, opts.agentRunName ?? "agent");
1200
+ }
1201
+ /**
1202
+ * Project one `SandboxEvent` onto Runtime's executor progress vocabulary: incremental text and
1203
+ * reasoning, tool calls and results, and an interaction request. It composes the existing
1204
+ * projections ({@link mapSandboxEvent}, {@link mapSandboxToolEvent}, and the canonical Agent
1205
+ * Interface decode) so every sandbox-shaped executor publishes live output through one reader.
1206
+ * Usage-bearing events project to nothing here — accounting stays on the `tokens`/`cost`
1207
+ * channels.
1208
+ *
1209
+ * Pass one {@link SandboxToolPartState} per turn so a multi-frame tool call yields one call and
1210
+ * at most one result.
1211
+ *
1212
+ * @experimental
1213
+ */
1214
+ function sandboxProgressEvents(event, state) {
1215
+ const canonical = canonicalStreamEventFromSandboxEvent(event);
1216
+ if (canonical?.type === "interaction") return [{
1217
+ kind: "interaction",
1218
+ request: canonical.request
1219
+ }];
1220
+ if (canonical?.type === "child-task") return [{
1221
+ kind: "child_task",
1222
+ event: canonical
1223
+ }];
1224
+ const tools = mapSandboxToolEvent(event, state).map((projected) => projected.type === "tool_call" ? {
1225
+ kind: "tool_call",
1226
+ toolName: projected.toolName,
1227
+ ...projected.toolCallId === void 0 ? {} : { toolCallId: projected.toolCallId },
1228
+ ...projected.args === void 0 ? {} : { args: projected.args }
1229
+ } : {
1230
+ kind: "tool_result",
1231
+ toolName: projected.toolName,
1232
+ ...projected.toolCallId === void 0 ? {} : { toolCallId: projected.toolCallId },
1233
+ ...projected.result === void 0 ? {} : { result: projected.result }
1234
+ });
1235
+ if (tools.length > 0) return tools;
1236
+ const mapped = mapSandboxEvent(event);
1237
+ if (mapped?.type === "text_delta") return [{
1238
+ kind: "text_delta",
1239
+ text: mapped.text
1240
+ }];
1241
+ if (mapped?.type === "reasoning_delta") return [{
1242
+ kind: "reasoning_delta",
1243
+ text: mapped.text
1244
+ }];
1245
+ return [];
1246
+ }
1247
+ /** Project the complete Sandbox event stream into the standard executor result shape. */
1248
+ function sandboxLeafOutputFromEvents(events) {
1249
+ const content = collectAgentFinalMessageText(events) ?? collectAgentResponseText(events);
1250
+ const toolCalls = sandboxToolCalls(events);
1251
+ const servedBackend = lastServedBackend(events);
1252
+ return {
1253
+ events,
1254
+ content,
1255
+ output: sandboxOutputMarker(content, events.some(carriesText)),
1256
+ ...servedBackend === void 0 ? {} : { servedBackend },
1257
+ ...toolCalls.length === 0 ? {} : { toolCalls }
1258
+ };
1259
+ }
1260
+ /**
1261
+ * Classify observed text into the explicit output marker. `sawTextEvent` says whether the stream
1262
+ * carried a text-bearing event at all, which is what separates a box that answered nothing from a
1263
+ * box whose answer was never observed.
1264
+ */
1265
+ function sandboxOutputMarker(content, sawTextEvent = content !== void 0) {
1266
+ if (content !== void 0 && content.length > 0) return {
1267
+ kind: "text",
1268
+ bytes: Buffer.byteLength(content, "utf8")
1269
+ };
1270
+ return sawTextEvent ? { kind: "empty" } : { kind: "absent" };
1271
+ }
1272
+ /** True when the event carries a text field a turn's answer could come from, empty or not. */
1273
+ function carriesText(event) {
1274
+ if (!event || typeof event !== "object") return false;
1275
+ const data = event.data && typeof event.data === "object" ? event.data : {};
1276
+ if (typeof data.finalText === "string" || typeof data.text === "string") return true;
1277
+ if (typeof data.delta === "string") return true;
1278
+ const part = data.part && typeof data.part === "object" ? data.part : void 0;
1279
+ return part !== void 0 && part.type === "text" && typeof part.text === "string";
1280
+ }
1281
+ /** The last served identity the platform reported across a turn's events, or `undefined`. */
1282
+ function lastServedBackend(events) {
1283
+ let served;
1284
+ for (const event of events) {
1285
+ const next = sandboxEventServedBackend(event);
1286
+ if (next !== void 0) served = next;
1287
+ }
1288
+ return served;
1289
+ }
1290
+ function sandboxToolCalls(events) {
1291
+ const state = createSandboxToolPartState();
1292
+ return events.flatMap((event) => mapSandboxToolEvent(event, state).flatMap((projected) => projected.type === "tool_call" ? [{
1293
+ ...projected.toolCallId === void 0 ? {} : { id: projected.toolCallId },
1294
+ name: projected.toolName,
1295
+ arguments: projected.args ?? {}
1296
+ }] : []));
1297
+ }
1298
+ /** Read the final text off a terminal sandbox event, when present. */
1299
+ function terminalTextFromSandboxEvent(event) {
1300
+ if (!event || typeof event !== "object") return void 0;
1301
+ if (!isSandboxTerminalEvent(String(event.type ?? ""))) return void 0;
1302
+ const data = event.data && typeof event.data === "object" ? event.data : {};
1303
+ for (const key of [
1304
+ "finalText",
1305
+ "text",
1306
+ "response",
1307
+ "content"
1308
+ ]) {
1309
+ const value = data[key];
1310
+ if (typeof value === "string") return value;
1311
+ }
1312
+ }
1313
+ // src/runtime/supervise/spend-validation.ts
1314
+ /** Reject malformed ceilings before they can mint capacity through negative reservations. */
1315
+ function assertValidBudget(budget, label = "budget") {
1316
+ const safeInteger = (value, field) => {
1317
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${label}.${field} must be a non-negative safe integer`);
1318
+ };
1319
+ const finiteNonNegative = (value, field) => {
1320
+ if (!Number.isFinite(value) || value < 0) throw new Error(`${label}.${field} must be a non-negative finite number`);
1321
+ };
1322
+ assertResources(budget.resources, "limit", `${label}.resources`);
1323
+ if (budget.maxIterations !== void 0) safeInteger(budget.maxIterations, "maxIterations");
1324
+ if (budget.maxTokens !== void 0) safeInteger(budget.maxTokens, "maxTokens");
1325
+ if (budget.maxUsd !== void 0) finiteNonNegative(budget.maxUsd, "maxUsd");
1326
+ if (budget.deadlineMs !== void 0) finiteNonNegative(budget.deadlineMs, "deadlineMs");
1327
+ }
1328
+ function assertValidSpend(spend, label) {
1329
+ assertResources(spend.resources, "amount", `${label}.resources`);
1330
+ if (!Number.isSafeInteger(spend.iterations) || spend.iterations < 0) throw new Error(`${label}.iterations must be a non-negative safe integer`);
1331
+ for (const [field, value] of [
1332
+ ["input", spend.tokens.input],
1333
+ ["output", spend.tokens.output],
1334
+ ["freshInput", spend.tokens.freshInput],
1335
+ ["cacheRead", spend.tokens.cacheRead],
1336
+ ["cacheWrite", spend.tokens.cacheWrite]
1337
+ ]) {
1338
+ if (value === void 0) continue;
1339
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${label}.tokens.${field} must be a non-negative safe integer`);
1340
+ }
1341
+ for (const [field, value] of [["tokensKnown", spend.tokens.tokensKnown], ["cacheBreakdownKnown", spend.tokens.cacheBreakdownKnown]]) if (value !== void 0 && value !== false) throw new Error(`${label}.tokens.${field} must be false when present`);
1342
+ const { freshInput, cacheRead, cacheWrite } = spend.tokens;
1343
+ if (freshInput !== void 0 && cacheRead !== void 0 && cacheWrite !== void 0) {
1344
+ const classified = freshInput + cacheRead + cacheWrite;
1345
+ if (spend.tokens.cacheBreakdownKnown !== false) {
1346
+ if (classified !== spend.tokens.input) throw new Error(`${label}.tokens cache classes must sum to input`);
1347
+ } else if (classified > spend.tokens.input) throw new Error(`${label}.tokens cache classes must not exceed input`);
1348
+ }
1349
+ for (const [field, value] of [["usd", spend.usd], ["ms", spend.ms]]) if (!Number.isFinite(value) || value < 0) throw new Error(`${label}.${field} must be a non-negative finite number`);
1350
+ if (spend.usdEstimated !== void 0) {
1351
+ if (!Number.isFinite(spend.usdEstimated) || spend.usdEstimated < 0) throw new Error(`${label}.usdEstimated must be a non-negative finite number`);
1352
+ if (spend.usdEstimated > spend.usd) throw new Error(`${label}.usdEstimated must not exceed ${label}.usd`);
1353
+ if (spend.usdKnown !== false) throw new Error(`${label}.usdEstimated requires ${label}.usdKnown false`);
1354
+ }
1355
+ }
1356
+ // src/runtime/supervise/budget-ledger.ts
1357
+ /**
1358
+ * The balances of one conserved budget pool, and the arithmetic that moves them. `createBudgetPool`
1359
+ * (`./budget`) owns tickets, the wait queue and the public contract; this module owns the numbers:
1360
+ * `total ≡ free + reserved + committed` per channel, the taint flags that say a balance is a
1361
+ * ceiling rather than a measurement, and the named-resource states.
1362
+ */
1363
+ function openBudgetLedger(root, runStartedAtMs) {
1364
+ return {
1365
+ tokensCapped: root.maxTokens !== void 0,
1366
+ iterationsCapped: root.maxIterations !== void 0,
1367
+ usdCapped: root.maxUsd !== void 0,
1368
+ absoluteDeadlineMs: root.deadlineMs === void 0 ? 0 : runStartedAtMs + root.deadlineMs,
1369
+ resources: new Map(Object.entries(root.resources ?? {}).map(([name, value]) => [name, {
1370
+ ...value,
1371
+ remaining: value.limit,
1372
+ reserved: 0,
1373
+ committed: 0,
1374
+ known: true
1375
+ }])),
1376
+ freeTokens: root.maxTokens ?? 0,
1377
+ reservedTokens: 0,
1378
+ committedTokens: 0,
1379
+ tokensTainted: false,
1380
+ cacheBreakdownTainted: false,
1381
+ freeUsd: root.maxUsd ?? 0,
1382
+ reservedUsd: 0,
1383
+ committedUsd: 0,
1384
+ usdTainted: false,
1385
+ usdMeasured: true,
1386
+ freeIterations: root.maxIterations ?? 0,
1387
+ reservedIterations: 0,
1388
+ committedIterations: 0,
1389
+ ownerSpent: {
1390
+ iterations: 0,
1391
+ tokens: zeroTokenUsage(),
1392
+ usd: 0,
1393
+ ms: 0
1394
+ }
1395
+ };
1396
+ }
1397
+ function ledgerValidateUnits(l, spend) {
1398
+ for (const [name, value] of Object.entries(spend.resources ?? {})) {
1399
+ const limit = l.resources.get(name);
1400
+ if (limit && limit.unit !== value.unit) throw new Error(`resource ${name}: unit mismatch`);
1401
+ }
1402
+ }
1403
+ /** Record that `spend` carried an unreported or unclassified channel. */
1404
+ function noteUnknowns(l, spend) {
1405
+ if (spend.tokensKnown === false) l.tokensTainted = true;
1406
+ if (!hasCompleteCacheBreakdown(spend.tokens)) l.cacheBreakdownTainted = true;
1407
+ if (spend.usdKnown === false) l.usdMeasured = false;
1408
+ }
1409
+ /**
1410
+ * Commit named-resource spend and classify it. `allocations` is the settling reservation's own
1411
+ * allocations, or `undefined` for spend holding no reservation (`observe`, restore). Unverifiable
1412
+ * usage is a `fault` (the remaining balance is consumed so admission closes); measured usage above
1413
+ * an allocation is `overspent`; without allocations, usage leaving a root limit overdrawn is
1414
+ * `rootExceeded`. A reservation within its own allocation is never charged with a root overdraw:
1415
+ * a negative balance at its settlement was caused, and reported, by earlier spend.
1416
+ */
1417
+ function ledgerCommitResources(l, spend, allocations, requireAll = true) {
1418
+ let fault;
1419
+ let rootExceeded;
1420
+ const overspent = [];
1421
+ for (const [name, state] of l.resources) {
1422
+ const value = spend.resources?.[name];
1423
+ if (!requireAll && value === void 0) continue;
1424
+ const allocation = allocations?.[name]?.limit ?? 0;
1425
+ const amount = value?.amount ?? 0;
1426
+ state.reserved -= allocation;
1427
+ const committed = state.committed + amount;
1428
+ const overflow = !Number.isSafeInteger(committed);
1429
+ state.committed = Math.min(committed, Number.MAX_SAFE_INTEGER);
1430
+ state.remaining = state.limit - state.reserved - state.committed;
1431
+ if (value?.known !== true || overflow) {
1432
+ state.known = false;
1433
+ const retained = Math.max(0, state.remaining);
1434
+ state.committed += retained;
1435
+ state.remaining -= retained;
1436
+ fault ??= overflow ? `resource ${name}: amount overflow under an enforced limit` : `resource ${name}: unknown usage under an enforced limit`;
1437
+ } else if (allocations !== void 0) {
1438
+ if (amount > allocation) overspent.push({
1439
+ channel: `resource:${name}`,
1440
+ reserved: allocation,
1441
+ spent: amount
1442
+ });
1443
+ } else if (state.remaining < 0) rootExceeded ??= `resource ${name}: exceeded root limit ${state.limit}`;
1444
+ }
1445
+ return {
1446
+ ...fault ? { fault } : {},
1447
+ overspent,
1448
+ ...rootExceeded ? { rootExceeded } : {}
1449
+ };
1450
+ }
1451
+ /** Every channel `b` does not fit, measured against the free balance less `keep`. */
1452
+ function ledgerShortfalls(l, b, keep) {
1453
+ const wantTokens = b.maxTokens ?? 0;
1454
+ const wantUsd = b.maxUsd ?? 0;
1455
+ const wantIterations = b.maxIterations ?? 0;
1456
+ const shortfalls = [];
1457
+ const short = (channel, requested, free, held, closedByUnknownSpend = false) => {
1458
+ shortfalls.push({
1459
+ channel,
1460
+ requested,
1461
+ free: closedByUnknownSpend ? 0 : Math.max(0, free),
1462
+ ...closedByUnknownSpend || held <= 0 ? {} : { held },
1463
+ ...closedByUnknownSpend ? { closedByUnknownSpend: true } : {}
1464
+ });
1465
+ };
1466
+ for (const [name, state] of l.resources) {
1467
+ const limit = b.resources[name].limit;
1468
+ if (!state.known) short(`resource:${name}`, limit, 0, 0, true);
1469
+ else if (limit > state.remaining) short(`resource:${name}`, limit, state.remaining, state.reserved);
1470
+ }
1471
+ if (l.usdCapped && l.usdTainted) short("usd", wantUsd, 0, 0, true);
1472
+ const kept = (share = 0, spent) => Math.max(0, share - spent);
1473
+ const tokensFree = l.freeTokens - kept(keep?.tokens, chargedTokens(l.ownerSpent.tokens));
1474
+ const iterationsFree = l.freeIterations - kept(keep?.iterations, l.ownerSpent.iterations);
1475
+ if (l.tokensCapped && wantTokens > tokensFree) short("tokens", wantTokens, tokensFree, l.reservedTokens);
1476
+ if (l.iterationsCapped && wantIterations > iterationsFree) short("iterations", wantIterations, iterationsFree, l.reservedIterations);
1477
+ const usdFree = l.freeUsd - kept(keep?.usd, l.ownerSpent.usd);
1478
+ if (l.usdCapped && !l.usdTainted && wantUsd > usdFree) short("usd", wantUsd, usdFree, l.reservedUsd);
1479
+ return shortfalls;
1480
+ }
1481
+ /** Move `b` from free to reserved. The caller has checked that it fits. */
1482
+ function ledgerTake(l, b) {
1483
+ for (const [name, state] of l.resources) {
1484
+ const amount = b.resources[name].limit;
1485
+ state.remaining -= amount;
1486
+ state.reserved += amount;
1487
+ }
1488
+ if (l.tokensCapped) {
1489
+ l.freeTokens -= b.maxTokens ?? 0;
1490
+ l.reservedTokens += b.maxTokens ?? 0;
1491
+ }
1492
+ if (l.iterationsCapped) {
1493
+ l.freeIterations -= b.maxIterations ?? 0;
1494
+ l.reservedIterations += b.maxIterations ?? 0;
1495
+ }
1496
+ l.freeUsd -= b.maxUsd ?? 0;
1497
+ l.reservedUsd += b.maxUsd ?? 0;
1498
+ }
1499
+ /**
1500
+ * The overspends a settlement of `spent` against `held` decides, before any balance moves. An
1501
+ * OVERSPEND is measured spend above the reservation; unknown dollars under a dollar cap (a fault
1502
+ * the caller reports) are flagged `unknownUnderCap`. `usdBudgeted` is whether the child declared a
1503
+ * dollar ceiling: without `maxUsd` it reserved NO dollars, so under a capped root its dollars are
1504
+ * OBSERVED spend, committed and debited from `free` like `observe`d inference.
1505
+ */
1506
+ function ledgerClassifyOverspend(l, held, usdBudgeted, spent, limits) {
1507
+ const unknownUnderCap = l.usdCapped && spent.usdKnown === false;
1508
+ const spentTokens = chargedTokens(spent.tokens);
1509
+ const overspent = [];
1510
+ const tokens = limits === void 0 ? held.tokens : limits.maxTokens;
1511
+ const iterations = limits === void 0 ? held.iterations : limits.maxIterations;
1512
+ if (tokens !== void 0 && spentTokens > tokens) overspent.push({
1513
+ channel: "tokens",
1514
+ reserved: tokens,
1515
+ spent: spentTokens
1516
+ });
1517
+ if (iterations !== void 0 && spent.iterations > iterations) overspent.push({
1518
+ channel: "iterations",
1519
+ reserved: iterations,
1520
+ spent: spent.iterations
1521
+ });
1522
+ if (!unknownUnderCap && l.usdCapped && usdBudgeted && spent.usd > held.usd) overspent.push({
1523
+ channel: "usd",
1524
+ reserved: held.usd,
1525
+ spent: spent.usd
1526
+ });
1527
+ for (const name of l.resources.keys()) {
1528
+ const value = spent.resources?.[name];
1529
+ const limit = held.resources?.[name]?.limit ?? 0;
1530
+ if (value?.known && value.amount > limit) overspent.push({
1531
+ channel: `resource:${name}`,
1532
+ reserved: limit,
1533
+ spent: value.amount
1534
+ });
1535
+ }
1536
+ return {
1537
+ overspent,
1538
+ unknownUnderCap
1539
+ };
1540
+ }
1541
+ /**
1542
+ * Release the whole reservation `held`, then commit actual spend; the difference is the refund
1543
+ * that flows back to `free`. Unconditional arithmetic: nothing here throws on spend it can read.
1544
+ */
1545
+ function ledgerSettle(l, held, spent, unknownUnderCap) {
1546
+ noteUnknowns(l, spent);
1547
+ const spentTokens = chargedTokens(spent.tokens);
1548
+ l.committedTokens += spentTokens;
1549
+ if (l.tokensCapped) {
1550
+ l.reservedTokens -= held.tokens;
1551
+ l.freeTokens += held.tokens - spentTokens;
1552
+ }
1553
+ l.committedIterations += spent.iterations;
1554
+ if (l.iterationsCapped) {
1555
+ l.reservedIterations -= held.iterations;
1556
+ l.freeIterations += held.iterations - spent.iterations;
1557
+ }
1558
+ if (l.usdCapped) {
1559
+ l.reservedUsd -= held.usd;
1560
+ l.committedUsd += spent.usd;
1561
+ if (unknownUnderCap) {
1562
+ l.usdTainted = true;
1563
+ l.freeUsd = 0;
1564
+ } else l.freeUsd += held.usd - spent.usd;
1565
+ } else l.committedUsd += spent.usd;
1566
+ return ledgerCommitResources(l, spent, held.resources ?? {});
1567
+ }
1568
+ /**
1569
+ * Direct free → committed debit (no ticket). `free` may go negative on overspend: the readout then
1570
+ * reports exhaustion and the in-loop guard halts the driver. Work with an unreported token count
1571
+ * still debits what IS known and marks the balance incomplete; refusing to record it is the "free
1572
+ * turn" the pool must never see.
1573
+ */
1574
+ function ledgerObserve(l, spend, unknownUnderCap, requireAllResources) {
1575
+ debit(l, spend);
1576
+ l.ownerSpent = addSpend(l.ownerSpent, spend);
1577
+ if (unknownUnderCap) l.usdTainted = true;
1578
+ return ledgerCommitResources(l, spend, void 0, requireAllResources);
1579
+ }
1580
+ /** Move measured `spend` from free to committed on the token, iteration and dollar channels. */
1581
+ function debit(l, spend) {
1582
+ noteUnknowns(l, spend);
1583
+ const tokens = chargedTokens(spend.tokens);
1584
+ if (l.tokensCapped) l.freeTokens -= tokens;
1585
+ l.committedTokens += tokens;
1586
+ if (l.iterationsCapped) l.freeIterations -= spend.iterations;
1587
+ l.committedIterations += spend.iterations;
1588
+ l.committedUsd += spend.usd;
1589
+ if (l.usdCapped) l.freeUsd -= spend.usd;
1590
+ }
1591
+ /**
1592
+ * Reconstruct the balances from a prior process's durable record. Measured prior spend is debited
1593
+ * exactly once; a started-without-terminal child is charged at its entire reservation, so restart
1594
+ * never mints capacity and the false known flags stay visible. Direct arithmetic, not `observe`:
1595
+ * the prior spend ALREADY happened, and refusing to record it would be a zero-cost restart.
1596
+ */
1597
+ function ledgerRestore(l, root, restore) {
1598
+ for (const held of restore.heldReservations ?? []) {
1599
+ assertValidBudget(held, "restored remaining reservation");
1600
+ const tokens = held.maxTokens ?? 0;
1601
+ const iterations = held.maxIterations ?? 0;
1602
+ const usd = held.maxUsd ?? 0;
1603
+ l.committedTokens += tokens;
1604
+ l.committedIterations += iterations;
1605
+ l.committedUsd += usd;
1606
+ if (l.tokensCapped) l.freeTokens -= tokens;
1607
+ if (l.iterationsCapped) l.freeIterations -= iterations;
1608
+ if (l.usdCapped) l.freeUsd -= usd;
1609
+ if (tokens > 0) l.tokensTainted = true;
1610
+ if (usd > 0) l.usdMeasured = false;
1611
+ for (const [name, value] of Object.entries(held.resources ?? {})) {
1612
+ const resource = l.resources.get(name);
1613
+ if (!resource || resource.unit !== value.unit) throw new Error(`restored reservation resource ${name}: unit mismatch`);
1614
+ resource.committed += value.limit;
1615
+ resource.remaining -= value.limit;
1616
+ if (value.limit > 0) resource.known = false;
1617
+ }
1618
+ }
1619
+ if (restore.owner) l.ownerSpent = addSpend(l.ownerSpent, restore.owner);
1620
+ if (restore.committed !== void 0) {
1621
+ const committed = restore.committed;
1622
+ assertValidSpend(committed, "budget restore committed");
1623
+ ledgerValidateUnits(l, committed);
1624
+ ledgerCommitResources(l, committed);
1625
+ debit(l, committed);
1626
+ if (l.usdCapped && committed.usdKnown === false) {
1627
+ l.usdTainted = true;
1628
+ if (l.freeUsd > 0) l.committedUsd += l.freeUsd;
1629
+ l.freeUsd = 0;
1630
+ }
1631
+ }
1632
+ for (const [index, uncertain] of (restore.uncertainReservations ?? []).entries()) {
1633
+ assertValidBudget(uncertain, `budget restore uncertainReservations[${index}]`);
1634
+ ledgerCommitResources(l, withBudgetResources({
1635
+ iterations: 0,
1636
+ tokens: zeroTokenUsage(),
1637
+ usd: 0,
1638
+ ms: 0
1639
+ }, root));
1640
+ l.tokensTainted = true;
1641
+ l.usdMeasured = false;
1642
+ const tokens = uncertain.maxTokens ?? (l.tokensCapped ? Math.max(0, l.freeTokens) : 0);
1643
+ const iterations = uncertain.maxIterations ?? (l.iterationsCapped ? Math.max(0, l.freeIterations) : 0);
1644
+ l.committedTokens += tokens;
1645
+ l.committedIterations += iterations;
1646
+ if (l.tokensCapped) l.freeTokens -= tokens;
1647
+ if (l.iterationsCapped) l.freeIterations -= iterations;
1648
+ if (!l.usdCapped) continue;
1649
+ if (uncertain.maxUsd === void 0) {
1650
+ l.usdTainted = true;
1651
+ l.committedUsd += Math.max(0, l.freeUsd);
1652
+ l.freeUsd = 0;
1653
+ } else {
1654
+ l.freeUsd -= uncertain.maxUsd;
1655
+ l.committedUsd += uncertain.maxUsd;
1656
+ }
1657
+ }
1658
+ }
1659
+ // src/runtime/supervise/usage-metering.ts
1660
+ /** Fold a normalized `UsageEvent` array into a `Spend`. Tokens and usd are separate
1661
+ * channels; iterations come from `'iteration'` events. Pure; `ms` stays zero (the
1662
+ * pool does not read wall-clock). */
1663
+ function spendFromUsageEvents(events) {
1664
+ const totals = newUsageTotals();
1665
+ for (const ev of events) meterUsageEvent(totals, ev);
1666
+ return spendFromUsageTotals(totals);
1667
+ }
1668
+ /** Fresh accounting totals, optionally restored from verified committed spend. */
1669
+ function newUsageTotals(priorSpent) {
1670
+ if (priorSpent !== void 0) assertValidSpend(priorSpent, "prior committed usage");
1671
+ return {
1672
+ ...addResourceSpend(priorSpent?.resources),
1673
+ tokens: priorSpent === void 0 ? zeroTokenUsage() : cloneTokenUsage(priorSpent.tokens),
1674
+ tokensKnown: priorSpent?.tokensKnown !== false,
1675
+ ...priorSpent?.tokensProvenance === void 0 ? {} : { tokensProvenance: priorSpent.tokensProvenance },
1676
+ usd: priorSpent?.usd ?? 0,
1677
+ usdEstimated: priorSpent?.usdEstimated ?? 0,
1678
+ usdKnown: priorSpent?.usdKnown !== false,
1679
+ iterations: priorSpent?.iterations ?? 0
1680
+ };
1681
+ }
1682
+ /**
1683
+ * Fold ONE usage event into running totals — the single place that decides which event kinds
1684
+ * meter. `progress` carries observed output rather than accounting, so it meters nothing; only
1685
+ * `iteration` advances the iteration count.
1686
+ */
1687
+ function meterUsageEvent(totals, ev) {
1688
+ if (ev.kind === "resource") {
1689
+ totals.resources = addResourceSpend(totals.resources, Object.fromEntries([[ev.name, {
1690
+ unit: ev.unit,
1691
+ amount: ev.amount,
1692
+ known: ev.known
1693
+ }]])).resources;
1694
+ return;
1695
+ }
1696
+ if (ev.kind === "tokens") {
1697
+ if (ev.mode === "cumulative") {
1698
+ if (ev.input < totals.tokens.input || ev.output < totals.tokens.output) throw new ValidationError("cumulative executor tokens must not decrease");
1699
+ const snapshot = zeroTokenUsage();
1700
+ addTokenUsage(snapshot, {
1701
+ ...ev,
1702
+ ...ev.freshInput === void 0 && totals.tokens.freshInput !== void 0 ? { freshInput: totals.tokens.freshInput } : {},
1703
+ ...ev.cacheRead === void 0 && totals.tokens.cacheRead !== void 0 ? { cacheRead: totals.tokens.cacheRead } : {},
1704
+ ...ev.cacheWrite === void 0 && totals.tokens.cacheWrite !== void 0 ? { cacheWrite: totals.tokens.cacheWrite } : {},
1705
+ ...totals.tokens.tokensKnown === false ? { tokensKnown: false } : {}
1706
+ });
1707
+ totals.tokens = snapshot;
1708
+ } else addTokenUsage(totals.tokens, ev);
1709
+ if (ev.tokensKnown === false) totals.tokensKnown = false;
1710
+ const source = ev.provenance ?? "stream-receipt";
1711
+ totals.tokensProvenance = totals.tokensProvenance === void 0 || totals.tokensProvenance === source ? source : "mixed";
1712
+ return;
1713
+ }
1714
+ if (ev.kind === "cost") {
1715
+ totals.usd += ev.usd;
1716
+ if (ev.usdKnown === false) {
1717
+ totals.usdEstimated += ev.usdEstimated ?? 0;
1718
+ totals.usdKnown = false;
1719
+ }
1720
+ return;
1721
+ }
1722
+ if (ev.kind === "iteration") totals.iterations += 1;
1723
+ }
1724
+ /** Project folded totals onto the conserved-pool `Spend`. `ms` stays zero — the pool does not
1725
+ * read wall-clock. */
1726
+ function spendFromUsageTotals(totals) {
1727
+ return {
1728
+ ...addResourceSpend(totals.resources),
1729
+ iterations: totals.iterations,
1730
+ tokens: totals.tokens,
1731
+ ...totals.tokensKnown ? {} : { tokensKnown: false },
1732
+ usd: totals.usd,
1733
+ ...totals.usdKnown ? {} : { usdKnown: false },
1734
+ ...totals.usdEstimated > 0 ? { usdEstimated: totals.usdEstimated } : {},
1735
+ ...totals.tokensProvenance === void 0 || totals.tokensProvenance === "stream-receipt" ? {} : { tokensProvenance: totals.tokensProvenance },
1736
+ ms: 0
1737
+ };
1738
+ }
1739
+ async function foldUsage(events) {
1740
+ if (Array.isArray(events)) return spendFromUsageEvents(events);
1741
+ const totals = newUsageTotals();
1742
+ for await (const ev of events) meterUsageEvent(totals, ev);
1743
+ return spendFromUsageTotals(totals);
1744
+ }
1745
+ // src/runtime/supervise/budget.ts
1746
+ /**
1747
+ * Conserved budget accounting: total ≡ free + reserved + committed on each capped channel.
1748
+ * Reservation moves current free capacity to a single-use ticket; reconciliation commits
1749
+ * measured spend and refunds the remainder. It closes the ticket before reporting any fault.
1750
+ * Measured overspend reduces future capacity and returns a BudgetViolation.
1751
+ *
1752
+ * Tokens use chargedTokens (input − cacheRead + output). Missing cache classification charges
1753
+ * the full prompt and marks the split unknown. Prices never weight this channel. Named resources
1754
+ * require explicit units and complete measurements; the pool trusts receipts, not external state.
1755
+ * Unknown enforced resource or dollar usage closes that channel's admission. Unknown tokens
1756
+ * preserve observed counts as a lower bound without ending the run. An uncapped child dollar
1757
+ * channel reports actual dollars without treating them as an overspend of zero.
1758
+ *
1759
+ * Recovery preserves durable cost and outstanding backing, queuing only missing funding until
1760
+ * actual settlements provide it. Fresh spawns reserve current funds. Restore debits each liability once,
1761
+ * preserves unknown markers, and keeps the original deadline. No I/O or ambient clock is read.
1762
+ * @experimental
1763
+ */
1764
+ /** A reconciliation whose spend the pool cannot verify, thrown after the reservation settled.
1765
+ * `budgetViolation` carries any measured overspend on the same settlement. */
1766
+ var BudgetReconcileFault = class extends Error {
1767
+ budgetViolation;
1768
+ constructor(message, budgetViolation) {
1769
+ super(message);
1770
+ this.name = "BudgetReconcileFault";
1771
+ if (budgetViolation !== void 0) this.budgetViolation = budgetViolation;
1772
+ }
1773
+ };
1774
+ /**
1775
+ * A waiting reservation that can never be granted: every open reservation settled and the free
1776
+ * balance still cannot cover it. `shortfalls` are the channels that did not fit at that moment.
1777
+ */
1778
+ var ReservationWaitRefused = class extends Error {
1779
+ reason = "budget-exhausted";
1780
+ shortfalls;
1781
+ constructor(shortfalls) {
1782
+ super(`budget-exhausted: nothing left running could return enough budget for this worker (${shortfalls.map((shortfall) => `${shortfall.channel} requested ${shortfall.requested}, free ${shortfall.free}`).join("; ")})`);
1783
+ this.name = "ReservationWaitRefused";
1784
+ this.shortfalls = shortfalls;
1785
+ }
1786
+ };
1787
+ /** Private lease operations; public pools retain their existing interface. */
1788
+ const budgetRecoverySeeds = /* @__PURE__ */ new WeakMap();
1789
+ const budgetLeases = /* @__PURE__ */ new WeakMap();
1790
+ const budgetLeaseUpdates = /* @__PURE__ */ new WeakMap();
1791
+ async function refreshBudgetLease(pool) {
1792
+ await budgetLeaseUpdates.get(pool)?.();
1793
+ }
1794
+ /**
1795
+ * Create a conserved reservation pool from a root `Budget`. `runStartedAtMs` is the WALL-CLOCK
1796
+ * instant the root was recorded; the deadline is `runStartedAtMs + root.deadlineMs` (`0` when
1797
+ * none), an absolute instant. A resumed pool passes the ORIGINAL instant.
1798
+ */
1799
+ function createBudgetPool(root, runStartedAtMs, restore = {}) {
1800
+ assertValidBudget(root, "root budget");
1801
+ if (!Number.isFinite(runStartedAtMs) || runStartedAtMs < 0) throw new Error("budget runStartedAtMs must be a non-negative finite number");
1802
+ const ledger = openBudgetLedger(root, runStartedAtMs);
1803
+ let nextTicketId = 0;
1804
+ const open = /* @__PURE__ */ new Map();
1805
+ /** Tickets admitted to wait for budget, in the order they asked. Each is also in `open`. */
1806
+ const waiting = [];
1807
+ /** Open tickets that hold nothing: waiting, or refused and not yet reconciled. */
1808
+ const holdingNothing = /* @__PURE__ */ new Set();
1809
+ const leases = new ReservationLeases(ledger, root, open, holdingNothing, waiting, grantWaiting, recover, budgetRecoverySeeds.get(restore));
1810
+ /** Grant waiting tickets in the order they asked while the head fits. When the head does not
1811
+ * fit and no reservation is held that could return budget, nothing can ever cover it: refuse
1812
+ * it, and go on with the next. */
1813
+ function grantWaiting() {
1814
+ while (waiting.length > 0) {
1815
+ const head = waiting[0];
1816
+ if (head.refresh) head.budget = head.refresh();
1817
+ const shortfalls = ledgerShortfalls(ledger, head.budget, head.keep).filter((entry) => !head.refresh || entry.closedByUnknownSpend || entry.requested > 0);
1818
+ if (shortfalls.length === 0) {
1819
+ waiting.shift();
1820
+ ledgerTake(ledger, head.budget);
1821
+ holdingNothing.delete(head.ticket.id);
1822
+ head.acquired?.();
1823
+ head.grant();
1824
+ continue;
1825
+ }
1826
+ if (leases.hasRefundSource(head.ticket.id) && !shortfalls.some((entry) => entry.closedByUnknownSpend)) return;
1827
+ waiting.shift();
1828
+ head.refuse(new ReservationWaitRefused(shortfalls));
1829
+ }
1830
+ }
1831
+ /** Admit `b` to wait: it holds nothing until settlements return enough, in the order asked. */
1832
+ function admitToWait(b, holder, keep) {
1833
+ const id = nextTicketId++;
1834
+ open.set(id, holder);
1835
+ const ticket = ticketFor(id, b, ledger);
1836
+ leases.remember(ticket, keep);
1837
+ let grant;
1838
+ let refuse;
1839
+ const granted = new Promise((resolve, reject) => {
1840
+ grant = resolve;
1841
+ refuse = reject;
1842
+ });
1843
+ granted.catch(() => void 0);
1844
+ holdingNothing.add(id);
1845
+ waiting.push({
1846
+ ticket,
1847
+ budget: b,
1848
+ keep,
1849
+ grant,
1850
+ refuse
1851
+ });
1852
+ return {
1853
+ ok: true,
1854
+ ticket,
1855
+ granted
1856
+ };
1857
+ }
1858
+ function recover(budget, holder, nodeId, keep) {
1859
+ const seed = leases.seeds.get(nodeId);
1860
+ if (!seed) return reserve(budget, holder, {
1861
+ wait: true,
1862
+ keep
1863
+ });
1864
+ if (seed.closed) throw new ValidationError("closed custody backing cannot authorize execution");
1865
+ leases.seeds.delete(nodeId);
1866
+ const ticket = ticketFor(nextTicketId++, budget, ledger);
1867
+ open.set(ticket.id, holder);
1868
+ leases.remember(ticket, keep);
1869
+ leases.restore(ticket, budget, seed.spent, seed.held);
1870
+ const granted = leases.resume(ticket);
1871
+ return {
1872
+ ok: true,
1873
+ ticket,
1874
+ ...leases.isPaused(ticket) ? { granted } : {}
1875
+ };
1876
+ }
1877
+ function reserve(b, holder = { stage: "admitted" }, options = {}) {
1878
+ assertValidBudget(b, "reservation budget");
1879
+ assertResourceDeclarations(ledger, b);
1880
+ if (leases.blocked) return {
1881
+ ok: false,
1882
+ reason: "budget-exhausted"
1883
+ };
1884
+ const wantUsd = b.maxUsd ?? 0;
1885
+ const keep = options.keep;
1886
+ const shortfalls = ledgerShortfalls(ledger, b, keep);
1887
+ if (shortfalls.length === 0 && wantUsd > 0 && !ledger.usdCapped) return {
1888
+ ok: false,
1889
+ reason: "usd-unbudgeted"
1890
+ };
1891
+ const queueAhead = options.wait === true && waiting.length > 0;
1892
+ if (shortfalls.length === 0 && !queueAhead) {
1893
+ ledgerTake(ledger, b);
1894
+ const id = nextTicketId++;
1895
+ open.set(id, holder);
1896
+ const ticket = ticketFor(id, b, ledger);
1897
+ leases.remember(ticket, keep);
1898
+ return {
1899
+ ok: true,
1900
+ ticket
1901
+ };
1902
+ }
1903
+ if (options.wait !== true || shortfalls.some((shortfall) => shortfall.closedByUnknownSpend) || !leases.hasRefundSource()) return {
1904
+ ok: false,
1905
+ reason: "budget-exhausted",
1906
+ shortfalls
1907
+ };
1908
+ return admitToWait(b, holder, keep);
1909
+ }
1910
+ function attribute(ticket, holder) {
1911
+ const current = open.get(ticket.id);
1912
+ if (current === void 0) return;
1913
+ open.set(ticket.id, {
1914
+ ...current,
1915
+ ...holder
1916
+ });
1917
+ }
1918
+ function reconcile(ticket, spent) {
1919
+ if (!open.has(ticket.id)) throw new Error(`budget pool: reconcile of unknown or already-settled ticket ${ticket.id}`);
1920
+ assertValidSpend(spent, `budget pool ticket ${ticket.id} spend`);
1921
+ ledgerValidateUnits(ledger, spent);
1922
+ const heldNothing = holdingNothing.delete(ticket.id);
1923
+ const index = waiting.findIndex((entry) => entry.ticket.id === ticket.id);
1924
+ if (index >= 0) waiting.splice(index, 1);
1925
+ const adjustment = leases.settle(ticket, spent);
1926
+ const held = adjustment?.held ?? (heldNothing ? {
1927
+ tokens: 0,
1928
+ usd: 0,
1929
+ iterations: 0,
1930
+ resources: void 0
1931
+ } : ticket.reserved);
1932
+ const charge = adjustment?.charge ?? spent;
1933
+ const usdBudgeted = ticket.reserved.usdBudgeted !== false;
1934
+ const { overspent, unknownUnderCap } = ledgerClassifyOverspend(ledger, heldNothing && adjustment === void 0 ? held : ticket.reserved, usdBudgeted, spent, heldNothing && adjustment === void 0 ? {
1935
+ maxTokens: 0,
1936
+ maxIterations: 0
1937
+ } : ticket.limits);
1938
+ let fault = unknownUnderCap ? `ticket ${ticket.id} reported unknown dollar cost under a dollar-capped budget` : void 0;
1939
+ open.delete(ticket.id);
1940
+ const resourceSettlement = ledgerSettle(ledger, held, charge, unknownUnderCap);
1941
+ fault ??= resourceSettlement.fault;
1942
+ grantWaiting();
1943
+ const violation = overspent.length === 0 ? void 0 : Object.freeze({ overspent: Object.freeze(overspent.map((entry) => Object.freeze(entry))) });
1944
+ if (fault !== void 0) throw new BudgetReconcileFault(`budget pool: ${fault}`, violation);
1945
+ return violation;
1946
+ }
1947
+ function observe(spend, options = {}) {
1948
+ assertValidSpend(spend, "observed spend");
1949
+ ledgerValidateUnits(ledger, spend);
1950
+ const unknownUnderCap = ledger.usdCapped && spend.usdKnown === false;
1951
+ if (unknownUnderCap && options.alreadySpent !== true) throw new ValidationError("budget pool: cannot observe unknown dollar cost under a dollar-capped budget");
1952
+ const settlement = ledgerObserve(ledger, spend, unknownUnderCap, !options.partial);
1953
+ const violation = settlement.fault ?? settlement.rootExceeded;
1954
+ if (violation) throw new ValidationError(`budget pool: ${violation}`);
1955
+ }
1956
+ function readout() {
1957
+ return {
1958
+ ...ledger.resources.size ? { resources: Object.fromEntries([...ledger.resources].map(([name, value]) => [name, { ...value }])) } : {},
1959
+ tokensLeft: ledger.freeTokens,
1960
+ tokensCapped: ledger.tokensCapped,
1961
+ committedTokens: ledger.committedTokens,
1962
+ tokensKnown: !ledger.tokensTainted,
1963
+ cacheBreakdownKnown: !ledger.cacheBreakdownTainted,
1964
+ usdLeft: ledger.usdCapped ? ledger.usdTainted ? 0 : ledger.freeUsd : 0,
1965
+ usdCapped: ledger.usdCapped,
1966
+ usdKnown: ledger.usdMeasured && !ledger.usdTainted,
1967
+ iterationsLeft: ledger.freeIterations,
1968
+ iterationsCapped: ledger.iterationsCapped,
1969
+ deadlineMs: ledger.absoluteDeadlineMs,
1970
+ reservedTokens: ledger.reservedTokens
1971
+ };
1972
+ }
1973
+ function openReservations() {
1974
+ return [...open].map(([ticketId, holder]) => Object.freeze({
1975
+ ticketId,
1976
+ ...holder
1977
+ }));
1978
+ }
1979
+ function assertNoOpenTickets() {
1980
+ if (open.size > 0) throw new Error(`budget pool: ${open.size} reservation(s) still open at join barrier (${openReservations().map(describeLeakedReservation).join("; ")}) — conserved-pool invariant violated`);
1981
+ }
1982
+ for (const seed of leases.seeds.values()) ledgerTake(ledger, seed.held);
1983
+ ledgerRestore(ledger, root, restore);
1984
+ for (const seed of leases.seeds.values()) if (!seed.closed) ledgerRestore(ledger, root, { committed: seed.spent });
1985
+ const pool = {
1986
+ reserve,
1987
+ attribute,
1988
+ reconcile,
1989
+ spendFrom: foldUsage,
1990
+ readout,
1991
+ observe,
1992
+ assertNoOpenTickets,
1993
+ openReservations
1994
+ };
1995
+ budgetLeases.set(pool, leases);
1996
+ return pool;
1997
+ }
1998
+ var ReservationLeases = class {
1999
+ ledger;
2000
+ root;
2001
+ open;
2002
+ empty;
2003
+ waiting;
2004
+ pump;
2005
+ recover;
2006
+ blocked = false;
2007
+ rebased = /* @__PURE__ */ new Map();
2008
+ kept = /* @__PURE__ */ new Map();
2009
+ tickets = /* @__PURE__ */ new Map();
2010
+ seeds;
2011
+ constructor(ledger, root, open, empty, waiting, pump, recover, seeds = []) {
2012
+ this.ledger = ledger;
2013
+ this.root = root;
2014
+ this.open = open;
2015
+ this.empty = empty;
2016
+ this.waiting = waiting;
2017
+ this.pump = pump;
2018
+ this.recover = recover;
2019
+ this.seeds = new Map(seeds.map(({ id, ...seed }) => [id, seed]));
2020
+ }
2021
+ restore(ticket, ceiling, spent, held) {
2022
+ this.rebased.set(ticket.id, {
2023
+ ceiling,
2024
+ spent,
2025
+ held,
2026
+ liabilities: held,
2027
+ paused: true
2028
+ });
2029
+ if (!hasAllocation(heldAmounts(held, this.ledger))) this.empty.add(ticket.id);
2030
+ }
2031
+ remember(ticket, keep) {
2032
+ this.tickets.set(ticket.id, ticket);
2033
+ this.kept.set(ticket.id, keep && { ...keep });
2034
+ }
2035
+ hasRefundSource(except) {
2036
+ for (const [id, ticket] of this.tickets) {
2037
+ if (id === except || !this.open.has(id) || this.empty.has(id)) continue;
2038
+ const state = this.rebased.get(id);
2039
+ if (hasAllocation(state ? heldAmounts(state.held, this.ledger) : ticket.reserved)) return true;
2040
+ }
2041
+ return [...this.seeds.values()].some((seed) => !seed.closed && hasAllocation(heldAmounts(seed.held, this.ledger)));
2042
+ }
2043
+ liabilities(spent) {
2044
+ const l = this.ledger;
2045
+ const keep = (cap, reserved, committed, reported, unknown = false) => cap === void 0 ? void 0 : Math.max(reserved + Math.max(0, committed - reported), unknown ? Math.max(0, cap - reported) : 0);
2046
+ return {
2047
+ ...this.root.maxTokens === void 0 ? {} : { maxTokens: keep(this.root.maxTokens, l.reservedTokens, l.committedTokens, chargedTokens(spent.tokens), l.tokensTainted) },
2048
+ ...this.root.maxIterations === void 0 ? {} : { maxIterations: keep(this.root.maxIterations, l.reservedIterations, l.committedIterations, spent.iterations) },
2049
+ ...this.root.maxUsd === void 0 ? {} : { maxUsd: keep(this.root.maxUsd, l.reservedUsd, l.committedUsd, spent.usd, l.usdTainted || !l.usdMeasured) },
2050
+ ...this.root.resources === void 0 ? {} : { resources: Object.fromEntries([...l.resources].map(([name, value]) => [name, {
2051
+ unit: value.unit,
2052
+ limit: keep(value.limit, value.reserved, value.committed, spent.resources?.[name]?.amount ?? 0, !value.known)
2053
+ }])) }
2054
+ };
2055
+ }
2056
+ rebase(ticket, ceiling, spent, liabilities, pause = false) {
2057
+ const old = this.rebased.get(ticket.id);
2058
+ if (!this.open.has(ticket.id) && !old?.closed) return;
2059
+ const state = old ?? {
2060
+ ceiling,
2061
+ spent: zeroSpend(),
2062
+ held: ceiling,
2063
+ paused: true,
2064
+ liabilities
2065
+ };
2066
+ state.paused ||= pause;
2067
+ const next = this.plannedHold(ticket, ceiling, spent, liabilities, pause);
2068
+ const held = heldAmounts(state.held, this.ledger);
2069
+ const delta = withBudgetResources(unreportedSpend(spent, state.spent), ceiling, true);
2070
+ ledgerSettle(this.ledger, held, delta, this.ledger.usdCapped && delta.usdKnown === false);
2071
+ ledgerTake(this.ledger, next);
2072
+ state.spent = spent;
2073
+ state.held = next;
2074
+ state.liabilities = liabilities;
2075
+ this.rebased.set(ticket.id, state);
2076
+ if (hasAllocation(heldAmounts(next, this.ledger))) this.empty.delete(ticket.id);
2077
+ else this.empty.add(ticket.id);
2078
+ this.pump();
2079
+ }
2080
+ plannedHold(ticket, ceiling, spent, liabilities, pause) {
2081
+ return pause || (this.rebased.get(ticket.id)?.paused ?? true) ? liabilities : maximumBudget(remainingBudget(ceiling, spent), liabilities);
2082
+ }
2083
+ resume(ticket) {
2084
+ const state = this.rebased.get(ticket.id);
2085
+ if (!state?.paused) return Promise.resolve();
2086
+ if (!this.open.has(ticket.id)) return Promise.reject(new ValidationError("closed admission cannot resume"));
2087
+ const refresh = () => differenceBudget(remainingBudget(state.ceiling, state.spent), state.held);
2088
+ const acquired = () => {
2089
+ state.paused = false;
2090
+ state.held = maximumBudget(remainingBudget(state.ceiling, state.spent), state.held);
2091
+ };
2092
+ const budget = refresh();
2093
+ const keep = this.kept.get(ticket.id);
2094
+ const shortfalls = ledgerShortfalls(this.ledger, budget, keep).filter((entry) => entry.closedByUnknownSpend || entry.requested > 0);
2095
+ if (shortfalls.length === 0 && (this.waiting.length === 0 || !hasAllocation(heldAmounts(budget, this.ledger)))) {
2096
+ ledgerTake(this.ledger, budget);
2097
+ this.empty.delete(ticket.id);
2098
+ acquired();
2099
+ return Promise.resolve();
2100
+ }
2101
+ if (shortfalls.some((entry) => entry.closedByUnknownSpend) || !this.hasRefundSource(ticket.id)) return Promise.reject(new ReservationWaitRefused(shortfalls));
2102
+ const granted = new Promise((grant, refuse) => {
2103
+ this.waiting.push({
2104
+ ticket,
2105
+ budget,
2106
+ keep,
2107
+ refresh,
2108
+ acquired,
2109
+ grant,
2110
+ refuse
2111
+ });
2112
+ });
2113
+ granted.catch(() => void 0);
2114
+ return granted;
2115
+ }
2116
+ reservation(ticket) {
2117
+ return this.rebased.get(ticket.id)?.held;
2118
+ }
2119
+ isPaused(ticket) {
2120
+ return this.rebased.get(ticket.id)?.paused === true;
2121
+ }
2122
+ isBacked(ticket) {
2123
+ return this.open.has(ticket.id) || this.rebased.get(ticket.id)?.closed === true;
2124
+ }
2125
+ observeTerminal(ticket, spent) {
2126
+ const state = this.rebased.get(ticket.id);
2127
+ if (state && !state.closed) state.liabilities = completedLeafBacking(state.held, spent, state.spent);
2128
+ }
2129
+ acknowledgeTeardown(ticket) {
2130
+ const state = this.rebased.get(ticket.id);
2131
+ if (!state?.closed) return;
2132
+ const next = completedLeafBacking(state.held, state.spent, state.spent, true);
2133
+ const refund = differenceBudget(state.held, next);
2134
+ ledgerSettle(this.ledger, heldAmounts(refund, this.ledger), withBudgetResources(zeroSpend(), state.ceiling, true), false);
2135
+ state.held = state.liabilities = next;
2136
+ if (!hasAllocation(heldAmounts(next, this.ledger))) this.rebased.delete(ticket.id);
2137
+ this.pump();
2138
+ }
2139
+ settle(ticket, spent) {
2140
+ const state = this.rebased.get(ticket.id);
2141
+ this.kept.delete(ticket.id);
2142
+ this.tickets.delete(ticket.id);
2143
+ if (!state) return void 0;
2144
+ const charge = unreportedSpend(spent, state.spent);
2145
+ const held = differenceBudget(state.held, state.liabilities);
2146
+ if (hasAllocation(heldAmounts(state.liabilities, this.ledger))) {
2147
+ state.closed = true;
2148
+ state.paused = true;
2149
+ state.spent = spent;
2150
+ state.held = state.liabilities;
2151
+ return {
2152
+ held: heldAmounts(held, this.ledger),
2153
+ charge
2154
+ };
2155
+ }
2156
+ this.rebased.delete(ticket.id);
2157
+ return {
2158
+ held: heldAmounts(state.held, this.ledger),
2159
+ charge
2160
+ };
2161
+ }
2162
+ };
2163
+ /** A real leaf result ends model work; named physical backing awaits its cleanup ACK.
2164
+ * Unknown past usage remains backed even after the resource itself has been released. */
2165
+ function completedLeafBacking(held, spent, prior, cleanupConfirmed = false) {
2166
+ const delta = unreportedSpend(spent, prior);
2167
+ return {
2168
+ ...held,
2169
+ ...held.maxTokens === void 0 || spent.tokensKnown === false || spent.tokens.tokensKnown === false ? {} : { maxTokens: 0 },
2170
+ ...held.maxIterations === void 0 ? {} : { maxIterations: 0 },
2171
+ ...held.maxUsd === void 0 || spent.usdKnown === false ? {} : { maxUsd: 0 },
2172
+ ...held.resources === void 0 ? {} : { resources: Object.fromEntries(Object.entries(held.resources).map(([name, value]) => [name, {
2173
+ ...value,
2174
+ limit: spent.resources?.[name]?.known !== true ? value.limit : cleanupConfirmed ? 0 : Math.max(0, value.limit - (delta.resources?.[name]?.amount ?? 0))
2175
+ }])) }
2176
+ };
2177
+ }
2178
+ function heldAmounts(budget, ledger) {
2179
+ return {
2180
+ tokens: ledger.tokensCapped ? budget.maxTokens ?? 0 : 0,
2181
+ iterations: ledger.iterationsCapped ? budget.maxIterations ?? 0 : 0,
2182
+ usd: budget.maxUsd ?? 0,
2183
+ ...budget.resources ? { resources: budget.resources } : {}
2184
+ };
2185
+ }
2186
+ function remainingBudget(budget, spent) {
2187
+ return differenceBudget(budget, {
2188
+ maxTokens: chargedTokens(spent.tokens),
2189
+ maxIterations: spent.iterations,
2190
+ maxUsd: spent.usd,
2191
+ resources: Object.fromEntries(Object.entries(spent.resources ?? {}).map(([name, value]) => [name, {
2192
+ unit: value.unit,
2193
+ limit: value.amount
2194
+ }]))
2195
+ });
2196
+ }
2197
+ function maximumBudget(grant, backing) {
2198
+ return {
2199
+ ...grant,
2200
+ ...grant.maxTokens === void 0 ? {} : { maxTokens: Math.max(grant.maxTokens, backing.maxTokens ?? 0) },
2201
+ ...grant.maxIterations === void 0 ? {} : { maxIterations: Math.max(grant.maxIterations, backing.maxIterations ?? 0) },
2202
+ ...grant.maxUsd === void 0 ? {} : { maxUsd: Math.max(grant.maxUsd, backing.maxUsd ?? 0) },
2203
+ ...grant.resources === void 0 ? {} : { resources: Object.fromEntries(Object.entries(grant.resources).map(([name, value]) => [name, {
2204
+ unit: value.unit,
2205
+ limit: Math.max(value.limit, backing.resources?.[name]?.limit ?? 0)
2206
+ }])) }
2207
+ };
2208
+ }
2209
+ function differenceBudget(total, prior) {
2210
+ return {
2211
+ ...total.maxTokens === void 0 ? {} : { maxTokens: Math.max(0, total.maxTokens - (prior.maxTokens ?? 0)) },
2212
+ ...total.maxIterations === void 0 ? {} : { maxIterations: Math.max(0, total.maxIterations - (prior.maxIterations ?? 0)) },
2213
+ ...total.maxUsd === void 0 ? {} : { maxUsd: Math.max(0, total.maxUsd - (prior.maxUsd ?? 0)) },
2214
+ ...total.resources === void 0 ? {} : { resources: Object.fromEntries(Object.entries(total.resources).map(([name, value]) => [name, {
2215
+ unit: value.unit,
2216
+ limit: Math.max(0, value.limit - (prior.resources?.[name]?.limit ?? 0))
2217
+ }])) }
2218
+ };
2219
+ }
2220
+ function hasAllocation(budget) {
2221
+ return budget.tokens > 0 || budget.iterations > 0 || budget.usd > 0 || Object.values(budget.resources ?? {}).some((value) => value.limit > 0);
2222
+ }
2223
+ /** A reservation must name a limit for exactly the resources the root declared, in its units. */
2224
+ function assertResourceDeclarations(ledger, b) {
2225
+ for (const [name, state] of ledger.resources) {
2226
+ const wanted = b.resources?.[name];
2227
+ if (!wanted) throw new ValidationError(`resource ${name}: child must declare its limit`);
2228
+ if (wanted.unit !== state.unit) throw new ValidationError(`resource ${name}: unit mismatch`);
2229
+ }
2230
+ for (const name of Object.keys(b.resources ?? {})) if (!ledger.resources.has(name)) throw new ValidationError(`resource ${name}: root must declare its limit`);
2231
+ }
2232
+ function ticketFor(id, b, ledger) {
2233
+ return {
2234
+ id,
2235
+ limits: {
2236
+ ...b.maxTokens === void 0 ? {} : { maxTokens: b.maxTokens },
2237
+ ...b.maxIterations === void 0 ? {} : { maxIterations: b.maxIterations }
2238
+ },
2239
+ reserved: {
2240
+ ...b.resources === void 0 ? {} : { resources: Object.fromEntries(Object.entries(b.resources).map(([name, value]) => [name, { ...value }])) },
2241
+ tokens: ledger.tokensCapped ? b.maxTokens ?? 0 : 0,
2242
+ usd: b.maxUsd ?? 0,
2243
+ iterations: ledger.iterationsCapped ? b.maxIterations ?? 0 : 0,
2244
+ usdBudgeted: b.maxUsd !== void 0
2245
+ }
2246
+ };
2247
+ }
2248
+ /** Name one leaked reservation by its holder. */
2249
+ function describeLeakedReservation(leak) {
2250
+ const parts = [`ticket ${leak.ticketId}`];
2251
+ if (leak.childId !== void 0) parts.push(`child ${leak.childId}`);
2252
+ if (leak.label !== void 0) parts.push(`label ${leak.label}`);
2253
+ if (leak.assignment !== void 0) parts.push(`assignment ${leak.assignment}`);
2254
+ parts.push(`stage ${leak.stage}`);
2255
+ return parts.join(", ");
2256
+ }
2257
+ // src/runtime/supervise/credential-refusal.ts
2258
+ /**
2259
+ * The account owner refused an unsupported credential route before dispatch. This is the
2260
+ * provider SDK's machine contract, not an HTTP status, class-name guess, or prose match.
2261
+ */
2262
+ function isCredentialRefusal(error) {
2263
+ if (!(error instanceof Error)) return false;
2264
+ try {
2265
+ return Object.getOwnPropertyDescriptor(error, "code")?.value === "model_credential_refused";
2266
+ } catch {
2267
+ return false;
2268
+ }
2269
+ }
2270
+ /**
2271
+ * The message prefix of agent-provider-tangle's generic credential command failure. The provider
2272
+ * exports no type or constant for it, so the kernel credential test raises it through the
2273
+ * provider's own command resolver and fails when the message drifts.
2274
+ */
2275
+ const CREDENTIAL_COMMAND_FAILURE = "Tangle credential command failed (";
2276
+ /**
2277
+ * The exit code of agent-provider-tangle's credential command (`acct sandbox resolve`) in the
2278
+ * error or its causes, or undefined.
2279
+ *
2280
+ * The provider reports the command's generic failure as `Tangle credential command failed
2281
+ * (exit N)` with the process's `exitCode` and `terminationSignal` as own fields; a refusal it can
2282
+ * parse (exit 75 or 78) arrives typed instead and is classified on its code. Before any dispatch
2283
+ * this failure ran nothing, and counting it as an unresolved pending invocation stopped 10 nodes
2284
+ * and lost 7 runs between 2026-10-12 and 2026-10-19 (test-acceptance-canary-20261015c met 26 in
2285
+ * 2.2 minutes). It pauses like a capacity refusal, bounded by the deadline, the budget and
2286
+ * cancellation as every pause is.
2287
+ */
2288
+ function credentialCommandExit(error) {
2289
+ for (const link of causeChain(error)) try {
2290
+ if (!(link instanceof Error) || !link.message.startsWith(CREDENTIAL_COMMAND_FAILURE) || !Object.hasOwn(link, "terminationSignal")) continue;
2291
+ const exitCode = Reflect.get(link, "exitCode");
2292
+ if (typeof exitCode === "number" && Number.isInteger(exitCode) && exitCode > 0) return exitCode;
2293
+ } catch {}
2294
+ }
2295
+ // src/runtime/json-content-hash.ts
2296
+ /**
2297
+ * Stable hash for the trace payload. Not cryptographic — only used so
2298
+ * downstream eval pipelines can group iterations whose task / output is the
2299
+ * same. Bare structural hash; non-JSON values stringify via their `toString`.
2300
+ */
2301
+ function hashJson(value) {
2302
+ const str = jsonContentText(value);
2303
+ return fnv1a32Hex(str);
2304
+ }
2305
+ /** JSON text with String fallback, including quoted JSON strings and cyclic values. */
2306
+ function jsonContentText(value) {
2307
+ let str;
2308
+ try {
2309
+ str = JSON.stringify(value) ?? String(value);
2310
+ } catch {
2311
+ str = String(value);
2312
+ }
2313
+ return str;
2314
+ }
2315
+ // src/runtime/supervise/executor-outcome.ts
2316
+ const outcomeSchema = AgentTurnResultSchema.pick({
2317
+ success: true,
2318
+ error: true,
2319
+ failure: true
2320
+ }).extend({
2321
+ errorCode: AgentTurnResultSchema.shape.error,
2322
+ statusCode: z.number().int().min(400).max(599).optional()
2323
+ }).strict();
2324
+ /** Read only the executor envelope; application output and grades are not execution status. */
2325
+ function executorFailure(result) {
2326
+ if (result.outcome === void 0) return void 0;
2327
+ const outcome = outcomeSchema.parse(result.outcome);
2328
+ if (outcome.success) return void 0;
2329
+ return {
2330
+ error: outcome.error ?? "Agent execution failed",
2331
+ ...outcome.failure === void 0 ? {} : { failure: outcome.failure },
2332
+ ...outcome.errorCode === void 0 ? {} : { errorCode: outcome.errorCode },
2333
+ ...outcome.statusCode === void 0 ? {} : { statusCode: outcome.statusCode }
2334
+ };
2335
+ }
2336
+ /** The failure text alone, for callers that record a settlement reason. */
2337
+ function executorFailureReason(result) {
2338
+ return executorFailure(result)?.error;
2339
+ }
2340
+ /** Canonical producer classifications take precedence over the legacy code/message vocabulary. */
2341
+ const TURN_FAILURE_POLICY = {
2342
+ capacity: {
2343
+ classification: "unavailable",
2344
+ failureKind: "infra",
2345
+ infra: true,
2346
+ code: "upstream-unavailable",
2347
+ owner: "platform"
2348
+ },
2349
+ caller: {
2350
+ classification: "terminal",
2351
+ failureKind: "deterministic",
2352
+ infra: void 0,
2353
+ code: "request-rejected",
2354
+ owner: "caller"
2355
+ },
2356
+ infra: {
2357
+ classification: "transient",
2358
+ failureKind: "infra",
2359
+ infra: true,
2360
+ code: "transport",
2361
+ owner: "platform"
2362
+ },
2363
+ work: {
2364
+ classification: "transient",
2365
+ failureKind: "deterministic",
2366
+ infra: void 0,
2367
+ code: "work-failed",
2368
+ owner: "work"
2369
+ }
2370
+ };
2371
+ const turnFailurePolicy = (failure) => TURN_FAILURE_POLICY[failure.kind];
2372
+ /** Validate the shared contract on an envelope or any wrapped cause; malformed legacy data falls back. */
2373
+ function turnFailureOf(value) {
2374
+ for (const link of causeChain(value)) try {
2375
+ const parsed = AgentTurnFailureSchema.safeParse(Reflect.get(link, "failure"));
2376
+ if (parsed.success) return parsed.data;
2377
+ } catch {}
2378
+ }
2379
+ const PLATFORM_FAILURE_CODES = new Set([
2380
+ "QUOTA_EXCEEDED",
2381
+ "provider_quota_exceeded",
2382
+ "provider_quota_exhausted",
2383
+ "buffer.overflow",
2384
+ "EXECUTION_INTERRUPTED",
2385
+ "TIMEOUT",
2386
+ "ECONNRESET",
2387
+ "ECONNREFUSED",
2388
+ "ETIMEDOUT",
2389
+ "EPIPE",
2390
+ "EADDRINUSE"
2391
+ ].map((code) => code.toLowerCase()));
2392
+ const PLATFORM_FAILURE_MESSAGES = [
2393
+ /^terminated$/u,
2394
+ /Execution exceeded its time limit/u,
2395
+ /Platform key[- ]verification/u,
2396
+ /Platform key delegation failed/u,
2397
+ /Bad Gateway/iu,
2398
+ /Cannot connect to API/u,
2399
+ /Failed to connect to Sandbox API/u,
2400
+ /fetch failed/u,
2401
+ /A sandbox lifecycle operation is already in progress/u,
2402
+ /exceeded its string bound/u,
2403
+ /exceeds its JSON bound/u,
2404
+ /No provider served model/u,
2405
+ /Invalid API key/u,
2406
+ /provider_quota_exceeded|provider_quota_exhausted|QUOTA_EXCEEDED|rate limit/iu,
2407
+ /is at its box cap/u,
2408
+ /could not materialize the seat credential/u,
2409
+ /OpenCode exited while a model step was still in progress/u
2410
+ ];
2411
+ /** Producer-owned classification first; legacy platform codes/messages otherwise leave attribution unknown. */
2412
+ function executorFailureInfra(failure) {
2413
+ if (failure.failure) return turnFailurePolicy(failure.failure).infra;
2414
+ const code = failure.errorCode?.toLowerCase();
2415
+ if (code !== void 0 && PLATFORM_FAILURE_CODES.has(code)) return true;
2416
+ return PLATFORM_FAILURE_MESSAGES.some((pattern) => pattern.test(failure.error)) ? true : void 0;
2417
+ }
2418
+ /** Preserve deterministic result pointers across built-in executors and replay.
2419
+ * FNV-1a is an identity convention here, not a cryptographic integrity check. */
2420
+ function contentRef(prefix, value) {
2421
+ const str = jsonContentText(value);
2422
+ return `${prefix}:${fnv1a32Hex(str)}`;
2423
+ }
2424
+ // src/durable/content-address.ts
2425
+ /** Stable content address shared by result and trace artifacts. */
2426
+ function contentAddress(artifact) {
2427
+ return `sha256:${createHash("sha256").update(stableStringify(artifact), "utf-8").digest("hex")}`;
2428
+ }
2429
+ function stableStringify(value) {
2430
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
2431
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
2432
+ return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
2433
+ }
2434
+ // src/runtime/supervise/trace-root.ts
2435
+ /**
2436
+ * Trace roots: one Merkle root over the events a turn archived, so a single event can be proven
2437
+ * against the hash its journal record carries without reading the rest of the archive.
2438
+ *
2439
+ * The leaves are the archived events in stored order, each hashed with its own random salt, then
2440
+ * one summary leaf that counts the events and the tool calls among them. The artifact keeps every
2441
+ * leaf and salt and is stored under its content address in the run's result blob store, beside
2442
+ * the archive it commits to. A verifier recomputes leaf `i` from `events[i]` of the `outRef` blob
2443
+ * and `salts[i]`, checks it against `leaves[i]`, and checks `merkleRoot(leaves)` against the root
2444
+ * the journal recorded. Leaf identity is `(outRef, index)`: an event's own `id` is a session
2445
+ * buffer offset and is absent on terminal events.
2446
+ *
2447
+ * One event array has one root per node. A result always gets its own. Evidence whose events the
2448
+ * node already rooted gets none: a retained owner's deferred workspace capture stores the turn it
2449
+ * just committed again, with the workspace fields added, under another `outRef`. A second root
2450
+ * over the same events would give one turn two count candidates and two run-root leaves.
2451
+ *
2452
+ * Salts are random, so a trace root can never be recomputed from the archive alone. Recovery and
2453
+ * replay copy the recorded receipt; they never derive a new one.
2454
+ */
2455
+ /** Schema identifier of a stored {@link TraceRootArtifact}. */
2456
+ const TRACE_ROOT_SCHEMA = "agent-runtime.trace-root.v1";
2457
+ /** Schema identifier of the {@link TraceSummary} carried by a trace root's last leaf. */
2458
+ const TRACE_SUMMARY_SCHEMA = "agent-runtime.trace-summary.v1";
2459
+ /** @internal */
2460
+ function traceRootWriter(blobs, nodeId) {
2461
+ const roots = /* @__PURE__ */ new Map();
2462
+ /** Digests of the event arrays this node holds a stored root for. */
2463
+ const rooted = /* @__PURE__ */ new Set();
2464
+ const memoized = (outRef, out, evidence) => {
2465
+ const known = roots.get(outRef);
2466
+ if (known !== void 0) return known;
2467
+ const pending = (async () => {
2468
+ const events = archivedEvents(out);
2469
+ if (events === void 0) return void 0;
2470
+ if (evidence) {
2471
+ await Promise.allSettled([...roots.values()]);
2472
+ if (rooted.has(await eventsDigest(events))) return void 0;
2473
+ }
2474
+ const built = await traceRootArtifact(nodeId, outRef, events).catch((error) => {
2475
+ if (error instanceof LedgerCanonicalizationError) return void 0;
2476
+ throw error;
2477
+ });
2478
+ if (built === void 0) return void 0;
2479
+ const { artifact, digest } = built;
2480
+ await setImmediate();
2481
+ const ref = contentAddress(artifact);
2482
+ await setImmediate();
2483
+ await blobs.put(ref, artifact);
2484
+ rooted.add(digest);
2485
+ return {
2486
+ root: artifact.root,
2487
+ ref,
2488
+ leafCount: artifact.leafCount
2489
+ };
2490
+ })();
2491
+ roots.set(outRef, pending);
2492
+ pending.catch(() => roots.delete(outRef));
2493
+ return pending;
2494
+ };
2495
+ return {
2496
+ write: (outRef, result) => result.outputFormat === "json" ? Promise.resolve(void 0) : memoized(outRef, result.out, false),
2497
+ writeEvidence: (outRef, out) => memoized(outRef, out, true),
2498
+ async recorded(outRef) {
2499
+ if (outRef === void 0) return void 0;
2500
+ return roots.get(outRef)?.catch(() => void 0);
2501
+ }
2502
+ };
2503
+ }
2504
+ function archivedEvents(out) {
2505
+ if (out === null || typeof out !== "object" || Array.isArray(out)) return void 0;
2506
+ const events = out.events;
2507
+ return Array.isArray(events) ? events : void 0;
2508
+ }
2509
+ /** The longest stretch of hashing between yields to the event loop. Hashing runs about 40 µs per
2510
+ * event, and the largest archived turn holds 65,276 events: unbroken, that blocked the process
2511
+ * for 2.7 s while sibling turns, coordination calls and heartbeats waited. A slice is measured
2512
+ * in time, not events, because one event can be megabytes. */
2513
+ const SLICE_MS = 10;
2514
+ /** Yields to the event loop once a slice has run `SLICE_MS`; `undefined` while it has not. */
2515
+ function slicer() {
2516
+ let started = performance.now();
2517
+ return () => {
2518
+ if (performance.now() - started < SLICE_MS) return void 0;
2519
+ return setImmediate().then(() => {
2520
+ started = performance.now();
2521
+ });
2522
+ };
2523
+ }
2524
+ /** The identity of an event array as stored: the digest of each event's stored JSON, in order.
2525
+ * Two arrays with one digest have the same leaves' content. */
2526
+ async function eventsDigest(events) {
2527
+ const hash = createHash("sha256");
2528
+ const slice = slicer();
2529
+ for (const event of events) {
2530
+ const yielded = slice();
2531
+ if (yielded !== void 0) await yielded;
2532
+ hash.update(storedText(event)).update("\n");
2533
+ }
2534
+ return hash.digest("hex");
2535
+ }
2536
+ async function traceRootArtifact(nodeId, outRef, archived) {
2537
+ const salts = [];
2538
+ const leaves = [];
2539
+ const tree = merkleTree();
2540
+ const identity = createHash("sha256");
2541
+ const tools = createSandboxToolPartState();
2542
+ const toolCalls = /* @__PURE__ */ new Map();
2543
+ const slice = slicer();
2544
+ for (const event of archived) {
2545
+ const yielded = slice();
2546
+ if (yielded !== void 0) await yielded;
2547
+ const text = storedText(event);
2548
+ identity.update(text).update("\n");
2549
+ const stored = JSON.parse(text);
2550
+ const salt = merkleSalt();
2551
+ const leaf = merkleLeafHash(canonicalString(jsonDocument(stored)), salt);
2552
+ salts.push(salt);
2553
+ leaves.push(leaf);
2554
+ tree.push(leaf);
2555
+ for (const projected of mapSandboxToolEvent(stored, tools)) {
2556
+ if (projected.type !== "tool_call") continue;
2557
+ toolCalls.set(projected.toolName, (toolCalls.get(projected.toolName) ?? 0) + 1);
2558
+ }
2559
+ }
2560
+ const summary = {
2561
+ schema: TRACE_SUMMARY_SCHEMA,
2562
+ events: archived.length,
2563
+ toolCalls: Object.fromEntries(toolCalls)
2564
+ };
2565
+ const salt = merkleSalt();
2566
+ const leaf = merkleLeafHash(canonicalString(summary), salt);
2567
+ salts.push(salt);
2568
+ leaves.push(leaf);
2569
+ tree.push(leaf);
2570
+ return {
2571
+ artifact: {
2572
+ schema: TRACE_ROOT_SCHEMA,
2573
+ nodeId,
2574
+ outRef,
2575
+ root: tree.root(),
2576
+ leafCount: leaves.length,
2577
+ salts,
2578
+ leaves,
2579
+ summary
2580
+ },
2581
+ digest: identity.digest("hex")
2582
+ };
2583
+ }
2584
+ /**
2585
+ * `merkleRoot(leaves)` built as the leaves arrive, so its interior hashes run inside the sliced
2586
+ * leaf loop instead of in one block after it (0.4 s for 65,277 leaves). It keeps the perfect
2587
+ * subtrees of RFC 9162, largest first, and joins two with ledger-core's own interior hash,
2588
+ * `merkleRoot([left, right])`; the root folds them from the right, as RFC 9162 splits at the
2589
+ * largest power of two.
2590
+ */
2591
+ function merkleTree() {
2592
+ const peaks = [];
2593
+ return {
2594
+ push(leaf) {
2595
+ let hash = leaf;
2596
+ let size = 1;
2597
+ while (peaks.at(-1)?.size === size) {
2598
+ hash = merkleRoot([peaks.pop().hash, hash]);
2599
+ size *= 2;
2600
+ }
2601
+ peaks.push({
2602
+ hash,
2603
+ size
2604
+ });
2605
+ },
2606
+ root() {
2607
+ let root = peaks.at(-1).hash;
2608
+ for (let index = peaks.length - 2; index >= 0; index -= 1) root = merkleRoot([peaks[index].hash, root]);
2609
+ return root;
2610
+ }
2611
+ };
2612
+ }
2613
+ /** One array item as `JSON.stringify` writes it: `JSON.parse` of it is what `events[i]` holds. */
2614
+ function storedText(event) {
2615
+ return JSON.stringify(event) ?? "null";
2616
+ }
2617
+ // src/runtime/supervise/upstream-unavailable.ts
2618
+ /** Shared capacity recognition and pause policy for drivers and retained leaves. */
2619
+ /** Legacy capacity codes for producers without the canonical failure contract. */
2620
+ const UNAVAILABLE_CODES = /* @__PURE__ */ new Set([
2621
+ "provider_quota_exhausted",
2622
+ "provider_quota_exceeded",
2623
+ "provider_rate_limit",
2624
+ "upstream_unavailable",
2625
+ "provider_key_invalid",
2626
+ "rate_limit_exceeded",
2627
+ "rate_limit_error",
2628
+ "overloaded_error",
2629
+ "capacity_exhausted",
2630
+ "host_pressure",
2631
+ "provisioning_paused"
2632
+ ]);
2633
+ /** 429 Too Many Requests, 503 Service Unavailable, and 529, which Anthropic uses for overload. */
2634
+ const UNAVAILABLE_STATUSES = /* @__PURE__ */ new Set([
2635
+ 429,
2636
+ 503,
2637
+ 529
2638
+ ]);
2639
+ /** Legacy text fallback reads whole code tokens and explicitly framed HTTP statuses. */
2640
+ function unavailableSignalInText(text) {
2641
+ for (const token of text.toLowerCase().matchAll(/[a-z_]+/gu)) if (UNAVAILABLE_CODES.has(token[0])) return token[0];
2642
+ const status = printedStatus(text);
2643
+ return status !== void 0 && UNAVAILABLE_STATUSES.has(status) ? `http-${status}` : void 0;
2644
+ }
2645
+ /** The HTTP status a harness printed in its `status code <n>` framing, if any. */
2646
+ const printedStatus = (text) => {
2647
+ const status = text.match(/\bstatus code (\d{3})\b/u)?.[1];
2648
+ return status === void 0 ? void 0 : Number(status);
2649
+ };
2650
+ /** Held room for an otherwise placeable shape is temporary capacity; oversized shapes stay refused. */
2651
+ const HELD_ROOM_REFUSAL = /\bits room is held placeable\b/u;
2652
+ /**
2653
+ * The code or status that marks a failed turn outcome as an upstream capacity refusal, or
2654
+ * `undefined`. The outcome's own `errorCode` decides first, with Sandbox's held-room text beside its
2655
+ * code; other text is read only when no code or numeric status decided, because a harness CLI can
2656
+ * report the router's refusal as text.
2657
+ */
2658
+ function unavailableSignalOfFailure(failure) {
2659
+ const typed = turnFailureOf(failure);
2660
+ if (typed) return turnFailurePolicy(typed).classification === "unavailable" ? typed.code : void 0;
2661
+ const code = failure.errorCode?.toLowerCase();
2662
+ if (code !== void 0 && UNAVAILABLE_CODES.has(code)) return code;
2663
+ if (code === "no_host_fits_shape" && HELD_ROOM_REFUSAL.test(failure.error)) return "host-room-held";
2664
+ if (failure.statusCode !== void 0) return UNAVAILABLE_STATUSES.has(failure.statusCode) ? `http-${failure.statusCode}` : void 0;
2665
+ return unavailableSignalInText(failure.error);
2666
+ }
2667
+ const DEFAULT_UNAVAILABLE_PAUSE_MS = 15e3;
2668
+ const DEFAULT_MAX_UNAVAILABLE_PAUSE_MS = 3e5;
2669
+ /**
2670
+ * The pause after the `consecutive`-th refusal in a row (1-based): the first pause, doubled per
2671
+ * earlier refusal, up to the ceiling. The one rule for a driver that re-enters and a leaf that
2672
+ * continues in its environment, so an outage costs both the same number of turns.
2673
+ */
2674
+ function unavailablePauseMs(consecutive, policy = {}) {
2675
+ return cappedDoublingMs(consecutive, policy.unavailablePauseMs ?? DEFAULT_UNAVAILABLE_PAUSE_MS, policy.maxUnavailablePauseMs ?? DEFAULT_MAX_UNAVAILABLE_PAUSE_MS);
2676
+ }
2677
+ /** `first` doubled per earlier consecutive wait (`consecutive` is 1-based), up to `ceiling`. */
2678
+ function cappedDoublingMs(consecutive, first, ceiling) {
2679
+ const start = Math.max(0, first);
2680
+ return Math.min(Math.max(start, ceiling), start * 2 ** Math.max(0, consecutive - 1));
2681
+ }
2682
+ /** The longest hold a refusal's own reset time may ask for: a 5-hour plan window plus a margin. */
2683
+ const MAX_RESET_HOLD_MS = 216e5;
2684
+ /** How often a refusal whose reset is beyond {@link MAX_RESET_HOLD_MS} is probed again. */
2685
+ const FAR_RESET_PROBE_MS = 36e5;
2686
+ /** Read canonical reset/retry-after before legacy structured reset fields; never parse text. */
2687
+ function reportedResetAt(error, nowMs = Date.now()) {
2688
+ const typed = turnFailureOf(error);
2689
+ if (typed) return typed.resetAt !== void 0 ? Date.parse(typed.resetAt) : typed.retryAfterMs !== void 0 ? nowMs + typed.retryAfterMs : void 0;
2690
+ for (const cause of causeChain(error)) {
2691
+ let value;
2692
+ try {
2693
+ value = Reflect.get(cause, "resetAt");
2694
+ } catch {
2695
+ continue;
2696
+ }
2697
+ const at = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : NaN;
2698
+ if (Number.isFinite(at)) return at;
2699
+ }
2700
+ }
2701
+ /**
2702
+ * Until when a reported reset holds a pause, or `undefined` for none (absent or past: the caller
2703
+ * keeps its doubling pause). A reset more than MAX_RESET_HOLD_MS ahead is held FAR_RESET_PROBE_MS
2704
+ * at a time; on magnetar-rust-20261019c a far reset drew about 12 attempts an hour.
2705
+ */
2706
+ function unavailableResumeAt(resetAt, nowMs) {
2707
+ if (resetAt === void 0 || resetAt <= nowMs) return void 0;
2708
+ return resetAt - nowMs > MAX_RESET_HOLD_MS ? nowMs + FAR_RESET_PROBE_MS : resetAt;
2709
+ }
2710
+ /**
2711
+ * Spread a wait over `[ms / 2, ms]`. Every driver a Platform restart cut off fails within the same
2712
+ * seconds; without jitter their doubling schedules stay aligned and they all re-enter together
2713
+ * when the service returns. `random` returns a value in `[0, 1)`; 0 keeps the full wait.
2714
+ */
2715
+ function jitteredMs(ms, random) {
2716
+ return ms - Math.floor(ms / 2 * Math.min(1, Math.max(0, random())));
2717
+ }
2718
+ // src/runtime/supervise/retained-executor.ts
2719
+ /** Scope owns the durable writer; provider executors only publish sanitized admissions. */
2720
+ const retainedExecutorSeamKey = "runtime.retainedExecutor";
2721
+ /** @internal A capture may finish after cancellation; its durable citation remains appendable. */
2722
+ function executorEvidenceWriter(args) {
2723
+ const traceRoots = args.traceRoots ?? traceRootWriter(args.blobs, args.nodeId);
2724
+ return async (out) => {
2725
+ const snapshot = detachedSnapshot(out, "executor evidence");
2726
+ const outRef = contentAddress(snapshot);
2727
+ await args.blobs.put(outRef, snapshot);
2728
+ const traceRoot = await traceRoots.writeEvidence(outRef, snapshot);
2729
+ await args.journal.appendEvent(args.rootId, {
2730
+ kind: "execution-evidence",
2731
+ id: args.nodeId,
2732
+ outRef,
2733
+ ...traceRoot === void 0 ? {} : { traceRoot },
2734
+ seq: args.nextSequence(),
2735
+ at: new Date(args.now()).toISOString()
2736
+ });
2737
+ };
2738
+ }
2739
+ function retainedExecutorContext(ctx) {
2740
+ return ctx.seams[retainedExecutorSeamKey];
2741
+ }
2742
+ const causeMessages = {
2743
+ unobservable: "retained provider execution requires reconciliation before replacement",
2744
+ "provider-contract": "retained provider response violated its contract; original execution remains unresolved",
2745
+ "request-rejected": "retained provider execution was refused before it ran; nothing to reconcile",
2746
+ transport: "retained provider execution lost its transport; status in doubt",
2747
+ "nested-recovery": "retained nested execution requires recovery before replacement"
2748
+ };
2749
+ /**
2750
+ * agent-provider-tangle's `TangleDispatchNotAdmittedError` (since 3.6.11): Sandbox answered a
2751
+ * dispatch with `dispatched: false` and named another execution that owns the session or turn.
2752
+ * Nothing ran for the request.
2753
+ */
2754
+ const DISPATCH_NOT_ADMITTED_CODE = "DISPATCH_NOT_ADMITTED";
2755
+ /**
2756
+ * agent-provider-tangle's `TangleDispatchExecutionChangedError` (since 5.0.8): Sandbox CONFIRMED
2757
+ * the dispatch but named an execution id other than the requested run's. The provider's own
2758
+ * answer violates its contract, identically on every retry (agent-sdk #475: 107 retries over
2759
+ * 39 minutes, all classed transient, before the run settled all-children-down).
2760
+ */
2761
+ const DISPATCH_EXECUTION_CHANGED_CODE = "DISPATCH_EXECUTION_CHANGED";
2762
+ /**
2763
+ * The Sandbox SDK's codes for a box that cannot be provisioned for this profile, by the HTTP status
2764
+ * each is sent with: a mount outside the box's writable roots and a materialization that would fail
2765
+ * the same way again (422), a mounted file changed on both sides since the last mount (409). Two
2766
+ * bare 500s are read by text: that conflict before Sandbox typed it, and two mounts of one target
2767
+ * (magnetar-rust-sandbox-20261031g's and 20261031h's managers retried them every turn). On run
2768
+ * queens21-h22-capture-root-1-20261019c 154 attempts across 4 workers retried a read-only mount of
2769
+ * `/work/queens21_count.c` as a lost transport. The same codes at another status may be transient.
2770
+ */
2771
+ const PROVISIONING_REFUSALS = /* @__PURE__ */ new Map([
2772
+ ["PROFILE_FILE_MOUNT_OUTSIDE_ROOTS", 422],
2773
+ ["PROFILE_FILES_MATERIALIZE_FAILED", 422],
2774
+ ["PROFILE_FILE_CONFLICT", 409]
2775
+ ]);
2776
+ const TEXT_REFUSALS = /Refusing to replace existing profile file: |Duplicate profile file target: /u;
2777
+ /** True for an error that is itself a deterministic provisioning refusal (see above). */
2778
+ const isProvisioningRefusal = (value) => refusedAs(PROVISIONING_REFUSALS, value) || value instanceof Error && TEXT_REFUSALS.test(errorProperty(value, "message") ?? "");
2779
+ /**
2780
+ * Platform refusals the orchestrator answers BEFORE it forwards a dispatch, by machine code and
2781
+ * the HTTP status it is sent with. Run 002f69d5: `HUB_CREDENTIAL_REFRESH_FAILED` at 503 left no
2782
+ * effect, yet read as a lost transport. Any other 5xx stays a transport failure, in doubt.
2783
+ */
2784
+ const PLATFORM_PREDISPATCH_REFUSALS = /* @__PURE__ */ new Map([["HUB_CREDENTIAL_REFRESH_FAILED", 503]]);
2785
+ /** True for an error that is itself a named platform refusal of a dispatch (see above). */
2786
+ const isPlatformPredispatchRefusal = (value) => refusedAs(PLATFORM_PREDISPATCH_REFUSALS, value);
2787
+ /** True when `value` carries one of `refusals`' codes at the status that code is sent with. */
2788
+ function refusedAs(refusals, value) {
2789
+ try {
2790
+ const code = readString(value, "code");
2791
+ const status = readNumber(value, "status") ?? readNumber(value, "statusCode");
2792
+ const expected = code === void 0 ? void 0 : refusals.get(code);
2793
+ return expected !== void 0 && expected === status;
2794
+ } catch {
2795
+ return false;
2796
+ }
2797
+ }
2798
+ /** The contract-error codes that wrap a failed READ rather than name a broken answer. */
2799
+ const readFailureCodes = /* @__PURE__ */ new Set(["RETAINED_RESULT_READ_FAILED", "RETAINED_CONTROL_REF_READ_FAILED"]);
2800
+ /** Socket-level failures, by the codes Node and undici assign, plus the Sandbox SDK's own. */
2801
+ const TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
2802
+ "ECONNRESET",
2803
+ "ECONNREFUSED",
2804
+ "ETIMEDOUT",
2805
+ "ENOTFOUND",
2806
+ "EAI_AGAIN",
2807
+ "EPIPE",
2808
+ "UND_ERR_SOCKET",
2809
+ "UND_ERR_CONNECT_TIMEOUT",
2810
+ "UND_ERR_HEADERS_TIMEOUT",
2811
+ "UND_ERR_BODY_TIMEOUT",
2812
+ "NETWORK_ERROR"
2813
+ ]);
2814
+ /** Refused by a schema or bound, the same way every attempt: agent-provider-tangle's JsonBoundError
2815
+ * (#1204's exhibit 6) or the Sandbox SDK refusing a capability document as HTTP 502, which
2816
+ * institutional-compiler-20261031c:s14 retried 44 times as a lost transport. */
2817
+ function isSchemaRejection(value) {
2818
+ const code = readString(value, "code");
2819
+ return readString(value, "name") === "ZodError" || Array.isArray(Reflect.get(value, "issues")) || code === "JSON_BOUND_VIOLATION" || code === "INVALID_CAPABILITY_DOCUMENT";
2820
+ }
2821
+ function readNumber(value, key) {
2822
+ const read = Reflect.get(value, key);
2823
+ return typeof read === "number" && Number.isFinite(read) ? read : void 0;
2824
+ }
2825
+ function readString(value, key) {
2826
+ const read = Reflect.get(value, key);
2827
+ return typeof read === "string" ? read : void 0;
2828
+ }
2829
+ const credentialAdmissionRefusals = /* @__PURE__ */ new WeakSet();
2830
+ /**
2831
+ * Walk the cause chain (bounded, cycle-safe) and name the first cause whose structure decides.
2832
+ *
2833
+ * `phase` says whether a 4xx or a client deadline can mean "refused before it ran": only at
2834
+ * admission. After admission the same status means the provider cannot resolve what it
2835
+ * admitted, and the honest name is the refusal.
2836
+ */
2837
+ function classifyRetainedPendingCause(cause, phase = "execution", onCredentialRefusal) {
2838
+ const seen = /* @__PURE__ */ new Set();
2839
+ const queue = [{
2840
+ value: cause,
2841
+ phase
2842
+ }];
2843
+ let steps = 0;
2844
+ while (queue.length > 0 && steps < 12) {
2845
+ steps += 1;
2846
+ const { value, phase: at } = queue.shift();
2847
+ if (typeof value !== "object" || value === null || seen.has(value)) continue;
2848
+ seen.add(value);
2849
+ if (value instanceof RetainedExecutionPendingError) {
2850
+ if (credentialAdmissionRefusals.has(value)) {
2851
+ if (at === "execution") return "unobservable";
2852
+ onCredentialRefusal?.();
2853
+ }
2854
+ return value.pendingCause;
2855
+ }
2856
+ const name = readString(value, "name");
2857
+ const code = readString(value, "code");
2858
+ const status = readNumber(value, "status") ?? readNumber(value, "statusCode");
2859
+ if (name === "RetainedRunProviderContractError") {
2860
+ if (code === void 0 || !readFailureCodes.has(code)) return "provider-contract";
2861
+ queue.unshift({
2862
+ value: Reflect.get(value, "cause"),
2863
+ phase: "execution"
2864
+ });
2865
+ continue;
2866
+ }
2867
+ if (isSchemaRejection(value)) return at === "admission" ? "request-rejected" : "provider-contract";
2868
+ if (code === "DISPATCH_NOT_ADMITTED") return at === "admission" ? "request-rejected" : "provider-contract";
2869
+ if (code === "DISPATCH_EXECUTION_CHANGED") return "provider-contract";
2870
+ if (isProvisioningRefusal(value)) return "request-rejected";
2871
+ if (isCredentialRefusal(value)) {
2872
+ if (at === "execution") return "unobservable";
2873
+ onCredentialRefusal?.();
2874
+ return "request-rejected";
2875
+ }
2876
+ if (code !== void 0 && TRANSPORT_ERROR_CODES.has(code)) return "transport";
2877
+ if (at === "admission" && isPlatformPredispatchRefusal(value)) return "request-rejected";
2878
+ if (name === "NetworkError" || name === "ServerError") return "transport";
2879
+ if (status === void 0 && at === "admission" && code !== void 0 && UNAVAILABLE_CODES.has(code.toLowerCase())) return "request-rejected";
2880
+ if (status !== void 0) {
2881
+ if (status >= 500) return "transport";
2882
+ if (at === "admission" && status !== 408) return "request-rejected";
2883
+ return "unobservable";
2884
+ }
2885
+ const errors = Reflect.get(value, "errors");
2886
+ if (Array.isArray(errors)) for (const member of errors) queue.push({
2887
+ value: member,
2888
+ phase: at
2889
+ });
2890
+ queue.push({
2891
+ value: Reflect.get(value, "cause"),
2892
+ phase: at
2893
+ });
2894
+ }
2895
+ return "unobservable";
2896
+ }
2897
+ /**
2898
+ * Local observation stopped; the retained provider execution has no accepted terminal result.
2899
+ *
2900
+ * The message names WHICH of the situations in {@link RetainedPendingCause} this is, and the
2901
+ * `pendingCause` field carries it as a value the settlement records, so a reader never splits
2902
+ * the population on the message's wording. The cause chain is kept for the `caused by` receipt.
2903
+ */
2904
+ var RetainedExecutionPendingError = class extends Error {
2905
+ pendingCause;
2906
+ phase;
2907
+ constructor(cause, pendingCause = "execution") {
2908
+ let credentialRefused = false;
2909
+ const resolved = pendingCause === "admission" || pendingCause === "execution" ? classifyRetainedPendingCause(cause, pendingCause, () => {
2910
+ credentialRefused = true;
2911
+ }) : pendingCause;
2912
+ super(causeMessages[resolved], { cause });
2913
+ this.name = "RetainedExecutionPendingError";
2914
+ this.pendingCause = resolved;
2915
+ this.phase = pendingCause === "admission" ? "admission" : "execution";
2916
+ if (credentialRefused) credentialAdmissionRefusals.add(this);
2917
+ }
2918
+ };
2919
+ /** The instruction a keyed continuation runs in the held session: the node's task is unchanged,
2920
+ * and its conversation and workspace are where the budget stop left them. */
2921
+ const BUDGET_CONTINUATION_TASK = "Your previous turn reached its budget and stopped. Your manager gave you more budget to continue the same task in the same session: your conversation so far and the files in your workspace are where you left them. Continue from where you stopped. Do not start over.";
2922
+ /** The execution id of a leaf's later invocation, derived from its `execution-input` sequence so
2923
+ * a recovery derives the same one. A first invocation keeps the node id. */
2924
+ function leafContinuationExecutionId(nodeId, inputSeq) {
2925
+ return `${nodeId}:input:${inputSeq}`;
2926
+ }
2927
+ const retainedPreparations = /* @__PURE__ */ new WeakMap();
2928
+ /** Reconstruct an admitted worker through its original composition boundary. @internal */
2929
+ function registerRetainedExecutorPreparation(factory, prepare) {
2930
+ retainedPreparations.set(factory, prepare);
2931
+ return factory;
2932
+ }
2933
+ function prepareRetainedExecutor(factory, input) {
2934
+ return retainedPreparations.get(factory)?.(input);
2935
+ }
2936
+ // src/runtime/failure-cause.ts
2937
+ const MAX_CAUSE_CHARS = 2048;
2938
+ const MACHINE_CODE_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u;
2939
+ /** @internal Canonical producer-supplied remediation, shared by transport and read models. */
2940
+ const runtimeFailureRemediationSchema = z.object({
2941
+ cause: z.enum([
2942
+ "api_key_selected",
2943
+ "provider_unresolved",
2944
+ "subscription_unverified",
2945
+ "not_authenticated"
2946
+ ]),
2947
+ fix: z.string().min(1).max(256),
2948
+ harness: z.string().min(1).max(64),
2949
+ provider: z.string().min(1).max(128).nullable()
2950
+ });
2951
+ /** @internal Validate Runtime-owned failure values on observation transports. */
2952
+ const runtimeFailureCauseSchema = z.object({
2953
+ code: z.enum([
2954
+ "aborted",
2955
+ "deadline-exceeded",
2956
+ "budget-exhausted",
2957
+ "credential-refused",
2958
+ "request-rejected",
2959
+ "upstream-unavailable",
2960
+ "transport",
2961
+ "provider-contract",
2962
+ "retained-unobservable",
2963
+ "nested-recovery",
2964
+ "platform",
2965
+ "work-failed",
2966
+ "unknown"
2967
+ ]),
2968
+ owner: z.enum([
2969
+ "provider",
2970
+ "platform",
2971
+ "runtime",
2972
+ "work",
2973
+ "caller",
2974
+ "unknown"
2975
+ ]),
2976
+ cause: z.string().max(MAX_CAUSE_CHARS),
2977
+ /** The upstream or provider machine code the failure carried, when it carried one. */
2978
+ providerCode: z.string().regex(MACHINE_CODE_PATTERN).optional(),
2979
+ /** The HTTP status the provider's typed error carried with that code. */
2980
+ providerStatus: z.number().int().min(100).max(599).optional(),
2981
+ /** The provider's typed retry-after hint, in milliseconds. A hint, never an automatic retry. */
2982
+ retryAfterMs: z.number().int().nonnegative().optional(),
2983
+ remediation: runtimeFailureRemediationSchema.readonly().optional()
2984
+ }).readonly();
2985
+ const retainedFailures = {
2986
+ unobservable: {
2987
+ code: "retained-unobservable",
2988
+ owner: "provider"
2989
+ },
2990
+ "provider-contract": {
2991
+ code: "provider-contract",
2992
+ owner: "provider"
2993
+ },
2994
+ "request-rejected": {
2995
+ code: "request-rejected",
2996
+ owner: "caller"
2997
+ },
2998
+ transport: {
2999
+ code: "transport",
3000
+ owner: "platform"
3001
+ },
3002
+ "nested-recovery": {
3003
+ code: "nested-recovery",
3004
+ owner: "runtime"
3005
+ }
3006
+ };
3007
+ function read(value, key) {
3008
+ try {
3009
+ return Reflect.get(value, key);
3010
+ } catch {
3011
+ return;
3012
+ }
3013
+ }
3014
+ const UNATTRIBUTED = {
3015
+ code: "unknown",
3016
+ owner: "unknown"
3017
+ };
3018
+ /** One link's own structure: budget refusal, credential refusal, machine code, HTTP status. */
3019
+ function structuralFailure(link) {
3020
+ if (link instanceof ReservationWaitRefused || read(link, "reason") === "budget-exhausted") return {
3021
+ code: "budget-exhausted",
3022
+ owner: "caller"
3023
+ };
3024
+ const code = upstreamMachineCode([link]);
3025
+ if (isCredentialRefusal(link) || code === "SEAT_NOT_LOGGED_IN") return {
3026
+ code: "credential-refused",
3027
+ owner: "caller"
3028
+ };
3029
+ const status = read(link, "status") ?? read(link, "statusCode");
3030
+ if (code === "MODEL_NOT_FOUND") return {
3031
+ code: "request-rejected",
3032
+ owner: "caller"
3033
+ };
3034
+ if (typeof code === "string" && UNAVAILABLE_CODES.has(code.toLowerCase())) return {
3035
+ code: "upstream-unavailable",
3036
+ owner: "platform"
3037
+ };
3038
+ if (typeof status === "number" && Number.isInteger(status)) {
3039
+ if (UNAVAILABLE_STATUSES.has(status)) return {
3040
+ code: "upstream-unavailable",
3041
+ owner: "platform"
3042
+ };
3043
+ if (status >= 500 || status === 0 || status === 408) return {
3044
+ code: "transport",
3045
+ owner: "platform"
3046
+ };
3047
+ if (status === 401 || status === 403) return {
3048
+ code: "credential-refused",
3049
+ owner: "caller"
3050
+ };
3051
+ if (status >= 400) return {
3052
+ code: "request-rejected",
3053
+ owner: "caller"
3054
+ };
3055
+ }
3056
+ if (typeof code === "string" && TRANSPORT_ERROR_CODES.has(code)) return {
3057
+ code: "transport",
3058
+ owner: "platform"
3059
+ };
3060
+ if (typeof code === "string" && PLATFORM_FAILURE_CODES.has(code.toLowerCase())) return {
3061
+ code: "platform",
3062
+ owner: "platform"
3063
+ };
3064
+ const name = read(link, "name");
3065
+ if (name === "NetworkError" || name === "ServerError") return {
3066
+ code: "transport",
3067
+ owner: "platform"
3068
+ };
3069
+ }
3070
+ /** @internal The same machine-code validation used by public failure values. */
3071
+ function runtimeProviderCode(value) {
3072
+ return typeof value === "string" && MACHINE_CODE_PATTERN.test(value) ? value : void 0;
3073
+ }
3074
+ function upstreamMachineCode(links) {
3075
+ const typed = links.map(turnFailureOf).find((value) => value !== void 0);
3076
+ if (typed) return runtimeProviderCode(typed.code);
3077
+ return [
3078
+ "upstreamCode",
3079
+ "errorCode",
3080
+ "code"
3081
+ ].flatMap((field) => links.map((link) => runtimeProviderCode(read(link, field)))).find((code) => code !== void 0);
3082
+ }
3083
+ /** The typed HTTP status and retry-after of the link carrying the provider's code. */
3084
+ function upstreamResponse(links, providerCode) {
3085
+ const typed = links.map(turnFailureOf).find((value) => value !== void 0);
3086
+ if (typed?.retryAfterMs !== void 0) return { retryAfterMs: typed.retryAfterMs };
3087
+ const link = links.find((each) => [
3088
+ "upstreamCode",
3089
+ "errorCode",
3090
+ "code"
3091
+ ].some((field) => read(each, field) === providerCode));
3092
+ if (providerCode === void 0 || link === void 0) return {};
3093
+ const status = read(link, "status") ?? read(link, "statusCode");
3094
+ const retryAfterMs = read(link, "retryAfterMs");
3095
+ return {
3096
+ ...Number.isInteger(status) && status >= 100 && status <= 599 ? { providerStatus: status } : {},
3097
+ ...Number.isInteger(retryAfterMs) && retryAfterMs >= 0 ? { retryAfterMs } : {}
3098
+ };
3099
+ }
3100
+ /**
3101
+ * Classify a thrown failure. Pass the caller's signal so a cancellation the caller asked for is
3102
+ * attributed to the caller even when the provider surfaced it as an ordinary error, and say when
3103
+ * the operation's own deadline expired so a blown deadline is never reported as a cancellation.
3104
+ */
3105
+ function runtimeFailureCause(error, context = {}) {
3106
+ const cause = errMessage(error).slice(0, MAX_CAUSE_CHARS);
3107
+ const caller = context.signal?.aborted ? "aborted" : context.deadlineExpired ? "deadline-exceeded" : void 0;
3108
+ try {
3109
+ const links = causeChain(error);
3110
+ const providerCode = upstreamMachineCode(links);
3111
+ const upstream = links.find((link) => link instanceof BackendTransportError && link.backend === "bridge" && link.status === 403 && link.upstreamCode === "subscription_required" && link.providerDispatch === "not_started");
3112
+ const remedy = runtimeFailureRemediationSchema.readonly().safeParse(upstream?.remediation);
3113
+ const failure = ({ code, owner }) => ({
3114
+ code,
3115
+ owner,
3116
+ cause,
3117
+ ...providerCode === void 0 ? {} : { providerCode },
3118
+ ...upstreamResponse(links, providerCode),
3119
+ ...code === "credential-refused" && providerCode === "subscription_required" && remedy.success ? { remediation: remedy.data } : {}
3120
+ });
3121
+ if (caller !== void 0) return failure({
3122
+ code: caller,
3123
+ owner: "caller"
3124
+ });
3125
+ for (const link of links) {
3126
+ if (link instanceof RetainedExecutionPendingError && link.pendingCause === "provider-contract") return failure(retainedFailures["provider-contract"]);
3127
+ if (read(link, "name") === "RetainedRunProviderContractError") return failure(retainedFailures[classifyRetainedPendingCause(link)]);
3128
+ }
3129
+ const typed = error instanceof AgentEvalError && !(error instanceof BackendTransportError) ? void 0 : turnFailureOf(error);
3130
+ if (typed) return failure(turnFailurePolicy(typed));
3131
+ if (context.signal === void 0 && links.some((link) => read(link, "name") === "AbortError")) return failure({
3132
+ code: "aborted",
3133
+ owner: "caller"
3134
+ });
3135
+ for (const link of links) {
3136
+ if (link instanceof RetainedExecutionPendingError) {
3137
+ if (link.pendingCause === "request-rejected" && links.some(isPlatformPredispatchRefusal)) return failure({
3138
+ code: "request-rejected",
3139
+ owner: "platform"
3140
+ });
3141
+ return failure(retainedFailures[link.pendingCause]);
3142
+ }
3143
+ if (read(link, "name") === "RetainedRunProviderContractError") return failure(retainedFailures[classifyRetainedPendingCause(link)]);
3144
+ }
3145
+ for (const link of links) {
3146
+ const classified = structuralFailure(link);
3147
+ if (classified !== void 0) return failure(classified);
3148
+ }
3149
+ return failure(UNATTRIBUTED);
3150
+ } catch {
3151
+ return {
3152
+ ...caller === void 0 ? UNATTRIBUTED : {
3153
+ code: caller,
3154
+ owner: "caller"
3155
+ },
3156
+ cause
3157
+ };
3158
+ }
3159
+ }
3160
+ /**
3161
+ * Classify a failure the execution reported without throwing — a Sandbox outcome or executor
3162
+ * envelope with `success: false` — from its machine code and HTTP status. A harness that reports
3163
+ * a failure with neither does not say who must act, so it is `unknown`, never the work's fault.
3164
+ */
3165
+ function reportedFailureCause(outcome) {
3166
+ return runtimeFailureCause(Object.assign(new Error(outcome.error ?? "execution reported a failure"), {
3167
+ errorCode: outcome.errorCode,
3168
+ statusCode: outcome.statusCode,
3169
+ failure: outcome.failure
3170
+ }));
3171
+ }
3172
+ /**
3173
+ * Classify a down settlement from the typed facts Runtime recorded while the cause was still a
3174
+ * value: the retained cause, the failure classified where the executor threw, then `infra: false`,
3175
+ * the throw path's statement that the work itself failed. `infra: true` is not an owner: Runtime
3176
+ * also sets it for cancellations, budget reconcile faults and validation errors, and from the
3177
+ * platform's failure messages, so a settlement with nothing else typed is `unknown`.
3178
+ */
3179
+ function settlementFailureCause(down) {
3180
+ const cause = errMessage(down.reason).slice(0, MAX_CAUSE_CHARS);
3181
+ if (down.retainedPendingCause !== void 0) {
3182
+ const retained = retainedFailures[down.retainedPendingCause];
3183
+ if (down.failure !== void 0 && down.failure.code === retained.code) return {
3184
+ ...down.failure,
3185
+ cause
3186
+ };
3187
+ return {
3188
+ ...retained,
3189
+ cause,
3190
+ ...down.failure?.providerCode === void 0 ? {} : { providerCode: down.failure.providerCode }
3191
+ };
3192
+ }
3193
+ if (down.failure !== void 0 && down.failure.code !== "unknown") return {
3194
+ ...down.failure,
3195
+ cause
3196
+ };
3197
+ return {
3198
+ ...down.infra === false ? {
3199
+ code: "work-failed",
3200
+ owner: "work"
3201
+ } : UNATTRIBUTED,
3202
+ cause,
3203
+ ...down.failure?.providerCode === void 0 ? {} : { providerCode: down.failure.providerCode }
3204
+ };
3205
+ }
3206
+ export { assertValidBudget as $, TRACE_SUMMARY_SCHEMA as A, credentialCommandExit as B, jitteredMs as C, parseCodexUsageRecord as Ct, unavailableResumeAt as D, unavailablePauseMs as E, executorFailureInfra as F, budgetRecoverySeeds as G, BudgetReconcileFault as H, executorFailureReason as I, refreshBudgetLease as J, completedLeafBacking as K, turnFailureOf as L, contentAddress as M, contentRef as N, unavailableSignalOfFailure as O, executorFailure as P, spendFromUsageTotals as Q, turnFailurePolicy as R, cappedDoublingMs as S, decodeHarnessUsage as St, reportedResetAt as T, budgetLeaseUpdates as U, isCredentialRefusal as V, budgetLeases as W, newUsageTotals as X, meterUsageEvent as Y, spendFromUsageEvents as Z, registerRetainedExecutorPreparation as _, notifySandboxEventObserver as _t, runtimeProviderCode as a, sandboxOutputMarker as at, UNAVAILABLE_CODES as b, sandboxTerminalUsageField as bt, DISPATCH_EXECUTION_CHANGED_CODE as c, canonicalStreamEventFromSandboxEvent as ct, TRANSPORT_ERROR_CODES as d, assertSandboxServedModel as dt, assertValidSpend as et, executorEvidenceWriter as f, canonicalSandboxUsageMode as ft, prepareRetainedExecutor as g, isSandboxTerminalEvent as gt, leafContinuationExecutionId as h, extractLlmCallEvent as ht, runtimeFailureRemediationSchema as i, sandboxLeafOutputFromEvents as it, traceRootWriter as j, TRACE_ROOT_SCHEMA as k, DISPATCH_NOT_ADMITTED_CODE as l, extractTransportEventIdentity as lt, isSchemaRejection as m, createSandboxUsageLedger as mt, runtimeFailureCause as n, mapSandboxEvent as nt, settlementFailureCause as o, sandboxProgressEvents as ot, isProvisioningRefusal as p, createSandboxTurnEventCollector as pt, createBudgetPool as q, runtimeFailureCauseSchema as r, mapSandboxToolEvent as rt, BUDGET_CONTINUATION_TASK as s, terminalTextFromSandboxEvent as st, reportedFailureCause as t, createSandboxToolPartState as tt, RetainedExecutionPendingError as u, parseCanonicalTransportEvent as ut, retainedExecutorContext as v, sameModelId as vt, printedStatus as w, recordValue as wt, UNAVAILABLE_STATUSES as x, sumSandboxUsage as xt, retainedExecutorSeamKey as y, sandboxEventServedBackend as yt, hashJson as z };
3207
+
3208
+ //# sourceMappingURL=failure-cause-BzjUUsRz.js.map