@tangle-network/agent-runtime 2.3.8 → 2.3.11
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.
- package/dist/{activation-Cks1h3Nw.d.ts → activation-B8dLwJj6.d.ts} +2 -2
- package/dist/{activation-CDPbi8JA.js → activation-BzNeFJDB.js} +4 -4
- package/dist/{activation-CDPbi8JA.js.map → activation-BzNeFJDB.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{bundle-PDYNXIEf.js → bundle-DhV73H6U.js} +2 -2
- package/dist/{bundle-PDYNXIEf.js.map → bundle-DhV73H6U.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{coordination-manager-DNrb7zMg.js → coordination-manager-BluavEgY.js} +42 -152
- package/dist/coordination-manager-BluavEgY.js.map +1 -0
- package/dist/{coordination-map-routing-CUvwHAtv.js → coordination-map-routing-BllzcZov.js} +5 -2
- package/dist/coordination-map-routing-BllzcZov.js.map +1 -0
- package/dist/{delegate-CHdWyLz9.js → delegate-CYWL0MrO.js} +2 -2
- package/dist/{delegate-CHdWyLz9.js.map → delegate-CYWL0MrO.js.map} +1 -1
- package/dist/durable-file-DstVeHcj.js.map +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +42 -202
- package/dist/durable.js.map +1 -1
- package/dist/{graph-oOdDpXFH.js → graph-ByNMeS0j.js} +8 -13
- package/dist/graph-ByNMeS0j.js.map +1 -0
- package/dist/{graph-registry-72DlMnUl.js → graph-registry-D6y6zffC.js} +2 -2
- package/dist/{graph-registry-72DlMnUl.js.map → graph-registry-D6y6zffC.js.map} +1 -1
- package/dist/{graph-registry-CAX15LO6.js → graph-registry-rV9mwxQO.js} +1 -1
- package/dist/{improve-BCjhWbVk.js → improve-D9A79N5a.js} +7 -7
- package/dist/{improve-BCjhWbVk.js.map → improve-D9A79N5a.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +10 -11
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +7 -6
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +12 -12
- package/dist/{loop-runner-Bkvx4Saw.d.ts → loop-runner-D9fuOb69.d.ts} +2 -2
- package/dist/{loop-runner-Cy1K7f-A.js → loop-runner-DiMfhI_z.js} +2 -2
- package/dist/{loop-runner-Cy1K7f-A.js.map → loop-runner-DiMfhI_z.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +6 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/{prepare-Bv6X2Wnx.js → prepare-DrHOZFJy.js} +3 -4
- package/dist/{prepare-Bv6X2Wnx.js.map → prepare-DrHOZFJy.js.map} +1 -1
- package/dist/{profile-Dir2A1_2.js → profile-BzzmKuIX.js} +3 -2
- package/dist/{profile-Dir2A1_2.js.map → profile-BzzmKuIX.js.map} +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-Pd95wA1X.js → provision-supervisor-DP5U58V4.js} +13 -5
- package/dist/provision-supervisor-DP5U58V4.js.map +1 -0
- package/dist/{run-cancellation-CzQZUlHr.js → run-cancellation-BxoFCpJ_.js} +208 -5
- package/dist/run-cancellation-BxoFCpJ_.js.map +1 -0
- package/dist/{runtime-CWZ9q7lU.js → runtime-DS5AgACg.js} +15 -16
- package/dist/{runtime-CWZ9q7lU.js.map → runtime-DS5AgACg.js.map} +1 -1
- package/dist/sandbox-profile-compat-DxegoIK5.js +65 -0
- package/dist/sandbox-profile-compat-DxegoIK5.js.map +1 -0
- package/dist/scope-DRaBilEX.js +16734 -0
- package/dist/scope-DRaBilEX.js.map +1 -0
- package/dist/{search-executor-CMPbMvpr.js → search-executor-DLo_9jUv.js} +4 -5
- package/dist/{search-executor-CMPbMvpr.js.map → search-executor-DLo_9jUv.js.map} +1 -1
- package/dist/{server-DyTbsg7n.js → server-DfHV4ajw.js} +4 -4
- package/dist/{server-DyTbsg7n.js.map → server-DfHV4ajw.js.map} +1 -1
- package/dist/{structural-rollout-BUqZsIhX.js → structural-rollout-BIjjZ_XX.js} +4 -5
- package/dist/{structural-rollout-BUqZsIhX.js.map → structural-rollout-BIjjZ_XX.js.map} +1 -1
- package/dist/{supervise-D1eYde7p.js → supervise-6BCQ73Xa.js} +34 -136
- package/dist/supervise-6BCQ73Xa.js.map +1 -0
- package/dist/{supervision-discovery-DmDWHwLu.js → supervision-discovery-Da5zebY2.js} +130 -5
- package/dist/supervision-discovery-Da5zebY2.js.map +1 -0
- package/dist/{supervisor-B8beIEqH.js → supervisor-3JHXy3tz.js} +7336 -19680
- package/dist/supervisor-3JHXy3tz.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +13 -13
- package/dist/{top-web-CUDlOKu0.js → top-web-DK6lTMHG.js} +89 -64
- package/dist/top-web-DK6lTMHG.js.map +1 -0
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +14 -8
- package/dist/tui/index.js +2 -2
- package/dist/{types-DzS0kBeK.d.ts → types-S3RbyJ4x.d.ts} +51 -65
- package/dist/{sandbox-profile-compat-DRiz9kME.js → workspace-streams-Dep2L6XD.js} +617 -57
- package/dist/workspace-streams-Dep2L6XD.js.map +1 -0
- package/package.json +2 -2
- package/dist/coordination-manager-DNrb7zMg.js.map +0 -1
- package/dist/coordination-map-routing-CUvwHAtv.js.map +0 -1
- package/dist/graph-oOdDpXFH.js.map +0 -1
- package/dist/provision-supervisor-Pd95wA1X.js.map +0 -1
- package/dist/root-stream-Bsh5WFcg.js +0 -4252
- package/dist/root-stream-Bsh5WFcg.js.map +0 -1
- package/dist/run-cancellation-CzQZUlHr.js.map +0 -1
- package/dist/sandbox-profile-compat-DRiz9kME.js.map +0 -1
- package/dist/supervise-D1eYde7p.js.map +0 -1
- package/dist/supervision-discovery-DmDWHwLu.js.map +0 -1
- package/dist/supervisor-B8beIEqH.js.map +0 -1
- package/dist/top-web-CUDlOKu0.js.map +0 -1
- package/dist/util-BX20UJ9X.js +0 -624
- package/dist/util-BX20UJ9X.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"root-stream-Bsh5WFcg.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/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/trace-root.ts","../src/runtime/supervise/upstream-unavailable.ts","../src/runtime/supervise/retained-executor.ts","../src/runtime/failure-cause.ts","../src/durable/observer-journal.ts","../src/durable/spawn-journal/event-index.ts","../src/durable/spawn-journal/result-blob-store.ts","../src/durable/spawn-journal/record-events.ts","../src/durable/spawn-journal/journal-store.ts","../src/runtime/supervise/run-layout.ts","../src/runtime/supervise/root-stream.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","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","/**\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/**\n * Platform refusals the orchestrator answers BEFORE it forwards a dispatch, by machine code and\n * the HTTP status it is sent with. Run 002f69d5: `HUB_CREDENTIAL_REFRESH_FAILED` at 503 left no\n * effect, yet read as a lost transport. Any other 5xx stays a transport failure, in doubt.\n */\nconst PLATFORM_PREDISPATCH_REFUSALS: ReadonlyMap<string, number> = new Map([\n ['HUB_CREDENTIAL_REFRESH_FAILED', 503],\n])\n\n/** True for an error that is itself a named platform refusal of a dispatch (see above). */\nexport function isPlatformPredispatchRefusal(value: object): boolean {\n try {\n const code = readString(value, 'code')\n const status = readNumber(value, 'status') ?? readNumber(value, 'statusCode')\n // An unnamed code has no expected status; never let two absent values match.\n const expected = code === undefined ? undefined : PLATFORM_PREDISPATCH_REFUSALS.get(code)\n return expected !== undefined && expected === status\n } catch {\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 // At admission a named platform refusal says nothing ran; after admission it says nothing.\n if (at === 'admission' && isPlatformPredispatchRefusal(value)) return 'request-rejected'\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 isPlatformPredispatchRefusal,\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 /** The HTTP status the provider's typed error carried with that code. */\n providerStatus: z.number().int().min(100).max(599).optional(),\n /** The provider's typed retry-after hint, in milliseconds. A hint, never an automatic retry. */\n retryAfterMs: z.number().int().nonnegative().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/** The typed HTTP status and retry-after of the link carrying the provider's code. */\nfunction upstreamResponse(\n links: readonly object[],\n providerCode: string | undefined,\n): Pick<RuntimeFailureCause, 'providerStatus' | 'retryAfterMs'> {\n const link = links.find((each) =>\n ['upstreamCode', 'errorCode', 'code'].some((field) => read(each, field) === providerCode),\n )\n if (providerCode === undefined || link === undefined) return {}\n const status = read(link, 'status') ?? read(link, 'statusCode')\n const retryAfterMs = read(link, 'retryAfterMs')\n return {\n ...(Number.isInteger(status) && (status as number) >= 100 && (status as number) <= 599\n ? { providerStatus: status as number }\n : {}),\n ...(Number.isInteger(retryAfterMs) && (retryAfterMs as number) >= 0\n ? { retryAfterMs: retryAfterMs as number }\n : {}),\n }\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 ...upstreamResponse(links, 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 // A named platform refusal before dispatch: nothing ran, and the platform must act.\n if (link.pendingCause === 'request-rejected' && links.some(isPlatformPredispatchRefusal))\n return failure({ code: 'request-rejected', owner: 'platform' })\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 const retained = retainedFailures[down.retainedPendingCause]\n // The failure classified where the executor threw agrees with the retained cause: keep its\n // typed facts (owner, provider code, status, retry-after). Otherwise the retained cause rules.\n if (down.failure !== undefined && down.failure.code === retained.code)\n return { ...down.failure, cause }\n return {\n ...retained,\n cause,\n // The retained cause names what to do; the provider's code still says what happened.\n ...(down.failure?.providerCode === undefined\n ? {}\n : { providerCode: down.failure.providerCode }),\n }\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'\nimport { resolve } from 'node:path'\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport {\n type RuntimeDecisionPoint,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { appendCommittedJsonLine, readCommittedJsonLines } from './jsonl-file'\nimport { captureRunWriteContext } from './run-fence'\n\nexport type ObserverRecordKind = 'event' | 'decision'\n\n/**\n * One immutable record in the observer plane. `sequence` is journal order, not\n * execution order; causal/runtime order remains available on the underlying event.\n * `previousDigest` + `digest` make deletion, reordering, or mutation detectable.\n */\nexport interface ObserverRecord {\n readonly schemaVersion: 1\n readonly pursuitId: string\n readonly sequence: number\n readonly kind: ObserverRecordKind\n readonly observedAt: number\n readonly previousDigest?: string\n readonly event?: RuntimeHookEvent\n readonly decision?: RuntimeDecisionPoint\n readonly digest: string\n}\n\nexport interface ObserverJournal {\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord>\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord>\n read(): Promise<readonly ObserverRecord[]>\n hooks(): RuntimeHooks\n}\n\ntype UnsignedObserverRecord = Omit<ObserverRecord, 'digest'>\n\n/**\n * Durable, append-only third-person history for one concrete Runtime execution.\n * It consumes Runtime's existing hook stream and does not participate in execution\n * decisions. A broken observer therefore cannot change what an agent is allowed to do.\n *\n * The write discipline deliberately matches `FileSpawnJournal`: serialized appends,\n * torn-tail recovery, short-write handling, and fsync before acknowledgement. One\n * execution owns one journal file; higher-level pursuit aggregation joins isolated\n * journals by `pursuitId` instead of making independent processes share a write head.\n */\nexport class FileObserverJournal implements ObserverJournal {\n readonly path: string\n readonly pursuitId: string\n private readonly writeContext = captureRunWriteContext()\n private tail: Promise<void> = Promise.resolve()\n private initialized = false\n private sequence = 0\n private previousDigest: string | undefined\n private appendFailure: Error | undefined\n\n constructor(path: string, pursuitId: string) {\n const stableId = pursuitId.trim()\n if (stableId.length === 0) {\n throw new TypeError('FileObserverJournal: pursuitId must be non-empty')\n }\n this.path = resolve(path)\n this.pursuitId = stableId\n }\n\n /** Open existing committed history by its recorded identity; never creates a file. */\n static async open(path: string): Promise<FileObserverJournal | undefined> {\n for await (const record of readCommittedJsonLines<ObserverRecord>(path, {\n allowMissing: true,\n })) {\n if (typeof record?.pursuitId !== 'string')\n throw new TypeError('observer journal: missing pursuit identity')\n const journal = new FileObserverJournal(path, record.pursuitId)\n verifyObserverRecords([record], journal.pursuitId)\n return journal\n }\n return undefined\n }\n\n hooks(): RuntimeHooks {\n return withPursuitContext(this.pursuitId, {\n onEvent: (event) => this.appendEvent(event).then(() => undefined),\n onDecisionPoint: (point) => this.appendDecision(point).then(() => undefined),\n })\n }\n\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord> {\n return this.enqueue('event', event)\n }\n\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord> {\n return this.enqueue('decision', point)\n }\n\n async read(): Promise<readonly ObserverRecord[]> {\n await this.tail\n this.assertComplete()\n const records: ObserverRecord[] = []\n const verify = observerVerifier(this.pursuitId)\n for await (const record of this.readExistingUnsafe()) {\n verify(record)\n records.push(record)\n }\n return Object.freeze(records)\n }\n\n private async enqueue(\n kind: ObserverRecordKind,\n value: RuntimeHookEvent | RuntimeDecisionPoint,\n ): Promise<ObserverRecord> {\n if (value.pursuitId !== this.pursuitId) {\n throw new Error(\n `FileObserverJournal: ${kind} pursuitId ${String(value.pursuitId)} does not match ${this.pursuitId}`,\n )\n }\n\n // Other hooks receive this same input and may mutate it before queued I/O runs.\n // Detach now, not after awaiting the previous append or computing the digest.\n const snapshot = detachedSnapshot(value, 'observer record')\n\n const operation = this.tail\n .then(() =>\n this.writeContext(async () => {\n this.assertComplete()\n await this.initialize()\n\n const unsigned: UnsignedObserverRecord = {\n schemaVersion: 1,\n pursuitId: this.pursuitId,\n sequence: this.sequence + 1,\n kind,\n observedAt: Date.now(),\n ...(this.previousDigest ? { previousDigest: this.previousDigest } : {}),\n ...(kind === 'event'\n ? { event: snapshot as RuntimeHookEvent }\n : { decision: snapshot as RuntimeDecisionPoint }),\n }\n const record: ObserverRecord = Object.freeze({\n ...unsigned,\n digest: observerRecordDigest(unsigned),\n })\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n await fs.mkdir(dirname(this.path), { recursive: true })\n await appendCommittedJsonLine(this.path, record)\n this.sequence = record.sequence\n this.previousDigest = record.digest\n return record\n }),\n )\n .catch((error) => {\n this.appendFailure ??= toError(error)\n throw error\n })\n this.tail = operation.then(\n () => undefined,\n () => undefined,\n )\n return operation\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) return\n const verify = observerVerifier(this.pursuitId)\n let tail: ObserverRecord | undefined\n for await (const record of this.readExistingUnsafe()) {\n verify(record)\n tail = record\n }\n this.sequence = tail?.sequence ?? 0\n this.previousDigest = tail?.digest\n // Only latch after recovery + verification succeed. A transient read error or\n // corruption must never leave an instance pretending it initialized cleanly.\n this.initialized = true\n }\n\n private readExistingUnsafe(): AsyncGenerator<ObserverRecord> {\n return readCommittedJsonLines<ObserverRecord>(this.path, { allowMissing: true })\n }\n\n private assertComplete(): void {\n if (!this.appendFailure) return\n throw new Error(\n 'FileObserverJournal: a prior durable append failed; observer completeness is unknown',\n { cause: this.appendFailure },\n )\n }\n}\n\n/** Verify identity, monotonic sequence, payload shape, and the complete digest chain. */\nexport function verifyObserverRecords(\n records: readonly ObserverRecord[],\n pursuitId?: string,\n): readonly ObserverRecord[] {\n const verify = observerVerifier(pursuitId)\n for (const record of records) verify(record)\n return Object.freeze([...records])\n}\n\n/** The same full chain validation is used for replay, startup and in-memory evidence. */\nfunction observerVerifier(pursuitId?: string): (record: ObserverRecord) => void {\n let previousDigest: string | undefined\n let expectedSequence = 1\n return (record) => {\n if (record.schemaVersion !== 1) throw new Error('observer journal: unsupported schemaVersion')\n if (pursuitId !== undefined && record.pursuitId !== pursuitId) {\n throw new Error(`observer journal: pursuit identity mismatch at sequence ${record.sequence}`)\n }\n if (record.sequence !== expectedSequence) {\n throw new Error(\n `observer journal: non-contiguous sequence ${record.sequence}; expected ${expectedSequence}`,\n )\n }\n if (record.previousDigest !== previousDigest) {\n throw new Error(`observer journal: digest-chain break at sequence ${record.sequence}`)\n }\n for (const kind of ['event', 'decision'] as const) {\n const payload = record[kind]\n if ((record.kind === kind) === (payload === undefined)) {\n throw new Error(`observer journal: invalid ${kind} payload at sequence ${record.sequence}`)\n }\n if (payload !== undefined && payload.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested ${kind} pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n }\n const { digest, ...unsigned } = record\n const expected = observerRecordDigest(unsigned)\n if (digest !== expected) {\n throw new Error(`observer journal: digest mismatch at sequence ${record.sequence}`)\n }\n previousDigest = digest\n expectedSequence += 1\n }\n}\n\n/** Compute the canonical SHA-256 digest for an unsigned observer record. */\nexport function observerRecordDigest(record: Omit<ObserverRecord, 'digest'>): string {\n return createHash('sha256').update(JSON.stringify(record)).digest('hex')\n}\n\n/** Build the canonical durable observer hook in one call. */\nexport function createFileObserverHooks(\n path: string,\n pursuitId: string,\n): {\n readonly journal: FileObserverJournal\n readonly hooks: RuntimeHooks\n} {\n const journal = new FileObserverJournal(path, pursuitId)\n return { journal, hooks: journal.hooks() }\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\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 assertNoSymlinkDescendant,\n publishExclusiveDurableFile,\n} from '../../runtime/supervise/durable-file'\nimport { detachedSnapshot } from '../../runtime/supervise/snapshot'\nimport type { ResultBlobStore } from '../../runtime/supervise/types'\nimport { contentAddress } from '../content-address'\nimport { isNoEntError } from '../jsonl-file'\nimport { captureRunWriteContext } from '../run-fence'\n\n/**\n * FS `ResultBlobStore`. One JSON file per artifact under `dir`, named by a\n * filesystem-safe encoding of the `outRef` (`sha256:<hex>` → `sha256-<hex>.json`).\n * `put` fsyncs so a crash between writes never loses an acknowledged blob.\n *\n * @stable\n */\nexport class FileResultBlobStore implements ResultBlobStore {\n private readonly writeContext = captureRunWriteContext()\n\n constructor(private readonly dir: string) {}\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n return this.writeContext(async () => {\n const { text } = encodeResultBlob(outRef, artifact)\n const filePath = this.blobPath(outRef)\n assertNoSymlinkDescendant(this.dir, filePath, 'result blob')\n const fs = await import('node:fs/promises')\n await fs.mkdir(this.dir, { recursive: true })\n assertNoSymlinkDescendant(this.dir, filePath, 'result blob')\n if (!publishExclusiveDurableFile(filePath, text, { mode: 0o600 })) {\n const existing = await this.get(outRef)\n assertContentAddress(outRef, existing)\n }\n })\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n const filePath = this.blobPath(outRef)\n assertNoSymlinkDescendant(this.dir, filePath, 'result blob')\n const fs = await import('node:fs/promises')\n const { constants } = await import('node:fs')\n let text: string\n try {\n const handle = await fs.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n if (!(await handle.stat()).isFile()) throw new Error('result blob must be a regular file')\n text = await handle.readFile('utf8')\n } finally {\n await handle.close()\n }\n } catch (err) {\n if (isNoEntError(err)) return undefined\n throw err\n }\n const artifact: unknown = JSON.parse(text)\n assertContentAddress(outRef, artifact)\n return artifact\n }\n\n private blobPath(outRef: string): string {\n if (!/^sha256:[0-9a-f]{64}$/.test(outRef))\n throw new Error('invalid result blob content address')\n return `${this.dir}/${outRef.replace(/:/g, '-')}.json`\n }\n}\n\n/** @internal shared with the SQL-backed store. */\nexport function encodeResultBlob(\n outRef: string,\n artifact: unknown,\n): { snapshot: unknown; text: string } {\n const detached = detachedSnapshot(artifact, 'result blob')\n assertContentAddress(outRef, detached)\n const text = JSON.stringify(detached)\n if (text === undefined) throw new Error('result blob must contain JSON')\n const snapshot: unknown = JSON.parse(text)\n // Both stores retain exactly the JSON value whose address survives durable serialization.\n assertContentAddress(outRef, snapshot)\n return { snapshot, text }\n}\n\n/** @internal shared with the SQL-backed store. */\nfunction assertContentAddress(outRef: string, artifact: unknown): void {\n const expected = contentAddress(artifact)\n if (outRef !== expected) {\n throw new Error(\n `blob outRef '${outRef}' does not match the artifact content hash '${expected}'; ` +\n 'a content-addressed store refuses a mismatched ref (breaks the replay invariant)',\n )\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","/**\n * The on-disk supervisor-run layout: `<root>/.agent/supervisor/<id>`.\n *\n * This is the durable, cross-process face of a supervisor run — the counterpart to the in-process\n * `Inbox` seam in `./inbox`. A run persists its state under one directory so that any OTHER process\n * can find it after the fact: `@tangle-network/traces` reads exactly this layout via\n * `traces analyze --supervisor-run-dir`, a restarted host can rehydrate a run it no longer holds\n * handles to, and a human can steer a live worker by appending one NDJSON line. Until now the\n * layout was defined only in the unpublished `loops` repo (`src/supervisor-control.ts`) — a\n * published reader depending on an unpublished writer's convention — so the contract is promoted\n * here, names preserved.\n *\n * `.agent` is the one dot-dir for ALL agent-owned state (skills already write\n * `.agent/hypotheses/`, `.agent/skill-runs.jsonl`); supervisor runs live beside them rather than\n * under a product-branded dir. Runs written by older writers used `.loops/supervisor/<id>` —\n * readers that must see those keep a legacy fallback; this writer never creates `.loops` again.\n *\n * Layout, relative to `supervisorRunDir(root, id)`:\n *\n * steers/requests/<hash>.json one exact, caller-idempotent {@link WorkerSteerRequest}\n * steers/acks/<hash>.json runtime acknowledgement for that steer operation\n * workers/<id>.inbox.ndjson best-effort readable projection of admitted steer requests\n * workers/<label>.ndjson best-effort per-worker control-event log (delivery bookkeeping)\n * cancellations/requests.ndjson worker-scoped cancel requests (durable inbox); each line is a\n * {@link WorkerCancelRequest}\n * cancellations/<opId>.json the acknowledgement for one cancel operation — a\n * {@link WorkerCancellation} written ONLY by the runtime\n * acknowledger in the OWNING manager's turn loop: exact node\n * ids route to the manager that parents them (any depth);\n * label/profile-name references to the root manager alone\n * cancellations/run.request.json the run-scoped cancel request — one {@link RunCancelRequest},\n * the whole RUN rather than one worker\n * cancellations/run.json the acknowledgement for the run-scoped request — a\n * {@link RunCancellation} written ONLY by the runtime (the root\n * manager issues the abort; the `supervise()` settle path records\n * what the run actually did)\n *\n * Reads are tolerant by contract: a partial trailing line (a writer mid-append) or a corrupt line\n * never poisons the rest of the file — later valid lines still matter. Duplicate operation ids\n * collapse to the first admitted request, while a payload conflict fails closed.\n *\n * Promoted from `loops/src/supervisor-control.ts`. Steer admission now requires the exact worker id\n * and a caller-owned operation id. One atomic request file is the durable inbox; the NDJSON file is\n * a readable projection only and never controls idempotency.\n *\n * @experimental\n */\n\nimport { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { canonicalCandidateDigest, type Sha256Digest } from '@tangle-network/agent-interface'\nimport { sha256 } from '../../content-digest'\nimport { fenceRunWrite } from '../../durable/run-fence'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport {\n appendDurableFile,\n assertNoSymlinkDescendant,\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from './durable-file'\n\n/** One atomically admitted down-leg request for an exact worker id. @stable */\nexport interface WorkerSteerRequest {\n readonly schemaVersion: 1\n /** Caller-minted stable idempotency key for this operation. */\n readonly operationId: string\n /** Digest of operation id, worker id, message, source, and interrupt mode. */\n readonly requestDigest: Sha256Digest\n /** ISO timestamp of durable admission. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Exact supervised node id, including the run id for its root manager. */\n readonly worker: string\n readonly message: string\n readonly interrupt: boolean\n}\n\n/** Runtime acknowledgement for one exact steer operation. @stable */\nexport interface WorkerSteerAcknowledgement {\n readonly schemaVersion: 1\n readonly operationId: string\n readonly requestDigest: Sha256Digest\n readonly worker: string\n readonly effect: 'unknown' | 'delivered' | 'not_live' | 'unsupported' | 'refused'\n readonly requestedAt: string\n readonly observedAt: string\n readonly detail: string\n}\n\n/** Caller input for one retry-safe steer operation. @stable */\nexport interface WriteWorkerSteerOptions {\n /** Exact Runtime event/control directory, matching the run's `steerDir`.\n * Defaults to `supervisorRunDir(rootDir, supervisorId)` when omitted. */\n readonly eventDir?: string\n readonly operationId: string\n readonly message: string\n readonly source?: string\n readonly interrupt?: boolean\n}\n\n/** One durable worker-scoped cancel request appended to the run's cancellation inbox. */\nexport interface WorkerCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the append. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** The worker the request targets: a workerId (node id — routed to the owning manager at any\n * depth), or a profile name or spawn label (resolved by the root manager against its direct\n * children only). */\n readonly worker: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for one worker-scoped cancel operation, keyed by\n * `operationId`. The runtime acknowledger is the ONLY writer; `cancelWorker` only reads it.\n *\n * `effect` reuses the retained-run vocabulary ({@link RetainedRunEffect}) so the runtime has one\n * spelling of the four cancellation states:\n * - `'unknown'` — not yet resolved by the runtime (also what `cancelWorker` returns for\n * a request no acknowledger has answered), or — terminally, with the\n * run-over detail — an abort was issued but the run ended before the\n * termination could be observed. Never a success.\n * - `'cancel_requested'` — the runtime issued the worker's abort; termination not yet proven.\n * - `'cancelled'` — the worker reached a terminal `down` state on the settle path.\n * - `'not_live'` — the worker was not live to cancel (already settled, it settled\n * `done` despite the abort, or the run ended before the request was\n * ever applied). Never a success of THIS operation.\n *\n * Expiry is run end: the owning manager's final pass closes every still-open request it owns\n * (`not_live` never applied, `unknown` issued-but-unproven), so a pending request cannot outlive\n * its run and abort a future spawn that happens to reuse a label.\n */\nexport interface WorkerCancellation {\n readonly operationId: string\n /** The worker reference exactly as requested. */\n readonly worker: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The node id the acknowledger resolved `worker` to, once resolved. */\n readonly workerId?: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n /**\n * Every node id this operation PROVED terminated: the requested worker plus each descendant of\n * its subtree observed to reach a terminal `down`/`cancelled` journal record at or after the\n * abort was ISSUED — the acknowledger's own `observedAt` on the `cancel_requested` record\n * (runtime clock), never the client's `requestedAt` (a cancelled lead cascades to its subtree\n * by design — the scope signal chain — so the acknowledgement names the set, not one id).\n * Proven at acknowledgement time; post-abort causation is approximate: a descendant that died\n * of its own cause after the abort is indistinguishable from the cascade and may be included,\n * a late teardown journal joins the set on a later pass while the manager still runs, and one\n * still absent at run end is absent from the set. Grows monotonically; empty until termination\n * is proven.\n */\n readonly terminated: ReadonlyArray<string>\n}\n\n/** The root every supervisor run of one workspace lives under. */\nexport function supervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.agent', 'supervisor')\n}\n\n/** The run directory every artifact of one supervisor run lives under. */\nexport function supervisorRunDir(rootDir: string, id: string): string {\n return join(supervisorRunsRoot(rootDir), id)\n}\n\n/**\n * Where a pre-rename writer put the same run (`<root>/.loops/supervisor/<id>`). Readers that must\n * see historical runs check {@link supervisorRunDir} first and fall back to this; nothing writes\n * here anymore.\n */\nexport function legacySupervisorRunDir(rootDir: string, id: string): string {\n return join(legacySupervisorRunsRoot(rootDir), id)\n}\n\n/**\n * The pre-rename runs root (`<root>/.loops/supervisor`). Only readers that ENUMERATE historical\n * runs need this — the per-id form is {@link legacySupervisorRunDir}. Nothing writes here.\n */\nexport function legacySupervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.loops', 'supervisor')\n}\n\n/** A worker label reduced to a safe filename stem. Empty labels get a stable fallback. */\nexport function safeWorkerFile(label: string): string {\n const safe = label.replace(/[^A-Za-z0-9._-]/g, '_')\n return safe.length > 0 ? safe : 'worker'\n}\n\n/** The directory holding every per-worker file of one run (inboxes and control-event logs). */\nexport function supervisorWorkersDir(eventDir: string): string {\n return join(eventDir, 'workers')\n}\n\n/** The durable inbox file for one worker of one run. */\nexport function workerInboxFile(rootDir: string, supervisorId: string, worker: string): string {\n return workerInboxFileFromEventDir(supervisorRunDir(rootDir, supervisorId), worker)\n}\n\n/** Same, addressed from an already-known run directory (the reader's usual entry point). */\nexport function workerInboxFileFromEventDir(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.inbox.ndjson`)\n}\n\n/**\n * The best-effort control-event log for one worker (`workers/<label>.ndjson`) — delivery\n * bookkeeping for steers, plus whatever lifecycle events a writer chooses to append. Distinct from\n * the inbox: the inbox is the durable down-leg queue, this is the record of what happened to it.\n */\nexport function workerControlLogFile(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.ndjson`)\n}\n\n/** Directory containing atomically admitted steer requests and runtime acknowledgements. */\nexport function workerSteersDir(eventDir: string): string {\n return join(eventDir, 'steers')\n}\n\n/** Directory containing one canonical request file per steer operation. */\nexport function workerSteerRequestsDir(eventDir: string): string {\n return join(workerSteersDir(eventDir), 'requests')\n}\n\n/** Directory containing one runtime acknowledgement per steer operation. */\nexport function workerSteerAcknowledgementsDir(eventDir: string): string {\n return join(workerSteersDir(eventDir), 'acks')\n}\n\n/** Canonical request file for one caller-owned steer operation id. */\nexport function workerSteerRequestFile(eventDir: string, operationId: string): string {\n return join(workerSteerRequestsDir(eventDir), `${operationFileHash(operationId)}.json`)\n}\n\n/** Runtime acknowledgement file for one caller-owned steer operation id. */\nexport function workerSteerAcknowledgementFile(eventDir: string, operationId: string): string {\n return join(workerSteerAcknowledgementsDir(eventDir), `${operationFileHash(operationId)}.json`)\n}\n\n/**\n * Admit one steer exactly once under a caller-owned operation id.\n *\n * Pass `supervisorId` as `worker` to address the root. Router roots consume requests between\n * turns; native roots use their existing accepting inbox during execution, or acknowledge\n * `unsupported` when none is available. Delivery does not prove model consumption.\n * This filesystem API requires trusted write access to the run directory; it adds no MCP grant.\n *\n * The per-operation request file is linked into place atomically after its bytes reach disk. A\n * same-body retry returns the winner's request. A changed-body retry fails loud. The NDJSON inbox\n * and control log are readable projections written only by the admission winner.\n * @stable\n */\nexport function writeWorkerSteer(\n rootDir: string,\n supervisorId: string,\n worker: string,\n options: WriteWorkerSteerOptions,\n): {\n worker: string\n file: string\n request: WorkerSteerRequest\n acknowledgement?: WorkerSteerAcknowledgement\n replayed: boolean\n} {\n const workerId = worker.trim()\n if (!workerId) throw new Error('writeWorkerSteer: worker id is empty')\n const operationId = options.operationId.trim()\n if (!operationId) throw new Error('writeWorkerSteer: operationId is empty')\n const trimmed = options.message.trim()\n if (!trimmed) throw new Error('steer message is empty')\n const source = options.source?.trim() || 'human'\n const interrupt = options.interrupt === true\n if (options.eventDir !== undefined && !options.eventDir.trim()) {\n throw new Error('writeWorkerSteer: eventDir is empty')\n }\n const dir =\n options.eventDir === undefined\n ? supervisorRunDir(rootDir, supervisorId)\n : resolve(options.eventDir)\n const requestDigest = workerSteerRequestDigest({\n operationId,\n worker: workerId,\n message: trimmed,\n source,\n interrupt,\n })\n const request: WorkerSteerRequest = {\n schemaVersion: 1,\n operationId,\n requestDigest,\n at: new Date().toISOString(),\n source,\n worker: workerId,\n message: trimmed,\n interrupt,\n }\n const file = workerSteerRequestFile(dir, operationId)\n assertNoSymlinkDescendant(dir, file, 'steer request')\n mkdirSync(workerSteerRequestsDir(dir), { recursive: true })\n assertNoSymlinkDescendant(dir, file, 'steer request')\n const admitted = admitSteerRequest(file, request)\n if (admitted.replayed) {\n return {\n worker: admitted.request.worker,\n file,\n request: admitted.request,\n ...(readWorkerSteerAcknowledgement(dir, operationId) === undefined\n ? {}\n : { acknowledgement: readWorkerSteerAcknowledgement(dir, operationId) }),\n replayed: true,\n }\n }\n mkdirSync(supervisorWorkersDir(dir), { recursive: true })\n const projection = workerInboxFileFromEventDir(dir, workerId)\n try {\n fenceRunWrite(() => appendFileSync(projection, `${JSON.stringify(request)}\\n`, 'utf8'))\n } catch {\n // The atomic operation file is the queue. This projection does not control admission.\n }\n appendWorkerControlEvent(dir, workerId, {\n kind: 'message',\n direction: 'down',\n source,\n operationId,\n requestDigest,\n message: trimmed,\n interrupt,\n queued: true,\n delivered: false,\n })\n return { worker: workerId, file, request, replayed: false }\n}\n\n/** Read every atomically admitted request for one exact worker id, in admission order. @stable */\nexport function readWorkerSteerRequests(eventDir: string, worker?: string): WorkerSteerRequest[] {\n const workerId = worker?.trim()\n if (worker !== undefined && !workerId) return []\n let names: string[]\n assertNoSymlinkDescendant(eventDir, workerSteerRequestsDir(eventDir), 'steer request')\n try {\n names = readdirSync(workerSteerRequestsDir(eventDir))\n } catch {\n return []\n }\n const out: WorkerSteerRequest[] = []\n for (const name of names) {\n if (!name.endsWith('.json')) continue\n try {\n const file = join(workerSteerRequestsDir(eventDir), name)\n assertNoSymlinkDescendant(eventDir, file, 'steer request')\n const parsed = parseWorkerSteerRequest(JSON.parse(readFileSync(file, 'utf8')))\n if (name !== `${operationFileHash(parsed.operationId)}.json`) continue\n if (workerId === undefined || parsed.worker === workerId) out.push(parsed)\n } catch {\n // One corrupt request cannot hide other independently committed operations.\n }\n }\n return out.sort((left, right) =>\n left.at === right.at\n ? left.operationId.localeCompare(right.operationId)\n : left.at.localeCompare(right.at),\n )\n}\n\n/** Read one runtime steer acknowledgement, or `undefined` while no manager has answered. @stable */\nexport function readWorkerSteerAcknowledgement(\n eventDir: string,\n operationId: string,\n): WorkerSteerAcknowledgement | undefined {\n const id = operationId.trim()\n if (!id) throw new Error('readWorkerSteerAcknowledgement: operationId is empty')\n const file = workerSteerAcknowledgementFile(eventDir, id)\n assertNoSymlinkDescendant(eventDir, file, 'steer acknowledgement')\n if (!existsSync(file)) return undefined\n const record = parseWorkerSteerAcknowledgement(JSON.parse(readFileSync(file, 'utf8')))\n if (record.operationId !== id) {\n throw new Error(`steer acknowledgement '${file}' belongs to another operation`)\n }\n return record\n}\n\n/**\n * Claim one steer for delivery with an atomic no-clobber acknowledgement.\n * Returns `true` only to the process that created the pre-delivery record.\n * @internal\n */\nexport function claimWorkerSteerDelivery(\n eventDir: string,\n record: WorkerSteerAcknowledgement,\n): boolean {\n const exact = parseWorkerSteerAcknowledgement(record)\n if (exact.effect !== 'unknown') {\n throw new Error('steer delivery claim must use effect unknown')\n }\n const request = readWorkerSteerRequest(eventDir, exact.operationId)\n if (request === undefined || request.requestDigest !== exact.requestDigest) {\n throw new Error('steer delivery claim does not match an admitted request')\n }\n const dir = workerSteerAcknowledgementsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n const file = workerSteerAcknowledgementFile(eventDir, exact.operationId)\n if (publishExclusiveDurableFile(file, `${JSON.stringify(exact, null, 2)}\\n`)) {\n return true\n }\n const winner = readWorkerSteerAcknowledgement(eventDir, exact.operationId)\n if (\n winner === undefined ||\n winner.operationId !== exact.operationId ||\n winner.requestDigest !== exact.requestDigest\n ) {\n throw new Error('steer delivery claim conflicts with another operation')\n }\n return false\n}\n\n/** Atomically replace the runtime acknowledgement for one steer operation. @internal */\nexport function writeWorkerSteerAcknowledgement(\n eventDir: string,\n record: WorkerSteerAcknowledgement,\n): void {\n const exact = parseWorkerSteerAcknowledgement(record)\n const request = readWorkerSteerRequest(eventDir, exact.operationId)\n if (request === undefined || request.requestDigest !== exact.requestDigest) {\n throw new Error('steer acknowledgement does not match an admitted request')\n }\n const dir = workerSteerAcknowledgementsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n const file = workerSteerAcknowledgementFile(eventDir, exact.operationId)\n const prior = readWorkerSteerAcknowledgement(eventDir, exact.operationId)\n if (\n prior !== undefined &&\n prior.effect !== 'unknown' &&\n canonicalCandidateDigest(prior) !== canonicalCandidateDigest(exact)\n ) {\n throw new Error(`steer operation '${exact.operationId}' already has a terminal acknowledgement`)\n }\n writeAtomicDurableFile(file, `${JSON.stringify(exact, null, 2)}\\n`)\n}\n\n/** The directory holding every cancellation artifact of one run (request inbox + acknowledgements). */\nexport function workerCancellationsDir(eventDir: string): string {\n return join(eventDir, 'cancellations')\n}\n\n/**\n * The durable cancel-request inbox of one run — one NDJSON line per {@link WorkerCancelRequest}.\n * It stays append-only so independent operations retain admission order and readers can skip a\n * partial trailing line. `appendDurableFile` uses O_APPEND, one write, file fsync, and directory\n * fsync; single-record acknowledgements use atomic replacement instead.\n */\nexport function workerCancelRequestsFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'requests.ndjson')\n}\n\n/**\n * The acknowledgement file for one cancel operation. The filename is a sanitized stem of the\n * `operationId`; the record inside carries the exact id, and readers verify it so two distinct\n * ids that sanitize to one stem fail loud instead of answering for each other.\n */\nexport function workerCancellationFile(eventDir: string, operationId: string): string {\n return join(workerCancellationsDir(eventDir), `${safeOperationFile(operationId)}.json`)\n}\n\nfunction safeOperationFile(operationId: string): string {\n const safe = operationId.replace(/[^A-Za-z0-9._-]/g, '_')\n if (safe.length === 0) throw new Error('cancel operationId is empty')\n return safe\n}\n\n/** Read every valid cancel request in the run's cancellation inbox. Corrupt lines are skipped. */\nexport function readWorkerCancelRequests(eventDir: string): WorkerCancelRequest[] {\n const dir = workerCancellationsDir(eventDir)\n const file = workerCancelRequestsFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'cancel request')\n if (!existsSync(file)) return []\n const out: WorkerCancelRequest[] = []\n const byOperationId = new Map<string, WorkerCancelRequest>()\n let raw = ''\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return out\n }\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n let parsed: Partial<WorkerCancelRequest>\n try {\n parsed = JSON.parse(trimmed) as Partial<WorkerCancelRequest>\n } catch {\n // Ignore partial or corrupt input lines; later valid lines still matter.\n continue\n }\n if (!isWorkerCancelRequest(parsed)) continue\n const prior = byOperationId.get(parsed.operationId)\n if (prior !== undefined) {\n assertSameWorkerCancelRequest(prior, parsed)\n } else {\n byOperationId.set(parsed.operationId, parsed)\n out.push(parsed)\n }\n }\n return out\n}\n\n/**\n * Read the acknowledgement for one cancel operation. `undefined` when the runtime has not\n * answered. A record whose stored `operationId` differs from the requested one is a filename\n * collision between two sanitized ids — fail loud rather than return another operation's answer.\n */\nexport function readWorkerCancellation(\n eventDir: string,\n operationId: string,\n): WorkerCancellation | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = workerCancellationFile(eventDir, operationId)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'cancel acknowledgement')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as WorkerCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `cancel acknowledgement collision: '${file}' holds operation '${parsed.operationId}', ` +\n `not '${operationId}' — use operation ids that stay distinct after filename sanitization`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write one acknowledgement record. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\n *\n * @internal The runtime acknowledger is the only intended writer; clients read via\n * {@link readWorkerCancellation} or {@link cancelWorker}.\n */\nexport function writeWorkerCancellation(eventDir: string, record: WorkerCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n const file = workerCancellationFile(eventDir, record.operationId)\n assertNoSymlinkDescendant(eventDir, file, 'cancel acknowledgement')\n writeAtomicDurableFile(file, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\n}\n\n/**\n * Request the cancellation of ONE worker, idempotently, and return the operation's current\n * durable state.\n *\n * The write half of the acknowledged-cancellation contract (`writeWorkerSteer` is the steer\n * analog): append the request to the run's cancellation inbox, where the OWNING manager's\n * acknowledger (its turn loop — the root for label/profile references, the parent manager for an\n * exact node id at any depth) applies it — aborting exactly that worker's subtree and recording\n * what it proved. This function never applies the cancellation itself; writing a\n * request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists, it is\n * returned AS-IS and nothing is appended — repeating one operation can never apply twice. A\n * retry that changes the worker, source, or reason fails closed. A request the runtime has not\n * answered yet returns `effect: 'unknown'` (never a success); call again with the same\n * `operationId` — or `readWorkerCancellation` — to read the acknowledged result after a\n * reconnect.\n */\nexport function cancelWorker(\n eventDir: string,\n worker: string,\n operationId: string,\n options: { readonly reason?: string; readonly source?: string } = {},\n): WorkerCancellation {\n const ref = worker.trim()\n if (!ref) throw new Error('cancelWorker: worker reference is empty')\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelWorker: operationId is empty')\n const pending = readWorkerCancelRequests(eventDir).find((r) => r.operationId === opId)\n const candidate = {\n operationId: opId,\n worker: ref,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (pending !== undefined) assertSameWorkerCancelRequest(pending, candidate)\n const acknowledged = readWorkerCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelWorker: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertWorkerCancellationMatchesCandidate(acknowledged, candidate)\n return acknowledged\n }\n const source = options.source ?? 'human'\n const request: WorkerCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n worker: ref,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (!pending) {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n const file = workerCancelRequestsFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'cancel request')\n appendDurableFile(file, `${JSON.stringify(request)}\\n`, { mode: 0o600 })\n appendWorkerControlEvent(eventDir, ref, {\n kind: 'cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n })\n }\n return {\n operationId: opId,\n worker: request.worker,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n terminated: [],\n }\n}\n\ntype WorkerCancelRequestCandidate = Omit<WorkerCancelRequest, 'at'>\n\nfunction assertSameWorkerCancelRequest(\n existing: WorkerCancelRequest,\n candidate: WorkerCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelWorker: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.worker !== candidate.worker) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(worker '${existing.worker}' != '${candidate.worker}')`,\n )\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction assertWorkerCancellationMatchesCandidate(\n existing: WorkerCancellation,\n candidate: WorkerCancelRequestCandidate,\n): void {\n if (existing.worker !== candidate.worker) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(worker '${existing.worker}' != '${candidate.worker}')`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction isWorkerCancelRequest(value: Partial<WorkerCancelRequest>): value is WorkerCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n typeof value.worker === 'string' &&\n value.worker.length > 0 &&\n (value.reason === undefined || typeof value.reason === 'string')\n )\n}\n\nexport function appendWorkerControlEvent(\n eventDir: string,\n label: string,\n event: Record<string, unknown>,\n): void {\n try {\n fenceRunWrite(() => {\n mkdirSync(supervisorWorkersDir(eventDir), { recursive: true })\n appendFileSync(\n workerControlLogFile(eventDir, label),\n `${JSON.stringify({ at: new Date().toISOString(), label, ...event })}\\n`,\n 'utf8',\n )\n })\n } catch {\n // Control logging is best-effort; the inbox write above is the durable part.\n }\n}\n\nfunction workerSteerRequestDigest(value: {\n readonly operationId: string\n readonly worker: string\n readonly message: string\n readonly source: string\n readonly interrupt: boolean\n}): Sha256Digest {\n return canonicalCandidateDigest({ kind: 'worker-steer-request.v1', ...value })\n}\n\nfunction operationFileHash(operationId: string): string {\n const id = operationId.trim()\n if (!id) throw new Error('steer operationId is empty')\n return sha256(id)\n}\n\nfunction admitSteerRequest(\n file: string,\n request: WorkerSteerRequest,\n): { readonly request: WorkerSteerRequest; readonly replayed: boolean } {\n const existing = readWorkerSteerRequestFile(file)\n if (existing !== undefined) {\n assertSameSteerRequest(existing, request)\n return { request: existing, replayed: true }\n }\n if (publishExclusiveDurableFile(file, `${JSON.stringify(request, null, 2)}\\n`)) {\n return { request, replayed: false }\n }\n const winner = readWorkerSteerRequestFile(file)\n if (winner === undefined) {\n throw new Error('steer request publication lost its winner')\n }\n assertSameSteerRequest(winner, request)\n return { request: winner, replayed: true }\n}\n\nfunction readWorkerSteerRequest(\n eventDir: string,\n operationId: string,\n): WorkerSteerRequest | undefined {\n const file = workerSteerRequestFile(eventDir, operationId)\n assertNoSymlinkDescendant(eventDir, file, 'steer request')\n const request = readWorkerSteerRequestFile(file)\n if (request !== undefined && request.operationId !== operationId) {\n throw new Error('steer request file belongs to another operation')\n }\n return request\n}\n\nfunction readWorkerSteerRequestFile(file: string): WorkerSteerRequest | undefined {\n if (!existsSync(file)) return undefined\n return parseWorkerSteerRequest(JSON.parse(readFileSync(file, 'utf8')))\n}\n\nfunction parseWorkerSteerRequest(value: unknown): WorkerSteerRequest {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('steer request is malformed')\n }\n const request = value as Partial<WorkerSteerRequest>\n if (\n request.schemaVersion !== 1 ||\n typeof request.operationId !== 'string' ||\n request.operationId.length === 0 ||\n typeof request.requestDigest !== 'string' ||\n typeof request.at !== 'string' ||\n typeof request.source !== 'string' ||\n request.source.length === 0 ||\n typeof request.worker !== 'string' ||\n request.worker.length === 0 ||\n typeof request.message !== 'string' ||\n request.message.trim().length === 0 ||\n typeof request.interrupt !== 'boolean'\n ) {\n throw new Error('steer request is malformed')\n }\n const exact = request as WorkerSteerRequest\n const expected = workerSteerRequestDigest({\n operationId: exact.operationId,\n worker: exact.worker,\n message: exact.message,\n source: exact.source,\n interrupt: exact.interrupt,\n })\n if (exact.requestDigest !== expected) throw new Error('steer request digest does not match')\n return exact\n}\n\nfunction parseWorkerSteerAcknowledgement(value: unknown): WorkerSteerAcknowledgement {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('steer acknowledgement is malformed')\n }\n const record = value as Partial<WorkerSteerAcknowledgement>\n if (\n record.schemaVersion !== 1 ||\n typeof record.operationId !== 'string' ||\n record.operationId.length === 0 ||\n typeof record.requestDigest !== 'string' ||\n typeof record.worker !== 'string' ||\n record.worker.length === 0 ||\n (record.effect !== 'unknown' &&\n record.effect !== 'delivered' &&\n record.effect !== 'not_live' &&\n record.effect !== 'unsupported' &&\n record.effect !== 'refused') ||\n typeof record.requestedAt !== 'string' ||\n typeof record.observedAt !== 'string' ||\n typeof record.detail !== 'string'\n ) {\n throw new Error('steer acknowledgement is malformed')\n }\n return record as WorkerSteerAcknowledgement\n}\n\nfunction assertSameSteerRequest(existing: WorkerSteerRequest, candidate: WorkerSteerRequest): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error('steer operation file collision')\n }\n if (existing.requestDigest !== candidate.requestDigest) {\n throw new Error(\n `writeWorkerSteer: operation '${candidate.operationId}' conflicts with its admitted request`,\n )\n }\n}\n","/**\n * The root manager's own provider stream, retained where Runtime owns it.\n *\n * Measured motive (agent-runtime#1233): a CHILD's full event stream — reasoning, text,\n * and tool parts, 28k to 76k reasoning characters per child — is retained in the blob its\n * `settled` record names as `outRef`. The ROOT's stream reached nobody: `driveHarnessFromBackend`\n * drained the root executor for accounting and discarded every `progress` event, and on a\n * `winner` run `result.outRef` is the SELECTED CHILD's artifact, not the root's. A root that died\n * at its join barrier (fourier-e, 63 children) left a 607-byte `failure.json` and nothing it\n * thought; the Lab's only transcript of a root was a post-hoc scrape of the harness's own\n * database.\n *\n * `<runDir>/root-stream.jsonl` is the record: one JSONL line per `ExecutorProgressEvent`, written\n * AS IT ARRIVES, so a root whose process is killed mid-turn keeps every line already written. The\n * file itself is the evidence; the receipt (`ref`, the content address of the file's bytes, and\n * `events`, its committed line count) is what `result.json` and `failure.json` carry. The winner's\n * `outRef` keeps its meaning; this is a separate reference.\n *\n * Durability boundary: each line is written synchronously to an `O_APPEND` descriptor before the\n * next event is drained, and the file is fsynced at every drive-attempt boundary and at close, not\n * per line. An fsync per line cost 7.1 ms per event over\n * 1,000 events and 8.1 ms over 5,000 (~80 s for a root emitting ten thousand text deltas, all of\n * it serialized inside the drain loop that also meters the budget); an async `FileHandle.write`\n * still cost 0.9 to 1.1 ms per line in the thread pool the children's journal writes share; a\n * `writeSync` costs 6 µs. A process kill loses nothing written; only a kernel crash or power\n * loss can drop lines written since the last fsync, and the reader's torn-tail rule keeps such a\n * file readable.\n *\n * The bridge wire carries text and tool calls only: cli-bridge's SSE frames decode\n * `delta.content` and `delta.tool_calls`, never a reasoning delta. A bridge-placed root's retained\n * stream is therefore text plus tool calls; reasoning arrives only on the provider/sandbox path,\n * which projects `message.part.updated` reasoning parts to `reasoning_delta`.\n */\n\nimport { createHash } from 'node:crypto'\nimport { closeSync, constants as fsConstants, fsyncSync, openSync, writeSync } from 'node:fs'\nimport { mkdir } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport { isNoEntError, prepareJsonlAppend, readCommittedJsonLines } from '../../durable/jsonl-file'\nimport { captureRunWriteContext, fenceRunWrite } from '../../durable/run-fence'\nimport { errorMessage } from '../util'\nimport { assertNoSymlinkDescendant } from './durable-file'\nimport { safeWorkerFile } from './run-layout'\nimport type { ExecutorProgressEvent, RootStreamReceipt } from './types'\n\nexport type { RootStreamReceipt } from './types'\n\n/** The root stream: one JSONL line per progress event the root's executor observed. */\nexport const ROOT_STREAM_FILE = 'root-stream.jsonl'\n\n/** Each other node's stream, in the same record shape, keyed by its node id. A name the filename\n * rules changed carries a digest of the id, so `a:b` and `a_b` never share a file. */\nexport function nodeStreamFile(nodeId: string): string {\n const safe = safeWorkerFile(nodeId)\n const name =\n safe === nodeId\n ? safe\n : `${safe}.${createHash('sha256').update(nodeId).digest('hex').slice(0, 12)}`\n return `streams/${name}.jsonl`\n}\n\n/** One line of `root-stream.jsonl`. */\nexport type RootStreamRecord = {\n /** 1-based position in the file, continuing across drive attempts and across processes. */\n readonly seq: number\n /** ISO instant the line was appended, from the run's own clock. */\n readonly at: string\n /** The 1-based drive attempt of the root that produced it: a driver retry or re-prompt\n * re-enters the harness and continues the same file with the next attempt number. */\n readonly attempt: number\n} & (\n | { readonly event: ExecutorProgressEvent }\n | {\n /** The event could not be written as JSON; its kind and the reason stand in so the gap\n * is recorded in the file itself instead of silently narrowing the stream. */\n readonly dropped: { readonly kind: ExecutorProgressEvent['kind']; readonly reason: string }\n }\n)\n\n/** The append-only writer one root drive holds. */\nexport interface RootStreamSink {\n /** Mark the next drive attempt; opens the file on the first call. */\n beginAttempt(): Promise<void>\n /** Append one event; the line is in the kernel when this returns. */\n append(event: ExecutorProgressEvent): void\n /** Fsync, close the writer, and return the receipt, or `undefined` when no attempt ever began. */\n close(): Promise<RootStreamReceipt | undefined>\n}\n\n/** Create the writer for `<runDir>/root-stream.jsonl`, or for another `file` in the run directory.\n * Nothing touches disk until the first `beginAttempt`, so a run whose root never drives leaves no\n * file and no receipt. The root numbers attempts per process; a node stream, whose writer closes\n * after every execution attempt, sets `continueAttempts` so a later attempt never reuses a number. */\nexport function createRootStreamSink(\n runDir: string,\n now: () => number,\n file = ROOT_STREAM_FILE,\n options: { readonly continueAttempts?: boolean } = {},\n): RootStreamSink {\n const withClaim = captureRunWriteContext()\n const dir = resolve(runDir)\n const path = resolve(dir, file)\n let fd: number | undefined\n let attempt = 0\n let seq = 0\n let closed = false\n\n const openOnce = async (): Promise<void> => {\n if (fd !== undefined) return\n await mkdir(dirname(path), { recursive: true })\n assertNoSymlinkDescendant(dir, path, 'root stream')\n // A resumed run continues the same file. Recovery scans the tail once, so a torn line from a\n // process that died mid-write is truncated rather than followed by a record it would corrupt.\n const needsSeparator = await prepareJsonlAppend(path)\n seq = 0\n let priorAttempts = 0\n for await (const record of readCommittedJsonLines<RootStreamRecord>(path, {\n allowMissing: true,\n })) {\n seq += 1\n priorAttempts = Math.max(priorAttempts, record.attempt)\n }\n // Text from different attempts never merges when their numbers stay distinct.\n if (options.continueAttempts === true) attempt += priorAttempts\n fd = fenceRunWrite(() => {\n const writer = openSync(\n path,\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n 0o600,\n )\n try {\n if (needsSeparator) writeLine(writer, '')\n return writer\n } catch (error) {\n closeSync(writer)\n throw error\n }\n })\n }\n\n return {\n async beginAttempt() {\n return withClaim(async () => {\n if (closed) throw new Error('root stream: beginAttempt after close')\n attempt += 1\n // A retry re-enters the harness after the previous attempt's lines; make them durable\n // before the next attempt appends after them.\n const writer = fd\n if (writer !== undefined) fenceRunWrite(() => fsyncSync(writer))\n await openOnce()\n })\n },\n append(event) {\n return withClaim(() =>\n fenceRunWrite(() => {\n if (closed) throw new Error('root stream: append after close')\n if (fd === undefined) throw new Error('root stream: append before beginAttempt')\n const at = new Date(now()).toISOString()\n const record = { seq: seq + 1, at, attempt, event }\n // A progress payload is JSON the wire already parsed, so this branch is a guard, not a\n // path: a value JSON cannot encode (a BigInt, a cycle, a hostile `toJSON`) is recorded as\n // a dropped line so the turn continues and the file still says something was lost.\n let line: string | undefined\n try {\n line = JSON.stringify(record)\n } catch (error) {\n line = JSON.stringify({\n seq: seq + 1,\n at,\n attempt,\n dropped: { kind: event.kind, reason: errorMessage(error) },\n })\n }\n if (line === undefined) {\n line = JSON.stringify({\n seq: seq + 1,\n at,\n attempt,\n dropped: { kind: event.kind, reason: 'event serialized to nothing' },\n })\n }\n writeLine(fd, line)\n seq += 1\n }),\n )\n },\n async close() {\n return withClaim(async () => {\n if (closed) throw new Error('root stream: closed twice')\n closed = true\n const writer = fd\n if (writer === undefined) return undefined\n try {\n fenceRunWrite(() => fsyncSync(writer))\n } finally {\n closeSync(writer)\n fd = undefined\n }\n return readRootStreamReceipt(dir, file)\n })\n },\n }\n}\n\n/** `writeSync` may legally make a short write; loop until the whole line and its newline land. */\nfunction writeLine(fd: number, line: string): void {\n const bytes = Buffer.from(`${line}\\n`, 'utf8')\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw new Error(`root stream: append made no progress at byte ${offset}`)\n offset += written\n }\n}\n\n/**\n * The receipt for the root stream a run directory holds, recomputed from the file's bytes, or\n * `undefined` when the directory holds none. This is what a run that never settled — a root that\n * died mid-turn — gets on its failure record, and it equals what `close()` returned for a run\n * that did.\n */\nexport async function readRootStreamReceipt(\n runDir: string,\n file = ROOT_STREAM_FILE,\n): Promise<RootStreamReceipt | undefined> {\n const path = resolve(runDir, file)\n const hash = createHash('sha256')\n let events = 0\n try {\n for await (const _record of readCommittedJsonLines<RootStreamRecord>(path, {\n onBytes: (bytes) => {\n hash.update(bytes)\n },\n })) {\n events += 1\n }\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return Object.freeze({ ref: `sha256:${hash.digest('hex')}`, events })\n}\n\n/** Every committed line of the root stream, in order, or `undefined` when there is no file. A\n * torn final line from a process that died mid-write is not a record and is left out. */\nexport async function readRootStream(runDir: string): Promise<RootStreamRecord[] | undefined> {\n const path = resolve(runDir, ROOT_STREAM_FILE)\n const records: RootStreamRecord[] = []\n try {\n for await (const record of readCommittedJsonLines<RootStreamRecord>(path)) records.push(record)\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return records\n}\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;CAChG,MAAM,eAAe,cAAc,OAAO,eAAe,iBAAiB,KAAK;CAC/E,MAAM,wBAAwB,cAC5B,OAAO,yBACP,2BACA,KACF;CACA,MAAM,wBACJ,OAAO,6BAA6B,KAAA,IAChC,KAAA,IACA,cAAc,OAAO,0BAA0B,4BAA4B,KAAK;CACtF,IAAI,oBAAoB,aACtB,MAAM,IAAI,gBAAgB,GAAG,MAAM,2CAA2C;CAEhF,IAAI,wBAAwB,cAC1B,MAAM,IAAI,gBAAgB,GAAG,MAAM,gDAAgD;CAErF,OAAO;EACL;EACA;EACA;EACA;EACA,GAAI,0BAA0B,KAAA,IAAY,CAAC,IAAI,EAAE,sBAAsB;CACzE;AACF;;AAwCA,MAAM,oBAAoB;;;;;;;;;;;;;;;AAgB1B,MAAM,wBAA6C,UAAU;CAC3D,IAAI,OAAO,MAAM,QAAQ,EAAE,MAAM,OAAO,OAAO,KAAA;CAC/C,MAAM,WAAWA,YAAY,MAAM,IAAI;CACvC,MAAM,OACJ,UAAU,SAAS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