@tangle-network/agent-runtime 7.0.0 → 8.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +0 -3
  3. package/dist/{activation-Ba9IAgQ3.js → activation-8AdN-3r4.js} +4 -4
  4. package/dist/{activation-Ba9IAgQ3.js.map → activation-8AdN-3r4.js.map} +1 -1
  5. package/dist/{activation-DIkTEBWF.d.ts → activation-xxvLF1-1.d.ts} +2 -2
  6. package/dist/agent.d.ts +1 -1
  7. package/dist/agent.js +3 -3
  8. package/dist/{bundle-Cy5igJdv.js → bundle-CcpL2lfr.js} +2 -2
  9. package/dist/{bundle-Cy5igJdv.js.map → bundle-CcpL2lfr.js.map} +1 -1
  10. package/dist/candidate-execution/index.js +4 -4
  11. package/dist/continuation-CIyKnS1Q.js +451 -0
  12. package/dist/continuation-CIyKnS1Q.js.map +1 -0
  13. package/dist/{coordination-manager-DQZ2u6L-.js → coordination-manager-DAGPerJy.js} +194 -148
  14. package/dist/coordination-manager-DAGPerJy.js.map +1 -0
  15. package/dist/{coordination-map-routing-CKRNZSaV.js → coordination-map-routing-XZXTlCmn.js} +2 -4
  16. package/dist/coordination-map-routing-XZXTlCmn.js.map +1 -0
  17. package/dist/{delegate-DFLSVjFG.js → delegate-CoaNr0hO.js} +3 -3
  18. package/dist/{delegate-DFLSVjFG.js.map → delegate-CoaNr0hO.js.map} +1 -1
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +13 -12
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{errors-AzSuGI23.js → errors-DG8yufqX.js} +8 -1
  23. package/dist/errors-DG8yufqX.js.map +1 -0
  24. package/dist/{failure-cause-rJTm_Tx8.js → failure-cause-CVB-YE88.js} +12 -8
  25. package/dist/{failure-cause-rJTm_Tx8.js.map → failure-cause-CVB-YE88.js.map} +1 -1
  26. package/dist/graph-pFTeNZ-G.js +1793 -0
  27. package/dist/graph-pFTeNZ-G.js.map +1 -0
  28. package/dist/{graph-registry-7X2nrreR.js → graph-registry-czAwYwNj.js} +133 -9
  29. package/dist/graph-registry-czAwYwNj.js.map +1 -0
  30. package/dist/{graph-registry-gYbq4L5Z.js → graph-registry-uTIyyy7A.js} +1 -1
  31. package/dist/{improve-BolbYegO.js → improve-I43jex8v.js} +19 -48
  32. package/dist/improve-I43jex8v.js.map +1 -0
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +16 -16
  35. package/dist/intelligence.d.ts +2 -2
  36. package/dist/intelligence.js +8 -8
  37. package/dist/intelligence.js.map +1 -1
  38. package/dist/kernel.d.ts +2 -2
  39. package/dist/kernel.js +16 -15
  40. package/dist/{loop-runner-Cs9IJ6Nk.d.ts → loop-runner-BGwhcn1p.d.ts} +2 -2
  41. package/dist/{loop-runner-C9W3T_3T.js → loop-runner-BN4KozR0.js} +3 -3
  42. package/dist/{loop-runner-C9W3T_3T.js.map → loop-runner-BN4KozR0.js.map} +1 -1
  43. package/dist/loop-runner-bin.d.ts +1 -1
  44. package/dist/loop-runner-bin.js +1 -1
  45. package/dist/mcp/bin.js +7 -5
  46. package/dist/mcp/bin.js.map +1 -1
  47. package/dist/mcp/index.d.ts +1 -1
  48. package/dist/mcp/index.js +9 -9
  49. package/dist/mcp/memory-bin.js +2 -2
  50. package/dist/{model-policy-JOcg3NRs.js → model-policy-CZwhXp8O.js} +15 -10
  51. package/dist/model-policy-CZwhXp8O.js.map +1 -0
  52. package/dist/{prepare-Dtfk_Wi_.js → prepare-BnF8nGIg.js} +4 -4
  53. package/dist/{prepare-Dtfk_Wi_.js.map → prepare-BnF8nGIg.js.map} +1 -1
  54. package/dist/{profile-CNSQjOes.js → profile-CD25rTJF.js} +4 -4
  55. package/dist/{profile-CNSQjOes.js.map → profile-CD25rTJF.js.map} +1 -1
  56. package/dist/profiles.d.ts +1 -1
  57. package/dist/profiles.js +2 -2
  58. package/dist/{provision-supervisor-BQFHjCtN.js → provision-supervisor-DvzayGpe.js} +8 -8
  59. package/dist/{provision-supervisor-BQFHjCtN.js.map → provision-supervisor-DvzayGpe.js.map} +1 -1
  60. package/dist/{run-cancellation-B84X8ZAP.js → run-cancellation-C5__aBKW.js} +4 -4
  61. package/dist/{run-cancellation-B84X8ZAP.js.map → run-cancellation-C5__aBKW.js.map} +1 -1
  62. package/dist/{run-state-Dh1bGERI.js → run-state-CJAaxqfp.js} +5 -5
  63. package/dist/{run-state-Dh1bGERI.js.map → run-state-CJAaxqfp.js.map} +1 -1
  64. package/dist/{runtime-C9F1PG2A.js → runtime-CuwHe8_K.js} +76 -987
  65. package/dist/runtime-CuwHe8_K.js.map +1 -0
  66. package/dist/{sandbox-profile-compat-oFGWESLn.js → sandbox-profile-compat-l-SLQnGb.js} +2 -2
  67. package/dist/{sandbox-profile-compat-oFGWESLn.js.map → sandbox-profile-compat-l-SLQnGb.js.map} +1 -1
  68. package/dist/{search-executor-CKR9_6NR.js → search-executor-DAjm-NlG.js} +17 -46
  69. package/dist/search-executor-DAjm-NlG.js.map +1 -0
  70. package/dist/{server-Dh3SQGQT.js → server-BUpNUn5D.js} +32 -8
  71. package/dist/{server-Dh3SQGQT.js.map → server-BUpNUn5D.js.map} +1 -1
  72. package/dist/{settle-record-C6LdVvok.js → settle-record-CeBdBuxP.js} +2 -2
  73. package/dist/{settle-record-C6LdVvok.js.map → settle-record-CeBdBuxP.js.map} +1 -1
  74. package/dist/{snapshot-Cgj2Wzi6.js → snapshot-BKI_w3JD.js} +19 -5
  75. package/dist/snapshot-BKI_w3JD.js.map +1 -0
  76. package/dist/{structural-rollout-Dapf2aZY.js → structural-rollout-CqxBKxKY.js} +18 -54
  77. package/dist/structural-rollout-CqxBKxKY.js.map +1 -0
  78. package/dist/{supervise-xwl2D6q3.js → supervise-Cdqj_oe4.js} +101 -111
  79. package/dist/supervise-Cdqj_oe4.js.map +1 -0
  80. package/dist/{supervision-discovery-B47U8TH5.js → supervision-discovery-CW-ildZ-.js} +4 -4
  81. package/dist/{supervision-discovery-B47U8TH5.js.map → supervision-discovery-CW-ildZ-.js.map} +1 -1
  82. package/dist/{supervisor-gC-u_PRk.js → supervisor-D-eT-6Tu.js} +206 -693
  83. package/dist/supervisor-D-eT-6Tu.js.map +1 -0
  84. package/dist/{supervisor-accounting-DxLQ_TQe.js → supervisor-accounting-Ow6CChpB.js} +434 -423
  85. package/dist/supervisor-accounting-Ow6CChpB.js.map +1 -0
  86. package/dist/testing.d.ts +1 -1
  87. package/dist/testing.js +61 -61
  88. package/dist/{tool-server-Dg350Bgz.js → tool-server-DYwRbi0I.js} +3 -3
  89. package/dist/{tool-server-Dg350Bgz.js.map → tool-server-DYwRbi0I.js.map} +1 -1
  90. package/dist/{top-web-BJLnFQdr.js → top-web-BuYMkJN4.js} +9 -7
  91. package/dist/{top-web-BJLnFQdr.js.map → top-web-BuYMkJN4.js.map} +1 -1
  92. package/dist/tui/bin.js +3 -3
  93. package/dist/tui/index.d.ts +1 -1
  94. package/dist/tui/index.js +2 -2
  95. package/dist/{types-Jg274chm.d.ts → types-C_qbnw9N.d.ts} +1335 -1413
  96. package/dist/{util-C_cdPNC4.js → util-fcckrkKp.js} +39 -113
  97. package/dist/util-fcckrkKp.js.map +1 -0
  98. package/dist/viewer/report-viewer.js +90 -90
  99. package/dist/viewer/runtime-viewer/AgentGraphCanvas-P_PFS2Ko-B7S6Fwwy.js +563 -0
  100. package/dist/viewer/runtime-viewer/latest-events-wofY6ifW-B8_bfLwI.js +17870 -0
  101. package/dist/viewer/styles.css +1592 -7027
  102. package/dist/viewer/workspace-viewer.js +10926 -10522
  103. package/dist/{workspace-streams-B7yNMahl.js → workspace-streams-DA9R3j-p.js} +2 -2
  104. package/dist/{workspace-streams-B7yNMahl.js.map → workspace-streams-DA9R3j-p.js.map} +1 -1
  105. package/package.json +9 -9
  106. package/dist/coordination-manager-DQZ2u6L-.js.map +0 -1
  107. package/dist/coordination-map-routing-CKRNZSaV.js.map +0 -1
  108. package/dist/errors-AzSuGI23.js.map +0 -1
  109. package/dist/graph-BjQF2syl.js +0 -579
  110. package/dist/graph-BjQF2syl.js.map +0 -1
  111. package/dist/graph-registry-7X2nrreR.js.map +0 -1
  112. package/dist/improve-BolbYegO.js.map +0 -1
  113. package/dist/model-policy-JOcg3NRs.js.map +0 -1
  114. package/dist/runtime-C9F1PG2A.js.map +0 -1
  115. package/dist/search-executor-CKR9_6NR.js.map +0 -1
  116. package/dist/snapshot-Cgj2Wzi6.js.map +0 -1
  117. package/dist/structural-rollout-Dapf2aZY.js.map +0 -1
  118. package/dist/supervise-xwl2D6q3.js.map +0 -1
  119. package/dist/supervisor-accounting-DxLQ_TQe.js.map +0 -1
  120. package/dist/supervisor-gC-u_PRk.js.map +0 -1
  121. package/dist/util-C_cdPNC4.js.map +0 -1
  122. package/dist/viewer/runtime-viewer/AgentGraphCanvas-DGq7_u8--C6yDfIUT.js +0 -8555
  123. package/dist/viewer/runtime-viewer/latest-events-CRq9sGkK-CfoBl1dP.js +0 -9592
  124. package/dist/viewer/runtime-viewer/sandbox-ui-BEziPi7D.css +0 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervisor-accounting-Ow6CChpB.js","names":["awaitAbortable","sha256Bytes","unavailable","DENY","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/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/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/supervise/workspace-checkpoint.ts","../src/runtime/retained-native-stop.ts","../src/runtime/supervise/executor-observation.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/provider-visible-profile.ts","../src/runtime/supervise/scope-owner-materialization.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/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/worker-slots.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","../src/durable/spawn-journal/provider-model-evidence.ts","../src/runtime/supervise/settled-usage.ts","../src/runtime/supervise/supervisor-accounting.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/** The signal's explicit reason, or the caller's fallback when none was supplied. */\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 // A default AbortError carries no caller reason.\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 parent abort stops the call at once. The timeout still bounds a parent that stays open. */\nexport function deadlineSignal(parent: AbortSignal | undefined, ms: number): AbortSignal {\n const timeout = AbortSignal.timeout(ms)\n return parent === undefined ? timeout : AbortSignal.any([parent, timeout])\n}\n\ninterface LinkedAbort {\n readonly signal: AbortSignal\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/** Cascade source aborts and preserve their reason; release removes the source listeners. */\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/** Settle work against cancellation once, observing the losing promise.\n * Defer abort one microtask so already-completed work wins. An action's own abort listener\n * cannot win this race: this function subscribes before invoking it.\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 { BackendTransportError } from '../errors'\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\n/** The provider returned a different session than the one this execution admitted. A lost\n * reply, which keeps the same coordinates and no session, is not this case. */\nconst replacedSessionMessage = new Set([\n 'provider reconstructed a different retained environment',\n 'provider reconstructed a different session',\n 'provider session reconstructed a different retained session',\n 'provider session returned a different exact run control reference',\n])\n\nexport function retainedSessionReplaced(error: unknown): boolean {\n const seen = new Set<unknown>()\n let current = error\n for (let depth = 0; depth < 8 && current !== undefined && !seen.has(current); depth += 1) {\n seen.add(current)\n if (current instanceof Error && replacedSessionMessage.has(current.message)) return true\n current = current instanceof Error ? current.cause : undefined\n }\n return false\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\nconst HTML_PAGE_START = /^<!doctype html|^<html|^<body/i\n\n/** A gateway's HTML error page that reached a retained-run read as the failure text: a replay\n * endpoint behind Cloudflare answers 5xx with markup, which is a transport failure (retry,\n * outage window), never a contract violation inviting reconciliation of an execution that never\n * started (#1203). Extracts the printed HTTP status and a bounded, tag-free excerpt. */\nexport function htmlTransportFailure(error: unknown): BackendTransportError | undefined {\n if (!(error instanceof Error)) return undefined\n const text = error.message ?? ''\n if (!HTML_PAGE_START.test(text.trim())) return undefined\n const title = /<title>([^<]*)<\\/title>/i.exec(text)?.[1]?.trim()\n const headline =\n title ??\n text\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n const status = /\\b([45]\\d\\d)\\b/.exec(headline)?.[1]\n const excerpt = headline.slice(0, 200)\n return new BackendTransportError(\n 'provider',\n `provider answered an HTML error page${status === undefined ? '' : ` (HTTP ${status})`}: ${excerpt}`,\n {\n ...(status === undefined ? {} : { status: Number(status) }),\n body: excerpt,\n cause: error,\n },\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 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\n/** A check node's executor factory runs a command, not a model, so it carries no model identity. */\nexport function runtimeCheckFactory<Factory extends object>(factory: Factory): Factory {\n flowOwners.add(factory)\n return factory\n}\n\nexport function isRuntimeCheckFactory(factory: unknown): boolean {\n return typeof factory === 'function' && flowOwners.has(factory)\n}\n","import { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { isRuntimeCheckFactory, 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 &&\n !isRuntimeFlowAgent(runtimeExtensions.driver) &&\n !isRuntimeCheckFactory(raw.executorFactory)\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 { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider'\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>()\ninterface ScopeOwnerControl {\n readonly provider: AgentEnvironmentProvider\n}\nconst runtimeOwnedScopeOwners = new WeakMap<\n object,\n { runtime: Runtime; control?: ScopeOwnerControl }\n>()\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 'resources',\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>(\n owner: T,\n runtime: Runtime,\n control?: ScopeOwnerControl,\n): T {\n runtimeOwnedScopeOwners.set(owner, { runtime, ...(control === undefined ? {} : { control }) })\n return owner\n}\n\n/** A trusted owner's existing provider control remains available before any execution turn. */\nexport function runtimeOwnedScopeOwnerControl(owner: object): ScopeOwnerControl | undefined {\n return runtimeOwnedScopeOwners.get(owner)?.control\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)?.runtime\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 assertResources(declaration.resources)\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 resources:\n declaration.resources ??\n ({ status: 'unknown', reason: 'executor-did-not-report-applied-resources' } as const),\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 assertResources(resources: ExecutorMaterialization['resources']): void {\n if (resources === undefined) return\n if (typeof resources !== 'object' || resources === null || Array.isArray(resources)) {\n throw new ValidationError('executor materialization: resources must be a known/unknown report')\n }\n const keys = Object.keys(resources).sort().join(',')\n if (resources.status === 'unknown') {\n if (keys !== 'reason,status') {\n throw new ValidationError(\n 'executor materialization: unknown resources accepts only status and reason',\n )\n }\n assertNonEmpty(resources.reason, 'resources.reason')\n return\n }\n if (resources.status !== 'known') {\n throw new ValidationError('executor materialization: resources.status must be known or unknown')\n }\n const sizes: Record<string, unknown> = {\n cpu: resources.cpu,\n memoryMb: resources.memoryMb,\n diskMb: resources.diskMb,\n }\n const allowed = new Set([...Object.keys(sizes), 'accelerator', 'origin', 'observedAt', 'status'])\n const stray = Object.keys(resources).filter((key) => !allowed.has(key))\n if (stray.length > 0) {\n throw new ValidationError(\n `executor materialization: known resources accepts only ${[...allowed].sort().join(', ')}: ${stray.sort().join(', ')}`,\n )\n }\n const positive = (value: unknown, integer: boolean) =>\n Number.isFinite(value as number) &&\n (value as number) > 0 &&\n (!integer || Number.isInteger(value))\n for (const [field, value] of Object.entries(sizes).filter(([, v]) => v !== undefined)) {\n if (!positive(value, field !== 'cpu')) {\n throw new ValidationError(\n `executor materialization: resources.${field} must be a positive ${field === 'cpu' ? 'number' : 'integer'}`,\n )\n }\n }\n if (resources.accelerator !== undefined) {\n const accelerator = resources.accelerator\n assertNonEmpty(accelerator.kind, 'resources.accelerator.kind')\n if (!positive(accelerator.count, true)) {\n throw new ValidationError(\n 'executor materialization: resources.accelerator.count must be a positive integer',\n )\n }\n if (accelerator.memoryMb !== undefined && !positive(accelerator.memoryMb, true)) {\n throw new ValidationError(\n 'executor materialization: resources.accelerator.memoryMb must be a positive integer',\n )\n }\n }\n if (Object.values(sizes).every((v) => v === undefined) && resources.accelerator === undefined) {\n throw new ValidationError(\n 'executor materialization: known resources needs at least one of cpu, memoryMb, diskMb, accelerator',\n )\n }\n if (!['estimated', 'measured', 'reported'].includes(resources.origin)) {\n throw new ValidationError(\n 'executor materialization: resources.origin must be estimated, measured or reported',\n )\n }\n assertNonEmpty(resources.observedAt, 'resources.observedAt')\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\n/** How often a pause with no known reset asks again, the account cache's cadence. */\nexport const SEAT_RECHECK_MS = 120_000\n\n/** No seat can start before `resumeAt`: the chain is exhausted, or `detail` says why not. */\nexport class SeatPauseError extends Error {\n readonly resumeAt: string\n readonly detail: string | undefined\n constructor(resumeAt: string, detail?: string) {\n super(`${detail ?? 'authored subscription seat chain exhausted'}; resume at ${resumeAt}`)\n this.name = 'SeatPauseError'\n this.resumeAt = resumeAt\n this.detail = detail\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, so this is not a\n // claimed reset time.\n const recheckAt = Math.max(earliestReset ?? 0, this.now() + SEAT_RECHECK_MS)\n throw new SeatPauseError(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\n/** The sidecar's native inventory has written both `sha256:<hex>` and bare `<hex>` digests\n * (#1264: whole runs skipped every file for the bare form); accept either and keep the\n * canonical prefix. `null` still means no digest and stays unverifiable. */\nfunction nativeDigest(value: string | null): string | null {\n return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) ? `sha256:${value}` : value\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: nativeDigest(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 ...(span.links\n ? {\n links: span.links.map((link) => ({\n trace_id: link.traceId,\n span_id: link.spanId,\n ...(link.traceState === undefined ? {} : { trace_state: link.traceState }),\n ...(link.flags === undefined ? {} : { flags: link.flags }),\n attributes: decodeOtlpAttributes(link.attributes ?? []),\n ...(link.droppedAttributesCount === undefined\n ? {}\n : { dropped_attributes_count: link.droppedAttributesCount }),\n })),\n }\n : {}),\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 to a spawned worker so one supervised tree spans machines. `traceContextToEnv`\n * writes W3C `TRACEPARENT` and the legacy `TRACE_ID` / `PARENT_SPAN_ID` pair; readers take\n * `TRACEPARENT` first. The legacy pair stays so a child on the previous package still joins.\n * `PARENT_SPAN_ID` is the spawning node's span (`parentId`): at depth 0 the run root, otherwise the\n * driver child, and the only span that exists when the child's `ExecutorContext` is built. With\n * `SuperviseOptions.otel` unset, {@link workerTraceEnv} is empty and spawn environments stay\n * byte-identical. `Scope` stamps registry children. `supervise({ backend })` must pass the same seam\n * into `workerFromBackend` or the front door stamps nothing. Precedence is ambient `process.env`,\n * then this stamp, then `CliSeam.env`. A seam that sets the legacy pair gets `TRACEPARENT` rebuilt\n * from those ids. Ambient ids do not win; join an outer trace with `SupervisorSpanOptions.traceId`\n * and `parentSpanId`. `cli`, `sandbox`, and `bridge` propagate. `router`, `router-tools`,\n * `cli-worktree`, `cli-in-place`, and `provider` have no worker environment channel and do not.\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","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 htmlTransportFailure,\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 // A gateway's HTML error page is a transport failure, not a contract violation (#1203).\n const html = htmlTransportFailure(error)\n if (html) throw html\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 htmlTransportFailure,\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 // A gateway's HTML error page is a transport failure, not a contract violation (#1203).\n const html = htmlTransportFailure(error)\n if (html) throw html\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/** Mint the same session and execution from `(idempotencyKey, turnId)` in every process. */\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/** Bound from a durable intent until `provider.create` resolves. */\nconst RETAINED_ENVIRONMENT_MATERIALIZATION_MS = 120_000\n\n/** Create never reached an environment. The message names the stage; the driver stops. */\nexport class RetainedMaterializationTimeoutError extends Error {\n readonly stage = 'intent' as const\n constructor() {\n super('retained run reached stage intent and did not materialize an environment')\n this.name = 'RetainedMaterializationTimeoutError'\n }\n}\n\nfunction createRetainedEnvironment(\n options: StartRetainedRunOptions,\n parent: AbortSignal | undefined,\n): Promise<AgentEnvironment> {\n const timeout = AbortSignal.timeout(\n options.materializationTimeoutMs ?? RETAINED_ENVIRONMENT_MATERIALIZATION_MS,\n )\n const signal = parent === undefined ? timeout : AbortSignal.any([parent, timeout])\n const create = options.provider.create({\n ...options.environment,\n signal,\n metadata: retainedEnvironmentMetadata(\n options.environment.metadata,\n options.environment.idempotencyKey,\n ),\n })\n const timedOut = () => timeout.aborted && parent?.aborted !== true\n return new Promise((resolve, reject) => {\n const fail = () => {\n reject(\n timedOut()\n ? new RetainedMaterializationTimeoutError()\n : parent?.reason instanceof Error\n ? parent.reason\n : new Error('retained run materialization aborted'),\n )\n }\n if (signal.aborted) {\n fail()\n return\n }\n signal.addEventListener('abort', fail, { once: true })\n create.then(\n (environment) => {\n signal.removeEventListener('abort', fail)\n resolve(environment)\n },\n (error: unknown) => {\n signal.removeEventListener('abort', fail)\n reject(timedOut() ? new RetainedMaterializationTimeoutError() : error)\n },\n )\n })\n}\n\n/** Dispatch one replayable run. Intent is durable before create; the promise resolves after dispatch is durable. @stable */\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 createRetainedEnvironment(options, attachmentSignal)\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/** Fresh session in an existing environment. A same-chat turn uses `continueNative`. @stable */\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/** Bind an environment to the retained key on its own get/create record. Missing metadata is a refusal; do not list the account. */\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/** Await the durability hook. A rejection keeps the environment and throws the admission error, not a provider error. */\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/** Mirror admissions into the observer journal. The caller's hook stays authoritative; an observer failure does not fail the run. */\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/** Journal accepted turns and the end beside admissions. A turn records its operation id, never the prompt. */\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/** Replay a persisted intent, or reattach coordinates the provider can prove. `unverifiable` keeps the environment; different coordinates throw. @stable */\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/** A measured environment capability document wins; an absent one uses the provider document. */\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","/**\n * Durable checkpoints of a retained owner's workspace, and the marker that proves a restore.\n * A replacement environment is created from the latest checkpoint. The marker is the evidence\n * the provider restored that workspace.\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. A turn capture cuts them short; the release captures again. */\nexport const WORKSPACE_CHECKPOINT_ROTATION_CAPTURES_MS = 2 * 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 {\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","import { defaultRedactor } from '../../redact'\nimport {\n notifyRuntimeHookEvent,\n type RuntimeExecutionAdmittedPayload,\n type RuntimeHooks,\n} from '../../runtime-hooks'\nimport type { RetainedRunAdmission } from '../retained-run-types'\nimport type { ExecutorContext, ExecutorNodeContext, ExecutorProgressEvent } from './types'\n\nexport const executorObservationSeamKey = 'runtime.executionObservation'\nexport interface ExecutorObservation {\n progress(event: ExecutorProgressEvent): void\n event(target: 'agent.model' | 'agent.tool_call', payload: Record<string, unknown>): void\n}\n\nexport function executorObservation(\n ctx: Pick<ExecutorContext, 'seams'>,\n): ExecutorObservation | undefined {\n return ctx.seams[executorObservationSeamKey] as ExecutorObservation | undefined\n}\n\n/** Promise and streaming executors share their owner's existing observation channel. */\nexport function createExecutorObservation(\n hooks: RuntimeHooks | undefined,\n node: Pick<ExecutorNodeContext, 'rootId' | 'parentId' | 'nodeId' | 'attemptId'>,\n onProgress: (event: ExecutorProgressEvent) => void,\n): ExecutorObservation {\n let sequence = 0\n return {\n progress: onProgress,\n event(target, payload) {\n notifyRuntimeHookEvent(hooks, {\n id: `${node.nodeId}:${node.attemptId}:${target}:${sequence++}`,\n runId: node.rootId,\n parentId: node.nodeId,\n target,\n phase: 'after',\n timestamp: Date.now(),\n payload: defaultRedactor({ ...payload, attemptId: node.attemptId }),\n })\n },\n }\n}\n\n/** Observe completed HTTP work without copying customer payloads into trace metadata. */\nexport async function observeModelRequest<\n T extends {\n model?: string\n usage?: { input: number; output: number }\n billedCostUsd?: number\n content?: string | null\n },\n>(\n observation: ExecutorObservation | undefined,\n model: string,\n request: () => Promise<T>,\n): Promise<T> {\n const startedAt = Date.now()\n try {\n const result = await request()\n observation?.event('agent.model', {\n model: result.model ?? model,\n startedAt,\n endedAt: Date.now(),\n status: 'ok',\n ...(result.usage && model !== 'tangle/auto'\n ? { tokensIn: result.usage.input, tokensOut: result.usage.output }\n : {}),\n ...(result.billedCostUsd === undefined || model === 'tangle/auto'\n ? {}\n : { costUsd: result.billedCostUsd }),\n })\n if (result.content) observation?.progress({ kind: 'text_delta', text: result.content })\n return result\n } catch (error) {\n observation?.event('agent.model', {\n model,\n startedAt,\n endedAt: Date.now(),\n status: 'error',\n error: { type: error instanceof Error ? error.name : 'Error' },\n })\n throw error\n }\n}\n\n/** Only a native call id can prove a tool duration; legacy results remain instant observations. */\nexport function createToolProgressObserver(observation: ExecutorObservation) {\n const calls = new Map<string, number>()\n return (event: ExecutorProgressEvent, at: number): void => {\n if (event.kind !== 'tool_call' && event.kind !== 'tool_result') return\n if (event.kind === 'tool_call') {\n if (event.toolCallId !== undefined && !calls.has(event.toolCallId))\n calls.set(event.toolCallId, at)\n return\n }\n const startedAt = event.toolCallId === undefined ? undefined : calls.get(event.toolCallId)\n if (event.toolCallId !== undefined) calls.delete(event.toolCallId)\n observation.event('agent.tool_call', {\n toolName: event.toolName,\n toolCallId: event.toolCallId,\n startedAt: startedAt ?? at,\n endedAt: at,\n durationKnown: startedAt !== undefined,\n status: event.status,\n ...(event.error ? { error: event.error } : {}),\n })\n }\n}\n\n/** Call only after the exact dispatched admission's journal write has acknowledged. */\nexport function notifyExecutionAdmitted(\n hooks: RuntimeHooks | undefined,\n runId: string,\n nodeId: string,\n admission: RetainedRunAdmission,\n now: () => number,\n attemptId?: string,\n): void {\n if (admission.phase !== 'dispatched' || admission.controlRef.sessionId === undefined) return\n notifyRuntimeHookEvent(hooks, {\n id: `${nodeId}:admitted:${admission.controlRef.executionId}`,\n runId,\n parentId: nodeId,\n target: 'agent.execution',\n phase: 'after',\n timestamp: now(),\n payload: {\n nodeId,\n ...(attemptId === undefined ? {} : { attemptId }),\n controlRef: { ...admission.controlRef },\n sessionId: admission.controlRef.sessionId,\n } satisfies RuntimeExecutionAdmittedPayload,\n })\n}\n","import { executorFailureReason } from '../../runtime/supervise/executor-outcome'\nimport { assertValidBudget, assertValidSpend } from '../../runtime/supervise/spend-validation'\nimport type { Budget, 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 budget?: Budget\n closed: boolean\n materialized: boolean\n grants?: Set<string>\n grantClock?: Pick<\n Extract<SpawnEvent, { kind: 'admission-granted' }>,\n 'deadlineArmedAt' | 'deadlineAt'\n >\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 === 'reconciled' && event.reservation) {\n if (!node?.budget) throw new Error('reservation evidence has no admitted node')\n assertValidBudget(event.reservation, 'reconciled reservation')\n for (const [name, value] of Object.entries(event.reservation.resources ?? {})) {\n if (node.budget.resources?.[name]?.unit !== value.unit)\n throw new Error(`reconciled reservation resource ${name}: original grant unit mismatch`)\n }\n for (const channel of ['maxTokens', 'maxIterations', 'maxUsd'] as const)\n if (event.reservation[channel] !== undefined && node.budget[channel] === undefined)\n throw new Error(`reconciled reservation adds an undeclared ${channel} channel`)\n }\n if (event.kind === 'admission-queued' || event.kind === 'admission-granted') {\n if (\n !node?.spawned ||\n node.closed ||\n typeof event.attemptId !== 'string' ||\n event.attemptId.length === 0 ||\n (event.kind === 'admission-granted' && node.grants?.has(`${event.attemptId}:${event.seq}`))\n )\n throw new Error(`spawn journal corrupted: invalid admission transition for '${event.id}'`)\n if (\n !Number.isSafeInteger(event.seq) ||\n event.seq < 0 ||\n (event.kind === 'admission-queued' &&\n (!['budget', 'slot', 'seat'].includes(event.gate) ||\n (event.resumeAt !== undefined && !Number.isFinite(Date.parse(event.resumeAt))))) ||\n !Number.isFinite(Date.parse(event.at)) ||\n (event.kind === 'admission-granted' &&\n (!Number.isFinite(Date.parse(event.deadlineArmedAt)) ||\n (event.deadlineAt !== undefined && !Number.isFinite(Date.parse(event.deadlineAt)))))\n )\n throw new Error(`spawn journal corrupted: invalid admission clock for '${event.id}'`)\n if (\n event.kind === 'admission-granted' &&\n node.grantClock &&\n (event.deadlineArmedAt !== node.grantClock.deadlineArmedAt ||\n event.deadlineAt !== node.grantClock.deadlineAt)\n )\n throw new Error(`spawn journal corrupted: admission deadline changed for '${event.id}'`)\n }\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 !== 'admission-granted' &&\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') {\n node.spawned = true\n node.budget = event.budget\n } else if (event.kind === 'admission-granted') {\n node.grants ??= new Set()\n node.grants.add(`${event.attemptId}:${event.seq}`)\n node.grantClock ??= { deadlineArmedAt: event.deadlineArmedAt, deadlineAt: event.deadlineAt }\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 'admission-queued',\n 'admission-granted',\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-refused',\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 if (\n ev.kind !== 'reconciled' &&\n ev.kind !== 'admission-queued' &&\n ev.kind !== 'admission-granted'\n )\n continue\n const node = requireNode(nodes, ev.id)\n if (node.status === 'pending' || node.status === 'queued' || node.status === 'acquiring') {\n node.status =\n ev.kind === 'reconciled'\n ? 'pending'\n : ev.kind === 'admission-queued'\n ? 'queued'\n : 'acquiring'\n if (ev.kind === 'reconciled') {\n node.spent = cloneSpend(ev.spent)\n node.failure = ev.failure\n }\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) => ['queued', 'running', 'acquiring'].includes(n.status)).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 { deadlineSignal, 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. A `not_found` older than\n * {@link WORKSPACE_CHECKPOINT_ABSENT_AFTER_MS} never created one. A parent abort starts no lookup.\n */\nexport async function reconcileCheckpointRequests(\n state: OwnerState,\n events: SpawnEvent[],\n parent?: AbortSignal,\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 if (parent?.aborted) {\n unconfirmed.push({ event, reason: 'cancelled before checkpoint lookup' })\n continue\n }\n const signal = deadlineSignal(parent, 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 workspaceCleanupAcknowledgementMatches,\n workspaceCleanupRequestDigest,\n} from '@tangle-network/agent-interface'\nimport { deadlineSignal, runAbortable } from './abortable'\nimport { errMessage } from './error-message'\nimport { type CheckpointEvent, checkpointHandle } from './retained-owner-checkpoint-requests'\nimport type { OwnerState } from './retained-owner-state'\nimport type { SpawnEvent } from './types'\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/** Deletes the provider did not confirm, and checkpoints kept because no capture holds their files. */\nexport interface CheckpointCleanup {\n readonly unconfirmed: ReadonlyArray<{ readonly event: CheckpointEvent; readonly reason: string }>\n readonly refused: CaptureRefusal[]\n}\n\n/** Delete captured checkpoints. An aborted parent starts no further provider call. */\nexport async function cleanCheckpoints(\n state: OwnerState,\n branching: AgentWorkspaceBranching | undefined,\n checkpoints: readonly CheckpointEvent[],\n events: readonly SpawnEvent[],\n parent?: AbortSignal,\n uncapturable = false,\n): Promise<CheckpointCleanup> {\n const unconfirmed: Array<{ readonly event: CheckpointEvent; readonly reason: string }> = []\n const refused: CaptureRefusal[] = []\n for (const event of checkpoints) {\n const captured = captureBeforeCleanup(state, event, events, uncapturable)\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 let reason: string | undefined\n const signal = deadlineSignal(parent, 30_000)\n try {\n if (parent?.aborted) reason = 'cancelled before checkpoint cleanup'\n else if (branching === undefined)\n throw new Error('source-scoped checkpoint handle unavailable')\n else {\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 if (!confirmed) reason = `provider acknowledged '${acknowledgement.status}'`\n }\n } catch (error) {\n // The journal and settle result retain the unresolved resource, with its reason (#1594).\n reason = errMessage(error).slice(0, 1_000)\n }\n if (!confirmed) unconfirmed.push({ event, reason: reason ?? 'delete was not confirmed' })\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 ...(reason === undefined ? {} : { refused: reason.slice(0, 1_000) }),\n ...(captured.digest === undefined ? {} : { capturedDigest: captured.digest }),\n seq: state.nextSequence(),\n at: new Date(state.args.now()).toISOString(),\n })\n }\n return { unconfirmed, refused }\n}\n\n/** Read the persisted checkpoint capture, or preserve an uncaptured checkpoint. */\nfunction captureBeforeCleanup(\n state: OwnerState,\n event: CheckpointEvent,\n events: readonly SpawnEvent[],\n uncapturable = false,\n): { readonly digest?: import('@tangle-network/agent-interface').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 return uncapturable\n ? {}\n : refuse(\n 'client checkpoint capture writers are retired; no persisted capture holds this checkpoint',\n false,\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 parent?: AbortSignal,\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 = deadlineSignal(parent, 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/** Destroy capture forks the journal does not show destroyed. An aborted parent starts no further fork call. Returns forks still unconfirmed. */\nexport async function settleCaptureForks(\n state: OwnerState,\n parent?: AbortSignal,\n): 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 if (parent?.aborted) {\n unresolved.push(named(request.idempotencyKey) ?? request.idempotencyKey)\n continue\n }\n const signal = deadlineSignal(parent, 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(\n state,\n branching,\n {\n provider: request.provider,\n environmentId: request.environmentId,\n checkpointId: request.checkpointId,\n fork: { idempotencyKey: request.idempotencyKey, environmentId: forkEnvironmentId },\n },\n parent,\n ))\n )\n unresolved.push(forkEnvironmentId ?? request.idempotencyKey)\n }\n return unresolved\n}\n","import type { AgentWorkspaceBranching } from '@tangle-network/agent-interface'\nimport type { AgentEnvironmentProvider } from '@tangle-network/agent-interface/environment-provider'\nimport type { RuntimeHooks } from '../../runtime-hooks'\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 /** Set on every prepare so a recovered invocation replays the committed identity. */\n freshSessions?: boolean\n /** The previous harness process died. Release that execution before the next dispatch. */\n replaceDeadExecution?: boolean\n provider?: AgentEnvironmentProvider\n /** Current environment id. Admissions miss a provider that never writes one. */\n liveEnvironmentId?: () => string | undefined\n nextSequence: () => number\n /** A 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 /** Captures this process refused. Rotation keeps them; release tries each once more. */\n captureRefused?: Set<string>\n /** Stops a rotation's captures when the turn's own workspace 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}\n\n/** @internal */\nexport interface OwnerRegistration {\n readonly hooks?: RuntimeHooks\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/** Bound native custody, read from its canonical receipts without probing another provider. */\nexport function scopeOwnerLiabilities(\n scope: Scope<unknown>,\n events: readonly SpawnEvent[],\n): {\n environmentHeld: boolean\n invocationUnsettled: boolean\n measuredResources: ReadonlyMap<string, string>\n} {\n const state = owners.get(scope)\n if (!state)\n return { environmentHeld: false, invocationUnsettled: false, measuredResources: new Map() }\n const held = new Set<string>()\n const destroyed = new Set<string>()\n const forks = new Set<string>()\n const key = (provider: string, id: string) => JSON.stringify([provider, id])\n const forkKey = (provider: string, id: string, environmentId?: string) =>\n JSON.stringify([provider, id, environmentId ?? null])\n let invocationUnsettled = false\n let environment: string | undefined\n const measurements = new Map<string, Map<string, string>>()\n for (const event of events) {\n if (event.id !== state.args.nodeId) continue\n if (event.kind === 'execution-admitted') {\n invocationUnsettled = true\n if (event.admission.phase === 'environment') {\n environment = key(event.admission.provider, event.admission.environmentId)\n held.add(environment)\n destroyed.delete(environment)\n measurements.delete(environment)\n }\n } else if (event.kind === 'execution-result') {\n invocationUnsettled = false\n if (environment !== undefined)\n measurements.set(\n environment,\n new Map(\n Object.entries(event.spent.resources ?? {}).flatMap(([name, value]) =>\n value.known ? [[name, value.unit] as const] : [],\n ),\n ),\n )\n } else if (event.kind === 'environment-teardown' && event.destroyed) {\n held.delete(key(event.provider, event.environmentId))\n destroyed.add(key(event.provider, event.environmentId))\n } else if (event.kind === 'workspace-checkpoint-fork-requested')\n forks.add(forkKey(event.provider, event.idempotencyKey))\n else if (event.kind === 'workspace-checkpoint-fork-ready') {\n forks.delete(forkKey(event.provider, event.fork.idempotencyKey))\n forks.add(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId))\n } else if (event.kind === 'workspace-checkpoint-fork-teardown' && event.destroyed) {\n forks.delete(forkKey(event.provider, event.fork.idempotencyKey))\n forks.delete(forkKey(event.provider, event.fork.idempotencyKey, event.fork.environmentId))\n }\n }\n const live = state.liveEnvironmentId?.()\n if (\n live !== undefined &&\n (state.provider === undefined || !destroyed.has(key(state.provider.name, live)))\n )\n held.add(key(state.provider?.name ?? '', live))\n const measuredResources = new Map(measurements.get([...held][0] ?? '') ?? [])\n for (const reference of held)\n for (const [name, unit] of measuredResources)\n if (measurements.get(reference)?.get(name) !== unit) measuredResources.delete(name)\n if (forks.size > 0 || invocationUnsettled) measuredResources.clear()\n return {\n environmentHeld: held.size > 0 || forks.size > 0,\n invocationUnsettled,\n measuredResources,\n }\n}\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/** Bind the provider that owns native stop, checkpoint and environment acknowledgements. */\nexport function bindScopeRetainedOwnerProvider(\n scope: Scope<unknown>,\n provider: AgentEnvironmentProvider,\n): void {\n const state = owners.get(scope)\n if (state) state.provider = provider\n}\n\n/** Bind the resolver for the owner's current environment id. Admissions alone miss a provider that never writes an environment admission. */\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 type AgentWorkspaceBranching,\n type WorkspaceCheckpointRequest,\n workspaceCheckpointRequestDigest,\n workspaceCheckpointResultMatchesRequest,\n} from '@tangle-network/agent-interface'\nimport type { AgentEnvironment } from '@tangle-network/agent-interface/environment-provider'\nimport { runAbortable } from './abortable'\nimport { errorText } from './error-message'\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/** Checkpoint after a coordination call once the last one is older than {@link WORKSPACE_CHECKPOINT_MIN_INTERVAL_MS}. It never delays the call, and a failure leaves the previous restore point. */\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 requestOne = () =>\n requestCheckpoint(scope, state, provider.name, environment, branching, source, signal)\n // A refusal, usually a plan's snapshot limit, gets one more try once a superseded checkpoint is\n // out of its way, so the restore point keeps moving.\n if (\n !(await requestOne()) &&\n (!(await deleteOldestUncapturable(state, branching, environment.id, signal)) ||\n !(await requestOne()))\n )\n return\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/** Ask for one checkpoint and journal the answer. True when the journal holds the checkpoint. */\nasync function requestCheckpoint(\n scope: Scope<unknown>,\n state: OwnerState,\n providerName: string,\n environment: AgentEnvironment,\n branching: AgentWorkspaceBranching,\n source: WorkspaceCheckpointRequest['source'],\n signal: AbortSignal,\n): Promise<boolean> {\n const { args } = state\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: providerName,\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') {\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-checkpoint-refused',\n id: args.nodeId,\n provider: providerName,\n environmentId: environment.id,\n idempotencyKey: request.idempotencyKey,\n message: errorText('message' in result ? result.message : result.status),\n seq: state.nextSequence(),\n at,\n })\n return false\n }\n if (!workspaceCheckpointResultMatchesRequest(request, result)) return false\n scope.signal.throwIfAborted()\n await args.journal.appendEvent(args.rootId, {\n kind: 'workspace-checkpoint',\n id: args.nodeId,\n provider: providerName,\n environmentId: environment.id,\n checkpoint: result.checkpoint,\n ...(marked ? { marker } : {}),\n seq: state.nextSequence(),\n at,\n })\n return true\n}\n\n/** Delete the oldest checkpoint past {@link WORKSPACE_CHECKPOINTS_KEPT} when no capture can hold it, so a snapshot limit cannot freeze the restore point. */\nasync function deleteOldestUncapturable(\n state: OwnerState,\n branching: AgentWorkspaceBranching,\n environmentId: string,\n signal: AbortSignal,\n): Promise<boolean> {\n const events = (await state.args.journal.loadTree(state.args.rootId)) ?? []\n const oldest = pendingCheckpoints(events, state)\n .filter((event) => event.environmentId === environmentId)\n .slice(0, -WORKSPACE_CHECKPOINTS_KEPT)\n .slice(0, 1)\n if (oldest.length === 0) return false\n const { unconfirmed } = await cleanCheckpoints(state, branching, oldest, events, signal, true)\n return unconfirmed.length === 0\n}\n","/** Retained-owner capture receipts, source verification before reuse, and accepted-turn evidence debt. */\nimport {\n type AgentExactRunControlRef,\n AgentExactRunControlRefSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n} from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { sameControlCoordinates } from '../retained-run-binding'\nimport type { RetainedRunAdmission, RetainedRunEnvironmentAdmission } from '../retained-run-types'\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/** Group owner admissions by input. A source with no verified workspace receipt is preserved, including one a later resume can still use. */\nconst UNVERIFIED_SOURCE =\n 'provider workspace retention: source preserved because the owner execution has no verified workspace receipt'\n\nexport async function ownerWorkspaceRetentionFailures(\n events: readonly SpawnEvent[],\n owner: OwnerRegistration,\n): Promise<ReadonlyMap<string, string>> {\n const attempts = ownerWorkspaceAttempts(events, owner.nodeId)\n const failures = new Map<string, string>()\n for (const index of attempts.keys()) {\n const attempt = withLaterEvidence(attempts, index)\n if (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)\n failures.set(environmentId, UNVERIFIED_SOURCE)\n continue\n }\n const environmentId = [...attempt.environmentIds][0]!\n const reason = await ownerAttemptHasCapture(attempt, environmentId, owner.blobs, owner)\n if (reason !== undefined) failures.set(environmentId, reason)\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\n/** Undefined when a receipt authorizes destroying the source. Otherwise why it stays. */\nasync function ownerAttemptHasCapture(\n attempt: OwnerAttempt,\n environmentId: string,\n blobs: ResultBlobStore,\n owner?: OwnerRegistration,\n allowPartialProcessCapture = false,\n): Promise<string | undefined> {\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 const identity = owner === undefined ? undefined : ownerCaptureIdentity(attempt, owner)\n let verified = false\n let nativeHold: string | undefined\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 const capture =\n output !== null && typeof output === 'object'\n ? (output as { readonly workspaceCapture?: unknown }).workspaceCapture\n : undefined\n const receipt =\n capture !== null && typeof capture === 'object'\n ? (capture as Record<string, unknown>)\n : undefined\n const matches =\n receipt !== undefined &&\n receipt.environmentId === environmentId &&\n receipt.executionId === attempt.executionId\n const durable = hasDurableWorkspaceCapture(\n output,\n snapshot,\n environmentId,\n attempt.executionId,\n controlRef,\n identity,\n allowPartialProcessCapture,\n )\n if (matches && receipt !== undefined) {\n const hold = nativeSessionCopyHoldReason(receipt)\n // The last copy of this execution decides. An earlier complete snapshot does not\n // authorize destroying a later incomplete native store.\n if (hold !== undefined) {\n nativeHold = hold\n verified = false\n } else if (durable) {\n nativeHold = undefined\n verified = true\n }\n } else if (nativeHold === undefined && durable) verified = true\n }\n if (nativeHold !== undefined) return nativeHold\n return verified ? undefined : UNVERIFIED_SOURCE\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 attempt of attempts) {\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 when Sandbox lost only raw process I/O.\n if (\n (await ownerAttemptHasCapture(attempt, environmentId, args.blobs, args, true)) === undefined\n )\n continue\n signal.throwIfAborted()\n const failure = capturePendingMessage(\n attempt.executionId ?? args.nodeId,\n new Error('client capture writers are retired; a persisted verified receipt is required'),\n )\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 throw new RetainedExecutionPendingError(new Error(failure), 'unobservable')\n }\n indebted.add(environmentId)\n state.forceNewSession = true\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/** Preserve a historical capture obligation without blocking work in a fresh environment. */\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}\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 !captureAuthorizesDestroy(receipt, allowPartialProcessCapture)\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\nconst NATIVE_STORE_GAP = /(?:^|\\s)((?:over_bound|store_file_):[^\\s;]+)/g\nconst COVERAGE_GAP_PREFIX = 'provider workspace retention coverage incomplete: '\nconst PROCESS_GAP = [\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]\nconst EVENT_GAP = /(?:^|:\\s)events_incomplete(?::[\\w.-]+)?$/\n\n/** Keep the box when the final native copy is incomplete. Process I/O or event-log gaps do not. */\nfunction nativeSessionCopyHoldReason(receipt: Record<string, unknown>): string | undefined {\n const provenance = receipt.provenance\n if (provenance === null || typeof provenance !== 'object') return undefined\n const reported = provenance as Record<string, unknown>\n const sessions = Array.isArray(reported.sessions) ? reported.sessions : []\n let incomplete = false\n const tokens = new Set<string>()\n const take = (value: unknown): void => {\n const text = Array.isArray(value)\n ? value.filter((item) => typeof item === 'string').join('; ')\n : typeof value === 'string'\n ? value\n : ''\n for (const match of text.matchAll(NATIVE_STORE_GAP)) tokens.add(match[1]!)\n }\n for (const session of sessions) {\n if (session === null || typeof session !== 'object') continue\n const row = session as Record<string, unknown>\n const store = row.nativeStore\n if (\n store !== null &&\n typeof store === 'object' &&\n (store as { complete?: unknown }).complete === false\n )\n incomplete = true\n take(row.nativeReason)\n if (store !== null && typeof store === 'object')\n take((store as { missingReasons?: unknown }).missingReasons)\n }\n take(reported.missing)\n if (!incomplete && tokens.size === 0) return undefined\n const detail = tokens.size > 0 ? [...tokens].join('; ') : 'nativeStore incomplete'\n return `native session copy incomplete: ${detail}`\n}\n\nfunction captureAuthorizesDestroy(\n receipt: Record<string, unknown>,\n allowPartialProcessCapture: boolean,\n): boolean {\n if (nativeSessionCopyHoldReason(receipt) !== undefined) return false\n if (receipt.coverageComplete === true) return true\n // Reuse accepts a process I/O gap only. Release also accepts an event-log gap alone.\n return hasOnlyRawProcessCaptureGap(receipt, !allowPartialProcessCapture)\n}\n\nfunction captureGapTexts(receipt: Record<string, unknown>): string[] {\n const reason = receipt.incompleteReason\n const named =\n typeof reason === 'string' && reason.startsWith(COVERAGE_GAP_PREFIX)\n ? reason.slice(COVERAGE_GAP_PREFIX.length).split('; ')\n : []\n const provenance = receipt.provenance\n const missing =\n provenance !== null &&\n typeof provenance === 'object' &&\n Array.isArray((provenance as { missing?: unknown }).missing)\n ? (provenance as { missing: unknown[] }).missing.filter(\n (item): item is string => typeof item === 'string',\n )\n : []\n return [...named, ...missing].map((gap) => gap.trim()).filter((gap) => gap.length > 0)\n}\n\n/**\n * A process I/O gap does not invalidate a verified workspace. `includeEvents` is the release\n * rule: an event-log gap alone also authorizes destroy. Any other gap keeps the source.\n */\nfunction hasOnlyRawProcessCaptureGap(\n receipt: Record<string, unknown>,\n includeEvents = false,\n): boolean {\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 (includeEvents && session.nativeEvents?.complete === false)),\n )\n )\n return false\n const gaps = captureGapTexts(receipt)\n return (\n gaps.length > 0 &&\n gaps.every(\n (gap) =>\n PROCESS_GAP.some((pattern) => pattern.test(gap)) || (includeEvents && EVENT_GAP.test(gap)),\n )\n )\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 { 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\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 Join the owner's drive, end-of-turn work and any release already in progress. */\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}\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 type { RuntimeHooks } from '../../runtime-hooks'\nimport {\n createExecutorObservation,\n createToolProgressObserver,\n type ExecutorObservation,\n executorObservation,\n} from './executor-observation'\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 ExecutorProgressEvent,\n MaterializedExecutionIdentity,\n NodeId,\n NodeSnapshot,\n ProfileMaterializationReceipt,\n ResultBlobStore,\n Scope,\n SpawnEvent,\n SpawnJournal,\n} from './types'\n\ninterface OwnerMaterializationState {\n readonly hooks?: RuntimeHooks\n readonly inheritedObservation?: ExecutorObservation\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 ...(args.hooks ? { hooks: args.hooks } : {}),\n ...(executorObservation(args) ? { inheritedObservation: executorObservation(args) } : {}),\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\n/** A nested manager forwards output to its existing node channel, never a second stream. */\nexport function scopeOwnerExecutionObservation(\n scope: Scope<unknown>,\n onProgress: (event: ExecutorProgressEvent) => void,\n): ExecutorObservation {\n const state = ownerMaterializationStates.get(scope)\n const observation = createExecutorObservation(\n state?.hooks,\n scopeOwnerExecutorNodeContext(scope),\n (event) => {\n if (state?.inheritedObservation) state.inheritedObservation.progress(event)\n else observeTool(event, Date.now())\n onProgress(event)\n },\n )\n const observeTool = createToolProgressObserver(observation)\n return observation\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 { notifyExecutionAdmitted } from './executor-observation'\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 unusableEnvironmentIds,\n} from './retained-owner-evidence'\nimport { type OwnerRegistration, type OwnerState, owners } from './retained-owner-state'\nimport { preemptRotationCaptures } from './retained-owner-turn-lifecycle'\nimport { ownerMaterializationStates } from './scope-owner-materialization'\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 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 const attemptId = ownerMaterializationStates.get(scope)?.attemptId\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 notifyExecutionAdmitted(\n args.hooks,\n args.rootId,\n args.nodeId,\n admission,\n args.now,\n attemptId,\n )\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 onEndOfTurnWork: (work) => {\n // 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/** Continue the latest committed environment, past abandoned ones. A live session stays. */\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\nconst ABANDON_STOP_TIMEOUT_MS = 30_000\n\nasync function releaseDeadRetainedExecution(\n state: OwnerState,\n events: readonly SpawnEvent[],\n scope: Scope<unknown>,\n): Promise<void> {\n if (state.provider === undefined) return\n const dispatched = [...events]\n .reverse()\n .find((event) => event.kind === 'execution-admitted' && event.admission.phase === 'dispatched')\n if (dispatched?.kind !== 'execution-admitted' || dispatched.admission.phase !== 'dispatched')\n return\n await stopRetainedNativeExecution({\n provider: state.provider,\n controlRef: dispatched.admission.controlRef,\n signal: AbortSignal.any([scope.signal, AbortSignal.timeout(ABANDON_STOP_TIMEOUT_MS)]),\n now: state.args.now,\n })\n}\n\n/** Abandon only after a confirmed stop. Without one, journal nothing. */\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 cannot prove the keyed create ended. Do not open a new key beside it.\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 prompt. A fresh session starts a new harness session in the environment. */\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 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 // Do not dispatch a 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 closes it.\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 // An abandoned invocation is not recovered. The next drive is new in its session.\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 segment recorded before dispatch starts fresh from the checkpoint, not the old 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 native session cannot continue in another harness. Later invocations start fresh.\n state.forceNewSession = true\n }\n if (state.forceNewSession) {\n delete state.priorSession\n delete state.forceNewSession\n }\n state.prepared = true\n // The journal fixes the restore point before input, so recovery replays that create.\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.replaceDeadExecution === true) {\n state.replaceDeadExecution = false\n if (state.taskRef === undefined) await releaseDeadRetainedExecution(state, owned, scope)\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 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 { ownerWorkspaceRetentionFailures } 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/** One budget for every checkpoint lookup, delete and fork this release starts. A cut-short capture keeps its checkpoint and source. */\nconst RELEASE_CHECKPOINT_CAPTURES_MS = 15 * 60_000\n\n/**\n * Release the owner's environment once no turn of it will run again. A second call joins the one\n * in flight. The end-of-turn capture finishes before destroy. `capturesMs` bounds checkpoint work.\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 const events = [...((await args.journal.loadTree(args.rootId)) ?? [])]\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 let requestFailures: Awaited<ReturnType<typeof reconcileCheckpointRequests>> = []\n const pendingSources = new Set<string>()\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 retentionFailures = await ownerWorkspaceRetentionFailures(events, args)\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: { readonly event: CheckpointEvent; readonly reason: string }[] = []\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 try {\n requestFailures = await reconcileCheckpointRequests(state, events, captures.signal)\n for (const { event } of requestFailures) pendingSources.add(event.environmentId)\n const pending = pendingCheckpoints(events, state).filter(\n (event) => !retentionFailures.has(event.environmentId),\n )\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, captures.signal)\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 const retentionReason = retentionFailures.get(environmentId)\n const nativeHold = retentionReason?.startsWith('native session copy incomplete:') === true\n if (\n retentionReason !== undefined ||\n pendingSources.has(environmentId) ||\n uncapturedSources.has(environmentId)\n ) {\n detail = nativeHold\n ? retentionReason\n : 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 : retentionReason\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, reason }): 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} (${reason})`,\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. `{ kind: 'inline', name, path }` is read by the\n * coordination server into ordinary `content`, so the model does not transcribe the bytes.\n * {@link SpawnResourceReader} is either a host directory (descriptor-identity checks) or the\n * manager's own execution environment (`read()`), because the coordination server cannot see a\n * sandbox filesystem. Refuse when no reader exists, the path is absolute or escapes with `..`, a\n * host symlink resolves outside the root, the path is not a regular file, the file exceeds\n * {@link SPAWN_RESOURCE_PATH_MAX_BYTES}, or the bytes are not UTF-8. Binary content is base64,\n * encoded by the manager 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. Containment of relative paths is the provider's property, not this\n * function's: the tangle sidecar enforces it in `resolveWorkspacePath`\n * (apps/sidecar/src/lib/workspace.ts:98-155, agent-dev-container) — relative paths stay inside\n * the sandbox workspace, absolute paths only through an allowlist, `.sidecar/` refused at any\n * depth because that tree holds the guest's orchestrator token. If that enforcement widened,\n * this reader would serve files from outside the workspace; the absolute, `..`, and `.sidecar`\n * refusals below are belt-and-braces so it stays correct for every path shape they can name\n * (#1284).\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 if (requested.split(/[\\\\/]/u).includes('.sidecar')) {\n return {\n ok: false,\n reason: `path ${requested} names .sidecar, the guest's control tree; a spawn resource cannot read it`,\n }\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/** Read spawn resources from the owner's latest environment. Path rules live in `environmentReader`. A missing admission or provider is a refusal, not a read from nowhere. */\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, and a checkpoint of the\n * old one, whose time it returns. */\nexport async function prepareScopeRetainedOwnerSeatSwitch(\n scope: Scope<unknown>,\n mode: 'same-environment' | 'replace-environment',\n): Promise<string | undefined> {\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 if (mode === 'same-environment') return undefined\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 since = owned.slice(acceptedIndex + 1).reverse()\n const checkpoint = since.find(\n (event) => event.kind === 'workspace-checkpoint' && event.environmentId === sourceEnvironmentId,\n )\n if (checkpoint?.kind !== 'workspace-checkpoint') {\n const refusal = since.find((event) => event.kind === 'workspace-checkpoint-refused')\n const why =\n state.checkpointsUnavailable ??\n (refusal?.kind === 'workspace-checkpoint-refused' ? refusal.message : 'none was taken')\n throw new ValidationError(`no checkpoint of its committed source: ${why}`)\n }\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 return checkpoint.at\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)).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/** A nested owner's existing allocation and permit, suspended across a seat wait. */\nexport const scopeSeatAccountingUpdates = new WeakMap<Scope<unknown>, () => Promise<void>>()\nexport const seatAdmissionPauses = new WeakMap<\n object,\n (resumeAt: string) => Promise<() => Promise<void>>\n>()\nexport async function pauseScopeSeatAdmission(\n scope: Scope<unknown>,\n resumeAt: string,\n): Promise<() => Promise<void>> {\n return (await seatAdmissionPauses.get(scope)?.(resumeAt)) ?? (async () => {})\n}\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 await scopeSeatAccountingUpdates.get(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).then((unconfirmed) => {\n ownerUnconfirmedByScope.set(scope, unconfirmed)\n }),\n ]).then(async () => {\n await scopeSeatAccountingUpdates.get(scope)?.()\n })\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 const direct = [\n ...scope.workerCapacity.unconfirmed,\n ...(ownerUnconfirmedByScope.get(scope) ?? []),\n ]\n const reported = new Set(direct.map((node) => node.id))\n return [\n ...direct,\n ...nestedManagerScopes(scope)\n .flatMap(unconfirmedTeardowns)\n .filter((node) => !reported.has(node.id)),\n ]\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 * `rollingDispatch` keeps `width` children in flight over `Scope.spawn` and `Scope.next`.\n * An admission rejection stops further admission. `width` bounds this dispatcher; `workerSlots`\n * queues past the tree-wide bound; a sandbox fork wave is a different unit. Do not fold this\n * into `runBatch`: a Scope settlement is real only once it is journaled.\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 // Completion and durable publication do not consume the manager's delivery.\n ...(c.resolved !== undefined && c.settledSeq !== 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 { ValidationError } from '../../errors'\nimport { notifyRuntimeHookEvent } from '../../runtime-hooks'\nimport { refreshBudgetLease } from './budget'\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 private readonly attemptId: () => string | undefined,\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 await refreshBudgetLease(args.pool)\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 ?? {}), attemptId: this.attemptId() },\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 { budgetLeases } from './budget'\nimport { releaseManagerEnvironment, 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 Budget,\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 reservation?: Budget,\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 ...(reservation === undefined ? {} : { reservation }),\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' | 'teardown-confirmed',\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\n/** An executor's acknowledged cleanup, including a child cancelled before it ran. */\nexport async function appendTeardownConfirmation(\n journal: SpawnJournal,\n root: NodeId,\n id: NodeId,\n at: string,\n): Promise<void> {\n const seq = await nextPerNodeSeq(journal, root, 'teardown-confirmed', id)\n await journal.appendEvent(root, { kind: 'teardown-confirmed', id, seq, at })\n}\n\nexport async 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/** Persist a completed child before publishing its terminal view and result. */\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 nestedScope = child.readNestedScope?.()\n const subtree = nestedScope === undefined ? undefined : subtreeSummaryOf(nestedScope)\n if (subtree !== undefined) child.subtree = subtree\n const settledAt = now()\n const at = new Date(settledAt).toISOString()\n if (\n child.cleanupConfirmed &&\n !child.recoveryPending &&\n child.held === undefined &&\n nestedScope === undefined\n ) {\n await appendTeardownConfirmation(args.journal, args.root, child.id, at)\n budgetLeases.get(args.pool)?.acknowledgeTeardown(child.admission.ticket)\n }\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 const cancellation = child.cancellationReason\n const retainedPending = child.recoveryPending === true\n if (!retainedPending)\n await args.journal.appendEvent(args.root, terminalDownEvent(child, settlement, seq, at))\n // Retained work records its reconciled floor, never a terminal receipt. Recovery or\n // acknowledged release closes the reserved seq; crash healing uses this same record.\n else {\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 child.admission.reservation,\n )\n }\n child.failure = settlement.failure\n child.status = cancellation === undefined ? 'failed' : 'cancelled'\n child.outRef = settlement.outRef\n child.trace = settlement.trace\n child.providerModel = settlement.providerModel\n child.settledAt = settledAt\n child.settledSeq = seq\n if (retainedPending) {\n child.retainedExecution = 'pending'\n child.retainedPendingCause = settlement.retainedPendingCause\n }\n if (!retainedPending && nestedScope !== undefined)\n void releaseManagerEnvironment(nestedScope).catch(() => undefined)\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: frozenHandle<Out>(child),\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 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 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 child.settledAt = settledAt\n child.settledSeq = seq\n if (!child.recoveryPending && nestedScope !== undefined)\n void releaseManagerEnvironment(nestedScope).catch(() => undefined)\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: frozenHandle<Out>(child),\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/** Commit completed children eagerly; deliver their acknowledged results exactly once. */\nexport class ScopeSettlementCursor<Out> {\n readonly writes = new Set<Promise<Settled<Out>>>()\n private readonly publications = new Map<NodeId, { seq: number; result: Promise<Settled<Out>> }>()\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 for (;;) {\n const pending = [...this.children.values()].filter((c) => !c.delivered)\n if (pending.length === 0) {\n await Promise.all([...this.writes])\n return null\n }\n const chosen = this.firstPublished(pending)\n if (!chosen) {\n await raceFirstSettled(pending)\n continue\n }\n chosen.delivered = true\n return await this.published(chosen)\n }\n }\n\n readonly nextResolved = async (): Promise<Settled<Out> | null> => {\n for (;;) {\n const candidates = [...this.children.values()].filter((c) => !c.delivered)\n const pick = this.firstPublished(candidates) ?? candidates.find((c) => c.executorDone)\n if (!pick) {\n await Promise.all([...this.writes])\n return null\n }\n if (!this.publications.has(pick.id)) {\n await pick.settled\n continue\n }\n pick.delivered = true\n return await this.published(pick)\n }\n }\n\n readonly publish = (child: LiveChild, settlement: PreSeqSettled): Promise<Settled<Out>> => {\n const prior = this.publications.get(child.id)\n if (prior) return prior.result\n const seq = this.cursorSeq++\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.publications.set(child.id, { seq, result: pending })\n this.writes.add(pending)\n void pending.then(\n () => this.writes.delete(pending),\n () => this.writes.delete(pending),\n )\n return pending\n }\n\n private firstPublished(children: LiveChild[]): LiveChild | undefined {\n return children\n .filter((child) => this.publications.has(child.id))\n .sort((a, b) => this.publications.get(a.id)!.seq - this.publications.get(b.id)!.seq)[0]\n }\n\n private published(child: LiveChild): Promise<Settled<Out>> {\n const publication = this.publications.get(child.id)\n if (!publication) throw new ValidationError(`scope: child '${child.id}' has no publication`)\n return publication.result\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 { notifyExecutionAdmitted } from './executor-observation'\nimport { executorFailureReason } from './executor-outcome'\nimport {\n executorEvidenceWriter,\n leafContinuationExecutionId,\n type RetainedChildRecovery,\n type RetainedExecutorContext,\n} from './retained-executor'\nimport { DEFAULT_BUDGET_STOP_HOLD_MS } from './scope-capabilities'\nimport type { ChildAdmission, 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 attemptId,\n identity,\n recovery,\n opts,\n now,\n traceRoots,\n markRecoveryReady,\n admission,\n readLive,\n completeEvidence,\n}: {\n args: ScopeArgs\n controller: AbortController\n id: NodeId\n ordinal: number\n attemptId: string\n identity: NodeExecutionIdentity | undefined\n recovery: RetainedChildRecovery | undefined\n opts: SpawnOpts\n now: () => number\n traceRoots: TraceRootWriter\n markRecoveryReady: (() => void) | undefined\n admission: ChildAdmission\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 notifyExecutionAdmitted(args.hooks, args.root, id, admission, now, attemptId)\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 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 (admission.deadlineAtMs !== undefined && now() > admission.deadlineAtMs)\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 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 (budget.maxTokens !== undefined && chargedTokens(spent.tokens) > budget.maxTokens) ||\n (budget.maxIterations !== undefined && 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 historical envelopes; readers own event validation. @internal */\nexport function spawnJournalRecordEvents(\n record: unknown,\n invalid: 'throw' | 'skip' = 'throw',\n): ReadonlyArray<SpawnEvent> {\n const corrupt = (reason: string): ReadonlyArray<SpawnEvent> => {\n if (invalid === 'skip') return []\n throw new Error(`spawn journal corrupted: ${reason}`)\n }\n if (!isRecord(record)) return corrupt('record must be an object')\n if (record.kind === 'begin') return []\n const single = record.kind === 'event' || (record.kind === undefined && 'event' in record)\n if (!single && record.kind !== 'events')\n return corrupt(`unknown record kind '${String(record.kind)}'`)\n const events = single ? [record.event] : record.events\n if (!Array.isArray(events)) return corrupt('group has no events array')\n return 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, ReservationTicket } 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 observe completion without consuming it. Publication reserves the journal seq independently;\n * `delivered` guards exactly-once cursor delivery.\n */\nexport interface ChildAdmission {\n readonly ticket: ReservationTicket\n rehomed?: Spend\n onStatus?: (status: NodeStatus) => void\n prepareAccounting?: (closing?: boolean) => Promise<void>\n reservation?: Budget\n grantedAtMs?: number\n deadlineAtMs?: number\n}\n\nexport interface LiveChild {\n readonly admission: ChildAdmission\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 publication seq reserved for 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 {\n type BudgetPool,\n BudgetReconcileFault,\n budgetLeases,\n type ReservationTicket,\n} from './budget'\nimport { teardownExecutor } from './deadline'\nimport { errMessage } from './error-message'\nimport { withBudgetResources } from './resources'\nimport type { ChildAdmission, 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 admission: ChildAdmission,\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 await live.admission.prepareAccounting?.(true)\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(\n executor,\n grace,\n this.admission.deadlineAtMs,\n this.now,\n live.askTeardown,\n )\n await live.admission.prepareAccounting?.(true)\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 if (\n this.terminalTelemetryCaptured &&\n !live.recoveryPending &&\n live.readNestedScope?.() === undefined\n )\n budgetLeases.get(this.pool)?.observeTerminal(this.ticket, spend)\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 } = this\n const deadlineAtMs = this.admission.deadlineAtMs\n const startedAt = this.admission.grantedAtMs ?? 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 { retainedSessionReplaced } from '../retained-run-binding'\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, withBudgetResources } from './resources'\nimport { RetainedExecutionPendingError } from './retained-executor'\nimport { ChildExecutionAttempt } from './scope-child-attempt'\nimport type { ChildAdmission, 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 admission: ChildAdmission,\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 admission,\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 await live.events.start()\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 live.events.settle()\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 live.events.settle().catch(() => undefined)\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/** Publish the running total. Do not abort the fold: usage often arrives last, and overspend is reconciled.\n * Progress rows publish once a second; awaiting-result rows always publish. */\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 let publishedAt = Number.NEGATIVE_INFINITY\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}\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 (retainedSessionReplaced(err)) {\n // The admitted session is gone. A recovered child starts pending so a live remote\n // execution is not replaced; this one is not that execution.\n live.recoveryPending = false\n return await settleCrashed(attempt, err, executionEvidence)\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 the observed spend, not the reservation. Reconcile refunds reserved minus spent, so a\n // ceiling refunds nothing. A still-remote execution is an unknown floor. A ticket already\n // 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 = {\n ...unknownFloor(\n withBudgetResources(\n accounting?.reported ?? live.spent,\n opts.budget,\n accounting !== undefined,\n ),\n ),\n ms,\n }\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/** Fold usage after every event, so a running worker is observable and a mid-stream throw keeps its partial spend. */\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 minutes are known only at teardown, so the terminal artifact is what reaches the journal.\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 // The fold's running total is already the exact result. Only the artifact still has the split.\n ...(terminal.streamedTokens === undefined\n ? {}\n : { streamedTokens: cloneTokenUsage(terminal.streamedTokens) }),\n ...(terminal.unobservedTokens === undefined\n ? {}\n : { unobservedTokens: cloneTokenUsage(terminal.unobservedTokens) }),\n ...(terminal.iterationsKnown === false ? { iterationsKnown: false as const } : {}),\n }\n}\n\n/** An abort wins unless the result was already accepted, in which case the executor bounds the wait. */\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, chargedTokens, zeroSpend } from '../util'\nimport {\n type BudgetPoolRestore,\n BudgetReconcileFault,\n budgetRecoverySeeds,\n completedLeafBacking,\n createBudgetPool,\n} 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/** Heal release-to-terminal crashes across the forest using the original floor's settlement,\n * cursor seq and timestamp. Require a complete floor, later nonempty successful receipts,\n * and the latest admitted environment among them. Recorded results take precedence. */\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 // Complete floors require cursor, reason and trace; infra remains optional.\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 // Reserved cursors cannot be reused by recovery or healing.\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 // Replay the live release hook with original spawn and acknowledged release times.\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 // Intern equal mounted strings across recovered children.\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 // Earlier invocation results cannot settle the latest input.\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 // Replayed and live settlements use the same Runtime/provider attribution.\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/** Latest keyed attempts, resolved against durable settlements. An interrupted inline\n * invocation died with its process; remote invocations remain in doubt. */\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 = openReconciledFloors(events)\n const granted = new Set(\n events.filter((event) => event.kind === 'admission-granted').map((event) => event.id),\n )\n const unknown = 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 (event.attemptId === undefined || granted.has(event.id)) &&\n // Inline work died with its process; only external executions remain uncertain.\n event.runtime !== 'inline',\n )\n .map((event) => event.budget)\n return unknown\n}\n\nfunction openReconciledFloors(events: readonly SpawnEvent[]) {\n const terminal = new Set(events.filter(closesCursorSlot).map((event) => event.id))\n const floors = new Map<NodeId, Extract<SpawnEvent, { kind: 'reconciled' }>>()\n for (const event of events) {\n if (\n event.kind === 'reconciled' &&\n !terminal.has(event.id) &&\n event.seq > (floors.get(event.id)?.seq ?? -1)\n )\n floors.set(event.id, event)\n }\n return floors\n}\n\nfunction heldSpawnBudgets(\n events: readonly SpawnEvent[],\n recovered: ReadonlySet<NodeId> = new Set(),\n): Array<{ id: NodeId; budget: Budget; custody?: Budget }> {\n const floors = new Map<NodeId, Reconciled>()\n for (const event of events)\n if (event.kind === 'reconciled' && event.seq > (floors.get(event.id)?.seq ?? -1))\n floors.set(event.id, event)\n const spawns = new Map(\n events\n .filter((event): event is Spawned => event.kind === 'spawned')\n .map((event) => [event.id, event]),\n )\n const terminal = new Map(\n events\n .filter(\n (event): event is Extract<SpawnEvent, { kind: 'settled' | 'cancelled' }> =>\n event.kind === 'settled' || event.kind === 'cancelled',\n )\n .map((event) => [event.id, event]),\n )\n return [...spawns].flatMap(([id, spawned]) => {\n const floor = floors.get(id),\n closed = terminal.get(id)\n const legacy =\n spawned.attemptId === undefined && (!closed || closed.retainedExecution !== undefined)\n const accepted = events.some((event) => event.id === id && event.kind === 'execution-result')\n const completedLeaf =\n spawned.ownedTreeRoot === undefined &&\n closed?.spent !== undefined &&\n closed.retainedExecution !== 'release-unconfirmed' &&\n ((closed.kind === 'settled' && closed.status === 'done') || accepted)\n // A normal leaf can close without a floor. Its grant still backs physical custody;\n // a terminal usage receipt alone is not a resource-teardown acknowledgement.\n let reservation =\n floor?.reservation ??\n ((floor && legacy) || (completedLeaf && accepted && spawned.parent !== undefined)\n ? spawned.budget\n : undefined)\n if (reservation && completedLeaf && closed?.spent) {\n const owned = events.filter((event) => event.id === id)\n const lastAdmission = owned.reduce(\n (last, event, index) =>\n event.kind === 'admission-granted' || event.kind === 'execution-admitted' ? index : last,\n -1,\n )\n const cleanupConfirmed =\n closed.retainedExecution === 'released' ||\n owned.some((event, index) => event.kind === 'teardown-confirmed' && index > lastAdmission)\n reservation = completedLeafBacking(\n reservation,\n closed.spent,\n floor?.spent ?? zeroSpend(),\n cleanupConfirmed,\n )\n }\n if (recovered.has(id) || !reservation) return []\n const custody =\n completedLeaf && accepted && spawned.parent !== undefined && reservation.resources\n ? {\n resources: Object.fromEntries(\n Object.entries(spawned.budget.resources ?? reservation.resources).map(\n ([name, value]) => [\n name,\n {\n unit: value.unit,\n limit:\n closed?.spent?.resources?.[name]?.known === true\n ? (reservation.resources?.[name]?.limit ?? 0)\n : 0,\n },\n ],\n ),\n ),\n }\n : undefined\n return [\n {\n id,\n budget: {\n ...reservation,\n ...(reservation.resources\n ? {\n resources: Object.fromEntries(\n Object.entries(reservation.resources).map(([name, value]) => [\n name,\n { ...value, limit: value.limit - (custody?.resources[name]?.limit ?? 0) },\n ]),\n ),\n }\n : {}),\n maxTokens: reservation.maxTokens ?? 0,\n maxIterations: reservation.maxIterations ?? 0,\n maxUsd: reservation.maxUsd ?? 0,\n },\n ...(custody && Object.values(custody.resources).some((value) => value.limit > 0)\n ? { custody }\n : {}),\n },\n ]\n })\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/** Closed cursor seqs and open retained floors both reserve their original positions.\n * Recovery must allocate above both so a later heal cannot collide with new delivery. */\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/** Durable measured costs plus conservative unmeasured ceilings and remaining backing.\n * Unknown flags distinguish those charges from observed spend. */\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 remainingRootTokens = Math.max(\n 0,\n (rootBudget?.maxTokens ?? 0) -\n chargedTokens(totals.childWork.tokens) -\n chargedTokens(totals.driverInference.tokens),\n )\n let remainingRootIterations = Math.max(\n 0,\n (rootBudget?.maxIterations ?? 0) -\n totals.childWork.iterations -\n totals.driverInference.iterations,\n )\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 const iterationCharge = budget.maxIterations ?? remainingRootIterations\n totals.childWork.iterations += iterationCharge\n remainingRootIterations = Math.max(0, remainingRootIterations - iterationCharge)\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 const tokenCharge = budget.maxTokens ?? remainingRootTokens\n totals.childWork.tokens.input += tokenCharge\n remainingRootTokens = Math.max(0, remainingRootTokens - tokenCharge)\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 for (const { budget: held } of heldSpawnBudgets(events)) {\n totals.childWork = addSpend(totals.childWork, {\n ...zeroSpend(),\n iterations: held.maxIterations ?? 0,\n tokens: { input: held.maxTokens ?? 0, output: 0 },\n tokensKnown: (held.maxTokens ?? 0) === 0,\n usd: held.maxUsd ?? 0,\n usdKnown: (held.maxUsd ?? 0) === 0,\n ...(held.resources === undefined\n ? {}\n : {\n resources: Object.fromEntries(\n Object.entries(held.resources).map(([name, value]) => [\n name,\n { unit: value.unit, amount: value.limit, known: value.limit === 0 },\n ]),\n ),\n }),\n })\n }\n return totals\n}\n\nexport function 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 // Latest open floors are cumulative child work; terminal costs replace their spend only.\n const floors = openReconciledFloors(events)\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 }\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 // Heal the forest once at root entry; nested restore uses already healed events.\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 // Recovery attaches its original ticket to the prefix and backing seeded below.\n // Exclude them here so the pool credits them exactly once before admitting any new work.\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 const holds = heldSpawnBudgets(prior, recovering)\n const poolRestore: BudgetPoolRestore = {\n ...(hasCommittedEvidence\n ? { committed: addSpend(measured.childWork, measured.driverInference) }\n : {}),\n owner: measured.owner,\n uncertainReservations: uncertainSpawnBudgets(prior, recovering),\n heldReservations: holds.map(({ budget }) => budget),\n }\n budgetRecoverySeeds.set(poolRestore, [\n ...prepared.recoveries.map(({ spawned }) => {\n const owned = prior.filter((event) => event.id === spawned.id)\n const totals = sumMeasuredSpendFromEvents(owned)\n const floor = owned.filter((event) => event.kind === 'reconciled').at(-1)\n const reservation =\n floor?.reservation ??\n (spawned.attemptId === undefined ||\n owned.some((event) => event.kind === 'admission-granted')\n ? spawned.budget\n : undefined)\n return {\n id: spawned.id,\n spent: withBudgetResources(\n addSpend(totals.childWork, totals.driverInference),\n spawned.budget,\n true,\n ),\n held: {\n ...(spawned.budget.maxTokens === undefined\n ? {}\n : { maxTokens: reservation?.maxTokens ?? 0 }),\n ...(spawned.budget.maxIterations === undefined\n ? {}\n : { maxIterations: reservation?.maxIterations ?? 0 }),\n ...(spawned.budget.maxUsd === undefined ? {} : { maxUsd: reservation?.maxUsd ?? 0 }),\n ...(spawned.budget.resources === undefined\n ? {}\n : {\n resources: Object.fromEntries(\n Object.entries(spawned.budget.resources).map(([name, value]) => [\n name,\n { unit: value.unit, limit: reservation?.resources?.[name]?.limit ?? 0 },\n ]),\n ),\n }),\n },\n }\n }),\n ...holds.flatMap(({ id, custody }) =>\n custody ? [{ id, spent: zeroSpend(), held: custody, closed: true as const }] : [],\n ),\n ])\n return {\n poolRestore,\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","/**\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 paused: 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>()\nconst permitOwners = new WeakMap<SlotPermit, { allocator: AllocatorState; depth: number }>()\n\n/** Pause only this owner's work; descendants retain their existing counted/lent units. */\nexport function pauseWorkerSlot(handle: SlotPermit): void {\n const inner = deferredPermits.get(handle)?.() ?? handle\n const permit = permitStates.get(inner)\n const owner = permitOwners.get(inner)\n if (!permit || !owner || permit.released || permit.paused) return\n permit.paused = true\n if (permit.granted) releasePermit(owner.allocator, permit)\n pump(owner.allocator)\n}\n\n/** Reacquire the same permit identity and child group using the ordinary fair queue. */\nexport function resumeWorkerSlot(handle: SlotPermit): Promise<void> {\n const inner = deferredPermits.get(handle)?.() ?? handle\n const permit = permitStates.get(inner)\n const owner = permitOwners.get(inner)\n if (!permit || !owner || permit.released)\n return Promise.reject(new ValidationError('closed worker slot cannot resume'))\n permit.paused = false\n if (permit.granted) return Promise.resolve()\n const state = owner.allocator\n if ((permit.children?.running ?? 0) > 0) {\n // Children that started while their owner slept already account for the working unit.\n if (costOf(permit.group) === 0) {\n permit.group.owner!.counted = false\n state.working -= 1\n }\n permit.granted = true\n permit.group.running += 1\n return Promise.resolve()\n }\n return new Promise<void>((resolve) => {\n const grant = () => {\n grantPermit(state, permit)\n resolve()\n }\n if (costOf(permit.group) === 0 || hasCapacity(state)) grant()\n else {\n permit.group.queued += 1\n state.waiters.push({ permit, depth: owner.depth, order: state.order++, grant })\n }\n })\n}\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 = {\n group,\n granted: false,\n released: false,\n paused: false,\n counted: false,\n }\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 permitOwners.set(handle, { allocator: state, depth })\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.paused && 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 if (permit.paused) permit.granted = false\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 || owner.paused) 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 { contentAddress } from '../../durable/content-address'\nimport { addSpend, chargedTokens, unreportedSpend, zeroSpend } from '../util'\nimport { runAbortable } from './abortable'\nimport { budgetLeases, budgetLeaseUpdates, createBudgetPool, refreshBudgetLease } from './budget'\nimport { prepareScopeResume, sumMeasuredSpendFromEvents } from './recover-executors'\nimport { withBudgetResources } from './resources'\nimport { scopeOwnerLiabilities } from './retained-owner-state'\nimport { scopeSeatAccountingUpdates, seatAdmissionPauses } from './scope-capabilities'\nimport { createScope } from './scope-construction'\nimport type {\n ChildAdmission,\n DeferredOwnerSlot,\n NestedScopeSeam,\n ScopeArgs,\n} from './scope-contract'\nimport { appendAcknowledged } from './scope-settlement'\nimport type { Budget, NodeId, Scope, SpawnEvent } from './types'\nimport {\n pauseWorkerSlot,\n resumeWorkerSlot,\n type SlotPermit,\n type WorkerSlots,\n} from './worker-slots'\n\nexport function makeNestedScopeSeam(\n args: ScopeArgs,\n workerSlots: WorkerSlots,\n childSlot: SlotPermit,\n childNodeId: NodeId,\n childBudget: Budget,\n admission: ChildAdmission,\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 childDeadlineAtMs = admission.deadlineAtMs\n const deadlineMs =\n childDeadlineAtMs === undefined ? undefined : Math.max(0, childDeadlineAtMs - mountedAtMs)\n const nestedBudget = {\n ...childBudget,\n ...(deadlineMs !== undefined ? { deadlineMs } : {}),\n }\n const pool = createBudgetPool(nestedBudget, mountedAtMs, restored?.poolRestore)\n const scope = createScope<unknown>({\n parentId: childNodeId,\n root: nestedRoot,\n rootDeadlineAtMs: args.rootDeadlineAtMs,\n pool,\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 bindSeatAdmission(scope, pool, nestedRoot)\n return scope\n }\n\n const bindSeatAdmission = (\n scope: Scope<unknown>,\n pool: ReturnType<typeof createBudgetPool>,\n nestedRoot: NodeId,\n ) => {\n const ownerLease = budgetLeases.get(args.pool)!\n const nestedLease = budgetLeases.get(pool)!\n if (!ownerLease || !nestedLease) return\n let activated = admission.reservation !== undefined\n let parked = false\n let queuedResumeAt: string | undefined\n let tail = Promise.resolve()\n const synchronize = (closing = false): Promise<void> => {\n const update = tail.then(async () => {\n if (closing) {\n activated = true\n parked = true\n }\n if (!activated || !ownerLease.isBacked(admission.ticket)) return\n const nested = (await args.journal.loadTree(nestedRoot)) ?? []\n const totals = sumMeasuredSpendFromEvents(nested, childNodeId)\n const childWork = withBudgetResources(totals.childWork, childBudget, true)\n const parent = ((await args.journal.loadTree(args.root)) ?? []).filter(\n (event) => event.id === childNodeId,\n )\n const reported = parent.reduce(\n (sum, event) => (event.kind === 'metered' ? addSpend(sum, event.spend) : sum),\n zeroSpend(),\n )\n const at = new Date(now()).toISOString()\n if (contentAddress(reported) !== contentAddress(totals.driverInference)) {\n const delta = unreportedSpend(totals.driverInference, reported)\n await appendAcknowledged(args.journal, args.root, {\n kind: 'metered',\n id: childNodeId,\n spend: delta,\n at,\n seq: parent.reduce(\n (seq, event) => (event.kind === 'metered' ? Math.max(seq, event.seq + 1) : seq),\n 0,\n ),\n })\n admission.rehomed = addSpend(admission.rehomed ?? zeroSpend(), delta)\n }\n const spent = addSpend(childWork, totals.driverInference)\n let liabilities = nestedLease.liabilities(spent)\n const custody = scopeOwnerLiabilities(scope, nested)\n if (custody.environmentHeld || custody.invocationUnsettled) {\n if (childBudget.resources)\n liabilities = {\n ...liabilities,\n resources: Object.fromEntries(\n Object.entries(childBudget.resources).map(([name, value]) => [\n name,\n {\n unit: value.unit,\n limit: Math.max(\n liabilities.resources?.[name]?.limit ?? 0,\n custody.measuredResources.get(name) === value.unit\n ? 0\n : value.limit - (spent.resources?.[name]?.amount ?? 0),\n ),\n },\n ]),\n ),\n }\n if (custody.invocationUnsettled) {\n if (childBudget.maxTokens !== undefined)\n liabilities = {\n ...liabilities,\n maxTokens: Math.max(\n liabilities.maxTokens ?? 0,\n childBudget.maxTokens - chargedTokens(spent.tokens),\n ),\n }\n if (childBudget.maxIterations !== undefined)\n liabilities = {\n ...liabilities,\n maxIterations: Math.max(\n liabilities.maxIterations ?? 0,\n childBudget.maxIterations - spent.iterations,\n ),\n }\n if (childBudget.maxUsd !== undefined)\n liabilities = {\n ...liabilities,\n maxUsd: Math.max(liabilities.maxUsd ?? 0, childBudget.maxUsd - spent.usd),\n }\n }\n }\n const reservation = ownerLease.plannedHold(\n admission.ticket,\n childBudget,\n spent,\n liabilities,\n parked,\n )\n const floor = parent.filter((event) => event.kind === 'reconciled').at(-1)\n const floorSpend = floor?.settledSeq === undefined ? childWork : floor.spent\n if (\n floor?.kind !== 'reconciled' ||\n contentAddress(floor.spent) !== contentAddress(floorSpend) ||\n contentAddress(floor.reservation ?? null) !== contentAddress(reservation)\n ) {\n await appendAcknowledged(args.journal, args.root, {\n ...floor,\n kind: 'reconciled',\n id: childNodeId,\n spent: floorSpend,\n reservation,\n at,\n seq: parent.reduce(\n (seq, event) => (event.kind === 'reconciled' ? Math.max(seq, event.seq + 1) : seq),\n 0,\n ),\n })\n }\n admission.reservation = reservation\n ownerLease.rebase(admission.ticket, childBudget, spent, liabilities, parked)\n await refreshBudgetLease(args.pool)\n })\n tail = update\n return update\n }\n budgetLeaseUpdates.set(pool, synchronize)\n scopeSeatAccountingUpdates.set(scope, synchronize)\n admission.prepareAccounting = synchronize\n const transition = async (gate?: 'seat' | 'budget' | 'slot', resumeAt?: string) => {\n const events = ((await args.journal.loadTree(args.root)) ?? []).filter(\n (event): event is Extract<SpawnEvent, { kind: 'admission-queued' | 'admission-granted' }> =>\n event.id === childNodeId &&\n (event.kind === 'admission-queued' || event.kind === 'admission-granted'),\n )\n const seq = events.reduce((max, event) => Math.max(max, event.seq + 1), 0)\n const prior = events.find((event) => event.kind === 'admission-granted')\n if (prior?.kind !== 'admission-granted')\n throw new Error('seat pause has no original execution grant')\n const attemptId = events.at(-1)!.attemptId\n await args.journal.appendEvent(\n args.root,\n gate\n ? {\n kind: 'admission-queued',\n id: childNodeId,\n attemptId,\n gate,\n ...(resumeAt === undefined ? {} : { resumeAt }),\n seq,\n at: new Date(now()).toISOString(),\n }\n : { ...prior, attemptId, seq, at: new Date(now()).toISOString() },\n )\n }\n const resume = async () => {\n scope.signal.throwIfAborted()\n parked = false\n const funded = ownerLease.resume(admission.ticket)\n if (ownerLease.isPaused(admission.ticket)) await transition('budget')\n await runAbortable(() => funded, scope.signal, 'seat reentry budget aborted')\n const ready = resumeWorkerSlot(childSlot)\n if (!childSlot.granted) await transition('slot')\n await runAbortable(() => ready, scope.signal, 'seat reentry slot aborted')\n await synchronize()\n await transition()\n scope.signal.throwIfAborted()\n nestedLease.blocked = false\n queuedResumeAt = undefined\n admission.onStatus?.('running')\n }\n seatAdmissionPauses.set(scope, async (resumeAt) => {\n scope.signal.throwIfAborted()\n activated = true\n parked = true\n nestedLease.blocked = true\n pauseWorkerSlot(childSlot)\n admission.onStatus?.('queued')\n if (queuedResumeAt !== resumeAt) {\n await transition('seat', resumeAt)\n queuedResumeAt = resumeAt\n }\n await synchronize()\n return resume\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 * On-disk supervisor run layout: `<root>/.agent/supervisor/<id>`. `@tangle-network/traces` reads it\n * via `traces analyze --supervisor-run-dir`. Older writers used `.loops/supervisor/<id>`; readers\n * keep that fallback and this writer never creates `.loops`. Layout, relative to\n * `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 * questions/<id>.json an `ask_parent` question {@link fileEscalateQuestion} hands to an\n * outside observer, who answers with a root `writeWorkerSteer`\n * cancellations/requests.ndjson worker-scoped cancel requests (durable inbox); each line is a\n * {@link WorkerCancelRequest}\n * cancellations/<opId>.json a {@link WorkerCancellation}, written ONLY by the owning\n * manager's acknowledger (labels resolve at the root 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 its {@link RunCancellation}, written ONLY by the runtime\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 * Steer admission requires the exact worker id and a caller-owned operation id. One atomic request\n * file is the durable inbox; the NDJSON file is a readable projection that 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 { EscalateQuestion } from '../../mcp/tools/coordination-questions'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport {\n appendDurableFile,\n assertNoSymlinkDescendant,\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from './durable-file'\n\n/** An `escalateQuestion` that writes each `ask_parent` question to `questions/<id>.json` for an\n * out-of-process observer, who answers through `writeWorkerSteer` on the root (#1165). */\nexport function fileEscalateQuestion(rootDir: string, runId: string): EscalateQuestion {\n return (question) => {\n const dir = join(supervisorRunDir(rootDir, runId), 'questions')\n mkdirSync(dir, { recursive: true })\n const file = join(dir, `${question.id.replace(/[^\\w.-]/g, '_')}.json`)\n writeAtomicDurableFile(file, `${JSON.stringify(question, null, 2)}\\n`, { mode: 0o600 })\n return { delivered: true, to: file }\n }\n}\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/** A `task` tool result names the session the harness itself spawned (`<task id=\"ses_...\">` or\n * `task_id: ses_...`), the same text `shared-box-worker` reads from a live part. #1264: the id\n * reached no record, so a subagent the harness completed stayed invisible to settle and\n * coverage alike. */\nconst TASK_SESSION_ID = /(?:<task id=\"|task_id: )(ses_[A-Za-z0-9]+)/gu\n\nfunction subagentSessionIdsIn(event: ExecutorProgressEvent): readonly string[] {\n if (event.kind !== 'tool_result' || event.toolName !== 'task') return []\n const ids: string[] = []\n for (const text of [event.result, event.error?.message]) {\n if (typeof text !== 'string') continue\n for (const match of text.matchAll(TASK_SESSION_ID)) ids.push(match[1]!)\n }\n return ids\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 const subagentSessionIds = new Set<string>()\n try {\n for await (const record of readCommittedJsonLines<RootStreamRecord>(path, {\n onBytes: (bytes) => void hash.update(bytes),\n })) {\n events += 1\n if ('event' in record)\n for (const id of subagentSessionIdsIn(record.event)) subagentSessionIds.add(id)\n }\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return Object.freeze({\n ref: `sha256:${hash.digest('hex')}`,\n events,\n ...(subagentSessionIds.size > 0 ? { subagentSessionIds: [...subagentSessionIds] } : {}),\n })\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(\n runDir: string,\n options: { readonly nodeId?: string } = {},\n): Promise<RootStreamRecord[] | undefined> {\n if (options.nodeId !== undefined && options.nodeId.trim().length === 0)\n throw new TypeError('node stream: nodeId must be non-empty')\n const dir = resolve(runDir)\n const path = resolve(\n dir,\n options.nodeId === undefined ? ROOT_STREAM_FILE : nodeStreamFile(options.nodeId),\n )\n assertNoSymlinkDescendant(dir, path, 'node stream')\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 readonly #stream: WorkerEventStream | undefined\n #sink: RootStreamSink | undefined\n #writes: Promise<void> = Promise.resolve()\n #failure: unknown\n\n constructor(\n stream?: WorkerEventStream,\n private readonly observeProgress?: (event: ExecutorProgressEvent, at: number) => void,\n ) {\n this.#stream = stream\n }\n\n async start(): Promise<void> {\n this.#capturing = true\n const stream = this.#stream\n if (stream === undefined) return\n this.#sink = createRootStreamSink(stream.runDir, stream.now, nodeStreamFile(stream.nodeId), {\n continueAttempts: true,\n })\n await this.#sink.beginAttempt()\n }\n #bytes = 0\n\n append(event: ExecutorProgressEvent, at: number): void {\n const redacted = defaultRedactor(event)\n this.observeProgress?.(redacted as ExecutorProgressEvent, at)\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 sink = this.#sink\n if (sink === undefined) return\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 createExecutorObservation,\n createToolProgressObserver,\n executorObservationSeamKey,\n} from './executor-observation'\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 ChildAdmission,\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 ExecutorProgressEvent,\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 admission: ChildAdmission\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 readonly onProgress: (event: ExecutorProgressEvent) => void\n },\n): ExecutorContext {\n const { id, identity, recovery, continuing, opts } = child\n const interactiveBindingDir = args.interactiveBindingDir\n const observation = createExecutorObservation(\n args.hooks,\n {\n rootId: args.root,\n parentId: args.parentId,\n nodeId: id,\n attemptId: child.attemptId,\n },\n seams.onProgress,\n )\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 [executorObservationSeamKey]: observation,\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, seams: { ...args.seams, [executorObservationSeamKey]: observation } },\n seams.workerSlots,\n seams.permit,\n id,\n opts.budget,\n child.admission,\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 admission: child.admission,\n events: new WorkerEvents(\n args.interactiveBindingDir === undefined\n ? undefined\n : { runDir: args.interactiveBindingDir, nodeId: id, now },\n createToolProgressObserver(\n createExecutorObservation(\n args.hooks,\n {\n rootId: args.root,\n parentId: args.parentId,\n nodeId: id,\n attemptId: child.attemptId,\n },\n () => {},\n ),\n ),\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 attemptId: child.attemptId,\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 { unreportedSpend, zeroSpend } from '../util'\nimport { runAbortable } from './abortable'\nimport {\n budgetLeases,\n type ReservationHolder,\n type ReservationShortfall,\n type ReservationTicket,\n} 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 publishSettlement: (child: LiveChild, settlement: PreSeqSettled) => Promise<unknown>\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 // Seal concrete profiles before admission; construct lazy factories only after funding.\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 * Fresh work reserves current funds before constructing a lazy factory. An original retained\n * invocation may queue without holding funds until a real settlement covers its ceiling.\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 const holder: ReservationHolder = {\n ...(assignment === undefined ? {} : { assignment }),\n label: opts.label,\n stage: 'admitted',\n }\n const lease = budgetLeases.get(args.pool)\n if (recovery && lease)\n return lease.recover(opts.budget, holder, recovery.spawned.id, ownerFloor)\n return args.pool.reserve(opts.budget, holder, {\n wait: recovery !== undefined,\n ...(!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 * A synchronous startup failure refunds its ticket before runChild takes ownership.\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 child.admission.reservation = budgetLeases.get(args.pool)?.reservation(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 attemptId: child.attemptId,\n identity: child.identity,\n recovery,\n opts,\n now,\n traceRoots,\n markRecoveryReady,\n admission: child.admission,\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 onProgress: (event) => live.events.append(event, 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 child.admission.onStatus = (status) => {\n live.status = status\n }\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 const executionReady = this.grantChild(\n child,\n live,\n controller,\n cleanup,\n materialization.ready,\n budgetGranted,\n permit,\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 executionReady,\n {\n complete: async () => materialization.complete(),\n fail: async () => materialization.fail(),\n },\n child.admission,\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 // Slots bound active work; cleanup uncertainty remains independently owned by custody.\n this.releaseStart(permit, cleanup)\n })\n .then(async (resolution) => {\n if (resolution.metered && live.admission.rehomed)\n resolution = {\n ...resolution,\n metered: unreportedSpend(resolution.metered, live.admission.rehomed),\n }\n await this.deps.publishSettlement(live, resolution)\n return resolution\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 const prior = (args.resumeFrom?.events ?? []).filter((event) => event.id === id)\n const granted = prior.find((event) => event.kind === 'admission-granted')\n // Legacy journals have no grant clock: preserve their original spawn-based cutoff.\n const legacy = recovery !== undefined && recovery.spawned.attemptId === undefined\n return {\n id,\n ordinal,\n attemptId,\n startedAt,\n admission:\n granted?.kind === 'admission-granted'\n ? {\n ticket,\n grantedAtMs: Date.parse(granted.deadlineArmedAt),\n deadlineAtMs:\n granted.deadlineAt === undefined ? undefined : Date.parse(granted.deadlineAt),\n }\n : legacy\n ? {\n ticket,\n grantedAtMs: startedAt,\n deadlineAtMs: boundedChildDeadlineAt(\n args.pool.readout().deadlineMs,\n opts.budget.deadlineMs,\n startedAt,\n ),\n }\n : { ticket },\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 * Cancellation and the parent's cutoff apply while queued; the child's time box starts at grant.\n */\n private armChildAbort(child: AdmittedChild, cleanup: StartCleanup): AbortController {\n const { args } = this.deps\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 this.armDeadline(\n child,\n controller,\n cleanup,\n child.admission.deadlineAtMs ??\n boundedChildDeadlineAt(args.pool.readout().deadlineMs, undefined, 0),\n )\n return controller\n }\n\n private armDeadline(\n child: AdmittedChild,\n controller: AbortController,\n cleanup: StartCleanup,\n deadlineAtMs: number | undefined,\n ): void {\n cleanup.clearChildDeadline?.()\n if (deadlineAtMs === undefined) return\n const { args, now } = this.deps\n const rootDeadline = args.rootDeadlineAtMs ?? args.pool.readout().deadlineMs\n const timeBox = !(rootDeadline > 0 && deadlineAtMs >= rootDeadline)\n let clearCheckIn: (() => void) | undefined\n const clear = armDeadlineTimer(Math.max(0, deadlineAtMs - now()), () => {\n clearCheckIn = timeBox ? this.deps.checkInAtTimeBox(child.id, controller) : undefined\n if (clearCheckIn === undefined) controller.abort(CHILD_DEADLINE_REASON)\n })\n cleanup.clearChildDeadline = () => {\n clear()\n clearCheckIn?.()\n }\n }\n\n private async grantChild(\n child: AdmittedChild,\n live: LiveChild,\n controller: AbortController,\n cleanup: StartCleanup,\n materialized: Promise<void>,\n budgetReady: Promise<void> | undefined,\n permit: SlotPermit,\n ): Promise<void> {\n const { args, now } = this.deps\n const queuedAt = new Date(now()).toISOString()\n const gate = budgetReady !== undefined ? 'budget' : permit.granted ? undefined : 'slot'\n const prior = (args.resumeFrom?.events ?? []).filter(\n (event) =>\n event.id === child.id &&\n (event.kind === 'admission-queued' || event.kind === 'admission-granted'),\n )\n let seq = prior.reduce((max, event) => Math.max(max, event.seq + 1), 0)\n const queue = (gate: 'budget' | 'slot', at = new Date(now()).toISOString()) =>\n args.journal.appendEvent(args.root, {\n kind: 'admission-queued',\n id: child.id,\n attemptId: child.attemptId,\n gate,\n seq: seq++,\n at,\n })\n await materialized\n if (gate !== undefined) await queue(gate, queuedAt)\n controller.signal.throwIfAborted()\n if (budgetReady !== undefined) {\n await runAbortable(() => budgetReady, controller.signal, 'budget admission aborted')\n }\n if (gate === 'budget' && !permit.granted) await queue('slot')\n await runAbortable(() => permit.ready, controller.signal, 'slot admission aborted')\n controller.signal.throwIfAborted()\n child.admission.grantedAtMs ??= now()\n child.admission.deadlineAtMs ??= boundedChildDeadlineAt(\n args.pool.readout().deadlineMs,\n child.opts.budget.deadlineMs,\n child.admission.grantedAtMs,\n )\n await args.journal.appendEvent(args.root, {\n kind: 'admission-granted',\n id: child.id,\n attemptId: child.attemptId,\n deadlineArmedAt: new Date(child.admission.grantedAtMs).toISOString(),\n ...(child.admission.deadlineAtMs === undefined\n ? {}\n : {\n deadlineAt: new Date(child.admission.deadlineAtMs).toISOString(),\n }),\n seq,\n at: new Date(now()).toISOString(),\n })\n if (child.admission.deadlineAtMs !== undefined && now() >= child.admission.deadlineAtMs)\n controller.abort(CHILD_DEADLINE_REASON)\n controller.signal.throwIfAborted()\n live.status = 'acquiring'\n this.armDeadline(child, controller, cleanup, child.admission.deadlineAtMs)\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 // Pending owned managers still need their own release even after descendants confirmed.\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.retainedExecution !== 'released' &&\n (child.recoveryPending === true || child.ownedTreeRoot !== undefined) &&\n child.teardownPermanent !== true &&\n child.releaseRetained !== undefined &&\n child.confirmTeardown !== undefined,\n )\n // Ordinary cleanup retries skip retained executions; their continuation owns release.\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 // Permanent refusals cannot change on another sweep.\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 child.cleanupConfirmed = false\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 // Snapshot duplicate guards once for the whole sweep.\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 // Only acknowledged native receipts may reduce a paused child's remaining backing.\n await child.admission.prepareAccounting?.()\n // Close only after this pass's release and confirmation acknowledgements. A manager\n // journals its native receipts inside its own tree and may return []; confirmation\n // must still find no owner or descendant debt. Refusals remain unconfirmed.\n // The durable floor retains the original settlement and cursor seq for crash healing.\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 // Restate the settlement in hook order without metering inference 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 // The sweep (or crash healing) owns confirmed release. Close remaining cursor slots\n // as unconfirmed, independently of a stale descendant-only cleanup flag.\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 { notifyRuntimeHookEvent } from '../../runtime-hooks'\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 private steerSequence = 0\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.executorDone || 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 notifyRuntimeHookEvent(this.args.hooks, {\n id: `${this.args.parentId}:steer:${nodeId}:${this.steerSequence++}`,\n runId: this.args.root,\n parentId: this.args.parentId,\n target: 'agent.steer',\n phase: 'after',\n timestamp: child.lastActivityAt,\n payload: { nodeId },\n })\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.executorDone && !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 { notifyRuntimeHookEvent } from '../../runtime-hooks'\nimport { refreshBudgetLease } from './budget'\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 { registerScopeRetainedOwner } 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 { detachedSnapshot } from './snapshot'\nimport type {\n NodeId,\n ResumedKeyState,\n ResumedWork,\n Scope,\n Settled,\n SpawnEvent,\n TreeView,\n} 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(\n args,\n now,\n () => ownerMaterializationStates.get(scope)?.attemptId,\n )\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 publishSettlement: async (child, settlement): Promise<unknown> => {\n const published = await cursor.publish(child, settlement)\n await refreshBudgetLease(args.pool)\n return published\n },\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 ...(args.hooks ? { hooks: args.hooks } : {}),\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 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 ?? 0) * reservationPolicy.ownerShare),\n iterations: Math.ceil((ownerBudget.maxIterations ?? 0) * 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 const event: Extract<SpawnEvent, { kind: 'driver-attempt' }> = {\n kind: 'driver-attempt',\n id: args.parentId,\n record: detachedSnapshot(\n {\n ...record,\n ...(record.error === undefined ? {} : { error: errorText(record.error) }),\n ...(observed === undefined ? {} : { observed }),\n },\n 'driver attempt record',\n ),\n ...(attemptId === undefined ? {} : { attemptId }),\n seq: driverAttemptSeq++,\n at: new Date(now()).toISOString(),\n }\n await args.journal.appendEvent(args.root, event)\n notifyRuntimeHookEvent(\n args.hooks,\n {\n id: `${event.id}:driver-attempt:${event.seq}`,\n runId: args.root,\n parentId: event.id,\n target: 'agent.execution',\n phase: 'event',\n timestamp: Date.parse(event.at),\n payload: {\n nodeId: event.id,\n ...(event.attemptId === undefined ? {} : { attemptId: event.attemptId }),\n record: event.record,\n },\n },\n { signal: args.signal },\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","import type {\n NodeId,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n SpawnEvent,\n} from '../../runtime/supervise/types'\nimport type { SpawnForest, SpawnForestNode } from './spawn-forest'\n\n/**\n * Aggregate provider-served model evidence across one recursively owned journal forest.\n *\n * The parent tree records an owned driver's terminal summary, while that driver's own inference\n * and descendants live in its owned tree. This reducer follows the forest reader's explicit tree\n * edges and consumes each tree's metered attempts plus terminal leaf settlements exactly once.\n * A summary node is skipped because its owned tree supplies the source records. Plan materialization\n * is intentionally not read: it proves only what Runtime requested, not what a provider served.\n *\n * Missing legacy evidence, an unfinished node, an unopened owned tree, an identity conflict, and a\n * paid attempt without a qualified served snapshot all return unknown. An explicit\n * `providerDispatch: \"not_started\"` arm and Runtime accounting-only metered records are ignored\n * for served-model identity, while absent or malformed legacy data remains unknown here.\n */\nexport function aggregateProviderModelEvidence(\n forest: SpawnForest,\n): ProviderModelExecutionEvidence {\n const attempts: ProviderModelAttemptEvidence[] = []\n const observedModels = new Set<string>()\n const canonicalModels = new Set<string>()\n const nodes = new Map<string, SpawnForestNode>()\n let reason: 'provider-model-missing' | 'provider-model-conflict' | undefined\n let sawProviderEvidence = false\n\n for (const node of forest.nodes) nodes.set(forestNodeKey(node.treeRoot, node.id), node)\n if (forest.missingTrees.length > 0 || forest.inDoubt.length > 0) {\n reason = 'provider-model-missing'\n }\n\n const markMissing = () => {\n reason ??= 'provider-model-missing'\n }\n const markConflict = () => {\n reason = 'provider-model-conflict'\n }\n\n const append = (raw: unknown): void => {\n sawProviderEvidence = true\n if (!isProviderEvidenceObject(raw)) {\n markMissing()\n return\n }\n if (raw.status === 'unknown') {\n if (raw.reason === 'provider-model-conflict') {\n markConflict()\n } else if (!hasOnlyNotStartedAttempts(raw)) {\n markMissing()\n }\n } else if (raw.status !== 'known') {\n markMissing()\n return\n }\n if (!Array.isArray(raw.attempts) || !Array.isArray(raw.models)) {\n markMissing()\n return\n }\n\n const declared = new Set<string>()\n for (const model of raw.models) {\n if (typeof model !== 'string' || model.length === 0) {\n markMissing()\n } else {\n declared.add(model)\n }\n }\n const observedInRecord = new Set<string>()\n for (const rawAttempt of raw.attempts) {\n if (!isProviderAttemptEvidence(rawAttempt)) {\n markMissing()\n continue\n }\n if (rawAttempt.identityConflict === true) markConflict()\n const observations = [...rawAttempt.observations]\n if (rawAttempt.providerDispatch === 'not_started') {\n if (observations.length > 0) markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze([]),\n providerDispatch: 'not_started' as const,\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n continue\n }\n if (observations.length === 0) {\n markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze([]),\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n continue\n }\n let base: string | undefined\n let snapshot: string | undefined\n for (const model of observations) {\n if (typeof model !== 'string' || model.length === 0) {\n markMissing()\n continue\n }\n observedInRecord.add(model)\n observedModels.add(model)\n const identity = servedIdentityParts(model)\n if (identity === undefined) {\n markMissing()\n continue\n }\n if (base !== undefined && base !== identity.base) markConflict()\n if (\n snapshot !== undefined &&\n identity.snapshot !== undefined &&\n snapshot !== identity.snapshot\n ) {\n markConflict()\n }\n base = identity.base\n snapshot ??= identity.snapshot\n if (identity.snapshot !== undefined) {\n canonicalModels.add(`${identity.base}@${identity.snapshot}`)\n if (canonicalModels.size > 1) markConflict()\n }\n }\n if (base === undefined || snapshot === undefined) markMissing()\n attempts.push(\n Object.freeze({\n observations: Object.freeze(observations),\n ...(rawAttempt.identityConflict === true ? { identityConflict: true } : {}),\n }),\n )\n }\n if (\n declared.size !== observedInRecord.size ||\n [...declared].some((model) => !observedInRecord.has(model))\n ) {\n markMissing()\n }\n }\n\n const terminal = (\n treeRoot: NodeId,\n event: Extract<SpawnEvent, { kind: 'settled' | 'cancelled' }>,\n ) => {\n const node = nodes.get(forestNodeKey(treeRoot, event.id))\n if (node === undefined) {\n markMissing()\n return\n }\n // This event is a parent-side summary. Its owned tree is the authoritative source and is\n // traversed above; consuming its summary here would count nested attempts twice.\n if (node.ownedTreeRoot !== undefined) return\n if (event.kind === 'cancelled' && event.providerModel === undefined) {\n markMissing()\n return\n }\n append(event.providerModel ?? node.providerModel)\n }\n\n for (const tree of forest.trees) {\n for (const event of tree.events) {\n if (event.kind === 'metered') {\n if (event.accountingOnly === true) {\n if (event.providerModel !== undefined) markMissing()\n continue\n }\n // The parent scope re-homes a driver's nested metered spend onto the driver's parent node.\n // Its owned tree carries the provider attempts; consuming this summary would both\n // double-count and treat the spend-only legacy summary as missing identity evidence.\n const summaryNode = nodes.get(forestNodeKey(tree.root, event.id))\n if (summaryNode?.ownedTreeRoot !== undefined) continue\n const evidence = (event as SpawnEvent & { providerModel?: unknown }).providerModel\n if (evidence === undefined) markMissing()\n else append(evidence)\n } else if (event.kind === 'settled' || event.kind === 'cancelled') {\n terminal(tree.root, event)\n }\n }\n }\n\n if (!sawProviderEvidence || attempts.length === 0 || observedModels.size === 0) {\n reason ??= 'provider-model-missing'\n }\n const models = Object.freeze([...observedModels])\n const frozenAttempts = Object.freeze(attempts)\n return Object.freeze(\n reason === undefined\n ? { status: 'known' as const, attempts: frozenAttempts, models }\n : { status: 'unknown' as const, attempts: frozenAttempts, models, reason },\n )\n}\n\nfunction forestNodeKey(treeRoot: NodeId, nodeId: NodeId): string {\n return `${treeRoot}\\u0000${nodeId}`\n}\n\nfunction isProviderEvidenceObject(value: unknown): value is ProviderModelExecutionEvidence {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && 'status' in value\n}\n\nfunction hasOnlyNotStartedAttempts(evidence: ProviderModelExecutionEvidence): boolean {\n return (\n Array.isArray(evidence.attempts) &&\n evidence.attempts.length > 0 &&\n evidence.attempts.every(\n (attempt) =>\n isProviderAttemptEvidence(attempt) &&\n attempt.providerDispatch === 'not_started' &&\n attempt.observations.length === 0 &&\n attempt.identityConflict !== true,\n )\n )\n}\n\nfunction isProviderAttemptEvidence(value: unknown): value is ProviderModelAttemptEvidence {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n Array.isArray((value as { observations?: unknown }).observations) &&\n ((value as { providerDispatch?: unknown }).providerDispatch === undefined ||\n (value as { providerDispatch?: unknown }).providerDispatch === 'not_started')\n )\n}\n\nfunction servedIdentityParts(\n model: string,\n): { readonly base: string; readonly snapshot?: string } | undefined {\n const at = model.lastIndexOf('@')\n const rawBase = at < 0 ? model : model.slice(0, at)\n const base = rawBase.slice(rawBase.lastIndexOf('/') + 1)\n if (base.length === 0) return undefined\n const snapshot = at < 0 ? undefined : model.slice(at + 1)\n if (snapshot !== undefined && snapshot.length === 0) return undefined\n return snapshot === undefined ? { base } : { base, snapshot }\n}\n","import type { AgentProfile } from '@tangle-network/agent-interface'\nimport type { SpawnForest } from '../../durable/spawn-journal/spawn-forest'\nimport type { ProviderModelExecutionEvidence, SpawnEvent, Spend } from './types'\n\n/** Measured tokens remain usable without claiming the unreported remainder is zero. */\nexport interface SettledUsage {\n readonly tokens: {\n readonly status: 'known' | 'lower-bound' | 'unknown'\n readonly input: number | null\n readonly output: number | null\n /** Null when legacy or unfinished work does not establish the number of attempts. */\n readonly unknownAttempts: number | null\n }\n readonly requestedModel: {\n readonly id: string | null\n readonly harness: string | null\n readonly provider: string | null\n }\n /** Observations only; providerModel separately states whether served identity is complete. */\n readonly observedModels: ReadonlyArray<string>\n}\n\n/** Use ownership edges to avoid counting parent summaries as additional inference attempts. */\nexport function settledUsage(\n forest: SpawnForest,\n spent: Spend,\n providerModel: ProviderModelExecutionEvidence,\n profile?: AgentProfile,\n): SettledUsage {\n let unknownAttempts: number | null = 0\n const nodes = new Map(forest.nodes.map((node) => [`${node.treeRoot}\\0${node.id}`, node]))\n for (const tree of forest.trees) {\n const metered = new Set(\n tree.events\n .filter((event) => event.kind === 'metered' && !event.accountingOnly)\n .map((event) => event.id),\n )\n for (const event of tree.events) {\n if (nodes.get(`${tree.root}\\0${event.id}`)?.ownedTreeRoot !== undefined) continue\n if (event.kind === 'metered' && event.accountingOnly) {\n if (event.spend.tokensKnown === false || event.spend.tokens.tokensKnown === false)\n unknownAttempts = null\n continue\n }\n let spend: Spend | undefined\n if (event.kind === 'metered' && !event.accountingOnly) spend = event.spend\n else if ((event.kind === 'settled' || event.kind === 'cancelled') && !metered.has(event.id))\n spend = event.spent\n else continue\n if (spend && spend.tokensKnown !== false && spend.tokens.tokensKnown !== false) continue\n const evidence = (event as SpawnEvent & { providerModel?: ProviderModelExecutionEvidence })\n .providerModel\n // A legacy aggregate without attempt identity cannot tell how many calls are missing.\n if (evidence?.attempts?.length !== 1) unknownAttempts = null\n else if (unknownAttempts !== null && evidence.attempts[0]?.providerDispatch !== 'not_started')\n unknownAttempts++\n }\n }\n if (forest.inDoubt.length || forest.missingTrees.length) unknownAttempts = null\n const status =\n spent.tokensKnown === true\n ? 'known'\n : spent.tokens.input > 0 || spent.tokens.output > 0\n ? 'lower-bound'\n : 'unknown'\n return {\n tokens: {\n status,\n input: status === 'unknown' ? null : spent.tokens.input,\n output: status === 'unknown' ? null : spent.tokens.output,\n unknownAttempts: status === 'known' ? 0 : unknownAttempts === 0 ? null : unknownAttempts,\n },\n requestedModel: {\n id: profile?.model?.default ?? null,\n harness: profile?.harness ?? null,\n provider: profile?.model?.provider ?? null,\n },\n observedModels: providerModel.models,\n }\n}\n","import type { AgentProfile } from '@tangle-network/agent-interface'\nimport { closesCursorSlot } from '../../durable/spawn-journal/event-index'\nimport { aggregateProviderModelEvidence } from '../../durable/spawn-journal/provider-model-evidence'\nimport { loadSpawnForest, type SpawnForest } from '../../durable/spawn-journal/spawn-forest'\nimport { RuntimeRunStateError } from '../../errors'\nimport { addSpend } from '../util'\nimport { sumMeasuredSpendFromEvents } from './recover-executors'\nimport { withBudgetResources } from './resources'\nimport { type SettledUsage, settledUsage } from './settled-usage'\nimport { assertValidSpend } from './spend-validation'\nimport type { SpawnedEvent } from './supervisor-root-contract'\nimport type {\n FleetYield,\n NodeId,\n SpawnEvent,\n SpawnJournal,\n Spend,\n SpendChannel,\n SpendGap,\n TreeView,\n} from './types'\n\n/** Terminal usage comes from receipts, never admission's conservative reservation charges.\n * Missing receipts stay named gaps; ms is wall time because parallel executor times overlap. */\nexport async function terminalAccounting(\n journal: SpawnJournal,\n root: string,\n elapsedMs: number,\n profile?: AgentProfile,\n): Promise<{\n tree: TreeView\n spentTotal: Spend\n usage: SettledUsage\n childWork: Spend\n driverInference: Spend\n gaps: SpendGap[]\n providerModel: import('./types').ProviderModelExecutionEvidence\n fleetYield: FleetYield\n}> {\n const forest = await loadSpawnForest(journal, root)\n const rootTree = forest.trees[0]!\n for (const event of rootTree.events) {\n const spend =\n event.kind === 'metered'\n ? event.spend\n : event.kind === 'settled' || event.kind === 'cancelled' || event.kind === 'reconciled'\n ? event.spent\n : undefined\n if (spend !== undefined) assertValidSpend(spend, `settlement ${event.id}/${event.kind}`)\n }\n const { childWork, driverInference } = sumMeasuredSpendFromEvents([...rootTree.events])\n // Forest-wide: a nested driver's children live in its owned tree, outside the root view (#1189).\n const gaps = spendGapsFromEvents(forest.events.map((entry) => entry.event))\n const providerModel = aggregateProviderModelEvidence(forest)\n const fleetYield = fleetYieldFromForest(forest)\n const summed = addSpend(childWork, driverInference)\n const spentTotal: Spend = {\n ...summed,\n ms: Math.max(0, elapsedMs),\n tokensKnown:\n summed.tokensKnown !== false &&\n summed.tokens.tokensKnown !== false &&\n !gaps.some((gap) => gap.channels.includes('tokens')),\n usdKnown: summed.usdKnown !== false && !gaps.some((gap) => gap.channels.includes('usd')),\n }\n assertValidSpend(spentTotal, 'settlement total')\n const forestNodes = forest.nodes.filter((node) => node.id !== forest.root)\n return {\n tree: {\n root: forest.root,\n nodes: forestNodes.map(({ treeRoot: _treeRoot, ...node }) => node),\n inFlight: forestNodes.filter((node) =>\n ['queued', 'acquiring', 'running'].includes(node.status),\n ).length,\n },\n spentTotal,\n usage: settledUsage(forest, spentTotal, providerModel, profile),\n childWork,\n driverInference,\n gaps,\n providerModel,\n fleetYield,\n }\n}\n\n/** Count each child by its last terminal record across the owned forest; roots are exempt. */\nfunction fleetYieldFromForest(forest: SpawnForest): FleetYield {\n const spawned = new Set<NodeId>()\n // Each id lands in exactly one bucket, by its last terminal record in journal order.\n const terminal = new Map<NodeId, 'done' | 'down' | 'cancelled'>()\n const released = new Set<NodeId>()\n const unconfirmed = new Set<NodeId>()\n for (const { event } of forest.events) {\n if (event.kind === 'spawned') {\n if (event.parent !== undefined) spawned.add(event.id)\n } else if (event.kind === 'settled' || event.kind === 'cancelled') {\n const bucket = event.kind === 'cancelled' ? 'cancelled' : event.status\n terminal.set(event.id, bucket)\n // `released` and `release-unconfirmed` are subsets of down + cancelled BY CONSTRUCTION here,\n // not by trust in the writer: only the release sweep and the final close write the markers\n // and they never write `done`, but a hand-built `done` record carrying one must not count\n // twice.\n released.delete(event.id)\n unconfirmed.delete(event.id)\n if (bucket !== 'done' && event.retainedExecution === 'released') released.add(event.id)\n if (bucket !== 'done' && event.retainedExecution === 'release-unconfirmed') {\n unconfirmed.add(event.id)\n }\n }\n }\n const count = (bucket: 'done' | 'down' | 'cancelled'): number =>\n [...terminal.values()].filter((value) => value === bucket).length\n const fleetYield: FleetYield = {\n spawned: spawned.size,\n done: count('done'),\n down: count('down'),\n cancelled: count('cancelled'),\n neverSettled: forest.inDoubt.length,\n releasedUnrecovered: released.size,\n releaseUnconfirmed: unconfirmed.size,\n }\n const accounted =\n fleetYield.done + fleetYield.down + fleetYield.cancelled + fleetYield.neverSettled\n if (accounted !== fleetYield.spawned) {\n throw new RuntimeRunStateError(\n `supervisor: fleet yield does not partition the spawned children of '${forest.root}' (${JSON.stringify(fleetYield)})`,\n )\n }\n if (\n fleetYield.releasedUnrecovered + fleetYield.releaseUnconfirmed >\n fleetYield.down + fleetYield.cancelled\n ) {\n throw new RuntimeRunStateError(\n `supervisor: released children exceed down + cancelled for '${forest.root}' (${JSON.stringify(fleetYield)})`,\n )\n }\n return fleetYield\n}\n\n/** Merge missing-receipt channels by node and cause; the root settles in result.json. */\nfunction spendGapsFromEvents(events: SpawnEvent[]): SpendGap[] {\n const labels = new Map<NodeId, string>()\n const budgets = new Map<NodeId, SpawnedEvent['budget']>()\n const terminal = new Set<NodeId>()\n for (const ev of events) {\n if (ev.kind === 'spawned') {\n labels.set(ev.id, ev.label)\n budgets.set(ev.id, ev.budget)\n } else if (closesCursorSlot(ev)) terminal.add(ev.id)\n }\n const gaps = new Map<\n string,\n { id: NodeId; kind: SpendGap['kind']; channels: Set<SpendChannel> }\n >()\n const record = (\n id: NodeId,\n kind: SpendGap['kind'],\n channels: ReadonlyArray<SpendChannel>,\n ): void => {\n if (channels.length === 0) return\n const key = `${kind}:${id}`\n const existing = gaps.get(key)\n if (existing !== undefined) for (const channel of channels) existing.channels.add(channel)\n else gaps.set(key, { id, kind, channels: new Set(channels) })\n }\n for (const ev of events) {\n if (ev.kind === 'spawned' && ev.parent !== undefined && !terminal.has(ev.id)) {\n record(ev.id, 'never-settled', [\n 'tokens',\n 'usd',\n ...Object.keys(ev.budget.resources ?? {}).map((name): SpendChannel => `resource:${name}`),\n ])\n } else if (ev.kind === 'cancelled' && ev.spent === undefined) {\n record(ev.id, 'unreported', [\n 'tokens',\n 'usd',\n ...Object.keys(budgets.get(ev.id)?.resources ?? {}).map(\n (name): SpendChannel => `resource:${name}`,\n ),\n ])\n } else if (ev.kind === 'settled' || (ev.kind === 'cancelled' && ev.spent !== undefined)) {\n record(\n ev.id,\n 'unreported',\n unknownChannels(withBudgetResources(ev.spent!, budgets.get(ev.id) ?? {})),\n )\n } else if (ev.kind === 'metered') {\n record(ev.id, 'unreported', unknownChannels(ev.spend))\n }\n }\n return [...gaps.values()].map((gap) => {\n const label = labels.get(gap.id)\n return {\n id: gap.id,\n ...(label !== undefined ? { label } : {}),\n kind: gap.kind,\n channels: [...gap.channels],\n }\n })\n}\n\n/** The channels a single spend record explicitly marks incomplete. */\nfunction unknownChannels(spend: Spend): SpendChannel[] {\n const channels: SpendChannel[] = []\n if (spend.tokensKnown === false || spend.tokens.tokensKnown === false) channels.push('tokens')\n if (spend.usdKnown === false) channels.push('usd')\n for (const [name, resource] of Object.entries(spend.resources ?? {})) {\n if (!resource.known) channels.push(`resource:${name}`)\n }\n return channels\n}\n\n/** True when any driver metered inference this run (so the winner carries a `spentBreakdown`).\n * Checks every channel `addSpend` sums — including `ms` — so the gate stays consistent with the\n * total even though the coordination driver currently stamps `ms: 0`. */\nexport function isNonEmptySpend(s: Spend): boolean {\n return (\n s.iterations > 0 ||\n s.tokens.input > 0 ||\n s.tokens.output > 0 ||\n s.usd > 0 ||\n s.ms > 0 ||\n s.tokensKnown === false ||\n s.usdKnown === false ||\n Object.values(s.resources ?? {}).some((resource) => resource.amount > 0 || !resource.known)\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,eACd,OACA,SAOgB;CAiBhB,OAAO;EAfL,GAAI,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO;EAC7D,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;EAC1D,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;EAC1D,GAAI,MAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;EAChE,GAAI,MAAM,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,MAAM,UAAU;EACtE,GAAI,MAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;EAChE,GAAI,MAAM,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,MAAM,aAAa;EAC/E,GAAI,MAAM,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,gBAAgB;EACxF,GAAI,M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