@tangle-network/agent-runtime 3.0.41 → 3.0.43
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-CiM6hSrn.js → activation-1YUy4GWu.js} +2 -2
- package/dist/{activation-CiM6hSrn.js.map → activation-1YUy4GWu.js.map} +1 -1
- package/dist/{activation-C1_GUwX8.d.ts → activation-CiUbW1QE.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{coordination-manager-_PcKOR-S.js → coordination-manager-DXOwLu9T.js} +4 -4
- package/dist/{coordination-manager-_PcKOR-S.js.map → coordination-manager-DXOwLu9T.js.map} +1 -1
- package/dist/{delegate-VmOpqr4q.js → delegate-CAvTMCk0.js} +2 -2
- package/dist/{delegate-VmOpqr4q.js.map → delegate-CAvTMCk0.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +6 -6
- package/dist/{graph-C3K0vEg-.js → graph-C7Xthj-4.js} +5 -5
- package/dist/{graph-C3K0vEg-.js.map → graph-C7Xthj-4.js.map} +1 -1
- package/dist/{improve-DhTBR1p-.js → improve-BZpoezFh.js} +6 -6
- package/dist/{improve-DhTBR1p-.js.map → improve-BZpoezFh.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +8 -8
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +4 -4
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +11 -11
- package/dist/{loop-runner-BCNdBh8P.js → loop-runner-BchibTTn.js} +2 -2
- package/dist/{loop-runner-BCNdBh8P.js.map → loop-runner-BchibTTn.js.map} +1 -1
- package/dist/{loop-runner-DMBWRkx0.d.ts → loop-runner-Dmjf2IY6.d.ts} +2 -2
- 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 +5 -5
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-wJp8ECNK.js → provision-supervisor-BtDnk11d.js} +4 -4
- package/dist/{provision-supervisor-wJp8ECNK.js.map → provision-supervisor-BtDnk11d.js.map} +1 -1
- package/dist/{run-cancellation-Xh0hv_aO.js → run-cancellation-DEW04dun.js} +2 -2
- package/dist/{run-cancellation-Xh0hv_aO.js.map → run-cancellation-DEW04dun.js.map} +1 -1
- package/dist/{runtime-C_bXuIBi.js → runtime-CKoChP6L.js} +11 -11
- package/dist/{runtime-C_bXuIBi.js.map → runtime-CKoChP6L.js.map} +1 -1
- package/dist/{scope-D04GkJ6P.js → scope-Bg1uCsPR.js} +9 -4
- package/dist/scope-Bg1uCsPR.js.map +1 -0
- package/dist/{search-executor-Dzhi0WRa.js → search-executor-CJ5y2-b8.js} +3 -3
- package/dist/{search-executor-Dzhi0WRa.js.map → search-executor-CJ5y2-b8.js.map} +1 -1
- package/dist/{server-BQhawXPP.js → server-zdmmyP7r.js} +3 -3
- package/dist/{server-BQhawXPP.js.map → server-zdmmyP7r.js.map} +1 -1
- package/dist/{structural-rollout-xXWwKM4G.js → structural-rollout-CH9b7K9B.js} +3 -3
- package/dist/{structural-rollout-xXWwKM4G.js.map → structural-rollout-CH9b7K9B.js.map} +1 -1
- package/dist/{supervise-Dh8Mp3v8.js → supervise-472pyfgQ.js} +43 -37
- package/dist/supervise-472pyfgQ.js.map +1 -0
- package/dist/{supervision-discovery-CcTLSYff.js → supervision-discovery-CD350Iar.js} +2 -2
- package/dist/{supervision-discovery-CcTLSYff.js.map → supervision-discovery-CD350Iar.js.map} +1 -1
- package/dist/{supervisor-BQz8lkcd.js → supervisor-BDOWzyCC.js} +45 -15
- package/dist/supervisor-BDOWzyCC.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +11 -11
- package/dist/{top-web-D-QEIh-x.js → top-web-CNTJBqFy.js} +4 -4
- package/dist/{top-web-D-QEIh-x.js.map → top-web-CNTJBqFy.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-CRCOBzGj.d.ts → types-tG_tps7N.d.ts} +4 -1
- package/package.json +1 -1
- package/dist/scope-D04GkJ6P.js.map +0 -1
- package/dist/supervise-Dh8Mp3v8.js.map +0 -1
- package/dist/supervisor-BQz8lkcd.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"scope-D04GkJ6P.js","names":["awaitAbortable","plainRecord","describe","plainRecord","nextTurn","sha256Bytes","unavailable","DENY","sha256Bytes","awaitAbortable","awaitAbortable","awaitAbortable","awaitAbortable","assertDigest","awaitAbortable","awaitAbortable","awaitAbortable","assertDigest","stableText","unavailable","fsConstants"],"sources":["../src/runtime/turn-input.ts","../src/runtime/supervise/abortable.ts","../src/runtime/retained-run-binding.ts","../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/runtime/supervise/flow-brain.ts","../src/runtime/supervise/executable-spec.ts","../src/runtime/provider-observation-snapshot.ts","../src/runtime/supervise/materialization.ts","../src/runtime/supervise/seat-chain.ts","../src/runtime/supervise/node-status.ts","../src/runtime/supervise/progress.ts","../src/runtime/retained-harness-transcript.ts","../src/runtime/harness-transcript.ts","../src/sanitize.ts","../src/otel-export.ts","../src/mcp/trace-propagation.ts","../src/runtime/supervise/worker-trace.ts","../src/runtime/supervise/worker-slots.ts","../src/runtime/provider-workspace-retention.ts","../src/runtime/retained-interactive-lifecycle.ts","../src/durable/observer-journal.ts","../src/runtime/interaction-capabilities.ts","../src/runtime/retained-context-transfer.ts","../src/runtime/retained-interactive-delegation.ts","../src/runtime/retained-run-control.ts","../src/runtime/retained-run-events.ts","../src/runtime/retained-run-native-continuation.ts","../src/runtime/retained-run-handle.ts","../src/runtime/retained-run-intent.ts","../src/runtime/retained-run-start.ts","../src/runtime/retained-native-stop.ts","../src/runtime/supervise/workspace-checkpoint.ts","../src/durable/spawn-journal/event-index.ts","../src/durable/spawn-journal/result-blob-store.ts","../src/runtime/supervise/tree-key.ts","../src/durable/spawn-journal/settlement-evidence.ts","../src/durable/spawn-journal/tree-view.ts","../src/durable/spawn-journal/spawn-forest.ts","../src/runtime/supervise/retained-owner-checkpoint-requests.ts","../src/runtime/supervise/retained-owner-checkpoint-capture.ts","../src/runtime/supervise/retained-owner-state.ts","../src/runtime/supervise/retained-owner-checkpoint-rotation.ts","../src/runtime/supervise/retained-owner-evidence.ts","../src/runtime/supervise/retained-owner-environment-recovery.ts","../src/runtime/supervise/retained-owner-turn-lifecycle.ts","../src/runtime/supervise/retained-owner-invocation.ts","../src/runtime/supervise/retained-owner-release.ts","../src/mcp/tools/spawn-resource-paths.ts","../src/runtime/supervise/retained-owner-resource-reader.ts","../src/runtime/supervise/retained-owner-seat-switch.ts","../src/runtime/supervise/scope-capabilities.ts","../src/runtime/supervise/dispatch.ts","../src/runtime/supervise/scope-identity.ts","../src/runtime/supervise/scope-observation.ts","../src/runtime/supervise/provider-visible-profile.ts","../src/runtime/supervise/scope-owner-materialization.ts","../src/runtime/supervise/scope-owner-meter.ts","../src/runtime/supervise/terminal-record.ts","../src/runtime/supervise/scope-settlement.ts","../src/runtime/supervise/scope-settlement-cursor.ts","../src/runtime/supervise/scope-child-materialization.ts","../src/runtime/supervise/scope-child-retention.ts","../src/durable/spawn-journal/record-events.ts","../src/durable/spawn-journal/journal-store.ts","../src/runtime/retained-interactive-handle.ts","../src/runtime/retained-interactive.ts","../src/runtime/supervise/worker-interactive.ts","../src/runtime/supervise/interactive-admission.ts","../src/runtime/supervise/scope-contract.ts","../src/runtime/supervise/trace-evidence.ts","../src/runtime/supervise/scope-child-attempt.ts","../src/runtime/supervise/scope-execution.ts","../src/durable/spawn-journal/replay.ts","../src/runtime/supervise/recover-executors.ts","../src/runtime/supervise/scope-nesting.ts","../src/runtime/supervise/run-layout.ts","../src/runtime/supervise/root-stream.ts","../src/runtime/supervise/worker-events.ts","../src/runtime/supervise/scope-child-start.ts","../src/runtime/supervise/scope-key-registry.ts","../src/runtime/supervise/scope-spawn.ts","../src/runtime/supervise/scope-teardown.ts","../src/runtime/supervise/scope-workers.ts","../src/runtime/supervise/scope-construction.ts"],"sourcesContent":["import {\n AgentExactRunControlRefSchema,\n type ContextTransferRequest,\n canonicalAgentProfileDigest,\n type InputPart,\n} from '@tangle-network/agent-interface'\nimport type { AgentTurnInput } from '@tangle-network/agent-interface/environment-provider'\nimport type { PromptInputPart, PromptOptions } from '@tangle-network/sandbox'\n\n/**\n * Copy only fields that describe a new provider turn.\n *\n * Session, replay, continuation, and transfer coordinates are runtime-owned\n * and are injected by the caller that owns that lifecycle. Keeping this copy\n * explicit also makes JavaScript callers subject to the same boundary.\n */\nexport function freshTurnInput(\n input: AgentTurnInput,\n runtime: {\n readonly turnId: string\n readonly detach: true\n readonly sessionId?: string\n readonly executionId?: string\n readonly contextTransfer?: ContextTransferRequest\n },\n): AgentTurnInput {\n const fresh: AgentTurnInput = {\n ...(input.prompt === undefined ? {} : { prompt: input.prompt }),\n ...(input.parts === undefined ? {} : { parts: input.parts }),\n ...(input.model === undefined ? {} : { model: input.model }),\n ...(input.profile === undefined ? {} : { profile: input.profile }),\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n ...(input.context === undefined ? {} : { context: input.context }),\n ...(input.interactions === undefined ? {} : { interactions: input.interactions }),\n ...(input.providerOptions === undefined ? {} : { providerOptions: input.providerOptions }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n turnId: runtime.turnId,\n detach: runtime.detach,\n ...(runtime.sessionId === undefined ? {} : { sessionId: runtime.sessionId }),\n ...(runtime.executionId === undefined ? {} : { executionId: runtime.executionId }),\n ...(runtime.contextTransfer === undefined ? {} : { contextTransfer: runtime.contextTransfer }),\n }\n return fresh\n}\n\n/** Project canonical turn parts onto the Sandbox prompt vocabulary once. */\nexport function promptFromAgentTurnInput(input: AgentTurnInput): string | PromptInputPart[] {\n if (input.parts !== undefined) return input.parts.map(promptPartFromInputPart)\n return input.prompt ?? providerMessageText(input.providerOptions) ?? ''\n}\n\n/** Project canonical turn controls onto the Sandbox prompt options once. */\nexport function promptOptionsFromAgentTurnInput(input: AgentTurnInput): PromptOptions {\n const providerBackend =\n input.providerOptions?.backend &&\n typeof input.providerOptions.backend === 'object' &&\n !Array.isArray(input.providerOptions.backend)\n ? (input.providerOptions.backend as NonNullable<PromptOptions['backend']>)\n : undefined\n if (\n input.profile !== undefined &&\n providerBackend?.profile !== undefined &&\n canonicalAgentProfileDigest(input.profile) !==\n canonicalAgentProfileDigest(providerBackend.profile)\n ) {\n throw Object.assign(new Error('provider turn contains conflicting AgentProfiles'), {\n name: 'ValidationError',\n })\n }\n const backend = {\n ...(providerBackend ?? {}),\n ...(input.profile === undefined ? {} : { profile: input.profile }),\n ...(input.interactions === undefined ? {} : { interactions: input.interactions }),\n }\n const runControlRef =\n input.controlRef === undefined\n ? undefined\n : AgentExactRunControlRefSchema.parse(input.controlRef)\n return {\n ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }),\n ...(input.model === undefined ? {} : { model: input.model }),\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n ...(input.context === undefined ? {} : { context: input.context }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...(input.executionId === undefined ? {} : { executionId: input.executionId }),\n ...(input.lastEventId === undefined ? {} : { lastEventId: input.lastEventId }),\n ...(input.turnId === undefined ? {} : { turnId: input.turnId }),\n ...(input.detach === undefined ? {} : { detach: input.detach }),\n ...(runControlRef === undefined ? {} : { runControlRef }),\n ...(Object.keys(backend).length === 0 ? {} : { backend }),\n }\n}\n\n/** Read a text fallback from provider-specific conversation options. */\nexport function providerMessageText(\n providerOptions: Record<string, unknown> | undefined,\n): string | undefined {\n const messages = providerOptions?.messages\n if (!Array.isArray(messages)) return undefined\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (!message || typeof message !== 'object' || Array.isArray(message)) continue\n if (!('role' in message) || message.role !== 'user') continue\n if (!('content' in message)) continue\n if (typeof message.content === 'string') return message.content\n }\n return undefined\n}\n\nfunction promptPartFromInputPart(part: InputPart): PromptInputPart {\n if (part.type === 'text' || part.type === 'image') return part\n if (part.content !== undefined || part.path !== undefined) {\n throw new Error(\n 'Sandbox file prompt parts require a URL; inline content and local paths are not representable',\n )\n }\n if (!part.filename || !part.url) {\n throw new Error('Sandbox file prompt parts require both filename and URL')\n }\n return {\n type: 'file',\n filename: part.filename,\n ...(part.mediaType === undefined ? {} : { mediaType: part.mediaType }),\n url: part.url,\n }\n}\n","/** Provenance of an explicit cancellation, preserved through every abort link. */\nexport class RunCancellationReason extends Error {\n constructor(\n readonly source: string,\n reason: string,\n readonly operationId?: string,\n /** Who stopped the run, from the durable cancel request; absent for an in-process abort. */\n readonly operator?: string,\n ) {\n super(reason)\n this.name = 'RunCancellationReason'\n }\n\n override toString(): string {\n return this.message\n }\n}\n\n/**\n * One abort race, and one abort cascade, for the supervision tree.\n *\n * Every layer that can be cancelled needs the same three things: the reason a signal\n * carries, an `AbortError` built from it, and a settle-once race between the work and\n * the signal. Written per layer, each drifts — a listener stops being removed on one\n * path, a late resolution overwrites a cancellation that already won, or a cascade\n * forwards no reason and renames every downstream death to the layer's own fallback.\n *\n * The fallback message is the only thing a layer supplies, so the error still names\n * which layer cancelled.\n */\n\n/**\n * The reason a signal carries, or `fallback` when it states none.\n *\n * A cascade that drops the upstream reason turns every downstream death into its own generic\n * message: the worker's `down` record then says nothing about WHY, which makes a whole class of\n * child mortality undiagnosable from the journal alone.\n */\nexport function abortReason(signal: AbortSignal, fallback: string): unknown {\n const reason = signal.reason\n if (reason instanceof RunCancellationReason) return reason\n if (typeof reason === 'string' && reason.length > 0) return reason\n // `abort()` with no argument sets a DOMException whose message is the platform placeholder\n // (\"This operation was aborted\"), which carries no more information than the generic death it\n // would replace — treat it as reasonless and use the fallback.\n if (reason instanceof Error && reason.name !== 'AbortError' && reason.message.length > 0) {\n return reason.message\n }\n return fallback\n}\n\n/** An `AbortError` carrying the signal's own string reason, or `fallback` when it states none. */\nexport function signalAbortError(signal: AbortSignal, fallback: string): Error {\n const reason = abortReason(signal, fallback)\n const error = new Error(\n reason instanceof Error\n ? reason.message\n : typeof reason === 'string' && reason.length > 0\n ? reason\n : fallback,\n )\n error.name = 'AbortError'\n return error\n}\n\n/** A downstream abort linked to one or more upstream signals. */\ninterface LinkedAbort {\n /** Fires when any source fires, or when {@link LinkedAbort.abort} is called. */\n readonly signal: AbortSignal\n /** Abort this link on its own (teardown, cancellation), carrying `reason`. */\n abort(reason?: unknown): void\n /** Stop listening to the sources. Idempotent; required where a source outlives the link. */\n release(): void\n}\n\n/**\n * Cascade N abort signals into one downstream abort that fires when ANY of them does, carrying\n * that signal's own reason ({@link abortReason}). Node-portable: `AbortSignal.any` needs >=20.3\n * and the package floor is >=20, and it would drop the reason anyway.\n *\n * The one cascade every executor uses, so a reason forwarded here reaches every layer below.\n */\nexport function linkAbort(...sources: ReadonlyArray<AbortSignal>): LinkedAbort {\n const controller = new AbortController()\n const listeners: Array<{ source: AbortSignal; onAbort: () => void }> = []\n const release = (): void => {\n for (const { source, onAbort } of listeners) source.removeEventListener('abort', onAbort)\n listeners.length = 0\n }\n const abort = (reason?: unknown): void => {\n release()\n controller.abort(reason)\n }\n const alreadyAborted = sources.find((source) => source.aborted)\n if (alreadyAborted !== undefined) {\n controller.abort(abortReason(alreadyAborted, 'aborted by parent scope'))\n return { signal: controller.signal, abort, release }\n }\n for (const source of sources) {\n const onAbort = (): void => abort(abortReason(source, 'aborted by parent scope'))\n listeners.push({ source, onAbort })\n source.addEventListener('abort', onAbort, { once: true })\n }\n return { signal: controller.signal, abort, release }\n}\n\n/**\n * Settle `act()` against `signal`. The first outcome wins and the listener is always\n * removed, so neither a late resolution nor a late abort can settle the promise twice.\n * The losing promise stays observed, so a late rejection cannot surface as an unhandled\n * process error.\n *\n * The abort rejection is deferred one microtask so a result the action had ALREADY\n * produced still wins. It does not hand the race to a listener the action registers\n * from inside `act()`: this function subscribes before it calls `act()`, so its own\n * abort handler runs first and settles the promise. A caller that must let the action\n * observe the abort itself has to hold a live promise and await that instead.\n *\n * A synchronous throw from `act()` propagates as the rejection, not as an abort.\n */\nexport async function runAbortable<T>(\n act: () => Promise<T>,\n signal: AbortSignal,\n /** The abort's message when the signal states none, or the abort error itself. */\n fallback: string | (() => unknown),\n): Promise<T> {\n const aborted = () =>\n typeof fallback === 'string' ? signalAbortError(signal, fallback) : fallback()\n if (signal.aborted) throw aborted()\n return await new Promise<T>((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n queueMicrotask(() => {\n if (settled) return\n settled = true\n cleanup()\n reject(aborted())\n })\n }\n signal.addEventListener('abort', onAbort, { once: true })\n let work: Promise<T>\n try {\n work = Promise.resolve(act())\n } catch (error) {\n cleanup()\n reject(error)\n return\n }\n work.then(\n (value) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(value)\n },\n (error) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n","import { isRecord } from '@tangle-network/agent-core'\nimport {\n type AgentExactRunControlRef,\n AgentExactRunControlRefSchema,\n type AgentRunCancellationAcknowledgement,\n AgentRunCancellationAcknowledgementSchema,\n type AgentRunCancellationRequest,\n AgentRunCancellationRequestSchema,\n agentRunCancellationAcknowledgementMatchesRequest,\n agentRunCancellationRequestDigest,\n canonicalCandidateDigest,\n type InteractionResponseCommand,\n type NativeContextBoundaryProof,\n type StreamEvent,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentEvent,\n AgentSession,\n AgentSessionStatus,\n AgentTurnResult,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { runAbortable } from './supervise/abortable'\nimport { armDeadlineTimer } from './supervise/deadline'\nimport { abortError } from './util'\n\nexport function exactSession(\n environment: AgentEnvironment,\n controlRef: AgentExactRunControlRef,\n): { session: AgentSession; controlRef: AgentExactRunControlRef } {\n if (environment.id !== controlRef.environmentId || environment.provider !== controlRef.provider) {\n throw new Error('provider reconstructed a different retained environment')\n }\n if (!environment.session || !controlRef.sessionId) {\n throw new Error('retained run control requires a provider session id')\n }\n const session = environment.session(controlRef.sessionId, { controlRef })\n if (session.id !== controlRef.sessionId) {\n throw new Error('provider reconstructed a different session')\n }\n if (session.controlRef === undefined) {\n throw new Error('provider session did not return its provider-owned run control reference')\n }\n const currentControlRef = AgentExactRunControlRefSchema.parse(session.controlRef)\n if (!sameControlCoordinates(currentControlRef, controlRef)) {\n throw new Error('provider session reconstructed a different retained session')\n }\n if (canonicalCandidateDigest(currentControlRef) !== canonicalCandidateDigest(controlRef)) {\n throw new Error('provider session did not retain the exact run control reference')\n }\n return { session, controlRef: currentControlRef }\n}\n\nexport function sameControlCoordinates(\n left: AgentExactRunControlRef,\n right: AgentExactRunControlRef,\n): boolean {\n return canonicalCandidateDigest(left) === canonicalCandidateDigest(right)\n}\n\nexport function freezeControlRef(controlRef: AgentExactRunControlRef): AgentExactRunControlRef {\n return Object.freeze({ ...AgentExactRunControlRefSchema.parse(controlRef) })\n}\n\nexport function copyControlRef(controlRef: AgentExactRunControlRef): AgentExactRunControlRef {\n return { ...controlRef }\n}\n\nexport function exactControlRef(\n candidate: unknown,\n expected: { provider: string; environmentId: string; sessionId: string },\n): AgentExactRunControlRef {\n if (!candidate) throw new Error('provider dispatch returned no durable run control reference')\n const controlRef = AgentExactRunControlRefSchema.parse(candidate)\n if (\n controlRef.provider !== expected.provider ||\n controlRef.environmentId !== expected.environmentId ||\n controlRef.sessionId !== expected.sessionId\n ) {\n throw new Error('provider dispatch returned control coordinates for another run')\n }\n return controlRef\n}\n\nexport function exactContinuedControlRef(\n candidate: AgentExactRunControlRef,\n initial: AgentExactRunControlRef,\n): AgentExactRunControlRef {\n const controlRef = AgentExactRunControlRefSchema.parse(candidate)\n if (\n controlRef.provider !== initial.provider ||\n controlRef.environmentId !== initial.environmentId ||\n controlRef.sessionId !== initial.sessionId\n ) {\n throw new Error('provider continuation advanced to another retained session')\n }\n if (controlRef.runId === initial.runId && controlRef.executionId === initial.executionId) {\n throw new Error('provider continuation did not return a new exact run execution')\n }\n return controlRef\n}\n\nexport function assertInteractionBinding(\n controlRef: AgentExactRunControlRef,\n command: InteractionResponseCommand,\n): void {\n // This digest identifies the interaction request, not the retained turn.\n // The inner provider can differ from the outer control provider. The provider validates\n // the unchanged binding against its durable interaction record.\n if (\n command.binding.runId !== controlRef.runId ||\n command.binding.environmentId !== controlRef.environmentId ||\n command.binding.sessionId !== controlRef.sessionId ||\n command.binding.executionId !== controlRef.executionId\n ) {\n throw new Error('interaction response command does not target this retained run')\n }\n}\n\nexport function assertBoundaryBinding(\n controlRef: AgentExactRunControlRef,\n proof: NativeContextBoundaryProof,\n): void {\n if (\n proof.runId !== controlRef.runId ||\n proof.provider !== controlRef.provider ||\n proof.environmentId !== controlRef.environmentId ||\n proof.sessionId !== controlRef.sessionId ||\n proof.executionId !== controlRef.executionId ||\n proof.requestDigest !== controlRef.requestDigest\n ) {\n throw new Error('native context proof does not identify this retained run')\n }\n}\n\nexport function assertSequence(value: unknown, label: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label} must be a non-negative safe integer`)\n }\n}\n\nexport function assertResultBinding(\n controlRef: AgentExactRunControlRef,\n result: AgentTurnResult,\n): void {\n if (result.sessionId !== controlRef.sessionId) {\n throw new Error('provider returned a result for another retained session')\n }\n const metadata = result.metadata\n if (controlRef.executionId !== undefined && metadata?.executionId !== controlRef.executionId) {\n throw new Error('provider returned a result for another retained execution')\n }\n if (metadata?.runId !== controlRef.runId) {\n throw new Error('provider returned a result for another retained run')\n }\n if (metadata?.requestDigest !== controlRef.requestDigest) {\n throw new Error('provider returned a result for another retained request')\n }\n}\n\ninterface ExactCancelOptions {\n readonly signal?: AbortSignal\n}\n\nexport class RetainedRunProviderContractError extends Error {\n readonly code: string\n\n constructor(message: string, options: { readonly code?: string; readonly cause?: unknown } = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause })\n this.name = 'RetainedRunProviderContractError'\n this.code = options.code ?? 'RETAINED_RUN_PROVIDER_CONTRACT_ERROR'\n }\n}\n\nexport function cancellationRequest(\n controlRef: AgentExactRunControlRef,\n operationId: string,\n reason?: string,\n): AgentRunCancellationRequest {\n const material = {\n operationId,\n run: AgentExactRunControlRefSchema.parse(controlRef),\n ...(reason === undefined ? {} : { reason }),\n }\n return AgentRunCancellationRequestSchema.parse({\n ...material,\n requestDigest: agentRunCancellationRequestDigest(material),\n })\n}\n\nexport async function exactSessionCancel(\n session: AgentSession,\n request: AgentRunCancellationRequest,\n options: ExactCancelOptions,\n): Promise<AgentRunCancellationAcknowledgement> {\n if (!session.cancelRun) {\n throw new Error('provider session does not expose durable cancellation operations')\n }\n const acknowledgement: unknown = await awaitAbortable(\n Promise.resolve().then(() => session.cancelRun!(request, options)),\n options.signal,\n )\n let exactAcknowledgement: AgentRunCancellationAcknowledgement\n try {\n exactAcknowledgement = AgentRunCancellationAcknowledgementSchema.parse(acknowledgement)\n } catch {\n throw new RetainedRunProviderContractError(\n 'provider returned an invalid retained cancellation acknowledgement',\n )\n }\n if (!agentRunCancellationAcknowledgementMatchesRequest(request, exactAcknowledgement)) {\n throw new RetainedRunProviderContractError(\n 'provider returned a retained cancellation acknowledgement for another request',\n )\n }\n return exactAcknowledgement\n}\n\nexport function hasDurableCancel(session: AgentSession): boolean {\n return typeof session.cancelRun === 'function'\n}\n\nexport async function awaitAbortable<T>(\n work: PromiseLike<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n if (signal === undefined) return await work\n // Work already running stays observed when the signal fired first.\n if (signal.aborted) void Promise.resolve(work).catch(() => undefined)\n return await runAbortable(\n () => Promise.resolve(work),\n signal,\n () => abortError(signal.reason),\n )\n}\n\nexport async function exactSessionResult(session: AgentSession): Promise<AgentTurnResult> {\n return session.result()\n}\n\nexport function assertEventBinding(\n source: AgentEnvironmentEvent,\n controlRef: AgentExactRunControlRef,\n): void {\n const transport = isRecord(source) ? source : undefined\n const payload = isRecord(source.data) ? source.data : undefined\n const providerEvent = isRecord(source.providerEvent) ? source.providerEvent : undefined\n const bindings = [\n { value: transport, checkSessionId: true },\n {\n value: payload,\n // The canonical session.updated payload identifies the harness-native chat.\n // It is event content, not the retained provider session coordinate.\n checkSessionId: source.type !== 'session.updated',\n },\n { value: providerEvent, checkSessionId: true },\n ]\n for (const { value, checkSessionId } of bindings) {\n if (value === undefined) continue\n if (value.runId !== undefined && value.runId !== controlRef.runId) {\n throw new Error('provider returned an event for another retained run')\n }\n if (value.executionId !== undefined && value.executionId !== controlRef.executionId) {\n throw new Error('provider returned an event for another retained execution')\n }\n if (\n checkSessionId &&\n value.sessionId !== undefined &&\n value.sessionId !== controlRef.sessionId\n ) {\n throw new Error('provider returned an event for another retained session')\n }\n }\n}\n\n/** Validate the retained coordinates. The nested provider names the inner adapter. */\nexport function assertCanonicalEventBinding(\n controlRef: AgentExactRunControlRef,\n event: StreamEvent,\n): void {\n if (event.type !== 'interaction') return\n const binding = event.request.binding\n if (\n binding.runId !== controlRef.runId ||\n binding.environmentId !== controlRef.environmentId ||\n binding.sessionId !== controlRef.sessionId ||\n binding.executionId !== controlRef.executionId ||\n binding.interactionId !== event.request.id\n ) {\n throw new Error('provider returned an interaction for another retained execution')\n }\n}\n\nexport function assertStableText(value: string, label: string): void {\n if (value.length === 0 || value.trim() !== value) {\n throw new Error(`${label} must be non-empty and have no outer whitespace`)\n }\n}\n\nexport function assertWaitDuration(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label} must be a non-negative safe integer`)\n }\n}\n\n/**\n * Whether a session can still change state.\n *\n * Exhaustive over `AgentSessionStatus` by construction: the map below is `satisfies\n * Record<AgentSessionStatus, boolean>`, so a member added upstream fails to compile here instead of\n * being silently classified as non-terminal. Written as a boolean chain, `stopped` was missing —\n * and a `status({ waitMs })` call on an already-stopped session then polled every 25 ms for the\n * whole wait before returning the answer it already had at the first snapshot.\n *\n * `unknown` is deliberately NOT terminal: it says the provider could not tell us, which is the one\n * state where continuing to poll is the point. That differs from\n * `sandboxSessionStatusFromAgentSessionStatus`, which projects `unknown` to `failed` because a run\n * RESULT must never claim success without proof — a different question about the same word.\n */\nconst sessionStatusIsTerminal = {\n pending: false,\n provisioning: false,\n running: false,\n unknown: false,\n stopped: true,\n completed: true,\n cancelled: true,\n failed: true,\n expired: true,\n} satisfies Record<AgentSessionStatus, boolean>\n\nexport function isTerminalSessionStatus(status: AgentSessionStatus | null): boolean {\n return status !== null && sessionStatusIsTerminal[status]\n}\n\nexport function delay(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) return Promise.reject(abortError(signal.reason))\n return new Promise((resolveDelay, rejectDelay) => {\n const clearTimer = armDeadlineTimer(ms, finish, true)\n function finish() {\n signal?.removeEventListener('abort', onAbort)\n resolveDelay()\n }\n function onAbort() {\n clearTimer()\n signal?.removeEventListener('abort', onAbort)\n rejectDelay(abortError(signal?.reason))\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n","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: the platform reports `effectiveBackend`\n * on `execution.started` and again on the terminal event. Absence stays unknown — a request is\n * not a receipt, so nothing here may be inferred from what was asked for.\n */\nexport function sandboxEventServedBackend(event: SandboxEvent): SandboxServedBackend | undefined {\n const served = plainRecord(\n plainRecord((event as { data?: unknown } | null)?.data)?.effectiveBackend,\n )\n const named = (['provider', 'model', 'source'] as const).flatMap((key) => {\n const value = firstString(served?.[key])\n return value === undefined ? [] : [[key, value] as const]\n })\n if (!named.some(([key]) => key !== 'source')) return undefined\n return Object.fromEntries(named)\n}\n\n/**\n * Fail the execution when the platform reports serving a model other than the exact one asked for.\n * Measured motive (agent-runtime#892): 6 of 6 boxes declaring `zai-coding-plan/glm-5.2` reported\n * `deepseek/deepseek-v4-flash` (`source: \"environment\"`) while the materialization receipt recorded\n * the declared model as known; only reading the report back detects the substitution.\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 const served = wanted ? sandboxEventServedBackend(event) : undefined\n if (!wanted || served?.model === undefined) return\n if (sameModelId(served.model, wanted, [served.provider, expected?.provider])) return\n const attribution = Object.entries({ provider: served.provider, source: served.source }).flatMap(\n ([key, value]) => (value === undefined ? [] : [`${key} ${JSON.stringify(value)}`]),\n )\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 */\nexport function 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 { addSpend, 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 /** The owner's own observed work. It spends the owner's kept share (`ReservationFloor`) first. */\n ownerSpent: Spend\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 ownerSpent: { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 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 kept = (share = 0, spent: number) => Math.max(0, share - spent)\n const tokensFree = l.freeTokens - kept(keep?.tokens, chargedTokens(l.ownerSpent.tokens))\n const iterationsFree = l.freeIterations - kept(keep?.iterations, l.ownerSpent.iterations)\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 - kept(keep?.usd, l.ownerSpent.usd)\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 l.freeUsd -= b.maxUsd ?? 0\n l.reservedUsd += b.maxUsd ?? 0\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 debit(l, spend)\n l.ownerSpent = addSpend(l.ownerSpent, spend)\n if (unknownUnderCap) l.usdTainted = true\n return ledgerCommitResources(l, spend, undefined, requireAllResources)\n}\n\n/** Move measured `spend` from free to committed on the token, iteration and dollar channels. */\nfunction debit(l: BudgetLedger, spend: Spend): void {\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}\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.owner) l.ownerSpent = addSpend(l.ownerSpent, restore.owner)\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 debit(l, committed)\n if (l.usdCapped && 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 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/** A manager's own share of each channel of its slice. Its children may not reserve the part of\n * it the manager's own observed work has not yet spent. */\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 owner share free after the reservation, less what `observe` already charged. */\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 /** The part of `committed` the owner's own work spent, charged against its kept share. */\n readonly owner?: 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 { setImmediate as nextTurn } from 'node:timers/promises'\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 { ExecutorResult, 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(\n outRef: string,\n result: Pick<ExecutorResult<unknown>, 'out' | 'outputFormat'>,\n ): 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 memoized = (outRef: string, out: unknown, evidence: boolean) => {\n const known = roots.get(outRef)\n if (known !== undefined) return known\n const pending = (async () => {\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 built = await traceRootArtifact(nodeId, outRef, events).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 if (built === undefined) return undefined\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 rooted.add(digest)\n return { root: artifact.root, ref, leafCount: artifact.leafCount }\n })()\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, result) =>\n result.outputFormat === 'json'\n ? Promise.resolve(undefined)\n : memoized(outRef, result.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\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\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 // Sandbox: no host can place a box now (the SDK's `sandboxFailureKind` reads them as capacity).\n 'capacity_exhausted',\n 'host_pressure',\n 'provisioning_paused',\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 * Sandbox's 409 `NO_HOST_FITS_SHAPE` for a shape that fits its host's ceiling: no exceeded\n * dimension, only `its room is held placeable on <sku>`. It is sent by mistake for \"no room now\"\n * while new hosts cannot be planned, and the create lands within one autoscaler purchase. Four\n * nodes of Discovery run magnetar-rust-sandbox-20261101a went down on it. A shape over the ceiling\n * names the dimension it exceeds instead, and stays refused.\n */\nconst HELD_ROOM_REFUSAL = /\\bits room is held placeable\\b/u\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, with Sandbox's held-room text beside its\n * code; other text is read only when no code or numeric status decided, because a harness CLI can\n * 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 (code === 'no_host_fits_shape' && HELD_ROOM_REFUSAL.test(failure.error))\n return 'host-room-held'\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 type { DriverAttemptRecord } from './driver-attempt-evidence'\nimport { errorProperty } from './error-message'\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 /** Asked once when a turn settles with a result: `true` keeps the environment for a keyed\n * continuation (`Executor.heldForContinuation`), as the scope answers for a keyed leaf whose\n * turn ended over its budget or past its deadline. */\n readonly holdOnSettle?: (spent: Spend) => boolean\n readonly admissions: readonly RetainedRunAdmission[]\n readonly onReady?: () => void | Promise<void>\n readonly onAdmission: RetainedRunAdmissionHook\n /** How far an owner's retained execution's event stream was read, and the hook that moves it;\n * the owner's `driver-attempt` records carry it across a restart. */\n readonly observed?: RetainedObservedPosition\n readonly onObserved?: (observed: RetainedObservedPosition) => void\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 /** Start this node's next invocation in its last one's environment and session, once that one\n * committed its result: the scope journals `task` as the next `execution-input` and answers the\n * new invocation's context. A Scope leaf has it; an owner's driver re-enters instead. */\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 /** Take over a stopped manager's end-of-turn workspace capture, run after the turn's result\n * commits. An owner whose environment outlives its turns awaits it before its next invocation\n * and before release, so the capture precedes the destroy; its receipt arrives through\n * `onEvidence`. Never rejects. */\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 capture was requested, before it waits; an owner also cuts its\n * checkpoint rotation's captures short here, so they never hold the 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 turns use it. */\n readonly onWorkspaceRestored?: (receipt: RetainedWorkspaceRestoreReceipt) => Promise<void>\n}\n\n/** A retained execution's event stream, read through `replayPosition`. */\nexport type RetainedObservedPosition = NonNullable<DriverAttemptRecord['observed']>\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 — and two untyped Sandbox refusals' text, never other message text: the provider is not a\n * dependency of this package and its messages are not a contract. #1204's exhibit 3 (an event\n * without a stable id) is delivered rather than thrown since agent-provider-tangle 1.4.0; 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 * agent-provider-tangle's `TangleDispatchExecutionChangedError` (since 5.0.8): Sandbox CONFIRMED\n * the dispatch but named an execution id other than the requested run's. The provider's own\n * answer violates its contract, identically on every retry (agent-sdk #475: 107 retries over\n * 39 minutes, all classed transient, before the run settled all-children-down).\n */\nexport const DISPATCH_EXECUTION_CHANGED_CODE = 'DISPATCH_EXECUTION_CHANGED'\n\n/**\n * The Sandbox SDK's codes for a box that cannot be provisioned for this profile, by the HTTP status\n * each is sent with: a mount outside the box's writable roots and a materialization that would fail\n * the same way again (422), a mounted file changed on both sides since the last mount (409). Two\n * bare 500s are read by text: that conflict before Sandbox typed it, and two mounts of one target\n * (magnetar-rust-sandbox-20261031g's and 20261031h's managers retried them every turn). On run\n * queens21-h22-capture-root-1-20261019c 154 attempts across 4 workers retried a read-only mount of\n * `/work/queens21_count.c` as a lost transport. The same codes at another status may be transient.\n */\nconst PROVISIONING_REFUSALS: ReadonlyMap<string, number> = new Map([\n ['PROFILE_FILE_MOUNT_OUTSIDE_ROOTS', 422],\n ['PROFILE_FILES_MATERIALIZE_FAILED', 422],\n ['PROFILE_FILE_CONFLICT', 409],\n])\nconst TEXT_REFUSALS = /Refusing to replace existing profile file: |Duplicate profile file target: /u\n\n/** True for an error that is itself a deterministic provisioning refusal (see above). */\nexport const isProvisioningRefusal = (value: object): boolean =>\n refusedAs(PROVISIONING_REFUSALS, value) ||\n (value instanceof Error && TEXT_REFUSALS.test(errorProperty(value, 'message') ?? ''))\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 const isPlatformPredispatchRefusal = (value: object): boolean =>\n refusedAs(PLATFORM_PREDISPATCH_REFUSALS, value)\n\n/** True when `value` carries one of `refusals`' codes at the status that code is sent with. */\nfunction refusedAs(refusals: ReadonlyMap<string, number>, 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 : 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\n/** Refused by a schema or bound, the same way every attempt: agent-provider-tangle's JsonBoundError\n * (#1204's exhibit 6) or the Sandbox SDK refusing a capability document as HTTP 502, which\n * institutional-compiler-20261031c:s14 retried 44 times as a lost transport. */\nexport function isSchemaRejection(value: object): boolean {\n const code = readString(value, 'code')\n return (\n readString(value, 'name') === 'ZodError' ||\n Array.isArray(Reflect.get(value, 'issues')) ||\n code === 'JSON_BOUND_VIOLATION' ||\n code === 'INVALID_CAPABILITY_DOCUMENT'\n )\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 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 (isSchemaRejection(value)) {\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 // Sandbox confirmed the dispatch but named a different execution: a broken answer at either\n // phase. Nothing about the request can change it — repeating the dispatch receives the same\n // contradiction — so it is a provider contract violation, which the driver classifies terminal.\n if (code === DISPATCH_EXECUTION_CHANGED_CODE) return '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 ? classifyRetainedPendingCause(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 { causeChain, 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 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/** 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 = causeChain(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 type { ToolLoopChat } from '../tool-loop'\nimport type { Agent } from './types'\n\nconst flowOwners = new WeakSet<object>()\n\n/** Runtime schedules this model-free brain under graph edge caps, pool, deadline and abort. */\nexport function runtimeFlowBrain(): ToolLoopChat {\n const brain: ToolLoopChat = async () => ({ content: null, toolCalls: [] })\n flowOwners.add(brain)\n return brain\n}\n\n/** True only for a brain `runtimeFlowBrain` minted. */\nexport function isRuntimeFlowBrain(brain: ToolLoopChat): boolean {\n return flowOwners.has(brain)\n}\n\n/** Carry the same unforgeable ownership through the built code driver and its spec copies. */\nexport function runtimeFlowAgent(\n agent: Agent<unknown, unknown>,\n brain: ToolLoopChat | undefined,\n): Agent<unknown, unknown> {\n if (brain && isRuntimeFlowBrain(brain)) flowOwners.add(agent)\n return agent\n}\n\nexport function isRuntimeFlowAgent(agent: unknown): boolean {\n return typeof agent === 'object' && agent !== null && flowOwners.has(agent)\n}\n","import { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { isRuntimeFlowAgent } from './flow-brain'\nimport { assertExecutableAgentProfile } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport type { AgentSpec } from './types'\n\n/** Read untrusted fields once, then parse and seal the exact executable profile. */\nexport function executableAgentProfileSnapshot(raw: unknown, context: string): AgentProfile {\n const profile = authoredAgentProfileSnapshot(raw, context)\n assertExecutableAgentProfile(profile, context)\n return profile\n}\n\n/** Seal code-owned behavior without inventing a model: verbatim executors and owned flow drivers. */\nfunction authoredAgentProfileSnapshot(raw: unknown, context: string): AgentProfile {\n const input = detachedSnapshot(raw, `${context}: AgentProfile input`)\n const profile = agentProfileSchema.parse(input)\n return detachedSnapshot(profile, `${context}: parsed AgentProfile`)\n}\n\n/** Snapshot an executable spec while retaining trusted callbacks by reference. */\nexport function executableAgentSpecSnapshot(raw: AgentSpec, context: string): AgentSpec {\n const {\n profile: rawProfile,\n harness,\n execution: rawExecution,\n ...runtimeExtensions\n } = raw as AgentSpec & Readonly<Record<string, unknown>>\n // Only model-backed resolution requires an executable model identity.\n const profile =\n raw.executor === undefined && !isRuntimeFlowAgent(runtimeExtensions.driver)\n ? executableAgentProfileSnapshot(rawProfile, context)\n : authoredAgentProfileSnapshot(rawProfile, context)\n const execution =\n rawExecution === undefined\n ? undefined\n : detachedSnapshot(rawExecution, `${context}: execution attribution`)\n return Object.freeze({\n ...runtimeExtensions,\n profile,\n harness,\n ...(execution === undefined ? {} : { execution }),\n }) as AgentSpec\n}\n","import type { ProviderModelAttemptEvidence } from './supervise/types'\n\n/** Detach provider attempt observations into their immutable journal evidence shape. */\nexport function snapshotProviderObservations(\n attempts: ReadonlyArray<ProviderModelAttemptEvidence>,\n): ReadonlyArray<ProviderModelAttemptEvidence> {\n return Object.freeze(\n attempts.map((attempt) =>\n Object.freeze({\n observations: Object.freeze([...attempt.observations]),\n ...(attempt.identityConflict ? { identityConflict: true } : {}),\n ...(attempt.providerDispatch === 'not_started'\n ? { providerDispatch: 'not_started' as const }\n : {}),\n }),\n ),\n )\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport type { AgentIdentity } from '@tangle-network/agent-trace-contract'\nimport { ValidationError } from '../../errors'\nimport { snapshotProviderObservations } from '../provider-observation-snapshot'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorExecutionBinding,\n ExecutorMaterialization,\n MaterializedExecutionIdentity,\n ProfileMaterializationReceipt,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n Runtime,\n UnknownMaterializationReason,\n} from './types'\n\ntype RuntimeOwnedExecutorMaterialization =\n | {\n readonly kind: 'known'\n readonly declaration: ExecutorMaterialization\n readonly binding?: ExecutorExecutionBinding\n }\n | {\n /** A Runtime-owned external executor whose exact launch is known, but whose remote\n * materializer has not yet returned its terminal acknowledgement. This private state lets\n * Runtime validate the planned authority before execution without presenting it as proof\n * that the remote process actually used that plan. */\n readonly kind: 'pending'\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | { readonly kind: 'deferred'; readonly runtime: Runtime }\n\ninterface RuntimeOwnedExecutorMaterializationRef {\n current: RuntimeOwnedExecutorMaterialization\n}\n\nconst runtimeOwnedExecutorMaterializations = new WeakMap<\n object,\n RuntimeOwnedExecutorMaterializationRef\n>()\nconst runtimeOwnedScopeOwners = new WeakMap<object, Runtime>()\nconst runtimeOwnedExecutorProviderEvidenceState = new WeakMap<\n object,\n {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n }\n>()\nconst runtimeOwnedDriveHarnessProviderEvidenceState = new WeakMap<\n object,\n ProviderModelExecutionEvidence\n>()\n\ninterface KnownReceiptInput {\n readonly authoredProfileDigest: Sha256Digest\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n}\n\ninterface UnknownReceiptInput {\n readonly authoredProfileDigest?: Sha256Digest\n readonly runtime: Runtime\n readonly reason: UnknownMaterializationReason\n}\n\nconst declarationKeys = new Set([\n 'effectiveProfile',\n 'authoredProfile',\n 'backend',\n 'model',\n 'execution',\n 'materializer',\n 'plan',\n 'platformAttachments',\n])\n\n/**\n * Bind a declaration to a runtime-owned executor without putting an attestable method on the\n * public Executor interface. This module is not a package export: arbitrary caller executors stay\n * unknown even if they add a lookalike `materialization()` property.\n */\nexport function attestRuntimeOwnedExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding?: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n ...(binding === undefined\n ? {}\n : {\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n }),\n }),\n })\n ensureProviderEvidenceState(executor)\n return executor\n}\n\n/** Brand an external Runtime executor whose exact remote materialization is provable only after\n * its terminal protocol acknowledgement. The declaration is a planned authority check, never a\n * known receipt; callers must finalize this same object after validating the acknowledgement. */\nexport function attestRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'pending',\n runtime,\n declaration: detachedSnapshot(declaration, 'pending executor materialization'),\n binding: detachedSnapshot(binding, 'pending executor execution binding'),\n }),\n })\n return executor\n}\n\n/** Replace a private pending brand with terminally acknowledged evidence. A caller-owned executor\n * cannot enter this path because only this module can create the pending WeakMap entry. */\nexport function finalizeRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(executor as object)\n if (ref?.current.kind !== 'pending' || ref.current.runtime !== executor.runtime) {\n throw new ValidationError(\n 'executor materialization: terminal acknowledgement has no matching Runtime-owned pending executor',\n )\n }\n ref.current = Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n })\n return executor\n}\n\n/** Mark a runtime-owned orchestration executor whose exact leaf declaration is published through\n * its private nested Scope before the first backend inference. Arbitrary executors cannot opt in. */\nexport function attestRuntimeOwnedDeferredExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({ kind: 'deferred', runtime }),\n })\n return executor\n}\n\n/** Preserve the runtime-owned attestation when a trusted wrapper changes result semantics only. */\nexport function inheritRuntimeOwnedExecutorAttestation<In, Out>(\n source: Executor<In>,\n wrapper: Executor<Out>,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(source as object)\n if (ref !== undefined) {\n runtimeOwnedExecutorMaterializations.set(wrapper as object, ref)\n }\n const providerState = ensureProviderEvidenceState(source)\n runtimeOwnedExecutorProviderEvidenceState.set(wrapper as object, providerState)\n return wrapper\n}\n\nfunction ensureProviderEvidenceState<Out>(executor: Executor<Out>): {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n} {\n const existing = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (existing !== undefined) return existing\n const state = { attempts: [] }\n runtimeOwnedExecutorProviderEvidenceState.set(executor as object, state)\n return state\n}\n\n/** Read a declaration only when Runtime itself branded this exact executor object. */\nexport function runtimeOwnedExecutorMaterialization<Out>(\n executor: Executor<Out>,\n): ExecutorMaterialization | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.declaration : undefined\n}\n\n/** Read one attempt binding only from the private brand on this exact executor object. */\nexport function runtimeOwnedExecutorExecutionBinding<Out>(\n executor: Executor<Out>,\n): ExecutorExecutionBinding | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.binding : undefined\n}\n\n/** Read a planned external declaration only for Runtime's private pending brand. This is useful for\n * pre-execution authority checks, but must never be turned into a known durable receipt. */\nexport function runtimeOwnedPendingExecutorMaterialization<Out>(executor: Executor<Out>):\n | {\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'pending'\n ? {\n runtime: attestation.runtime,\n declaration: attestation.declaration,\n binding: attestation.binding,\n }\n : undefined\n}\n\n/** Read the expected leaf runtime only for a privately branded deferred orchestration executor. */\nexport function runtimeOwnedDeferredExecutorRuntime<Out>(\n executor: Executor<Out>,\n): Runtime | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'deferred' ? attestation.runtime : undefined\n}\n\n/** Propagate trust from a built-in driver adapter to the Agent and recursive executor it owns. */\nexport function attestRuntimeOwnedScopeOwner<T extends object>(owner: T, runtime: Runtime): T {\n runtimeOwnedScopeOwners.set(owner, runtime)\n return owner\n}\n\n/** Return a built-in scope owner's expected concrete leaf runtime; caller-owned functions/Agents\n * deliberately have no entry even if they add lookalike fields. */\nexport function runtimeOwnedScopeOwnerRuntime(owner: object): Runtime | undefined {\n return runtimeOwnedScopeOwners.get(owner)\n}\n\n/** Mark one provider inference attempt on a Runtime-owned executor. */\nexport function recordRuntimeOwnedProviderAttemptStart<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n state.attempts.push({ observations: [] })\n}\n\n/** Mark the current attempt as rejected before provider dispatch.\n *\n * The caller may use this only after consuming the Router-owned\n * `provider_dispatch: \"not_started\"` fact. Any other error stays an empty,\n * unknown attempt and must not be upgraded here.\n */\nexport function recordRuntimeOwnedProviderDispatchNotStarted<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider dispatch rejection arrived before an attempt started')\n }\n if (attempt.observations.length > 0 || attempt.identityConflict === true) {\n throw new ValidationError(\n 'provider dispatch rejection arrived after provider identity evidence was observed',\n )\n }\n attempt.providerDispatch = 'not_started'\n}\n\n/** Record a trusted served model on the current provider attempt. */\nexport function recordRuntimeOwnedProviderModel<Out>(executor: Executor<Out>, model: string): void {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n const attempt = state?.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider model observation arrived before an attempt started')\n }\n if (attempt.observations.at(-1) !== model) attempt.observations.push(model)\n}\n\n/** Convert process-local provider observations into a frozen, replayable evidence value. */\nexport function runtimeOwnedExecutorProviderEvidence<Out>(\n executor: Executor<Out>,\n): ProviderModelExecutionEvidence | undefined {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (state === undefined || state.attempts.length === 0) return undefined\n const attempts: ReadonlyArray<ProviderModelAttemptEvidence> = snapshotProviderObservations(\n state.attempts,\n )\n const models = Object.freeze([...new Set(attempts.flatMap((attempt) => attempt.observations))])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n return Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n )\n}\n\n/** Mark the current provider attempt unusable after conflicting served identity metadata. */\nexport function recordRuntimeOwnedProviderIdentityConflict<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider identity conflict arrived before an attempt started')\n }\n attempt.identityConflict = true\n}\n\n/** Attach one executor's provider evidence to a Runtime-owned root drive for final projection. */\nexport function recordRuntimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n evidence: ProviderModelExecutionEvidence | undefined,\n): void {\n if (evidence === undefined) return\n const prior = runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n if (prior === undefined) {\n runtimeOwnedDriveHarnessProviderEvidenceState.set(owner, evidence)\n return\n }\n const attempts = Object.freeze([...prior.attempts, ...evidence.attempts])\n const models = Object.freeze([...new Set([...prior.models, ...evidence.models])])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n runtimeOwnedDriveHarnessProviderEvidenceState.set(\n owner,\n Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n ),\n )\n}\n\n/** Read provider evidence recorded by a Runtime-owned root drive. */\nexport function runtimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n): ProviderModelExecutionEvidence | undefined {\n return runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n}\n\n/** Build one kernel-owned known receipt from a data-only executor declaration. */\nexport function knownMaterializationReceipt(\n input: KnownReceiptInput,\n): ProfileMaterializationReceipt {\n const declaration = detachedSnapshot(input.declaration, 'executor materialization')\n assertExactDeclaration(declaration)\n const effectiveProfile = agentProfileSchema.safeParse(declaration.effectiveProfile)\n if (!effectiveProfile.success) {\n throw new ValidationError('executor materialization: effectiveProfile must be an AgentProfile')\n }\n const authoredProfile =\n declaration.authoredProfile === undefined\n ? effectiveProfile\n : agentProfileSchema.safeParse(declaration.authoredProfile)\n if (!authoredProfile.success) {\n throw new ValidationError('executor materialization: authoredProfile must be an AgentProfile')\n }\n assertNonEmpty(declaration.backend, 'backend')\n assertNonEmpty(declaration.materializer, 'materializer')\n assertNonEmpty(declaration.execution?.kind, 'execution.kind')\n assertNonEmpty(declaration.execution?.id, 'execution.id')\n assertModel(declaration.model)\n\n let effectiveProfileDigest: Sha256Digest\n let materializationPlanDigest: Sha256Digest\n let platformAttachmentsDigest: Sha256Digest | undefined\n try {\n effectiveProfileDigest = canonicalAgentProfileDigest(effectiveProfile.data)\n if (canonicalAgentProfileDigest(authoredProfile.data) !== input.authoredProfileDigest) {\n throw new ValidationError(\n 'executor materialization: authoredProfile conflicts with the admitted AgentProfile',\n )\n }\n materializationPlanDigest = canonicalCandidateDigest(jsonWireSnapshot(declaration.plan))\n platformAttachmentsDigest =\n declaration.platformAttachments === undefined\n ? undefined\n : canonicalCandidateDigest(jsonWireSnapshot(declaration.platformAttachments))\n } catch (error) {\n throw new ValidationError(\n 'executor materialization: profile, plan, and attachments must be finite RFC 8785 JSON',\n { cause: error },\n )\n }\n\n return Object.freeze({\n status: 'known' as const,\n authoredProfileDigest: input.authoredProfileDigest,\n effectiveProfileDigest,\n materializationPlanDigest,\n ...(platformAttachmentsDigest === undefined ? {} : { platformAttachmentsDigest }),\n runtime: input.runtime,\n backend: declaration.backend,\n model: declaration.model,\n execution: declaration.execution,\n materializer: declaration.materializer,\n })\n}\n\n/** Build an explicit unknown receipt without fabricating any executor-owned identity. */\nexport function unknownMaterializationReceipt(\n input: UnknownReceiptInput,\n): ProfileMaterializationReceipt {\n return Object.freeze({\n status: 'unknown' as const,\n ...(input.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: input.authoredProfileDigest }),\n runtime: input.runtime,\n reason: input.reason,\n })\n}\n\n/** Mint a process-unique attempt id before executor construction. */\nexport function newExecutionAttemptId(nodeId: string): string {\n return `${nodeId}:attempt:${randomUUID()}`\n}\n\n/** Build the immutable safe receipt for a full, transient execution binding. */\nexport function knownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n bindingInput: ExecutorExecutionBinding,\n): ExecutionBindingReceipt {\n const binding = detachedSnapshot(bindingInput, 'executor execution binding')\n assertNonEmpty(binding.attemptId, 'binding.attemptId')\n assertSafeDescriptor(binding.descriptor)\n let materializationReceiptDigest: Sha256Digest\n let bindingDigest: Sha256Digest\n try {\n materializationReceiptDigest = canonicalCandidateDigest(materialization)\n // Bind the exact JSON document a backend receives. Optional AgentProfile fields are represented\n // as `undefined` in memory but omitted by JSON transport; normalize that one distinction while\n // rejecting every non-finite/non-data value instead of silently coercing it.\n bindingDigest = canonicalCandidateDigest(jsonWireSnapshot(binding.binding))\n } catch (error) {\n throw new ValidationError('executor binding must be finite RFC 8785 JSON', { cause: error })\n }\n return Object.freeze({\n status: 'known' as const,\n attemptId: binding.attemptId,\n materializationReceiptDigest,\n bindingDigest,\n descriptor: binding.descriptor,\n })\n}\n\n/** Preserve an attempt boundary even when its caller-owned transport cannot be attested. */\nexport function unknownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n reason: UnknownMaterializationReason,\n execution?: MaterializedExecutionIdentity,\n): ExecutionBindingReceipt {\n assertNonEmpty(attemptId, 'binding.attemptId')\n return Object.freeze({\n status: 'unknown' as const,\n attemptId,\n materializationReceiptDigest: canonicalCandidateDigest(materialization),\n reason,\n ...(execution === undefined ? {} : { execution: Object.freeze({ ...execution }) }),\n })\n}\n\n/** Derive an authored-profile digest without turning non-canonical input into a fake identity. */\nexport function authoredProfileDigest(profile: unknown): Sha256Digest | undefined {\n try {\n return canonicalAgentProfileDigest(agentProfileSchema.parse(profile))\n } catch {\n return undefined\n }\n}\n\n/**\n * Who acted, as a trace span says it: the authored profile's canonical digest, its name, the model\n * and harness it declares, and a digest of its skill set. `profileDigest` is the digest the spawn\n * journal already recorded for the node, passed so the span and the journal name the same agent.\n * A field the profile does not declare stays absent; input that is not an AgentProfile yields only\n * the recorded digest, if any.\n */\nexport function authoredAgentIdentity(profile: unknown, profileDigest?: string): AgentIdentity {\n const parsed = agentProfileSchema.safeParse(profile)\n if (!parsed.success) return profileDigest === undefined ? {} : { profileDigest }\n const authored = parsed.data\n const digest = profileDigest ?? authoredProfileDigest(authored)\n const skills = authored.resources?.skills\n let skillsDigest: string | undefined\n try {\n skillsDigest = skills && skills.length > 0 ? canonicalCandidateDigest(skills) : undefined\n } catch {\n skillsDigest = undefined\n }\n return {\n ...(digest === undefined ? {} : { profileDigest: digest }),\n ...(authored.name ? { profileName: authored.name } : {}),\n ...(authored.model?.default ? { model: authored.model.default } : {}),\n ...(authored.harness ? { harness: authored.harness } : {}),\n ...(skillsDigest === undefined ? {} : { skillsDigest }),\n }\n}\n\nfunction assertExactDeclaration(value: ExecutorMaterialization): void {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('executor materialization: declaration must be an object')\n }\n const unknown = Object.keys(value).filter((key) => !declarationKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(\n `executor materialization: unknown declaration fields: ${unknown.sort().join(', ')}`,\n )\n }\n if (!Object.hasOwn(value, 'plan')) {\n throw new ValidationError('executor materialization: plan is required')\n }\n}\n\nfunction assertModel(model: ExecutorMaterialization['model']): void {\n if (typeof model !== 'object' || model === null || Array.isArray(model)) {\n throw new ValidationError('executor materialization: model must be a known/unknown identity')\n }\n const keys = Object.keys(model).sort()\n if (model.status === 'known') {\n if (keys.join(',') !== 'id,status') {\n throw new ValidationError('executor materialization: known model accepts only status and id')\n }\n assertNonEmpty(model.id, 'model.id')\n return\n }\n if (model.status === 'unknown') {\n if (keys.join(',') !== 'reason,status') {\n throw new ValidationError(\n 'executor materialization: unknown model accepts only status and reason',\n )\n }\n assertNonEmpty(model.reason, 'model.reason')\n return\n }\n throw new ValidationError('executor materialization: model.status must be known or unknown')\n}\n\nfunction assertNonEmpty(value: unknown, field: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`executor materialization: ${field} must be a non-empty string`)\n }\n}\n\nfunction assertSafeDescriptor(descriptor: ExecutorExecutionBinding['descriptor']): void {\n if (typeof descriptor !== 'object' || descriptor === null || Array.isArray(descriptor)) {\n throw new ValidationError('executor binding: descriptor must be an object')\n }\n for (const [key, value] of Object.entries(descriptor)) {\n if (/(url|uri|token|key|secret|bearer|credential|authorization)/i.test(key)) {\n throw new ValidationError(`executor binding: unsafe descriptor key ${JSON.stringify(key)}`)\n }\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} must be scalar`,\n )\n }\n if (typeof value === 'string' && (value.includes('://') || value.includes('@'))) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} contains transport or credential text`,\n )\n }\n }\n}\n\nfunction jsonWireSnapshot(value: unknown, path = '$'): unknown {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new ValidationError(`executor binding: ${path} must be finite`)\n }\n return value\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => {\n if (item === undefined) {\n throw new ValidationError(`executor binding: ${path}[${index}] cannot be undefined`)\n }\n return jsonWireSnapshot(item, `${path}[${index}]`)\n })\n }\n if (typeof value !== 'object' || value === null) {\n throw new ValidationError(`executor binding: ${path} must be JSON data`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new ValidationError(`executor binding: ${path} must be a plain object`)\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item === undefined) continue\n out[key] = jsonWireSnapshot(item, `${path}.${key}`)\n }\n return out\n}\n\n/**\n * The provider-identity evidence for ONE attempt, from the served model alone. `unknown` with a\n * `provider-model-missing` reason when the attempt produced no model, because an attempt that\n * cannot name what served it is not evidence that nothing did.\n */\nexport function providerAttemptEvidence(model: string | undefined): ProviderModelExecutionEvidence {\n const attempts = Object.freeze([\n Object.freeze({ observations: Object.freeze(model === undefined ? [] : [model]) }),\n ])\n const models = Object.freeze(model === undefined ? [] : [model])\n return Object.freeze(\n model === undefined\n ? { status: 'unknown' as const, attempts, models, reason: 'provider-model-missing' as const }\n : { status: 'known' as const, attempts, models },\n )\n}\n","import type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { ExecutorConfig } from './runtime'\nimport type { NodeId, SpawnEvent, SpawnJournal } from './types'\n\n/** A stage is authored in the immutable profile. A selection is a concrete, private placement. */\nexport type SeatStage = Readonly<NonNullable<AgentProfile['seats']>[number]>\n\nexport interface SeatSegment {\n readonly seat: string\n readonly harness: string\n readonly provider: string\n readonly model: string\n readonly startedAt: string\n readonly endedAt?: string\n readonly reason?: 'usage-limit' | 'completed' | 'failed' | 'cancelled' | 'paused'\n}\n\nexport interface SeatSelectionInput {\n readonly profile: AgentProfile\n readonly nodeId: string\n readonly stage: SeatStage\n readonly stageIndex: number\n readonly segmentIndex: number\n readonly excludedSeatIds: readonly string[]\n readonly previous?: Pick<SeatSegment, 'seat' | 'harness' | 'provider' | 'model'>\n /** Last admitted environment without a confirmed destroy receipt. Check live capability before reuse. */\n readonly retainedEnvironmentId?: string\n /** This selection must grant a different credential on the retained native session. */\n readonly requiresNativeTurnGrant: boolean\n /** Rebind the exact prior seat after coordinator restart, never choose another implicitly. */\n readonly resumeSeatId?: string\n}\n\nexport type SeatSelection =\n | {\n readonly seat: string\n readonly backend: Extract<ExecutorConfig, { backend: 'provider' }>\n /** Lab verified that this backend can grant the selected seat on an existing native session. */\n readonly nativeTurnGrant?: true\n }\n | { readonly resumeAt: string }\n\n/** The caller owns account eligibility and credential resolution; Runtime owns the chain order. */\nexport type SelectSeat = (input: SeatSelectionInput) => Promise<SeatSelection>\n\nexport class SeatChainExhaustedError extends Error {\n readonly resumeAt: string\n constructor(resumeAt: string) {\n super(`authored subscription seat chain exhausted; resume at ${resumeAt}`)\n this.name = 'SeatChainExhaustedError'\n this.resumeAt = resumeAt\n }\n}\n\nexport interface ActiveSeat {\n readonly seat: string\n readonly stageIndex: number\n readonly segmentIndex: number\n readonly stage: SeatStage\n readonly backend: Extract<ExecutorConfig, { backend: 'provider' }>\n readonly nativeTurnGrant?: true\n /** The completed predecessor, if this segment changed a seat. */\n readonly previous?: Pick<SeatSegment, 'seat' | 'harness' | 'provider' | 'model'>\n}\n\n/** One logical node's durable chain. The spawn journal is the sole transition authority. */\nexport class SeatChain {\n private observedThrough = -1\n\n constructor(\n private readonly profile: AgentProfile,\n private readonly nodeId: NodeId,\n private readonly rootId: NodeId,\n private readonly journal: SpawnJournal,\n private readonly select: SelectSeat,\n private readonly now: () => number = Date.now,\n private readonly onSegment?: (\n segment: SeatSegment,\n phase: 'started' | 'ended',\n ) => Promise<void>,\n private readonly beforeStart?: (\n selection: ActiveSeat,\n previous?: Pick<SeatSegment, 'seat' | 'harness' | 'provider' | 'model'>,\n ) => Promise<void>,\n ) {}\n\n async next(afterUsageLimit = false, afterRecheck = false): Promise<ActiveSeat> {\n const stages = authoredSeatStages(this.profile)\n if (!stages) throw new ValidationError('SeatChain requires authored AgentProfile.seats')\n const allEvents = (await this.journal.loadTree(this.rootId)) ?? []\n const events = allEvents.filter(\n (event): event is Extract<SpawnEvent, { kind: 'seat-segment' }> =>\n event.kind === 'seat-segment' && event.id === this.nodeId,\n )\n const destroyed = new Set(\n allEvents\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'environment-teardown' }> =>\n event.kind === 'environment-teardown' && event.id === this.nodeId && event.destroyed,\n )\n .map((event) => event.environmentId),\n )\n let admittedEnvironmentId: string | undefined\n for (const event of allEvents) {\n if (\n event.kind === 'execution-admitted' &&\n event.id === this.nodeId &&\n event.admission.phase === 'environment'\n ) {\n admittedEnvironmentId = event.admission.environmentId\n }\n }\n const retainedEnvironmentId =\n admittedEnvironmentId !== undefined && !destroyed.has(admittedEnvironmentId)\n ? admittedEnvironmentId\n : undefined\n await this.reconcile(events)\n const starts = events.filter((event) => event.phase === 'started')\n const last = starts.at(-1)\n const closed =\n last &&\n events.some((event) => event.phase === 'ended' && event.segmentIndex === last.segmentIndex)\n if (last && !closed && afterUsageLimit) await this.end(last, 'usage-limit')\n const resume = last && !closed && !afterUsageLimit\n const segmentIndex = resume ? last.segmentIndex : (last?.segmentIndex ?? -1) + 1\n const firstStageIndex = afterRecheck ? 0 : (last?.stageIndex ?? 0)\n let earliestReset: number | undefined\n for (let stageIndex = firstStageIndex; stageIndex < stages.length; stageIndex += 1) {\n const stage = stages[stageIndex]!\n const excludedSeatIds = (afterRecheck ? [] : starts)\n .filter((event) => event.stageIndex === stageIndex && (!resume || event.seat !== last.seat))\n .map((event) => event.seat)\n const prior =\n last === undefined\n ? undefined\n : {\n seat: last.seat,\n harness: last.harness,\n provider: last.provider,\n model: last.model,\n }\n const preceding = resume ? starts.at(-2) : last\n const requiresNativeTurnGrant = Boolean(\n preceding &&\n preceding.provider === stage.provider &&\n preceding.harness === stage.harness &&\n (!resume || preceding.seat !== last.seat),\n )\n const selection = checkedSeatSelection(\n stage,\n await this.select({\n profile: this.profile,\n nodeId: this.nodeId,\n stage,\n stageIndex,\n segmentIndex,\n excludedSeatIds,\n requiresNativeTurnGrant,\n ...(retainedEnvironmentId === undefined ? {} : { retainedEnvironmentId }),\n ...(prior === undefined ? {} : { previous: prior }),\n ...(resume ? { resumeSeatId: last.seat } : {}),\n }),\n )\n if ('resumeAt' in selection) {\n const reset = Date.parse(selection.resumeAt)\n earliestReset = earliestReset === undefined ? reset : Math.min(earliestReset, reset)\n if (resume) break\n continue\n }\n if (resume && selection.seat !== last.seat) {\n throw new ValidationError('selectSeat: resume changed the committed seat')\n }\n if (excludedSeatIds.includes(selection.seat)) {\n throw new ValidationError('selectSeat: selected an exhausted seat')\n }\n if (\n preceding &&\n preceding.seat !== selection.seat &&\n preceding.provider === stage.provider &&\n preceding.harness === stage.harness &&\n selection.nativeTurnGrant !== true\n ) {\n throw new ValidationError(\n 'selectSeat: same-environment seat requires a verified native turn grant',\n )\n }\n const active: ActiveSeat = {\n seat: selection.seat,\n stageIndex,\n segmentIndex,\n stage,\n backend: selection.backend,\n ...(selection.nativeTurnGrant === true ? { nativeTurnGrant: true } : {}),\n ...(preceding === undefined\n ? {}\n : {\n previous: {\n seat: preceding.seat,\n harness: preceding.harness,\n provider: preceding.provider,\n model: preceding.model,\n },\n }),\n }\n if (!resume) {\n await this.beforeStart?.(active, prior)\n const at = new Date(this.now()).toISOString()\n await this.journal.appendEvent(this.rootId, {\n kind: 'seat-segment',\n id: this.nodeId,\n segmentIndex,\n stageIndex,\n phase: 'started',\n seat: selection.seat,\n harness: stage.harness,\n provider: stage.provider,\n model: stage.model,\n seq: segmentIndex,\n at,\n })\n await this.onSegment?.(\n {\n seat: selection.seat,\n harness: stage.harness,\n provider: stage.provider,\n model: stage.model,\n startedAt: at,\n },\n 'started',\n )\n this.observedThrough = events.length\n return active\n }\n return active\n }\n // A provider may know that quota is exhausted without publishing its reset. Recheck the\n // authored chain at the account cache's two-minute cadence; this is not a claimed reset time.\n const recheckAt = Math.max(earliestReset ?? 0, this.now() + 120_000)\n throw new SeatChainExhaustedError(new Date(recheckAt).toISOString())\n }\n\n async close(reason: 'completed' | 'failed' | 'cancelled' | 'paused'): Promise<void> {\n const events = ((await this.journal.loadTree(this.rootId)) ?? []).filter(\n (event): event is Extract<SpawnEvent, { kind: 'seat-segment' }> =>\n event.kind === 'seat-segment' && event.id === this.nodeId,\n )\n await this.reconcile(events)\n const last = events.filter((event) => event.phase === 'started').at(-1)\n if (\n last &&\n !events.some((event) => event.phase === 'ended' && event.segmentIndex === last.segmentIndex)\n ) {\n await this.end(last, reason)\n }\n }\n\n private async end(\n start: Extract<SpawnEvent, { kind: 'seat-segment' }>,\n reason: 'usage-limit' | 'completed' | 'failed' | 'cancelled' | 'paused',\n ): Promise<void> {\n const at = new Date(this.now()).toISOString()\n await this.journal.appendEvent(this.rootId, { ...start, phase: 'ended', reason, at })\n await this.onSegment?.(\n {\n seat: start.seat,\n harness: start.harness,\n provider: start.provider,\n model: start.model,\n startedAt: start.at,\n endedAt: at,\n reason,\n },\n 'ended',\n )\n this.observedThrough += 1\n }\n\n /** A crash may land between the authoritative journal append and observer delivery. On\n * reconstruction, deliver every unobserved boundary again; the observer projection folds\n * repeated boundaries by seat and start time, so a callback never decides execution identity. */\n private async reconcile(\n events: readonly Extract<SpawnEvent, { kind: 'seat-segment' }>[],\n ): Promise<void> {\n const starts = new Map<number, Extract<SpawnEvent, { kind: 'seat-segment' }>>()\n for (let index = 0; index < events.length; index += 1) {\n const event = events[index]!\n if (event.phase === 'started') starts.set(event.segmentIndex, event)\n if (index <= this.observedThrough) continue\n const start = event.phase === 'started' ? event : starts.get(event.segmentIndex)\n if (!start) throw new ValidationError('seat segment ended without a committed start')\n await this.onSegment?.(\n {\n seat: start.seat,\n harness: start.harness,\n provider: start.provider,\n model: start.model,\n startedAt: start.at,\n ...(event.phase === 'ended' ? { endedAt: event.at, reason: event.reason } : {}),\n },\n event.phase,\n )\n this.observedThrough = index\n }\n }\n}\n\n/** Preserve the authored profile for identity; only the provider-facing copy changes stages. */\nexport function seatExecutionProfile(profile: AgentProfile, stage: SeatStage): AgentProfile {\n const { seats: _seats, ...withoutSeats } = profile as AgentProfile & { seats?: unknown }\n return {\n ...withoutSeats,\n harness: stage.harness as AgentProfile['harness'],\n ...(stage.tools === undefined ? {} : { tools: stage.tools }),\n ...(stage.permissions === undefined ? {} : { permissions: stage.permissions }),\n model: {\n ...profile.model,\n default: stage.model,\n provider: stage.provider,\n ...(stage.reasoningEffort === undefined ? {} : { reasoningEffort: stage.reasoningEffort }),\n ...(stage.credentialSource === undefined\n ? {}\n : { metadata: { ...profile.model?.metadata, credentialSource: stage.credentialSource } }),\n },\n } as AgentProfile\n}\n\nexport function authoredSeatStages(profile: AgentProfile): readonly SeatStage[] | undefined {\n const seats = (profile as AgentProfile & { seats?: unknown }).seats\n if (seats === undefined) return undefined\n if (!Array.isArray(seats) || seats.length === 0) {\n throw new ValidationError('AgentProfile.seats must be a nonempty ordered chain')\n }\n return seats as SeatStage[]\n}\n\nconst USAGE_LIMIT_CODES = new Set([\n // A harness turn's outcome code for its exhausted subscription quota: the Sandbox sidecar's\n // `rate_limit_event rejected`, and the exact result agent-provider-tangle refuses with it.\n 'provider_quota_exhausted',\n 'subscription_usage_limit',\n 'usage_limit_reached',\n 'usage_limit_exceeded',\n 'weekly_limit_reached',\n 'session_limit_reached',\n])\n\n/** Normalize a native harness refusal into a typed limit. A plain HTTP 429 is insufficient. */\nexport function subscriptionUsageLimitSignal(failure: {\n readonly error: string\n readonly errorCode?: string\n}): 'subscription-usage-limit' | undefined {\n if (failure.errorCode && USAGE_LIMIT_CODES.has(failure.errorCode.toLowerCase())) {\n return 'subscription-usage-limit'\n }\n // Native Codex and Claude Code often expose their limit only as an exact CLI stop message.\n // Claude Code reports exhausted extra-usage credits as \"You've hit your monthly spend limit ·\n // raise it at https://claude.ai/settings/usage\" (drew-gtr-pro).\n if (/\\bYou've hit your (?:usage|weekly|session|monthly spend) limit\\b/iu.test(failure.error)) {\n return 'subscription-usage-limit'\n }\n // The Z.ai Coding Plan (OpenCode, zai-coding-plan/*) states its rolling-window refusal only in words:\n // \"Usage limit reached for 5 hour. Your limit will reset at ...\" (drew-gtr-pro).\n if (/\\bUsage limit reached for \\d+ hours?\\b/iu.test(failure.error)) {\n return 'subscription-usage-limit'\n }\n return undefined\n}\n\n/** An ineligible or misconfigured account must never turn an authored stage into another model. */\nfunction checkedSeatSelection(stage: SeatStage, selected: SeatSelection): SeatSelection {\n if ('resumeAt' in selected) {\n if (!Number.isFinite(Date.parse(selected.resumeAt))) {\n throw new ValidationError('selectSeat: resumeAt must be an ISO timestamp')\n }\n return selected\n }\n if (!selected.seat.trim()) throw new ValidationError('selectSeat: seat must be nonempty')\n if (stage.selector.kind === 'seat' && stage.selector.id !== selected.seat) {\n throw new ValidationError('selectSeat: selection does not match the authored seat')\n }\n if (selected.backend.backend !== 'provider') {\n throw new ValidationError('selectSeat: selection must use a provider backend')\n }\n return selected\n}\n","import type { NodeStatus } from './types'\n\n/** Which {@link NodeStatus} values mean the node is finished. */\nconst terminalNodeStatuses: ReadonlySet<NodeStatus> = new Set<NodeStatus>([\n 'done',\n 'failed',\n 'cancelled',\n])\n\n/**\n * True once a node has reached a terminal status.\n *\n * The single owner of this rule. Written per call site it drifts silently: a status added to\n * `NodeStatus` is classified by whichever sites the author remembered, and the ones they missed\n * keep a dead node in the live set — a stop rule that never fires, mail delivered to a worker that\n * cannot read it, or a cancel answered `not_live` for a node that is still running.\n */\nexport function isTerminalNodeStatus(status: NodeStatus): boolean {\n return terminalNodeStatuses.has(status)\n}\n\n/** True while a node has not yet reached a terminal status. The complement of\n * {@link isTerminalNodeStatus}, so the two can never disagree. */\nexport function isLiveNodeStatus(status: NodeStatus): boolean {\n return !terminalNodeStatuses.has(status)\n}\n","/**\n *\n * The LIVE read-model of a still-RUNNING worker — what a driver can see BEFORE the worker settles.\n *\n * Until this existed, `observe_agent` on a running worker returned `{status:'running', spent:{0,0},\n * outRef:null, output:null}`: nothing a brain could act on, so a brain that wanted to steer had no\n * evidence to steer FROM. This is the other half of the steering wire (the first half is\n * `Executor.deliver`): a supervisor cannot correct a worker it cannot watch.\n *\n * Two layers, both pull-based — no timer, no background task, so it is safe to leave on:\n *\n * - The SCOPE layer, available for EVERY executor with no executor cooperation at all: usage\n * events are timestamped as they arrive, so `lastActivityAt` / `idleMs` / `stalled` /\n * `tokens` / `turns` are derived from the stream the conserved pool already meters.\n * - The EXECUTOR layer, optional enrichment via `Executor.progress()`: the tool/file activity\n * the harness exposes, its own turn count, and how many steers are queued but unread.\n *\n * `stalled` is a DERIVED read, computed at observation time against `stallAfterMs` — never a\n * background watchdog. A worker that has produced no metered activity for longer than the\n * threshold reads `stalled: true`; nothing is killed, nothing is retried. The driver decides.\n *\n * @experimental\n */\n\nimport { isLiveNodeStatus } from './node-status'\nimport { addResourceSpend } from './resources'\nimport type { NodeStatus, Spend } from './types'\n\n/** How long a worker may produce no metered activity before a `progress()` read calls it stalled.\n * Deliberately generous: a coding harness routinely spends minutes inside one tool call, and a\n * false stall that provokes a steer is worse than a late one. */\nexport const DEFAULT_STALL_AFTER_MS = 180_000\n\n/** The most recent activity the executor can name — one tool call, one turn, or a free-form note.\n * `label` is the tool/file/turn name; `detail` is a short, already-truncated descriptor (a path,\n * a command head) that a driver can read without pulling the whole transcript. */\nexport interface ActivityNote {\n readonly at: number\n readonly kind: 'turn' | 'tool' | 'note'\n readonly label: string\n readonly status?: 'ok' | 'error'\n readonly detail?: string\n}\n\n/** What an executor OPTIONALLY adds to the scope-derived progress (`Executor.progress()`). Every\n * field is optional: an executor that knows only its own turn count reports only that. */\nexport interface ExecutorProgress {\n /** The executor's own turn/step count when it is more meaningful than metered iterations. */\n readonly turns?: number\n /** Steers/answers delivered but not yet folded into the worker's conversation. */\n readonly pendingMessages?: number\n /** Newest-last window of what the worker has been doing. */\n readonly recentActivity?: ReadonlyArray<ActivityNote>\n /**\n * What the executor CHANGED about what the caller declared, one short line each — an MCP config\n * it materialized, an extension it had to add for the caller's own servers to mount at all.\n *\n * Deliberately NOT part of `recentActivity`: that is a bounded newest-last ring, so a derived\n * change made before the first turn is evicted by turn 13 and gone by the time anyone looks. And\n * deliberately not only on the settled artifact: a run that fails on turn 40 never produces one,\n * yet \"what was this worker actually given?\" is exactly the question a failure raises. This\n * channel is append-only and readable at any moment, including from a run that never finishes.\n */\n readonly derived?: ReadonlyArray<string>\n /** A one-line human-readable state (\"turn 3, running tests\"). */\n readonly note?: string\n}\n\n/** The team a worker leads, as its own lead observes it mid-flight: every agent below the worker,\n * at every depth. A lead reads this instead of the team's raw outputs, so the read stays bounded\n * however large the team grows. */\nexport interface TeamProgress {\n /** Agents spawned below the worker, at every depth. */\n readonly agents: number\n /** Levels below the worker: `1` when it leads only workers that lead no one. */\n readonly depth: number\n /** Agents below it that hold a worker slot and are running. */\n readonly working: number\n /** Agents below it waiting for a worker slot. */\n readonly queued: number\n /** Agents below it that settled done. */\n readonly done: number\n /** Agents below it that settled down or were cancelled. */\n readonly down: number\n}\n\n/** The full live view of one worker, as `observe_agent` returns it mid-flight. */\nexport interface WorkerProgress {\n readonly id: string\n readonly status: NodeStatus\n /** True while the node is neither done, failed, nor cancelled — i.e. a steer could still land. */\n readonly live: boolean\n /** True when this worker's executor exposes an inbox (`Executor.deliver`) — i.e. `steer_agent`\n * can actually reach it. False means a steer would be recorded and dropped. */\n readonly steerable: boolean\n readonly startedAt: number\n /** Epoch ms of the last metered usage event or executor-reported activity. For a worker that\n * leads a team, the newest activity anywhere in that team counts, its own turns included. */\n readonly lastActivityAt: number\n readonly idleMs: number\n /** Live, not waiting for a worker slot, and idle past `stallAfterMs`. */\n readonly stalled: boolean\n readonly stallAfterMs: number\n /** Metered iterations so far (the executor's own count when it reports one). */\n readonly turns: number\n readonly tokens: { readonly input: number; readonly output: number }\n /** False when observed `tokens` is only a known subtotal, not a complete total — the worker did\n * work whose token count its provider never reported. The twin of `usdKnown`, carried for the\n * same reason: a driver reading this over `observe_agent` would otherwise read the subtotal as\n * the measurement and conclude a busy worker was cheap. */\n readonly tokensKnown?: boolean\n readonly usd: number\n /** False when observed dollar spend is only a known subtotal, not a complete total. */\n readonly usdKnown?: boolean\n readonly resources?: Spend['resources']\n /** Steers delivered but not yet read by the worker. */\n readonly pendingMessages: number\n /** Newest-last window of tool/turn activity; empty when the executor exposes none. */\n readonly recentActivity: ReadonlyArray<ActivityNote>\n /** What the executor changed about the caller's declaration; absent when it changed nothing.\n * Unlike `recentActivity` this is never evicted, so it still answers on a failed run. */\n readonly derived?: ReadonlyArray<string>\n readonly note?: string\n /** The team this worker leads; absent while it leads no one. */\n readonly team?: TeamProgress\n}\n\n/** A bounded newest-last ring of `ActivityNote`s an executor keeps to answer `progress()`. */\nexport interface ActivityLog {\n push(note: ActivityNote): void\n /** Newest-last, at most `limit` entries. */\n read(): ReadonlyArray<ActivityNote>\n last(): ActivityNote | undefined\n size(): number\n}\n\n/** A short, already-truncated descriptor of a tool call's target — the file/command a driver\n * needs to tell \"editing the right module\" from \"re-reading the same file for the fifth time\",\n * without pulling the worker's transcript across the wire. Shared by every executor that fills an\n * `ActivityLog` (pi RPC, sandbox session parts, cli-bridge tool-call deltas) so one harness's\n * argument naming never reads differently from another's in the same driver's window. */\nexport function describeToolArgs(argsValue: unknown): string | undefined {\n if (!argsValue || typeof argsValue !== 'object') return undefined\n const a = argsValue as Record<string, unknown>\n for (const key of ['filePath', 'file_path', 'path', 'file', 'command', 'cmd', 'pattern']) {\n const v = a[key]\n if (typeof v === 'string' && v.length > 0) return v.length > 120 ? `${v.slice(0, 117)}...` : v\n }\n return undefined\n}\n\n/** Create a bounded activity ring. `limit` caps memory for a worker that runs thousands of tools. */\nexport function createActivityLog(limit = 12): ActivityLog {\n const notes: ActivityNote[] = []\n const cap = Math.max(1, Math.floor(limit))\n return {\n push(note) {\n notes.push(note)\n if (notes.length > cap) notes.splice(0, notes.length - cap)\n },\n read: () => [...notes],\n last: () => notes[notes.length - 1],\n size: () => notes.length,\n }\n}\n\n/** The scope-side facts about a child, independent of whether its executor cooperates. */\nexport interface ScopeProgressInput {\n readonly id: string\n readonly status: NodeStatus\n readonly steerable: boolean\n readonly startedAt: number\n readonly lastActivityAt: number\n readonly turns: number\n readonly tokens: { readonly input: number; readonly output: number }\n readonly tokensKnown?: boolean\n readonly usd: number\n readonly usdKnown?: boolean\n readonly resources?: Spend['resources']\n /** The team the worker leads, when it leads one. */\n readonly team?: TeamProgress\n}\n\n/** Fold the scope-derived facts and the executor's optional enrichment into one read. Pure: the\n * caller supplies `now`, so a test can observe a stall without waiting for one. */\nexport function readWorkerProgress(\n scope: ScopeProgressInput,\n executor: ExecutorProgress | undefined,\n now: number,\n stallAfterMs: number = DEFAULT_STALL_AFTER_MS,\n): WorkerProgress {\n const live = isLiveNodeStatus(scope.status)\n // An executor-reported activity is newer evidence than the last metered usage event: a harness\n // can run a five-minute tool call without emitting a single token.\n const executorActivityAt = executor?.recentActivity?.length\n ? (executor.recentActivity[executor.recentActivity.length - 1] as ActivityNote).at\n : 0\n const lastActivityAt = Math.max(scope.lastActivityAt, executorActivityAt)\n const idleMs = Math.max(0, now - lastActivityAt)\n const note = executor?.note\n return {\n ...addResourceSpend(scope.resources),\n id: scope.id,\n status: scope.status,\n live,\n steerable: scope.steerable,\n startedAt: scope.startedAt,\n lastActivityAt,\n idleMs,\n // Only a LIVE worker can stall; a settled one is simply finished, and a queued one has not\n // started: it waits for a worker slot, which no steer or cancel would free any sooner.\n stalled: live && scope.status !== 'queued' && idleMs > stallAfterMs,\n stallAfterMs,\n turns: executor?.turns ?? scope.turns,\n tokens: scope.tokens,\n // Both markers are carried the same way and only when false, so an unmarked read means the\n // channel is measured — never \"the fold forgot to pass it through\".\n ...(scope.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: scope.usd,\n ...(scope.usdKnown === false ? { usdKnown: false } : {}),\n pendingMessages: executor?.pendingMessages ?? 0,\n recentActivity: executor?.recentActivity ?? [],\n // Absent rather than empty, so \"this executor derived nothing\" and \"this executor does not\n // report derivations\" read the same way — neither is a claim that nothing was changed.\n ...(executor?.derived?.length ? { derived: executor.derived } : {}),\n ...(note ? { note } : {}),\n ...(scope.team ? { team: scope.team } : {}),\n }\n}\n","import {\n type AgentCandidateArtifactRef,\n type AgentExactRunControlRef,\n AgentExactRunControlRefSchema,\n agentCandidateArtifactRefSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n} from '@tangle-network/agent-interface'\nimport { z } from 'zod'\nimport { verifiedArtifactChunks } from '../candidate-execution/artifact-streams'\nimport { deepFreezeCandidate, sha256Bytes } from '../candidate-execution/digest'\nimport type { AgentCandidateArtifactPort } from '../candidate-execution/types'\nimport type { AgentCandidateWorkspaceArchiveLimits } from '../candidate-execution/workspace-archive'\nimport { safeArchivePath, workspaceLimits } from '../candidate-execution/workspace-archive'\nimport { readAgentCandidateWorkspaceArtifactFiles } from '../candidate-execution/workspace-streams'\nimport { ValidationError } from '../errors'\nimport type {\n HarnessTranscriptArtifact,\n HarnessTranscriptBinding,\n HarnessTranscriptCapture,\n HarnessTranscriptFile,\n HarnessTranscriptUnavailable,\n} from './harness-transcript'\nimport type { ProviderWorkspaceCaptureReceipt } from './provider-workspace-retention'\nimport { runAbortable } from './supervise/abortable'\nimport type { ExecutorNodeContext } from './supervise/types'\n\nconst digest = z.custom<`sha256:${string}`>(\n (value) => typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value),\n)\nconst count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nconst text = z.string().min(1)\nconst node = z.custom<ExecutorNodeContext>((value) => {\n if (value === null || typeof value !== 'object') return false\n return ['rootId', 'parentId', 'nodeId', 'attemptId'].every(\n (key) => typeof Reflect.get(value, key) === 'string',\n )\n})\nconst sourceSchema = z.object({\n executionId: text,\n controlRef: AgentExactRunControlRefSchema.optional(),\n node: node.optional(),\n environmentId: text,\n profileDigest: digest,\n providerSessionId: text.nullable(),\n nativeSessionId: text.nullable(),\n coverageComplete: z.boolean(),\n incompleteReason: z.string().optional(),\n})\nconst attributionSchema = z.object({\n providerSessionId: text,\n sourceId: text.optional(),\n rootScope: z.enum(['session-home', 'workspace-session']),\n nativePath: text,\n})\nconst fileSchema = z.object({\n path: text,\n bytes: count,\n sha256: digest,\n attribution: attributionSchema,\n})\nconst skippedSchema = z.object({ path: text, reason: text })\nconst retainedSchema = z.object({\n kind: z.literal('retained-harness-transcript'),\n schemaVersion: z.literal(1),\n harness: text,\n source: sourceSchema,\n provider: z.string().optional(),\n capturedAt: z.string().optional(),\n snapshot: z.object({\n kind: z.literal('agent-candidate-workspace-snapshot'),\n digest,\n manifest: agentCandidateArtifactRefSchema,\n archive: agentCandidateArtifactRefSchema,\n }),\n files: z.array(fileSchema),\n skipped: z.array(skippedSchema),\n missing: z.array(z.string()),\n})\n\n/** Inventory and source identity only; native bytes remain in the original workspace archive. */\nexport interface RetainedHarnessTranscriptDescriptor {\n readonly kind: 'retained-harness-transcript'\n readonly schemaVersion: 1\n readonly harness: string\n readonly source: {\n readonly executionId: string\n readonly controlRef?: AgentExactRunControlRef\n readonly node?: ExecutorNodeContext\n readonly environmentId: string\n readonly profileDigest: `sha256:${string}`\n readonly providerSessionId: string | null\n readonly nativeSessionId: string | null\n readonly coverageComplete: boolean\n readonly incompleteReason?: string\n }\n readonly provider?: string\n readonly capturedAt?: string\n readonly snapshot: {\n readonly kind: 'agent-candidate-workspace-snapshot'\n readonly digest: `sha256:${string}`\n readonly manifest: AgentCandidateArtifactRef\n readonly archive: AgentCandidateArtifactRef\n }\n readonly files: readonly {\n readonly path: string\n readonly bytes: number\n readonly sha256: `sha256:${string}`\n readonly attribution: {\n readonly providerSessionId: string\n readonly sourceId?: string\n readonly rootScope: 'session-home' | 'workspace-session'\n readonly nativePath: string\n }\n }[]\n readonly skipped: readonly { readonly path: string; readonly reason: string }[]\n readonly missing: readonly string[]\n}\nexport interface RetainedHarnessTranscriptCapture {\n readonly status: 'retained'\n readonly descriptor: RetainedHarnessTranscriptDescriptor\n readonly fileCount: number\n readonly totalBytes: number\n readonly skippedCount: number\n}\n\nexport interface HarnessTranscriptMetadata {\n readonly schemaVersion: 1\n readonly harness: string\n readonly binding?: HarnessTranscriptBinding\n readonly files: readonly {\n readonly path: string\n readonly bytes: number\n readonly sha256: string\n readonly attribution?: RetainedHarnessTranscriptDescriptor['files'][number]['attribution']\n }[]\n readonly skipped: readonly { readonly path: string; readonly reason: string }[]\n readonly source?: RetainedHarnessTranscriptDescriptor['source']\n readonly missing?: readonly string[]\n readonly provider?: string\n readonly capturedAt?: string\n}\n\n/** Projection limits do not change what the original archive retained. */\nexport interface HarnessTranscriptReadLimits {\n readonly maxFileBytes: number\n readonly maxTotalBytes: number\n readonly maxFiles: number\n readonly maxManifestBytes: number\n}\nexport interface HarnessTranscriptReadOptions {\n readonly content?: boolean\n readonly artifacts?: AgentCandidateArtifactPort\n readonly limits?: Partial<HarnessTranscriptReadLimits>\n readonly workspaceLimits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n readonly signal?: AbortSignal\n}\n/** One native capture/read bound per child; replay resolves references rather than copying bytes. */\nexport const HARNESS_TRANSCRIPT_READ_LIMITS: HarnessTranscriptReadLimits = Object.freeze({\n maxFileBytes: 2 * 1024 * 1024,\n maxTotalBytes: 16 * 1024 * 1024,\n maxFiles: 1_000,\n maxManifestBytes: 16 * 1024 * 1024,\n})\n\n/** Validate persisted descriptors before trusting their identity, locators, or inventory. */\nexport function parseRetainedHarnessTranscript(\n value: unknown,\n): RetainedHarnessTranscriptDescriptor {\n const parsed = retainedSchema.safeParse(value)\n if (!parsed.success)\n throw new ValidationError(`Invalid retained harness transcript: ${parsed.error.message}`)\n const paths = new Set<string>()\n for (const file of parsed.data.files) {\n if (paths.has(file.path))\n throw new ValidationError(`Retained transcript repeats native identity: ${file.path}`)\n paths.add(file.path)\n if (file.path !== nativeIdentity(file.attribution))\n throw new ValidationError(\n `Retained transcript native identity does not match its attribution: ${file.path}`,\n )\n }\n return deepFreezeCandidate(parsed.data)\n}\n\nfunction nativeIdentity(attribution: z.infer<typeof attributionSchema>): string {\n return (\n [attribution.providerSessionId, attribution.sourceId ?? '', attribution.rootScope]\n .map(encodeURIComponent)\n .join('/') +\n '/' +\n attribution.nativePath\n )\n}\n\n/** Describe already-verified retention, without reading the environment or copying archive bytes. */\nexport function retainHarnessTranscript(\n receipt: ProviderWorkspaceCaptureReceipt,\n harness: string,\n): RetainedHarnessTranscriptCapture | HarnessTranscriptUnavailable {\n try {\n return retainedCapture(receipt, harness)\n } catch (error) {\n if (error instanceof ValidationError) throw error\n throw new ValidationError(\n `Invalid retained transcript receipt: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\nfunction retainedCapture(\n receipt: ProviderWorkspaceCaptureReceipt,\n harness: string,\n): RetainedHarnessTranscriptCapture | HarnessTranscriptUnavailable {\n const { snapshot, provenance, ...source } = receipt\n const files: Array<RetainedHarnessTranscriptDescriptor['files'][number]> = []\n const skipped: Array<RetainedHarnessTranscriptDescriptor['skipped'][number]> = []\n const missing = [...provenance.missing]\n for (const session of provenance.sessions ?? []) {\n if (session.executionId !== receipt.executionId || session.backendType !== harness)\n throw new ValidationError('Retained transcript session has a different execution or harness')\n if (!session.nativeStore) {\n missing.push(`Session ${session.id} native inventory unavailable`)\n continue\n }\n if (!session.nativeStore.complete)\n missing.push(`Session ${session.id} native inventory incomplete`)\n for (const entry of session.nativeStore.entries) {\n if (entry.kind !== 'file') continue\n const attribution = {\n providerSessionId: session.id,\n ...(entry.sourceId === undefined ? {} : { sourceId: entry.sourceId }),\n rootScope: entry.rootScope,\n nativePath: entry.path,\n }\n const parsed = fileSchema.safeParse({\n path: nativeIdentity(attribution),\n bytes: entry.sizeBytes,\n sha256: entry.sha256,\n attribution,\n })\n if (parsed.success) files.push(parsed.data)\n else {\n const reason = `Native inventory cannot identify verified bytes: ${parsed.error.message}`\n skipped.push({ path: nativeIdentity(attribution), reason })\n missing.push(`${nativeIdentity(attribution)}: ${reason}`)\n }\n }\n for (const entry of session.nativeStore.excludedPaths) {\n skipped.push({\n path: nativeIdentity({\n providerSessionId: session.id,\n ...(entry.sourceId === undefined ? {} : { sourceId: entry.sourceId }),\n rootScope: entry.rootScope,\n nativePath: entry.path,\n }),\n reason: entry.reason,\n })\n }\n }\n if (files.length === 0) missing.push('No native files declared by provider capture')\n const descriptor = parseRetainedHarnessTranscript({\n kind: 'retained-harness-transcript',\n schemaVersion: 1,\n harness,\n source,\n ...(provenance.provider === undefined ? {} : { provider: provenance.provider }),\n ...(provenance.capturedAt === undefined ? {} : { capturedAt: provenance.capturedAt }),\n snapshot: {\n kind: snapshot.kind,\n digest: snapshot.digest,\n manifest: snapshot.manifest,\n archive: snapshot.archive,\n },\n files,\n skipped,\n missing,\n })\n if (files.length === 0)\n return deepFreezeCandidate({\n status: 'unavailable' as const,\n reason:\n source.coverageComplete && skipped.length === 0\n ? ('no-transcript' as const)\n : ('nothing-carried' as const),\n skipped: [...skipped, ...missing.map((reason) => ({ path: receipt.executionId, reason }))],\n })\n return deepFreezeCandidate({\n status: 'retained' as const,\n descriptor,\n fileCount: files.length,\n totalBytes: files.reduce((sum, file) => sum + file.bytes, 0),\n skippedCount: skipped.length,\n })\n}\n\n/** Read native metadata without archive I/O, or verify retained bytes before projecting bounded text. */\nexport function resolveHarnessTranscriptCapture(\n capture: HarnessTranscriptCapture,\n options: HarnessTranscriptReadOptions & { content: false },\n): Promise<HarnessTranscriptMetadata | undefined>\nexport function resolveHarnessTranscriptCapture(\n capture: HarnessTranscriptCapture,\n options?: HarnessTranscriptReadOptions & { content?: true },\n): Promise<HarnessTranscriptArtifact | undefined>\nexport async function resolveHarnessTranscriptCapture(\n capture: HarnessTranscriptCapture,\n options: HarnessTranscriptReadOptions = {},\n): Promise<HarnessTranscriptArtifact | HarnessTranscriptMetadata | undefined> {\n if (capture.status === 'unavailable') return undefined\n if (capture.status === 'captured') {\n const limits = { ...HARNESS_TRANSCRIPT_READ_LIMITS, ...options.limits }\n if (capture.artifact.files.length > limits.maxFiles)\n throw new ValidationError('Transcript exceeds maxFiles')\n let total = 0\n const paths = new Set<string>()\n for (const file of capture.artifact.files) {\n options.signal?.throwIfAborted()\n if (HARNESS_TRANSCRIPT_DENY.test(file.path) || paths.has(file.path))\n throw new ValidationError('Transcript path is denied or repeated')\n paths.add(file.path)\n total += file.bytes\n if (\n Buffer.byteLength(file.content, 'utf8') !== file.bytes ||\n file.bytes > limits.maxFileBytes ||\n total > limits.maxTotalBytes\n )\n throw new ValidationError(`Transcript file violates its byte bound: ${file.path}`)\n }\n if (options.content !== false) return capture.artifact\n return {\n ...capture.artifact,\n files: capture.artifact.files.map(({ path, bytes, content }) => ({\n path,\n bytes,\n sha256: sha256Bytes(Buffer.from(content)),\n })),\n }\n }\n const descriptor = parseRetainedHarnessTranscript(capture.descriptor)\n if (options.content === false) {\n const { snapshot: _snapshot, kind: _kind, ...metadata } = descriptor\n return metadata\n }\n if (!options.artifacts)\n throw new ValidationError('Retained transcript content requires an ArtifactPort')\n const limits = { ...HARNESS_TRANSCRIPT_READ_LIMITS, ...options.limits }\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value < 0)\n throw new ValidationError(`Invalid transcript read limit: ${name}`)\n }\n if (descriptor.snapshot.manifest.byteLength > limits.maxManifestBytes)\n throw new ValidationError('Retained transcript manifest exceeds maxManifestBytes')\n const manifestChunks: Uint8Array[] = []\n for await (const chunk of verifiedArtifactChunks(\n descriptor.snapshot.manifest,\n options.artifacts,\n options.signal,\n ))\n manifestChunks.push(Uint8Array.from(chunk))\n const material = agentCandidateWorkspaceManifestMaterialSchema.parse(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(manifestChunks))),\n )\n const snapshot = { ...descriptor.snapshot, material }\n // The inventory supplies attribution. An archive copy only supplies content with that exact digest.\n const byContent = new Map<string, string>()\n for (const file of material.files) byContent.set(`${file.sha256}:${file.byteLength}`, file.path)\n const selected: {\n file: RetainedHarnessTranscriptDescriptor['files'][number]\n archivePath: string\n }[] = []\n const skipped = [...descriptor.skipped]\n let total = 0\n for (const file of descriptor.files) {\n const archivePath = byContent.get(`${file.sha256}:${file.bytes}`)\n if (archivePath === undefined)\n throw new ValidationError(`Retained native file is missing from archive: ${file.path}`)\n const reason =\n file.bytes > limits.maxFileBytes\n ? 'read-limit:maxFileBytes'\n : selected.length >= limits.maxFiles\n ? 'read-limit:maxFiles'\n : total + file.bytes > limits.maxTotalBytes\n ? 'read-limit:maxTotalBytes'\n : undefined\n if (reason) skipped.push({ path: file.path, reason })\n else {\n selected.push({ file, archivePath })\n total += file.bytes\n }\n }\n const contents = await readAgentCandidateWorkspaceArtifactFiles({\n role: 'candidate',\n snapshot,\n artifacts: options.artifacts,\n paths: [...new Set(selected.map(({ archivePath }) => archivePath))],\n maxReadBytes: limits.maxTotalBytes,\n ...(options.workspaceLimits === undefined ? {} : { limits: options.workspaceLimits }),\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n const files: HarnessTranscriptFile[] = []\n for (const { file, archivePath } of selected) {\n const bytes = contents.get(archivePath)\n if (bytes === undefined)\n throw new ValidationError(`Verified native file was not returned: ${file.path}`)\n try {\n const content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)\n if (content.includes('\\0')) throw new Error('NUL in native file')\n files.push({ path: file.path, bytes: file.bytes, content })\n } catch {\n skipped.push({\n path: file.path,\n reason: 'binary-or-invalid-utf8; bytes remain retained in workspace archive',\n })\n }\n }\n return deepFreezeCandidate({\n schemaVersion: 1 as const,\n harness: descriptor.harness,\n source: descriptor.source,\n files,\n skipped,\n })\n}\n\n/** Credential-shaped paths are refused even when a producer lists them. */\nexport const HARNESS_TRANSCRIPT_DENY =\n /(^|\\/)(auth\\.json|\\.credentials\\.json|credentials|\\.netrc|\\.env(\\..*)?|secrets?(\\.|$)|.*\\.(pem|key|p12|pfx)|id_[a-z0-9_]+)$/iu\n\nexport interface BoundHarnessSession {\n readonly nativeSessionId: string\n readonly parentNativeSessionId?: string | null\n readonly children: readonly { readonly nativeSessionId: string }[]\n readonly integrity: {\n readonly truncated: boolean\n readonly unparsedRecords: number\n readonly gaps: readonly unknown[]\n }\n}\nexport interface HarnessFileBinding {\n readonly path: string\n readonly nativeSessionId: string\n readonly sha256?: string\n readonly byteLength?: number\n}\n\n/** Verify a bound native family without owning a store, filesystem layout or native parser. */\nexport async function readBoundHarnessSessions<S extends BoundHarnessSession>(input: {\n readonly nativeSessionId: string\n readonly files: readonly HarnessFileBinding[]\n readonly read: (file: HarnessFileBinding, signal?: AbortSignal) => Promise<Uint8Array>\n readonly parse: (text: string, file: HarnessFileBinding) => S\n readonly signal?: AbortSignal\n}) {\n const files: { path: string; nativeSessionId: string; sha256: string; byteLength: number }[] = []\n const sessions = new Map<string, S>()\n const parents = new Map<string, string>()\n const paths = new Set<string>()\n const pathBytes = workspaceLimits(undefined).maxPathBytes\n const pending = [input.nativeSessionId]\n let total = 0\n while (pending.length) {\n const id = pending.shift()!\n if (sessions.has(id)) continue\n const candidates = input.files.filter((file) => file.nativeSessionId === id)\n if (!candidates.length)\n throw new ValidationError('The exact native session or a recorded child was not retained')\n for (const file of candidates) {\n input.signal?.throwIfAborted()\n if (files.length >= HARNESS_TRANSCRIPT_READ_LIMITS.maxFiles)\n throw new ValidationError('Native file count exceeds the capture bound')\n safeArchivePath(file.path, pathBytes)\n if (HARNESS_TRANSCRIPT_DENY.test(file.path) || paths.has(file.path))\n throw new ValidationError('Native file path is denied or repeated')\n paths.add(file.path)\n const read = () => input.read(file, input.signal)\n const bytes = input.signal\n ? await runAbortable(read, input.signal, 'Native source read stopped')\n : await read()\n total += bytes.byteLength\n if (\n bytes.byteLength > HARNESS_TRANSCRIPT_READ_LIMITS.maxFileBytes ||\n total > HARNESS_TRANSCRIPT_READ_LIMITS.maxTotalBytes\n )\n throw new ValidationError('Native bytes exceed the capture bound')\n const actual = sha256Bytes(bytes)\n if (\n (file.sha256 && file.sha256.replace(/^sha256:/, '') !== actual.slice(7)) ||\n (file.byteLength !== undefined && file.byteLength !== bytes.byteLength)\n )\n throw new ValidationError('Captured native session bytes changed')\n const session = input.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes), file)\n if (\n session.nativeSessionId !== id ||\n session.integrity.truncated ||\n session.integrity.unparsedRecords ||\n session.integrity.gaps.length\n )\n throw new ValidationError('Native session identity or integrity did not match its binding')\n if (\n session.parentNativeSessionId &&\n parents.has(id) &&\n session.parentNativeSessionId !== parents.get(id)\n )\n throw new ValidationError('Native child has a different recorded parent')\n const prior = files.find((value) => value.nativeSessionId === id)\n if (prior && prior.sha256 !== actual)\n throw new ValidationError('Native session copies are ambiguous')\n files.push({\n path: file.path,\n nativeSessionId: id,\n sha256: actual,\n byteLength: bytes.byteLength,\n })\n if (!prior) sessions.set(id, session)\n }\n for (const child of sessions.get(id)!.children) {\n if (parents.has(child.nativeSessionId) && parents.get(child.nativeSessionId) !== id)\n throw new ValidationError('Native child has ambiguous recorded parents')\n parents.set(child.nativeSessionId, id)\n if (!sessions.has(child.nativeSessionId)) pending.push(child.nativeSessionId)\n }\n }\n return { files, sessions: [...sessions.values()] }\n}\n","/**\n * Persist a harness transcript receipt beside the supervisor tool trace.\n * Provider workspace retention supplies an attributed descriptor whose bytes stay in the\n * original verified archive. Environments without retention use the bounded read/exec\n * fallback below. Neither path embeds transcript content in settlement events.\n * Readers request metadata without archive I/O, or explicitly resolve bounded text content.\n */\nimport { deepFreezeCandidate } from '../candidate-execution/digest'\nimport { contentAddress } from '../durable/content-address'\nimport { ValidationError } from '../errors'\nimport {\n type BoundHarnessSession,\n HARNESS_TRANSCRIPT_DENY as DENY,\n HARNESS_TRANSCRIPT_READ_LIMITS,\n type HarnessTranscriptMetadata,\n type HarnessTranscriptReadOptions,\n parseRetainedHarnessTranscript,\n type RetainedHarnessTranscriptCapture,\n readBoundHarnessSessions,\n resolveHarnessTranscriptCapture,\n} from './retained-harness-transcript'\nimport type { ExecutorNodeContext, ResultBlobStore } from './supervise/types'\n\nconst {\n maxFileBytes: MAX_FILE_BYTES,\n maxTotalBytes: MAX_TOTAL_BYTES,\n maxFiles: MAX_FILES,\n} = HARNESS_TRANSCRIPT_READ_LIMITS\n\nexport {\n type BoundHarnessSession,\n HARNESS_TRANSCRIPT_READ_LIMITS,\n type HarnessFileBinding,\n type HarnessTranscriptMetadata,\n type HarnessTranscriptReadLimits,\n type HarnessTranscriptReadOptions,\n type RetainedHarnessTranscriptCapture,\n type RetainedHarnessTranscriptDescriptor,\n readBoundHarnessSessions,\n resolveHarnessTranscriptCapture,\n retainHarnessTranscript,\n} from './retained-harness-transcript'\n\n/** Where each harness keeps the session files that hold the conversation. */\nconst HARNESS_ROOTS: Readonly<Record<string, readonly string[]>> = Object.freeze({\n 'claude-code': Object.freeze(['.claude/projects', '.claude/history.jsonl', '.claude/todos']),\n codex: Object.freeze(['.codex/sessions', '.codex/history.jsonl']),\n // Current opencode keeps sessions in SQLite, which a text capture cannot carry. A shared-box\n // worker exports each session as JSON under `export`; a dedicated Tangle box's sidecar keeps\n // its own per-session record under `.opencode/sessions` and `.opencode/messages`, and the\n // capture exports each harness subagent session those records name under `export`\n // (`exportSubagentSessions`). The sidecar's records come first, so a subagent's export can\n // never push the agent's own record out of the byte budget.\n opencode: Object.freeze([\n '.opencode/sessions',\n '.opencode/messages',\n '.local/share/opencode/export',\n '.local/share/opencode/storage',\n '.local/share/opencode/log',\n ]),\n // Pi keeps a session tree per cwd; it had no entry, so a pi child captured nothing.\n pi: Object.freeze(['.pi/agent/sessions']),\n})\n\nexport const HARNESS_TRANSCRIPT_SCHEMA_VERSION = 1 as const\n\nexport interface HarnessTranscriptFile {\n readonly path: string\n readonly bytes: number\n readonly content: string\n}\n\nexport interface HarnessTranscriptBinding {\n readonly kind: 'bridge'\n readonly node?: ExecutorNodeContext\n readonly sessionId: string\n readonly nativeSessionId: string\n readonly profileDigest: string\n readonly runs: readonly { readonly runId: string; readonly requestDigest: string }[]\n}\n\nexport interface HarnessTranscriptArtifact {\n readonly schemaVersion: typeof HARNESS_TRANSCRIPT_SCHEMA_VERSION\n readonly harness: string\n readonly binding?: HarnessTranscriptBinding\n readonly source?: HarnessTranscriptMetadata['source']\n readonly files: readonly HarnessTranscriptFile[]\n /** Paths found but not read, with why — a gap named is a gap an operator can act on. */\n readonly skipped: readonly { readonly path: string; readonly reason: string }[]\n}\n\n/** Why no transcript reached a record, from either the capture or the settle path. */\nexport type HarnessTranscriptUnavailableReason =\n | 'unsupported-environment'\n | 'unknown-harness'\n | 'no-transcript'\n | 'enumeration-failed'\n /** No environment was ever created for this child, so there is no transcript and never\n * was one. The admission refusal of #1240 is the measured case: a budget pool that\n * refuses an unknown dollar cost kills the child before it runs. Distinct from\n * `unsupported-environment`, which means a box existed and could not be read. */\n | 'execution-never-started'\n /** An environment WAS created and the child ran, but the capture never executed — the\n * deadline/abort path closes the stream with `iterator.return()`, which runs the\n * generator's `finally` and skips its `catch`. Says only what is known: this child had a\n * transcript and nobody read it. Never collapse it into `execution-never-started`; that\n * would report a child that reasoned for twenty seconds as one that never ran. */\n | 'capture-did-not-run'\n /** Opted-in capture failed; the task result is retained independently. */\n | 'capture-failed'\n /** This executor implements no transcript port at all: a CLI, in-process, bridge, or\n * sandbox-session executor that has no capture yet. An absence by construction, never a\n * failure — and never a claim that the harness wrote nothing. */\n | 'executor-exposes-no-transcript'\n /** Session files were found and none was carried: every path was refused, over budget,\n * unreadable, or skipped by an abort. The `skipped` list beside this reason names each one,\n * so \"there was a transcript and it was not kept\" never reads as \"no transcript\". */\n | 'nothing-carried'\n /** The capture succeeded and the blob write did not. The transcript existed in memory and\n * never reached disk; mirrors `trace-persistence-failed` on the tool-span receipt. */\n | 'transcript-persistence-failed'\n /** Workspace bytes survived but their transcript descriptor could not be constructed. */\n | 'retained-projection-failed'\n\nexport interface HarnessTranscriptUnavailable {\n readonly status: 'unavailable'\n readonly reason: HarnessTranscriptUnavailableReason\n /** Present with `nothing-carried`: the paths that existed and why each was not read. */\n readonly skipped?: readonly { readonly path: string; readonly reason: string }[]\n}\n\n/**\n * What the executor holds before settlement: a retained descriptor, inline files, or absence.\n *\n * Never embedded in a settlement event. The scope persists it under its own content\n * ref and records the {@link HarnessTranscriptEvidence} receipt instead, so the settlement stays\n * small and a replay pays nothing for a transcript nobody opens.\n */\nexport type HarnessTranscriptCapture =\n | RetainedHarnessTranscriptCapture\n | {\n readonly status: 'captured'\n readonly artifact: HarnessTranscriptArtifact\n readonly fileCount: number\n readonly totalBytes: number\n /** Non-zero when some transcript was found but deliberately not carried. */\n readonly skippedCount: number\n readonly coverageComplete?: boolean\n readonly missing?: readonly string[]\n }\n | HarnessTranscriptUnavailable\n\n/**\n * The durable receipt on a settlement: a content-addressed pointer to a persisted\n * {@link HarnessTranscriptArtifact} or a retained descriptor, or the exact reason there is none. A SIBLING of the tool-span\n * `trace` receipt, never nested inside it — a dropped child has zero tool spans and an\n * unavailable trace, and it is precisely the child whose transcript this exists to keep.\n */\nexport type HarnessTranscriptEvidence =\n | {\n readonly status: 'available'\n /** Content-addressed pointer to a persisted `HarnessTranscriptArtifact` in the run's blobs. */\n readonly transcriptRef: string\n readonly harness: string\n readonly fileCount: number\n readonly totalBytes: number\n /** Non-zero when some transcript was found but deliberately not carried. */\n readonly skippedCount: number\n /** Retained source coverage, independent of text projection limits. */\n readonly coverageComplete?: boolean\n readonly missing?: readonly string[]\n }\n | HarnessTranscriptUnavailable\n\n/** The two optional environment reads the capture needs. Public because `captureHarnessTranscript`\n * is, so a BYO executor can satisfy it with any box that offers a bounded `read` and an `exec`. */\nexport interface ReadableEnvironment {\n readonly read?: (path: string, options?: { readonly signal?: AbortSignal }) => Promise<string>\n readonly exec?: (\n command: string,\n options?: Record<string, unknown>,\n ) => Promise<{ readonly stdout?: string; readonly exitCode?: number }>\n}\n\nfunction unavailable(reason: HarnessTranscriptUnavailableReason): HarnessTranscriptUnavailable {\n return Object.freeze({ status: 'unavailable', reason })\n}\n\n/** The one place an absent transcript is spelled, so every settlement reads the same — the\n * settle path needs it for the reasons only IT can know (an executor that offers no transcript,\n * a child that never started), which the capture itself never sees. */\nexport function harnessTranscriptUnavailable(\n reason: HarnessTranscriptUnavailableReason,\n): HarnessTranscriptUnavailable {\n return unavailable(reason)\n}\n\n/**\n * Read one executor's harness-transcript receipt without letting a broken port escape.\n *\n * The three answers this has to keep apart, because #1214 and #1244 are both about an artifact\n * that reads as coverage without being coverage:\n * - `available` the transcript survived;\n * - a reason the CAPTURE produced a box existed and could not be read;\n * - `executor-exposes-no-transcript` this runtime has no transcript to offer at all;\n * - `execution-never-started` no environment was ever created (the executor's\n * own seed, set before `create`);\n * - `capture-did-not-run` the port answered nothing, so the capture was\n * skipped rather than attempted and failed.\n *\n * Mirrors the supervise scope's `readInteractiveSession`: an absence is always a named reason,\n * never `undefined`. The scope reads each child with it, and `supervise` reads the root with it.\n */\n/**\n * The longest a settle waits for an executor's final transcript. The provider executor's own\n * steps are bounded (the harness stop at 30 s, each native copy by its port's `nativeTimeoutMs`,\n * 120 s by default), so this guards only an executor that never answers.\n */\nexport const HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS = 6 * 60_000\n\n/**\n * Wait, bounded, until the executor's transcript is final (`Executor.harnessTranscriptSettled`).\n * Never throws: on a timeout or a failure the read that follows reports what was kept.\n */\nexport async function settleHarnessTranscript(\n executor: { harnessTranscriptSettled?: () => Promise<void> },\n timeoutMs: number = HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS,\n): Promise<void> {\n if (!executor.harnessTranscriptSettled) return\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.resolve().then(() => executor.harnessTranscriptSettled?.()),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs)\n }),\n ])\n } catch {\n // The transcript read that follows names what was kept.\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\nexport function readHarnessTranscript(executor: {\n harnessTranscript?: () => unknown\n}): HarnessTranscriptCapture {\n if (!executor.harnessTranscript) {\n return harnessTranscriptUnavailable('executor-exposes-no-transcript')\n }\n let reported: unknown\n try {\n reported = executor.harnessTranscript()\n } catch {\n return harnessTranscriptUnavailable('executor-exposes-no-transcript')\n }\n if (reported === undefined) return harnessTranscriptUnavailable('capture-did-not-run')\n const capture = reported as HarnessTranscriptCapture\n if (capture.status === 'captured' && capture.artifact) return capture\n if (capture.status === 'retained' && capture.descriptor) return capture\n if (capture.status === 'unavailable' && capture.reason) return capture\n return harnessTranscriptUnavailable('executor-exposes-no-transcript')\n}\n\n/**\n * Bounds on the subagent export, per capture. The capture runs after every turn and again at\n * release, so they bound how long a turn's end or a teardown can wait on it; each session they\n * leave out is named in `skipped`.\n */\nconst MAX_SUBAGENT_EXPORTS = 32\nconst SUBAGENT_EXPORT_SECONDS = 120\n/** The script starts no export after SUBAGENT_EXPORT_SECONDS and bounds each one at 30 s, so it\n * ends inside this. It is passed to `exec`, because the Sandbox SDK's default is 30 s. */\nconst SUBAGENT_EXPORT_EXEC_MS = (SUBAGENT_EXPORT_SECONDS + 60) * 1000\nconst SUBAGENT_EXPORT_DIR = '~/.local/share/opencode/export'\n\n/**\n * The export, run in the box. For each sidecar record it reads the runtime home and the parent\n * session, collects the subagent sessions its messages name, and writes `opencode export` of each\n * one under `export`, where the capture reads it. It prints one `<state> <sessionId>` line per\n * subagent: `exported`, `failed`, or `unexported` (over a bound), then `done`. Every capture exports again,\n * because a later turn can continue a subagent and the store changes with every turn; an export\n * takes about 2 s in a Tangle box. Each export goes to a temporary file first, so a failed or\n * interrupted export never leaves a partial file for the capture to read.\n */\nconst SUBAGENT_EXPORT_SCRIPT = String.raw`cd \"$HOME\" 2>/dev/null || exit 0\nout=\"$HOME/.local/share/opencode/export\"\nt=\"\"; command -v timeout >/dev/null 2>&1 && t=\"timeout 30\"\nstart=$(date +%s); n=0\nfor rec in .opencode/sessions/*.json; do\n [ -f \"$rec\" ] || continue\n h=$(sed -n 's/.*\"providerSessionHome\"[[:space:]]*:[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p' \"$rec\" | head -n 1)\n p=$(sed -n 's/.*\"providerSessionId\"[[:space:]]*:[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p' \"$rec\" | head -n 1)\n db=\"$h/.local/share/opencode/opencode.db\"\n case \"$h\" in /*) [ -f \"$db\" ] || continue ;; *) continue ;; esac\n ids=$(grep -rhoE '<task id=\\\\?\"ses_[A-Za-z0-9]+|task_id: ses_[A-Za-z0-9]+|\"sessionId\"[[:space:]]*:[[:space:]]*\"ses_[A-Za-z0-9]+' \".opencode/messages/$(basename \"$rec\" .json)\" 2>/dev/null | grep -oE 'ses_[A-Za-z0-9]+' | sort -u)\n for id in $ids; do\n [ \"$id\" = \"$p\" ] && continue\n n=$((n + 1))\n if [ \"$n\" -gt ${MAX_SUBAGENT_EXPORTS} ] || [ $(($(date +%s) - start)) -ge ${SUBAGENT_EXPORT_SECONDS} ]; then echo \"unexported $id\"; continue; fi\n mkdir -p \"$out\" && tmp=$(mktemp) || { echo \"failed $id\"; continue; }\n if HOME=\"$h\" XDG_DATA_HOME=\"$h/.local/share\" XDG_CONFIG_HOME=\"$h/.config\" XDG_STATE_HOME=\"$h/.local/state\" XDG_CACHE_HOME=\"$h/.cache\" OPENCODE_DISABLE_AUTOUPDATE=1 OPENCODE_DISABLE_MODELS_FETCH=1 $t opencode export \"$id\" > \"$tmp\" 2>/dev/null && [ -s \"$tmp\" ]; then\n mv \"$tmp\" \"$out/$id.json\" && echo \"exported $id\"\n else\n rm -f \"$tmp\"; echo \"failed $id\"\n fi\n done\ndone\necho done`\n\n/**\n * Export each opencode subagent session a Tangle box's sidecar names, so the capture carries the\n * subagent's own steps (#1264).\n *\n * The sidecar runs opencode under a private runtime home and records the parent session under\n * `.opencode/sessions` and `.opencode/messages`. A `task` subagent runs in a child session, and\n * those records name it only in the tool's result (`<task id=\"ses_…\">`, or `task_id: ses_…` on a\n * failure). Its steps are only in the runtime home's `opencode.db`, which a text capture cannot\n * carry. Each sidecar record names that home as `providerSessionHome`, so `opencode export` reads\n * the child from there. A shared-box worker exports its own subagents after each turn (#1371) and\n * keeps no sidecar record, so the export finds nothing to do for it.\n *\n * Returns the sessions it could not export, as `skipped` entries. An export that did not run, or\n * stopped before its `done` line, is named once, because the subagents it did not reach are\n * unknown.\n */\nasync function exportSubagentSessions(\n environment: ReadableEnvironment,\n signal?: AbortSignal,\n): Promise<{ readonly path: string; readonly reason: string }[]> {\n if (!environment.exec || signal?.aborted) return []\n let stdout: string\n try {\n const result = await environment.exec(SUBAGENT_EXPORT_SCRIPT, {\n timeoutMs: SUBAGENT_EXPORT_EXEC_MS,\n ...(signal ? { signal } : {}),\n })\n stdout = result.stdout ?? ''\n } catch {\n return [{ path: SUBAGENT_EXPORT_DIR, reason: 'subagent-export-did-not-run' }]\n }\n const lines = stdout.split('\\n').map((line) => line.trim())\n const gaps: { path: string; reason: string }[] = []\n for (const line of lines) {\n const match = /^(failed|unexported) (ses_[A-Za-z0-9]+)$/u.exec(line)\n if (match === null) continue\n gaps.push({\n path: `${SUBAGENT_EXPORT_DIR}/${match[2]}.json`,\n reason: match[1] === 'failed' ? 'subagent-export-failed' : 'subagent-export-over-bound',\n })\n }\n if (!lines.includes('done')) {\n gaps.push({ path: SUBAGENT_EXPORT_DIR, reason: 'subagent-export-incomplete' })\n }\n return gaps\n}\n\ninterface Enumeration {\n /** Paths to read, at most MAX_FILES of them. */\n readonly paths: readonly string[]\n /** What the enumeration itself left out, named — never folded silently into \"no transcript\". */\n readonly omitted: readonly { readonly path: string; readonly reason: string }[]\n}\n\n/**\n * Enumerate candidate transcript paths inside the environment.\n *\n * `find -printf` is given the roots and prints one `size<TAB>path` line per file. A missing root\n * is not an error: a child that never used a harness has no directory for it. GNU find is the\n * target (the Tangle Linux box); BSD and BusyBox `find` have no `-printf`, their error is\n * discarded by `2>/dev/null`, and the empty listing then reads as `no-transcript` — that is a\n * known limit, not a fallback. A path-only line (no size) is still accepted and bounded after\n * the read, which is what a stub or a wrapped `find` produces, not what BSD does.\n *\n * Two omissions used to be silent, so `skippedCount` could read 0 on an incomplete capture: a\n * `-size` filter dropped oversized files before they were ever listed, and `head` cut the listing\n * at MAX_FILES with nothing saying so. Both are reported now: an oversized file is skipped by its\n * listed size WITHOUT being read, and a listing that overflows carries one\n * `enumeration-truncated` entry naming the bound.\n */\nasync function enumerate(\n environment: ReadableEnvironment,\n roots: readonly string[],\n signal?: AbortSignal,\n): Promise<Enumeration | undefined> {\n if (!environment.exec) return undefined\n const quoted = roots.map((r) => `\"$HOME/${r}\"`).join(' ')\n // One past the bound, so an exact overflow is observable rather than indistinguishable from\n // a listing that happened to be full.\n const command = `find ${quoted} -type f -printf '%s\\\\t%p\\\\n' 2>/dev/null | head -${MAX_FILES + 1}`\n try {\n const result = await environment.exec(command, signal ? { signal } : undefined)\n const lines = (result.stdout ?? '')\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l.length > 0)\n const omitted: { path: string; reason: string }[] = []\n const paths: string[] = []\n for (const line of lines.slice(0, MAX_FILES)) {\n const tab = line.indexOf('\\t')\n const path = tab === -1 ? line : line.slice(tab + 1)\n const size = tab === -1 ? undefined : Number(line.slice(0, tab))\n if (size !== undefined && Number.isFinite(size) && size > MAX_FILE_BYTES) {\n omitted.push({ path, reason: 'file-exceeds-byte-bound' })\n continue\n }\n paths.push(path)\n }\n if (lines.length > MAX_FILES) {\n omitted.push({ path: roots.join(' '), reason: `enumeration-truncated-at-${MAX_FILES}` })\n }\n return { paths, omitted }\n } catch {\n return undefined\n }\n}\n\n/**\n * Read the harness transcript out of one LIVE environment.\n *\n * Call this before the environment is destroyed — on the settled path that means before the\n * result is built, since the `finally` that destroys runs after. It never throws: a teardown\n * must not fail because evidence could not be collected, and every failure mode is a named\n * `reason` the settled receipt carries instead of an empty artifact that reads as coverage.\n */\nexport async function captureHarnessTranscript(\n environment: ReadableEnvironment | undefined,\n harness: string | undefined,\n signal?: AbortSignal,\n): Promise<HarnessTranscriptCapture> {\n if (!environment?.read) return unavailable('unsupported-environment')\n // Narrow `harness` before use: the roots lookup alone does not, and an artifact must\n // name the harness it came from.\n if (harness === undefined) return unavailable('unknown-harness')\n const roots = HARNESS_ROOTS[harness]\n if (!roots) return unavailable('unknown-harness')\n\n // Before the listing, so the subagent sessions it exports are listed with the rest.\n const unexported = harness === 'opencode' ? await exportSubagentSessions(environment, signal) : []\n const enumerated = await enumerate(environment, roots, signal)\n if (enumerated === undefined) return unavailable('enumeration-failed')\n const { paths } = enumerated\n if (paths.length === 0 && enumerated.omitted.length === 0 && unexported.length === 0) {\n return unavailable('no-transcript')\n }\n\n const files: HarnessTranscriptFile[] = []\n // Seeded with what the export and the enumeration left out, so an incomplete capture is never\n // a receipt with skippedCount 0.\n const skipped: { path: string; reason: string }[] = [...unexported, ...enumerated.omitted]\n let total = 0\n for (const path of paths) {\n // Stop on abort rather than attempting every remaining read and failing each: a\n // cancelled run should leave the dying environment alone, not make MAX_FILES doomed\n // calls into it. The remainder is still named in `skipped`.\n if (signal?.aborted) {\n skipped.push({ path, reason: 'aborted' })\n continue\n }\n if (DENY.test(path)) {\n skipped.push({ path, reason: 'denied-credential-shaped-path' })\n continue\n }\n if (total >= MAX_TOTAL_BYTES) {\n skipped.push({ path, reason: 'total-byte-budget-exhausted' })\n continue\n }\n try {\n const content = await environment.read(path, signal ? { signal } : undefined)\n const bytes = Buffer.byteLength(content, 'utf8')\n if (bytes > MAX_FILE_BYTES) {\n skipped.push({ path, reason: 'file-exceeds-byte-bound' })\n continue\n }\n // Checked AFTER the read so the ceiling is exact. A pre-read check let one child land at\n // MAX_TOTAL_BYTES plus one more file, about 18 MB against a stated 16 (#1248).\n if (total + bytes > MAX_TOTAL_BYTES) {\n skipped.push({ path, reason: 'total-byte-budget-exhausted' })\n continue\n }\n files.push(Object.freeze({ path, bytes, content }))\n total += bytes\n } catch {\n skipped.push({ path, reason: 'read-failed' })\n }\n }\n return capturedTranscript({\n schemaVersion: HARNESS_TRANSCRIPT_SCHEMA_VERSION,\n harness,\n files,\n skipped,\n })\n}\n\n/**\n * A transcript this process holds in memory, one JSON line per record, as a capture under the same\n * bounds a box's session files get: each file at most MAX_FILE_BYTES, all files together at most\n * MAX_TOTAL_BYTES. Lines fill `<name>-000.jsonl`, `<name>-001.jsonl`, ... in order, and a line is\n * never split. A line longer than one file, and every line past the total, is named in `skipped`\n * with its line number, so a cut transcript never reads as the whole one.\n */\nexport function harnessTranscriptFromLines(\n harness: string,\n name: string,\n lines: ReadonlyArray<string>,\n): HarnessTranscriptCapture {\n if (lines.length === 0) return unavailable('no-transcript')\n const files: HarnessTranscriptFile[] = []\n const skipped: { path: string; reason: string }[] = []\n let total = 0\n let chunk: string[] = []\n let chunkBytes = 0\n const flush = (): void => {\n if (chunk.length === 0) return\n const content = `${chunk.join('\\n')}\\n`\n files.push(\n Object.freeze({\n path: `${name}-${String(files.length).padStart(3, '0')}.jsonl`,\n bytes: Buffer.byteLength(content, 'utf8'),\n content,\n }),\n )\n chunk = []\n chunkBytes = 0\n }\n lines.forEach((line, index) => {\n const bytes = Buffer.byteLength(line, 'utf8') + 1\n const where = `${name} line ${index + 1}`\n if (bytes > MAX_FILE_BYTES) {\n skipped.push({ path: where, reason: 'file-exceeds-byte-bound' })\n return\n }\n if (total + bytes > MAX_TOTAL_BYTES) {\n skipped.push({ path: where, reason: 'total-byte-budget-exhausted' })\n return\n }\n if (chunkBytes + bytes > MAX_FILE_BYTES) flush()\n chunk.push(line)\n chunkBytes += bytes\n total += bytes\n })\n flush()\n return capturedTranscript({\n schemaVersion: HARNESS_TRANSCRIPT_SCHEMA_VERSION,\n harness,\n files,\n skipped,\n })\n}\n\n/**\n * Persist a capture under its own content ref and return the receipt a settlement carries.\n *\n * The scope calls this, not the executor: storage stays out of every provider and destroy site,\n * exactly as the tool-span trace is persisted by `captureWorkerTraceEvidence` and not by the\n * source that collected it. A capture that is already unavailable passes through untouched.\n */\nexport async function persistHarnessTranscript(\n capture: HarnessTranscriptCapture,\n blobs: Pick<ResultBlobStore, 'put'>,\n): Promise<HarnessTranscriptEvidence> {\n if (capture.status === 'unavailable') return capture\n const artifact =\n capture.status === 'captured'\n ? capture.artifact\n : parseRetainedHarnessTranscript(capture.descriptor)\n const transcriptRef = contentAddress(artifact)\n try {\n await blobs.put(transcriptRef, artifact)\n } catch {\n return unavailable('transcript-persistence-failed')\n }\n return Object.freeze({\n status: 'available',\n transcriptRef,\n harness: artifact.harness,\n fileCount: capture.fileCount,\n totalBytes: capture.totalBytes,\n skippedCount: capture.skippedCount,\n ...(capture.status === 'retained'\n ? {\n coverageComplete:\n capture.descriptor.source.coverageComplete && capture.descriptor.missing.length === 0,\n missing: capture.descriptor.missing,\n }\n : { coverageComplete: capture.coverageComplete, missing: capture.missing }),\n })\n}\n\n/**\n * Rehydrate the exact persisted transcript a receipt points at, or `undefined` when the receipt\n * says there is none. Throws only when the receipt claims a blob the store does not hold — that\n * is corruption, not absence, and must not read as \"no transcript\".\n */\nexport function harnessTranscriptArtifact(\n evidence: HarnessTranscriptEvidence,\n blobs: Pick<ResultBlobStore, 'get'>,\n options: HarnessTranscriptReadOptions & { content: false },\n): Promise<HarnessTranscriptMetadata | undefined>\nexport function harnessTranscriptArtifact(\n evidence: HarnessTranscriptEvidence,\n blobs: Pick<ResultBlobStore, 'get'>,\n options?: HarnessTranscriptReadOptions & { content?: true },\n): Promise<HarnessTranscriptArtifact | undefined>\nexport async function harnessTranscriptArtifact(\n evidence: HarnessTranscriptEvidence,\n blobs: Pick<ResultBlobStore, 'get'>,\n options: HarnessTranscriptReadOptions = {},\n): Promise<HarnessTranscriptArtifact | HarnessTranscriptMetadata | undefined> {\n if (evidence.status !== 'available') return undefined\n const raw = await blobs.get(evidence.transcriptRef)\n let capture: HarnessTranscriptCapture\n if (isHarnessTranscriptArtifact(raw)) {\n capture = {\n status: 'captured',\n artifact: raw,\n fileCount: raw.files.length,\n totalBytes: raw.files.reduce((sum, file) => sum + file.bytes, 0),\n skippedCount: raw.skipped.length,\n }\n } else {\n if (\n raw === null ||\n typeof raw !== 'object' ||\n Reflect.get(raw, 'kind') !== 'retained-harness-transcript'\n )\n throw new ValidationError(\n `harnessTranscriptArtifact: blob store has no transcript artifact for '${evidence.transcriptRef}'`,\n )\n const descriptor = parseRetainedHarnessTranscript(raw)\n if (contentAddress(descriptor) !== evidence.transcriptRef)\n throw new ValidationError('Retained transcript descriptor does not match its transcriptRef')\n capture = {\n status: 'retained',\n descriptor,\n fileCount: descriptor.files.length,\n totalBytes: descriptor.files.reduce((sum, file) => sum + file.bytes, 0),\n skippedCount: descriptor.skipped.length,\n }\n }\n if (contentAddress(raw) !== evidence.transcriptRef)\n throw new ValidationError('Transcript artifact does not match its transcriptRef')\n return options.content === false\n ? resolveHarnessTranscriptCapture(capture, { ...options, content: false })\n : resolveHarnessTranscriptCapture(capture, { ...options, content: true })\n}\n\n/** Every entry, not just the arrays: a blob with `files: [null]` is corruption, not a transcript. */\nfunction isHarnessTranscriptArtifact(value: unknown): value is HarnessTranscriptArtifact {\n if (value === null || typeof value !== 'object') return false\n const artifact = value as Partial<HarnessTranscriptArtifact>\n return (\n artifact.schemaVersion === HARNESS_TRANSCRIPT_SCHEMA_VERSION &&\n typeof artifact.harness === 'string' &&\n Array.isArray(artifact.files) &&\n artifact.files.every(\n (file) =>\n file !== null &&\n typeof file === 'object' &&\n typeof file.path === 'string' &&\n typeof file.content === 'string' &&\n Number.isSafeInteger(file.bytes) &&\n file.bytes >= 0,\n ) &&\n Array.isArray(artifact.skipped) &&\n artifact.skipped.every(\n (entry) =>\n entry !== null &&\n typeof entry === 'object' &&\n typeof entry.path === 'string' &&\n typeof entry.reason === 'string',\n )\n )\n}\n\n/** All transcript producers share artifact accounting and the empty/partial distinction. */\nfunction capturedTranscript(\n artifact: HarnessTranscriptArtifact,\n coverageComplete?: boolean,\n): HarnessTranscriptCapture {\n const { files, skipped } = artifact\n if (!files.length)\n return deepFreezeCandidate({\n status: 'unavailable' as const,\n reason: 'nothing-carried' as const,\n skipped,\n })\n return deepFreezeCandidate({\n status: 'captured' as const,\n artifact,\n fileCount: files.length,\n totalBytes: files.reduce((sum, file) => sum + file.bytes, 0),\n skippedCount: skipped.length,\n ...(coverageComplete === undefined ? {} : { coverageComplete, missing: [] }),\n })\n}\n\n/** Local native bytes enter the same artifact/settlement path as every other transcript. */\nexport async function captureBoundHarnessTranscript<S extends BoundHarnessSession>(\n input: Parameters<typeof readBoundHarnessSessions<S>>[0] & {\n readonly harness: string\n readonly binding: HarnessTranscriptBinding\n },\n): Promise<HarnessTranscriptCapture> {\n if (\n input.binding.nativeSessionId !== input.nativeSessionId ||\n !input.binding.sessionId ||\n !/^sha256:[a-f0-9]{64}$/.test(input.binding.profileDigest) ||\n !input.binding.runs.length ||\n input.binding.runs.some((run) => !run.runId || !/^sha256:[a-f0-9]{64}$/.test(run.requestDigest))\n )\n throw new ValidationError('Native capture binding is incomplete')\n const files: HarnessTranscriptFile[] = []\n await readBoundHarnessSessions({\n ...input,\n read: async (file, signal) => {\n const bytes = await input.read(file, signal)\n files.push({\n path: file.path,\n bytes: bytes.byteLength,\n content: new TextDecoder('utf-8', { fatal: true }).decode(bytes),\n })\n return bytes\n },\n })\n return capturedTranscript(\n { schemaVersion: 1, harness: input.harness, binding: input.binding, files, skipped: [] },\n true,\n )\n}\n","/**\n *\n * Sanitization for runtime telemetry. The rule: nothing user-controlled leaks\n * unless the caller opts in with a `RuntimeTelemetryOptions` flag, and an\n * opted-in payload or error message still passes through agent-eval's\n * redaction core, so credentials never leak. This is the envelope that ends up\n * in `agent_run.metadata.runtimeEvents` on every consumer, so the default must\n * be safe.\n *\n * @stable\n */\n\nimport type {\n ControlEvalResult,\n ControlRunResult,\n ControlStep,\n DataAcquisitionPlan,\n KnowledgeReadinessReport,\n KnowledgeRequirement,\n UserQuestion,\n} from '@tangle-network/agent-eval'\n\nimport { redact } from '@tangle-network/agent-eval/traces'\nimport type { RuntimeFailureCause } from './runtime/failure-cause'\nimport type {\n AgentRuntimeEvent,\n AgentTaskSpec,\n AgentTaskStatus,\n RuntimeSession,\n RuntimeStreamEvent,\n} from './types'\n\n/** @stable */\nexport interface RuntimeTelemetryOptions {\n /**\n * Include raw task inputs. Off by default because task inputs often contain\n * customer facts, credentials, source text, or internal IDs.\n */\n includeInputs?: boolean\n /** Include requirement descriptions. Secret requirements are always redacted. */\n includeRequirementDescriptions?: boolean\n /** Include evidence IDs. Off by default; counts are safer for shared reports. */\n includeEvidenceIds?: boolean\n /** Include user answers from question preflight. Off by default. */\n includeUserAnswers?: boolean\n /** Include action payloads and action results for control steps. Off by default. */\n includeControlPayloads?: boolean\n /** Include task metadata. Off by default because metadata may carry IDs or policy internals. */\n includeMetadata?: boolean\n /** Include eval detail/evidence strings. Off by default because validators may echo private input. */\n includeEvalDetails?: boolean\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeRequirement {\n id: string\n description?: string\n requiredFor: string[]\n category: KnowledgeRequirement['category']\n acquisitionMode: KnowledgeRequirement['acquisitionMode']\n importance: KnowledgeRequirement['importance']\n freshness: KnowledgeRequirement['freshness']\n sensitivity: KnowledgeRequirement['sensitivity']\n confidenceNeeded: number\n currentConfidence: number\n evidenceCount: number\n evidenceIds?: string[]\n fallbackPolicy: KnowledgeRequirement['fallbackPolicy']\n}\n\n/** @stable */\nexport interface SanitizedKnowledgeReadinessReport {\n taskId: string\n readinessScore: number\n recommendedAction: KnowledgeReadinessReport['recommendedAction']\n severity: KnowledgeReadinessReport['severity']\n reason: string\n blockingMissingRequirements: SanitizedKnowledgeRequirement[]\n nonBlockingGaps: SanitizedKnowledgeRequirement[]\n evidenceCount: number\n evidenceIds?: string[]\n missingRequirementIds: string[]\n}\n\n/** Strip PII and large blobs from a `KnowledgeReadinessReport` for safe telemetry emission. @stable */\nexport function sanitizeKnowledgeReadinessReport(\n report: KnowledgeReadinessReport,\n options: RuntimeTelemetryOptions = {},\n): SanitizedKnowledgeReadinessReport {\n return {\n taskId: report.taskId,\n readinessScore: report.readinessScore,\n recommendedAction: report.recommendedAction,\n severity: report.severity,\n reason: report.reason,\n blockingMissingRequirements: report.blockingMissingRequirements.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n nonBlockingGaps: report.nonBlockingGaps.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n evidenceCount: report.bundle.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? report.bundle.evidenceIds : undefined,\n missingRequirementIds: report.bundle.missing.map((requirement) => requirement.id),\n }\n}\n\n/** Reduce an `AgentRuntimeEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeAgentRuntimeEvent<\n TState,\n TAction,\n TActionResult,\n TEval extends ControlEvalResult,\n>(\n event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const base = { type: event.type, task: sanitizeTask(event.task, options) }\n if (\n event.type === 'readiness_start' ||\n event.type === 'task_start' ||\n event.type === 'control_start'\n ) {\n return event.type === 'control_start'\n ? { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n : base\n }\n if (event.type === 'readiness_end') {\n return { ...base, knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options) }\n }\n if (event.type === 'questions_start') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n ...base,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers\n ? included(event.userAnswers)\n : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return { ...base, acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan) }\n }\n if (event.type === 'acquisition_end') {\n return {\n ...base,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'control_step') {\n return { ...base, step: sanitizeControlStep(event.step, options) }\n }\n if (event.type === 'control_end') {\n return { ...base, control: sanitizeControlRun(event.control, options) }\n }\n return { ...base, status: event.status, reason: event.reason }\n}\n\n/** Reduce a `RuntimeStreamEvent` to a PII-safe, serializable plain object for telemetry. @stable */\nexport function sanitizeRuntimeStreamEvent(\n event: RuntimeStreamEvent,\n options: RuntimeTelemetryOptions = {},\n): Record<string, unknown> {\n const withTask = 'task' in event && event.task ? { task: sanitizeTask(event.task, options) } : {}\n const withSession =\n 'session' in event && event.session\n ? { session: sanitizeRuntimeSession(event.session, options) }\n : {}\n\n if (event.type === 'readiness_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n decision: event.decision,\n knowledge: sanitizeKnowledgeReadinessReport(event.knowledge, options),\n }\n }\n if (event.type === 'questions_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n }\n }\n if (event.type === 'questions_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n questions: event.questions.map((question) => sanitizeQuestion(question, options)),\n userAnswers: options.includeUserAnswers\n ? included(event.userAnswers)\n : redactRecord(event.userAnswers),\n }\n }\n if (event.type === 'acquisition_start') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n }\n }\n if (event.type === 'acquisition_end') {\n return {\n type: event.type,\n ...withTask,\n timestamp: event.timestamp,\n acquisitionPlans: event.acquisitionPlans.map(sanitizeAcquisitionPlan),\n acquiredEvidenceCount: event.acquiredEvidenceIds.length,\n acquiredEvidenceIds: options.includeEvidenceIds ? event.acquiredEvidenceIds : undefined,\n }\n }\n if (event.type === 'tool_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n args: options.includeControlPayloads ? included(event.args) : undefined,\n }\n }\n if (event.type === 'tool_result') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n result: options.includeControlPayloads ? included(event.result) : undefined,\n }\n }\n if (event.type === 'llm_call') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n model: event.model,\n tokensIn: event.tokensIn,\n tokensOut: event.tokensOut,\n costUsd: event.costUsd,\n latencyMs: event.latencyMs,\n finishReason: event.finishReason,\n }\n }\n if (event.type === 'artifact') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n artifactId: event.artifactId,\n name: event.name,\n mimeType: event.mimeType,\n uri: options.includeEvidenceIds ? event.uri : undefined,\n content: options.includeControlPayloads ? included(event.content) : undefined,\n metadata: options.includeMetadata ? included(event.metadata) : undefined,\n }\n }\n if (event.type === 'proposal_created') {\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n proposalId: event.proposalId,\n title: options.includeControlPayloads ? included(event.title) : undefined,\n content: options.includeControlPayloads ? included(event.content) : undefined,\n status: event.status,\n }\n }\n if (event.type === 'final') {\n // Surface error `kind` + `status` always — operators need failure\n // classification regardless of telemetry payload opt-in. `body` follows\n // the same gating as raw payloads (`includeControlPayloads`) because it\n // can echo user-visible text from the upstream provider's error page.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n message: included(event.error.message),\n status: event.error.status,\n body: options.includeControlPayloads ? included(event.error.body) : undefined,\n }\n : undefined\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: event.timestamp,\n status: event.status,\n reason: event.reason,\n text: options.includeControlPayloads ? included(event.text) : undefined,\n metadata: options.includeMetadata ? included(event.metadata) : undefined,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n // Already redacted and bounded at its source; `code` and `owner` are the classification\n // operators need regardless of payload opt-in, exactly like `error.kind`.\n ...(event.failure !== undefined ? { failure: sanitizedFailure(event.failure) } : {}),\n }\n }\n return {\n type: event.type,\n ...withTask,\n ...withSession,\n timestamp: 'timestamp' in event ? event.timestamp : undefined,\n ...pickPublicStreamFields(event),\n }\n}\n\nfunction sanitizeTask(\n task: AgentTaskSpec,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: task.id,\n intent: task.intent,\n domain: task.domain,\n inputs: options.includeInputs ? included(task.inputs) : task.inputs ? '[redacted]' : undefined,\n requiredKnowledge: task.requiredKnowledge?.map((requirement) =>\n sanitizeKnowledgeRequirement(requirement, options),\n ),\n metadata: options.includeMetadata\n ? included(task.metadata)\n : task.metadata\n ? '[redacted]'\n : undefined,\n }\n}\n\nfunction sanitizeRuntimeSession(\n session: RuntimeSession,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: session.id,\n backend: session.backend,\n status: session.status,\n hasResumeToken: Boolean(session.resumeToken),\n createdAt: session.createdAt,\n updatedAt: session.updatedAt,\n metadata: options.includeMetadata\n ? included(session.metadata)\n : session.metadata\n ? '[redacted]'\n : undefined,\n }\n}\n\nfunction sanitizeKnowledgeRequirement(\n requirement: KnowledgeRequirement,\n options: RuntimeTelemetryOptions,\n): SanitizedKnowledgeRequirement {\n const includeDescription =\n options.includeRequirementDescriptions && requirement.sensitivity !== 'secret'\n return {\n id: requirement.id,\n description: includeDescription ? requirement.description : undefined,\n requiredFor: requirement.requiredFor,\n category: requirement.category,\n acquisitionMode: requirement.acquisitionMode,\n importance: requirement.importance,\n freshness: requirement.freshness,\n sensitivity: requirement.sensitivity,\n confidenceNeeded: requirement.confidenceNeeded,\n currentConfidence: requirement.currentConfidence,\n evidenceCount: requirement.evidenceIds.length,\n evidenceIds: options.includeEvidenceIds ? requirement.evidenceIds : undefined,\n fallbackPolicy: requirement.fallbackPolicy,\n }\n}\n\nfunction sanitizeQuestion(\n question: UserQuestion,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n id: question.id,\n question:\n options.includeRequirementDescriptions && question.answerType !== 'credential'\n ? question.question\n : undefined,\n reason: options.includeRequirementDescriptions ? question.reason : undefined,\n requirementId: question.requirementId,\n importance: question.importance,\n answerType: question.answerType,\n impactIfUnknown: options.includeRequirementDescriptions ? question.impactIfUnknown : undefined,\n optionCount: question.options?.length ?? 0,\n }\n}\n\nfunction sanitizeAcquisitionPlan(plan: DataAcquisitionPlan): Record<string, unknown> {\n return {\n id: plan.id,\n requirementIds: plan.requirementIds,\n mode: plan.mode,\n priority: plan.priority,\n expectedEvidenceCount: plan.expectedEvidenceIds?.length ?? 0,\n questionCount: plan.questions?.length ?? 0,\n }\n}\n\nfunction sanitizeControlStep<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n step: ControlStep<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n const actionOutcome = step.actionOutcome\n return {\n index: step.index,\n decisionType: step.decision.type,\n reason: step.decision.reason,\n action:\n options.includeControlPayloads && step.decision.type === 'continue'\n ? included(step.decision.action)\n : undefined,\n result:\n options.includeControlPayloads && actionOutcome?.ok\n ? included(actionOutcome.result)\n : undefined,\n actionOk: actionOutcome?.ok,\n actionError: actionOutcome?.ok === false ? actionOutcome.error : undefined,\n durationMs: actionOutcome?.durationMs,\n evalsBefore: summarizeEvals(step.evalsBefore, options),\n evalsAfter: summarizeEvals(step.evalsAfter, options),\n startedAt: step.startedAt,\n endedAt: step.endedAt,\n }\n}\n\nfunction sanitizeControlRun<TState, TAction, TActionResult, TEval extends ControlEvalResult>(\n control: ControlRunResult<TState, TAction, TActionResult, TEval>,\n options: RuntimeTelemetryOptions,\n): Record<string, unknown> {\n return {\n pass: control.pass,\n completed: control.completed,\n reason: control.reason,\n score: control.score,\n stepCount: control.steps.length,\n wallMs: control.wallMs,\n spentCostUsd: control.spentCostUsd,\n failureClass: control.failureClass,\n stoppedBy: control.stoppedBy,\n runId: control.runId,\n runtimeErrorCount: control.runtimeErrors.length,\n finalEvals: summarizeEvals(control.finalEvals, options),\n }\n}\n\nfunction summarizeEvals(\n evals: ControlEvalResult[],\n options: RuntimeTelemetryOptions,\n): Array<Record<string, unknown>> {\n return evals.map((evalResult) => ({\n id: evalResult.id,\n passed: evalResult.passed,\n score: evalResult.score,\n severity: evalResult.severity,\n objective: evalResult.objective,\n detail: options.includeEvalDetails ? included(evalResult.detail) : undefined,\n evidence: options.includeEvalDetails ? included(evalResult.evidence) : undefined,\n }))\n}\n\n/**\n * An opted-in payload still goes through agent-eval's redaction core: the\n * flags decide whether content is shared, never whether credentials are.\n */\nfunction included<T>(value: T): T {\n return value === undefined ? value : redact(value).value\n}\n\nfunction sanitizedFailure(failure: RuntimeFailureCause): RuntimeFailureCause {\n return {\n code: failure.code,\n owner: failure.owner,\n cause: included(failure.cause),\n ...(failure.providerCode === undefined ? {} : { providerCode: failure.providerCode }),\n }\n}\n\nfunction redactRecord(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.keys(record).map((key) => [key, '[redacted]']))\n}\n\nfunction pickPublicStreamFields(event: RuntimeStreamEvent): Record<string, unknown> {\n if (event.type === 'session_created' || event.type === 'session_resumed') return {}\n if (event.type === 'backend_start' || event.type === 'backend_end')\n return { backend: event.backend }\n if (event.type === 'backend_error') {\n // `error.body` is the truncated upstream response — it can carry\n // user-visible text (a `free_tier_limit` envelope is safe, but an HTML\n // error page from a misconfigured proxy may echo the request URL with\n // query string). Redact body by default; surface `kind` + `status` so\n // operators can still classify the failure without raw text.\n const sanitizedError =\n event.error !== undefined\n ? {\n kind: event.error.kind,\n status: event.error.status,\n }\n : undefined\n return {\n backend: event.backend,\n message: included(event.message),\n recoverable: event.recoverable,\n ...(sanitizedError !== undefined ? { error: sanitizedError } : {}),\n ...(event.failure !== undefined ? { failure: sanitizedFailure(event.failure) } : {}),\n }\n }\n if (event.type === 'task_end') return { status: event.status, reason: event.reason }\n if (event.type === 'text_delta' || event.type === 'reasoning_delta') return { text: event.text }\n return {}\n}\n\n/** @stable */\nexport interface RuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n> {\n onEvent: (event: AgentRuntimeEvent<TState, TAction, TActionResult, TEval>) => void\n events: Array<Record<string, unknown>>\n}\n\n/** @stable */\nexport type RuntimeStreamEventSink = (event: RuntimeStreamEvent) => void\n\n/** @stable */\nexport interface RuntimeStreamEventSummary {\n /** Total count of sanitized events collected. */\n eventCount: number\n /** Count of events per `type`. Useful for log-line summaries. */\n eventCountsByType: Record<string, number>\n /** First session id observed in a `session_created` / `session_resumed` event, if any. */\n firstSessionId?: string\n /** Last `final` event's status, if a final event was observed. */\n finalStatus?: AgentTaskStatus\n /** Last `final` event's reason, if a final event was observed. */\n finalReason?: string\n /** Concatenated `text_delta.text` across the stream, even when payloads are redacted. */\n finalText: string\n}\n\n/** @stable */\nexport interface RuntimeStreamEventCollector {\n onEvent: RuntimeStreamEventSink\n events: Array<Record<string, unknown>>\n /** Snapshot of a small streaming-flavored summary derived from collected events. */\n summary(): RuntimeStreamEventSummary\n}\n\n/** Build an in-memory collector that sanitizes and accumulates `AgentRuntimeEvent`s for inspection. @stable */\nexport function createRuntimeEventCollector<\n TState = unknown,\n TAction = unknown,\n TActionResult = unknown,\n TEval extends ControlEvalResult = ControlEvalResult,\n>(\n options: RuntimeTelemetryOptions = {},\n): RuntimeEventCollector<TState, TAction, TActionResult, TEval> {\n const events: Array<Record<string, unknown>> = []\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeAgentRuntimeEvent(event, options))\n },\n }\n}\n\n/**\n *\n * Streaming-event counterpart of `createRuntimeEventCollector`. Pass each\n * event yielded by `runAgentTaskStream` through `onEvent` and read the\n * sanitized copies off `events`; the same `RuntimeTelemetryOptions` redaction\n * flags apply. Kept distinct from `createRuntimeEventCollector` because the\n * stream and non-stream event shapes overlap on `type` literals — dispatching\n * on `type` alone would misroute events.\n *\n * @stable\n */\nexport function createRuntimeStreamEventCollector(\n options: RuntimeTelemetryOptions = {},\n): RuntimeStreamEventCollector {\n const events: Array<Record<string, unknown>> = []\n const eventCountsByType: Record<string, number> = {}\n let firstSessionId: string | undefined\n let finalStatus: AgentTaskStatus | undefined\n let finalReason: string | undefined\n let finalText = ''\n return {\n events,\n onEvent: (event) => {\n events.push(sanitizeRuntimeStreamEvent(event, options))\n eventCountsByType[event.type] = (eventCountsByType[event.type] ?? 0) + 1\n if (event.type === 'text_delta') finalText += event.text\n if (\n !firstSessionId &&\n (event.type === 'session_created' || event.type === 'session_resumed')\n ) {\n firstSessionId = event.session.id\n }\n if (event.type === 'final') {\n finalStatus = event.status\n finalReason = event.reason\n }\n },\n summary() {\n return {\n eventCount: events.length,\n eventCountsByType: { ...eventCountsByType },\n firstSessionId,\n finalStatus,\n finalReason,\n finalText,\n }\n },\n }\n}\n","/**\n * OTEL span exporter — streams LoopTraceEvents to an OTLP/HTTP collector.\n *\n * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env\n * when no explicit config is given. Keeps the runtime dep-free from\n * @opentelemetry/sdk-trace-base — minimal OTLP/JSON serializer.\n *\n * The exporter accepts both raw OtelSpan objects and LoopTraceEvents\n * (which get converted to OTLP spans automatically).\n */\n\nimport { appendFileSync } from 'node:fs'\n\nimport {\n ATTR,\n OPERATION_NAME_ATTR,\n type SpanKind,\n toW3CSpanId,\n toW3CTraceId,\n} from '@tangle-network/agent-trace-contract'\nimport {\n decodeOtlpAttributes,\n msToUnixNano,\n type OtlpKeyValue,\n type OtlpSpan,\n otlpTraceExport,\n readOtlpPartialSuccess,\n toOtlpAttributes,\n} from '@tangle-network/agent-trace-contract/otlp'\nimport { type RuntimeTelemetryOptions, sanitizeRuntimeStreamEvent } from './sanitize'\nimport type { RuntimeStreamEvent } from './types'\n\nexport interface OtelExportConfig {\n /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */\n endpoint?: string\n /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */\n headers?: Record<string, string>\n /** Batch size before flush. Default 64. */\n batchSize?: number\n /** Flush interval ms. Default 5000. */\n flushIntervalMs?: number\n /**\n * Most spans held at once, queued plus in flight. Default 2048, the OpenTelemetry batch\n * processor's own default. A span that arrives when the queue is full is dropped and counted in\n * {@link OtelExportStats.dropped}, so a stalled collector costs a bounded amount of memory.\n */\n maxQueueSize?: number\n /** Milliseconds one POST may take before it is abandoned and its spans count as dropped. Default 10000. */\n timeoutMs?: number\n /** Resource attributes stamped on every export. */\n resourceAttributes?: Record<string, string | number | boolean>\n /** Service name. Default 'agent-runtime'. */\n serviceName?: string\n}\n\nexport interface OtelExporter {\n /** Export a span. Never throws: a sink that cannot take the span counts it as dropped. */\n exportSpan(span: OtelSpan): void\n /**\n * Deliver everything queued so far. Rejects when spans were dropped since the previous `flush`,\n * naming how many and the last error, because a caller that awaits delivery is owed the answer.\n */\n flush(): Promise<void>\n /** Stop accepting spans and deliver what is queued. Never rejects. */\n shutdown(): Promise<void>\n /** What this sink has delivered and lost so far. */\n stats(): OtelExportStats\n}\n\n/**\n * Delivery accounting for one exporter. `written + dropped + pending` covers every span handed to\n * `exportSpan`, so a trace that arrives short can be told apart from a run that emitted less.\n */\nexport interface OtelExportStats {\n /** Spans the sink confirmed: a 2xx collector response, or a completed file append. */\n written: number\n /** Spans lost: refused by the collector, failed in transit, over the queue bound, or unwritable. */\n dropped: number\n /** Spans accepted and not yet written or dropped. */\n pending: number\n /** The most recent failure, when there has been one. */\n lastError?: string\n}\n\n/** One OTLP/JSON span: agent-trace-contract's wire type. */\nexport type OtelSpan = OtlpSpan\nexport type OtelAttribute = OtlpKeyValue\n\nconst SCOPE = { name: '@tangle-network/agent-runtime', version: '0.83.0' }\n\n/**\n * Create an exporter that APPENDS spans to a local OpenInference-JSONL file, one complete span per\n * line, instead of posting them to a collector.\n *\n * Why this exists beside {@link createOtelExporter}: that one needs an OTLP endpoint, so a run on a\n * laptop, in CI, or inside a sandbox with no collector emits nothing and its per-turn shape is\n * simply lost. The journal records the TREE (who spawned whom, what settled, what it spent); it\n * does not record what happened inside a turn. A run whose tree is readable but whose turns are not\n * is exactly the state that made an observability gap invisible until someone went looking.\n *\n * The line shape is the one `@tangle-network/traces` reads (`spans.otlp.jsonl`) and is a standard\n * OpenInference representation, so the same file feeds any OpenInference tool with no conversion:\n * snake_case identity fields, ISO-8601 times, `parent_span_id` empty at the root, and attributes as\n * a plain object rather than OTLP's key/value array.\n *\n * Appends synchronously per span so a killed process keeps every span it had already finished —\n * matching the spawn journal's durability posture, since a trace that only survives a clean exit is\n * useless for the runs you most want to look at.\n */\nexport function createOpenInferenceFileExporter(filePath: string): OtelExporter {\n let written = 0\n let dropped = 0\n let failed: Error | undefined\n return {\n exportSpan(span: OtelSpan): void {\n try {\n appendFileSync(filePath, `${JSON.stringify(toOpenInferenceLine(span))}\\n`, 'utf8')\n written += 1\n } catch (error) {\n // Telemetry must never take the run down with it, but a silently dead exporter is how a\n // missing trace gets mistaken for an empty one. Count the loss, remember the first failure\n // and surface it from flush(), where a caller is already awaiting an answer.\n dropped += 1\n failed ??= error instanceof Error ? error : new Error(String(error))\n }\n },\n async flush(): Promise<void> {\n if (failed)\n throw new Error(\n `OpenInference file exporter failed writing ${filePath} (${dropped} spans dropped): ${failed.message}`,\n )\n },\n async shutdown(): Promise<void> {},\n stats(): OtelExportStats {\n return { written, dropped, pending: 0, ...(failed ? { lastError: failed.message } : {}) }\n },\n }\n}\n\n/** OTLP's numeric status codes in the NAMES OpenInference requires. */\nconst OTEL_STATUS_NAME: Record<number, string> = { 0: 'UNSET', 1: 'OK', 2: 'ERROR' }\n\n/** Nanosecond string -> ISO-8601, the time format an OpenInference reader parses with `Date.parse`. */\nfunction nanosToIso(nanos: string): string {\n const ms = Number(BigInt(nanos) / 1_000_000n)\n return new Date(ms).toISOString()\n}\n\n/** One `OtelSpan` as the OpenInference JSONL line `traces` and other OpenInference tools read. */\nfunction toOpenInferenceLine(span: OtelSpan): Record<string, unknown> {\n const { attributes } = decodeOtlpAttributes(span.attributes)\n const kind = attributes['openinference.span.kind']\n const resource: Record<string, unknown> = {}\n for (const key of ['service.name', 'agent.name']) {\n if (attributes[key] !== undefined) resource[key] = attributes[key]\n }\n return {\n trace_id: span.traceId,\n span_id: span.spanId,\n // Empty string, not null: the root is spelled \"\" in this representation.\n parent_span_id: span.parentSpanId ?? '',\n name: span.name,\n kind: typeof kind === 'string' ? kind : 'CHAIN',\n start_time: nanosToIso(span.startTimeUnixNano),\n end_time: nanosToIso(span.endTimeUnixNano),\n // OpenInference spells status as a NAME, not OTLP's numeric code. Writing the number produced\n // a file a reader found and then refused: \"status.code must be OK, ERROR, UNSET, or its\n // STATUS_CODE_* form\" — the whole run's per-turn detail lost to one field.\n status: {\n code: OTEL_STATUS_NAME[span.status?.code ?? 0] ?? 'UNSET',\n ...(span.status?.message === undefined ? {} : { message: span.status.message }),\n },\n resource: { attributes: resource },\n scope: { name: 'agent-runtime', version: '' },\n attributes,\n }\n}\n\n/**\n * Create an OTLP/HTTP exporter. Returns undefined when no endpoint is configured.\n *\n * One batch is in flight at a time; spans that arrive meanwhile wait in a queue bounded by\n * `maxQueueSize`. Every span ends in exactly one of `written` or `dropped`: a non-2xx response, a\n * network error, a timeout, an OTLP `partialSuccess.rejectedSpans` count and a full queue each count\n * as drops and set `lastError`. Nothing here throws into the caller's run; `flush()` reports the\n * loss, the same rule `createOpenInferenceFileExporter` follows.\n */\nexport function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined {\n const resolvedEndpoint =\n config?.endpoint ??\n (typeof process !== 'undefined' ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : undefined)\n if (!resolvedEndpoint) return undefined\n const url = `${resolvedEndpoint.replace(/\\/+$/, '')}/v1/traces`\n\n const headers = config?.headers ?? parseHeadersFromEnv()\n const batchSize = positiveInteger(config?.batchSize, 64)\n const flushIntervalMs = config?.flushIntervalMs ?? 5000\n const maxQueueSize = Math.max(positiveInteger(config?.maxQueueSize, 2048), batchSize)\n const timeoutMs = positiveInteger(config?.timeoutMs, 10_000)\n const resource = toOtlpAttributes({\n 'service.name': config?.serviceName ?? 'agent-runtime',\n ...(config?.resourceAttributes ?? {}),\n })\n\n const queue: OtelSpan[] = []\n let inFlight = 0\n let written = 0\n let dropped = 0\n let droppedAtLastFlush = 0\n let lastError: string | undefined\n let sending: Promise<void> | undefined\n let stopped = false\n\n const drop = (count: number, reason: string): void => {\n dropped += count\n lastError = reason\n }\n\n async function send(batch: OtelSpan[]): Promise<void> {\n const body = otlpTraceExport(resource, SCOPE, batch)\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...headers },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(timeoutMs),\n })\n const text = await response.text()\n if (!response.ok) {\n const detail = text ? `: ${text.slice(0, 200)}` : ''\n drop(batch.length, `HTTP ${response.status} from ${url}${detail}`)\n return\n }\n const partial = readOtlpPartialSuccess(text)\n const rejected = Math.min(partial.rejectedSpans, batch.length)\n if (rejected > 0) {\n drop(\n rejected,\n `collector rejected ${rejected} spans: ${partial.errorMessage ?? 'no message'}`,\n )\n }\n written += batch.length - rejected\n } catch (error) {\n drop(batch.length, `POST ${url} failed: ${describeFetchError(error)}`)\n }\n }\n\n /** The single sender: it drains the queue batch by batch until the queue is empty. */\n function drain(): Promise<void> {\n if (sending === undefined && queue.length === 0) return Promise.resolve()\n sending ??= (async () => {\n try {\n while (queue.length > 0) {\n const batch = queue.splice(0, batchSize)\n inFlight = batch.length\n await send(batch)\n inFlight = 0\n }\n } finally {\n sending = undefined\n }\n })()\n return sending\n }\n\n const timer = setInterval(() => {\n if (queue.length > 0) void drain()\n }, flushIntervalMs)\n if (typeof timer === 'object' && 'unref' in timer) {\n ;(timer as NodeJS.Timeout).unref()\n }\n\n return {\n exportSpan(span: OtelSpan): void {\n if (stopped) {\n drop(1, 'span exported after the exporter stopped')\n return\n }\n if (queue.length + inFlight >= maxQueueSize) {\n drop(1, `queue full: ${maxQueueSize} spans already waiting on ${url}`)\n return\n }\n queue.push(span)\n if (queue.length >= batchSize) void drain()\n },\n\n async flush(): Promise<void> {\n await drain()\n const lost = dropped - droppedAtLastFlush\n droppedAtLastFlush = dropped\n if (lost > 0) {\n throw new Error(`OTLP exporter dropped ${lost} spans since the last flush: ${lastError}`)\n }\n },\n\n async shutdown(): Promise<void> {\n stopped = true\n clearInterval(timer)\n await drain()\n },\n\n stats(): OtelExportStats {\n return {\n written,\n dropped,\n pending: queue.length + inFlight,\n ...(lastError !== undefined ? { lastError } : {}),\n }\n },\n }\n}\n\n/** Node's fetch reports every socket failure as \"fetch failed\"; the cause names which one. */\nfunction describeFetchError(error: unknown): string {\n if (!(error instanceof Error)) return String(error)\n const cause = error.cause\n const code =\n cause && typeof cause === 'object' && 'code' in cause && typeof cause.code === 'string'\n ? cause.code\n : undefined\n return code ? `${error.message} (${code})` : error.message\n}\n\nfunction positiveInteger(value: number | undefined, fallback: number): number {\n return value !== undefined && Number.isSafeInteger(value) && value > 0 ? value : fallback\n}\n\n/**\n * Convert a LoopTraceEvent into an OtelSpan for export.\n */\nexport function loopEventToOtelSpan(\n event: {\n kind: string\n runId: string\n timestamp: number\n payload: object\n },\n traceId: string,\n parentSpanId?: string,\n): OtelSpan {\n const spanId = generateSpanId()\n const attrs: Record<string, string | number | boolean> = {\n 'loop.event_kind': event.kind,\n 'loop.run_id': event.runId,\n }\n for (const [k, v] of Object.entries(event.payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n attrs[`loop.${k}`] = v\n }\n }\n const ts = msToNs(event.timestamp)\n return {\n traceId: toW3CTraceId(traceId),\n spanId,\n parentSpanId: parentSpanId ? toW3CSpanId(parentSpanId) : undefined,\n name: event.kind,\n kind: 1,\n startTimeUnixNano: ts,\n endTimeUnixNano: ts,\n attributes: toOtlpAttributes(attrs),\n status: { code: 1 },\n }\n}\n\n/**\n * Build a single flat OtelSpan whose attribute keys are emitted VERBATIM — no\n * `loop.` namespace. Use for non-loop spans (e.g. the intelligence per-run\n * span) whose keys ARE the downstream contract (`gen_ai.request.model`,\n * `tangle.sessionId`) and are exact-matched by readers. `loopEventToOtelSpan`\n * namespaces payload keys because loop payload fields are free-form; do not\n * reuse it for spans with contract keys.\n */\nexport function flatOtelSpan(\n name: string,\n attributes: Record<string, string | number | boolean>,\n traceId: string,\n timestampMs: number,\n parentSpanId?: string,\n endTimestampMs = timestampMs,\n): OtelSpan {\n const start = msToNs(timestampMs)\n const end = msToNs(Math.max(timestampMs, endTimestampMs))\n return {\n traceId: toW3CTraceId(traceId),\n spanId: generateSpanId(),\n parentSpanId: parentSpanId ? toW3CSpanId(parentSpanId) : undefined,\n name,\n kind: 1,\n startTimeUnixNano: start,\n endTimeUnixNano: end,\n attributes: toOtlpAttributes(attributes),\n status: { code: 1 },\n }\n}\n\ninterface RuntimeEventOtelOptions extends RuntimeTelemetryOptions {\n /** Final customer redactor applied after the schema-aware runtime sanitizer. */\n redact?: (value: unknown) => unknown\n}\n\nfunction eventTimestampMs(event: RuntimeStreamEvent): number {\n if ('timestamp' in event && typeof event.timestamp === 'string') {\n const parsed = Date.parse(event.timestamp)\n if (Number.isFinite(parsed)) return parsed\n }\n return Date.now()\n}\n\nfunction serialized(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\nfunction mcpIdentity(toolName: string): { server?: string; tool?: string } {\n if (!toolName.startsWith('mcp__')) return {}\n const [, server, ...toolParts] = toolName.split('__')\n return {\n ...(server ? { server } : {}),\n ...(toolParts.length > 0 ? { tool: toolParts.join('__') } : {}),\n }\n}\n\n/** Convert normalized runtime events into lossless, redacted child spans. */\nexport function buildRuntimeEventOtelSpans(\n events: ReadonlyArray<RuntimeStreamEvent>,\n traceId: string,\n parentSpanId?: string,\n options: RuntimeEventOtelOptions = {},\n): OtelSpan[] {\n return events.map((event) => {\n const sanitized = sanitizeRuntimeStreamEvent(event, options)\n const safe = options.redact ? options.redact(sanitized) : sanitized\n const record =\n safe && typeof safe === 'object' && !Array.isArray(safe)\n ? (safe as Record<string, unknown>)\n : { value: safe }\n const attrs: Record<string, string | number | boolean> = {\n 'tangle.runtime.event_type': event.type,\n 'tangle.runtime.event': serialized(record),\n }\n let name = `tangle.runtime.${event.type}`\n if (parentSpanId) attrs[ATTR.parentConfidence] = 'explicit'\n\n if (event.type === 'tool_call' || event.type === 'tool_result') {\n name = `agent.${event.type}`\n // Only the call declares TOOL: one span per event means a call and its\n // result would otherwise both count as a tool span, doubling the true\n // invocation count. The result still exports losslessly (tool.output\n // below, joined to the call by tool.call_id); it is just not a second\n // declared TOOL kind for anyone counting tool spans. The result span\n // still carries 'tool.name' (for lookup and MCP identity below), and the\n // contract's inference falls back to TOOL from that same key on ANY\n // undeclared span — so the result must declare a kind explicitly (a\n // real UNKNOWN, not silence) or a reader with no declared-only path\n // (agent-trace-contract's resolveSpanKind, and traces/the validator's\n // TOOL breakdown, which both fall back to inference) double-counts it.\n attrs[ATTR.spanKind] = event.type === 'tool_call' ? 'TOOL' : 'UNKNOWN'\n attrs['tool.name'] = event.toolName\n // tool.call_id joins the call and its result. It is NOT\n // ATTR.operationId: that key names a retry-safety operation that a\n // supervised action's attempts share (see runtime/supervise/otel-spans.ts),\n // a different span-tree concept a single tool call/result pair does not\n // represent.\n if (event.toolCallId) attrs['tool.call_id'] = event.toolCallId\n const mcp = mcpIdentity(event.toolName)\n if (mcp.server) attrs['mcp.server'] = mcp.server\n if (mcp.tool) attrs['mcp.tool.name'] = mcp.tool\n const payload = event.type === 'tool_call' ? record.args : record.result\n if (payload !== undefined) {\n attrs[event.type === 'tool_call' ? 'tool.input' : 'tool.output'] = serialized(payload)\n }\n } else if (event.type === 'llm_call') {\n name = 'gen_ai.client.inference'\n attrs[ATTR.spanKind] = 'LLM'\n attrs['gen_ai.request.model'] = event.model\n if (event.tokensIn !== undefined) attrs['gen_ai.usage.input_tokens'] = event.tokensIn\n if (event.tokensOut !== undefined) attrs['gen_ai.usage.output_tokens'] = event.tokensOut\n if (event.costUsd !== undefined) attrs['tangle.cost.usd'] = event.costUsd\n if (event.latencyMs !== undefined) attrs['tangle.latency_ms'] = event.latencyMs\n if (event.finishReason !== undefined)\n attrs['gen_ai.response.finish_reasons'] = event.finishReason\n // The OTel GenAI convention a trace-contract gate reads to tell \"offered no tools\" from\n // \"never recorded the offered set\" (agent-eval's `tools.enforced`/capture-evidence checks).\n // Only set when THIS producer knows its own offered set (review finding on rows 13/14); a\n // sandboxed CLI harness's tool list belongs to its own transcript reader instead.\n if (event.tools !== undefined && event.tools.length > 0) {\n attrs[ATTR.toolDefinitions] = JSON.stringify(\n event.tools.map((toolName) => ({ type: 'function', name: toolName })),\n )\n }\n } else if (event.type === 'backend_error') {\n attrs['error.type'] = event.error?.kind ?? 'backend'\n attrs['error.message'] = event.message\n } else if (event.type === 'final') {\n attrs['tangle.outcome.status'] = event.status\n attrs['tangle.outcome.reason'] = event.reason\n if (event.error) {\n attrs['error.type'] = event.error.kind\n attrs['error.message'] = event.error.message\n }\n }\n\n const startMs = eventTimestampMs(event)\n const endMs =\n event.type === 'llm_call' && event.latencyMs !== undefined && Number.isFinite(event.latencyMs)\n ? startMs + event.latencyMs\n : startMs\n const span = flatOtelSpan(name, attrs, traceId, startMs, parentSpanId, endMs)\n if (\n event.type === 'backend_error' ||\n (event.type === 'final' && event.status !== 'completed')\n ) {\n span.status = { code: 2, message: attrs['error.message']?.toString() ?? event.type }\n }\n return span\n })\n}\n\n/**\n * Sink-neutral node in a reconstructed loop span tree. The root node's\n * `parentSpanId` is `undefined` — sinks decide how to parent it (the OTEL\n * mapper attaches the inherited delegation span; the delegation journal\n * leaves it as the tree root).\n */\ninterface LoopSpanNode {\n spanId: string\n parentSpanId?: string\n /** `'loop'` | `'loop.round'` | `'loop.iteration'`. */\n name: string\n /** Topology level: loop root, plan round, or iteration branch. */\n kind: 'loop' | 'round' | 'branch'\n startMs: number\n endMs: number\n attrs: Record<string, string | number | boolean>\n /** True when the iteration carried an error — maps to OTEL status code 2. */\n error: boolean\n}\n\n/**\n * Build a nested, real-duration OTLP span tree for ONE loop run from its full\n * ordered `LoopTraceEvent` stream. Unlike `loopEventToOtelSpan` (one flat,\n * zero-duration span per event), this reconstructs the topology hierarchy a\n * GenAI trace viewer renders natively:\n *\n * loop (invoke_workflow)\n * └─ loop.round[k] (invoke_workflow) ← tangle.loop.move.{kind,width,rationale}\n * ├─ loop.iteration[i] (invoke_agent) ← gen_ai.agent.name + usage + verdict + placement\n * └─ …\n *\n * Attributes follow the current GenAI semconv (`gen_ai.*`) where they apply and\n * a namespaced `tangle.loop.*` / `tangle.cost.usd` extension for topology /\n * verdict / placement / cost (not yet standardized). Pure: feed it a buffered\n * per-runId event array (e.g. flushed on `loop.ended`) and export the result.\n */\nexport function buildLoopOtelSpans(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n traceId: string,\n rootParentSpanId?: string,\n redact?: (value: unknown) => unknown,\n): OtelSpan[] {\n const tid = toW3CTraceId(traceId)\n return buildLoopSpanNodes(events, redact).map((node) => ({\n traceId: tid,\n spanId: node.spanId,\n parentSpanId: node.parentSpanId\n ? toW3CSpanId(node.parentSpanId)\n : rootParentSpanId\n ? toW3CSpanId(rootParentSpanId)\n : undefined,\n name: node.name,\n kind: 1,\n startTimeUnixNano: msToNs(node.startMs),\n endTimeUnixNano: msToNs(node.endMs),\n attributes: toOtlpAttributes({\n ...node.attrs,\n [ATTR.spanKind]: LOOP_SPAN_KIND[node.kind],\n ...(node.parentSpanId === undefined && rootParentSpanId\n ? { [ATTR.parentConfidence]: 'explicit' }\n : {}),\n }),\n status: { code: node.error ? 2 : 1 },\n }))\n}\n\n/**\n * The declared kind of each loop level. An iteration span carries its own token total, and an\n * undeclared span with tokens reads as an LLM call, so declaring AGENT keeps those tokens from\n * being counted a second time beside the model-call spans beneath it.\n */\nconst LOOP_SPAN_KIND: Record<LoopSpanNode['kind'], SpanKind> = {\n loop: 'CHAIN',\n round: 'CHAIN',\n branch: 'AGENT',\n}\n\n/**\n * Sink-neutral core behind {@link buildLoopOtelSpans}: reconstruct the\n * loop → round → branch span tree from one run's ordered `LoopTraceEvent`\n * stream. Consumed by the OTEL mapper above and by the MCP delegation\n * journal's compact trace tee — one topology reconstruction, two sinks.\n * Tolerates partial streams (a run that never reached `loop.ended` closes\n * at the last observed event's timestamp).\n */\nexport function buildLoopSpanNodes(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n redact?: (value: unknown) => unknown,\n): LoopSpanNode[] {\n if (events.length === 0) return []\n const out: LoopSpanNode[] = []\n const num = (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) ? v : undefined\n const str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined\n // Free-text node fields (rationale, decision, error, output preview) are model- or\n // customer-authored and may carry secrets — every one goes through the same redactor\n // as `tangle.input`/`tangle.output` before it becomes a span attribute.\n const strRedacted = (v: unknown): string | undefined => {\n const s = str(v)\n if (s === undefined) return undefined\n if (!redact) return s\n const safe = redact(s)\n return typeof safe === 'string' ? safe : JSON.stringify(safe)\n }\n const rec = (v: unknown): Record<string, unknown> =>\n v && typeof v === 'object' ? (v as Record<string, unknown>) : {}\n\n const started = events.find((e) => e.kind === 'loop.started')\n const ended = events.find((e) => e.kind === 'loop.ended')\n const runId = events[0]?.runId ?? ''\n const rootStart = started?.timestamp ?? events[0]!.timestamp\n const rootEnd = ended?.timestamp ?? events[events.length - 1]!.timestamp\n const rootId = generateSpanId()\n\n const make = (\n spanId: string,\n parentSpanId: string | undefined,\n name: string,\n kind: LoopSpanNode['kind'],\n startMs: number,\n endMs: number,\n attrs: Record<string, string | number | boolean>,\n error = false,\n ): LoopSpanNode => ({\n spanId,\n parentSpanId,\n name,\n kind,\n startMs,\n endMs,\n attrs,\n error,\n })\n\n // root\n const sp = rec(started?.payload)\n const rootAttrs: Record<string, string | number | boolean> = {\n [OPERATION_NAME_ATTR]: 'invoke_workflow',\n [ATTR.conversationId]: runId,\n // Explicit run identity under the tangle namespace so a consuming system of\n // record (Tangle Intelligence's run spine) maps this span tree to one run\n // deterministically, instead of inferring it from the conversation id.\n 'tangle.run.id': runId,\n 'tangle.loop.driver': str(sp.driver) ?? 'driver',\n }\n if (Array.isArray(sp.agentRunNames) && sp.agentRunNames.length > 0) {\n rootAttrs['tangle.loop.agents'] = sp.agentRunNames.map(String).join(',')\n // Subject grain: the primary agent/profile this run drove. Lets the spine\n // group runs under the thing being worked on rather than one service-wide\n // bucket. `agentRunNames[0]` is the lead agent on a fan-out.\n rootAttrs['tangle.subject.key'] = String(sp.agentRunNames[0])\n }\n if (ended) {\n const ep = rec(ended.payload)\n const win = num(ep.winnerIterationIndex)\n if (win !== undefined) rootAttrs['tangle.loop.winner.iteration_index'] = win\n const cost = num(ep.totalCostUsd)\n if (cost !== undefined) rootAttrs['tangle.cost.usd'] = cost\n const dur = num(ep.durationMs)\n if (dur !== undefined) rootAttrs['tangle.loop.duration_ms'] = dur\n const iters = num(ep.iterations)\n if (iters !== undefined) rootAttrs['tangle.loop.iterations'] = iters\n }\n out.push(make(rootId, undefined, 'loop', 'loop', rootStart, rootEnd, rootAttrs))\n\n // rounds + iterations\n const iterStartTs = new Map<number, number>()\n const placementByIdx = new Map<number, Record<string, string>>()\n let currentRoundId: string | undefined\n /** Plan round index → its span id, so an iteration joins the round it records (`groupId`). */\n const roundIdByIndex = new Map<number, string>()\n let pendingRound:\n | { id: string; start: number; attrs: Record<string, string | number | boolean> }\n | undefined\n const flushRound = (endMs: number) => {\n if (!pendingRound) return\n out.push(\n make(pendingRound.id, rootId, 'loop.round', 'round', pendingRound.start, endMs, {\n ...pendingRound.attrs,\n [ATTR.parentConfidence]: 'explicit',\n }),\n )\n pendingRound = undefined\n }\n\n for (const e of events) {\n const p = rec(e.payload)\n switch (e.kind) {\n case 'loop.plan': {\n flushRound(e.timestamp)\n const id = generateSpanId()\n const roundIdx = num(p.roundIndex) ?? 0\n const attrs: Record<string, string | number | boolean> = {\n [OPERATION_NAME_ATTR]: 'invoke_workflow',\n 'tangle.loop.round.index': roundIdx,\n 'tangle.loop.move.kind': str(p.moveKind) ?? 'unknown',\n 'tangle.loop.move.round': roundIdx,\n 'tangle.loop.move.width': num(p.plannedCount) ?? 0,\n }\n const r = strRedacted(p.rationale)\n if (r) attrs['tangle.loop.move.rationale'] = r\n const parent = num(p.parentIndex)\n if (parent !== undefined) attrs['tangle.loop.move.parent_index'] = parent\n if (Array.isArray(p.childIndices) && p.childIndices.length > 0) {\n attrs['tangle.loop.move.child_indices'] = p.childIndices.map(String).join(',')\n }\n pendingRound = { id, start: e.timestamp, attrs }\n currentRoundId = id\n roundIdByIndex.set(roundIdx, id)\n break\n }\n case 'loop.iteration.started': {\n const idx = num(p.iterationIndex)\n if (idx !== undefined) iterStartTs.set(idx, e.timestamp)\n break\n }\n case 'loop.iteration.dispatch': {\n const idx = num(p.iterationIndex)\n if (idx === undefined) break\n const place: Record<string, string> = {}\n const kind = str(p.placement)\n if (kind) place['tangle.loop.placement.kind'] = kind\n const sid = str(p.sandboxId)\n if (sid) place['tangle.sandbox.id'] = sid\n const fid = str(p.fleetId)\n if (fid) place['tangle.fleet.id'] = fid\n const mid = str(p.machineId)\n if (mid) place['tangle.machine.id'] = mid\n placementByIdx.set(idx, place)\n break\n }\n case 'loop.iteration.ended': {\n const idx = num(p.iterationIndex) ?? 0\n const start = iterStartTs.get(idx) ?? e.timestamp\n const err = strRedacted(p.error)\n const attrs: Record<string, string | number | boolean> = {\n [OPERATION_NAME_ATTR]: 'invoke_agent',\n 'tangle.loop.iteration.index': idx,\n }\n const agent = str(p.agentRunName)\n if (agent) attrs[ATTR.agentName] = agent\n const tu = rec(p.tokenUsage)\n const inTok = num(tu.input)\n if (inTok !== undefined) attrs[ATTR.inputTokens] = inTok\n const outTok = num(tu.output)\n if (outTok !== undefined) attrs[ATTR.outputTokens] = outTok\n const cost = num(p.costUsd)\n if (cost !== undefined) attrs['tangle.cost.usd'] = cost\n const verdict = rec(p.verdict)\n if (typeof verdict.valid === 'boolean') attrs['tangle.loop.verdict.valid'] = verdict.valid\n const score = num(verdict.score)\n if (score !== undefined) attrs['tangle.loop.verdict.score'] = score\n if (err) attrs['tangle.loop.error'] = err\n const gid = num(p.groupId)\n if (gid !== undefined) attrs['tangle.loop.iteration.group_id'] = gid\n // The round the iteration recorded is its parent. Without one, the round open when it ended\n // is only a guess from stream order.\n const recordedRoundId = gid === undefined ? undefined : roundIdByIndex.get(gid)\n attrs[ATTR.parentConfidence] = recordedRoundId ? 'explicit' : 'heuristic'\n const par = num(p.parentIndex)\n if (par !== undefined) attrs['tangle.loop.iteration.parent_index'] = par\n const dur = num(p.durationMs)\n if (dur !== undefined) attrs['tangle.loop.iteration.duration_ms'] = dur\n const preview = strRedacted(p.outputPreview)\n if (preview) attrs['tangle.loop.iteration.output_preview'] = preview\n Object.assign(attrs, placementByIdx.get(idx) ?? {})\n out.push(\n make(\n generateSpanId(),\n recordedRoundId ?? currentRoundId ?? rootId,\n 'loop.iteration',\n 'branch',\n start,\n e.timestamp,\n attrs,\n err !== undefined,\n ),\n )\n break\n }\n case 'loop.decision': {\n if (pendingRound) {\n const dec = strRedacted(p.decision)\n if (dec) pendingRound.attrs['tangle.loop.decision'] = dec\n flushRound(e.timestamp)\n }\n currentRoundId = undefined\n break\n }\n }\n }\n flushRound(rootEnd)\n return out\n}\n\nfunction parseHeadersFromEnv(): Record<string, string> {\n if (typeof process === 'undefined') return {}\n const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(',')) {\n const eq = pair.indexOf('=')\n if (eq < 0) continue\n const key = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n if (key) out[key] = value\n }\n return out\n}\n\nfunction msToNs(ms: number): string {\n return msToUnixNano(Number.isFinite(ms) ? ms : Date.now())\n}\n\n/** Mint a fresh 16-hex-character OTLP span id. Exported so a producer that must know a span's id\n * BEFORE the span closes (a node opened at spawn and parented by its children) uses this one\n * generator instead of a second copy of it. */\nexport function generateSpanId(): string {\n const bytes = new Uint8Array(8)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n","/**\n *\n * Trace context propagation across process-spawn boundaries.\n *\n * CANONICAL WIRE: the W3C `TRACEPARENT` environment variable\n * (`00-<32 hex trace id>-<16 hex span id>-<2 hex flags>`), the convention the wider ecosystem —\n * OTel SDKs, collectors, the Claude Code harness binary — already reads at spawn. The bespoke\n * `TRACE_ID` / `PARENT_SPAN_ID` pair this package shipped first is the FORK, not the standard:\n * it is still read as a fallback and still written alongside `TRACEPARENT` for one release, so\n * a child running either version of this package joins the same trace. The legacy pair is\n * scheduled for removal in the next major.\n *\n * read: TRACEPARENT first, then TRACE_ID / PARENT_SPAN_ID, else a fresh root.\n * write: BOTH — TRACEPARENT (+ TRACESTATE untouched) and TRACE_ID / PARENT_SPAN_ID.\n *\n * A fresh root minted because NO context reached this process is a severed hop, not a normal\n * start: it is marked `unpropagated: true` and every span tree it emits carries\n * `tangle.trace.unpropagated=true`, so a disconnected trace is a queryable fact instead of a\n * silent stranger.\n *\n * @experimental\n */\n\nimport * as traceContract from '@tangle-network/agent-trace-contract'\nimport type { OtelExporter } from '../otel-export'\nimport { buildLoopOtelSpans, createOtelExporter } from '../otel-export'\nimport { resolveRedactor } from '../redact'\nimport type { LoopTraceEmitter, LoopTraceEvent } from '../runtime/types'\n\nexport interface TraceContext {\n /** Trace id inherited from the parent process, or a fresh one. */\n traceId: string\n /** Parent span id from the delegation that launched this MCP server. */\n parentSpanId?: string\n /** True when NO context reached this process and the trace id is a fallback mint — the hop\n * above this process is severed. Span trees emitted under this context are stamped\n * `tangle.trace.unpropagated=true` so the severed hop is queryable. */\n unpropagated?: boolean\n}\n\n/** `00-<traceId>-<spanId>-<flags>`, any version prefix, case-insensitive per the W3C grammar. */\nconst TRACEPARENT_PATTERN = /^[0-9a-f]{2}-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i\n\n/** Parse a W3C `traceparent` header/env value, or `undefined` when malformed. Fails closed: a\n * half-formed value yields no context rather than an unjoinable id. */\nexport function parseTraceparent(value: unknown): TraceContext | undefined {\n if (typeof value !== 'string') return undefined\n const match = TRACEPARENT_PATTERN.exec(value.trim())\n if (!match) return undefined\n const traceId = (match[1] as string).toLowerCase()\n const parentSpanId = (match[2] as string).toLowerCase()\n if (!traceContract.isW3CTraceId(traceId) || !traceContract.isW3CSpanId(parentSpanId))\n return undefined\n return { traceId, parentSpanId }\n}\n\n/**\n * Read trace context from a process environment (defaults to `process.env`).\n * `TRACEPARENT` wins; the legacy `TRACE_ID` / `PARENT_SPAN_ID` pair is the fallback; with\n * neither present a fresh root is generated AND marked `unpropagated` — see {@link TraceContext}.\n */\nexport function readTraceContextFromEnv(\n env: Record<string, string | undefined> = process.env,\n): TraceContext {\n const fromTraceparent = parseTraceparent(env.TRACEPARENT)\n if (fromTraceparent) return fromTraceparent\n if (env.TRACE_ID) {\n return {\n traceId: env.TRACE_ID,\n ...(env.PARENT_SPAN_ID ? { parentSpanId: env.PARENT_SPAN_ID } : {}),\n }\n }\n return { traceId: generateTraceId(), unpropagated: true }\n}\n\n/**\n * Create a LoopTraceEmitter that:\n * 1. Parents all spans under the inherited parent span id.\n * 2. Exports spans to OTEL when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n *\n * Returns both the emitter and the optional exporter handle for shutdown.\n */\nexport function createPropagatingTraceEmitter(ctx: TraceContext): {\n emitter: LoopTraceEmitter\n exporter: OtelExporter | undefined\n context: TraceContext\n} {\n const exporter = createOtelExporter()\n // Same default scrubber `exportRunRecord` threads into its own loop-topology\n // export (src/intelligence/index.ts) — this sink emits the identical free-text\n // node attributes (rationale/decision/error/output_preview) and must not skip it.\n const redactor = resolveRedactor(undefined)\n\n // Buffer events per loop run, then emit the full nested span tree on\n // `loop.ended` so the topology hierarchy (loop → round → branch) reaches the\n // OTLP collector — not a flat list of zero-duration point spans. A run that\n // never reaches `loop.ended` (hard abort) drops its buffer; acceptable for\n // the short-lived MCP subprocess.\n const buffers = new Map<string, LoopTraceEvent[]>()\n\n const emitter: LoopTraceEmitter = {\n emit(event: LoopTraceEvent) {\n if (!exporter) return\n const buf = buffers.get(event.runId)\n if (buf) buf.push(event)\n else buffers.set(event.runId, [event])\n if (event.kind === 'loop.ended') {\n const events = buffers.get(event.runId) ?? [event]\n buffers.delete(event.runId)\n for (const span of buildLoopOtelSpans(events, ctx.traceId, ctx.parentSpanId, redactor)) {\n // The child-side severed-hop marker: a fallback-minted root stamps every span it emits,\n // so a trace with no inbound link SAYS so instead of appearing as a stranger tree. The\n // human run id stays in `loop.run_id` / `tangle.run.id` where it was already searchable.\n exporter.exportSpan(\n ctx.unpropagated === true\n ? {\n ...span,\n attributes: [\n ...(span.attributes ?? []),\n { key: 'tangle.trace.unpropagated', value: { boolValue: true } },\n ],\n }\n : span,\n )\n }\n }\n },\n }\n\n return { emitter, exporter, context: ctx }\n}\n\n/**\n * Build env vars to pass to a child subprocess so it inherits the current trace context.\n *\n * Writes BOTH conventions (see the module doc): `TRACEPARENT` carries the W3C-hex ids — mapped\n * through agent-trace-contract's `toW3CTraceId`/`toW3CSpanId` (dashed hex passes through dash-stripped, a\n * human id is derived through the contract's `deriveHexId`), the SAME normalization every emitted\n * span uses, so both spellings and the parent's own spans all name ONE trace — and the legacy\n * pair carries the caller's ids verbatim. `TRACEPARENT` needs a parent span id by grammar; when\n * the context has none, the legacy pair still propagates the trace id alone.\n */\nexport function traceContextToEnv(ctx: TraceContext): Record<string, string> {\n const env: Record<string, string> = { TRACE_ID: ctx.traceId }\n if (ctx.parentSpanId) env.PARENT_SPAN_ID = ctx.parentSpanId\n if (ctx.parentSpanId) {\n env.TRACEPARENT = `00-${traceContract.toW3CTraceId(ctx.traceId)}-${traceContract.toW3CSpanId(ctx.parentSpanId)}-01`\n }\n return env\n}\n\n/**\n * Merge a spawned child's environment from lowest to highest precedence — ambient env, the\n * recorder's stamped trace env, the caller's own overrides — while keeping the ONE cross-key\n * invariant a plain spread cannot: `TRACEPARENT` and the legacy pair must name the SAME trace.\n * A caller override that declares `TRACE_ID` / `PARENT_SPAN_ID` without its own `TRACEPARENT`\n * would otherwise keep the recorder's W3C wire — the child would join the caller's trace on the\n * legacy pair and the RECORDER's on the standard one. The dual-write is performed on the\n * caller's behalf: the merged `TRACEPARENT` is rebuilt from the merged legacy pair through the\n * same {@link traceContextToEnv} derivation (`deriveHexId` for human ids), or dropped when no\n * parent span id survives the merge (the W3C grammar requires one).\n */\nexport function mergeTraceEnv(\n ambient: Record<string, string | undefined>,\n traceEnv: Record<string, string>,\n overrides?: Record<string, string>,\n): Record<string, string | undefined> {\n const merged: Record<string, string | undefined> = {\n ...ambient,\n ...traceEnv,\n ...(overrides ?? {}),\n }\n const overridesIdentity =\n overrides !== undefined &&\n overrides.TRACEPARENT === undefined &&\n (overrides.TRACE_ID !== undefined || overrides.PARENT_SPAN_ID !== undefined)\n if (!overridesIdentity) return merged\n delete merged.TRACEPARENT\n if (merged.TRACE_ID !== undefined) {\n const rewritten = traceContextToEnv({\n traceId: merged.TRACE_ID,\n ...(merged.PARENT_SPAN_ID !== undefined ? { parentSpanId: merged.PARENT_SPAN_ID } : {}),\n })\n if (rewritten.TRACEPARENT !== undefined) merged.TRACEPARENT = rewritten.TRACEPARENT\n }\n return merged\n}\n\nfunction generateTraceId(): string {\n const bytes = new Uint8Array(16)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n","/**\n * Trace context handed DOWN to a spawned worker, so one supervised tree spans machines.\n *\n * WHY. `otel-spans.ts` makes the supervisor's own tree readable by any trace viewer, but it stops at\n * the process boundary: a worker running on a remote sandbox or in a child process opens its OWN\n * trace root, so the viewer shows two unrelated trees for one run. A worker that inherits the\n * parent's trace id and the spawning node's span id emits spans that JOIN the parent's trace, and\n * the viewer assembles the whole cross-machine tree with no viewer change.\n *\n * THE WIRE IS W3C `TRACEPARENT`, dual-written with the legacy pair. `traceContextToEnv`\n * (`src/mcp/trace-propagation.ts`) writes `TRACEPARENT` (the convention the ecosystem — OTel SDKs,\n * collectors, the Claude Code harness binary — reads at spawn) ALONGSIDE the bespoke\n * `TRACE_ID` / `PARENT_SPAN_ID` pair this package shipped first, and `readTraceContextFromEnv()`\n * reads `TRACEPARENT` first with the legacy pair as fallback. The bespoke pair is the fork, not\n * the standard; it is kept for one release so children on the previous package version still join,\n * then removed in the next major.\n *\n * WHICH SPAN. The stamped `PARENT_SPAN_ID` is the span of the node that DID the spawning — the\n * scope's own `parentId` — not the span of the worker's own node. At depth 0 that is the run's root\n * span; inside a driver's nested scope it is that driver child's span, so a depth-2 worker joins\n * under the middle node rather than the root. That is also the only span guaranteed to exist at the\n * moment the child's `ExecutorContext` is built (the worker's own node span is opened by the\n * `agent.spawn` hook that fires just after), so the wire needs no ordering assumption.\n *\n * OFF WHEN TRACING IS OFF. The context reaches an executor only through the `ExecutorContext` seam\n * this module names, and that seam is seeded only when a run configured `SuperviseOptions.otel` AND\n * an exporter resolved. With tracing off there is no seam, {@link workerTraceEnv} returns an empty\n * record, and every spawn environment is byte-identical to what it was before this module existed.\n *\n * TWO SEEDING SITES, because there are two ways a worker's `ExecutorContext` gets built. `Scope`\n * seeds it per child for anything the executor registry resolves — that is the path that knows the\n * spawning node and reaches arbitrary depth. `workerFromBackend` (what `supervise({ backend })`\n * uses) instead builds its leaf executor eagerly and hands it back as a bring-your-own `Executor`,\n * which the registry resolves WITHOUT consulting the scope's context at all; `supervise()` therefore\n * passes the seam to `workerFromBackend` itself, resolved against the run root, which is the node\n * that spawns every front-door worker. Miss that second site and the front door looks wired and\n * stamps nothing.\n *\n * PRECEDENCE, from lowest to highest:\n * 1. the supervisor process's own `process.env` (ambient inheritance),\n * 2. the trace context stamped here,\n * 3. the caller's own seam env (`CliSeam.env`).\n * A caller who sets `TRACE_ID` / `PARENT_SPAN_ID` on a seam wins — theirs is a deliberate\n * declaration about the worker — and the W3C wire follows: a seam that overrides the legacy pair\n * without its own `TRACEPARENT` gets `TRACEPARENT` rebuilt from ITS ids (`mergeTraceEnv` performs\n * the dual-write on the caller's behalf), never left as the recorder's, so both spellings always\n * name the same trace. Ambient `process.env` does NOT win: when the supervisor process was\n * itself launched as someone's worker, its inherited ids describe the SUPERVISOR's place in an\n * outer trace, and reusing them for a child would file the child's spans under the wrong parent.\n * The supported way to join that outer trace is `SupervisorSpanOptions.traceId` / `parentSpanId`\n * (feed them from `readTraceContextFromEnv()`), which makes the recorder's own ids the outer ones\n * and so makes every stamped child inherit them too.\n *\n * WHICH BACKENDS PROPAGATE. Only a backend with a real channel to the worker can carry this, and\n * the ones that have none say so here rather than dropping it silently:\n * - `cli` YES — `CliSeam.env` → the spawned subprocess.\n * - `sandbox` YES — `CreateSandboxOptions.env` on the box the worker runs in (single-shot\n * and steerable). This is the cross-MACHINE case the feature exists for.\n * - `bridge` YES — request headers on the bridge POST (`traceparent` plus the legacy\n * `x-trace-id` / `x-parent-span-id` pair, {@link workerTraceHeaders}); the\n * bridge stamps them into the harness child's environment at spawn.\n * - `router`,\n * `router-tools` NO — a direct model HTTP call. There is no worker process to inherit anything.\n * - `cli-worktree`,\n * `cli-in-place` NO — the work is dispatched through a local harness transport that exposes\n * no environment channel. Wiring it means adding that channel to the transport\n * first; until then it is honestly unpropagated.\n * - `provider` NO — `AgentEnvironmentProvider` has no environment field on its port.\n */\n\nimport { type TraceContext, traceContextToEnv } from '../../mcp/trace-propagation'\nimport type { ExecutorConfig } from './runtime'\n\n/**\n * The census above, as a value the compiler checks. `satisfies` against every `ExecutorConfig`\n * discriminant means an EIGHTH backend arm cannot be added without classifying it here — the prose\n * alone could go stale silently, which is the failure this table exists to prevent.\n *\n * `true` = the arm has a real channel to the worker (environment or transport headers) and stamps\n * the context. `false` = it has none today; it is honestly unpropagated rather than silently\n * dropping.\n */\nexport const WORKER_TRACE_PROPAGATION = {\n cli: true,\n sandbox: true,\n router: false,\n 'router-tools': false,\n bridge: true,\n 'cli-worktree': false,\n 'cli-in-place': false,\n provider: false,\n} as const satisfies Record<ExecutorConfig['backend'], boolean>\n\nexport type { TraceContext }\n\n/**\n * Seam key the `Scope` seeds a {@link TraceContext} under on each child's `ExecutorContext.seams`.\n * Single-sourced here so the scope and every backend agree on it without a circular import — the\n * same arrangement `nestedScopeSeamKey` uses.\n */\nexport const workerTraceSeamKey = 'worker-trace'\n\n/**\n * Resolve the trace context a worker spawned BY `spawningNodeId` should inherit. `undefined` means\n * this run records no spans, so nothing is stamped. Supplied by\n * `SupervisorSpanRecorder.workerTrace` and threaded to the scope as `SupervisorOpts.workerTrace`.\n */\nexport type WorkerTraceResolver = (spawningNodeId: string) => TraceContext | undefined\n\n/**\n * What the two readers below need off an `ExecutorContext` — its seam bag, and nothing else.\n * Structural (not an `ExecutorContext` import) so this module stays free of the keystone type\n * surface, and exported because it is part of a public signature.\n */\nexport interface WorkerTraceSeamCarrier {\n readonly seams: Readonly<Record<string, unknown>>\n}\n\n/**\n * Read the inherited trace context off an `ExecutorContext`, or `undefined` when the run records no\n * spans. Fails CLOSED on a malformed seam value (returns `undefined`) rather than stamping a\n * half-formed id that would produce an unjoinable orphan span downstream.\n */\nexport function readWorkerTraceContext(ctx: WorkerTraceSeamCarrier): TraceContext | undefined {\n const seam = ctx.seams[workerTraceSeamKey]\n if (seam === undefined || seam === null || typeof seam !== 'object') return undefined\n const { traceId, parentSpanId } = seam as { traceId?: unknown; parentSpanId?: unknown }\n if (typeof traceId !== 'string' || traceId.length === 0) return undefined\n return {\n traceId,\n ...(typeof parentSpanId === 'string' && parentSpanId.length > 0 ? { parentSpanId } : {}),\n }\n}\n\n/**\n * The trace env to merge into a worker's environment — `TRACEPARENT` plus the legacy\n * `TRACE_ID` / `PARENT_SPAN_ID` pair (dual-written for one release) — EMPTY when the run\n * records no spans, which is what keeps the untraced path byte-identical. Merge it BELOW the\n * caller's own seam env so a deliberately-set id wins (see the precedence note above).\n */\nexport function workerTraceEnv(ctx: WorkerTraceSeamCarrier): Record<string, string> {\n const traceContext = readWorkerTraceContext(ctx)\n return traceContext ? traceContextToEnv(traceContext) : {}\n}\n\n/**\n * The trace request headers for a worker dispatched over the cli-bridge HTTP transport — W3C\n * `traceparent` plus the legacy `x-trace-id` / `x-parent-span-id` pair the bridge also reads —\n * EMPTY when the run records no spans, which keeps the untraced request byte-identical. Derived\n * from the same dual-write the env channel uses ({@link workerTraceEnv}), so the header and env\n * spellings can never name different traces. `traceparent` is present only when a parent span id\n * exists (the W3C grammar requires one); the legacy pair still carries a lone trace id.\n */\nexport function workerTraceHeaders(ctx: WorkerTraceSeamCarrier): Record<string, string> {\n const env = workerTraceEnv(ctx)\n return {\n ...(env.TRACEPARENT !== undefined ? { traceparent: env.TRACEPARENT } : {}),\n ...(env.TRACE_ID !== undefined ? { 'x-trace-id': env.TRACE_ID } : {}),\n ...(env.PARENT_SPAN_ID !== undefined ? { 'x-parent-span-id': env.PARENT_SPAN_ID } : {}),\n }\n}\n","/**\n * Worker slots: the one bound on how many spawned agents work at the same time.\n *\n * Every scope of a supervised tree draws from one allocator. A host that runs several trees in one\n * process can pass the same allocator to each of them, and the bound then holds across all of them.\n *\n * A spawn past the bound is never refused. It keeps its reserved budget slice and waits in a queue,\n * and it starts when a slot frees. The queue releases the deepest spawn first and then the oldest,\n * so a subtree that is already paid for finishes before the tree grows wider.\n *\n * A slot counts a working agent: a spawned agent that runs with no running child of its own. A\n * manager whose children are all running is waiting on them, so its first running child takes over\n * the manager's slot and the manager takes it back when its last running child ends. This makes\n * nested waits deadlock-free: a manager can always run one child on its own slot, so a queued subtree\n * always keeps a path to completion, whatever the bound and however deep the tree.\n *\n * The bound therefore limits working agents, not environments. The environments alive at one time\n * can exceed it by the number of managers that have a running child. The conserved budget pool and\n * the deadline bound the total work; this allocator only bounds how much of it runs at once.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\n\n/** A fleet-wide bound on concurrently working agents, with a queue for the spawns past it. */\nexport interface WorkerSlots {\n /** The bound on working agents, or `undefined` when only the budget bounds concurrency. */\n readonly max: number | undefined\n /** Working agents that hold a slot now. */\n readonly working: number\n /** Spawns that hold a budget slice and wait for a slot. */\n readonly queued: number\n}\n\n/**\n * One held or awaited slot. `ready` resolves when the slot is granted; `granted` reads whether it\n * has been. `release` returns the slot, or withdraws a request that is still queued, and is\n * idempotent.\n */\nexport interface SlotPermit {\n readonly ready: Promise<void>\n readonly granted: boolean\n release(): void\n}\n\n/** The children of one scope. A root scope has no owner; a nested scope's owner is the permit its\n * own manager holds in the parent scope. */\nexport interface SlotGroup {\n /** Request a slot for one child spawned at `depth`. `force` grants at once past the bound, for\n * a recovered execution that already runs remotely. */\n acquire(depth: number, options?: { readonly force?: boolean }): SlotPermit\n /** This group's children that hold a slot or a lent slot. */\n readonly running: number\n /** This group's children that wait for a slot. */\n readonly queued: number\n}\n\ninterface PermitState {\n readonly group: GroupState\n granted: boolean\n released: boolean\n /** Whether this permit is one of the allocator's working units now. False while one of its own\n * children works on its slot. */\n counted: boolean\n /** The group of this permit's own children, once its scope is open. */\n children?: GroupState\n}\n\ninterface GroupState {\n readonly owner: PermitState | undefined\n running: number\n queued: number\n}\n\ninterface Waiter {\n readonly permit: PermitState\n readonly depth: number\n readonly order: number\n readonly grant: () => void\n}\n\ninterface AllocatorState {\n readonly max: number | undefined\n working: number\n order: number\n readonly waiters: Waiter[]\n}\n\nconst allocatorStates = new WeakMap<WorkerSlots, AllocatorState>()\n\n/**\n * Create a worker-slot allocator. `max` omitted, `0`, or negative leaves concurrency bounded by the\n * budget alone, and every spawn starts at once. Pass the returned allocator as `workerSlots` to each\n * run that should share one bound.\n */\nexport function createWorkerSlots(max?: number): WorkerSlots {\n const bound = normalizeWorkerSlotBound(max)\n const state: AllocatorState = { max: bound, working: 0, order: 0, waiters: [] }\n const slots: WorkerSlots = Object.freeze({\n max: bound,\n get working() {\n return state.working\n },\n get queued() {\n return state.waiters.length\n },\n })\n allocatorStates.set(slots, state)\n return slots\n}\n\n/** Accept a bound or an allocator; a number creates an allocator for one tree. */\nexport function resolveWorkerSlots(value: number | WorkerSlots | undefined): WorkerSlots {\n if (value === undefined || typeof value === 'number') return createWorkerSlots(value)\n if (!allocatorStates.has(value)) {\n throw new ValidationError('workerSlots must be a number or an allocator from createWorkerSlots')\n }\n return value\n}\n\n/** @internal Open the group of one scope's children. */\nexport function openSlotGroup(slots: WorkerSlots, owner?: SlotPermit): SlotGroup {\n const state = allocatorStates.get(slots)\n if (state === undefined) {\n throw new ValidationError('openSlotGroup: allocator was not created by createWorkerSlots')\n }\n const issued = owner === undefined ? undefined : (deferredPermits.get(owner)?.() ?? owner)\n const ownerState = issued === undefined ? undefined : permitStates.get(issued)\n if (owner !== undefined && ownerState === undefined) {\n throw new ValidationError('openSlotGroup: owner permit was not issued by this allocator')\n }\n const group: GroupState = { owner: ownerState, running: 0, queued: 0 }\n if (ownerState !== undefined) {\n if (ownerState.children !== undefined) {\n throw new ValidationError('openSlotGroup: a permit owns at most one group of children')\n }\n ownerState.children = group\n }\n return {\n acquire: (depth, options) => acquire(state, group, depth, options?.force === true),\n get running() {\n return group.running\n },\n get queued() {\n return group.queued\n },\n }\n}\n\nconst permitStates = new WeakMap<SlotPermit, PermitState>()\n/** Each deferred permit's reader of the permit it acquired, once it has acquired one. */\nconst deferredPermits = new WeakMap<SlotPermit, () => SlotPermit | undefined>()\n\n/**\n * @internal A slot requested only once `after` resolves. A spawn that waits for budget takes no\n * slot while it waits, so it cannot hold a slot that the work it waits on needs. `ready` rejects\n * when `after` does; `release` before then withdraws the request.\n */\nexport function deferSlot(after: Promise<void>, acquire: () => SlotPermit): SlotPermit {\n let inner: SlotPermit | undefined\n let released = false\n const ready = after.then(() => {\n if (released) return\n inner = acquire()\n return inner.ready\n })\n // A spawn that is withdrawn before it awaits `ready` never reads a refusal of `after`.\n ready.catch(() => undefined)\n const handle: SlotPermit = {\n ready,\n get granted() {\n return inner?.granted ?? false\n },\n release() {\n if (released) return\n released = true\n inner?.release()\n },\n }\n deferredPermits.set(handle, () => inner)\n return handle\n}\n\nfunction acquire(\n state: AllocatorState,\n group: GroupState,\n depth: number,\n force: boolean,\n): SlotPermit {\n if (!Number.isSafeInteger(depth) || depth < 0) {\n throw new ValidationError(`worker slots: depth must be a non-negative integer, got ${depth}`)\n }\n const permit: PermitState = { group, granted: false, released: false, counted: false }\n let resolveReady!: () => void\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve\n })\n const grant = () => {\n grantPermit(state, permit)\n resolveReady()\n }\n if (force || costOf(group) === 0 || hasCapacity(state)) {\n grant()\n } else {\n group.queued += 1\n const waiter: Waiter = { permit, depth, order: state.order++, grant }\n state.waiters.push(waiter)\n }\n const handle: SlotPermit = {\n ready,\n get granted() {\n return permit.granted\n },\n release() {\n if (permit.released) return\n permit.released = true\n if (!permit.granted) {\n withdraw(state, permit)\n return\n }\n releasePermit(state, permit)\n pump(state)\n },\n }\n permitStates.set(handle, permit)\n return handle\n}\n\n/** A child of `group` adds a working unit unless its manager is working on its own slot now, in\n * which case the child takes that slot over. */\nfunction costOf(group: GroupState): 0 | 1 {\n const owner = group.owner\n return owner?.granted && !owner.released && owner.counted ? 0 : 1\n}\n\nfunction hasCapacity(state: AllocatorState): boolean {\n return state.max === undefined || state.working < state.max\n}\n\nfunction grantPermit(state: AllocatorState, permit: PermitState): void {\n const group = permit.group\n if (costOf(group) === 0) {\n group.owner!.counted = false\n } else {\n state.working += 1\n }\n permit.granted = true\n permit.counted = true\n group.running += 1\n}\n\nfunction releasePermit(state: AllocatorState, permit: PermitState): void {\n // A manager that ends while its own children still run keeps its place in the chain of lent\n // slots until the last of them ends; the slot then passes up as if the manager ended then.\n if ((permit.children?.running ?? 0) > 0) return\n const group = permit.group\n group.running -= 1\n if (group.running < 0)\n throw new ValidationError('worker slots: a group released more than it ran')\n if (!permit.counted) return\n permit.counted = false\n const owner = group.owner\n if (group.running === 0 && owner !== undefined && owner.granted) {\n // The manager's last running child ended: the slot returns to the manager.\n owner.counted = true\n if (owner.released) releasePermit(state, owner)\n return\n }\n state.working -= 1\n if (state.working < 0) throw new ValidationError('worker slots: released more than granted')\n}\n\nfunction withdraw(state: AllocatorState, permit: PermitState): void {\n const index = state.waiters.findIndex((waiter) => waiter.permit === permit)\n if (index === -1) return\n state.waiters.splice(index, 1)\n permit.group.queued -= 1\n}\n\n/** Grant every waiter that can run: any waiter whose manager is working on its own slot, and then\n * the deepest and oldest waiters while capacity remains. */\nfunction pump(state: AllocatorState): void {\n for (;;) {\n let chosen: number | undefined\n for (let index = 0; index < state.waiters.length; index++) {\n const waiter = state.waiters[index]!\n if (costOf(waiter.permit.group) === 0) {\n chosen = index\n break\n }\n if (!hasCapacity(state)) continue\n const best = chosen === undefined ? undefined : state.waiters[chosen]!\n if (\n best === undefined ||\n waiter.depth > best.depth ||\n (waiter.depth === best.depth && waiter.order < best.order)\n ) {\n chosen = index\n }\n }\n if (chosen === undefined) return\n const [waiter] = state.waiters.splice(chosen, 1)\n waiter!.permit.group.queued -= 1\n waiter!.grant()\n }\n}\n\nfunction normalizeWorkerSlotBound(value: number | undefined): number | undefined {\n if (value === undefined || value <= 0) return undefined\n if (!Number.isSafeInteger(value)) {\n throw new ValidationError(\n `workerSlots must be a positive safe integer, or 0 or less for no bound, got ${String(value)}`,\n )\n }\n return value\n}\n","import type {\n AgentCandidateCapturedArtifact,\n AgentCandidateWorkspaceSnapshotEvidence,\n AgentExactRunControlRef,\n AgentProfile,\n WorkspaceCheckpointRef,\n} from '@tangle-network/agent-interface'\nimport {\n AgentExactRunControlRefSchema,\n canonicalAgentProfileDigest,\n} from '@tangle-network/agent-interface'\nimport type { AgentEnvironment } from '@tangle-network/agent-interface/environment-provider'\nimport type { AgentRunOutcome } from '@tangle-network/sandbox/runtime'\nimport { verifyWorkspaceSnapshotArtifacts } from '../candidate-execution/artifacts'\nimport { sha256Bytes } from '../candidate-execution/digest'\nimport type { AgentCandidateArtifactPort } from '../candidate-execution/types'\nimport {\n type AgentCandidateWorkspaceArchiveLimits,\n verifyAgentCandidateWorkspaceArchive,\n} from '../candidate-execution/workspace-archive'\nimport {\n type AgentCandidateWorkspaceTree,\n verifyAgentCandidateWorkspaceArtifacts,\n verifyAgentCandidateWorkspaceTree,\n} from '../candidate-execution/workspace-streams'\nimport { ValidationError } from '../errors'\nimport { sameControlCoordinates } from './retained-run-binding'\nimport { runAbortable } from './supervise/abortable'\nimport { armDeadlineTimer } from './supervise/deadline'\nimport { detachedSnapshot } from './supervise/snapshot'\nimport type { ExecutorNodeContext } from './supervise/types'\nimport { createWorkerSlots, openSlotGroup, type SlotGroup } from './supervise/worker-slots'\n\n/** The caller-owned boundary used to retain an executable provider workspace. */\nexport interface ProviderWorkspaceRetentionPort {\n /** Maximum wall-clock time Runtime gives queueing, capture, and verification. */\n readonly timeoutMs: number\n /**\n * Maximum simultaneous captures and verifications using this exact port object, including\n * recursive children. Omit for no admission bound. Share the port to share the bound.\n * Timed-out callbacks keep their slot until they settle, even if they ignore cancellation.\n */\n readonly maxConcurrentCaptures?: number\n /** Same explicit archive bounds used by the capture callback. */\n readonly limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n /** Refuse cleanup while any native session or workspace coverage remains missing. */\n readonly requireCompleteProvenance?: boolean\n /** Reads the durable manifest and archive after capture returns. */\n readonly artifacts: AgentCandidateArtifactPort\n /** Capture the live environment into the standard candidate workspace evidence shape. */\n capture(\n context: ProviderWorkspaceRetentionContext,\n ): Promise<AgentCandidateWorkspaceSnapshotEvidence | ProviderWorkspaceCaptureResult>\n /**\n * Capture only the harness's native session evidence, without the workspace, into the same\n * durable artifacts, reporting `workspaceScope: 'none'`.\n *\n * Runtime calls it every {@link nativeIntervalMs} while a turn runs and once more on every way\n * the turn ends: settled, failed, and an abort or deadline that closes the stream without\n * reaching either. A crash, deadline, credential renewal, reap or coordinator loss then loses\n * at most one interval of the session, and a workspace too large to capture no longer costs\n * the session. Measured before this existed: 85 of the 116 Discovery nodes that ran on Runtime\n * 0.297.x kept no session because their turn ended on an abort path, which never captured.\n *\n * When a deadline or an explicit cancellation ends a retained turn, Runtime stops its harness\n * and waits for the provider to report it stopped, within a 30 s bound, before the failure\n * capture and the final native copy, so both read a session that has stopped changing.\n *\n * Its captures use their own queue and bound, so they never wait behind workspace captures.\n */\n captureNative?(\n context: ProviderWorkspaceRetentionContext,\n ): Promise<ProviderWorkspaceCaptureResult>\n /**\n * Store one workspace checkpoint's files in the run's content-addressed store, before Runtime\n * deletes the checkpoint. Return what `captureAgentCandidateWorkspaceTreeToArtifacts` returns\n * for the files the environment holds, written to {@link artifacts}.\n *\n * A checkpoint is a provider snapshot that Runtime takes while a director works and deletes\n * once two newer ones exist. Its files are read from a fork Runtime creates from the snapshot\n * for this call alone: the fork holds exactly the checkpoint's workspace and runs no harness,\n * so the capture has no session to copy. Runtime verifies the tree against the store and the\n * checkpoint's marker file, journals its digest, and destroys the fork. Without this method, or\n * when a capture fails, Runtime keeps the checkpoint: on Discovery Lab run\n * terraform-dc-tokens-20261006d, 76 of the first 101 checkpoint deletions removed the only copy\n * of a director's workspace at that moment.\n *\n * Captures run on their own queue of {@link maxConcurrentCaptures} slots, under {@link timeoutMs}.\n */\n captureCheckpoint?(\n context: ProviderCheckpointCaptureContext,\n ): Promise<AgentCandidateWorkspaceTree>\n /** Capture a running environment's workspace without waiting for its turn to settle. */\n captureLive?(context: ProviderWorkspaceRetentionContext): Promise<AgentCandidateWorkspaceTree>\n /** Time between live workspace captures. Omit to leave live capture disabled. */\n readonly liveIntervalMs?: number\n /** Bound on one live capture and verification, including queue wait. Defaults to timeoutMs. */\n readonly liveTimeoutMs?: number\n /** Milliseconds between native captures of a running turn. Default 120,000. */\n readonly nativeIntervalMs?: number\n /** Bound on one native capture, including its queue wait. Default 120,000. */\n readonly nativeTimeoutMs?: number\n}\n\n/** When {@link ProviderWorkspaceRetentionPort.captureNative} runs relative to its turn. */\nexport type ProviderNativeCapturePhase = 'running' | 'settled' | 'failed' | 'interrupted'\n\n/** Default {@link ProviderWorkspaceRetentionPort.nativeIntervalMs}. */\nexport const DEFAULT_NATIVE_CAPTURE_INTERVAL_MS = 120_000\n/** Default {@link ProviderWorkspaceRetentionPort.nativeTimeoutMs}. */\nconst DEFAULT_NATIVE_CAPTURE_TIMEOUT_MS = 120_000\n\n/** Source inventory metadata for a workspace entry. */\nexport interface ProviderWorkspaceEntryMetadata {\n readonly path: string\n readonly type: 'file' | 'directory' | 'symlink'\n readonly sizeBytes: number\n readonly mode: number\n readonly owner?: string | null\n readonly group?: string | null\n readonly modifiedAt?: string | null\n readonly accessedAt?: string | null\n readonly symlinkTarget?: string | null\n}\n\n/** One Sidecar execution attempt; retries remain separate evidence. */\nexport interface ProviderWorkspaceAttemptProvenance {\n readonly executionId: string\n readonly ordinal: number\n readonly providerSessionId: string\n readonly nativeSessionIds: ReadonlyArray<string>\n readonly processIds: ReadonlyArray<string>\n readonly outcome: 'succeeded' | 'failed' | 'cancelled' | 'unknown'\n readonly missingReasons: ReadonlyArray<string>\n}\n\n/** Source-reported coverage retained with the verified archive reference. */\nexport interface ProviderWorkspaceCaptureProvenance {\n readonly status: 'reported' | 'unavailable'\n readonly provider?: string\n readonly environmentId?: string\n readonly executionId?: string\n /** Exact admitted provider execution; executionId above remains the Runtime artifact identity. */\n readonly controlRef?: AgentExactRunControlRef\n /** `none` marks a native-only capture: no workspace was scanned. */\n readonly workspaceScope?: 'environment' | 'none'\n readonly workspaceRoot?: string\n readonly capturedAt?: string\n readonly entries?: ReadonlyArray<ProviderWorkspaceEntryMetadata>\n readonly excludedPaths?: ReadonlyArray<\n ProviderWorkspaceEntryMetadata & { readonly reason: string }\n >\n readonly workspace?: {\n readonly scannedFiles: number\n readonly scannedDirectories: number\n readonly reportedFiles: number\n readonly reportedDirectories: number\n readonly complete: boolean\n }\n /** Sidecar attempts join sessions through executionIds, not the Runtime node ID. */\n readonly attempts?: ReadonlyArray<ProviderWorkspaceAttemptProvenance>\n readonly sessions?: ReadonlyArray<{\n readonly id: string\n readonly executionId: string\n readonly transportEvents: string\n readonly eventCount: number\n readonly messageCount: number\n readonly messageScope?: string\n readonly backendType?: string\n readonly executionIds?: ReadonlyArray<string>\n readonly eventCountsByExecutionId?: Readonly<Record<string, number>>\n readonly nativeSessionId?: string | null\n readonly nativeReason?: string | null\n readonly sidecarImageDigest?: string | null\n readonly sidecarBundleRevision?: string | null\n readonly nativeStore?: {\n readonly scope: 'session'\n readonly roots: ReadonlyArray<{\n readonly scope: 'session-home' | 'workspace-session'\n readonly path: string\n }>\n readonly inventory: {\n readonly scannedFiles: number\n readonly reportedFiles: number\n readonly scannedDirectories: number\n readonly reportedDirectories: number\n readonly scannedSymlinks: number\n readonly reportedSymlinks: number\n readonly skippedEntries: number\n } | null\n readonly complete: boolean\n readonly entries: ReadonlyArray<{\n readonly sourceId?: string\n readonly rootScope: 'session-home' | 'workspace-session'\n readonly path: string\n readonly kind: 'file' | 'directory' | 'symlink'\n readonly mode: number\n readonly sizeBytes: number\n readonly sha256: string | null\n readonly linkTarget: string | null\n }>\n readonly excludedPaths: ReadonlyArray<{\n readonly sourceId?: string\n readonly rootScope: 'session-home' | 'workspace-session'\n readonly path: string\n readonly kind: 'file' | 'directory' | 'symlink'\n readonly mode: number\n readonly sizeBytes: number\n readonly reason: 'credential'\n }>\n }\n readonly processStreams?: {\n readonly complete: boolean\n readonly streamCount: number\n readonly stdinBytes: number\n readonly stdoutBytes: number\n readonly stderrBytes: number\n readonly protocolBytes: number\n }\n readonly nativeEvents?: { readonly complete: boolean; readonly count: number }\n }>\n readonly missing: ReadonlyArray<string>\n}\n\nexport interface ProviderWorkspaceCaptureResult {\n readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence\n readonly provenance: ProviderWorkspaceCaptureProvenance\n readonly coverageComplete?: boolean\n readonly incompleteReason?: string\n /** Where the port's own capture spent its time, in the port's names and units (ms, bytes),\n * copied verbatim onto the `workspace-capture` journal event. Runtime sees only the call's\n * total; on canary test-acceptance-canary-20261019q the split was in the port alone. */\n readonly stages?: Readonly<Record<string, number>>\n}\n\n/** At most this many stage entries are kept from a port, each a finite, non-negative number. */\nconst MAX_CAPTURE_STAGES = 16\n\nfunction captureStages(value: unknown): Readonly<Record<string, number>> | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined\n const stages: Record<string, number> = {}\n for (const [name, amount] of Object.entries(value).slice(0, MAX_CAPTURE_STAGES)) {\n if (/^[A-Za-z][A-Za-z0-9]{0,63}$/u.test(name) && Number.isFinite(amount) && amount >= 0)\n stages[name] = amount\n }\n return Object.keys(stages).length === 0 ? undefined : Object.freeze(stages)\n}\n\n/**\n * Where one workspace capture's time went: the wait for a slot of the port's queue, which every\n * recursive environment shares, and the capture itself. Reported once per workspace capture, on\n * success and on failure, so a run records the split instead of leaving it to inference: on\n * Discovery Lab run terraform-economics-20261005f a turn's result arrived 4 to 28 minutes after its\n * stream ended, and nothing said how much of that was queue.\n */\nexport interface ProviderWorkspaceCaptureTiming {\n /** Captures of this port holding or waiting for a slot when this one was requested. */\n readonly ahead: number\n /** From the request to the slot being granted, or to the failure when none was granted. */\n readonly queuedMs: number\n /** From the slot being granted to the verified archive, or to the failure. Absent when the\n * capture never held a slot. */\n readonly captureMs?: number\n /** Bytes of the verified workspace archive. */\n readonly archiveBytes?: number\n readonly outcome: 'captured' | 'failed'\n /** Why a failed capture failed, bounded. */\n readonly error?: string\n /** The port's own split of `captureMs` ({@link ProviderWorkspaceCaptureResult.stages}). */\n readonly stages?: Readonly<Record<string, number>>\n}\n\n/** The exact live execution facts supplied to a retention callback. */\nexport interface ProviderWorkspaceRetentionContext {\n readonly environment: AgentEnvironment\n /** Runtime invocation identity used by the artifact store; never a provider session coordinate. */\n readonly executionId: string\n /** Exact admitted provider execution, available even before the harness emits its session id. */\n readonly controlRef?: AgentExactRunControlRef\n /** Exact supervised tree identity, when a supervisor created this execution. */\n readonly node?: ExecutorNodeContext\n /** Sandbox/provider session used for this turn; null means no session id was observed. */\n readonly providerSessionId?: string | null\n /** The harness's own session identity is unknown until a provider reports it. */\n readonly nativeSessionId?: string | null\n /** The exact profile used to create the provider environment. */\n readonly profile: AgentProfile\n /** The provider-derived outcome, when one was available before cleanup. */\n readonly outcome?: AgentRunOutcome\n /** Set on native captures only: whether the turn was still running or how it ended. */\n readonly phase?: ProviderNativeCapturePhase\n /** A fresh signal bounded by {@link ProviderWorkspaceRetentionPort.timeoutMs}. */\n readonly signal: AbortSignal\n}\n\n/** What {@link ProviderWorkspaceRetentionPort.captureCheckpoint} receives. */\nexport interface ProviderCheckpointCaptureContext {\n /** A fork of the checkpoint, created for this capture alone. It holds the checkpoint's\n * workspace and runs no harness. */\n readonly environment: AgentEnvironment\n /** The checkpoint the fork was created from. */\n readonly checkpoint: WorkspaceCheckpointRef\n /** Runtime artifact identity of this capture: `<node>:checkpoint:<checkpoint id>`. */\n readonly executionId: string\n /** The owner's profile; its harness names what the fork's source ran. */\n readonly profile: AgentProfile\n /** A fresh signal bounded by {@link ProviderWorkspaceRetentionPort.timeoutMs}. */\n readonly signal: AbortSignal\n}\n\nconst checkpointSlotKeys = new WeakMap<ProviderWorkspaceRetentionPort, CaptureSlots>()\nfunction checkpointSlots(port: ProviderWorkspaceRetentionPort): CaptureSlots {\n let key = checkpointSlotKeys.get(port)\n if (key === undefined) {\n key = Object.freeze({ maxConcurrentCaptures: port.maxConcurrentCaptures })\n checkpointSlotKeys.set(port, key)\n }\n return key\n}\n\n/**\n * Capture a checkpoint through the port on its own queue and bound, then verify that the store\n * holds every file of the returned tree and, when the checkpoint took a marker, that the tree\n * holds the marker's exact bytes, which proves it read this checkpoint and no other state.\n */\nexport async function captureProviderCheckpointWorkspace(\n port: ProviderWorkspaceRetentionPort,\n prepare: (signal: AbortSignal) => Promise<Omit<ProviderCheckpointCaptureContext, 'signal'>>,\n marker: { readonly path: string; readonly content: string } | undefined,\n parent?: AbortSignal,\n): Promise<AgentCandidateWorkspaceTree> {\n assertProviderWorkspaceRetentionPort(port, 'provider workspace retention')\n const capture = port.captureCheckpoint\n if (capture === undefined)\n throw new ValidationError('provider workspace retention: the port has no captureCheckpoint')\n const controller = new AbortController()\n const clearDeadline = armDeadlineTimer(\n port.timeoutMs,\n () => controller.abort(new Error(`checkpoint capture timed out after ${port.timeoutMs}ms`)),\n true,\n )\n const signal =\n parent === undefined ? controller.signal : AbortSignal.any([controller.signal, parent])\n try {\n return await runAbortable(\n () =>\n withCaptureSlot(checkpointSlots(port), signal, async () => {\n // Reserve capacity before creating the temporary checkpoint fork. A fork waiting in\n // this queue can otherwise idle into provider suspension before capture starts.\n const context = await prepare(signal)\n const tree = detachedSnapshot(\n await capture.call(port, { ...context, signal }),\n 'checkpoint capture tree',\n )\n if (tree?.kind !== 'agent-candidate-workspace-tree')\n throw new Error('checkpoint capture returned no workspace tree')\n const material = await verifyAgentCandidateWorkspaceTree(tree, port.artifacts, {\n ...(port.limits === undefined ? {} : { limits: port.limits }),\n signal,\n })\n if (material.files.length !== tree.files)\n throw new Error('checkpoint capture tree misstates its file count')\n if (marker !== undefined) {\n const bytes = Buffer.from(marker.content, 'utf8')\n const held = material.files.find((file) => file.path === marker.path)\n if (\n held === undefined ||\n held.byteLength !== bytes.byteLength ||\n held.sha256 !== sha256Bytes(bytes)\n )\n throw new Error(\n `checkpoint capture does not hold the checkpoint's marker ${marker.path}`,\n )\n }\n return tree\n }),\n signal,\n `checkpoint capture timed out after ${port.timeoutMs}ms`,\n )\n } finally {\n clearDeadline()\n }\n}\n\n/** Verify a running workspace copy before treating it as retained evidence. `parent` stops the\n * copy, in the queue or under way, when its turn ends. */\nexport async function captureProviderLiveWorkspace(\n port: ProviderWorkspaceRetentionPort,\n context: Omit<ProviderWorkspaceRetentionContext, 'signal'>,\n parent?: AbortSignal,\n): Promise<AgentCandidateWorkspaceTree> {\n assertProviderWorkspaceRetentionPort(port, 'provider workspace retention')\n if (port.captureLive === undefined)\n throw new ValidationError('provider workspace retention: the port has no captureLive')\n const timeoutMs = port.liveTimeoutMs ?? port.timeoutMs\n const controller = new AbortController()\n const clearDeadline = armDeadlineTimer(\n timeoutMs,\n () => controller.abort(new Error(`live workspace capture timed out after ${timeoutMs}ms`)),\n true,\n )\n const signal =\n parent === undefined ? controller.signal : AbortSignal.any([controller.signal, parent])\n try {\n return await runAbortable(\n () =>\n withCaptureSlot(checkpointSlots(port), signal, async () => {\n const tree = detachedSnapshot(\n await port.captureLive!({ ...context, signal }),\n 'live workspace capture tree',\n )\n if (tree?.kind !== 'agent-candidate-workspace-tree')\n throw new Error('live workspace capture returned no workspace tree')\n const material = await verifyAgentCandidateWorkspaceTree(tree, port.artifacts, {\n ...(port.limits === undefined ? {} : { limits: port.limits }),\n signal,\n })\n if (material.files.length !== tree.files)\n throw new Error('live workspace capture tree misstates its file count')\n return tree\n }),\n signal,\n `live workspace capture timed out after ${timeoutMs}ms`,\n )\n } finally {\n clearDeadline()\n }\n}\n\n/** Durable join from one provider box to the verified bytes retained before cleanup. */\nexport interface ProviderWorkspaceCaptureReceipt {\n readonly executionId: string\n /** Durable provider-native identity, separate from the Runtime invocation identity. */\n readonly controlRef?: AgentExactRunControlRef\n readonly node?: ExecutorNodeContext\n readonly environmentId: string\n /** Exact provider-create profile identity; materialization receipts bind it to the authored profile. */\n readonly profileDigest: string\n readonly providerSessionId: string | null\n readonly nativeSessionId: string | null\n readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence\n readonly provenance: ProviderWorkspaceCaptureProvenance\n readonly coverageComplete: boolean\n readonly incompleteReason?: string\n}\n\n/** @internal Construct the same exact receipt for a live capture and evidence-only recovery. */\nexport function workspaceCaptureReceipt(\n context: Omit<ProviderWorkspaceRetentionContext, 'signal'>,\n captured: ProviderWorkspaceCaptureResult,\n): ProviderWorkspaceCaptureReceipt {\n const { snapshot, provenance, coverageComplete = false, incompleteReason } = captured\n return {\n executionId: context.executionId,\n ...(context.controlRef === undefined ? {} : { controlRef: context.controlRef }),\n ...(context.node === undefined ? {} : { node: context.node }),\n environmentId: context.environment.id,\n profileDigest: canonicalAgentProfileDigest(context.profile),\n ...capturedSessionIdentity(\n provenance,\n coverageComplete,\n context.executionId,\n context.providerSessionId ?? null,\n ),\n snapshot,\n provenance,\n coverageComplete,\n ...(incompleteReason === undefined ? {} : { incompleteReason }),\n }\n}\n\n/** Only a verified, single-session capture may supply a scalar session identity. */\nfunction capturedSessionIdentity(\n provenance: ProviderWorkspaceCaptureProvenance | undefined,\n coverageComplete: boolean,\n executionId: string,\n providerSessionId: string | null,\n): { providerSessionId: string | null; nativeSessionId: string | null } {\n const unknown = { providerSessionId, nativeSessionId: null }\n if (\n !coverageComplete ||\n provenance?.status !== 'reported' ||\n provenance.executionId !== executionId ||\n provenance.sessions?.length !== 1\n )\n return unknown\n const session = provenance.sessions[0]!\n if (\n session.executionId !== executionId ||\n (providerSessionId !== null && session.id !== providerSessionId)\n )\n return unknown\n const ids = new Set(\n (provenance.attempts ?? [])\n .filter((attempt) => session.executionIds?.includes(attempt.executionId))\n .flatMap((attempt) => attempt.nativeSessionIds),\n )\n const nativeSessionId = ids.size === 1 ? [...ids][0]! : null\n if (session.nativeSessionId != null && nativeSessionId !== session.nativeSessionId)\n return { providerSessionId, nativeSessionId: null }\n return { providerSessionId, nativeSessionId }\n}\n\n/** Validate the executable retention port at the create boundary. */\nexport function assertProviderWorkspaceRetentionPort(\n port: ProviderWorkspaceRetentionPort,\n context: string,\n): void {\n if (!Number.isSafeInteger(port.timeoutMs) || port.timeoutMs <= 0) {\n throw new ValidationError(\n `${context}: workspaceRetention.timeoutMs must be a positive safe integer`,\n )\n }\n if (\n port.maxConcurrentCaptures !== undefined &&\n (!Number.isSafeInteger(port.maxConcurrentCaptures) || port.maxConcurrentCaptures <= 0)\n ) {\n throw new ValidationError(\n `${context}: workspaceRetention.maxConcurrentCaptures must be a positive safe integer`,\n )\n }\n if (port.artifacts === null || typeof port.artifacts?.read !== 'function') {\n throw new ValidationError(`${context}: workspaceRetention.artifacts.read is required`)\n }\n if (typeof port.capture !== 'function') {\n throw new ValidationError(`${context}: workspaceRetention.capture is required`)\n }\n for (const key of ['captureNative', 'captureCheckpoint', 'captureLive'] as const) {\n if (port[key] !== undefined && typeof port[key] !== 'function') {\n throw new ValidationError(`${context}: workspaceRetention.${key} must be a function`)\n }\n }\n if (port.liveIntervalMs !== undefined && port.captureLive === undefined) {\n throw new ValidationError(`${context}: workspaceRetention.liveIntervalMs requires captureLive`)\n }\n for (const key of [\n 'nativeIntervalMs',\n 'nativeTimeoutMs',\n 'liveIntervalMs',\n 'liveTimeoutMs',\n ] as const) {\n const value = port[key]\n if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {\n throw new ValidationError(\n `${context}: workspaceRetention.${key} must be a positive safe integer`,\n )\n }\n }\n}\n\ntype CaptureSlots = Pick<ProviderWorkspaceRetentionPort, 'maxConcurrentCaptures'>\nconst captureGroups = new WeakMap<CaptureSlots, SlotGroup>()\n// Native captures are small and frequent; their own queue keeps them out from behind\n// multi-gigabyte workspace captures at a deadline wave. One stable key per port shares it.\nconst nativeSlotKeys = new WeakMap<ProviderWorkspaceRetentionPort, CaptureSlots>()\nfunction nativeSlots(port: ProviderWorkspaceRetentionPort): CaptureSlots {\n let key = nativeSlotKeys.get(port)\n if (key === undefined) {\n key = Object.freeze({ maxConcurrentCaptures: port.maxConcurrentCaptures })\n nativeSlotKeys.set(port, key)\n }\n return key\n}\n\n// Native mirrors running on one port, read to pace each running copy against the port's slots.\nconst nativeMirrors = new WeakMap<ProviderWorkspaceRetentionPort, number>()\n\n/** Count one running native mirror on `port`; the returned close is idempotent. @internal */\nexport function openNativeMirror(port: ProviderWorkspaceRetentionPort): () => void {\n nativeMirrors.set(port, (nativeMirrors.get(port) ?? 0) + 1)\n let open = true\n return () => {\n if (!open) return\n open = false\n nativeMirrors.set(port, Math.max(0, (nativeMirrors.get(port) ?? 1) - 1))\n }\n}\n\n/**\n * The delay before a mirror's next running copy: its interval, or longer when the port's mirrors\n * need more copy time than its slots hold in that interval. queens21-h22-swarm16-20261018b copied\n * 9 sessions every 2 minutes through 4 slots at a median 134 s each, so all 4 slots stayed busy,\n * each copy waited behind the others, and copies past the 30-minute bound were dropped. @internal\n */\nexport function nativeCopyDelayMs(\n port: ProviderWorkspaceRetentionPort,\n intervalMs: number,\n lastCopyMs: number,\n): number {\n const mirrors = Math.max(1, nativeMirrors.get(port) ?? 1)\n const slots = port.maxConcurrentCaptures ?? mirrors\n return Math.max(intervalMs, Math.ceil((lastCopyMs * mirrors) / slots))\n}\n\n// Captures of one port that hold or wait for a slot, read as `ahead` by the next request.\nconst capturesInFlight = new WeakMap<CaptureSlots, number>()\n\nasync function withCaptureSlot<T>(\n port: CaptureSlots,\n signal: AbortSignal,\n capture: () => Promise<T>,\n): Promise<T> {\n if (port.maxConcurrentCaptures === undefined) return capture()\n let group = captureGroups.get(port)\n if (group === undefined) {\n // A root group never lends slots. Equal depths reuse the maintained allocator's FIFO queue.\n group = openSlotGroup(createWorkerSlots(port.maxConcurrentCaptures))\n captureGroups.set(port, group)\n }\n const permit = group.acquire(0)\n try {\n await runAbortable(() => permit.ready, signal, 'provider workspace retention queue aborted')\n signal.throwIfAborted()\n return await capture()\n } finally {\n // Release the actual operation, not its outer timeout race: late I/O still consumes capacity.\n permit.release()\n }\n}\n\n/** Count one capture of `port` in flight until `work` settles, and say how many were ahead. */\nfunction trackCapture<T>(port: CaptureSlots, work: (ahead: number) => Promise<T>): Promise<T> {\n const ahead = capturesInFlight.get(port) ?? 0\n capturesInFlight.set(port, ahead + 1)\n return work(ahead).finally(() => {\n capturesInFlight.set(port, Math.max(0, (capturesInFlight.get(port) ?? 1) - 1))\n })\n}\n\n/**\n * Capture, require durable refs, and verify every returned manifest/archive byte.\n * `native` calls {@link ProviderWorkspaceRetentionPort.captureNative} under its own queue and\n * bound, and judges coverage by the sessions alone. `onTiming` receives the queue wait and the\n * capture time of a workspace capture once it settles, whether it succeeded or failed.\n */\nexport async function captureProviderWorkspaceSnapshot(\n port: ProviderWorkspaceRetentionPort,\n context: Omit<ProviderWorkspaceRetentionContext, 'signal'>,\n scope: 'environment' | 'native' = 'environment',\n onTiming?: (timing: ProviderWorkspaceCaptureTiming) => void,\n /** Stops the capture, queued or under way; a native mirror's copy ends with its turn. */\n parent?: AbortSignal,\n): Promise<ProviderWorkspaceCaptureResult> {\n assertProviderWorkspaceRetentionPort(port, 'provider workspace retention')\n if (scope === 'native' || onTiming === undefined) {\n return await captureWithinSlot(port, context, scope, undefined, parent)\n }\n return await trackCapture(port, async (ahead) => {\n const requestedAt = Date.now()\n let grantedAt: number | undefined\n const report = (timing: Omit<ProviderWorkspaceCaptureTiming, 'ahead' | 'queuedMs'>): void => {\n const settledAt = Date.now()\n try {\n onTiming({\n ahead,\n queuedMs: (grantedAt ?? settledAt) - requestedAt,\n ...(grantedAt === undefined ? {} : { captureMs: settledAt - grantedAt }),\n ...timing,\n })\n } catch {\n // An observer that throws must not change the capture's outcome.\n }\n }\n try {\n const captured = await captureWithinSlot(port, context, scope, () => {\n grantedAt = Date.now()\n })\n report({\n outcome: 'captured',\n archiveBytes: captured.snapshot.archive.byteLength,\n ...(captured.stages === undefined ? {} : { stages: captured.stages }),\n })\n return captured\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n report({ outcome: 'failed', error: message.slice(0, 1_000) })\n throw error\n }\n })\n}\n\nasync function captureWithinSlot(\n port: ProviderWorkspaceRetentionPort,\n context: Omit<ProviderWorkspaceRetentionContext, 'signal'>,\n scope: 'environment' | 'native',\n onGranted?: () => void,\n parent?: AbortSignal,\n): Promise<ProviderWorkspaceCaptureResult> {\n const native = scope === 'native'\n if (native && port.captureNative === undefined) {\n throw new ValidationError('provider workspace retention: the port has no captureNative')\n }\n const timeoutMs = native\n ? (port.nativeTimeoutMs ?? DEFAULT_NATIVE_CAPTURE_TIMEOUT_MS)\n : port.timeoutMs\n const controlRef =\n context.controlRef === undefined\n ? undefined\n : AgentExactRunControlRefSchema.parse(context.controlRef)\n if (\n controlRef !== undefined &&\n (controlRef.environmentId !== context.environment.id ||\n controlRef.provider !== context.environment.provider ||\n (context.providerSessionId != null && controlRef.sessionId !== context.providerSessionId))\n )\n throw new Error(\n 'provider workspace retention control reference names another environment or session',\n )\n const controller = new AbortController()\n const clearDeadline = armDeadlineTimer(\n timeoutMs,\n () =>\n controller.abort(new Error(`provider workspace retention timed out after ${timeoutMs}ms`)),\n true,\n )\n const stopFromParent = () => controller.abort(parent?.reason)\n if (parent?.aborted) stopFromParent()\n else parent?.addEventListener('abort', stopFromParent, { once: true })\n try {\n const snapshot = await runAbortable(\n () =>\n withCaptureSlot(native ? nativeSlots(port) : port, controller.signal, async () => {\n onGranted?.()\n // Detach before any asynchronous artifact read. The callback owns its return object and\n // could otherwise mutate the manifest or archive references while verification is in flight.\n const input = {\n ...context,\n ...(controlRef === undefined ? {} : { controlRef: Object.freeze({ ...controlRef }) }),\n signal: controller.signal,\n }\n const result = detachedSnapshot(\n native ? await port.captureNative!(input) : await port.capture(input),\n 'provider workspace retention snapshot',\n )\n const snapshot = 'snapshot' in result ? result.snapshot : result\n const provenance =\n 'snapshot' in result\n ? detachedSnapshot(result.provenance, 'provider workspace retention provenance')\n : {\n status: 'unavailable' as const,\n missing: ['Capture callback returned no coverage metadata'],\n }\n if (\n !Array.isArray(provenance.missing) ||\n !['reported', 'unavailable'].includes(provenance.status)\n ) {\n throw new Error('provider workspace retention provenance is malformed')\n }\n if (\n provenance.status === 'reported' &&\n provenance.environmentId !== context.environment.id\n ) {\n throw new Error('provider workspace retention provenance names another environment')\n }\n if (\n provenance.executionId !== undefined &&\n provenance.executionId !== context.executionId\n ) {\n throw new Error('provider workspace retention provenance names another execution')\n }\n if (\n provenance.controlRef !== undefined &&\n (controlRef === undefined ||\n !sameControlCoordinates(\n AgentExactRunControlRefSchema.parse(provenance.controlRef),\n controlRef,\n ))\n )\n throw new Error(\n 'provider workspace retention provenance names another admitted execution',\n )\n const coverageGaps = [...provenance.missing]\n if (controlRef !== undefined) {\n if (provenance.controlRef === undefined)\n coverageGaps.push('Exact admitted control reference missing')\n if (\n !provenance.sessions?.some(\n (session) =>\n session.id === controlRef.sessionId &&\n session.executionIds?.includes(controlRef.executionId),\n )\n )\n coverageGaps.push('Exact admitted provider execution missing from capture')\n }\n if (provenance.status !== 'reported') coverageGaps.push('Coverage metadata unavailable')\n if (provenance.executionId !== context.executionId)\n coverageGaps.push('Exact execution identity missing')\n if (native) {\n if (provenance.workspaceScope !== 'none')\n coverageGaps.push('Native capture did not report a native-only scope')\n } else if (provenance.workspace?.complete !== true)\n coverageGaps.push('Workspace inventory incomplete')\n if (provenance.sessions === undefined) coverageGaps.push('Session inventory missing')\n if (\n context.providerSessionId != null &&\n !provenance.sessions?.some(\n (session) =>\n session.id === context.providerSessionId &&\n session.executionId === context.executionId,\n )\n )\n coverageGaps.push(`Provider session ${context.providerSessionId} missing from capture`)\n for (const session of provenance.sessions ?? []) {\n if (session.executionId !== context.executionId)\n coverageGaps.push(`Session ${session.id} names another execution`)\n if (session.transportEvents !== 'complete')\n coverageGaps.push(`Session ${session.id} transport events unavailable`)\n if (session.backendType !== context.profile.harness)\n coverageGaps.push(`Session ${session.id} harness identity mismatch`)\n if (\n session.nativeStore?.complete !== true ||\n session.nativeStore.inventory?.skippedEntries !== 0\n )\n coverageGaps.push(`Session ${session.id} native store incomplete`)\n if (session.processStreams?.complete !== true)\n coverageGaps.push(`Session ${session.id} process streams incomplete`)\n if (session.nativeEvents?.complete !== true)\n coverageGaps.push(`Session ${session.id} native events incomplete`)\n if (!/^sha256:[0-9a-f]{64}$/.test(session.sidecarImageDigest ?? ''))\n coverageGaps.push(`Session ${session.id} sidecar image digest missing`)\n if (!/^[0-9a-f]{40}$/.test(session.sidecarBundleRevision ?? ''))\n coverageGaps.push(`Session ${session.id} sidecar bundle revision missing`)\n }\n coverageGaps.push(\n ...attemptCoverageGaps(provenance, port.requireCompleteProvenance === true),\n )\n const coverageComplete = coverageGaps.length === 0\n requireDurableWorkspaceArtifacts(snapshot)\n if (port.artifacts.readStream) {\n await verifyAgentCandidateWorkspaceArtifacts({\n role: 'candidate',\n snapshot,\n artifacts: port.artifacts,\n signal: controller.signal,\n ...(port.limits === undefined ? {} : { limits: port.limits }),\n })\n } else {\n const { archive } = await verifyWorkspaceSnapshotArtifacts(snapshot, port.artifacts)\n await verifyAgentCandidateWorkspaceArchive({\n role: 'candidate',\n snapshot,\n archive,\n ...(port.limits === undefined ? {} : { limits: port.limits }),\n })\n }\n const stages = 'snapshot' in result ? captureStages(result.stages) : undefined\n return {\n snapshot,\n provenance,\n coverageComplete,\n ...(stages === undefined ? {} : { stages }),\n ...(coverageComplete\n ? {}\n : {\n incompleteReason: `provider workspace retention coverage incomplete: ${coverageGaps.join('; ')}`,\n }),\n }\n }),\n controller.signal,\n `provider workspace retention timed out after ${timeoutMs}ms`,\n )\n return snapshot\n } finally {\n clearDeadline()\n parent?.removeEventListener('abort', stopFromParent)\n }\n}\n\n/** Reconcile Sidecar attempts to the exact captured session executions. */\nfunction attemptCoverageGaps(\n provenance: ProviderWorkspaceCaptureProvenance,\n strict: boolean,\n): string[] {\n const attempts = provenance.attempts\n if (attempts === undefined) return strict ? ['Attempt inventory missing'] : []\n if (!Array.isArray(attempts)) return ['Attempt inventory malformed']\n const gaps: string[] = []\n if (strict && attempts.length === 0) gaps.push('Attempt inventory empty')\n const owners = new Map<string, string>()\n for (const session of provenance.sessions ?? []) {\n if (!Array.isArray(session.executionIds) || session.executionIds.length === 0) {\n gaps.push(`Session ${session.id} has no Sidecar execution inventory`)\n continue\n }\n for (const id of session.executionIds) {\n if (typeof id !== 'string' || id.trim() === '') {\n gaps.push(`Session ${session.id} has an invalid Sidecar execution ID`)\n continue\n }\n if (owners.has(id)) gaps.push(`Sidecar execution ${id} has multiple session owners`)\n else owners.set(id, session.id)\n const count = session.eventCountsByExecutionId?.[id]\n if (!Number.isSafeInteger(count) || (count ?? 0) <= 0)\n gaps.push(`Sidecar execution ${id} has no retained event count`)\n }\n }\n const ordinals = new Map<string, Set<number>>()\n for (const [index, attempt] of attempts.entries()) {\n if (attempt === null || typeof attempt !== 'object') {\n gaps.push(`Attempt ${index} is malformed`)\n continue\n }\n const id = attempt.executionId\n if (typeof id !== 'string' || id.trim() === '' || !owners.has(id)) {\n gaps.push(`Attempt ${index} has no exact Sidecar execution owner`)\n continue\n }\n if (typeof attempt.providerSessionId !== 'string' || attempt.providerSessionId.trim() === '')\n gaps.push(`Attempt ${id} has no provider session ID`)\n if (!Number.isSafeInteger(attempt.ordinal) || attempt.ordinal <= 0) {\n gaps.push(`Attempt ${id} has an invalid ordinal`)\n } else {\n const seen = ordinals.get(id) ?? new Set<number>()\n if (seen.has(attempt.ordinal)) gaps.push(`Attempt ${id} repeats ordinal ${attempt.ordinal}`)\n seen.add(attempt.ordinal)\n ordinals.set(id, seen)\n }\n if (\n !Array.isArray(attempt.nativeSessionIds) ||\n attempt.nativeSessionIds.length === 0 ||\n attempt.nativeSessionIds.some(\n (nativeId: unknown) => typeof nativeId !== 'string' || nativeId.trim() === '',\n ) ||\n new Set(attempt.nativeSessionIds).size !== attempt.nativeSessionIds.length\n )\n gaps.push(`Attempt ${id}/${attempt.ordinal} has incomplete native session identity`)\n if (\n !Array.isArray(attempt.processIds) ||\n attempt.processIds.some(\n (processId: unknown) => typeof processId !== 'string' || processId.trim() === '',\n ) ||\n new Set(attempt.processIds).size !== attempt.processIds.length\n )\n gaps.push(`Attempt ${id}/${attempt.ordinal} has invalid process identity`)\n if (!['succeeded', 'failed', 'cancelled', 'unknown'].includes(attempt.outcome))\n gaps.push(`Attempt ${id}/${attempt.ordinal} has invalid outcome`)\n else if (strict && attempt.outcome === 'unknown')\n gaps.push(`Attempt ${id}/${attempt.ordinal} has unknown outcome`)\n if (\n !Array.isArray(attempt.missingReasons) ||\n attempt.missingReasons.some(\n (reason: unknown) => typeof reason !== 'string' || reason.trim() === '',\n )\n )\n gaps.push(`Attempt ${id}/${attempt.ordinal} has malformed missing reasons`)\n else if (attempt.missingReasons.length > 0)\n gaps.push(`Attempt ${id}/${attempt.ordinal}: ${attempt.missingReasons.join('; ')}`)\n }\n for (const session of provenance.sessions ?? []) {\n const ownedAttempts = attempts.filter(\n (attempt) =>\n attempt != null &&\n typeof attempt === 'object' &&\n session.executionIds?.includes(attempt.executionId),\n )\n if (session.nativeSessionId != null) {\n const nativeIds = new Set(\n ownedAttempts.flatMap((attempt) =>\n Array.isArray(attempt.nativeSessionIds) ? attempt.nativeSessionIds : [],\n ),\n )\n if (!nativeIds.has(session.nativeSessionId))\n gaps.push(`Session ${session.id} native identity conflicts with attempt inventory`)\n }\n if (\n (session.processStreams?.streamCount ?? 0) > 0 &&\n !ownedAttempts.some(\n (attempt) => Array.isArray(attempt.processIds) && attempt.processIds.length > 0,\n )\n )\n gaps.push(`Session ${session.id} process streams lack attempt process identity`)\n }\n for (const id of owners.keys()) {\n const seen = ordinals.get(id)\n if (!seen || seen.size === 0) {\n gaps.push(`Sidecar execution ${id} has no attempt record`)\n continue\n }\n for (let ordinal = 1; ordinal <= seen.size; ordinal++)\n if (!seen.has(ordinal))\n gaps.push(`Sidecar execution ${id} is missing attempt ordinal ${ordinal}`)\n }\n return gaps\n}\n\n/** Native checkpoints, embedded bytes, and digest-only values cannot outlive their source. */\nfunction requireDurableWorkspaceArtifacts(snapshot: AgentCandidateWorkspaceSnapshotEvidence): void {\n if (!isDurableArtifact(snapshot.manifest) || !isDurableArtifact(snapshot.archive)) {\n throw new Error(\n 'provider workspace retention requires durable manifest and archive artifact references',\n )\n }\n}\n\nfunction isDurableArtifact(artifact: AgentCandidateCapturedArtifact): boolean {\n return 'locator' in artifact\n}\n","import type {\n AgentEnvironment,\n AgentEnvironmentProvider,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { awaitAbortable } from './retained-run-binding'\nimport { abortError } from './util'\n\nconst INTERACTIVE_CLEANUP_TIMEOUT_MS = 30_000\n/** Bound on one lookup that asks the provider whether it still holds an environment. */\nexport const ENVIRONMENT_LOOKUP_TIMEOUT_MS = 30_000\n\n/**\n * Whether the provider no longer holds `environmentId`, asked after a destroy failed.\n *\n * A delete that ran on the server but whose answer was lost, or that a cancel aborted in flight,\n * fails on every later delete with not-found: the Tangle SDK throws `NotFoundError` on a 404. A\n * retry that only re-sends the delete then never confirms, and names for a sweeper an environment\n * that no longer exists. The provider's lookup is the confirmation left: `get` answering `null`\n * means the environment is gone, the same rule a retained release applies. A lookup that fails,\n * times out or finds the environment confirms nothing.\n */\nexport async function environmentGone(\n provider: Pick<AgentEnvironmentProvider, 'get'>,\n environmentId: string,\n signal?: AbortSignal,\n): Promise<boolean> {\n if (provider.get === undefined) return false\n const bound = AbortSignal.timeout(ENVIRONMENT_LOOKUP_TIMEOUT_MS)\n try {\n const found = await awaitAbortable(\n Promise.resolve().then(() => provider.get!(environmentId)),\n signal === undefined ? bound : AbortSignal.any([signal, bound]),\n )\n return found === null\n } catch {\n return false\n }\n}\n\n/** Create one environment while retaining ownership if cancellation wins the race. */\nexport async function createInteractiveEnvironment(\n create: () => Promise<AgentEnvironment>,\n signal?: AbortSignal,\n): Promise<AgentEnvironment> {\n if (signal?.aborted) throw abortError(signal.reason)\n const creation = Promise.resolve().then(create)\n if (signal === undefined) return creation\n\n return new Promise<AgentEnvironment>((resolve, reject) => {\n let owner: 'pending' | 'caller' | 'runtime' = 'pending'\n const removeAbortListener = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n if (owner !== 'pending') return\n owner = 'runtime'\n removeAbortListener()\n disposeInteractiveEnvironment(creation, signal.reason)\n reject(abortError(signal.reason))\n }\n\n signal.addEventListener('abort', onAbort, { once: true })\n creation.then(\n (environment) => {\n if (owner !== 'pending') return\n owner = 'caller'\n removeAbortListener()\n resolve(environment)\n },\n (error) => {\n if (owner !== 'pending') return\n owner = 'runtime'\n removeAbortListener()\n reject(error)\n },\n )\n })\n}\n\n/** Start one process while destroying its unreturned environment on cancellation. */\nexport async function startInteractiveProcess<T>(\n environment: AgentEnvironment,\n start: () => Promise<T>,\n signal?: AbortSignal,\n): Promise<T> {\n if (signal?.aborted) {\n disposeInteractiveEnvironment(Promise.resolve(environment), signal.reason)\n throw abortError(signal.reason)\n }\n const pending = Promise.resolve().then(start)\n if (signal === undefined) return pending\n\n return new Promise<T>((resolve, reject) => {\n let owner: 'pending' | 'caller' | 'runtime' = 'pending'\n const removeAbortListener = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n if (owner !== 'pending') return\n owner = 'runtime'\n removeAbortListener()\n disposeInteractiveEnvironment(Promise.resolve(environment), signal.reason)\n reject(abortError(signal.reason))\n }\n\n signal.addEventListener('abort', onAbort, { once: true })\n pending.then(\n (result) => {\n if (owner !== 'pending') return\n owner = 'caller'\n removeAbortListener()\n resolve(result)\n },\n (error) => {\n if (owner !== 'pending') return\n owner = 'runtime'\n removeAbortListener()\n reject(error)\n },\n )\n })\n}\n\n/** Destroy an environment with fresh, bounded cleanup authority. */\nexport async function destroyInteractiveEnvironment(environment: AgentEnvironment): Promise<void> {\n if (!environment.destroy) {\n throw new Error(`provider environment \"${environment.id}\" does not expose destroy()`)\n }\n\n const controller = new AbortController()\n const timeout = new Error('interactive environment cleanup timed out')\n let timer: ReturnType<typeof setTimeout> | undefined\n const destruction = Promise.resolve().then(() =>\n environment.destroy?.({ signal: controller.signal }),\n )\n void destruction.catch(() => undefined)\n try {\n await Promise.race([\n destruction,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort(timeout)\n reject(timeout)\n }, INTERACTIVE_CLEANUP_TIMEOUT_MS)\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\nfunction disposeInteractiveEnvironment(\n environment: Promise<AgentEnvironment>,\n abortReason: unknown,\n): void {\n void environment\n .then(destroyInteractiveEnvironment, () => undefined)\n .catch((cleanupError: unknown) => {\n const reason = abortReason instanceof Error ? abortReason : new Error(String(abortReason))\n const failure = new AggregateError(\n [reason, cleanupError],\n 'cancelled interactive environment cleanup failed',\n )\n process.emitWarning(failure, {\n code: 'AGENT_RUNTIME_INTERACTIVE_CLEANUP_FAILED',\n })\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 type { RequestedInteractions } from '@tangle-network/agent-interface'\nimport type { AgentEnvironmentCapabilities } from '@tangle-network/agent-interface/environment-provider'\n\n/**\n * Check one turn's interaction request before the provider can dispatch it.\n *\n * A requested interaction is durable only when the provider can replay its\n * event and safely replay the response command. An unsupported request fails\n * before environment creation or dispatch begins.\n */\nexport function assertRequestedInteractionCapabilities(\n providerName: string,\n requested: RequestedInteractions | undefined,\n capabilities: AgentEnvironmentCapabilities,\n): void {\n const requestedKinds = Object.entries(requested ?? {})\n .filter(([, enabled]) => enabled === true)\n .map(([kind]) => kind)\n if (requestedKinds.length === 0) return\n\n const interactions = capabilities.interactions\n if (!interactions) {\n throw new Error(\n `provider \"${providerName}\" does not support requested interactions: ${requestedKinds.join(', ')}`,\n )\n }\n const unsupportedKinds = requestedKinds.filter((kind) => !interactions.kinds.includes(kind))\n if (unsupportedKinds.length > 0) {\n throw new Error(\n `provider \"${providerName}\" does not support requested interaction kinds: ${unsupportedKinds.join(', ')}`,\n )\n }\n if (interactions.replay !== true || interactions.responseIdempotency !== true) {\n throw new Error(\n `provider \"${providerName}\" cannot safely dispatch requested interactions without replay and response idempotency`,\n )\n }\n}\n","import {\n type ContextTransferReceipt,\n ContextTransferReceiptSchema,\n type ContextTransferRequest,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n contextTransferReceiptMatches,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type { RetainedRunStartMaterial } from './retained-run-types'\nimport { detachedSnapshot } from './supervise/snapshot'\n\n/** Validate attachment authority before admission or any provider operation. */\nexport function retainedContextTransferReceipt(\n options: RetainedRunStartMaterial,\n provider: string,\n request: ContextTransferRequest | undefined,\n): ContextTransferReceipt | undefined {\n if (request === undefined) {\n if (options.contextTransferReceipt !== undefined)\n throw new Error('context transfer receipt requires its exact request')\n return undefined\n }\n if (options.contextTransferReceipt === undefined) {\n throw new Error(\n 'retained context transfer requires an accepted receipt; it cannot create another environment',\n )\n }\n const receipt = detachedSnapshot(\n ContextTransferReceiptSchema.parse(options.contextTransferReceipt),\n 'retained context transfer receipt',\n )\n if (!contextTransferReceiptMatches(request, receipt) || receipt.provider !== provider) {\n throw new Error(\n 'retained context transfer receipt does not match its exact request or provider',\n )\n }\n const { environment, turn } = options\n const destination = request.plan.destination\n if (\n request.profile === undefined ||\n typeof environment.profile === 'string' ||\n canonicalAgentProfileDigest(environment.profile) !== destination.profileDigest ||\n (turn.profile !== undefined &&\n canonicalAgentProfileDigest(turn.profile) !== destination.profileDigest)\n ) {\n throw new Error('retained context transfer requires the accepted exact profile')\n }\n if (environment.backend !== undefined && environment.backend !== destination.runner) {\n throw new Error('retained context transfer runner conflicts with the accepted destination')\n }\n // The attaching provider resolves and pins the accepted effective model, including profile\n // defaults, and validates any turn override. Runtime cannot interpret provider-native routes.\n if (\n canonicalCandidateDigest(environment.workspace ?? null) !==\n canonicalCandidateDigest(request.workspace ?? null) ||\n canonicalCandidateDigest(environment.resources ?? null) !==\n canonicalCandidateDigest(request.resources ?? null)\n ) {\n throw new Error('retained context transfer workspace or resources conflict with acceptance')\n }\n if (\n (environment.requestedId !== undefined && environment.requestedId !== receipt.environmentId) ||\n (options.existingEnvironmentId !== undefined &&\n options.existingEnvironmentId !== receipt.environmentId)\n ) {\n throw new Error('retained context transfer targets another environment')\n }\n // These are create-time effects, absent from the accepted transfer request. Attachment cannot\n // apply them retroactively or silently drop them. Public labels and admission metadata are local.\n if (\n environment.runtimeAttachments !== undefined ||\n environment.egress !== undefined ||\n environment.billingOwner !== undefined ||\n Object.keys(environment.env ?? {}).length > 0 ||\n Object.keys(environment.secrets ?? {}).length > 0 ||\n Object.keys(environment.providerOptions ?? {}).length > 0\n ) {\n throw new Error(\n 'retained context transfer attachment cannot apply unaccepted create-time options',\n )\n }\n return receipt\n}\n\nexport function assertRetainedContextTransferIdentity(\n receipt: ContextTransferReceipt | undefined,\n identity: { sessionId: string; executionId: string },\n): void {\n if (\n receipt !== undefined &&\n (identity.sessionId !== receipt.sessionId || identity.executionId !== receipt.executionId)\n ) {\n throw new Error('retained context transfer identity conflicts with the accepted receipt')\n }\n}\n\nexport function assertRetainedContextTransferCapability(\n capabilities: AgentEnvironmentCapabilities,\n): void {\n if (capabilities.contextTransfer?.attach !== true) {\n throw new Error('provider cannot attach the accepted context transfer destination')\n }\n}\n\n/** The provider get contract performs the authoritative operation lookup once. */\nexport function assertRetainedContextTransferEnvironment(\n environment: AgentEnvironment,\n request: ContextTransferRequest,\n receipt: ContextTransferReceipt,\n): void {\n const actual = ContextTransferReceiptSchema.safeParse(environment.contextTransferReceipt)\n if (\n !actual.success ||\n !contextTransferReceiptMatches(request, actual.data) ||\n environment.id !== receipt.environmentId ||\n environment.provider !== receipt.provider ||\n canonicalCandidateDigest({ ...actual.data, status: 'accepted' }) !==\n canonicalCandidateDigest({ ...receipt, status: 'accepted' })\n ) {\n throw new Error(\n 'provider did not reconstruct the authoritative accepted context transfer receipt',\n )\n }\n}\n","import { createHash } from 'node:crypto'\nimport {\n closeSync,\n constants,\n fstatSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n realpathSync,\n unlinkSync,\n} from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport {\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from '@tangle-network/agent-eval/lock-holder'\nimport type {\n AgentInteractiveSessionControlClaim,\n AgentInteractiveTerminalSession,\n} from '@tangle-network/agent-interface'\nimport {\n AgentInteractiveSessionControlClaimSchema,\n agentInteractiveSessionControlClaimMatchesRef,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { withJsonlFileLock } from '../durable/jsonl-file'\nimport type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport { assertNoSymlinkDescendant, writeAtomicDurableFile } from './supervise/durable-file'\n\nconst MAX_GRANT_BYTES = 4 * 1024 * 1024\nconst scopes = new WeakMap<RetainedInteractiveRunHandle, string>()\nconst offered = new WeakSet<RetainedInteractiveRunHandle>()\nconst participants = new WeakMap<\n RetainedInteractiveRunHandle,\n AgentInteractiveSessionControlClaim\n>()\n\n/** Observation access alone never grants control. Only the explicit offer helper publishes here. */\nexport function bindInteractiveDelegation(\n handle: RetainedInteractiveRunHandle,\n journalRoot: string,\n): void {\n scopes.set(handle, resolve(journalRoot))\n}\n\nfunction privateDirectory(path: string, root: string): void {\n mkdirSync(path, { recursive: true, mode: 0o700 })\n assertNoSymlinkDescendant(root, path, 'interactive control directory')\n const stat = lstatSync(path)\n if (\n !stat.isDirectory() ||\n (stat.mode & 0o777) !== 0o700 ||\n (process.getuid && stat.uid !== process.getuid())\n )\n throw new Error('interactive control directory must be private to the current OS principal')\n}\n\nfunction scopeDirectory(handle: RetainedInteractiveRunHandle): string {\n const journal = scopes.get(handle)\n if (!journal) throw new Error('interactive delegation requires a Runtime journal scope')\n const root = realpathSync(journal)\n const key = createHash('sha256')\n .update(root)\n .update(canonicalCandidateDigest(handle.ref))\n .digest('hex')\n const privateRoot = join(dirname(root), '.agent-runtime-control')\n const dir = join(privateRoot, key)\n privateDirectory(privateRoot, dirname(root))\n privateDirectory(dir, privateRoot)\n return dir\n}\n\n/** Both reader and writer use the same bounded private-file boundary. */\nfunction privateFile<T>(path: string, flags: number, operation: (fd: number) => T): T {\n const fd = openSync(path, flags | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600)\n try {\n const stat = fstatSync(fd)\n if (\n !stat.isFile() ||\n stat.nlink !== 1 ||\n stat.size > MAX_GRANT_BYTES ||\n (stat.mode & 0o077) !== 0 ||\n (process.getuid && stat.uid !== process.getuid())\n )\n throw new Error('interactive control state must be a bounded private regular file')\n return operation(fd)\n } finally {\n closeSync(fd)\n }\n}\n\nasync function withPublicationLock<T>(\n handle: RetainedInteractiveRunHandle,\n operation: (dir: string) => Promise<T>,\n): Promise<T> {\n const dir = scopeDirectory(handle)\n const path = join(dir, 'publication.jsonl')\n privateFile(path, constants.O_RDWR | constants.O_APPEND | constants.O_CREAT, () => undefined)\n return withJsonlFileLock(path, async () => operation(dir))\n}\n\n/** Validate the actual writer before provider CAS; later I/O failures remain explicitly recoverable. */\nexport async function prepareInteractiveDelegation(\n handle: RetainedInteractiveRunHandle,\n): Promise<void> {\n await withPublicationLock(handle, async (dir) => {\n readDelegation(handle, dir)\n })\n}\n\nfunction readDelegation(handle: RetainedInteractiveRunHandle, dir: string) {\n try {\n return privateFile(join(dir, 'delegation.json'), constants.O_RDONLY, (fd) => {\n const value = JSON.parse(readFileSync(fd, 'utf8')) as { control: unknown; owner: unknown }\n const control = AgentInteractiveSessionControlClaimSchema.parse(value.control)\n if (!agentInteractiveSessionControlClaimMatchesRef(handle.ref, control))\n throw new Error('interactive delegation names another process')\n return {\n control,\n owner: parseLockHolderRecord(value.owner),\n identity: lockIdentity(fstatSync(fd, { bigint: true })),\n }\n })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n if (error instanceof SyntaxError) throw new Error('invalid interactive delegation encoding')\n throw error\n }\n}\n\n/** Publish only provider-verified authority. Its generation already uniquely identifies the lease. */\nexport async function offerInteractiveControl(\n handle: RetainedInteractiveRunHandle,\n control: AgentInteractiveSessionControlClaim,\n): Promise<void> {\n try {\n await withPublicationLock(handle, async (dir) => {\n const prior = readDelegation(handle, dir)\n if (prior && prior.control.generation > control.generation) return\n offered.add(handle)\n participants.set(handle, control)\n writeAtomicDurableFile(\n join(dir, 'delegation.json'),\n (file) =>\n JSON.stringify({\n control,\n owner: { ...readLockHolderIdentity(), lock: lockIdentity(file) },\n }),\n { mode: 0o600 },\n )\n })\n } catch {\n throw new Error(\n 'provider control was acquired but local delegation publication failed; correct storage and reacquire with the same holderId before dispatching commands',\n )\n }\n}\n\n/** A leftover lease never delegates after its offering process dies. */\nexport async function acceptedInteractiveControl(\n handle: RetainedInteractiveRunHandle,\n): Promise<AgentInteractiveSessionControlClaim | undefined> {\n return withPublicationLock(handle, async (dir) => {\n const value = readDelegation(handle, dir)\n if (!value || Date.parse(value.control.expiresAt) <= Date.now()) return undefined\n if (lockHolderVerdict(value.owner, value.identity).liveness !== 'alive') return undefined\n participants.set(handle, value.control)\n return value.control\n })\n}\n\n/** Provider generations fence both stale terminal cleanup and local owner cleanup. */\nexport async function revokeInteractiveControl(\n handle: RetainedInteractiveRunHandle,\n control = participants.get(handle),\n): Promise<void> {\n if (!control || !participants.has(handle)) return\n await withPublicationLock(handle, async (dir) => {\n if (readDelegation(handle, dir)?.control.generation === control.generation)\n unlinkSync(join(dir, 'delegation.json'))\n if (participants.get(handle)?.generation === control.generation) {\n offered.delete(handle)\n participants.delete(handle)\n }\n })\n}\n\nexport function delegatedTerminal(\n handle: RetainedInteractiveRunHandle,\n terminal: AgentInteractiveTerminalSession,\n): AgentInteractiveTerminalSession {\n if (!offered.has(handle)) return terminal\n const end = async (action: () => ReturnType<AgentInteractiveTerminalSession['close']>) => {\n const result = await action()\n await revokeInteractiveControl(handle, terminal.control)\n return result\n }\n return {\n get control() {\n return terminal.control\n },\n input: (input, options) => terminal.input(input, options),\n resize: (size, options) => terminal.resize(size, options),\n events: (options) => terminal.events(options),\n get ref() {\n return terminal.ref\n },\n get cursors() {\n return terminal.cursors\n },\n detach: (options) => end(() => terminal.detach(options)),\n close: (options) => end(() => terminal.close(options)),\n }\n}\n\n/** Claim replacement updates only an already explicitly delegated owner scope. */\nexport async function refreshInteractiveDelegation(\n handle: RetainedInteractiveRunHandle,\n control: AgentInteractiveSessionControlClaim,\n): Promise<void> {\n if (offered.has(handle)) await offerInteractiveControl(handle, control)\n}\n","import {\n type AgentExactRunControlRef,\n AgentExactRunControlRefSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type { AgentSession } from '@tangle-network/agent-interface/environment-provider'\nimport {\n exactContinuedControlRef,\n freezeControlRef,\n RetainedRunProviderContractError,\n sameControlCoordinates,\n} from './retained-run-binding'\n\n/**\n * The control reference one retained handle currently believes in, with every reference it\n * has seen. A provider may expose the previous reference while a terminal read catches up;\n * remembering what was seen keeps that read from moving control backwards.\n */\nexport class RetainedRunControl {\n private active: AgentExactRunControlRef\n private readonly known: Set<string>\n\n constructor(\n readonly session: AgentSession,\n initial: AgentExactRunControlRef,\n ) {\n this.active = freezeControlRef(initial)\n this.known = new Set([canonicalCandidateDigest(this.active)])\n }\n\n get current(): AgentExactRunControlRef {\n return this.active\n }\n\n /** Make an already-validated continuation reference the current one. */\n adopt(next: AgentExactRunControlRef): AgentExactRunControlRef {\n this.active = freezeControlRef(next)\n this.known.add(canonicalCandidateDigest(this.active))\n return this.active\n }\n\n assertContinuationIsCurrent(\n continuationSource: AgentExactRunControlRef,\n nextControlRef: AgentExactRunControlRef,\n ): void {\n if (\n !sameControlCoordinates(this.active, continuationSource) &&\n !sameControlCoordinates(this.active, nextControlRef)\n ) {\n throw new Error(\n 'provider advanced the retained session while another native continuation was pending',\n )\n }\n }\n\n /** Read the provider's current reference and advance to it when it is a valid continuation. */\n sync(): void {\n let candidate: unknown\n try {\n candidate = this.session.controlRef\n } catch (error) {\n throw new RetainedRunProviderContractError(\n 'provider retained session control reference read failed',\n { code: 'RETAINED_CONTROL_REF_READ_FAILED', cause: error },\n )\n }\n if (candidate === undefined) return\n const parsed = AgentExactRunControlRefSchema.safeParse(candidate)\n if (!parsed.success) {\n throw new RetainedRunProviderContractError(\n 'provider retained session returned an invalid current control reference',\n { code: 'RETAINED_CONTROL_REF_INVALID', cause: parsed.error },\n )\n }\n const candidateDigest = canonicalCandidateDigest(parsed.data)\n if (sameControlCoordinates(parsed.data, this.active) || this.known.has(candidateDigest)) return\n try {\n this.active = freezeControlRef(exactContinuedControlRef(parsed.data, this.active))\n this.known.add(candidateDigest)\n } catch (error) {\n throw new RetainedRunProviderContractError(\n 'provider retained session advanced to an invalid control reference',\n { code: 'RETAINED_CONTROL_REF_ADVANCE_INVALID', cause: error },\n )\n }\n }\n}\n","import {\n type AgentExactRunControlRef,\n type RuntimeEventEnvelope,\n RuntimeEventEnvelopeSchema,\n type StreamEvent,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentEvent,\n AgentSession,\n} from '@tangle-network/agent-interface/environment-provider'\nimport {\n assertCanonicalEventBinding,\n assertEventBinding,\n assertSequence,\n assertStableText,\n awaitAbortable,\n RetainedRunProviderContractError,\n} from './retained-run-binding'\nimport type { RetainedRunEventOptions } from './retained-run-types'\nimport {\n extractTransportEventIdentity,\n parseCanonicalTransportEvent,\n} from './sandbox-transport-events'\nimport { abortError } from './util'\n\n/** The runtime's own contract checks inside the stream loop, so the catch can tell a broken\n * answer (a verdict) from a read the provider's iterator failed (a wrapper). */\nconst runtimeChecks = new WeakSet<Error>()\nfunction contractCheckFailed(message: string): never {\n const error = new Error(message)\n runtimeChecks.add(error)\n throw error\n}\n/** Run one of the runtime's own checks; whatever it throws is a verdict, not a failed read. */\nfunction verdict<T>(check: () => T): T {\n try {\n return check()\n } catch (error) {\n if (error instanceof Error) runtimeChecks.add(error)\n throw error\n }\n}\n\nexport async function* retainedRunEvents(\n session: AgentSession,\n controlRef: AgentExactRunControlRef,\n options: RetainedRunEventOptions | undefined,\n now: () => number,\n): AsyncGenerator<RuntimeEventEnvelope> {\n const after = options?.after\n if (after) {\n assertStableText(after.cursor, 'replay cursor')\n assertSequence(after.sequence, 'replay sequence')\n }\n let nextSequence = after === undefined ? 1 : after.sequence + 1\n let lastSequence = after?.sequence ?? -1\n const seen = new Set<string>()\n let firstAfterEvent = after !== undefined\n const iterator = session\n .events({\n ...(after === undefined ? {} : { since: after.cursor }),\n ...(controlRef.executionId === undefined ? {} : { executionId: controlRef.executionId }),\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n })\n [Symbol.asyncIterator]()\n try {\n for (;;) {\n const next = await awaitAbortable(\n Promise.resolve().then(() => iterator.next()),\n options?.signal,\n )\n if (next.done) break\n const source = next.value\n const identity = extractTransportEventIdentity(source)\n const sourceCursor = identity.cursor ?? identity.eventId\n verdict(() => assertEventBinding(source, controlRef))\n if (sourceCursor === after?.cursor) continue\n const event = canonicalEvent(source)\n if (!event) continue\n verdict(() => assertCanonicalEventBinding(controlRef, event))\n if (firstAfterEvent && after !== undefined) {\n if (identity.sequence !== undefined && identity.sequence <= after.sequence) {\n contractCheckFailed(\n 'provider replay did not prove that the first event follows the requested cursor',\n )\n }\n firstAfterEvent = false\n }\n const eventId = identity.eventId ?? identity.cursor\n if (!eventId) {\n contractCheckFailed('replayable canonical event has no stable provider event id or cursor')\n }\n assertStableText(eventId, 'provider event id')\n if (seen.has(eventId)) contractCheckFailed(`provider replay repeated event id \"${eventId}\"`)\n seen.add(eventId)\n const sourceSequence = identity.sequence\n const sequence = sourceSequence ?? nextSequence\n if (sequence <= lastSequence) {\n contractCheckFailed(\n `provider event sequence is not monotonic: ${sequence} follows ${lastSequence}`,\n )\n }\n const occurredAt = identity.occurredAt\n const envelope = verdict(() =>\n RuntimeEventEnvelopeSchema.parse({\n runId: controlRef.runId,\n eventId,\n sequence,\n cursor: identity.cursor ?? eventId,\n ...(occurredAt === undefined ? {} : { occurredAt }),\n receivedAt: new Date(now()).toISOString(),\n event,\n }),\n )\n yield envelope\n lastSequence = sequence\n nextSequence = sequence + 1\n }\n } catch (error) {\n if (options?.signal?.aborted) {\n try {\n void Promise.resolve(iterator.return?.()).catch(() => undefined)\n } catch {\n // The caller's abort is the only observable result of an interrupted read.\n }\n throw abortError(options.signal.reason)\n }\n if (error instanceof RetainedRunProviderContractError) throw error\n // Two facts share this catch: the runtime's own checks above threw (the provider's answer\n // broke its contract), or the provider's iterator threw (the READ failed). Name each so a\n // settlement can tell them apart (#1204); the read is a wrapper, the check is a verdict.\n const fromProvider = error instanceof Error && !runtimeChecks.has(error)\n throw new RetainedRunProviderContractError(\n error instanceof Error ? error.message : 'provider retained event stream failed',\n {\n code: fromProvider ? 'RETAINED_EVENT_STREAM_READ_FAILED' : 'RETAINED_EVENT_STREAM_INVALID',\n cause: error,\n },\n )\n } finally {\n if (!options?.signal?.aborted) await iterator.return?.()\n }\n}\n\nfunction canonicalEvent(source: AgentEnvironmentEvent): StreamEvent | undefined {\n return parseCanonicalTransportEvent(\n source.type,\n source.data,\n source.normalized ?? source.data.normalized,\n 'provider',\n )\n}\n","import {\n type AgentExactRunControlRef,\n AgentExactRunControlRefSchema,\n type AgentNativeContextContinuationOptions,\n AgentNativeContextContinuationResultSchema,\n agentNativeContextContinuationResultMatchesRequest,\n NativeContextBoundaryProofSchema,\n type NativeContextContinuationRequest,\n NativeContextContinuationRequestSchema,\n nativeContextContinuationTurnDigest,\n} from '@tangle-network/agent-interface'\nimport type { AgentEnvironmentCapabilities } from '@tangle-network/agent-interface/environment-provider'\nimport {\n assertBoundaryBinding,\n assertResultBinding,\n awaitAbortable,\n copyControlRef,\n exactContinuedControlRef,\n RetainedRunProviderContractError,\n sameControlCoordinates,\n} from './retained-run-binding'\nimport type { RetainedRunControl } from './retained-run-control'\nimport type {\n NativeContextContinuationExecution,\n NativeContextContinuationInput,\n RetainedRunHandle,\n} from './retained-run-types'\n\nconst semanticTurnOf = ({\n timeoutMs: _timeoutMs,\n signal: _signal,\n ...semanticTurn\n}: NativeContextContinuationInput) => semanticTurn\n\nconst unsupportedAdmissionControl = (provider: string): Error =>\n new Error(`provider \"${provider}\" does not advertise early native continuation admission control`)\n\nconst missingContinuationAdmission = (): RetainedRunProviderContractError =>\n new RetainedRunProviderContractError(\n 'provider accepted a native continuation without an admission reference',\n { code: 'RETAINED_NATIVE_CONTINUATION_ADMISSION_MISSING' },\n )\n\n/** Early-admission bookkeeping for one native continuation: exactly one valid admission call. */\nexport class NativeContinuationAdmission {\n settled = false\n failure: unknown\n readonly promise: Promise<AgentExactRunControlRef>\n private called = false\n private admitted: AgentExactRunControlRef | undefined\n private resolve!: (controlRef: AgentExactRunControlRef) => void\n private reject!: (error: unknown) => void\n\n constructor(\n private readonly control: RetainedRunControl,\n private readonly source: AgentExactRunControlRef,\n ) {\n this.promise = new Promise<AgentExactRunControlRef>((resolve, reject) => {\n this.resolve = resolve\n this.reject = reject\n })\n // Callers may only observe the terminal result. Keep an internal observer\n // on admission so a provider failure cannot become an unhandled rejection.\n void this.promise.catch(() => undefined)\n }\n\n admittedControlRef(): AgentExactRunControlRef | undefined {\n return this.admitted === undefined ? undefined : copyControlRef(this.admitted)\n }\n\n fail(error: unknown): void {\n this.failure ??= error\n if (this.settled) return\n this.settled = true\n this.reject(error)\n }\n\n readonly onAdmission = (candidate: AgentExactRunControlRef): void => {\n if (this.called) {\n const error = new RetainedRunProviderContractError(\n 'provider called native continuation admission more than once',\n { code: 'RETAINED_NATIVE_CONTINUATION_ADMISSION_DUPLICATE' },\n )\n this.fail(error)\n throw error\n }\n this.called = true\n try {\n const parsed = AgentExactRunControlRefSchema.parse(candidate)\n const nextControlRef = exactContinuedControlRef(parsed, this.source)\n this.control.assertContinuationIsCurrent(this.source, nextControlRef)\n this.admitted = this.control.adopt(nextControlRef)\n if (!this.settled) {\n this.settled = true\n this.resolve(copyControlRef(this.admitted))\n }\n } catch (error) {\n const contractError =\n error instanceof RetainedRunProviderContractError\n ? error\n : new RetainedRunProviderContractError(\n error instanceof Error\n ? error.message\n : 'provider returned an invalid native continuation admission reference',\n { code: 'RETAINED_NATIVE_CONTINUATION_ADMISSION_INVALID', cause: error },\n )\n this.fail(contractError)\n throw contractError\n }\n }\n}\n\nfunction assertNativeSupport(\n control: RetainedRunControl,\n capabilities: AgentEnvironmentCapabilities,\n early: boolean,\n): void {\n const native = capabilities.nativeContinuation\n const provider = control.current.provider\n if (\n native?.atomicBoundary !== true ||\n native.requestIdempotency !== true ||\n !control.session.continueNative\n ) {\n throw new Error(`provider \"${provider}\" does not support retry-safe native continuation`)\n }\n if (early && native.admissionControl !== true) throw unsupportedAdmissionControl(provider)\n}\n\nasync function callProviderContinuation(\n control: RetainedRunControl,\n exactRequest: NativeContextContinuationRequest,\n turn: NativeContextContinuationInput,\n admission: NativeContinuationAdmission | undefined,\n): Promise<NativeContextContinuationExecution> {\n const { timeoutMs, signal } = turn\n const semanticTurn = semanticTurnOf(turn)\n try {\n return AgentNativeContextContinuationResultSchema.parse(\n await awaitAbortable(\n Promise.resolve().then(() => {\n const providerOptions: AgentNativeContextContinuationOptions = {\n turn: semanticTurn,\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n ...(signal === undefined ? {} : { signal }),\n ...(admission === undefined ? {} : { onAdmission: admission.onAdmission }),\n }\n return control.session.continueNative!(exactRequest, providerOptions)\n }),\n signal,\n ),\n )\n } catch (error) {\n try {\n control.sync()\n } catch (syncError) {\n throw new AggregateError(\n [error, syncError],\n 'native continuation failed and its current control reference could not be read',\n )\n }\n throw error\n }\n}\n\n/** Bind an accepted outcome to the admitted run, then make its reference current. */\nfunction bindAcceptedOutcome(\n control: RetainedRunControl,\n exactRequest: NativeContextContinuationRequest,\n outcome: NativeContextContinuationExecution,\n admission: NativeContinuationAdmission | undefined,\n continuationSource: AgentExactRunControlRef,\n): NativeContextContinuationExecution {\n if (\n admission !== undefined &&\n !admission.settled &&\n outcome.acknowledgement.status === 'accepted'\n ) {\n throw missingContinuationAdmission()\n }\n if (!('result' in outcome) || !('controlRef' in outcome)) {\n throw new Error('provider omitted the successful native continuation result')\n }\n if (!agentNativeContextContinuationResultMatchesRequest(exactRequest, outcome)) {\n throw new Error('provider returned a native continuation result for another request')\n }\n const nextControlRef = exactContinuedControlRef(outcome.controlRef, continuationSource)\n assertResultBinding(nextControlRef, outcome.result)\n control.assertContinuationIsCurrent(continuationSource, nextControlRef)\n if (admission !== undefined && !admission.settled) {\n if (outcome.acknowledgement.status !== 'replayed') throw missingContinuationAdmission()\n // A replay may already have been admitted before this process started and\n // can therefore return only its durable terminal record.\n admission.onAdmission(nextControlRef)\n }\n const admittedControlRef = admission?.admittedControlRef()\n if (admission !== undefined && admittedControlRef === undefined) {\n throw missingContinuationAdmission()\n }\n if (\n admittedControlRef !== undefined &&\n !sameControlCoordinates(nextControlRef, admittedControlRef)\n ) {\n throw new RetainedRunProviderContractError(\n 'provider changed the native continuation run after admission',\n { code: 'RETAINED_NATIVE_CONTINUATION_RESULT_CHANGED' },\n )\n }\n return structuredClone({ ...outcome, controlRef: copyControlRef(control.adopt(nextControlRef)) })\n}\n\nexport async function executeNativeContinuation(\n control: RetainedRunControl,\n capabilities: AgentEnvironmentCapabilities,\n request: NativeContextContinuationRequest,\n turn: NativeContextContinuationInput,\n admission?: NativeContinuationAdmission,\n expectedSource?: AgentExactRunControlRef,\n): Promise<NativeContextContinuationExecution> {\n control.sync()\n const exactRequest = NativeContextContinuationRequestSchema.parse(request)\n const continuationSource = expectedSource ?? control.current\n if (!sameControlCoordinates(control.current, continuationSource)) {\n throw new Error('native continuation retained-run control changed before admission')\n }\n if (!sameControlCoordinates(exactRequest.run, continuationSource)) {\n throw new Error('native continuation request targets another retained run')\n }\n if (nativeContextContinuationTurnDigest(semanticTurnOf(turn)) !== exactRequest.turnDigest) {\n throw new Error('native continuation request targets another user turn')\n }\n assertNativeSupport(control, capabilities, admission !== undefined)\n const outcome = await callProviderContinuation(control, exactRequest, turn, admission)\n const admissionFailure = admission?.failure\n if (admissionFailure !== undefined) throw admissionFailure\n control.sync()\n if (\n outcome.acknowledgement.operationId !== exactRequest.operationId ||\n outcome.acknowledgement.requestDigest !== exactRequest.requestDigest\n ) {\n throw new Error('provider returned a native continuation result for another request')\n }\n if (outcome.acknowledgement.actualBoundary !== undefined) {\n assertBoundaryBinding(\n exactRequest.run,\n NativeContextBoundaryProofSchema.parse(outcome.acknowledgement.actualBoundary),\n )\n }\n if (\n outcome.acknowledgement.status !== 'accepted' &&\n outcome.acknowledgement.status !== 'replayed'\n ) {\n return structuredClone(outcome)\n }\n return bindAcceptedOutcome(control, exactRequest, outcome, admission, continuationSource)\n}\n\n/** Start a continuation whose admission reference is observable before its result. */\nexport function beginNativeContinuation(\n control: RetainedRunControl,\n capabilities: AgentEnvironmentCapabilities,\n request: NativeContextContinuationRequest,\n turn: NativeContextContinuationInput,\n): ReturnType<RetainedRunHandle['beginNativeContinuation']> {\n control.sync()\n if (capabilities.nativeContinuation?.admissionControl !== true) {\n throw unsupportedAdmissionControl(control.current.provider)\n }\n const continuationSource = control.current\n const admission = new NativeContinuationAdmission(control, continuationSource)\n const result = executeNativeContinuation(\n control,\n capabilities,\n request,\n turn,\n admission,\n continuationSource,\n )\n void result.then(\n (outcome) => {\n if (admission.settled) return\n const accepted =\n outcome.acknowledgement.status === 'accepted' ||\n outcome.acknowledgement.status === 'replayed'\n admission.fail(\n new RetainedRunProviderContractError(\n accepted\n ? 'provider accepted a native continuation without an admission reference'\n : 'native continuation ended without durable admission',\n {\n code: accepted\n ? 'RETAINED_NATIVE_CONTINUATION_ADMISSION_MISSING'\n : 'RETAINED_NATIVE_CONTINUATION_NOT_ADMITTED',\n },\n ),\n )\n },\n (error) => {\n admission.fail(error)\n },\n )\n return { admission: admission.promise, result }\n}\n","import {\n type AgentExactRunControlRef,\n AgentTurnResultSchema,\n canonicalCandidateDigest,\n type InteractionAcknowledgement,\n InteractionAcknowledgementSchema,\n InteractionResponseCommandSchema,\n type NativeContextBoundaryProof,\n NativeContextBoundaryProofSchema,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentSession,\n AgentSessionStatus,\n} from '@tangle-network/agent-interface/environment-provider'\nimport {\n assertBoundaryBinding,\n assertInteractionBinding,\n assertResultBinding,\n assertStableText,\n assertWaitDuration,\n awaitAbortable,\n cancellationRequest,\n copyControlRef,\n delay,\n exactSessionCancel,\n exactSessionResult,\n hasDurableCancel,\n isTerminalSessionStatus,\n RetainedRunProviderContractError,\n} from './retained-run-binding'\nimport { RetainedRunControl } from './retained-run-control'\nimport { retainedRunEvents } from './retained-run-events'\nimport {\n beginNativeContinuation,\n executeNativeContinuation,\n} from './retained-run-native-continuation'\nimport type {\n RetainedRunCancellation,\n RetainedRunEffect,\n RetainedRunHandle,\n RetainedRunSnapshot,\n} from './retained-run-types'\nimport { abortError } from './util'\n\nasync function snapshot(\n control: RetainedRunControl,\n clock: () => number,\n reason?: string,\n signal?: AbortSignal,\n): Promise<RetainedRunSnapshot> {\n if (signal?.aborted) throw abortError(signal.reason)\n control.sync()\n let status: AgentSessionStatus | null\n try {\n status = await awaitAbortable(\n Promise.resolve().then(() => control.session.status({ signal })),\n signal,\n )\n } catch {\n if (signal?.aborted) throw abortError(signal.reason)\n status = 'unknown'\n }\n control.sync()\n const effect: RetainedRunEffect =\n status === 'cancelled'\n ? 'cancelled'\n : status === 'completed' || status === 'failed' || status === 'expired'\n ? 'not_live'\n : 'unknown'\n return {\n runId: control.current.runId,\n controlRef: copyControlRef(control.current),\n status,\n effect,\n observedAt: new Date(clock()).toISOString(),\n ...(reason === undefined ? {} : { reason }),\n ...(signal?.aborted ? { signal: String(signal.reason ?? 'aborted') } : {}),\n }\n}\n\nasync function retainedStatus(\n control: RetainedRunControl,\n clock: () => number,\n options: Parameters<RetainedRunHandle['status']>[0],\n): Promise<RetainedRunSnapshot> {\n const waitMs = options?.waitMs ?? 0\n assertWaitDuration(waitMs, 'retained status wait')\n const initial = await snapshot(control, clock, undefined, options?.signal)\n if (waitMs === 0 || isTerminalSessionStatus(initial.status)) return initial\n const deadline = Date.now() + waitMs\n let current = initial\n while (Date.now() < deadline) {\n await delay(Math.min(25, Math.max(1, deadline - Date.now())), options?.signal)\n current = await snapshot(control, clock, undefined, options?.signal)\n if (current.status !== initial.status || isTerminalSessionStatus(current.status)) {\n return current\n }\n }\n return current\n}\n\nasync function retainedResult(control: RetainedRunControl) {\n control.sync()\n let candidate: unknown\n try {\n candidate = await exactSessionResult(control.session)\n } catch (error) {\n if (error instanceof RetainedRunProviderContractError) throw error\n throw new RetainedRunProviderContractError(\n error instanceof Error ? error.message : 'provider retained result read failed',\n { code: 'RETAINED_RESULT_READ_FAILED', cause: error },\n )\n }\n const parsed = AgentTurnResultSchema.safeParse(candidate)\n if (!parsed.success) {\n throw new RetainedRunProviderContractError('provider returned an invalid retained result', {\n code: 'RETAINED_RESULT_SCHEMA_INVALID',\n cause: parsed.error,\n })\n }\n control.sync()\n try {\n assertResultBinding(control.current, parsed.data)\n } catch (error) {\n throw new RetainedRunProviderContractError(\n error instanceof Error ? error.message : 'provider returned an unbound retained result',\n { code: 'RETAINED_RESULT_BINDING_INVALID', cause: error },\n )\n }\n return structuredClone(parsed.data)\n}\n\nasync function respondToRetainedInteraction(\n environment: AgentEnvironment,\n control: RetainedRunControl,\n capabilities: AgentEnvironmentCapabilities,\n command: Parameters<RetainedRunHandle['respondToInteraction']>[0],\n options: Parameters<RetainedRunHandle['respondToInteraction']>[1],\n): Promise<InteractionAcknowledgement> {\n const { session } = control\n control.sync()\n const exactCommand = InteractionResponseCommandSchema.parse(command)\n assertInteractionBinding(control.current, exactCommand)\n if (\n capabilities.interactions?.replay !== true ||\n capabilities.interactions.responseIdempotency !== true\n ) {\n throw new Error(\n `provider \"${control.current.provider}\" does not promise retry-safe interaction responses`,\n )\n }\n const respond = session.respondToInteraction ?? environment.respondToInteraction\n if (!respond) {\n throw new Error(`provider \"${control.current.provider}\" does not support interaction responses`)\n }\n const acknowledgement = InteractionAcknowledgementSchema.parse(\n await awaitAbortable(\n Promise.resolve().then(() =>\n respond.call(session.respondToInteraction ? session : environment, exactCommand, options),\n ),\n options?.signal,\n ),\n )\n control.sync()\n if (\n acknowledgement.operationId !== exactCommand.operationId ||\n acknowledgement.commandDigest !== exactCommand.commandDigest ||\n canonicalCandidateDigest(acknowledgement.binding) !==\n canonicalCandidateDigest(exactCommand.binding)\n ) {\n throw new Error('provider returned an interaction acknowledgement for another command')\n }\n return structuredClone(acknowledgement)\n}\n\nasync function retainedContextBoundary(\n control: RetainedRunControl,\n options: Parameters<RetainedRunHandle['contextBoundary']>[0],\n): Promise<NativeContextBoundaryProof | null> {\n const { session } = control\n control.sync()\n if (!session.contextBoundary) return null\n const proof = await awaitAbortable(\n Promise.resolve().then(() => session.contextBoundary!(options)),\n options?.signal,\n )\n control.sync()\n if (proof === null) return null\n const exactProof = NativeContextBoundaryProofSchema.parse(proof)\n assertBoundaryBinding(control.current, exactProof)\n return structuredClone(exactProof)\n}\n\nasync function cancelRetainedRun(\n control: RetainedRunControl,\n clock: () => number,\n options: Parameters<RetainedRunHandle['cancel']>[0],\n): Promise<RetainedRunCancellation> {\n control.sync()\n assertStableText(options.operationId, 'retained cancellation operation id')\n if (options.reason !== undefined) assertStableText(options.reason, 'retained cancellation reason')\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n if (!hasDurableCancel(control.session)) {\n throw new Error(\n `provider \"${control.current.provider}\" does not expose durable cancellation operations`,\n )\n }\n const request = cancellationRequest(control.current, options.operationId, options.reason)\n let effect: RetainedRunEffect = 'unknown'\n let providerStatus: RetainedRunCancellation['status'] | undefined\n try {\n const acknowledgement = await exactSessionCancel(control.session, request, {\n signal: options.signal,\n })\n effect = acknowledgement.effect\n providerStatus = acknowledgement.status\n } catch (error) {\n if (error instanceof RetainedRunProviderContractError) throw error\n if (error instanceof Error && error.name === 'AbortError') throw error\n effect = 'unknown'\n }\n const current = await snapshot(control, clock, options.reason, options.signal)\n const observedEffect =\n effect === 'unknown' && providerStatus === undefined && current.status === 'cancelled'\n ? 'cancelled'\n : effect\n return structuredClone({\n operationId: options.operationId,\n requestDigest: request.requestDigest,\n status: providerStatus ?? (observedEffect === 'unknown' ? 'unknown' : ('accepted' as const)),\n effect: observedEffect,\n snapshot: { ...current, effect: observedEffect },\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.signal?.aborted ? { signal: String(options.signal.reason ?? 'aborted') } : {}),\n })\n}\n\nexport function createRetainedRunHandle(\n environment: AgentEnvironment,\n session: AgentSession,\n initialControlRef: AgentExactRunControlRef,\n capabilities: AgentEnvironmentCapabilities,\n now: (() => number) | undefined,\n): RetainedRunHandle {\n const clock = now ?? Date.now\n const measuredCapabilities = structuredClone(capabilities)\n const control = new RetainedRunControl(session, initialControlRef)\n return {\n get controlRef() {\n control.sync()\n return copyControlRef(control.current)\n },\n get capabilities() {\n return structuredClone(measuredCapabilities)\n },\n status: (options) => retainedStatus(control, clock, options),\n events: (options) => {\n control.sync()\n return retainedRunEvents(session, copyControlRef(control.current), options, clock)\n },\n result: () => retainedResult(control),\n respondToInteraction: (command, options) =>\n respondToRetainedInteraction(environment, control, measuredCapabilities, command, options),\n contextBoundary: (options) => retainedContextBoundary(control, options),\n beginNativeContinuation: (request, turn) =>\n beginNativeContinuation(control, measuredCapabilities, request, turn),\n continueNative: (request, turn) =>\n executeNativeContinuation(control, measuredCapabilities, request, turn),\n cancel: (options) => cancelRetainedRun(control, clock, options),\n }\n}\n","import type { ContextTransferRequest } from '@tangle-network/agent-interface'\nimport {\n agentWorkspaceSnapshotRefDigest,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentTurnInput,\n CreateAgentEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { recordValue } from '../record-value'\nimport { promptOptionsFromAgentTurnInput } from './turn-input'\n\nfunction definedMaterial(fields: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined))\n}\n\nfunction recordNames(value: object | undefined): string[] | undefined {\n return value === undefined ? undefined : Object.keys(value).sort()\n}\n\n/** Replay-only projection of the create identity persisted before Interface 5. */\nexport function legacyRetainedCreateMaterial(\n environment: CreateAgentEnvironmentInput,\n): Record<string, unknown> {\n const { snapshot: _snapshot, ...workspace } = environment.workspace ?? {}\n return retainedCreateMaterial({\n ...environment,\n requestedId: undefined,\n egress: undefined,\n billingOwner: undefined,\n workspace: environment.workspace === undefined ? undefined : workspace,\n })\n}\n\nexport function retainedCreateMaterial(\n environment: CreateAgentEnvironmentInput,\n): Record<string, unknown> {\n const { workspace, resources } = environment\n return definedMaterial({\n placement: environment.metadata?.runtimeProviderPlacement,\n backend: environment.backend,\n requestedId: environment.requestedId,\n egress: environment.egress,\n billingOwner: environment.billingOwner,\n workspaceDigest: publicMaterialDigest(\n workspace,\n ['environment', 'image', 'repoUrl', 'gitRef', 'cwd', 'checkpoint'],\n workspace?.snapshot,\n ),\n resourcesDigest: publicMaterialDigest(resources, ['cpu', 'memoryMb', 'diskMb', 'gpu']),\n runtimeAttachmentsDigest:\n environment.runtimeAttachments === undefined\n ? undefined\n : canonicalCandidateDigest(environment.runtimeAttachments),\n name: environment.name,\n environmentVariableNames: recordNames(environment.env),\n secretNames:\n environment.secrets === undefined ? undefined : retainedSecretNames(environment.secrets),\n proxySecrets: environment.proxySecrets,\n metadataKeys: recordNames(environment.metadata),\n providerOptionNames: recordNames(environment.providerOptions),\n })\n}\n\n/** Add the retained ownership marker without attaching turn identity. */\nexport function retainedEnvironmentMetadata(\n metadata: Record<string, unknown> | undefined,\n idempotencyKey: string,\n): Record<string, unknown> {\n return {\n ...metadata,\n retainedIdempotencyKey: idempotencyKey,\n }\n}\n\nfunction publicMaterialDigest(\n value: { providerOptions?: Record<string, unknown> } | undefined,\n fields: readonly string[],\n snapshot?: NonNullable<CreateAgentEnvironmentInput['workspace']>['snapshot'],\n): string | undefined {\n if (value === undefined) return undefined\n const material = recordValue(value) ?? {}\n const selected = definedMaterial({\n ...Object.fromEntries(fields.map((field) => [field, material[field]])),\n snapshotDigest: snapshot === undefined ? undefined : agentWorkspaceSnapshotRefDigest(snapshot),\n providerOptionNames: recordNames(value.providerOptions),\n })\n return canonicalCandidateDigest(selected)\n}\n\nfunction retainedSecretNames(\n secrets: NonNullable<CreateAgentEnvironmentInput['secrets']>,\n): NonNullable<CreateAgentEnvironmentInput['secrets']> {\n if (!Array.isArray(secrets)) return secrets === 'all' ? secrets : Object.keys(secrets).sort()\n if (secrets.every((entry) => typeof entry === 'string')) return [...secrets].sort()\n return [...secrets].sort((a, b) =>\n canonicalCandidateDigest(a).localeCompare(canonicalCandidateDigest(b)),\n )\n}\n\n/** Project one headless turn into the material that `freshTurnInput` forwards. */\nexport function retainedTurnMaterial(\n input: AgentTurnInput,\n contextTransfer: ContextTransferRequest | undefined,\n fields: Pick<AgentTurnInput, 'providerOptions'> = {},\n): Record<string, unknown> {\n const backend = recordValue(input.providerOptions?.backend)\n if (backend && Object.hasOwn(backend, 'runtimeSecretNames'))\n throw new Error('retained backend runtimeSecretNames is runtime-owned')\n const secrets = recordValue(backend?.runtimeSecrets)\n if (\n backend?.runtimeSecrets !== undefined &&\n (!secrets || Object.values(secrets).some((value) => typeof value !== 'string'))\n ) {\n throw new Error('retained private replay material is not string-valued')\n }\n const { runtimeSecrets: _values, ...publicBackend } = backend ?? {}\n return definedMaterial({\n prompt: input.prompt,\n parts: input.parts,\n model: input.model,\n profileDigest:\n input.profile === undefined ? undefined : canonicalAgentProfileDigest(input.profile),\n timeoutMs: input.timeoutMs,\n context: input.context,\n interactions: input.interactions,\n providerOptions: secrets\n ? {\n ...input.providerOptions,\n backend: {\n ...publicBackend,\n // Private values bind only names; every public backend field stays bound.\n runtimeSecretNames: Object.keys(secrets).sort(),\n },\n }\n : input.providerOptions,\n contextTransferRequestDigest: contextTransfer?.requestDigest,\n ...fields,\n })\n}\n\nexport function retainedTurnForDispatch(turn: AgentTurnInput, env: CreateAgentEnvironmentInput) {\n if (recordValue(turn.providerOptions?.backend)?.runtimeSecrets === undefined) return turn\n const publicBackend = promptOptionsFromAgentTurnInput(turn).backend\n const profile = publicBackend?.profile === undefined ? env.profile : publicBackend.profile\n if (typeof profile === 'string' || !profile) return turn\n const backend: Record<string, unknown> = { ...publicBackend, profile }\n if (backend.type === undefined)\n backend.type = profile.harness === undefined ? env.backend : profile.harness\n return { ...turn, providerOptions: { ...turn.providerOptions, backend } }\n}\n","import { join } from 'node:path'\nimport type { ContextTransferRequest, Sha256Digest } from '@tangle-network/agent-interface'\nimport {\n AgentEnvironmentCapabilitiesSchema,\n AgentExactRunControlRefSchema,\n AgentTurnInputSchema,\n ContextTransferRequestSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n AgentSession,\n AgentSessionRef,\n AgentTurnInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { withJsonlFileLock } from '../durable/jsonl-file'\nimport { FileObserverJournal } from '../durable/observer-journal'\nimport {\n RetainedInteractiveAdmissionError,\n RetainedRunAdmissionError,\n RetainedRunDispatchBindingError,\n} from '../errors'\nimport type { RuntimeHookPhase, RuntimeHookTarget } from '../runtime-hooks'\nimport { assertRequestedInteractionCapabilities } from './interaction-capabilities'\nimport {\n assertRetainedContextTransferCapability,\n assertRetainedContextTransferEnvironment,\n assertRetainedContextTransferIdentity,\n retainedContextTransferReceipt,\n} from './retained-context-transfer'\nimport {\n bindInteractiveDelegation,\n delegatedTerminal,\n refreshInteractiveDelegation,\n revokeInteractiveControl,\n} from './retained-interactive-delegation'\nimport type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport {\n assertStableText,\n exactControlRef,\n exactSession,\n freezeControlRef,\n} from './retained-run-binding'\nimport { createRetainedRunHandle } from './retained-run-handle'\nimport {\n retainedCreateMaterial,\n retainedEnvironmentMetadata,\n retainedTurnForDispatch,\n retainedTurnMaterial,\n} from './retained-run-intent'\nimport type {\n ReconnectRetainedRunOptions,\n RecoverRetainedRunIntentOptions,\n RecoverRetainedRunOptions,\n RecoverRetainedRunResult,\n RetainedInteractiveAdmission,\n RetainedRunAdmission,\n RetainedRunAdmissionHook,\n RetainedRunHandle,\n RetainedRunIntentAdmission,\n RetainedRunStartMaterial,\n StartRetainedRunInEnvironmentOptions,\n StartRetainedRunOptions,\n} from './retained-run-types'\nimport { detachedSnapshot } from './supervise/snapshot'\nimport { freshTurnInput } from './turn-input'\n\n/**\n * Mint deterministic dispatch coordinates from the two caller-supplied keys.\n * The same `(idempotencyKey, turnId)` pair yields the same coordinates in\n * every process, so a pre-dispatch admission record always names the exact\n * session and execution the dispatch will request. A full SHA-256 digest\n * keeps provider session identifiers bounded and safe for workspace paths.\n */\nexport function mintRetainedIdentity(\n idempotencyKey: string,\n turnId: string,\n): { sessionId: string; executionId: string } {\n const base = `${encodeURIComponent(idempotencyKey)}:${encodeURIComponent(turnId)}`\n const digest = canonicalCandidateDigest({ kind: 'retained-identity.v1', base }).slice(\n 'sha256:'.length,\n )\n return {\n sessionId: `retained-session-${digest}`,\n executionId: `retained-execution-${digest}`,\n }\n}\n\n/**\n * Dispatch one detached, replayable run and return only after exact durable\n * coordinates are confirmed by the provider and persisted by the caller.\n *\n * The required `onAdmission` hook first records a digest-only intent before\n * creation or receipt-authorized attachment, then records recovery coordinates and the verified exact control\n * reference. The returned promise resolves only after the dispatched admission\n * is durable, so a crash cannot lose a successful start's exact reference.\n *\n * @stable\n */\nexport async function startRetainedRun(\n options: StartRetainedRunOptions,\n): Promise<RetainedRunHandle> {\n assertStableText(options.environment.idempotencyKey, 'environment idempotency key')\n assertStableText(options.turn.turnId, 'turn idempotency key')\n if (typeof options.onAdmission !== 'function') {\n throw new Error('startRetainedRun requires an awaited onAdmission durability hook')\n }\n const onAdmission = journaledAdmissions(\n options.journalRoot,\n options.intent?.runId,\n options.onAdmission,\n )\n const contextTransfer = retainedContextTransfer(options.turn.contextTransfer)\n const transferReceipt = retainedContextTransferReceipt(\n options,\n options.provider.name,\n contextTransfer,\n )\n const { sessionId, executionId } =\n options.identity ??\n // Admission coordinates remain authoritative across generator changes.\n options.intent ??\n (transferReceipt === undefined\n ? undefined\n : { sessionId: transferReceipt.sessionId, executionId: transferReceipt.executionId }) ??\n mintRetainedIdentity(options.environment.idempotencyKey, options.turn.turnId)\n const identity = { sessionId, executionId }\n assertStableText(identity.sessionId, 'retained session id')\n assertStableText(identity.executionId, 'retained execution id')\n assertRetainedContextTransferIdentity(transferReceipt, identity)\n AgentTurnInputSchema.parse(\n freshTurnInput(options.turn, {\n turnId: options.turn.turnId,\n detach: true,\n ...identity,\n contextTransfer,\n }),\n )\n if (!options.provider.get) {\n throw new Error(`provider \"${options.provider.name}\" cannot reconstruct an environment by id`)\n }\n const intent = retainedRunIntent(options, identity, contextTransfer)\n if (options.intent === undefined) {\n await admitDurably(onAdmission, intent)\n } else {\n assertExactRetainedRunIntent(options.intent, intent, () =>\n retainedRunIntent(options, identity, contextTransfer, {\n providerOptions: options.turn.providerOptions,\n }),\n )\n }\n const providerCapabilities = await assertRetainedCapabilities(options.provider)\n if (transferReceipt !== undefined) assertRetainedContextTransferCapability(providerCapabilities)\n assertRequestedInteractionCapabilities(\n options.provider.name,\n options.turn.interactions,\n providerCapabilities,\n )\n options.environment.signal?.throwIfAborted()\n options.turn.signal?.throwIfAborted()\n const attachmentSignal =\n options.environment.signal === undefined\n ? options.turn.signal\n : options.turn.signal === undefined\n ? options.environment.signal\n : AbortSignal.any([options.environment.signal, options.turn.signal])\n let environment: AgentEnvironment\n if (transferReceipt !== undefined && contextTransfer !== undefined) {\n const existing = await options.provider.get(transferReceipt.environmentId, {\n contextTransfer,\n ...(attachmentSignal === undefined ? {} : { signal: attachmentSignal }),\n })\n attachmentSignal?.throwIfAborted()\n if (!existing)\n throw new Error('accepted context transfer environment is unavailable; it cannot be replaced')\n assertRetainedContextTransferEnvironment(existing, contextTransfer, transferReceipt)\n environment = existing\n } else if (options.existingEnvironmentId !== undefined) {\n assertStableText(options.existingEnvironmentId, 'retained environment id')\n const existing = await options.provider.get(options.existingEnvironmentId)\n if (\n !existing ||\n existing.id !== options.existingEnvironmentId ||\n existing.provider !== options.provider.name\n ) {\n throw new Error('retained provider environment is unavailable or has another identity')\n }\n await assertRetainedEnvironmentOwnership(\n options.provider,\n existing,\n options.environment.idempotencyKey,\n )\n environment = existing\n } else {\n environment = await options.provider.create({\n ...options.environment,\n metadata: retainedEnvironmentMetadata(\n options.environment.metadata,\n options.environment.idempotencyKey,\n ),\n })\n }\n let capabilities: AgentEnvironmentCapabilities\n let teardownFailure =\n 'retained run environment published invalid capabilities and could not be destroyed'\n try {\n capabilities = retainedCapabilitiesForEnvironment(\n options.provider.name,\n providerCapabilities,\n environment,\n )\n if (transferReceipt !== undefined) assertRetainedContextTransferCapability(capabilities)\n assertRequestedInteractionCapabilities(\n options.provider.name,\n options.turn.interactions,\n capabilities,\n )\n if (!environment.dispatch || !environment.session) {\n teardownFailure =\n 'retained run could not start and its unused environment could not be destroyed'\n throw new Error(\n `provider \"${options.provider.name}\" does not expose detached session control`,\n )\n }\n } catch (error) {\n if (transferReceipt !== undefined || options.existingEnvironmentId !== undefined) throw error\n try {\n await environment.destroy?.()\n } catch (cleanupError) {\n throw new AggregateError([error, cleanupError], teardownFailure)\n }\n throw error\n }\n\n return dispatchRetainedRun({\n provider: options.provider,\n environment,\n signal: attachmentSignal,\n environmentIdempotencyKey: options.environment.idempotencyKey,\n create: options.environment,\n turn: options.turn,\n contextTransfer,\n expectedRunId: transferReceipt?.runId,\n identity,\n onAdmission,\n capabilities,\n now: options.now,\n preserveEnvironment:\n options.preserveEnvironment === true ||\n transferReceipt !== undefined ||\n options.existingEnvironmentId !== undefined,\n })\n}\n\n/**\n * Dispatch a fresh retained session inside an existing provider environment.\n *\n * This operation reuses only the environment. It does not append to a prior\n * harness chat and does not claim native conversation continuity. The caller\n * must use `RetainedRunHandle.continueNative` for a verified same-chat turn.\n *\n * @stable\n */\nexport async function startRetainedRunInEnvironment(\n options: StartRetainedRunInEnvironmentOptions,\n): Promise<RetainedRunHandle> {\n if (options.turn.contextTransfer !== undefined) {\n throw new Error(\n 'accepted context transfer requires startRetainedRun with its exact profile and receipt',\n )\n }\n assertStableText(options.environment.id, 'retained environment id')\n assertStableText(options.environment.idempotencyKey, 'environment idempotency key')\n assertStableText(options.turn.turnId, 'turn idempotency key')\n if (options.identity !== undefined) {\n assertStableText(options.identity.sessionId, 'retained session id')\n assertStableText(options.identity.executionId, 'retained execution id')\n }\n if (typeof options.onAdmission !== 'function') {\n throw new Error('startRetainedRunInEnvironment requires an awaited onAdmission durability hook')\n }\n const identity =\n options.identity ??\n mintRetainedIdentity(options.environment.idempotencyKey, options.turn.turnId)\n const contextTransfer = retainedContextTransfer(options.turn.contextTransfer)\n AgentTurnInputSchema.parse(\n freshTurnInput(options.turn, {\n turnId: options.turn.turnId,\n detach: true,\n ...identity,\n contextTransfer,\n }),\n )\n const providerCapabilities = await assertRetainedCapabilities(options.provider)\n if (!options.provider.get) {\n throw new Error(`provider \"${options.provider.name}\" cannot reconstruct an environment by id`)\n }\n const environment = await options.provider.get(options.environment.id)\n if (!environment) {\n throw new Error(\n `provider \"${options.provider.name}\" no longer holds environment \"${options.environment.id}\"`,\n )\n }\n if (environment.id !== options.environment.id || environment.provider !== options.provider.name) {\n throw new Error('provider reconstructed a different retained environment')\n }\n const capabilities = retainedCapabilitiesForEnvironment(\n options.provider.name,\n providerCapabilities,\n environment,\n )\n assertRequestedInteractionCapabilities(\n options.provider.name,\n options.turn.interactions,\n capabilities,\n )\n if (!environment.dispatch || !environment.session) {\n throw new Error(`provider \"${options.provider.name}\" does not expose detached session control`)\n }\n await assertRetainedEnvironmentOwnership(\n options.provider,\n environment,\n options.environment.idempotencyKey,\n )\n\n return dispatchRetainedRun({\n provider: options.provider,\n environment,\n environmentIdempotencyKey: options.environment.idempotencyKey,\n turn: options.turn,\n contextTransfer,\n identity,\n onAdmission: options.onAdmission,\n capabilities,\n now: options.now,\n preserveEnvironment: true,\n })\n}\n\n/**\n * Bind an existing environment to the retained key it was created under, from the metadata the\n * provider's own `get` or `create` record carries. One read, no listing.\n *\n * A metadata-filtered `list` used to stand in when that record had none. The only provider with\n * detached session control and a `list` (Tangle Sandbox) filters client-side, so the fallback\n * walked the caller's whole inventory: on Braid's ~68.5k-sandbox account, ~55 pages at ~1.4 s\n * each before admission (2026-10-28), and past 2,000 sandboxes the route answered 400\n * (2026-10-04). A record without metadata cannot prove ownership, so it is refused at once.\n */\nasync function assertRetainedEnvironmentOwnership(\n provider: AgentEnvironmentProvider,\n environment: AgentEnvironment,\n idempotencyKey: string,\n): Promise<void> {\n if (environment.metadata === undefined) {\n throw new Error(\n `provider \"${provider.name}\" returned environment \"${environment.id}\" without metadata, so it cannot prove retained environment ownership`,\n )\n }\n if (environment.metadata.retainedIdempotencyKey !== idempotencyKey) {\n throw new Error(\n `provider \"${provider.name}\" could not bind environment \"${environment.id}\" to its retained idempotency key`,\n )\n }\n}\n\ninterface DispatchRetainedRunOptions {\n readonly expectedRunId?: string\n readonly preserveEnvironment?: boolean\n readonly signal?: AbortSignal\n readonly provider: AgentEnvironmentProvider\n readonly environment: AgentEnvironment\n readonly environmentIdempotencyKey: string\n readonly create?: RetainedRunStartMaterial['environment']\n readonly turn: StartRetainedRunOptions['turn']\n readonly contextTransfer?: ContextTransferRequest\n readonly identity: { readonly sessionId: string; readonly executionId: string }\n readonly onAdmission: RetainedRunAdmissionHook\n readonly capabilities: AgentEnvironmentCapabilities\n readonly now?: () => number\n}\n\nasync function dispatchRetainedRun(\n options: DispatchRetainedRunOptions,\n): Promise<RetainedRunHandle> {\n const { environment, identity } = options\n assertRequestedInteractionCapabilities(\n options.provider.name,\n options.turn.interactions,\n options.capabilities,\n )\n // The environment admission fires only for a dispatch-capable environment.\n await admitDurably(options.onAdmission, {\n phase: 'environment',\n provider: options.provider.name,\n environmentId: environment.id,\n idempotencyKey: options.environmentIdempotencyKey,\n turnId: options.turn.turnId,\n sessionId: identity.sessionId,\n executionId: identity.executionId,\n })\n\n // Dispatch failure leaks a paid environment when THIS call provisioned it, and deletes another\n // caller's workspace when it did not. The provider's creation receipt is what separates the two:\n // only `created` is destroyed, and `replayed` or an absent receipt is kept, because an\n // environment whose creation cannot be proven may be held by someone else.\n const destroyIfCreated = async (cause: unknown): Promise<never> => {\n if (options.preserveEnvironment || environment.creation !== 'created') throw cause\n try {\n await environment.destroy?.()\n } catch (cleanupError) {\n throw new AggregateError(\n [cause, cleanupError],\n 'retained run dispatch failed and the environment it created could not be destroyed',\n )\n }\n throw cause\n }\n\n options.signal?.throwIfAborted()\n options.turn.signal?.throwIfAborted()\n let reference: AgentSessionRef\n try {\n const turn = options.create\n ? retainedTurnForDispatch(options.turn, options.create)\n : options.turn\n reference = await environment.dispatch!(\n freshTurnInput(turn, {\n turnId: options.turn.turnId,\n detach: true,\n ...identity,\n ...(options.contextTransfer === undefined\n ? {}\n : { contextTransfer: options.contextTransfer }),\n }),\n )\n } catch (error) {\n await destroyIfCreated(error)\n throw error\n }\n // Every post-dispatch binding failure is triageable: the durable\n // environment admission names the requested coordinates, and the error\n // carries the provider's actual answer. The environment is kept.\n let exact: ReturnType<typeof exactSession>\n try {\n if (reference.provider !== undefined && reference.provider !== options.provider.name) {\n throw new Error('provider dispatch returned a session reference for another provider')\n }\n if (reference.id !== identity.sessionId) {\n throw new Error('provider dispatched into another session than the requested identity')\n }\n const controlRef = exactControlRef(reference.controlRef, {\n provider: options.provider.name,\n environmentId: environment.id,\n sessionId: identity.sessionId,\n })\n if (controlRef.executionId !== identity.executionId) {\n throw new Error('provider bound another execution than the requested identity')\n }\n if (options.expectedRunId !== undefined && controlRef.runId !== options.expectedRunId) {\n throw new Error('provider bound another run than the accepted context transfer receipt')\n }\n exact = exactSession(environment, controlRef)\n } catch (error) {\n const bindingError = new RetainedRunDispatchBindingError(\n {\n provider: options.provider.name,\n environmentId: environment.id,\n sessionId: identity.sessionId,\n executionId: identity.executionId,\n },\n {\n ...(reference.id === undefined ? {} : { id: reference.id }),\n ...(reference.provider === undefined ? {} : { provider: reference.provider }),\n ...(reference.controlRef === undefined ? {} : { controlRef: reference.controlRef }),\n },\n { cause: error },\n )\n await destroyIfCreated(bindingError)\n throw bindingError\n }\n await admitDurably(options.onAdmission, {\n phase: 'dispatched',\n controlRef: freezeControlRef(exact.controlRef),\n idempotencyKey: options.environmentIdempotencyKey,\n turnId: options.turn.turnId,\n })\n return createRetainedRunHandle(\n environment,\n exact.session,\n exact.controlRef,\n options.capabilities,\n options.now,\n )\n}\n\n/**\n * Await one admission record through the caller's durability hook. A rejection\n * keeps the environment alive — the provider state plus any partial admission\n * record is the recovery path — and surfaces as `RetainedRunAdmissionError` so\n * callers can distinguish a persistence failure from a provider failure.\n */\nexport async function admitDurably<\n TAdmission extends RetainedRunAdmission | RetainedInteractiveAdmission,\n>(onAdmission: (admission: TAdmission) => Promise<void>, admission: TAdmission): Promise<void> {\n const stableAdmission = detachedSnapshot(admission, 'retained run admission')\n try {\n await onAdmission(stableAdmission)\n } catch (error) {\n if (isInteractiveAdmission(stableAdmission)) {\n throw new RetainedInteractiveAdmissionError(stableAdmission, { cause: error })\n }\n throw new RetainedRunAdmissionError(stableAdmission, { cause: error })\n }\n}\n\n/**\n * Mirror each admission into `<journalRoot>/<runId>/observer.jsonl`, the observer format\n * agent-runtime-top reads. The caller's hook stays authoritative; an observer append that\n * fails never fails the run, matching `FileObserverJournal`'s contract.\n */\nexport function journaledAdmissions<\n TAdmission extends RetainedRunAdmission | RetainedInteractiveAdmission,\n>(\n journalRoot: string | undefined,\n replayRunId: string | undefined,\n onAdmission: (admission: TAdmission) => Promise<void>,\n): (admission: TAdmission) => Promise<void> {\n if (journalRoot === undefined) return onAdmission\n let runId = replayRunId\n return async (admission) => {\n await onAdmission(admission)\n if ('runId' in admission) runId ??= admission.runId\n if (runId === undefined) return\n await appendRetainedObserverEvent(journalRoot, runId, admission.phase, 'agent.run', 'before', {\n status: 'running',\n admission: admission.phase,\n })\n }\n}\n\n/**\n * The interactive handle with its accepted turns and its end journaled beside its admissions, so a\n * viewer sees the run take turns and settle rather than run forever. A turn records its operation id,\n * never the prompt, so handles in different processes agree. The end is the first exited status\n * read or accepted stop.\n */\nexport function journaledInteractiveHandle(\n handle: RetainedInteractiveRunHandle,\n journalRoot: string | undefined,\n runId: string,\n): RetainedInteractiveRunHandle {\n if (journalRoot === undefined) return handle\n const settle = async (failed: boolean, detail: Record<string, unknown>) => {\n await appendRetainedObserverEvent(\n journalRoot,\n runId,\n 'settled',\n 'agent.run',\n failed ? 'error' : 'after',\n { status: failed ? 'failed' : 'done', ...detail },\n )\n }\n const journaled: RetainedInteractiveRunHandle = {\n ...handle,\n claimControl: async (request, options) => {\n const ack = await handle.claimControl(request, options)\n if ((ack.status === 'accepted' || ack.status === 'replayed') && ack.control)\n await refreshInteractiveDelegation(journaled, ack.control)\n return ack\n },\n attach: async (request, options) =>\n delegatedTerminal(journaled, await handle.attach(request, options)),\n sendPrompt: async (command, options) => {\n const ack = await handle.sendPrompt(command, options)\n if (ack.status === 'accepted' || ack.status === 'replayed') {\n await appendRetainedObserverEvent(\n journalRoot,\n runId,\n `turn:${command.operationId}`,\n 'agent.turn',\n 'event',\n { operationId: command.operationId },\n )\n }\n return ack\n },\n status: async (options) => {\n const status = await handle.status(options)\n if (status.state === 'exited') {\n await revokeInteractiveControl(journaled)\n await settle(status.reason === 'lost' || (status.exitCode ?? 0) !== 0, {\n reason: status.reason,\n ...(status.exitCode === undefined ? {} : { exitCode: status.exitCode }),\n })\n }\n return status\n },\n stop: async (command, options) => {\n const ack = await handle.stop(command, options)\n if (ack.status === 'accepted' || ack.status === 'replayed') {\n await revokeInteractiveControl(journaled, command.control)\n await settle(false, { reason: 'stopped' })\n }\n return ack\n },\n }\n bindInteractiveDelegation(journaled, journalRoot)\n return Object.freeze(journaled)\n}\n\n/** One observer record of a retained run, at `<journalRoot>/<runId>/observer.jsonl`. A viewer's\n * record never fails the run it describes, so a write failure is dropped. */\nasync function appendRetainedObserverEvent(\n journalRoot: string,\n runId: string,\n name: string,\n target: RuntimeHookTarget,\n phase: RuntimeHookPhase,\n payload: Record<string, unknown>,\n): Promise<void> {\n await withJsonlFileLock(join(journalRoot, runId, 'observer.jsonl'), async (path) => {\n const journal = new FileObserverJournal(path, runId)\n const id = `${runId}:${name}`\n if ((await journal.read()).some((record) => record.event?.id === id)) return\n await journal.appendEvent({\n id,\n pursuitId: runId,\n runId,\n target,\n phase,\n timestamp: Date.now(),\n payload,\n })\n }).catch(() => undefined)\n}\n\nfunction isInteractiveAdmission(\n admission: RetainedRunAdmission | RetainedInteractiveAdmission,\n): admission is RetainedInteractiveAdmission {\n return (\n admission.phase === 'interactive_intent' ||\n admission.phase === 'interactive_environment' ||\n admission.phase === 'interactive_started'\n )\n}\n\n/**\n * Rebuild the exact run named by a persisted pre-create intent or pre-dispatch\n * admission coordinates, or report why the provider cannot prove it.\n *\n * An intent recovery replays the exact original start material through\n * `startRetainedRun`; a changed replay is rejected before provider creation.\n *\n * `not_found`: the provider no longer holds the environment, so nothing\n * remains to destroy. `recovered`: the provider self-identified the session\n * with a strict exact reference matching the recorded coordinates.\n * `unverifiable`: the environment exists but the provider cannot\n * self-identify the session — no session accessor, an accessor that throws,\n * a lazy accessor with no stored reference, or a loose reference. That\n * outcome is never destroy-safe: keep the environment, retry\n * `reconnectRetainedRun` with a dispatched admission record, or inspect the\n * environment with provider-native tools. A session that self-identifies\n * with different coordinates throws: something live is not the recorded run.\n *\n * @stable\n */\nexport function recoverRetainedRun(\n options: RecoverRetainedRunIntentOptions,\n): Promise<RecoverRetainedRunResult>\nexport function recoverRetainedRun(\n options: RecoverRetainedRunOptions,\n): Promise<RecoverRetainedRunResult>\nexport async function recoverRetainedRun(\n options: RecoverRetainedRunIntentOptions | RecoverRetainedRunOptions,\n): Promise<RecoverRetainedRunResult> {\n if ('admission' in options) {\n if (options.admission.provider !== options.provider.name) {\n throw new Error('retained run intent belongs to another provider')\n }\n const handle = await startRetainedRun({\n provider: options.provider,\n ...options.replay,\n intent: options.admission,\n onAdmission: options.onAdmission,\n now: options.now,\n })\n return { outcome: 'recovered', via: 'resumed', handle }\n }\n assertStableText(options.environmentId, 'retained environment id')\n assertStableText(options.sessionId, 'retained session id')\n assertStableText(options.executionId, 'retained execution id')\n const contextTransfer = retainedContextTransfer(options.contextTransfer)\n const providerCapabilities = await assertRetainedCapabilities(options.provider)\n if (!options.provider.get) {\n throw new Error(`provider \"${options.provider.name}\" cannot reconstruct an environment by id`)\n }\n // A run that started from an ACCEPTED context transfer repeats the receipt-authorized\n // lookup here: without the request, an adapter requiring receipt authorization answers\n // not_found; without the receipt check, a run the receipt never bound can be accepted.\n const environment =\n contextTransfer === undefined || options.transferReceipt === undefined\n ? await options.provider.get(options.environmentId)\n : await options.provider.get(options.environmentId, {\n contextTransfer,\n })\n if (!environment) return { outcome: 'not_found' }\n if (contextTransfer !== undefined && options.transferReceipt !== undefined) {\n assertRetainedContextTransferEnvironment(environment, contextTransfer, options.transferReceipt)\n }\n const capabilities = retainedCapabilitiesForEnvironment(\n options.provider.name,\n providerCapabilities,\n environment,\n )\n if (!environment.session) return { outcome: 'unverifiable', environment }\n let session: AgentSession\n try {\n session = environment.session(options.sessionId)\n } catch {\n return { outcome: 'unverifiable', environment }\n }\n // A lazy accessor returns a session for any id and only echoes a reference\n // the caller supplied, so an absent or loose reference proves nothing about\n // the run either way: the answer is unverifiable, never destroy-safe.\n const parsed = AgentExactRunControlRefSchema.safeParse(session.controlRef)\n if (!parsed.success) return { outcome: 'unverifiable', environment }\n const controlRef = parsed.data\n if (\n controlRef.provider !== options.provider.name ||\n controlRef.environmentId !== options.environmentId ||\n controlRef.sessionId !== options.sessionId ||\n controlRef.executionId !== options.executionId\n ) {\n throw new Error('provider session is bound to other retained run coordinates')\n }\n const exact = exactSession(environment, controlRef)\n return {\n outcome: 'recovered',\n via: 'reattached',\n handle: createRetainedRunHandle(\n environment,\n exact.session,\n exact.controlRef,\n capabilities,\n options.now,\n ),\n }\n}\n\n/** Check public replay material before reconnecting an already-dispatched execution. */\nexport function assertRetainedRunReplayMaterial(\n provider: AgentEnvironmentProvider,\n replay: RetainedRunStartMaterial,\n admission: RetainedRunIntentAdmission,\n): void {\n const identity = replay.identity ?? admission\n assertStableText(identity.sessionId, 'retained session id')\n assertStableText(identity.executionId, 'retained execution id')\n const options = { ...replay, provider }\n const contextTransfer = retainedContextTransfer(replay.turn.contextTransfer)\n assertExactRetainedRunIntent(\n admission,\n retainedRunIntent(options, identity, contextTransfer),\n () =>\n retainedRunIntent(options, identity, contextTransfer, {\n providerOptions: replay.turn.providerOptions,\n }),\n )\n}\n\nfunction retainedRunIntent(\n options: RetainedRunStartMaterial & { readonly provider: AgentEnvironmentProvider },\n identity: { readonly sessionId: string; readonly executionId: string },\n contextTransfer: ContextTransferRequest | undefined,\n turnFields?: Pick<AgentTurnInput, 'providerOptions'>,\n): RetainedRunIntentAdmission {\n const receipt = retainedContextTransferReceipt(options, options.provider.name, contextTransfer)\n assertRetainedContextTransferIdentity(receipt, identity)\n // A named profile is only its name until the provider resolves it; an inline\n // profile has the one AgentProfile identity every other Runtime record uses.\n const { profile } = options.environment\n const requestedProfileDigest =\n typeof profile === 'string'\n ? canonicalCandidateDigest(profile)\n : canonicalAgentProfileDigest(profile)\n const material = {\n provider: options.provider.name,\n idempotencyKey: options.environment.idempotencyKey,\n turnId: options.turn.turnId,\n sessionId: identity.sessionId,\n executionId: identity.executionId,\n requestedProfileDigest,\n }\n const requestDigest = canonicalCandidateDigest({\n kind: turnFields === undefined ? 'retained-run-intent.v2' : 'retained-run-intent.v1',\n ...material,\n ...(options.existingEnvironmentId === undefined\n ? {}\n : { existingEnvironmentId: options.existingEnvironmentId }),\n ...(receipt === undefined\n ? {}\n : {\n contextTransferReceiptDigest: canonicalCandidateDigest({\n ...receipt,\n status: 'accepted',\n }),\n }),\n create: retainedCreateMaterial(options.environment),\n turn: retainedTurnMaterial(options.turn, contextTransfer, turnFields),\n })\n return {\n phase: 'intent',\n ...material,\n runId: `retained-intent-run:${requestDigest.slice('sha256:'.length)}`,\n requestDigest,\n }\n}\n\nfunction retainedContextTransfer(\n value: ContextTransferRequest | undefined,\n): ContextTransferRequest | undefined {\n if (value === undefined) return undefined\n const parsed = ContextTransferRequestSchema.safeParse(value)\n if (!parsed.success) {\n throw new Error(\n 'retained context transfer request is invalid or uses an incompatible wire contract; preserve the original record and explicitly reconstruct and review an Interface 5 transfer request before retrying',\n { cause: parsed.error },\n )\n }\n return detachedSnapshot(parsed.data, 'retained context transfer request')\n}\n\nfunction assertExactRetainedRunIntent(\n received: RetainedRunIntentAdmission,\n expected: RetainedRunIntentAdmission,\n legacyExpected?: () => RetainedRunIntentAdmission,\n): void {\n const receivedDigest = canonicalCandidateDigest(parseRetainedRunIntent(received, expected))\n if (receivedDigest === canonicalCandidateDigest(expected)) return\n if (legacyExpected && receivedDigest === canonicalCandidateDigest(legacyExpected())) return\n throw new Error('retained run intent conflicts with replay material')\n}\n\nfunction parseRetainedRunIntent(\n value: unknown,\n expected: RetainedRunIntentAdmission,\n): RetainedRunIntentAdmission {\n const stable = detachedSnapshot(value, 'retained run intent')\n if (stable === null || typeof stable !== 'object' || Array.isArray(stable)) {\n throw new Error('retained run intent is malformed')\n }\n const record = stable as Record<string, unknown>\n if (Object.keys(record).some((key) => !Object.hasOwn(expected, key))) {\n throw new Error('retained run intent contains unsupported material')\n }\n if (record.phase !== 'intent') {\n throw new Error('retained run intent has an invalid phase')\n }\n for (const [key, value] of Object.entries(record)) {\n if (key !== 'phase' && (typeof value !== 'string' || value.length === 0)) {\n throw new Error(`retained run intent field \"${key}\" is invalid`)\n }\n }\n assertDigest(record.requestedProfileDigest, 'retained run intent profile digest')\n assertDigest(record.requestDigest, 'retained run intent request digest')\n return stable as RetainedRunIntentAdmission\n}\n\nfunction assertDigest(value: unknown, label: string): asserts value is Sha256Digest {\n if (typeof value !== 'string' || !/^sha256:[a-f0-9]{64}$/u.test(value)) {\n throw new Error(`${label} is invalid`)\n }\n}\n\n/** Rebuild a retained-run client without retaining any object from the starter. @stable */\nexport async function reconnectRetainedRun(\n options: ReconnectRetainedRunOptions,\n): Promise<RetainedRunHandle | null> {\n const controlRef = AgentExactRunControlRefSchema.parse(options.controlRef)\n if (controlRef.provider !== options.provider.name) {\n throw new Error(\n `run provider \"${controlRef.provider}\" does not match \"${options.provider.name}\"`,\n )\n }\n const providerCapabilities = await assertRetainedCapabilities(options.provider)\n if (!options.provider.get) {\n throw new Error(`provider \"${options.provider.name}\" cannot reconstruct an environment by id`)\n }\n const environment = await options.provider.get(controlRef.environmentId)\n if (!environment) return null\n const capabilities = retainedCapabilitiesForEnvironment(\n options.provider.name,\n providerCapabilities,\n environment,\n )\n const exact = exactSession(environment, controlRef)\n return createRetainedRunHandle(\n environment,\n exact.session,\n exact.controlRef,\n capabilities,\n options.now,\n )\n}\n\nasync function assertRetainedCapabilities(\n provider: AgentEnvironmentProvider,\n): Promise<AgentEnvironmentCapabilities> {\n const capabilities = AgentEnvironmentCapabilitiesSchema.parse(await provider.capabilities())\n assertRetainedCapabilityRequirements(provider.name, capabilities)\n return capabilities\n}\n\n/**\n * Select the capability document for one concrete environment.\n *\n * A measured environment document is authoritative. An absent document uses\n * the provider document because that provider claims the same guarantee for\n * every environment it creates.\n */\nfunction retainedCapabilitiesForEnvironment(\n providerName: string,\n providerCapabilities: AgentEnvironmentCapabilities,\n environment: AgentEnvironment,\n): AgentEnvironmentCapabilities {\n if (environment.capabilities === undefined) return providerCapabilities\n const measured = AgentEnvironmentCapabilitiesSchema.parse(environment.capabilities)\n assertRetainedCapabilityRequirements(providerName, measured)\n return measured\n}\n\nfunction assertRetainedCapabilityRequirements(\n providerName: string,\n capabilities: AgentEnvironmentCapabilities,\n): void {\n if (capabilities.retainedControl === undefined) {\n throw new Error(`provider \"${providerName}\" cannot control a retry-safe retained run`)\n }\n}\n","import {\n type AgentExactRunControlRef,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider'\nimport { awaitAbortable, isTerminalSessionStatus } from './retained-run-binding'\nimport { reconnectRetainedRun } from './retained-run-start'\nimport type { RetainedRunEffect, RetainedRunHandle } from './retained-run-types'\nimport { errorText } from './supervise/error-message'\nimport { sleep } from './util'\n\n/** One request per run: every caller that stops the same execution replays one provider operation,\n * so the operation id and its reason never disagree across a teardown and a release. */\nconst NATIVE_STOP_REASON = 'Runtime stopped the native harness: its execution is no longer observed'\n/** How often a stop the provider accepted asynchronously reads the run's status. */\nconst STOP_STATUS_POLL_MS = 1_000\n\n/** What one attempt to stop a retained execution's native harness process established. */\nexport interface RetainedNativeStop {\n readonly executionId: string\n /** `cancelled`: the provider stopped a live execution. `not_live`: it had already ended. Any\n * other effect leaves the native process unconfirmed. */\n readonly effect: RetainedRunEffect\n readonly at: string\n readonly error?: string\n}\n\n/**\n * Stop the native harness process of a retained execution that Runtime no longer observes.\n *\n * A retained execution outlives its local stream by design, so an aborted observer can reconnect.\n * Keeping its environment preserves the files; it must not keep the harness running. Measured on\n * Discovery: after `disco cancel` the kept root box ran `claude --print` for two\n * more minutes, untraced and charged to the subscription, until an operator stopped the box; on\n * 2026-10-03 a cancelled run kept 18 boxes whose `claude` processes ran until an operator stopped\n * them. The provider's exact cancellation stops the process; the box and its files stay.\n *\n * The operation id is derived from the run reference, so a repeated stop replays the first one.\n * Never rejects: the answer is evidence for the teardown receipt.\n */\nexport async function stopRetainedNativeExecution(options: {\n readonly provider: AgentEnvironmentProvider\n readonly controlRef: AgentExactRunControlRef\n /** The live handle, when this process holds one; otherwise the reference is reconnected. */\n readonly handle?: RetainedRunHandle\n /** Bounds the whole stop, so an unanswered provider cannot hold up a release. */\n readonly signal: AbortSignal\n readonly now?: () => number\n}): Promise<RetainedNativeStop> {\n const now = options.now ?? Date.now\n const executionId = options.controlRef.executionId\n const operationId = `runtime-native-stop-${canonicalCandidateDigest({\n kind: 'runtime-native-stop.v1',\n run: options.controlRef,\n }).slice('sha256:'.length)}`\n // The last effect the provider confirmed, kept when the deadline cuts the stop short.\n let effect: RetainedRunEffect = 'unknown'\n const stop = async (): Promise<RetainedRunEffect> => {\n const handle =\n options.handle ??\n (await reconnectRetainedRun({ provider: options.provider, controlRef: options.controlRef }))\n // The provider no longer holds the environment, so nothing inside it can still run.\n if (handle === null) return 'not_live'\n const cancellation = await handle.cancel({\n operationId,\n reason: NATIVE_STOP_REASON,\n signal: options.signal,\n })\n effect = cancellation.status === 'conflict' ? 'unknown' : cancellation.effect\n // An asynchronous provider acknowledges the request before the process ends. Only a terminal\n // status proves it stopped, so the stop waits for one within its deadline.\n while (effect === 'cancel_requested') {\n await sleep(STOP_STATUS_POLL_MS, options.signal)\n const current = await handle.status({ signal: options.signal })\n // Any terminal status ends the run. After an accepted stop, `cancelled` or `stopped` is that\n // stop; `completed`, `failed` and `expired` say the run ended on its own first.\n if (isTerminalSessionStatus(current.status)) {\n effect =\n current.status === 'cancelled' || current.status === 'stopped' ? 'cancelled' : 'not_live'\n }\n }\n return effect\n }\n try {\n // The deadline covers the reconnect too: its capability and environment reads are provider\n // calls, and a release that awaits this stop must not wait on a stalled one.\n effect = await awaitAbortable(stop(), options.signal)\n return { executionId, effect, at: new Date(now()).toISOString() }\n } catch (error) {\n return {\n executionId,\n effect: effect === 'cancel_requested' ? effect : 'unknown',\n at: new Date(now()).toISOString(),\n error: errorText(error instanceof Error ? error.message : error).slice(0, 512),\n }\n }\n}\n\n/**\n * The teardown-receipt text for stopped executions. A killed harness never reports the usage of\n * its last turn, so the receipt says so instead of letting a reader take the settled spend as\n * complete.\n */\nexport function describeRetainedNativeStops(stops: ReadonlyArray<RetainedNativeStop>): string {\n return stops\n .map((stop) => {\n if (stop.effect === 'cancelled') {\n return `native execution ${stop.executionId} stopped at ${stop.at}; usage unknown: killed at ${stop.at}`\n }\n if (stop.effect === 'not_live') {\n return `native execution ${stop.executionId} was not live at ${stop.at}`\n }\n return `native execution ${stop.executionId} stop unconfirmed at ${stop.at} (effect ${stop.effect}${\n stop.error === undefined ? '' : `: ${stop.error}`\n }); it may still be running`\n })\n .join('; ')\n}\n","/**\n * Durable checkpoints of a retained owner's workspace, and the marker that proves a restore.\n *\n * A director placed on a provider sandbox keeps its working files in that sandbox. When the\n * provider loses the sandbox, Runtime re-enters the director in a new one with the coordinator's\n * run state (`reentry.ts`), but the files were gone: measured in discovery-lab Autopsy A\n * (`autopsy-a-after-20260924b`), the re-entered director found no `objective.md` and\n * wrote a new nonce. So while a manager coordinates, Runtime checkpoints its workspace through the\n * provider's durable branching surface, and a replacement environment is created from the latest\n * checkpoint. The checkpoint belongs to the provider: a Tangle checkpoint is a Sandbox snapshot,\n * which outlives its box (a snapshot took 4.0 to 5.0 s, and a box created\n * from it 19 s after its source box was deleted held every file byte-identical).\n *\n * Before each checkpoint Runtime writes a marker file into the workspace. A restored environment\n * is verified by reading that file back: the provider's create is contracted to restore or fail,\n * and the marker is the evidence that it did.\n */\n\nimport type { AgentEnvironment } from '@tangle-network/agent-interface/environment-provider'\nimport type { WorkspaceCheckpointMarker } from './types'\n\n/** Workspace-relative path of the marker Runtime writes before every checkpoint. */\nexport const WORKSPACE_CHECKPOINT_MARKER_PATH = '.agent-runtime-checkpoint'\n\n/** Least time between two checkpoints of one owner. Each checkpoint stores the whole workspace. */\nexport const WORKSPACE_CHECKPOINT_MIN_INTERVAL_MS = 60_000\n\n/** Bound on one checkpoint: environment lookup, marker write, and the provider operation. */\nexport const WORKSPACE_CHECKPOINT_TIMEOUT_MS = 120_000\n\n/** After this long, a checkpoint request the provider answers `not_found` for was never created:\n * ten times the bound on the request itself, so nothing it started can still be in flight. */\nexport const WORKSPACE_CHECKPOINT_ABSENT_AFTER_MS = 10 * WORKSPACE_CHECKPOINT_TIMEOUT_MS\n\n/** Checkpoints kept per source environment; older ones are deleted once a newer one is journaled,\n * and only after their files are captured. */\nexport const WORKSPACE_CHECKPOINTS_KEPT = 2\n\n/** Bound on the captures one checkpoint rotation runs, all of them together, forks included.\n * A turn's own workspace capture also cuts them short when it starts. A capture cut short keeps\n * its checkpoint, and the owner's release, bounded by `RELEASE_CHECKPOINT_CAPTURES_MS`, captures\n * it again. */\nexport const WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS = 2 * 60_000\n\n/** Bound on creating and reconstructing the fork a checkpoint's capture reads: a Sandbox box\n * created from a snapshot (19 s). The capture itself is bounded by its port. */\nexport const WORKSPACE_CHECKPOINT_FORK_TIMEOUT_MS = 10 * 60_000\n\n/** Write the marker. False when the environment cannot take it, so no restore can be verified. */\nexport async function writeWorkspaceMarker(\n environment: AgentEnvironment,\n marker: WorkspaceCheckpointMarker,\n signal: AbortSignal,\n): Promise<boolean> {\n if (typeof environment.write !== 'function') return false\n try {\n await environment.write(marker.path, marker.content, { signal })\n return true\n } catch {\n return false\n }\n}\n\n/** Read the marker back from a restored environment and compare it byte for byte. */\nexport async function verifyWorkspaceMarker(\n environment: AgentEnvironment,\n marker: WorkspaceCheckpointMarker | undefined,\n signal: AbortSignal,\n): Promise<{ readonly verified: boolean; readonly detail?: string }> {\n if (marker === undefined) {\n return {\n verified: false,\n detail: 'the checkpoint has no marker: the source could not take one',\n }\n }\n if (typeof environment.read !== 'function') {\n return { verified: false, detail: 'the restored environment does not expose read' }\n }\n try {\n const content = await environment.read(marker.path, { signal })\n return content === marker.content\n ? { verified: true }\n : {\n verified: false,\n detail: 'the marker in the restored environment differs from the checkpoint',\n }\n } catch (error) {\n return {\n verified: false,\n detail:\n `the marker could not be read: ${error instanceof Error ? error.message : String(error)}`.slice(\n 0,\n 500,\n ),\n }\n }\n}\n","import { executorFailureReason } from '../../runtime/supervise/executor-outcome'\nimport { assertValidSpend } from '../../runtime/supervise/spend-validation'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\n\n/** Minimal state needed to validate a node; progress and trace payloads are never retained here. */\ninterface JournalNodeIndex {\n spawned: boolean\n closed: boolean\n materialized: boolean\n authoredProfileDigest?: string\n latestSeatMaterialization: number\n bindings: Set<string>\n inputs: Set<number>\n input: boolean\n /** The sequence of the latest `execution-input`. */\n latestInput?: number\n result: boolean\n /** The latest invocation was abandoned: nothing of it is accepted, and a new input may follow. */\n abandoned: boolean\n admissions: Map<\n Extract<SpawnEvent, { kind: 'execution-admitted' }>['admission']['phase'],\n Extract<SpawnEvent, { kind: 'execution-admitted' }>['admission']\n >\n /** The environment this node's retained invocations last ran in, across invocations. */\n lastEnvironmentId?: string\n /** Environments that can run no more turns, from teardown or provider terminal observation. */\n unusableEnvironments: Set<string>\n}\n\n/**\n * A trace root is valid only beside the output it commits to, with a well-formed root, artifact\n * reference and leaf count (at least the summary leaf). Records written before trace roots carry\n * none and stay valid.\n */\nfunction assertTraceRoot(event: SpawnEvent, root: NodeId): void {\n if (!('traceRoot' in event) || event.traceRoot === undefined) return\n const receipt: unknown = event.traceRoot\n const fields =\n receipt !== null && typeof receipt === 'object' ? (receipt as Record<string, unknown>) : {}\n if (\n typeof event.outRef !== 'string' ||\n typeof fields.root !== 'string' ||\n !/^sha256:[0-9a-f]{64}$/.test(fields.root) ||\n typeof fields.ref !== 'string' ||\n !/^sha256:[0-9a-f]{64}$/.test(fields.ref) ||\n typeof fields.leafCount !== 'number' ||\n !Number.isSafeInteger(fields.leafCount) ||\n fields.leafCount < 1\n ) {\n throw new Error(\n `spawn journal corrupted: ${event.kind} for node '${event.id}' carries a malformed trace root in tree '${root}'`,\n )\n }\n}\n\n/** One validation implementation for memory, durable append, and cold replay. */\n/** @internal shared with the SQL-backed store. */\nexport class SpawnEventIndex {\n private readonly nodes = new Map<NodeId, JournalNodeIndex>()\n private readonly cursors = new Set<number>()\n\n constructor(private readonly root: NodeId) {}\n\n assert(event: SpawnEvent): void {\n const node = this.nodes.get(event.id)\n this.assertRetained(node, event)\n assertTraceRoot(event, this.root)\n if (event.kind === 'execution-evidence') {\n if (!node?.spawned || !/^sha256:[0-9a-f]{64}$/.test(event.outRef)) {\n throw new Error(\n 'spawn journal corrupted: executor evidence has no spawned node or valid content reference',\n )\n }\n }\n if (event.kind === 'materialized') {\n if (node?.materialized) {\n throw new Error(\n `spawn journal corrupted: duplicate materialization receipt for node '${event.id}' in tree '${this.root}'`,\n )\n }\n if (!node?.spawned) {\n throw new Error(\n `spawn journal corrupted: materialization for node '${event.id}' precedes its spawn in tree '${this.root}'`,\n )\n }\n }\n if (event.kind === 'seat-materialized') {\n if (\n !node?.materialized ||\n node.authoredProfileDigest === undefined ||\n event.receipt.status !== 'known' ||\n event.receipt.authoredProfileDigest !== node.authoredProfileDigest ||\n !Number.isSafeInteger(event.segmentIndex) ||\n event.segmentIndex <= node.latestSeatMaterialization\n ) {\n throw new Error(\n `spawn journal corrupted: invalid seat materialization for node '${event.id}' in tree '${this.root}'`,\n )\n }\n }\n if (event.kind === 'execution-bound') {\n if (node?.bindings.has(event.binding.attemptId)) {\n throw new Error(\n `spawn journal corrupted: duplicate execution binding for node '${event.id}' attempt '${event.binding.attemptId}' in tree '${this.root}'`,\n )\n }\n if (!node?.materialized) {\n throw new Error(\n `spawn journal corrupted: execution binding for node '${event.id}' precedes materialization in tree '${this.root}'`,\n )\n }\n }\n if (!outsideCursorNamespace(event) && this.cursors.has(event.seq)) {\n throw new Error(\n `spawn journal corrupted: duplicate cursor seq ${event.seq} in tree '${this.root}'; ` +\n 'the cursor order replay relies on is not unique',\n )\n }\n }\n\n /** Called after validation; a file writer discards staged state if grouped publication fails. */\n add(event: SpawnEvent): void {\n if (!outsideCursorNamespace(event)) this.cursors.add(event.seq)\n if (\n event.kind !== 'spawned' &&\n event.kind !== 'materialized' &&\n event.kind !== 'seat-materialized' &&\n event.kind !== 'execution-bound' &&\n event.kind !== 'execution-input' &&\n event.kind !== 'execution-admitted' &&\n event.kind !== 'execution-result' &&\n event.kind !== 'execution-abandoned' &&\n event.kind !== 'environment-teardown' &&\n event.kind !== 'environment-terminal' &&\n !closesCursorSlot(event)\n )\n return\n let node = this.nodes.get(event.id)\n if (!node) {\n node = {\n spawned: false,\n closed: false,\n materialized: false,\n latestSeatMaterialization: 0,\n bindings: new Set(),\n inputs: new Set(),\n input: false,\n result: false,\n abandoned: false,\n admissions: new Map(),\n unusableEnvironments: new Set(),\n }\n this.nodes.set(event.id, node)\n }\n if (event.kind === 'environment-teardown') {\n if (event.destroyed) node.unusableEnvironments.add(event.environmentId)\n return\n }\n if (event.kind === 'environment-terminal') {\n node.unusableEnvironments.add(event.environmentId)\n return\n }\n if (event.kind === 'execution-admitted' && event.admission.phase === 'environment') {\n node.lastEnvironmentId = event.admission.environmentId\n }\n if (event.kind === 'spawned') node.spawned = true\n else if (event.kind === 'materialized') {\n node.materialized = true\n node.authoredProfileDigest = event.receipt.authoredProfileDigest\n } else if (event.kind === 'seat-materialized')\n node.latestSeatMaterialization = event.segmentIndex\n else if (event.kind === 'execution-bound') node.bindings.add(event.binding.attemptId)\n else if (event.kind === 'execution-input') {\n node.inputs.add(event.seq)\n node.input = true\n node.latestInput = event.seq\n node.result = false\n node.abandoned = false\n node.admissions.clear()\n } else if (event.kind === 'execution-admitted') {\n node.admissions.set(event.admission.phase, event.admission)\n } else if (event.kind === 'execution-result') node.result = true\n else if (event.kind === 'execution-abandoned') node.abandoned = true\n if (closesCursorSlot(event)) node.closed = true\n }\n\n private assertRetained(node: JournalNodeIndex | undefined, event: SpawnEvent): void {\n if (\n event.kind !== 'execution-input' &&\n event.kind !== 'execution-admitted' &&\n event.kind !== 'execution-result' &&\n event.kind !== 'execution-abandoned'\n )\n return\n function fail(reason: string): never {\n throw new Error(`spawn journal corrupted: retained execution '${event.id}' ${reason}`)\n }\n if (!node?.spawned) fail('precedes its spawn')\n if (node.closed) fail('follows its terminal settlement')\n if (event.kind === 'execution-input') {\n if (!/^sha256:[0-9a-f]{64}$/.test(event.taskRef)) fail('has an invalid task reference')\n if (node.inputs.has(event.seq)) fail('has duplicate input sequence')\n // An unfinished invocation may be replaced only once its environment is gone, the provider\n // reports its compute terminal, or Runtime abandoned it: then nothing of the old turn can\n // be accepted, because every later admission or result of it is refused below.\n const environment = node.admissions.get('environment')\n const ranIn =\n environment?.phase === 'environment' ? environment.environmentId : node.lastEnvironmentId\n const closed = node.abandoned || (ranIn !== undefined && node.unusableEnvironments.has(ranIn))\n if (node.input && !node.result && !closed) fail('input replaces an unfinished invocation')\n return\n }\n if (event.kind === 'execution-abandoned') {\n if (!node.input || node.latestInput !== event.inputSeq)\n fail('abandons an invocation that is not its latest')\n if (node.result) fail('abandons an invocation that has a result')\n if (node.abandoned) fail('abandons an invocation twice')\n if (!Number.isSafeInteger(event.failures) || event.failures < 1)\n fail('abandons without a failure count')\n return\n }\n // Nothing of an abandoned invocation is accepted: its replacement is the only invocation.\n if (node.abandoned) fail(`${event.kind} follows its abandonment`)\n if (event.kind === 'execution-result') {\n if (node.result) fail('has duplicate result')\n if (!node.admissions.has('dispatched')) fail('result precedes dispatch')\n if (!/^sha256:[0-9a-f]{64}$/.test(event.outRef)) fail('has an invalid result reference')\n if (event.outputFormat !== undefined && event.outputFormat !== 'json')\n fail('has an invalid output format')\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 type { NodeId } from './types'\n\n/** Runtime tag used only for a child that owns another supervised scope. */\nexport const driverRuntime = 'driver' as const\n\n// Recursive ownership is an executor capability, not a Runtime string. `Runtime` is deliberately\n// open, so a caller-owned leaf may also call itself \"driver\". Keep the capability on the exact\n// Runtime-created executor object and never expose a public lookalike property that a leaf can set.\nconst nestedDriverTreeOwners = new WeakSet<object>()\n\n/** Canonical journal key for the scope owned by one nested driver node. */\nexport function nestedDriverTreeRoot(parentTreeRoot: NodeId, driverNodeId: NodeId): NodeId {\n return `${parentTreeRoot}/${driverNodeId}`\n}\n\n/** Privately mark the exact recursive executor that will create a nested journal tree. */\nexport function attestNestedDriverTreeOwner<T extends object>(owner: T): T {\n nestedDriverTreeOwners.add(owner)\n return owner\n}\n\n/** Return the canonical owned tree only for an exact privately marked recursive executor. */\nexport function runtimeOwnedNestedDriverTreeRoot(\n owner: object,\n parentTreeRoot: NodeId,\n driverNodeId: NodeId,\n): NodeId | undefined {\n return nestedDriverTreeOwners.has(owner)\n ? nestedDriverTreeRoot(parentTreeRoot, driverNodeId)\n : undefined\n}\n","import { snapshotProviderObservations } from '../../runtime/provider-observation-snapshot'\nimport type { BudgetViolation, NodeSnapshot, SpawnEvent } from '../../runtime/supervise/types'\n\n/** Copy a terminal record's overspend at the journal boundary; absent stays absent. */\nexport function budgetViolationOf(event: Extract<SpawnEvent, { kind: 'settled' | 'cancelled' }>): {\n readonly budgetViolation?: BudgetViolation\n} {\n if (event.budgetViolation === undefined) return {}\n return {\n budgetViolation: Object.freeze({\n overspent: Object.freeze(\n event.budgetViolation.overspent.map((entry) =>\n Object.freeze({ channel: entry.channel, reserved: entry.reserved, spent: entry.spent }),\n ),\n ),\n }),\n }\n}\n\n/** Copy provider evidence at the journal boundary so replay never exposes mutable event state. */\nexport function copyProviderModelEvidence(\n evidence: NodeSnapshot['providerModel'],\n): NodeSnapshot['providerModel'] {\n if (evidence === undefined) return undefined\n const attempts = snapshotProviderObservations(evidence.attempts)\n const models = Object.freeze([...evidence.models])\n return Object.freeze(\n evidence.status === 'unknown'\n ? { status: 'unknown' as const, attempts, models, reason: evidence.reason }\n : { status: 'known' as const, attempts, models },\n )\n}\n\nexport function traceEvidenceFor(\n event: Extract<SpawnEvent, { kind: 'settled' }>,\n): NonNullable<NodeSnapshot['trace']> {\n return (\n event.trace ?? {\n status: 'unavailable',\n reason: 'legacy-settlement-without-trace-evidence',\n }\n )\n}\n","import { settlementFailureCause } from '../../runtime/failure-cause'\nimport type { NodeId, NodeSnapshot, SpawnEvent, TreeView } from '../../runtime/supervise/types'\nimport { addSpend, cloneSpend, zeroSpend } from '../../runtime/util'\nimport { insideCursorNamespace } from './event-index'\nimport {\n budgetViolationOf,\n copyProviderModelEvidence,\n traceEvidenceFor,\n} from './settlement-evidence'\n\n/**\n * Materialize a recorded `TreeView` from a journaled event list for inspection. Folds\n * `spawned`/`settled`/`cancelled` into a per-node snapshot in `seq` order, then adds each\n * `metered` event's driver-inference spend onto its node in a separate additive pass so the view\n * matches the recorded cursor. It does not recover live executors or driver state after restart.\n */\nexport function materializeTreeView(events: SpawnEvent[]): TreeView {\n const nodes = new Map<NodeId, MutableSnapshot>()\n let root: NodeId | undefined\n // `spawned` (ordinal namespace) and `settled`/`cancelled` (cursor namespace) carry\n // overlapping `seq` values, so create every node before any update — process spawns in\n // ordinal order, then settlements/cancellations in cursor order. A settle/cancel for an\n // un-spawned node is a corrupted log (fail loud via requireNode).\n const spawns = events\n .filter((ev): ev is Extract<SpawnEvent, { kind: 'spawned' }> => ev.kind === 'spawned')\n .sort((a, b) => a.seq - b.seq)\n const settlements = events.filter((ev) => insideCursorNamespace(ev)).sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.parent === undefined && root === undefined) root = ev.id\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n status: 'pending',\n runtime: ev.runtime,\n budget: ev.budget,\n ...(ev.ownedTreeRoot === undefined ? {} : { ownedTreeRoot: ev.ownedTreeRoot }),\n ...(ev.assignmentId === undefined ? {} : { assignmentId: ev.assignmentId }),\n ...(ev.identity ? { identity: ev.identity } : {}),\n ...(ev.modelSubstitution ? { modelSubstitution: ev.modelSubstitution } : {}),\n ...(Number.isFinite(Date.parse(ev.at)) ? { spawnedAt: Date.parse(ev.at) } : {}),\n spent: zeroSpend(),\n })\n }\n for (const ev of settlements) {\n const node = requireNode(nodes, ev.id)\n const down = ev.kind === 'cancelled' || ev.status === 'down'\n node.status = ev.kind === 'cancelled' ? 'cancelled' : down ? 'failed' : 'done'\n if (ev.spent !== undefined) node.spent = cloneSpend(ev.spent)\n node.providerModel = copyProviderModelEvidence(ev.providerModel)\n node.outRef = ev.outRef\n node.failure = down\n ? (ev.failure ??\n settlementFailureCause({\n reason:\n ev.reason ?? (ev.kind === 'settled' ? ev.verdict?.notes : undefined) ?? 'child down',\n infra: ev.infra,\n retainedPendingCause: ev.retainedPendingCause,\n }))\n : undefined\n node.trace =\n ev.kind === 'cancelled'\n ? (ev.trace ?? { status: 'unavailable', reason: 'execution-did-not-start' })\n : traceEvidenceFor(ev)\n node.budgetViolation = budgetViolationOf(ev).budgetViolation\n if (ev.retainedExecution !== undefined) node.retainedExecution = ev.retainedExecution\n if (ev.retainedPendingCause !== undefined) node.retainedPendingCause = ev.retainedPendingCause\n const settledAt = Date.parse(ev.at)\n if (Number.isFinite(settledAt)) node.settledAt = settledAt\n }\n // Materialization is node evidence, not a settlement. Fold it after node creation and before\n // freezing the view; exactly one receipt per node is enforced by the journal corruption guard.\n for (const ev of events) {\n if (ev.kind !== 'materialized' && ev.kind !== 'seat-materialized') continue\n const node = requireNode(nodes, ev.id)\n node.materialization = ev.receipt\n node.runtime = ev.receipt.runtime\n }\n for (const ev of events) {\n if (ev.kind !== 'execution-bound') continue\n const node = requireNode(nodes, ev.id)\n node.executionBindings ??= []\n node.executionBindings.push(ev.binding)\n }\n // An open node's reconciled floor is its child-work base until a terminal record replaces it: a\n // retained-pending child stays `pending` here, and a view that showed zero for a node the ledger\n // charges would be a second ledger. The latest record wins; a settled node ignores it.\n for (const ev of [...events]\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'reconciled' }> => event.kind === 'reconciled',\n )\n .sort((a, b) => a.seq - b.seq)) {\n const node = requireNode(nodes, ev.id)\n if (node.status === 'pending') {\n node.spent = cloneSpend(ev.spent)\n node.failure = ev.failure\n }\n }\n // Driver inference: a separate pass so it accumulates ONTO the settled child-work base (no\n // dependence on metered-vs-settled seq order) without touching node status.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id)\n node.spent = addSpend(node.spent, ev.spend)\n }\n const snapshots = [...nodes.values()].map(freezeSnapshot)\n return {\n root: root ?? snapshots[0]?.id ?? '',\n nodes: snapshots,\n inFlight: snapshots.filter((n) => n.status === 'running' || n.status === 'acquiring').length,\n }\n}\n\n/** The journal fold mutates the canonical snapshot shape; only bindings need a mutable list. */\ntype MutableSnapshot = {\n -readonly [Key in keyof NodeSnapshot]: NodeSnapshot[Key]\n} & {\n executionBindings?: NonNullable<NodeSnapshot['executionBindings']>[number][]\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableSnapshot>, id: NodeId): MutableSnapshot {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(`spawn journal corrupted: settle/cancel for node '${id}' with no prior spawn`)\n }\n return node\n}\n\nfunction freezeSnapshot(node: MutableSnapshot): NodeSnapshot {\n return {\n id: node.id,\n parent: node.parent,\n label: node.label,\n status: node.status,\n ...(node.failure === undefined ? {} : { failure: node.failure }),\n runtime: node.runtime,\n budget: node.budget,\n ownedTreeRoot: node.ownedTreeRoot,\n assignmentId: node.assignmentId,\n identity: node.identity,\n modelSubstitution: node.modelSubstitution,\n materialization: node.materialization,\n executionBindings:\n node.executionBindings === undefined ? undefined : Object.freeze([...node.executionBindings]),\n spent: node.spent,\n providerModel: node.providerModel,\n outRef: node.outRef,\n trace: node.trace,\n ...(node.budgetViolation === undefined ? {} : { budgetViolation: node.budgetViolation }),\n ...(node.retainedExecution === undefined ? {} : { retainedExecution: node.retainedExecution }),\n ...(node.retainedPendingCause === undefined\n ? {}\n : { retainedPendingCause: node.retainedPendingCause }),\n settledAt: node.settledAt,\n spawnedAt: node.spawnedAt,\n }\n}\n","import { detachedSnapshot } from '../../runtime/supervise/snapshot'\nimport { nestedDriverTreeRoot } from '../../runtime/supervise/tree-key'\nimport type {\n NodeId,\n NodeSnapshot,\n Runtime,\n SpawnEvent,\n SpawnJournal,\n TreeView,\n} from '../../runtime/supervise/types'\nimport { materializeTreeView } from './tree-view'\n\n/** One journal tree in a recursively loaded supervision forest. */\nexport interface SpawnForestTree {\n readonly root: NodeId\n /** Driver node that owns this tree; absent for the requested root tree. */\n readonly ownerNodeId?: NodeId\n /** Journal tree containing `ownerNodeId`; absent for the requested root tree. */\n readonly parentTreeRoot?: NodeId\n readonly events: ReadonlyArray<SpawnEvent>\n readonly view: TreeView\n}\n\n/** One event with the journal tree that establishes its cursor namespace. */\nexport interface SpawnForestEvent {\n readonly treeRoot: NodeId\n readonly event: SpawnEvent\n}\n\n/** One flattened node with the journal tree that owns its records. */\nexport interface SpawnForestNode extends NodeSnapshot {\n readonly treeRoot: NodeId\n}\n\n/** A spawned worker with no terminal record in a cold snapshot. Resume treats the same state as\n * in-doubt and conservatively retains its reservation. Root nodes and armed waits are excluded. */\nexport interface SpawnForestInDoubtNode {\n readonly treeRoot: NodeId\n readonly nodeId: NodeId\n readonly label: string\n readonly runtime: Runtime\n}\n\n/** A driver spawn whose owned journal tree was never begun before the process stopped. */\nexport interface SpawnForestMissingTree {\n readonly parentTreeRoot: NodeId\n readonly ownerNodeId: NodeId\n readonly root: NodeId\n}\n\n/** Complete cold-readable view of one recursive supervision run. */\nexport interface SpawnForest {\n readonly root: NodeId\n readonly trees: ReadonlyArray<SpawnForestTree>\n readonly nodes: ReadonlyArray<SpawnForestNode>\n readonly events: ReadonlyArray<SpawnForestEvent>\n readonly inDoubt: ReadonlyArray<SpawnForestInDoubtNode>\n readonly missingTrees: ReadonlyArray<SpawnForestMissingTree>\n}\n\n/**\n * Load every journal tree owned by one recursive supervision run and flatten its nodes/events.\n *\n * Nested driver tree keys are a Runtime implementation detail; callers should use this reader\n * instead of deriving or scanning keys themselves. The reader follows only the explicit\n * `ownedTreeRoot` written after Runtime privately attested a recursive executor; the open runtime\n * string `driver` is never treated as ownership. Legacy records without `ownedTreeRoot` are\n * intentionally treated as leaves rather than guessing or scanning convention-derived keys.\n * This preserves each tree's independent cursor namespace on flattened events.\n * A driver whose subtree was never begun is reported in `missingTrees`; any spawned non-root node\n * without a terminal record is reported in `inDoubt`, matching resume's conservative lost-work\n * interpretation.\n *\n * This is a cold/quiescent reader, not a transaction across an actively mutating file. Every value\n * returned is a detached immutable snapshot, so later journal writes or caller mutation cannot\n * change the result already observed.\n */\nexport async function loadSpawnForest(journal: SpawnJournal, root: NodeId): Promise<SpawnForest> {\n const rootEvents = await journal.loadTree(root)\n if (rootEvents === undefined) {\n throw new Error(`loadSpawnForest: no journaled tree for root '${root}'`)\n }\n\n const trees: SpawnForestTree[] = []\n const nodes: SpawnForestNode[] = []\n const events: SpawnForestEvent[] = []\n const inDoubt: SpawnForestInDoubtNode[] = []\n const missingTrees: SpawnForestMissingTree[] = []\n const visited = new Set<NodeId>()\n const queue: Array<{\n readonly root: NodeId\n readonly events: SpawnEvent[]\n readonly ownerNodeId?: NodeId\n readonly parentTreeRoot?: NodeId\n /** Parent-tree spawn that establishes the root node omitted from an owned journal tree. */\n readonly ownerSpawn?: Extract<SpawnEvent, { kind: 'spawned' }>\n }> = [{ root, events: rootEvents }]\n\n for (let cursor = 0; cursor < queue.length; cursor += 1) {\n const current = queue[cursor]!\n if (visited.has(current.root)) {\n throw new Error(`loadSpawnForest: recursive journal tree '${current.root}' was reached twice`)\n }\n visited.add(current.root)\n const stableEvents = detachedSnapshot(\n current.events,\n `loadSpawnForest tree ${JSON.stringify(current.root)}`,\n )\n const viewEvents =\n current.ownerSpawn === undefined ||\n stableEvents.some((event) => event.kind === 'spawned' && event.id === current.ownerSpawn?.id)\n ? [...stableEvents]\n : [ownedTreeRootSpawn(current.ownerSpawn), ...stableEvents]\n const view = detachedSnapshot(\n materializeTreeView(viewEvents),\n `loadSpawnForest view ${JSON.stringify(current.root)}`,\n )\n trees.push({\n root: current.root,\n ...(current.ownerNodeId === undefined ? {} : { ownerNodeId: current.ownerNodeId }),\n ...(current.parentTreeRoot === undefined ? {} : { parentTreeRoot: current.parentTreeRoot }),\n events: stableEvents,\n view,\n })\n // The owner is already a real node in its parent tree. Keep it in this tree's local view so\n // metered root events have a node, but omit the synthetic duplicate from the flattened list.\n nodes.push(\n ...view.nodes\n .filter((node) => current.ownerNodeId === undefined || node.id !== current.ownerNodeId)\n .map((node) => ({ treeRoot: current.root, ...node })),\n )\n events.push(...stableEvents.map((event) => ({ treeRoot: current.root, event })))\n\n const terminal = new Set<NodeId>()\n for (const event of stableEvents) {\n if (event.kind === 'settled' || event.kind === 'cancelled') terminal.add(event.id)\n }\n const spawns = stableEvents\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'spawned' }> => event.kind === 'spawned',\n )\n .sort((a, b) => a.seq - b.seq || a.id.localeCompare(b.id))\n for (const spawn of spawns) {\n if (spawn.parent !== undefined && !terminal.has(spawn.id)) {\n inDoubt.push({\n treeRoot: current.root,\n nodeId: spawn.id,\n label: spawn.label,\n runtime: spawn.runtime,\n })\n }\n if (spawn.ownedTreeRoot === undefined) continue\n const expectedRoot = nestedDriverTreeRoot(current.root, spawn.id)\n if (spawn.ownedTreeRoot !== expectedRoot) {\n throw new Error(\n `loadSpawnForest: node '${spawn.id}' owns non-canonical tree '${spawn.ownedTreeRoot}'; expected '${expectedRoot}'`,\n )\n }\n const nestedRoot = spawn.ownedTreeRoot\n const nestedEvents = await journal.loadTree(nestedRoot)\n if (nestedEvents === undefined) {\n missingTrees.push({\n parentTreeRoot: current.root,\n ownerNodeId: spawn.id,\n root: nestedRoot,\n })\n continue\n }\n queue.push({\n root: nestedRoot,\n events: nestedEvents,\n ownerNodeId: spawn.id,\n parentTreeRoot: current.root,\n ownerSpawn: spawn,\n })\n }\n }\n\n return detachedSnapshot(\n { root, trees, nodes, events, inDoubt, missingTrees },\n 'loadSpawnForest result',\n )\n}\n\n/** Owned journal trees record the owner's turns and descendants, but the owner's spawn belongs to\n * the parent tree. Supply a view-only parentless copy so strict materialization can fold root\n * metering without weakening its missing-spawn corruption check for ordinary event lists. */\n/** @internal Exact parentless root for a Runtime-owned subtree. */\nexport function ownedTreeRootSpawn(\n spawn: Extract<SpawnEvent, { kind: 'spawned' }>,\n): Extract<SpawnEvent, { kind: 'spawned' }> {\n const { parent: _parent, ownedTreeRoot: _ownedTreeRoot, ...root } = spawn\n return root\n}\n","import {\n type AgentWorkspaceBranching,\n workspaceCheckpointResultMatchesRequest,\n} from '@tangle-network/agent-interface'\nimport { runAbortable } from './abortable'\nimport { errorText } from './error-message'\nimport type { OwnerState } from './retained-owner-state'\nimport type { SpawnEvent } from './types'\nimport { WORKSPACE_CHECKPOINT_ABSENT_AFTER_MS } from './workspace-checkpoint'\n\nexport type CheckpointEvent = Extract<SpawnEvent, { kind: 'workspace-checkpoint' }>\n\ntype CheckpointRequestEvent = Extract<SpawnEvent, { kind: 'workspace-checkpoint-requested' }>\n\n/** Reconstruct authority for this source only; a replacement cannot own its snapshots. */\nexport async function checkpointHandle(\n state: OwnerState,\n sourceEnvironmentId: string,\n signal: AbortSignal,\n): Promise<AgentWorkspaceBranching | undefined> {\n const cached = state.checkpointHandles?.get(sourceEnvironmentId)\n if (cached !== undefined) return cached\n const provider = state.provider\n if (provider === undefined) return undefined\n try {\n const branching = await runAbortable(\n async () => {\n if (provider.workspaceBranching) {\n return (\n (await provider.workspaceBranching.forEnvironment(sourceEnvironmentId, { signal })) ??\n undefined\n )\n }\n const source = await provider.get?.(sourceEnvironmentId)\n return source?.id === sourceEnvironmentId && source.provider === provider.name\n ? source.workspaceBranching\n : undefined\n },\n signal,\n 'retained owner checkpoint handle lookup timed out',\n )\n if (branching !== undefined) {\n state.checkpointHandles ??= new Map()\n state.checkpointHandles.set(sourceEnvironmentId, branching)\n }\n return branching\n } catch {\n return undefined\n }\n}\n\n/** A checkpoint request whose outcome a lookup could not establish, and what the lookup said. */\ninterface UnresolvedCheckpointRequest {\n readonly event: CheckpointRequestEvent\n readonly reason: string\n}\n\n/**\n * An aborted observation cannot prove that the provider never created a snapshot, so a request\n * whose lookup does not find it keeps its source alive for a later lookup, with one exception: a\n * provider that answers `not_found` for a request older than {@link WORKSPACE_CHECKPOINT_ABSENT_AFTER_MS}\n * never created it. No operation that request started can still be in flight, and keeping the\n * source then holds a sandbox for nothing: on Discovery Lab runs terraform-economics-20261005e and\n * f, each root was kept after its run settled over requests made hours earlier.\n */\nexport async function reconcileCheckpointRequests(\n state: OwnerState,\n events: SpawnEvent[],\n): Promise<UnresolvedCheckpointRequest[]> {\n const operationKey = (operation: { idempotencyKey: string; requestDigest: string }): string =>\n JSON.stringify([operation.idempotencyKey, operation.requestDigest])\n const resolved = new Set(\n events.flatMap((event) =>\n event.kind === 'workspace-checkpoint' &&\n event.id === state.args.nodeId &&\n event.provider === state.provider?.name\n ? [operationKey(event.checkpoint)]\n : [],\n ),\n )\n const pending = events.filter(\n (event): event is CheckpointRequestEvent =>\n event.kind === 'workspace-checkpoint-requested' &&\n event.id === state.args.nodeId &&\n event.provider === state.provider?.name &&\n !resolved.has(operationKey(event.request)),\n )\n const unconfirmed: UnresolvedCheckpointRequest[] = []\n for (const event of pending) {\n const signal = AbortSignal.timeout(30_000)\n try {\n const branching = await checkpointHandle(state, event.environmentId, signal)\n if (branching === undefined) throw new Error('source-scoped checkpoint handle unavailable')\n const result = await runAbortable(\n () =>\n branching.lookupCheckpoint(\n {\n idempotencyKey: event.request.idempotencyKey,\n requestDigest: event.request.requestDigest,\n },\n { signal },\n ),\n signal,\n 'retained owner checkpoint lookup timed out',\n )\n if (result.status === 'not_found') {\n const requestedAt = Date.parse(event.at)\n if (\n Number.isFinite(requestedAt) &&\n state.args.now() - requestedAt >= WORKSPACE_CHECKPOINT_ABSENT_AFTER_MS\n )\n continue\n unconfirmed.push({ event, reason: 'lookup not_found while the request may be in flight' })\n continue\n }\n if (result.status !== 'found') {\n unconfirmed.push({\n event,\n reason: `lookup ${result.status}${'message' in result && result.message ? `: ${result.message}` : ''}`,\n })\n continue\n }\n if (!workspaceCheckpointResultMatchesRequest(event.request, result)) {\n unconfirmed.push({ event, reason: 'lookup found a checkpoint for another request' })\n continue\n }\n const recovered: CheckpointEvent = {\n kind: 'workspace-checkpoint',\n id: event.id,\n provider: event.provider,\n environmentId: event.environmentId,\n checkpoint: result.checkpoint,\n ...(event.marker === undefined ? {} : { marker: event.marker }),\n seq: state.nextSequence(),\n at: event.at,\n }\n await state.args.journal.appendEvent(state.args.rootId, recovered)\n events.push(recovered)\n } catch (error) {\n unconfirmed.push({\n event,\n reason: `lookup failed: ${errorText(error instanceof Error ? error.message : error)}`,\n })\n }\n }\n return unconfirmed\n}\n\nexport function pendingCheckpoints(\n events: readonly SpawnEvent[],\n state: OwnerState,\n): CheckpointEvent[] {\n const confirmed = new Set(\n events.flatMap((event) =>\n event.kind === 'workspace-checkpoint-cleanup' &&\n event.id === state.args.nodeId &&\n event.provider === state.provider?.name &&\n event.confirmed\n ? [JSON.stringify([event.environmentId, event.checkpointId])]\n : [],\n ),\n )\n return events.filter(\n (event): event is CheckpointEvent =>\n event.kind === 'workspace-checkpoint' &&\n event.id === state.args.nodeId &&\n event.provider === state.provider?.name &&\n !confirmed.has(JSON.stringify([event.environmentId, event.checkpoint.checkpointId])),\n )\n}\n","import {\n type AgentWorkspaceBranching,\n type Sha256Digest,\n workspaceCleanupAcknowledgementMatches,\n workspaceCleanupRequestDigest,\n workspaceForkRequestDigest,\n workspaceForkResultMatchesRequest,\n} from '@tangle-network/agent-interface'\nimport { captureProviderCheckpointWorkspace } from '../provider-workspace-retention'\nimport { runAbortable, signalAbortError } from './abortable'\nimport { errorText } from './error-message'\nimport { type CheckpointEvent, checkpointHandle } from './retained-owner-checkpoint-requests'\nimport type { OwnerState } from './retained-owner-state'\nimport type { SpawnEvent } from './types'\nimport { WORKSPACE_CHECKPOINT_FORK_TIMEOUT_MS } from './workspace-checkpoint'\n\ntype CheckpointCaptureEvent = Extract<SpawnEvent, { kind: 'workspace-checkpoint-capture' }>\n\ntype ForkTeardownEvent = Extract<SpawnEvent, { kind: 'workspace-checkpoint-fork-teardown' }>\n\n/** A checkpoint kept without a delete because no capture holds its files. */\nexport interface CaptureRefusal {\n readonly event: CheckpointEvent\n readonly reason: string\n /** Whether a later capture needs the source: its handle is the only one that can fork it. */\n readonly needsSource: boolean\n}\n\n/** What cleaning a group of checkpoints left: deletes the provider did not confirm, and\n * checkpoints kept because their files are in no capture. */\ninterface CheckpointCleanup {\n readonly unconfirmed: CheckpointEvent[]\n readonly refused: CaptureRefusal[]\n}\n\n/**\n * Delete checkpoints, each only after its files are captured into the run's content-addressed\n * store; a checkpoint no capture holds is kept, and the cleanup record says why. Only the\n * source-scoped handle can fork a checkpoint and attest its deletion, including after its source\n * is lost. `parent` cancels the captures (the owner's scope during rotation); each provider\n * operation also has its own bound.\n */\nexport async function cleanCheckpoints(\n state: OwnerState,\n branching: AgentWorkspaceBranching | undefined,\n checkpoints: readonly CheckpointEvent[],\n events: readonly SpawnEvent[],\n parent?: AbortSignal,\n): Promise<CheckpointCleanup> {\n const unconfirmed: CheckpointEvent[] = []\n const refused: CaptureRefusal[] = []\n for (const event of checkpoints) {\n const captured = await captureBeforeCleanup(state, branching, event, events, parent)\n if ('reason' in captured) {\n state.captureRefused ??= new Set()\n state.captureRefused.add(event.checkpoint.checkpointId)\n refused.push(captured)\n await state.args.journal.appendEvent(state.args.rootId, {\n kind: 'workspace-checkpoint-cleanup',\n id: state.args.nodeId,\n provider: event.provider,\n environmentId: event.environmentId,\n checkpointId: event.checkpoint.checkpointId,\n confirmed: false,\n refused: captured.reason.slice(0, 1_000),\n seq: state.nextSequence(),\n at: new Date(state.args.now()).toISOString(),\n })\n continue\n }\n state.captureRefused?.delete(event.checkpoint.checkpointId)\n const material = {\n kind: 'checkpoint' as const,\n targetId: event.checkpoint.checkpointId,\n provider: event.checkpoint.provider,\n }\n const request = {\n ...material,\n operationId: `${event.checkpoint.idempotencyKey}:delete`,\n requestDigest: workspaceCleanupRequestDigest(material),\n }\n let confirmed = false\n try {\n if (branching === undefined) throw new Error('source-scoped checkpoint handle unavailable')\n const signal = AbortSignal.timeout(30_000)\n const acknowledgement = await runAbortable(\n () => branching.deleteCheckpoint(request, { signal }),\n signal,\n 'retained owner checkpoint cleanup timed out',\n )\n confirmed =\n workspaceCleanupAcknowledgementMatches(request, acknowledgement) &&\n (acknowledgement.status === 'deleted' || acknowledgement.status === 'already_absent')\n } catch {\n // The journal and settle result retain the unresolved resource below.\n }\n if (!confirmed) unconfirmed.push(event)\n await state.args.journal.appendEvent(state.args.rootId, {\n kind: 'workspace-checkpoint-cleanup',\n id: state.args.nodeId,\n provider: event.provider,\n environmentId: event.environmentId,\n checkpointId: event.checkpoint.checkpointId,\n confirmed,\n capturedDigest: captured.digest,\n seq: state.nextSequence(),\n at: new Date(state.args.now()).toISOString(),\n })\n }\n return { unconfirmed, refused }\n}\n\n/**\n * The digest of the tree that holds a checkpoint's files, capturing it first when no record says\n * one exists, or why it cannot be had. The files are read from a fork of the checkpoint: a box\n * created from the snapshot itself, so the capture is the checkpoint's state and not the live\n * workspace's, which has moved on. The fork request is journaled before it is made and the fork\n * destroyed once the capture is journaled, so neither a failure nor a crash leaves it running\n * unrecorded.\n */\nasync function captureBeforeCleanup(\n state: OwnerState,\n branching: AgentWorkspaceBranching | undefined,\n event: CheckpointEvent,\n events: readonly SpawnEvent[],\n parent?: AbortSignal,\n): Promise<{ readonly digest: Sha256Digest } | CaptureRefusal> {\n const { args } = state\n const checkpointId = event.checkpoint.checkpointId\n const recorded = events.find(\n (prior): prior is CheckpointCaptureEvent =>\n prior.kind === 'workspace-checkpoint-capture' &&\n prior.id === args.nodeId &&\n prior.provider === event.provider &&\n prior.environmentId === event.environmentId &&\n prior.checkpointId === checkpointId,\n )\n if (recorded !== undefined) return { digest: recorded.tree.digest }\n const refuse = (reason: string, needsSource: boolean): CaptureRefusal => ({\n event,\n reason,\n needsSource,\n })\n const capture = state.checkpointCapture\n if (capture?.port.captureCheckpoint === undefined)\n return refuse('no checkpoint capture: the owner backend has no captureCheckpoint', false)\n const provider = state.provider\n if (provider?.get === undefined)\n return refuse('the provider cannot reconstruct a fork of the checkpoint', false)\n const get = provider.get.bind(provider)\n // A bound already spent (the release's, or the owner's cancellation) forks nothing more.\n if (parent?.aborted)\n return refuse(\n `capture failed: ${errorText(signalAbortError(parent, 'capture stopped').message)}`,\n true,\n )\n if (branching === undefined) return refuse('source-scoped checkpoint handle unavailable', true)\n const material = { checkpoint: event.checkpoint, placement: { kind: 'sandbox' as const } }\n // One key per attempt: a fork an earlier attempt destroyed cannot be replayed into this one.\n const request = {\n ...material,\n idempotencyKey: `${event.checkpoint.idempotencyKey}:capture:${state.nextSequence()}`,\n requestDigest: workspaceForkRequestDigest(material),\n }\n let forkEnvironmentId: string | undefined\n let captureEnded = false\n try {\n const tree = await captureProviderCheckpointWorkspace(\n capture.port,\n async (captureSignal) => {\n const forkSignal = AbortSignal.any([\n captureSignal,\n ...(parent === undefined ? [] : [parent]),\n AbortSignal.timeout(WORKSPACE_CHECKPOINT_FORK_TIMEOUT_MS),\n ])\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-checkpoint-fork-requested',\n id: args.nodeId,\n provider: event.provider,\n environmentId: event.environmentId,\n checkpointId,\n idempotencyKey: request.idempotencyKey,\n requestDigest: request.requestDigest,\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n const result = await runAbortable(\n () =>\n branching.fork(request, { signal: forkSignal }).then(async (result) => {\n if (result.status === 'created' || result.status === 'replayed') {\n const forkId = result.environment.environmentId\n if (captureEnded)\n await destroyCaptureFork(state, branching, {\n provider: event.provider,\n environmentId: event.environmentId,\n checkpointId,\n fork: { idempotencyKey: request.idempotencyKey, environmentId: forkId },\n })\n else forkEnvironmentId = forkId\n }\n return result\n }),\n forkSignal,\n 'checkpoint fork timed out',\n )\n if (\n (result.status !== 'created' && result.status !== 'replayed') ||\n !workspaceForkResultMatchesRequest(request, result)\n )\n throw new Error(\n `fork ${result.status}${'message' in result ? `: ${result.message}` : ''}`,\n )\n const forkId = result.environment.environmentId\n const environment = await runAbortable(\n () => get(forkId),\n forkSignal,\n 'checkpoint fork lookup timed out',\n )\n if (\n environment === null ||\n environment.id !== forkId ||\n environment.provider !== provider.name\n )\n throw new Error(`fork ${forkId} could not be reconstructed`)\n parent?.throwIfAborted()\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-checkpoint-fork-ready',\n id: args.nodeId,\n provider: event.provider,\n environmentId: event.environmentId,\n checkpointId,\n fork: { idempotencyKey: request.idempotencyKey, environmentId: forkId },\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n return {\n environment,\n checkpoint: event.checkpoint,\n executionId: `${args.nodeId}:checkpoint:${checkpointId}`,\n profile: capture.profile,\n }\n },\n event.marker,\n parent,\n )\n const forkId = forkEnvironmentId\n if (forkId === undefined) throw new Error('checkpoint capture fork identity missing')\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-checkpoint-capture',\n id: args.nodeId,\n provider: event.provider,\n environmentId: event.environmentId,\n checkpointId,\n fork: { idempotencyKey: request.idempotencyKey, environmentId: forkId },\n tree: {\n digest: tree.digest,\n manifest: tree.manifest,\n files: tree.files,\n bytes: tree.bytes,\n storedBytes: tree.storedBytes,\n },\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n return { digest: tree.digest }\n } catch (error) {\n return refuse(\n `capture failed: ${errorText(error instanceof Error ? error.message : error)}`,\n true,\n )\n } finally {\n captureEnded = true\n if (forkEnvironmentId !== undefined)\n await destroyCaptureFork(state, branching, {\n provider: event.provider,\n environmentId: event.environmentId,\n checkpointId,\n fork: { idempotencyKey: request.idempotencyKey, environmentId: forkEnvironmentId },\n })\n }\n}\n\n/** Destroy a capture's fork and journal whether the provider confirmed it. */\nasync function destroyCaptureFork(\n state: OwnerState,\n branching: AgentWorkspaceBranching,\n target: Pick<ForkTeardownEvent, 'provider' | 'environmentId' | 'checkpointId' | 'fork'>,\n): Promise<boolean> {\n const material = {\n kind: 'fork' as const,\n targetId: target.fork.environmentId,\n provider: target.provider,\n }\n const request = {\n ...material,\n operationId: `${target.fork.idempotencyKey}:destroy`,\n requestDigest: workspaceCleanupRequestDigest(material),\n }\n let destroyed = false\n try {\n const signal = AbortSignal.timeout(30_000)\n const acknowledgement = await runAbortable(\n () => branching.destroyFork(request, { signal }),\n signal,\n 'checkpoint capture fork cleanup timed out',\n )\n destroyed =\n workspaceCleanupAcknowledgementMatches(request, acknowledgement) &&\n (acknowledgement.status === 'deleted' || acknowledgement.status === 'already_absent')\n } catch {\n // Journaled unconfirmed below; the release asks again.\n }\n await state.args.journal.appendEvent(state.args.rootId, {\n kind: 'workspace-checkpoint-fork-teardown',\n id: state.args.nodeId,\n ...target,\n destroyed,\n seq: state.nextSequence(),\n at: new Date(state.args.now()).toISOString(),\n })\n return destroyed\n}\n\n/**\n * Destroy every capture fork the journal does not show destroyed: one a crash left between its\n * request and its teardown, or whose teardown the provider did not confirm. Returns the forks\n * still not confirmed destroyed, by environment or, when none was ever named, by request key.\n */\nexport async function settleCaptureForks(state: OwnerState): Promise<string[]> {\n const { args } = state\n const providerName = state.provider?.name\n const events = ((await args.journal.loadTree(args.rootId)) ?? []).filter(\n (event) => event.id === args.nodeId,\n )\n const named = (key: string): string | undefined => {\n for (const event of events) {\n if (\n (event.kind === 'workspace-checkpoint-capture' ||\n event.kind === 'workspace-checkpoint-fork-teardown') &&\n event.fork.idempotencyKey === key\n )\n return event.fork.environmentId\n }\n return undefined\n }\n const destroyed = new Set(\n events.flatMap((event) =>\n event.kind === 'workspace-checkpoint-fork-teardown' && event.destroyed\n ? [event.fork.idempotencyKey]\n : [],\n ),\n )\n const unresolved: string[] = []\n for (const request of events) {\n if (request.kind !== 'workspace-checkpoint-fork-requested' || request.provider !== providerName)\n continue\n if (destroyed.has(request.idempotencyKey)) continue\n const signal = AbortSignal.timeout(30_000)\n const branching = await checkpointHandle(state, request.environmentId, signal)\n let forkEnvironmentId = named(request.idempotencyKey)\n if (forkEnvironmentId === undefined && branching !== undefined) {\n try {\n const found = await runAbortable(\n () =>\n branching.lookupFork(\n { idempotencyKey: request.idempotencyKey, requestDigest: request.requestDigest },\n { signal },\n ),\n signal,\n 'checkpoint capture fork lookup timed out',\n )\n // No fork was ever created for this request: nothing to destroy.\n if (found.status === 'not_found') continue\n if (found.status === 'found') forkEnvironmentId = found.environment.environmentId\n } catch {\n // Unresolved below.\n }\n }\n if (\n forkEnvironmentId === undefined ||\n branching === undefined ||\n !(await destroyCaptureFork(state, branching, {\n provider: request.provider,\n environmentId: request.environmentId,\n checkpointId: request.checkpointId,\n fork: { idempotencyKey: request.idempotencyKey, environmentId: forkEnvironmentId },\n }))\n )\n unresolved.push(forkEnvironmentId ?? request.idempotencyKey)\n }\n return unresolved\n}\n","import type { AgentProfile, AgentWorkspaceBranching } from '@tangle-network/agent-interface'\nimport type { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider'\nimport type { ProviderWorkspaceRetentionPort } from '../provider-workspace-retention'\nimport type { RetainedRunAdmission, RetainedRunEnvironmentAdmission } from '../retained-run-types'\nimport type { RetainedExecutorContext, RetainedWorkspaceRestore } from './retained-executor'\nimport type {\n ExecutorResult,\n NodeId,\n ResultBlobStore,\n Scope,\n SpawnEvent,\n SpawnJournal,\n UnconfirmedTeardown,\n} from './types'\n\n/** @internal */\nexport interface OwnerState {\n readonly admissions: RetainedRunAdmission[]\n readonly context: RetainedExecutorContext\n readonly args: OwnerRegistration\n inputSequence?: number\n prepared?: boolean\n acceptedConsumed?: boolean\n priorSession?: RetainedRunEnvironmentAdmission\n /** A changed native provider starts a new harness session from a verified checkpoint. */\n forceNewSession?: boolean\n /** `continuation.session: 'fresh'`: a later invocation keeps the environment and starts a new\n * harness session in it. Set on every prepare, so a recovered invocation replays the identity\n * it committed. */\n freshSessions?: boolean\n provider?: AgentEnvironmentProvider\n /** The provider backend captures executable workspace evidence for unsettled owner turns. */\n workspaceRetention: boolean\n /** The owner's current environment id, from its executor's materialization receipt. Set by the\n * drive harness; populated on the retained AND non-retained provider paths, where an\n * `environment` admission exists only on the retained one. */\n liveEnvironmentId?: () => string | undefined\n nextSequence: () => number\n /** Whether the last release left an environment that another release could still destroy: a\n * failed or unanswered destroy, not a source preserved on purpose. */\n releaseRetriable?: boolean\n taskRef?: string\n accepted?: ExecutorResult<unknown>\n acceptedRef?: Extract<SpawnEvent, { kind: 'execution-result' }>\n /** The checkpoint the current invocation's NEW environment starts from, if any. */\n restore?: RetainedWorkspaceRestore\n /** The checkpoint in progress, so two never run at once. */\n checkpointing?: Promise<void>\n checkpointHandles?: Map<string, AgentWorkspaceBranching>\n lastCheckpointAt?: number\n /** Set once checkpoints cannot be taken for this owner, with why; no later call retries. */\n checkpointsUnavailable?: string\n /** Where a checkpoint's files are captured before it is deleted, and the profile its capture\n * names. Bound with the provider; absent when the owner's backend retains no workspace. */\n checkpointCapture?: {\n readonly port: ProviderWorkspaceRetentionPort\n readonly profile: AgentProfile\n }\n /** Checkpoints whose capture failed in this process. Rotation keeps them without forking them\n * again; the release tries each once more. */\n captureRefused?: Set<string>\n /** Cuts short the captures a checkpoint rotation is running, when a turn's own workspace\n * capture starts. */\n rotationCaptures?: AbortController\n /** The drive in progress: from before its executor exists until its turn has ended. */\n drive?: Promise<void>\n /** End-of-turn work a turn handed over: its workspace capture and the evidence of its receipt. */\n turnEnd?: Promise<void>\n /** The release in progress, so a second caller joins it instead of destroying twice. */\n releasing?: Promise<readonly UnconfirmedTeardown[]>\n /** Capture retries of the evidence this node owes, while any is owed; the release stops them. */\n evidenceRetry?: { readonly stop: AbortController; done: Promise<void> }\n}\n\n/** @internal */\nexport interface OwnerRegistration {\n readonly rootId: NodeId\n readonly executionRootId?: NodeId\n readonly nodeId: NodeId\n readonly depth?: number\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly priorEvents: readonly SpawnEvent[]\n readonly now: () => number\n}\n\nexport const owners = new WeakMap<object, OwnerState>()\n\n/** @internal Scope construction carries this private policy to every nested owner scope. */\nexport const retainedOwnerWorkspaceRetentionSeamKey = 'runtime.retainedOwnerWorkspaceRetention'\n\nexport function scopeRetainedOwnerContext(\n scope: Scope<unknown>,\n): RetainedExecutorContext | undefined {\n return owners.get(scope)?.context\n}\n\n/** The journal tree that owns this manager turn, including nested driver children. */\nexport function scopeRetainedOwnerJournalRoot(scope: Scope<unknown>): NodeId | undefined {\n return owners.get(scope)?.args.rootId\n}\n\n/**\n * Bind cleanup before replay can return an already accepted owner result. `checkpointCapture` is\n * where each checkpoint's files are stored before the checkpoint is deleted; without it, no\n * checkpoint of this owner is deleted.\n */\nexport function bindScopeRetainedOwnerProvider(\n scope: Scope<unknown>,\n provider: AgentEnvironmentProvider,\n checkpointCapture?: {\n readonly port: ProviderWorkspaceRetentionPort\n readonly profile: AgentProfile\n },\n): void {\n const state = owners.get(scope)\n if (state === undefined) return\n state.provider = provider\n if (checkpointCapture !== undefined) state.checkpointCapture = checkpointCapture\n}\n\n/** Bind the owner cleanup policy selected by its provider executor. */\nexport function bindScopeRetainedOwnerWorkspaceRetention(\n scope: Scope<unknown>,\n enabled: boolean,\n): void {\n const state = owners.get(scope)\n if (state) state.workspaceRetention = enabled\n}\n\n/**\n * Bind where the owner's CURRENT environment id can be read from. The drive harness supplies a\n * resolver over its active executor's materialization receipt, which every provider path\n * publishes once the environment exists. The `environment` admission is written only on the\n * retained path, and the production tangle provider declares no `retainedControl`, so a reader\n * that scanned admissions alone would refuse every read on a real sandbox root while looking\n * correct in every test that uses the retained fixture.\n */\nexport function bindScopeRetainedOwnerEnvironmentId(\n scope: Scope<unknown>,\n liveEnvironmentId: () => string | undefined,\n): void {\n const state = owners.get(scope)\n if (state) state.liveEnvironmentId = liveEnvironmentId\n}\n","import {\n workspaceCheckpointRequestDigest,\n workspaceCheckpointResultMatchesRequest,\n} from '@tangle-network/agent-interface'\nimport { runAbortable } from './abortable'\nimport { cleanCheckpoints } from './retained-owner-checkpoint-capture'\nimport { type CheckpointEvent, pendingCheckpoints } from './retained-owner-checkpoint-requests'\nimport { type OwnerState, owners } from './retained-owner-state'\nimport type { Scope, WorkspaceCheckpointMarker } from './types'\nimport {\n WORKSPACE_CHECKPOINT_MARKER_PATH,\n WORKSPACE_CHECKPOINT_MIN_INTERVAL_MS,\n WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS,\n WORKSPACE_CHECKPOINT_TIMEOUT_MS,\n WORKSPACE_CHECKPOINTS_KEPT,\n writeWorkspaceMarker,\n} from './workspace-checkpoint'\n\n/**\n * Note that the owner's manager made a coordination call, and checkpoint its workspace when the\n * last checkpoint is older than {@link WORKSPACE_CHECKPOINT_MIN_INTERVAL_MS}.\n *\n * A coordination call is where a manager commits work: it spawns, waits for, reads, or submits.\n * The checkpoint runs in the background and never delays the call. A failed checkpoint leaves the\n * previous one as the restore point; a provider or environment that cannot checkpoint stops the\n * attempts for this owner.\n */\nexport function noteScopeRetainedOwnerCoordination(scope: Scope<unknown>): void {\n const state = owners.get(scope)\n if (state?.provider === undefined || state.checkpointsUnavailable !== undefined) return\n // No rotation starts while a turn's handed-over capture is still running.\n if (state.checkpointing !== undefined || state.turnEnd !== undefined || scope.signal.aborted)\n return\n const now = state.args.now()\n if (\n state.lastCheckpointAt !== undefined &&\n now - state.lastCheckpointAt < WORKSPACE_CHECKPOINT_MIN_INTERVAL_MS\n )\n return\n state.lastCheckpointAt = now\n state.checkpointing = checkpointOwnerWorkspace(scope, state)\n .catch(() => undefined)\n .finally(() => {\n delete state.checkpointing\n })\n}\n\n/** @internal The checkpoint in progress for this owner, for a test or a release to wait on. */\nexport function scopeRetainedOwnerCheckpointing(scope: Scope<unknown>): Promise<void> | undefined {\n return owners.get(scope)?.checkpointing\n}\n\nexport async function checkpointOwnerWorkspace(\n scope: Scope<unknown>,\n state: OwnerState,\n): Promise<void> {\n const { provider, args } = state\n if (provider === undefined) return\n if (!provider.get) {\n state.checkpointsUnavailable = `provider ${provider.name} cannot reconstruct an environment`\n return\n }\n // A checkpoint no create can restore is storage for nothing.\n if ((await provider.capabilities()).create?.workspaceCheckpoint !== true) {\n state.checkpointsUnavailable = `provider ${provider.name} cannot create an environment from a checkpoint`\n return\n }\n const dispatched = [...state.admissions]\n .reverse()\n .find((admission) => admission.phase === 'dispatched')\n if (dispatched?.phase !== 'dispatched') return\n const source = dispatched.controlRef\n const signal = AbortSignal.any([\n scope.signal,\n AbortSignal.timeout(WORKSPACE_CHECKPOINT_TIMEOUT_MS),\n ])\n const get = provider.get.bind(provider)\n const environment = await runAbortable(\n () => get(source.environmentId),\n signal,\n 'retained owner checkpoint timed out',\n )\n if (\n environment === null ||\n environment.id !== source.environmentId ||\n environment.provider !== provider.name\n )\n return\n const branching = environment.workspaceBranching\n if (branching === undefined) {\n state.checkpointsUnavailable = `environment ${environment.id} offers no durable checkpoint`\n return\n }\n const seq = state.nextSequence()\n const at = new Date(args.now()).toISOString()\n const name = `owner-checkpoint-${seq}`\n const marker: WorkspaceCheckpointMarker = {\n path: WORKSPACE_CHECKPOINT_MARKER_PATH,\n content: `${JSON.stringify({ node: args.nodeId, checkpoint: name, at })}\\n`,\n }\n const marked = await writeWorkspaceMarker(environment, marker, signal)\n const material = { source, name }\n const request = {\n ...material,\n idempotencyKey: `${args.nodeId}:workspace-checkpoint:${seq}`,\n requestDigest: workspaceCheckpointRequestDigest(material),\n }\n state.checkpointHandles ??= new Map()\n state.checkpointHandles.set(environment.id, branching)\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-checkpoint-requested',\n id: args.nodeId,\n provider: provider.name,\n environmentId: environment.id,\n request,\n ...(marked ? { marker } : {}),\n seq,\n at,\n })\n const result = await runAbortable(\n () => branching.checkpoint(request, { signal }),\n signal,\n 'retained owner checkpoint timed out',\n )\n if (result.status !== 'created' && result.status !== 'replayed') return\n if (!workspaceCheckpointResultMatchesRequest(request, result)) return\n scope.signal.throwIfAborted()\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-checkpoint',\n id: args.nodeId,\n provider: provider.name,\n environmentId: environment.id,\n checkpoint: result.checkpoint,\n ...(marked ? { marker } : {}),\n seq: state.nextSequence(),\n at,\n })\n const events = (await args.journal.loadTree(args.rootId)) ?? []\n const owned = pendingCheckpoints(events, state).filter(\n (event): event is CheckpointEvent =>\n event.environmentId === environment.id &&\n state.captureRefused?.has(event.checkpoint.checkpointId) !== true,\n )\n // The capture forks a box and reads its whole workspace, so it is bounded by its own budget and\n // the turn's workspace capture, never by this checkpoint's bound. A capture cut short keeps its\n // checkpoint, and the release captures it again.\n const rotation = new AbortController()\n state.rotationCaptures = rotation\n const timer = setTimeout(\n () =>\n rotation.abort(\n new Error(\n `the rotation's ${WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS} ms for checkpoint captures ran out; checkpoint kept`,\n ),\n ),\n WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS,\n )\n try {\n await cleanCheckpoints(\n state,\n branching,\n owned.slice(0, -WORKSPACE_CHECKPOINTS_KEPT),\n events,\n AbortSignal.any([scope.signal, rotation.signal]),\n )\n } finally {\n clearTimeout(timer)\n if (state.rotationCaptures === rotation) delete state.rotationCaptures\n }\n}\n\n/**\n * The owner's workspace-capture journal writers. A turn's capture starting cuts short the\n * checkpoint rotation's captures: on Discovery canary test-acceptance-canary-20261019j (Runtime\n * 0.327.0) a rotation capture of an older checkpoint started 4 s before the root's final capture,\n * on the same evidence store, and the final capture spent 26.6 of its 32.6 minutes storing its\n * archive until the root's budget deadline aborted the rotation.\n */\n","/** Retained-owner capture receipts, source verification before reuse, and accepted-turn evidence debt. */\nimport {\n type AgentExactRunControlRef,\n AgentExactRunControlRefSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n canonicalAgentProfileDigest,\n} from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport {\n captureProviderWorkspaceSnapshot,\n workspaceCaptureReceipt,\n} from '../provider-workspace-retention'\nimport { sameControlCoordinates } from '../retained-run-binding'\nimport type { RetainedRunAdmission, RetainedRunEnvironmentAdmission } from '../retained-run-types'\nimport { sleep } from '../util'\nimport { runAbortable } from './abortable'\nimport { executorFailureReason } from './executor-outcome'\nimport { RetainedExecutionPendingError } from './retained-executor'\nimport type { OwnerRegistration, OwnerState } from './retained-scope-owner'\nimport type {\n ExecutionBindingReceipt,\n ExecutorNodeContext,\n NodeId,\n ResultBlobStore,\n SpawnEvent,\n} from './types'\n\ninterface OwnerAttempt {\n readonly environmentIds: Set<string>\n readonly executionId?: string\n readonly workspaceRetention?: boolean\n readonly admissions: RetainedRunAdmission[]\n readonly controlByEnvironment: Map<string, AgentExactRunControlRef>\n binding?: ExecutionBindingReceipt\n result?: Extract<SpawnEvent, { kind: 'execution-result' }>\n /** Captures retained as evidence of this attempt: the capture a turn handed over after its\n * result, or the capture of a turn that failed. */\n readonly evidence: Array<Extract<SpawnEvent, { kind: 'execution-evidence' }>>\n}\n\n/** One grouping for release and the evidence gate before another owner invocation. */\nfunction ownerWorkspaceAttempts(events: readonly SpawnEvent[], nodeId: NodeId): OwnerAttempt[] {\n const attempts: OwnerAttempt[] = []\n let current: OwnerAttempt | undefined\n const flush = (): void => {\n if (current !== undefined) attempts.push(current)\n current = undefined\n }\n const fresh = (executionId?: string, workspaceRetention?: boolean): OwnerAttempt => ({\n workspaceRetention,\n admissions: [],\n ...(executionId === undefined ? {} : { executionId }),\n environmentIds: new Set<string>(),\n controlByEnvironment: new Map(),\n evidence: [],\n })\n for (const event of events) {\n if (!('id' in event) || event.id !== nodeId) continue\n if (event.kind === 'execution-input') {\n flush()\n current = fresh(`${nodeId}:input:${event.seq}`, event.workspaceRetention)\n } else if (event.kind === 'execution-admitted' && event.admission.phase === 'environment') {\n if (current?.result !== undefined) flush()\n current ??= fresh()\n current.environmentIds.add(event.admission.environmentId)\n current.admissions.push(event.admission)\n } else if (event.kind === 'execution-admitted' && event.admission.phase === 'dispatched') {\n current?.admissions.push(event.admission)\n current?.controlByEnvironment.set(\n event.admission.controlRef.environmentId,\n event.admission.controlRef,\n )\n } else if (event.kind === 'execution-admitted') {\n current?.admissions.push(event.admission)\n } else if (event.kind === 'execution-bound') {\n // A later coordinator may finalize without running another invocation. Its bookkeeping\n // binding cannot rename the provider attempt whose result was already accepted.\n if (current !== undefined && current.result === undefined) current.binding = event.binding\n } else if (event.kind === 'execution-result') {\n current ??= fresh()\n current.result = event\n } else if (event.kind === 'execution-evidence') {\n current?.evidence.push(event)\n }\n }\n flush()\n return attempts\n}\n\n/**\n * Group owner admissions by input and require a verified workspace receipt before deletion.\n *\n * The receipt is the attempt's committed result, or an evidence record of the same attempt: a\n * turn its manager stopped commits its result first and journals its capture as evidence after\n * it, and a turn that failed journals the capture it took of the stopped session. A root capture\n * failure can enter this cleanup barrier and still be resumed, so any receipt refused before\n * reuse must also preserve its source here.\n */\nexport async function ownerWorkspaceRetentionFailures(\n events: readonly SpawnEvent[],\n owner: OwnerRegistration,\n retainedOnly = false,\n): Promise<ReadonlySet<string>> {\n const attempts = ownerWorkspaceAttempts(events, owner.nodeId)\n const failures = new Set<string>()\n for (const index of attempts.keys()) {\n const attempt = withLaterEvidence(attempts, index)\n if (retainedOnly && attempt.workspaceRetention !== true) continue\n if (attempt.environmentIds.size === 0) continue\n // One result receipt cannot prove which source belongs to which environment when a\n // recovered attempt admitted more than one. Preserve every source until a later run can\n // establish a one-to-one receipt rather than guessing from a shared result.\n if (attempt.environmentIds.size > 1) {\n for (const environmentId of attempt.environmentIds) failures.add(environmentId)\n continue\n }\n const environmentId = [...attempt.environmentIds][0]!\n const verified = await ownerAttemptHasCapture(\n attempt,\n environmentId,\n owner.blobs,\n attempt.workspaceRetention === true ? owner : undefined,\n )\n if (!verified) failures.add(environmentId)\n }\n return failures\n}\n\n/**\n * The attempt with the evidence journaled after it. A release's capture of a preserved source is\n * journaled after later invocations began; every receipt names its exact execution, environment\n * and control reference, so a receipt of another attempt never verifies this one.\n */\nfunction withLaterEvidence(attempts: readonly OwnerAttempt[], index: number): OwnerAttempt {\n const attempt = attempts[index]!\n const later = attempts.slice(index + 1).flatMap((next) => next.evidence)\n return later.length === 0 ? attempt : { ...attempt, evidence: [...attempt.evidence, ...later] }\n}\n\nasync function ownerAttemptHasCapture(\n attempt: OwnerAttempt,\n environmentId: string,\n blobs: ResultBlobStore,\n owner?: OwnerRegistration,\n allowPartialProcessCapture = false,\n): Promise<boolean> {\n const controlRef = attempt.controlByEnvironment.get(environmentId)\n const receipts = [\n ...(attempt.result === undefined || attempt.result.outputFormat === 'json'\n ? []\n : [attempt.result.outRef]),\n ...attempt.evidence.map((event) => event.outRef),\n ]\n let verified = false\n for (const outRef of receipts) {\n const output = await storedOutput(blobs, outRef)\n const snapshot =\n output !== null && typeof output === 'object'\n ? (output as { readonly workspaceSnapshot?: unknown }).workspaceSnapshot\n : undefined\n if (\n hasDurableWorkspaceCapture(\n output,\n snapshot,\n environmentId,\n attempt.executionId,\n controlRef,\n owner === undefined ? undefined : ownerCaptureIdentity(attempt, owner),\n allowPartialProcessCapture,\n )\n ) {\n verified = true\n break\n }\n }\n return verified\n}\n\nfunction ownerCaptureIdentity(attempt: OwnerAttempt, owner: OwnerRegistration) {\n const intent = attempt.admissions.find((admission) => admission.phase === 'intent')\n const node: ExecutorNodeContext | undefined =\n attempt.binding === undefined\n ? undefined\n : {\n rootId: owner.executionRootId ?? owner.rootId,\n parentId: owner.nodeId,\n nodeId: owner.nodeId,\n ...(owner.depth === undefined ? {} : { depth: owner.depth }),\n attemptId: attempt.binding.attemptId,\n }\n return { profileDigest: intent?.requestedProfileDigest, node }\n}\n\n/** Recover evidence before reuse. Failed unverified turns keep their invocation; accepted turns owe evidence. */\nexport async function reconcileOwnerWorkspaceBeforeReuse(\n state: OwnerState,\n signal: AbortSignal,\n): Promise<ReadonlySet<string>> {\n const { args } = state\n const indebted = new Set<string>()\n const events = (await args.journal.loadTree(args.rootId)) ?? []\n const attempts = ownerWorkspaceAttempts(events, args.nodeId)\n const latest = attempts.at(-1)\n const unusable = unusableEnvironmentIds(events.filter((event) => event.id === args.nodeId))\n if (latest === undefined) return indebted\n const reusing = new Set(latest.environmentIds)\n if (latest.result === undefined && state.priorSession !== undefined)\n reusing.add(state.priorSession.environmentId)\n for (const [index, attempt] of attempts.entries()) {\n // The obligation is what the invocation persisted, never today's backend configuration.\n if (attempt.workspaceRetention !== true || attempt.result === undefined) continue\n for (const environmentId of attempt.environmentIds) {\n if (!reusing.has(environmentId) || unusable.has(environmentId)) continue\n // A verified workspace may continue in its retained environment even when Sandbox lost\n // only raw process I/O. The partial receipt stays journaled and cleanup remains strict.\n if (await ownerAttemptHasCapture(attempt, environmentId, args.blobs, args, true)) continue\n try {\n await captureOwnerSource(state, attempts, index, environmentId, signal)\n } catch (cause) {\n const failure = capturePendingMessage(attempt.executionId ?? args.nodeId, cause)\n if (executorFailureReason(attempt.result) === undefined) {\n await owePendingEvidence(state, events, attempt, environmentId, failure)\n } else {\n await state.context.onEvidence!({\n executionId: attempt.executionId,\n environmentId,\n controlRef: attempt.controlByEnvironment.get(environmentId),\n ...ownerCaptureIdentity(attempt, args),\n workspaceCaptureFailure: failure,\n })\n // Preserve this failed invocation's admissions until its source is verified.\n throw new RetainedExecutionPendingError(new Error(failure, { cause }), 'unobservable')\n }\n indebted.add(environmentId)\n state.forceNewSession = true\n }\n }\n }\n return indebted\n}\n\nfunction capturePendingMessage(executionId: string, cause: unknown): string {\n return `retained workspace capture pending for ${executionId}; source environment preserved: ${cause instanceof Error ? cause.message : String(cause)}`\n}\n\n/**\n * Record an accepted turn's failed capture as evidence debt, once per source, and start the\n * owner's capture retries. The node continues in another environment and the source is never\n * mutated, so the debt holds only the evidence, never the run.\n *\n * Throwing here instead leaves nothing driving any agent of the run, and every restart meets the\n * same failure: 66 supervisor starts in 17 Discovery runs, 76.7 wall-hours dead, between\n * 2026-10-12 and 2026-10-19 (magnetar-rust-20261016b, 24 starts on \"This Platform key has\n * expired\").\n */\nasync function owePendingEvidence(\n state: OwnerState,\n events: readonly SpawnEvent[],\n attempt: OwnerAttempt,\n environmentId: string,\n failure: string,\n): Promise<void> {\n const { args } = state\n const owed = events.some(\n (event) =>\n event.kind === 'evidence-pending' &&\n event.id === args.nodeId &&\n event.environmentId === environmentId,\n )\n if (!owed) {\n const at = new Date(args.now()).toISOString()\n await args.journal.appendEvent(args.rootId, {\n kind: 'evidence-pending',\n id: args.nodeId,\n environmentId,\n ...(attempt.executionId === undefined ? {} : { executionId: attempt.executionId }),\n error: failure,\n since: at,\n seq: state.nextSequence(),\n at,\n })\n }\n retryOwnerEvidence(state)\n}\n\n/** How capture retries of owed evidence back off, measured on the run's clock. */\nconst EVIDENCE_RETRY_BACKOFF_MS = { initial: 30_000, max: 5 * 60_000 } as const\n/** How often the retry loop reads the run's clock. Reading it costs no provider call. */\nconst EVIDENCE_RETRY_TICK_MS = 1_000\n\n/**\n * Retry the captures this node owes while the supervisor lives, backing off from\n * {@link EVIDENCE_RETRY_BACKOFF_MS}'s `initial` to its `max`. One loop per owner; it ends when\n * nothing is owed or the release stops it, and the release tries once more itself.\n */\nexport function retryOwnerEvidence(state: OwnerState): void {\n if (state.evidenceRetry !== undefined || state.releasing !== undefined) return\n const stop = new AbortController()\n const retry: { stop: AbortController; done: Promise<void> } = { stop, done: Promise.resolve() }\n retry.done = (async () => {\n let backoff: number = EVIDENCE_RETRY_BACKOFF_MS.initial\n let dueAt = state.args.now() + backoff\n while (!stop.signal.aborted) {\n await sleep(EVIDENCE_RETRY_TICK_MS, stop.signal, false)\n if (stop.signal.aborted || state.args.now() < dueAt) continue\n if ((await payOwedEvidence(state, stop.signal)) === 0) return\n backoff = Math.min(backoff * 2, EVIDENCE_RETRY_BACKOFF_MS.max)\n dueAt = state.args.now() + backoff\n }\n })()\n .catch(() => undefined)\n .finally(() => {\n if (state.evidenceRetry === retry) delete state.evidenceRetry\n })\n state.evidenceRetry = retry\n}\n\n/** Stop the owner's capture retries and wait for the one in flight. */\nexport async function stopOwnerEvidenceRetry(state: OwnerState): Promise<void> {\n const retry = state.evidenceRetry\n if (retry === undefined) return\n retry.stop.abort(new Error('the owner settled'))\n await retry.done\n}\n\n/**\n * Capture each source this node still owes evidence for, from its `evidence-pending` rows. A\n * receipt journaled by the capture pays the debt. A source no capture can pay any more (gone,\n * without an exact execution, or admitted by a later invocation) is left to the release, which\n * keeps it. Returns how many sources are still owed and payable.\n */\nasync function payOwedEvidence(state: OwnerState, signal: AbortSignal): Promise<number> {\n const { args } = state\n const events = (await args.journal.loadTree(args.rootId)) ?? []\n const attempts = ownerWorkspaceAttempts(events, args.nodeId)\n const unusable = unusableEnvironmentIds(events.filter((event) => event.id === args.nodeId))\n let owed = 0\n for (const row of events) {\n if (row.kind !== 'evidence-pending' || row.id !== args.nodeId) continue\n if (unusable.has(row.environmentId)) continue\n const index = attempts.findIndex((attempt) => attempt.executionId === row.executionId)\n if (index < 0 || row.executionId === undefined) continue\n if (attempts.slice(index + 1).some((later) => later.environmentIds.has(row.environmentId)))\n continue\n const attempt = withLaterEvidence(attempts, index)\n if (await ownerAttemptHasCapture(attempt, row.environmentId, args.blobs, args, true)) continue\n if (signal.aborted) return owed + 1\n try {\n await captureOwnerSource(state, attempts, index, row.environmentId, signal)\n } catch {\n owed += 1\n }\n }\n return owed\n}\n\n/**\n * Capture the workspace an accepted turn left in its retained source and journal the receipt.\n * Throws when the capture cannot be certified for that exact attempt.\n */\nasync function captureOwnerSource(\n state: OwnerState,\n attempts: readonly OwnerAttempt[],\n index: number,\n environmentId: string,\n signal: AbortSignal,\n): Promise<void> {\n const { args } = state\n const attempt = attempts[index]!\n if (attempt.environmentIds.size !== 1 || attempt.executionId === undefined) {\n throw new Error('accepted workspace has ambiguous admission identity')\n }\n // A later invocation in another environment leaves this source as the turn left it.\n if (attempts.slice(index + 1).some((later) => later.environmentIds.has(environmentId))) {\n throw new Error(\n 'a later invocation already admitted this environment; historical workspace cannot be recaptured',\n )\n }\n const capture = state.checkpointCapture\n const provider = state.provider\n const intent = attempt.admissions.find((admission) => admission.phase === 'intent')\n const admission = attempt.admissions.find((admission) => admission.phase === 'environment')\n const dispatched = attempt.admissions.find((admission) => admission.phase === 'dispatched')\n if (\n capture === undefined ||\n provider?.get === undefined ||\n intent?.phase !== 'intent' ||\n admission?.phase !== 'environment' ||\n dispatched?.phase !== 'dispatched'\n ) {\n throw new Error('accepted workspace recovery requires its retention port and exact admissions')\n }\n const controlRef = dispatched.controlRef\n if (\n provider.name !== intent.provider ||\n admission.provider !== intent.provider ||\n controlRef.provider !== intent.provider ||\n admission.environmentId !== controlRef.environmentId ||\n admission.sessionId !== controlRef.sessionId ||\n admission.executionId !== controlRef.executionId ||\n admission.idempotencyKey !== intent.idempotencyKey ||\n dispatched.idempotencyKey !== intent.idempotencyKey ||\n admission.sessionId !== intent.sessionId ||\n admission.executionId !== intent.executionId ||\n admission.turnId !== intent.turnId ||\n dispatched.turnId !== intent.turnId ||\n canonicalAgentProfileDigest(capture.profile) !== intent.requestedProfileDigest\n ) {\n throw new Error('accepted workspace recovery does not match its original profile or admission')\n }\n // The lookup shares the retention port's bound. A box idle 21 minutes took over 30 s to\n // answer in test-acceptance-canary-20261018h, and a fixed 30 s cap left its accepted\n // workspace pending and the resumed supervisor exited. A timeout says what timed out.\n const lookupMs = capture.port.timeoutMs\n const lookupBound = AbortSignal.timeout(lookupMs)\n const environment = await runAbortable(\n () => provider.get!(environmentId),\n AbortSignal.any([signal, lookupBound]),\n 'accepted workspace source lookup aborted',\n ).catch((error: unknown) => {\n if (lookupBound.aborted && !signal.aborted) {\n throw new Error(`accepted workspace source lookup timed out after ${lookupMs} ms`)\n }\n throw error\n })\n if (\n environment === null ||\n environment.id !== environmentId ||\n environment.provider !== provider.name\n )\n throw new Error('accepted workspace source is unavailable')\n const identity = ownerCaptureIdentity(attempt, args)\n const context = {\n environment,\n executionId: attempt.executionId,\n controlRef,\n providerSessionId: controlRef.sessionId,\n nativeSessionId: null,\n profile: capture.profile,\n ...(identity.node === undefined ? {} : { node: identity.node }),\n }\n const captured = await runAbortable(\n () => captureProviderWorkspaceSnapshot(capture.port, context),\n signal,\n 'accepted workspace capture aborted',\n )\n const output = {\n workspaceSnapshot: captured.snapshot,\n workspaceCapture: workspaceCaptureReceipt(context, captured),\n }\n // Partial or foreign captures never authorize mutation, even with a permissive port.\n if (\n !hasDurableWorkspaceCapture(\n output,\n captured.snapshot,\n environmentId,\n attempt.executionId,\n controlRef,\n identity,\n true,\n )\n )\n throw new Error(captured.incompleteReason ?? 'accepted workspace capture is incomplete')\n await state.context.onEvidence!(output)\n}\n\n/**\n * Before a release, try once more to capture each source preserved for a missing receipt of an\n * accepted turn, so a capture fault that has cleared settles the evidence debt and frees its\n * source. A source whose capture fails again is kept for evidence.\n */\nexport async function recaptureOwnerSources(state: OwnerState, signal: AbortSignal): Promise<void> {\n const { args } = state\n if (state.checkpointCapture === undefined || state.provider?.get === undefined) return\n const events = (await args.journal.loadTree(args.rootId)) ?? []\n const owned = events.filter((event) => event.id === args.nodeId)\n const attempts = ownerWorkspaceAttempts(events, args.nodeId)\n const unusable = unusableEnvironmentIds(owned)\n for (const index of attempts.keys()) {\n const attempt = withLaterEvidence(attempts, index)\n if (attempt.workspaceRetention !== true || attempt.result === undefined) continue\n if (executorFailureReason(attempt.result) !== undefined) continue\n for (const environmentId of attempt.environmentIds) {\n if (unusable.has(environmentId)) continue\n if (await ownerAttemptHasCapture(attempt, environmentId, args.blobs, args)) continue\n if (signal.aborted) return\n try {\n await captureOwnerSource(state, attempts, index, environmentId, signal)\n } catch {\n // The source stays preserved and the release names it as kept for evidence.\n }\n }\n }\n}\n\n/** A stored output whose bytes match its content reference, or undefined. */\nasync function storedOutput(blobs: ResultBlobStore, outRef: string): Promise<unknown | undefined> {\n try {\n const output = await blobs.get(outRef)\n return output === undefined || contentAddress(output) !== outRef ? undefined : output\n } catch {\n return undefined\n }\n}\n\n/** A stored result authorizes cleanup only for the exact source and complete capture. */\nfunction hasDurableWorkspaceCapture(\n output: unknown,\n snapshot: unknown,\n environmentId: string,\n executionId: string | undefined,\n controlRef: AgentExactRunControlRef | undefined,\n identity?: ReturnType<typeof ownerCaptureIdentity>,\n allowPartialProcessCapture = false,\n): boolean {\n const parsed = agentCandidateWorkspaceSnapshotEvidenceSchema.safeParse(snapshot)\n if (\n !parsed.success ||\n !('locator' in parsed.data.manifest) ||\n !('locator' in parsed.data.archive)\n )\n return false\n if (output === null || typeof output !== 'object') return false\n const capture = (output as { readonly workspaceCapture?: unknown }).workspaceCapture\n if (capture === null || typeof capture !== 'object') return false\n const receipt = capture as Record<string, unknown>\n // Both reuse and release check persisted invocation identity. Release retains the older\n // receipt contract only for legacy inputs without a persisted retention obligation.\n if (\n identity !== undefined &&\n (identity.profileDigest === undefined ||\n receipt.profileDigest !== identity.profileDigest ||\n (identity.node === undefined\n ? receipt.node !== undefined\n : receipt.node === undefined ||\n contentAddress(receipt.node) !== contentAddress(identity.node)))\n )\n return false\n const capturedControl = AgentExactRunControlRefSchema.safeParse(receipt.controlRef)\n if (\n executionId === undefined ||\n controlRef === undefined ||\n !capturedControl.success ||\n !sameControlCoordinates(capturedControl.data, controlRef) ||\n receipt.environmentId !== environmentId ||\n receipt.executionId !== executionId ||\n (receipt.coverageComplete !== true &&\n !(allowPartialProcessCapture && hasOnlyRawProcessCaptureGap(receipt)))\n )\n return false\n const linked = agentCandidateWorkspaceSnapshotEvidenceSchema.safeParse(receipt.snapshot)\n return (\n linked.success &&\n linked.data.digest === parsed.data.digest &&\n JSON.stringify(linked.data.manifest) === JSON.stringify(parsed.data.manifest) &&\n JSON.stringify(linked.data.archive) === JSON.stringify(parsed.data.archive)\n )\n}\n\n/**\n * A process I/O gap does not invalidate a verified workspace archive or the live environment\n * that owns it. This narrow exception is for continuation only: release still requires complete\n * capture. The reason is assembled by captureProviderWorkspaceSnapshot after identity, inventory,\n * and archive checks, so any other gap keeps the accepted turn pending.\n */\nfunction hasOnlyRawProcessCaptureGap(receipt: Record<string, unknown>): boolean {\n const reason = receipt.incompleteReason\n const prefix = 'provider workspace retention coverage incomplete: '\n if (typeof reason !== 'string' || !reason.startsWith(prefix)) return false\n const provenance = receipt.provenance\n if (provenance === null || typeof provenance !== 'object') return false\n const reported = provenance as Record<string, unknown>\n const workspace = reported.workspace\n if (\n reported.status !== 'reported' ||\n workspace === null ||\n typeof workspace !== 'object' ||\n (workspace as Record<string, unknown>).complete !== true\n )\n return false\n const sessions = reported.sessions\n if (\n !Array.isArray(sessions) ||\n !sessions.some(\n (session) =>\n session !== null &&\n typeof session === 'object' &&\n session.processStreams?.complete === false,\n )\n )\n return false\n const allowed = [\n /^process_(?:io_missing|io_unavailable|source_unavailable)(?::[\\w-]+)?$/,\n /^Sandbox session [\\w-]+ declared partial raw capture$/,\n /^Sandbox session [\\w-]+ attempt [\\w-]+\\/\\d+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\\w-]+)?$/,\n /^Sandbox session [\\w-]+ has no original process source: [\\w-]+$/,\n /^Sandbox session [\\w-]+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\\w-]+)?$/,\n /^Raw native session capture for Sandbox session [\\w-]+ is unavailable: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\\w-]+)?$/,\n /^Session [\\w-]+ process streams incomplete$/,\n /^Attempt [\\w-]+\\/\\d+: process_(?:io_missing|io_unavailable|source_unavailable)(?::[\\w-]+)?$/,\n ]\n const gaps = reason.slice(prefix.length).split('; ')\n return gaps.length > 0 && gaps.every((gap) => allowed.some((pattern) => pattern.test(gap)))\n}\n\n/** Environments that cannot execute another turn, whether absent or terminal at the provider. */\nexport function unusableEnvironmentIds(owned: readonly SpawnEvent[]): ReadonlySet<string> {\n return new Set(\n owned.flatMap((event) =>\n event.kind === 'environment-terminal' ||\n (event.kind === 'environment-teardown' && event.destroyed)\n ? [event.environmentId]\n : [],\n ),\n )\n}\n\n/**\n * After {@link reconcileOwnerWorkspaceBeforeReuse}: an unfinished input an older coordinator\n * admitted into a source now owed evidence, but never dispatched there, is abandoned. Replaying\n * it would mutate the source, so the next drive is a new invocation in another environment. A\n * dispatch lost before its admission was journaled cannot be ruled out, so the outcome is\n * uncertain.\n */\nexport async function abandonInputAdmittedIntoDebt(\n state: OwnerState,\n indebted: ReadonlySet<string>,\n): Promise<void> {\n const { args } = state\n const pending = state.admissions.find(\n (admission): admission is RetainedRunEnvironmentAdmission =>\n admission.phase === 'environment' && indebted.has(admission.environmentId),\n )\n if (\n pending === undefined ||\n state.admissions.some((admission) => admission.phase === 'dispatched')\n )\n return\n await args.journal.appendEvent(args.rootId, {\n kind: 'execution-abandoned',\n id: args.nodeId,\n inputSeq: state.inputSequence!,\n pendingCause: 'unobservable',\n failures: 1,\n detail: `admitted into ${pending.environmentId}, whose workspace capture is pending; never dispatched there`,\n outcome: 'uncertain',\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n delete state.inputSequence\n delete state.taskRef\n state.admissions.length = 0\n}\n","import type { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider'\nimport { ValidationError } from '../../errors'\nimport { ENVIRONMENT_LOOKUP_TIMEOUT_MS } from '../retained-interactive-lifecycle'\nimport type { RetainedRunEnvironmentAdmission } from '../retained-run-types'\nimport { runAbortable } from './abortable'\nimport type { CheckpointEvent } from './retained-owner-checkpoint-requests'\nimport { unusableEnvironmentIds } from './retained-owner-evidence'\nimport { owners } from './retained-owner-state'\nimport type { Scope, SpawnEvent } from './types'\n\nexport function restoreBefore(\n owned: readonly SpawnEvent[],\n inputIndex: number,\n): CheckpointEvent | undefined {\n const unusable = unusableEnvironmentIds(owned)\n return owned\n .slice(0, inputIndex < 0 ? owned.length : inputIndex)\n .filter(\n (event): event is CheckpointEvent =>\n event.kind === 'workspace-checkpoint' && unusable.has(event.environmentId),\n )\n .at(-1)\n}\n\nexport async function restoreCapable(\n provider: AgentEnvironmentProvider | undefined,\n): Promise<boolean> {\n if (provider === undefined) return false\n try {\n return (await provider.capabilities()).create?.workspaceCheckpoint === true\n } catch {\n return false\n }\n}\n\n/** The verified checkpoint the next new environment starts from, if any. */\nexport async function scopeRetainedOwnerRestorePoint(scope: Scope<unknown>): Promise<\n | {\n readonly checkpointId: string\n readonly takenAt: string\n readonly sourceEnvironmentId: string\n }\n | undefined\n> {\n const state = owners.get(scope)\n if (state === undefined || !(await restoreCapable(state.provider))) return undefined\n const owned = ((await state.args.journal.loadTree(state.args.rootId)) ?? []).filter(\n (event) => event.id === state.args.nodeId,\n )\n const latest = restoreBefore(owned, -1)\n return latest === undefined\n ? undefined\n : {\n checkpointId: latest.checkpoint.checkpointId,\n takenAt: latest.at,\n sourceEnvironmentId: latest.checkpoint.source.environmentId,\n }\n}\n\nexport function continuedEnvironment(\n owned: readonly SpawnEvent[],\n): { readonly admission: RetainedRunEnvironmentAdmission; readonly inFlight: boolean } | undefined {\n const latestInput = [...owned].reverse().find((event) => event.kind === 'execution-input')\n if (latestInput === undefined) return undefined\n const attempt = owned.slice(owned.indexOf(latestInput))\n const admission = [...owned]\n .reverse()\n .flatMap((event) =>\n event.kind === 'execution-admitted' && event.admission.phase === 'environment'\n ? [event.admission]\n : [],\n )[0]\n if (admission === undefined) return undefined\n return { admission, inFlight: !attempt.some((event) => event.kind === 'execution-result') }\n}\n\n/** What the owner's next invocation continues, read before it starts. */\ntype RetainedOwnerEnvironmentState =\n | { readonly state: 'none' }\n | { readonly state: 'live'; readonly environmentId: string; readonly inFlight: boolean }\n | { readonly state: 'lost'; readonly environmentId: string }\n /** The provider could not say. Nothing is concluded and nothing is journaled. */\n | { readonly state: 'unknown'; readonly environmentId: string }\n\n/** Observe exact environment loss before replacing its invocation; preserve uncertain work. */\nexport async function reconcileScopeRetainedOwnerEnvironment(\n scope: Scope<unknown>,\n): Promise<RetainedOwnerEnvironmentState> {\n const state = owners.get(scope)\n if (!state?.provider) return { state: 'none' }\n const { provider, args } = state\n const owned = ((await args.journal.loadTree(args.rootId)) ?? []).filter(\n (event) => event.id === args.nodeId,\n )\n const continued = continuedEnvironment(owned)\n if (continued === undefined) return { state: 'none' }\n const environmentId = continued.admission.environmentId\n if (unusableEnvironmentIds(owned).has(environmentId)) return { state: 'lost', environmentId }\n if (!provider.get) return { state: 'unknown', environmentId }\n let environment: Awaited<ReturnType<NonNullable<AgentEnvironmentProvider['get']>>>\n let terminalStatus: 'failed' | 'expired' | undefined\n try {\n environment = await runAbortable(\n () => provider.get!(environmentId),\n AbortSignal.any([scope.signal, AbortSignal.timeout(ENVIRONMENT_LOOKUP_TIMEOUT_MS)]),\n 'retained owner environment check timed out',\n )\n if (environment !== null) {\n const found = environment\n if (found.id !== environmentId || found.provider !== provider.name)\n return { state: 'unknown', environmentId }\n const status = await runAbortable(\n () => found.status(),\n AbortSignal.any([scope.signal, AbortSignal.timeout(ENVIRONMENT_LOOKUP_TIMEOUT_MS)]),\n 'retained owner environment status timed out',\n )\n if (status === 'failed' || status === 'expired') terminalStatus = status\n }\n } catch {\n return { state: 'unknown', environmentId }\n }\n if (environment !== null && terminalStatus === undefined)\n return { state: 'live', environmentId, inFlight: continued.inFlight }\n scope.signal.throwIfAborted()\n await args.journal.appendEvent(\n args.rootId,\n terminalStatus === undefined\n ? {\n kind: 'environment-teardown',\n id: args.nodeId,\n provider: provider.name,\n environmentId,\n destroyed: true,\n detail:\n 'lost: the provider no longer holds this environment, so the next invocation starts in a new one',\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n }\n : {\n kind: 'environment-terminal',\n id: args.nodeId,\n provider: provider.name,\n environmentId,\n status: terminalStatus,\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n },\n )\n return { state: 'lost', environmentId }\n}\n\n/** A fresh unsigned listener rekeys only after exact prior execution is terminal. */\nexport async function assertRetainedOwnerCoordinationRekey(scope: Scope<unknown>): Promise<void> {\n const state = owners.get(scope)\n const admission = state?.admissions.find((record) => record.phase === 'environment')\n if (!state || admission?.phase !== 'environment') return\n const { environmentId: id, sessionId, provider: name } = admission\n const signal = AbortSignal.any([scope.signal, AbortSignal.timeout(ENVIRONMENT_LOOKUP_TIMEOUT_MS)])\n await runAbortable(\n async () => {\n const environment = await state.provider?.get?.(id, { signal })\n if (environment === null) return\n if (!environment || environment.id !== id || environment.provider !== name)\n throw new ValidationError('retained coordination ownership cannot be established')\n const dispatched = state.admissions.find((record) => record.phase === 'dispatched')\n if (dispatched?.phase !== 'dispatched')\n throw new ValidationError('retained coordination lacks exact dispatch authority')\n const session = environment.session?.(sessionId, {\n signal,\n controlRef: dispatched.controlRef,\n })\n const status = await session?.status({ signal })\n if (status !== 'completed' && status !== 'failed' && status !== 'cancelled')\n throw new ValidationError('active retained coordination needs a durable signer')\n },\n signal,\n 'retained coordination reconciliation timed out',\n )\n}\n","import { HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS } from '../harness-transcript'\nimport { workspaceCaptureWriter } from './retained-executor'\nimport { stopOwnerEvidenceRetry } from './retained-owner-evidence'\nimport { type OwnerState, owners } from './retained-owner-state'\nimport type { Scope } from './types'\n\n/** Cut short the captures a checkpoint rotation is running; each keeps its checkpoint. */\nexport function preemptRotationCaptures(state: OwnerState): void {\n state.rotationCaptures?.abort(\n new Error(\"the turn's end-of-turn capture goes first; checkpoint kept\"),\n )\n}\n\nexport function ownerCaptureWriter(state: OwnerState): ReturnType<typeof workspaceCaptureWriter> {\n const { args } = state\n return workspaceCaptureWriter({\n journal: args.journal,\n rootId: args.rootId,\n nodeId: args.nodeId,\n nextSequence: () => state.nextSequence(),\n now: args.now,\n })\n}\n\n/**\n * Mark one drive of the owner in progress until the returned function is called. An abort settles\n * the node while the drive is still ending its turn: stopping the harness, copying its session and\n * handing its workspace capture over. A release that ran then would find no receipt for the turn\n * and keep the source alive, as on terraform-economics-20261005f, where the root's last attempt was\n * recorded two minutes after its environment's release.\n */\nexport function beginScopeRetainedOwnerDrive(scope: Scope<unknown>): () => void {\n const state = owners.get(scope)\n if (state === undefined) return () => {}\n let end!: () => void\n const drive = new Promise<void>((resolve) => {\n end = resolve\n })\n state.drive = drive\n return () => {\n end()\n if (state.drive === drive) delete state.drive\n }\n}\n\n/** Wait, bounded like a turn's own ending, for the owner's drive in progress to end. */\nexport async function ownerDriveEnded(state: OwnerState): Promise<void> {\n const drive = state.drive\n if (drive === undefined) return\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n drive,\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS)\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\n/**\n * Wait for the end-of-turn work the owner's last turn handed over: its workspace capture and the\n * evidence record of its receipt. A turn hands it over so that its node settles without it; the\n * owner's next turn and its environment's release wait for it here.\n */\nexport async function scopeRetainedOwnerTurnEnded(scope: Scope<unknown>): Promise<void> {\n const state = owners.get(scope)\n if (state === undefined) return\n for (;;) {\n const pending = state.turnEnd\n if (pending === undefined) return\n await pending\n if (state.turnEnd === pending) {\n delete state.turnEnd\n return\n }\n }\n}\n\n/** @internal Wait for everything this owner still has in flight: the drive ending its turn, the\n * work that turn handed over, and a release. The run is settling, so its capture retries stop;\n * a release retries once itself, and a resumed process starts them again. */\nexport async function scopeRetainedOwnerSettled(scope: Scope<unknown>): Promise<void> {\n const state = owners.get(scope)\n if (state === undefined) return\n await ownerDriveEnded(state)\n await scopeRetainedOwnerTurnEnded(scope)\n await state.releasing?.catch(() => undefined)\n await stopOwnerEvidenceRetry(state)\n}\n","import { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport { stopRetainedNativeExecution } from '../retained-native-stop'\nimport type { RetainedRunEnvironmentAdmission } from '../retained-run-types'\nimport { addSpend, zeroSpend } from '../util'\nimport { errMessage, errorText } from './error-message'\nimport { executorFailureReason } from './executor-outcome'\nimport {\n executorEvidenceWriter,\n type RetainedExecutionPendingError,\n type RetainedWorkspaceRestore,\n type RetainedWorkspaceRestoreReceipt,\n} from './retained-executor'\nimport { restoreBefore, restoreCapable } from './retained-owner-environment-recovery'\nimport {\n abandonInputAdmittedIntoDebt,\n reconcileOwnerWorkspaceBeforeReuse,\n retryOwnerEvidence,\n unusableEnvironmentIds,\n} from './retained-owner-evidence'\nimport { type OwnerRegistration, type OwnerState, owners } from './retained-owner-state'\nimport { ownerCaptureWriter, preemptRotationCaptures } from './retained-owner-turn-lifecycle'\nimport { detachedSnapshot } from './snapshot'\nimport { assertValidSpend } from './spend-validation'\nimport { traceRootWriter } from './trace-root'\nimport type { ExecutorResult, Scope, SpawnEvent } from './types'\n\n/** The scope owns these writers; provider adapters receive only the restricted context. */\nexport function registerScopeRetainedOwner(scope: Scope<unknown>, args: OwnerRegistration): void {\n const events = args.priorEvents.filter((event) => 'id' in event && event.id === args.nodeId)\n const taskEvent = [...events].reverse().find((event) => event.kind === 'execution-input')\n const start = taskEvent === undefined ? 0 : events.indexOf(taskEvent)\n const attempt = events.slice(start)\n const admissions = attempt.flatMap((event) =>\n event.kind === 'execution-admitted' ? [event.admission] : [],\n )\n const acceptedRef = [...attempt].reverse().find((event) => event.kind === 'execution-result')\n const records = events.flatMap((event) => (event.kind === 'driver-attempt' ? [event.record] : []))\n let observed = records.filter((record) => record.observed).at(-1)?.observed\n const priorSession = taskEvent === undefined ? undefined : committedSession(events, start)\n let sequence = Math.max(0, ...events.map((event) => ('seq' in event ? event.seq : 0)))\n const traceRoots = traceRootWriter(args.blobs, args.nodeId)\n const state: OwnerState = {\n args,\n admissions,\n workspaceRetention: false,\n nextSequence: () => ++sequence,\n ...(taskEvent?.kind === 'execution-input'\n ? { taskRef: taskEvent.taskRef, inputSequence: taskEvent.seq }\n : {}),\n ...(acceptedRef?.kind === 'execution-result' ? { acceptedRef } : {}),\n ...(priorSession ? { priorSession } : {}),\n context: {\n get executionId() {\n if (state.inputSequence === undefined)\n throw new ValidationError('retained owner input was not committed')\n return `${args.nodeId}:input:${state.inputSequence}`\n },\n get priorSession() {\n return state.priorSession\n },\n get newSession() {\n return state.freshSessions === true && state.priorSession !== undefined\n },\n // Kept alive for a later deliberate invocation; the scope releases it when the manager ends.\n preserveEnvironment: true,\n admissions,\n get restoreWorkspace() {\n return state.restore\n },\n onWorkspaceRestored: async (receipt: RetainedWorkspaceRestoreReceipt) => {\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-restored',\n id: args.nodeId,\n provider: receipt.checkpoint.provider,\n environmentId: receipt.environmentId,\n checkpointId: receipt.checkpoint.checkpointId,\n sourceEnvironmentId: receipt.checkpoint.source.environmentId,\n verified: receipt.verified,\n ...(receipt.detail === undefined ? {} : { detail: receipt.detail }),\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n },\n get observed() {\n return observed\n },\n onObserved: (position) => {\n observed = position\n },\n onAdmission: async (admission) => {\n scope.signal.throwIfAborted()\n const prior = admissions.find((record) => record.phase === admission.phase)\n if (prior !== undefined) {\n if (contentAddress(prior) !== contentAddress(admission)) {\n throw new ValidationError('retained owner admission conflicts with its committed phase')\n }\n return\n }\n await args.journal.appendEvent(args.rootId, {\n kind: 'execution-admitted',\n id: args.nodeId,\n admission: detachedSnapshot(admission, 'retained owner admission'),\n seq: ++sequence,\n at: new Date(args.now()).toISOString(),\n })\n scope.signal.throwIfAborted()\n admissions.push(detachedSnapshot(admission, 'retained owner admission'))\n },\n onEvidence: executorEvidenceWriter({\n journal: args.journal,\n blobs: args.blobs,\n rootId: args.rootId,\n nodeId: args.nodeId,\n nextSequence: () => state.nextSequence(),\n now: args.now,\n traceRoots,\n }),\n onWorkspaceCapture: (capture) => ownerCaptureWriter(state).onWorkspaceCapture(capture),\n // The turn's own capture goes first: it cuts short the captures a checkpoint rotation runs.\n onWorkspaceCaptureStarted: (capture) => {\n preemptRotationCaptures(state)\n return ownerCaptureWriter(state).onWorkspaceCaptureStarted(capture)\n },\n onEndOfTurnWork: (work) => {\n // The handed-over work starts with the turn's final session copy, before its workspace\n // capture: on test-acceptance-canary-20261019m (Runtime 0.331.0) that copy ran 77 s beside\n // a rotation capture, which ran to its 120 s bound, so the capture started 77.8 s after the\n // turn ended. The rotation yields when the turn ends, not when its capture starts.\n preemptRotationCaptures(state)\n const prior = state.turnEnd\n const settled = work.catch(() => undefined)\n state.turnEnd = prior === undefined ? settled : Promise.all([prior, settled]).then(() => {})\n },\n onResult: async (result) => {\n scope.signal.throwIfAborted()\n assertValidSpend(result.spent, 'retained owner result')\n executorFailureReason(result)\n const outRef = contentAddress(result.out)\n await args.blobs.put(outRef, result.out)\n scope.signal.throwIfAborted()\n // The abort is decided once the result is stored: one while its events hash still commits.\n const traceRoot = await traceRoots.write(outRef, result)\n const event: Extract<SpawnEvent, { kind: 'execution-result' }> = {\n kind: 'execution-result',\n id: args.nodeId,\n outRef,\n ...(traceRoot === undefined ? {} : { traceRoot }),\n spent: detachedSnapshot(result.spent, 'retained owner spend'),\n ...(result.verdict ? { verdict: result.verdict } : {}),\n ...(result.outcome ? { outcome: result.outcome } : {}),\n ...(result.outputFormat === undefined ? {} : { outputFormat: result.outputFormat }),\n seq: ++sequence,\n at: new Date(args.now()).toISOString(),\n }\n await args.journal.appendEvent(args.rootId, event)\n state.acceptedRef = event\n state.accepted = detachedSnapshot(result, 'retained owner result')\n state.acceptedConsumed = true\n },\n },\n }\n owners.set(scope, state)\n}\n\n/** The environment admission an invocation starting at `before` continues in: the latest earlier\n * committed invocation's, past abandoned ones. A live process keeps its session across an\n * abandonment, so a resumed one derives it the same way or its replay would not match. */\nfunction committedSession(\n events: readonly SpawnEvent[],\n before: number,\n): RetainedRunEnvironmentAdmission | undefined {\n let end = before\n for (;;) {\n const head = events.slice(0, end)\n const input = [...head].reverse().find((event) => event.kind === 'execution-input')\n if (input === undefined) return undefined\n const start = head.indexOf(input)\n const attempt = head.slice(start)\n const result = [...attempt].reverse().find((event) => event.kind === 'execution-result')\n if (result !== undefined) {\n return attempt\n .slice(0, attempt.indexOf(result))\n .reverse()\n .flatMap((event) =>\n event.kind === 'execution-admitted' && event.admission.phase === 'environment'\n ? [event.admission]\n : [],\n )[0]\n }\n if (!attempt.some((event) => event.kind === 'execution-abandoned')) return undefined\n end = start\n }\n}\n\n/** Bounds the stop Runtime asks for before abandoning a dispatched invocation. */\nconst ABANDON_STOP_TIMEOUT_MS = 30_000\n\n/** Abandon the owner's in-flight invocation when its reconciliation keeps failing the same way\n * (`DriverRetryRun.resolvePending`), only once the provider confirms the dispatched execution\n * stopped or is not live; the journal then refuses its later admissions and results. Answers\n * `false`, journaling nothing, without an unfinished invocation or a confirmed native stop. */\nexport async function abandonScopeRetainedOwnerInvocation(\n scope: Scope<unknown>,\n failure: RetainedExecutionPendingError,\n failures: number,\n): Promise<boolean> {\n const state = owners.get(scope)\n if (state === undefined || state.inputSequence === undefined) return false\n const { args } = state\n const owned = ((await args.journal.loadTree(args.rootId)) ?? []).filter(\n (event) => event.id === args.nodeId,\n )\n const latestInput = [...owned].reverse().find((event) => event.kind === 'execution-input')\n if (latestInput?.kind !== 'execution-input' || latestInput.seq !== state.inputSequence)\n return false\n const attempt = owned.slice(owned.indexOf(latestInput))\n const closing = new Set(['execution-result', 'execution-abandoned'])\n if (attempt.some((event) => closing.has(event.kind))) return false\n const dispatched = [...attempt]\n .reverse()\n .flatMap((event) =>\n event.kind === 'execution-admitted' && event.admission.phase === 'dispatched'\n ? [event.admission]\n : [],\n )[0]\n const stop =\n dispatched === undefined || state.provider === undefined\n ? undefined\n : await stopRetainedNativeExecution({\n provider: state.provider,\n controlRef: dispatched.controlRef,\n signal: AbortSignal.any([scope.signal, AbortSignal.timeout(ABANDON_STOP_TIMEOUT_MS)]),\n now: args.now,\n })\n scope.signal.throwIfAborted()\n const stopped = stop?.effect === 'cancelled' || stop?.effect === 'not_live'\n // A timeout or an unavailable stop cannot prove that a keyed create or dispatch ended.\n // Keep this invocation's task and admissions recoverable: an abandonment closes their journal\n // identity and the next drive would provision under a new key beside the unresolved original.\n if (!stopped) return false\n await args.journal.appendEvent(args.rootId, {\n kind: 'execution-abandoned',\n id: args.nodeId,\n inputSeq: latestInput.seq,\n pendingCause: failure.pendingCause,\n failures,\n detail: errorText(errMessage(failure)).slice(0, 2_048),\n outcome: 'stopped',\n ...(stop === undefined\n ? {}\n : {\n stop: {\n executionId: stop.executionId,\n effect: stop.effect,\n ...(stop.error === undefined ? {} : { error: stop.error }),\n },\n }),\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n return true\n}\n\n/** Resume the original backend prompt; rebuilt coordination observations cannot replace it.\n * `session: 'fresh'` makes every invocation after the first start a new harness session in the\n * environment it continues. */\nexport async function prepareScopeRetainedOwnerTask(\n scope: Scope<unknown>,\n task: unknown,\n session: 'native' | 'fresh' = 'native',\n): Promise<unknown> {\n const state = owners.get(scope)\n if (!state) return task\n const { args } = state\n state.freshSessions = session === 'fresh'\n scope.signal.throwIfAborted()\n const journal = (await args.journal.loadTree(args.rootId)) ?? []\n const owned = journal.filter((event) => event.id === args.nodeId)\n // A restarted supervisor resumes the capture retries of evidence this node may still owe.\n if (owned.some((event) => event.kind === 'evidence-pending')) retryOwnerEvidence(state)\n const latestInput = [...owned].reverse().find((event) => event.kind === 'execution-input')\n if (latestInput?.kind === 'execution-input') {\n const attempt = owned.slice(owned.indexOf(latestInput))\n state.taskRef = latestInput.taskRef\n state.inputSequence = latestInput.seq\n state.admissions.splice(\n 0,\n state.admissions.length,\n ...attempt.flatMap((event) => (event.kind === 'execution-admitted' ? [event.admission] : [])),\n )\n const accepted = [...attempt].reverse().find((event) => event.kind === 'execution-result')\n if (accepted?.kind === 'execution-result') state.acceptedRef = accepted\n }\n // Older coordinators could admit the next input before the previous capture finished.\n // Recovery must not dispatch that pending input over an uncertified historical workspace.\n if (state.taskRef !== undefined && state.acceptedRef === undefined) {\n const indebted = await reconcileOwnerWorkspaceBeforeReuse(state, scope.signal)\n await abandonInputAdmittedIntoDebt(state, indebted)\n }\n const unusable = unusableEnvironmentIds(owned)\n const currentEnvironment = state.admissions.find((admission) => admission.phase === 'environment')\n if (\n state.acceptedRef === undefined &&\n currentEnvironment?.phase === 'environment' &&\n unusable.has(currentEnvironment.environmentId)\n ) {\n // Only loss of this invocation's admitted target can close it. An older accepted turn's lost\n // environment says nothing about a new intent whose create may still be running elsewhere.\n // The current target is absent or terminal, so nothing of this invocation can still run there.\n delete state.inputSequence\n delete state.taskRef\n state.admissions.length = 0\n delete state.priorSession\n }\n if (\n latestInput?.kind === 'execution-input' &&\n state.inputSequence === latestInput.seq &&\n owned.slice(owned.indexOf(latestInput)).some((event) => event.kind === 'execution-abandoned')\n ) {\n // Nothing of an abandoned invocation is recovered. The next drive is a new invocation in the\n // session the abandoned one continued, and the journal admits its input.\n delete state.inputSequence\n delete state.taskRef\n state.admissions.length = 0\n }\n if (state.prepared && state.acceptedRef && state.acceptedConsumed) {\n await reconcileOwnerWorkspaceBeforeReuse(state, scope.signal)\n const currentEnvironment = [...state.admissions]\n .reverse()\n .find((admission) => admission.phase === 'environment')\n if (currentEnvironment?.phase === 'environment') state.priorSession = currentEnvironment\n delete state.inputSequence\n delete state.taskRef\n delete state.acceptedRef\n delete state.accepted\n // A deliberate later drive starts a distinct invocation after an accepted result.\n state.admissions.length = 0\n delete state.acceptedConsumed\n }\n // A later invocation never reuses an environment the provider confirmed unusable.\n if (state.priorSession !== undefined && unusable.has(state.priorSession.environmentId)) {\n delete state.priorSession\n }\n const segmentStarts = owned.filter(\n (event): event is Extract<SpawnEvent, { kind: 'seat-segment' }> =>\n event.kind === 'seat-segment' && event.phase === 'started',\n )\n const latestSeat = segmentStarts.at(-1)\n const previousSeat = segmentStarts.at(-2)\n if (\n latestSeat &&\n previousSeat &&\n latestSeat.provider !== previousSeat.provider &&\n owned.indexOf(latestSeat) > owned.indexOf(latestInput as SpawnEvent)\n ) {\n // A coordinator that died after recording the new segment but before dispatch still starts\n // a fresh native session from the committed checkpoint, never the old provider's session.\n state.forceNewSession = true\n }\n const rootSegment = owned\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'root-segment' }> =>\n event.kind === 'root-segment',\n )\n .at(-1)\n if (\n rootSegment?.from !== undefined &&\n rootSegment.from.harness !== rootSegment.to.harness &&\n owned.indexOf(rootSegment) > owned.indexOf(latestInput as SpawnEvent)\n ) {\n // A root resumed in another harness: a native session of one harness cannot continue in\n // another. An in-flight turn of the old harness is still recovered as it committed; every\n // invocation after it starts a new session, from the latest checkpoint when the provider holds\n // one, exactly as a seat that changed provider does.\n state.forceNewSession = true\n }\n if (state.forceNewSession) {\n delete state.priorSession\n delete state.forceNewSession\n }\n state.prepared = true\n // The invocation's restore point is fixed by the journal before its input, so a recovered\n // invocation replays the same create it committed.\n const capable = await restoreCapable(state.provider)\n const restoreFor = (inputIndex: number): RetainedWorkspaceRestore | undefined => {\n if (!capable || state.priorSession !== undefined) return undefined\n const point = restoreBefore(owned, inputIndex)\n return point === undefined\n ? undefined\n : {\n checkpoint: point.checkpoint,\n ...(point.marker === undefined ? {} : { marker: point.marker }),\n }\n }\n if (state.taskRef !== undefined) {\n const original = await args.blobs.get(state.taskRef)\n if (original === undefined || contentAddress(original) !== state.taskRef) {\n throw new ValidationError('retained owner task is missing or corrupt')\n }\n const inputIndex = owned.findIndex(\n (event) => event.kind === 'execution-input' && event.seq === state.inputSequence,\n )\n const restore = restoreFor(inputIndex)\n if (restore === undefined) delete state.restore\n else state.restore = restore\n return original\n }\n const restore = restoreFor(-1)\n if (restore === undefined) delete state.restore\n else state.restore = restore\n const snapshot = detachedSnapshot(task, 'retained owner task')\n const taskRef = contentAddress(snapshot)\n await args.blobs.put(taskRef, snapshot)\n scope.signal.throwIfAborted()\n const inputSequence = state.nextSequence()\n await args.journal.appendEvent(args.rootId, {\n kind: 'execution-input',\n id: args.nodeId,\n taskRef,\n ...(state.workspaceRetention ? { workspaceRetention: true } : {}),\n seq: inputSequence,\n at: new Date(args.now()).toISOString(),\n })\n state.taskRef = taskRef\n state.inputSequence = inputSequence\n return snapshot\n}\n\n/** Accepted backend output remains evidence, never the supervisor's finalized output. */\nexport async function scopeRetainedOwnerResult(\n scope: Scope<unknown>,\n): Promise<ExecutorResult<unknown> | undefined> {\n const state = owners.get(scope)\n if (!state?.acceptedRef) return undefined\n if (state.accepted) return state.accepted\n const event = state.acceptedRef\n const out = await state.args.blobs.get(event.outRef)\n if (out === undefined || contentAddress(out) !== event.outRef) {\n throw new ValidationError('retained owner result is missing or corrupt')\n }\n assertValidSpend(event.spent, 'replayed retained owner result')\n return {\n outRef: event.outRef,\n out,\n spent: event.spent,\n ...(event.verdict ? { verdict: event.verdict } : {}),\n ...(event.outcome ? { outcome: event.outcome } : {}),\n ...(event.outputFormat === undefined ? {} : { outputFormat: event.outputFormat }),\n }\n}\n\nexport async function scopeRetainedOwnerPriorSpend(scope: Scope<unknown>) {\n const state = owners.get(scope)\n if (!state) return zeroSpend()\n const events = ((await state.args.journal.loadTree(state.args.rootId)) ?? []).filter(\n (event) => event.id === state.args.nodeId,\n )\n const input = [...events].reverse().find((event) => event.kind === 'execution-input')\n if (!input) return zeroSpend()\n return events\n .slice(events.indexOf(input))\n .reduce(\n (total, event) => (event.kind === 'metered' ? addSpend(total, event.spend) : total),\n zeroSpend(),\n )\n}\n\n/** Called only after the scope verifies the accepted invocation's materialization. */\nexport function consumeScopeRetainedOwnerResult(scope: Scope<unknown>): void {\n const state = owners.get(scope)\n if (!state?.acceptedRef) throw new ValidationError('retained owner has no accepted result')\n state.acceptedConsumed = true\n}\n","import type { AgentExactRunControlRef } from '@tangle-network/agent-interface'\nimport type { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider'\nimport { contentAddress } from '../../durable/content-address'\nimport { describeRetainedNativeStops, stopRetainedNativeExecution } from '../retained-native-stop'\nimport { runAbortable } from './abortable'\nimport {\n type CaptureRefusal,\n cleanCheckpoints,\n settleCaptureForks,\n} from './retained-owner-checkpoint-capture'\nimport {\n type CheckpointEvent,\n checkpointHandle,\n pendingCheckpoints,\n reconcileCheckpointRequests,\n} from './retained-owner-checkpoint-requests'\nimport {\n ownerWorkspaceRetentionFailures,\n recaptureOwnerSources,\n stopOwnerEvidenceRetry,\n} from './retained-owner-evidence'\nimport { type OwnerState, owners } from './retained-owner-state'\nimport { ownerDriveEnded, scopeRetainedOwnerTurnEnded } from './retained-owner-turn-lifecycle'\nimport type { NodeId, Scope, SpawnEvent, UnconfirmedTeardown } from './types'\n\n/** @internal Whether another owner release could still destroy what the last one left. */\nexport function retainedOwnerReleaseRetriable(scope: Scope<unknown>): boolean {\n return owners.get(scope)?.releaseRetriable ?? false\n}\n\n/**\n * How long one release spends capturing the owner's pending checkpoints, all of them together. A\n * capture it cuts short keeps its checkpoint and the source, as a failed capture does, and the\n * release goes on to settle. Each capture is otherwise bounded only by its port, and one at a\n * time: on Discovery run terraform-dc-model-20261010h-c1 (Runtime 0.314.0) a director's release\n * waited 00:19:18Z to 01:19:38Z for one capture to reach the port's 60-minute bound, and the run\n * settled 98 minutes after its deadline. The release captures that finished there took 67 seconds\n * and 7 and 34 minutes, beside live captures of abandoned directors on the same slots.\n */\nconst RELEASE_CHECKPOINT_CAPTURES_MS = 15 * 60_000\n\n/**\n * Release the owner's environment once no turn of it will run again: at the run's final\n * settlement for the root, and when a nested manager's own scope has finished. A second call while\n * one is in flight joins it. The release first waits for the end-of-turn capture of the owner's\n * last turn, so the capture always precedes the destroy. `capturesMs` bounds the checkpoint\n * captures it runs ({@link RELEASE_CHECKPOINT_CAPTURES_MS}).\n */\nexport function releaseScopeRetainedOwnerEnvironment(\n scope: Scope<unknown>,\n { capturesMs = RELEASE_CHECKPOINT_CAPTURES_MS }: { readonly capturesMs?: number } = {},\n): Promise<readonly UnconfirmedTeardown[]> {\n const state = owners.get(scope)\n const provider = state?.provider\n if (state === undefined || provider === undefined) return Promise.resolve([])\n if (state.releasing !== undefined) return state.releasing\n const releasing = (async () => {\n await ownerDriveEnded(state)\n await scopeRetainedOwnerTurnEnded(scope)\n return await releaseOwnerEnvironment(state, provider, capturesMs)\n })()\n const tracked = releasing.finally(() => {\n if (state.releasing === tracked) delete state.releasing\n })\n state.releasing = tracked\n return tracked\n}\n\nasync function releaseOwnerEnvironment(\n state: OwnerState,\n provider: AgentEnvironmentProvider,\n capturesMs: number,\n): Promise<readonly UnconfirmedTeardown[]> {\n const { args } = state\n // No checkpoint may race the destroy below, and none is needed after it.\n state.checkpointsUnavailable ??= 'released'\n await state.checkpointing?.catch(() => undefined)\n // One budget bounds every capture this release runs: the evidence it retries, then checkpoints.\n const capturesDeadline = Date.now() + capturesMs\n await stopOwnerEvidenceRetry(state)\n await recaptureOwnerSources(state, AbortSignal.timeout(capturesMs))\n const events = [...((await args.journal.loadTree(args.rootId)) ?? [])]\n const requestFailures = await reconcileCheckpointRequests(state, events)\n const pendingSources = new Set(requestFailures.map(({ event }) => event.environmentId))\n const released = new Set(\n events.flatMap((event) =>\n event.kind === 'environment-teardown' &&\n event.id === args.nodeId &&\n event.provider === provider.name &&\n event.destroyed\n ? [event.environmentId]\n : [],\n ),\n )\n const environments = new Set(\n events.flatMap((event) =>\n event.id === args.nodeId &&\n event.kind === 'execution-admitted' &&\n event.admission.phase === 'environment'\n ? [event.admission.environmentId]\n : [],\n ),\n )\n const retentionConfigured =\n state.workspaceRetention ||\n events.some(\n (event) =>\n event.kind === 'execution-input' &&\n event.id === args.nodeId &&\n event.workspaceRetention === true,\n )\n const retentionFailures = retentionConfigured\n ? await ownerWorkspaceRetentionFailures(events, args)\n : new Set<string>()\n const unconfirmed: string[] = []\n // Sources preserved for lack of a verified workspace receipt: evidence, never swept.\n const preserved: string[] = []\n let lastDetail: string | undefined\n let retriable = false\n const checkpointFailures: CheckpointEvent[] = []\n const checkpointsKept: CaptureRefusal[] = []\n // Sources kept because a checkpoint of theirs is in no capture, and only they can fork it.\n const uncapturedSources = new Set<string>()\n const pending = pendingCheckpoints(events, state).filter(\n (event) => !retentionFailures.has(event.environmentId),\n )\n const captures = new AbortController()\n const capturesTimer = setTimeout(\n () =>\n captures.abort(\n new Error(\n `the release's ${capturesMs} ms for checkpoint captures ran out; checkpoint and source kept`,\n ),\n ),\n Math.max(0, capturesDeadline - Date.now()),\n )\n try {\n for (const sourceEnvironmentId of new Set(pending.map((event) => event.environmentId))) {\n const branching = await checkpointHandle(\n state,\n sourceEnvironmentId,\n AbortSignal.any([captures.signal, AbortSignal.timeout(30_000)]),\n )\n const cleaned = await cleanCheckpoints(\n state,\n branching,\n pending.filter((event) => event.environmentId === sourceEnvironmentId),\n events,\n captures.signal,\n )\n checkpointFailures.push(...cleaned.unconfirmed)\n checkpointsKept.push(...cleaned.refused)\n for (const refusal of cleaned.refused)\n if (refusal.needsSource) uncapturedSources.add(sourceEnvironmentId)\n }\n } finally {\n clearTimeout(capturesTimer)\n }\n const forksUnresolved = await settleCaptureForks(state)\n for (const event of checkpointFailures) pendingSources.add(event.environmentId)\n for (const environmentId of environments) {\n if (released.has(environmentId)) continue\n let destroyed = false\n let detail: string | undefined\n if (\n retentionFailures.has(environmentId) ||\n pendingSources.has(environmentId) ||\n uncapturedSources.has(environmentId)\n ) {\n detail = pendingSources.has(environmentId)\n ? 'checkpoint cleanup unresolved: source preserved for exact lookup and cleanup'\n : uncapturedSources.has(environmentId)\n ? 'checkpoint kept uncaptured: source preserved so its checkpoint can still be forked and captured'\n : 'provider workspace retention: source preserved because the owner execution has no verified workspace receipt'\n preserved.push(environmentId)\n lastDetail = detail\n } else {\n // A provider that cannot reconstruct or destroy the environment answers the same way every\n // time; only a destroy that failed or went unanswered is worth asking again.\n let permanent = false\n try {\n await runAbortable(\n async () => {\n if (!provider.get) {\n permanent = true\n throw new Error('provider cannot reconstruct the retained environment')\n }\n const environment = await provider.get(environmentId)\n if (environment === null) return\n if (environment.id !== environmentId || environment.provider !== provider.name) {\n permanent = true\n throw new Error('provider returned another retained environment')\n }\n if (!environment.destroy) {\n permanent = true\n throw new Error('provider cannot destroy the retained environment')\n }\n await environment.destroy()\n },\n AbortSignal.timeout(30_000),\n 'retained owner cleanup timed out',\n )\n destroyed = true\n } catch {\n detail = 'retained owner environment cleanup was not confirmed'\n unconfirmed.push(environmentId)\n lastDetail = detail\n if (!permanent) retriable = true\n }\n }\n if (!destroyed) {\n // A kept environment keeps its files, never its running harness: the run has settled, so\n // nothing will observe or reconcile an owner turn still executing inside it.\n const runs = unsettledOwnerRuns(events, args.nodeId, environmentId)\n if (runs.length > 0) {\n const stops = await Promise.all(\n runs.map((controlRef) =>\n stopRetainedNativeExecution({\n provider,\n controlRef,\n signal: AbortSignal.timeout(30_000),\n now: args.now,\n }),\n ),\n )\n detail = `${detail}; ${describeRetainedNativeStops(stops)}`\n lastDetail = detail\n }\n }\n await args.journal.appendEvent(args.rootId, {\n kind: 'environment-teardown',\n id: args.nodeId,\n provider: provider.name,\n environmentId,\n destroyed,\n ...(detail === undefined ? {} : { detail }),\n seq: state.nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n }\n state.releaseRetriable = retriable\n const checkpointTeardowns: UnconfirmedTeardown[] = [\n ...checkpointFailures.map(\n (event): UnconfirmedTeardown => ({\n id: args.nodeId,\n label: 'scope owner workspace checkpoint',\n runtime: provider.name,\n status: 'done',\n detail: `checkpoint cleanup unconfirmed: ${event.checkpoint.checkpointId} from ${event.environmentId}`,\n }),\n ),\n ...requestFailures.map(\n ({ event, reason }): UnconfirmedTeardown => ({\n id: args.nodeId,\n label: 'scope owner checkpoint request',\n runtime: provider.name,\n status: 'done',\n detail: `checkpoint request unresolved: ${event.request.idempotencyKey} from ${event.environmentId} (${reason})`,\n }),\n ),\n ...checkpointsKept.map(\n ({ event, reason }): UnconfirmedTeardown => ({\n id: args.nodeId,\n label: 'scope owner workspace checkpoint',\n runtime: provider.name,\n status: 'done',\n detail: `checkpoint kept uncaptured: ${event.checkpoint.checkpointId} from ${event.environmentId} (${reason})`,\n }),\n ),\n ...(forksUnresolved.length === 0\n ? []\n : [\n {\n id: args.nodeId,\n label: 'scope owner checkpoint capture fork',\n runtime: provider.name,\n status: 'done',\n detail: `checkpoint capture fork destruction unconfirmed: ${forksUnresolved.join(', ')}`,\n } satisfies UnconfirmedTeardown,\n ]),\n ]\n return unconfirmed.length > 0 || preserved.length > 0\n ? [\n {\n id: args.nodeId,\n label: 'scope owner',\n runtime: provider.name,\n status: 'done',\n ...(unconfirmed.length === 0\n ? {}\n : {\n environments: unconfirmed.map((environmentId) => ({\n provider: provider.name,\n environmentId,\n })),\n }),\n ...(preserved.length === 0\n ? {}\n : {\n kept: preserved.map((environmentId) => ({\n provider: provider.name,\n environmentId,\n keptFor: 'evidence' as const,\n })),\n }),\n ...(lastDetail === undefined ? {} : { detail: lastDetail }),\n },\n ...checkpointTeardowns,\n ]\n : checkpointTeardowns\n}\n\n/**\n * The owner's dispatched executions in one environment whose turn committed no result. A turn\n * with a result has ended; one without may still be running even after a later turn started.\n */\nfunction unsettledOwnerRuns(\n events: readonly SpawnEvent[],\n nodeId: NodeId,\n environmentId: string,\n): AgentExactRunControlRef[] {\n const runs = new Map<string, AgentExactRunControlRef>()\n let turn: AgentExactRunControlRef[] = []\n const close = (): void => {\n for (const controlRef of turn) runs.set(contentAddress(controlRef), controlRef)\n turn = []\n }\n for (const event of events) {\n if (!('id' in event) || event.id !== nodeId) continue\n if (event.kind === 'execution-input') close()\n else if (event.kind === 'execution-result') turn = []\n else if (\n event.kind === 'execution-admitted' &&\n event.admission.phase === 'dispatched' &&\n event.admission.controlRef.environmentId === environmentId\n ) {\n turn.push(event.admission.controlRef)\n }\n }\n close()\n return [...runs.values()]\n}\n","import { createHash } from 'node:crypto'\nimport { type FileHandle, open, realpath, stat } from 'node:fs/promises'\nimport { isAbsolute, relative, resolve, sep } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\n\n/**\n * Inline resources a manager hands a child by PATH instead of by content.\n *\n * The canonical profile schema knows two resource kinds, `inline` (a content string) and `github`.\n * A manager that wants a child to receive a data file therefore had one way to do it: emit the\n * bytes inside its own `spawn` tool call. That is a transcription by a language model, and it does\n * not survive size. Measured 2026-09-12 (discovery-lab `mech-interp-foundations-glm2-b-20260912b`):\n * a 29,144-character base64 payload on the manager's disk reached three children as 15,928\n * characters with 11 substitutions, and a fourth child received the literal placeholder the\n * manager meant to replace. Seven blind-check attempts across two runs delivered no data.\n *\n * `{ kind: 'inline', name, path }` lets the coordination server be the transport: it reads the\n * file from the manager's workspace, fills `content`, and the profile that reaches the schema,\n * the journal, and the provider is an ordinary inline resource. Nothing downstream changes; the\n * model's output stops carrying the bytes.\n *\n * Where the bytes come from is a {@link SpawnResourceReader}, and there are two:\n * - a HOST DIRECTORY, for a manager whose driver runs on this host (a loopback bridge with a\n * `cwd`), read through the descriptor-identity checks below;\n * - the manager's OWN EXECUTION ENVIRONMENT, for a manager inside a provider sandbox, read\n * through the environment's `read()`. The coordination server cannot see a sandbox filesystem,\n * but the provider that created the sandbox can, and it is already in hand.\n *\n * The second reader exists because the first one's absence was not a refusal a manager could\n * work around. Measured 2026-09-17 (discovery-lab `mech-interp-foundations-sandbox-a-20260917h`):\n * a sandbox-rooted director, refused by path, fell back to emitting its files as content and got\n * 5 characters wrong in 24,008, destroying 3 of 7 files including its instrument and both\n * drivers. At that rate 20 KB of mounts all arrive intact about 2% of the time, and gzip makes it\n * worse by turning one wrong character into total loss. Four consecutive runs in that lane lost\n * their research children to this. There is no encoding that fixes a transcription channel; the\n * only fix is a channel with no model in it.\n *\n * Fail-closed rules, each with the reason a manager needs to fix its call:\n * - no reader available → refused (neither a host directory nor an environment with `read`)\n * - absolute path or `..` escape → refused by both readers; a symlink that resolves outside the\n * root → refused by the host reader (the environment reader delegates containment to the\n * provider, which serves only the sandbox's own workspace)\n * - not a regular file → refused\n * - over {@link SPAWN_RESOURCE_PATH_MAX_BYTES} → refused naming the bound\n * - bytes that are not valid UTF-8 → refused; `content` is a string, so binary data is encoded\n * (base64) by the manager first, exactly as it would be for a content resource\n */\nexport const SPAWN_RESOURCE_PATH_MAX_BYTES = 4 * 1024 * 1024\n\n/** One successful read: the bytes as a string plus the identity the journal records. */\nexport interface SpawnResourceBytes {\n readonly content: string\n readonly byteLength: number\n readonly sha256: string\n}\n\nexport type SpawnResourceRead =\n | ({ readonly ok: true } & SpawnResourceBytes)\n | { readonly ok: false; readonly reason: string }\n\n/**\n * Where a by-path resource's bytes come from. `describe` names the source in a refusal so a\n * manager reading \"path X does not exist under the workspace root\" and \"path X: sandbox read\n * failed\" can tell which filesystem was consulted.\n */\nexport interface SpawnResourceReader {\n readonly describe: string\n read(path: string): Promise<SpawnResourceRead>\n}\n\n/** The host-directory reader: a manager whose workspace is a directory this process can open. */\nexport function hostDirectoryReader(root: string): SpawnResourceReader {\n return {\n describe: `workspace root ${root}`,\n read: (requested) => readUnderRoot(root, requested),\n }\n}\n\n/**\n * The environment reader: a manager running inside a provider environment whose `read()` serves\n * its own workspace. The provider owns containment — it will not serve a path outside the box —\n * but the relative-path and `..` rules are enforced here too, so the refusal names the rule the\n * manager broke rather than whatever the provider says about an escape it declined.\n *\n * `read()` returns a string, so an environment cannot hand back bytes that are not UTF-8; the\n * provider has already decoded. The size bound is checked on what arrives.\n */\nexport function environmentReader(environment: {\n readonly id: string\n read(path: string): Promise<string>\n}): SpawnResourceReader {\n return {\n describe: `environment ${environment.id}`,\n async read(requested) {\n if (requested.length === 0) return { ok: false, reason: 'path is empty' }\n if (isAbsolute(requested)) {\n return {\n ok: false,\n reason: `path must be relative to the manager's workspace, not absolute (${requested})`,\n }\n }\n if (requested.split(/[\\\\/]/u).includes('..')) {\n return { ok: false, reason: `path ${requested} leaves the manager's workspace` }\n }\n let content: string\n try {\n content = await environment.read(requested)\n } catch (error) {\n return {\n ok: false,\n reason: `path ${requested}: ${describe(error)} (read from environment ${environment.id})`,\n }\n }\n const bytes = Buffer.from(content, 'utf8')\n if (bytes.length > SPAWN_RESOURCE_PATH_MAX_BYTES) {\n return {\n ok: false,\n reason: `path ${requested} is ${bytes.length} bytes; an inline resource is at most ${SPAWN_RESOURCE_PATH_MAX_BYTES} bytes`,\n }\n }\n return {\n ok: true,\n content,\n byteLength: bytes.length,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n }\n },\n }\n}\n\nexport interface ResolvedSpawnResourcePath {\n /** The `resources` location, e.g. `files[0].resource` or `skills[2]`. */\n readonly at: string\n /** The path as the manager wrote it. */\n readonly path: string\n readonly byteLength: number\n readonly sha256: string\n}\n\nexport type ResolveSpawnResourcePathsResult =\n | {\n readonly ok: true\n readonly profile: unknown\n readonly resolved: readonly ResolvedSpawnResourcePath[]\n }\n | { readonly ok: false; readonly at: string; readonly reason: string }\n\ninterface PathInlineRef {\n readonly kind: 'inline'\n readonly name: string\n readonly path: string\n}\n\n/** An inline ref that names a path and carries no content. Anything else is left untouched so the\n * canonical schema keeps its verdict on it. */\nfunction pathInlineRef(value: unknown): PathInlineRef | undefined {\n if (!isRecord(value)) return undefined\n if (value.kind !== 'inline' || value.content !== undefined) return undefined\n if (typeof value.path !== 'string' || typeof value.name !== 'string') return undefined\n return { kind: 'inline', name: value.name, path: value.path }\n}\n\nasync function readUnderRoot(root: string, requested: string): Promise<SpawnResourceRead> {\n if (requested.length === 0) return { ok: false, reason: 'path is empty' }\n if (isAbsolute(requested)) {\n return {\n ok: false,\n reason: `path must be relative to the workspace root, not absolute (${requested})`,\n }\n }\n const rootReal = await realpath(root).catch(() => undefined)\n if (rootReal === undefined) return { ok: false, reason: `workspace root ${root} does not exist` }\n const candidate = resolve(rootReal, requested)\n if (!inside(rootReal, candidate)) {\n return { ok: false, reason: `path ${requested} leaves the workspace root` }\n }\n // Open first, then judge the OPENED file. A containment check on a path alone can be raced: the\n // manager's workspace is live (a background process of its own can rename a directory and put a\n // symlink in its place between the check and the read), so the descriptor's identity is what the\n // verdict is about. The in-root real path must name the same inode the descriptor holds, and the\n // bytes are read from the descriptor, never from the path.\n let handle: FileHandle\n try {\n handle = await open(candidate, 'r')\n } catch (error) {\n return { ok: false, reason: `path ${requested}: ${describe(error)}` }\n }\n try {\n const info = await handle.stat()\n if (!info.isFile()) return { ok: false, reason: `path ${requested} is not a regular file` }\n const real = await realpath(candidate).catch(() => undefined)\n if (real === undefined || !inside(rootReal, real)) {\n return { ok: false, reason: `path ${requested} resolves outside the workspace root` }\n }\n const named = await stat(real).catch(() => undefined)\n if (named === undefined || named.dev !== info.dev || named.ino !== info.ino) {\n return {\n ok: false,\n reason: `path ${requested} changed while it was being read; retry the spawn`,\n }\n }\n if (info.size > SPAWN_RESOURCE_PATH_MAX_BYTES) {\n return {\n ok: false,\n reason: `path ${requested} is ${info.size} bytes; an inline resource is at most ${SPAWN_RESOURCE_PATH_MAX_BYTES} bytes`,\n }\n }\n const bytes = await handle.readFile()\n if (bytes.length > SPAWN_RESOURCE_PATH_MAX_BYTES) {\n return {\n ok: false,\n reason: `path ${requested} is ${bytes.length} bytes; an inline resource is at most ${SPAWN_RESOURCE_PATH_MAX_BYTES} bytes`,\n }\n }\n const content = bytes.toString('utf8')\n if (!Buffer.from(content, 'utf8').equals(bytes)) {\n return {\n ok: false,\n reason: `path ${requested} is not valid UTF-8; encode binary data (base64) before handing it to a child`,\n }\n }\n return {\n ok: true,\n content,\n byteLength: bytes.length,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n }\n } catch (error) {\n return { ok: false, reason: `path ${requested}: ${describe(error)}` }\n } finally {\n await handle.close().catch(() => undefined)\n }\n}\n\n/** `target` is `rootReal` itself or strictly below it; both must already be absolute. */\nfunction inside(rootReal: string, target: string): boolean {\n const rel = relative(rootReal, target)\n return rel !== '' && !rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel)\n}\n\nfunction describe(error: unknown): string {\n const code = (error as { code?: unknown } | null)?.code\n if (code === 'ENOENT') return 'does not exist under the workspace root'\n if (code === 'EACCES' || code === 'EPERM') return 'is not readable by the runtime process'\n if (code === 'EISDIR') return 'is not a regular file'\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Replace every `{ kind: 'inline', name, path }` under `profile.resources` with the inline\n * resource its bytes make. Returns the profile unchanged (same reference) when nothing names a\n * path, so callers pay nothing on the common case.\n *\n * `source` is a host directory (a string, kept for the existing call sites), a\n * {@link SpawnResourceReader}, or `undefined` when the manager has neither — in which case a path\n * is refused with the reason and what to do instead.\n */\nexport async function resolveSpawnResourcePaths(\n profile: unknown,\n source: string | SpawnResourceReader | undefined,\n): Promise<ResolveSpawnResourcePathsResult> {\n if (!isRecord(profile) || !isRecord(profile.resources)) return { ok: true, profile, resolved: [] }\n const reader = typeof source === 'string' ? hostDirectoryReader(source) : source\n const resources = profile.resources\n const resolved: ResolvedSpawnResourcePath[] = []\n let touched = false\n const next: Record<string, unknown> = { ...resources }\n\n const substitute = async (\n at: string,\n ref: PathInlineRef,\n ): Promise<{ kind: 'inline'; name: string; content: string } | { error: string }> => {\n if (reader === undefined) {\n return {\n // Keep \"no workspace root\": discovery-lab's failure catalog and its director prompts match\n // that phrase, and a reworded refusal would silently stop being recognised downstream.\n error:\n 'this manager has no workspace root the coordination server may read (no host directory and no environment with read), so a resource by path cannot be resolved; pass content, or a github resource',\n }\n }\n const read = await reader.read(ref.path)\n if (!read.ok) return { error: read.reason }\n resolved.push({ at, path: ref.path, byteLength: read.byteLength, sha256: read.sha256 })\n touched = true\n return { kind: 'inline', name: ref.name, content: read.content }\n }\n\n for (const list of ['tools', 'skills', 'agents'] as const) {\n const entries = resources[list]\n if (!Array.isArray(entries)) continue\n const out: unknown[] = []\n for (const [index, entry] of entries.entries()) {\n const ref = pathInlineRef(entry)\n if (ref === undefined) {\n out.push(entry)\n continue\n }\n const at = `${list}[${index}]`\n const replaced = await substitute(at, ref)\n if ('error' in replaced) return { ok: false, at, reason: replaced.error }\n out.push(replaced)\n }\n next[list] = out\n }\n if (Array.isArray(resources.files)) {\n const out: unknown[] = []\n for (const [index, mount] of resources.files.entries()) {\n const ref = isRecord(mount) ? pathInlineRef(mount.resource) : undefined\n if (ref === undefined || !isRecord(mount)) {\n out.push(mount)\n continue\n }\n const at = `files[${index}].resource`\n const replaced = await substitute(at, ref)\n if ('error' in replaced) return { ok: false, at, reason: replaced.error }\n out.push({ ...mount, resource: replaced })\n }\n next.files = out\n }\n const instructions = pathInlineRef(resources.instructions)\n if (instructions !== undefined) {\n const replaced = await substitute('instructions', instructions)\n if ('error' in replaced) return { ok: false, at: 'instructions', reason: replaced.error }\n next.instructions = replaced\n }\n if (!touched) return { ok: true, profile, resolved: [] }\n return { ok: true, profile: { ...profile, resources: next }, resolved }\n}\n","import type { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider'\nimport { environmentReader, type SpawnResourceReader } from '../../mcp/tools/spawn-resource-paths'\nimport { owners } from './retained-owner-state'\nimport type { Scope } from './types'\n\n/**\n * The owner's environment as a source of by-path spawn resources.\n *\n * Built once per scope, before the environment exists: the coordination tools are created ahead\n * of the owner's first turn, and the environment is admitted during it. So the reader resolves\n * its target on every read — the latest environment admission on this node, reconstructed through\n * the bound provider the same way cleanup reconstructs it, with the same identity check. A manager\n * that has not yet been admitted, or whose provider was never bound, gets a refusal that names the\n * missing piece rather than a read from nowhere.\n *\n * The environment's `read()` serves the sandbox's own workspace; containment against that\n * workspace is the provider's. The relative-path and `..` rules are the reader's, in\n * `environmentReader`, so a manager is refused for the rule it broke.\n */\nexport function scopeRetainedOwnerResourceReader(\n scope: Scope<unknown>,\n): SpawnResourceReader | undefined {\n const state = owners.get(scope)\n if (state === undefined) return undefined\n const latestEnvironmentId = (): string | undefined =>\n state.liveEnvironmentId?.() ??\n [...state.admissions]\n .reverse()\n .flatMap((admission) =>\n admission.phase === 'environment' ? [admission.environmentId] : [],\n )[0]\n return {\n get describe() {\n return `environment ${latestEnvironmentId() ?? '<not yet admitted>'}`\n },\n async read(path) {\n const provider = state.provider\n if (provider === undefined) {\n return { ok: false, reason: 'the manager’s environment provider is not bound yet' }\n }\n const environmentId = latestEnvironmentId()\n if (environmentId === undefined) {\n return { ok: false, reason: 'the manager’s environment has not been admitted yet' }\n }\n if (!provider.get) {\n return {\n ok: false,\n reason: `provider ${provider.name} cannot reconstruct the manager’s environment`,\n }\n }\n let environment: Awaited<ReturnType<NonNullable<AgentEnvironmentProvider['get']>>>\n try {\n environment = await provider.get(environmentId)\n } catch (error) {\n return {\n ok: false,\n reason: `environment ${environmentId}: ${error instanceof Error ? error.message : String(error)}`,\n }\n }\n if (environment === null) {\n return { ok: false, reason: `environment ${environmentId} is gone` }\n }\n if (environment.id !== environmentId || environment.provider !== provider.name) {\n return { ok: false, reason: `provider returned another environment for ${environmentId}` }\n }\n if (typeof environment.read !== 'function') {\n return {\n ok: false,\n reason: `environment ${environmentId} does not expose read; its provider cannot serve a resource by path`,\n }\n }\n const read = environment.read.bind(environment)\n return environmentReader({ id: environment.id, read }).read(path)\n },\n }\n}\n","import { ValidationError } from '../../errors'\nimport { runAbortable } from './abortable'\nimport { checkpointOwnerWorkspace } from './retained-owner-checkpoint-rotation'\nimport {\n ownerWorkspaceRetentionFailures,\n reconcileOwnerWorkspaceBeforeReuse,\n} from './retained-owner-evidence'\nimport { type OwnerState, owners } from './retained-owner-state'\nimport { scopeRetainedOwnerTurnEnded } from './retained-owner-turn-lifecycle'\nimport type { Scope, SpawnEvent } from './types'\n\n/** A committed turn is the seat boundary. Keep its native home for a same-harness provider\n * continuation; only a provider/harness change needs a new environment. */\nexport async function prepareScopeRetainedOwnerSeatSwitch(\n scope: Scope<unknown>,\n mode: 'same-environment' | 'replace-environment',\n): Promise<{\n readonly checkpointAt: string\n readonly checkpointId: string\n readonly sourceEnvironmentId: string\n}> {\n const state = owners.get(scope)\n if (!state?.acceptedRef || !state.acceptedConsumed)\n throw new ValidationError('seat switch requires a committed owner turn')\n const accepted = state.acceptedRef\n const owned = await checkpointOwner(scope, state)\n const acceptedIndex = owned.findIndex(\n (event) =>\n event.kind === 'execution-result' &&\n event.seq === accepted.seq &&\n event.outRef === accepted.outRef,\n )\n if (acceptedIndex < 0)\n throw new ValidationError('seat switch has no committed result in its journal')\n const source = owned\n .slice(0, acceptedIndex)\n .reverse()\n .find((event) => event.kind === 'execution-admitted' && event.admission.phase === 'environment')\n const sourceEnvironmentId =\n source?.kind === 'execution-admitted' && source.admission.phase === 'environment'\n ? source.admission.environmentId\n : undefined\n const checkpoint = owned\n .slice(acceptedIndex + 1)\n .reverse()\n .find(\n (event) =>\n event.kind === 'workspace-checkpoint' && event.environmentId === sourceEnvironmentId,\n )\n if (checkpoint?.kind !== 'workspace-checkpoint')\n throw new ValidationError('seat switch requires a checkpoint of its committed source')\n if (mode === 'replace-environment') {\n // A seat may move from a verified checkpoint while the old source remains evidence.\n await retireCheckpointed(scope, state, owned, checkpoint, 'seat changed')\n state.forceNewSession = true\n }\n return {\n checkpointAt: checkpoint.at,\n checkpointId: checkpoint.checkpoint.checkpointId,\n sourceEnvironmentId: checkpoint.environmentId,\n }\n}\n\n/** An exhausted seat chain pauses its manager until `resumeAt` with no turn to run: on\n * magnetar-rust-sandbox-20261031b (Runtime 3.0.5) a resume paused four managers until 11-04 with\n * their 16 GiB boxes running. Retire a box its latest checkpoint holds; the next drive restores. */\nexport async function releaseScopeRetainedOwnerForSeatPause(\n scope: Scope<unknown>,\n resumeAt: string,\n): Promise<void> {\n const state = owners.get(scope)\n if (state?.provider === undefined) return\n const owned = await checkpointOwner(scope, state)\n const at = owned.map((event) => event.kind).lastIndexOf('workspace-checkpoint')\n const checkpoint = owned[at]\n const later = owned.slice(at + 1).some((event) => event.kind.startsWith('execution-'))\n if (checkpoint?.kind === 'workspace-checkpoint' && !later)\n await retireCheckpointed(scope, state, owned, checkpoint, `seat paused until ${resumeAt}`)\n}\n\nasync function checkpointOwner(scope: Scope<unknown>, state: OwnerState): Promise<SpawnEvent[]> {\n await scopeRetainedOwnerTurnEnded(scope)\n await reconcileOwnerWorkspaceBeforeReuse(state, scope.signal)\n await state.checkpointing\n await checkpointOwnerWorkspace(scope, state)\n return ((await state.args.journal.loadTree(state.args.rootId)) ?? []).filter(\n (event) => event.id === state.args.nodeId,\n )\n}\n\n/** Retire a checkpointed environment whose capture is complete, and commit the teardown so\n * recovery never tries its old session; the next one receives fresh create-time credentials. */\nasync function retireCheckpointed(\n scope: Scope<unknown>,\n { provider, args, nextSequence }: OwnerState,\n owned: readonly SpawnEvent[],\n { environmentId }: { readonly environmentId: string },\n detail: string,\n): Promise<void> {\n if ((await ownerWorkspaceRetentionFailures(owned, args, true)).has(environmentId)) return\n if (!provider?.get)\n throw new ValidationError('seat change requires a provider with exact environment lookup')\n const unusable = (event: SpawnEvent) =>\n event.kind === 'environment-teardown' &&\n event.destroyed &&\n event.environmentId === environmentId\n if (owned.some(unusable)) return\n const signal = AbortSignal.any([scope.signal, AbortSignal.timeout(30_000)])\n const environment = await runAbortable(\n () => provider.get!(environmentId),\n signal,\n 'seat change environment lookup timed out',\n )\n if (environment !== null) {\n if (\n environment.id !== environmentId ||\n environment.provider !== provider.name ||\n !environment.destroy\n ) {\n throw new ValidationError('seat change cannot retire the exact source environment')\n }\n await runAbortable(() => environment.destroy!(), signal, 'seat change retirement timed out')\n }\n await args.journal.appendEvent(args.rootId, {\n kind: 'environment-teardown',\n id: args.nodeId,\n provider: provider.name,\n environmentId,\n destroyed: true,\n detail,\n seq: nextSequence(),\n at: new Date(args.now()).toISOString(),\n })\n}\n","import { ValidationError } from '../../errors'\nimport type { DriverAttemptRecord } from './driver-attempt-evidence'\nimport type { TeamProgress } from './progress'\nimport {\n releaseScopeRetainedOwnerEnvironment,\n scopeRetainedOwnerSettled,\n} from './retained-scope-owner'\nimport type { LiveChild } from './scope-contract'\nimport type {\n HeldEnvironment,\n ProviderModelExecutionEvidence,\n Scope,\n SpawnEvent,\n Spend,\n SubtreeSummary,\n UnconfirmedTeardown,\n} from './types'\n\ntype RuntimeOwnedProviderMeter = (\n spend: Spend,\n providerModel: ProviderModelExecutionEvidence | undefined,\n detail?: Record<string, unknown>,\n accountingOnly?: boolean,\n alreadySpent?: boolean,\n) => Promise<void>\n\n/** Runtime-owned provider evidence is written through this private scope capability. */\nexport const runtimeOwnedProviderMeters = new WeakMap<object, RuntimeOwnedProviderMeter>()\n/** What {@link recordScopeOwnerPause} journals, less the fields the scope supplies. */\ntype ScopeOwnerPause = Omit<Extract<SpawnEvent, { kind: 'paused' }>, 'kind' | 'id' | 'seq' | 'at'>\nexport const pauseRecorders = new WeakMap<object, (pause: ScopeOwnerPause) => Promise<void>>()\n/** What {@link recordScopeOwnerBarrenPause} journals, less the fields the scope supplies. */\ntype ScopeOwnerBarrenPause = Omit<\n Extract<SpawnEvent, { kind: 'barren-pause' }>,\n 'kind' | 'id' | 'seq' | 'at'\n>\nexport const barrenPauseRecorders = new WeakMap<\n object,\n (pause: ScopeOwnerBarrenPause) => Promise<void>\n>()\nexport const driverAttemptRecorders = new WeakMap<\n object,\n (record: DriverAttemptRecord) => Promise<void>\n>()\nexport const recoveryStarters = new WeakMap<object, () => Promise<void>>()\nexport const retainedReleasers = new WeakMap<object, () => Promise<void>>()\nexport const heldReleasers = new WeakMap<object, () => Promise<void>>()\nexport const childDrains = new WeakMap<object, () => Promise<void>>()\nexport const retainedSlotClosers = new WeakMap<object, () => Promise<void>>()\nexport const teardownRetriers = new WeakMap<object, () => Promise<void>>()\nexport const teardownRetriable = new WeakMap<object, (release: boolean) => boolean>()\n/** The retained owner environments a scope's last release could not confirm destroyed. */\nconst ownerUnconfirmedByScope = new WeakMap<object, ReadonlyArray<UnconfirmedTeardown>>()\n/** The scope a recursive executor owns, so the settlement retry reaches its descendants. */\nexport const nestedTeardownScopes = new WeakMap<object, () => Scope<unknown> | undefined>()\n/** Each scope's reader of the manager scopes its children own, read live. */\nexport const nestedManagerScopeReaders = new WeakMap<object, () => Scope<unknown>[]>()\n/** A manager scope's release of its own environment, started once and joined by later callers. */\nconst managerEnvironmentReleases = new WeakMap<object, Promise<void>>()\n/** Scopes whose settlement released retained environments: none of their retained children is\n * kept for a resume any longer. */\nexport const releasingScopes = new WeakSet<object>()\nexport const admissionSeals = new WeakMap<object, () => void>()\n/** Each scope's reader of its own team, for the settlement its owner writes one level up. */\nexport const subtreeReaders = new WeakMap<object, () => SubtreeSummary | undefined>()\n/** A scope's live team and its owner's own turns, as the owner's lead observes them. */\nexport interface LiveTeam extends TeamProgress {\n /** Newest activity anywhere in the scope: the owner's own turn, or any agent below it. */\n readonly lastActivityAt: number\n /** Turns the scope's owner metered for itself. */\n readonly ownerTurns: number\n}\n/** Each scope's reader of its live team, for the progress its owner's lead reads mid-flight. */\nexport const liveTeamReaders = new WeakMap<object, () => LiveTeam>()\n\n/** How many of a manager's direct children its summary lists; the counts always cover all. */\nexport const SUBTREE_RESULT_LIMIT = 8\n\n/** @internal The bounded account of the children a scope spawned and everything below them.\n * `undefined` when the scope spawned no worker. */\nexport function subtreeSummaryOf(scope: Scope<unknown>): SubtreeSummary | undefined {\n return subtreeReaders.get(scope)?.()\n}\n\n/** Per-child bound on a retained release: one remote destroy, answered or abandoned. */\nexport const RETAINED_RELEASE_TIMEOUT_MS = 30_000\n\n/**\n * One unconfirmed child as the run names it: the node, the environments its executor still\n * reports holding, and what the last teardown attempt answered.\n *\n * Environments split by intent. Those kept on purpose go in `kept`, so a sweeper that deletes\n * `environments` never destroys work a resume would recover or evidence preserved on purpose.\n * The executor marks what it preserves as evidence. A retained-pending child is kept for a resume\n * until its scope releases retained environments at settlement: `releasing` says whether it has.\n * After a release, a retained environment still held is a leak like any other.\n */\nexport function unconfirmedTeardownOf(child: LiveChild, releasing: boolean): UnconfirmedTeardown {\n const keptForResume = child.recoveryPending === true && !releasing\n const environments: HeldEnvironment[] = []\n const kept: HeldEnvironment[] = []\n try {\n for (const environment of child.readHeldEnvironments?.() ?? []) {\n const keptFor = environment.keptFor ?? (keptForResume ? 'resume' : undefined)\n const named = Object.freeze({\n provider: environment.provider,\n environmentId: environment.environmentId,\n ...(keptFor === undefined ? {} : { keptFor }),\n })\n if (keptFor === undefined) environments.push(named)\n else kept.push(named)\n }\n } catch {\n // The read is contractually non-throwing; one that throws names nothing rather than failing\n // the barrier that reports the leak.\n }\n return Object.freeze({\n id: child.id,\n label: child.label,\n runtime: child.runtime,\n status: child.status,\n ...(environments.length === 0 ? {} : { environments: Object.freeze(environments) }),\n ...(kept.length === 0 ? {} : { kept: Object.freeze(kept) }),\n ...(child.teardownAttempts > 0 ? { attempts: child.teardownAttempts } : {}),\n ...(child.teardownDetail === undefined ? {} : { detail: child.teardownDetail }),\n })\n}\n\n/** Ten minutes: a manager that is alive decides within a turn or two; one that crashed, or a host\n * that restarted, must not leave a paid environment running until a retire pass finds it. */\nexport const DEFAULT_BUDGET_STOP_HOLD_MS = 600_000\n\n/**\n * @internal Release every environment this scope's settled children still hold after a budget\n * stop, at the join barrier: no later spawn of this scope can continue them. Each release journals\n * an `environment-teardown` with `heldRelease: 'scope-join'`. Never rejects.\n */\nexport async function releaseHeldEnvironments(scope: Scope<unknown>): Promise<void> {\n await heldReleasers.get(scope)?.()\n}\n\n/** @internal Admit original children before the parent acts; do not wait for their results. */\nexport async function startScopeRecoveries(scope: Scope<unknown>): Promise<void> {\n const start = recoveryStarters.get(scope)\n if (!start) return\n recoveryStarters.delete(scope)\n await start()\n}\n\n/**\n * @internal Release what this scope's settled children still hold for a retained execution, and\n * confirm each one's teardown afterwards through the executor's own teardown verb.\n *\n * A retained-pending child settles `down` with its cursor slot open and its environment alive,\n * because a resumed process reconciles the paid execution inside it. The supervisor calls this\n * once the root has reached a terminal outcome that no later process resumes — never while the\n * root is live, and never on a resumable interruption, since the open slot and the live\n * environment are exactly what a resume recovers. One `environment-teardown` receipt is journaled\n * per environment, on this scope's own tree; a nested manager reaches its children through\n * `Executor.releaseRetained`, and its nested scope journals theirs.\n */\nexport async function releaseRetainedEnvironments(\n scope: Scope<unknown>,\n): Promise<ReadonlyArray<UnconfirmedTeardown>> {\n releasingScopes.add(scope)\n const release = retainedReleasers.get(scope)\n if (release) await release()\n // A nested manager whose own teardown confirmed is not among the children `release` reaches,\n // and it still holds the environment it kept between its turns.\n await releaseNestedManagerEnvironments(scope)\n ownerUnconfirmedByScope.set(scope, await releaseScopeRetainedOwnerEnvironment(scope))\n return unconfirmedTeardowns(scope)\n}\n\n/** The manager scopes this scope's children own, read live. */\nfunction nestedManagerScopes(scope: Scope<unknown>): Scope<unknown>[] {\n return nestedManagerScopeReaders.get(scope)?.() ?? []\n}\n\nasync function releaseNestedManagerEnvironments(scope: Scope<unknown>): Promise<void> {\n await Promise.all(\n nestedManagerScopes(scope).map(async (nested) => {\n await releaseNestedManagerEnvironments(nested)\n // One a retained release already reached keeps that release's answer.\n if (!ownerUnconfirmedByScope.has(nested)) await releaseManagerEnvironment(nested)\n }),\n )\n}\n\n/**\n * @internal Release a finished manager's environment and the retained executions of the children\n * its completion aborted: no resume re-enters a settled manager, so none reconciles them (on\n * magnetar-rust-sandbox-20261031b six kept running sandboxes for hours). It waits for the manager's\n * last end-of-turn capture, so it runs beside the settlement; later calls join it.\n */\nexport function releaseManagerEnvironment(scope: Scope<unknown>): Promise<void> {\n let release = managerEnvironmentReleases.get(scope)\n if (release === undefined) {\n release = Promise.all([\n retainedReleasers.get(scope)?.(),\n releaseScopeRetainedOwnerEnvironment(scope),\n ]).then(() => undefined)\n managerEnvironmentReleases.set(scope, release)\n }\n return release\n}\n\n/**\n * @internal Wait for the work every manager in this scope's tree still has in flight after its\n * node settled: the end-of-turn capture its last turn handed over, and the release of its\n * environment. The run's settlement awaits it under either retention policy, so nothing writes to\n * the run's journal after the run settles and no capture is cut short by the process exiting.\n */\nexport async function settleManagerWork(scope: Scope<unknown>): Promise<void> {\n await Promise.all(nestedManagerScopes(scope).map((nested) => settleManagerWork(nested)))\n await scopeRetainedOwnerSettled(scope)\n await managerEnvironmentReleases.get(scope)?.catch(() => undefined)\n}\n\n/**\n * @internal Close the cursor slot of every retained child this scope and its nested scopes still\n * hold open, once the settlement is final and the release and its retries are done.\n *\n * The release sweep closes a slot only when it confirms the environment destroyed, and nothing\n * else ever closed the rest: a refused delete, a teardown probe that failed after a destroy, or an\n * admission that timed out before `create` named an environment. Measured on the Discovery fleet\n * of 2026-09-23/24 (Runtime 0.249.1 to 0.261.0): 338 of 1,620 agents never settled, so they had no\n * terminal record, no spend but the reservation ceiling, and no transcript receipt (#1301). A\n * settlement under `retainedAtSettlement: 'release'` is final, so no process will recover these\n * executions. Each slot closes with the settlement the driver already received, under the seq it\n * saw, marked `retainedExecution: 'release-unconfirmed'`. The environment it may still hold stays\n * named by its `teardown-unconfirmed` record for a sweeper. Never call this on a run a later\n * process may resume.\n */\nexport async function closeRetainedSlots(scope: Scope<unknown>): Promise<void> {\n const close = retainedSlotClosers.get(scope)\n if (close) await close()\n}\n\n/**\n * @internal Everything this scope cannot prove destroyed: its settled children whose teardown is\n * unconfirmed and, after a release, the retained owner environment that release could not\n * confirm. Read live, so a later retry that confirms a node removes it.\n */\nexport function unconfirmedTeardowns(scope: Scope<unknown>): ReadonlyArray<UnconfirmedTeardown> {\n return [...scope.workerCapacity.unconfirmed, ...(ownerUnconfirmedByScope.get(scope) ?? [])]\n}\n\n/** @internal Let the settlement retry reach the scope a recursive executor owns. */\nexport function registerNestedTeardownScope(\n executor: object,\n read: () => Scope<unknown> | undefined,\n): void {\n nestedTeardownScopes.set(executor, read)\n}\n\n/**\n * @internal Ask each settled child whose teardown is still unconfirmed to tear down once more,\n * and resolve when every attempt has answered.\n *\n * A child's first teardown runs inside its settlement with a short acknowledgement window, and a\n * provider delete that fails once or answers late then leaves its sandbox running for good. This\n * is one retry pass; the supervisor paces passes with backoff inside a bounded window, and a\n * nested manager runs one pass over its own scope each time its teardown is asked again, so the\n * retry reaches every level of the tree.\n *\n * A retained-pending child is skipped: its executor answers `destroyed: false` by construction\n * while a resume may still reconcile it, and `releaseRetainedEnvironments` owns its release. An\n * attempt still in flight from an earlier pass is awaited, never duplicated. Never rejects.\n */\nexport async function retryUnconfirmedTeardowns(scope: Scope<unknown>): Promise<void> {\n const retry = teardownRetriers.get(scope)\n if (retry) await retry()\n}\n\n/**\n * @internal Whether another retry can still change this scope's unconfirmed set. With `release`\n * the run releases retained environments at settlement, so a retained child or owner whose\n * release failed can still be released again; without it those are kept for a resume, and only\n * an ordinary unconfirmed teardown counts.\n */\nexport function hasRetriableTeardowns(scope: Scope<unknown>, release: boolean): boolean {\n return teardownRetriable.get(scope)?.(release) ?? false\n}\n\n/**\n * @internal Close this scope to NEW children. Idempotent, synchronous, and irreversible.\n *\n * The supervisor calls it the instant the root `act` has settled, before the join barrier drains.\n * A driver's `act` returning does not stop everything that holds its scope: a supervisor tool\n * whose handler outran its response fence keeps running detached (`single-flight-tools`\n * `background()`) with the coordination verbs still bound, and a verb call reaches `spawn`\n * in-process — closing the MCP listener does not reach it. Such a handler\n * spawned `distill:all` 309 ms after the barrier had drained and released. The child was\n * admitted, took a conserved reservation, built a sandbox, ran 12.4 s of provider work, and\n * journaled its settlement 19 s after the run had already written its failure — while the live\n * reservation it legitimately held was read back at the barrier as a conserved-pool leak and\n * threw away 63 settled children.\n *\n * Nothing admitted here could reach the result anyway: the driver has already selected over the\n * settled ledger. Sealing is total because `spawn` never suspends between this gate and the\n * point the child is registered and its ticket marked `executing`, so no spawn can straddle it.\n *\n * Not a `Scope` method: an Agent must not be able to close its own siblings out of the run.\n */\nexport function closeScopeAdmission(scope: Scope<unknown>): void {\n admissionSeals.get(scope)?.()\n}\n\n/** Join local observers after abort without requiring a writable settlement journal. */\nexport async function waitForScopeChildren(scope: Scope<unknown>): Promise<void> {\n await childDrains.get(scope)?.()\n}\n\n/** @internal Meter one Runtime-owned provider attempt into the durable scope journal. */\nexport function meterRuntimeOwnedProviderAttempt(\n scope: Scope<unknown>,\n spend: Spend,\n providerModel: ProviderModelExecutionEvidence,\n detail?: Record<string, unknown>,\n): Promise<void> {\n const meter = runtimeOwnedProviderMeters.get(scope as object)\n if (meter === undefined) {\n throw new ValidationError('scope: Runtime-owned provider meter is not bound to this scope')\n }\n return meter(spend, providerModel, detail)\n}\n\n/**\n * @internal Journal that this scope's owner paused on an unavailable upstream. The pause is the\n * owner's, so it is recorded against the owner node, beside its `metered` turns.\n */\nexport function recordScopeOwnerPause(\n scope: Scope<unknown>,\n pause: ScopeOwnerPause,\n): Promise<void> {\n const record = pauseRecorders.get(scope as object)\n if (record === undefined) {\n throw new ValidationError('scope: pause recorder is not bound to this scope')\n }\n return record(pause)\n}\n\n/**\n * @internal Journal that this scope's owner paused before a continuation because its barren\n * streak reached `continuation.maxBarren`. Recorded against the owner node.\n */\nexport function recordScopeOwnerBarrenPause(\n scope: Scope<unknown>,\n pause: ScopeOwnerBarrenPause,\n): Promise<void> {\n const record = barrenPauseRecorders.get(scope as object)\n if (record === undefined) {\n throw new ValidationError('scope: barren pause recorder is not bound to this scope')\n }\n return record(pause)\n}\n\n/** @internal Persist the owner's driver outcome even after its scope has been aborted. */\nexport function recordScopeOwnerDriverAttempt(\n scope: Scope<unknown>,\n attempt: DriverAttemptRecord,\n): Promise<void> {\n const record = driverAttemptRecorders.get(scope as object)\n if (record === undefined) {\n throw new ValidationError('scope: driver attempt recorder is not bound to this scope')\n }\n return record(attempt)\n}\n\n/**\n * @internal Meter Runtime-owned accounting that does not represent provider execution.\n * `alreadySpent` marks work that finished with no caller left to refuse it: under a dollar cap its\n * unknown dollars close dollar admission instead of being refused (`BudgetPool.observe`).\n */\nexport function meterRuntimeOwnedAccounting(\n scope: Scope<unknown>,\n spend: Spend,\n detail?: Record<string, unknown>,\n options?: { readonly alreadySpent?: boolean },\n): Promise<void> {\n const meter = runtimeOwnedProviderMeters.get(scope as object)\n if (meter === undefined) {\n throw new ValidationError('scope: Runtime-owned provider meter is not bound to this scope')\n }\n return meter(spend, undefined, detail, true, options?.alreadySpent === true)\n}\n","/**\n *\n * `rollingDispatch` — the REFILLING dispatch policy over a `Scope`. It keeps `width` children in\n * flight and admits the next queued unit of work the instant one settles, instead of waiting for\n * a whole round to drain (`fanout`) or for a driver to decide again (`spawn → await → spawn`).\n *\n * The gap it closes: `fanout` opens every item at once and then drains — one round, no refill —\n * and a driver brain's manual loop opens one worker per model turn. Between those two there was\n * nothing that holds N slots full, which is why a 5-worker run can peak at 2 live workers and sit\n * ~50% idle. This is a policy over the EXISTING `Scope.spawn` / `Scope.next` primitives: it adds\n * no second admission path, so the conserved budget pool stays the only fence on total work and\n * `width` is only a fence on simultaneous work.\n *\n * Fail-closed by construction: an admission rejection (`budget-exhausted` / `depth-exceeded`) is\n * recorded and STOPS further admission — the loop then drains what is already live and returns.\n * It never retries a rejected spawn against the same pool, and it never spawns past `width`.\n *\n * ── Concurrency ────────────────────────────────────────────────────────────────────────────────\n *\n * `width` bounds the children THIS dispatcher holds in flight. The tree-wide bound on working\n * agents is `SuperviseOptions.workerSlots` (`./worker-slots`): a spawn past it is queued by the\n * scope, not refused, so a `width` above the free slots only lengthens the allocator's queue.\n * `SandboxLineage`'s fork concurrency bounds boxes inside ONE leaf's fork wave, a different unit.\n *\n * ── Why this is not a copy of the kernel's batch loop ──────────────────────────────────────────\n *\n * `runBatch` (`src/runtime/run-loop.ts`) runs the same hold-N-slots-full shape over the KERNEL's\n * substrate: bare promises in a `Set`, raced with `Promise.race`, bounded by `maxConcurrency`.\n * This one runs it over the SUPERVISOR's substrate — `Scope.spawn`'s atomic reservation against\n * the conserved pool, `Scope.next`'s journaled settlement cursor, and the blob store behind each\n * result. Neither can be expressed in the other's terms without dragging its whole substrate\n * along: the kernel loop has no budget to reserve and no cursor to order settlements by, and this\n * one cannot race raw promises because a settlement is only real once it is journaled. The shape\n * repeating across the two deliberate layers is resonance, not duplication — do not \"unify\" them\n * into a shared helper that would have to know about both.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport type { Agent, Budget, NodeId, Scope, Settled, SpawnOpts } from './types'\n\n/** One unit of queued work: the agent to run, its task, and the spawn options (budget + label).\n * `nextUnit` mints these lazily so a queue can be generated, re-ordered, or grown while the\n * dispatcher runs. */\nexport interface DispatchUnit<Out> {\n readonly agent: Agent<unknown, Out>\n readonly task: unknown\n readonly opts: SpawnOpts\n}\n\n/** Why the dispatcher stopped admitting work. `drained` = the queue ran dry (the ordinary end);\n * `not-admitted` = the conserved pool or the depth ceiling refused a spawn; `stopped` = the\n * caller's `shouldStop` returned true; `aborted` = the scope's signal fired. */\nexport type DispatchStopReason = 'drained' | 'not-admitted' | 'stopped' | 'aborted'\n\nexport interface RollingDispatchOptions<Out> {\n /**\n * How many children to hold in flight. Must be a positive integer. This is a SIMULTANEITY fence\n * only — the conserved pool still bounds total work, and a `width` larger than the pool can\n * afford simply hits `not-admitted` sooner.\n */\n readonly width: number\n /**\n * Produce the next unit of work, or `undefined` when the queue is dry. Called only when a slot\n * is free, so a caller may compute the next unit from what has already settled (the point of a\n * refilling dispatcher: the queue is allowed to react). Never called after a stop.\n */\n nextUnit(): DispatchUnit<Out> | undefined | Promise<DispatchUnit<Out> | undefined>\n /**\n * Called once per settlement, in cursor order, BEFORE the freed slot is refilled — so an\n * `onSettled` that appends to the caller's queue is visible to the very next `nextUnit`.\n */\n onSettled?(settled: Settled<Out>): void | Promise<void>\n /**\n * Consulted before each admission. `true` stops admitting; the already-live children are still\n * drained to completion (no orphan, no lost settlement). Use it for a progress/plateau rule.\n */\n shouldStop?(): boolean\n}\n\nexport interface DispatchReport<Out> {\n /** Every settlement, in the order `scope.next()` yielded them. */\n readonly settled: ReadonlyArray<Settled<Out>>\n /** How many children this dispatcher admitted. */\n readonly admitted: number\n /** Admission rejections, in order — `label: reason`. Non-empty ⇒ the pool or depth fenced. */\n readonly rejected: ReadonlyArray<string>\n readonly stopReason: DispatchStopReason\n /** The highest simultaneous live count actually reached — the number to compare against\n * `width` when asking \"did the slots really stay full?\" */\n readonly peakLive: number\n}\n\n/**\n * Run the refilling dispatch loop over `scope` until the queue is dry (or a stop fires) and every\n * admitted child has settled. Returns the settlements in cursor order plus the admission ledger.\n *\n * The loop is: fill free slots from `nextUnit` → `await scope.next()` → deliver the settlement →\n * refill → repeat. Because the refill happens immediately after each settlement rather than after\n * a whole round, a slow child never idles the other slots.\n */\nexport async function rollingDispatch<Out>(\n scope: Scope<Out>,\n opts: RollingDispatchOptions<Out>,\n): Promise<DispatchReport<Out>> {\n if (!Number.isInteger(opts.width) || opts.width < 1) {\n throw new ValidationError(\n `rollingDispatch: width must be a positive integer, got ${String(opts.width)}`,\n )\n }\n\n const settled: Settled<Out>[] = []\n const rejected: string[] = []\n const live = new Set<NodeId>()\n let admitted = 0\n let peakLive = 0\n let queueDry = false\n let stopReason: DispatchStopReason = 'drained'\n\n // Fill every free slot from the queue. Returns false when nothing further may be admitted\n // (queue dry, caller stop, pool/depth rejection, or abort) — the caller then only drains.\n const fill = async (): Promise<void> => {\n while (live.size < opts.width) {\n if (queueDry) return\n if (scope.signal.aborted) {\n stopReason = 'aborted'\n queueDry = true\n return\n }\n if (opts.shouldStop?.() === true) {\n stopReason = 'stopped'\n queueDry = true\n return\n }\n const unit = await opts.nextUnit()\n if (unit === undefined) {\n queueDry = true\n return\n }\n // The ONE admission path: the scope's own atomic reservation. The scope already waits for\n // what live children will refund, so a rejection means nothing running could fund this\n // unit, and it is terminal for this dispatcher: admitting a DIFFERENT unit past it would\n // silently reorder the caller's queue.\n const res = scope.spawn(unit.agent, unit.task, unit.opts)\n if (!res.ok) {\n rejected.push(`${unit.opts.label}: ${res.reason}`)\n stopReason = 'not-admitted'\n queueDry = true\n return\n }\n live.add(res.handle.id)\n admitted += 1\n if (live.size > peakLive) peakLive = live.size\n }\n }\n\n await fill()\n while (live.size > 0) {\n const s = await scope.next()\n // `next()` is null only when the scope's live set is empty; this dispatcher may share the\n // scope with children it did not admit, so treat null as \"nothing of ours left to await\".\n if (s === null) break\n live.delete(s.handle.id)\n settled.push(s)\n await opts.onSettled?.(s)\n await fill()\n }\n\n return { settled, admitted, rejected, stopReason, peakLive }\n}\n\n/**\n * Free worker slots under a simultaneity cap: `cap - live`, floored at 0, or `null` when there is\n * no cap (the conserved pool is then the only fence and \"free slots\" is not a finite number).\n * The one place the answer is computed, so the driver-facing tool payload and a dispatcher agree.\n */\nexport function freeSlots(liveCount: number, cap: number | undefined): number | null {\n if (cap === undefined || cap <= 0) return null\n return Math.max(0, cap - liveCount)\n}\n\n/** Convenience: a `DispatchUnit` factory over a fixed array of tasks, for the common case where\n * the queue is known up front and only the refill behavior is wanted. */\nexport function queueOf<Out>(\n units: ReadonlyArray<{ agent: Agent<unknown, Out>; task: unknown; label: string }>,\n budget: Budget,\n): () => DispatchUnit<Out> | undefined {\n let i = 0\n return () => {\n const u = units[i]\n if (u === undefined) return undefined\n i += 1\n return { agent: u.agent, task: u.task, opts: { budget, label: u.label } }\n }\n}\n","import { canonicalCandidateDigest, sha256DigestSchema } from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport { authoredProfileDigest } from './materialization'\nimport type { AgentSpec, NodeExecutionIdentity, RecursiveReservationPolicy } from './types'\n\n/** Fail before execution when a reservation policy is malformed. */\nexport function assertRecursiveReservationPolicy(\n policy: RecursiveReservationPolicy | undefined,\n): void {\n if (policy === undefined) return\n if (\n typeof policy !== 'object' ||\n policy === null ||\n Object.keys(policy).some((key) => key !== 'ownerShare')\n ) {\n throw new ValidationError('reservationPolicy accepts only ownerShare')\n }\n if (!Number.isFinite(policy.ownerShare) || policy.ownerShare <= 0 || policy.ownerShare >= 1) {\n throw new ValidationError('reservationPolicy.ownerShare must be greater than 0 and less than 1')\n }\n}\n\nexport function deriveNodeExecutionIdentity(\n spec: Pick<AgentSpec, 'profile' | 'execution'>,\n task: unknown,\n): NodeExecutionIdentity | undefined {\n const digest = (value: unknown) => {\n try {\n return canonicalCandidateDigest(value)\n } catch {\n return undefined\n }\n }\n const profileDigest = authoredProfileDigest(spec.profile)\n const taskDigest = digest(task)\n const candidateDigest = spec.execution?.candidateDigest\n if (candidateDigest !== undefined && !sha256DigestSchema.safeParse(candidateDigest).success) {\n throw new ValidationError('scope.spawn: execution.candidateDigest must be a sha256 digest')\n }\n const correlation = freezeCorrelation(spec.execution?.correlation)\n if (!profileDigest && !taskDigest && !candidateDigest && !correlation) return undefined\n return Object.freeze({\n ...(profileDigest ? { profileDigest } : {}),\n ...(taskDigest ? { taskDigest } : {}),\n ...(candidateDigest ? { candidateDigest } : {}),\n ...(correlation ? { correlation } : {}),\n })\n}\n\nexport function isCompleteIdentity(\n identity: NodeExecutionIdentity | undefined,\n): identity is NodeExecutionIdentity & {\n readonly profileDigest: string\n readonly taskDigest: string\n} {\n return identity?.profileDigest !== undefined && identity.taskDigest !== undefined\n}\n\nexport function sameNodeExecutionIdentity(\n a: NodeExecutionIdentity,\n b: NodeExecutionIdentity,\n): boolean {\n return canonicalCandidateDigest(a) === canonicalCandidateDigest(b)\n}\n\nfunction freezeCorrelation(\n value: Readonly<Record<string, string>> | undefined,\n): Readonly<Record<string, string>> | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('scope.spawn: execution.correlation must be a string record')\n }\n const entries = Object.entries(value)\n for (const [key, item] of entries) {\n if (key.length === 0 || typeof item !== 'string' || item.length === 0) {\n throw new ValidationError(\n 'scope.spawn: execution.correlation keys and values must be non-empty strings',\n )\n }\n }\n return Object.freeze(Object.fromEntries(entries))\n}\n\n/** An `AgentSpec` is identified structurally — it carries a `profile` and a `harness`\n * field (`null` or a `BackendType`) and optionally an `executor`. */\nexport function isAgentSpec(value: unknown): value is AgentSpec {\n if (typeof value !== 'object' || value === null) return false\n const v = value as Record<string, unknown>\n return 'profile' in v && 'harness' in v\n}\n","import { ValidationError } from '../../errors'\nimport type { Iteration } from '../types'\nimport { cloneTokenUsage } from '../util'\nimport { isLiveNodeStatus, isTerminalNodeStatus } from './node-status'\nimport type { TeamProgress } from './progress'\nimport { type LiveTeam, liveTeamReaders, SUBTREE_RESULT_LIMIT } from './scope-capabilities'\nimport type { LiveChild, ScopeArgs } from './scope-contract'\nimport type {\n Handle,\n NodeId,\n NodeSnapshot,\n ReenteredWorkers,\n Scope,\n Settled,\n SubtreeResult,\n SubtreeSummary,\n TreeView,\n WorkerInteractiveSession,\n WorkerInteractiveUnavailableReason,\n} from './types'\n\n/**\n * The direct workers of `parentId` that a resumed journal holds open, and which of them this\n * process re-places through a retained recovery. One function, so the root's `root-reentered`\n * record and its first re-entered drive cannot disagree.\n */\nexport function reenteredWorkers(\n resumeFrom: NonNullable<ScopeArgs['resumeFrom']>,\n parentId: NodeId,\n): ReenteredWorkers {\n const live = resumeFrom.view.nodes\n .filter((node) => node.parent === parentId && isLiveNodeStatus(node.status))\n .map((node) => node.id)\n const recovering = new Set((resumeFrom.recoveries ?? []).map((recovery) => recovery.spawned.id))\n return { live, replaced: live.filter((id) => recovering.has(id)) }\n}\n\n/**\n * The step-8 merge-boundary adapter (M4): rehydrate a `Settled.done` into the kernel's\n * `Iteration` shape so `defaultSelectWinner` stays single-sourced — the supervisor selects\n * across settled children with the SAME argmax the loop kernel uses, not a forked copy.\n *\n * `index` is the cursor `seq` (the recorded, replay-stable order); `output`/`verdict`/\n * `tokenUsage`/`costUsd` are read straight off the settlement (already rehydrated from the\n * `outRef` blob by `next()`). Events are empty — a settled child is an opaque leaf result,\n * not a sandbox event stream — and the timing/cost fields project its conserved `Spend`.\n * Fail loud on a `down` settlement: only a `done` child is an iteration.\n */\nexport function settledToIteration<Out>(settled: Settled<Out>): Iteration<unknown, Out> {\n if (settled.kind === 'down') {\n throw new ValidationError(\n `settledToIteration: cannot adapt a 'down' settlement (node '${settled.handle.id}', seq ${settled.seq}) to an Iteration`,\n )\n }\n return {\n index: settled.seq,\n task: undefined,\n agentRunName: settled.handle.label,\n output: settled.out,\n ...(settled.verdict ? { verdict: settled.verdict } : {}),\n events: [],\n startedAt: 0,\n endedAt: settled.spent.ms,\n costUsd: settled.spent.usd,\n tokenUsage: cloneTokenUsage(settled.spent.tokens),\n }\n}\n\n/** The live team a child manager leads, read through the nested scope it owns. */\nexport function liveTeamOf(child: LiveChild): LiveTeam | undefined {\n let nested: Scope<unknown> | undefined\n try {\n nested = child.readNestedScope?.()\n } catch {\n return undefined\n }\n return nested === undefined ? undefined : liveTeamReaders.get(nested)?.()\n}\n\nexport function teamProgress(team: LiveTeam): TeamProgress {\n const { lastActivityAt: _lastActivityAt, ownerTurns: _ownerTurns, ...counts } = team\n return Object.freeze(counts)\n}\n\n/** Latest activity an executor names, or 0. A throwing read is no evidence of activity. */\nfunction executorActivityAt(child: LiveChild): number {\n try {\n const recent = child.readProgress?.()?.recentActivity\n return recent?.length ? (recent[recent.length - 1]?.at ?? 0) : 0\n } catch {\n return 0\n }\n}\n\n/** Count a scope's team at every depth and find its newest activity. Live members are read through\n * their own nested scopes; settled members contribute the summary their settlement carried. */\nexport function readLiveTeam(\n children: Iterable<LiveChild>,\n ownerTurns: number,\n ownerLastTurnAt: number,\n): LiveTeam {\n let agents = 0\n let depth = 0\n let working = 0\n let queued = 0\n let done = 0\n let down = 0\n let lastActivityAt = ownerLastTurnAt\n for (const child of children) {\n agents += 1\n lastActivityAt = Math.max(\n lastActivityAt,\n child.lastActivityAt,\n child.settledAt ?? 0,\n executorActivityAt(child),\n )\n if (child.status === 'done') done += 1\n else if (child.status === 'failed' || child.status === 'cancelled') down += 1\n else if (child.status === 'queued' || child.status === 'pending') queued += 1\n else working += 1\n const below = isTerminalNodeStatus(child.status) ? child.subtree : liveTeamOf(child)\n if (below === undefined || below.agents === 0) continue\n agents += below.agents\n depth = Math.max(depth, below.depth)\n done += below.done\n down += below.down\n if ('working' in below) {\n working += below.working\n queued += below.queued\n lastActivityAt = Math.max(lastActivityAt, below.lastActivityAt)\n }\n }\n return {\n agents,\n depth: agents === 0 ? 0 : depth + 1,\n working,\n queued,\n done,\n down,\n lastActivityAt,\n ownerTurns,\n }\n}\n\nexport function summarizeTeam(children: Iterable<LiveChild>): SubtreeSummary | undefined {\n let agents = 0\n let depth = 0\n let done = 0\n let down = 0\n let members = 0\n const results: Array<SubtreeResult & { readonly order: number }> = []\n for (const child of children) {\n members += 1\n const below = child.subtree\n agents += 1 + (below?.agents ?? 0)\n depth = Math.max(depth, 1 + (below?.depth ?? 0))\n done += below?.done ?? 0\n down += below?.down ?? 0\n const status =\n child.status === 'done'\n ? 'done'\n : child.status === 'failed' || child.status === 'cancelled'\n ? 'down'\n : undefined\n if (status === undefined) continue\n if (status === 'done') done += 1\n else down += 1\n const score =\n child.resolved?.kind === 'done' ? child.resolved.verdict?.score : (undefined as undefined)\n results.push({\n id: child.id,\n label: child.label,\n status,\n ...(child.outRef === undefined ? {} : { outRef: child.outRef }),\n ...(score === undefined ? {} : { score }),\n agents: below?.agents ?? 0,\n order: child.settledSeq ?? Number.MAX_SAFE_INTEGER,\n })\n }\n if (members === 0) return undefined\n results.sort(\n (a, b) =>\n (a.status === b.status ? 0 : a.status === 'done' ? -1 : 1) ||\n (b.score ?? Number.NEGATIVE_INFINITY) - (a.score ?? Number.NEGATIVE_INFINITY) ||\n a.order - b.order,\n )\n const listed = results\n .slice(0, SUBTREE_RESULT_LIMIT)\n .map(({ order: _order, ...result }) => Object.freeze(result))\n return Object.freeze({\n agents,\n depth,\n done,\n down,\n results: Object.freeze(listed),\n omitted: members - listed.length,\n })\n}\n\nexport function makeTreeView(root: NodeId, children: Map<NodeId, LiveChild>): TreeView {\n const nodes: NodeSnapshot[] = [...children.values()].map((c) => ({\n id: c.id,\n parent: root,\n label: c.label,\n status: c.status,\n ...(c.failure === undefined ? {} : { failure: c.failure }),\n runtime: c.runtime,\n budget: c.budget,\n ...(c.ownedTreeRoot === undefined ? {} : { ownedTreeRoot: c.ownedTreeRoot }),\n ...(c.assignmentId === undefined ? {} : { assignmentId: c.assignmentId }),\n ...(c.identity ? { identity: c.identity } : {}),\n ...(c.modelSubstitution ? { modelSubstitution: c.modelSubstitution } : {}),\n ...(c.materialization ? { materialization: c.materialization } : {}),\n ...(c.executionBindings.length > 0\n ? { executionBindings: Object.freeze([...c.executionBindings]) }\n : {}),\n spent: c.spent,\n // Finished but not yet drained: `resolved` is set the moment the executor's promise settles\n // (spawn's `.then` above), while `status` flips only inside `next()`. Surface the window.\n ...(c.resolved !== undefined && !c.delivered\n ? { settlementPending: { kind: c.resolved.kind } }\n : {}),\n ...(c.settledAt === undefined ? {} : { settledAt: c.settledAt }),\n ...(c.outRef ? { outRef: c.outRef } : {}),\n ...(c.trace ? { trace: c.trace } : {}),\n ...(c.providerModel ? { providerModel: c.providerModel } : {}),\n ...(c.budgetViolation ? { budgetViolation: c.budgetViolation } : {}),\n ...(c.retainedExecution ? { retainedExecution: c.retainedExecution } : {}),\n ...(c.retainedPendingCause ? { retainedPendingCause: c.retainedPendingCause } : {}),\n }))\n return {\n root,\n nodes,\n inFlight: nodes.filter(\n (n) => n.status === 'running' || n.status === 'acquiring' || n.status === 'queued',\n ).length,\n }\n}\n\nexport function frozenHandle<C>(child: LiveChild): Handle<C> {\n return {\n id: child.id,\n label: child.label,\n status: child.status,\n ...(child.assignmentId === undefined ? {} : { assignmentId: child.assignmentId }),\n ...(child.identity ? { identity: child.identity } : {}),\n ...(child.modelSubstitution ? { modelSubstitution: child.modelSubstitution } : {}),\n ...(child.materialization ? { materialization: child.materialization } : {}),\n ...(child.executionBindings.length > 0\n ? { executionBindings: Object.freeze([...child.executionBindings]) }\n : {}),\n abort(): void {\n // A settled child is terminal; abort is a no-op (its executor already tore down).\n },\n }\n}\n\n/** The one place an absent interactive process is spelled, so every refusal reads the same. */\nexport function noInteractiveSession(\n reason: WorkerInteractiveUnavailableReason,\n): WorkerInteractiveSession {\n return Object.freeze({ status: 'unavailable' as const, reason })\n}\n\n/** Read one executor's declared interactive capability without letting a malformed port escape. */\nexport function readInteractiveSession(child: LiveChild): WorkerInteractiveSession {\n if (!child.readInteractive) {\n return noInteractiveSession('executor-exposes-no-interactive-session')\n }\n let reported: WorkerInteractiveSession\n try {\n reported = child.readInteractive()\n } catch {\n return noInteractiveSession('executor-exposes-no-interactive-session')\n }\n if (reported?.status === 'unavailable' && reported.reason) return reported\n if (reported?.status === 'available' && reported.handle) return reported\n return noInteractiveSession('executor-exposes-no-interactive-session')\n}\n\n/** Stop waiting for optional readiness when the worker settles or its lifetime is cancelled. */\nexport async function readInteractiveReadyUntilWorkerEnds(\n readReady: () => Promise<WorkerInteractiveSession>,\n workerEnded: Promise<unknown>,\n signal: AbortSignal,\n): Promise<WorkerInteractiveSession | undefined> {\n if (signal.aborted) return undefined\n let resolveAborted!: () => void\n const aborted = new Promise<void>((resolve) => {\n resolveAborted = resolve\n })\n const onAbort = () => resolveAborted()\n signal.addEventListener('abort', onAbort, { once: true })\n try {\n const outcome = await Promise.race([\n Promise.resolve()\n .then(readReady)\n .then((session) => ({ kind: 'ready' as const, session })),\n workerEnded.then(\n () => ({ kind: 'ended' as const }),\n () => ({ kind: 'ended' as const }),\n ),\n aborted.then(() => ({ kind: 'ended' as const })),\n ])\n return outcome.kind === 'ready' ? outcome.session : undefined\n } finally {\n signal.removeEventListener('abort', onAbort)\n }\n}\n","import type { AgentProfile } from '@tangle-network/agent-interface'\n\n/** Runtime-owned coordination is mounted under this MCP alias. */\nexport const coordinationMcpAlias = 'agent-runtime-coordination'\n\n/** A profile declares Runtime-owned tools with this provider-neutral prefix. */\nexport const coordinationProfileToolPrefix = `${coordinationMcpAlias.replaceAll('-', '_')}_`\n\n/** The metadata key under which the root of a `run_graph` subtask carries its graph's topology.\n * Runtime writes it; `spawn_worker` refuses a profile that carries it. */\nexport const runtimeGraphMetadataKey = 'agentRuntimeGraph'\n\n/** Remove Runtime-only grants, seat policy and graph topology from the provider-facing profile. */\nexport function providerVisibleProfile(profile: AgentProfile): AgentProfile {\n const { seats: _seats, ...withoutSeats } = profile as AgentProfile & { seats?: unknown }\n const visible = withoutRuntimeGraph(withoutSeats)\n if (profile.tools === undefined) return visible\n const providerTools = Object.fromEntries(\n Object.entries(profile.tools).filter(\n ([name]) => !name.startsWith(coordinationProfileToolPrefix),\n ),\n )\n if (Object.keys(providerTools).length === Object.keys(profile.tools).length) return visible\n if (Object.keys(providerTools).length > 0) return { ...visible, tools: providerTools }\n const { tools: _runtimeTools, ...withoutTools } = visible\n return withoutTools\n}\n\nfunction withoutRuntimeGraph(profile: AgentProfile): AgentProfile {\n const source = profile.metadata\n if (source === undefined || source[runtimeGraphMetadataKey] === undefined) return profile\n const { [runtimeGraphMetadataKey]: _graph, ...metadata } = source\n if (Object.keys(metadata).length > 0) return { ...profile, metadata }\n const { metadata: _metadata, ...withoutMetadata } = profile\n return withoutMetadata\n}\n","import {\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport {\n authoredProfileDigest,\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n newExecutionAttemptId,\n unknownExecutionBindingReceipt,\n unknownMaterializationReceipt,\n} from './materialization'\nimport { providerVisibleProfile } from './provider-visible-profile'\nimport type { ScopeArgs } from './scope-contract'\nimport { authoredSeatStages, seatExecutionProfile } from './seat-chain'\nimport { detachedSnapshot } from './snapshot'\nimport { assertValidSpend } from './spend-validation'\nimport type {\n ExecutionBindingReceipt,\n ExecutorExecutionBinding,\n ExecutorNodeContext,\n MaterializedExecutionIdentity,\n NodeId,\n NodeSnapshot,\n ProfileMaterializationReceipt,\n ResultBlobStore,\n Scope,\n SpawnEvent,\n SpawnJournal,\n} from './types'\n\ninterface OwnerMaterializationState {\n readonly retainedRoot: NodeId\n readonly blobs: ResultBlobStore\n readonly journal: SpawnJournal\n readonly root: NodeId\n readonly nodeId: NodeId\n readonly depth: number\n readonly runtime: NodeSnapshot['runtime']\n /** Rotated by `beginScopeOwnerAttempt` on every driver attempt after the first. */\n attemptId: string\n readonly authoredProfile?: unknown\n readonly authoredProfileDigest?: Sha256Digest\n readonly prior?: ProfileMaterializationReceipt\n readonly requiredKnown: boolean\n readonly onReceipt?: (\n materialization: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n ) => void\n readonly now: () => number\n receipt?: ProfileMaterializationReceipt\n bindingPublished: boolean\n publishedThisProcess: boolean\n /** The execution the latest attempt started under a pending executor plan, before any\n * acknowledgement. Finalization names it when no receipt ever arrived. */\n plannedExecution?: {\n readonly attemptId: string\n readonly execution: MaterializedExecutionIdentity\n }\n /** The latest owner materialization write; the next one starts after it settles. */\n writes?: Promise<unknown>\n}\n\n/**\n * @internal Record the execution a pending executor started for the current attempt. A bridge\n * manager whose turn ends before the bridge acknowledges it then still names its session:\n * magnetar-rust-20261018b:s2 ran 177 model calls in supervised-manager-46c412bb9975, and its\n * receipts read `root-agent-did-not-report` with no session at all.\n */\nexport function noteScopeOwnerPlannedExecution(\n scope: Scope<unknown>,\n execution: MaterializedExecutionIdentity,\n): void {\n const state = ownerMaterializationStates.get(scope)\n if (state === undefined) return\n state.plannedExecution = Object.freeze({\n attemptId: state.attemptId,\n execution: Object.freeze({ ...execution }),\n })\n}\n\nexport const ownerMaterializationStates = new WeakMap<Scope<unknown>, OwnerMaterializationState>()\n\n/**\n * One owner materialization write at a time. A cancelled run settles without waiting for its root\n * driver, so the driver's late receipt and the settlement's finalization could each read no\n * receipt before the other's journal append returned, and both appended one: the journal then\n * refused the run as corrupted (duplicate materialization receipt).\n */\nfunction serializedOwnerWrite<T>(\n state: OwnerMaterializationState,\n write: () => Promise<T>,\n): Promise<T> {\n const next = (state.writes ?? Promise.resolve()).then(write, write)\n state.writes = next.catch(() => undefined)\n return next\n}\n\n/**\n * @internal Publish exact root-manager materialization from a runtime-owned adapter after dynamic\n * attachments exist and before its executor starts. This is deliberately a module function backed\n * by a private WeakMap, not a Scope method an Agent can call.\n */\nexport async function recordScopeOwnerMaterialization(\n scope: Scope<unknown>,\n runtime: NodeSnapshot['runtime'],\n declaration: import('./types').ExecutorMaterialization,\n bindingInput: ExecutorExecutionBinding,\n): Promise<void> {\n const state = ownerMaterializationState(scope)\n await serializedOwnerWrite(state, () =>\n publishOwnerMaterialization(state, runtime, declaration, bindingInput),\n )\n}\n\nasync function publishOwnerMaterialization(\n state: OwnerMaterializationState,\n runtime: NodeSnapshot['runtime'],\n declaration: import('./types').ExecutorMaterialization,\n bindingInput: ExecutorExecutionBinding,\n): Promise<void> {\n if (runtime !== state.runtime) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError(\n `scope owner materialization runtime ${JSON.stringify(runtime)} does not match ${JSON.stringify(state.runtime)}`,\n )\n }\n if (state.authoredProfileDigest === undefined) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError('scope owner materialization requires an exact authored profile')\n }\n let receipt: ProfileMaterializationReceipt\n let binding: ExecutionBindingReceipt\n try {\n if (bindingInput.attemptId !== state.attemptId) {\n throw new ValidationError(\n 'scope owner execution binding does not use the kernel-minted attempt id',\n )\n }\n receipt = knownMaterializationReceipt({\n authoredProfileDigest: state.authoredProfileDigest,\n runtime,\n declaration,\n })\n binding = knownExecutionBindingReceipt(receipt, bindingInput)\n } catch (error) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError('scope owner returned invalid materialization evidence', {\n cause: error,\n })\n }\n const committed = state.receipt ?? state.prior\n if (\n committed?.status === 'known' &&\n canonicalCandidateDigest(committed) !== canonicalCandidateDigest(receipt)\n ) {\n const events = (await state.journal.loadTree(state.retainedRoot)) ?? []\n const started = [...events]\n .reverse()\n .find(\n (event) =>\n event.id === state.nodeId && event.kind === 'seat-segment' && event.phase === 'started',\n )\n const latestMaterialization = [...events]\n .reverse()\n .find(\n (event) =>\n event.id === state.nodeId &&\n (event.kind === 'materialized' || event.kind === 'seat-materialized'),\n )\n const lastSegmentIndex =\n latestMaterialization?.kind === 'seat-materialized' ? latestMaterialization.segmentIndex : 0\n const authored = agentProfileSchema.safeParse(state.authoredProfile)\n const authoredProfile = authored.success ? authored.data : undefined\n const stage =\n authoredProfile && started?.kind === 'seat-segment'\n ? authoredSeatStages(authoredProfile)?.[started.stageIndex]\n : undefined\n if (\n authoredProfile &&\n stage &&\n started?.kind === 'seat-segment' &&\n started.segmentIndex > lastSegmentIndex &&\n started.harness === stage.harness &&\n started.provider === stage.provider &&\n started.model === stage.model &&\n receipt.status === 'known' &&\n receipt.effectiveProfileDigest ===\n canonicalAgentProfileDigest(\n providerVisibleProfile(seatExecutionProfile(authoredProfile, stage)),\n ) &&\n receipt.model.status === 'known' &&\n receipt.model.id === stage.model\n ) {\n await appendOwnerSeatMaterialization(state, started.segmentIndex, receipt, binding)\n state.onReceipt?.(receipt, binding)\n state.publishedThisProcess = true\n return\n }\n // A root resumed on another segment of its registered profile (another model, effort or harness:\n // `SuperviseOptions.segment`) materializes that segment once, after its `root-segment` record, under the same\n // authored profile. Before this, the resumed root's every drive was refused \"materialization changed mid-run\"\n // until its retry bound (the one-run-one-id canary, 2026-10-08, 14 attempts on gpt-6.1-sol).\n const rootSegment = [...events]\n .reverse()\n .find(\n (event): event is Extract<SpawnEvent, { kind: 'root-segment' }> =>\n event.id === state.nodeId && event.kind === 'root-segment',\n )\n if (\n rootSegment !== undefined &&\n (latestMaterialization === undefined ||\n events.indexOf(rootSegment) > events.indexOf(latestMaterialization)) &&\n receipt.status === 'known' &&\n receipt.authoredProfileDigest === committed.authoredProfileDigest &&\n (rootSegment.to.model === undefined ||\n (receipt.model.status === 'known' && receipt.model.id === rootSegment.to.model))\n ) {\n await appendOwnerSeatMaterialization(state, lastSegmentIndex + 1, receipt, binding)\n state.onReceipt?.(receipt, binding)\n state.publishedThisProcess = true\n return\n }\n }\n if (state.prior !== undefined && state.receipt === undefined) {\n if (canonicalCandidateDigest(state.prior) !== canonicalCandidateDigest(receipt)) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError(\n 'scope owner materialization changed across resume; backend, model, execution identity, and plan must match',\n )\n }\n state.receipt = state.prior\n await appendOwnerBinding(state, binding)\n state.onReceipt?.(state.prior, binding)\n state.publishedThisProcess = true\n return\n }\n if (state.receipt !== undefined && state.receipt.status !== 'known') {\n // The committed receipt is `unknown`: an attempt ended before its agent reported, and\n // finalization recorded that (finalizeOwnerMaterialization). It attests no backend, model, plan\n // or execution identity, so a report that arrives later cannot have changed one. Refusing it\n // as \"changed mid-run: status\" killed owners that had already done their work: a retained\n // owner whose pending executor publishes at result time loses the race to the scope's\n // finalization, and an owner whose first attempt failed before reporting dies on the attempt\n // that succeeds. Measured on Discovery 2026-10-01..05: 20 such refusals, classified terminal,\n // after 5 to 96 minutes of each node's work. The committed record stays `unknown`; an attempt\n // not yet bound binds its transport to it, and an attempt finalization already bound keeps\n // that binding, because the journal holds one binding per attempt.\n if (!state.bindingPublished) {\n const boundToCommitted = knownExecutionBindingReceipt(state.receipt, bindingInput)\n await appendOwnerBinding(state, boundToCommitted)\n state.onReceipt?.(state.receipt, boundToCommitted)\n }\n state.publishedThisProcess = true\n return\n }\n if (state.receipt !== undefined) {\n // A root driver may be re-entered inside one process after a transient executor failure\n // (`runDriverWithRetry`, #741). That attempt publishes the SAME materialization with a NEW\n // execution binding, which is the resume path's shape minus the process boundary — so it\n // appends a binding rather than a second receipt. A materialization that actually CHANGED is\n // still a fault: backend, model, execution identity, and plan may not move under a live run.\n if (canonicalCandidateDigest(state.receipt) !== canonicalCandidateDigest(receipt)) {\n const changed = changedRunIdentityFields(state.receipt, receipt)\n if (changed.length > 0) {\n await rejectOwnerMaterialization(state)\n throw new ValidationError(\n 'scope owner materialization changed mid-run; these fields must match across driver ' +\n `attempts but differ: ${changed.join(', ')}`,\n )\n }\n // The attempt ran in a DIFFERENT execution instance with everything else identical, which is\n // Runtime's own doing: a continuation re-entry asks the provider for a new environment,\n // and a retained environment can be replaced between attempts. Rejecting it stranded a root\n // that had already completed a turn (agent-runtime#1225): the refusal surfaced as a transient\n // RetainedExecutionPendingError and every remaining driver attempt hit the same wall.\n // The committed materialization stays the run's identity — the journal commits one per node —\n // and this attempt binds to it. Which instance served the attempt is per-attempt routing, and\n // the admission events already name it.\n const boundToCommitted = knownExecutionBindingReceipt(state.receipt, bindingInput)\n await appendOwnerBinding(state, boundToCommitted)\n state.onReceipt?.(state.receipt, boundToCommitted)\n state.publishedThisProcess = true\n return\n }\n await appendOwnerBinding(state, binding)\n state.onReceipt?.(state.receipt, binding)\n state.publishedThisProcess = true\n return\n }\n await appendOwnerMaterialization(state, receipt, binding)\n state.onReceipt?.(receipt, binding)\n state.publishedThisProcess = true\n}\n\n/** @internal Kernel identity for constructing the exact deferred owner executor. */\n/**\n * @internal Each driver attempt of the scope owner is its own execution attempt. A driver retry\n * after a failed drive, and the continuation re-entry after an unmet completion check, both\n * run the harness again and report a new execution binding; the journal keys owner bindings by\n * attempt id, so every attempt after the first is given a fresh kernel-minted id and its\n * published flags are cleared, and the new binding lands beside the earlier ones. The first\n * attempt keeps the id minted at run start. Returns the id the attempt reports under, or\n * undefined when the scope owner is not a deferred runtime-owned root.\n */\nexport function beginScopeOwnerAttempt(scope: Scope<unknown>, attempt: number): string | undefined {\n const state = ownerMaterializationStates.get(scope)\n if (state === undefined) return undefined\n if (attempt > 1) {\n state.attemptId = newExecutionAttemptId(state.nodeId)\n state.bindingPublished = false\n state.publishedThisProcess = false\n }\n return state.attemptId\n}\n\nexport function scopeOwnerExecutorNodeContext(scope: Scope<unknown>): ExecutorNodeContext {\n const state = ownerMaterializationState(scope)\n return Object.freeze({\n rootId: state.root,\n parentId: state.nodeId,\n nodeId: state.nodeId,\n depth: state.depth,\n attemptId: state.attemptId,\n })\n}\n\n/** Reuse a committed owner invocation without inventing another provider attempt. @internal */\nexport async function restoreScopeOwnerAcceptedExecution(scope: Scope<unknown>): Promise<void> {\n const state = ownerMaterializationState(scope)\n const events = (await state.journal.loadTree(state.retainedRoot)) ?? []\n const owned = events.filter((event) => event.id === state.nodeId)\n const latestInput = [...owned].reverse().find((event) => event.kind === 'execution-input')\n const latestResult = [...owned].reverse().find((event) => event.kind === 'execution-result')\n const inputIndex = latestInput === undefined ? -1 : owned.indexOf(latestInput)\n const resultIndex = latestResult === undefined ? -1 : owned.indexOf(latestResult)\n const result = owned[resultIndex]\n if (inputIndex < 0 || resultIndex <= inputIndex || result?.kind !== 'execution-result') {\n throw new ValidationError('scope owner has no accepted retained invocation')\n }\n const receiptEvent = owned\n .slice(0, resultIndex)\n .reverse()\n .find((event) => event.kind === 'materialized' || event.kind === 'seat-materialized')\n const bindingEvent = owned\n .slice(inputIndex, resultIndex)\n .reverse()\n .find((event) => event.kind === 'execution-bound')\n if (\n (receiptEvent?.kind !== 'materialized' && receiptEvent?.kind !== 'seat-materialized') ||\n bindingEvent?.kind !== 'execution-bound'\n ) {\n throw new ValidationError(\n 'accepted scope owner result has no preceding materialization evidence',\n )\n }\n const { receipt } = receiptEvent\n const { binding } = bindingEvent\n if (\n receipt.status !== 'known' ||\n binding.status !== 'known' ||\n receipt.runtime !== state.runtime ||\n receipt.authoredProfileDigest !== state.authoredProfileDigest ||\n binding.materializationReceiptDigest !== canonicalCandidateDigest(receipt) ||\n ((state.receipt ?? state.prior) !== undefined &&\n canonicalCandidateDigest(state.receipt ?? state.prior) !== canonicalCandidateDigest(receipt))\n ) {\n throw new ValidationError(\n 'accepted scope owner materialization does not match the resumed owner',\n )\n }\n assertValidSpend(result.spent, 'accepted scope owner result')\n const output = await state.blobs.get(result.outRef)\n if (output === undefined || contentAddress(output) !== result.outRef) {\n throw new ValidationError('accepted scope owner output is missing or corrupt')\n }\n state.receipt = receipt\n state.bindingPublished = true\n state.publishedThisProcess = true\n state.onReceipt?.(receipt, binding)\n}\n\n/** @internal Ensure a deferred root that never published evidence remains visibly unknown. */\nexport async function finalizeScopeOwnerMaterialization(scope: Scope<unknown>): Promise<void> {\n const state = ownerMaterializationStates.get(scope)\n if (state === undefined) return\n await serializedOwnerWrite(state, () => finalizeOwnerMaterialization(state))\n}\n\nasync function finalizeOwnerMaterialization(state: OwnerMaterializationState): Promise<void> {\n // Rejection paths publish an unknown binding before returning the original validation error.\n // Finalization still runs after that error, so it must not append the same attempt again.\n if (state.publishedThisProcess || state.bindingPublished) return\n if (state.prior !== undefined) {\n await appendUnknownOwnerBinding(state, state.prior, 'root-agent-did-not-report')\n throw new ValidationError(\n 'resumed scope owner did not re-attest its prior materialization before execution',\n )\n }\n if (state.receipt !== undefined) return\n // An attempt that started a planned execution and ended before its acknowledgement failed\n // before its receipt; only an owner that never started one did not report.\n const planned =\n state.plannedExecution?.attemptId === state.attemptId ? state.plannedExecution : undefined\n const reason = planned ? 'executor-failed-before-receipt' : 'root-agent-did-not-report'\n const receipt = unknownMaterializationReceipt({\n ...(state.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: state.authoredProfileDigest }),\n runtime: state.runtime,\n reason,\n })\n const binding = unknownExecutionBindingReceipt(\n receipt,\n state.attemptId,\n reason,\n planned?.execution,\n )\n await appendOwnerMaterialization(state, receipt, binding)\n state.onReceipt?.(receipt, binding)\n if (state.requiredKnown) {\n throw new ValidationError(\n 'runtime-owned scope owner did not publish materialization before completing',\n )\n }\n}\n\nfunction ownerMaterializationState(scope: Scope<unknown>): OwnerMaterializationState {\n const state = ownerMaterializationStates.get(scope)\n if (state === undefined) {\n throw new ValidationError('scope has no deferred runtime-owned root materialization channel')\n }\n return state\n}\n\nasync function rejectOwnerMaterialization(state: OwnerMaterializationState): Promise<void> {\n if (state.bindingPublished) return\n if (state.prior !== undefined) {\n await appendUnknownOwnerBinding(state, state.prior, 'invalid-executor-report')\n return\n }\n if (state.receipt !== undefined) {\n await appendUnknownOwnerBinding(state, state.receipt, 'invalid-executor-report')\n return\n }\n const receipt = unknownMaterializationReceipt({\n ...(state.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: state.authoredProfileDigest }),\n runtime: state.runtime,\n reason: 'invalid-executor-report',\n })\n const binding = unknownExecutionBindingReceipt(\n receipt,\n state.attemptId,\n 'invalid-executor-report',\n )\n await appendOwnerMaterialization(state, receipt, binding)\n state.onReceipt?.(receipt, binding)\n}\n\n/**\n * The fields two known receipts disagree on, ignoring which execution instance served the attempt.\n * Empty means only the instance moved, which a re-prompted attempt is allowed to do: Runtime asks\n * the provider for a new environment when it re-prompts an unmet completion check, and a retained\n * environment can be replaced between attempts.\n *\n * This answers WHICH field moved, not just THAT one did. The guard used to return a boolean, so a\n * production rejection named four candidate fields and identified none of them. Measured on\n * mech-interp-foundations-pi-20260915g and -20260915h: ten rejected bindings across two runs, and\n * the receipt that was rejected is not journalled, so no operator could tell from the record which\n * field had changed. A guard that refuses a live run owes the reason.\n */\nfunction changedRunIdentityFields(\n prior: ProfileMaterializationReceipt,\n next: ProfileMaterializationReceipt,\n): readonly string[] {\n if (prior.status !== 'known' || next.status !== 'known') return ['status']\n const withoutInstance = (\n receipt: Extract<ProfileMaterializationReceipt, { status: 'known' }>,\n ): Record<string, unknown> => {\n const { execution, ...rest } = receipt\n return { ...rest, execution: { kind: execution.kind } }\n }\n const before = withoutInstance(prior)\n const after = withoutInstance(next)\n const names = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort()\n return names.filter(\n (name) => canonicalCandidateDigest(before[name]) !== canonicalCandidateDigest(after[name]),\n )\n}\n\nasync function appendOwnerMaterialization(\n state: OwnerMaterializationState,\n receipt: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n): Promise<void> {\n await appendOwnerEvidence(state, {\n kind: 'materialized',\n id: state.nodeId,\n receipt,\n seq: 0,\n at: new Date(state.now()).toISOString(),\n })\n state.receipt = receipt\n await appendOwnerBinding(state, binding)\n}\n\nasync function appendOwnerSeatMaterialization(\n state: OwnerMaterializationState,\n segmentIndex: number,\n receipt: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n): Promise<void> {\n await appendOwnerEvidence(state, {\n kind: 'seat-materialized',\n id: state.nodeId,\n segmentIndex,\n receipt,\n seq: segmentIndex,\n at: new Date(state.now()).toISOString(),\n })\n state.receipt = receipt\n await appendOwnerBinding(state, binding)\n}\n\nasync function appendOwnerBinding(\n state: OwnerMaterializationState,\n binding: ExecutionBindingReceipt,\n): Promise<void> {\n await appendOwnerEvidence(state, {\n kind: 'execution-bound',\n id: state.nodeId,\n binding,\n seq: 0,\n at: new Date(state.now()).toISOString(),\n })\n state.bindingPublished = true\n}\n\nasync function appendOwnerEvidence(\n state: OwnerMaterializationState,\n event: Extract<SpawnEvent, { kind: 'materialized' | 'seat-materialized' | 'execution-bound' }>,\n): Promise<void> {\n for (const root of new Set([state.root, state.retainedRoot])) {\n await appendExactMaterializationEvent(state.journal, root, event)\n }\n}\n\nexport async function appendExactMaterializationEvent(\n journal: SpawnJournal,\n root: NodeId,\n event: Extract<SpawnEvent, { kind: 'materialized' | 'seat-materialized' | 'execution-bound' }>,\n): Promise<void> {\n const prior = (await journal.loadTree(root))?.find(\n (item) =>\n item.id === event.id &&\n (event.kind === 'materialized'\n ? item.kind === 'materialized'\n : event.kind === 'seat-materialized'\n ? item.kind === 'seat-materialized' && item.segmentIndex === event.segmentIndex\n : item.kind === 'execution-bound' && item.binding.attemptId === event.binding.attemptId),\n )\n if (\n prior?.kind === 'materialized' ||\n prior?.kind === 'seat-materialized' ||\n prior?.kind === 'execution-bound'\n ) {\n const previous = prior.kind === 'execution-bound' ? prior.binding : prior.receipt\n const next = event.kind === 'execution-bound' ? event.binding : event.receipt\n if (canonicalCandidateDigest(previous) !== canonicalCandidateDigest(next)) {\n throw new ValidationError('scope execution evidence conflicts with its committed record')\n }\n return\n }\n await journal.appendEvent(root, event)\n}\n\nasync function appendUnknownOwnerBinding(\n state: OwnerMaterializationState,\n receipt: ProfileMaterializationReceipt,\n reason: import('./types').UnknownMaterializationReason,\n): Promise<void> {\n const binding = unknownExecutionBindingReceipt(receipt, state.attemptId, reason)\n await appendOwnerBinding(state, binding)\n state.onReceipt?.(receipt, binding)\n}\n\nexport function bindScopeOwnerMaterialization(\n scope: Scope<unknown>,\n args: ScopeArgs,\n now: () => number,\n): void {\n if (args.ownerMaterialization !== undefined) {\n const authoredProfile =\n args.ownerMaterialization.authoredProfile === undefined\n ? undefined\n : detachedSnapshot(\n args.ownerMaterialization.authoredProfile,\n 'scope owner authored profile',\n )\n ownerMaterializationStates.set(scope as Scope<unknown>, {\n retainedRoot: args.root,\n blobs: args.blobs,\n journal: args.journal,\n root: args.ownerMaterialization.journalRoot ?? args.root,\n nodeId: args.ownerMaterialization.nodeId ?? args.parentId,\n depth: args.depth,\n runtime: args.ownerMaterialization.runtime,\n attemptId: args.ownerMaterialization.attemptId,\n ...(authoredProfile === undefined ? {} : { authoredProfile }),\n ...(authoredProfile === undefined\n ? {}\n : { authoredProfileDigest: authoredProfileDigest(authoredProfile) }),\n ...(args.ownerMaterialization.prior === undefined\n ? {}\n : { prior: args.ownerMaterialization.prior }),\n requiredKnown: args.ownerMaterialization.requiredKnown === true,\n ...(args.ownerMaterialization.onReceipt === undefined\n ? {}\n : { onReceipt: args.ownerMaterialization.onReceipt }),\n now,\n receipt: args.ownerMaterialization.prior,\n bindingPublished: false,\n publishedThisProcess: false,\n })\n }\n}\n","import { ValidationError } from '../../errors'\nimport { notifyRuntimeHookEvent } from '../../runtime-hooks'\nimport { withBudgetResources } from './resources'\nimport type { ScopeArgs } from './scope-contract'\nimport { detachedSnapshot } from './snapshot'\nimport type { ProviderModelExecutionEvidence, Spend } from './types'\n\n/** The scope owner's own inference: debited from the shared pool, journaled, and announced. */\nexport class ScopeOwnerMeter {\n /** The owner's own turns, so its lead reads a manager that takes turns as active. */\n ownerTurns = 0\n ownerLastTurnAt = 0\n private meterSeq = 0\n\n constructor(\n private readonly args: ScopeArgs,\n private readonly now: () => number,\n ) {}\n\n async record(\n spend: Spend,\n detail?: Record<string, unknown>,\n providerModel?: ProviderModelExecutionEvidence,\n accountingOnly = false,\n runtimeOwned = false,\n alreadySpent = false,\n ): Promise<void> {\n const args = this.args\n const now = this.now\n if (args.signal.aborted && !runtimeOwned) {\n throw new ValidationError('scope.meter: cannot record new driver work after scope abort')\n }\n const partial = providerModel !== undefined || accountingOnly\n if (!partial) spend = withBudgetResources(spend, args.pool.readout())\n const seq = this.meterSeq++\n // Debit the driver's own inference against the shared pool (free → committed), so equal-k and\n // `budget.tokensLeft` see it live. An invalid observation (unknown dollars under a ceiling) still\n // describes compute that happened: record it durably before returning the refusal, or the\n // terminal result would report that cost as $0.\n let observeError: unknown\n try {\n args.pool.observe(spend, { partial, ...(alreadySpent ? { alreadySpent } : {}) })\n } catch (error) {\n observeError = error\n }\n this.ownerLastTurnAt = now()\n if (!accountingOnly) this.ownerTurns += 1\n // Journal it as a `metered` event — the durable TWIN of the pool debit (as `settled` is the\n // twin of `reconcile`), so every journal-based cost reader sums driver inference automatically.\n // Awaited like the settled append (cost-critical), so it has landed before the supervisor's\n // join-barrier cost roll-up.\n await args.journal.appendEvent(args.root, {\n kind: 'metered',\n id: args.parentId,\n spend,\n ...(accountingOnly ? { accountingOnly: true as const } : {}),\n ...(providerModel === undefined\n ? {}\n : { providerModel: detachedSnapshot(providerModel, 'runtime provider model evidence') }),\n seq,\n at: new Date(now()).toISOString(),\n })\n // Emit it as an `agent.turn` event so the trace/topology view sees per-turn driver inference\n // (the same stream `spawn`/`next` feed — one observable tree).\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${args.parentId}:meter:${seq}`,\n runId: args.root,\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n parentId: args.parentId,\n payload: { spend, ...(detail ?? {}) },\n },\n { signal: args.signal },\n )\n if (observeError !== undefined) throw observeError\n }\n}\n","/**\n * The one builder of a down child's terminal record and of the evidence an observer sees beside\n * it, shared by every writer: the settle path at the reconcile, the release sweep closing a\n * retained slot at root settlement, and `healReleasedSlots` closing that slot on the next resume\n * when the settling process died between the last `environment-teardown` receipt and the record.\n *\n * This is its own module rather than a corner of scope.ts because scope.ts value-imports\n * recover-executors.ts, so a value import in the other direction would be a runtime ESM cycle\n * that biome does not flag. Every import of './scope' here is type-only and erased.\n *\n * Two hand-written literals for one record shape is how a field lands on one path and not the\n * other (#1244 was exactly that for `harnessTranscript`), so the subject is a structural type a\n * live `LiveChild` satisfies unchanged and a journaled `reconciled` record can be projected onto.\n */\n\nimport type { PreSeqSettled } from './scope'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n BudgetViolation,\n ExecutionBindingReceipt,\n NodeId,\n NodeSnapshot,\n ProfileMaterializationReceipt,\n ProviderModelExecutionEvidence,\n RetainedExecutionState,\n SpawnEvent,\n Spend,\n SubtreeSummary,\n} from './types'\n\nexport type DownSettlement = Extract<PreSeqSettled, { kind: 'down' }>\n\n/** The states a terminal record states: the slot closed at a final settlement, with the\n * environment confirmed destroyed or not. `'pending'` is never journaled. */\ntype ClosedRetainedExecution = Exclude<RetainedExecutionState, 'pending'>\n\n/** What the terminal record needs from the node beyond its settlement. `RunCancellationReason`\n * has `readonly source: string`, so a live child's `cancellationReason` fits as it is. */\nexport type TerminalDownSubject = {\n readonly id: NodeId\n readonly spent: Spend\n readonly budgetViolation?: BudgetViolation\n readonly cancellationReason?: { readonly source: string }\n /** The bounded account of the team this node led, when it led one. */\n readonly subtree?: SubtreeSummary\n}\n\n/** The settlement fields every writer copies, in the terminal record's key order. The\n * `reconciled` record is built from this same spread so it and the terminal record can never\n * disagree on a field. */\nexport function settlementFields(subject: TerminalDownSubject, settlement: DownSettlement) {\n return {\n spent: subject.spent,\n ...(settlement.infra === undefined ? {} : { infra: settlement.infra }),\n reason: settlement.reason,\n ...(settlement.failure === undefined ? {} : { failure: settlement.failure }),\n ...(settlement.retainedPendingCause === undefined\n ? {}\n : { retainedPendingCause: settlement.retainedPendingCause }),\n ...(settlement.outRef ? { outRef: settlement.outRef } : {}),\n ...(settlement.outRef && settlement.traceRoot ? { traceRoot: settlement.traceRoot } : {}),\n ...(settlement.providerModel ? { providerModel: settlement.providerModel } : {}),\n ...(subject.budgetViolation ? { budgetViolation: subject.budgetViolation } : {}),\n trace: settlement.trace,\n ...(settlement.harnessTranscript ? { harnessTranscript: settlement.harnessTranscript } : {}),\n ...(subject.subtree === undefined ? {} : { subtree: subject.subtree }),\n }\n}\n\n/** `cancelled` keeps its `source` from the subject's own cancellation reason, so a released\n * cancelled child records the same source it settled with. */\nexport function terminalDownEvent(\n subject: TerminalDownSubject,\n settlement: DownSettlement,\n seq: number,\n at: string,\n retainedExecution?: ClosedRetainedExecution,\n): Extract<SpawnEvent, { kind: 'settled' | 'cancelled' }> {\n const cancellation = subject.cancellationReason\n return {\n ...(cancellation === undefined\n ? { kind: 'settled' as const, status: 'down' as const }\n : { kind: 'cancelled' as const, source: cancellation.source }),\n id: subject.id,\n ...settlementFields(subject, settlement),\n ...(retainedExecution === undefined ? {} : { retainedExecution }),\n seq,\n at,\n }\n}\n\n/** What the observer evidence needs from the node beyond its settlement. */\ntype SettledEvidenceSubject = {\n readonly runtime: NodeSnapshot['runtime']\n readonly startedAt: number\n readonly providerModel?: ProviderModelExecutionEvidence\n readonly materialization?: ProfileMaterializationReceipt\n readonly executionBindings: ReadonlyArray<ExecutionBindingReceipt>\n readonly budgetViolation?: BudgetViolation\n}\n\n/**\n * The evidence a settled node carries beyond its status: the receipts that name what actually\n * ran, the own-inference spend the parent tree re-homes as a `metered` event, and the wall-clock\n * window. One builder feeds BOTH terminal paths, so an observer never sees a `down` node\n * described in different terms from a `done` one. Every field is omitted when the fact is\n * absent — an unreported receipt must not read as an empty one. Snapshots are detached because\n * an observer may serialize them after the live child has moved on.\n */\nexport function settledNodeEvidence(\n subject: SettledEvidenceSubject,\n settlement: PreSeqSettled,\n settledAt: number,\n): Record<string, unknown> {\n return {\n ...(settlement.kind === 'down' && settlement.failure !== undefined\n ? { failure: detachedSnapshot(settlement.failure, 'worker failure') }\n : {}),\n runtime: subject.runtime,\n startedAt: subject.startedAt,\n settledAt,\n ...(settlement.metered ? { metered: detachedSnapshot(settlement.metered, 'metered') } : {}),\n ...(subject.providerModel\n ? { providerModel: detachedSnapshot(subject.providerModel, 'provider model evidence') }\n : {}),\n ...(subject.materialization\n ? { materialization: detachedSnapshot(subject.materialization, 'materialization receipt') }\n : {}),\n ...(subject.executionBindings.length > 0\n ? {\n executionBindings: detachedSnapshot(\n [...subject.executionBindings],\n 'execution binding receipts',\n ),\n }\n : {}),\n ...(subject.budgetViolation\n ? { budgetViolation: detachedSnapshot(subject.budgetViolation, 'budget violation') }\n : {}),\n trace: detachedSnapshot(settlement.trace, 'worker trace evidence'),\n }\n}\n\n/** The `agent.child` payload of a closed retained slot: the settlement restated with the state\n * the slot closed in, `settledAt` kept at the settlement instant and `metered` omitted so the\n * driver's inference is not summed twice. The sweep, the final close and the resume heal emit\n * it from the same builder. */\nexport function releasedChildPayload(\n subject: TerminalDownSubject & SettledEvidenceSubject,\n settlement: DownSettlement,\n settledAt: number,\n releasedAt: number,\n retainedExecution: ClosedRetainedExecution = 'released',\n): Record<string, unknown> {\n return {\n childId: subject.id,\n status: 'down',\n retainedExecution,\n ...(settlement.retainedPendingCause === undefined\n ? {}\n : { retainedPendingCause: settlement.retainedPendingCause }),\n releasedAt,\n ...(settlement.outRef === undefined ? {} : { outRef: settlement.outRef }),\n reason: settlement.reason,\n ...(settlement.infra === undefined ? {} : { infra: settlement.infra }),\n spent: subject.spent,\n ...settledNodeEvidence(subject, { ...settlement, metered: undefined }, settledAt),\n }\n}\n","import { contentAddress } from '../../durable/content-address'\nimport { notifyRuntimeHookEvent } from '../../runtime-hooks'\nimport { settlementFailureCause } from '../failure-cause'\nimport { subtreeSummaryOf } from './scope-capabilities'\nimport type { LiveChild, PreSeqSettled, ScopeArgs } from './scope-contract'\nimport { frozenHandle } from './scope-observation'\nimport {\n type DownSettlement,\n settledNodeEvidence,\n settlementFields,\n type TerminalDownSubject,\n terminalDownEvent,\n} from './terminal-record'\nimport type {\n EnvironmentTeardownReceipt,\n HeldRelease,\n NodeId,\n Settled,\n SpawnEvent,\n SpawnJournal,\n Spend,\n} from './types'\n\n/** Await whichever pending child settles first, returning the child (its `resolved` is set\n * by the time this resolves because `runChild`'s `.then` sets it before the promise\n * resolves downstream). */\nexport async function raceFirstSettled(pending: LiveChild[]): Promise<LiveChild> {\n return Promise.race(pending.map((c) => c.settled.then(() => c)))\n}\n\n/** Rehomed inference has its own per-child sequence, independent of terminal cursors. */\nasync function appendSettlementMetering(\n journal: SpawnJournal,\n root: NodeId,\n id: NodeId,\n spend: Spend,\n at: string,\n): Promise<void> {\n const seq = await nextPerNodeSeq(journal, root, 'metered', id)\n await appendAcknowledged(journal, root, { kind: 'metered', id, spend, seq, at })\n}\n\n/** An open node's reconciled floor has the same per-child sequence discipline as its metering:\n * outside the cursor namespace, monotonic per node, so a node reconciled once per process (a\n * retained failure, a recovery, a second retained failure) keeps its records ordered. It carries\n * the whole settlement and the cursor seq (`settledSeq`) beside the floor, through the same\n * field spread the terminal record uses, so a resume that finds the release sweep died before\n * its record can write that record byte-for-byte instead of inventing one. */\nasync function appendReconciledFloor(\n journal: SpawnJournal,\n root: NodeId,\n subject: TerminalDownSubject,\n settlement: DownSettlement,\n settledSeq: number,\n at: string,\n): Promise<void> {\n const seq = await nextPerNodeSeq(journal, root, 'reconciled', subject.id)\n await appendAcknowledged(journal, root, {\n kind: 'reconciled',\n id: subject.id,\n ...settlementFields(subject, settlement),\n ...(subject.cancellationReason === undefined\n ? {}\n : { cancellation: { source: subject.cancellationReason.source } }),\n settledSeq,\n seq,\n at,\n })\n}\n\n/** A release receipt has the same per-child sequence discipline: outside the cursor namespace and\n * monotonic per node, so a run released in two processes keeps its receipts ordered. */\nexport async function appendEnvironmentTeardown(\n journal: SpawnJournal,\n root: NodeId,\n id: NodeId,\n receipt: EnvironmentTeardownReceipt,\n at: string,\n heldRelease?: HeldRelease,\n): Promise<void> {\n const seq = await nextPerNodeSeq(journal, root, 'environment-teardown', id)\n await journal.appendEvent(root, {\n kind: 'environment-teardown',\n id,\n provider: receipt.provider,\n environmentId: receipt.environmentId,\n destroyed: receipt.destroyed,\n ...(receipt.detail === undefined ? {} : { detail: receipt.detail }),\n ...(heldRelease === undefined ? {} : { heldRelease }),\n seq,\n at,\n })\n}\n\nasync function nextPerNodeSeq(\n journal: SpawnJournal,\n root: NodeId,\n kind: 'metered' | 'reconciled' | 'environment-teardown',\n id: NodeId,\n): Promise<number> {\n const prior = (await journal.loadTree(root)) ?? []\n return (\n prior.reduce(\n (max, event) => (event.kind === kind && event.id === id ? Math.max(max, event.seq) : max),\n -1,\n ) + 1\n )\n}\n\nasync function appendAcknowledged(\n journal: SpawnJournal,\n root: NodeId,\n event: Extract<SpawnEvent, { kind: 'metered' | 'reconciled' }>,\n): Promise<void> {\n try {\n await journal.appendEvent(root, event)\n } catch (error) {\n // An acknowledged durable prefix permits the terminal write; a missing prefix does not.\n const persisted = await journal.loadTree(root)\n if (\n !persisted?.some(\n (record) => record.kind === event.kind && contentAddress(record) === contentAddress(event),\n )\n )\n throw error\n }\n}\n\n/** Stamp the cursor `seq`, write the `settled` journal record, and project the\n * `PreSeqSettled` into the frozen `Settled` the driver branches on. */\nexport async function finalizeSettlement<Out>(\n child: LiveChild,\n settlement: PreSeqSettled,\n seq: number,\n args: ScopeArgs,\n now: () => number,\n): Promise<Settled<Out>> {\n const handle = frozenHandle<Out>(child)\n const nestedScope = child.readNestedScope?.()\n const subtree = nestedScope === undefined ? undefined : subtreeSummaryOf(nestedScope)\n if (subtree !== undefined) child.subtree = subtree\n const settledAt = now()\n child.settledAt = settledAt\n child.settledSeq = seq\n const at = new Date(settledAt).toISOString()\n // A terminal cursor must never hide inference that has not reached the parent journal.\n if (settlement.metered) {\n await appendSettlementMetering(args.journal, args.root, child.id, settlement.metered, at)\n }\n if (settlement.kind === 'down') {\n settlement.failure ??= settlementFailureCause(settlement)\n child.failure = settlement.failure\n const cancellation = child.cancellationReason\n child.status = cancellation === undefined ? 'failed' : 'cancelled'\n child.outRef = settlement.outRef\n child.trace = settlement.trace\n child.providerModel = settlement.providerModel\n const retainedPending = child.recoveryPending === true\n if (!retainedPending)\n await args.journal.appendEvent(args.root, terminalDownEvent(child, settlement, seq, at))\n // A retained-pending node keeps its cursor slot open for recovery, so it carries no terminal\n // record yet — but its reservation WAS reconciled, and a journal that says nothing about that\n // leaves every reader (terminal accounting, a restored pool, the tree view) charging the\n // ceiling the pool refunded: the reported `childWork` carried 4M per\n // retained child against a metered 10 (#1190). The floor is journaled in the settlement's\n // place, outside the cursor namespace, so the slot stays open and the ledgers agree. The\n // slot closes in exactly three ways: a resume recovers the execution and settles it on the\n // ordinary path; root settlement under `retainedAtSettlement: 'release'` destroys the\n // environment and the release sweep (`retainedReleasers`, above) writes this settlement as\n // the terminal record with `retainedExecution: 'released'`, under the seq stamped here; or\n // the next resume's `healReleasedSlots` writes that same record from this reconciled record\n // and the receipts, when the sweep's process died between them. The reconciled record\n // therefore carries the settlement and `seq` in full: `spent` is the floor the pool committed\n // (`live.spent` at the retained branch, the same object `child.spent` holds), the withheld\n // overspend is `retainedViolation`, and `cancellationReason` is final because\n // `recordCancellation` only assigns before `executorDone`.\n else {\n child.retainedExecution = 'pending'\n child.retainedPendingCause = settlement.retainedPendingCause\n if (settlement.reconciled !== undefined)\n await appendReconciledFloor(\n args.journal,\n args.root,\n {\n id: child.id,\n spent: settlement.reconciled,\n ...(child.retainedViolation === undefined\n ? {}\n : { budgetViolation: child.retainedViolation }),\n ...(child.cancellationReason === undefined\n ? {}\n : { cancellationReason: child.cancellationReason }),\n },\n settlement,\n seq,\n at,\n )\n }\n // The in-memory down and the first `agent.child` are the only surfaces that exist while the\n // slot is open, so they are where `'pending'` lives; the journal states the same fact as the\n // `reconciled` record and replay never yields it.\n const retainedExecution = retainedPending\n ? {\n retainedExecution: 'pending' as const,\n ...(settlement.retainedPendingCause === undefined\n ? {}\n : { retainedPendingCause: settlement.retainedPendingCause }),\n }\n : {}\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${child.id}:settled`,\n runId: args.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: settledAt,\n stepIndex: seq,\n parentId: args.parentId,\n payload: {\n childId: child.id,\n status: 'down',\n ...(settlement.outRef === undefined ? {} : { outRef: settlement.outRef }),\n reason: settlement.reason,\n ...(settlement.infra === undefined ? {} : { infra: settlement.infra }),\n ...retainedExecution,\n spent: child.spent,\n ...(subtree === undefined ? {} : { subtree }),\n ...settledNodeEvidence(child, settlement, settledAt),\n },\n },\n { signal: args.signal },\n )\n return {\n kind: 'down',\n handle,\n reason: settlement.reason,\n ...(settlement.infra === undefined ? {} : { infra: settlement.infra }),\n ...retainedExecution,\n ...(settlement.outRef === undefined ? {} : { outRef: settlement.outRef }),\n ...(settlement.providerModel ? { providerModel: settlement.providerModel } : {}),\n ...(child.budgetViolation ? { budgetViolation: child.budgetViolation } : {}),\n trace: settlement.trace,\n ...(settlement.harnessTranscript ? { harnessTranscript: settlement.harnessTranscript } : {}),\n ...(subtree === undefined ? {} : { subtree }),\n ...(settlement.failure === undefined ? {} : { failure: settlement.failure }),\n settledAt,\n seq,\n }\n }\n\n child.failure = undefined\n child.status = 'done'\n child.outRef = settlement.outRef\n child.spent = settlement.spent\n child.trace = settlement.trace\n child.providerModel = settlement.providerModel\n await args.journal.appendEvent(args.root, {\n kind: 'settled',\n id: child.id,\n status: 'done',\n outRef: settlement.outRef,\n ...(settlement.traceRoot === undefined ? {} : { traceRoot: settlement.traceRoot }),\n ...(settlement.verdict ? { verdict: settlement.verdict } : {}),\n spent: settlement.spent,\n ...(settlement.providerModel ? { providerModel: settlement.providerModel } : {}),\n ...(child.budgetViolation ? { budgetViolation: child.budgetViolation } : {}),\n trace: settlement.trace,\n ...(settlement.harnessTranscript ? { harnessTranscript: settlement.harnessTranscript } : {}),\n ...(subtree === undefined ? {} : { subtree }),\n seq,\n at,\n })\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${child.id}:settled`,\n runId: args.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: settledAt,\n stepIndex: seq,\n parentId: args.parentId,\n payload: {\n childId: child.id,\n status: 'done',\n outRef: settlement.outRef,\n score: settlement.verdict?.score,\n valid: settlement.verdict?.valid,\n spent: settlement.spent,\n ...(subtree === undefined ? {} : { subtree }),\n ...settledNodeEvidence(child, settlement, settledAt),\n },\n },\n { signal: args.signal },\n )\n return {\n kind: 'done',\n handle,\n out: settlement.out as Out,\n outRef: settlement.outRef,\n ...(settlement.verdict ? { verdict: settlement.verdict } : {}),\n spent: settlement.spent,\n ...(settlement.providerModel ? { providerModel: settlement.providerModel } : {}),\n ...(child.budgetViolation ? { budgetViolation: child.budgetViolation } : {}),\n trace: settlement.trace,\n ...(settlement.harnessTranscript ? { harnessTranscript: settlement.harnessTranscript } : {}),\n ...(subtree === undefined ? {} : { subtree }),\n settledAt,\n seq,\n }\n}\n\n/**\n * Drive one child's `Executor` to a terminal `PreSeqSettled`, folding usage into the\n * conserved `Spend`, reconciling the reservation, and persisting the result blob. Both\n * executor shapes are handled here: a one-shot `Promise<ExecutorResult>` and a streaming\n * `AsyncIterable<UsageEvent>` whose terminal artifact is read from `resultArtifact()`.\n *\n * A thrown executor (or a real abort) becomes a TYPED `down` — never re-thrown — so a\n * single failing child cannot reject the `next()` cursor (the M2 typed-result discipline,\n * applied per child). The reservation is reconciled on EVERY path (success, abort, throw)\n * so the conserved pool can never leak a reservation.\n */\n","import { ValidationError } from '../../errors'\nimport type { LiveChild, PreSeqSettled, ScopeArgs } from './scope-contract'\nimport { finalizeSettlement, raceFirstSettled } from './scope-settlement'\nimport type { NodeId, Settled } from './types'\n\n/**\n * The scope's `next()` cursor: delivers each child's settlement exactly once, stamps the cursor\n * `seq`, and tracks the settlement writes still landing so a drain can wait for them.\n */\nexport class ScopeSettlementCursor<Out> {\n /** Settlement writes in flight; a drain or an empty cursor waits for every one. */\n readonly writes = new Set<Promise<Settled<Out>>>()\n // The order `next()` yields settlements (B2): the `seq` of `settled`/`cancelled` events and of\n // `Settled`. Separate from the spawn ordinal so a `spawned` event never collides with a `settled`\n // one in the per-tree uniqueness guard. A resumed scope continues PAST the recorded maximum.\n private cursorSeq: number\n\n constructor(\n private readonly args: ScopeArgs,\n private readonly children: Map<NodeId, LiveChild>,\n private readonly now: () => number,\n private readonly recordKeyedSettlement: (key: string, settled: Settled<Out>) => void,\n ) {\n this.cursorSeq = args.resumeFrom ? args.resumeFrom.maxCursorSeq + 1 : 0\n }\n\n readonly next = async (): Promise<Settled<Out> | null> => {\n const undelivered = () => [...this.children.values()].filter((c) => !c.delivered)\n\n // ray.wait n=1: await the FIRST not-yet-delivered child to settle. Loop because a\n // concurrent `next()` may take the race winner between the await and the pick.\n for (;;) {\n const pending = undelivered()\n if (pending.length === 0) {\n await Promise.all([...this.writes])\n return null\n }\n // Prefer an already-resolved-but-undelivered child (no await needed).\n const ready = pending.find((c) => c.resolved !== undefined)\n const chosen = ready ?? (await raceFirstSettled(pending))\n if (chosen.delivered) continue\n chosen.delivered = true\n\n const seq = this.cursorSeq++\n const settlement = chosen.resolved\n if (!settlement) {\n throw new ValidationError(\n `scope.next: child '${chosen.id}' won the settle race without a resolved value`,\n )\n }\n return await this.commit(chosen, settlement, seq)\n }\n }\n\n readonly nextResolved = async (): Promise<Settled<Out> | null> => {\n // Same exactly-once delivery as `next()`, but never awaits a RUNNING executor. A child\n // whose executor has finished (`executorDone`) may still be mid-persistence — awaiting its\n // `settled` promise there completes in bounded bookkeeping time, never on live work.\n for (;;) {\n const candidates = [...this.children.values()].filter((c) => !c.delivered)\n const pick =\n candidates.find((c) => c.resolved !== undefined) ?? candidates.find((c) => c.executorDone)\n if (!pick) {\n await Promise.all([...this.writes])\n return null\n }\n const settlement = await pick.settled\n if (pick.delivered) continue // lost the race with a concurrent cursor — pick again\n pick.delivered = true\n const seq = this.cursorSeq++\n return await this.commit(pick, settlement, seq)\n }\n }\n\n private async commit(\n child: LiveChild,\n settlement: PreSeqSettled,\n seq: number,\n ): Promise<Settled<Out>> {\n const pending = finalizeSettlement<Out>(child, settlement, seq, this.args, this.now).then(\n (delivered) => {\n if (child.key !== undefined) this.recordKeyedSettlement(child.key, delivered)\n return delivered\n },\n )\n this.writes.add(pending)\n try {\n return await pending\n } finally {\n this.writes.delete(pending)\n }\n }\n}\n","import { ValidationError } from '../../errors'\nimport {\n authoredProfileDigest,\n knownExecutionBindingReceipt,\n knownMaterializationReceipt,\n runtimeOwnedDeferredExecutorRuntime,\n runtimeOwnedExecutorExecutionBinding,\n runtimeOwnedExecutorMaterialization,\n runtimeOwnedPendingExecutorMaterialization,\n unknownExecutionBindingReceipt,\n unknownMaterializationReceipt,\n} from './materialization'\nimport type { RetainedChildRecovery } from './retained-executor'\nimport type { DeferredOwnerSlot, LiveChild, ScopeArgs } from './scope-contract'\nimport { appendExactMaterializationEvent } from './scope-owner-materialization'\nimport type {\n AgentSpec,\n ExecutionBindingReceipt,\n Executor,\n NodeExecutionIdentity,\n NodeId,\n ProfileMaterializationReceipt,\n} from './types'\n\n/** Publish the execution receipt only after the child spawn is durable. */\nexport function createChildMaterialization({\n args,\n spawnCommitted,\n identity,\n spec,\n executor,\n deferredOwner,\n attemptId,\n id,\n recovery,\n live,\n ordinal,\n now,\n}: {\n args: ScopeArgs\n spawnCommitted: Promise<void>\n identity: NodeExecutionIdentity | undefined\n spec: AgentSpec\n executor: Executor<unknown>\n deferredOwner: DeferredOwnerSlot\n attemptId: string\n id: NodeId\n recovery: RetainedChildRecovery | undefined\n live: LiveChild\n ordinal: number\n now: () => number\n}) {\n let pendingEvidence: { complete: () => Promise<void>; fail: () => Promise<void> } | undefined\n const ready = spawnCommitted.then(async () => {\n const profileDigest = identity?.profileDigest ?? authoredProfileDigest(spec.profile)\n let receipt: ProfileMaterializationReceipt\n let binding: ExecutionBindingReceipt\n const declaration = runtimeOwnedExecutorMaterialization(executor)\n const pending = runtimeOwnedPendingExecutorMaterialization(executor)\n const deferredRuntime = runtimeOwnedDeferredExecutorRuntime(executor)\n if (deferredRuntime !== undefined) {\n deferredOwner.ownerMaterialization = {\n runtime: deferredRuntime,\n authoredProfile: spec.profile,\n attemptId,\n journalRoot: args.root,\n nodeId: id,\n requiredKnown: true,\n ...(recovery?.priorMaterialization ? { prior: recovery.priorMaterialization } : {}),\n onReceipt(materialization, executionBinding) {\n live.runtime = materialization.runtime\n live.materialization = materialization\n live.executionBindings.push(executionBinding)\n },\n }\n return\n }\n if (pending !== undefined) {\n if (profileDigest === undefined) {\n throw new ValidationError(\n 'scope.spawn: a pending materialization requires a canonical authored profile',\n )\n }\n if (pending.runtime !== executor.runtime || pending.binding.attemptId !== attemptId) {\n throw new ValidationError(\n 'scope.spawn: pending executor did not bind the kernel-minted attempt id',\n )\n }\n // Validate the planned shape before spend, but do not persist it as proof that the\n // external bridge actually used it. Only the terminal acknowledgement can finalize it.\n const plannedReceipt = knownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n declaration: pending.declaration,\n })\n if (plannedReceipt.status !== 'known') {\n throw new ValidationError('scope.spawn: pending executor returned an unknown receipt')\n }\n let recorded = false\n pendingEvidence = {\n complete: async () => {\n if (recorded) return\n const acknowledged = runtimeOwnedExecutorMaterialization(executor)\n const acknowledgedBinding = runtimeOwnedExecutorExecutionBinding(executor)\n if (acknowledged === undefined || acknowledgedBinding?.attemptId !== attemptId) {\n throw new ValidationError(\n 'scope.spawn: external executor completed without a terminal materialization acknowledgement',\n )\n }\n const finalReceipt = knownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n declaration: acknowledged,\n })\n if (finalReceipt.status !== 'known') {\n throw new ValidationError('scope.spawn: terminal materialization remained unknown')\n }\n const finalBinding = knownExecutionBindingReceipt(finalReceipt, acknowledgedBinding)\n await appendNodeMaterialization(args, id, ordinal, finalReceipt, finalBinding, now)\n live.materialization = finalReceipt\n live.executionBindings.push(finalBinding)\n recorded = true\n },\n fail: async () => {\n if (recorded) return\n // The remote turn can be acknowledged before a later local persistence/check step\n // fails. Preserve that known execution truth even though the child settles down.\n if (runtimeOwnedExecutorMaterialization(executor) !== undefined) {\n await pendingEvidence?.complete()\n return\n }\n // This is the terminal record for a failed attempt, so the receipt is not pending:\n // the child is down and the executor will never acknowledge. Recording a wait that\n // has already ended reads as \"not yet known\" on a row that is final, and a consumer\n // fleet mined exactly that value as a pre-launch death predictor (41 of 41 deaths).\n // The correlation was total because only this failure path ever wrote the value.\n const unknown = unknownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n reason: 'executor-failed-before-receipt',\n })\n const unknownBinding = unknownExecutionBindingReceipt(\n unknown,\n attemptId,\n 'executor-failed-before-receipt',\n )\n await appendNodeMaterialization(args, id, ordinal, unknown, unknownBinding, now)\n live.materialization = unknown\n live.executionBindings.push(unknownBinding)\n recorded = true\n },\n }\n return\n }\n if (declaration === undefined) {\n receipt = unknownMaterializationReceipt({\n ...(profileDigest === undefined ? {} : { authoredProfileDigest: profileDigest }),\n runtime: executor.runtime,\n reason: 'executor-did-not-report',\n })\n binding = unknownExecutionBindingReceipt(receipt, attemptId, 'executor-did-not-report')\n } else {\n try {\n if (profileDigest === undefined) {\n throw new ValidationError(\n 'scope.spawn: a known materialization requires a canonical authored profile',\n )\n }\n receipt = knownMaterializationReceipt({\n authoredProfileDigest: profileDigest,\n runtime: executor.runtime,\n declaration,\n })\n const reportedBinding = runtimeOwnedExecutorExecutionBinding(executor)\n if (reportedBinding === undefined || reportedBinding.attemptId !== attemptId) {\n throw new ValidationError(\n 'scope.spawn: trusted executor did not bind the kernel-minted attempt id',\n )\n }\n binding = knownExecutionBindingReceipt(receipt, reportedBinding)\n } catch (error) {\n receipt = unknownMaterializationReceipt({\n ...(profileDigest === undefined ? {} : { authoredProfileDigest: profileDigest }),\n runtime: executor.runtime,\n reason: 'invalid-executor-report',\n })\n binding = unknownExecutionBindingReceipt(receipt, attemptId, 'invalid-executor-report')\n await appendNodeMaterialization(args, id, ordinal, receipt, binding, now)\n live.materialization = receipt\n live.executionBindings.push(binding)\n throw new ValidationError(\n `scope.spawn: executor ${JSON.stringify(executor.runtime)} returned invalid materialization evidence`,\n { cause: error },\n )\n }\n }\n await appendNodeMaterialization(args, id, ordinal, receipt, binding, now)\n live.materialization = receipt\n live.executionBindings.push(binding)\n })\n return {\n ready,\n complete: async () => pendingEvidence?.complete(),\n fail: async () => pendingEvidence?.fail(),\n }\n}\nasync function appendNodeMaterialization(\n args: Pick<ScopeArgs, 'journal' | 'root'>,\n id: NodeId,\n seq: number,\n receipt: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n now: () => number,\n): Promise<void> {\n const at = new Date(now()).toISOString()\n await appendExactMaterializationEvent(args.journal, args.root, {\n kind: 'materialized',\n id,\n receipt,\n seq,\n at,\n })\n await appendExactMaterializationEvent(args.journal, args.root, {\n kind: 'execution-bound',\n id,\n binding,\n seq,\n at,\n })\n}\n","import { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { RetainedRunEnvironmentAdmission } from '../retained-run-types'\nimport { chargedTokens } from '../util'\nimport { executorFailureReason } from './executor-outcome'\nimport {\n executorEvidenceWriter,\n leafContinuationExecutionId,\n type RetainedChildRecovery,\n type RetainedExecutorContext,\n workspaceCaptureWriter,\n} from './retained-executor'\nimport { DEFAULT_BUDGET_STOP_HOLD_MS } from './scope-capabilities'\nimport type { LiveChild, ScopeArgs } from './scope-contract'\nimport { detachedSnapshot } from './snapshot'\nimport { assertValidSpend } from './spend-validation'\nimport type { TraceRootWriter } from './trace-root'\nimport type { Budget, NodeExecutionIdentity, NodeId, SpawnOpts, Spend } from './types'\n\n/** Own the retained child invocation and its durable writes. */\nexport function createChildRetention({\n args,\n controller,\n id,\n ordinal,\n identity,\n recovery,\n opts,\n now,\n traceRoots,\n markRecoveryReady,\n childDeadlineAtMs,\n readLive,\n completeEvidence,\n}: {\n args: ScopeArgs\n controller: AbortController\n id: NodeId\n ordinal: number\n identity: NodeExecutionIdentity | undefined\n recovery: RetainedChildRecovery | undefined\n opts: SpawnOpts\n now: () => number\n traceRoots: TraceRootWriter\n markRecoveryReady: (() => void) | undefined\n childDeadlineAtMs: number | undefined\n readLive: () => LiveChild\n completeEvidence: () => Promise<void>\n}) {\n const retainedWrites = new Set<Promise<void>>()\n let retainedWritesClosed = false\n const retainedWrite = (write: () => Promise<void>): Promise<void> => {\n controller.signal.throwIfAborted()\n if (retainedWritesClosed) throw new ValidationError('retained child writer is closed')\n const pending = write()\n retainedWrites.add(pending)\n void pending.then(\n () => retainedWrites.delete(pending),\n () => retainedWrites.delete(pending),\n )\n return pending\n }\n const closeRetainedWrites = async () => {\n retainedWritesClosed = true\n await Promise.allSettled([...retainedWrites])\n }\n // The invocation this child is running. A leaf whose upstream refused its turn continues in\n // the same environment as a later invocation (`continueInvocation`), journaled the way an\n // owner's later drive is: a new `execution-input`, then that invocation's own admissions\n // and result. The first invocation's input takes the spawn ordinal; each later one the next\n // number, so a recovery derives the same execution id from the journal.\n let admissions = [...(recovery?.admissions ?? [])]\n let inputSeq = recovery?.continuation?.inputSeq ?? ordinal\n let pauseSeq = 0\n const onAdmission: RetainedExecutorContext['onAdmission'] = (admission) =>\n retainedWrite(async () => {\n controller.signal.throwIfAborted()\n const existing = admissions.find((record) => record.phase === admission.phase)\n if (existing) {\n if (contentAddress(existing) !== contentAddress(admission)) {\n throw new ValidationError('scope retained admission conflicts with its committed phase')\n }\n return\n }\n if (identity?.taskDigest === undefined)\n throw new ValidationError('retained execution requires a canonical task identity')\n await args.journal.appendEvent(args.root, {\n kind: 'execution-admitted',\n id,\n admission: detachedSnapshot(admission, 'retained admission'),\n seq: ordinal,\n at: new Date(now()).toISOString(),\n })\n admissions.push(detachedSnapshot(admission, 'retained admission'))\n readLive().recoveryPending = true\n controller.signal.throwIfAborted()\n })\n const onResult: RetainedExecutorContext['onResult'] = (result) =>\n retainedWrite(async () => {\n controller.signal.throwIfAborted()\n assertValidSpend(result.spent, 'retained executor result')\n executorFailureReason(result)\n await completeEvidence()\n const outRef = contentAddress(result.out)\n await args.blobs.put(outRef, result.out)\n controller.signal.throwIfAborted()\n // As for a retained owner: an abort that arrives while the events hash still commits.\n const traceRoot = await traceRoots.write(outRef, result)\n await args.journal.appendEvent(args.root, {\n kind: 'execution-result',\n id,\n outRef,\n ...(traceRoot === undefined ? {} : { traceRoot }),\n spent: result.spent,\n ...(result.verdict ? { verdict: result.verdict } : {}),\n ...(result.outcome ? { outcome: result.outcome } : {}),\n ...(result.outputFormat === undefined ? {} : { outputFormat: result.outputFormat }),\n seq: ordinal,\n at: new Date(now()).toISOString(),\n })\n readLive().acceptedResult = detachedSnapshot(\n { ...result, outRef },\n 'accepted retained child result',\n )\n readLive().recoveryPending = false\n })\n let captureSeq = 0\n const { onWorkspaceCapture, onWorkspaceCaptureStarted } = workspaceCaptureWriter({\n journal: args.journal,\n rootId: args.root,\n nodeId: id,\n nextSequence: () => captureSeq++,\n now,\n })\n const onPause: NonNullable<RetainedExecutorContext['onPause']> = (pause) =>\n retainedWrite(async () => {\n await args.journal.appendEvent(args.root, {\n kind: 'paused',\n id,\n ...pause,\n seq: pauseSeq++,\n at: new Date(now()).toISOString(),\n })\n })\n // Only a keyed leaf can be continued (by re-spawning its key), so only one keeps its\n // environment after a turn that ended over its budget or past its time box.\n const holdMs = args.budgetStopHoldMs ?? DEFAULT_BUDGET_STOP_HOLD_MS\n const holdOnSettle =\n opts.key !== undefined && holdMs > 0\n ? (spent: Spend): boolean =>\n overBudget(opts.budget, spent) ||\n (childDeadlineAtMs !== undefined && now() > childDeadlineAtMs)\n : undefined\n const retainedContext = (\n continuing:\n | {\n executionId: string\n priorSession: RetainedRunEnvironmentAdmission\n priorSpent?: Spend\n }\n | undefined,\n ): RetainedExecutorContext => ({\n ...(continuing === undefined\n ? {}\n : {\n executionId: continuing.executionId,\n priorSession: continuing.priorSession,\n ...(continuing.priorSpent === undefined ? {} : { priorSpent: continuing.priorSpent }),\n }),\n admissions,\n ...(holdOnSettle === undefined ? {} : { holdOnSettle }),\n ...(markRecoveryReady && continuing === undefined ? { onReady: markRecoveryReady } : {}),\n onAdmission,\n onResult,\n onEvidence: executorEvidenceWriter({\n journal: args.journal,\n blobs: args.blobs,\n rootId: args.root,\n nodeId: id,\n nextSequence: () => ordinal,\n now,\n traceRoots,\n }),\n onPause,\n onWorkspaceCapture,\n onWorkspaceCaptureStarted,\n continueInvocation: async (nextTask) => {\n controller.signal.throwIfAborted()\n const live = readLive()\n // An input after a committed result starts a new invocation; before one, it would pay\n // for the unfinished turn twice (the journal refuses it too).\n if (live.acceptedResult === undefined) {\n throw new ValidationError(\n 'scope: a retained child continues only after its invocation committed a result',\n )\n }\n const environment = admissions.find((record) => record.phase === 'environment')\n if (environment?.phase !== 'environment') {\n throw new ValidationError(\n 'scope: a retained child continues only in an environment it was admitted to',\n )\n }\n const snapshot = detachedSnapshot(nextTask, 'retained child continuation')\n const taskRef = contentAddress(snapshot)\n const nextSeq = inputSeq + 1\n await retainedWrite(async () => {\n await args.blobs.put(taskRef, snapshot)\n controller.signal.throwIfAborted()\n await args.journal.appendEvent(args.root, {\n kind: 'execution-input',\n id,\n taskRef,\n seq: nextSeq,\n at: new Date(now()).toISOString(),\n })\n })\n inputSeq = nextSeq\n admissions = []\n // The committed result belongs to the invocation this one continues. A cancellation\n // from here on leaves this invocation pending, not that result accepted.\n const priorSpent = live.acceptedResult.spent\n live.acceptedResult = undefined\n return retainedContext({\n executionId: leafContinuationExecutionId(id, nextSeq),\n priorSession: environment,\n priorSpent,\n })\n },\n })\n return {\n retainedContext,\n closeRetainedWrites,\n holdMs,\n readEnvironmentAdmission: () => {\n const admission = admissions.find((record) => record.phase === 'environment')\n return admission?.phase === 'environment' ? admission : undefined\n },\n }\n}\n\n/** Whether a settled spend exceeds the budget it was given, by the channels the pool reconciles. */\nfunction overBudget(budget: Budget, spent: Spend): boolean {\n return (\n chargedTokens(spent.tokens) > budget.maxTokens ||\n spent.iterations > budget.maxIterations ||\n (budget.maxUsd !== undefined && spent.usdKnown !== false && spent.usd > budget.maxUsd)\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","import type {\n AgentInteractiveSessionAttach,\n AgentInteractiveSessionControlClaimAcknowledgement,\n AgentInteractiveSessionControlClaimRequest,\n AgentInteractiveSessionPromptAcknowledgement,\n AgentInteractiveSessionPromptCommand,\n AgentInteractiveSessionRef,\n AgentInteractiveSessionStart,\n AgentInteractiveSessionStatus,\n AgentInteractiveSessionStopAcknowledgement,\n AgentInteractiveSessionStopCommand,\n AgentInteractiveTerminalSession,\n} from '@tangle-network/agent-interface'\nimport {\n AgentInteractiveSessionControlClaimAcknowledgementSchema,\n AgentInteractiveSessionControlClaimSchema,\n AgentInteractiveSessionPromptAcknowledgementSchema,\n AgentInteractiveSessionRefSchema,\n AgentInteractiveSessionStatusSchema,\n AgentInteractiveSessionStopAcknowledgementSchema,\n agentInteractiveSessionControlClaimAcknowledgementMatchesRequest,\n agentInteractiveSessionControlClaimMatchesRef,\n agentInteractiveSessionPromptAcknowledgementMatchesCommand,\n agentInteractiveSessionStatusMatchesRef,\n agentInteractiveSessionStopAcknowledgementMatchesCommand,\n canonicalCandidateDigest,\n TerminalReplayWindowSchema,\n TerminalSessionRefSchema,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { RetainedInteractiveBindingError } from '../errors'\nimport type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport { awaitAbortable, RetainedRunProviderContractError } from './retained-run-binding'\nimport { detachedSnapshot } from './supervise/snapshot'\n\nexport function createRetainedInteractiveRunHandle(\n environment: AgentEnvironment,\n inputRef: AgentInteractiveSessionRef,\n capabilities: AgentEnvironmentCapabilities,\n requestedStart?: AgentInteractiveSessionStart,\n): RetainedInteractiveRunHandle {\n const ref = freezeInteractiveRef(inputRef)\n const source = environment.interactive!(ref)\n if (!sameInteractiveRef(source.ref, ref)) {\n throw new Error('provider reconstructed a different interactive process')\n }\n if (!source.sendPrompt) {\n throw new Error('provider declared interactive prompt support but exposed no prompt method')\n }\n return Object.freeze({\n ref,\n capabilities,\n claimControl: async (\n request: AgentInteractiveSessionControlClaimRequest,\n options?: { signal?: AbortSignal },\n ): Promise<AgentInteractiveSessionControlClaimAcknowledgement> =>\n exactClaim(\n ref,\n request,\n await awaitAbortable(\n Promise.resolve().then(() => source.claimControl(request, options)),\n options?.signal,\n ),\n ),\n status: async (options?: { signal?: AbortSignal }) =>\n exactStatus(\n ref,\n await awaitAbortable(\n Promise.resolve().then(() => source.status(options)),\n options?.signal,\n ),\n requestedStart,\n ),\n attach: async (request: AgentInteractiveSessionAttach, options?: { signal?: AbortSignal }) =>\n exactTerminal(\n ref,\n request,\n await awaitAbortable(\n Promise.resolve().then(() => source.attach(request, options)),\n options?.signal,\n ),\n ),\n sendPrompt: async (\n command: AgentInteractiveSessionPromptCommand,\n options?: { signal?: AbortSignal },\n ): Promise<AgentInteractiveSessionPromptAcknowledgement> =>\n exactPrompt(\n ref,\n await awaitAbortable(\n Promise.resolve().then(() => source.sendPrompt!(command, options)),\n options?.signal,\n ),\n command,\n ),\n stop: async (\n command: AgentInteractiveSessionStopCommand,\n options?: { signal?: AbortSignal },\n ): Promise<AgentInteractiveSessionStopAcknowledgement> =>\n exactStop(\n ref,\n await awaitAbortable(\n Promise.resolve().then(() => source.stop(command, options)),\n options?.signal,\n ),\n command,\n ),\n })\n}\n\nexport function freezeInteractiveRef(\n value: AgentInteractiveSessionRef,\n): AgentInteractiveSessionRef {\n return detachedSnapshot(AgentInteractiveSessionRefSchema.parse(value), 'interactive session ref')\n}\n\nfunction exactClaim(\n ref: AgentInteractiveSessionRef,\n request: AgentInteractiveSessionControlClaimRequest,\n value: unknown,\n): AgentInteractiveSessionControlClaimAcknowledgement {\n const acknowledgement = parseProviderAcknowledgement(\n AgentInteractiveSessionControlClaimAcknowledgementSchema,\n value,\n 'control claim',\n )\n if (!agentInteractiveSessionControlClaimAcknowledgementMatchesRequest(request, acknowledgement)) {\n throw new RetainedRunProviderContractError(\n 'provider returned a control claim acknowledgement for another request',\n )\n }\n if (\n acknowledgement.control &&\n !agentInteractiveSessionControlClaimMatchesRef(ref, acknowledgement.control)\n ) {\n throw new RetainedRunProviderContractError(\n 'provider returned a control claim for another interactive process',\n )\n }\n return acknowledgement\n}\n\nfunction exactPrompt(\n ref: AgentInteractiveSessionRef,\n value: unknown,\n command: AgentInteractiveSessionPromptCommand,\n): AgentInteractiveSessionPromptAcknowledgement {\n const acknowledgement = parseProviderAcknowledgement(\n AgentInteractiveSessionPromptAcknowledgementSchema,\n value,\n 'prompt',\n )\n if (!agentInteractiveSessionPromptAcknowledgementMatchesCommand(command, acknowledgement)) {\n throw new RetainedRunProviderContractError(\n 'provider returned a prompt acknowledgement for another request',\n )\n }\n if (!agentInteractiveSessionControlClaimMatchesRef(ref, acknowledgement.control)) {\n throw new RetainedRunProviderContractError(\n 'provider returned a prompt acknowledgement for another interactive process',\n )\n }\n return acknowledgement\n}\n\nfunction exactStop(\n ref: AgentInteractiveSessionRef,\n value: unknown,\n command: AgentInteractiveSessionStopCommand,\n): AgentInteractiveSessionStopAcknowledgement {\n const acknowledgement = parseProviderAcknowledgement(\n AgentInteractiveSessionStopAcknowledgementSchema,\n value,\n 'stop',\n )\n if (!agentInteractiveSessionStopAcknowledgementMatchesCommand(command, acknowledgement)) {\n throw new RetainedRunProviderContractError(\n 'provider returned a stop acknowledgement for another request',\n )\n }\n if (!agentInteractiveSessionControlClaimMatchesRef(ref, acknowledgement.control)) {\n throw new RetainedRunProviderContractError(\n 'provider returned a stop acknowledgement for another interactive process',\n )\n }\n return acknowledgement\n}\n\nfunction parseProviderAcknowledgement<T>(\n schema: { parse(value: unknown): T },\n value: unknown,\n operation: string,\n): T {\n try {\n return schema.parse(value)\n } catch {\n throw new RetainedRunProviderContractError(\n `provider returned an invalid interactive ${operation} acknowledgement`,\n )\n }\n}\n\nfunction exactStatus(\n ref: AgentInteractiveSessionRef,\n value: AgentInteractiveSessionStatus,\n requestedStart?: AgentInteractiveSessionStart,\n): AgentInteractiveSessionStatus {\n let status: AgentInteractiveSessionStatus\n try {\n status = AgentInteractiveSessionStatusSchema.parse(value)\n } catch (error) {\n if (requestedStart === undefined) throw error\n throw new RetainedInteractiveBindingError(\n detachedSnapshot(requestedStart, 'interactive status binding request'),\n {},\n { cause: error },\n )\n }\n if (!agentInteractiveSessionStatusMatchesRef(ref, status)) {\n if (requestedStart !== undefined) {\n throw new RetainedInteractiveBindingError(\n detachedSnapshot(requestedStart, 'interactive status binding request'),\n detachedSnapshot(\n { status: detachedSnapshot(status, 'interactive provider status') },\n 'interactive provider status result',\n ),\n { cause: new Error('provider returned status for another interactive process') },\n )\n }\n throw new Error('provider returned status for another interactive process')\n }\n return status\n}\n\nfunction exactTerminal(\n ref: AgentInteractiveSessionRef,\n request: AgentInteractiveSessionAttach,\n terminal: AgentInteractiveTerminalSession,\n): AgentInteractiveTerminalSession {\n const terminalRef = TerminalSessionRefSchema.parse(terminal.ref)\n TerminalReplayWindowSchema.parse(terminal.cursors)\n if (terminalRef.parentExecutionId !== ref.run.executionId) {\n throw new Error('provider attached a terminal from another interactive run')\n }\n AgentInteractiveSessionControlClaimSchema.parse(terminal.control)\n if (!agentInteractiveSessionControlClaimMatchesRef(ref, terminal.control)) {\n throw new Error('provider attached a terminal with a claim for another interactive process')\n }\n if (canonicalCandidateDigest(terminal.control) !== canonicalCandidateDigest(request.control)) {\n throw new Error('provider attached a terminal with a different interactive control claim')\n }\n return terminal\n}\n\nfunction sameInteractiveRef(\n left: AgentInteractiveSessionRef,\n right: AgentInteractiveSessionRef,\n): boolean {\n return canonicalCandidateDigest(left) === canonicalCandidateDigest(right)\n}\n","import type {\n AgentInteractiveSessionRef,\n AgentInteractiveSessionStart,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n AgentEnvironmentCapabilitiesSchema,\n AgentInteractiveSessionRefSchema,\n agentInteractiveSessionRefMatchesStart,\n agentInteractiveSessionRunRef,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n exactAgentInteractiveSessionStart,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { RetainedInteractiveBindingError } from '../errors'\nimport {\n createRetainedInteractiveRunHandle,\n freezeInteractiveRef,\n} from './retained-interactive-handle'\nimport {\n createInteractiveEnvironment,\n destroyInteractiveEnvironment,\n startInteractiveProcess,\n} from './retained-interactive-lifecycle'\nimport type {\n ReconnectRetainedInteractiveRunOptions,\n RecoverRetainedInteractiveRunOptions,\n RetainedInteractiveRunHandle,\n RetainedInteractiveStartMaterial,\n StartRetainedInteractiveRunOptions,\n} from './retained-interactive-types'\nimport { assertStableText, awaitAbortable } from './retained-run-binding'\nimport {\n legacyRetainedCreateMaterial,\n retainedCreateMaterial,\n retainedEnvironmentMetadata,\n} from './retained-run-intent'\nimport {\n admitDurably,\n journaledAdmissions,\n journaledInteractiveHandle,\n mintRetainedIdentity,\n} from './retained-run-start'\nimport type {\n RetainedInteractiveEnvironmentAdmission,\n RetainedInteractiveIntentAdmission,\n} from './retained-run-types'\nimport { detachedSnapshot } from './supervise/snapshot'\n\n/**\n * Start one retry-safe native coding-agent TUI without dispatching a headless turn.\n * The intent admission is durable before provider.create; the environment and\n * process admissions follow only after their exact provider coordinates exist.\n * @stable\n */\nexport async function startRetainedInteractiveRun(\n options: StartRetainedInteractiveRunOptions,\n): Promise<RetainedInteractiveRunHandle> {\n options.signal?.throwIfAborted()\n const startOptions = options\n assertStableText(startOptions.environment.idempotencyKey, 'environment idempotency key')\n assertStableText(startOptions.interactiveIdempotencyKey, 'interactive idempotency key')\n if (typeof startOptions.onAdmission !== 'function') {\n throw new Error('startRetainedInteractiveRun requires an awaited onAdmission durability hook')\n }\n if (!startOptions.provider.get) {\n throw new Error(\n `provider \"${startOptions.provider.name}\" cannot reconstruct an environment by id`,\n )\n }\n const profile = agentProfileSchema.parse(startOptions.environment.profile)\n if (profile.harness === undefined) {\n throw new Error('retained interactive runs require AgentProfile.harness')\n }\n const requestedProfileDigest = canonicalAgentProfileDigest(profile)\n const identity =\n startOptions.intent === undefined\n ? mintRetainedIdentity(\n startOptions.environment.idempotencyKey,\n startOptions.interactiveIdempotencyKey,\n )\n : {\n sessionId: startOptions.intent.sessionId,\n executionId: startOptions.intent.executionId,\n }\n assertStableText(identity.sessionId, 'retained session id')\n assertStableText(identity.executionId, 'retained execution id')\n // The journal is keyed by the session id, which every admission phase and the started ref carry,\n // so a recovery or a reconnect in another process appends to the same observer.jsonl.\n const onAdmission = journaledAdmissions(\n startOptions.journalRoot,\n identity.sessionId,\n startOptions.onAdmission,\n )\n const intent = interactiveIntent(startOptions, profile, identity)\n if (startOptions.intent === undefined) {\n // This is the only admission that can be written before provider.create.\n // A replay supplies the same record and therefore skips a duplicate write.\n await admitDurably(onAdmission, intent)\n } else {\n assertExactInteractiveIntent(startOptions.intent, intent, () =>\n // A record persisted by the previous version digested the pre-interface5\n // create projection; the exact legacy projection is accepted so an\n // upgrade never strands an in-flight interactive run.\n interactiveIntent(startOptions, profile, identity, legacyRetainedCreateMaterial),\n )\n }\n const providerCapabilities = AgentEnvironmentCapabilitiesSchema.parse(\n await awaitAbortable(\n Promise.resolve().then(() => startOptions.provider.capabilities()),\n startOptions.signal,\n ),\n )\n assertInteractiveCapabilities(startOptions.provider.name, providerCapabilities)\n\n const environment = await createInteractiveEnvironment(\n () =>\n startOptions.provider.create({\n ...startOptions.environment,\n profile,\n signal: startOptions.signal,\n metadata: retainedEnvironmentMetadata(\n startOptions.environment.metadata,\n startOptions.environment.idempotencyKey,\n ),\n }),\n startOptions.signal,\n )\n let capabilities: AgentEnvironmentCapabilities\n try {\n assertExactEnvironment(startOptions.provider.name, environment)\n startOptions.signal?.throwIfAborted()\n capabilities = interactiveCapabilitiesForEnvironment(\n startOptions.provider.name,\n providerCapabilities,\n environment,\n )\n assertInteractiveMethods(startOptions.provider.name, environment)\n } catch (error) {\n await destroyUnusedEnvironment(environment, error)\n throw error\n }\n\n const request = interactiveRequest(\n startOptions,\n environment,\n profile,\n requestedProfileDigest,\n identity,\n )\n await admitDurably(onAdmission, {\n phase: 'interactive_environment',\n provider: startOptions.provider.name,\n environmentId: environment.id,\n idempotencyKey: startOptions.environment.idempotencyKey,\n interactiveIdempotencyKey: startOptions.interactiveIdempotencyKey,\n request,\n })\n\n const ref = exactStartedRef(\n request,\n await startInteractiveProcess(\n environment,\n () =>\n environment.startInteractive!(request, {\n signal: startOptions.signal,\n }),\n startOptions.signal,\n ),\n )\n await admitDurably(onAdmission, {\n phase: 'interactive_started',\n idempotencyKey: startOptions.environment.idempotencyKey,\n interactiveIdempotencyKey: startOptions.interactiveIdempotencyKey,\n ref,\n })\n return journaledInteractiveHandle(\n createRetainedInteractiveRunHandle(environment, ref, capabilities, request),\n startOptions.journalRoot,\n identity.sessionId,\n )\n}\n\n/**\n * Retry one exact start after its provider response may have been lost.\n *\n * Resolves to the handle of the admitted process (resumed through the exact,\n * idempotent start request), or `null` when the provider no longer holds the\n * environment (not found; nothing remains to stop). @stable\n */\nexport async function recoverRetainedInteractiveRun(\n options: RecoverRetainedInteractiveRunOptions,\n): Promise<RetainedInteractiveRunHandle | null> {\n options.signal?.throwIfAborted()\n if (typeof options.onAdmission !== 'function') {\n throw new Error('recoverRetainedInteractiveRun requires an awaited onAdmission durability hook')\n }\n const admission = options.admission\n if (admission.provider !== options.provider.name) {\n throw new Error('interactive admission belongs to another provider')\n }\n if (admission.phase === 'interactive_intent') {\n if (options.replay === undefined) {\n throw new Error(\n 'recoverRetainedInteractiveRun requires the original start material for an interactive intent',\n )\n }\n return startRetainedInteractiveRun({\n provider: options.provider,\n ...options.replay,\n intent: admission,\n onAdmission: options.onAdmission,\n signal: options.signal,\n ...(options.journalRoot === undefined ? {} : { journalRoot: options.journalRoot }),\n })\n }\n const request = exactRecoveryRequest(admission)\n const { environment, capabilities } = await reconstructEnvironment(\n options.provider,\n admission.environmentId,\n options.signal,\n )\n if (!environment || !capabilities) return null\n const ref = exactStartedRef(\n request,\n await awaitAbortable(\n Promise.resolve().then(() =>\n environment.startInteractive!(request, {\n signal: options.signal,\n }),\n ),\n options.signal,\n ),\n )\n const sessionId = request.run.sessionId\n await admitDurably(journaledAdmissions(options.journalRoot, sessionId, options.onAdmission), {\n phase: 'interactive_started',\n idempotencyKey: admission.idempotencyKey,\n interactiveIdempotencyKey: admission.interactiveIdempotencyKey,\n ref,\n })\n return journaledInteractiveHandle(\n createRetainedInteractiveRunHandle(environment, ref, capabilities, request),\n options.journalRoot,\n sessionId,\n )\n}\n\nfunction exactRecoveryRequest(\n admission: RetainedInteractiveEnvironmentAdmission,\n): AgentInteractiveSessionStart {\n assertStableText(admission.environmentId, 'interactive environment id')\n assertStableText(admission.idempotencyKey, 'environment idempotency key')\n assertStableText(admission.interactiveIdempotencyKey, 'interactive idempotency key')\n const request = exactAgentInteractiveSessionStart(admission.request)\n const identity = mintRetainedIdentity(\n admission.idempotencyKey,\n admission.interactiveIdempotencyKey,\n )\n if (\n request.run.provider !== admission.provider ||\n request.run.environmentId !== admission.environmentId ||\n ((request.run.sessionId !== identity.sessionId ||\n request.run.executionId !== identity.executionId) &&\n !matchesHistoricalInteractiveIdentity(admission, request))\n ) {\n throw new Error('interactive admission does not match its recovery coordinates')\n }\n return request\n}\n\nfunction matchesHistoricalInteractiveIdentity(\n admission: RetainedInteractiveEnvironmentAdmission,\n request: AgentInteractiveSessionStart,\n): boolean {\n // These admissions predate storage-safe IDs and still bind both idempotency keys.\n // Reconstruct their coordinates only to validate the stored request, never to replace it.\n const base = `${encodeURIComponent(admission.idempotencyKey)}:${encodeURIComponent(admission.interactiveIdempotencyKey)}`\n const digest = canonicalCandidateDigest({ kind: 'retained-identity.v1', base }).slice(\n 'sha256:'.length,\n )\n const historicalId = (prefix: string): string => {\n const readable = `${prefix}:${base}`\n return readable.length <= 128 ? readable : `${prefix}:${digest}`\n }\n return (\n request.run.sessionId === historicalId('retained-session') &&\n request.run.executionId === historicalId('retained-execution')\n )\n}\n\n/** Rebuild controls for one exact provider-owned coding-agent process. @stable */\nexport async function reconnectRetainedInteractiveRun(\n options: ReconnectRetainedInteractiveRunOptions,\n): Promise<RetainedInteractiveRunHandle | null> {\n options.signal?.throwIfAborted()\n const ref = AgentInteractiveSessionRefSchema.parse(options.ref)\n if (ref.run.provider !== options.provider.name) {\n throw new Error('interactive session reference belongs to another provider')\n }\n const { environment, capabilities } = await reconstructEnvironment(\n options.provider,\n ref.run.environmentId,\n options.signal,\n )\n if (!environment || !capabilities) return null\n const handle = journaledInteractiveHandle(\n createRetainedInteractiveRunHandle(environment, ref, capabilities),\n options.journalRoot,\n ref.run.sessionId,\n )\n await handle.status({ signal: options.signal })\n return handle\n}\n\nfunction interactiveRequest(\n options: StartRetainedInteractiveRunOptions,\n environment: AgentEnvironment,\n profile: StartRetainedInteractiveRunOptions['environment']['profile'],\n requestedProfileDigest: `sha256:${string}`,\n identity: { readonly sessionId: string; readonly executionId: string },\n): AgentInteractiveSessionStart {\n const start = {\n profile,\n requestedProfileDigest,\n ...(options.initialPrompt === undefined ? {} : { initialPrompt: options.initialPrompt }),\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n ...(options.cols === undefined ? {} : { cols: options.cols }),\n ...(options.rows === undefined ? {} : { rows: options.rows }),\n }\n const run = agentInteractiveSessionRunRef(\n {\n provider: options.provider.name,\n environmentId: environment.id,\n ...identity,\n },\n start,\n )\n return exactAgentInteractiveSessionStart({ run, ...start })\n}\n\nfunction interactiveIntent(\n options: StartRetainedInteractiveRunOptions,\n profile: StartRetainedInteractiveRunOptions['environment']['profile'],\n identity: { readonly sessionId: string; readonly executionId: string },\n createMaterial: typeof retainedCreateMaterial = retainedCreateMaterial,\n): RetainedInteractiveIntentAdmission {\n const requestedProfileDigest = canonicalAgentProfileDigest(profile)\n const requestDigest = canonicalCandidateDigest({\n kind: 'retained-interactive-intent.v1',\n provider: options.provider.name,\n idempotencyKey: options.environment.idempotencyKey,\n interactiveIdempotencyKey: options.interactiveIdempotencyKey,\n sessionId: identity.sessionId,\n executionId: identity.executionId,\n requestedProfileDigest,\n create: createMaterial(options.environment),\n start: sanitizedStartMaterial(options),\n })\n return {\n phase: 'interactive_intent',\n provider: options.provider.name,\n idempotencyKey: options.environment.idempotencyKey,\n interactiveIdempotencyKey: options.interactiveIdempotencyKey,\n sessionId: identity.sessionId,\n executionId: identity.executionId,\n runId: `interactive-intent-run:${requestDigest.slice('sha256:'.length)}`,\n requestedProfileDigest,\n requestDigest,\n }\n}\n\nfunction sanitizedStartMaterial(\n options: RetainedInteractiveStartMaterial,\n): Record<string, unknown> {\n return {\n ...(options.initialPrompt === undefined ? {} : { initialPrompt: options.initialPrompt }),\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n ...(options.cols === undefined ? {} : { cols: options.cols }),\n ...(options.rows === undefined ? {} : { rows: options.rows }),\n }\n}\n\nfunction assertExactInteractiveIntent(\n received: RetainedInteractiveIntentAdmission,\n expected: RetainedInteractiveIntentAdmission,\n legacyExpected?: () => RetainedInteractiveIntentAdmission,\n): void {\n const stableReceived = parseInteractiveIntent(received)\n if (canonicalCandidateDigest(stableReceived) !== canonicalCandidateDigest(expected)) {\n if (\n legacyExpected === undefined ||\n canonicalCandidateDigest(stableReceived) !== canonicalCandidateDigest(legacyExpected())\n ) {\n throw new Error('interactive intent conflicts with replay material')\n }\n }\n}\n\nfunction parseInteractiveIntent(value: unknown): RetainedInteractiveIntentAdmission {\n const stable = detachedSnapshot(value, 'interactive intent')\n if (stable === null || typeof stable !== 'object' || Array.isArray(stable)) {\n throw new Error('interactive intent is malformed')\n }\n const record = stable as Record<string, unknown>\n const allowed = new Set([\n 'phase',\n 'provider',\n 'idempotencyKey',\n 'interactiveIdempotencyKey',\n 'sessionId',\n 'executionId',\n 'runId',\n 'requestedProfileDigest',\n 'requestDigest',\n ])\n if (Object.keys(record).some((key) => !allowed.has(key))) {\n throw new Error('interactive intent contains unsupported material')\n }\n if (record.phase !== 'interactive_intent') {\n throw new Error('interactive intent has an invalid phase')\n }\n for (const [key, value] of Object.entries(record)) {\n if (key === 'phase') continue\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`interactive intent field \"${key}\" is invalid`)\n }\n }\n assertDigest(record.requestedProfileDigest, 'interactive intent profile digest')\n assertDigest(record.requestDigest, 'interactive intent request digest')\n return stable as RetainedInteractiveIntentAdmission\n}\n\nfunction assertDigest(value: unknown, label: string): asserts value is Sha256Digest {\n if (typeof value !== 'string' || !/^sha256:[a-f0-9]{64}$/u.test(value)) {\n throw new Error(`${label} is invalid`)\n }\n}\n\nasync function reconstructEnvironment(\n provider: ReconnectRetainedInteractiveRunOptions['provider'],\n environmentId: string,\n signal?: AbortSignal,\n): Promise<{\n environment: AgentEnvironment | null\n capabilities: AgentEnvironmentCapabilities | null\n}> {\n if (!provider.get) {\n throw new Error(`provider \"${provider.name}\" cannot reconstruct an environment by id`)\n }\n const providerCapabilities = AgentEnvironmentCapabilitiesSchema.parse(\n await awaitAbortable(\n Promise.resolve().then(() => provider.capabilities()),\n signal,\n ),\n )\n assertInteractiveCapabilities(provider.name, providerCapabilities)\n const environment = await awaitAbortable(\n Promise.resolve().then(() => provider.get!(environmentId, { signal })),\n signal,\n )\n if (!environment) return { environment: null, capabilities: null }\n assertExactEnvironment(provider.name, environment, environmentId)\n const capabilities = interactiveCapabilitiesForEnvironment(\n provider.name,\n providerCapabilities,\n environment,\n )\n assertInteractiveMethods(provider.name, environment)\n return { environment, capabilities }\n}\n\nfunction exactStartedRef(\n request: AgentInteractiveSessionStart,\n value: AgentInteractiveSessionRef,\n): AgentInteractiveSessionRef {\n const stableRequest = detachedSnapshot(request, 'interactive start binding request')\n let ref: AgentInteractiveSessionRef\n try {\n ref = AgentInteractiveSessionRefSchema.parse(value)\n } catch (error) {\n throw new RetainedInteractiveBindingError(stableRequest, {}, { cause: error })\n }\n if (!agentInteractiveSessionRefMatchesStart(request, ref)) {\n throw new RetainedInteractiveBindingError(\n stableRequest,\n detachedSnapshot(\n { ref: detachedSnapshot(ref, 'interactive provider start reference') },\n 'interactive provider start result',\n ),\n { cause: new Error('provider started another interactive run than requested') },\n )\n }\n return freezeInteractiveRef(ref)\n}\n\nfunction assertExactEnvironment(\n providerName: string,\n environment: AgentEnvironment,\n environmentId?: string,\n): void {\n if (\n environment.provider !== providerName ||\n (environmentId && environment.id !== environmentId)\n ) {\n throw new Error('provider returned another interactive environment')\n }\n assertStableText(environment.id, 'interactive environment id')\n}\n\nfunction interactiveCapabilitiesForEnvironment(\n providerName: string,\n providerCapabilities: AgentEnvironmentCapabilities,\n environment: AgentEnvironment,\n): AgentEnvironmentCapabilities {\n const capabilities =\n environment.capabilities === undefined\n ? providerCapabilities\n : AgentEnvironmentCapabilitiesSchema.parse(environment.capabilities)\n assertInteractiveCapabilities(providerName, capabilities)\n return capabilities\n}\n\nfunction assertInteractiveCapabilities(\n providerName: string,\n capabilities: AgentEnvironmentCapabilities,\n): void {\n const interactive = capabilities.interactiveAgent\n if (\n !interactive?.start ||\n !interactive.control ||\n !interactive.status ||\n !interactive.attach ||\n !interactive.reattach ||\n !interactive.sendPrompt ||\n !interactive.input ||\n !interactive.resize ||\n !interactive.stop\n ) {\n throw new Error(`provider \"${providerName}\" cannot control an exact interactive agent`)\n }\n}\n\nfunction assertInteractiveMethods(providerName: string, environment: AgentEnvironment): void {\n if (!environment.startInteractive || !environment.interactive) {\n throw new Error(`provider \"${providerName}\" exposes incomplete interactive agent controls`)\n }\n}\n\nasync function destroyUnusedEnvironment(\n environment: AgentEnvironment,\n cause: unknown,\n): Promise<void> {\n try {\n await destroyInteractiveEnvironment(environment)\n } catch (cleanupError) {\n throw new AggregateError(\n [cause, cleanupError],\n 'interactive environment was invalid and could not be destroyed',\n )\n }\n}\n","import { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { AgentInteractiveSessionRef } from '@tangle-network/agent-interface'\nimport {\n AgentInteractiveSessionRefSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider'\nimport { FileSpawnJournal } from '../../durable/spawn-journal/journal-store'\nimport { spawnJournalRecordEvents } from '../../durable/spawn-journal/record-events'\nimport { loadSpawnForest } from '../../durable/spawn-journal/spawn-forest'\nimport type { AgentEnvironmentProviderRegistry } from '../environment-provider/provider-registry'\nimport { reconnectRetainedInteractiveRun } from '../retained-interactive'\nimport { assertNoSymlinkDescendant, publishExclusiveDurableFile } from './durable-file'\nimport type { WorkerInteractiveSession, WorkerInteractiveUnavailableReason } from './types'\n\nconst WORKER_BINDING_SCHEMA_VERSION = 1 as const\nconst SPAWN_JOURNAL_FILE = 'spawn-journal.jsonl'\n\n/** Durable exact-process binding or capability decision for one supervised worker. @stable */\nexport type WorkerInteractiveBinding =\n | {\n readonly schemaVersion: 1\n readonly workerId: string\n readonly label: string\n readonly journalRoot: string\n readonly recordedAt: string\n readonly status: 'available'\n readonly ref: AgentInteractiveSessionRef\n readonly refDigest: `sha256:${string}`\n }\n | {\n readonly schemaVersion: 1\n readonly workerId: string\n readonly label: string\n readonly journalRoot: string\n readonly recordedAt: string\n readonly status: 'unavailable'\n readonly reason: WorkerInteractiveUnavailableReason\n }\n\n/** Provider lookup accepted by {@link attachWorker}. @stable */\nexport type WorkerInteractiveProviderSource =\n | AgentEnvironmentProvider\n | AgentEnvironmentProviderRegistry\n\n/** Options for reconstructing one worker's exact retained interactive process. @stable */\nexport interface AttachWorkerOptions {\n readonly providers: WorkerInteractiveProviderSource\n readonly signal?: AbortSignal\n}\n\n/** Directory containing exact per-worker interactive binding records. @stable */\nexport function workerInteractiveBindingsDir(eventDir: string): string {\n return join(eventDir, 'interactive-workers')\n}\n\n/** Exact durable binding file for one worker id. @stable */\nexport function workerInteractiveBindingFile(eventDir: string, workerId: string): string {\n const id = stableText(workerId, 'worker id')\n const stem = createHash('sha256').update(id).digest('hex')\n return join(workerInteractiveBindingsDir(eventDir), `${stem}.json`)\n}\n\n/** Read and validate one exact durable worker binding. @stable */\nexport function readWorkerInteractiveBinding(\n eventDir: string,\n workerId: string,\n): WorkerInteractiveBinding | undefined {\n const id = stableText(workerId, 'worker id')\n const file = workerInteractiveBindingFile(eventDir, id)\n assertNoSymlinkDescendant(eventDir, file, 'worker interactive')\n if (!existsSync(file)) return undefined\n const binding = parseBinding(JSON.parse(readFileSync(file, 'utf8')))\n if (binding.workerId !== id) {\n throw new Error(\n `worker interactive binding collision: '${file}' holds '${binding.workerId}', not '${id}'`,\n )\n }\n return binding\n}\n\n/**\n * Publish the exact interactive capability of one worker after its spawn record commits.\n * Replays of the same binding are no-ops; a different binding for one worker fails loud.\n * @internal\n */\nexport function writeWorkerInteractiveBinding(\n eventDir: string,\n workerId: string,\n label: string,\n journalRoot: string,\n session: WorkerInteractiveSession,\n now = Date.now,\n): WorkerInteractiveBinding {\n const id = stableText(workerId, 'worker id')\n const workerLabel = stableText(label, 'worker label')\n const root = stableText(journalRoot, 'journal root')\n const binding: WorkerInteractiveBinding =\n session.status === 'available'\n ? (() => {\n const ref = AgentInteractiveSessionRefSchema.parse(session.handle.ref)\n return {\n schemaVersion: WORKER_BINDING_SCHEMA_VERSION,\n workerId: id,\n label: workerLabel,\n journalRoot: root,\n recordedAt: new Date(now()).toISOString(),\n status: 'available',\n ref,\n refDigest: canonicalCandidateDigest(ref),\n }\n })()\n : {\n schemaVersion: WORKER_BINDING_SCHEMA_VERSION,\n workerId: id,\n label: workerLabel,\n journalRoot: root,\n recordedAt: new Date(now()).toISOString(),\n status: 'unavailable',\n reason: session.reason,\n }\n const file = workerInteractiveBindingFile(eventDir, id)\n assertNoSymlinkDescendant(eventDir, file, 'worker interactive')\n mkdirSync(dirname(file), { recursive: true })\n assertNoSymlinkDescendant(eventDir, file, 'worker interactive')\n const existing = readWorkerInteractiveBinding(eventDir, id)\n if (existing !== undefined) {\n assertSameBinding(existing, binding)\n return existing\n }\n if (publishExclusiveDurableFile(file, `${JSON.stringify(binding, null, 2)}\\n`)) {\n return binding\n }\n const winner = readWorkerInteractiveBinding(eventDir, id)\n if (winner === undefined) {\n throw new Error(`worker interactive binding publication lost its winner`)\n }\n assertSameBinding(winner, binding)\n return winner\n}\n\n/**\n * Reconstruct the exact provider-owned interactive process bound to one supervised worker.\n * Unknown, headless, unsupported, settled, stale, and unregistered-provider cases fail closed.\n * @stable\n */\nexport async function attachWorker(\n eventDir: string,\n workerId: string,\n options: AttachWorkerOptions,\n): Promise<WorkerInteractiveSession> {\n const id = stableText(workerId, 'worker id')\n options.signal?.throwIfAborted()\n const binding = readWorkerInteractiveBinding(eventDir, id)\n if (binding === undefined) {\n const lifecycle = workerLifecycle(eventDir, id)\n return unavailable(\n lifecycle.terminal\n ? 'not-live'\n : lifecycle.spawned\n ? 'interactive-binding-not-found'\n : 'unknown-node',\n )\n }\n try {\n const forest = await loadSpawnForest(\n new FileSpawnJournal(join(eventDir, SPAWN_JOURNAL_FILE)),\n binding.journalRoot,\n )\n const node = forest.nodes.find((candidate) => candidate.id === id)\n if (node === undefined) return unavailable('unknown-node')\n if (node.status === 'done' || node.status === 'failed' || node.status === 'cancelled') {\n return unavailable('not-live')\n }\n } catch {\n return unavailable('interactive-binding-stale')\n }\n if (binding.status === 'unavailable') return unavailable(binding.reason)\n const provider = resolveProvider(options.providers, binding.ref.run.provider)\n if (provider === undefined) return unavailable('interactive-provider-not-registered')\n let handle: Awaited<ReturnType<typeof reconnectRetainedInteractiveRun>>\n try {\n handle = await reconnectRetainedInteractiveRun({\n provider,\n ref: binding.ref,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n } catch (error) {\n options.signal?.throwIfAborted()\n if (isUnsupportedProvider(error)) return unavailable('provider-has-no-interactive-contract')\n return unavailable('interactive-binding-stale')\n }\n if (handle === null) return unavailable('interactive-binding-stale')\n let status: Awaited<ReturnType<typeof handle.status>>\n try {\n status = await handle.status(\n options.signal === undefined ? undefined : { signal: options.signal },\n )\n } catch {\n options.signal?.throwIfAborted()\n return unavailable('interactive-binding-stale')\n }\n if (status.state !== 'running') return unavailable('interactive-binding-stale')\n return { status: 'available', handle }\n}\n\nfunction parseBinding(value: unknown): WorkerInteractiveBinding {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('worker interactive binding is malformed')\n }\n const record = value as Record<string, unknown>\n if (\n record.schemaVersion !== WORKER_BINDING_SCHEMA_VERSION ||\n typeof record.workerId !== 'string' ||\n record.workerId.length === 0 ||\n typeof record.label !== 'string' ||\n record.label.length === 0 ||\n typeof record.journalRoot !== 'string' ||\n record.journalRoot.length === 0 ||\n typeof record.recordedAt !== 'string'\n ) {\n throw new Error('worker interactive binding is malformed')\n }\n if (record.status === 'available') {\n const ref = AgentInteractiveSessionRefSchema.parse(record.ref)\n const refDigest = canonicalCandidateDigest(ref)\n if (record.refDigest !== refDigest) {\n throw new Error('worker interactive binding ref digest does not match its exact ref')\n }\n return {\n schemaVersion: WORKER_BINDING_SCHEMA_VERSION,\n workerId: record.workerId,\n label: record.label,\n journalRoot: record.journalRoot,\n recordedAt: record.recordedAt,\n status: 'available',\n ref,\n refDigest,\n }\n }\n if (record.status !== 'unavailable' || !isUnavailableReason(record.reason)) {\n throw new Error('worker interactive binding is malformed')\n }\n return {\n schemaVersion: WORKER_BINDING_SCHEMA_VERSION,\n workerId: record.workerId,\n label: record.label,\n journalRoot: record.journalRoot,\n recordedAt: record.recordedAt,\n status: 'unavailable',\n reason: record.reason,\n }\n}\n\nfunction assertSameBinding(\n current: WorkerInteractiveBinding,\n candidate: WorkerInteractiveBinding,\n): void {\n const currentMaterial = bindingMaterial(current)\n const candidateMaterial = bindingMaterial(candidate)\n if (canonicalCandidateDigest(currentMaterial) !== canonicalCandidateDigest(candidateMaterial)) {\n throw new Error(`worker '${candidate.workerId}' already has a different interactive binding`)\n }\n}\n\nfunction bindingMaterial(binding: WorkerInteractiveBinding): Record<string, unknown> {\n return binding.status === 'available'\n ? {\n schemaVersion: binding.schemaVersion,\n workerId: binding.workerId,\n label: binding.label,\n journalRoot: binding.journalRoot,\n status: binding.status,\n ref: binding.ref,\n refDigest: binding.refDigest,\n }\n : {\n schemaVersion: binding.schemaVersion,\n workerId: binding.workerId,\n label: binding.label,\n journalRoot: binding.journalRoot,\n status: binding.status,\n reason: binding.reason,\n }\n}\n\nfunction workerLifecycle(\n eventDir: string,\n workerId: string,\n): { readonly spawned: boolean; readonly terminal: boolean } {\n let raw: string\n try {\n raw = readFileSync(join(eventDir, SPAWN_JOURNAL_FILE), 'utf8')\n } catch {\n return { spawned: false, terminal: false }\n }\n let spawned = false\n let terminal = false\n for (const line of raw.split('\\n')) {\n const text = line.trim()\n if (!text) continue\n try {\n for (const event of spawnJournalRecordEvents(JSON.parse(text))) {\n if (event?.id !== workerId) continue\n if (event.kind === 'spawned') spawned = true\n if (event.kind === 'settled' || event.kind === 'cancelled') terminal = true\n }\n } catch {\n // A partial tail cannot erase earlier committed lifecycle evidence.\n }\n }\n return { spawned, terminal }\n}\n\nfunction resolveProvider(\n source: WorkerInteractiveProviderSource,\n name: string,\n): AgentEnvironmentProvider | undefined {\n if ('register' in source) return source.get(name)\n return source.name === name ? source : undefined\n}\n\nfunction unavailable(reason: WorkerInteractiveUnavailableReason): WorkerInteractiveSession {\n return { status: 'unavailable', reason }\n}\n\nfunction stableText(value: string, label: string): string {\n const text = value.trim()\n if (!text) throw new Error(`${label} is empty`)\n return text\n}\n\nfunction isUnsupportedProvider(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error)\n return (\n message.includes('cannot reconstruct an environment') ||\n message.includes('cannot control an exact interactive agent') ||\n message.includes('incomplete interactive agent controls')\n )\n}\n\nfunction isUnavailableReason(value: unknown): value is WorkerInteractiveUnavailableReason {\n return (\n value === 'unknown-node' ||\n value === 'not-live' ||\n value === 'executor-exposes-no-interactive-session' ||\n value === 'provider-has-no-interactive-contract' ||\n value === 'interactive-session-not-started' ||\n value === 'interactive-binding-not-found' ||\n value === 'interactive-binding-stale' ||\n value === 'interactive-provider-not-registered'\n )\n}\n","/**\n * Durable, credential-free admissions for Runtime-owned interactive workers.\n *\n * `startRetainedInteractiveRun` deliberately asks its caller to persist each admission before it\n * advances. A supervised worker supplies this hook through `Scope`; the hook stores only recovery\n * coordinates and digests, never the profile, prompt, environment variables, or other private\n * create material.\n */\n\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport {\n type AgentInteractiveSessionRef,\n AgentInteractiveSessionRefSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { assertNoSymlinkDescendant, publishExclusiveDurableFile } from './durable-file'\nimport { workerInteractiveBindingsDir } from './worker-interactive'\n\n/** The Scope seam key used by `workerFromInteractiveProvider`. */\nexport const interactiveAdmissionSeamKey = 'runtime.interactiveAdmission'\n\n/** The credential-free record written for one interactive admission phase. */\nexport type WorkerInteractiveAdmission =\n | {\n readonly schemaVersion: 1\n readonly workerId: string\n readonly recordedAt: string\n readonly phase: 'interactive_intent'\n readonly provider: string\n readonly idempotencyKey: string\n readonly interactiveIdempotencyKey: string\n readonly sessionId: string\n readonly executionId: string\n readonly runId: string\n readonly requestedProfileDigest: `sha256:${string}`\n readonly requestDigest: `sha256:${string}`\n }\n | {\n readonly schemaVersion: 1\n readonly workerId: string\n readonly recordedAt: string\n readonly phase: 'interactive_environment'\n readonly provider: string\n readonly environmentId: string\n readonly idempotencyKey: string\n readonly interactiveIdempotencyKey: string\n readonly requestDigest: `sha256:${string}`\n }\n | {\n readonly schemaVersion: 1\n readonly workerId: string\n readonly recordedAt: string\n readonly phase: 'interactive_started'\n readonly idempotencyKey: string\n readonly interactiveIdempotencyKey: string\n readonly ref: AgentInteractiveSessionRef\n readonly refDigest: `sha256:${string}`\n }\n\n/** Runtime-owned admission sink supplied to an interactive worker executor. */\nexport type InteractiveAdmissionWriter = (admission: RetainedInteractiveAdmission) => Promise<void>\n\n/** Return the exact credential-free admission file for one worker and phase. */\nfunction workerInteractiveAdmissionFile(\n eventDir: string,\n workerId: string,\n phase: WorkerInteractiveAdmission['phase'],\n): string {\n const dir = workerInteractiveBindingsDir(eventDir)\n const id = stableText(workerId, 'worker id')\n assertNoSymlinkDescendant(eventDir, dir, 'interactive admission')\n const stem = canonicalCandidateDigest({ workerId: id }).slice('sha256:'.length).slice(0, 32)\n return join(dir, `${stem}.${phase}.admission.json`)\n}\n\n/** Read all durable admissions for one worker, oldest phase first. */\nexport function readWorkerInteractiveAdmissions(\n eventDir: string,\n workerId: string,\n): ReadonlyArray<WorkerInteractiveAdmission> {\n const phases: ReadonlyArray<WorkerInteractiveAdmission['phase']> = [\n 'interactive_intent',\n 'interactive_environment',\n 'interactive_started',\n ]\n const admissions: WorkerInteractiveAdmission[] = []\n let missingPhase = false\n for (const phase of phases) {\n const file = workerInteractiveAdmissionFile(eventDir, workerId, phase)\n if (!existsSync(file)) {\n missingPhase = true\n continue\n }\n if (missingPhase) {\n throw new Error(`interactive admission phase '${phase}' exists after a missing earlier phase`)\n }\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown\n admissions.push(parseAdmission(parsed, workerId, phase))\n }\n return admissions\n}\n\n/**\n * Persist one retained-interactive admission without retaining sensitive start material.\n *\n * The phase file is an idempotency key. A retry with the same exact admission is a no-op; a\n * different admission for the same phase fails closed rather than overwriting recovery evidence.\n */\nexport function writeWorkerInteractiveAdmission(\n eventDir: string,\n workerId: string,\n admission: RetainedInteractiveAdmission,\n now: () => number = Date.now,\n): WorkerInteractiveAdmission {\n const id = stableText(workerId, 'worker id')\n const record = credentialFreeAdmission(id, admission, now)\n const file = workerInteractiveAdmissionFile(eventDir, id, record.phase)\n assertNoSymlinkDescendant(eventDir, file, 'interactive admission')\n mkdirSync(dirname(file), { recursive: true })\n assertNoSymlinkDescendant(eventDir, file, 'interactive admission')\n\n const existing = readWorkerInteractiveAdmission(eventDir, id, record.phase)\n if (existing !== undefined) {\n assertSameAdmission(existing, record)\n return existing\n }\n\n if (publishExclusiveDurableFile(file, `${JSON.stringify(record, null, 2)}\\n`)) {\n return record\n }\n const winner = readWorkerInteractiveAdmission(eventDir, id, record.phase)\n if (winner === undefined) {\n throw new Error(`interactive admission publication for '${record.phase}' lost its winner`)\n }\n assertSameAdmission(winner, record)\n return winner\n}\n\nfunction credentialFreeAdmission(\n workerId: string,\n admission: RetainedInteractiveAdmission,\n now: () => number,\n): WorkerInteractiveAdmission {\n const recordedAt = new Date(now()).toISOString()\n switch (admission.phase) {\n case 'interactive_intent':\n return {\n schemaVersion: 1,\n workerId,\n recordedAt,\n phase: admission.phase,\n provider: admission.provider,\n idempotencyKey: admission.idempotencyKey,\n interactiveIdempotencyKey: admission.interactiveIdempotencyKey,\n sessionId: admission.sessionId,\n executionId: admission.executionId,\n runId: admission.runId,\n requestedProfileDigest: admission.requestedProfileDigest,\n requestDigest: admission.requestDigest,\n }\n case 'interactive_environment':\n return {\n schemaVersion: 1,\n workerId,\n recordedAt,\n phase: admission.phase,\n provider: admission.provider,\n environmentId: admission.environmentId,\n idempotencyKey: admission.idempotencyKey,\n interactiveIdempotencyKey: admission.interactiveIdempotencyKey,\n requestDigest: canonicalCandidateDigest(admission.request),\n }\n case 'interactive_started':\n return {\n schemaVersion: 1,\n workerId,\n recordedAt,\n phase: admission.phase,\n idempotencyKey: admission.idempotencyKey,\n interactiveIdempotencyKey: admission.interactiveIdempotencyKey,\n ref: admission.ref,\n refDigest: canonicalCandidateDigest(admission.ref),\n }\n }\n}\n\nfunction readWorkerInteractiveAdmission(\n eventDir: string,\n workerId: string,\n phase: WorkerInteractiveAdmission['phase'],\n): WorkerInteractiveAdmission | undefined {\n const file = workerInteractiveAdmissionFile(eventDir, workerId, phase)\n if (!existsSync(file)) return undefined\n return parseAdmission(JSON.parse(readFileSync(file, 'utf8')), workerId, phase)\n}\n\nfunction parseAdmission(\n value: unknown,\n expectedWorkerId?: string,\n expectedPhase?: WorkerInteractiveAdmission['phase'],\n): WorkerInteractiveAdmission {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('interactive admission is malformed')\n }\n const record = value as Record<string, unknown>\n if (\n record.schemaVersion !== 1 ||\n typeof record.workerId !== 'string' ||\n record.workerId.length === 0 ||\n typeof record.recordedAt !== 'string' ||\n !Number.isFinite(Date.parse(record.recordedAt))\n ) {\n throw new Error('interactive admission is malformed')\n }\n if (expectedWorkerId !== undefined && record.workerId !== expectedWorkerId) {\n throw new Error('interactive admission worker id does not match its file')\n }\n if (record.phase === 'interactive_intent') {\n assertAllowedFields(record, [\n 'schemaVersion',\n 'workerId',\n 'recordedAt',\n 'phase',\n 'provider',\n 'idempotencyKey',\n 'interactiveIdempotencyKey',\n 'sessionId',\n 'executionId',\n 'runId',\n 'requestedProfileDigest',\n 'requestDigest',\n ])\n assertStrings(record, [\n 'provider',\n 'idempotencyKey',\n 'interactiveIdempotencyKey',\n 'sessionId',\n 'executionId',\n 'runId',\n 'requestedProfileDigest',\n 'requestDigest',\n ])\n assertDigest(record.requestedProfileDigest, 'interactive admission profile digest')\n assertDigest(record.requestDigest, 'interactive admission request digest')\n assertPhase(record.phase, expectedPhase)\n return {\n schemaVersion: 1,\n workerId: record.workerId,\n recordedAt: record.recordedAt,\n phase: record.phase,\n provider: record.provider as string,\n idempotencyKey: record.idempotencyKey as string,\n interactiveIdempotencyKey: record.interactiveIdempotencyKey as string,\n sessionId: record.sessionId as string,\n executionId: record.executionId as string,\n runId: record.runId as string,\n requestedProfileDigest: record.requestedProfileDigest,\n requestDigest: record.requestDigest,\n }\n }\n if (record.phase === 'interactive_environment') {\n assertAllowedFields(record, [\n 'schemaVersion',\n 'workerId',\n 'recordedAt',\n 'phase',\n 'provider',\n 'environmentId',\n 'idempotencyKey',\n 'interactiveIdempotencyKey',\n 'requestDigest',\n ])\n assertStrings(record, [\n 'provider',\n 'environmentId',\n 'idempotencyKey',\n 'interactiveIdempotencyKey',\n 'requestDigest',\n ])\n assertDigest(record.requestDigest, 'interactive admission environment request digest')\n assertPhase(record.phase, expectedPhase)\n return {\n schemaVersion: 1,\n workerId: record.workerId,\n recordedAt: record.recordedAt,\n phase: record.phase,\n provider: record.provider as string,\n environmentId: record.environmentId as string,\n idempotencyKey: record.idempotencyKey as string,\n interactiveIdempotencyKey: record.interactiveIdempotencyKey as string,\n requestDigest: record.requestDigest,\n }\n }\n if (record.phase === 'interactive_started') {\n assertAllowedFields(record, [\n 'schemaVersion',\n 'workerId',\n 'recordedAt',\n 'phase',\n 'idempotencyKey',\n 'interactiveIdempotencyKey',\n 'ref',\n 'refDigest',\n ])\n assertStrings(record, ['idempotencyKey', 'interactiveIdempotencyKey', 'refDigest'])\n const ref = AgentInteractiveSessionRefSchema.parse(record.ref)\n const refDigest = canonicalCandidateDigest(ref)\n if (record.refDigest !== refDigest) {\n throw new Error('interactive admission ref digest does not match its exact ref')\n }\n assertPhase(record.phase, expectedPhase)\n return {\n schemaVersion: 1,\n workerId: record.workerId,\n recordedAt: record.recordedAt,\n phase: record.phase,\n idempotencyKey: record.idempotencyKey as string,\n interactiveIdempotencyKey: record.interactiveIdempotencyKey as string,\n ref,\n refDigest,\n }\n }\n throw new Error('interactive admission has an invalid phase')\n}\n\nfunction assertDigest(value: unknown, label: string): asserts value is `sha256:${string}` {\n if (typeof value !== 'string' || !/^sha256:[a-f0-9]{64}$/u.test(value)) {\n throw new Error(`${label} is malformed`)\n }\n}\n\nfunction assertPhase(\n phase: WorkerInteractiveAdmission['phase'],\n expected: WorkerInteractiveAdmission['phase'] | undefined,\n): void {\n if (expected !== undefined && phase !== expected) {\n throw new Error('interactive admission phase does not match its file')\n }\n}\n\nfunction assertStrings(record: Record<string, unknown>, keys: ReadonlyArray<string>): void {\n for (const key of keys) {\n if (typeof record[key] !== 'string' || (record[key] as string).length === 0) {\n throw new Error(`interactive admission field '${key}' is invalid`)\n }\n }\n}\n\nfunction assertAllowedFields(\n record: Record<string, unknown>,\n allowed: ReadonlyArray<string>,\n): void {\n const fields = new Set(allowed)\n const unsupported = Object.keys(record).filter((key) => !fields.has(key))\n if (unsupported.length > 0) {\n throw new Error(`interactive admission contains unsupported fields: ${unsupported.join(', ')}`)\n }\n}\n\nfunction assertSameAdmission(\n current: WorkerInteractiveAdmission,\n candidate: WorkerInteractiveAdmission,\n): void {\n const comparable = (value: WorkerInteractiveAdmission): unknown => {\n const { recordedAt: _recordedAt, ...stable } = value\n return stable\n }\n if (\n canonicalCandidateDigest(comparable(current)) !==\n canonicalCandidateDigest(comparable(candidate))\n ) {\n throw new Error(\n `worker '${candidate.workerId}' already has a different ${candidate.phase} admission`,\n )\n }\n}\n\nfunction stableText(value: string, label: string): string {\n const text = value.trim()\n if (!text) throw new Error(`${label} is empty`)\n return text\n}\n","import type { RuntimeHooks } from '../../runtime-hooks'\nimport type { RuntimeFailureCause } from '../failure-cause'\nimport type { HarnessTranscriptEvidence } from '../harness-transcript'\nimport type { RetainedRunEnvironmentAdmission } from '../retained-run-types'\nimport type { RunCancellationReason } from './abortable'\nimport type { BudgetPool } from './budget'\nimport type { DeadlineCheckIn, TeardownAnswer } from './deadline'\nimport type { ExecutorProgress } from './progress'\nimport type { RetainedChildRecovery, RetainedPendingCause } from './retained-executor'\nimport type { TraceRootWriter } from './trace-root'\nimport type { TraceSource } from './trace-source'\nimport type {\n Budget,\n BudgetViolation,\n DefaultVerdict,\n EnvironmentTeardownReceipt,\n ExecutionBindingReceipt,\n ExecutorCancellation,\n ExecutorCancellationRequest,\n ExecutorFactory,\n ExecutorRegistry,\n ExecutorResult,\n HeldEnvironment,\n HeldForContinuation,\n NodeExecutionIdentity,\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ProfileMaterializationReceipt,\n RecursiveReservationPolicy,\n ResultBlobStore,\n ResumedKeyState,\n RetainedExecutionState,\n Scope,\n Settled,\n SpawnEvent,\n SpawnJournal,\n SpawnModelSubstitution,\n Spend,\n SubtreeSummary,\n TraceRootReceipt,\n TreeView,\n WorkerInteractiveSession,\n WorkerTraceEvidence,\n} from './types'\nimport type { WorkerEvents } from './worker-events'\nimport type { SlotPermit, WorkerSlots } from './worker-slots'\nimport type { WorkerTraceResolver } from './worker-trace'\n\n/** Scope construction: conserved pool, journal, executors, tree identity and recursion bounds. */\nexport interface ScopeArgs {\n /** This scope's owning node id — children get `${parentId}:s${seq}` ids. */\n readonly parentId: NodeId\n /** Journal/blob root key the supervisor `beginTree`'d. */\n readonly root: NodeId\n readonly rootDeadlineAtMs?: number\n /** The reservation pool for this scope: the root total or one nested allocated partition. */\n readonly pool: BudgetPool\n /** Append-only spawn journal; this scope writes `spawned` + `settled` records. */\n readonly journal: SpawnJournal\n /** Content-addressed result store backing `outRef` rehydration. */\n readonly blobs: ResultBlobStore\n /** The open executor resolver (BYO → router/inline → registered harness factory). */\n readonly executors: ExecutorRegistry\n /** Per-spawn executor-construction seams (sandbox client, router config, cli bin). */\n readonly seams: Readonly<Record<string, unknown>>\n /** This scope's recursion depth (root = 0). */\n readonly depth: number\n /** Runtime recursion-depth ceiling — a spawn past it fails closed `depth-exceeded`. */\n readonly maxDepth?: number\n /** The allocator that bounds concurrently working agents across this scope, every nested scope,\n * and every other tree that shares it. Absent means no bound: only the budget limits concurrency. */\n readonly workerSlots?: WorkerSlots\n /** @internal The slot this scope's own manager holds in its parent scope. A nested scope's first\n * running child works on it while the manager waits. Absent on a root scope. */\n readonly slotOwner?: SlotPermit\n /** Optional policy that keeps part of each manager's budget for its own inference. */\n readonly reservationPolicy?: RecursiveReservationPolicy\n /** The budget from which this scope's owner-share floor is derived. */\n readonly ownerBudget?: Budget\n /** What a steerable child's own time box does: a check-in by default (`deadline.ts`\n * `DeadlineCheckIn`); `false` stops the child at its time box. Nested scopes inherit it. */\n readonly deadlineCheckIn?: DeadlineCheckIn\n /** How long a keyed leaf whose turn ended over its budget keeps its environment for a same-key\n * re-spawn to continue (ms). Default `DEFAULT_BUDGET_STOP_HOLD_MS`; `0` keeps none.\n * Nested scopes inherit it. */\n readonly budgetStopHoldMs?: number\n /** Abort signal for this scope; an abort cascades into every live child's executor. */\n readonly signal: AbortSignal\n /** Injected clock — keeps the journal `at` timestamp deterministic in tests. */\n readonly now?: () => number\n /** Lifecycle stream sink. `spawn` emits `agent.spawn`, `next` emits `agent.child` — the\n * SAME stream `runAgentRounds`/`tool-loop` feed, so the recursive tree is ONE observable stream\n * (the topology viewer reads it). Undefined ⇒ the journal stays the only record. */\n readonly hooks?: RuntimeHooks\n /**\n * Trace context to hand down to each spawned worker (`SupervisorOpts.workerTrace`). Called with\n * THIS scope's own `parentId` — the node doing the spawning — and the resolved context is seeded\n * onto each child's `ExecutorContext` under `workerTraceSeamKey`. Absent (the untraced default)\n * ⇒ no seam is seeded and no worker environment is touched.\n */\n readonly workerTrace?: WorkerTraceResolver\n /**\n * Present when this run RECORDS spans but the worker backend has NO channel to carry the trace\n * context (`WORKER_TRACE_PROPAGATION[backend] === false` — cli-worktree has no env\n * channel; router / router-tools / provider have no worker process). Each spawn then journals a\n * `trace-unpropagated` event naming the severed hop, so a child whose trace shows up as a\n * disconnected root is a recorded fact rather than a silent stranger. Absent ⇒ either the run\n * is untraced or the backend propagates; nothing is journaled.\n */\n readonly workerTraceUnpropagated?: {\n readonly backend: string\n readonly reason: 'no-env-channel' | 'no-worker-process' | 'caller-omitted'\n }\n /** Durable run directory that receives exact worker interactive bindings. */\n readonly interactiveBindingDir?: string\n /** @internal Trusted root-adapter publication channel. It is never exposed as a Scope method. */\n readonly ownerMaterialization?: {\n readonly runtime: NodeSnapshot['runtime']\n readonly authoredProfile?: unknown\n readonly attemptId: string\n readonly prior?: ProfileMaterializationReceipt\n readonly journalRoot?: NodeId\n readonly nodeId?: NodeId\n readonly requiredKnown?: boolean\n readonly onReceipt?: (\n materialization: ProfileMaterializationReceipt,\n binding: ExecutionBindingReceipt,\n ) => void\n }\n /**\n * Resume seam — set ONLY by the supervisor when `SupervisorOpts.resume` is on AND a non-empty\n * journal tree exists for this root. It carries the replayed committed work (so `scope.resume`\n * exposes it to a resume-aware `act`) and the recorded ordinal/cursor maxima the new counters\n * continue past, so a freshly-spawned child never reuses a journaled `seq`. Absent ⇒ fresh run.\n */\n readonly resumeFrom?: {\n /** @internal Executor adoption plans validated by the supervisor's recovery preparation. */\n readonly recoveries?: readonly RetainedChildRecovery[]\n readonly events?: readonly SpawnEvent[]\n readonly settled: ReadonlyArray<Settled<unknown>>\n readonly view: TreeView\n /** Highest `spawned` ordinal already journaled; new spawns start at `+1`. */\n readonly maxSpawnOrdinal: number\n /** Highest cursor `seq` already journaled; new settlements start at `+1`. */\n readonly maxCursorSeq: number\n /** Keyed assignments from the prior journal — what a keyed re-spawn resolves against. */\n readonly keys: ReadonlyMap<string, ResumedKeyState<unknown>>\n /** Prior committed spend summed off the journal (settled child work + metered inference). */\n readonly priorSpend: { readonly childWork: Spend; readonly driverInference: Spend }\n }\n}\n\n/**\n * Internal live-set entry. `settled` resolves once the child's executor has fully drained,\n * its reservation reconciled, and its result blob persisted; `next()` awaits these to drive\n * the cursor. `resolved` mirrors that terminal value synchronously so a concurrent `next()`\n * can pick the next undelivered settlement without re-racing. `delivered` guards exactly-once\n * delivery; `seq` is stamped by `next()`, never here.\n */\nexport interface LiveChild {\n readonly events: WorkerEvents\n cancellationReason?: RunCancellationReason\n readonly id: NodeId\n status: NodeStatus\n failure?: RuntimeFailureCause\n runtime: NodeSnapshot['runtime']\n readonly ownedTreeRoot?: NodeId\n readonly budget: Budget\n readonly label: string\n readonly assignmentId?: string\n readonly identity?: NodeExecutionIdentity\n readonly modelSubstitution?: SpawnModelSubstitution\n /** The semantic spawn key, when this child was spawned with one — the settle path folds the\n * terminal state back into the scope's key registry under it. */\n readonly key?: string\n spent: Spend\n /** The overspend its reconciliation returned. Every terminal record of this node carries it. */\n budgetViolation?: BudgetViolation\n /** The overspend a RETAINED reconcile returned, held back from the open-slot surfaces (the\n * driver's settlement, the tree, the first `agent.child`) because the floor is not the\n * execution's final spend. The release sweep restores it onto `budgetViolation` before it\n * writes the terminal record, so that record agrees with what the pool committed. */\n retainedViolation?: BudgetViolation\n recoveryReady?: Promise<void>\n /** The environment a settled budget-stopped turn kept for a same-key continuation, until it is\n * released or handed to the successor node. */\n held?: { readonly continuation: HeldForContinuation; clearCeiling?: () => void }\n /** The environment admission of this child's current invocation: what a continuation reuses. */\n readEnvironmentAdmission?: () => RetainedRunEnvironmentAdmission | undefined\n acceptedResult?: ExecutorResult<unknown>\n recoveryPending?: boolean\n outRef?: string\n /** The trace root of each output this process stored for the node, by `outRef`. */\n readonly traceRoots: TraceRootWriter\n /** Durable structured tool evidence once this executor is terminal. */\n trace?: WorkerTraceEvidence\n /** Provider-served model evidence once this executor has attempted inference. */\n providerModel?: import('./types').ProviderModelExecutionEvidence\n /** Exact terminal timestamp committed to the journal. */\n settledAt?: number\n /** The cursor seq `next()` stamped on this child's settlement. A retained-pending child's\n * terminal record is written later by the release sweep under THIS seq, so replay yields it\n * at the position the driver saw it; the sweep never mints a new `cursorSeq` for it, and\n * neither does a resume that heals a crashed sweep — it reads this seq back from the\n * reconciled record's `settledSeq`. */\n settledSeq?: number\n /** Mirrors the journal's statement about a retained execution so `makeTreeView` reports it. */\n retainedExecution?: RetainedExecutionState\n retainedPendingCause?: RetainedPendingCause\n /** Resolves with the terminal settlement WITHOUT a `seq` — `next()` stamps the seq. */\n readonly settled: Promise<PreSeqSettled>\n /** Synchronous mirror of `settled`'s value once it has resolved (else `undefined`). */\n resolved?: PreSeqSettled\n /** True once the EXECUTOR's own work is finished (artifact read or throw caught) — from then\n * on `settled` resolves without further executor progress (only persistence/teardown), so a\n * non-blocking drain may await it without waiting on live work. */\n executorDone: boolean\n /** True only after executor teardown returned `{ destroyed: true }`. A failed/unknown cleanup\n * retains the shared capacity slot so replacement work cannot exceed the physical live count. */\n cleanupConfirmed: boolean\n /** True once `next()` has yielded this child's settlement. */\n delivered: boolean\n /** The executor's out-of-band inbox, captured at spawn — backs `scope.send`. */\n readonly deliver?: (msg: unknown) => boolean\n /** The executor's optional live progress read, captured at spawn — backs `scope.progress`. */\n readonly readProgress?: () => ExecutorProgress | undefined\n /** The executor's optional live tool trace, captured at spawn — backs `scope.traceSource`. */\n readonly readTraceSource?: () => TraceSource | undefined\n /** The executor's optional interactive process, captured at spawn — backs `scope.interactive`. */\n readonly readInteractive?: () => WorkerInteractiveSession\n /** Async readiness for an executor that creates its interactive process during `execute`. */\n readonly readInteractiveReady?: () => Promise<WorkerInteractiveSession>\n /** The executor's optional cancellation operation, captured at spawn — backs `scope.cancel`. */\n readonly requestCancel?: (request: ExecutorCancellationRequest) => Promise<ExecutorCancellation>\n /** The executor's optional retained release, captured at spawn — what the root's settlement\n * sweep calls for a settled child whose cleanup is still unconfirmed. */\n readonly releaseRetained?: (\n signal: AbortSignal,\n ) => Promise<ReadonlyArray<EnvironmentTeardownReceipt>>\n /** Re-ask the executor's teardown verb after a retained release; resolves only on\n * `destroyed: true`, so confirmation always comes from the same verb every other path uses. */\n readonly confirmTeardown?: () => Promise<void>\n /** Every teardown Runtime sends this child's executor, single-flight: while one request is\n * still running, another ask awaits it instead of sending a second (see\n * `singleFlightTeardown`). Unbounded itself; each caller bounds its wait. */\n readonly askTeardown?: (grace: number | 'brutalKill' | 'infinity') => Promise<TeardownAnswer>\n /** The executor's `heldEnvironments` read, captured at spawn: what a sweeper must delete when\n * this child's teardown stays unconfirmed. */\n readonly readHeldEnvironments?: () => ReadonlyArray<HeldEnvironment>\n /** The scope this child's recursive executor owns, once it has mounted one. */\n readonly readNestedScope?: () => Scope<unknown> | undefined\n /** Persist the executor's harness transcript as it stands now. A retained release may read a\n * session the failure path could not, and the record that closes the slot carries it. */\n readonly readTranscriptAtRelease?: () => Promise<HarnessTranscriptEvidence>\n /** The bounded account of the team this child led, read from its own scope at settlement. */\n subtree?: SubtreeSummary\n /** How many teardown requests this child's executor was sent. */\n teardownAttempts: number\n /** Why the last teardown attempt did not confirm destruction. */\n teardownDetail?: string\n /** The executor answered that asking again cannot change its answer. */\n teardownPermanent?: boolean\n /** The settlement retry's pass over this child still in flight, so a later pass awaits it. */\n teardownRetry?: Promise<void>\n /** Abort this child's own signal — the local half of `scope.cancel`. */\n readonly abortChild: (reason?: unknown) => void\n /** Kernel-owned declaration of the exact execution plan, durable before `execute` starts. */\n materialization?: ProfileMaterializationReceipt\n /** One immutable record per concrete execution attempt. */\n executionBindings: ExecutionBindingReceipt[]\n /** Wall-clock of the spawn, and of the last metered usage event this child produced. Both are\n * stamped by the scope from the stream the conserved pool already meters, so EVERY executor —\n * including one that implements no progress read at all — has an observable liveness signal. */\n readonly startedAt: number\n lastActivityAt: number\n}\n\n/** A child's terminal settlement before the cursor stamps the monotonic `seq`. */\nexport type PreSeqSettled =\n | {\n kind: 'done'\n out: unknown\n outRef: string\n traceRoot?: TraceRootReceipt\n verdict?: DefaultVerdict\n spent: Spend\n providerModel?: import('./types').ProviderModelExecutionEvidence\n trace: WorkerTraceEvidence\n /** Whether the child's own harness transcript survived its environment. Sibling of `trace`;\n * see the `Settled` doc for why it cannot live inside the trace receipt. */\n harnessTranscript?: HarnessTranscriptEvidence\n /** A driver child's OWN-inference subtree total (from `Executor.metered()`) — journaled as a\n * `metered` event for this node, NOT reconciled (already debited live via `observe`). */\n metered?: Spend\n }\n | {\n kind: 'down'\n reason: string\n /** See `Settled['infra']`: `true` platform, `false` the work, absent unattributable. */\n infra?: boolean\n outRef?: string\n traceRoot?: TraceRootReceipt\n trace: WorkerTraceEvidence\n /** The dropped child's own harness transcript, or the named reason it is absent. The whole\n * point of #1244: this path has no result artifact for a capture to ride in. */\n harnessTranscript?: HarnessTranscriptEvidence\n providerModel?: import('./types').ProviderModelExecutionEvidence\n /** A CRASHED driver child's partial OWN-inference subtree total — re-homed on the down path\n * too, so the journal matches the pool (which already debited it via `observe`). */\n metered?: Spend\n /** The child-work floor a RETAINED-PENDING child's reservation was reconciled at. Its cursor\n * slot stays open, so the settle path journals this as a `reconciled` record in place of\n * the `settled` record it cannot write — otherwise every journal reader charges the ceiling\n * the pool just refunded. */\n reconciled?: Spend\n /** Why the retained execution is pending, as a value (#1204). Present iff `reconciled` is. */\n retainedPendingCause?: RetainedPendingCause\n /** See `Settled['failure']`: the thrown error, classified before `errMessage` flattens it. */\n failure?: RuntimeFailureCause\n }\n\n/**\n * The recursion seam key. A `Scope` seeds a value of this on each child's\n * `ExecutorContext.seams` so a child whose executor is a DRIVER can mount a NESTED `Scope`\n * over the driver's reserved child allocation at `depth+1`. A leaf executor never reads it. Single-sourced\n * here so the scope and the driver-executor agree on the seam without a circular import.\n */\nexport const nestedScopeSeamKey = 'nested-scope'\n\n/**\n * The recursion seam value: mount a nested `Scope` for a driver child. `parentId` is the\n * driver child's own node id (so its children get `${nodeId}:s${ordinal}` ids and its\n * nested journal tree is namespaced under it); `root` is the journal tree key for the\n * nested tree (distinct from the parent's so cursor seqs never collide in the per-tree\n * guard). `depth` is `parent.depth + 1`. The nested scope spends from a child pool backed by\n * the driver's already-reserved allocation; it shares the parent's `journal`/`blobs` and\n * `executors` (a nested child resolves to leaf-or-driver through the same open registry).\n */\nexport interface NestedScopeSeam {\n /** Durable id of the driver child that owns the nested tree. */\n readonly nodeId: NodeId\n /** This scope's recursion depth — a nested scope runs at `depth + 1`. */\n readonly depth: number\n /** The runtime recursion-depth ceiling, paired with the conserved pool (R3). */\n readonly maxDepth?: number\n /** The journal tree key the parent scope writes to (used to namespace nested trees). */\n readonly journalRoot: NodeId\n /** Mount a nested scope rooted at `nestedRoot`, parented at this driver child's node id. */\n mount(nestedRoot: NodeId, signal: AbortSignal): Scope<unknown>\n restore?(\n nestedRoot: NodeId,\n signal: AbortSignal,\n events: SpawnEvent[],\n recoverExecutor: ExecutorFactory<unknown>,\n ): Promise<Scope<unknown>>\n}\n\nexport interface DeferredOwnerSlot {\n ownerMaterialization?: NonNullable<ScopeArgs['ownerMaterialization']>\n}\n","/**\n * Durable structured tool evidence for supervised workers.\n *\n * The executor-owned `TraceSource` is collected before teardown, snapshotted into the shared\n * content-addressed blob store, and only then referenced by a settlement. Analysis reconstructs\n * agent-eval's bounded `TraceAnalysisStore` from those exact bytes. Worker output is never accepted\n * as a substitute for tool evidence.\n *\n * @experimental\n */\n\nimport {\n isToolSpan,\n type Span,\n type ToolSpan,\n type TraceAnalysisStore,\n toolSpansToTraceAnalysisStore,\n} from '@tangle-network/agent-eval'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type { TraceSource } from './trace-source'\nimport type { ResultBlobStore, WorkerTraceEvidence } from './types'\n\n/** Schema version for content-addressed worker tool-trace artifacts. */\nexport const WORKER_TOOL_TRACE_SCHEMA_VERSION = 1 as const\n\n/** Bytes stored under `WorkerTraceEvidence.traceRef`. */\nexport interface WorkerToolTraceArtifact {\n readonly schemaVersion: typeof WORKER_TOOL_TRACE_SCHEMA_VERSION\n readonly spans: ReadonlyArray<ToolSpan>\n}\n\n/** Structural guard for the official bounded trace-analysis read contract. */\nexport function isTraceAnalysisStore(value: unknown): value is TraceAnalysisStore {\n if (value === null || typeof value !== 'object') return false\n const store = value as Partial<Record<keyof TraceAnalysisStore, unknown>>\n return (\n typeof store.getOverview === 'function' &&\n typeof store.queryTraces === 'function' &&\n typeof store.countTraces === 'function' &&\n typeof store.viewTrace === 'function' &&\n typeof store.viewSpans === 'function' &&\n typeof store.searchTrace === 'function' &&\n typeof store.searchSpan === 'function'\n )\n}\n\n/** Collect and persist one executor's structured tool trace without changing its task outcome. */\nexport async function captureWorkerTraceEvidence(\n readSource: (() => TraceSource | undefined) | undefined,\n blobs: ResultBlobStore,\n executed: boolean,\n): Promise<WorkerTraceEvidence> {\n if (!executed) return unavailable('execution-did-not-start')\n if (readSource === undefined) return unavailable('executor-did-not-expose-trace-source')\n\n let source: TraceSource | undefined\n try {\n source = readSource()\n } catch {\n return unavailable('trace-source-unavailable')\n }\n if (source === undefined) return unavailable('trace-source-unavailable')\n\n let collected: unknown\n try {\n collected = await source.collect()\n } catch {\n return unavailable('trace-collection-failed')\n }\n if (!Array.isArray(collected) || collected.some((span) => !isToolSpanValue(span))) {\n return unavailable('invalid-tool-spans')\n }\n if (collected.length === 0) return unavailable('no-tool-spans-captured')\n\n let artifact: WorkerToolTraceArtifact\n let traceRef: string\n try {\n const snapshot = structuredClone(collected) as ToolSpan[]\n // Use agent-eval's canonical adapter as the full integrity check before the durable receipt\n // claims these spans are analyzable. `isToolSpan` only narrows the discriminated union.\n toolSpansToTraceAnalysisStore(snapshot)\n artifact = {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: snapshot,\n }\n traceRef = contentAddress(artifact)\n } catch {\n return unavailable('invalid-tool-spans')\n }\n try {\n await blobs.put(traceRef, artifact)\n } catch {\n return unavailable('trace-persistence-failed')\n }\n return Object.freeze({ status: 'available', traceRef, spanCount: artifact.spans.length })\n}\n\n/** Rehydrate exact persisted spans through agent-eval's one bounded trace-analysis adapter. */\nexport async function workerTraceAnalysisStore(\n evidence: WorkerTraceEvidence,\n blobs: Pick<ResultBlobStore, 'get'>,\n): Promise<TraceAnalysisStore> {\n if (evidence.status === 'unavailable') {\n // The published adapter owns the missing-evidence error and its classification.\n return toolSpansToTraceAnalysisStore(undefined)\n }\n const raw = await blobs.get(evidence.traceRef)\n if (raw === undefined) {\n throw new ValidationError(\n `worker trace blob '${evidence.traceRef}' is missing; the settlement evidence is incomplete`,\n )\n }\n const artifact = parseWorkerToolTraceArtifact(raw, evidence.traceRef)\n if (artifact.spans.length !== evidence.spanCount) {\n throw new ValidationError(\n `worker trace blob '${evidence.traceRef}' has ${artifact.spans.length} spans but its settlement records ${evidence.spanCount}`,\n )\n }\n return toolSpansToTraceAnalysisStore(artifact.spans)\n}\n\n/** Validate a stored trace artifact before an analyst or replay trusts it. */\nexport function parseWorkerToolTraceArtifact(\n value: unknown,\n traceRef = '<unknown>',\n): WorkerToolTraceArtifact {\n if (\n value === null ||\n typeof value !== 'object' ||\n (value as { schemaVersion?: unknown }).schemaVersion !== WORKER_TOOL_TRACE_SCHEMA_VERSION ||\n !Array.isArray((value as { spans?: unknown }).spans)\n ) {\n throw new ValidationError(\n `worker trace blob '${traceRef}' is not a version-${WORKER_TOOL_TRACE_SCHEMA_VERSION} tool trace artifact`,\n )\n }\n const spans = (value as { spans: unknown[] }).spans\n if (spans.length === 0) {\n // Missing spans cannot prove a tool-free run; preserve agent-eval's explicit integrity error.\n return {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: spans as ToolSpan[],\n }\n }\n if (spans.some((span) => !isToolSpanValue(span))) {\n throw new ValidationError(`worker trace blob '${traceRef}' contains a non-tool span`)\n }\n return {\n schemaVersion: WORKER_TOOL_TRACE_SCHEMA_VERSION,\n spans: spans as ToolSpan[],\n }\n}\n\nfunction unavailable(reason: Extract<WorkerTraceEvidence, { status: 'unavailable' }>['reason']) {\n return Object.freeze({ status: 'unavailable' as const, reason })\n}\n\nfunction isToolSpanValue(value: unknown): value is ToolSpan {\n try {\n return isToolSpan(value as Span)\n } catch {\n return false\n }\n}\n","import { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport {\n type HarnessTranscriptEvidence,\n persistHarnessTranscript,\n readHarnessTranscript,\n} from '../harness-transcript'\nimport { type BudgetPool, BudgetReconcileFault, type ReservationTicket } from './budget'\nimport { teardownExecutor } from './deadline'\nimport { errMessage } from './error-message'\nimport { withBudgetResources } from './resources'\nimport type { LiveChild } from './scope-contract'\nimport { detachedSnapshot } from './snapshot'\nimport { captureWorkerTraceEvidence } from './trace-evidence'\nimport type {\n Executor,\n ExecutorResult,\n ResultBlobStore,\n SpawnOpts,\n Spend,\n WorkerTraceEvidence,\n} from './types'\n\n/**\n * One child execution's settle-once state: its output, trace and transcript evidence, its\n * teardown, and the single reconciliation of its reservation. Every settle exit of `runChild`\n * reads and writes this owner, so each piece of evidence is captured once whichever arm ends it.\n */\nexport class ChildExecutionAttempt<C> {\n /** The executor was invoked: a pre-execution refusal reconciles zero and refunds everything. */\n started = false\n /** The executor's terminal usage reached `live.spent`. */\n terminalTelemetryCaptured = false\n /** The reservation was reconciled; a later reconcile returns its first answer. */\n reconciled = false\n reconciliationError: unknown\n teardownFailure: unknown\n /** The content ref of the output this process stored, on every arm that has one. */\n retainedOutputRef: string | undefined\n private teardownStarted = false\n private traceEvidence: WorkerTraceEvidence | undefined\n // Like the trace: read once per settle exit, persisted under its own content ref, only the receipt\n // travels. Every arm carries it, failure arms included (#1244).\n private transcriptEvidence: HarnessTranscriptEvidence | undefined\n\n constructor(\n readonly live: LiveChild,\n readonly executor: Executor<C>,\n readonly childAbort: AbortController,\n readonly opts: SpawnOpts,\n private readonly pool: BudgetPool,\n private readonly ticket: ReservationTicket,\n private readonly blobs: ResultBlobStore,\n readonly now: () => number,\n private readonly deadlineAtMs: number | undefined,\n private readonly startedAt: number | undefined,\n ) {}\n\n async retainOutput(\n result: ExecutorResult<C>,\n measured: Spend = result.spent,\n ): Promise<ExecutorResult<C>> {\n const { live } = this\n // Capture valid usage before storage: a failed write must not refund paid-for execution.\n let usageError: unknown\n try {\n assertReportedSpend(result.spent, `scope.spawn ${live.id}`)\n live.spent = this.executor.accounting?.()?.reported ?? measured\n this.terminalTelemetryCaptured = true\n live.executorDone = true\n } catch (error) {\n usageError = error\n }\n // Output is evidence, not a success verdict. Preserve it even when terminal usage is invalid.\n const out = detachedSnapshot(result.out, 'scope child output')\n const outRef = contentAddress(out)\n await this.blobs.put(outRef, out)\n await live.traceRoots.write(outRef, { out, outputFormat: result.outputFormat })\n this.retainedOutputRef = outRef\n if (usageError !== undefined) throw usageError\n return { ...result, out, outRef }\n }\n\n async captureTrace(): Promise<WorkerTraceEvidence> {\n this.traceEvidence ??= await captureWorkerTraceEvidence(\n this.live.readTraceSource,\n this.blobs,\n this.started,\n )\n return this.traceEvidence\n }\n\n async persistTranscript(): Promise<HarnessTranscriptEvidence> {\n this.transcriptEvidence ??= await persistHarnessTranscript(\n readHarnessTranscript(this.executor),\n this.blobs,\n )\n return this.transcriptEvidence\n }\n\n async teardown(grace: number | 'brutalKill' | 'infinity'): Promise<void> {\n if (this.teardownStarted) return\n this.teardownStarted = true\n const { live, executor } = this\n try {\n // An environment kept for a continuation this settlement will not offer is released too.\n await executor.heldForContinuation?.()?.release()\n await teardownExecutor(executor, grace, this.deadlineAtMs, this.now, live.askTeardown)\n live.cleanupConfirmed = true\n } catch (error) {\n this.teardownFailure = error\n live.teardownDetail = errMessage(error)\n throw error\n }\n }\n\n reconcile(spend: Spend): unknown | undefined {\n if (this.reconciled) return this.reconciliationError\n this.reconciled = true\n const { live, opts } = this\n // A pre-execution refusal reconciles zero and refunds the reservation; every executing path\n // reports measured or unknown spend.\n try {\n try {\n spend = withBudgetResources(spend, opts.budget, !this.started)\n live.spent = withBudgetResources(\n live.spent,\n opts.budget,\n !this.started || this.executor.accounting?.() !== undefined,\n )\n } catch (error) {\n // Invalid resource receipts cannot leave a ticket open or authorize a refund.\n spend = withBudgetResources({ ...spend, resources: undefined }, opts.budget)\n live.spent = withBudgetResources({ ...live.spent, resources: undefined }, opts.budget)\n try {\n live.budgetViolation = this.pool.reconcile(this.ticket, spend)\n } catch (fault) {\n // Unknown enforced usage closes the ticket before reporting its violation.\n if (fault instanceof BudgetReconcileFault) live.budgetViolation = fault.budgetViolation\n }\n throw error\n }\n // An overspend is recorded, not thrown (the pool committed the true spend); a fault throws.\n live.budgetViolation = this.pool.reconcile(this.ticket, spend)\n this.recordDeadlineOverrun()\n return undefined\n } catch (error) {\n if (error instanceof BudgetReconcileFault) live.budgetViolation = error.budgetViolation\n this.reconciliationError = error\n return error\n }\n }\n\n /** Commit a terminal artifact's spend: its usage is captured and its reservation reconciled. */\n commitTerminalSpend(terminalSpend: Spend): void {\n const { live } = this\n const accounting = this.executor.accounting?.()\n live.spent = accounting?.reported ?? terminalSpend\n this.terminalTelemetryCaptured = true\n live.executorDone = true\n const reconcileError = this.reconcile(accounting?.reservation ?? terminalSpend)\n if (reconcileError !== undefined) throw reconcileError\n }\n\n /** Commit an accepted result's spend; returns the reconciliation error, if any. */\n commitAcceptedSpend(accepted: NonNullable<LiveChild['acceptedResult']>): unknown | undefined {\n const { live, executor } = this\n live.spent = executor.accounting?.()?.reported ?? accepted.spent\n live.executorDone = true\n live.recoveryPending = false\n this.terminalTelemetryCaptured = true\n return this.reconcile(executor.accounting?.()?.reservation ?? accepted.spent)\n }\n\n // A child that settled past its time box names it the same way, as time given and taken.\n private recordDeadlineOverrun(): void {\n const { live, deadlineAtMs } = this\n const startedAt = this.startedAt\n const settledAt = this.now()\n if (deadlineAtMs !== undefined && startedAt !== undefined && settledAt > deadlineAtMs) {\n live.budgetViolation = {\n overspent: [\n ...(live.budgetViolation?.overspent ?? []),\n {\n channel: 'deadline',\n reserved: deadlineAtMs - startedAt,\n spent: settledAt - startedAt,\n },\n ],\n }\n }\n }\n}\n\nfunction assertReportedSpend(spent: unknown, context: string): asserts spent is Spend {\n const candidate = spent as Partial<Spend> | null | undefined\n if (\n typeof candidate !== 'object' ||\n candidate === null ||\n typeof candidate.iterations !== 'number' ||\n typeof candidate.tokens !== 'object' ||\n candidate.tokens === null\n ) {\n throw new ValidationError(\n `${context}: executor settled without a Spend — report what was spent or mark it unknown; a budget-exempt executor reports zero`,\n )\n }\n}\n","import { ValidationError } from '../../errors'\nimport { reportedFailureCause, runtimeFailureCause } from '../failure-cause'\nimport { type HarnessTranscriptEvidence, settleHarnessTranscript } from '../harness-transcript'\nimport { cloneTokenUsage, isAsyncIterable } from '../util'\nimport { runAbortable, signalAbortError } from './abortable'\nimport type { BudgetPool, ReservationTicket } from './budget'\nimport { DEFAULT_SUCCESSFUL_SHUTDOWN_MS } from './deadline'\nimport { errMessage } from './error-message'\nimport { executorFailure, executorFailureInfra } from './executor-outcome'\nimport { runtimeOwnedExecutorProviderEvidence } from './materialization'\nimport { addResourceSpend, resourceTelemetry } from './resources'\nimport { RetainedExecutionPendingError } from './retained-executor'\nimport { ChildExecutionAttempt } from './scope-child-attempt'\nimport type { LiveChild, PreSeqSettled } from './scope-contract'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n Executor,\n ExecutorProgressEvent,\n ExecutorResult,\n NodeId,\n ProviderModelExecutionEvidence,\n ResultBlobStore,\n SpawnJournal,\n SpawnOpts,\n Spend,\n UsageEvent,\n WorkerTraceEvidence,\n} from './types'\nimport { meterUsageEvent, newUsageTotals, spendFromUsageTotals } from './usage-metering'\n\nexport async function runChild<C>(\n live: LiveChild,\n executor: Executor<C>,\n childAbort: AbortController,\n task: unknown,\n opts: SpawnOpts,\n pool: BudgetPool,\n ticket: ReservationTicket,\n blobs: ResultBlobStore,\n now: () => number,\n journal: SpawnJournal,\n journalRoot: NodeId,\n nextProgressSeq: () => number,\n executionReady: Promise<void>,\n executionEvidence: ExecutionEvidence,\n deadlineAtMs: number | undefined,\n recovering = false,\n closeRetainedWrites: () => Promise<void> = async () => {},\n budgetReady: Promise<void> | undefined = undefined,\n slotReady: Promise<void> = Promise.resolve(),\n priorSpent?: Spend,\n startedAt?: number,\n): Promise<PreSeqSettled> {\n if (priorSpent !== undefined) live.spent = detachedSnapshot(priorSpent, 'prior committed usage')\n const attempt = new ChildExecutionAttempt(\n live,\n executor,\n childAbort,\n opts,\n pool,\n ticket,\n blobs,\n now,\n deadlineAtMs,\n startedAt,\n )\n try {\n // Materialization evidence must be durable before execution begins; a failure here types the\n // child down and refunds its reservation with zero executor calls.\n await executionReady\n if (childAbort.signal.aborted) throw signalAbortError(childAbort.signal, 'execution aborted')\n // A queued child runs nothing until the pool grants its budget slice and then a worker slot.\n if (budgetReady !== undefined) await awaitAbortable(budgetReady, childAbort.signal)\n await awaitAbortable(slotReady, childAbort.signal)\n // A budgetExempt WORKER (the raw `cli` printer) reports zero spend by contract and its\n // reconcile refunds the whole reservation; only the DRIVER path refuses such runtimes.\n live.status = 'running'\n attempt.started = true\n const ran = recovering\n ? executor.recover!(task, childAbort.signal)\n : executor.execute(task, childAbort.signal)\n let artifact: ExecutorResult<C>\n let terminalSpend: Spend\n if (isAsyncIterable<UsageEvent>(ran)) {\n const spend = await foldExecutorStream(\n attempt,\n ran,\n journal,\n journalRoot,\n nextProgressSeq,\n priorSpent,\n )\n live.spent = spend\n const reported = executor.resultArtifact() as ExecutorResult<C>\n artifact = await attempt.retainOutput(\n reported,\n preserveUnknownTelemetry(spend, reported.spent),\n )\n terminalSpend = preserveUnknownTelemetry(spend, artifact.spent)\n } else {\n artifact = await attempt.retainOutput(\n await awaitUnlessAccepted(Promise.resolve(ran), childAbort.signal, executor),\n )\n terminalSpend = artifact.spent\n }\n await executionEvidence.complete()\n attempt.commitTerminalSpend(terminalSpend)\n return await settleExecuted(attempt, artifact)\n } catch (cause) {\n return await settleThrown(attempt, cause, executionEvidence, closeRetainedWrites)\n } finally {\n await closeRetainedWrites()\n }\n}\n\n/** Kernel-owned materialization evidence for one execution, closed by its outcome. */\ninterface ExecutionEvidence {\n complete: () => Promise<void>\n fail: () => Promise<void>\n}\n\n/**\n * Fold a streaming executor's running total onto the live child, so `scope.progress(id)` sees it.\n * The fold never aborts at the reservation: usage arrives after the call it measures, often last,\n * so aborting would discard completed work and save no spend; reconciliation records overspend.\n * `progress` rows, replaced by the settlement, publish on a leading-edge second (#2337, #2339);\n * awaiting-result rows always publish.\n */\nasync function foldExecutorStream<C>(\n { live, childAbort, now }: ChildExecutionAttempt<C>,\n stream: AsyncIterable<UsageEvent>,\n journal: SpawnJournal,\n journalRoot: NodeId,\n nextProgressSeq: () => number,\n priorSpent: Spend | undefined,\n): Promise<Spend> {\n live.events.start()\n let publishedAt = Number.NEGATIVE_INFINITY\n try {\n return await foldStream(\n stream,\n async (running, event) => {\n live.spent = running\n live.lastActivityAt = now()\n const mark = event.kind === 'progress' ? event.progress : undefined\n if (mark?.kind !== 'awaiting-result' && live.lastActivityAt - publishedAt < 1_000) return\n publishedAt = live.lastActivityAt\n await journal.appendEvent(journalRoot, {\n kind: 'progress',\n id: live.id,\n spend: running,\n ...(mark?.kind === 'awaiting-result' ? { awaitingResult: { since: mark.since } } : {}),\n seq: nextProgressSeq(),\n at: new Date(publishedAt).toISOString(),\n })\n },\n childAbort.signal,\n priorSpent,\n (event) => live.events.append(event, now()),\n )\n } finally {\n await live.events.settle()\n }\n}\n\n/** Settle an execution that returned its terminal artifact and reconciled its reservation. */\nasync function settleExecuted<C>(\n attempt: ChildExecutionAttempt<C>,\n artifact: ExecutorResult<C>,\n): Promise<PreSeqSettled> {\n const { live, executor, childAbort, opts } = attempt\n // Executor work is complete; the non-blocking drain keys on this.\n live.executorDone = true\n\n // A driver child's OWN-inference subtree total — re-homed by the parent on EVERY settle exit\n // (done, aborted, crash) so the journal always matches what the pool already debited.\n const ownMetered = executor.metered?.()\n const trace = await attempt.captureTrace()\n await settleHarnessTranscript(executor)\n const childHarnessTranscript = await attempt.persistTranscript()\n\n if (\n childAbort.signal.aborted &&\n live.acceptedResult === undefined &&\n executor.resultAccepted?.() !== true\n ) {\n await attempt.teardown(opts.shutdown ?? 'brutalKill')\n return downRecord(\n 'aborted before settle',\n true,\n trace,\n ownMetered,\n runtimeOwnedExecutorProviderEvidence(executor),\n attempt.retainedOutputRef,\n childHarnessTranscript,\n )\n }\n\n const failure = executorFailure(artifact)\n if (failure !== undefined) {\n await attempt.teardown(opts.shutdown ?? DEFAULT_SUCCESSFUL_SHUTDOWN_MS).catch(() => undefined)\n return failureRecord(\n failure,\n trace,\n ownMetered,\n runtimeOwnedExecutorProviderEvidence(executor),\n childHarnessTranscript,\n // retainOutput derived and persisted the canonical reference before settlement work.\n artifact.outRef,\n )\n }\n // A turn that ended over its budget keeps its environment for a same-key continuation; the\n // scope releases it at its hold ceiling, on cancel_worker, or at the join barrier.\n const held = executor.heldForContinuation?.()\n if (held !== undefined && live.budgetViolation !== undefined) live.held = { continuation: held }\n else await attempt.teardown(opts.shutdown ?? DEFAULT_SUCCESSFUL_SHUTDOWN_MS)\n return doneRecord(\n artifact,\n live.spent,\n trace,\n childHarnessTranscript,\n runtimeOwnedExecutorProviderEvidence(executor),\n ownMetered,\n )\n}\n\n/** Settle a throw from execution or its persistence: accepted, retained-pending, or down. */\nasync function settleThrown<C>(\n attempt: ChildExecutionAttempt<C>,\n cause: unknown,\n executionEvidence: ExecutionEvidence,\n closeRetainedWrites: () => Promise<void>,\n): Promise<PreSeqSettled> {\n const { live, executor, childAbort } = attempt\n let err = cause\n // An abort reaches here while a streaming executor still ends its turn: it stops the harness\n // and copies the session after the abort. Everything below reads that transcript or tears the\n // executor down, so wait (bounded) for the copy first.\n await settleHarnessTranscript(executor)\n await closeRetainedWrites()\n if (\n live.acceptedResult !== undefined &&\n attempt.reconciliationError === undefined &&\n (isAbortError(err) ||\n (attempt.teardownFailure !== undefined && err === attempt.teardownFailure) ||\n (childAbort.signal.aborted && err === childAbort.signal.reason))\n ) {\n // Provider release and cancellation cannot revoke an already committed terminal result.\n const accepted = live.acceptedResult\n const acceptedAccountingError = attempt.commitAcceptedSpend(accepted)\n if (acceptedAccountingError === undefined) return await settleAccepted(attempt, accepted)\n err = acceptedAccountingError\n }\n if (err instanceof RetainedExecutionPendingError || live.recoveryPending) {\n return await settleRetainedPending(attempt, err)\n }\n return await settleCrashed(attempt, err, executionEvidence)\n}\n\n/** Settle a result the child submitted and the kernel accepted before the abort arrived. */\nasync function settleAccepted<C>(\n attempt: ChildExecutionAttempt<C>,\n accepted: NonNullable<LiveChild['acceptedResult']>,\n): Promise<PreSeqSettled> {\n const { executor, opts } = attempt\n const trace = await attempt.captureTrace()\n await attempt.teardown(opts.shutdown ?? DEFAULT_SUCCESSFUL_SHUTDOWN_MS).catch(() => undefined)\n const metered = executor.metered?.()\n const failure = executorFailure(accepted)\n if (failure !== undefined) {\n const providerModel = runtimeOwnedExecutorProviderEvidence(executor)\n return failureRecord(\n failure,\n trace,\n metered,\n providerModel,\n await attempt.persistTranscript(),\n accepted.outRef,\n )\n }\n const spent = attempt.live.spent\n const harnessTranscript = await attempt.persistTranscript()\n return doneRecord(\n accepted,\n spent,\n trace,\n harnessTranscript,\n runtimeOwnedExecutorProviderEvidence(executor),\n metered,\n )\n}\n\n/** Settle an execution that may still run remotely: its node keeps its cursor slot open. */\nasync function settleRetainedPending<C>(\n attempt: ChildExecutionAttempt<C>,\n err: unknown,\n): Promise<PreSeqSettled> {\n const { live, executor, opts, now } = attempt\n live.recoveryPending = true\n live.executorDone = true\n const trace = await attempt.captureTrace()\n // Teardown so a receipt exists at all. A nested manager's executor answers `destroyed: true`\n // once its descendants are confirmed though its owner environment is still held, so\n // `cleanupConfirmed` here does not mean the execution is gone (#1189).\n await attempt.teardown(opts.shutdown ?? 'brutalKill').catch(() => undefined)\n // Charge what was observed, not the reservation ceiling: a recursive executor's explicit\n // accounting, else the running total the pool metered off the stream. `reconcile` refunds\n // `reserved - spent`, so passing the ceiling refunded nothing: 16 dead children\n // were charged 64M having metered 890k (#1190). The floor is `live.spent` for a leaf (no\n // production leaf implements `metered`), with every channel marked unknown because the remote\n // execution may still be consuming; it is journaled as this node's `reconciled` floor. A\n // ticket already reconciled at a measured terminal spend keeps that measurement.\n if (!attempt.reconciled) {\n const accounting = executor.accounting?.()\n const ms = Math.max(0, now() - live.startedAt)\n live.spent = { ...unknownFloor(accounting?.reported ?? live.spent), ms }\n attempt.reconcile({ ...unknownFloor(accounting?.reservation ?? live.spent), ms })\n }\n // The slot stays open, so no terminal record carries an overspend yet and the floor is not the\n // final spend; reporting it here would make live views disagree with replay. The pool did\n // commit it, so the answer is held for the release sweep's terminal record.\n live.retainedViolation = live.budgetViolation\n live.budgetViolation = undefined\n return {\n ...downRecord(\n errMessage(err),\n true,\n trace,\n executor.metered?.(),\n undefined,\n attempt.retainedOutputRef,\n // #1244: 45 of these in one evening executed and left no artifact; this is the only record\n // their transcript can reach.\n await attempt.persistTranscript(),\n ),\n reconciled: live.spent,\n // Classified from the typed cause before `errMessage` flattens it (#1204). `recoveryPending`\n // without a RetainedExecutionPendingError is an admission that never got a result:\n // unobservable by definition.\n retainedPendingCause:\n err instanceof RetainedExecutionPendingError ? err.pendingCause : 'unobservable',\n // The provider's own machine code survives the wrapper, as on the crashed path.\n failure: runtimeFailureCause(err),\n }\n}\n\n/** Settle a thrown executor (or failed persistence) as a typed down record. */\nasync function settleCrashed<C>(\n attempt: ChildExecutionAttempt<C>,\n err: unknown,\n executionEvidence: ExecutionEvidence,\n): Promise<PreSeqSettled> {\n const { live, executor, childAbort } = attempt\n // A thrown executor has also finished its own work — only the down-record persistence\n // remains, so the non-blocking drain may await this child too.\n live.executorDone = true\n let evidenceError: unknown\n try {\n await executionEvidence.fail()\n } catch (error) {\n evidenceError = error\n }\n // A recursive executor can still report the nested work committed before it threw. A\n // box-backed trace must be collected before teardown destroys the session that owns it.\n const trace = await attempt.captureTrace()\n let teardownError: unknown\n try {\n await attempt.teardown('brutalKill')\n } catch (error) {\n teardownError = error\n }\n const accounting = executor.accounting?.()\n if (accounting) live.spent = accounting.reported\n const providerModel = runtimeOwnedExecutorProviderEvidence(executor)\n const aborted = childAbort.signal.aborted || isAbortError(err)\n if (attempt.started && !attempt.terminalTelemetryCaptured && accounting === undefined) {\n // No terminal usage receipt arrived (a crash or an abort): keep observed partial counts as a\n // lower bound, never read the unreported remainder as zero. A recursive executor's explicit\n // accounting stays authoritative, as after a persistence failure behind a terminal artifact.\n live.spent = unknownFloor(live.spent)\n }\n const reconcileError = attempt.reconcile(accounting?.reservation ?? live.spent)\n const failure = runtimeFailureCause(err, { signal: childAbort.signal })\n // A crashed driver child still re-homes the partial inference it durably metered.\n const down = downRecord(\n // The failed operation is the causal error; a cleanup or accounting failure never replaces it\n // but still marks the settlement as infrastructure-related.\n errMessage(err),\n evidenceError !== undefined ||\n teardownError !== undefined ||\n reconcileError !== undefined ||\n aborted ||\n isInfraError(err),\n trace,\n executor.metered?.(),\n providerModel,\n attempt.retainedOutputRef,\n await attempt.persistTranscript(),\n )\n return { ...down, failure }\n}\n\n/** The done record of a terminal result. */\nfunction doneRecord(\n result: Pick<ExecutorResult<unknown>, 'out' | 'outRef' | 'verdict'>,\n spent: Spend,\n trace: WorkerTraceEvidence,\n harnessTranscript: HarnessTranscriptEvidence,\n providerModel: ProviderModelExecutionEvidence | undefined,\n metered: Spend | undefined,\n): PreSeqSettled {\n return {\n kind: 'done',\n out: result.out,\n outRef: result.outRef,\n ...(result.verdict ? { verdict: result.verdict } : {}),\n spent,\n trace,\n harnessTranscript,\n providerModel,\n ...(metered ? { metered } : {}),\n }\n}\n\n/** The down record of a result whose envelope reported failure; it still cites its output. */\nfunction failureRecord(\n failure: NonNullable<ReturnType<typeof executorFailure>>,\n trace: WorkerTraceEvidence,\n metered: Spend | undefined,\n providerModel: ProviderModelExecutionEvidence | undefined,\n harnessTranscript: HarnessTranscriptEvidence,\n outRef: string | undefined,\n): PreSeqSettled {\n return {\n ...downRecord(\n failure.error,\n // The envelope's own vocabulary decides; an unattributable failure carries no claim.\n executorFailureInfra(failure),\n trace,\n metered,\n providerModel,\n undefined,\n harnessTranscript,\n ),\n outRef,\n failure: reportedFailureCause(failure),\n }\n}\n\n/**\n * Fold a streaming executor's usage into the conserved `Spend`, publishing the running total\n * after EVERY event: a RUNNING worker is observable (it used to report zero until the stream\n * drained) and one that throws mid-stream reconciles its real partial spend.\n */\nasync function foldStream(\n stream: AsyncIterable<UsageEvent>,\n onProgress?: (running: Spend, event: UsageEvent) => void | Promise<void>,\n signal?: AbortSignal,\n priorSpent?: Spend,\n onEvent?: (event: ExecutorProgressEvent) => void,\n): Promise<Spend> {\n const totals = newUsageTotals(priorSpent)\n const iterator = stream[Symbol.asyncIterator]()\n try {\n for (;;) {\n const next = signal\n ? await awaitAbortable(Promise.resolve(iterator.next()), signal)\n : await iterator.next()\n if (next.done) break\n const ev = next.value\n if (ev.kind === 'progress') onEvent?.(ev.progress)\n meterUsageEvent(totals, ev)\n await onProgress?.(\n {\n ...addResourceSpend(totals.resources),\n iterations: totals.iterations,\n tokens: cloneTokenUsage(totals.tokens),\n ...(totals.tokensKnown ? {} : { tokensKnown: false }),\n usd: totals.usd,\n ...(totals.usdEstimated > 0 ? { usdEstimated: totals.usdEstimated } : {}),\n ...(totals.usdKnown ? {} : { usdKnown: false }),\n // A live read says which receipt the running total came from, so `observe_agent` on a\n // codex seat reports store-read tokens as store-read rather than as a stream receipt.\n ...(totals.tokensProvenance === undefined || totals.tokensProvenance === 'stream-receipt'\n ? {}\n : { tokensProvenance: totals.tokensProvenance }),\n ms: 0,\n },\n ev,\n )\n }\n } catch (error) {\n // Ask a cooperative async generator to close, but never let a broken `return()` hide the\n // deadline that already won. Its promise is observed so a late rejection is not unhandled.\n void Promise.resolve(iterator.return?.()).catch(() => undefined)\n throw error\n }\n return spendFromUsageTotals(totals)\n}\n\n/** Usage events carry measured increments; the terminal artifact carries whether a provider omitted\n * a whole accounting channel. Preserve those unknowns on the common streaming path. */\nfunction preserveUnknownTelemetry(streamed: Spend, terminal: Spend): Spend {\n const terminalTokens = cloneTokenUsage(terminal.tokens)\n return {\n ...streamed,\n ...resourceTelemetry(streamed, terminal),\n tokens: {\n ...streamed.tokens,\n ...(streamed.tokens.freshInput === undefined && terminalTokens.freshInput !== undefined\n ? { freshInput: terminalTokens.freshInput }\n : {}),\n ...(streamed.tokens.cacheRead === undefined && terminalTokens.cacheRead !== undefined\n ? { cacheRead: terminalTokens.cacheRead }\n : {}),\n ...(streamed.tokens.cacheWrite === undefined && terminalTokens.cacheWrite !== undefined\n ? { cacheWrite: terminalTokens.cacheWrite }\n : {}),\n ...(streamed.tokens.cacheBreakdownKnown === false ||\n terminalTokens.cacheBreakdownKnown === false\n ? { cacheBreakdownKnown: false as const }\n : {}),\n },\n ...(terminal.tokensKnown === false ? { tokensKnown: false } : {}),\n ...(terminal.usdKnown === false ? { usdKnown: false } : {}),\n ms: terminal.ms,\n // Box-time is terminal-artifact-only BY DESIGN (minutes are unknown until the box dies), so\n // this is the one place it can reach `live.spent` and the journal; without it the channel was\n // dropped at settlement (value audit, PR #1053).\n ...(terminal.boxMinutes !== undefined ? { boxMinutes: terminal.boxMinutes } : {}),\n ...(terminal.boxMinutesKnown !== undefined\n ? { boxMinutesKnown: terminal.boxMinutesKnown }\n : {}),\n ...(terminal.boxMinutesProvenance !== undefined\n ? { boxMinutesProvenance: terminal.boxMinutesProvenance }\n : {}),\n // The terminal artifact supplies provenance for an executor whose stream did not.\n ...((streamed.tokensProvenance ?? terminal.tokensProvenance) === undefined\n ? {}\n : { tokensProvenance: streamed.tokensProvenance ?? terminal.tokensProvenance }),\n }\n}\n\n/**\n * Await a one-shot executor's terminal result unless an abort wins first, except for an execution\n * whose result was accepted before the abort arrived: it is ending the turn that submitted that\n * result, so it is awaited rather than discarded, and the executor bounds that wait itself.\n */\nasync function awaitUnlessAccepted<T>(\n work: Promise<T>,\n signal: AbortSignal,\n executor: Pick<Executor<unknown>, 'resultAccepted'>,\n): Promise<T> {\n try {\n return await awaitAbortable(work, signal)\n } catch (error) {\n if (signal.aborted && executor.resultAccepted?.() === true) return await work\n throw error\n }\n}\n\nasync function awaitAbortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n // `execute()` may have returned a promise that rejects from the same abort. Observe it before\n // the already-winning cancellation so a fast abort cannot become an unhandled provider rejection.\n if (signal.aborted) void work.catch(() => undefined)\n // runAbortable defers the abort one microtask: a cooperative executor often resolves its\n // terminal usage receipt from an abort listener, and that already-triggered result still wins.\n return await runAbortable(() => work, signal, 'execution aborted')\n}\n\n/** Observed partial counts as a lower bound on every channel: the work happened, its remainder went\n * unreported, and no reader may take the counts for a measurement. */\nfunction unknownFloor(spend: Spend): Spend {\n return {\n ...spend,\n tokensKnown: false,\n usdKnown: false,\n ...(spend.resources === undefined\n ? {}\n : {\n resources: Object.fromEntries(\n Object.entries(spend.resources).map(([name, value]) => [\n name,\n { ...value, known: false },\n ]),\n ),\n }),\n }\n}\n\nexport function downRecord(\n reason: string,\n infra: boolean | undefined,\n trace: WorkerTraceEvidence,\n metered?: Spend,\n providerModel?: ProviderModelExecutionEvidence,\n outRef?: string,\n harnessTranscript?: HarnessTranscriptEvidence,\n): Extract<PreSeqSettled, { kind: 'down' }> {\n return {\n kind: 'down',\n reason,\n // Absent when unattributable; the record must not carry a boolean it cannot stand behind.\n ...(infra === undefined ? {} : { infra }),\n trace,\n ...(harnessTranscript ? { harnessTranscript } : {}),\n ...(providerModel ? { providerModel } : {}),\n ...(metered ? { metered } : {}),\n ...(outRef === undefined ? {} : { outRef }),\n }\n}\n\nfunction isAbortError(err: unknown): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'name' in err &&\n (err as { name: unknown }).name === 'AbortError'\n )\n}\n\n/** External-boundary failures (network/FS/subprocess) are infra — excluded from the merge\n * `n` and the equal-k assertion. A `ValidationError` from a built-in executor wraps a\n * config/transport failure, so it counts as infra; other throws are a real bad result. */\nfunction isInfraError(err: unknown): boolean {\n return err instanceof ValidationError\n}\n","import { settlementFailureCause } from '../../runtime/failure-cause'\nimport { workerTraceAnalysisStore } from '../../runtime/supervise/trace-evidence'\nimport type {\n NodeExecutionIdentity,\n NodeId,\n NodeSnapshot,\n NodeStatus,\n ResultBlobStore,\n Settled,\n SpawnJournal,\n} from '../../runtime/supervise/types'\nimport { cloneSpend } from '../../runtime/util'\nimport { outsideCursorNamespace } from './event-index'\nimport {\n budgetViolationOf,\n copyProviderModelEvidence,\n traceEvidenceFor,\n} from './settlement-evidence'\n\n/**\n * Re-feed a journaled spawn tree in strict `seq` order, rehydrating each settled\n * child's `out` from the blob store by `outRef`, and return the `Settled[]` exactly\n * as `scope.next()` originally delivered them.\n *\n * Determinism (B2): the events are sorted by `seq` BEFORE any blob `get`, so the\n * replay order is the recorded cursor order regardless of how fast each rehydration\n * resolves. `at` (wall-clock) is never a replay input. Fail loud on a tree that was\n * never begun, a settled-done event missing its `outRef`, or a blob the store can't\n * rehydrate — a silent gap would let `act` branch on the wrong evidence.\n *\n * @stable\n */\nexport async function replaySpawnTree(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n): Promise<Settled<unknown>[]> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`replaySpawnTree: no journaled tree for root '${root}'`)\n }\n const ordered = [...events].sort((a, b) => a.seq - b.seq)\n const labels = new Map<NodeId, string>()\n const assignmentIds = new Map<NodeId, string>()\n const identities = new Map<NodeId, NodeExecutionIdentity>()\n const materializations = new Map<NodeId, NodeSnapshot['materialization']>()\n const executionBindings = new Map<\n NodeId,\n NonNullable<NodeSnapshot['executionBindings']>[number][]\n >()\n for (const ev of ordered) {\n if (ev.kind === 'spawned') labels.set(ev.id, ev.label)\n if (ev.kind === 'spawned' && ev.assignmentId !== undefined) {\n assignmentIds.set(ev.id, ev.assignmentId)\n }\n if (ev.kind === 'spawned' && ev.identity !== undefined) {\n identities.set(ev.id, copyFrozenIdentity(ev.identity))\n }\n if (ev.kind === 'materialized') materializations.set(ev.id, ev.receipt)\n if (ev.kind === 'execution-bound') {\n const bindings = executionBindings.get(ev.id) ?? []\n bindings.push(ev.binding)\n executionBindings.set(ev.id, bindings)\n }\n }\n const handleFor = (id: NodeId, status: NodeStatus) =>\n replayHandle(id, labels.get(id) ?? id, status, {\n assignmentId: assignmentIds.get(id),\n identity: identities.get(id),\n materialization: materializations.get(id),\n executionBindings: executionBindings.get(id),\n })\n const settlementTime = (at: string): { readonly settledAt?: number } => {\n const settledAt = Date.parse(at)\n return Number.isFinite(settledAt) ? { settledAt } : {}\n }\n const settled: Settled<unknown>[] = []\n for (const ev of ordered) {\n // Node creation and informational records, read above for handles, are not settlements.\n if (outsideCursorNamespace(ev)) continue\n const trace =\n ev.kind === 'cancelled'\n ? (ev.trace ?? {\n status: 'unavailable' as const,\n reason: 'execution-did-not-start' as const,\n })\n : traceEvidenceFor(ev)\n if (ev.kind === 'settled' && trace.status === 'available')\n await workerTraceAnalysisStore(trace, blobs)\n const evidence = {\n ...(ev.outRef === undefined ? {} : { outRef: ev.outRef }),\n ...(ev.providerModel === undefined\n ? {}\n : { providerModel: copyProviderModelEvidence(ev.providerModel) }),\n ...budgetViolationOf(ev),\n trace,\n ...(ev.harnessTranscript === undefined ? {} : { harnessTranscript: ev.harnessTranscript }),\n ...(ev.subtree === undefined ? {} : { subtree: ev.subtree }),\n ...settlementTime(ev.at),\n seq: ev.seq,\n }\n if (ev.kind === 'cancelled' || ev.status === 'down') {\n // Legacy reasonless journals remain readable without inferring a native diagnosis.\n const reason =\n ev.reason ?? (ev.kind === 'settled' ? ev.verdict?.notes : undefined) ?? 'child down'\n settled.push({\n ...evidence,\n kind: 'down',\n handle: handleFor(ev.id, ev.kind === 'cancelled' ? 'cancelled' : 'failed'),\n reason,\n failure:\n ev.failure ??\n settlementFailureCause({\n reason,\n infra: ev.infra,\n retainedPendingCause: ev.retainedPendingCause,\n }),\n ...(ev.infra === undefined ? {} : { infra: ev.infra }),\n // A released record states how the earlier retained-pending slot finally closed.\n ...(ev.retainedExecution === undefined ? {} : { retainedExecution: ev.retainedExecution }),\n ...(ev.retainedPendingCause === undefined\n ? {}\n : { retainedPendingCause: ev.retainedPendingCause }),\n })\n continue\n }\n if (ev.outRef === undefined) {\n throw new Error(\n `replaySpawnTree: settled-done event for '${ev.id}' (seq ${ev.seq}) has no outRef; ` +\n 'cannot rehydrate the result the driver branched on',\n )\n }\n const out = await blobs.get(ev.outRef)\n if (out === undefined) {\n throw new Error(\n `replaySpawnTree: blob store has no artifact for outRef '${ev.outRef}' (node '${ev.id}', seq ${ev.seq})`,\n )\n }\n settled.push({\n ...evidence,\n kind: 'done',\n handle: handleFor(ev.id, 'done'),\n out,\n outRef: ev.outRef,\n verdict: ev.verdict,\n spent: cloneSpend(ev.spent),\n })\n }\n return settled\n}\n\nfunction replayHandle(\n id: NodeId,\n label: string,\n status: NodeStatus,\n evidence: {\n readonly assignmentId?: string\n readonly identity?: NodeExecutionIdentity\n readonly materialization?: NodeSnapshot['materialization']\n readonly executionBindings?: ReadonlyArray<\n NonNullable<NodeSnapshot['executionBindings']>[number]\n >\n } = {},\n) {\n return Object.freeze({\n id,\n label,\n status,\n ...(evidence.assignmentId === undefined ? {} : { assignmentId: evidence.assignmentId }),\n ...(evidence.identity === undefined ? {} : { identity: evidence.identity }),\n ...(evidence.materialization === undefined\n ? {}\n : { materialization: evidence.materialization }),\n ...(evidence.executionBindings === undefined\n ? {}\n : { executionBindings: Object.freeze([...evidence.executionBindings]) }),\n abort() {\n throw new Error(`cannot abort node '${id}': replayed handles are terminal, not live`)\n },\n })\n}\n\n/** A replayed handle must not retain mutable references into the loaded journal event. */\nfunction copyFrozenIdentity(identity: NodeExecutionIdentity): NodeExecutionIdentity {\n const correlation =\n identity.correlation === undefined ? undefined : Object.freeze({ ...identity.correlation })\n return Object.freeze({\n ...(identity.profileDigest === undefined ? {} : { profileDigest: identity.profileDigest }),\n ...(identity.taskDigest === undefined ? {} : { taskDigest: identity.taskDigest }),\n ...(identity.candidateDigest === undefined\n ? {}\n : { candidateDigest: identity.candidateDigest }),\n ...(correlation === undefined ? {} : { correlation }),\n })\n}\n","import {\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { closesCursorSlot } from '../../durable/spawn-journal/event-index'\nimport { replaySpawnTree } from '../../durable/spawn-journal/replay'\nimport { loadSpawnForest, ownedTreeRootSpawn } from '../../durable/spawn-journal/spawn-forest'\nimport { materializeTreeView } from '../../durable/spawn-journal/tree-view'\nimport { RuntimeRunStateError } from '../../errors'\nimport { notifyRuntimeHookEvent } from '../../runtime-hooks'\nimport { reportedFailureCause } from '../failure-cause'\nimport { addSpend, zeroSpend } from '../util'\nimport { type BudgetPoolRestore, BudgetReconcileFault, createBudgetPool } from './budget'\nimport { executorFailure, executorFailureInfra } from './executor-outcome'\nimport { addResourceSpend, withBudgetResources } from './resources'\nimport {\n BUDGET_CONTINUATION_TASK,\n leafContinuationExecutionId,\n prepareRetainedExecutor,\n type RetainedChildRecovery,\n type RetainedLeafContinuation,\n} from './retained-executor'\nimport type { ScopeArgs } from './scope'\nimport { detachedSnapshot, shareParsedStrings } from './snapshot'\nimport { assertValidSpend } from './spend-validation'\nimport { releasedChildPayload, terminalDownEvent } from './terminal-record'\nimport { nestedDriverTreeRoot } from './tree-key'\nimport type {\n Budget,\n BudgetViolation,\n NodeId,\n ResumedKeyState,\n Settled,\n SpawnEvent,\n Spend,\n SupervisorOpts,\n} from './types'\n\ntype ResumeStores = Pick<\n SupervisorOpts,\n 'runId' | 'journal' | 'blobs' | 'recoverExecutor' | 'hooks'\n>\ntype Spawned = Extract<SpawnEvent, { kind: 'spawned' }>\ntype RecordedResult = Extract<SpawnEvent, { kind: 'execution-result' }>\ntype Reconciled = Extract<SpawnEvent, { kind: 'reconciled' }>\ntype TeardownReceipt = Extract<SpawnEvent, { kind: 'environment-teardown' }>\n\n/** The environment id the node's latest durable admission names — the executor's own rule\n * (`admittedEnvironmentId` in environment-provider.ts), read off the journal. */\nfunction journaledEnvironmentId(owned: ReadonlyArray<SpawnEvent>): string | undefined {\n for (const event of [...owned].reverse()) {\n if (event.kind !== 'execution-admitted') continue\n if (event.admission.phase === 'dispatched') return event.admission.controlRef.environmentId\n if (event.admission.phase === 'environment') return event.admission.environmentId\n }\n return undefined\n}\n\n/**\n * Close the cursor slot of every node the release sweep destroyed but never recorded: the\n * settling process died between the last `environment-teardown` receipt and the terminal record\n * (the 0.233.0 crash window). The record is the sweep's own — the same builder, the cursor seq\n * `next()` stamped on the delivery and the settlement instant, all read back from the node's\n * latest `reconciled` record — so a healed journal replays as one the sweep completed.\n *\n * The gate is fail-closed, every clause required, because the heal cannot re-ask the executor\n * to confirm teardown the way the sweep does:\n * - the latest `reconciled` record carries `settledSeq`, `reason` and `trace` (a record written\n * before those fields existed names no cursor position and is not healed; `infra` is carried\n * when present and never required, since an unattributable envelope failure has none);\n * - at least one receipt sits after that record and every such receipt reads `destroyed: true`\n * (an empty set must not close the slot vacuously, and a receipt from an earlier process\n * belongs to an earlier settlement);\n * - the environment the latest admission names is among those receipts, so a receipt for an\n * environment the journal never admitted, or a re-admitted node whose receipt names the\n * earlier environment, is left open where the live sweep would have closed it.\n * A node with an `execution-result` is left to the recorded-result branch of\n * {@link prepareInterruptedExecutors}, which settles it from the durable blob and takes\n * precedence. The walk is over the whole forest because a nested manager settled on the ordinary\n * path is never restored, so a per-tree heal inside the resume of its tree would never reach its\n * grandchild. Returns the number of records written.\n */\nasync function healReleasedSlots(\n opts: ResumeStores,\n signal: AbortSignal,\n now: () => number,\n): Promise<number> {\n const forest = await loadSpawnForest(opts.journal, opts.runId)\n let healed = 0\n for (const tree of forest.trees) {\n signal.throwIfAborted()\n const events = tree.events\n const closed = new Set(events.filter(closesCursorSlot).map((event) => event.id))\n const recorded = new Set(\n events.flatMap((event) => (event.kind === 'execution-result' ? [event.id] : [])),\n )\n for (const spawned of events) {\n if (spawned.kind !== 'spawned' || spawned.parent === undefined) continue\n if (closed.has(spawned.id) || recorded.has(spawned.id)) continue\n const owned = events.filter((event) => event.id === spawned.id)\n const floor = owned.reduce<Reconciled | undefined>(\n (latest, event) =>\n event.kind === 'reconciled' && (latest === undefined || event.seq > latest.seq)\n ? event\n : latest,\n undefined,\n )\n // A complete floor names its cursor seq, its reason and its trace. `infra` is not required:\n // a floor whose envelope failure the runtime could not attribute carries none, and a\n // release that healed everything else must not be skipped for a claim the record never made.\n if (\n floor?.settledSeq === undefined ||\n floor.reason === undefined ||\n floor.trace === undefined\n )\n continue\n const receipts = owned\n .slice(owned.indexOf(floor) + 1)\n .filter((event): event is TeardownReceipt => event.kind === 'environment-teardown')\n if (receipts.length === 0 || !receipts.every((receipt) => receipt.destroyed)) continue\n const held = journaledEnvironmentId(owned)\n if (held === undefined || !receipts.some((receipt) => receipt.environmentId === held))\n continue\n const settledSeq = floor.settledSeq\n // The journal's own duplicate-cursor guard is the backstop; this names the node first, and\n // writes nothing. A fixed process cannot produce it: the resumed cursor starts past every\n // open node's `settledSeq` (see `maxCursorSeq` below).\n if (events.some((event) => closesCursorSlot(event) && event.seq === settledSeq)) {\n throw new RuntimeRunStateError(\n `retained child '${spawned.id}' cannot be released at cursor seq ${settledSeq}: tree '${tree.root}' already closes that seq`,\n )\n }\n const subject = {\n id: spawned.id,\n spent: floor.spent,\n ...(floor.budgetViolation ? { budgetViolation: floor.budgetViolation } : {}),\n ...(floor.cancellation ? { cancellationReason: floor.cancellation } : {}),\n }\n const settlement = {\n kind: 'down' as const,\n reason: floor.reason,\n ...(floor.failure === undefined ? {} : { failure: floor.failure }),\n ...(floor.infra === undefined ? {} : { infra: floor.infra }),\n trace: floor.trace,\n ...(floor.outRef ? { outRef: floor.outRef } : {}),\n ...(floor.traceRoot ? { traceRoot: floor.traceRoot } : {}),\n ...(floor.providerModel ? { providerModel: floor.providerModel } : {}),\n ...(floor.harnessTranscript ? { harnessTranscript: floor.harnessTranscript } : {}),\n ...(floor.retainedPendingCause ? { retainedPendingCause: floor.retainedPendingCause } : {}),\n }\n await opts.journal.appendEvent(\n tree.root,\n terminalDownEvent(subject, settlement, settledSeq, floor.at, 'released'),\n )\n healed += 1\n // The sweep's `agent.child` on the resumed stream, so a projection whose node state comes\n // only from that target flips the node to released as it does live. `startedAt` is the\n // runtime's own rule for a recovered child (the spawn instant), `releasedAt` the last\n // receipt's instant; the journal record above is the byte-identical surface.\n const materialized = [...owned]\n .reverse()\n .find((event) => event.kind === 'materialized' || event.kind === 'seat-materialized')\n const lastReceipt = receipts[receipts.length - 1]!\n notifyRuntimeHookEvent(\n opts.hooks,\n {\n id: `${spawned.id}:released`,\n runId: tree.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: now(),\n stepIndex: settledSeq,\n parentId: tree.ownerNodeId ?? opts.runId,\n payload: releasedChildPayload(\n {\n ...subject,\n runtime: materialized?.receipt.runtime ?? spawned.runtime,\n startedAt: Date.parse(spawned.at),\n ...(materialized === undefined ? {} : { materialization: materialized.receipt }),\n executionBindings: owned.flatMap((event) =>\n event.kind === 'execution-bound' ? [event.binding] : [],\n ),\n ...(floor.providerModel ? { providerModel: floor.providerModel } : {}),\n },\n settlement,\n Date.parse(floor.at),\n Date.parse(lastReceipt.at),\n ),\n },\n { signal },\n )\n }\n }\n return healed\n}\n\n/** Validate durable inputs without waiting for work that may need its resumed manager. */\nasync function prepareInterruptedExecutors(\n opts: ResumeStores,\n events: SpawnEvent[],\n signal: AbortSignal,\n now: () => number,\n parentId = opts.runId,\n): Promise<{ events: SpawnEvent[]; recoveries: RetainedChildRecovery[] }> {\n signal.throwIfAborted()\n const roots = events.filter((event) => event.kind === 'spawned' && event.parent === undefined)\n if (roots.length !== 1 || roots[0]?.id !== parentId) {\n throw new RuntimeRunStateError(\n `retained tree '${opts.runId}' must have exactly one original root '${parentId}'`,\n )\n }\n const terminal = new Set(events.filter(closesCursorSlot).map((event) => event.id))\n const interrupted = events.filter(\n (event): event is Spawned =>\n event.kind === 'spawned' && event.parent === parentId && !terminal.has(event.id),\n )\n const recoveries: RetainedChildRecovery[] = []\n // Interrupted children usually carry the same mounted files. Each blob parses to its own\n // strings, so share equal ones across this pass instead of holding one copy per child.\n const parsedStrings = new Map<string, string>()\n const accepted: Array<{\n result: RecordedResult\n fault?: string\n budgetViolation?: BudgetViolation\n }> = []\n const rootBudget = events.find(\n (event): event is Spawned => event.kind === 'spawned' && event.parent === undefined,\n )?.budget\n for (const node of interrupted) {\n signal.throwIfAborted()\n const owned = events.filter((event) => event.id === node.id)\n // A leaf that continued after an unavailable upstream has one invocation per\n // `execution-input`. Only the latest decides: an earlier invocation's result is the refusal\n // the leaf continued past, not its outcome.\n const inputs = owned.filter(\n (event): event is Extract<SpawnEvent, { kind: 'execution-input' }> =>\n event.kind === 'execution-input',\n )\n const latestInput = inputs.at(-1)\n const current =\n latestInput === undefined || inputs.length === 1\n ? owned\n : owned.slice(owned.indexOf(latestInput))\n const recorded = current.find(\n (event): event is RecordedResult => event.kind === 'execution-result',\n )\n if (recorded) {\n await assertRecordedResult(node, recorded, owned, opts)\n if (!rootBudget)\n throw new RuntimeRunStateError('retained results have no original root budget')\n const validation = createBudgetPool(rootBudget, 0)\n const reservation = validation.reserve(node.budget)\n if (!reservation.ok)\n throw new RuntimeRunStateError(\n `retained child '${node.id}' exceeds its original root budget`,\n )\n // An overspend is recorded beside the saved result, exactly as a live settlement records\n // it. Only spend the pool cannot verify settles the saved result down.\n let fault: string | undefined\n let budgetViolation: BudgetViolation | undefined\n try {\n budgetViolation = validation.reconcile(reservation.ticket, recorded.spent)\n } catch (error) {\n fault = error instanceof Error ? error.message : String(error)\n if (error instanceof BudgetReconcileFault) budgetViolation = error.budgetViolation\n }\n accepted.push({\n result: recorded,\n ...(fault === undefined ? {} : { fault }),\n ...(budgetViolation === undefined ? {} : { budgetViolation }),\n })\n continue\n }\n const admissions = current.flatMap((event) =>\n event.kind === 'execution-admitted' ? [event.admission] : [],\n )\n if (\n !opts.recoverExecutor ||\n (admissions.length === 0 &&\n !node.ownedTreeRoot &&\n (opts.journal.appendEvents === undefined || latestInput === undefined))\n )\n continue\n const taskRef = inputs[0]?.taskRef\n if (\n !node.profileRef ||\n !taskRef ||\n !node.identity?.profileDigest ||\n !node.identity.taskDigest\n ) {\n throw new RuntimeRunStateError(\n `cannot recover '${node.id}' without exact profile and task bytes`,\n )\n }\n const profile = shareParsedStrings(\n agentProfileSchema.parse(await opts.blobs.get(node.profileRef)),\n parsedStrings,\n )\n const task = shareParsedStrings(await opts.blobs.get(taskRef), parsedStrings)\n if (\n canonicalAgentProfileDigest(profile) !== node.identity.profileDigest ||\n canonicalCandidateDigest(task) !== node.identity.taskDigest\n ) {\n throw new RuntimeRunStateError(\n `recovery inputs for '${node.id}' do not match its admitted identity`,\n )\n }\n if (node.ownedTreeRoot !== undefined) {\n if (node.ownedTreeRoot !== nestedDriverTreeRoot(opts.runId, node.id)) {\n throw new RuntimeRunStateError(`retained manager '${node.id}' changed its owned tree`)\n }\n const nested = await opts.journal.loadTree(node.ownedTreeRoot)\n const roots =\n nested?.filter((event) => event.kind === 'spawned' && event.parent === undefined) ?? []\n if (\n nested?.length &&\n (roots.length !== 1 ||\n contentAddress(roots[0]) !== contentAddress(ownedTreeRootSpawn(node)))\n ) {\n throw new RuntimeRunStateError(\n `retained manager '${node.id}' has conflicting subtree ownership`,\n )\n }\n }\n const prepared = prepareRetainedExecutor(opts.recoverExecutor, { spawned: node, profile, task })\n if (node.ownedTreeRoot !== undefined && !prepared) continue\n const priorMaterialization = [...owned]\n .reverse()\n .find((event) => event.kind === 'materialized' || event.kind === 'seat-materialized')?.receipt\n const continuation =\n latestInput !== undefined && inputs.length > 1 && node.ownedTreeRoot === undefined\n ? await leafContinuation(node, owned, latestInput, opts)\n : latestInput !== undefined &&\n node.continues !== undefined &&\n admissions.length === 0 &&\n node.ownedTreeRoot === undefined\n ? heldContinuation(node, events, latestInput)\n : undefined\n recoveries.push({\n ...detachedSnapshot(\n {\n spawned: node,\n task,\n admissions,\n ...(priorMaterialization === undefined ? {} : { priorMaterialization }),\n ...(continuation === undefined ? {} : { continuation }),\n },\n 'retained child recovery',\n ),\n spec: prepared?.spec ?? { profile, harness: null, execution: node.identity },\n factory: prepared?.factory ?? opts.recoverExecutor,\n })\n }\n // Past every closed AND reserved seq: an open node's `settledSeq` is where its terminal record\n // lands, and a recovered result written there would be the collision the heal refuses.\n let seq = reservedCursorFloor(events) + 1\n for (const { result, fault, budgetViolation } of accepted) {\n signal.throwIfAborted()\n const failure = executorFailure(result)\n const reason = fault ?? failure?.error\n // A reconcile fault is the runtime's own failure; an envelope failure is attributed by the\n // same vocabulary the live path uses, so a child settled here and one settled live from the\n // same durable result carry the same label. This site used to stamp `infra: false` for every\n // envelope failure, which made the label depend on whether the process survived to settle it.\n const infra =\n fault !== undefined ? true : failure === undefined ? undefined : executorFailureInfra(failure)\n // Await every admitted write before releasing the run lock, including cancellation races.\n await opts.journal.appendEvent(opts.runId, {\n kind: 'settled',\n id: result.id,\n status: reason === undefined ? 'done' : 'down',\n outRef: result.outRef,\n // Copied, never recomputed: salts are random, so only the recorded root proves this output.\n ...(result.traceRoot === undefined ? {} : { traceRoot: result.traceRoot }),\n ...(reason === undefined ? {} : { reason }),\n ...(infra === undefined ? {} : { infra }),\n ...(fault === undefined && failure !== undefined\n ? { failure: reportedFailureCause(failure) }\n : {}),\n spent: result.spent,\n ...(budgetViolation === undefined ? {} : { budgetViolation }),\n ...(result.verdict ? { verdict: result.verdict } : {}),\n seq: seq++,\n at: new Date(now()).toISOString(),\n })\n }\n signal.throwIfAborted()\n return { events: (await opts.journal.loadTree(opts.runId)) ?? events, recoveries }\n}\n\n/**\n * The later invocation a leaf was running when its process stopped: its own task, and the\n * environment admission of the invocation before it, which it continued in. The execution id is\n * derived from the input sequence exactly as the live scope derived it.\n */\nasync function leafContinuation(\n node: Spawned,\n owned: SpawnEvent[],\n latestInput: Extract<SpawnEvent, { kind: 'execution-input' }>,\n opts: ResumeStores,\n): Promise<RetainedLeafContinuation> {\n const before = owned.slice(0, owned.indexOf(latestInput))\n const priorSession = [...before]\n .reverse()\n .flatMap((event) =>\n event.kind === 'execution-admitted' && event.admission.phase === 'environment'\n ? [event.admission]\n : [],\n )[0]\n if (priorSession === undefined) {\n throw new RuntimeRunStateError(\n `cannot recover '${node.id}': its continuation names no environment it continued in`,\n )\n }\n const priorResult = [...before]\n .reverse()\n .find((event): event is RecordedResult => event.kind === 'execution-result')\n if (priorResult === undefined) {\n throw new RuntimeRunStateError(\n `cannot recover '${node.id}': its continuation has no committed predecessor result`,\n )\n }\n await assertRecordedResult(node, priorResult, owned, opts)\n const task = await opts.blobs.get(latestInput.taskRef)\n if (task === undefined || contentAddress(task) !== latestInput.taskRef) {\n throw new RuntimeRunStateError(`continuation task for '${node.id}' is missing or corrupt`)\n }\n return {\n task,\n inputSeq: latestInput.seq,\n executionId: leafContinuationExecutionId(node.id, latestInput.seq),\n priorSession,\n priorSpent: priorResult.spent,\n }\n}\n\n/**\n * A node that continues a budget-stopped node's held environment, recovered before its own first\n * admission: it runs in the environment and session of its predecessor's last environment\n * admission, so the recovery neither creates a second environment nor leaves the held one behind.\n */\nfunction heldContinuation(\n node: Spawned,\n events: ReadonlyArray<SpawnEvent>,\n latestInput: Extract<SpawnEvent, { kind: 'execution-input' }>,\n): RetainedLeafContinuation {\n const continues = node.continues!\n const priorSession = [...events]\n .reverse()\n .flatMap((event) =>\n event.id === continues.ofWorker &&\n event.kind === 'execution-admitted' &&\n event.admission.phase === 'environment'\n ? [event.admission]\n : [],\n )[0]\n if (priorSession === undefined || priorSession.environmentId !== continues.environmentId) {\n throw new RuntimeRunStateError(\n `cannot recover '${node.id}': '${continues.ofWorker}' has no admission for the environment it continues`,\n )\n }\n return {\n task: BUDGET_CONTINUATION_TASK,\n inputSeq: latestInput.seq,\n executionId: node.id,\n priorSession,\n priorSpent: zeroSpend(),\n }\n}\n\nasync function assertRecordedResult(\n node: Spawned,\n result: RecordedResult,\n events: SpawnEvent[],\n opts: ResumeStores,\n): Promise<void> {\n const before = events.slice(0, events.indexOf(result))\n const receipt = [...before]\n .reverse()\n .find((event) => event.kind === 'materialized' || event.kind === 'seat-materialized')?.receipt\n const binding = [...before].reverse().find((event) => event.kind === 'execution-bound')?.binding\n if (\n receipt?.status !== 'known' ||\n binding?.status !== 'known' ||\n receipt.runtime !== node.runtime ||\n receipt.authoredProfileDigest !== node.identity?.profileDigest ||\n binding.materializationReceiptDigest !== canonicalCandidateDigest(receipt)\n ) {\n throw new RuntimeRunStateError(\n `retained result '${node.id}' has no matching execution evidence`,\n )\n }\n assertValidSpend(result.spent, `retained result '${result.id}'`)\n const output = await opts.blobs.get(result.outRef)\n if (output === undefined || contentAddress(output) !== result.outRef)\n throw new RuntimeRunStateError(`retained result '${result.id}' is missing or corrupt`)\n}\n\n/** The committed work + cursor maxima the supervisor hands a resumed scope. Shaped to spread\n * into `ScopeArgs.resumeFrom`. */\nexport type ScopeResumeState = NonNullable<ScopeArgs['resumeFrom']> & {\n readonly events: readonly SpawnEvent[]\n readonly recoveries: readonly RetainedChildRecovery[]\n}\n\n/**\n * The keyed assignments a prior journal proves: every `spawned` event carrying a `key`, resolved\n * against the replayed settlements. A key spawned more than once (a retry chain) resolves to its\n * LATEST attempt — iterate in ordinal order so later spawns overwrite earlier ones. A spawned\n * event with no matching settlement is `in-doubt`: the process died with it in flight — UNLESS\n * the spawn's own runtime proves the execution cannot have outlived the process (`inline`, the\n * same predicate the budget layer charges no uncertain reservation for), in which case the resume\n * itself is the terminal evidence and the key resolves `down` with a derived reason, so a re-spawn\n * under the same key retries instead of wedging in-doubt.\n */\nfunction keyedAssignments(\n events: SpawnEvent[],\n settled: ReadonlyArray<Settled<unknown>>,\n): ReadonlyMap<string, ResumedKeyState<unknown>> {\n const byId = new Map(settled.map((s) => [s.handle.id, s]))\n const keys = new Map<string, ResumedKeyState<unknown>>()\n const spawns = events\n .filter(\n (ev): ev is Extract<SpawnEvent, { kind: 'spawned' }> =>\n ev.kind === 'spawned' && ev.parent !== undefined,\n )\n .sort((a, b) => a.seq - b.seq)\n for (const ev of spawns) {\n if (ev.key === undefined) continue\n if (ev.identity === undefined) {\n throw new RuntimeRunStateError(\n `supervisor: keyed node '${ev.id}' has no durable execution identity`,\n )\n }\n const s = byId.get(ev.id)\n keys.set(\n ev.key,\n s === undefined\n ? ev.runtime === 'inline'\n ? {\n id: ev.id,\n label: ev.label,\n identity: ev.identity,\n state: 'down',\n reason: `interrupted: the process died with '${ev.label}' in flight and its '${ev.runtime}' runtime cannot outlive that process, so the resume proves the attempt dead`,\n }\n : { id: ev.id, label: ev.label, identity: ev.identity, state: 'in-doubt' }\n : {\n id: ev.id,\n label: ev.label,\n identity: ev.identity,\n state: s.kind === 'done' ? 'completed' : 'down',\n settled: s,\n },\n )\n }\n return keys\n}\n\n/** Child reservations whose spawn was durable, whose terminal record never landed, and whose\n * reservation was never reconciled: the process died with them in flight, so nothing observed\n * their spend and the ceiling is the only sound charge. An open node with a `reconciled` record is\n * not uncertain in that sense — its floor is measured evidence and is charged by\n * {@link sumMeasuredSpendFromEvents}, never here, so the two readers cannot charge one node twice. */\nfunction uncertainSpawnBudgets(\n events: SpawnEvent[],\n recovered: ReadonlySet<NodeId> = new Set(),\n): Budget[] {\n const terminal = new Set(events.filter(closesCursorSlot).map((event) => event.id))\n const reconciled = new Set(\n events.flatMap((event) => (event.kind === 'reconciled' ? [event.id] : [])),\n )\n return events\n .filter(\n (event): event is Spawned =>\n event.kind === 'spawned' &&\n event.parent !== undefined &&\n !terminal.has(event.id) &&\n !reconciled.has(event.id) &&\n !recovered.has(event.id) &&\n // An `inline` executor runs inside the process that spawned it, so a resume can prove it\n // dead rather than in-doubt: holding its reservation would charge the pool for work no\n // process can ever finish. Only a runtime that can re-attach across a process boundary\n // (bridge, sandbox) keeps its reservation charged as uncertain.\n event.runtime !== 'inline',\n )\n .map((event) => event.budget)\n}\n\n/** Highest `seq` among events matching `pred`, or `-1` when none match (so a resumed scope's\n * first new ordinal/seq is 0 — the same start a fresh scope uses). */\nfunction maxSeqOf(events: SpawnEvent[], pred: (ev: SpawnEvent) => boolean): number {\n let max = -1\n for (const ev of events) if (pred(ev) && ev.seq > max) max = ev.seq\n return max\n}\n\n/**\n * The highest cursor seq any record in the journal already owns, closed OR reserved.\n *\n * A closed slot owns its seq outright. An open retained node owns the `settledSeq` its\n * `reconciled` record carries: that is the seq the driver already branched on, and the seq the\n * heal (or a later release sweep) writes the terminal record under. Every writer that mints a\n * new cursor seq in a resumed process — the recorded-result settlements below and the resumed\n * scope's own cursor — must start past BOTH, or a recovered result lands on a seq an open node\n * has reserved and the heal can only ever collide. One function so no writer can drift.\n */\nfunction reservedCursorFloor(events: SpawnEvent[]): number {\n return Math.max(\n maxSeqOf(events, closesCursorSlot),\n events.reduce(\n (max, event) =>\n event.kind === 'reconciled' && event.settledSeq !== undefined\n ? Math.max(max, event.settledSeq)\n : max,\n -1,\n ),\n )\n}\n\n/** Per-channel sum over a journaled event list: `settled` = spawned-child work (reconciled), plus\n * the reconciled floor of every node still open, plus the declared ceiling of every open node\n * nothing reconciled; `metered` = driver inference (re-homed up the tree, so a single root-tree\n * pass already includes every nested driver's inference). The pool commits exactly these amounts\n * — a floor where a reconcile ran, a ceiling where the process died first — so this sum is the\n * same ledger the pool holds, read from the journal. */\nexport function sumSpendFromEvents(events: SpawnEvent[]): {\n childWork: Spend\n driverInference: Spend\n} {\n const totals = sumMeasuredSpendFromEvents(events)\n const rootBudget = events.find(\n (event): event is Spawned => event.kind === 'spawned' && event.parent === undefined,\n )?.budget\n let remainingRootUsd = Math.max(\n 0,\n (rootBudget?.maxUsd ?? 0) - totals.childWork.usd - totals.driverInference.usd,\n )\n for (const budget of uncertainSpawnBudgets(events)) {\n const unknown = withBudgetResources(zeroSpend(), budget)\n Object.assign(totals.childWork, addResourceSpend(totals.childWork.resources, unknown.resources))\n totals.childWork.iterations += budget.maxIterations\n // The numeric value is the charged upper bound, not a fabricated measurement. The false flag\n // makes that distinction machine-readable in every report.\n totals.childWork.tokens.input += budget.maxTokens\n totals.childWork.tokensKnown = false\n const usdCharge = budget.maxUsd ?? (rootBudget?.maxUsd !== undefined ? remainingRootUsd : 0)\n totals.childWork.usd += usdCharge\n totals.childWork.usdKnown = false\n remainingRootUsd = Math.max(0, remainingRootUsd - usdCharge)\n }\n return totals\n}\n\nfunction sumMeasuredSpendFromEvents(events: SpawnEvent[], ownerId?: NodeId) {\n const budgets = new Map(\n events.flatMap((event) =>\n event.kind === 'spawned' ? [[event.id, event.budget] as const] : [],\n ),\n )\n let childWork = zeroSpend()\n let driverInference = zeroSpend()\n const owners = new Map<NodeId, Spend>()\n const terminal = new Set(events.filter(closesCursorSlot).map((event) => event.id))\n // A retained-pending node's reconciled floor is its child work for as long as the node stays\n // open. The LATEST record is the whole charge, not a sum: a recovered execution reports its\n // total again on its next reconcile, so an earlier floor would count the same work twice. A\n // terminal record supersedes every floor for the same reason.\n const floors = new Map<NodeId, Extract<SpawnEvent, { kind: 'reconciled' }>>()\n for (const ev of events) {\n if (ev.kind === 'settled' || ev.kind === 'cancelled')\n childWork = addSpend(\n childWork,\n withBudgetResources(\n ev.spent ?? { ...zeroSpend(), tokensKnown: false, usdKnown: false },\n budgets.get(ev.id) ?? {},\n ),\n )\n else if (ev.kind === 'metered')\n owners.set(ev.id, addSpend(owners.get(ev.id) ?? zeroSpend(), ev.spend))\n else if (ev.kind === 'reconciled' && !terminal.has(ev.id)) {\n const prior = floors.get(ev.id)\n if (prior === undefined || ev.seq > prior.seq) floors.set(ev.id, ev)\n }\n }\n for (const [id, floor] of floors) {\n childWork = addSpend(childWork, withBudgetResources(floor.spent, budgets.get(id) ?? {}))\n }\n for (const [id, spend] of owners) {\n driverInference = addSpend(driverInference, withBudgetResources(spend, budgets.get(id) ?? {}))\n }\n const owner = ownerId === undefined ? undefined : owners.get(ownerId)\n return { childWork, driverInference, owner }\n}\n\n/** Restore the same journal projection and accounting for root and nested scopes. @internal */\nexport async function prepareScopeResume(\n opts: ResumeStores,\n events: SpawnEvent[],\n signal: AbortSignal,\n now: () => number,\n parentId = opts.runId,\n /** A terminal entry restores cleanup descriptors, never slot heals or execution. */\n settleOnly = false,\n): Promise<{ resumeFrom: ScopeResumeState; poolRestore: BudgetPoolRestore }> {\n // The root resume walks the whole forest once; the nested restore, whose `parentId` is the\n // manager node, does not walk again. A healed node is then terminal to everything below:\n // never interrupted, never a recovery, charged its floor as `settled.spent` instead of the\n // reconciled floor (the same object), and replayed at the driver's own seq.\n if (!settleOnly && parentId === opts.runId && (await healReleasedSlots(opts, signal, now)) > 0) {\n events = (await opts.journal.loadTree(opts.runId)) ?? events\n }\n if (settleOnly) signal = new AbortController().signal\n const prepared = await prepareInterruptedExecutors(opts, events, signal, now, parentId)\n const prior = prepared.events\n const recovering = new Set(prepared.recoveries.map((item) => item.spawned.id))\n // A restored child's full reservation already covers its previous inference and its reconciled\n // floor. Its executor reconciles total spend and publishes only the unrecorded meter delta, so\n // neither prior record may be committed a second time.\n const measuredEvents = prior.filter(\n (event) =>\n (event.kind !== 'metered' && event.kind !== 'reconciled') || !recovering.has(event.id),\n )\n const measured = sumMeasuredSpendFromEvents(measuredEvents, parentId)\n const hasCommittedEvidence = measuredEvents.some(\n (event) =>\n event.kind === 'metered' ||\n event.kind === 'reconciled' ||\n event.kind === 'settled' ||\n event.kind === 'cancelled',\n )\n const settled = await replaySpawnTree(opts.journal, opts.blobs, opts.runId)\n if (!settleOnly) signal.throwIfAborted()\n return {\n poolRestore: {\n ...(hasCommittedEvidence\n ? { committed: addSpend(measured.childWork, measured.driverInference) }\n : {}),\n owner: measured.owner,\n uncertainReservations: uncertainSpawnBudgets(prior, recovering),\n },\n resumeFrom: {\n events: prior,\n recoveries: prepared.recoveries,\n settled,\n view: materializeTreeView(prior),\n maxSpawnOrdinal: maxSeqOf(prior, (event) => event.kind === 'spawned'),\n // An open node's journaled cursor seq is reserved across processes: the resumed scope must\n // never mint it for another node, or the heal above could only ever collide.\n maxCursorSeq: reservedCursorFloor(prior),\n keys: keyedAssignments(prior, settled),\n priorSpend: sumMeasuredSpendFromEvents(prior),\n },\n }\n}\n","import { createBudgetPool } from './budget'\nimport { prepareScopeResume } from './recover-executors'\nimport { createScope } from './scope-construction'\nimport type { DeferredOwnerSlot, NestedScopeSeam, ScopeArgs } from './scope-contract'\nimport type { Budget, NodeId, Scope } from './types'\nimport type { SlotPermit, WorkerSlots } from './worker-slots'\n\nexport function makeNestedScopeSeam(\n args: ScopeArgs,\n workerSlots: WorkerSlots,\n childSlot: SlotPermit,\n childNodeId: NodeId,\n childBudget: Budget,\n childDeadlineAtMs: number | undefined,\n deferredOwner: DeferredOwnerSlot,\n): NestedScopeSeam {\n const now = args.now ?? Date.now\n const mountScope = (\n nestedRoot: NodeId,\n signal: AbortSignal,\n restored?: Awaited<ReturnType<typeof prepareScopeResume>>,\n ): Scope<unknown> => {\n // One clock anchors both the remaining duration and nested absolute deadline.\n const mountedAtMs = now()\n const deadlineMs =\n childDeadlineAtMs === undefined ? undefined : Math.max(0, childDeadlineAtMs - mountedAtMs)\n const nestedBudget = {\n ...childBudget,\n ...(deadlineMs !== undefined ? { deadlineMs } : {}),\n }\n return createScope<unknown>({\n parentId: childNodeId,\n root: nestedRoot,\n rootDeadlineAtMs: args.rootDeadlineAtMs,\n pool: createBudgetPool(nestedBudget, mountedAtMs, restored?.poolRestore),\n journal: args.journal,\n blobs: args.blobs,\n executors: args.executors,\n // Re-seed the parent's NON-recursion seams (sandbox/router for leaf grandchildren);\n // the nested scope adds its OWN nested-scope seam per child in `spawn`.\n seams: args.seams,\n depth: args.depth + 1,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n workerSlots,\n slotOwner: childSlot,\n ...(args.reservationPolicy\n ? { reservationPolicy: args.reservationPolicy, ownerBudget: nestedBudget }\n : {}),\n ...(args.deadlineCheckIn === undefined ? {} : { deadlineCheckIn: args.deadlineCheckIn }),\n ...(args.budgetStopHoldMs === undefined ? {} : { budgetStopHoldMs: args.budgetStopHoldMs }),\n signal,\n ...(restored ? { resumeFrom: restored.resumeFrom } : {}),\n ...(args.now ? { now: args.now } : {}),\n ...(args.hooks ? { hooks: args.hooks } : {}),\n // The nested scope resolves the trace context against ITS OWN `parentId` (this driver\n // child), so a grandchild worker joins under the middle node's span, not the run root's.\n ...(args.workerTrace ? { workerTrace: args.workerTrace } : {}),\n ...(args.workerTraceUnpropagated\n ? { workerTraceUnpropagated: args.workerTraceUnpropagated }\n : {}),\n ...(args.interactiveBindingDir ? { interactiveBindingDir: args.interactiveBindingDir } : {}),\n ...(deferredOwner.ownerMaterialization === undefined\n ? {}\n : { ownerMaterialization: deferredOwner.ownerMaterialization }),\n })\n }\n return {\n nodeId: childNodeId,\n depth: args.depth,\n ...(args.maxDepth !== undefined ? { maxDepth: args.maxDepth } : {}),\n journalRoot: args.root,\n mount: mountScope,\n restore: async (nestedRoot, signal, events, recoverExecutor) => {\n const restored = await prepareScopeResume(\n {\n runId: nestedRoot,\n journal: args.journal,\n blobs: args.blobs,\n recoverExecutor,\n },\n events,\n signal,\n now,\n childNodeId,\n )\n signal.throwIfAborted()\n return mountScope(nestedRoot, signal, restored)\n },\n }\n}\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 is retained in the blob its\n * `settled` record names as `outRef`, but the root's reached nobody: `driveHarnessFromBackend`\n * discarded every root `progress` event, and a `winner` run's `result.outRef` is the selected\n * child's. A root that died at its join barrier (fourier-e, 63 children) left a 607-byte\n * `failure.json` and nothing it thought.\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: after a quiet second an append reaches an `O_APPEND` descriptor when the\n * event-loop turn ends; under load, lines group into one fenced `writeSync` per second. A fence\n * fsyncs a lock-owner file: 10-20 ms on SSD, 150 ms to 1.8 s on a busy SMR drive, where a fence per\n * line drained 2.5 events/s and one per turn (one upstream page, ~24 lines) ~20/s while the model\n * streamed ~210 (us-legal-exploits-20261103a and b). The file is fsynced at each drive-attempt\n * boundary and at close. A process kill loses at most the last second; a kernel crash or power loss\n * can drop lines since the last fsync, and the reader's torn-tail rule keeps the file readable.\n *\n * The bridge wire carries text and tool calls only (cli-bridge decodes `delta.content` and\n * `delta.tool_calls`), so a bridge-placed root's stream has no reasoning; reasoning arrives only on\n * the provider path, 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; its line reaches the kernel within one turn, or a second under load. */\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 const pending: string[] = []\n let failure: unknown\n let flushedAt = 0\n // Group commit: at most one fenced write per second; a lost claim is thrown to the next caller.\n const flush = (): void =>\n withClaim(() => {\n const writer = fd\n if (pending.length === 0 || writer === undefined) return\n const lines = pending.splice(0).join('\\n')\n flushedAt = Date.now()\n try {\n fenceRunWrite(() => writeLine(writer, lines))\n } catch (error) {\n failure ??= error\n }\n })\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 flush()\n if (failure !== undefined) throw failure\n if (writer !== undefined) fenceRunWrite(() => fsyncSync(writer))\n await openOnce()\n })\n },\n append(event) {\n if (closed) throw new Error('root stream: append after close')\n if (fd === undefined) throw new Error('root stream: append before beginAttempt')\n if (failure !== undefined) throw failure\n seq += 1\n const at = new Date(now()).toISOString()\n // A progress payload is JSON the wire already parsed, so this is a guard, not a path: a value\n // JSON cannot encode (a BigInt, a cycle, a hostile `toJSON`) is recorded as a dropped line so\n // the turn continues and the file still says something was lost.\n let line: string\n try {\n line = JSON.stringify({ seq, at, attempt, event })\n } catch (error) {\n const dropped = { kind: event.kind, reason: errorMessage(error) }\n line = JSON.stringify({ seq, at, attempt, dropped })\n }\n pending.push(line)\n if (pending.length > 1) return\n const wait = flushedAt + 1_000 - Date.now()\n if (wait > 0) setTimeout(flush, wait).unref()\n else setImmediate(flush)\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 flush()\n if (failure !== undefined) throw failure\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) => void hash.update(bytes),\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","import { randomUUID } from 'node:crypto'\nimport { defaultRedactor } from '../../redact'\nimport { createRootStreamSink, nodeStreamFile, type RootStreamSink } from './root-stream'\nimport type { ExecutorProgressEvent } from './types'\n\n/** Live observation is bounded and process-local. A reconnect explicitly reports expired history. */\nexport interface WorkerEventCursor {\n readonly epoch: string\n readonly next: number\n}\n\nexport interface WorkerEventEntry {\n readonly sequence: number\n readonly at: number\n readonly event: unknown\n readonly omitted?: 'event-too-large' | 'event-not-serializable'\n}\n\nexport type WorkerEventPage =\n | { readonly status: 'unavailable'; readonly reason: 'unknown-worker' | 'not-captured' }\n | {\n readonly status: 'available'\n readonly entries: readonly WorkerEventEntry[]\n readonly cursor: WorkerEventCursor\n readonly reset: boolean\n readonly historyExpired: boolean\n readonly remaining: number\n }\n\nconst MAX_EVENTS = 256\nconst MAX_BYTES = 262_144\n\n/** Where a worker's redacted output is also kept: its node stream in the durable run directory. */\nexport interface WorkerEventStream {\n readonly runDir: string\n readonly nodeId: string\n readonly now: () => number\n}\n\n/** One worker's already-redacted live output. Accounting stays on Scope's existing usage channel. */\nexport class WorkerEvents {\n readonly #epoch = randomUUID()\n readonly #entries: { entry: WorkerEventEntry; bytes: number }[] = []\n #next = 0\n #capturing = false\n // The bounded live view above is process-local; the node stream is the durable record, opened\n // by an attempt's first event so a worker that streams nothing leaves no file.\n readonly #stream: WorkerEventStream | undefined\n #sink: RootStreamSink | undefined\n #writes: Promise<void> = Promise.resolve()\n #attemptOpen = false\n #failure: unknown\n\n constructor(stream?: WorkerEventStream) {\n this.#stream = stream\n }\n\n start(): void {\n this.#capturing = true\n this.#attemptOpen = false\n }\n #bytes = 0\n\n append(event: ExecutorProgressEvent, at: number): void {\n const redacted = defaultRedactor(event)\n this.#record(redacted as ExecutorProgressEvent)\n let entry: WorkerEventEntry = { sequence: this.#next++, at, event: redacted }\n let bytes: number\n try {\n bytes = Buffer.byteLength(JSON.stringify(entry))\n } catch {\n entry = { sequence: entry.sequence, at, event: null, omitted: 'event-not-serializable' }\n bytes = Buffer.byteLength(JSON.stringify(entry))\n }\n if (bytes > MAX_BYTES) {\n entry = { sequence: entry.sequence, at, event: null, omitted: 'event-too-large' }\n bytes = Buffer.byteLength(JSON.stringify(entry))\n }\n this.#entries.push({ entry, bytes })\n this.#bytes += bytes\n while (this.#entries.length > MAX_EVENTS || this.#bytes > MAX_BYTES) {\n this.#bytes -= this.#entries.shift()!.bytes\n }\n }\n\n #record(event: ExecutorProgressEvent): void {\n const stream = this.#stream\n if (stream === undefined) return\n if (!this.#attemptOpen || this.#sink === undefined) {\n this.#attemptOpen = true\n this.#sink ??= createRootStreamSink(\n stream.runDir,\n stream.now,\n nodeStreamFile(stream.nodeId),\n { continueAttempts: true },\n )\n const sink = this.#sink\n this.#chain(() => sink.beginAttempt())\n }\n const sink = this.#sink!\n this.#chain(() => sink.append(event))\n }\n\n #chain(write: () => void | Promise<void>): void {\n this.#writes = this.#writes.then(write).catch((error: unknown) => {\n this.#failure ??= error\n })\n }\n\n /** Make this attempt's node stream durable and close it; throws the first write failure. */\n async settle(): Promise<void> {\n await this.#writes\n const sink = this.#sink\n this.#sink = undefined\n if (sink !== undefined) await sink.close()\n if (this.#failure !== undefined) throw this.#failure\n }\n\n read(cursor?: WorkerEventCursor): WorkerEventPage {\n if (!this.#capturing) return { status: 'unavailable', reason: 'not-captured' }\n if (cursor && (!Number.isSafeInteger(cursor.next) || cursor.next < 0)) {\n throw new Error('worker event cursor must name a non-negative safe integer')\n }\n const reset = cursor !== undefined && cursor.epoch !== this.#epoch\n const first = this.#entries[0]?.entry.sequence ?? this.#next\n const start = reset ? first : (cursor?.next ?? first)\n if (!reset && start > this.#next) throw new Error('worker event cursor is ahead of this stream')\n return {\n status: 'available',\n entries: this.#entries\n .filter(({ entry }) => entry.sequence >= start)\n .map(({ entry }) => structuredClone(entry)),\n cursor: { epoch: this.#epoch, next: this.#next },\n reset,\n historyExpired: start < first || (cursor === undefined && first > 0),\n remaining: 0,\n }\n }\n}\n","/**\n * The records one admitted child starts with: its executor context, its handle, its live-child\n * row, its spawn journal record and hook, and the settlement chain that closes it. `scope-spawn`\n * sequences them; each builder here owns one record.\n */\n\nimport { contentAddress } from '../../durable/content-address'\nimport { appendSpawnEvents } from '../../durable/spawn-journal/journal-store'\nimport { notifyRuntimeHookEvent } from '../../runtime-hooks'\nimport { persistHarnessTranscript, readHarnessTranscript } from '../harness-transcript'\nimport type {\n RetainedInteractiveAdmission,\n RetainedRunEnvironmentAdmission,\n} from '../retained-run-types'\nimport { zeroSpend } from '../util'\nimport { RunCancellationReason } from './abortable'\nimport { singleFlightTeardown, teardownExecutor } from './deadline'\nimport {\n interactiveAdmissionSeamKey,\n writeWorkerInteractiveAdmission,\n} from './interactive-admission'\nimport { authoredAgentIdentity } from './materialization'\nimport { type RetainedChildRecovery, retainedExecutorSeamKey } from './retained-executor'\nimport { nestedTeardownScopes } from './scope-capabilities'\nimport type { createChildRetention } from './scope-child-retention'\nimport {\n type DeferredOwnerSlot,\n type LiveChild,\n nestedScopeSeamKey,\n type PreSeqSettled,\n type ScopeArgs,\n} from './scope-contract'\nimport { downRecord } from './scope-execution'\nimport { makeNestedScopeSeam } from './scope-nesting'\nimport { readInteractiveReadyUntilWorkerEnds, readInteractiveSession } from './scope-observation'\nimport type { TraceRootWriter } from './trace-root'\nimport type {\n AgentSpec,\n ExecutionBindingReceipt,\n Executor,\n ExecutorContext,\n Handle,\n HeldRelease,\n NodeExecutionIdentity,\n NodeId,\n NodeStatus,\n ProfileMaterializationReceipt,\n SpawnEvent,\n SpawnOpts,\n WorkerInteractiveSession,\n} from './types'\nimport { WorkerEvents } from './worker-events'\nimport { writeWorkerInteractiveBinding } from './worker-interactive'\nimport type { SlotPermit, WorkerSlots } from './worker-slots'\nimport { type TraceContext, workerTraceSeamKey } from './worker-trace'\n\ntype ChildRetention = ReturnType<typeof createChildRetention>\n\n/** A budget-stopped node's held environment and session, continued by a same-key spawn. */\nexport interface HeldContinuation {\n readonly from: LiveChild\n readonly admission: RetainedRunEnvironmentAdmission\n readonly held: NonNullable<LiveChild['held']>\n}\n\n/** A child past every admission refusal: its node, its clocks, and what it runs. */\nexport interface AdmittedChild {\n readonly id: NodeId\n readonly ordinal: number\n readonly attemptId: string\n readonly startedAt: number\n readonly childDeadlineAtMs: number | undefined\n readonly successorOf: NodeId | undefined\n readonly task: unknown\n readonly opts: SpawnOpts\n readonly spec: AgentSpec\n readonly identity: NodeExecutionIdentity | undefined\n /** A recovered node keeps the substitution its spawn record journaled. */\n readonly modelSubstitution: AgentSpec['modelSubstitution']\n readonly recovery: RetainedChildRecovery | undefined\n readonly continuing: HeldContinuation | undefined\n}\n\n/**\n * Seed THIS scope's keystone deps into the child's `ExecutorContext.seams`, so a DRIVER child can\n * mount a nested `Scope` at `depth+1` over a pool backed by THIS reservation. Leaves ignore it.\n */\nexport function childExecutorContext(\n args: ScopeArgs,\n child: AdmittedChild,\n controller: AbortController,\n seams: {\n readonly workerSlots: WorkerSlots\n readonly permit: SlotPermit\n readonly deferredOwner: DeferredOwnerSlot\n readonly workerTrace: TraceContext | undefined\n readonly retainedContext: ChildRetention['retainedContext']\n readonly now: () => number\n },\n): ExecutorContext {\n const { id, identity, recovery, continuing, opts } = child\n const interactiveBindingDir = args.interactiveBindingDir\n return {\n signal: controller.signal,\n node: {\n rootId: args.root,\n parentId: args.parentId,\n nodeId: id,\n depth: args.depth + 1,\n attemptId: child.attemptId,\n ...(identity ? { identity } : {}),\n },\n seams: {\n ...args.seams,\n [retainedExecutorSeamKey]: seams.retainedContext(\n recovery?.continuation !== undefined\n ? {\n executionId: recovery.continuation.executionId,\n priorSession: recovery.continuation.priorSession,\n priorSpent: recovery.continuation.priorSpent,\n }\n : continuing !== undefined\n ? // The successor's first invocation runs in the held environment and session.\n { executionId: id, priorSession: continuing.admission }\n : undefined,\n ),\n [nestedScopeSeamKey]: makeNestedScopeSeam(\n args,\n seams.workerSlots,\n seams.permit,\n id,\n opts.budget,\n child.childDeadlineAtMs,\n seams.deferredOwner,\n ),\n ...(seams.workerTrace ? { [workerTraceSeamKey]: seams.workerTrace } : {}),\n ...(interactiveBindingDir\n ? {\n [interactiveAdmissionSeamKey]: (admission: RetainedInteractiveAdmission) =>\n Promise.resolve(\n writeWorkerInteractiveAdmission(interactiveBindingDir, id, admission, seams.now),\n ).then(() => undefined),\n }\n : {}),\n },\n }\n}\n\n/** The caller's handle: live reads of the child's row, and its own abort. */\nexport function childHandle<C>(\n child: AdmittedChild,\n children: Map<NodeId, LiveChild>,\n controller: AbortController,\n): Handle<C> {\n const { id, opts, identity, modelSubstitution } = child\n return {\n id,\n label: opts.label,\n ...(opts.assignmentId === undefined ? {} : { assignmentId: opts.assignmentId }),\n ...(identity ? { identity } : {}),\n ...(modelSubstitution === undefined ? {} : { modelSubstitution }),\n get status(): NodeStatus {\n return children.get(id)?.status ?? 'cancelled'\n },\n get materialization(): ProfileMaterializationReceipt | undefined {\n return children.get(id)?.materialization\n },\n get executionBindings(): ReadonlyArray<ExecutionBindingReceipt> | undefined {\n const bindings = children.get(id)?.executionBindings\n return bindings && bindings.length > 0 ? Object.freeze([...bindings]) : undefined\n },\n abort(reason?: string): void {\n controller.abort(new RunCancellationReason('worker-handle', reason ?? 'worker cancelled'))\n },\n }\n}\n\n/** The scope's row for a started child, reading the executor's optional capabilities. */\nexport function liveChildRecord<C>(\n args: ScopeArgs,\n child: AdmittedChild,\n executor: Executor<C>,\n start: {\n readonly granted: boolean\n readonly controller: AbortController\n readonly ownedTreeRoot: NodeId | undefined\n readonly traceRoots: TraceRootWriter\n readonly recoveryReady: Promise<void> | undefined\n readonly readEnvironmentAdmission: LiveChild['readEnvironmentAdmission']\n readonly now: () => number\n },\n): LiveChild {\n const { id, identity, modelSubstitution, opts, recovery, startedAt } = child\n const { ownedTreeRoot, recoveryReady, controller, now } = start\n const askTeardown = singleFlightTeardown(executor, () => {\n live.teardownAttempts += 1\n })\n const live: LiveChild = {\n events: new WorkerEvents(\n args.interactiveBindingDir === undefined\n ? undefined\n : { runDir: args.interactiveBindingDir, nodeId: id, now },\n ),\n id,\n status: start.granted ? 'acquiring' : 'queued',\n runtime: executor.runtime,\n ...(ownedTreeRoot === undefined ? {} : { ownedTreeRoot }),\n ...(identity ? { identity } : {}),\n ...(modelSubstitution === undefined ? {} : { modelSubstitution }),\n budget: opts.budget,\n label: opts.label,\n ...(opts.assignmentId === undefined ? {} : { assignmentId: opts.assignmentId }),\n ...(opts.key !== undefined ? { key: opts.key } : {}),\n spent: zeroSpend(),\n traceRoots: start.traceRoots,\n settled: undefined as unknown as Promise<PreSeqSettled>,\n delivered: false,\n executorDone: false,\n cleanupConfirmed: false,\n ...(recovery ? { recoveryPending: true } : {}),\n ...(recoveryReady ? { recoveryReady } : {}),\n ...(recovery?.priorMaterialization ? { materialization: recovery.priorMaterialization } : {}),\n executionBindings: recovery\n ? (args.resumeFrom?.events ?? []).flatMap((event) =>\n event.kind === 'execution-bound' && event.id === id ? [event.binding] : [],\n )\n : [],\n startedAt,\n lastActivityAt: startedAt,\n ...(executor.deliver\n ? { deliver: (message: unknown): boolean => executor.deliver?.(message) !== false }\n : {}),\n ...(executor.progress ? { readProgress: executor.progress.bind(executor) } : {}),\n ...(executor.traceSource ? { readTraceSource: executor.traceSource.bind(executor) } : {}),\n ...(executor.interactive ? { readInteractive: executor.interactive.bind(executor) } : {}),\n ...(executor.interactiveReady\n ? { readInteractiveReady: executor.interactiveReady.bind(executor) }\n : {}),\n ...(executor.cancel ? { requestCancel: executor.cancel.bind(executor) } : {}),\n ...(executor.releaseRetained\n ? {\n releaseRetained: executor.releaseRetained.bind(executor),\n confirmTeardown: () =>\n teardownExecutor(executor, 'brutalKill', undefined, now, askTeardown),\n }\n : {}),\n askTeardown,\n ...(executor.heldEnvironments\n ? { readHeldEnvironments: executor.heldEnvironments.bind(executor) }\n : {}),\n ...(nestedTeardownScopes.has(executor)\n ? { readNestedScope: nestedTeardownScopes.get(executor)! }\n : {}),\n ...(executor.harnessTranscript\n ? {\n readTranscriptAtRelease: () =>\n persistHarnessTranscript(readHarnessTranscript(executor), args.blobs),\n }\n : {}),\n teardownAttempts: 0,\n abortChild: (reason?: unknown): void => controller.abort(reason),\n readEnvironmentAdmission: start.readEnvironmentAdmission,\n }\n return live\n}\n\n/** Keep the run-level cancellation reason that aborted a child before it produced a result. */\nexport function recordChildCancellation<C>(\n live: LiveChild,\n executor: Executor<C>,\n controller: AbortController,\n): void {\n const recordCancellation = (): void => {\n if (\n !live.executorDone &&\n live.acceptedResult === undefined &&\n executor.resultAccepted?.() !== true &&\n controller.signal.reason instanceof RunCancellationReason\n ) {\n live.cancellationReason = controller.signal.reason\n }\n }\n if (controller.signal.aborted) recordCancellation()\n else controller.signal.addEventListener('abort', recordCancellation, { once: true })\n}\n\n/**\n * Journal the spawn with the authored child profile itself: `identity.profileDigest` is not a blob\n * key (`FileResultBlobStore.put` asserts the key IS `contentAddress(artifact)`), so the event\n * carries the digest that names the agent and the ref that retrieves its bytes. The blob lands\n * BEFORE the event that names it; N children sharing a profile store one body.\n */\nexport function commitSpawnRecord<C>(\n args: ScopeArgs,\n child: AdmittedChild,\n executor: Executor<C>,\n ownedTreeRoot: NodeId | undefined,\n workerTrace: TraceContext | undefined,\n now: () => number,\n): Promise<void> {\n const { id, task, identity, ordinal, spec } = child\n const profileRef = contentAddress(spec.profile)\n const taskRef = identity?.taskDigest === undefined ? undefined : contentAddress(task)\n return args.blobs\n .put(profileRef, spec.profile)\n .then(() => (taskRef === undefined ? undefined : args.blobs.put(taskRef, task)))\n .then(async () => {\n // The spawn record and its execution input publish as ONE grouped record where supported, so\n // a crash never leaves a spawned node with unreferenced task bytes.\n const events: SpawnEvent[] = [\n spawnedEvent(args, child, executor, ownedTreeRoot, profileRef, now),\n ]\n if (taskRef !== undefined) {\n events.push({\n kind: 'execution-input',\n id,\n taskRef,\n seq: ordinal,\n at: new Date(now()).toISOString(),\n })\n }\n await appendSpawnEvents(args.journal, args.root, events)\n })\n .then(async () => {\n // The severed distributed-trace hop, journaled beside its spawn: the run records spans AND\n // resolved a context, but the backend has no channel to carry it, so the child's trace\n // surfaces as a disconnected root; this makes that a queryable fact.\n if (args.workerTraceUnpropagated === undefined || workerTrace === undefined) return\n await args.journal.appendEvent(args.root, {\n kind: 'trace-unpropagated',\n id,\n expectedTraceId: workerTrace.traceId,\n backend: args.workerTraceUnpropagated.backend,\n reason: args.workerTraceUnpropagated.reason,\n seq: ordinal,\n at: new Date(now()).toISOString(),\n })\n })\n}\n\nfunction spawnedEvent<C>(\n args: ScopeArgs,\n child: AdmittedChild,\n executor: Executor<C>,\n ownedTreeRoot: NodeId | undefined,\n profileRef: string,\n now: () => number,\n): SpawnEvent {\n const { id, opts, identity, successorOf, continuing, modelSubstitution } = child\n return {\n kind: 'spawned',\n id,\n parent: args.parentId,\n label: opts.label,\n ...(opts.key !== undefined ? { key: opts.key } : {}),\n ...(opts.assignmentId === undefined ? {} : { assignmentId: opts.assignmentId }),\n ...(successorOf === undefined ? {} : { successorOf }),\n ...(continuing === undefined\n ? {}\n : {\n continues: {\n ofWorker: continuing.from.id,\n environmentId: continuing.admission.environmentId,\n },\n }),\n budget: opts.budget,\n runtime: executor.runtime,\n ...(ownedTreeRoot === undefined ? {} : { ownedTreeRoot }),\n ...(identity ? { identity } : {}),\n profileRef,\n ...(modelSubstitution === undefined ? {} : { modelSubstitution }),\n seq: child.ordinal,\n at: new Date(now()).toISOString(),\n }\n}\n\n/** Announce a fresh child on the `agent.spawn` hook. */\nexport function notifyChildSpawned<C>(\n args: ScopeArgs,\n child: AdmittedChild,\n executor: Executor<C>,\n now: () => number,\n): void {\n const { id, opts, successorOf, identity, spec } = child\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${id}:spawn`,\n runId: args.root,\n target: 'agent.spawn',\n phase: 'after',\n timestamp: now(),\n stepIndex: child.ordinal,\n parentId: args.parentId,\n payload: {\n childId: id,\n label: opts.label,\n ...(opts.assignmentId === undefined ? {} : { assignmentId: opts.assignmentId }),\n ...(opts.key === undefined ? {} : { key: opts.key }),\n ...(successorOf === undefined ? {} : { successorOf }),\n runtime: executor.runtime,\n ...(identity ? { identity } : {}),\n // Who acted, for span observers: the authored profile under the digest the\n // journal recorded for this node.\n agent: authoredAgentIdentity(spec.profile, identity?.profileDigest),\n budget: opts.budget,\n depth: args.depth,\n attemptId: child.attemptId,\n startedAt: child.startedAt,\n },\n },\n { signal: args.signal },\n )\n}\n\n/** Past every refusal: the held environment belongs to the successor now, and the node it came\n * from holds nothing (its settlement and result stand). */\nexport function handOverContinuation(continuing: HeldContinuation): void {\n continuing.held.clearCeiling?.()\n continuing.held.continuation.handOver()\n continuing.from.held = undefined\n continuing.from.cleanupConfirmed = true\n}\n\n/** Persist the child's interactive-session binding once the spawn is committed and it is ready. */\nexport function bindInteractiveWorker(\n args: ScopeArgs,\n live: LiveChild,\n label: string,\n childRun: Promise<PreSeqSettled>,\n signal: AbortSignal,\n spawnCommitted: Promise<void>,\n now: () => number,\n): Promise<void> {\n return spawnCommitted.then(async () => {\n if (args.interactiveBindingDir === undefined) return\n const notStarted = (session: WorkerInteractiveSession): boolean =>\n session.status !== 'available' && session.reason === 'interactive-session-not-started'\n let session = readInteractiveSession(live)\n if (notStarted(session) && live.readInteractiveReady !== undefined) {\n const ready = await readInteractiveReadyUntilWorkerEnds(\n live.readInteractiveReady,\n childRun,\n signal,\n )\n if (ready === undefined || notStarted(ready)) return\n session = ready\n }\n writeWorkerInteractiveBinding(\n args.interactiveBindingDir,\n live.id,\n label,\n args.root,\n session,\n now,\n )\n })\n}\n\n/**\n * The child's settlement as the cursor reads it: the run's record with its trace root, downgraded\n * when the interactive binding could not persist, with a held environment timed or released.\n */\nexport async function resolveChildSettlement(\n live: LiveChild,\n ran: PreSeqSettled,\n interactiveBindingCommitted: Promise<void>,\n holdMs: number,\n releaseHeld: (child: LiveChild, reason: HeldRelease) => Promise<boolean>,\n): Promise<PreSeqSettled> {\n // Every settlement arm that cites an output this process stored cites its trace root.\n const traceRoot = await live.traceRoots.recorded(ran.outRef)\n const s: PreSeqSettled = traceRoot === undefined ? ran : { ...ran, traceRoot }\n let resolution = s\n try {\n await interactiveBindingCommitted\n } catch {\n resolution = {\n ...downRecord(\n 'interactive worker binding persistence failed',\n true,\n s.trace,\n s.metered,\n s.providerModel,\n s.outRef,\n // Re-wrapping a record the child already settled: its transcript receipt is\n // established evidence and a persistence failure here does not unmake it.\n s.harnessTranscript,\n ),\n ...(s.traceRoot === undefined ? {} : { traceRoot: s.traceRoot }),\n }\n }\n live.resolved = resolution\n if (live.held !== undefined) {\n if (resolution.kind === 'done') {\n const timer = setTimeout(() => void releaseHeld(live, 'hold-ceiling'), holdMs)\n timer.unref?.()\n live.held.clearCeiling = () => clearTimeout(timer)\n } else {\n await releaseHeld(live, 'scope-join')\n }\n }\n return resolution\n}\n","import { ValidationError } from '../../errors'\nimport type { LiveChild, ScopeArgs } from './scope-contract'\nimport type { NodeExecutionIdentity, NodeId, ResumedKeyState, Settled } from './types'\n\n/** One semantic key's current assignment state. */\nexport type ScopeKeyState<Out> = {\n readonly id: NodeId\n readonly identity: NodeExecutionIdentity\n} & (\n | { readonly state: 'live' | 'in-doubt' }\n | { readonly state: 'done'; readonly settled: Settled<Out> & { kind: 'done' } }\n | { readonly state: 'down'; readonly reason: string }\n)\n\n/**\n * The semantic-key registry (`SpawnOpts.key`): every keyed assignment's current state, seeded\n * from the prior journal on resume and updated live as keyed children spawn and settle. This is\n * what makes a keyed spawn idempotent per key across process lifetimes: `done` returns the\n * committed result, `live` refuses a concurrent duplicate, `down` retries after a terminal\n * receipt, and `in-doubt` refuses until the exact prior execution is recovered.\n */\nexport class ScopeKeyRegistry<Out> {\n private readonly keyed = new Map<string, ScopeKeyState<Out>>()\n\n constructor(\n resumeFrom: ScopeArgs['resumeFrom'],\n private readonly children: Map<NodeId, LiveChild>,\n ) {\n for (const [key, prior] of resumeFrom?.keys ?? []) {\n // A key the journal never gave an identity is not seeded.\n if (prior.identity !== undefined) this.keyed.set(key, resumedKeyState(prior, prior.identity))\n }\n }\n\n get(key: string): ScopeKeyState<Out> | undefined {\n return this.keyed.get(key)\n }\n\n markLive(key: string, id: NodeId, identity: NodeExecutionIdentity): void {\n this.keyed.set(key, { state: 'live', id, identity })\n }\n\n /** Fold a keyed child's terminal settlement back into the registry, so a later spawn with the\n * same key resolves to it (done → committed result; down → explicit retry). */\n readonly recordSettlement = (key: string, settled: Settled<Out>): void => {\n const identity = settled.handle.identity\n if (identity === undefined) {\n throw new ValidationError(`scope: keyed settlement '${key}' lost its execution identity`)\n }\n if (this.children.get(settled.handle.id)?.recoveryPending) {\n this.keyed.set(key, { state: 'in-doubt', id: settled.handle.id, identity })\n } else if (settled.kind === 'done') {\n this.keyed.set(key, { state: 'done', id: settled.handle.id, identity, settled })\n } else {\n this.keyed.set(key, {\n state: 'down',\n id: settled.handle.id,\n identity,\n reason: settled.reason,\n })\n }\n }\n}\n\n/** A journaled key's state on resume. */\nfunction resumedKeyState<Out>(\n prior: ResumedKeyState<unknown>,\n identity: NodeExecutionIdentity,\n): ScopeKeyState<Out> {\n if (prior.state === 'completed' && prior.settled?.kind === 'done') {\n return {\n state: 'done',\n id: prior.id,\n identity,\n settled: prior.settled as Settled<Out> & { kind: 'done' },\n }\n }\n if (prior.state === 'down' && (prior.settled?.kind === 'down' || prior.settled === undefined)) {\n // With no settlement the `down` is derived: the resume itself proved the attempt dead (an\n // `inline` runtime cannot outlive its process), and the derived reason is the evidence a\n // same-key re-spawn reports as `resumed: \"retried\"`.\n const reason =\n prior.settled?.kind === 'down'\n ? prior.settled.reason\n : (prior.reason ?? 'interrupted: resume proved the prior attempt dead')\n return { state: 'down', id: prior.id, identity, reason }\n }\n return { state: 'in-doubt', id: prior.id, identity }\n}\n","import { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport { zeroSpend } from '../util'\nimport type { ReservationShortfall, ReservationTicket } from './budget'\nimport { armDeadlineTimer, boundedChildDeadlineAt, CHILD_DEADLINE_REASON } from './deadline'\nimport { executableAgentSpecSnapshot } from './executable-spec'\nimport { newExecutionAttemptId } from './materialization'\nimport { withBudgetResources } from './resources'\nimport { BUDGET_CONTINUATION_TASK, type RetainedChildRecovery } from './retained-executor'\nimport { createChildMaterialization } from './scope-child-materialization'\nimport { createChildRetention } from './scope-child-retention'\nimport {\n type AdmittedChild,\n bindInteractiveWorker,\n childExecutorContext,\n childHandle,\n commitSpawnRecord,\n type HeldContinuation,\n handOverContinuation,\n liveChildRecord,\n notifyChildSpawned,\n recordChildCancellation,\n resolveChildSettlement,\n} from './scope-child-start'\nimport type { DeferredOwnerSlot, LiveChild, PreSeqSettled, ScopeArgs } from './scope-contract'\nimport { runChild } from './scope-execution'\nimport {\n deriveNodeExecutionIdentity,\n isAgentSpec,\n isCompleteIdentity,\n sameNodeExecutionIdentity,\n} from './scope-identity'\nimport { ScopeKeyRegistry } from './scope-key-registry'\nimport { detachedSnapshot } from './snapshot'\nimport { traceRootWriter } from './trace-root'\nimport { runtimeOwnedNestedDriverTreeRoot } from './tree-key'\nimport type {\n Agent,\n AgentSpec,\n Executor,\n ExecutorContext,\n Handle,\n HeldRelease,\n NodeExecutionIdentity,\n NodeId,\n Settled,\n SpawnOpts,\n SpawnPrior,\n SpawnRejection,\n} from './types'\nimport { deferSlot, type openSlotGroup, type SlotPermit, type WorkerSlots } from './worker-slots'\n\ninterface ScopeSpawnerDeps {\n args: ScopeArgs\n children: Map<NodeId, LiveChild>\n slotGroup: ReturnType<typeof openSlotGroup>\n workerSlots: WorkerSlots\n ownerFloor: { tokens: number; iterations: number; usd?: number } | undefined\n now: () => number\n isAdmissionClosed: () => boolean\n checkInAtTimeBox: (id: NodeId, controller: AbortController) => (() => void) | undefined\n releaseHeld: (child: LiveChild, reason: HeldRelease) => Promise<boolean>\n}\n\ntype SpawnResult<C> =\n | { ok: true; handle: Handle<C>; prior?: SpawnPrior<C> }\n | { ok: false; reason: SpawnRejection; shortfalls?: readonly ReservationShortfall[] }\n\n/** The agent a spawn runs, prepared far enough to compare its identity with the journal. */\ninterface PreparedAgent<C> {\n readonly agent: Agent<unknown, C>\n readonly spec: AgentSpec\n readonly identity: NodeExecutionIdentity | undefined\n}\n\n/** One spawn call in flight: its detached inputs and the agent once it is prepared. */\ninterface SpawnRequest<C> {\n readonly agentOrFactory: Agent<unknown, C> | (() => Agent<unknown, C>)\n readonly task: unknown\n readonly opts: SpawnOpts\n readonly recovery: RetainedChildRecovery | undefined\n prepared?: PreparedAgent<C>\n}\n\n/** What a keyed spawn resumes from: a retried down node, or a held over-budget environment. */\ninterface KeyedReuse<C> {\n readonly prior?: SpawnPrior<C>\n readonly continuing?: HeldContinuation\n}\n\n/** The executor factory admission resolved for a spawn. */\ninterface ResolvedExecutor<C> {\n readonly succeeded: true\n readonly value: (spec: AgentSpec, ctx: ExecutorContext) => Executor<C>\n}\n\n/** Cleanup a failed start must run for what it already armed. */\ninterface StartCleanup {\n cascadeAbort?: () => void\n clearChildDeadline?: () => void\n}\n\n/** Own child admission, keyed identity and executor startup. */\nexport function createScopeSpawner<Out>(deps: ScopeSpawnerDeps) {\n const spawner = new ScopeSpawner<Out>(deps)\n return { spawn: spawner.spawn, recordKeyedSettlement: spawner.keys.recordSettlement }\n}\n\nclass ScopeSpawner<Out> {\n readonly keys: ScopeKeyRegistry<Out>\n private spawnOrdinal: number\n private progressSeq = 0\n\n constructor(private readonly deps: ScopeSpawnerDeps) {\n this.keys = new ScopeKeyRegistry<Out>(deps.args.resumeFrom, deps.children)\n this.spawnOrdinal = deps.args.resumeFrom ? deps.args.resumeFrom.maxSpawnOrdinal + 1 : 0\n }\n\n readonly spawn = <C extends Out>(\n agentOrFactory: Agent<unknown, C> | (() => Agent<unknown, C>),\n rawTask: unknown,\n rawOpts: SpawnOpts,\n recovery?: RetainedChildRecovery,\n ): SpawnResult<C> => {\n const { args } = this.deps\n // Original recovery is bookkeeping: its child inherits this abort, so runChild invokes no work.\n if (args.signal.aborted && recovery === undefined) return { ok: false, reason: 'scope-aborted' }\n // The run reached its join barrier: no later child can be joined, released, or selected over.\n // Distinct from an abort — nothing cancelled this run (see `closeScopeAdmission`).\n if (this.deps.isAdmissionClosed()) return { ok: false, reason: 'scope-settled' }\n const request: SpawnRequest<C> = {\n agentOrFactory,\n task: detachedSnapshot(rawTask, 'scope.spawn task'),\n opts: detachedSnapshot(rawOpts, 'scope.spawn options'),\n recovery,\n }\n const reuse = this.resolveKeyedReuse(request)\n if ('ok' in reuse) return reuse\n if (recovery) this.assertRecoveryMatches(request, recovery)\n if (args.maxDepth !== undefined && args.depth >= args.maxDepth) {\n return { ok: false, reason: 'depth-exceeded' }\n }\n // A concrete child exposes its profile now, so parse and seal it before capacity or budget\n // admission. A lazy agent factory cannot reveal a profile without being constructed; preserve\n // the refusal invariant for those factories and validate the result immediately after the\n // reservation, before registry resolution or any executor code.\n if (typeof agentOrFactory !== 'function') prepareOnce(request)\n const reservation = this.reserve(request)\n if (!reservation.ok) {\n return {\n ok: false,\n reason: reservation.reason,\n ...(reservation.shortfalls === undefined ? {} : { shortfalls: reservation.shortfalls }),\n }\n }\n const resolved = this.resolveExecutorFactory(request, reservation.ticket)\n if (resolved === 'invalid-identity') return { ok: false, reason: 'invalid-identity' }\n // A recovered execution already runs remotely, so it takes a slot past the bound. A child\n // that waits for budget asks for its slot only once the budget is granted, so it never holds\n // a slot that the children it waits on need.\n const budgetGranted = reservation.granted\n const acquire = () =>\n this.deps.slotGroup.acquire(args.depth + 1, { force: recovery !== undefined })\n const permit = budgetGranted === undefined ? acquire() : deferSlot(budgetGranted, acquire)\n return this.start(request, reuse, reservation.ticket, budgetGranted, resolved, permit)\n }\n\n /**\n * A key is an identity claim, not a cache label. An in-doubt start has no terminal receipt, so\n * it refuses before touching a lazy factory; every other reuse compares the prepared agent's\n * identity with the journal. The completed path resolves, reserves and runs nothing.\n */\n private resolveKeyedReuse<C extends Out>(\n request: SpawnRequest<C>,\n ): KeyedReuse<C> | SpawnResult<C> {\n const { opts, recovery } = request\n if (opts.key === undefined) return {}\n const existing = this.keys.get(opts.key)\n if (existing?.state === 'in-doubt' && recovery?.spawned.id !== existing.id) {\n // No terminal receipt does not prove the remote execution stopped: no replacement beside it.\n return { ok: false, reason: 'in-doubt' }\n }\n if (existing === undefined) return {}\n const prepared = prepareOnce(request)\n if (!isCompleteIdentity(prepared.identity)) {\n return { ok: false, reason: 'invalid-identity' }\n }\n if (!sameNodeExecutionIdentity(existing.identity, prepared.identity)) {\n return { ok: false, reason: 'key-conflict' }\n }\n if (existing.state === 'live') return { ok: false, reason: 'duplicate-key' }\n if (existing.state === 'down') {\n return { prior: { state: 'retried', priorId: existing.id, reason: existing.reason } }\n }\n if (existing.state !== 'done') return {}\n // A result that ended over its budget, whose environment is still held, continues in a new\n // node when the caller asks for it; any other committed result is returned as it stands.\n const from = this.deps.children.get(existing.id)\n const admission =\n opts.continueHeld === true && existing.settled.budgetViolation !== undefined\n ? from?.held !== undefined\n ? from.readEnvironmentAdmission?.()\n : undefined\n : undefined\n if (from?.held === undefined || admission === undefined) {\n return {\n ok: true,\n handle: existing.settled.handle as Handle<C>,\n prior: {\n state: 'completed',\n settled: existing.settled as Settled<C> & { kind: 'done' },\n },\n }\n }\n return {\n continuing: { from, admission, held: from.held },\n prior: {\n state: 'continued',\n priorId: existing.id,\n environmentId: from.held.continuation.environmentId,\n },\n }\n }\n\n private assertRecoveryMatches<C extends Out>(\n request: SpawnRequest<C>,\n recovery: RetainedChildRecovery,\n ): void {\n const prepared = prepareOnce(request)\n if (\n recovery.spawned.parent !== this.deps.args.parentId ||\n this.deps.children.has(recovery.spawned.id) ||\n !prepared.identity ||\n !recovery.spawned.identity ||\n !sameNodeExecutionIdentity(prepared.identity, recovery.spawned.identity) ||\n contentAddress(request.opts.budget) !== contentAddress(recovery.spawned.budget)\n ) {\n throw new ValidationError('scope recovery does not match its original admitted child')\n }\n }\n\n /**\n * Reserve the child's whole ceiling atomically so Σk is conserved by construction. A ceiling\n * the pool could cover once this scope's running children return what they hold WAITS (the\n * child is admitted `queued`); it fails CLOSED when nothing running could free enough. This\n * runs before a lazy agent factory is called: refused work constructs nothing. The ticket is\n * named from the start (assignment now, node id at admission).\n */\n private reserve<C extends Out>({ opts, recovery }: SpawnRequest<C>) {\n const { args, ownerFloor } = this.deps\n const assignment = opts.assignmentId ?? opts.key\n return args.pool.reserve(\n opts.budget,\n {\n ...(assignment === undefined ? {} : { assignment }),\n label: opts.label,\n stage: 'admitted',\n },\n { wait: true, ...(!recovery && ownerFloor ? { keep: ownerFloor } : {}) },\n )\n }\n\n /**\n * Resolve the leaf executor through the open registry after budget admission. If preparation\n * fails, refund the reservation here because runChild never receives it.\n */\n private resolveExecutorFactory<C extends Out>(\n request: SpawnRequest<C>,\n ticket: ReservationTicket,\n ): ResolvedExecutor<C> | 'invalid-identity' {\n const { args } = this.deps\n const { opts, recovery } = request\n try {\n const { spec, identity } = prepareOnce(request)\n if (opts.key !== undefined && !isCompleteIdentity(identity)) {\n args.pool.reconcile(ticket, withBudgetResources(zeroSpend(), opts.budget, true))\n return 'invalid-identity'\n }\n const outcome = recovery\n ? {\n succeeded: true as const,\n value: recovery.factory as (spec: AgentSpec, ctx: ExecutorContext) => Executor<C>,\n }\n : args.executors.resolve<C>(spec)\n if (!outcome.succeeded) throw new ValidationError(`scope.spawn: ${outcome.error}`)\n return outcome\n } catch (error) {\n args.pool.reconcile(ticket, withBudgetResources(zeroSpend(), opts.budget, true))\n throw error\n }\n }\n\n /**\n * Everything between reserve and runChild's hand-off owns the reservation: a SYNCHRONOUS throw\n * (most likely the executor factory) would leak it, so it is released with zero spend and\n * rethrown, keeping `total ≡ free + reserved + committed`. runChild never sync-throws.\n */\n private start<C extends Out>(\n request: SpawnRequest<C>,\n reuse: KeyedReuse<C>,\n ticket: ReservationTicket,\n budgetGranted: Promise<void> | undefined,\n resolved: ResolvedExecutor<C>,\n permit: SlotPermit,\n ): SpawnResult<C> {\n const { args } = this.deps\n const cleanup: StartCleanup = {}\n try {\n return this.startChild(request, reuse, ticket, budgetGranted, resolved, permit, cleanup)\n } catch (err) {\n this.releaseStart(permit, cleanup)\n args.pool.reconcile(ticket, withBudgetResources(zeroSpend(), request.opts.budget, true))\n throw err\n }\n }\n\n private startChild<C extends Out>(\n request: SpawnRequest<C>,\n reuse: KeyedReuse<C>,\n ticket: ReservationTicket,\n budgetGranted: Promise<void> | undefined,\n resolved: ResolvedExecutor<C>,\n permit: SlotPermit,\n cleanup: StartCleanup,\n ): SpawnResult<C> {\n const { args, children, now } = this.deps\n const { recovery, opts } = request\n const child = this.admit(request, reuse, ticket)\n const { id, continuing } = child\n const controller = this.armChildAbort(child, cleanup)\n const deferredOwner: DeferredOwnerSlot = {}\n // Resolved per spawn: the spawning node's span is opened by the `agent.spawn` hook, so lazy\n // reading assumes no hook ordering. No resolver (untraced) means no seam.\n const workerTrace = args.workerTrace?.(args.parentId)\n const { recoveryReady, markRecoveryReady } = recoveryReadyGate(recovery, budgetGranted)\n // Built before the retained seam, which cites it before the live child exists.\n const traceRoots = traceRootWriter(args.blobs, id)\n const retention = createChildRetention({\n args,\n controller,\n id,\n ordinal: child.ordinal,\n identity: child.identity,\n recovery,\n opts,\n now,\n traceRoots,\n markRecoveryReady,\n childDeadlineAtMs: child.childDeadlineAtMs,\n readLive: () => live,\n completeEvidence: async () => materialization.complete(),\n })\n const ctx = childExecutorContext(args, child, controller, {\n workerSlots: this.deps.workerSlots,\n permit,\n deferredOwner,\n workerTrace,\n retainedContext: retention.retainedContext,\n now,\n })\n const executor = resolved.value(child.spec, ctx) as Executor<C>\n const ownedTreeRoot = runtimeOwnedNestedDriverTreeRoot(executor, args.root, id)\n if (\n recovery &&\n (!executor.recover ||\n executor.runtime !== recovery.spawned.runtime ||\n ownedTreeRoot !== recovery.spawned.ownedTreeRoot)\n ) {\n throw new ValidationError(\n 'scope recovery executor does not preserve its runtime, recovery method, or owned tree',\n )\n }\n const handle = childHandle<C>(child, children, controller)\n const live = liveChildRecord(args, child, executor, {\n granted: permit.granted,\n controller,\n ownedTreeRoot,\n traceRoots,\n recoveryReady,\n readEnvironmentAdmission: retention.readEnvironmentAdmission,\n now,\n })\n recordChildCancellation(live, executor, controller)\n children.set(id, live)\n if (opts.key !== undefined) {\n this.keys.markLive(opts.key, id, child.identity as NodeExecutionIdentity)\n }\n const spawnCommitted = recovery\n ? Promise.resolve()\n : commitSpawnRecord(args, child, executor, ownedTreeRoot, workerTrace, now)\n const materialization = createChildMaterialization({\n args,\n spawnCommitted,\n identity: child.identity,\n spec: child.spec,\n executor,\n deferredOwner,\n attemptId: child.attemptId,\n id,\n recovery,\n live,\n ordinal: child.ordinal,\n now,\n })\n if (!recovery) notifyChildSpawned(args, child, executor, now)\n if (continuing !== undefined) handOverContinuation(continuing)\n\n // A thrown executor (or a real abort) is TYPED into a `down` record by `runChild`, never\n // re-thrown, so one failing child never rejects the cursor.\n const childRun = runChild(\n live,\n executor,\n controller,\n // A recovered continuation replays its own invocation's task, and a keyed continuation\n // tells the held session to go on; the spawn identity above stays the node's original task.\n recovery?.continuation?.task ??\n (continuing === undefined ? request.task : BUDGET_CONTINUATION_TASK),\n opts,\n args.pool,\n ticket,\n args.blobs,\n now,\n args.journal,\n args.root,\n () => this.progressSeq++,\n materialization.ready,\n {\n complete: async () => materialization.complete(),\n fail: async () => materialization.fail(),\n },\n child.childDeadlineAtMs,\n recovery !== undefined,\n retention.closeRetainedWrites,\n budgetGranted,\n permit.ready,\n args.signal.aborted && recovery !== undefined\n ? (args.resumeFrom?.events\n ?.flatMap((event) =>\n event.id === id && event.kind === 'reconciled' ? [event.spent] : [],\n )\n .at(-1) ?? recovery.continuation?.priorSpent)\n : recovery?.continuation?.priorSpent,\n child.startedAt,\n )\n // `runChild` owns the ticket from here: a leak at the join barrier is a child that never settled.\n args.pool.attribute(ticket, { stage: 'executing' })\n const interactiveBindingCommitted = bindInteractiveWorker(\n args,\n live,\n opts.label,\n childRun,\n controller.signal,\n spawnCommitted,\n now,\n )\n this.trackSettlement(\n live,\n childRun,\n interactiveBindingCommitted,\n retention.holdMs,\n permit,\n cleanup,\n )\n return { ok: true, handle, ...(reuse.prior ? { prior: reuse.prior } : {}) }\n }\n\n /** Publish the child's settlement for the cursor, freeing its slot and timers once it ends. */\n private trackSettlement(\n live: LiveChild,\n childRun: Promise<PreSeqSettled>,\n interactiveBindingCommitted: Promise<void>,\n holdMs: number,\n permit: SlotPermit,\n cleanup: StartCleanup,\n ): void {\n const settled = childRun\n .then((ran) =>\n resolveChildSettlement(\n live,\n ran,\n interactiveBindingCommitted,\n holdMs,\n this.deps.releaseHeld,\n ),\n )\n .finally(() => {\n // The worker slot bounds agents that are SIMULTANEOUSLY WORKING, and a settled child is\n // not working. Gating the release on proof of destruction held a slot forever for every\n // retained execution (its executor answers `destroyed: false` while reconciliation is\n // pending): 127 of 177 children across 14 pursuits, until `max-live-workers`\n // refused with `live: 16, freeSlots: 0` while 1 child ran (#1183). The unconfirmed-cleanup\n // fact stays on `live.cleanupConfirmed`, `scope.workerCapacity.unconfirmed`, the\n // `teardown-unconfirmed` journal event and `result.teardownUnconfirmed`.\n this.releaseStart(permit, cleanup)\n })\n // Persistence may fail before a cursor starts awaiting this child.\n void settled.catch(() => undefined)\n ;(live as { settled: Promise<PreSeqSettled> }).settled = settled\n }\n\n /** Free what a start armed: its worker slot, its deadline watch, and its abort cascade. */\n private releaseStart(permit: SlotPermit, cleanup: StartCleanup): void {\n permit.release()\n cleanup.clearChildDeadline?.()\n if (cleanup.cascadeAbort) {\n this.deps.args.signal.removeEventListener('abort', cleanup.cascadeAbort)\n }\n }\n\n /** Name the admitted child: its node id, attempt, start time and bounded deadline. */\n private admit<C extends Out>(\n request: SpawnRequest<C>,\n reuse: KeyedReuse<C>,\n ticket: ReservationTicket,\n ): AdmittedChild {\n const { args, now } = this.deps\n const { recovery, opts } = request\n const { spec, identity } = request.prepared as PreparedAgent<C>\n const ordinal = recovery?.spawned.seq ?? this.spawnOrdinal++\n const id: NodeId = recovery?.spawned.id ?? `${args.parentId}:s${ordinal}`\n const successorOf = opts.successorOf ?? reuse.continuing?.from.id\n args.pool.attribute(ticket, { childId: id, stage: 'admitted' })\n const attemptId = newExecutionAttemptId(id)\n const startedAt = recovery ? Date.parse(recovery.spawned.at) : now()\n if (!Number.isFinite(startedAt))\n throw new ValidationError('scope recovery has an invalid original start time')\n return {\n id,\n ordinal,\n attemptId,\n startedAt,\n childDeadlineAtMs: boundedChildDeadlineAt(\n args.pool.readout().deadlineMs,\n opts.budget.deadlineMs,\n startedAt,\n ),\n successorOf,\n task: request.task,\n opts,\n spec,\n identity,\n modelSubstitution: recovery ? recovery.spawned.modelSubstitution : spec.modelSubstitution,\n recovery,\n continuing: reuse.continuing,\n }\n }\n\n /**\n * The child's abort chains off this scope's signal AND its own handle.abort() or bounded\n * deadline; aborting mid-acquire cascades into acquireSandbox's find-by-name reap.\n */\n private armChildAbort(child: AdmittedChild, cleanup: StartCleanup): AbortController {\n const { args, now } = this.deps\n const { id, childDeadlineAtMs } = child\n const controller = new AbortController()\n cleanup.cascadeAbort = () => controller.abort(args.signal.reason)\n if (args.signal.aborted) controller.abort(args.signal.reason)\n else args.signal.addEventListener('abort', cleanup.cascadeAbort, { once: true })\n if (childDeadlineAtMs !== undefined) {\n // The run's own deadline (a root scope's pool cutoff) stops the child; any shorter cutoff\n // is a time box its lead set, which is a check-in for a child that can be told.\n const runDeadlineAtMs = args.depth === 0 ? args.pool.readout().deadlineMs : 0\n const timeBox = !(runDeadlineAtMs > 0 && childDeadlineAtMs >= runDeadlineAtMs)\n let clearCheckIn: (() => void) | undefined\n const clearTimer = armDeadlineTimer(Math.max(0, childDeadlineAtMs - now()), () => {\n clearCheckIn = timeBox ? this.deps.checkInAtTimeBox(id, controller) : undefined\n if (clearCheckIn === undefined) controller.abort(CHILD_DEADLINE_REASON)\n })\n cleanup.clearChildDeadline = () => {\n clearTimer()\n clearCheckIn?.()\n }\n }\n return controller\n }\n}\n\n/**\n * The barrier a recovered owner's nested mount opens. A budget-queued recovery is already\n * represented by its child handle, and waiting for its mount here can deadlock a funded sibling\n * that needs its parent.\n */\nfunction recoveryReadyGate(\n recovery: RetainedChildRecovery | undefined,\n budgetGranted: Promise<void> | undefined,\n): { recoveryReady?: Promise<void>; markRecoveryReady?: () => void } {\n if (recovery?.spawned.ownedTreeRoot === undefined || budgetGranted !== undefined) return {}\n let markRecoveryReady: (() => void) | undefined\n const recoveryReady = new Promise<void>((resolve) => {\n markRecoveryReady = resolve\n })\n return { recoveryReady, markRecoveryReady }\n}\n\n/** Prepare the requested agent once: construct a lazy factory and seal its executable spec. */\nfunction prepareOnce<C>(request: SpawnRequest<C>): PreparedAgent<C> {\n if (request.prepared !== undefined) return request.prepared\n const { agentOrFactory } = request\n const agent = typeof agentOrFactory === 'function' ? agentOrFactory() : agentOrFactory\n const rawSpec = (agent as unknown as { executorSpec?: unknown }).executorSpec\n if (!isAgentSpec(rawSpec)) {\n throw new ValidationError(\n `scope.spawn: agent \"${agent.name}\" exposes no \\`executorSpec\\` (AgentSpec) to resolve a Executor`,\n )\n }\n const spec = executableAgentSpecSnapshot(rawSpec, 'scope.spawn')\n request.prepared = { agent, spec, identity: deriveNodeExecutionIdentity(spec, request.task) }\n return request.prepared\n}\n","import { closesCursorSlot } from '../../durable/spawn-journal/event-index'\nimport { ValidationError } from '../../errors'\nimport { notifyRuntimeHookEvent } from '../../runtime-hooks'\nimport { errMessage } from './error-message'\nimport { isTerminalNodeStatus } from './node-status'\nimport { retainedOwnerReleaseRetriable } from './retained-scope-owner'\nimport {\n closeRetainedSlots,\n hasRetriableTeardowns,\n nestedManagerScopeReaders,\n RETAINED_RELEASE_TIMEOUT_MS,\n retainedReleasers,\n retainedSlotClosers,\n retryUnconfirmedTeardowns,\n teardownRetriable,\n teardownRetriers,\n unconfirmedTeardowns,\n} from './scope-capabilities'\nimport type { LiveChild, ScopeArgs } from './scope-contract'\nimport { appendEnvironmentTeardown } from './scope-settlement'\nimport { releasedChildPayload, terminalDownEvent } from './terminal-record'\nimport type {\n EnvironmentTeardownReceipt,\n HeldRelease,\n NodeId,\n RetainedExecutionState,\n Scope,\n SpawnEvent,\n} from './types'\n\n/** Release settled child environments and close their retained journal slots. */\nexport function createHeldChildRelease(args: ScopeArgs, now: () => number) {\n // In flight, so the join barrier waits for a ceiling or cancel release that already started.\n const heldReleases = new Set<Promise<boolean>>()\n /** Release the environment a settled child holds after a budget stop, once, and journal why. */\n function releaseHeld(child: LiveChild, reason: HeldRelease): Promise<boolean> {\n const held = child.held\n if (held === undefined) return Promise.resolve(false)\n child.held = undefined\n held.clearCeiling?.()\n const release = (async () => {\n const answer = await held.continuation\n .release()\n .catch((error: unknown) => ({ destroyed: false, detail: errMessage(error) }))\n if (answer.destroyed) child.cleanupConfirmed = true\n else if (answer.detail !== undefined) child.teardownDetail = answer.detail\n await appendEnvironmentTeardown(\n args.journal,\n args.root,\n child.id,\n {\n provider: held.continuation.provider,\n environmentId: held.continuation.environmentId,\n destroyed: answer.destroyed,\n ...(answer.detail === undefined ? {} : { detail: answer.detail }),\n },\n new Date(now()).toISOString(),\n reason,\n ).catch(() => undefined)\n return true\n })()\n heldReleases.add(release)\n void release.finally(() => heldReleases.delete(release))\n return release\n }\n\n return { releaseHeld, heldReleases }\n}\n\nexport function bindChildTeardown<Out>(\n scope: Scope<Out>,\n args: ScopeArgs,\n children: Map<NodeId, LiveChild>,\n now: () => number,\n): void {\n // Settled children whose cleanup is unconfirmed because they hold a retained execution\n // themselves, or because a nested manager's descendants do: what a retained release reaches.\n const retainedHeld = (): LiveChild[] =>\n [...children.values()].filter(\n (child) =>\n isTerminalNodeStatus(child.status) &&\n !child.cleanupConfirmed &&\n (child.recoveryPending === true || child.ownedTreeRoot !== undefined) &&\n child.teardownPermanent !== true &&\n child.releaseRetained !== undefined &&\n child.confirmTeardown !== undefined,\n )\n // The children one settlement retry pass re-asks: settled, teardown unconfirmed, and not a\n // retained execution (its executor answers `destroyed: false` by construction while a resume may\n // still reconcile it; its release is `retainedReleasers`' job). A nested manager whose only\n // unconfirmed descendants are such retained executions is skipped for the same reason: asking\n // it again cannot change its answer.\n const retriableTeardowns = (): LiveChild[] =>\n [...children.values()].filter((child) => {\n if (\n !isTerminalNodeStatus(child.status) ||\n child.cleanupConfirmed ||\n child.recoveryPending === true ||\n child.teardownPermanent === true ||\n child.askTeardown === undefined\n ) {\n return false\n }\n const nested = child.readNestedScope?.()\n return (\n nested === undefined ||\n unconfirmedTeardowns(nested).length === 0 ||\n hasRetriableTeardowns(nested, false)\n )\n })\n // Of those a release reaches, the ones another release could still change: a retained\n // execution, or a manager whose own tree still holds something a release or retry can change.\n const releasable = (): LiveChild[] =>\n retainedHeld().filter((child) => {\n const nested = child.readNestedScope?.()\n return (\n child.ownedTreeRoot === undefined ||\n nested === undefined ||\n hasRetriableTeardowns(nested, true)\n )\n })\n teardownRetriable.set(\n scope,\n (release) =>\n retriableTeardowns().length > 0 ||\n (release && (releasable().length > 0 || retainedOwnerReleaseRetriable(scope))),\n )\n nestedManagerScopeReaders.set(scope, () =>\n [...children.values()].flatMap((child) => {\n const nested = child.readNestedScope?.()\n return nested === undefined ? [] : [nested]\n }),\n )\n teardownRetriers.set(scope, async () => {\n await Promise.all(\n retriableTeardowns().map((child) => {\n child.teardownRetry ??= (async () => {\n try {\n // Descendants first: a manager's teardown confirms only once its own tree has.\n const nested = child.readNestedScope?.()\n if (nested !== undefined) await retryUnconfirmedTeardowns(nested)\n // A settlement request that missed its acknowledgement window is still this child's\n // request in flight; the asker hands it back rather than sending another beside it.\n const receipt = await child.askTeardown!('brutalKill')\n if (receipt.destroyed) {\n child.cleanupConfirmed = true\n child.teardownDetail = undefined\n } else {\n child.teardownDetail = `executor teardown reported destroyed=false${\n receipt.detail ? `: ${receipt.detail}` : ''\n }`\n if (receipt.permanent === true) child.teardownPermanent = true\n }\n } catch (error) {\n child.teardownDetail = errMessage(error)\n } finally {\n child.teardownRetry = undefined\n }\n })()\n return child.teardownRetry\n }),\n )\n })\n retainedReleasers.set(scope, async () => {\n // Any other unconfirmed child (a destroy that failed on the ordinary path) is retried by\n // `teardownRetriers`, not here.\n const held = retainedHeld()\n const released = await Promise.all(\n held.map(\n async (\n child,\n ): Promise<{ child: LiveChild; receipts: ReadonlyArray<EnvironmentTeardownReceipt> }> => {\n const bound = new AbortController()\n const timer = setTimeout(\n () =>\n bound.abort(\n new ValidationError(\n `retained release did not acknowledge within ${RETAINED_RELEASE_TIMEOUT_MS}ms`,\n ),\n ),\n RETAINED_RELEASE_TIMEOUT_MS,\n )\n timer.unref?.()\n try {\n const receipts = await child.releaseRetained!(bound.signal)\n // An environment the executor keeps on purpose, or cannot destroy, is not released by\n // asking again.\n if (receipts.some((receipt) => !receipt.destroyed && receipt.permanent === true)) {\n child.teardownPermanent = true\n }\n if (receipts.every((receipt) => receipt.destroyed)) {\n try {\n await child.confirmTeardown!()\n child.cleanupConfirmed = true\n } catch {\n // Still unconfirmed; the barrier names the node as it did before. A leaf that\n // named no environment to release has nothing a later release could destroy.\n if (receipts.length === 0 && child.ownedTreeRoot === undefined) {\n child.teardownPermanent = true\n }\n }\n }\n return { child, receipts }\n } catch {\n // The executor answered with no receipt at all. Nothing can be named, so the node\n // stays unconfirmed rather than being receipted as released.\n return { child, receipts: [] }\n } finally {\n clearTimeout(timer)\n }\n },\n ),\n )\n // One tree read for the whole sweep: the duplicate guard below only needs the records that\n // existed before it, and a 35-child release must not cost 35 full-tree reads.\n const prior = released.length > 0 ? ((await args.journal.loadTree(args.root)) ?? []) : []\n for (const { child, receipts } of released) {\n for (const receipt of receipts) {\n await appendEnvironmentTeardown(\n args.journal,\n args.root,\n child.id,\n receipt,\n new Date(now()).toISOString(),\n )\n }\n // A retained-pending child whose environment is now gone can never be recovered, so its\n // cursor slot closes here with the settlement the driver already received, under the seq\n // `next()` stamped on it. 0 of 35 reconciled children on one pursuit\n // ever settled, and 185 of 223 lost sandbox children across 385 runs stopped at\n // `reconciled` — every one read as `never-settled` and charged its ceiling by every\n // journal reader although the pool had committed the floor. The gate is the same\n // `cleanupConfirmed` the barrier reads: a `destroyed: false` receipt, an executor throw, an\n // environment-less `[]` answer or a refused `confirmTeardown` do not make a release, because\n // the environment may still exist and `[].every` would otherwise close it vacuously; the\n // final close (`closeRetainedSlots`) states those as `'release-unconfirmed'` once no retry\n // is left. A crash between the last receipt and this record no longer strands the slot:\n // the reconciled record carries this settlement and the cursor seq, and `healReleasedSlots`\n // (recover-executors.ts) writes this same record from it on the next resume, under the\n // same seq. A manager settled on the ordinary path already has its record and never\n // passes `recoveryPending`.\n if (child.cleanupConfirmed) await closeRetainedSlot(child, 'released', prior)\n }\n })\n // One writer for the record that closes a retained child's slot, in either state, so the\n // released record and the unconfirmed one can never disagree on a field.\n const closeRetainedSlot = async (\n child: LiveChild,\n state: Exclude<RetainedExecutionState, 'pending'>,\n prior: ReadonlyArray<SpawnEvent>,\n ): Promise<void> => {\n if (\n child.recoveryPending !== true ||\n child.resolved?.kind !== 'down' ||\n child.settledSeq === undefined ||\n child.settledAt === undefined ||\n child.retainedExecution === 'released' ||\n child.retainedExecution === 'release-unconfirmed' ||\n prior.some((event) => event.id === child.id && closesCursorSlot(event))\n ) {\n return\n }\n child.budgetViolation = child.retainedViolation\n const settledAt = child.settledAt\n // The record restates the driver's settlement, with one exception: a session the release read\n // after the failure path could not. Only an available receipt replaces the earlier one.\n let settlement = child.resolved\n if (settlement.harnessTranscript?.status !== 'available' && child.readTranscriptAtRelease) {\n const atRelease = await child.readTranscriptAtRelease()\n if (atRelease.status === 'available')\n settlement = { ...settlement, harnessTranscript: atRelease }\n }\n await args.journal.appendEvent(\n args.root,\n terminalDownEvent(\n child,\n settlement,\n child.settledSeq,\n new Date(settledAt).toISOString(),\n state,\n ),\n )\n child.retainedExecution = state\n const closedAt = now()\n // A second `agent.child` for one node is already how a live-recovered child flips\n // down→done, so the projection folds this in observed order; `settledAt` stays the\n // settlement instant and `metered` is omitted so the driver's inference is not summed twice.\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${child.id}:${state}`,\n runId: args.root,\n target: 'agent.child',\n phase: 'after',\n timestamp: closedAt,\n stepIndex: child.settledSeq,\n parentId: args.parentId,\n payload: releasedChildPayload(child, settlement, settledAt, closedAt, state),\n },\n { signal: args.signal },\n )\n }\n retainedSlotClosers.set(scope, async () => {\n // Descendants first, in their own trees: a nested manager's retained children close where its\n // scope journals them, whether the manager itself settled or is retained too.\n for (const child of children.values()) {\n const nested = child.readNestedScope?.()\n if (nested !== undefined) await closeRetainedSlots(nested)\n }\n // A confirmed release is the sweep's to record, and after a crash the resume heal's, so this\n // pass writes only the unconfirmed state and never a second `released` record. It does not\n // read `cleanupConfirmed`: a nested manager that settled retained-pending reports its teardown\n // confirmed while its owner environment is held, so the sweep skipped it and the slot stayed\n // open for good. 38 of 38 such directors over 45 runs, 0 closed.\n const open = [...children.values()].filter(\n (child) =>\n child.recoveryPending === true &&\n isTerminalNodeStatus(child.status) &&\n child.retainedExecution !== 'released' &&\n child.retainedExecution !== 'release-unconfirmed',\n )\n if (open.length === 0) return\n const prior = (await args.journal.loadTree(args.root)) ?? []\n for (const child of open) await closeRetainedSlot(child, 'release-unconfirmed', prior)\n })\n}\n","import { ValidationError } from '../../errors'\nimport { RunCancellationReason } from './abortable'\nimport { CHILD_DEADLINE_REASON, checkInIdleMs, DEADLINE_CHECK_IN_MESSAGE } from './deadline'\nimport { isTerminalNodeStatus } from './node-status'\nimport {\n DEFAULT_STALL_AFTER_MS,\n type ExecutorProgress,\n readWorkerProgress,\n type WorkerProgress,\n} from './progress'\nimport { addResourceSpend } from './resources'\nimport type { LiveChild, ScopeArgs } from './scope-contract'\nimport {\n liveTeamOf,\n makeTreeView,\n noInteractiveSession,\n readInteractiveSession,\n teamProgress,\n} from './scope-observation'\nimport type { TraceSource } from './trace-source'\nimport type {\n ExecutorCancellation,\n ExecutorCancellationRequest,\n NodeId,\n TreeView,\n WorkerInteractiveSession,\n} from './types'\nimport type { WorkerEventCursor, WorkerEventPage } from './worker-events'\nimport { writeWorkerInteractiveBinding } from './worker-interactive'\n\n/**\n * A scope's live children as its driver addresses them: steer, read progress, cancel, read the\n * trace and interactive session, and observe the tree and event streams, nested scopes included.\n */\nexport class ScopeWorkers {\n constructor(\n private readonly args: ScopeArgs,\n private readonly children: Map<NodeId, LiveChild>,\n private readonly now: () => number,\n ) {}\n\n /**\n * A child's own time box: tell it to save state and submit what it has, and keep it running\n * while it progresses (`deadline.ts` `DeadlineCheckIn`). Returns the watch's stop, or undefined\n * when the child cannot be told (no inbox, settled, or check-ins off), and the caller stops it.\n */\n readonly checkInAtTimeBox = (\n nodeId: NodeId,\n controller: AbortController,\n ): (() => void) | undefined => {\n const idleMs = checkInIdleMs(this.args.deadlineCheckIn)\n if (idleMs === undefined || controller.signal.aborted) return undefined\n if (!this.send(nodeId, { steer: DEADLINE_CHECK_IN_MESSAGE, interrupt: false })) return undefined\n const watch = setInterval(\n () => {\n const read = this.progress(nodeId, { stallAfterMs: idleMs })\n if (read === undefined || !read.live || controller.signal.aborted) {\n clearInterval(watch)\n return\n }\n if (read.stalled) {\n clearInterval(watch)\n controller.abort(CHILD_DEADLINE_REASON)\n }\n },\n Math.min(idleMs, 60_000),\n )\n if (typeof watch.unref === 'function') watch.unref()\n return () => clearInterval(watch)\n }\n\n readonly send = (nodeId: NodeId, msg: unknown): boolean => {\n if (this.args.signal.aborted) return false\n const child = this.children.get(nodeId)\n // Only a LIVE child whose executor accepts an inbox can be steered.\n if (!child || child.delivered || !child.deliver) return false\n const accepted = child.deliver(msg) !== false\n if (!accepted) return false\n // A delivered steer IS activity: it resets the idle clock so the worker is not re-steered before it can act.\n child.lastActivityAt = this.now()\n return true\n }\n\n readonly progress = (\n nodeId: NodeId,\n opts: { now?: number; stallAfterMs?: number } = {},\n ): WorkerProgress | undefined => {\n const child = this.children.get(nodeId)\n if (!child) return undefined\n // Best-effort enrichment on a live path: a throwing progress implementation must not break observation.\n let fromExecutor: ExecutorProgress | undefined\n try {\n fromExecutor = child.readProgress?.()\n } catch {\n fromExecutor = undefined\n }\n // A manager child reports no usage until it settles; without its team the lead would read it idle, then stalled.\n const team = liveTeamOf(child)\n return readWorkerProgress(\n {\n id: child.id,\n status: child.status,\n steerable: child.deliver !== undefined && !child.delivered,\n startedAt: child.startedAt,\n lastActivityAt: Math.max(child.lastActivityAt, team?.lastActivityAt ?? 0),\n ...addResourceSpend(child.spent.resources),\n turns: Math.max(child.spent.iterations, team?.ownerTurns ?? 0),\n ...(team && team.agents > 0 ? { team: teamProgress(team) } : {}),\n tokens: child.spent.tokens,\n ...(child.spent.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: child.spent.usd,\n ...(child.spent.usdKnown === false ? { usdKnown: false } : {}),\n },\n fromExecutor,\n opts.now ?? this.now(),\n opts.stallAfterMs ?? DEFAULT_STALL_AFTER_MS,\n )\n }\n\n readonly cancel = async (\n nodeId: NodeId,\n request: ExecutorCancellationRequest,\n ): Promise<ExecutorCancellation> => {\n const child = this.children.get(nodeId)\n if (!child) {\n throw new ValidationError(`scope.cancel: unknown node ${JSON.stringify(nodeId)}`)\n }\n if (child.requestCancel) return await child.requestCancel(request)\n // No backend operation exists for this runtime. Abort the child locally and say exactly that,\n // so a caller never reads a local abort as provider acceptance.\n child.abortChild(new RunCancellationReason('scope', 'cancelled'))\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt: new Date().toISOString(),\n detail: `executor runtime ${JSON.stringify(child.runtime ?? 'unknown')} exposes no cancellation operation; the child was aborted locally`,\n }\n }\n\n readonly traceSource = (nodeId: NodeId): TraceSource | undefined => {\n const child = this.children.get(nodeId)\n if (!child) return undefined\n try {\n return child.readTraceSource?.()\n } catch {\n return undefined\n }\n }\n\n readonly interactive = (nodeId: NodeId): WorkerInteractiveSession => {\n const child = this.children.get(nodeId)\n if (!child) return noInteractiveSession('unknown-node')\n // A settled child holds no process.\n if (child.executorDone || isTerminalNodeStatus(child.status)) {\n return noInteractiveSession('not-live')\n }\n const session = readInteractiveSession(child)\n if (this.args.interactiveBindingDir !== undefined && session.status === 'available') {\n writeWorkerInteractiveBinding(\n this.args.interactiveBindingDir,\n child.id,\n child.label,\n this.args.root,\n session,\n this.now,\n )\n }\n return session\n }\n\n /** The whole subtree: replayed nodes, then this scope's children, then nested scopes' nodes. */\n readonly observeTree = (): TreeView => {\n const { args, children } = this\n const view = makeTreeView(args.parentId, children)\n const nodes = new Map((args.resumeFrom?.view.nodes ?? []).map((node) => [node.id, node]))\n for (const node of view.nodes) nodes.set(node.id, node)\n for (const child of children.values()) {\n const nested = child.readNestedScope?.()\n if (nested)\n for (const node of (nested.observeTree?.() ?? nested.view).nodes) nodes.set(node.id, node)\n }\n const all = [...nodes.values()]\n return {\n root: view.root,\n nodes: all,\n inFlight: all.filter((node) => ['queued', 'acquiring', 'running'].includes(node.status))\n .length,\n }\n }\n\n readonly observeEvents = (nodeId: NodeId, cursor?: WorkerEventCursor): WorkerEventPage => {\n const { args, children } = this\n const child = children.get(nodeId)\n if (child) return child.events.read(cursor)\n for (const candidate of children.values()) {\n const nested = candidate.readNestedScope?.()\n const page = nested?.observeEvents?.(nodeId, cursor)\n if (page && (page.status === 'available' || page.reason !== 'unknown-worker')) return page\n }\n return {\n status: 'unavailable',\n reason: args.resumeFrom?.view.nodes.some((node) => node.id === nodeId)\n ? 'not-captured'\n : 'unknown-worker',\n }\n }\n}\n","import { ValidationError } from '../../errors'\nimport { checkInIdleMs } from './deadline'\nimport { freeSlots } from './dispatch'\nimport { errorText } from './error-message'\nimport { isTerminalNodeStatus } from './node-status'\nimport { owners } from './retained-owner-state'\nimport {\n bindScopeRetainedOwnerWorkspaceRetention,\n registerScopeRetainedOwner,\n retainedOwnerWorkspaceRetentionSeamKey,\n} from './retained-scope-owner'\nimport {\n admissionSeals,\n barrenPauseRecorders,\n childDrains,\n driverAttemptRecorders,\n heldReleasers,\n liveTeamReaders,\n pauseRecorders,\n recoveryStarters,\n releasingScopes,\n runtimeOwnedProviderMeters,\n subtreeReaders,\n unconfirmedTeardownOf,\n waitForScopeChildren,\n} from './scope-capabilities'\nimport type { LiveChild, ScopeArgs } from './scope-contract'\nimport { assertRecursiveReservationPolicy } from './scope-identity'\nimport { makeTreeView, readLiveTeam, reenteredWorkers, summarizeTeam } from './scope-observation'\nimport {\n bindScopeOwnerMaterialization,\n ownerMaterializationStates,\n} from './scope-owner-materialization'\nimport { ScopeOwnerMeter } from './scope-owner-meter'\nimport { ScopeSettlementCursor } from './scope-settlement-cursor'\nimport { createScopeSpawner } from './scope-spawn'\nimport { bindChildTeardown, createHeldChildRelease } from './scope-teardown'\nimport { ScopeWorkers } from './scope-workers'\nimport type { NodeId, ResumedKeyState, ResumedWork, Scope, Settled, TreeView } from './types'\nimport { createWorkerSlots, openSlotGroup } from './worker-slots'\n\n/** Create the reactive `Scope` a driver's `Agent.act` runs inside: spawn children on an atomically reserved conserved budget, settle via the `next()` cursor, journal for replay. */\nexport function createScope<Out>(args: ScopeArgs): Scope<Out> {\n if (args.depth === 0) args = { ...args, rootDeadlineAtMs: args.pool.readout().deadlineMs }\n checkInIdleMs(args.deadlineCheckIn)\n const children = new Map<NodeId, LiveChild>()\n let admissionClosed = false\n const workerSlots = args.workerSlots ?? createWorkerSlots()\n const slotGroup = openSlotGroup(workerSlots, args.slotOwner)\n const ownerFloor = reservationOwnerFloor(args)\n const now = args.now ?? Date.now\n const workers = new ScopeWorkers(args, children, now)\n const meter = new ScopeOwnerMeter(args, now)\n const { releaseHeld, heldReleases } = createHeldChildRelease(args, now)\n const { spawn, recordKeyedSettlement } = createScopeSpawner<Out>({\n args,\n children,\n slotGroup,\n workerSlots,\n ownerFloor,\n now,\n isAdmissionClosed: () => admissionClosed,\n checkInAtTimeBox: workers.checkInAtTimeBox,\n releaseHeld,\n })\n const cursor = new ScopeSettlementCursor<Out>(args, children, now, recordKeyedSettlement)\n\n // Replayed committed work, frozen at construction: a resume-aware `act` skips settled children.\n const resume: ResumedWork<Out> | undefined = args.resumeFrom\n ? {\n settled: args.resumeFrom.settled as ReadonlyArray<Settled<Out>>,\n view: args.resumeFrom.view,\n keys: args.resumeFrom.keys as ReadonlyMap<string, ResumedKeyState<Out>>,\n priorSpend: args.resumeFrom.priorSpend,\n reentered: reenteredWorkers(args.resumeFrom, args.parentId),\n }\n : undefined\n\n const scope: Scope<Out> = {\n spawn,\n next: cursor.next,\n nextResolved: cursor.nextResolved,\n send: workers.send,\n releaseHeld: (nodeId, reason) => {\n const child = children.get(nodeId)\n return child === undefined ? Promise.resolve(false) : releaseHeld(child, reason)\n },\n progress: workers.progress,\n observeTree: workers.observeTree,\n observeEvents: workers.observeEvents,\n traceSource: workers.traceSource,\n interactive: workers.interactive,\n cancel: workers.cancel,\n signal: args.signal,\n rootDeadlineAtMs: args.rootDeadlineAtMs || undefined,\n meter: (spend, detail) => meter.record(spend, detail),\n ...(resume ? { resume } : {}),\n get view(): TreeView {\n return makeTreeView(args.parentId, children)\n },\n get budget() {\n return args.pool.readout()\n },\n get workerCapacity() {\n return {\n working: workerSlots.working,\n queued: workerSlots.queued,\n freeSlots: freeSlots(workerSlots.working, workerSlots.max),\n // Settled nodes whose teardown was never acknowledged, each scope naming its OWN children.\n unconfirmed: Object.freeze(\n [...children.values()]\n .filter((child) => isTerminalNodeStatus(child.status) && !child.cleanupConfirmed)\n .map((child) => unconfirmedTeardownOf(child, releasingScopes.has(scope))),\n ),\n }\n },\n }\n childDrains.set(scope, async () => {\n await Promise.allSettled([...children.values()].map((child) => child.settled))\n await Promise.allSettled([...cursor.writes])\n await Promise.all(\n [...children.values()].map(async (child) => {\n const nested = child.readNestedScope?.()\n if (nested !== undefined) await waitForScopeChildren(nested)\n }),\n )\n })\n admissionSeals.set(scope as Scope<unknown>, () => {\n admissionClosed = true\n })\n heldReleasers.set(scope, async () => {\n await Promise.all([...children.values()].map((child) => releaseHeld(child, 'scope-join')))\n await Promise.allSettled([...heldReleases])\n })\n subtreeReaders.set(scope as Scope<unknown>, () => summarizeTeam(children.values()))\n liveTeamReaders.set(scope as Scope<unknown>, () =>\n readLiveTeam(children.values(), meter.ownerTurns, meter.ownerLastTurnAt),\n )\n runtimeOwnedProviderMeters.set(\n scope as Scope<unknown>,\n async (spend, providerModel, detail, accountingOnly, alreadySpent) =>\n // A provider attempt already started before abort can finish without a usage receipt.\n // Its unknown-cost marker still belongs in the durable journal after the scope aborts.\n meter.record(spend, detail, providerModel, accountingOnly, true, alreadySpent),\n )\n bindOwnerJournalRecorders(scope as Scope<unknown>, args, now)\n bindScopeOwnerMaterialization(scope, args, now)\n if (args.resumeFrom?.recoveries?.length) {\n recoveryStarters.set(scope, () => recoverRetainedChildren(args, children, spawn, cursor.next))\n }\n bindChildTeardown(scope, args, children, now)\n registerScopeRetainedOwner(scope as Scope<unknown>, {\n rootId: args.root,\n executionRootId: args.ownerMaterialization?.journalRoot ?? args.root,\n nodeId: args.parentId,\n depth: args.depth,\n journal: args.journal,\n blobs: args.blobs,\n priorEvents: args.resumeFrom?.events ?? [],\n now,\n })\n bindScopeRetainedOwnerWorkspaceRetention(\n scope as Scope<unknown>,\n args.seams[retainedOwnerWorkspaceRetentionSeamKey] === true,\n )\n return scope\n}\n\n/** The owner's reserved share of its own budget, which child admission must leave free. */\nfunction reservationOwnerFloor(\n args: ScopeArgs,\n): { tokens: number; iterations: number; usd?: number } | undefined {\n const reservationPolicy = args.reservationPolicy\n assertRecursiveReservationPolicy(reservationPolicy)\n if (reservationPolicy && !args.ownerBudget) {\n throw new ValidationError('reservationPolicy requires the owning scope budget')\n }\n const ownerBudget = args.ownerBudget\n return reservationPolicy && ownerBudget\n ? {\n tokens: Math.ceil(ownerBudget.maxTokens * reservationPolicy.ownerShare),\n iterations: Math.ceil(ownerBudget.maxIterations * reservationPolicy.ownerShare),\n ...(ownerBudget.maxUsd === undefined\n ? {}\n : { usd: ownerBudget.maxUsd * reservationPolicy.ownerShare }),\n }\n : undefined\n}\n\n/** Journal the owner's driver attempts, pauses and barren pauses, each in its own monotonic `seq` namespace. */\nfunction bindOwnerJournalRecorders(scope: Scope<unknown>, args: ScopeArgs, now: () => number) {\n let driverAttemptSeq: number | undefined\n driverAttemptRecorders.set(scope, async (record) => {\n if (driverAttemptSeq === undefined) {\n const events = (await args.journal.loadTree(args.root)) ?? []\n const prior = events.filter((e) => e.kind === 'driver-attempt' && e.id === args.parentId)\n driverAttemptSeq = prior.reduce((next, event) => Math.max(next, event.seq + 1), 0)\n }\n const attemptId = ownerMaterializationStates.get(scope)?.attemptId\n // A retained owner's read position rides on its record, where a restarted owner finds it.\n const observed = owners.get(scope)?.context.observed\n await args.journal.appendEvent(args.root, {\n kind: 'driver-attempt',\n id: args.parentId,\n record: {\n ...record,\n ...(record.error === undefined ? {} : { error: errorText(record.error) }),\n ...(observed === undefined ? {} : { observed }),\n },\n ...(attemptId === undefined ? {} : { attemptId }),\n seq: driverAttemptSeq++,\n at: new Date(now()).toISOString(),\n })\n })\n let pauseSeq = 0\n pauseRecorders.set(scope, async (pause) => {\n await args.journal.appendEvent(args.root, {\n kind: 'paused',\n id: args.parentId,\n ...pause,\n seq: pauseSeq++,\n at: new Date(now()).toISOString(),\n })\n })\n // Counted from the journal, like the driver records, so a resumed run continues the sequence.\n let barrenPauseSeq: number | undefined\n barrenPauseRecorders.set(scope, async (pause) => {\n if (barrenPauseSeq === undefined) {\n const events = (await args.journal.loadTree(args.root)) ?? []\n barrenPauseSeq = events.filter(\n (event) => event.kind === 'barren-pause' && event.id === args.parentId,\n ).length\n }\n await args.journal.appendEvent(args.root, {\n kind: 'barren-pause',\n id: args.parentId,\n ...pause,\n seq: barrenPauseSeq++,\n at: new Date(now()).toISOString(),\n })\n })\n}\n\n/** Re-admit every retained child the resume recovered, each through its recovered executor. */\nasync function recoverRetainedChildren<Out>(\n args: ScopeArgs,\n children: Map<NodeId, LiveChild>,\n spawn: ReturnType<typeof createScopeSpawner<Out>>['spawn'],\n next: () => Promise<Settled<Out> | null>,\n): Promise<void> {\n const adopted: LiveChild[] = []\n try {\n for (const recovery of args.resumeFrom!.recoveries!) {\n // Terminal recovery adopts only original leaves for teardown. Nested owners need their\n // original driver binding; keep those explicitly unconfirmed instead of a vacuous release.\n if (args.signal.aborted && recovery.spawned.ownedTreeRoot !== undefined) continue\n const node = recovery.spawned\n const agent = Object.assign(\n {\n name: recovery.spec.profile.name ?? node.label,\n act: async () => {\n throw new ValidationError('retained children execute through their recovered executor')\n },\n },\n { executorSpec: recovery.spec },\n )\n const result = spawn(\n agent,\n recovery.task,\n {\n budget: node.budget,\n label: node.label,\n ...(node.key === undefined ? {} : { key: node.key }),\n ...(node.assignmentId === undefined ? {} : { assignmentId: node.assignmentId }),\n },\n recovery,\n )\n if (!result.ok)\n throw new ValidationError(`scope recovery admission refused '${node.id}': ${result.reason}`)\n adopted.push(children.get(node.id)!)\n }\n // A recovered child can reach its deadline before mounting its descendants; its outcome\n // belongs to next(), not to this barrier, which rejected settlement or storage still fails.\n await Promise.all(\n adopted.map((child) =>\n child.recoveryReady === undefined\n ? undefined\n : Promise.race([child.recoveryReady, child.settled]),\n ),\n )\n } catch (error) {\n for (const child of adopted) child.abortChild?.('recovery startup failed')\n await Promise.allSettled(adopted.map((child) => child.settled))\n for (;;) {\n try {\n if ((await next()) === null) break\n } catch {\n break\n }\n }\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,eACd,OACA,SAOgB;CAiBhB,OAAO;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