@tangle-network/agent-runtime 1.0.0 → 2.0.1

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 (96) hide show
  1. package/dist/{activation-CFS31SWI.d.ts → activation-BuK2H7qx.d.ts} +2 -2
  2. package/dist/{activation-BwoSqHCc.js → activation-ZQWz04u8.js} +4 -4
  3. package/dist/{activation-BwoSqHCc.js.map → activation-ZQWz04u8.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +4 -3
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{bundle-DeDkJbsr.js → bundle-PDYNXIEf.js} +2 -2
  8. package/dist/{bundle-DeDkJbsr.js.map → bundle-PDYNXIEf.js.map} +1 -1
  9. package/dist/candidate-execution/index.js +4 -4
  10. package/dist/{coordination-manager-ewBF777W.js → coordination-manager-BZLp9qpE.js} +8 -363
  11. package/dist/coordination-manager-BZLp9qpE.js.map +1 -0
  12. package/dist/coordination-map-routing-CUvwHAtv.js +362 -0
  13. package/dist/coordination-map-routing-CUvwHAtv.js.map +1 -0
  14. package/dist/{delegate-BiuSfwBa.js → delegate-C-MUU6ML.js} +2 -2
  15. package/dist/{delegate-BiuSfwBa.js.map → delegate-C-MUU6ML.js.map} +1 -1
  16. package/dist/durable-file-CksURHlH.js +1 -0
  17. package/dist/durable-file-DstVeHcj.js +228 -0
  18. package/dist/durable-file-DstVeHcj.js.map +1 -0
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +10 -8
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{graph-D6FL1xze.js → graph-CM-6CV_K.js} +6 -5
  23. package/dist/{graph-D6FL1xze.js.map → graph-CM-6CV_K.js.map} +1 -1
  24. package/dist/graph-registry-72DlMnUl.js +585 -0
  25. package/dist/graph-registry-72DlMnUl.js.map +1 -0
  26. package/dist/graph-registry-CAX15LO6.js +1 -0
  27. package/dist/{improve-SiKDcz5_.js → improve-BuZ-I8DP.js} +9 -8
  28. package/dist/{improve-SiKDcz5_.js.map → improve-BuZ-I8DP.js.map} +1 -1
  29. package/dist/index.d.ts +3 -3
  30. package/dist/index.js +12 -11
  31. package/dist/index.js.map +1 -1
  32. package/dist/intelligence.d.ts +2 -2
  33. package/dist/intelligence.js +7 -7
  34. package/dist/{journal-store-BJPMUydp.js → journal-store-BpCOCDoO.js} +208 -635
  35. package/dist/journal-store-BpCOCDoO.js.map +1 -0
  36. package/dist/jsonl-file-BBP9Dz9w.js +429 -0
  37. package/dist/jsonl-file-BBP9Dz9w.js.map +1 -0
  38. package/dist/kernel.d.ts +1 -1
  39. package/dist/kernel.js +13 -12
  40. package/dist/{loop-runner-CqlcC0i4.js → loop-runner-BWD6v1rd.js} +2 -2
  41. package/dist/{loop-runner-CqlcC0i4.js.map → loop-runner-BWD6v1rd.js.map} +1 -1
  42. package/dist/{loop-runner-D9rcTNf2.d.ts → loop-runner-BpLTU_J4.d.ts} +2 -2
  43. package/dist/loop-runner-bin.d.ts +1 -1
  44. package/dist/loop-runner-bin.js +1 -1
  45. package/dist/mcp/bin.js +3 -3
  46. package/dist/mcp/index.d.ts +1 -1
  47. package/dist/mcp/index.js +5 -5
  48. package/dist/{prepare-XWwsOh8O.js → prepare-Bv6X2Wnx.js} +4 -4
  49. package/dist/{prepare-XWwsOh8O.js.map → prepare-Bv6X2Wnx.js.map} +1 -1
  50. package/dist/{profile-C01SQZKa.js → profile-Dir2A1_2.js} +2 -2
  51. package/dist/{profile-C01SQZKa.js.map → profile-Dir2A1_2.js.map} +1 -1
  52. package/dist/profiles.d.ts +1 -1
  53. package/dist/{provision-supervisor-DnwR0AyW.js → provision-supervisor-BWEeWag1.js} +8 -6
  54. package/dist/{provision-supervisor-DnwR0AyW.js.map → provision-supervisor-BWEeWag1.js.map} +1 -1
  55. package/dist/{run-cancellation-CoJRKvih.js → run-cancellation-Cpm-BIUu.js} +3 -2
  56. package/dist/{run-cancellation-CoJRKvih.js.map → run-cancellation-Cpm-BIUu.js.map} +1 -1
  57. package/dist/{runtime-DSYZeav8.js → runtime-Cnr3213E.js} +18 -15
  58. package/dist/{runtime-DSYZeav8.js.map → runtime-Cnr3213E.js.map} +1 -1
  59. package/dist/{sandbox-profile-compat-CXjozdWL.js → sandbox-profile-compat-DRiz9kME.js} +2 -2
  60. package/dist/{sandbox-profile-compat-CXjozdWL.js.map → sandbox-profile-compat-DRiz9kME.js.map} +1 -1
  61. package/dist/{search-executor-DcGAOrAh.js → search-executor-__X1VKnU.js} +5 -5
  62. package/dist/{search-executor-DcGAOrAh.js.map → search-executor-__X1VKnU.js.map} +1 -1
  63. package/dist/{server-SrPLb8w0.js → server-CntFSTpW.js} +4 -4
  64. package/dist/{server-SrPLb8w0.js.map → server-CntFSTpW.js.map} +1 -1
  65. package/dist/{structural-rollout-C_lg83-u.js → structural-rollout-s8W19Mws.js} +5 -5
  66. package/dist/{structural-rollout-C_lg83-u.js.map → structural-rollout-s8W19Mws.js.map} +1 -1
  67. package/dist/{supervise-BXw89Ajc.js → supervise-Cl0F57m9.js} +32 -647
  68. package/dist/supervise-Cl0F57m9.js.map +1 -0
  69. package/dist/{supervision-discovery-CewADdEs.js → supervision-discovery-C3t0Xw-T.js} +5 -158
  70. package/dist/supervision-discovery-C3t0Xw-T.js.map +1 -0
  71. package/dist/{supervisor-hHU3ZJnR.js → supervisor-L7u3pQ1j.js} +99 -150
  72. package/dist/supervisor-L7u3pQ1j.js.map +1 -0
  73. package/dist/task-queue-DbpZAp6C.js +49 -0
  74. package/dist/task-queue-DbpZAp6C.js.map +1 -0
  75. package/dist/task-queue.js +1 -49
  76. package/dist/testing.d.ts +1 -1
  77. package/dist/testing.js +13 -13
  78. package/dist/top-web-CkXPPXjI.js +1114 -0
  79. package/dist/top-web-CkXPPXjI.js.map +1 -0
  80. package/dist/tui/bin.js +4 -3
  81. package/dist/tui/bin.js.map +1 -1
  82. package/dist/tui/index.d.ts +22 -2
  83. package/dist/tui/index.js +3 -3
  84. package/dist/{types-DTHxh4X9.d.ts → types-BfnQq-_k.d.ts} +17 -21
  85. package/dist/{util-ebWMWzY0.js → util-BX20UJ9X.js} +2 -2
  86. package/dist/{util-ebWMWzY0.js.map → util-BX20UJ9X.js.map} +1 -1
  87. package/package.json +4 -4
  88. package/skills/agent-graphs/references/authoring.md +1 -0
  89. package/dist/coordination-manager-ewBF777W.js.map +0 -1
  90. package/dist/journal-store-BJPMUydp.js.map +0 -1
  91. package/dist/supervise-BXw89Ajc.js.map +0 -1
  92. package/dist/supervision-discovery-CewADdEs.js.map +0 -1
  93. package/dist/supervisor-hHU3ZJnR.js.map +0 -1
  94. package/dist/task-queue.js.map +0 -1
  95. package/dist/top-snapshot-DcV7VG4m.js +0 -520
  96. package/dist/top-snapshot-DcV7VG4m.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"journal-store-BJPMUydp.js","names":["plainRecord","plainRecord","fsConstants"],"sources":["../src/record-value.ts","../src/runtime/harness-usage.ts","../src/runtime/sandbox-events.ts","../src/runtime/timestamps.ts","../src/runtime/sandbox-transport-events.ts","../src/runtime/sandbox-executor-output.ts","../src/runtime/supervise/spend-validation.ts","../src/runtime/supervise/budget-ledger.ts","../src/runtime/supervise/usage-metering.ts","../src/runtime/supervise/budget.ts","../src/redact.ts","../src/runtime/supervise/error-message.ts","../src/runtime/supervise/credential-refusal.ts","../src/runtime/json-content-hash.ts","../src/runtime/supervise/executor-outcome.ts","../src/durable/content-address.ts","../src/runtime/supervise/snapshot.ts","../src/runtime/supervise/trace-root.ts","../src/runtime/supervise/upstream-unavailable.ts","../src/runtime/supervise/retained-executor.ts","../src/runtime/failure-cause.ts","../src/content-digest.ts","../src/durable/run-fence.ts","../src/runtime/supervise/durable-file.ts","../src/durable/spawn-journal/event-index.ts","../src/durable/jsonl-append.ts","../src/durable/jsonl-file.ts","../src/durable/spawn-journal/record-events.ts","../src/durable/spawn-journal/journal-store.ts"],"sourcesContent":["import { isRecord } from '@tangle-network/agent-core'\n\nexport function recordValue(value: unknown): Record<string, unknown> | undefined {\n return isRecord(value) ? value : undefined\n}\n","/**\n * Harness-native token-usage decoders — the ONE registry of per-harness usage wire shapes.\n *\n * A sandbox backend that reports usage under a canonical event (`llm_call`, `cost.usage`,\n * `usage`, or a terminal `usage` / `tokenUsage` record) is read by `extractLlmCallEvent`\n * (`sandbox-events.ts`). A harness that reports usage ONLY inside its own event needs an adapter,\n * and every such adapter lives here — the same rule the tool-part decoders follow\n * (`supervise/trace-source.ts`): one entry per harness family, each owning its real wire shape,\n * while the kernel's accounting stays harness-agnostic.\n *\n * A worker whose usage no reader decodes settles with `tokensKnown: false` and pays nothing into\n * the conserved budget pool, so equal-compute accounting cannot see it. That is why a decode\n * failure here is a typed error rather than a skip: a usage receipt the runtime cannot read must\n * not settle as a turn that spent nothing. The live-stream paths turn the typed error into a\n * settled failure that carries the message; the post-hoc readers degrade to `tokensKnown: false`.\n *\n * This module also owns `parseCodexUsageRecord`, the single reader of codex's `turn.completed`\n * usage record. `runLocalHarness` reads the same record off `codex exec --json` stdout and calls\n * the same function, so both surfaces hold the same field policy and the same two cross-field\n * invariants.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport { recordValue as plainRecord } from '../record-value'\n\n/**\n * Codex's `turn.completed` usage record, validated.\n *\n * Four counters are required, which is the set every observed codex build reports.\n * `cacheWriteInputTokens` is optional: the codex CLI reports it and a provider-normalized capture\n * omits it, and an absent counter must stay absent rather than become a zero that claims the\n * provider measured no cache write.\n */\ninterface CodexUsageRecord {\n /** Total prompt tokens for the turn, the cached ones included. */\n readonly inputTokens: number\n /** The part of `inputTokens` the provider served from its prompt cache. */\n readonly cachedInputTokens: number\n /** Total completion tokens for the turn, the reasoning ones included. */\n readonly outputTokens: number\n /** The part of `outputTokens` the model spent on reasoning. */\n readonly reasoningOutputTokens: number\n /** The part of `inputTokens` the provider wrote into its prompt cache. */\n readonly cacheWriteInputTokens?: number\n}\n\n/**\n * Read and validate one codex `turn.completed` usage record.\n *\n * Every counter must be a non-negative safe integer. Two cross-field invariants hold, and they are\n * what states that the two named counters are SUBSETS of their totals rather than additions to\n * them: `cached_input_tokens <= input_tokens` and `reasoning_output_tokens <= output_tokens`.\n * Measured against the codex CLI: a turn reporting `output_tokens 1523` with\n * `reasoning_output_tokens 1516` answered with about seven tokens of text.\n *\n * `label` names the surface the record came from, so one message serves both readers.\n * Throws `ValidationError` on any violation.\n */\nexport function parseCodexUsageRecord(usage: unknown, label: string): CodexUsageRecord {\n const record = plainRecord(usage)\n if (record === undefined) {\n throw new ValidationError(`${label}: usage must be an object, received ${describe(usage)}`)\n }\n const inputTokens = naturalNumber(record.input_tokens, 'input_tokens', label)\n const cachedInputTokens = naturalNumber(record.cached_input_tokens, 'cached_input_tokens', label)\n const outputTokens = naturalNumber(record.output_tokens, 'output_tokens', label)\n const reasoningOutputTokens = naturalNumber(\n record.reasoning_output_tokens,\n 'reasoning_output_tokens',\n label,\n )\n const cacheWriteInputTokens =\n record.cache_write_input_tokens === undefined\n ? undefined\n : naturalNumber(record.cache_write_input_tokens, 'cache_write_input_tokens', label)\n if (cachedInputTokens > inputTokens) {\n throw new ValidationError(`${label}: cached_input_tokens exceeds input_tokens`)\n }\n if (reasoningOutputTokens > outputTokens) {\n throw new ValidationError(`${label}: reasoning_output_tokens exceeds output_tokens`)\n }\n return {\n inputTokens,\n cachedInputTokens,\n outputTokens,\n reasoningOutputTokens,\n ...(cacheWriteInputTokens === undefined ? {} : { cacheWriteInputTokens }),\n }\n}\n\n/**\n * One harness's own token-usage report for one turn, in the runtime's field names.\n *\n * `input` is the provider's TOTAL prompt count and `output` is its TOTAL completion count.\n * The other three counters CLASSIFY a part of one of those totals; none of them adds to it.\n * `cachedInput` and `cacheWriteInput` classify `input`, which is the convention\n * `promptCacheTokenClasses` (`util.ts`) folds: `freshInput = input - cacheRead - cacheWrite`.\n * `reasoningOutput` classifies `output`.\n *\n * A counter the harness does not report stays absent, because a zero would claim the harness\n * measured none.\n */\nexport interface HarnessUsage {\n /** The harness family whose adapter produced this report. */\n readonly harness: HarnessType\n /** Total prompt tokens the provider charged for the turn, the cached ones included. */\n readonly input: number\n /** Total completion tokens the provider charged for the turn, the reasoning ones included. */\n readonly output: number\n /** The part of `input` the provider served from its prompt cache. */\n readonly cachedInput?: number\n /** The part of `input` the provider wrote into its prompt cache. */\n readonly cacheWriteInput?: number\n /** The part of `output` the model spent on reasoning. Never added to `output`. */\n readonly reasoningOutput?: number\n}\n\n/**\n * Decode one harness's own usage report off a sandbox event, or `undefined` when the event carries\n * no usage for that harness. ONE adapter per harness family — each owns its real wire shape. Add a\n * harness by adding a decoder and registering it; no other code changes.\n *\n * A decoder throws `ValidationError` when the event IS the harness's usage carrier and its\n * numbers cannot be read.\n */\ntype HarnessUsageDecoder = (event: SandboxEvent) => HarnessUsage | undefined\n\n/** Names the wire record every codex decode error is reported against. */\nconst codexUsageContext = 'codex turn.completed'\n\n/**\n * codex reports the tokens of a turn inside its own `turn.completed` event, which rides the\n * transport either as `{ type: 'raw', data: { type: 'turn.completed', usage: { … } } }` or as\n * the provider-normalized Interface envelope `{ type: 'raw', data: { type: 'raw', event: {\n * type: 'turn.completed', usage: { … } } } }`. It emits no canonical usage event, so this adapter\n * is a codex worker's only usage source.\n *\n * The record is read by `parseCodexUsageRecord`, the same reader `runLocalHarness` uses on the\n * codex CLI's own stdout, so both surfaces hold one field policy and both cross-field invariants.\n *\n * A `turn.completed` that carries a `usage` member the reader cannot read is a `ValidationError`\n * naming the field. A `turn.completed` with no `usage` member reports no usage at all, which\n * leaves the turn's tokens unknown rather than zero.\n */\nconst decodeCodexTurnUsage: HarnessUsageDecoder = (event) => {\n if (String(event.type ?? '') !== 'raw') return undefined\n const envelope = plainRecord(event.data)\n const data =\n envelope?.type === 'raw' && plainRecord(envelope.event) !== undefined\n ? plainRecord(envelope.event)\n : envelope\n if (data === undefined || data.type !== 'turn.completed' || data.usage === undefined) {\n return undefined\n }\n const record = parseCodexUsageRecord(data.usage, codexUsageContext)\n return {\n harness: 'codex',\n input: record.inputTokens,\n output: record.outputTokens,\n cachedInput: record.cachedInputTokens,\n reasoningOutput: record.reasoningOutputTokens,\n ...(record.cacheWriteInputTokens === undefined\n ? {}\n : { cacheWriteInput: record.cacheWriteInputTokens }),\n }\n}\n\n/** Claude's adapter forwards one delta per response snapshot, keyed and deduplicated there. */\nconst decodeClaudeAssistantUsage: HarnessUsageDecoder = (event) => {\n if (String(event.type ?? '') !== 'raw') return undefined\n const envelope = plainRecord(event.data)\n const data =\n envelope?.type === 'raw' && plainRecord(envelope.event) !== undefined\n ? plainRecord(envelope.event)\n : envelope\n if (data?.type !== 'assistant.usage') return undefined\n if (typeof data.message_id !== 'string' || data.message_id.length === 0) {\n throw new ValidationError('claude assistant.usage: missing response identity')\n }\n const usage = plainRecord(data.usage)\n if (!usage) throw new ValidationError('claude assistant.usage: usage must be an object')\n const fresh = naturalNumber(usage.input_tokens, 'input_tokens', 'claude assistant.usage')\n const cachedInput = naturalNumber(\n usage.cache_read_input_tokens,\n 'cache_read_input_tokens',\n 'claude assistant.usage',\n )\n const cacheWriteInput = naturalNumber(\n usage.cache_creation_input_tokens,\n 'cache_creation_input_tokens',\n 'claude assistant.usage',\n )\n const output = naturalNumber(usage.output_tokens, 'output_tokens', 'claude assistant.usage')\n const input = fresh + cachedInput + cacheWriteInput\n if (!Number.isSafeInteger(input)) {\n throw new ValidationError('claude assistant.usage: total input tokens exceed a safe integer')\n }\n return { harness: 'claude-code', input, output, cachedInput, cacheWriteInput }\n}\n\n/**\n * The harness → usage-decoder registry. Add a harness by adding one entry.\n *\n * Keyed by `HarnessType`, the vocabulary the `harness` argument is drawn from, so a key no caller\n * can produce does not compile. A harness absent from this registry reports usage through the\n * canonical events or not at all.\n */\nconst harnessUsageDecoders: Partial<Record<HarnessType, HarnessUsageDecoder>> = {\n codex: decodeCodexTurnUsage,\n 'claude-code': decodeClaudeAssistantUsage,\n}\n\n/**\n * Decode a sandbox event with one harness's adapter, or `undefined` when the event carries no\n * harness-native usage.\n *\n * A NAMED harness reads with that harness's adapter only, and a named harness with no adapter\n * reports nothing. It never falls through to another harness's adapter: a different harness's\n * `turn.completed` decoded as codex would either drop the counters codex does not name or fail on\n * a field codex requires, and both answers would be about the wrong harness. The composite over\n * every registered adapter runs only when the caller cannot name the harness.\n *\n * Throws `ValidationError` when an adapter recognizes the event as its harness's usage carrier and\n * cannot read the numbers.\n */\nexport function decodeHarnessUsage(\n event: SandboxEvent,\n harness?: HarnessType,\n): HarnessUsage | undefined {\n if (!event || typeof event !== 'object') return undefined\n if (harness !== undefined) return harnessUsageDecoders[harness]?.(event)\n for (const decode of new Set(Object.values(harnessUsageDecoders))) {\n const usage = decode(event)\n if (usage !== undefined) return usage\n }\n return undefined\n}\n\nfunction naturalNumber(value: unknown, field: string, label: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new ValidationError(\n `${label}: usage.${field} must be a non-negative safe integer, received ${describe(value)}`,\n )\n }\n return value\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (typeof value === 'string') return JSON.stringify(value)\n if (Array.isArray(value)) return 'an array'\n return typeof value\n}\n","/**\n * Sandbox-event → runtime-event mapping.\n *\n * The sandbox SDK emits a polymorphic `SandboxEvent = { type, data, id? }`\n * whose `type` vocabulary is backend-determined (opencode, etc.) rather than\n * enumerated by the SDK. Two consumers project it:\n * - the loop kernel's cost ledger (`extractLlmCallEvent`, and\n * `createSandboxUsageLedger` for a turn's full accounting) — sums usage off\n * every cost-bearing event, regardless of stream shape;\n * - the `AgentRuntime.act` streaming contract (`mapSandboxEvent`) — projects\n * incremental events to the `RuntimeStreamEvent` chat-UX vocabulary.\n *\n * Usage stays here; streaming/executor output lives in `sandbox-executor-output.ts`,\n * and canonical transport-envelope decoding in `sandbox-transport-events.ts`.\n * A harness that reports usage only inside its OWN event is decoded by the\n * per-harness registry in `harness-usage.ts`; this module holds the canonical\n * fold and the once-per-turn precedence rule between the two sources.\n */\n\nimport type { HarnessType, TokenUsage } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { recordValue as plainRecord } from '../record-value'\nimport type { RuntimeStreamEvent } from '../types'\nimport { decodeHarnessUsage, type HarnessUsage } from './harness-usage'\nimport type { LoopTokenUsage } from './types'\nimport { addTokenUsage, cloneTokenUsage, promptCacheTokenClasses, zeroTokenUsage } from './util'\n\n/** The canonical usage receipt every accounting path in the kernel reads. */\ntype LlmCallEvent = RuntimeStreamEvent & { type: 'llm_call' }\n\n/**\n * Forward a sandbox event to an optional observer without letting observer\n * behavior affect the run. The observer receives a defensive copy, synchronous\n * throws are swallowed, and returned promises are deliberately not awaited.\n */\nexport function notifySandboxEventObserver<Meta>(\n event: SandboxEvent,\n observer: ((event: SandboxEvent, meta: Meta) => void | PromiseLike<void>) | undefined,\n meta: Meta,\n): void {\n if (!observer) return\n try {\n const result = observer(cloneEventForObserver(event), meta)\n if (result && typeof result.then === 'function') {\n void result.then(undefined, () => {})\n }\n } catch {\n // Live observation is optional and must never interrupt the event stream.\n }\n}\n\nfunction cloneEventForObserver(event: SandboxEvent): SandboxEvent {\n try {\n return structuredClone(event)\n } catch {\n return copyPlainSpine(event, new WeakMap()) as SandboxEvent\n }\n}\n\nfunction copyPlainSpine(value: unknown, seen: WeakMap<object, unknown>): unknown {\n if (value === null || typeof value !== 'object') return value\n const existing = seen.get(value)\n if (existing !== undefined) return existing\n if (Array.isArray(value)) {\n const copy: unknown[] = []\n seen.set(value, copy)\n for (const item of value) copy.push(copyPlainSpine(item, seen))\n return copy\n }\n const proto = Object.getPrototypeOf(value)\n if (proto !== Object.prototype && proto !== null) return {}\n const copy: Record<string, unknown> = {}\n seen.set(value, copy)\n for (const [key, child] of Object.entries(value)) {\n copy[key] = copyPlainSpine(child, seen)\n }\n return copy\n}\n\n/** The provider/model the platform reports it actually bound to a turn, when it reports one.\n * `source` is the platform's own account of where that choice came from — `environment` means\n * the platform chose, not the request. */\nexport interface SandboxServedBackend {\n readonly provider?: string\n readonly model?: string\n readonly source?: string\n}\n\n/**\n * Read the served execution identity off one Sandbox event.\n *\n * The platform reports `effectiveBackend` on `execution.started` and again on the terminal\n * event (`@tangle-network/sandbox`, `EffectiveBackend`). Absence returns `undefined`\n * and must stay unknown — a request is not a receipt, so nothing here may be inferred from\n * what was asked for.\n */\nexport function sandboxEventServedBackend(event: SandboxEvent): SandboxServedBackend | undefined {\n if (!event || typeof event !== 'object') return undefined\n const data = plainRecord(event.data)\n const served = plainRecord(data?.effectiveBackend)\n if (!served) return undefined\n const provider = firstString(served.provider)\n const model = firstString(served.model)\n const source = firstString(served.source)\n if (provider === undefined && model === undefined) return undefined\n return {\n ...(provider !== undefined ? { provider } : {}),\n ...(model !== undefined ? { model } : {}),\n ...(source !== undefined ? { source } : {}),\n }\n}\n\n/**\n * Fail the execution when the platform reports serving a model other than the exact one asked for.\n *\n * Measured motive (agent-runtime#892, live infrastructure): 6 of 6 boxes whose profile\n * declared `zai-coding-plan/glm-5.2` reported\n * `{\"provider\":\"openai-compat\",\"model\":\"deepseek/deepseek-v4-flash\",\"source\":\"environment\"}`,\n * while the materialization receipt recorded the declared model as `status: \"known\"`. Sending\n * `backend.model` makes that substitution unlikely; only reading the report back makes it\n * detectable. A run that cannot say which model produced its evidence must not settle as one\n * that can.\n *\n * Silent when the platform reports no served model: unobserved stays unobserved.\n */\nexport function assertSandboxServedModel(\n event: SandboxEvent,\n expected: { readonly provider?: string; readonly model?: string } | undefined,\n): void {\n const wanted = expected?.model?.trim()\n if (!wanted) return\n const served = sandboxEventServedBackend(event)\n if (served?.model === undefined) return\n if (sameModelId(served.model, wanted, [served.provider, expected?.provider])) return\n const attribution = [\n served.provider !== undefined ? `provider ${JSON.stringify(served.provider)}` : undefined,\n served.source !== undefined ? `source ${JSON.stringify(served.source)}` : undefined,\n ].filter((part): part is string => part !== undefined)\n const detail = attribution.length > 0 ? ` (${attribution.join(', ')})` : ''\n throw new Error(\n `sandbox served model ${JSON.stringify(served.model)}${detail} instead of the exact profile model ${JSON.stringify(wanted)}`,\n )\n}\n\n/**\n * Do two model ids name the same model, allowing for routing prefixes?\n *\n * Either side may spell the model bare (`glm-5.2`), provider-qualified\n * (`zai-coding-plan/glm-5.2`), or route-qualified, and the platform reports the provider in its\n * own field rather than always in the id. So the comparison drops any known provider prefix and\n * then accepts a `/`-boundary suffix match: a longer route to the SAME leaf model is a routing\n * difference, not a substitution.\n *\n * What it deliberately does NOT absorb is a different leaf: `glm-5.2` against `glm-5.3` stays a\n * mismatch, which is the substitution measured directly against the provider API (a request for\n * `glm-5.2` was served `glm-5.3`). A version suffix is the whole difference between two\n * instruments, so nothing here may treat it as noise.\n */\nfunction sameModelId(\n served: string,\n wanted: string,\n providers: readonly (string | undefined)[],\n): boolean {\n const a = stripProviderPrefix(served, providers)\n const b = stripProviderPrefix(wanted, providers)\n return a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`)\n}\n\nfunction stripProviderPrefix(id: string, providers: readonly (string | undefined)[]): string {\n let out = id.trim().toLowerCase()\n for (const provider of providers) {\n const prefix = provider?.trim().toLowerCase()\n if (prefix && out.startsWith(`${prefix}/`)) out = out.slice(prefix.length + 1)\n }\n return out\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n return values.find((value): value is string => typeof value === 'string' && value.length > 0)\n}\n\n/**\n * The sandbox event types that END a turn.\n *\n * One list, because two consumers ask this question about the same wire event and must agree: the\n * usage credit below, and the terminal-text lift in `sandbox-executor-output.ts`. Written separately they\n * drifted by exactly one member — `message.completed` credited tokens and dollars while its final\n * text was never lifted, so a backend whose terminal frame carries that type produced a run that\n * was billed and recorded no answer.\n */\nconst sandboxTerminalEventTypes = ['message.completed', 'result', 'final', 'done'] as const\n\ntype SandboxTerminalEventType = (typeof sandboxTerminalEventTypes)[number]\n\nconst terminalTypes: ReadonlySet<string> = new Set<string>(sandboxTerminalEventTypes)\n\n/** True for an event type that ends a sandbox turn. */\nexport function isSandboxTerminalEvent(type: string): type is SandboxTerminalEventType {\n return terminalTypes.has(type)\n}\n\n/**\n * Which member of a terminal event's `data` carries its usage receipt.\n *\n * The one place the terminal types legitimately differ, stated rather than implied by two lists:\n * sandbox 0.4.0's `done` reports under `tokenUsage` with the cost at the top level, every other\n * terminal type reports under `usage`.\n */\nexport function sandboxTerminalUsageField(type: SandboxTerminalEventType): 'usage' | 'tokenUsage' {\n return type === 'done' ? 'tokenUsage' : 'usage'\n}\n\n/**\n * Extract a `RuntimeStreamEvent`-shaped `llm_call` from a sandbox event when\n * the event carries usage/cost data. Returns `undefined` for non-cost events\n * so the kernel can iterate the full stream without branching.\n *\n * Pure by contract: it never throws on a failed run. The terminal truth\n * boundary is the public Sandbox outcome tracker, applied after the complete\n * stream. Post-hoc readers — {@link sumSandboxUsage}, the\n * analyst trace store, the chat projection — must stay able to read a failed\n * turn's events, which is when reading them matters most.\n *\n * Canonical cost-carrying types observed in the wild:\n * - `llm_call` — `data: { model, tokensIn, tokensOut, costUsd, ... }`\n * - `message.completed` / `result` — `data: { usage: { inputTokens,\n * outputTokens, totalCostUsd? } }`\n * - `cost.usage` / `usage` — same shape under a dedicated type\n *\n * Numeric coercion is strict: `Number.isFinite` gates every accumulator write\n * so a sentinel `NaN` from a misbehaving backend cannot poison the ledger.\n */\nexport function extractLlmCallEvent(\n event: SandboxEvent,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n const data = canonicalUsageData(event)\n return data === undefined ? undefined : buildLlmCall(data, agentRunName)\n}\n\nfunction canonicalUsageData(event: SandboxEvent): Record<string, unknown> | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'llm_call' || type === 'cost.usage' || type === 'usage') {\n return usageReceiptData(data, plainRecord(data.usage))\n }\n if (type === 'error' || isSandboxTerminalEvent(type)) {\n const field = type === 'error' ? 'tokenUsage' : sandboxTerminalUsageField(type)\n const usage =\n plainRecord(data[field]) ?? plainRecord(data[field === 'usage' ? 'tokenUsage' : 'usage'])\n // Completeness and cost provenance describe the receipt from its envelope.\n // Keep that envelope instead of projecting only counters from the nested usage.\n return usageReceiptData(data, usage)\n }\n return undefined\n}\n\n/**\n * Per-turn usage accounting over BOTH the canonical events and the harness-native ones.\n *\n * Some harnesses report a turn's tokens only inside their own event (`harness-usage.ts`), and a\n * stream may carry that report AND a canonical usage event for the same turn. Crediting both\n * counts one turn twice, so this ledger holds the precedence rule: a canonical usage event WINS,\n * and a harness-native report is credited only for a turn in which no canonical usage arrived.\n *\n * The harness-native report is held until the turn ends, because it can arrive before the\n * canonical answer is known — codex emits `turn.completed` ahead of the terminal transport\n * events. Call {@link SandboxUsageLedger.observe} for every event of a turn, then\n * {@link SandboxUsageLedger.settleTurn} once at the turn boundary; settling also resets the\n * ledger for the next turn, so one ledger serves a whole multi-turn session.\n *\n * The ledger never throws on a receipt it cannot read: `observe` returns a receipt with\n * `tokensKnown: false` and `tokensUnknownReason`, so one policy serves every consumer.\n */\nexport interface SandboxUsageLedger {\n /** Cumulative worker tokens, including cache classifications reported after the prompt total. */\n tokenUsage(): LoopTokenUsage\n /** Read a detached snapshot of the latest settled turn, without settling the active turn.\n * Absent/incomplete usage stays absent; cost is the reported number, not a billing-completeness\n * claim or a catalog estimate. A later empty settlement replaces the snapshot with undefined. */\n settledUsage(): TokenUsage | undefined\n /** Account one event. Returns the canonical usage receipt to credit now, if the event is one. */\n observe(\n event: SandboxEvent,\n agentRunName: string,\n ): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined\n /** End the turn. Returns the held harness-native receipt when no canonical usage arrived. */\n settleTurn(agentRunName: string): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined\n}\n\n/** A {@link SandboxUsageLedger} for one worker. Pass the worker's harness to decode with that\n * harness's adapter; omit it to try every registered adapter. */\nexport function createSandboxUsageLedger(harness?: HarnessType): SandboxUsageLedger {\n let held: HarnessUsage[] = []\n let sawCanonical = false\n const credited: Record<string, number> = {}\n const receipts = new Map<string, string>()\n const settledTokens = zeroTokenUsage()\n let turnTokens = zeroTokenUsage()\n let turnUsageUnknown = false\n let settledUsage: TokenUsage | undefined\n return {\n settledUsage: () => (settledUsage === undefined ? undefined : { ...settledUsage }),\n tokenUsage() {\n const total = cloneTokenUsage(settledTokens)\n addTokenUsage(total, turnTokens)\n return total\n },\n observe(event, agentRunName) {\n const call = extractLlmCallEvent(event, agentRunName)\n if (call) {\n sawCanonical = true\n const receipt = creditCanonicalUsage(event, call, credited, receipts, (receipt, mode) => {\n refineCanonicalTokens(turnTokens, call, receipt, mode)\n })\n if (receipt?.tokensKnown === false) {\n turnTokens.tokensKnown = false\n turnUsageUnknown = true\n }\n return receipt\n }\n let usage: HarnessUsage | undefined\n try {\n usage = decodeHarnessUsage(event, harness)\n } catch (err) {\n turnUsageUnknown = true\n // A receipt the ledger cannot read is a measurement fact, not an outcome fact. It is\n // answered like any other receipt, marked unknown with the decode message, so every\n // consumer marks the spend unknown through the fold it already applies and none decides\n // on its own whether an unreadable counter fails the turn. Before the ledger owned this,\n // the leaf kernel failed the iteration and, as a ValidationError, the whole batch.\n return {\n type: 'llm_call',\n model: agentRunName,\n tokensKnown: false,\n usdKnown: false,\n tokensUnknownReason: err instanceof Error ? err.message : String(err),\n }\n }\n // Every report of the turn is kept: a stream carrying more than one is more than one\n // charge, and keeping only the last would drop tokens the provider billed.\n if (usage) held.push(usage)\n return undefined\n },\n settleTurn(agentRunName) {\n const reports = held\n const canonical = sawCanonical\n held = []\n sawCanonical = false\n const receipt =\n !canonical && reports.length > 0 ? harnessUsageLlmCall(reports, agentRunName) : undefined\n if (receipt) {\n creditCanonicalUsage(\n { type: 'llm_call', data: {} },\n receipt,\n credited,\n receipts,\n (credit, mode) => refineCanonicalTokens(turnTokens, receipt, credit, mode),\n )\n }\n // The same credit pass owns totals, presence, replay and mode semantics for this projection.\n settledUsage =\n !turnUsageUnknown && credited.tokensIn !== undefined && credited.tokensOut !== undefined\n ? {\n inputTokens: credited.tokensIn,\n outputTokens: credited.tokensOut,\n ...(credited.totalTokens === undefined ? {} : { totalTokens: credited.totalTokens }),\n ...(credited.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: credited.reasoningTokens }),\n ...(credited['promptCache.readTokens'] === undefined\n ? {}\n : { cacheReadInputTokens: credited['promptCache.readTokens'] }),\n ...(credited['promptCache.writeTokens'] === undefined\n ? {}\n : { cacheCreationInputTokens: credited['promptCache.writeTokens'] }),\n ...(credited.costUsd === undefined ? {} : { cost: credited.costUsd }),\n }\n : undefined\n for (const key of Object.keys(credited)) delete credited[key]\n receipts.clear()\n addTokenUsage(settledTokens, turnTokens)\n turnTokens = zeroTokenUsage()\n turnUsageUnknown = false\n return receipt\n },\n }\n}\n\n/** Shared receipt semantics; an undeclared nonterminal observation is not a cumulative total. */\nexport function canonicalSandboxUsageMode(event: SandboxEvent): 'delta' | 'cumulative' | undefined {\n const declaredMode = plainRecord(event.data)?.usageMode\n return declaredMode === 'delta' || declaredMode === 'cumulative'\n ? declaredMode\n : declaredMode === undefined && event.type === 'llm_call'\n ? 'delta'\n : declaredMode === undefined &&\n (event.type === 'error' || isSandboxTerminalEvent(String(event.type)))\n ? 'cumulative'\n : undefined\n}\n\n/** Terminal totals replace already credited usage; only per-call receipts add to it. */\nfunction creditCanonicalUsage(\n event: SandboxEvent,\n call: LlmCallEvent,\n credited: Record<string, number>,\n receipts: Map<string, string>,\n onCredit: (receipt: LlmCallEvent, mode: 'delta' | 'cumulative' | undefined) => void,\n): LlmCallEvent | undefined {\n const mode = canonicalSandboxUsageMode(event)\n const result: LlmCallEvent = { ...call }\n // A cost-only receipt says nothing about token completeness. A later complete token total\n // can still establish it; a stream containing only cost receipts stays unknown at its fold.\n const data = plainRecord(event.data) ?? {}\n const usageData = canonicalUsageData(event) ?? {}\n const supplemental = Object.fromEntries(\n ['totalTokens', 'reasoningTokens'].flatMap((key) => {\n const value = usageData[key]\n return value === undefined\n ? []\n : [[key, typeof value === 'number' && Number.isFinite(value) ? value : null]]\n }),\n )\n const explicitTokensUnknown = [data, plainRecord(data.usage), plainRecord(data.tokenUsage)].some(\n (receipt) =>\n ['tokensKnown', 'tokens_known'].some(\n (key) => receipt?.[key] !== undefined && receipt[key] !== true,\n ),\n )\n if (\n call.tokensIn === undefined &&\n call.tokensOut === undefined &&\n !call.tokensUnknownReason &&\n !explicitTokensUnknown\n ) {\n delete result.tokensKnown\n }\n let reason =\n mode === undefined ? 'usage receipt has no declared delta or cumulative semantics' : undefined\n if (event.id) {\n const signature = JSON.stringify({ mode, call, supplemental })\n const previous = receipts.get(event.id)\n if (previous === signature) return undefined\n if (previous !== undefined) {\n return {\n type: 'llm_call',\n model: call.model,\n tokensKnown: false,\n usdKnown: false,\n tokensUnknownReason: `usage receipt ${event.id} changed after it was credited`,\n }\n }\n receipts.set(event.id, signature)\n }\n const credit = (key: string, value: number): number => {\n const previous = credited[key] ?? 0\n if (!Number.isFinite(value) || value < 0) {\n reason = `usage receipt has an invalid ${key}`\n return 0\n }\n if (mode === 'delta') {\n credited[key] = previous + value\n return value\n }\n if (value < previous) reason = `cumulative usage ${key} is below already credited usage`\n credited[key] = Math.max(previous, value)\n return Math.max(0, value - previous)\n }\n for (const key of ['tokensIn', 'tokensOut', 'costUsd', 'estimatedCostUsd'] as const) {\n if (call[key] !== undefined) result[key] = credit(key, call[key])\n }\n for (const [key, value] of Object.entries(supplemental)) {\n if (typeof value !== 'number') reason = `usage receipt has an invalid ${key}`\n else credit(key, value)\n }\n if (call.promptCache) {\n result.promptCache = Object.fromEntries(\n Object.entries(call.promptCache).map(([key, value]) => [\n key,\n typeof value === 'number' ? credit(`promptCache.${key}`, value) : value,\n ]),\n )\n }\n if (reason !== undefined) {\n result.usdKnown = false\n if (call.tokensIn !== undefined || call.tokensOut !== undefined) {\n result.tokensKnown = false\n result.tokensUnknownReason = reason\n }\n }\n onCredit(result, mode)\n return result\n}\n\n/** Cache partitions belong to the original receipt, not the smaller incremental charge. */\nfunction refineCanonicalTokens(\n tokens: LoopTokenUsage,\n call: LlmCallEvent,\n receipt: LlmCallEvent,\n mode: 'delta' | 'cumulative' | undefined,\n): void {\n const input = receipt.tokensIn ?? 0\n const output = receipt.tokensOut ?? 0\n const cache = promptCacheTokenClasses(call.tokensIn, call.promptCache)\n if (mode !== 'cumulative') {\n addTokenUsage(tokens, { input, output, ...cache })\n return\n }\n tokens.input += input\n tokens.output += output\n const full = cache.freshInput !== undefined && call.tokensIn === tokens.input\n if (full && receipt.tokensKnown !== false) {\n tokens.freshInput = cache.freshInput\n tokens.cacheRead = cache.cacheRead\n tokens.cacheWrite = cache.cacheWrite\n delete tokens.cacheBreakdownKnown\n return\n }\n if (cache.cacheRead !== undefined)\n tokens.cacheRead = Math.max(tokens.cacheRead ?? 0, cache.cacheRead)\n if (cache.cacheWrite !== undefined)\n tokens.cacheWrite = Math.max(tokens.cacheWrite ?? 0, cache.cacheWrite)\n if (\n (tokens.freshInput ?? 0) + (tokens.cacheRead ?? 0) + (tokens.cacheWrite ?? 0) >\n tokens.input\n ) {\n delete tokens.freshInput\n delete tokens.cacheRead\n delete tokens.cacheWrite\n }\n if (input > 0 || cache.cacheBreakdownKnown === false) tokens.cacheBreakdownKnown = false\n}\n\n/**\n * Fold harness-native usage reports into the canonical `llm_call` the accounting paths read.\n *\n * Every counter a `HarnessUsage` carries beside `input` and `output` CLASSIFIES one of those two\n * totals, so none of them is added to the total it describes:\n *\n * - the prompt-cache counters classify `input` and ride `promptCache`, the convention the\n * terminal `tokenUsage` branch above already follows and `promptCacheTokenClasses` folds,\n * where `freshInput = input - cacheRead - cacheWrite`;\n * - `reasoningOutput` classifies `output`. Codex counts its reasoning tokens INSIDE\n * `output_tokens` — a turn reporting `output_tokens 1523` with `reasoning_output_tokens 1516`\n * answered with about seven tokens of text — and `parseCodexUsageRecord` holds that as an\n * invariant. The canonical `llm_call` carries no reasoning class, so the count is not\n * forwarded to {@link buildLlmCall}. Canonical output totals already include reasoning.\n *\n * A counter no report carried stays absent, because a zero would claim the provider measured none.\n */\nfunction harnessUsageLlmCall(\n reports: readonly HarnessUsage[],\n agentRunName: string,\n): LlmCallEvent | undefined {\n let inputTokens = 0\n let outputTokens = 0\n let readTokens: number | undefined\n let writeTokens: number | undefined\n for (const report of reports) {\n inputTokens += report.input\n outputTokens += report.output\n if (report.cachedInput !== undefined) readTokens = (readTokens ?? 0) + report.cachedInput\n if (report.cacheWriteInput !== undefined)\n writeTokens = (writeTokens ?? 0) + report.cacheWriteInput\n }\n const promptCache: Record<string, number> = {}\n if (readTokens !== undefined) promptCache.readTokens = readTokens\n if (writeTokens !== undefined) promptCache.writeTokens = writeTokens\n return buildLlmCall(\n {\n inputTokens,\n outputTokens,\n ...(Object.keys(promptCache).length > 0 ? { promptCache } : {}),\n },\n agentRunName,\n )\n}\n\n/**\n * Sum the token usage + USD cost of a sandbox turn's events — the one honest way to meter an\n * `openSandboxRun` cell. Folds a {@link SandboxUsageLedger} over the stream, so it reads usage off\n * EVERY backend event shape — the canonical events plus a harness that reports usage only in its\n * own event — and a `runProfileMatrix` dispatch can report it to `ctx.cost`:\n *\n * receipt: (turn) => {\n * const u = sumSandboxUsage(turn.events)\n * return { model, inputTokens: u.input, outputTokens: u.output,\n * ...(u.tokensKnown === false ? { usageUnknown: true } : {}),\n * ...(u.usdKnown !== false && u.costUsd > 0 ? { actualCostUsd: u.costUsd } : {}),\n * ...(u.usdKnown === false ? { costUnknown: true } : {}),\n * ...(u.estimatedCostUsd !== undefined ? { estimatedCostUsd: u.estimatedCostUsd } : {}) }\n * }\n *\n * Without this a cell reads `{tokens:0, cost:0}` and the backend-integrity guard correctly aborts the\n * matrix as a stub. `agentRunName` is the fallback model label for cost-only events (default `'agent'`).\n *\n * Pure by contract, like the ledger it folds: it never throws. A harness receipt the ledger cannot\n * read leaves the result at `tokensKnown: false` with `tokensUnknownReason` carrying the decode\n * message — an unreadable receipt is a different fact from a turn that reported no usage, and a\n * post-hoc reader that threw would lose the whole failed turn it exists to report.\n */\nexport function sumSandboxUsage(\n events: readonly SandboxEvent[],\n agentRunName = 'agent',\n): {\n input: number\n output: number\n costUsd: number\n tokensKnown?: false\n usdKnown?: false\n estimatedCostUsd?: number\n tokensUnknownReason?: string\n} {\n let input = 0\n let output = 0\n let costUsd = 0\n let estimatedCostUsd = 0\n let sawEstimate = false\n let sawCall = false\n let sawTokenReceipt = false\n let tokensKnown = true\n let usdKnown = true\n let unreadable: string | undefined\n const ledger = createSandboxUsageLedger()\n const credit = (call: LlmCallEvent): void => {\n sawCall = true\n sawTokenReceipt ||= call.tokensIn !== undefined || call.tokensOut !== undefined\n input += call.tokensIn ?? 0\n output += call.tokensOut ?? 0\n costUsd += call.costUsd ?? 0\n if (call.tokensKnown === false) tokensKnown = false\n if (call.usdKnown === false) usdKnown = false\n // The FIRST decode message is kept: it names the receipt the ledger could not read, and a\n // later one from the same turn does not make the answer any more unknown.\n unreadable ??= call.tokensUnknownReason\n if (call.estimatedCostUsd !== undefined) {\n estimatedCostUsd += call.estimatedCostUsd\n sawEstimate = true\n }\n }\n for (const ev of events) {\n const call = ledger.observe(ev, agentRunName)\n if (call) credit(call)\n }\n const harnessCall = ledger.settleTurn(agentRunName)\n if (harnessCall) credit(harnessCall)\n return {\n input,\n output,\n costUsd,\n ...(sawTokenReceipt && tokensKnown ? {} : { tokensKnown: false as const }),\n ...(sawCall && usdKnown ? {} : { usdKnown: false as const }),\n ...(sawEstimate ? { estimatedCostUsd } : {}),\n ...(unreadable === undefined ? {} : { tokensUnknownReason: unreadable }),\n }\n}\n\nfunction usageReceiptData(\n envelope: Record<string, unknown>,\n usage: Record<string, unknown> = {},\n): Record<string, unknown> {\n const merged = { ...usage, ...envelope }\n // An envelope overrides nested receipt fields even when their wire aliases differ.\n for (const aliases of [\n ['tokensIn', 'inputTokens', 'prompt_tokens'],\n ['tokensOut', 'outputTokens', 'completion_tokens'],\n ['costUsd', 'totalCostUsd', 'cost_usd', 'cost'],\n ['costProvenance', 'cost_provenance'],\n ]) {\n const key = aliases.find((alias) => envelope[alias] !== undefined)\n if (key === undefined) continue\n for (const alias of aliases) delete merged[alias]\n merged[key] = envelope[key]\n }\n // A complete flag cannot promote a conflicting, malformed, or partial observation.\n for (const aliases of [\n ['tokensKnown', 'tokens_known'],\n ['costKnown', 'cost_known', 'usdKnown', 'usd_known'],\n ] as const) {\n const values = [usage, envelope].flatMap((receipt) =>\n aliases.map((key) => receipt[key]).filter((value) => value !== undefined),\n )\n if (values.length > 0) merged[aliases[0]] = values.every((value) => value === true)\n }\n return merged\n}\n\nfunction buildLlmCall(\n data: Record<string, unknown>,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n const tokensIn = pickFiniteNumber(data, ['tokensIn', 'inputTokens', 'prompt_tokens'])\n const outputTokens = pickFiniteNumber(data, ['tokensOut', 'outputTokens', 'completion_tokens'])\n const reasoningTokens = pickFiniteNumber(data, ['reasoningTokens'])\n // Reasoning classifies the inclusive output total. Alone, it is only a lower bound.\n const tokensOut = outputTokens ?? reasoningTokens\n const reportedCostUsd = pickFiniteNumber(data, ['costUsd', 'totalCostUsd', 'cost_usd', 'cost'])\n const explicitTokensKnown = data.tokensKnown ?? data.tokens_known\n const explicitCostKnown = data.costKnown ?? data.cost_known ?? data.usdKnown ?? data.usd_known\n const costProvenance = data.costProvenance ?? data.cost_provenance\n const explicitEstimate = pickFiniteNumber(data, ['estimatedCostUsd', 'estimated_cost_usd'])\n const catalogEstimate =\n costProvenance === 'catalog-estimate' ? (explicitEstimate ?? reportedCostUsd) : explicitEstimate\n const costUsd = costProvenance === 'catalog-estimate' ? undefined : reportedCostUsd\n const promptCache = readPromptCacheUsage(data)\n const tokensKnown =\n explicitTokensKnown !== false && tokensIn !== undefined && outputTokens !== undefined\n // Sandbox's canonical terminal `totalCostUsd` is already the provider-reported receipt. The\n // current SDK carries no provenance tag, so absence means the canonical receipt rather than\n // \"unknown\". Explicit estimates and explicit false-known markers remain unknown.\n const usdKnown =\n explicitCostKnown !== false &&\n costUsd !== undefined &&\n (costProvenance === undefined ||\n costProvenance === 'provider-receipt' ||\n costProvenance === 'billing-receipt')\n const tools = readOfferedTools(data.tools)\n if (\n tokensIn === undefined &&\n tokensOut === undefined &&\n costUsd === undefined &&\n catalogEstimate === undefined &&\n promptCache === undefined &&\n tools === undefined &&\n explicitTokensKnown !== false &&\n explicitCostKnown !== false\n ) {\n return undefined\n }\n const model = typeof data.model === 'string' && data.model.length > 0 ? data.model : agentRunName\n const event: RuntimeStreamEvent & { type: 'llm_call' } = {\n type: 'llm_call',\n model,\n }\n if (tokensIn !== undefined) event.tokensIn = tokensIn\n if (tokensOut !== undefined) event.tokensOut = tokensOut\n if (!tokensKnown) event.tokensKnown = false\n if (costUsd !== undefined) event.costUsd = costUsd\n if (!usdKnown) event.usdKnown = false\n if (catalogEstimate !== undefined) event.estimatedCostUsd = catalogEstimate\n if (promptCache !== undefined) event.promptCache = promptCache\n if (tools !== undefined) event.tools = tools\n return event\n}\n\n/** `data.tools`, when it is a non-empty array of non-empty tool-name strings. Anything else\n * (absent, empty, wrong element type) is treated as \"the producer did not report its offered\n * set\" — never a placeholder empty list, which would read as \"offered zero tools\" downstream. */\nfunction readOfferedTools(value: unknown): readonly string[] | undefined {\n if (!Array.isArray(value) || value.length === 0) return undefined\n const names = value.filter((v): v is string => typeof v === 'string' && v.length > 0)\n return names.length === value.length ? names : undefined\n}\n\n/**\n * Every wire spelling of a prompt-cache READ counter, in precedence order: the canonical name\n * first, then the spellings observed on the paths that reach this extractor — the sandbox terminal\n * `tokenUsage` record, the cli-bridge OpenAI-compatible usage object (which normalizes every\n * backend to Anthropic's `cache_read_input_tokens`), Anthropic verbatim, OpenAI's\n * `prompt_tokens_details.cached_tokens`, and DeepSeek's `prompt_cache_hit_tokens`.\n */\nconst PROMPT_CACHE_READ_KEYS = [\n 'readTokens',\n 'read_tokens',\n 'cacheReadInputTokens',\n 'cache_read_input_tokens',\n 'cacheRead',\n 'cache_read',\n 'cachedInputTokens',\n 'cachedTokens',\n 'cached_tokens',\n 'prompt_cache_hit_tokens',\n]\n\n/**\n * Every wire spelling of a prompt-cache WRITE counter. OpenAI reports no write counter at all, so\n * an OpenAI-shaped usage record matches nothing here and the write stays absent — which is the\n * point: absent is not zero.\n */\nconst PROMPT_CACHE_WRITE_KEYS = [\n 'writeTokens',\n 'write_tokens',\n 'cacheWriteInputTokens',\n 'cache_write_input_tokens',\n 'cacheCreationInputTokens',\n 'cache_creation_input_tokens',\n 'cacheWrite',\n 'cache_write',\n]\n\nconst PROMPT_CACHE_MISS_KEYS = ['missTokens', 'miss_tokens', 'prompt_cache_miss_tokens']\n\nconst PROMPT_CACHE_SAVINGS_KEYS = ['readSavingsUsd', 'read_savings_usd']\n\n/**\n * Read the provider's own prompt-cache accounting off one usage-bearing event payload, in the\n * `PromptCacheUsage` vocabulary the router, driver, and chat-client paths already speak.\n *\n * Two sources, one record. A payload that already carries a `promptCache` / `prompt_cache` object\n * is forwarded VERBATIM — those fields are the provider's own report, and an unrecognized one must\n * stay visible rather than be bucketed away. On top of that, flat provider counters are translated\n * to the canonical names, filling only the names the verbatim object did not already define.\n *\n * A counter the payload does not carry is left out. Defaulting it to zero would assert the provider\n * measured no cache, which is a different fact from a provider that reported nothing — and it is\n * the fact the budget reads to decide whether its charge is a measurement or a bound.\n */\nfunction readPromptCacheUsage(\n data: Record<string, unknown>,\n): Record<string, number | string> | undefined {\n const declared = finiteMetadata(data.promptCache ?? data.prompt_cache)\n const nested = plainRecord(data.promptCache) ?? plainRecord(data.prompt_cache)\n const details = plainRecord(data.prompt_tokens_details)\n const sources = [nested, data, details].filter(\n (s): s is Record<string, unknown> => s !== undefined,\n )\n\n const canonical: Record<string, number | string> = {}\n const readTokens = pickTokenCount(sources, PROMPT_CACHE_READ_KEYS)\n const writeTokens = pickTokenCount(sources, PROMPT_CACHE_WRITE_KEYS)\n const missTokens = pickTokenCount(sources, PROMPT_CACHE_MISS_KEYS)\n const readSavingsUsd = pickNonNegativeNumber(sources, PROMPT_CACHE_SAVINGS_KEYS)\n const status =\n nested !== undefined && typeof nested.status === 'string' ? nested.status : undefined\n if (readTokens !== undefined) canonical.readTokens = readTokens\n if (writeTokens !== undefined) canonical.writeTokens = writeTokens\n if (missTokens !== undefined) canonical.missTokens = missTokens\n if (readSavingsUsd !== undefined) canonical.readSavingsUsd = readSavingsUsd\n if (status !== undefined) canonical.status = status\n\n const merged = { ...canonical, ...declared }\n return Object.keys(merged).length > 0 ? merged : undefined\n}\n\nfunction pickTokenCount(\n sources: readonly Record<string, unknown>[],\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n for (const source of sources) {\n const value = source[key]\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value\n }\n }\n return undefined\n}\n\nfunction pickNonNegativeNumber(\n sources: readonly Record<string, unknown>[],\n keys: readonly string[],\n): number | undefined {\n for (const key of keys) {\n for (const source of sources) {\n const value = source[key]\n if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value\n }\n }\n return undefined\n}\n\nfunction finiteMetadata(value: unknown): Record<string, number | string> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined\n const result: Record<string, number | string> = {}\n for (const [key, entry] of Object.entries(value)) {\n if ((typeof entry === 'number' && Number.isFinite(entry)) || typeof entry === 'string') {\n result[key] = entry\n }\n }\n return Object.keys(result).length > 0 ? result : undefined\n}\n\nfunction pickFiniteNumber(data: Record<string, unknown>, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\n/**\n * Collect one turn's events, keeping only the newest snapshot of each streamed text or\n * reasoning part.\n *\n * opencode sends `message.part.updated` once per token, and every frame carries the part's\n * whole cumulative text, so keeping every frame holds O(L²) bytes per turn: two concurrent\n * audit workflows took the platform API from 459 MB to an OOM at 1.95 GB in 11 minutes.\n * A snapshot (a frame whose part carries `text`) whose text extends the previous snapshot\n * of the same part replaces it and moves to the newest position, which is the rule the\n * Sandbox SDK's text collectors already apply, so the collected text is unchanged. The kept\n * frame drops its `delta`, because its text already holds every earlier increment and a\n * reader that joins `delta ?? part.text` across frames would otherwise read only the last\n * one. Delta-only frames and every other event are kept as they arrived.\n */\nexport function createSandboxTurnEventCollector() {\n const slots: (SandboxEvent | undefined)[] = []\n const snapshots = new Map<string, { at: number; text: string }>()\n return {\n push(event: SandboxEvent) {\n const snapshot = partSnapshot(event)\n if (!snapshot) {\n slots.push(event)\n return\n }\n const previous = snapshots.get(snapshot.key)\n const extends_ = previous !== undefined && snapshot.text.startsWith(previous.text)\n if (extends_) slots[previous.at] = undefined\n snapshots.set(snapshot.key, { at: slots.length, text: snapshot.text })\n slots.push(extends_ ? withoutDelta(event) : event)\n },\n events(): SandboxEvent[] {\n return slots.filter((event): event is SandboxEvent => event !== undefined)\n },\n }\n}\n\nfunction partSnapshot(event: SandboxEvent): { key: string; text: string } | undefined {\n if (event?.type !== 'message.part.updated') return undefined\n const data = asRecord(event.data)\n const part = asRecord(data?.part) ?? asRecord(asRecord(data?.properties)?.part)\n if (!part || typeof part.id !== 'string') return undefined\n if (part.type !== 'text' && part.type !== 'reasoning' && part.type !== 'thinking')\n return undefined\n const text =\n typeof part.text === 'string'\n ? part.text\n : typeof part.content === 'string'\n ? part.content\n : undefined\n return text === undefined ? undefined : { key: `${part.type}:${part.id}`, text }\n}\n\nfunction withoutDelta(event: SandboxEvent): SandboxEvent {\n const data = asRecord(event.data)\n if (!data || !('delta' in data)) return event\n const { delta: _delta, ...rest } = data\n return { ...event, data: rest }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object'\n ? (value as Record<string, unknown>)\n : undefined\n}\n","import { RuntimeEventEnvelopeSchema } from '@tangle-network/agent-interface'\n\nconst validTimestamp = '2026-01-01T00:00:00.000Z'\n\n/** Validate a timestamp with the public runtime envelope contract. */\nexport function assertRuntimeTimestamp(value: unknown, label: string): asserts value is string {\n try {\n RuntimeEventEnvelopeSchema.parse({\n runId: 'runtime',\n eventId: 'event',\n sequence: 0,\n occurredAt: value,\n receivedAt: validTimestamp,\n event: { type: 'status', status: 'processing' },\n })\n } catch (error) {\n throw new Error(`${label} must be a valid ISO timestamp`, { cause: error })\n }\n}\n","/** Canonical Sandbox/provider wire-envelope decoding and transport identity. */\n\nimport { isRecord } from '@tangle-network/agent-core'\nimport { CanonicalStreamEventSchema, type StreamEvent } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { assertRuntimeTimestamp } from './timestamps'\n\nexport const CANONICAL_STREAM_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'child-task',\n 'message.part.updated',\n 'tool-heartbeat',\n 'tool-slow',\n 'model-processing',\n 'status',\n 'warning',\n 'raw',\n 'session.updated',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n])\n\n/** Decode one known Agent Interface event from a Sandbox event. */\nexport function canonicalStreamEventFromSandboxEvent(event: SandboxEvent): StreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n const normalized = data.normalized\n if (normalized === undefined && !CANONICAL_STREAM_EVENT_TYPES.has(type)) return undefined\n return parseCanonicalTransportEvent(type, data, normalized, 'sandbox')\n}\n\n/**\n * Transport type whose payload is the harness's OWN event, passed through verbatim.\n *\n * A `raw` payload names a harness-native type from a vocabulary the canonical schema does not\n * define (codex emits `thread.started` / `turn.started` / `turn.completed`). The transport type is\n * therefore the only canonical statement such an event makes, and its payload must never be read\n * as a canonical type: the mismatch guard below exists to catch a producer that MISLABELS a\n * canonical event, which a harness-native payload cannot do. A payload that does satisfy the\n * canonical `raw` shape (`backend` + `event`) still parses; anything else is not a canonical\n * event, and the caller reads it off the transport event instead.\n */\nconst harnessNativePayloadType = 'raw'\n\n/** Parse canonical payload fields without treating transport identity as event data. */\nexport function parseCanonicalTransportEvent(\n type: unknown,\n data: Record<string, unknown>,\n normalized: unknown,\n source: string,\n): StreamEvent | undefined {\n if (!isRecord(data)) {\n throw new Error(`${source} emitted a canonical event without an object payload`)\n }\n const outerType = String(type ?? '')\n const harnessNative = outerType === harnessNativePayloadType\n if (normalized !== undefined) {\n if (\n !harnessNative &&\n typeof normalized === 'object' &&\n normalized !== null &&\n 'type' in normalized &&\n typeof normalized.type === 'string' &&\n normalized.type !== outerType\n ) {\n throw new Error(\n `${source} canonical event type \"${normalized.type}\" does not match transport type \"${outerType}\"`,\n )\n }\n const candidate = CanonicalStreamEventSchema.safeParse(normalized)\n if (!candidate.success) {\n if (harnessNative) return undefined\n throw new Error(`${source} emitted an invalid normalized canonical event`, {\n cause: candidate.error,\n })\n }\n return candidate.data\n }\n const {\n type: embeddedType,\n eventId: _eventId,\n cursor: _cursor,\n sequence: _sequence,\n occurredAt: _occurredAt,\n normalized: _normalized,\n ...payload\n } = data\n if (!harnessNative && embeddedType !== undefined && embeddedType !== outerType) {\n throw new Error(\n `${source} canonical event type \"${String(embeddedType)}\" does not match transport type \"${outerType}\"`,\n )\n }\n const candidate = CanonicalStreamEventSchema.safeParse({ ...payload, type: outerType })\n return candidate.success ? candidate.data : undefined\n}\n\n/** Identity fields carried by either the transport envelope or its data payload. */\ninterface TransportEventIdentity {\n readonly eventId?: string\n readonly cursor?: string\n readonly sequence?: number\n readonly occurredAt?: string\n}\n\n/** Extract shared event identity without privileging one provider wire shape. */\nexport function extractTransportEventIdentity(event: unknown): TransportEventIdentity {\n const record = isRecord(event) ? event : {}\n const data = isRecord(record.data) ? record.data : {}\n const providerEvent = isRecord(record.providerEvent) ? record.providerEvent : {}\n const providerData = isRecord(providerEvent.data) ? providerEvent.data : {}\n const eventId = canonicalEventId(record, data, providerEvent, providerData)\n const cursor = stableString(\n record.cursor ?? data.cursor ?? providerEvent.cursor ?? providerData.cursor,\n )\n const sequence = optionalSequence(\n record.sequence ?? data.sequence ?? providerEvent.sequence ?? providerData.sequence,\n )\n const occurredAt = optionalTimestamp(\n record.occurredAt ?? data.occurredAt ?? providerEvent.occurredAt ?? providerData.occurredAt,\n )\n return {\n ...(eventId === undefined ? {} : { eventId }),\n ...(cursor === undefined ? {} : { cursor }),\n ...(sequence === undefined ? {} : { sequence }),\n ...(occurredAt === undefined ? {} : { occurredAt }),\n }\n}\n\nfunction canonicalEventId(\n record: Record<string, unknown>,\n data: Record<string, unknown>,\n providerEvent: Record<string, unknown>,\n providerData: Record<string, unknown>,\n): string | undefined {\n const candidates = [\n ['data.eventId', data.eventId],\n ['providerEvent.eventId', providerEvent.eventId],\n ['providerData.eventId', providerData.eventId],\n ['record.eventId', record.eventId],\n ] as const\n const present = candidates.filter(([, value]) => value !== undefined)\n // `record.id` may be the provider's replay cursor, so use it only without a canonical field.\n if (present.length === 0) return stableString(record.id ?? providerEvent.id)\n\n const normalized = present.map(([source, value]) => {\n const eventId = stableString(value)\n if (eventId === undefined) throw new Error(`transport event ${source} must be a stable string`)\n return { source, eventId }\n })\n const first = normalized[0]!\n if (normalized.some((candidate) => candidate.eventId !== first.eventId)) {\n throw new Error('transport event canonical identities disagree')\n }\n return first.eventId\n}\n\nfunction stableString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 && value.trim() === value ? value : undefined\n}\n\nfunction finiteNonNegativeInteger(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nfunction optionalSequence(value: unknown): number | undefined {\n if (value === undefined) return undefined\n if (finiteNonNegativeInteger(value) === undefined) {\n throw new Error('transport event sequence must be a non-negative safe integer')\n }\n return value as number\n}\n\nfunction optionalTimestamp(value: unknown): string | undefined {\n if (value === undefined) return undefined\n assertRuntimeTimestamp(value, 'occurredAt')\n return value\n}\n","/** Streamed and terminal Sandbox executor output, using one tool-part projector. */\n\nimport {\n collectAgentFinalMessageText,\n collectAgentResponseText,\n type SandboxEvent,\n} from '@tangle-network/sandbox'\nimport type { AgentRunOutcome } from '@tangle-network/sandbox/runtime'\nimport type { RuntimeStreamEvent } from '../types'\nimport {\n extractLlmCallEvent,\n isSandboxTerminalEvent,\n type SandboxServedBackend,\n sandboxEventServedBackend,\n} from './sandbox-events'\nimport {\n CANONICAL_STREAM_EVENT_TYPES,\n canonicalStreamEventFromSandboxEvent,\n} from './sandbox-transport-events'\nimport type { ExecutorProgressEvent, ExecutorToolCall } from './supervise/types'\n\n/**\n * Cross-event state for {@link mapSandboxToolEvent}. Sandbox backends emit a\n * tool invocation as MANY `message.part.updated` frames on the same call id\n * (pending → running → completed), so faithful projection needs per-call\n * status memory: one `tool_call` on first sighting, at most one `tool_result`\n * on the terminal transition, nothing on intermediate re-frames. Create one\n * state per turn via {@link createSandboxToolPartState}.\n *\n * @experimental\n */\nexport interface SandboxToolPartState {\n /** Last seen status per tool call id. A terminal status is sticky — later\n * frames on a settled call project to nothing. */\n statusByCall: Map<string, string>\n /** Sequence for synthesized call ids when an event carries none. */\n seq: number\n}\n\n/**\n * Fresh per-turn {@link SandboxToolPartState} for {@link mapSandboxToolEvent} — an\n * empty call-status map so each turn projects tool frames independently.\n *\n * @experimental\n */\nexport function createSandboxToolPartState(): SandboxToolPartState {\n return { statusByCall: new Map(), seq: 0 }\n}\n\n/** Statuses that settle one tool call as a failure. A failed tool call stays a tool result:\n * the run's terminal state comes from the public Sandbox outcome tracker, never from here. */\nconst TERMINAL_FAILURE = /^(error|errored|failed|failure|cancelled|canceled|timeout|timed_out)$/i\n\n/**\n * Project one `SandboxEvent` onto the `tool_call` / `tool_result` variants of\n * `RuntimeStreamEvent` — the tool-part projection `mapSandboxEvent`\n * deliberately does NOT perform. Opt-in and additive: `mapSandboxEvent`'s\n * default vocabulary (text/reasoning deltas + `llm_call`) is unchanged;\n * consumers that need the tool surface (chat UIs rendering tool activity)\n * compose this projector alongside it — `streamAgentTurn` does exactly that\n * under its `preserveToolParts` option.\n *\n * Handled shapes (observed on the opencode / claude-code sandbox backends):\n * - `message.part.updated` with `part.type === 'tool'` — stateful: a\n * `tool_call` on the call id's first frame (args from `state.input` or\n * `state.metadata.input`), a `tool_result` when the status transitions to\n * `completed` (result from `state.output` / `metadata.output`) or to a\n * terminal failure (result is `{ error, status, output? }` — the error\n * surfaced in-band, never dropped).\n * - bare `tool*` event types (`tool.call`, `tool_result`, …) — stateless:\n * `*result*` types project to `tool_result`, the rest to `tool_call`.\n * - codex `raw` events whose inner `item.started` / `item.updated` /\n * `item.completed` carries a command, MCP, collaboration, web search or\n * file change item — stateful on the item id, like a tool part. Other raw\n * events, including opencode's raw `tool_use` echoes, project nothing.\n *\n * Returns `[]` for every non-tool event.\n *\n * @experimental\n */\nexport function mapSandboxToolEvent(\n event: SandboxEvent,\n state: SandboxToolPartState,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n if (!event || typeof event !== 'object') return []\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n if (String(part.type ?? '') !== 'tool') return []\n return projectToolPart(part, state, typeof event.id === 'string' ? event.id : undefined)\n }\n // Codex reports a tool only as an `item.*` event inside a `raw` event, never as a tool part.\n // 83 of 83 archived codex turns held 3,320 tool items and projected none.\n if (type === 'raw') return projectCodexItem(data, state)\n // `tool-heartbeat` and `tool-slow` report that a call is STILL RUNNING. They carry the call's\n // `partId`, not a call id, so projecting them as calls recorded a new `tool_call` every 5 s of\n // every long call: 432 of a root's 448 recorded `await_event` calls were\n // heartbeats of 16 real ones.\n if (CANONICAL_STREAM_EVENT_TYPES.has(type)) return []\n\n if (type.includes('tool')) {\n const callId =\n pickString(data, ['toolCallId', 'tool_use_id', 'id']) ??\n (typeof event.id === 'string' ? event.id : undefined) ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(data, ['name', 'toolName', 'tool']) ?? 'sandbox_tool'\n if (type.includes('result')) {\n return [\n {\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: data.output ?? data.result ?? data.content ?? data,\n },\n ]\n }\n return [\n { type: 'tool_call', toolName, toolCallId: callId, args: data.input ?? data.args ?? {} },\n ]\n }\n\n return []\n}\n\nfunction projectToolPart(\n part: Record<string, unknown>,\n state: SandboxToolPartState,\n eventId: string | undefined,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n const callId =\n pickString(part, ['callID', 'callId', 'toolCallId', 'id']) ??\n eventId ??\n `sandbox-tool-${++state.seq}`\n const toolName = pickString(part, ['tool', 'toolName', 'name']) ?? 'sandbox_tool'\n const toolState =\n part.state && typeof part.state === 'object' ? (part.state as Record<string, unknown>) : {}\n const metadata =\n toolState.metadata && typeof toolState.metadata === 'object'\n ? (toolState.metadata as Record<string, unknown>)\n : {}\n const status = pickString(toolState, ['status']) ?? 'updated'\n\n const previous = state.statusByCall.get(callId)\n const settled =\n previous === 'completed' || (previous !== undefined && TERMINAL_FAILURE.test(previous))\n if (settled) return []\n\n const out: (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] = []\n if (previous === undefined) {\n out.push({\n type: 'tool_call',\n toolName,\n toolCallId: callId,\n args: toolState.input ?? metadata.input ?? {},\n })\n }\n state.statusByCall.set(callId, status)\n\n if (status === 'completed') {\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: toolState.output ?? metadata.output ?? '',\n })\n } else if (TERMINAL_FAILURE.test(status)) {\n const message =\n pickString(toolState, ['error', 'message']) ??\n pickString(metadata, ['error', 'message']) ??\n `sandbox tool ended with status ${status}`\n const output = toolState.output ?? metadata.output\n out.push({\n type: 'tool_result',\n toolName,\n toolCallId: callId,\n result: { error: message, status, ...(output !== undefined ? { output } : {}) },\n })\n }\n return out\n}\n\n/** Codex item types that are tool calls. Reasoning, messages and todo lists are not. */\nconst CODEX_TOOL_ITEMS: ReadonlySet<string> = new Set([\n 'command_execution',\n 'mcp_tool_call',\n 'collab_tool_call',\n 'web_search',\n 'file_change',\n])\n\n/** Item fields that describe the call's progress or outcome rather than what it was asked to do. */\nconst CODEX_ITEM_OUTCOME_FIELDS: ReadonlySet<string> = new Set([\n 'id',\n 'type',\n 'status',\n 'result',\n 'error',\n 'aggregated_output',\n 'exit_code',\n])\n\n/**\n * Project a codex `item.started` / `item.updated` / `item.completed` tool item through the same\n * per-call state as a tool part, keyed on the item id: one `tool_call` on its first frame and one\n * `tool_result` when it completes. Tool names follow Eval's codex intake: `server/tool` for MCP.\n */\nfunction projectCodexItem(\n data: Record<string, unknown>,\n state: SandboxToolPartState,\n): (RuntimeStreamEvent & { type: 'tool_call' | 'tool_result' })[] {\n if (data.backend !== 'codex' || !data.event || typeof data.event !== 'object') return []\n const inner = data.event as Record<string, unknown>\n const phase = inner.type\n if (phase !== 'item.started' && phase !== 'item.updated' && phase !== 'item.completed') return []\n if (!inner.item || typeof inner.item !== 'object') return []\n const item = inner.item as Record<string, unknown>\n const itemType = pickString(item, ['type'])\n if (itemType === undefined || !CODEX_TOOL_ITEMS.has(itemType)) return []\n const error =\n item.error && typeof item.error === 'object'\n ? (pickString(item.error as Record<string, unknown>, ['message']) ?? `${itemType} failed`)\n : undefined\n const failed =\n item.status === 'failed' ||\n error !== undefined ||\n (itemType === 'command_execution' && typeof item.exit_code === 'number' && item.exit_code !== 0)\n const status = phase !== 'item.completed' ? 'running' : failed ? 'failed' : 'completed'\n const input = Object.fromEntries(\n Object.entries(item).filter(([key]) => !CODEX_ITEM_OUTCOME_FIELDS.has(key)),\n )\n const output = item.result ?? item.aggregated_output ?? item.changes\n return projectToolPart(\n {\n ...(typeof item.id === 'string' ? { callID: item.id } : {}),\n tool: codexToolName(itemType, item),\n state: {\n status,\n input,\n ...(output === undefined || output === null ? {} : { output }),\n ...(status === 'failed' ? { error: error ?? `${itemType} failed` } : {}),\n },\n },\n state,\n undefined,\n )\n}\n\nfunction codexToolName(itemType: string, item: Record<string, unknown>): string {\n if (itemType === 'mcp_tool_call') {\n const name = [pickString(item, ['server']), pickString(item, ['tool'])]\n .filter((part) => part !== undefined)\n .join('/')\n return name === '' ? 'mcp' : name\n }\n if (itemType === 'collab_tool_call') return pickString(item, ['tool']) ?? 'subagent'\n if (itemType === 'web_search' || itemType === 'file_change') return itemType\n return pickString(item, ['name']) ?? itemType\n}\n\nfunction pickString(data: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\n/**\n * Project one `SandboxEvent` onto the `RuntimeStreamEvent` chat-UX vocabulary,\n * for runtimes that bridge a sandbox `streamPrompt` into the\n * `AgentRuntime.act` streaming contract. Returns `undefined` for events that\n * have no faithful projection — the raw stream is preserved separately for the\n * `OutputAdapter`, so an unmapped event never loses data.\n *\n * Mapped (the task-optional incremental variants — no synthesized task\n * lifecycle, no guessed tool-part shapes):\n * - `message.part.updated` text part → `text_delta`\n * - `message.part.updated` reasoning/thinking part → `reasoning_delta`\n * - cost-bearing events → `llm_call` (shared with the ledger extractor)\n *\n * Tool parts are deliberately NOT mapped here (unchanged default) — compose\n * {@link mapSandboxToolEvent} alongside when a consumer needs them.\n *\n * The opencode backend emits incremental text as\n * `{ type: 'message.part.updated', data: { part: { type, text }, delta } }`;\n * `delta` is the increment, `part.text` the running accumulation.\n */\nexport function mapSandboxEvent(\n event: SandboxEvent,\n opts: { agentRunName?: string } = {},\n): RuntimeStreamEvent | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'message.part.updated') {\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : {}\n const partType = String(part.type ?? '')\n const delta = typeof data.delta === 'string' ? data.delta : undefined\n const text = delta ?? (typeof part.text === 'string' ? part.text : undefined)\n if (text === undefined) return undefined\n if (partType === 'text') return { type: 'text_delta', text }\n if (partType === 'reasoning' || partType === 'thinking')\n return { type: 'reasoning_delta', text }\n return undefined\n }\n\n return extractLlmCallEvent(event, opts.agentRunName ?? 'agent')\n}\n\n/**\n * Project one `SandboxEvent` onto Runtime's executor progress vocabulary: incremental text and\n * reasoning, tool calls and results, and an interaction request. It composes the existing\n * projections ({@link mapSandboxEvent}, {@link mapSandboxToolEvent}, and the canonical Agent\n * Interface decode) so every sandbox-shaped executor publishes live output through one reader.\n * Usage-bearing events project to nothing here — accounting stays on the `tokens`/`cost`\n * channels.\n *\n * Pass one {@link SandboxToolPartState} per turn so a multi-frame tool call yields one call and\n * at most one result.\n *\n * @experimental\n */\nexport function sandboxProgressEvents(\n event: SandboxEvent,\n state: SandboxToolPartState,\n): ExecutorProgressEvent[] {\n const canonical = canonicalStreamEventFromSandboxEvent(event)\n if (canonical?.type === 'interaction') {\n return [{ kind: 'interaction', request: canonical.request }]\n }\n if (canonical?.type === 'child-task') {\n return [{ kind: 'child_task', event: canonical }]\n }\n const tools = mapSandboxToolEvent(event, state).map((projected) =>\n projected.type === 'tool_call'\n ? ({\n kind: 'tool_call',\n toolName: projected.toolName,\n ...(projected.toolCallId === undefined ? {} : { toolCallId: projected.toolCallId }),\n ...(projected.args === undefined ? {} : { args: projected.args }),\n } as const)\n : ({\n kind: 'tool_result',\n toolName: projected.toolName,\n ...(projected.toolCallId === undefined ? {} : { toolCallId: projected.toolCallId }),\n ...(projected.result === undefined ? {} : { result: projected.result }),\n } as const),\n )\n if (tools.length > 0) return tools\n const mapped = mapSandboxEvent(event)\n if (mapped?.type === 'text_delta') return [{ kind: 'text_delta', text: mapped.text }]\n if (mapped?.type === 'reasoning_delta') return [{ kind: 'reasoning_delta', text: mapped.text }]\n return []\n}\n\n/**\n * What a settled turn produced, as an explicit marker.\n *\n * `text` carries the byte length of the answer, `empty` says a text-bearing terminal event was\n * observed and carried nothing, and `absent` says no text-bearing event was observed at all.\n * The three are distinct on purpose: an empty settle blob used to be indistinguishable from lost\n * output, so a reader could not tell a box that produced nothing from one whose answer never\n * arrived.\n */\nexport type SandboxOutputMarker =\n | { readonly kind: 'text'; readonly bytes: number }\n | { readonly kind: 'empty' }\n | { readonly kind: 'absent' }\n\n/** Parsed output of one Sandbox executor turn. */\nexport interface SandboxLeafOut {\n events: SandboxEvent[]\n /** The observed answer. `undefined` when no text-bearing event was observed — never `''`. */\n content: string | undefined\n /** Explicit account of what the turn produced. */\n output: SandboxOutputMarker\n /**\n * Provider and model the platform reported serving this turn, when it reported one. Absent means\n * the platform said nothing; it is never filled from the request, because a request is not a\n * receipt.\n */\n servedBackend?: SandboxServedBackend\n toolCalls?: ExecutorToolCall[]\n outcome?: AgentRunOutcome\n}\n\n/** Project the complete Sandbox event stream into the standard executor result shape. */\nexport function sandboxLeafOutputFromEvents(events: SandboxEvent[]): SandboxLeafOut {\n const content = collectAgentFinalMessageText(events) ?? collectAgentResponseText(events)\n const toolCalls = sandboxToolCalls(events)\n const servedBackend = lastServedBackend(events)\n return {\n events,\n content,\n output: sandboxOutputMarker(content, events.some(carriesText)),\n ...(servedBackend === undefined ? {} : { servedBackend }),\n ...(toolCalls.length === 0 ? {} : { toolCalls }),\n }\n}\n\n/**\n * Classify observed text into the explicit output marker. `sawTextEvent` says whether the stream\n * carried a text-bearing event at all, which is what separates a box that answered nothing from a\n * box whose answer was never observed.\n */\nexport function sandboxOutputMarker(\n content: string | undefined,\n sawTextEvent = content !== undefined,\n): SandboxOutputMarker {\n if (content !== undefined && content.length > 0) {\n return { kind: 'text', bytes: Buffer.byteLength(content, 'utf8') }\n }\n return sawTextEvent ? { kind: 'empty' } : { kind: 'absent' }\n}\n\n/** True when the event carries a text field a turn's answer could come from, empty or not. */\nfunction carriesText(event: SandboxEvent): boolean {\n if (!event || typeof event !== 'object') return false\n const data =\n event.data && typeof event.data === 'object' ? (event.data as Record<string, unknown>) : {}\n if (typeof data.finalText === 'string' || typeof data.text === 'string') return true\n if (typeof data.delta === 'string') return true\n const part =\n data.part && typeof data.part === 'object' ? (data.part as Record<string, unknown>) : undefined\n return part !== undefined && part.type === 'text' && typeof part.text === 'string'\n}\n\n/** The last served identity the platform reported across a turn's events, or `undefined`. */\nfunction lastServedBackend(events: readonly SandboxEvent[]): SandboxServedBackend | undefined {\n let served: SandboxServedBackend | undefined\n for (const event of events) {\n const next = sandboxEventServedBackend(event)\n if (next !== undefined) served = next\n }\n return served\n}\n\nfunction sandboxToolCalls(events: readonly SandboxEvent[]): ExecutorToolCall[] {\n const state = createSandboxToolPartState()\n return events.flatMap((event) =>\n mapSandboxToolEvent(event, state).flatMap((projected) =>\n projected.type === 'tool_call'\n ? [\n {\n ...(projected.toolCallId === undefined ? {} : { id: projected.toolCallId }),\n name: projected.toolName,\n arguments: projected.args ?? {},\n },\n ]\n : [],\n ),\n )\n}\n\n/** Read the final text off a terminal sandbox event, when present. */\nexport function terminalTextFromSandboxEvent(event: SandboxEvent): string | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n if (!isSandboxTerminalEvent(type)) return undefined\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n for (const key of ['finalText', 'text', 'response', 'content']) {\n const value = data[key]\n if (typeof value === 'string') return value\n }\n return undefined\n}\n","import { assertResources } from './resources'\nimport type { Budget, Spend } from './types'\n\n/** Reject malformed ceilings before they can mint capacity through negative reservations. */\nexport function assertValidBudget(budget: Budget, label = 'budget'): void {\n const safeInteger = (value: number, field: string) => {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label}.${field} must be a non-negative safe integer`)\n }\n }\n const finiteNonNegative = (value: number, field: string) => {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${label}.${field} must be a non-negative finite number`)\n }\n }\n assertResources(budget.resources, 'limit', `${label}.resources`)\n safeInteger(budget.maxIterations, 'maxIterations')\n safeInteger(budget.maxTokens, 'maxTokens')\n if (budget.maxUsd !== undefined) finiteNonNegative(budget.maxUsd, 'maxUsd')\n if (budget.deadlineMs !== undefined) finiteNonNegative(budget.deadlineMs, 'deadlineMs')\n}\n\nexport function assertValidSpend(spend: Spend, label: string): void {\n assertResources(spend.resources, 'amount', `${label}.resources`)\n if (!Number.isSafeInteger(spend.iterations) || spend.iterations < 0) {\n throw new Error(`${label}.iterations must be a non-negative safe integer`)\n }\n for (const [field, value] of [\n ['input', spend.tokens.input],\n ['output', spend.tokens.output],\n ['freshInput', spend.tokens.freshInput],\n ['cacheRead', spend.tokens.cacheRead],\n ['cacheWrite', spend.tokens.cacheWrite],\n ] as const) {\n if (value === undefined) continue\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label}.tokens.${field} must be a non-negative safe integer`)\n }\n }\n for (const [field, value] of [\n ['tokensKnown', spend.tokens.tokensKnown],\n ['cacheBreakdownKnown', spend.tokens.cacheBreakdownKnown],\n ] as const) {\n if (value !== undefined && value !== false) {\n throw new Error(`${label}.tokens.${field} must be false when present`)\n }\n }\n const { freshInput, cacheRead, cacheWrite } = spend.tokens\n if (freshInput !== undefined && cacheRead !== undefined && cacheWrite !== undefined) {\n const classified = freshInput + cacheRead + cacheWrite\n // A spend that CLAIMS a complete split must partition `input` exactly — that invariant is what\n // lets the charge credit a cache read. A spend that declares its split INCOMPLETE reports\n // classes covering only part of `input`, which is exactly what `addTokenUsage` produces when it\n // folds a classified turn together with an unclassified one. Demanding an exact partition there\n // rejects the shape the incomplete flag exists to describe, and a resumed pool built from such\n // an aggregate died at construction. Either way the classes may never EXCEED the total they\n // partition; that direction would let bad telemetry credit tokens nobody presented.\n if (spend.tokens.cacheBreakdownKnown !== false) {\n if (classified !== spend.tokens.input) {\n throw new Error(`${label}.tokens cache classes must sum to input`)\n }\n } else if (classified > spend.tokens.input) {\n throw new Error(`${label}.tokens cache classes must not exceed input`)\n }\n }\n for (const [field, value] of [\n ['usd', spend.usd],\n ['ms', spend.ms],\n ] as const) {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${label}.${field} must be a non-negative finite number`)\n }\n }\n if (spend.usdEstimated !== undefined) {\n if (!Number.isFinite(spend.usdEstimated) || spend.usdEstimated < 0) {\n throw new Error(`${label}.usdEstimated must be a non-negative finite number`)\n }\n // The catalog-priced part is a part OF `usd`, not an addition to it. A larger value would let\n // `usd - usdEstimated` report negative provider-billed dollars.\n if (spend.usdEstimated > spend.usd) {\n throw new Error(`${label}.usdEstimated must not exceed ${label}.usd`)\n }\n // A catalog price is never a measurement. Admitting one under `usdKnown: true` would let an\n // estimate be read as billed spend.\n if (spend.usdKnown !== false) {\n throw new Error(`${label}.usdEstimated requires ${label}.usdKnown false`)\n }\n }\n}\n","/**\n * The balances of one conserved budget pool, and the arithmetic that moves them. `createBudgetPool`\n * (`./budget`) owns tickets, the wait queue and the public contract; this module owns the numbers:\n * `total ≡ free + reserved + committed` per channel, the taint flags that say a balance is a\n * ceiling rather than a measurement, and the named-resource states.\n */\n\nimport { chargedTokens, hasCompleteCacheBreakdown, zeroTokenUsage } from '../util'\nimport type { BudgetPoolRestore, ReservationFloor, ReservationShortfall } from './budget'\nimport { withBudgetResources } from './resources'\nimport { assertValidBudget, assertValidSpend } from './spend-validation'\nimport type { Budget, BudgetOverspend, Spend } from './types'\n\ninterface ResourceBalance {\n unit: string\n limit: number\n remaining: number\n reserved: number\n committed: number\n known: boolean\n}\n\nexport interface BudgetLedger {\n readonly usdCapped: boolean\n readonly absoluteDeadlineMs: number\n readonly resources: Map<string, ResourceBalance>\n freeTokens: number\n reservedTokens: number\n committedTokens: number\n // Set once the pool records work with an unreported token count, never cleared. Unlike\n // `usdTainted` it does NOT close admission (the token channel is always capped; refusing every\n // later reservation would turn one skipped usage report into a dead run): the cap is enforced on\n // what is known and `readout().tokensKnown` reports an under-count.\n tokensTainted: boolean\n // Set once the pool charges a spend whose cache split it could not read, never cleared: it was\n // charged at its rolled-up prompt total, an upper bound on newly-presented tokens. Same treatment\n // as `tokensTainted`. A restored uncertain reservation does NOT set it (a declared ceiling has no\n // cache composition to misread; `tokensTainted` already reports it).\n cacheBreakdownTainted: boolean\n freeUsd: number\n reservedUsd: number\n committedUsd: number\n // Closes dollar admission: set when unknown dollar cost lands under a dollar-capped root.\n usdTainted: boolean\n // Reporting only: set whenever ANY recorded work carried `usdKnown: false`, capped or not, so\n // the readout never presents a lower bound as a measured dollar total.\n usdMeasured: boolean\n freeIterations: number\n reservedIterations: number\n committedIterations: number\n}\n\nexport interface ResourceSettlement {\n fault?: string\n overspent: BudgetOverspend[]\n rootExceeded?: string\n}\n\nexport function openBudgetLedger(root: Budget, runStartedAtMs: number): BudgetLedger {\n return {\n usdCapped: root.maxUsd !== undefined,\n absoluteDeadlineMs: root.deadlineMs === undefined ? 0 : runStartedAtMs + root.deadlineMs,\n resources: new Map(\n Object.entries(root.resources ?? {}).map(\n ([name, value]) =>\n [\n name,\n { ...value, remaining: value.limit, reserved: 0, committed: 0, known: true },\n ] as const,\n ),\n ),\n freeTokens: root.maxTokens,\n reservedTokens: 0,\n committedTokens: 0,\n tokensTainted: false,\n cacheBreakdownTainted: false,\n freeUsd: root.maxUsd ?? 0,\n reservedUsd: 0,\n committedUsd: 0,\n usdTainted: false,\n usdMeasured: true,\n freeIterations: root.maxIterations,\n reservedIterations: 0,\n committedIterations: 0,\n }\n}\n\nexport function ledgerValidateUnits(l: BudgetLedger, spend: Spend): void {\n for (const [name, value] of Object.entries(spend.resources ?? {})) {\n const limit = l.resources.get(name)\n if (limit && limit.unit !== value.unit) throw new Error(`resource ${name}: unit mismatch`)\n }\n}\n\n/** Record that `spend` carried an unreported or unclassified channel. */\nfunction noteUnknowns(l: BudgetLedger, spend: Spend): void {\n if (spend.tokensKnown === false) l.tokensTainted = true\n if (!hasCompleteCacheBreakdown(spend.tokens)) l.cacheBreakdownTainted = true\n if (spend.usdKnown === false) l.usdMeasured = false\n}\n\n/**\n * Commit named-resource spend and classify it. `allocations` is the settling reservation's own\n * allocations, or `undefined` for spend holding no reservation (`observe`, restore). Unverifiable\n * usage is a `fault` (the remaining balance is consumed so admission closes); measured usage above\n * an allocation is `overspent`; without allocations, usage leaving a root limit overdrawn is\n * `rootExceeded`. A reservation within its own allocation is never charged with a root overdraw:\n * a negative balance at its settlement was caused, and reported, by earlier spend.\n */\nexport function ledgerCommitResources(\n l: BudgetLedger,\n spend: Spend,\n allocations?: Budget['resources'],\n requireAll = true,\n): ResourceSettlement {\n let fault: string | undefined\n let rootExceeded: string | undefined\n const overspent: BudgetOverspend[] = []\n for (const [name, state] of l.resources) {\n const value = spend.resources?.[name]\n if (!requireAll && value === undefined) continue\n const allocation = allocations?.[name]?.limit ?? 0\n const amount = value?.amount ?? 0\n state.reserved -= allocation\n const committed = state.committed + amount\n const overflow = !Number.isSafeInteger(committed)\n state.committed = Math.min(committed, Number.MAX_SAFE_INTEGER)\n // Subtract reserved capacity first so every intermediate balance stays a safe integer.\n state.remaining = state.limit - state.reserved - state.committed\n if (value?.known !== true || overflow) {\n state.known = false\n // The remaining balance cannot fund another invocation without a complete receipt.\n // Consume free capacity conservatively; later known refunds do not reopen admission.\n const retained = Math.max(0, state.remaining)\n state.committed += retained\n state.remaining -= retained\n fault ??= overflow\n ? `resource ${name}: amount overflow under an enforced limit`\n : `resource ${name}: unknown usage under an enforced limit`\n } else if (allocations !== undefined) {\n if (amount > allocation) {\n overspent.push({ channel: `resource:${name}`, reserved: allocation, spent: amount })\n }\n } else if (state.remaining < 0) {\n rootExceeded ??= `resource ${name}: exceeded root limit ${state.limit}`\n }\n }\n return { ...(fault ? { fault } : {}), overspent, ...(rootExceeded ? { rootExceeded } : {}) }\n}\n\n/** Every channel `b` does not fit, measured against the free balance less `keep`. */\nexport function ledgerShortfalls(\n l: BudgetLedger,\n b: Budget,\n keep: ReservationFloor | undefined,\n): ReservationShortfall[] {\n const wantTokens = b.maxTokens\n const wantUsd = b.maxUsd ?? 0\n const wantIterations = b.maxIterations\n const shortfalls: ReservationShortfall[] = []\n const short = (\n channel: ReservationShortfall['channel'],\n requested: number,\n free: number,\n held: number,\n closedByUnknownSpend = false,\n ): void => {\n shortfalls.push({\n channel,\n requested,\n free: closedByUnknownSpend ? 0 : Math.max(0, free),\n ...(closedByUnknownSpend || held <= 0 ? {} : { held }),\n ...(closedByUnknownSpend ? { closedByUnknownSpend: true as const } : {}),\n })\n }\n for (const [name, state] of l.resources) {\n const limit = b.resources![name]!.limit\n if (!state.known) short(`resource:${name}`, limit, 0, 0, true)\n else if (limit > state.remaining)\n short(`resource:${name}`, limit, state.remaining, state.reserved)\n }\n if (l.usdCapped && l.usdTainted) short('usd', wantUsd, 0, 0, true)\n const tokensFree = l.freeTokens - (keep?.tokens ?? 0)\n const iterationsFree = l.freeIterations - (keep?.iterations ?? 0)\n if (wantTokens > tokensFree) short('tokens', wantTokens, tokensFree, l.reservedTokens)\n if (wantIterations > iterationsFree)\n short('iterations', wantIterations, iterationsFree, l.reservedIterations)\n const usdFree = l.freeUsd - (keep?.usd ?? 0)\n if (l.usdCapped && !l.usdTainted && wantUsd > usdFree)\n short('usd', wantUsd, usdFree, l.reservedUsd)\n return shortfalls\n}\n\n/** Move `b` from free to reserved. The caller has checked that it fits. */\nexport function ledgerTake(l: BudgetLedger, b: Budget): void {\n for (const [name, state] of l.resources) {\n const amount = b.resources![name]!.limit\n state.remaining -= amount\n state.reserved += amount\n }\n l.freeTokens -= b.maxTokens\n l.reservedTokens += b.maxTokens\n l.freeIterations -= b.maxIterations\n l.reservedIterations += b.maxIterations\n const wantUsd = b.maxUsd ?? 0\n if (wantUsd > 0) {\n l.freeUsd -= wantUsd\n l.reservedUsd += wantUsd\n }\n}\n\n/**\n * The overspends a settlement of `spent` against `held` decides, before any balance moves. An\n * OVERSPEND is measured spend above the reservation; unknown dollars under a dollar cap (a fault\n * the caller reports) are flagged `unknownUnderCap`. `usdBudgeted` is whether the child declared a\n * dollar ceiling: without `maxUsd` it reserved NO dollars, so under a capped root its dollars are\n * OBSERVED spend, committed and debited from `free` like `observe`d inference.\n */\nexport function ledgerClassifyOverspend(\n l: BudgetLedger,\n held: { tokens: number; usd: number; iterations: number },\n usdBudgeted: boolean,\n spent: Spend,\n): { overspent: BudgetOverspend[]; unknownUnderCap: boolean } {\n const unknownUnderCap = l.usdCapped && spent.usdKnown === false\n const spentTokens = chargedTokens(spent.tokens)\n const overspent: BudgetOverspend[] = []\n if (spentTokens > held.tokens) {\n overspent.push({ channel: 'tokens', reserved: held.tokens, spent: spentTokens })\n }\n if (spent.iterations > held.iterations) {\n overspent.push({ channel: 'iterations', reserved: held.iterations, spent: spent.iterations })\n }\n // Unmeasured dollars may not be compared against a reservation as if billed (a catalog-priced\n // turn could exceed the ceiling and report an overspend the child never made): the known\n // channels settle, then the dollar channel is tainted and admission closes.\n // USD is conserved ONLY when the root AND the child declared a ceiling (`maxUsd` is optional on\n // both); otherwise it is an OBSERVED quantity, and an unset ceiling must not act as a hard $0.\n if (!unknownUnderCap && l.usdCapped && usdBudgeted && spent.usd > held.usd) {\n overspent.push({ channel: 'usd', reserved: held.usd, spent: spent.usd })\n }\n return { overspent, unknownUnderCap }\n}\n\n/**\n * Release the whole reservation `held`, then commit actual spend; the difference is the refund\n * that flows back to `free`. Unconditional arithmetic: nothing here throws on spend it can read.\n */\nexport function ledgerSettle(\n l: BudgetLedger,\n held: { tokens: number; usd: number; iterations: number; resources?: Budget['resources'] },\n spent: Spend,\n unknownUnderCap: boolean,\n): ResourceSettlement {\n noteUnknowns(l, spent)\n const spentTokens = chargedTokens(spent.tokens)\n l.reservedTokens -= held.tokens\n l.committedTokens += spentTokens\n l.freeTokens += held.tokens - spentTokens\n\n l.reservedIterations -= held.iterations\n l.committedIterations += spent.iterations\n l.freeIterations += held.iterations - spent.iterations\n\n if (l.usdCapped) {\n l.reservedUsd -= held.usd\n l.committedUsd += spent.usd\n if (unknownUnderCap) {\n l.usdTainted = true\n l.freeUsd = 0\n } else {\n // `held.usd` is 0 for a child that declared no ceiling, so this debits its observed\n // dollars straight out of the capped root's free balance — the root's `usdLeft`\n // shrinks by what the child really spent and admission closes when it runs out.\n l.freeUsd += held.usd - spent.usd\n }\n } else {\n // With no root dollar limit, record observed spend without a reservation channel.\n l.committedUsd += spent.usd\n }\n return ledgerCommitResources(l, spent, held.resources ?? {})\n}\n\n/**\n * Direct free → committed debit (no ticket). `free` may go negative on overspend: the readout then\n * reports exhaustion and the in-loop guard halts the driver. Work with an unreported token count\n * still debits what IS known and marks the balance incomplete; refusing to record it is the \"free\n * turn\" the pool must never see.\n */\nexport function ledgerObserve(\n l: BudgetLedger,\n spend: Spend,\n unknownUnderCap: boolean,\n requireAllResources: boolean,\n): ResourceSettlement {\n noteUnknowns(l, spend)\n const tokens = chargedTokens(spend.tokens)\n l.freeTokens -= tokens\n l.committedTokens += tokens\n l.freeIterations -= spend.iterations\n l.committedIterations += spend.iterations\n l.committedUsd += spend.usd\n if (l.usdCapped) l.freeUsd -= spend.usd\n if (unknownUnderCap) l.usdTainted = true\n return ledgerCommitResources(l, spend, undefined, requireAllResources)\n}\n\n/**\n * Reconstruct the balances from a prior process's durable record. Measured prior spend is debited\n * exactly once; a started-without-terminal child is charged at its entire reservation, so restart\n * never mints capacity and the false known flags stay visible. Direct arithmetic, not `observe`:\n * the prior spend ALREADY happened, and refusing to record it would be a zero-cost restart.\n */\nexport function ledgerRestore(l: BudgetLedger, root: Budget, restore: BudgetPoolRestore): void {\n if (restore.committed !== undefined) {\n const committed = restore.committed\n assertValidSpend(committed, 'budget restore committed')\n ledgerValidateUnits(l, committed)\n ledgerCommitResources(l, committed)\n noteUnknowns(l, committed)\n const tokens = chargedTokens(committed.tokens)\n l.freeTokens -= tokens\n l.committedTokens += tokens\n l.freeIterations -= committed.iterations\n l.committedIterations += committed.iterations\n l.committedUsd += committed.usd\n if (l.usdCapped) {\n l.freeUsd -= committed.usd\n if (committed.usdKnown === false) {\n // The prior process spent dollars it could not measure under a dollar cap: the remaining\n // balance is not a sound bound, so consume it and close dollar admission.\n l.usdTainted = true\n if (l.freeUsd > 0) l.committedUsd += l.freeUsd\n l.freeUsd = 0\n }\n }\n }\n for (const [index, uncertain] of (restore.uncertainReservations ?? []).entries()) {\n assertValidBudget(uncertain, `budget restore uncertainReservations[${index}]`)\n // The child ran (or may have run) without a settle record: its telemetry is unknown, so the\n // pool charges the full declared ceiling and reports the balance as a ceiling, never a\n // measurement.\n ledgerCommitResources(\n l,\n withBudgetResources({ iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }, root),\n )\n l.tokensTainted = true\n l.usdMeasured = false\n l.freeTokens -= uncertain.maxTokens\n l.committedTokens += uncertain.maxTokens\n l.freeIterations -= uncertain.maxIterations\n l.committedIterations += uncertain.maxIterations\n if (!l.usdCapped) continue\n if (uncertain.maxUsd === undefined) {\n // No child dollar ceiling existed, so the root's remaining dollar capacity is not safe.\n l.usdTainted = true\n l.committedUsd += l.freeUsd > 0 ? l.freeUsd : 0\n l.freeUsd = 0\n } else {\n l.freeUsd -= uncertain.maxUsd\n l.committedUsd += uncertain.maxUsd\n }\n }\n}\n","import { ValidationError } from '../../errors'\nimport type { LoopTokenUsage } from '../types'\nimport { addTokenUsage, cloneTokenUsage, zeroTokenUsage } from '../util'\nimport { addResourceSpend } from './resources'\nimport { assertValidSpend } from './spend-validation'\nimport type { Spend, TokenUsageProvenance, UsageEvent } from './types'\n\n/** Fold a normalized `UsageEvent` array into a `Spend`. Tokens and usd are separate\n * channels; iterations come from `'iteration'` events. Pure; `ms` stays zero (the\n * pool does not read wall-clock). */\nexport function spendFromUsageEvents(events: UsageEvent[]): Spend {\n const totals = newUsageTotals()\n for (const ev of events) meterUsageEvent(totals, ev)\n return spendFromUsageTotals(totals)\n}\n\n/** Running accounting totals folded from `UsageEvent`s. */\ninterface UsageTotals {\n resources?: Spend['resources']\n tokens: LoopTokenUsage\n tokensKnown: boolean\n /** Which evidence the counted tokens came from. `undefined` until the first `tokens` event. */\n tokensProvenance?: TokenUsageProvenance\n usd: number\n usdEstimated: number\n usdKnown: boolean\n iterations: number\n}\n\n/** Fresh accounting totals, optionally restored from verified committed spend. */\nexport function newUsageTotals(priorSpent?: Spend): UsageTotals {\n if (priorSpent !== undefined) assertValidSpend(priorSpent, 'prior committed usage')\n return {\n ...addResourceSpend(priorSpent?.resources),\n tokens: priorSpent === undefined ? zeroTokenUsage() : cloneTokenUsage(priorSpent.tokens),\n tokensKnown: priorSpent?.tokensKnown !== false,\n ...(priorSpent?.tokensProvenance === undefined\n ? {}\n : { tokensProvenance: priorSpent.tokensProvenance }),\n usd: priorSpent?.usd ?? 0,\n usdEstimated: priorSpent?.usdEstimated ?? 0,\n usdKnown: priorSpent?.usdKnown !== false,\n iterations: priorSpent?.iterations ?? 0,\n }\n}\n\n/**\n * Fold ONE usage event into running totals — the single place that decides which event kinds\n * meter. `progress` carries observed output rather than accounting, so it meters nothing; only\n * `iteration` advances the iteration count.\n */\nexport function meterUsageEvent(totals: UsageTotals, ev: UsageEvent): void {\n if (ev.kind === 'resource') {\n totals.resources = addResourceSpend(\n totals.resources,\n Object.fromEntries([[ev.name, { unit: ev.unit, amount: ev.amount, known: ev.known }]]),\n ).resources\n return\n }\n if (ev.kind === 'tokens') {\n if (ev.mode === 'cumulative') {\n if (ev.input < totals.tokens.input || ev.output < totals.tokens.output) {\n throw new ValidationError('cumulative executor tokens must not decrease')\n }\n const snapshot = zeroTokenUsage()\n addTokenUsage(snapshot, {\n ...ev,\n ...(ev.freshInput === undefined && totals.tokens.freshInput !== undefined\n ? { freshInput: totals.tokens.freshInput }\n : {}),\n ...(ev.cacheRead === undefined && totals.tokens.cacheRead !== undefined\n ? { cacheRead: totals.tokens.cacheRead }\n : {}),\n ...(ev.cacheWrite === undefined && totals.tokens.cacheWrite !== undefined\n ? { cacheWrite: totals.tokens.cacheWrite }\n : {}),\n ...(totals.tokens.tokensKnown === false ? { tokensKnown: false } : {}),\n })\n totals.tokens = snapshot\n } else {\n addTokenUsage(totals.tokens, ev)\n }\n if (ev.tokensKnown === false) totals.tokensKnown = false\n // An event that names no provenance came from the executor's own live stream, which is what\n // every path reported before a harness store was readable.\n const source = ev.provenance ?? 'stream-receipt'\n totals.tokensProvenance =\n totals.tokensProvenance === undefined || totals.tokensProvenance === source ? source : 'mixed'\n return\n }\n if (ev.kind === 'cost') {\n totals.usd += ev.usd\n if (ev.usdKnown === false) {\n totals.usdEstimated += ev.usdEstimated ?? 0\n totals.usdKnown = false\n }\n return\n }\n if (ev.kind === 'iteration') totals.iterations += 1\n}\n\n/** Project folded totals onto the conserved-pool `Spend`. `ms` stays zero — the pool does not\n * read wall-clock. */\nexport function spendFromUsageTotals(totals: UsageTotals): Spend {\n return {\n ...addResourceSpend(totals.resources),\n iterations: totals.iterations,\n tokens: totals.tokens,\n ...(totals.tokensKnown ? {} : { tokensKnown: false }),\n usd: totals.usd,\n ...(totals.usdKnown ? {} : { usdKnown: false }),\n ...(totals.usdEstimated > 0 ? { usdEstimated: totals.usdEstimated } : {}),\n // Only a provenance OTHER than the live stream is stated. Absence is the historical answer and\n // means the same thing, so every path that never reads a harness store is byte-unchanged.\n ...(totals.tokensProvenance === undefined || totals.tokensProvenance === 'stream-receipt'\n ? {}\n : { tokensProvenance: totals.tokensProvenance }),\n ms: 0,\n }\n}\n\nexport async function foldUsage(events: AsyncIterable<UsageEvent> | UsageEvent[]): Promise<Spend> {\n if (Array.isArray(events)) return spendFromUsageEvents(events)\n const totals = newUsageTotals()\n for await (const ev of events) meterUsageEvent(totals, ev)\n return spendFromUsageTotals(totals)\n}\n","/**\n * The conserved budget reservation pool — the invariant the whole instrument rests on (critique\n * M5/B3). One root `Budget` becomes a pool of standard quantities (tokens, usd, iterations) and\n * caller-named resources plus an absolute deadline. Children reserve atomically at spawn and\n * reconcile at settle:\n *\n * total ≡ free + reserved + committed (for every known quantity)\n *\n * `reserve` moves a child's whole ceiling `free` → `reserved` and fails closed when `free` can't\n * cover it (never read-then-spawn overcommit, so `Σk(treatment) ≡ Σk(blind)` by construction).\n * `reconcile` releases the reservation, commits ACTUAL spend, and refunds the remainder to `free`.\n * Tokens and usd are separate channels; iterations are conserved alongside them.\n *\n * The token unit is `chargedTokens`: every token counted ONCE, when it first enters the context\n * (`input − cacheRead + output`, which is `freshInput + cacheWrite + output` under a complete\n * split). A cached prefix was already charged when written; charging a cache read again made a\n * declared cap bite about 56x early on a real fleet (cache is 98% of the rolled-up prompt total).\n * No price weight enters the token channel; money is budgeted on `maxUsd`. The unit is additive,\n * so a rolled-up report agrees with the pool. Prompt tokens the provider never classified are\n * charged in full and `readout().cacheBreakdownKnown` reads false (an upper bound on newly-\n * presented work). The pool trusts reported usage: it is an accounting unit, not a trust boundary.\n *\n * Named resources require explicit units, ceilings, and complete executor measurements; missing\n * or unknown enforced measurements close admission for that resource. The pool trusts those\n * receipts and meters no external system. `Spend.boxMinutes` is evidence only, with no implicit\n * resource ceiling; never present estimated box lifetime as a measured resource receipt.\n *\n * Pure and deterministic: the run's start instant is supplied; no I/O, wall-clock or RNG read. A\n * ticket is single-use (fail-loud on double or unknown reconcile). Reconciling an OPEN ticket\n * always closes it: a fail-loud condition settles the reservation first and throws afterwards, so\n * no error path strands a reservation past `assertNoOpenTickets`. Measured spend above a\n * reservation is not fail-loud: the pool commits it, returns a `BudgetViolation`, and refuses\n * later reservations from the reduced free balance. A child that declared no `maxUsd` reserved no\n * dollars, so its real dollars are committed as observed spend against the root, not as an\n * overspend of a $0 ceiling. Unknowable dollar cost under a dollar limit closes the known\n * token/iteration work, marks the dollar channel unusable and refuses later reservations. An\n * unknowable TOKEN count records the work, debits what is known, and marks\n * `readout().tokensKnown` false (a ceiling, not a measurement); tokens are always capped, so one\n * unreported turn must not end the run.\n *\n * A reservation the free balance cannot cover now can WAIT (`reserve(b, holder, { wait: true })`)\n * when it would fit once open reservations return. It holds nothing while waiting, so\n * conservation is untouched; waiters are granted in asking order and refused once no open\n * reservation is left to return any.\n *\n * A pool can be RESTORED from a prior process's durable record: measured committed spend is\n * debited once, and each child journaled as started but never settled is charged at its full\n * declared ceiling. Restart never mints capacity, unknown flags stay visible, and the original\n * absolute deadline never slides.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport {\n type BudgetLedger,\n ledgerClassifyOverspend,\n ledgerObserve,\n ledgerRestore,\n ledgerSettle,\n ledgerShortfalls,\n ledgerTake,\n ledgerValidateUnits,\n openBudgetLedger,\n} from './budget-ledger'\nimport { assertValidBudget, assertValidSpend } from './spend-validation'\nimport type { Budget, BudgetViolation, Spend, UsageEvent } from './types'\nimport { foldUsage } from './usage-metering'\n\n/** A reconciliation whose spend the pool cannot verify, thrown after the reservation settled.\n * `budgetViolation` carries any measured overspend on the same settlement. */\nexport class BudgetReconcileFault extends Error {\n readonly budgetViolation?: BudgetViolation\n\n constructor(message: string, budgetViolation?: BudgetViolation) {\n super(message)\n this.name = 'BudgetReconcileFault'\n if (budgetViolation !== undefined) this.budgetViolation = budgetViolation\n }\n}\n\n/** Opaque, single-use reservation handle returned by `reserve` and consumed by\n * `reconcile`. Carries the reserved ceilings so reconciliation needs no lookup. */\nexport interface ReservationTicket {\n readonly id: number\n readonly reserved: {\n readonly resources?: Budget['resources']\n readonly tokens: number\n readonly usd: number\n readonly iterations: number\n /**\n * Whether the child's `Budget` declared `maxUsd`. `reserved.usd` is `0` for both an undeclared\n * ceiling (real dollars are committed as OBSERVED spend) and a declared `$0` (a breach is\n * fail-loud). An absent flag is read as `true`, the fail-closed reading.\n */\n readonly usdBudgeted?: boolean\n }\n}\n\n/** Where in the spawn lifecycle a reservation was last seen. `admitted` is the window between\n * `reserve` and the hand-off to the child's execution, which the spawning code owns; `executing`\n * means the child owns the ticket and only its settlement can close it. */\nexport type ReservationStage = 'admitted' | 'executing'\n\n/** Who holds a reservation, recorded at `reserve` and refined through `attribute`, so a ticket\n * stranded at the join barrier names its work. Only `stage` is required. */\nexport interface ReservationHolder {\n /** The caller's assignment identity (`SpawnOpts.assignmentId`, else its `key`). */\n readonly assignment?: string\n /** The spawn label — the name an operator recognizes in a journal. */\n readonly label?: string\n /** The spawned node's id, once admission minted one. */\n readonly childId?: string\n readonly stage: ReservationStage\n}\n\n/** One reservation still open at the join barrier — a pool leak, with the holder to chase. */\nexport interface LeakedReservation extends ReservationHolder {\n readonly ticketId: number\n}\n\n/** Post-reservation pool readout — the shape `Scope.budget` exposes. `deadlineMs` is the ABSOLUTE\n * wall-clock deadline (0 when none). `usdCapped` distinguishes a real `usdLeft <= 0` exhaustion\n * from an uncapped pool (which always reads `usdLeft: 0`). */\nexport type BudgetReadout = Readonly<{\n resources?: Readonly<\n Record<\n string,\n {\n unit: string\n limit: number\n remaining: number\n reserved: number\n committed: number\n known: boolean\n }\n >\n >\n tokensLeft: number\n /** False once the pool recorded work with UNREPORTED tokens (`tokensKnown: false`): `tokensLeft`\n * is then a ceiling, and real consumption is at least the debited amount. */\n tokensKnown: boolean\n /** False once the pool charged a REPORTED spend whose prompt-cache split it could not read: the\n * unclassified prompt tokens were charged in full, so the debit is an upper bound. Separate from\n * `tokensKnown` (counts arrived, composition did not); a restored uncertain reservation leaves\n * it alone, since a declared ceiling has no composition to misread. */\n cacheBreakdownKnown: boolean\n usdLeft: number\n usdCapped: boolean\n /** False once any recorded work reported an unknown dollar cost; the dollar totals are then a\n * lower bound on real spend, not a measurement. */\n usdKnown: boolean\n iterationsLeft: number\n deadlineMs: number\n reservedTokens: number\n}>\n\n/** The part of each channel a reservation must leave free: a manager's own share of its slice,\n * which its children may not reserve. */\nexport interface ReservationFloor {\n readonly tokens: number\n readonly iterations: number\n readonly usd?: number\n}\n\n/** How a caller asks for a reservation. */\nexport interface ReserveOptions {\n /** Wait for budget instead of failing, when the reservations still open would return enough.\n * The reservation then holds nothing until it is granted. */\n readonly wait?: boolean\n /** Leave this much of each channel free after the reservation. */\n readonly keep?: ReservationFloor\n}\n\n/**\n * A waiting reservation that can never be granted: every open reservation settled and the free\n * balance still cannot cover it. `shortfalls` are the channels that did not fit at that moment.\n */\nexport class ReservationWaitRefused extends Error {\n readonly reason = 'budget-exhausted' as const\n readonly shortfalls: readonly ReservationShortfall[]\n\n constructor(shortfalls: readonly ReservationShortfall[]) {\n super(\n `budget-exhausted: nothing left running could return enough budget for this worker (${shortfalls\n .map(\n (shortfall) =>\n `${shortfall.channel} requested ${shortfall.requested}, free ${shortfall.free}`,\n )\n .join('; ')})`,\n )\n this.name = 'ReservationWaitRefused'\n this.shortfalls = shortfalls\n }\n}\n\n/** Why a reservation was refused. `usd-unbudgeted`: the root declared no dollar ceiling, so the\n * fix is to budget the root, not to ask for less. */\nexport type ReservationRejection = 'budget-exhausted' | 'usd-unbudgeted'\n\n/** One channel a `budget-exhausted` reservation could not fit. A refusal lists every such channel\n * so shrinking one request is not met by a second refusal (a director whose 100-iteration child\n * was refused spent a probe worker to learn the pool admitted 3). `free` is a snapshot, and a\n * driver's metered turns draw from the same pool, so only `iterations` can be requested at exactly\n * `free`. `closedByUnknownSpend`: unmeasured usage ran under that enforced limit, so the channel\n * refuses every reservation for the rest of the run. */\nexport interface ReservationShortfall {\n readonly channel: 'tokens' | 'iterations' | 'usd' | `resource:${string}`\n readonly requested: number\n readonly free: number\n /** What open reservations hold on this channel, when they hold any. A request of at most\n * `free + held` can wait for them to settle; a larger one never fits. */\n readonly held?: number\n readonly closedByUnknownSpend?: true\n}\n\n/** State recovered from a prior process before new work is admitted. `committed` is measured spend\n * already present in the durable journal. Each `uncertainReservation` is a child that was recorded\n * as started but never recorded as settled: its full declared ceiling is charged conservatively,\n * while the public readout remains explicitly unknown. */\nexport interface BudgetPoolRestore {\n readonly committed?: Spend\n readonly uncertainReservations?: ReadonlyArray<Budget>\n}\n\nexport interface BudgetPool {\n /**\n * Atomically reserve a child's full ceiling from the free balance; fails closed\n * ({ ok: false }) when the pool can't cover standard or named channels.\n *\n * With `wait`, a request that could fit once open reservations return is admitted as a WAITING\n * ticket: `granted` resolves when reserved and rejects with `ReservationWaitRefused` once\n * nothing open could return enough. A waiting ticket reserves nothing; reconciling it withdraws\n * it. New waiting requests queue behind existing waiters, so asking order is grant order.\n */\n reserve(\n b: Budget,\n holder?: ReservationHolder,\n options?: ReserveOptions,\n ):\n | { ok: true; ticket: ReservationTicket; granted?: Promise<void> }\n | { ok: false; reason: ReservationRejection; shortfalls?: readonly ReservationShortfall[] }\n /** Name (or rename) who holds an open reservation, merging into what `reserve` recorded. A\n * settled or unknown ticket is ignored: attribution is leak EVIDENCE, never a lifecycle guard. */\n attribute(ticket: ReservationTicket, holder: ReservationHolder): void\n /**\n * Release a reservation: commit the actual `spent`, refund the remainder. Throws on an unknown\n * or already-reconciled ticket (a double refund would break conservation). Returns the\n * overspend, after committing it; throws, also after committing, when the spend cannot be\n * verified (unknown dollars under a cap, unknown or overflowing enforced-resource usage).\n */\n reconcile(ticket: ReservationTicket, spent: Spend): BudgetViolation | undefined\n /** Fold a normalized `UsageEvent` stream (or array) into a `Spend`; `ms` is left zero. */\n spendFrom(events: AsyncIterable<UsageEvent> | UsageEvent[]): Promise<Spend>\n /** The current readout, reflecting all outstanding reservations. */\n readout(): BudgetReadout\n /**\n * Record OBSERVED spend outside reserve/reconcile — the driver's OWN inference. A direct\n * `free → committed` debit preserving the invariant; `free` may go negative on overspend.\n * Unknown enforced resource usage is recorded before throwing; partial increments defer\n * completeness checks until the terminal spend. Unknown dollars under a cap are refused, unless\n * `alreadySpent` says the work finished with no caller left to refuse (that closes dollar\n * admission instead). The DURABLE record is the journal's `metered` event (`Scope.meter`).\n */\n observe(spend: Spend, options?: { partial?: boolean; alreadySpent?: boolean }): void\n /** Fail loud if any reservation is still open — the leak detector, called at the join barrier. */\n assertNoOpenTickets(): void\n /** Every reservation still open, with its holder; lets a failed run REPORT a leak. */\n openReservations(): ReadonlyArray<LeakedReservation>\n}\n\n/**\n * Create a conserved reservation pool from a root `Budget`. `runStartedAtMs` is the WALL-CLOCK\n * instant the root was recorded; the deadline is `runStartedAtMs + root.deadlineMs` (`0` when\n * none), an absolute instant. A resumed pool passes the ORIGINAL instant.\n */\nexport function createBudgetPool(\n root: Budget,\n runStartedAtMs: number,\n restore: BudgetPoolRestore = {},\n): BudgetPool {\n assertValidBudget(root, 'root budget')\n if (!Number.isFinite(runStartedAtMs) || runStartedAtMs < 0) {\n throw new Error('budget runStartedAtMs must be a non-negative finite number')\n }\n // free + reserved + committed ≡ root totals, per channel, always.\n const ledger = openBudgetLedger(root, runStartedAtMs)\n let nextTicketId = 0\n const open = new Map<number, ReservationHolder>()\n /** Tickets admitted to wait for budget, in the order they asked. Each is also in `open`. */\n const waiting: WaitingReservation[] = []\n /** Open tickets that hold nothing: waiting, or refused and not yet reconciled. */\n const holdingNothing = new Set<number>()\n\n /** Grant waiting tickets in the order they asked while the head fits. When the head does not\n * fit and no reservation is held that could return budget, nothing can ever cover it: refuse\n * it, and go on with the next. */\n function grantWaiting(): void {\n while (waiting.length > 0) {\n const head = waiting[0]!\n const shortfalls = ledgerShortfalls(ledger, head.budget, head.keep)\n if (shortfalls.length === 0) {\n waiting.shift()\n ledgerTake(ledger, head.budget)\n holdingNothing.delete(head.ticket.id)\n head.grant()\n continue\n }\n if (open.size > holdingNothing.size) return\n waiting.shift()\n head.refuse(new ReservationWaitRefused(shortfalls))\n }\n }\n\n /** Admit `b` to wait: it holds nothing until settlements return enough, in the order asked. */\n function admitToWait(\n b: Budget,\n holder: ReservationHolder,\n keep: ReservationFloor | undefined,\n ): { ok: true; ticket: ReservationTicket; granted: Promise<void> } {\n const id = nextTicketId++\n open.set(id, holder)\n const ticket = ticketFor(id, b)\n let grant!: () => void\n let refuse!: (error: ReservationWaitRefused) => void\n const granted = new Promise<void>((resolve, reject) => {\n grant = resolve\n refuse = reject\n })\n // A refusal the caller never reads (a withdrawn waiter) must not be an unhandled rejection.\n granted.catch(() => undefined)\n holdingNothing.add(id)\n waiting.push({ ticket, budget: b, keep, grant, refuse })\n return { ok: true, ticket, granted }\n }\n\n function reserve(\n b: Budget,\n holder: ReservationHolder = { stage: 'admitted' },\n options: ReserveOptions = {},\n ):\n | { ok: true; ticket: ReservationTicket; granted?: Promise<void> }\n | { ok: false; reason: ReservationRejection; shortfalls?: readonly ReservationShortfall[] } {\n assertValidBudget(b, 'reservation budget')\n assertResourceDeclarations(ledger, b)\n const wantUsd = b.maxUsd ?? 0\n const keep = options.keep\n // Fail-closed admission: every requested channel must fit the free balance. Every channel\n // that does not fit is reported, so a caller that shrinks one request is not refused again\n // on a second channel it was never told about.\n const shortfalls = ledgerShortfalls(ledger, b, keep)\n // A dollar request against a root with no dollar ceiling is unsatisfiable at ANY amount: budget\n // the root, don't retry smaller (a driver once walked its child budget down to $0.01, 68k\n // tokens). An exhausted channel above still takes precedence.\n if (shortfalls.length === 0 && wantUsd > 0 && !ledger.usdCapped) {\n return { ok: false, reason: 'usd-unbudgeted' }\n }\n const queueAhead = options.wait === true && waiting.length > 0\n if (shortfalls.length === 0 && !queueAhead) {\n ledgerTake(ledger, b)\n const id = nextTicketId++\n open.set(id, holder)\n return { ok: true, ticket: ticketFor(id, b) }\n }\n if (options.wait !== true || !fitsAfterRefunds(shortfalls)) {\n return { ok: false, reason: 'budget-exhausted', shortfalls }\n }\n return admitToWait(b, holder, keep)\n }\n\n function attribute(ticket: ReservationTicket, holder: ReservationHolder): void {\n const current = open.get(ticket.id)\n if (current === undefined) return\n open.set(ticket.id, { ...current, ...holder })\n }\n\n function reconcile(ticket: ReservationTicket, spent: Spend): BudgetViolation | undefined {\n if (!open.has(ticket.id)) {\n throw new Error(`budget pool: reconcile of unknown or already-settled ticket ${ticket.id}`)\n }\n assertValidSpend(spent, `budget pool ticket ${ticket.id} spend`)\n ledgerValidateUnits(ledger, spent)\n // A ticket still waiting, or refused while waiting, reserved nothing: it settles against a\n // zero reservation, and a waiting one leaves the queue.\n const heldNothing = holdingNothing.delete(ticket.id)\n if (heldNothing) {\n const index = waiting.findIndex((entry) => entry.ticket.id === ticket.id)\n if (index >= 0) waiting.splice(index, 1)\n }\n const held = heldNothing\n ? { tokens: 0, usd: 0, iterations: 0, resources: undefined }\n : ticket.reserved\n\n // Two outcomes are DECIDED here and reported at the END, after settlement: a throw before it\n // strands the ticket (`Scope.runChild` marks the child reconciled first, so nothing retries)\n // and `assertNoOpenTickets` fails the run. A FAULT (unverifiable spend) throws; an OVERSPEND\n // is returned, with `free` allowed negative (agent-runtime#1206). Unknown dollars are a fault\n // even beside an overspend.\n const usdBudgeted = ticket.reserved.usdBudgeted !== false\n const { overspent, unknownUnderCap } = ledgerClassifyOverspend(ledger, held, usdBudgeted, spent)\n let fault = unknownUnderCap\n ? `ticket ${ticket.id} reported unknown dollar cost under a dollar-capped budget`\n : undefined\n\n // Settlement: unconditional, and the only place the ticket closes.\n open.delete(ticket.id)\n const resourceSettlement = ledgerSettle(ledger, held, spent, unknownUnderCap)\n fault ??= resourceSettlement.fault\n overspent.push(...resourceSettlement.overspent)\n // The refund may cover waiting tickets, and a settlement that leaves nothing held ends the\n // wait of any ticket that cannot fit.\n grantWaiting()\n // Frozen: the same record reaches the journal, the settlement, and every observer.\n const violation =\n overspent.length === 0\n ? undefined\n : Object.freeze({\n overspent: Object.freeze(overspent.map((entry) => Object.freeze(entry))),\n })\n if (fault !== undefined) throw new BudgetReconcileFault(`budget pool: ${fault}`, violation)\n return violation\n }\n\n function observe(\n spend: Spend,\n options: { partial?: boolean; alreadySpent?: boolean } = {},\n ): void {\n assertValidSpend(spend, 'observed spend')\n ledgerValidateUnits(ledger, spend)\n // Unknown dollars under a cap are REFUSED before any balance mutates: an observation has no\n // ticket to strand, so the honest reading is a fail-loud `driver-failed`. Work already finished\n // with no caller left (a Runtime-owned analyst lens) closes dollar admission instead.\n const unknownUnderCap = ledger.usdCapped && spend.usdKnown === false\n if (unknownUnderCap && options.alreadySpent !== true) {\n // Typed so a driver retry can tell this contract failure from a recoverable accident.\n throw new ValidationError(\n 'budget pool: cannot observe unknown dollar cost under a dollar-capped budget',\n )\n }\n const settlement = ledgerObserve(ledger, spend, unknownUnderCap, !options.partial)\n const violation = settlement.fault ?? settlement.rootExceeded\n if (violation) throw new ValidationError(`budget pool: ${violation}`)\n }\n\n function readout(): BudgetReadout {\n return {\n ...(ledger.resources.size\n ? {\n resources: Object.fromEntries(\n [...ledger.resources].map(([name, value]) => [name, { ...value }]),\n ),\n }\n : {}),\n tokensLeft: ledger.freeTokens,\n tokensKnown: !ledger.tokensTainted,\n cacheBreakdownKnown: !ledger.cacheBreakdownTainted,\n usdLeft: ledger.usdCapped ? (ledger.usdTainted ? 0 : ledger.freeUsd) : 0,\n usdCapped: ledger.usdCapped,\n usdKnown: ledger.usdMeasured && !ledger.usdTainted,\n iterationsLeft: ledger.freeIterations,\n deadlineMs: ledger.absoluteDeadlineMs,\n reservedTokens: ledger.reservedTokens,\n }\n }\n\n function openReservations(): ReadonlyArray<LeakedReservation> {\n return [...open].map(([ticketId, holder]) => Object.freeze({ ticketId, ...holder }))\n }\n\n function assertNoOpenTickets(): void {\n if (open.size > 0) {\n throw new Error(\n `budget pool: ${open.size} reservation(s) still open at join barrier (${openReservations().map(describeLeakedReservation).join('; ')}) — conserved-pool invariant violated`,\n )\n }\n }\n\n ledgerRestore(ledger, root, restore)\n\n return {\n reserve,\n attribute,\n reconcile,\n spendFrom: foldUsage,\n readout,\n observe,\n assertNoOpenTickets,\n openReservations,\n }\n}\n\ninterface WaitingReservation {\n readonly ticket: ReservationTicket\n readonly budget: Budget\n readonly keep: ReservationFloor | undefined\n readonly grant: () => void\n readonly refuse: (error: ReservationWaitRefused) => void\n}\n\n/** A reservation must name a limit for exactly the resources the root declared, in its units. */\nfunction assertResourceDeclarations(ledger: BudgetLedger, b: Budget): void {\n for (const [name, state] of ledger.resources) {\n const wanted = b.resources?.[name]\n if (!wanted) throw new ValidationError(`resource ${name}: child must declare its limit`)\n if (wanted.unit !== state.unit) throw new ValidationError(`resource ${name}: unit mismatch`)\n }\n for (const name of Object.keys(b.resources ?? {})) {\n if (!ledger.resources.has(name))\n throw new ValidationError(`resource ${name}: root must declare its limit`)\n }\n}\n\n/** Whether every short channel would fit once the open reservations return what they hold. */\nfunction fitsAfterRefunds(shortfalls: readonly ReservationShortfall[]): boolean {\n return shortfalls.every(\n (shortfall) =>\n shortfall.closedByUnknownSpend !== true &&\n shortfall.requested <= shortfall.free + (shortfall.held ?? 0),\n )\n}\n\nfunction ticketFor(id: number, b: Budget): ReservationTicket {\n return {\n id,\n reserved: {\n ...(b.resources === undefined\n ? {}\n : {\n resources: Object.fromEntries(\n Object.entries(b.resources).map(([name, value]) => [name, { ...value }]),\n ),\n }),\n tokens: b.maxTokens,\n usd: b.maxUsd ?? 0,\n iterations: b.maxIterations,\n usdBudgeted: b.maxUsd !== undefined,\n },\n }\n}\n\n/** Name one leaked reservation by its holder. */\nfunction describeLeakedReservation(leak: LeakedReservation): string {\n const parts = [`ticket ${leak.ticketId}`]\n if (leak.childId !== undefined) parts.push(`child ${leak.childId}`)\n if (leak.label !== undefined) parts.push(`label ${leak.label}`)\n if (leak.assignment !== undefined) parts.push(`assignment ${leak.assignment}`)\n parts.push(`stage ${leak.stage}`)\n return parts.join(', ')\n}\n","/**\n * Redaction for values that may leave the Runtime process. The built-in\n * redactor is agent-eval's redaction core (`@tangle-network/agent-eval/traces`,\n * default profile): credentials found by field name or value shape are\n * replaced whole, email, card, SSN and phone values in place, and token counts\n * such as `inputTokens` or `max_tokens` are kept. A customer with\n * domain-specific PII supplies their own `redact` hook.\n *\n * This is narrower than `src/sanitize.ts`, which drops fields of the runtime's\n * *event envelope* unless the caller opts in: here the value is opaque customer\n * payload, so the scrub is value-shaped, not schema-shaped.\n *\n * @experimental\n */\n\nimport { REDACTION_VERSION, redact } from '@tangle-network/agent-eval/traces'\n\n/** A redactor maps an arbitrary trace value to a safe-to-export value. Pure;\n * must not throw on cyclic input (the default tolerates cycles). */\nexport type Redactor = (value: unknown) => unknown\n\n/**\n * The built-in redactor. Cycle-safe, depth-bounded and total: it never throws\n * on customer input and never mutates it.\n */\nexport function defaultRedactor(value: unknown): unknown {\n return redact(value).value\n}\n\n/** Stable identity input for saved work that depends on built-in redaction behavior. */\nexport function defaultRedactorIdentityMaterial(): unknown {\n return {\n core: '@tangle-network/agent-eval/traces redact',\n profile: 'default',\n version: REDACTION_VERSION,\n }\n}\n\n/**\n * Resolve the redactor a client uses. A caller-supplied hook handles\n * domain-specific values first, then the built-in scrubber still removes\n * credentials and personal data. Returning `false` is the explicit opt-out for\n * already-reviewed public values.\n */\nexport function resolveRedactor(redact: Redactor | false | undefined): Redactor {\n if (redact === false) return (value) => value\n if (!redact) return defaultRedactor\n return (value) => defaultRedactor(redact(value))\n}\n","import { defaultRedactor } from '../../redact'\n\nconst maxCauseDepth = 4\nconst maxMessageLength = 32_768\nconst maxPartLength = 2_048\n\n/** A persisted failure must explain its wrappers without exporting credentials or unbounded data. */\nexport function errorText(value: unknown): string {\n let text: string\n try {\n text = typeof value === 'string' ? value : (JSON.stringify(value) ?? String(value))\n } catch {\n text = '[unprintable rejection]'\n }\n return String(defaultRedactor(text)).slice(0, maxMessageLength)\n}\n\nexport function errorProperty(\n error: Error,\n field: 'name' | 'message' | 'stack',\n): string | undefined {\n try {\n const value = error[field]\n return value === undefined\n ? undefined\n : errorText(value).slice(0, field === 'name' ? 256 : maxMessageLength)\n } catch {\n return `[unreadable error ${field}]`\n }\n}\n\n/** An HTTP status carried on a thrown error, read without trusting its getter. Provider SDKs put\n * one on their own error classes, so this is how a refusal is recognised outside the transport\n * taxonomy — for the persisted message here, and for the driver's retry verdict. */\nexport function errorHttpStatus(error: Error): number | undefined {\n try {\n const status: unknown = Reflect.get(error, 'status')\n return typeof status === 'number' && Number.isInteger(status) && status >= 100 && status <= 599\n ? status\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** Shared by child settlements, driver attempts, and the final no-winner result. */\nexport function errMessage(error: unknown): string {\n const parts: string[] = []\n const seen = new Set<Error>()\n let current = error\n for (let depth = 0; depth <= maxCauseDepth; depth += 1) {\n try {\n if (!(current instanceof Error)) {\n parts.push(errorText(current).slice(0, maxPartLength))\n break\n }\n if (seen.has(current)) {\n parts.push('[circular]')\n break\n }\n seen.add(current)\n const status = errorHttpStatus(current)\n const message =\n (status === undefined ? '' : `HTTP ${status}: `) + (errorProperty(current, 'message') ?? '')\n parts.push(\n (depth === 0 ? message : `${errorProperty(current, 'name')}: ${message}`).slice(\n 0,\n maxPartLength,\n ),\n )\n current = current.cause\n if (current === undefined || current === null) break\n if (depth === maxCauseDepth) parts.push('[cause chain truncated]')\n } catch {\n parts.push('[unreadable error cause]')\n break\n }\n }\n return parts.join(': caused by ').slice(0, maxMessageLength)\n}\n\n/** The error and its causes (`cause`, and `errors` members), bounded and cycle-safe. */\nexport function causeChain(error: unknown): object[] {\n const chain: object[] = []\n const queue: unknown[] = [error]\n while (queue.length > 0 && chain.length < 12) {\n const value = queue.shift()\n if (typeof value !== 'object' || value === null || chain.includes(value)) continue\n chain.push(value)\n try {\n const errors: unknown = Reflect.get(value, 'errors')\n if (Array.isArray(errors)) queue.push(...errors)\n queue.push(Reflect.get(value, 'cause'))\n } catch {\n // A cause that cannot be read ends this branch of the walk.\n }\n }\n return chain\n}\n","import { causeChain } from './error-message'\n\n/**\n * The account owner refused an unsupported credential route before dispatch. This is the\n * provider SDK's machine contract, not an HTTP status, class-name guess, or prose match.\n */\nexport function isCredentialRefusal(error: unknown): boolean {\n if (!(error instanceof Error)) return false\n try {\n return Object.getOwnPropertyDescriptor(error, 'code')?.value === 'model_credential_refused'\n } catch {\n return false\n }\n}\n\n/**\n * The message prefix of agent-provider-tangle's generic credential command failure. The provider\n * exports no type or constant for it, so the kernel credential test raises it through the\n * provider's own command resolver and fails when the message drifts.\n */\nconst CREDENTIAL_COMMAND_FAILURE = 'Tangle credential command failed ('\n\n/**\n * The exit code of agent-provider-tangle's credential command (`acct sandbox resolve`) in the\n * error or its causes, or undefined.\n *\n * The provider reports the command's generic failure as `Tangle credential command failed\n * (exit N)` with the process's `exitCode` and `terminationSignal` as own fields; a refusal it can\n * parse (exit 75 or 78) arrives typed instead and is classified on its code. Before any dispatch\n * this failure ran nothing, and counting it as an unresolved pending invocation stopped 10 nodes\n * and lost 7 runs between 2026-10-12 and 2026-10-19 (test-acceptance-canary-20261015c met 26 in\n * 2.2 minutes). It pauses like a capacity refusal, bounded by the deadline, the budget and\n * cancellation as every pause is.\n */\nexport function credentialCommandExit(error: unknown): number | undefined {\n for (const link of causeChain(error)) {\n try {\n if (\n !(link instanceof Error) ||\n !link.message.startsWith(CREDENTIAL_COMMAND_FAILURE) ||\n !Object.hasOwn(link, 'terminationSignal')\n )\n continue\n const exitCode: unknown = Reflect.get(link, 'exitCode')\n if (typeof exitCode === 'number' && Number.isInteger(exitCode) && exitCode > 0)\n return exitCode\n } catch {\n // A cause whose fields cannot be read is not the credential command's failure.\n }\n }\n return undefined\n}\n","import { fnv1a32Hex } from './util'\n\n/**\n * Stable hash for the trace payload. Not cryptographic — only used so\n * downstream eval pipelines can group iterations whose task / output is the\n * same. Bare structural hash; non-JSON values stringify via their `toString`.\n */\nexport function hashJson(value: unknown): string {\n const str = jsonContentText(value)\n return fnv1a32Hex(str)\n}\n\n/** JSON text with String fallback, including quoted JSON strings and cyclic values. */\nexport function jsonContentText(value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n return str\n}\n","import { AgentTurnResultSchema } from '@tangle-network/agent-interface'\nimport { z } from 'zod'\nimport { jsonContentText } from '../json-content-hash'\nimport { fnv1a32Hex } from '../util'\nimport type { ExecutorResult } from './types'\n\nconst outcomeSchema = AgentTurnResultSchema.pick({ success: true, error: true })\n .extend({\n errorCode: AgentTurnResultSchema.shape.error,\n statusCode: z.number().int().min(400).max(599).optional(),\n })\n .strict()\n\n/** Why an executor's own envelope says the execution failed, with the provider's machine code\n * when it reported one. */\ninterface ExecutorFailure {\n readonly error: string\n readonly errorCode?: string\n readonly statusCode?: number\n}\n\n/** Read only the executor envelope; application output and grades are not execution status. */\nexport function executorFailure(\n result: Pick<ExecutorResult<unknown>, 'outcome'>,\n): ExecutorFailure | undefined {\n if (result.outcome === undefined) return undefined\n const outcome = outcomeSchema.parse(result.outcome)\n if (outcome.success) return undefined\n return {\n error: outcome.error ?? 'Agent execution failed',\n ...(outcome.errorCode === undefined ? {} : { errorCode: outcome.errorCode }),\n ...(outcome.statusCode === undefined ? {} : { statusCode: outcome.statusCode }),\n }\n}\n\n/** The failure text alone, for callers that record a settlement reason. */\nexport function executorFailureReason(\n result: Pick<ExecutorResult<unknown>, 'outcome'>,\n): string | undefined {\n return executorFailure(result)?.error\n}\n\n/**\n * The platform's own failure vocabulary: machine codes and lifecycle messages that the sandbox\n * runtime, the router, or the egress path put in an executor envelope when the platform, not\n * the agent's work, ended the execution. Each entry names its evidence: the count is how many\n * down children carried it on the 2026-09-20 fleet corpus (277 down settlements across 691\n * runs), every one of them stamped `infra: false` by the hard-coded call site this table\n * replaced. The table is deliberately the platform's fixed strings, not the agent's prose.\n */\nexport const PLATFORM_FAILURE_CODES: ReadonlySet<string> = new Set(\n [\n 'QUOTA_EXCEEDED', // the Sandbox interactive status failed (HTTP 429; code QUOTA_EXCEEDED): 3\n 'provider_quota_exceeded', // No provider served model \"kimi-k2\" (provider_quota_exceeded): 7\n 'provider_quota_exhausted', // the router's current code for the same refusal\n 'buffer.overflow', // agent-container#7730: the 10,000-event buffer dropped the stream\n 'TIMEOUT',\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'EPIPE',\n 'EADDRINUSE', // listen EADDRINUSE: address already in use: 2\n ].map((code) => code.toLowerCase()),\n)\n\nconst PLATFORM_FAILURE_MESSAGES: ReadonlyArray<RegExp> = [\n /^terminated$/u, // the box was terminated under the execution: 25\n /Execution exceeded its time limit/u, // the platform's execution TTL: 4\n /Execution interrupted: the agent runtime restarted/u, // buffer.overflow misreported: 3\n /Platform key[- ]verification/u, // key-verification brownout: 9\n /Platform key delegation failed/u,\n /Bad Gateway/iu, // egress proxy header timeout, router 502: 4\n /Cannot connect to API/u, // egress proxy killed by downloads: 3\n /Failed to connect to Sandbox API/u, // the driver lost its box environment (discovery-lab#888)\n /fetch failed/u,\n /A sandbox lifecycle operation is already in progress/u, // 2\n /exceeded its string bound/u, // Tangle Sandbox event data exceeded its string bound: 4\n /exceeds its JSON bound/u, // 3\n /No provider served model/u, // router capacity: 7\n /Invalid API key/u, // the sandbox model key expired mid-turn: 2\n /provider_quota_exceeded|provider_quota_exhausted|QUOTA_EXCEEDED|rate limit/iu,\n /is at its box cap/u, // seat capacity: 4\n /could not materialize the seat credential/u, // 3\n /OpenCode exited while a model step was still in progress/u, // tmpfs OOM, SIGKILL: 4\n /the agent runtime restarted/u,\n]\n\n/**\n * Whether an executor envelope's failure was the platform's, as far as the envelope can say.\n *\n * `true` when the code or the message is in the platform's own vocabulary above. `undefined`\n * otherwise: the harness reported a failure and nothing in the envelope attributes it, so the\n * settlement carries no `infra` claim at all rather than a false one. This path never answers\n * `false`, because an executor envelope cannot prove the agent's work was at fault; the throw\n * path in `scope.ts` still answers `false` for an ordinary thrown result, where the runtime does\n * know. Until this function existed both envelope sites stamped `infra: false` unconditionally,\n * and the flag caught 1 of the 78 platform losses it was checked against on the fleet corpus.\n */\nexport function executorFailureInfra(failure: ExecutorFailure): true | undefined {\n const code = failure.errorCode?.toLowerCase()\n if (code !== undefined && PLATFORM_FAILURE_CODES.has(code)) return true\n return PLATFORM_FAILURE_MESSAGES.some((pattern) => pattern.test(failure.error)) ? true : undefined\n}\n\n/** Preserve deterministic result pointers across built-in executors and replay.\n * FNV-1a is an identity convention here, not a cryptographic integrity check. */\nexport function contentRef(prefix: string, value: unknown): string {\n const str = jsonContentText(value)\n return `${prefix}:${fnv1a32Hex(str)}`\n}\n","import { createHash } from 'node:crypto'\n\n/** Stable content address shared by result and trace artifacts. */\nexport function contentAddress(artifact: unknown): string {\n const hex = createHash('sha256').update(stableStringify(artifact), 'utf-8').digest('hex')\n return `sha256:${hex}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n","import { ValidationError } from '../../errors'\n\n/** Deeply detach and freeze untrusted data at a runtime decision boundary. The clone prevents the\n * caller from mutating it later; the freeze prevents downstream code from mutating the snapshot.\n * Strings are immutable, so the snapshot shares the caller's strings instead of copying them. */\nexport function detachedSnapshot<T>(value: T, context: string): T {\n let clone: T\n try {\n clone = structuredClone(value)\n } catch (error) {\n throw new ValidationError(`${context}: input must be structured-cloneable`, { cause: error })\n }\n return deepFreeze(shareSourceStrings(value, clone))\n}\n\n/** Detach a value from its caller and freeze it, without the `ValidationError` framing\n * {@link detachedSnapshot} adds. For a boundary that has already validated its input. */\nexport function detachedFrozen<T>(value: T): T {\n return deepFreeze(shareSourceStrings(value, structuredClone(value)))\n}\n\n/**\n * Point each string in a fresh structured clone at the equal string in its source.\n *\n * `structuredClone` copies every string, and a copied string buys no isolation: only objects and\n * arrays can change through a shared reference. A spawned profile passes several boundaries, and\n * each one kept its own copy: in a reproduction of Discovery's hosted coordinator, a child profile\n * that mounts a 5.3 MB file packet was held four times per spawned child. A scope keeps every\n * child it spawned, so the heap grew about 22 MB per spawn, and hosted coordinators died with V8\n * heap OOM after 37 spawns.\n *\n * The walk pairs only own data properties of plain objects and arrays. Accessors, Maps, Sets and\n * other cloned types keep the clone's values. A string is replaced only by a string equal to it,\n * so the snapshot holds exactly the clone's value. The snapshot keeps the source's strings alive.\n */\nfunction shareSourceStrings<T>(source: unknown, clone: T): T {\n const visited = new Set<object>()\n const visit = (from: unknown, to: unknown): void => {\n if (from === null || to === null || typeof from !== 'object' || typeof to !== 'object') return\n const array = Array.isArray(to)\n if (array !== Array.isArray(from)) return\n if (!array && Object.getPrototypeOf(to) !== Object.prototype) return\n if (visited.has(to)) return\n visited.add(to)\n const target = to as Record<string, unknown>\n for (const key of Object.keys(target)) {\n const own = Object.getOwnPropertyDescriptor(from, key)\n if (own === undefined || !('value' in own)) continue\n const cloned = target[key]\n if (typeof cloned === 'string') {\n if (own.value === cloned) target[key] = own.value\n } else visit(own.value, cloned)\n }\n }\n visit(source, clone)\n return clone\n}\n\n/**\n * Replace each string in a freshly parsed JSON value with an equal string already in `pool`, and\n * add the new ones. One recovery pass parses every interrupted child's profile from its own blob,\n * so children that carry the same file packet would otherwise hold one copy each. The value is\n * updated in place, so it must belong to the caller; frozen objects are left as they are.\n */\nexport function shareParsedStrings<T>(value: T, pool: Map<string, string>): T {\n const visit = (node: unknown): void => {\n if (node === null || typeof node !== 'object' || Object.isFrozen(node)) return\n if (!Array.isArray(node) && Object.getPrototypeOf(node) !== Object.prototype) return\n const target = node as Record<string, unknown>\n for (const key of Object.keys(target)) {\n const item = target[key]\n if (typeof item !== 'string') {\n visit(item)\n continue\n }\n const shared = pool.get(item)\n if (shared === undefined) pool.set(item, item)\n else target[key] = shared\n }\n }\n visit(value)\n return value\n}\n\nfunction deepFreeze<T>(value: T, seen = new Set<object>()): T {\n // `Object.freeze` throws `TypeError: Cannot freeze array buffer views with elements` on any\n // non-empty TypedArray or Buffer, so binary inside a payload must be handed back untouched\n // rather than frozen. Its bytes are already detached by the `structuredClone` above.\n if (value === null || typeof value !== 'object' || ArrayBuffer.isView(value) || seen.has(value)) {\n return value\n }\n seen.add(value)\n for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child, seen)\n return Object.freeze(value)\n}\n","/**\n * Trace roots: one Merkle root over the events a turn archived, so a single event can be proven\n * against the hash its journal record carries without reading the rest of the archive.\n *\n * The leaves are the archived events in stored order, each hashed with its own random salt, then\n * one summary leaf that counts the events and the tool calls among them. The artifact keeps every\n * leaf and salt and is stored under its content address in the run's result blob store, beside\n * the archive it commits to. A verifier recomputes leaf `i` from `events[i]` of the `outRef` blob\n * and `salts[i]`, checks it against `leaves[i]`, and checks `merkleRoot(leaves)` against the root\n * the journal recorded. Leaf identity is `(outRef, index)`: an event's own `id` is a session\n * buffer offset and is absent on terminal events.\n *\n * One event array has one root per node. A result always gets its own. Evidence whose events the\n * node already rooted gets none: a retained owner's deferred workspace capture stores the turn it\n * just committed again, with the workspace fields added, under another `outRef`. A second root\n * over the same events would give one turn two count candidates and two run-root leaves.\n *\n * Salts are random, so a trace root can never be recomputed from the archive alone. Recovery and\n * replay copy the recorded receipt; they never derive a new one.\n */\nimport { createHash } from 'node:crypto'\nimport {\n canonicalString,\n jsonDocument,\n LedgerCanonicalizationError,\n type LedgerHash,\n merkleLeafHash,\n merkleRoot,\n merkleSalt,\n} from '@tangle-network/agent-eval/ledger-core'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { contentAddress } from '../../durable/content-address'\nimport { createSandboxToolPartState, mapSandboxToolEvent } from '../sandbox-executor-output'\n\nimport type { ResultBlobStore, TraceRootReceipt } from './types'\n\n/** Schema identifier of a stored {@link TraceRootArtifact}. */\nexport const TRACE_ROOT_SCHEMA = 'agent-runtime.trace-root.v1'\n/** Schema identifier of the {@link TraceSummary} carried by a trace root's last leaf. */\nexport const TRACE_SUMMARY_SCHEMA = 'agent-runtime.trace-summary.v1'\n\n/** The last leaf of a trace root: how many events the archive holds and the tool calls among them,\n * one per distinct call id, by tool name. An absence or count claim is checked against it. */\nexport interface TraceSummary {\n readonly schema: typeof TRACE_SUMMARY_SCHEMA\n readonly events: number\n readonly toolCalls: Readonly<Record<string, number>>\n}\n\n/** The stored trace-root artifact. `leaves[i]` and `salts[i]` belong to `events[i]` of the\n * `outRef` blob for `i < summary.events`; the final entry belongs to `summary`. */\nexport interface TraceRootArtifact {\n readonly schema: typeof TRACE_ROOT_SCHEMA\n readonly nodeId: string\n readonly outRef: string\n readonly root: string\n readonly leafCount: number\n readonly salts: readonly string[]\n readonly leaves: readonly string[]\n readonly summary: TraceSummary\n}\n\n/** @internal One trace root per archived output of one node, however many records cite it. */\nexport interface TraceRootWriter {\n /** Store the trace root of the result `out` stored under `outRef`; `undefined` when it archived\n * no events. */\n write(outRef: string, out: unknown): Promise<TraceRootReceipt | undefined>\n /** As `write`, for evidence: also `undefined` when this node already rooted the same events\n * under another output. */\n writeEvidence(outRef: string, out: unknown): Promise<TraceRootReceipt | undefined>\n /** The receipt an earlier write produced for `outRef`, if any. */\n recorded(outRef: string | undefined): Promise<TraceRootReceipt | undefined>\n}\n\n/** @internal */\nexport function traceRootWriter(blobs: ResultBlobStore, nodeId: string): TraceRootWriter {\n const roots = new Map<string, Promise<TraceRootReceipt | undefined>>()\n /** Digests of the event arrays this node holds a stored root for. */\n const rooted = new Set<string>()\n const persist = async (\n outRef: string,\n out: unknown,\n evidence: boolean,\n ): Promise<TraceRootReceipt | undefined> => {\n const events = archivedEvents(out)\n if (events === undefined) return undefined\n if (evidence) {\n // A root still being written counts once it is stored.\n await Promise.allSettled([...roots.values()])\n if (rooted.has(await eventsDigest(events))) return undefined\n }\n const stored = await persistTraceRoot(blobs, nodeId, outRef, events)\n if (stored === undefined) return undefined\n rooted.add(stored.digest)\n return stored.receipt\n }\n const memoized = (outRef: string, out: unknown, evidence: boolean) => {\n const known = roots.get(outRef)\n if (known !== undefined) return known\n const pending = persist(outRef, out, evidence)\n roots.set(outRef, pending)\n // A failed write is retried by the next writer rather than remembered.\n pending.catch(() => roots.delete(outRef))\n return pending\n }\n return {\n write: (outRef, out) => memoized(outRef, out, false),\n writeEvidence: (outRef, out) => memoized(outRef, out, true),\n async recorded(outRef) {\n if (outRef === undefined) return undefined\n return roots.get(outRef)?.catch(() => undefined)\n },\n }\n}\n\nasync function persistTraceRoot(\n blobs: ResultBlobStore,\n nodeId: string,\n outRef: string,\n events: readonly unknown[],\n): Promise<{ receipt: TraceRootReceipt; digest: string } | undefined> {\n let built: { artifact: TraceRootArtifact; digest: string }\n try {\n built = await traceRootArtifact(nodeId, outRef, events)\n } catch (error) {\n // An event with no canonical JSON form (an unpaired surrogate) leaves the output unproven;\n // it never fails the turn that produced it. 0 of 366 archives.\n if (error instanceof LedgerCanonicalizationError) return undefined\n throw error\n }\n const { artifact, digest } = built\n // The content address and the store's own encoding each walk the whole artifact (9.2 MB for\n // the largest turn); each takes its own turn of the event loop.\n await nextTurn()\n const ref = contentAddress(artifact)\n await nextTurn()\n await blobs.put(ref, artifact)\n return { receipt: { root: artifact.root, ref, leafCount: artifact.leafCount }, digest }\n}\n\nfunction archivedEvents(out: unknown): readonly unknown[] | undefined {\n if (out === null || typeof out !== 'object' || Array.isArray(out)) return undefined\n const events = (out as { events?: unknown }).events\n return Array.isArray(events) ? events : undefined\n}\n\n/** The longest stretch of hashing between yields to the event loop. Hashing runs about 40 µs per\n * event, and the largest archived turn holds 65,276 events: unbroken, that blocked the process\n * for 2.7 s while sibling turns, coordination calls and heartbeats waited. A slice is measured\n * in time, not events, because one event can be megabytes. */\nconst SLICE_MS = 10\n\n/** Yields to the event loop once a slice has run `SLICE_MS`; `undefined` while it has not. */\nfunction slicer(): () => Promise<void> | undefined {\n let started = performance.now()\n return () => {\n if (performance.now() - started < SLICE_MS) return undefined\n return nextTurn().then(() => {\n started = performance.now()\n })\n }\n}\n\nfunction nextTurn(): Promise<void> {\n return new Promise<void>((resolve) => setImmediate(resolve))\n}\n\n/** The identity of an event array as stored: the digest of each event's stored JSON, in order.\n * Two arrays with one digest have the same leaves' content. */\nasync function eventsDigest(events: readonly unknown[]): Promise<string> {\n const hash = createHash('sha256')\n const slice = slicer()\n for (const event of events) {\n const yielded = slice()\n if (yielded !== undefined) await yielded\n hash.update(storedText(event)).update('\\n')\n }\n return hash.digest('hex')\n}\n\nasync function traceRootArtifact(\n nodeId: string,\n outRef: string,\n archived: readonly unknown[],\n): Promise<{ artifact: TraceRootArtifact; digest: string }> {\n const salts: string[] = []\n const leaves: LedgerHash[] = []\n const tree = merkleTree()\n const identity = createHash('sha256')\n const tools = createSandboxToolPartState()\n const toolCalls = new Map<string, number>()\n const slice = slicer()\n for (const event of archived) {\n const yielded = slice()\n if (yielded !== undefined) await yielded\n // Hash the event as the blob store keeps it: a JSON document, read back the way a verifier\n // reads `events[i]`. The writer's copy is a structured clone and can hold values JSON drops.\n const text = storedText(event)\n identity.update(text).update('\\n')\n const stored: unknown = JSON.parse(text)\n const salt = merkleSalt()\n const leaf = merkleLeafHash(canonicalString(jsonDocument(stored)), salt)\n salts.push(salt)\n leaves.push(leaf)\n tree.push(leaf)\n for (const projected of mapSandboxToolEvent(stored as SandboxEvent, tools)) {\n if (projected.type !== 'tool_call') continue\n toolCalls.set(projected.toolName, (toolCalls.get(projected.toolName) ?? 0) + 1)\n }\n }\n const summary: TraceSummary = {\n schema: TRACE_SUMMARY_SCHEMA,\n events: archived.length,\n toolCalls: Object.fromEntries(toolCalls),\n }\n const salt = merkleSalt()\n const leaf = merkleLeafHash(canonicalString(summary), salt)\n salts.push(salt)\n leaves.push(leaf)\n tree.push(leaf)\n return {\n artifact: {\n schema: TRACE_ROOT_SCHEMA,\n nodeId,\n outRef,\n root: tree.root(),\n leafCount: leaves.length,\n salts,\n leaves,\n summary,\n },\n digest: identity.digest('hex'),\n }\n}\n\n/**\n * `merkleRoot(leaves)` built as the leaves arrive, so its interior hashes run inside the sliced\n * leaf loop instead of in one block after it (0.4 s for 65,277 leaves). It keeps the perfect\n * subtrees of RFC 9162, largest first, and joins two with ledger-core's own interior hash,\n * `merkleRoot([left, right])`; the root folds them from the right, as RFC 9162 splits at the\n * largest power of two.\n */\nfunction merkleTree(): { push(leaf: LedgerHash): void; root(): LedgerHash } {\n const peaks: { hash: LedgerHash; size: number }[] = []\n return {\n push(leaf) {\n let hash = leaf\n let size = 1\n while (peaks.at(-1)?.size === size) {\n hash = merkleRoot([peaks.pop()!.hash, hash])\n size *= 2\n }\n peaks.push({ hash, size })\n },\n root() {\n let root = peaks.at(-1)!.hash\n for (let index = peaks.length - 2; index >= 0; index -= 1) {\n root = merkleRoot([peaks[index]!.hash, root])\n }\n return root\n },\n }\n}\n\n/** One array item as `JSON.stringify` writes it: `JSON.parse` of it is what `events[i]` holds. */\nfunction storedText(event: unknown): string {\n return JSON.stringify(event) ?? 'null'\n}\n","/**\n * An upstream that cannot serve NOW: how Runtime recognizes one, and how long an agent waits for it.\n *\n * A model provider's exhausted quota, a rate limit, an overload, or the router's own refused\n * credential is not a fault in the agent: the same request succeeds when capacity returns. A\n * driver that meets one re-enters after a pause (`runDriverWithRetry`), and a leaf continues in\n * its environment after the same pause (`providerAsExecutor`). Both read the refusal and the pause\n * from here, so an outage costs a director and its workers the same number of turns.\n *\n * This module imports nothing, so the provider executor can read it without the error classes of\n * `../../errors`.\n */\n\n/**\n * Machine codes that say the upstream cannot serve now rather than that the request is wrong.\n * Each is a code an upstream publishes, not prose: the router's\n * (`lib/model-substitution.ts`, `lib/upstream-error-triage.ts`) and the OpenAI- and Anthropic-shaped\n * error types a relayed body carries.\n */\nexport const UNAVAILABLE_CODES: ReadonlySet<string> = new Set([\n 'provider_quota_exhausted', // router: the upstream account has no remaining quota (429)\n 'provider_quota_exceeded', // router: the earlier spelling, on the 2026-09-20 fleet corpus\n 'provider_rate_limit', // router: the upstream is rate limiting this model (429)\n 'upstream_unavailable', // router: upstream outage or an unexplained upstream refusal (503)\n // Router: its OWN credential for the provider was refused, answered 503. An operator restores\n // it, and the agent can only wait. The caller's key refused is `invalid_api_key` at 401 and\n // stays terminal. Measured 2026-09-24 from 14:15Z: every flash request ended\n // `No provider served model \"deepseek/deepseek-v4.1-flash\" (provider_key_invalid)`.\n 'provider_key_invalid',\n 'rate_limit_exceeded', // OpenAI-shaped 429\n 'rate_limit_error', // Anthropic-shaped 429\n 'overloaded_error', // Anthropic-shaped 529\n])\n\n/** 429 Too Many Requests, 503 Service Unavailable, and 529, which Anthropic uses for overload. */\nexport const UNAVAILABLE_STATUSES: ReadonlySet<number> = new Set([429, 503, 529])\n\n/**\n * A harness that flattens the router's JSON body into its own failure text leaves the router's\n * code in that text: `opencode execution failed: No provider served model \"...\"\n * (provider_quota_exhausted)`. The code is matched as a whole token, and a status only in the\n * `status code <n>` framing a harness prints, so prose that merely mentions a quota does not match.\n */\nexport function unavailableSignalInText(text: string): string | undefined {\n for (const token of text.toLowerCase().matchAll(/[a-z_]+/gu)) {\n if (UNAVAILABLE_CODES.has(token[0])) return token[0]\n }\n const status = text.match(/\\bstatus code (\\d{3})\\b/u)?.[1]\n return status !== undefined && UNAVAILABLE_STATUSES.has(Number(status))\n ? `http-${status}`\n : undefined\n}\n\n/**\n * The code or status that marks a failed turn outcome as an upstream capacity refusal, or\n * `undefined`. The outcome's own `errorCode` decides first; the failure text is read only when no\n * code or numeric status decided, because a harness CLI can report the router's refusal as text.\n */\nexport function unavailableSignalOfFailure(failure: {\n readonly error: string\n readonly errorCode?: string\n readonly statusCode?: number\n}): string | undefined {\n const code = failure.errorCode?.toLowerCase()\n if (code !== undefined && UNAVAILABLE_CODES.has(code)) return code\n if (failure.statusCode !== undefined) {\n return UNAVAILABLE_STATUSES.has(failure.statusCode) ? `http-${failure.statusCode}` : undefined\n }\n return unavailableSignalInText(failure.error)\n}\n\nconst DEFAULT_UNAVAILABLE_PAUSE_MS = 15_000\nconst DEFAULT_MAX_UNAVAILABLE_PAUSE_MS = 300_000\n\n/** How long an agent waits after its upstream refused a turn for capacity: the codes and\n * statuses `upstreamUnavailableSignal` reads. A pause is not a failure: a driver spends neither\n * `maxAttempts` nor `maxConsecutiveFailures` on it. */\nexport interface UnavailablePausePolicy {\n /** The first pause, doubling per consecutive refusal. Default 15000ms. */\n readonly unavailablePauseMs?: number\n /** Ceiling on the doubling. Default 300000ms, so a long outage costs at most twelve turns an\n * hour. */\n readonly maxUnavailablePauseMs?: number\n}\n\n/**\n * The pause after the `consecutive`-th refusal in a row (1-based): the first pause, doubled per\n * earlier refusal, up to the ceiling. The one rule for a driver that re-enters and a leaf that\n * continues in its environment, so an outage costs both the same number of turns.\n */\nexport function unavailablePauseMs(\n consecutive: number,\n policy: UnavailablePausePolicy = {},\n): number {\n return cappedDoublingMs(\n consecutive,\n policy.unavailablePauseMs ?? DEFAULT_UNAVAILABLE_PAUSE_MS,\n policy.maxUnavailablePauseMs ?? DEFAULT_MAX_UNAVAILABLE_PAUSE_MS,\n )\n}\n\n/** `first` doubled per earlier consecutive wait (`consecutive` is 1-based), up to `ceiling`. */\nexport function cappedDoublingMs(consecutive: number, first: number, ceiling: number): number {\n const start = Math.max(0, first)\n return Math.min(Math.max(start, ceiling), start * 2 ** Math.max(0, consecutive - 1))\n}\n\n/** The longest hold a refusal's own reset time may ask for: a 5-hour plan window plus a margin. */\nconst MAX_RESET_HOLD_MS = 6 * 60 * 60_000\n\n/** How often a refusal whose reset is beyond {@link MAX_RESET_HOLD_MS} is probed again. */\nconst FAR_RESET_PROBE_MS = 60 * 60_000\n\n/**\n * When a refusal says its quota resets, as epoch ms, or `undefined` when it names no usable time.\n * The Z.ai Coding Plan's opencode refusal names one in Beijing time with no zone:\n * `Usage limit reached for 5 hour. Your limit will reset at 2026-10-18 15:17:33`. On Discovery run\n * magnetar-rust-20261018b, 219 of 324 driver attempts ended on it between 06:04Z and 22:18Z, and\n * the last refusal came at 22:18Z against `reset at 2026-10-19 06:18:14`, which is 22:18:14Z at\n * +08:00. A time with its own zone is read as written. A time in the past is no reset time: the\n * caller keeps its doubling pause. A time more than MAX_RESET_HOLD_MS ahead is held for only\n * FAR_RESET_PROBE_MS at a time, so a misread zone cannot hold a seat for a day, yet the spent seat\n * is not asked again every 5 minutes: on magnetar-rust-20261019c a reset beyond 6 h drew about 12\n * attempts an hour against the refusing seat.\n */\nexport function unavailableResumeAt(text: string, nowMs: number): number | undefined {\n const match = text.match(\n /\\breset at (\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(?:\\.\\d+)?(Z|[+-]\\d{2}:?\\d{2})?/u,\n )\n if (match === null) return undefined\n const zone = match[3] ?? (/Usage limit reached for \\d+ hour/u.test(text) ? '+08:00' : undefined)\n if (zone === undefined) return undefined\n const at = Date.parse(\n `${match[1]}T${match[2]}${zone.length === 5 ? `${zone.slice(0, 3)}:${zone.slice(3)}` : zone}`,\n )\n if (!Number.isFinite(at) || at <= nowMs) return undefined\n return at - nowMs > MAX_RESET_HOLD_MS ? nowMs + FAR_RESET_PROBE_MS : at\n}\n\n/**\n * Spread a wait over `[ms / 2, ms]`. Every driver a Platform restart cut off fails within the same\n * seconds; without jitter their doubling schedules stay aligned and they all re-enter together\n * when the service returns. `random` returns a value in `[0, 1)`; 0 keeps the full wait.\n */\nexport function jitteredMs(ms: number, random: () => number): number {\n return ms - Math.floor((ms / 2) * Math.min(1, Math.max(0, random())))\n}\n","import type { AgentProfile, WorkspaceCheckpointRef } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport type {\n RetainedRunAdmission,\n RetainedRunAdmissionHook,\n RetainedRunEnvironmentAdmission,\n} from '../retained-run-types'\nimport { isCredentialRefusal } from './credential-refusal'\nimport { detachedSnapshot } from './snapshot'\nimport { type TraceRootWriter, traceRootWriter } from './trace-root'\nimport type {\n AgentSpec,\n ExecutorContext,\n ExecutorFactory,\n ExecutorResult,\n NodeId,\n ProfileMaterializationReceipt,\n ResultBlobStore,\n SpawnEvent,\n SpawnJournal,\n Spend,\n WorkspaceCheckpointMarker,\n} from './types'\nimport { UNAVAILABLE_CODES } from './upstream-unavailable'\n\n/** Scope owns the durable writer; provider executors only publish sanitized admissions. */\nexport const retainedExecutorSeamKey = 'runtime.retainedExecutor'\n\nexport interface RetainedExecutorContext {\n /** Stable across recovery; distinct for deliberate later invocations of one owner. */\n readonly executionId?: string\n /** Prior committed environment admission to reuse for a deliberate later invocation. */\n readonly priorSession?: RetainedRunEnvironmentAdmission\n /** Reuse only `priorSession`'s environment and start a new harness session in it, under the\n * identity minted from this invocation's own keys (`continuation.session: 'fresh'`). */\n readonly newSession?: boolean\n /** Cumulative committed spend before this invocation; restored without summing prior totals. */\n readonly priorSpent?: Spend\n /** Keep the retained provider environment alive across deliberate invocations. */\n readonly preserveEnvironment?: boolean\n /**\n * Asked once when a turn settles with a result: `true` keeps the environment for a keyed\n * continuation instead of destroying it (`Executor.heldForContinuation`). The scope answers\n * `true` for a keyed leaf whose turn ended over its budget or past its deadline.\n */\n readonly holdOnSettle?: (spent: Spend) => boolean\n readonly admissions: readonly RetainedRunAdmission[]\n readonly onReady?: () => void | Promise<void>\n readonly onAdmission: RetainedRunAdmissionHook\n readonly onResult: (result: ExecutorResult<unknown>) => Promise<void>\n /** Retain failure evidence without accepting a result or changing recovery state. */\n readonly onEvidence?: (out: unknown) => Promise<void>\n /**\n * Start this node's next invocation in the environment and session its last one ran in, once\n * that one committed its result. The scope journals `task` as the node's next\n * `execution-input` and answers with the context the new invocation runs under. A Scope leaf\n * has it; an owner's later invocations are its driver's re-entries, so an owner does not.\n */\n readonly continueInvocation?: (task: unknown) => Promise<RetainedExecutorContext>\n /** Journal a pause of this node on an unavailable upstream: infrastructure time. */\n readonly onPause?: (pause: RetainedExecutorPause) => Promise<void>\n /**\n * Take over the end-of-turn workspace capture of a turn whose manager stopped, which the\n * executor runs after it has committed the turn's result. An owner whose environment outlives\n * its turns has it: the owner awaits the work before its next invocation starts and before it\n * releases the environment, so the capture still precedes the destroy. Its receipt arrives\n * through `onEvidence`. Never rejects.\n */\n readonly onEndOfTurnWork?: (work: Promise<void>) => void\n /** Journal where one workspace capture's time went: queue wait, capture time, archive bytes. */\n readonly onWorkspaceCapture?: (capture: RetainedWorkspaceCapture) => Promise<void>\n /** Journal that an end-of-turn workspace capture was requested, before it waits for anything.\n * An owner also cuts its checkpoint rotation's captures short here, so they never hold the\n * final capture up. */\n readonly onWorkspaceCaptureStarted?: (capture: RetainedWorkspaceCaptureStarted) => Promise<void>\n /** The checkpoint a NEW environment of this invocation starts from: set only when the provider\n * lost the environment the previous invocation ran in, and it holds a checkpoint of it. */\n readonly restoreWorkspace?: RetainedWorkspaceRestore\n /** Receives what a restored environment held of the checkpoint's marker, before any turn is\n * judged by it. */\n readonly onWorkspaceRestored?: (receipt: RetainedWorkspaceRestoreReceipt) => Promise<void>\n}\n\n/** @internal A capture may finish after cancellation; its durable citation remains appendable. */\nexport function executorEvidenceWriter(args: {\n journal: SpawnJournal\n blobs: ResultBlobStore\n rootId: string\n nodeId: string\n nextSequence: () => number\n now: () => number\n /** The node's trace-root writer: evidence whose events its result already rooted gets none. */\n traceRoots?: TraceRootWriter\n}): (out: unknown) => Promise<void> {\n const traceRoots = args.traceRoots ?? traceRootWriter(args.blobs, args.nodeId)\n return async (out) => {\n const snapshot = detachedSnapshot(out, 'executor evidence')\n const outRef = contentAddress(snapshot)\n await args.blobs.put(outRef, snapshot)\n const traceRoot = await traceRoots.writeEvidence(outRef, snapshot)\n await args.journal.appendEvent(args.rootId, {\n kind: 'execution-evidence',\n id: args.nodeId,\n outRef,\n ...(traceRoot === undefined ? {} : { traceRoot }),\n seq: args.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n }\n}\n\n/** A checkpoint to create the next environment from, with the marker it must hold. */\nexport interface RetainedWorkspaceRestore {\n readonly checkpoint: WorkspaceCheckpointRef\n readonly marker?: WorkspaceCheckpointMarker\n}\n\n/** What a restored environment was found to hold. */\nexport interface RetainedWorkspaceRestoreReceipt {\n readonly environmentId: string\n readonly checkpoint: WorkspaceCheckpointRef\n /** True only when the environment held the checkpoint's marker with its exact content. */\n readonly verified: boolean\n readonly detail?: string\n}\n\n/** What a `paused` spawn event records, less the fields the scope supplies. */\nexport type RetainedExecutorPause = Omit<\n Extract<SpawnEvent, { kind: 'paused' }>,\n 'kind' | 'id' | 'seq' | 'at'\n>\n\n/** What a `workspace-capture` spawn event records, less the fields the scope supplies. */\nexport type RetainedWorkspaceCapture = Omit<\n Extract<SpawnEvent, { kind: 'workspace-capture' }>,\n 'kind' | 'id' | 'seq' | 'at'\n>\n\n/** What a `workspace-capture-started` spawn event records, less the fields the scope supplies. */\nexport type RetainedWorkspaceCaptureStarted = Omit<\n Extract<SpawnEvent, { kind: 'workspace-capture-started' }>,\n 'kind' | 'id' | 'seq' | 'at'\n>\n\n/** @internal The journal writers for `onWorkspaceCapture` and `onWorkspaceCaptureStarted`;\n * `nextSequence` is the node's own. */\nexport function workspaceCaptureWriter(args: {\n journal: SpawnJournal\n rootId: string\n nodeId: string\n nextSequence: () => number\n now: () => number\n}): {\n readonly onWorkspaceCapture: (capture: RetainedWorkspaceCapture) => Promise<void>\n readonly onWorkspaceCaptureStarted: (capture: RetainedWorkspaceCaptureStarted) => Promise<void>\n} {\n return {\n onWorkspaceCapture: async (capture) => {\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-capture',\n id: args.nodeId,\n ...detachedSnapshot(capture, 'workspace capture timing'),\n seq: args.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n },\n onWorkspaceCaptureStarted: async (capture) => {\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-capture-started',\n id: args.nodeId,\n ...detachedSnapshot(capture, 'workspace capture start'),\n seq: args.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n },\n }\n}\n\nexport function retainedExecutorContext(ctx: ExecutorContext): RetainedExecutorContext | undefined {\n return ctx.seams[retainedExecutorSeamKey] as RetainedExecutorContext | undefined\n}\n\n/**\n * Why a retained execution has no accepted terminal result, classified where the cause is still\n * a typed value rather than a string in a journal.\n *\n * One reason string used to cover two situations that call for opposite operator responses\n * (#1204): an execution whose status genuinely cannot be determined — refusing to replace it is\n * correct, and the operator must reconcile before retrying or pay twice for one turn — and a\n * provider that broke its contract, where the reader or provider needs repair before the original\n * execution can be reconciled. Six exhibits in three days wore the first name for the second fault.\n *\n * - `'unobservable'`: the execution may have run and nothing local can say. The safety refusal.\n * Anything unclassifiable lands here, and so does a 4xx, a not-found, or a client deadline hit\n * AFTER admission: the provider cannot resolve what it admitted, which is exactly the case the\n * refusal exists for, not a rejected request.\n * - `'provider-contract'`: the provider answered with something its own contract forbids — a\n * `RetainedRunProviderContractError` naming a broken answer (an `*_INVALID`, `*_CHANGED`,\n * `*_DUPLICATE`, `*_MISSING` code), an event bound to another run.\n * - `'request-rejected'`: the request itself was refused BEFORE it ran — a schema violation\n * (`ZodError`), an HTTP 4xx at admission, a capacity refusal at admission that carries an\n * upstream capacity `code` and no HTTP status (the account owner's credential command refused a\n * fresh dispatch before the dispatch request existed), an unsupported credential route, or a\n * dispatch that Sandbox did not admit\n * because another execution owns the session or turn. Never named after admission.\n * - `'transport'`: the provider or a gateway in front of it failed — an HTTP 5xx, a socket\n * error, a platform service answering with a server error. Status is in doubt only because\n * the transport was.\n * - `'nested-recovery'`: a nested manager's own recovery could not be reconstructed. Stated by\n * the thrower, never inferred.\n *\n * Classification reads the cause's structure — class name, `code`, HTTP `status`, a Zod issue\n * list — never its message text, because the provider is not a dependency of this package and\n * its messages are not a contract. #1204's exhibit 3 (an event without a stable id) is delivered\n * rather than thrown since agent-provider-tangle 1.4.0, so it no longer reaches this path; its\n * exhibit 6 is typed as `JsonBoundError` (`code: 'JSON_BOUND_VIOLATION'`) since 1.5.0 and lands\n * with the schema violations. A provider still throwing plain `Error`s lands on `'unobservable'`,\n * which is the safe side.\n *\n * One `RetainedRunProviderContractError` is NOT one meaning. The runtime mints it both when the\n * provider answered wrongly and when a READ of the provider failed (`RETAINED_RESULT_READ_FAILED`,\n * `RETAINED_CONTROL_REF_READ_FAILED`). The second kind is a wrapper: what it wraps decides, in a\n * post-admission context, and a wrapper around nothing classifiable is exhibit 4.\n */\nexport type RetainedPendingCause =\n | 'unobservable'\n | 'provider-contract'\n | 'request-rejected'\n | 'transport'\n | 'nested-recovery'\n\nconst causeMessages: Record<RetainedPendingCause, string> = {\n unobservable: 'retained provider execution requires reconciliation before replacement',\n 'provider-contract':\n 'retained provider response violated its contract; original execution remains unresolved',\n 'request-rejected': 'retained provider execution was refused before it ran; nothing to reconcile',\n transport: 'retained provider execution lost its transport; status in doubt',\n 'nested-recovery': 'retained nested execution requires recovery before replacement',\n}\n\n/**\n * agent-provider-tangle's `TangleDispatchNotAdmittedError` (since 3.6.11): Sandbox answered a\n * dispatch with `dispatched: false` and named another execution that owns the session or turn.\n * Nothing ran for the request.\n */\nexport const DISPATCH_NOT_ADMITTED_CODE = 'DISPATCH_NOT_ADMITTED'\n\n/**\n * The Sandbox SDK's codes for a box that cannot be provisioned for this profile, sent with HTTP\n * 422 when the failure is deterministic: a profile file mount outside the box's writable roots,\n * refused before any box exists, and a profile-file materialization that would fail the same way\n * again. On Discovery run queens21-h22-capture-root-1-20261019c every child profile mounted\n * `/work/queens21_count.c` on a read-only root filesystem, and 154 attempts across 4 workers were\n * retried as a lost transport. The same codes at another status may be transient and are not\n * read here.\n */\nconst PROVISIONING_REFUSAL_CODES: ReadonlySet<string> = new Set([\n 'PROFILE_FILE_MOUNT_OUTSIDE_ROOTS',\n 'PROFILE_FILES_MATERIALIZE_FAILED',\n])\n\n/** True for an error that is itself a deterministic provisioning refusal (see above). */\nexport function isProvisioningRefusal(value: object): boolean {\n try {\n const code = readString(value, 'code')\n const status = readNumber(value, 'status') ?? readNumber(value, 'statusCode')\n return code !== undefined && status === 422 && PROVISIONING_REFUSAL_CODES.has(code)\n } catch {\n // An error whose fields cannot be read is no refusal this classifier can name.\n return false\n }\n}\n\n/** The contract-error codes that wrap a failed READ rather than name a broken answer. */\nconst readFailureCodes = new Set([\n 'RETAINED_RESULT_READ_FAILED',\n 'RETAINED_CONTROL_REF_READ_FAILED',\n])\n\n/** Socket-level failures, by the codes Node and undici assign, plus the Sandbox SDK's own. */\nexport const TRANSPORT_ERROR_CODES: ReadonlySet<string> = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'EPIPE',\n 'UND_ERR_SOCKET',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_HEADERS_TIMEOUT',\n 'UND_ERR_BODY_TIMEOUT',\n 'NETWORK_ERROR',\n])\n\nfunction readNumber(value: object, key: string): number | undefined {\n const read: unknown = Reflect.get(value, key)\n return typeof read === 'number' && Number.isFinite(read) ? read : undefined\n}\n\nfunction readString(value: object, key: string): string | undefined {\n const read: unknown = Reflect.get(value, key)\n return typeof read === 'string' ? read : undefined\n}\n\n/**\n * When the cause arose relative to admission. A read wrapper, an event-stream failure and the\n * scope's own retained branch are all post-admission; only the bare admission path is not.\n */\ntype RetainedPendingPhase = 'admission' | 'execution'\n\n// Preserve the specific admission evidence across local wrappers without adding a public cause\n// category. An unsupported route observed later cannot settle an already admitted execution.\nconst credentialAdmissionRefusals = new WeakSet<RetainedExecutionPendingError>()\n\n/**\n * Walk the cause chain (bounded, cycle-safe) and name the first cause whose structure decides.\n *\n * `phase` says whether a 4xx or a client deadline can mean \"refused before it ran\": only at\n * admission. After admission the same status means the provider cannot resolve what it\n * admitted, and the honest name is the refusal.\n */\nexport function classifyRetainedPendingCause(\n cause: unknown,\n phase: RetainedPendingPhase = 'execution',\n): RetainedPendingCause {\n return classifyPendingCause(cause, phase)\n}\n\nfunction classifyPendingCause(\n cause: unknown,\n phase: RetainedPendingPhase,\n onCredentialRefusal?: () => void,\n): RetainedPendingCause {\n const seen = new Set<object>()\n const queue: Array<{ value: unknown; phase: RetainedPendingPhase }> = [{ value: cause, phase }]\n let steps = 0\n while (queue.length > 0 && steps < 12) {\n steps += 1\n const { value, phase: at } = queue.shift()!\n if (typeof value !== 'object' || value === null || seen.has(value)) continue\n seen.add(value)\n if (value instanceof RetainedExecutionPendingError) {\n if (credentialAdmissionRefusals.has(value)) {\n if (at === 'execution') return 'unobservable'\n onCredentialRefusal?.()\n }\n return value.pendingCause\n }\n const name = readString(value, 'name')\n const code = readString(value, 'code')\n const status = readNumber(value, 'status') ?? readNumber(value, 'statusCode')\n if (name === 'RetainedRunProviderContractError') {\n if (code === undefined || !readFailureCodes.has(code)) return 'provider-contract'\n // A read that failed is a wrapper; what the read hit decides, after admission.\n queue.unshift({ value: Reflect.get(value, 'cause'), phase: 'execution' })\n continue\n }\n if (\n name === 'ZodError' ||\n Array.isArray(Reflect.get(value, 'issues')) ||\n // agent-provider-tangle's bound refusal (JsonBoundError, since 1.5.0): the same fact as a\n // schema violation, typed at last — #1204's exhibit 6.\n code === 'JSON_BOUND_VIOLATION'\n ) {\n // A schema or bound violation at admission is a rejected request. After admission it is\n // the runtime refusing the PROVIDER's answer — a contract violation on the provider's side.\n return at === 'admission' ? 'request-rejected' : 'provider-contract'\n }\n // Sandbox started nothing for this dispatch. After admission the same answer contradicts the\n // dispatch the provider already confirmed.\n if (code === DISPATCH_NOT_ADMITTED_CODE)\n return at === 'admission' ? 'request-rejected' : 'provider-contract'\n // The box could not be provisioned for this profile, at either phase: no turn ran in it.\n if (isProvisioningRefusal(value)) return 'request-rejected'\n // The credential command refused this route before dispatch. After admission, a refusal\n // encountered while observing the run cannot establish whether the admitted execution ran.\n if (isCredentialRefusal(value)) {\n if (at === 'execution') return 'unobservable'\n onCredentialRefusal?.()\n return 'request-rejected'\n }\n if (code !== undefined && TRANSPORT_ERROR_CODES.has(code)) return 'transport'\n if (name === 'NetworkError' || name === 'ServerError') return 'transport'\n // A capacity refusal with no HTTP response is the account owner refusing to bind a credential\n // to a fresh dispatch: agent-provider-tangle resolves the subscription credential before it\n // sends the dispatch, and its `TangleCredentialCapacityError` carries the router's code. At\n // admission nothing was sent, so nothing ran. Discovery run terraform-dc-tokens-20261006d died\n // on 20 such refusals named \"requires reconciliation\" (2026-10-07 19:07:56Z to 19:23:45Z).\n if (\n status === undefined &&\n at === 'admission' &&\n code !== undefined &&\n UNAVAILABLE_CODES.has(code.toLowerCase())\n )\n return 'request-rejected'\n if (status !== undefined) {\n if (status >= 500) return 'transport'\n if (at === 'admission' && status !== 408) return 'request-rejected'\n // 4xx after admission: the provider cannot resolve what it admitted. 408 is a client\n // deadline at either phase and says nothing about whether the request was admitted.\n return 'unobservable'\n }\n // An AggregateError carries its members in `errors`, with `cause` possibly the last one;\n // the first classifiable member decides.\n const errors: unknown = Reflect.get(value, 'errors')\n if (Array.isArray(errors)) for (const member of errors) queue.push({ value: member, phase: at })\n queue.push({ value: Reflect.get(value, 'cause'), phase: at })\n }\n return 'unobservable'\n}\n\n/**\n * Evidence debt, a {@link SpawnEvent} row: the workspace an accepted turn left in its retained\n * source environment could not be captured. The turn's result stands, the node continues in\n * another environment, and the source is never mutated. Written once per source, at the first\n * failed capture. A later `execution-evidence` receipt of that exact execution and source pays\n * it; the owner retries the capture on backoff while the supervisor lives, and a source still\n * owed at release is kept, named in the result's `teardownUnconfirmed[].kept` with\n * `keptFor: 'evidence'`, for the caller's salvage. Replay and cost readers skip it.\n */\nexport interface EvidencePendingEvent {\n kind: 'evidence-pending'\n id: NodeId\n environmentId: string\n /** The accepted turn's execution; absent when its admissions named none exactly. */\n executionId?: string\n /** The failed capture, as recorded. */\n error: string\n /** When the capture first failed: the durable copy is behind since then. */\n since: string\n seq: number\n at: string\n}\n\n/**\n * Local observation stopped; the retained provider execution has no accepted terminal result.\n *\n * The message names WHICH of the situations in {@link RetainedPendingCause} this is, and the\n * `pendingCause` field carries it as a value the settlement records, so a reader never splits\n * the population on the message's wording. The cause chain is kept for the `caused by` receipt.\n */\nexport class RetainedExecutionPendingError extends Error {\n readonly pendingCause: RetainedPendingCause\n readonly phase: RetainedPendingPhase\n\n constructor(\n cause: unknown,\n pendingCause: RetainedPendingCause | RetainedPendingPhase = 'execution',\n ) {\n let credentialRefused = false\n const resolved =\n pendingCause === 'admission' || pendingCause === 'execution'\n ? classifyPendingCause(cause, pendingCause, () => {\n credentialRefused = true\n })\n : pendingCause\n super(causeMessages[resolved], { cause })\n this.name = 'RetainedExecutionPendingError'\n this.pendingCause = resolved\n this.phase = pendingCause === 'admission' ? 'admission' : 'execution'\n if (credentialRefused) credentialAdmissionRefusals.add(this)\n }\n}\n\n/** @internal Validated original invocation selected for live adoption by the supervisor. */\nexport interface RetainedChildRecovery {\n readonly spawned: Extract<SpawnEvent, { kind: 'spawned' }>\n readonly spec: AgentSpec\n /** The node's original task, which its admitted identity digests. */\n readonly task: unknown\n /** The admissions of the invocation being recovered. */\n readonly admissions: readonly RetainedRunAdmission[]\n readonly factory: ExecutorFactory<unknown>\n readonly priorMaterialization?: ProfileMaterializationReceipt\n /** The invocation being recovered, when it is a leaf's continuation rather than its first. */\n readonly continuation?: RetainedLeafContinuation\n}\n\n/** @internal A leaf's later invocation: its own task, input and execution identity, and the\n * environment admission of the invocation it continues. */\nexport interface RetainedLeafContinuation {\n readonly task: unknown\n readonly inputSeq: number\n readonly executionId: string\n readonly priorSession: RetainedRunEnvironmentAdmission\n readonly priorSpent: Spend\n}\n\n/** The instruction a keyed continuation runs in the held session: the node's task is unchanged,\n * and its conversation and workspace are where the budget stop left them. */\nexport const BUDGET_CONTINUATION_TASK =\n 'Your previous turn reached its budget and stopped. Your manager gave you more budget to ' +\n 'continue the same task in the same session: your conversation so far and the files in your ' +\n 'workspace are where you left them. Continue from where you stopped. Do not start over.'\n\n/** The execution id of a leaf's later invocation, derived from its `execution-input` sequence so\n * a recovery derives the same one. A first invocation keeps the node id. */\nexport function leafContinuationExecutionId(nodeId: string, inputSeq: number): string {\n return `${nodeId}:input:${inputSeq}`\n}\n\ninterface RetainedExecutorPreparation {\n readonly spawned: Extract<SpawnEvent, { kind: 'spawned' }>\n readonly profile: AgentProfile\n readonly task: unknown\n}\n\ntype PrepareRetainedExecutor = (input: RetainedExecutorPreparation) =>\n | {\n spec: AgentSpec\n factory: ExecutorFactory<unknown>\n }\n | undefined\n\nconst retainedPreparations = new WeakMap<ExecutorFactory<unknown>, PrepareRetainedExecutor>()\n\n/** Reconstruct an admitted worker through its original composition boundary. @internal */\nexport function registerRetainedExecutorPreparation(\n factory: ExecutorFactory<unknown>,\n prepare: PrepareRetainedExecutor,\n): ExecutorFactory<unknown> {\n retainedPreparations.set(factory, prepare)\n return factory\n}\n\nexport function prepareRetainedExecutor(\n factory: ExecutorFactory<unknown>,\n input: RetainedExecutorPreparation,\n) {\n return retainedPreparations.get(factory)?.(input)\n}\n","import { z } from 'zod'\nimport { BackendTransportError } from '../errors'\nimport { ReservationWaitRefused } from './supervise/budget'\nimport { isCredentialRefusal } from './supervise/credential-refusal'\nimport { errMessage } from './supervise/error-message'\nimport { PLATFORM_FAILURE_CODES } from './supervise/executor-outcome'\nimport {\n classifyRetainedPendingCause,\n RetainedExecutionPendingError,\n type RetainedPendingCause,\n TRANSPORT_ERROR_CODES,\n} from './supervise/retained-executor'\nimport { UNAVAILABLE_CODES, UNAVAILABLE_STATUSES } from './supervise/upstream-unavailable'\n\nconst MAX_CAUSE_CHARS = 2_048\nconst MAX_CHAIN_STEPS = 12\nconst MACHINE_CODE_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u\n\n/**\n * Who must act before the same work can succeed.\n *\n * - `provider`: the execution provider holds the answer — reconcile the admitted execution, or\n * repair the reader or provider that broke its contract.\n * - `platform`: infrastructure or an upstream model service failed or is out of capacity.\n * - `runtime`: Runtime could not reconstruct work it owns.\n * - `work`: the agent's own work failed.\n * - `caller`: the request, its credential, its budget, its deadline, or its cancellation decided\n * the outcome.\n * - `unknown`: nothing structural attributes the failure.\n * @stable\n */\nexport type RuntimeFailureOwner = RuntimeFailureCause['owner']\n\n/** Stable failure codes. A consumer branches on these, never on `cause` text. @stable */\nexport type RuntimeFailureCode = RuntimeFailureCause['code']\n\n/** @internal Canonical producer-supplied remediation, shared by transport and read models. */\nexport const runtimeFailureRemediationSchema = z.object({\n cause: z.enum([\n 'api_key_selected',\n 'provider_unresolved',\n 'subscription_unverified',\n 'not_authenticated',\n ]),\n fix: z.string().min(1).max(256),\n harness: z.string().min(1).max(64),\n provider: z.string().min(1).max(128).nullable(),\n})\n\n/** @internal Validate Runtime-owned failure values on observation transports. */\nexport const runtimeFailureCauseSchema = z\n .object({\n code: z.enum([\n 'aborted',\n 'deadline-exceeded',\n 'budget-exhausted',\n 'credential-refused',\n 'request-rejected',\n 'upstream-unavailable',\n 'transport',\n 'provider-contract',\n 'retained-unobservable',\n 'nested-recovery',\n 'platform',\n 'work-failed',\n 'unknown',\n ]),\n owner: z.enum(['provider', 'platform', 'runtime', 'work', 'caller', 'unknown']),\n cause: z.string().max(MAX_CAUSE_CHARS),\n /** The upstream or provider machine code the failure carried, when it carried one. */\n providerCode: z.string().regex(MACHINE_CODE_PATTERN).optional(),\n remediation: runtimeFailureRemediationSchema.readonly().optional(),\n })\n .readonly()\n/**\n * A terminal failure as values, carried on final and settled events beside their existing\n * `reason` and `error` fields.\n *\n * `code` and `owner` are read from the failure's structure — its class, machine code, HTTP status\n * and cause chain, the caller's signal and deadline, or the settlement's typed fields — never from\n * message text. `cause` is the redacted, bounded cause chain for people; it is not a contract.\n * @stable\n * @useDeclaredType\n */\nexport type RuntimeFailureCause = z.infer<typeof runtimeFailureCauseSchema>\n\nconst retainedFailures: Record<RetainedPendingCause, Classified> = {\n unobservable: { code: 'retained-unobservable', owner: 'provider' },\n 'provider-contract': { code: 'provider-contract', owner: 'provider' },\n 'request-rejected': { code: 'request-rejected', owner: 'caller' },\n transport: { code: 'transport', owner: 'platform' },\n 'nested-recovery': { code: 'nested-recovery', owner: 'runtime' },\n}\n\nfunction read(value: object, key: string): unknown {\n try {\n return Reflect.get(value, key)\n } catch {\n return undefined\n }\n}\n\n/** Every object in a failure's cause chain and aggregate members, bounded and cycle-safe. */\nfunction chain(error: unknown): object[] {\n const out: object[] = []\n const queue: unknown[] = [error]\n while (queue.length > 0 && out.length < MAX_CHAIN_STEPS) {\n const value = queue.shift()\n if (typeof value !== 'object' || value === null || out.includes(value)) continue\n out.push(value)\n const members = read(value, 'errors')\n if (Array.isArray(members)) {\n const limit = Math.min(members.length, MAX_CHAIN_STEPS)\n for (let index = 0; index < limit; index++) queue.push(read(members, String(index)))\n }\n queue.push(read(value, 'cause'))\n }\n return out\n}\n\n/** What the caller knows about how a failed operation ended. */\nexport interface RuntimeFailureContext {\n /** The caller's own signal. Aborted means the caller cancelled. */\n readonly signal?: AbortSignal\n /** The operation's own deadline expired before the caller cancelled it. */\n readonly deadlineExpired?: boolean\n}\n\ntype Classified = { code: RuntimeFailureCode; owner: RuntimeFailureOwner }\n\nconst UNATTRIBUTED: Classified = { code: 'unknown', owner: 'unknown' }\n\n/** One link's own structure: budget refusal, credential refusal, machine code, HTTP status. */\nfunction structuralFailure(link: object): Classified | undefined {\n if (link instanceof ReservationWaitRefused || read(link, 'reason') === 'budget-exhausted') {\n return { code: 'budget-exhausted', owner: 'caller' }\n }\n const code = upstreamMachineCode([link])\n if (isCredentialRefusal(link) || code === 'SEAT_NOT_LOGGED_IN')\n return { code: 'credential-refused', owner: 'caller' }\n const status = read(link, 'status') ?? read(link, 'statusCode')\n if (code === 'MODEL_NOT_FOUND') return { code: 'request-rejected', owner: 'caller' }\n if (typeof code === 'string' && UNAVAILABLE_CODES.has(code.toLowerCase())) {\n return { code: 'upstream-unavailable', owner: 'platform' }\n }\n if (typeof status === 'number' && Number.isInteger(status)) {\n if (UNAVAILABLE_STATUSES.has(status)) return { code: 'upstream-unavailable', owner: 'platform' }\n if (status >= 500 || status === 0 || status === 408)\n return { code: 'transport', owner: 'platform' }\n if (status === 401 || status === 403) return { code: 'credential-refused', owner: 'caller' }\n if (status >= 400) return { code: 'request-rejected', owner: 'caller' }\n }\n if (typeof code === 'string' && TRANSPORT_ERROR_CODES.has(code)) {\n return { code: 'transport', owner: 'platform' }\n }\n if (typeof code === 'string' && PLATFORM_FAILURE_CODES.has(code.toLowerCase())) {\n return { code: 'platform', owner: 'platform' }\n }\n const name = read(link, 'name')\n if (name === 'NetworkError' || name === 'ServerError')\n return { code: 'transport', owner: 'platform' }\n return undefined\n}\n\n/** @internal The same machine-code validation used by public failure values. */\nexport function runtimeProviderCode(value: unknown): string | undefined {\n return typeof value === 'string' && MACHINE_CODE_PATTERN.test(value) ? value : undefined\n}\n\nfunction upstreamMachineCode(links: readonly object[]): string | undefined {\n return ['upstreamCode', 'errorCode', 'code']\n .flatMap((field) => links.map((link) => runtimeProviderCode(read(link, field))))\n .find((code) => code !== undefined)\n}\n\n/**\n * Classify a thrown failure. Pass the caller's signal so a cancellation the caller asked for is\n * attributed to the caller even when the provider surfaced it as an ordinary error, and say when\n * the operation's own deadline expired so a blown deadline is never reported as a cancellation.\n */\nexport function runtimeFailureCause(\n error: unknown,\n context: RuntimeFailureContext = {},\n): RuntimeFailureCause {\n const cause = errMessage(error).slice(0, MAX_CAUSE_CHARS)\n const caller = context.signal?.aborted\n ? 'aborted'\n : context.deadlineExpired\n ? 'deadline-exceeded'\n : undefined\n try {\n const links = chain(error)\n // Prefer an upstream diagnosis across the whole chain over a wrapper's generic code.\n const providerCode = upstreamMachineCode(links)\n const upstream = links.find(\n (link) =>\n link instanceof BackendTransportError &&\n link.backend === 'bridge' &&\n link.status === 403 &&\n link.upstreamCode === 'subscription_required' &&\n link.providerDispatch === 'not_started',\n ) as BackendTransportError | undefined\n const remedy = runtimeFailureRemediationSchema.readonly().safeParse(upstream?.remediation)\n const failure = ({ code, owner }: Classified): RuntimeFailureCause => ({\n code,\n owner,\n cause,\n ...(providerCode === undefined ? {} : { providerCode }),\n ...(code === 'credential-refused' &&\n providerCode === 'subscription_required' &&\n remedy.success\n ? { remediation: remedy.data }\n : {}),\n })\n if (caller !== undefined) return failure({ code: caller, owner: 'caller' })\n // Without the caller's signal, an AbortError is the only evidence of a cancellation. With it,\n // an AbortError the caller did not ask for is some other party's abort, classified below.\n if (context.signal === undefined && links.some((link) => read(link, 'name') === 'AbortError')) {\n return failure({ code: 'aborted', owner: 'caller' })\n }\n for (const link of links) {\n // A retained execution names why it has no accepted result as a value; a provider contract\n // error is classified the way the retained settlement classifies it.\n if (link instanceof RetainedExecutionPendingError) {\n return failure(retainedFailures[link.pendingCause])\n }\n if (read(link, 'name') === 'RetainedRunProviderContractError') {\n return failure(retainedFailures[classifyRetainedPendingCause(link)])\n }\n }\n for (const link of links) {\n const classified = structuralFailure(link)\n if (classified !== undefined) return failure(classified)\n }\n return failure(UNATTRIBUTED)\n } catch {\n // Foreign arrays, proxies and prototype checks cannot replace the original rejection.\n return { ...(caller === undefined ? UNATTRIBUTED : { code: caller, owner: 'caller' }), cause }\n }\n}\n\n/**\n * Classify a failure the execution reported without throwing — a Sandbox outcome or executor\n * envelope with `success: false` — from its machine code and HTTP status. A harness that reports\n * a failure with neither does not say who must act, so it is `unknown`, never the work's fault.\n */\nexport function reportedFailureCause(outcome: {\n readonly error?: string\n readonly errorCode?: string\n readonly statusCode?: number\n}): RuntimeFailureCause {\n return runtimeFailureCause(\n Object.assign(new Error(outcome.error ?? 'execution reported a failure'), {\n errorCode: outcome.errorCode,\n statusCode: outcome.statusCode,\n }),\n )\n}\n\n/**\n * Classify a down settlement from the typed facts Runtime recorded while the cause was still a\n * value: the retained cause, the failure classified where the executor threw, then `infra: false`,\n * the throw path's statement that the work itself failed. `infra: true` is not an owner: Runtime\n * also sets it for cancellations, budget reconcile faults and validation errors, and from the\n * platform's failure messages, so a settlement with nothing else typed is `unknown`.\n */\nexport function settlementFailureCause(down: {\n readonly reason: string\n readonly infra?: boolean\n readonly retainedPendingCause?: RetainedPendingCause\n readonly failure?: RuntimeFailureCause\n}): RuntimeFailureCause {\n const cause = errMessage(down.reason).slice(0, MAX_CAUSE_CHARS)\n if (down.retainedPendingCause !== undefined) {\n return { ...retainedFailures[down.retainedPendingCause], cause }\n }\n if (down.failure !== undefined && down.failure.code !== 'unknown')\n return { ...down.failure, cause }\n return {\n ...(down.infra === false\n ? { code: 'work-failed' as const, owner: 'work' as const }\n : UNATTRIBUTED),\n cause,\n ...(down.failure?.providerCode === undefined\n ? {}\n : { providerCode: down.failure.providerCode }),\n }\n}\n","import { createHash } from 'node:crypto'\n\nexport function sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { closeSync, existsSync, fstatSync, openSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { tryAcquireAtomicFileLock } from '@tangle-network/agent-eval/ledger-core'\nimport type { LockIdentity } from '@tangle-network/agent-eval/lock-holder'\n\n/** The immutable claim carried by every write in one directory execution. @internal */\nexport interface RunWriteClaim {\n readonly path: string\n readonly generation: number\n readonly lock: LockIdentity\n}\n\nconst claims = new AsyncLocalStorage<RunWriteClaim | undefined>()\nconst publications = new AsyncLocalStorage<{ readonly claim: RunWriteClaim; active: boolean }>()\n\n/** Bind asynchronous work, including callbacks, to the generation that admitted it. @internal */\nexport function runWithWriteClaim<T>(claim: RunWriteClaim, operation: () => T): T {\n return claims.run(claim, operation)\n}\n\n/** Capture a store's acquisition once, even when later called from an unrelated emitter. @internal */\nexport function captureRunWriteContext(): <T>(operation: () => T) => T {\n let claim = claims.getStore()\n return <T>(operation: () => T): T => {\n claim ??= claims.getStore()\n return claims.run(claim, operation)\n }\n}\n\n/** Serialize claim changes and file mutations under the same cross-process guard. @internal */\nexport function mutateRunClaim<T>(path: string, operation: () => T): T {\n // Old writers use an unowned directory guard. Never race one or guess that it is stale.\n const legacyGuard = `${path}.guard`\n if (existsSync(legacyGuard)) {\n throw new Error(\n `supervisePursuit: cannot mutate ${path}; inspect ${legacyGuard} and remove it only after confirming no lock mutation is active`,\n )\n }\n const deadline = performance.now() + 5_000\n const sleeper = new Int32Array(new SharedArrayBuffer(4))\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${path}.mutation` })\n if (acquisition.acquired) {\n try {\n return operation()\n } finally {\n acquisition.lock.release()\n }\n }\n if (performance.now() >= deadline) throw new Error(`run directory mutation is held: ${path}`)\n Atomics.wait(sleeper, 0, 0, 10)\n }\n}\n\n/**\n * Fence an actual file mutation, not an earlier advisory check. No await occurs between the\n * ownership check and publication, and acquire/release use this same guard. Unclaimed standalone\n * stores retain their existing single-writer contract; pursuit-owned work always carries a claim.\n * @internal\n */\nexport function fenceRunWrite<T>(operation: () => T): T {\n const claim = claims.getStore()\n if (claim === undefined) return operation()\n const publication = publications.getStore()\n if (\n publication?.active &&\n publication.claim.path === claim.path &&\n publication.claim.generation === claim.generation\n )\n return operation()\n return mutateRunClaim(claim.path, () => {\n let holder: Partial<RunWriteClaim> | undefined\n try {\n const fd = openSync(claim.path, 'r')\n try {\n const stat = fstatSync(fd, { bigint: true })\n if (\n stat.dev.toString() !== claim.lock.dev ||\n stat.ino.toString() !== claim.lock.ino ||\n stat.birthtimeNs.toString() !== claim.lock.birthtimeNs\n ) {\n throw new Error('run lock inode changed')\n }\n holder = JSON.parse(readFileSync(fd, 'utf8')) as Partial<RunWriteClaim>\n } finally {\n closeSync(fd)\n }\n } catch (cause) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`, { cause })\n }\n if (\n holder?.generation !== claim.generation ||\n holder.lock?.dev !== claim.lock.dev ||\n holder.lock?.ino !== claim.lock.ino ||\n holder.lock?.birthtimeNs !== claim.lock.birthtimeNs\n ) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`)\n }\n // Nested synchronous primitives share the guard. A callback queued here keeps its claim,\n // but cannot inherit a live guard after this publication has returned.\n const publication = { claim, active: true }\n try {\n return publications.run(publication, operation)\n } finally {\n publication.active = false\n }\n })\n}\n\n/** Persistent generation counter survives a clean release of supervise.lock. @internal */\nexport function runGenerationPath(runDir: string): string {\n return resolve(runDir, 'supervise.generation')\n}\n","/**\n * Small filesystem durability primitives for Runtime-owned state.\n *\n * Callers must validate their path and parent directory before invoking these functions.\n * The exclusive writer protects a no-clobber publication race; the atomic writer replaces one\n * state file after its temporary contents reach stable storage.\n *\n * @internal\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n type BigIntStats,\n closeSync,\n existsSync,\n fchmodSync,\n constants as fsConstants,\n fstatSync,\n fsyncSync,\n linkSync,\n lstatSync,\n openSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n writeSync,\n} from 'node:fs'\nimport { dirname, join, relative, resolve } from 'node:path'\nimport { fenceRunWrite } from '../../durable/run-fence'\n\ninterface DurableFileOptions {\n readonly mode?: number\n}\n\n/**\n * File content, or content computed from the new file's own stat when it must name the file's\n * inode (a lock record that later proves it was written for this very file).\n */\ntype DurableFileContent = string | ((file: BigIntStats) => string)\n\n/**\n * Publish a new file without replacing a concurrent winner. The published entry is a hard link\n * of the temporary file, so a content function sees the published file's inode.\n */\nexport function publishExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n return fenceRunWrite(() => publishExclusiveDurableFileUnchecked(filePath, content, options))\n}\n\nfunction publishExclusiveDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n let published = false\n try {\n writeExclusiveDurableFile(temporaryPath, content, options)\n try {\n linkSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n published = true\n } catch (error) {\n if (!isAlreadyExistsError(error)) throw error\n }\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n return published\n}\n\n/** Fsync a directory after publishing a durable file entry. */\nexport function syncDurableDirectory(directoryPath: string): void {\n const fd = openSync(directoryPath, 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Fsync one durable file after its contents reach stable storage. */\nfunction syncDurableFile(filePath: string, exactMode?: number): void {\n const fd = openSync(filePath, 'r')\n try {\n if (exactMode !== undefined && process.platform !== 'win32') fchmodSync(fd, exactMode)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Append one record with O_APPEND, then fsync the file and containing directory. */\nexport function appendDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n fenceRunWrite(() => appendDurableFileUnchecked(filePath, content, options))\n}\n\nfunction appendDurableFileUnchecked(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n const flags =\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0)\n const fd = openSync(filePath, flags, options.mode ?? 0o600)\n try {\n if (process.platform !== 'win32') fchmodSync(fd, options.mode ?? 0o600)\n const expectedBytes = Buffer.byteLength(content, 'utf8')\n const writtenBytes = writeSync(fd, content, undefined, 'utf8')\n if (writtenBytes !== expectedBytes) {\n throw new Error(\n `durable append wrote ${writtenBytes} of ${expectedBytes} bytes to '${filePath}'`,\n )\n }\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n syncDurableDirectory(dirname(filePath))\n}\n\n/** Reject a path that escapes its run directory or traverses a symbolic link. */\nexport function assertNoSymlinkDescendant(root: string, target: string, label = 'path'): void {\n const base = resolve(root)\n const exact = resolve(target)\n const rel = relative(base, exact)\n if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`)) {\n throw new Error(`${label} path escapes its run directory`)\n }\n if (existsSync(base) && lstatSync(base).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${base}`)\n }\n let current = base\n for (const part of rel.split(/[\\\\/]/u).filter(Boolean)) {\n current = join(current, part)\n if (!existsSync(current)) continue\n if (lstatSync(current).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${current}`)\n }\n }\n}\n\n/** Write, fsync, atomically replace, and fsync one Runtime-owned state file.\n * preserveMode retains ordinary access permissions despite the current umask; a new\n * file keeps normal creation semantics. Callers still own path validation and write exclusion. */\nexport function writeAtomicDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n fenceRunWrite(() => writeAtomicDurableFileUnchecked(filePath, content, options))\n}\n\nfunction writeAtomicDurableFileUnchecked(\n filePath: string,\n content: string,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n try {\n let mode = options.mode\n let exactMode = false\n if (options.preserveMode) {\n try {\n mode = statSync(filePath).mode & 0o777\n exactMode = true\n } catch (error) {\n if (!isNoEntryError(error)) throw error\n }\n }\n writeExclusiveDurableFile(temporaryPath, content, { mode }, exactMode)\n renameSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n // A successful rename removes the temporary directory entry.\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n}\n\nfunction writeExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions,\n exactMode = false,\n): void {\n const fd = openSync(filePath, 'wx', options.mode ?? 0o666)\n try {\n const text = typeof content === 'string' ? content : content(fstatSync(fd, { bigint: true }))\n writeFileSync(fd, text, 'utf8')\n } finally {\n closeSync(fd)\n }\n syncDurableFile(filePath, exactMode ? options.mode : undefined)\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n )\n}\n\nfunction isNoEntryError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\n}\n","import { executorFailureReason } from '../../runtime/supervise/executor-outcome'\nimport { assertValidSpend } from '../../runtime/supervise/spend-validation'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\n\n/** Minimal state needed to validate a node; progress and trace payloads are never retained here. */\ninterface JournalNodeIndex {\n spawned: boolean\n closed: boolean\n materialized: boolean\n authoredProfileDigest?: string\n latestSeatMaterialization: number\n bindings: Set<string>\n inputs: Set<number>\n input: boolean\n /** The sequence of the latest `execution-input`. */\n latestInput?: number\n result: boolean\n /** The latest invocation was abandoned: nothing of it is accepted, and a new input may follow. */\n abandoned: boolean\n admissions: Map<\n Extract<SpawnEvent, { kind: 'execution-admitted' }>['admission']['phase'],\n Extract<SpawnEvent, { kind: 'execution-admitted' }>['admission']\n >\n /** The environment this node's retained invocations last ran in, across invocations. */\n lastEnvironmentId?: string\n /** Environments that can run no more turns, from teardown or provider terminal observation. */\n unusableEnvironments: Set<string>\n}\n\n/**\n * A trace root is valid only beside the output it commits to, with a well-formed root, artifact\n * reference and leaf count (at least the summary leaf). Records written before trace roots carry\n * none and stay valid.\n */\nfunction assertTraceRoot(event: SpawnEvent, root: NodeId): void {\n if (!('traceRoot' in event) || event.traceRoot === undefined) return\n const receipt: unknown = event.traceRoot\n const fields =\n receipt !== null && typeof receipt === 'object' ? (receipt as Record<string, unknown>) : {}\n if (\n typeof event.outRef !== 'string' ||\n typeof fields.root !== 'string' ||\n !/^sha256:[0-9a-f]{64}$/.test(fields.root) ||\n typeof fields.ref !== 'string' ||\n !/^sha256:[0-9a-f]{64}$/.test(fields.ref) ||\n typeof fields.leafCount !== 'number' ||\n !Number.isSafeInteger(fields.leafCount) ||\n fields.leafCount < 1\n ) {\n throw new Error(\n `spawn journal corrupted: ${event.kind} for node '${event.id}' carries a malformed trace root in tree '${root}'`,\n )\n }\n}\n\n/** One validation implementation for memory, durable append, and cold replay. */\n/** @internal shared with the SQL-backed store. */\nexport class SpawnEventIndex {\n private readonly nodes = new Map<NodeId, JournalNodeIndex>()\n private readonly cursors = new Set<number>()\n\n constructor(private readonly root: NodeId) {}\n\n assert(event: SpawnEvent): void {\n const node = this.nodes.get(event.id)\n this.assertRetained(node, event)\n assertTraceRoot(event, this.root)\n if (event.kind === 'execution-evidence') {\n if (!node?.spawned || !/^sha256:[0-9a-f]{64}$/.test(event.outRef)) {\n throw new Error(\n 'spawn journal corrupted: executor evidence has no spawned node or valid content reference',\n )\n }\n }\n if (event.kind === 'materialized') {\n if (node?.materialized) {\n throw new Error(\n `spawn journal corrupted: duplicate materialization receipt for node '${event.id}' in tree '${this.root}'`,\n )\n }\n if (!node?.spawned) {\n throw new Error(\n `spawn journal corrupted: materialization for node '${event.id}' precedes its spawn in tree '${this.root}'`,\n )\n }\n }\n if (event.kind === 'seat-materialized') {\n if (\n !node?.materialized ||\n node.authoredProfileDigest === undefined ||\n event.receipt.status !== 'known' ||\n event.receipt.authoredProfileDigest !== node.authoredProfileDigest ||\n !Number.isSafeInteger(event.segmentIndex) ||\n event.segmentIndex <= node.latestSeatMaterialization\n ) {\n throw new Error(\n `spawn journal corrupted: invalid seat materialization for node '${event.id}' in tree '${this.root}'`,\n )\n }\n }\n if (event.kind === 'execution-bound') {\n if (node?.bindings.has(event.binding.attemptId)) {\n throw new Error(\n `spawn journal corrupted: duplicate execution binding for node '${event.id}' attempt '${event.binding.attemptId}' in tree '${this.root}'`,\n )\n }\n if (!node?.materialized) {\n throw new Error(\n `spawn journal corrupted: execution binding for node '${event.id}' precedes materialization in tree '${this.root}'`,\n )\n }\n }\n if (!outsideCursorNamespace(event) && this.cursors.has(event.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${event.seq} in tree '${this.root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n }\n\n /** Called after validation; a file writer discards staged state if grouped publication fails. */\n add(event: SpawnEvent): void {\n if (!outsideCursorNamespace(event)) this.cursors.add(event.seq)\n if (\n event.kind !== 'spawned' &&\n event.kind !== 'materialized' &&\n event.kind !== 'seat-materialized' &&\n event.kind !== 'execution-bound' &&\n event.kind !== 'execution-input' &&\n event.kind !== 'execution-admitted' &&\n event.kind !== 'execution-result' &&\n event.kind !== 'execution-abandoned' &&\n event.kind !== 'environment-teardown' &&\n event.kind !== 'environment-terminal' &&\n !closesCursorSlot(event)\n )\n return\n let node = this.nodes.get(event.id)\n if (!node) {\n node = {\n spawned: false,\n closed: false,\n materialized: false,\n latestSeatMaterialization: 0,\n bindings: new Set(),\n inputs: new Set(),\n input: false,\n result: false,\n abandoned: false,\n admissions: new Map(),\n unusableEnvironments: new Set(),\n }\n this.nodes.set(event.id, node)\n }\n if (event.kind === 'environment-teardown') {\n if (event.destroyed) node.unusableEnvironments.add(event.environmentId)\n return\n }\n if (event.kind === 'environment-terminal') {\n node.unusableEnvironments.add(event.environmentId)\n return\n }\n if (event.kind === 'execution-admitted' && event.admission.phase === 'environment') {\n node.lastEnvironmentId = event.admission.environmentId\n }\n if (event.kind === 'spawned') node.spawned = true\n else if (event.kind === 'materialized') {\n node.materialized = true\n node.authoredProfileDigest = event.receipt.authoredProfileDigest\n } else if (event.kind === 'seat-materialized')\n node.latestSeatMaterialization = event.segmentIndex\n else if (event.kind === 'execution-bound') node.bindings.add(event.binding.attemptId)\n else if (event.kind === 'execution-input') {\n node.inputs.add(event.seq)\n node.input = true\n node.latestInput = event.seq\n node.result = false\n node.abandoned = false\n node.admissions.clear()\n } else if (event.kind === 'execution-admitted') {\n node.admissions.set(event.admission.phase, event.admission)\n } else if (event.kind === 'execution-result') node.result = true\n else if (event.kind === 'execution-abandoned') node.abandoned = true\n if (closesCursorSlot(event)) node.closed = true\n }\n\n private assertRetained(node: JournalNodeIndex | undefined, event: SpawnEvent): void {\n if (\n event.kind !== 'execution-input' &&\n event.kind !== 'execution-admitted' &&\n event.kind !== 'execution-result' &&\n event.kind !== 'execution-abandoned'\n )\n return\n function fail(reason: string): never {\n throw new Error(`spawn journal corrupted: retained execution '${event.id}' ${reason}`)\n }\n if (!node?.spawned) fail('precedes its spawn')\n if (node.closed) fail('follows its terminal settlement')\n if (event.kind === 'execution-input') {\n if (!/^sha256:[0-9a-f]{64}$/.test(event.taskRef)) fail('has an invalid task reference')\n if (node.inputs.has(event.seq)) fail('has duplicate input sequence')\n // An unfinished invocation may be replaced only once its environment is gone, the provider\n // reports its compute terminal, or Runtime abandoned it: then nothing of the old turn can\n // be accepted, because every later admission or result of it is refused below.\n const environment = node.admissions.get('environment')\n const ranIn =\n environment?.phase === 'environment' ? environment.environmentId : node.lastEnvironmentId\n const closed = node.abandoned || (ranIn !== undefined && node.unusableEnvironments.has(ranIn))\n if (node.input && !node.result && !closed) fail('input replaces an unfinished invocation')\n return\n }\n if (event.kind === 'execution-abandoned') {\n if (!node.input || node.latestInput !== event.inputSeq)\n fail('abandons an invocation that is not its latest')\n if (node.result) fail('abandons an invocation that has a result')\n if (node.abandoned) fail('abandons an invocation twice')\n if (!Number.isSafeInteger(event.failures) || event.failures < 1)\n fail('abandons without a failure count')\n return\n }\n // Nothing of an abandoned invocation is accepted: its replacement is the only invocation.\n if (node.abandoned) fail(`${event.kind} follows its abandonment`)\n if (event.kind === 'execution-result') {\n if (node.result) fail('has duplicate result')\n if (!node.admissions.has('dispatched')) fail('result precedes dispatch')\n if (!/^sha256:[0-9a-f]{64}$/.test(event.outRef)) fail('has an invalid result reference')\n assertValidSpend(event.spent, 'retained execution result')\n executorFailureReason(event)\n return\n }\n const admission = event.admission\n if (!admission || !['intent', 'environment', 'dispatched'].includes(admission.phase))\n fail('has an invalid admission phase')\n if (node.admissions.has(admission.phase)) fail('has duplicate admission phase')\n if (node.result) fail('admission follows result')\n if (!node.input) fail('admission precedes input')\n if (admission.phase === 'intent') {\n if (node.admissions.size !== 0) fail('intent follows another admission')\n return\n }\n const intent = node.admissions.get('intent')\n if (intent?.phase !== 'intent') fail('admission precedes intent')\n if (admission.idempotencyKey !== intent.idempotencyKey || admission.turnId !== intent.turnId)\n fail('changes its admitted request identity')\n if (admission.phase === 'environment') {\n if (\n admission.provider !== intent.provider ||\n admission.sessionId !== intent.sessionId ||\n admission.executionId !== intent.executionId\n )\n fail('changes its admitted execution identity')\n return\n }\n const environment = node.admissions.get('environment')\n if (environment?.phase !== 'environment') fail('dispatch precedes environment')\n const control = admission.controlRef\n if (\n !control ||\n control.provider !== intent.provider ||\n control.environmentId !== environment.environmentId ||\n control.sessionId !== intent.sessionId ||\n control.executionId !== intent.executionId\n )\n fail('dispatch changes its admitted execution identity')\n }\n}\n\n/**\n * The records that CLOSE a node's cursor slot: a settlement or a cancellation. The complement question to {@link outsideCursorNamespace}, and the one a resume needs —\n * a kind missing here leaves a finished node looking live, so its budget is never reclaimed and\n * its reservation is replayed as still in doubt.\n */\nexport function closesCursorSlot(ev: SpawnEvent): boolean {\n return ev.kind === 'settled' || ev.kind === 'cancelled'\n}\n\n/**\n * The kinds that sit OUTSIDE the cursor namespace: node-CREATION and informational records. The\n * cursor namespace is the one whose per-node uniqueness replay ordering rests on, so every side of\n * that guard reads this one list — the seq guard, `materializeTreeView`'s settlement split, and\n * `trajectory`'s close list.\n *\n * Declared once as data. `SpawnEvent` is a discriminated union, so the complement below is\n * COMPUTED rather than hand-written: a twelfth kind lands in the cursor namespace by construction\n * instead of by whichever copies its author remembered to update.\n */\nconst outsideCursorNamespaceKinds = [\n 'spawned',\n 'metered',\n 'materialized',\n 'execution-bound',\n 'execution-input',\n 'execution-admitted',\n 'execution-result',\n 'execution-abandoned',\n 'execution-evidence',\n 'evidence-pending',\n 'progress',\n 'reconciled',\n 'edge',\n 'teardown-unconfirmed',\n 'teardown-pending',\n 'teardown-confirmed',\n 'environment-teardown',\n 'environment-terminal',\n 'workspace-checkpoint-requested',\n 'workspace-checkpoint',\n 'workspace-checkpoint-fork-requested',\n 'workspace-checkpoint-fork-ready',\n 'workspace-checkpoint-fork-teardown',\n 'workspace-checkpoint-capture',\n 'workspace-checkpoint-cleanup',\n 'workspace-restored',\n 'workspace-capture-started',\n 'workspace-capture',\n 'trace-unpropagated',\n 'seat-segment',\n 'seat-materialized',\n 'seat-paused',\n 'run-parked',\n 'root-segment',\n 'root-reentered',\n 'reopened',\n 'paused',\n 'barren-pause',\n 'driver-attempt',\n 'node-inputs-resolved',\n 'edge-verdict',\n 'join-state',\n] as const satisfies ReadonlyArray<SpawnEvent['kind']>\n\ntype OutsideCursorNamespaceKind = (typeof outsideCursorNamespaceKinds)[number]\n\n/** A record that closes or advances a node's cursor slot — the complement of\n * {@link outsideCursorNamespace}, computed from the union rather than restated. */\ntype CursorNamespaceEvent = Exclude<SpawnEvent, { kind: OutsideCursorNamespaceKind }>\n\nconst outsideKinds: ReadonlySet<string> = new Set<string>(outsideCursorNamespaceKinds)\n\n/** True for a node-CREATION or informational record. Narrows, so a caller keeps the union's arms. */\nexport function outsideCursorNamespace(\n ev: SpawnEvent,\n): ev is Extract<SpawnEvent, { kind: OutsideCursorNamespaceKind }> {\n return outsideKinds.has(ev.kind)\n}\n\n/** True for a record inside the cursor namespace. Narrows to {@link CursorNamespaceEvent}. */\nexport function insideCursorNamespace(ev: SpawnEvent): ev is CursorNamespaceEvent {\n return !outsideKinds.has(ev.kind)\n}\n","import {\n closeSync,\n fstatSync,\n fsyncSync,\n ftruncateSync,\n openSync,\n readSync,\n writeSync,\n} from 'node:fs'\nimport { fenceRunWrite } from './run-fence'\n\n/** Commit JSONL bytes and validate their descriptor under one generation fence. @internal */\nexport function commitJsonLine<T>(\n path: string,\n record: unknown,\n acknowledge?: (fd: number) => T,\n): T | undefined {\n const encoded = JSON.stringify(record)\n if (encoded === undefined) throw new TypeError('JSONL records must be JSON serializable')\n return fenceRunWrite(() => {\n const separator = prepareJsonlTail(path)\n const fd = openSync(path, 'a')\n try {\n const bytes = Buffer.from(`${separator ? '\\n' : ''}${encoded}\\n`)\n let offset = 0\n while (offset < bytes.length) {\n const written = writeSync(fd, bytes, offset, bytes.length - offset)\n if (written <= 0)\n throw new Error(`append-only file write made no progress at byte ${offset}`)\n offset += written\n }\n fsyncSync(fd)\n return acknowledge?.(fd)\n } finally {\n closeSync(fd)\n }\n })\n}\n\n/** Recover only an uncommitted tail. Caller holds the generation fence. @internal */\nexport function prepareJsonlTail(path: string): boolean {\n let fd: number\n try {\n fd = openSync(path, 'r+')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw error\n }\n try {\n const size = fstatSync(fd).size\n if (size === 0) return false\n const last = Buffer.allocUnsafe(1)\n readAt(fd, last, size - 1)\n if (last[0] === 0x0a) return false\n const chunks: Buffer[] = []\n let end = size\n let tailStart = 0\n while (end > 0) {\n const start = Math.max(0, end - 65_536)\n const chunk = Buffer.allocUnsafe(end - start)\n readAt(fd, chunk, start)\n const newline = chunk.lastIndexOf(0x0a)\n chunks.push(chunk.subarray(newline + 1))\n if (newline >= 0) {\n tailStart = start + newline + 1\n break\n }\n end = start\n }\n try {\n JSON.parse(Buffer.concat(chunks.reverse()).toString('utf8'))\n return true\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error\n ftruncateSync(fd, tailStart)\n fsyncSync(fd)\n return false\n }\n } finally {\n closeSync(fd)\n }\n}\n\nfunction readAt(fd: number, buffer: Buffer, position: number): void {\n let offset = 0\n while (offset < buffer.length) {\n const read = readSync(fd, buffer, offset, buffer.length - offset, position + offset)\n if (read === 0) throw new Error('journal changed while preparing its append tail')\n offset += read\n }\n}\n","import type { FileHandle } from 'node:fs/promises'\nimport { commitJsonLine, prepareJsonlTail } from './jsonl-append'\nimport { fenceRunWrite } from './run-fence'\n\n/** Parse in-memory evidence with the same commit boundary as streamed journal reads. */\nexport function parseCommittedJsonLines<T>(text: string, source: string): T[] {\n const lines = text.split('\\n')\n const records: T[] = []\n for (const [index, line] of lines.entries()) {\n const record = parseRecord<T>(line, source, index + 1, index < lines.length - 1)\n if (record !== undefined) records.push(record.value)\n }\n return records\n}\n\n/** Read a fixed file prefix one record at a time, never allocating the whole journal as a string.\n * A reader cannot chase concurrent appends forever. Missing files are empty only when requested;\n * corruption, short reads, and other I/O errors remain failures. Closing the iterator closes the fd. */\nexport async function* readCommittedJsonLines<T>(\n path: string,\n options: {\n allowMissing?: boolean\n allowWhitespaceLines?: boolean\n onBytes?: (bytes: Uint8Array) => void\n } = {},\n): AsyncGenerator<T> {\n const fs = await import('node:fs/promises')\n let handle: FileHandle\n try {\n handle = await fs.open(path, 'r')\n } catch (error) {\n if (options.allowMissing && isNoEntError(error)) return\n throw error\n }\n try {\n const { size } = await handle.stat()\n if (size === 0) return\n const { StringDecoder } = await import('node:string_decoder')\n const decoder = new StringDecoder('utf8')\n const stream = handle.createReadStream({ autoClose: false, end: size - 1 })\n const fragments: string[] = []\n let lineNumber = 1\n try {\n for await (const chunk of stream) {\n options.onBytes?.(chunk as Buffer)\n const text = decoder.write(chunk as Buffer)\n let start = 0\n let end = text.indexOf('\\n', start)\n while (end !== -1) {\n fragments.push(text.slice(start, end))\n const record = parseRecord<T>(\n fragments.join(''),\n path,\n lineNumber++,\n true,\n options.allowWhitespaceLines,\n )\n fragments.length = 0\n if (record !== undefined) yield record.value\n start = end + 1\n end = text.indexOf('\\n', start)\n }\n if (start < text.length) fragments.push(text.slice(start))\n }\n if (stream.bytesRead !== size) {\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n }\n fragments.push(decoder.end())\n const record = parseRecord<T>(\n fragments.join(''),\n path,\n lineNumber,\n false,\n options.allowWhitespaceLines,\n )\n if (record !== undefined) yield record.value\n } finally {\n stream.destroy()\n }\n } finally {\n await handle.close()\n }\n}\n\n/** An invalid unterminated tail may be a torn write; other parse failures are not evidence of one. */\nfunction parseRecord<T>(\n line: string,\n source: string,\n lineNumber: number,\n terminated: boolean,\n allowWhitespaceLines = false,\n): { value: T } | undefined {\n if (line.length === 0 || (allowWhitespaceLines && line.trim().length === 0)) return undefined\n try {\n return { value: JSON.parse(line) as T }\n } catch (cause) {\n if (!(cause instanceof SyntaxError)) throw cause\n if (!terminated) return undefined\n throw new Error(`${source}: malformed JSONL record at line ${lineNumber}`, { cause })\n }\n}\n\n/** Append one JSONL record under the caller's existing single-writer discipline.\n * The caller creates the parent directory. Recover only an uncommitted tail, handle short\n * writes, and fsync before acknowledging.\n * An optional acknowledgement reads the same open descriptor after sync (the spawn journal\n * validates its file stamp here). Queueing, validation, and failure policy belong to the owner.\n * @internal\n */\nexport function appendCommittedJsonLine(path: string, record: unknown): Promise<void>\nexport function appendCommittedJsonLine<T>(\n path: string,\n record: unknown,\n acknowledge: (fd: number) => T,\n): Promise<T>\nexport async function appendCommittedJsonLine<T>(\n path: string,\n record: unknown,\n acknowledge?: (fd: number) => T,\n): Promise<T | undefined> {\n return commitJsonLine(path, record, acknowledge)\n}\n\n/** Serialize JSONL file updates across processes and aliases using Eval's existing file lock.\n * The caller owns validation and the record format. The lock path names the canonical file,\n * including its first write, so two directory aliases cannot acquire different write heads.\n * @internal\n */\nexport async function withJsonlFileLock<T>(\n path: string,\n operation: (canonicalPath: string) => Promise<T>,\n): Promise<T> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n const { tryAcquireAtomicFileLock } = await import('@tangle-network/agent-eval/ledger-core')\n await fs.mkdir(dirname(path), { recursive: true })\n const file = await fs.open(path, 'a')\n await file.close()\n const canonicalPath = await fs.realpath(path)\n const deadline = Date.now() + 5000\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${canonicalPath}.lock` })\n if (!acquisition.acquired) {\n if (Date.now() >= deadline) {\n throw new Error(`journal file lock unavailable after 5000ms: ${canonicalPath}`)\n }\n await new Promise((resolve) => setTimeout(resolve, 25))\n continue\n }\n try {\n return await operation(canonicalPath)\n } finally {\n acquisition.lock.release()\n }\n }\n}\n\n/** Read one keyed registry snapshot without an extra whole-file text allocation.\n * Historical registry files allow whitespace-only separators; append journals remain strict.\n * @internal\n */\nexport async function readCommittedJsonFile<T>(path: string): Promise<T[]> {\n const records: T[] = []\n for await (const record of readCommittedJsonLines<T>(path, {\n allowMissing: true,\n allowWhitespaceLines: true,\n })) {\n records.push(record)\n }\n return records\n}\n\n/** Replace one keyed row and publish one durable snapshot. The caller holds the file lock.\n * Keep unrelated rows in order and put the replacement last. No revision archive is retained.\n * @internal\n */\nexport async function upsertCommittedJsonLine<T>(\n path: string,\n record: T,\n key: (record: T) => string,\n): Promise<void> {\n const encoded = JSON.stringify(record)\n if (encoded === undefined) throw new Error('JSONL records must be JSON serializable')\n const snapshot: T = JSON.parse(encoded)\n const id = key(snapshot)\n const updated: T[] = []\n for await (const prior of readCommittedJsonLines<T>(path, {\n allowMissing: true,\n allowWhitespaceLines: true,\n })) {\n if (key(prior) !== id) updated.push(prior)\n }\n updated.push(snapshot)\n // Reuse Runtime's file publication owner; this module owns JSONL framing, not another\n // durability implementation. Preserve the existing snapshot's permissions across rename.\n const { writeAtomicDurableFile } = await import('../runtime/supervise/durable-file')\n writeAtomicDurableFile(path, `${updated.map((row) => JSON.stringify(row)).join('\\n')}\\n`, {\n preserveMode: true,\n })\n}\n\n/** Recover a torn tail under the same generation fence as durable publications. @internal */\nexport async function prepareJsonlAppend(path: string): Promise<boolean> {\n return fenceRunWrite(() => prepareJsonlTail(path))\n}\n\n/** True for a filesystem error meaning \"the file is not there yet\" — the one condition an\n * append-only reader treats as an empty log rather than a fault. */\nexport function isNoEntError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n )\n}\n","import { isRecord } from '@tangle-network/agent-core'\nimport type { SpawnEvent } from '../../runtime/supervise/types'\n\n/** Decode the file journal's historical single-event and atomic-group envelopes. @internal */\nexport function spawnJournalRecordEvents(record: unknown): ReadonlyArray<SpawnEvent> {\n if (!isRecord(record)) throw new Error('spawn journal corrupted: record must be an object')\n if (record.kind === 'begin') return []\n if (record.kind === 'event') return [record.event as SpawnEvent]\n if (record.kind !== 'events') {\n throw new Error(`spawn journal corrupted: unknown record kind '${String(record.kind)}'`)\n }\n if (!Array.isArray(record.events)) throw new Error('spawn journal group has no events array')\n return record.events as SpawnEvent[]\n}\n","import { type BigIntStats, fstatSync, statSync } from 'node:fs'\nimport { detachedSnapshot } from '../../runtime/supervise/snapshot'\nimport type { NodeId, SpawnEvent, SpawnJournal } from '../../runtime/supervise/types'\nimport { appendCommittedJsonLine, isNoEntError, readCommittedJsonLines } from '../jsonl-file'\nimport { captureRunWriteContext } from '../run-fence'\nimport { SpawnEventIndex } from './event-index'\nimport { spawnJournalRecordEvents } from './record-events'\n\n/**\n * Append every event as one grouped publication where the journal supports it (`appendEvents`),\n * preserving legacy per-event appends otherwise — the SQL contexts' fenced head advances once.\n * @internal\n */\nexport async function appendSpawnEvents(\n journal: SpawnJournal,\n root: NodeId,\n events: ReadonlyArray<SpawnEvent>,\n): Promise<void> {\n if (journal.appendEvents !== undefined) return journal.appendEvents(root, events)\n for (const event of events) await journal.appendEvent(root, event)\n}\n\n/**\n * JSONL on disk. One line per record: the first record is `begin`, subsequent records\n * are `event` or atomic `events` envelopes. `loadTree` replays the whole file,\n * filtering by `root`, and applies the same begin-precedes-events + unique-seq\n * corruption guards as the in-memory impl. Each append fsyncs so a crash between\n * writes never loses an acknowledged event.\n *\n * @stable\n */\nexport class FileSpawnJournal implements SpawnJournal {\n private readonly writeContext = captureRunWriteContext()\n private appendTail: Promise<void> = Promise.resolve()\n // Rebuildable validation state, not another journal or a copy of event payloads.\n private appendIndex:\n | { stamp: string | undefined; trees: Map<NodeId, { begunAt: string; index: SpawnEventIndex }> }\n | undefined\n\n constructor(private readonly path: string) {}\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n let begun = false\n const events: SpawnEvent[] = []\n const index = new SpawnEventIndex(root)\n for await (const record of readCommittedJsonLines<SpawnJournalRecord>(this.path, {\n allowMissing: true,\n })) {\n if (record.root !== root) continue\n if (record.kind === 'begin') {\n begun = true\n } else {\n if (!begun) {\n throw new Error(\n `spawn journal corrupted: event for tree '${root}' precedes its begin record`,\n )\n }\n for (const event of spawnJournalRecordEvents(record)) {\n index.assert(event)\n index.add(event)\n events.push(event)\n }\n }\n }\n return begun ? events : undefined\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n return this.serializeAppend(async () => {\n const state = await this.validationIndex()\n const existing = state.trees.get(root)\n if (existing) {\n if (existing.begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in ${this.path} at ${existing.begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n state.stamp = await this.writeRecord({ kind: 'begin', root, at })\n state.trees.set(root, { begunAt: at, index: new SpawnEventIndex(root) })\n })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const event = detachedSnapshot(ev, 'spawn event')\n return this.serializeAppend(async () => {\n const state = await this.validationIndex()\n const tree = state.trees.get(root)\n if (tree === undefined) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n tree.index.assert(event)\n state.stamp = await this.writeRecord({ kind: 'event', root, event })\n // An unacknowledged append cannot advance validation state. A failed write invalidates\n // the index, so recovery reads the actual committed bytes before admitting another event.\n tree.index.add(event)\n })\n }\n\n async appendEvents(root: NodeId, events: ReadonlyArray<SpawnEvent>): Promise<void> {\n const captured = detachedSnapshot(events, 'spawn events')\n return this.serializeAppend(async () => {\n const state = await this.validationIndex()\n const tree = state.trees.get(root)\n if (tree === undefined) {\n throw new Error(\n `appendEvents called for unknown spawn tree '${root}'; call beginTree first`,\n )\n }\n try {\n // This queue exclusively owns the private index. Stage validation without copying the\n // entire tree per spawn; any rejection discards it before another append can use it.\n for (const event of captured) {\n tree.index.assert(event)\n tree.index.add(event)\n }\n state.stamp = await this.writeRecord({ kind: 'events', root, events: captured })\n } catch (error) {\n this.appendIndex = undefined\n throw error\n }\n })\n }\n\n private async validationIndex() {\n const stamp = await this.fileStamp()\n if (this.appendIndex && this.appendIndex.stamp === stamp) return this.appendIndex\n this.appendIndex = undefined\n const trees = new Map<NodeId, { begunAt: string; index: SpawnEventIndex }>()\n if (stamp !== undefined) {\n for await (const record of readCommittedJsonLines<SpawnJournalRecord>(this.path)) {\n if (record.kind === 'begin') {\n if (!trees.has(record.root)) {\n trees.set(record.root, { begunAt: record.at, index: new SpawnEventIndex(record.root) })\n }\n } else {\n const tree = trees.get(record.root)\n if (!tree) {\n throw new Error(\n `spawn journal corrupted: event for tree '${record.root}' precedes its begin record`,\n )\n }\n for (const event of spawnJournalRecordEvents(record)) {\n tree.index.assert(event)\n tree.index.add(event)\n }\n }\n }\n }\n if ((await this.fileStamp()) !== stamp) {\n throw new Error('spawn journal changed while rebuilding its append index')\n }\n this.appendIndex = { stamp, trees }\n return this.appendIndex\n }\n\n private async fileStamp(): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n try {\n return journalFileStamp(await fs.stat(this.path, { bigint: true }))\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n }\n\n private async serializeAppend(operation: () => Promise<void>): Promise<void> {\n const append = this.appendTail.then(() => this.writeContext(operation))\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async writeRecord(record: SpawnJournalRecord): Promise<string> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n try {\n await fs.mkdir(dirname(this.path), { recursive: true })\n return await appendCommittedJsonLine(this.path, record, (fd) => {\n const stamp = journalFileStamp(fstatSync(fd, { bigint: true }))\n if (journalFileStamp(statSync(this.path, { bigint: true })) !== stamp) {\n throw new Error('spawn journal changed while acknowledging its append')\n }\n return stamp\n })\n } catch (error) {\n this.appendIndex = undefined\n throw error\n }\n }\n}\n\n/** Detect replacement, truncation, and same-size edits; this is not a cross-process write lock. */\nfunction journalFileStamp(stat: BigIntStats): string {\n return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`\n}\n\ntype SpawnJournalRecord =\n | { kind: 'begin'; root: NodeId; at: string }\n | { kind: 'event'; root: NodeId; event: SpawnEvent }\n | { kind: 'events'; root: NodeId; events: ReadonlyArray<SpawnEvent> }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAgB,YAAY,OAAqD;CAC/E,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AACnC;;;;;;;;;;;;;;ACwDA,SAAgB,sBAAsB,OAAgB,OAAiC;CACrF,MAAM,SAASA,YAAY,KAAK;CAChC,IAAI,WAAW,KAAA,GACb,MAAM,IAAI,gBAAgB,GAAG,MAAM,sCAAsC,SAAS,KAAK,GAAG;CAE5F,MAAM,cAAc,cAAc,OAAO,cAAc,gBAAgB,KAAK;CAC5E,MAAM,oBAAoB,cAAc,OAAO,qBAAqB,uBAAuB,KAAK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