@tangle-network/agent-runtime 0.175.0 → 0.177.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.
- package/README.md +4 -0
- package/dist/{activation-CsdJWRXX.js → activation-XVI_z1g3.js} +3 -3
- package/dist/{activation-CsdJWRXX.js.map → activation-XVI_z1g3.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/{authoring-DsLNInAz.js → authoring-bXmPNfCI.js} +2 -2
- package/dist/{authoring-DsLNInAz.js.map → authoring-bXmPNfCI.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-BbMbyhgC.js → candidate-execution-fBNUyWyE.js} +10 -4
- package/dist/candidate-execution-fBNUyWyE.js.map +1 -0
- package/dist/{conversation-7XGKoDM6.js → conversation-BREx2hi-.js} +3 -3
- package/dist/{conversation-7XGKoDM6.js.map → conversation-BREx2hi-.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/coordination-driver-xO1tkxy-.js +3063 -0
- package/dist/coordination-driver-xO1tkxy-.js.map +1 -0
- package/dist/durable-file-g3YdfEh4.js +131 -0
- package/dist/durable-file-g3YdfEh4.js.map +1 -0
- package/dist/durable.d.ts +2 -2
- package/dist/durable.js +1 -1
- package/dist/{environment-provider-DWjbGH8W.d.ts → environment-provider-5E82esWE.d.ts} +6 -3
- package/dist/{environment-provider-Bn3652YU.js → environment-provider-DKyMWQJd.js} +121 -17
- package/dist/environment-provider-DKyMWQJd.js.map +1 -0
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-BbeHgLXH.js → graph-DwJXa1Ph.js} +3 -3
- package/dist/graph-DwJXa1Ph.js.map +1 -0
- package/dist/graph.d.ts +3 -3
- package/dist/graph.js +4 -4
- package/dist/{improvement-cycle-DKGDCukL.js → improvement-cycle-eiSv6aH4.js} +5 -5
- package/dist/{improvement-cycle-DKGDCukL.js.map → improvement-cycle-eiSv6aH4.js.map} +1 -1
- package/dist/{index-CIhkH7mq.d.ts → index-BnAiQVLD.d.ts} +290 -29
- package/dist/{index-CFMB9ux3.d.ts → index-Bs0uhf-y.d.ts} +2 -2
- package/dist/{index-Dk5X9eKg.d.ts → index-C9XTLVP1.d.ts} +4 -4
- package/dist/index.d.ts +7 -7
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +4 -4
- package/dist/intelligence.js +6 -6
- package/dist/kernel.d.ts +6 -6
- package/dist/kernel.js +13 -11
- package/dist/{knowledge-BaAX0HVu.js → knowledge-Bmtj_7u7.js} +5 -5
- package/dist/{knowledge-BaAX0HVu.js.map → knowledge-Bmtj_7u7.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-DRYApMiu.d.ts → loop-runner-bin-ChS5deJ0.d.ts} +3 -3
- package/dist/{loop-runner-bin-D63Tytdk.js → loop-runner-bin-GTN5wqCt.js} +3 -3
- package/dist/{loop-runner-bin-D63Tytdk.js.map → loop-runner-bin-GTN5wqCt.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/{materialization-Ct3I4wu3.js → materialization-CekWK6OO.js} +5 -3
- package/dist/materialization-CekWK6OO.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +3 -3
- package/dist/mcp/index.js +5 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-BBgjWYNw.js → openai-tools-BBj1QGJp.js} +2 -2
- package/dist/{openai-tools-BBgjWYNw.js.map → openai-tools-BBj1QGJp.js.map} +1 -1
- package/dist/{prepare-BAyaNoZu.js → prepare-Tip-2ZoZ.js} +2 -2
- package/dist/{prepare-BAyaNoZu.js.map → prepare-Tip-2ZoZ.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/{protected-model-port-T2UWrDNQ.js → protected-model-port-Dd3a1SRm.js} +2 -2
- package/dist/{protected-model-port-T2UWrDNQ.js.map → protected-model-port-Dd3a1SRm.js.map} +1 -1
- package/dist/provision-supervisor-zA__ayUX.js +1020 -0
- package/dist/provision-supervisor-zA__ayUX.js.map +1 -0
- package/dist/{redact-DvLf4x1m.d.ts → redact-DkRLcSiE.d.ts} +3 -3
- package/dist/run-layout-Cd_l2XWV.js +645 -0
- package/dist/run-layout-Cd_l2XWV.js.map +1 -0
- package/dist/{runtime-D5u1M6T5.d.ts → runtime-B2eZ76kG.d.ts} +3 -3
- package/dist/{runtime-CojgP-hr.js → runtime-CJNlF5wM.js} +16 -1095
- package/dist/runtime-CJNlF5wM.js.map +1 -0
- package/dist/{spawn-journal-Tgvp5VS5.js → spawn-journal--N8Ten1q.js} +3 -1
- package/dist/{spawn-journal-Tgvp5VS5.js.map → spawn-journal--N8Ten1q.js.map} +1 -1
- package/dist/{stream-agent-turn-DxQ3GOuR.d.ts → stream-agent-turn-ByY8po9W.d.ts} +2 -2
- package/dist/{stream-agent-turn-CKIpCbSq.js → stream-agent-turn-CPj9SqVm.js} +2 -2
- package/dist/{stream-agent-turn-CKIpCbSq.js.map → stream-agent-turn-CPj9SqVm.js.map} +1 -1
- package/dist/{structural-rollout-BUYA61iV.js → structural-rollout-BeAUK7Ta.js} +4 -4
- package/dist/{structural-rollout-BUYA61iV.js.map → structural-rollout-BeAUK7Ta.js.map} +1 -1
- package/dist/{supervise-Ci0RfWQF.js → supervise-HsRKOlKY.js} +405 -3374
- package/dist/supervise-HsRKOlKY.js.map +1 -0
- package/dist/{supervisor-Bt1XLCVq.js → supervisor-ChLgoYhG.js} +1620 -33
- package/dist/supervisor-ChLgoYhG.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +13 -12
- package/dist/testing.js.map +1 -1
- package/dist/{top-app-3rYfFPTW.js → top-app-DIBApkt1.js} +25 -9
- package/dist/top-app-DIBApkt1.js.map +1 -0
- package/dist/tui/bin.js +1 -1
- package/dist/tui/index.d.ts +9 -1
- package/dist/tui/index.js +3 -2
- package/dist/{types-DjVO-p7R.d.ts → types-a2ZZUl80.d.ts} +25 -2
- package/dist/{workspace-archive-B0Hqp2eJ.js → workspace-archive-DOZAeeKU.js} +2 -2
- package/dist/{workspace-archive-B0Hqp2eJ.js.map → workspace-archive-DOZAeeKU.js.map} +1 -1
- package/package.json +6 -4
- package/dist/candidate-execution-BbMbyhgC.js.map +0 -1
- package/dist/environment-provider-Bn3652YU.js.map +0 -1
- package/dist/graph-BbeHgLXH.js.map +0 -1
- package/dist/materialization-Ct3I4wu3.js.map +0 -1
- package/dist/run-layout-C2jgwsCq.js +0 -393
- package/dist/run-layout-C2jgwsCq.js.map +0 -1
- package/dist/runtime-CojgP-hr.js.map +0 -1
- package/dist/supervise-Ci0RfWQF.js.map +0 -1
- package/dist/supervisor-Bt1XLCVq.js.map +0 -1
- package/dist/top-app-3rYfFPTW.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"environment-provider-Bn3652YU.js","names":[],"sources":["../src/runtime/supervise/abortable.ts","../src/runtime/tangle-sandbox-exact-process-provider.ts","../src/runtime/environment-provider.ts"],"sourcesContent":["/**\n * One abort race, and one abort cascade, for the supervision tree.\n *\n * Every layer that can be cancelled needs the same three things: the reason a signal\n * carries, an `AbortError` built from it, and a settle-once race between the work and\n * the signal. Written per layer, each drifts — a listener stops being removed on one\n * path, a late resolution overwrites a cancellation that already won, or a cascade\n * forwards no reason and renames every downstream death to the layer's own fallback.\n *\n * The fallback message is the only thing a layer supplies, so the error still names\n * which layer cancelled.\n */\n\n/**\n * The reason a signal carries, or `fallback` when it states none.\n *\n * A cascade that drops the upstream reason turns every downstream death into its own generic\n * message: the worker's `down` record then says nothing about WHY, which makes a whole class of\n * child mortality undiagnosable from the journal alone.\n */\nexport function abortReason(signal: AbortSignal, fallback: string): unknown {\n const reason = signal.reason\n if (typeof reason === 'string' && reason.length > 0) return reason\n // `abort()` with no argument sets a DOMException whose message is the platform placeholder\n // (\"This operation was aborted\"), which carries no more information than the generic death it\n // would replace — treat it as reasonless and use the fallback.\n if (reason instanceof Error && reason.name !== 'AbortError' && reason.message.length > 0) {\n return reason.message\n }\n return fallback\n}\n\n/** An `AbortError` carrying the signal's own string reason, or `fallback` when it states none. */\nexport function abortError(signal: AbortSignal, fallback: string): Error {\n const reason = abortReason(signal, fallback)\n const error = new Error(typeof reason === 'string' && reason.length > 0 ? reason : fallback)\n error.name = 'AbortError'\n return error\n}\n\n/** A downstream abort linked to one or more upstream signals. */\nexport interface LinkedAbort {\n /** Fires when any source fires, or when {@link LinkedAbort.abort} is called. */\n readonly signal: AbortSignal\n /** Abort this link on its own (teardown, cancellation), carrying `reason`. */\n abort(reason?: unknown): void\n /** Stop listening to the sources. Idempotent; required where a source outlives the link. */\n release(): void\n}\n\n/**\n * Cascade N abort signals into one downstream abort that fires when ANY of them does, carrying\n * that signal's own reason ({@link abortReason}). Node-portable: `AbortSignal.any` needs >=20.3\n * and the package floor is >=20, and it would drop the reason anyway.\n *\n * The one cascade every executor uses, so a reason forwarded here reaches every layer below.\n */\nexport function linkAbort(...sources: ReadonlyArray<AbortSignal>): LinkedAbort {\n const controller = new AbortController()\n const listeners: Array<{ source: AbortSignal; onAbort: () => void }> = []\n const release = (): void => {\n for (const { source, onAbort } of listeners) source.removeEventListener('abort', onAbort)\n listeners.length = 0\n }\n const abort = (reason?: unknown): void => {\n release()\n controller.abort(reason)\n }\n const alreadyAborted = sources.find((source) => source.aborted)\n if (alreadyAborted !== undefined) {\n controller.abort(abortReason(alreadyAborted, 'aborted by parent scope'))\n return { signal: controller.signal, abort, release }\n }\n for (const source of sources) {\n const onAbort = (): void => abort(abortReason(source, 'aborted by parent scope'))\n listeners.push({ source, onAbort })\n source.addEventListener('abort', onAbort, { once: true })\n }\n return { signal: controller.signal, abort, release }\n}\n\n/**\n * Settle `act()` against `signal`. The first outcome wins and the listener is always\n * removed, so neither a late resolution nor a late abort can settle the promise twice.\n * The losing promise stays observed, so a late rejection cannot surface as an unhandled\n * process error.\n *\n * The abort rejection is deferred one microtask so a result the action had ALREADY\n * produced still wins. It does not hand the race to a listener the action registers\n * from inside `act()`: this function subscribes before it calls `act()`, so its own\n * abort handler runs first and settles the promise. A caller that must let the action\n * observe the abort itself has to hold a live promise and await that instead.\n *\n * A synchronous throw from `act()` propagates as the rejection, not as an abort.\n */\nexport async function runAbortable<T>(\n act: () => Promise<T>,\n signal: AbortSignal,\n fallback: string,\n): Promise<T> {\n if (signal.aborted) throw abortError(signal, fallback)\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(abortError(signal, fallback))\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 { isDeepStrictEqual } from 'node:util'\n\nimport type { AgentCandidateTermination } from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n AgentExactProcess,\n AgentExactProcessEnvironment,\n AgentExactProcessEnvironmentQuery,\n AgentExactProcessProvider,\n AgentExactProcessStatus,\n CreateAgentExactProcessEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type {\n Process,\n ProcessStatus,\n Sandbox,\n SandboxInstance,\n SandboxResources,\n} from '@tangle-network/sandbox'\n\nexport type SandboxControlClient = Pick<Sandbox, 'create' | 'get' | 'list'>\n\ntype ExactSandboxEgressPolicy =\n | { mode: 'blocked' }\n | { mode: 'strict'; allowDomains: string[]; includeImplicitDomains: false }\n\nexport interface CreateTangleSandboxExactProcessProviderOptions {\n name?: string\n}\n\nconst exactProcessProviderMarker = 'agent-runtime.exact-process-provider'\nconst exactProcessEgressMarker = 'agent-runtime.exact-process-egress'\n\n/**\n * Adapt Tangle Sandbox's managed control runtime to Runtime's exact-process provider.\n *\n * The adapter deliberately exposes no ordinary agent environment: an exact experiment\n * must start a fresh Sandbox with no managed agent and launch its declared argv directly.\n */\nexport function createTangleSandboxExactProcessProvider(\n client: SandboxControlClient,\n options: CreateTangleSandboxExactProcessProviderOptions = {},\n): AgentEnvironmentProvider {\n const name = options.name ?? 'tangle-sandbox-exact-process'\n if (!name.trim()) throw new Error('Tangle Sandbox exact-process provider name must not be empty')\n\n const exactProcess: AgentExactProcessProvider = {\n async create(input: CreateAgentExactProcessEnvironmentInput) {\n throwIfAborted(input.signal)\n assertNoProviderOptions(input.providerOptions)\n const egressPolicy = sandboxEgressPolicy(input.egress)\n const metadata = exactMetadata(input.metadata, name, egressPolicy)\n const sandbox = await client.create(\n {\n environment: requiredText(input.image, 'exact-process image'),\n agent: false,\n bare: false,\n ephemeral: true,\n egressPolicy,\n resources: sandboxResources(input),\n maxLifetimeSeconds: sandboxLifetimeSeconds(input.maxLifetimeMs),\n metadata,\n idempotencyKey: requiredText(input.idempotencyKey, 'exact-process idempotency key'),\n },\n {\n ...(input.provisionTimeoutMs === undefined\n ? {}\n : { timeoutMs: positiveInteger(input.provisionTimeoutMs, 'provision timeout') }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n },\n )\n try {\n throwIfAborted(input.signal)\n assertExactSandboxMetadata(sandbox, metadata)\n await assertExactSandboxEgress(sandbox, egressPolicy)\n } catch (error) {\n await discardInvalidSandbox(sandbox, error)\n }\n return sandboxAsExactProcessEnvironment(sandbox, name)\n },\n async get(id: string) {\n const sandbox = await client.get(id)\n if (!sandbox || !isExactSandbox(sandbox, name)) return null\n await assertExactSandboxEgress(sandbox, egressFromMetadata(sandbox.metadata))\n return sandboxAsExactProcessEnvironment(sandbox, name)\n },\n async list(query?: AgentExactProcessEnvironmentQuery) {\n assertNoProviderOptions(query?.providerOptions)\n const sandboxes = await client.list()\n return Promise.all(\n sandboxes\n .filter((sandbox) => isExactSandbox(sandbox, name))\n .filter((sandbox) => metadataMatches(sandbox.metadata, query?.metadata))\n .map(async (sandbox) => {\n await assertExactSandboxEgress(sandbox, egressFromMetadata(sandbox.metadata))\n return sandboxAsExactProcessEnvironment(sandbox, name)\n }),\n )\n },\n }\n\n return {\n name,\n exactProcess,\n capabilities: exactProcessOnlyCapabilities,\n async create() {\n throw new Error(`agent environment provider \"${name}\" supports exactProcess.create() only`)\n },\n }\n}\n\nfunction sandboxAsExactProcessEnvironment(\n sandbox: SandboxInstance,\n provider: string,\n): AgentExactProcessEnvironment {\n return {\n id: requiredText(sandbox.id, 'Sandbox id'),\n provider,\n ...(sandbox.metadata ? { metadata: sandbox.metadata } : {}),\n process: {\n async list(): Promise<AgentExactProcessStatus[]> {\n return (await sandbox.process.list()).map((status) => exactProcessStatus(status))\n },\n async get(pid: number): Promise<AgentExactProcess | null> {\n const process = await sandbox.process.get(pid)\n return process ? sandboxProcessAsExactProcess(process) : null\n },\n async spawn(input, options): Promise<AgentExactProcess> {\n const process = await afterAbortCheck(options?.signal, () =>\n sandbox.process.spawnExact(input.executable, [...input.args], {\n cwd: input.cwd,\n env: { ...input.env },\n inheritEnv: false,\n ...(input.stdin === undefined ? {} : { stdin: input.stdin }),\n timeoutMs: input.timeoutMs,\n }),\n )\n return sandboxProcessAsExactProcess(process)\n },\n },\n async writeFile(path, bytes, options): Promise<void> {\n if (sandbox.fs.supportsWriteMode !== true) {\n throw new Error('Tangle Sandbox does not declare exact file-mode support')\n }\n await afterAbortCheck(options.signal, () =>\n sandbox.fs.write(path, Buffer.from(bytes).toString('base64'), {\n encoding: 'base64',\n mode: fileMode(options.mode),\n }),\n )\n },\n async readFile(path, options): Promise<Uint8Array> {\n const maxBytes = nonnegativeInteger(options.maxBytes, 'exact-process file read maximum')\n const initialSize = nonnegativeInteger(\n (await afterAbortCheck(options.signal, () => sandbox.fs.stat(path))).size,\n `Tangle Sandbox file size for \"${path}\"`,\n )\n if (initialSize > maxBytes) {\n throw new Error(\n `Tangle Sandbox file \"${path}\" exceeds the ${maxBytes}-byte exact read maximum`,\n )\n }\n const result = await afterAbortCheck(options.signal, () =>\n sandbox.fs.readBatch([path], { encoding: 'base64' }),\n )\n const failure = result.errors.find((entry) => entry.path === path)\n if (failure) {\n throw new Error(`Tangle Sandbox failed to read \"${path}\": ${failure.error}`)\n }\n const files = result.files.filter((entry) => entry.path === path)\n if (files.length !== 1) {\n throw new Error(`Tangle Sandbox returned ${files.length} files for exact read \"${path}\"`)\n }\n const file = files[0]!\n if (file.encoding !== 'base64') {\n throw new Error(`Tangle Sandbox returned non-binary content for exact read \"${path}\"`)\n }\n const size = nonnegativeInteger(file.size, `Tangle Sandbox file size for \"${path}\"`)\n if (size !== initialSize) {\n throw new Error(`Tangle Sandbox file \"${path}\" changed during exact read`)\n }\n if (size > maxBytes) {\n throw new Error(\n `Tangle Sandbox file \"${path}\" exceeds the ${maxBytes}-byte exact read maximum`,\n )\n }\n const bytes = Buffer.from(file.content, 'base64')\n if (bytes.byteLength !== size || bytes.toString('base64') !== file.content) {\n throw new Error(\n `Tangle Sandbox returned an invalid binary payload for exact read \"${path}\"`,\n )\n }\n return Uint8Array.from(bytes)\n },\n async destroy(): Promise<void> {\n await sandbox.delete()\n },\n }\n}\n\nfunction sandboxProcessAsExactProcess(process: Process): AgentExactProcess {\n const pid = positiveInteger(process.pid, 'Tangle Sandbox process pid')\n return {\n pid,\n async status(): Promise<AgentExactProcessStatus> {\n return exactProcessStatus(await process.status(), pid)\n },\n async wait(): Promise<AgentCandidateTermination> {\n const waitExitCode = await process.wait()\n if (!Number.isSafeInteger(waitExitCode)) {\n throw new Error('Tangle Sandbox process wait returned an invalid exit code')\n }\n const status = exactProcessStatus(await process.status(), pid)\n if (status.running || !status.termination) {\n throw new Error('Tangle Sandbox process wait returned before terminal status')\n }\n if (status.termination.kind === 'exit' && status.termination.exitCode !== waitExitCode) {\n throw new Error('Tangle Sandbox process wait and status disagree on exit code')\n }\n return status.termination\n },\n async kill(): Promise<void> {\n await process.kill('SIGKILL', { tree: true })\n },\n async *stdout(): AsyncIterable<string> {\n yield* process.stdout()\n },\n async *stderr(): AsyncIterable<string> {\n yield* process.stderr()\n },\n }\n}\n\nfunction exactProcessStatus(status: ProcessStatus, expectedPid?: number): AgentExactProcessStatus {\n const pid = positiveInteger(status.pid, 'Tangle Sandbox process pid')\n if (expectedPid !== undefined && pid !== expectedPid) {\n throw new Error('Tangle Sandbox process status changed process identity')\n }\n if (typeof status.running !== 'boolean') {\n throw new Error('Tangle Sandbox process status is missing running state')\n }\n if (!Number.isSafeInteger(status.exitCode)) {\n throw new Error('Tangle Sandbox process status is missing an integer exit code')\n }\n const exitSignal = optionalText(status.exitSignal, 'Tangle Sandbox process exit signal')\n if (status.running) {\n if (status.exitCode !== -1) {\n throw new Error('Tangle Sandbox running process must report exit code -1')\n }\n if (exitSignal) {\n throw new Error('Tangle Sandbox running process must not report an exit signal')\n }\n return {\n pid,\n running: true,\n exitCode: -1,\n }\n }\n const termination = exitSignal\n ? ({ kind: 'signal', signal: exitSignal } as const)\n : status.exitCode >= 0\n ? ({ kind: 'exit', exitCode: status.exitCode } as const)\n : undefined\n if (!termination) {\n throw new Error('Tangle Sandbox stopped process has no terminal reason')\n }\n return {\n pid,\n running: false,\n exitCode: status.exitCode,\n ...(exitSignal ? { exitSignal } : {}),\n termination,\n }\n}\n\nfunction exactMetadata(\n metadata: Record<string, unknown>,\n provider: string,\n egressPolicy: ExactSandboxEgressPolicy,\n): Record<string, unknown> {\n for (const marker of [exactProcessProviderMarker, exactProcessEgressMarker]) {\n if (Object.hasOwn(metadata, marker)) {\n throw new Error(`exact-process metadata must not set \"${marker}\"`)\n }\n }\n return {\n ...metadata,\n [exactProcessProviderMarker]: provider,\n [exactProcessEgressMarker]: serializeEgressPolicy(egressPolicy),\n }\n}\n\nfunction isExactSandbox(sandbox: SandboxInstance, provider: string): boolean {\n return sandbox.metadata?.[exactProcessProviderMarker] === provider\n}\n\nfunction metadataMatches(\n metadata: Record<string, unknown> | undefined,\n expected: Record<string, unknown> | undefined,\n): boolean {\n return (\n expected === undefined ||\n Object.entries(expected).every(([key, value]) => isDeepStrictEqual(metadata?.[key], value))\n )\n}\n\nfunction assertExactSandboxMetadata(\n sandbox: SandboxInstance,\n expected: Record<string, unknown>,\n): void {\n if (!metadataMatches(sandbox.metadata, expected)) {\n throw new Error('Tangle Sandbox did not persist exact-process metadata')\n }\n}\n\nfunction egressFromMetadata(\n metadata: Record<string, unknown> | undefined,\n): ExactSandboxEgressPolicy {\n const encoded = metadata?.[exactProcessEgressMarker]\n if (typeof encoded !== 'string') {\n throw new Error('Tangle Sandbox exact-process environment is missing egress metadata')\n }\n try {\n const parsed: unknown = JSON.parse(encoded)\n if (!parsed || typeof parsed !== 'object') throw new Error('expected egress object')\n const policy = parsed as {\n mode?: unknown\n allowDomains?: unknown\n includeImplicitDomains?: unknown\n }\n if (policy.mode === 'blocked' && policy.allowDomains === undefined) return { mode: 'blocked' }\n if (\n policy.mode === 'strict' &&\n policy.includeImplicitDomains === false &&\n Array.isArray(policy.allowDomains) &&\n policy.allowDomains.every((domain): domain is string => typeof domain === 'string')\n ) {\n const allowDomains = sortedDomains(policy.allowDomains)\n if (new Set(allowDomains).size === allowDomains.length) {\n return { mode: 'strict', allowDomains, includeImplicitDomains: false }\n }\n }\n } catch {\n throw new Error('Tangle Sandbox exact-process environment has invalid egress metadata')\n }\n throw new Error('Tangle Sandbox exact-process environment has invalid egress metadata')\n}\n\nasync function assertExactSandboxEgress(\n sandbox: SandboxInstance,\n expected: ExactSandboxEgressPolicy,\n): Promise<void> {\n const actual = (await sandbox.egress.get()).policy\n if (actual.mode !== expected.mode) {\n throw new Error(\n `Tangle Sandbox egress mismatch: expected ${expected.mode}, received ${actual.mode}`,\n )\n }\n if (expected.mode === 'blocked') {\n const allowDomains = (actual as { allowDomains?: unknown }).allowDomains\n if (\n actual.mode === 'blocked' &&\n (allowDomains === undefined || (Array.isArray(allowDomains) && allowDomains.length === 0))\n ) {\n return\n }\n throw new Error('Tangle Sandbox blocked egress retained an allowlist')\n }\n if (actual.mode !== 'strict') {\n throw new Error('Tangle Sandbox did not return strict egress policy')\n }\n const expectedDomains = sortedDomains(expected.allowDomains)\n const actualDomains = sortedDomains(actual.allowDomains ?? [])\n if (!isDeepStrictEqual(actualDomains, expectedDomains)) {\n throw new Error('Tangle Sandbox strict egress differs from the exact allowlist')\n }\n if (actual.includeImplicitDomains !== false) {\n throw new Error('Tangle Sandbox strict egress retained implicit domains')\n }\n}\n\nfunction sandboxEgressPolicy(\n input: CreateAgentExactProcessEnvironmentInput['egress'],\n): ExactSandboxEgressPolicy {\n if (input.mode === 'blocked') return { mode: 'blocked' }\n const allowDomains = input.allowDomains.map((domain) =>\n requiredText(domain, 'strict egress domain'),\n )\n if (new Set(allowDomains).size !== allowDomains.length) {\n throw new Error('strict egress domains must not contain duplicates')\n }\n return { mode: 'strict', allowDomains, includeImplicitDomains: false }\n}\n\nfunction serializeEgressPolicy(policy: ExactSandboxEgressPolicy): string {\n return JSON.stringify(\n policy.mode === 'blocked'\n ? { mode: 'blocked' }\n : {\n mode: 'strict',\n allowDomains: sortedDomains(policy.allowDomains),\n includeImplicitDomains: false,\n },\n )\n}\n\nfunction sandboxResources(input: CreateAgentExactProcessEnvironmentInput): SandboxResources {\n const cpuCores = positiveNumber(input.resources.cpu, 'exact-process cpu')\n const memoryMB = positiveInteger(input.resources.memoryMb, 'exact-process memory')\n const diskMb = positiveInteger(input.resources.diskMb, 'exact-process disk')\n if (diskMb % 1024 !== 0) {\n throw new Error('Tangle Sandbox exact-process disk must be a whole GiB')\n }\n return { cpuCores, memoryMB, diskGB: diskMb / 1024 }\n}\n\nfunction sandboxLifetimeSeconds(maxLifetimeMs: number): number {\n const milliseconds = positiveInteger(maxLifetimeMs, 'exact-process maximum lifetime')\n if (milliseconds % 1_000 !== 0) {\n throw new Error(\n 'Tangle Sandbox exact-process maximum lifetime must be a whole number of seconds',\n )\n }\n return milliseconds / 1_000\n}\n\nfunction fileMode(value: number): number {\n const mode = nonnegativeInteger(value, 'exact-process file mode')\n if (mode > 0o7777) throw new Error('exact-process file mode exceeds POSIX mode bits')\n return mode\n}\n\nfunction assertNoProviderOptions(providerOptions: Record<string, unknown> | undefined): void {\n if (providerOptions && Object.keys(providerOptions).length > 0) {\n throw new Error('Tangle Sandbox exact-process provider does not accept providerOptions')\n }\n}\n\nfunction exactProcessOnlyCapabilities(): AgentEnvironmentCapabilities {\n return {\n profile: {\n namedProfiles: false,\n // Exact-process runs a command as given and interprets no part of a profile, so neither\n // spelling is honored and a profile carrying one is refused rather than silently dropped.\n systemPrompt: { replace: false, append: false },\n instructions: false,\n tools: false,\n permissions: false,\n mcp: false,\n subagents: false,\n resources: {\n files: false,\n instructions: false,\n tools: false,\n skills: false,\n agents: false,\n commands: false,\n },\n hooks: false,\n modes: false,\n runtimeUpdate: false,\n validation: false,\n },\n streaming: { live: false, replay: false, detach: false, turnIdempotency: false },\n sessions: { continue: false, list: false, messages: false },\n workspace: {\n read: false,\n write: false,\n exec: false,\n git: false,\n upload: false,\n download: false,\n },\n branching: { checkpoint: false, fork: false },\n placement: false,\n usage: false,\n confidential: false,\n exactProcess: { egress: ['blocked', 'strict'] },\n }\n}\n\nasync function discardInvalidSandbox(sandbox: SandboxInstance, cause: unknown): Promise<never> {\n try {\n await sandbox.delete()\n } catch (destroyError) {\n throw new AggregateError(\n [cause, destroyError],\n 'Tangle Sandbox exact-process creation failed and cleanup failed',\n )\n }\n throw cause\n}\n\nfunction sortedDomains(domains: readonly string[]): string[] {\n return [...domains].sort((left, right) => left.localeCompare(right))\n}\n\nfunction requiredText(value: string, label: string): string {\n if (typeof value !== 'string' || !value.trim())\n throw new Error(`${label} must be a non-empty string`)\n return value\n}\n\nfunction optionalText(value: string | undefined, label: string): string | undefined {\n if (value === undefined) return undefined\n return requiredText(value, label)\n}\n\nfunction positiveNumber(value: number, label: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new Error(`${label} must be positive`)\n return value\n}\n\nfunction positiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1)\n throw new Error(`${label} must be a positive integer`)\n return value\n}\n\nfunction nonnegativeInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 0)\n throw new Error(`${label} must be a non-negative integer`)\n return value\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n signal?.throwIfAborted()\n}\n\nasync function afterAbortCheck<T>(\n signal: AbortSignal | undefined,\n operation: () => Promise<T>,\n): Promise<T> {\n throwIfAborted(signal)\n const result = await operation()\n throwIfAborted(signal)\n return result\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n type AgentExactRunControlRef,\n AgentExactRunControlRefSchema,\n type AgentProfile,\n type AgentProfileValidationResult,\n type AgentRunCancellationAcknowledgement,\n type AgentRunCancellationRequest,\n AgentRunCancellationRequestSchema,\n type AgentRunControlRef,\n harnessSystemPromptIntents,\n type InteractionAcknowledgement,\n type InteractionResponseCommand,\n type TokenUsage,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentEvent,\n AgentEnvironmentProvider,\n AgentEnvironmentQuery,\n AgentEnvironmentStatus,\n AgentEnvironmentSummary,\n AgentProfileRef,\n AgentSession,\n AgentSessionRef,\n AgentSessionStatus,\n AgentTurnInput,\n AgentTurnResult,\n CheckpointRef,\n CheckpointRequest,\n CreateAgentEnvironmentInput,\n ExecRequest,\n ExecResult,\n ForkRequest,\n PlacementInfo,\n ResourceRequest,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type {\n BackendType,\n CreateSandboxOptions,\n PromptInputPart,\n PromptOptions,\n PromptResult,\n SandboxEvent,\n ExecResult as SandboxExecResult,\n SandboxInstance,\n} from '@tangle-network/sandbox'\nimport { awaitAbortable, sameControlCoordinates } from './retained-run-binding'\nimport {\n canonicalStreamEventFromSandboxEvent,\n createSandboxToolPartState,\n isSandboxTerminalEvent,\n sandboxProgressEvents,\n sandboxTerminalUsageField,\n} from './sandbox-events'\nimport { linkAbort } from './supervise/abortable'\nimport {\n attestRuntimeOwnedPendingExecutor,\n finalizeRuntimeOwnedPendingExecutor,\n newExecutionAttemptId,\n} from './supervise/materialization'\nimport {\n concreteProfileModel,\n enforceTokenLimits,\n profileModelExecutionSettings,\n} from './supervise/model-policy'\nimport type {\n Executor,\n ExecutorCancellation,\n ExecutorContext,\n ExecutorExecutionBinding,\n ExecutorFactory,\n ExecutorMaterialization,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n} from './supervise/types'\nimport { promptFromAgentTurnInput, promptOptionsFromAgentTurnInput } from './turn-input'\nimport type { LoopSandboxPlacement, SandboxClient } from './types'\nimport { zeroTokenUsage } from './util'\n\n// Keep this file loadable from the lean `./environment-provider` export without agent-eval installed.\nclass ValidationError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'ValidationError'\n }\n}\n\nexport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentEvent,\n AgentEnvironmentProvider,\n AgentEnvironmentQuery,\n AgentEnvironmentStatus,\n AgentEnvironmentSummary,\n AgentProfileRef,\n AgentSession,\n AgentSessionRef,\n AgentSessionStatus,\n AgentTurnInput,\n AgentTurnResult,\n CheckpointRef,\n CheckpointRequest,\n CreateAgentEnvironmentInput,\n ExecRequest,\n ExecResult,\n ForkRequest,\n PlacementInfo,\n ResourceRequest,\n WorkspaceRequest,\n} from '@tangle-network/agent-interface/environment-provider'\n\nexport {\n type CreateTangleSandboxExactProcessProviderOptions,\n createTangleSandboxExactProcessProvider,\n} from './tangle-sandbox-exact-process-provider'\n\n/** Provider object or registry name accepted by runtime provider adapters.\n * @experimental */\nexport type AgentEnvironmentProviderRef = AgentEnvironmentProvider | string\n\n/** In-memory registry for named `AgentEnvironmentProvider` instances.\n * @experimental */\nexport interface AgentEnvironmentProviderRegistry {\n register(provider: AgentEnvironmentProvider, options?: { replace?: boolean }): void\n has(name: string): boolean\n get(name: string): AgentEnvironmentProvider | undefined\n require(name: string): AgentEnvironmentProvider\n names(): string[]\n providers(): AgentEnvironmentProvider[]\n capabilities(name: string): Promise<AgentEnvironmentCapabilities>\n}\n\n/** Create a registry that resolves provider names to concrete provider instances.\n * @experimental */\nexport function createAgentEnvironmentProviderRegistry(\n providers: Iterable<AgentEnvironmentProvider> = [],\n): AgentEnvironmentProviderRegistry {\n const entries = new Map<string, AgentEnvironmentProvider>()\n\n const registry: AgentEnvironmentProviderRegistry = {\n register(provider, options = {}): void {\n if (!provider.name) {\n throw new ValidationError('agent environment provider registry: provider.name required')\n }\n if (!options.replace && entries.has(provider.name)) {\n throw new ValidationError(\n `agent environment provider registry: provider \"${provider.name}\" already registered`,\n )\n }\n entries.set(provider.name, provider)\n },\n has(name): boolean {\n return entries.has(name)\n },\n get(name): AgentEnvironmentProvider | undefined {\n return entries.get(name)\n },\n require(name): AgentEnvironmentProvider {\n const provider = entries.get(name)\n if (!provider) {\n const available = Array.from(entries.keys()).sort()\n const suffix = available.length > 0 ? `; available: ${available.join(', ')}` : ''\n throw new ValidationError(\n `agent environment provider registry: provider \"${name}\" is not registered${suffix}`,\n )\n }\n return provider\n },\n names(): string[] {\n return Array.from(entries.keys()).sort()\n },\n providers(): AgentEnvironmentProvider[] {\n return registry.names().map((name) => registry.require(name))\n },\n async capabilities(name): Promise<AgentEnvironmentCapabilities> {\n return registry.require(name).capabilities()\n },\n }\n\n for (const provider of providers) registry.register(provider)\n return registry\n}\n\n/** Resolve a provider instance or registry name, failing loudly when a name is unknown.\n * @experimental */\nexport function resolveAgentEnvironmentProvider(\n provider: AgentEnvironmentProviderRef,\n registry?: AgentEnvironmentProviderRegistry,\n): AgentEnvironmentProvider {\n if (typeof provider !== 'string') return provider\n if (!registry) {\n throw new ValidationError(\n `agent environment provider \"${provider}\" requires an AgentEnvironmentProviderRegistry`,\n )\n }\n return registry.require(provider)\n}\n\n/** Options for exposing an `AgentEnvironmentProvider` through the legacy sandbox client port.\n * @experimental */\nexport interface ProviderAsSandboxClientOptions {\n defaults?: Partial<CreateAgentEnvironmentInput>\n requireTerminalEvent?: boolean\n /** Require declared live continuation plus concrete session controls. */\n requireSession?: boolean\n mapCreateOptions?: (\n options: CreateSandboxOptions | undefined,\n ) => Partial<CreateAgentEnvironmentInput>\n}\n\n/** Adapt a neutral environment provider to the `SandboxClient` interface used by existing loop paths.\n * @experimental */\nexport function providerAsSandboxClient(\n provider: AgentEnvironmentProvider,\n options: ProviderAsSandboxClientOptions = {},\n): SandboxClient {\n return {\n async create(createOptions?: CreateSandboxOptions): Promise<SandboxInstance> {\n const defaults = options.defaults ?? {}\n const sandboxInput = createInputFromSandboxOptions(createOptions)\n const customInput = options.mapCreateOptions?.(createOptions) ?? {}\n const mapped = {\n ...defaults,\n ...sandboxInput,\n ...customInput,\n providerOptions: {\n ...(defaults.providerOptions ?? {}),\n ...(sandboxInput.providerOptions ?? {}),\n ...(customInput.providerOptions ?? {}),\n },\n }\n if (mapped.backend === undefined) delete mapped.backend\n if (mapped.profile === undefined) {\n throw new ValidationError(\n `providerAsSandboxClient(${provider.name}): profile required in defaults or CreateSandboxOptions.backend.profile`,\n )\n }\n if (options.requireSession) {\n const capabilities = await provider.capabilities()\n if (!capabilities.streaming.live || !capabilities.sessions.continue) {\n throw new ValidationError(\n `providerAsSandboxClient(${provider.name}): live session continuation is required`,\n )\n }\n }\n const environment = await provider.create(mapped as CreateAgentEnvironmentInput)\n if (options.requireSession && !environment.session) {\n await environment.destroy?.()\n throw new ValidationError(\n `providerAsSandboxClient(${provider.name}): session() is required`,\n )\n }\n return environmentAsSandboxInstance(environment, {\n requireTerminalEvent: options.requireTerminalEvent ?? true,\n })\n },\n }\n}\n\n/** Options for wrapping the current Tangle sandbox client as an environment provider.\n * @experimental */\nexport interface SandboxClientProviderOptions {\n name?: string\n defaultBackend?: BackendType\n capabilities?:\n | AgentEnvironmentCapabilities\n | (() => AgentEnvironmentCapabilities | Promise<AgentEnvironmentCapabilities>)\n validateProfile?: (\n profile: AgentProfileRef,\n ) => AgentProfileValidationResult | Promise<AgentProfileValidationResult>\n /** Resolve a named profile before calling Sandbox, which accepts inline profiles only. */\n resolveProfile?: (profileId: string) => AgentProfile | Promise<AgentProfile>\n mapCreateInput?: (input: CreateAgentEnvironmentInput) => CreateSandboxOptions\n}\n\n/** Adapt a `SandboxClient` into the shared `AgentEnvironmentProvider` contract.\n * @experimental */\nexport function sandboxClientAsProvider(\n client: SandboxClient,\n options: SandboxClientProviderOptions = {},\n): AgentEnvironmentProvider {\n const providerName = options.name ?? 'tangle-sandbox'\n return {\n name: providerName,\n capabilities: async () => {\n if (options.capabilities) {\n return typeof options.capabilities === 'function'\n ? options.capabilities()\n : options.capabilities\n }\n return defaultTangleSandboxCapabilities({\n namedProfiles: options.resolveProfile !== undefined,\n })\n },\n ...(options.validateProfile ? { validateProfile: options.validateProfile } : {}),\n async create(input: CreateAgentEnvironmentInput): Promise<AgentEnvironment> {\n const createOptions =\n options.mapCreateInput?.(input) ??\n (await sandboxOptionsFromCreateInput(\n input,\n options.defaultBackend ?? 'opencode',\n options.resolveProfile,\n ))\n const box = await client.create(\n createOptions,\n input.signal === undefined ? undefined : { signal: input.signal },\n )\n return sandboxInstanceAsEnvironment(box, providerName, client)\n },\n ...(hasGet(client)\n ? {\n async get(id: string): Promise<AgentEnvironment | null> {\n const box = await client.get(id)\n return box ? sandboxInstanceAsEnvironment(box, providerName, client) : null\n },\n }\n : {}),\n ...(hasList(client)\n ? {\n async list(query?: AgentEnvironmentQuery): Promise<AgentEnvironmentSummary[]> {\n const boxes = await client.list(query?.providerOptions)\n return boxes.map((box) => ({\n id: String(box.id),\n provider: providerName,\n name: typeof box.name === 'string' ? box.name : undefined,\n status: statusFromUnknown(readBoxStatus(box)),\n metadata: readBoxMetadata(box),\n }))\n },\n }\n : {}),\n }\n}\n\n/** Options for running a provider as a supervise-mode executor.\n * @experimental */\nexport interface ProviderExecutorOptions {\n defaults?: Partial<CreateAgentEnvironmentInput>\n runtime?: Runtime\n destroyOnSettle?: boolean\n requireTerminalEvent?: boolean\n /** Transform only the profile sent to `provider.create`. The original profile\n * remains the input to `taskToTurn`, so execution-only normalization cannot\n * rewrite the caller's task mapping. */\n profileForCreate?: (profile: AgentProfile) => AgentProfile\n taskToTurn?: (task: unknown, specProfile: AgentProfile) => AgentTurnInput\n}\n\n/** Adapt an environment provider into an `ExecutorFactory` for `createExecutor`.\n * @experimental */\nexport function providerAsExecutor(\n provider: AgentEnvironmentProvider,\n options: ProviderExecutorOptions = {},\n): ExecutorFactory<unknown> {\n return (spec, ctx) => createProviderExecutor(provider, spec.profile, ctx, options)\n}\n\nfunction createProviderExecutor(\n provider: AgentEnvironmentProvider,\n profile: AgentProfile,\n ctx: ExecutorContext,\n options: ProviderExecutorOptions,\n): Executor<unknown> {\n const controller = linkAbort(ctx.signal)\n\n let environment: AgentEnvironment | undefined\n let artifact: ExecutorResult<unknown> | undefined\n\n const runtime = options.runtime ?? (provider.name as Runtime)\n // The exact bytes this executor hands to `provider.create`. A `profileForCreate` overlay changes\n // them, so the declaration carries the overlaid profile and exact turn execution refuses the run\n // rather than presenting the authored profile as what the provider received.\n const createProfile = options.profileForCreate?.(profile) ?? profile\n const executionId = ctx.node?.nodeId ?? `provider-run-${randomUUID()}`\n const attemptId = ctx.node?.attemptId ?? newExecutionAttemptId(executionId)\n const providerModel = concreteProfileModel(createProfile)\n // The provider owns the model call inside its environment and the create input carries no\n // completion cap, so a requested ceiling is refused before the environment is paid for.\n const tokenLimits = enforceTokenLimits(\n profileModelExecutionSettings(createProfile, `providerAsExecutor(${provider.name})`)\n .tokenLimits,\n 'provider',\n `providerAsExecutor(${provider.name})`,\n )\n // The environment identity is server-issued, so before `create` resolves this declaration is a\n // planned authority check, never a receipt.\n const plannedDeclaration: ExecutorMaterialization = {\n effectiveProfile: createProfile,\n backend: provider.name,\n model: providerModel\n ? { status: 'known', id: providerModel }\n : { status: 'unknown', reason: 'provider environment selected its default model' },\n execution: { kind: 'environment', id: executionId },\n materializer: 'environment-provider-create',\n plan: {\n kind: 'agent-environment',\n provider: provider.name,\n destroyOnSettle: options.destroyOnSettle ?? true,\n requireTerminalEvent: options.requireTerminalEvent ?? true,\n tokenLimits,\n environmentId: null,\n },\n }\n const plannedBinding: ExecutorExecutionBinding = {\n attemptId,\n binding: {\n provider: provider.name,\n executionId,\n model: providerModel ?? null,\n },\n descriptor: { kind: 'agent-environment', transport: 'provider', backend: provider.name },\n }\n\n let executor!: Executor<unknown>\n executor = {\n runtime,\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamProviderExecutor({\n provider,\n profile,\n createProfile,\n task,\n signal,\n controller,\n options,\n onEnvironment: (env) => {\n environment = env\n // `create` resolved, so the environment identity the provider issued is now evidence.\n finalizeRuntimeOwnedPendingExecutor(\n executor,\n {\n ...plannedDeclaration,\n execution: { kind: 'environment', id: env.id },\n plan: { ...(plannedDeclaration.plan as object), environmentId: env.id },\n },\n plannedBinding,\n )\n },\n onArtifact: (next) => {\n artifact = next\n },\n })\n },\n async cancel(request): Promise<ExecutorCancellation> {\n // The provider streams a turn rather than dispatching a durable run, so this executor holds\n // no exact control reference the provider could cancel against. Aborting the local stream is\n // all Runtime can prove; the environment stays alive for `teardown` to release.\n controller.abort()\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt: new Date().toISOString(),\n detail: `providerAsExecutor(${provider.name}): the streamed turn carries no durable run reference, so the provider acknowledged nothing`,\n evidence: {\n operationId: request.operationId,\n ...(environment ? { environmentId: environment.id } : {}),\n },\n }\n },\n async teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n await environment?.destroy?.()\n return { destroyed: true }\n },\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) {\n throw new ValidationError(\n `providerAsExecutor(${provider.name}): resultArtifact() read before stream drained`,\n )\n }\n return artifact\n },\n }\n return attestRuntimeOwnedPendingExecutor(executor, runtime, plannedDeclaration, plannedBinding)\n}\n\ninterface StreamProviderExecutorArgs {\n provider: AgentEnvironmentProvider\n profile: AgentProfile\n /** The exact profile handed to `provider.create` — the authored profile unless the caller\n * installed a `profileForCreate` overlay. */\n createProfile: AgentProfile\n task: unknown\n signal: AbortSignal\n controller: AbortController\n options: ProviderExecutorOptions\n onEnvironment: (environment: AgentEnvironment) => void\n onArtifact: (artifact: ExecutorResult<unknown>) => void\n}\n\nasync function* streamProviderExecutor(\n args: StreamProviderExecutorArgs,\n): AsyncIterable<UsageEvent> {\n const started = Date.now()\n const linked = linkAbort(args.signal, args.controller.signal).signal\n const environment = await args.provider.create({\n ...(args.options.defaults ?? {}),\n profile: args.createProfile,\n signal: linked,\n })\n args.onEnvironment(environment)\n\n const turn =\n args.options.taskToTurn?.(args.task, args.profile) ?? taskToTurnInput(args.task, linked)\n const events: AgentEnvironmentEvent[] = []\n const tokens = zeroTokenUsage()\n let usd = 0\n let text = ''\n let terminal = false\n try {\n const toolParts = createSandboxToolPartState()\n for await (const event of environment.stream({ ...turn, signal: linked })) {\n events.push(event)\n text += textFromEnvironmentEvent(event)\n // One projection for every sandbox-shaped stream: the provider event is adapted to the\n // sandbox wire the mappers already read, so live output needs no provider-specific parser.\n for (const progress of sandboxProgressEvents(\n sandboxEventFromEnvironmentEvent(event),\n toolParts,\n )) {\n yield { kind: 'progress', progress }\n }\n const usage = usageFromEnvironmentEvent(event)\n if (usage.input || usage.output) {\n tokens.input += usage.input\n tokens.output += usage.output\n yield { kind: 'tokens', input: usage.input, output: usage.output }\n }\n if (usage.usd) {\n usd += usage.usd\n // A provider-reported dollar figure carries no receipt, so it is an observed floor.\n yield { kind: 'cost', usdKnown: false, usd: usage.usd, provenance: 'uncaptured' }\n }\n if (isTerminalEnvironmentEvent(event)) terminal = true\n }\n if ((args.options.requireTerminalEvent ?? true) && !terminal) {\n throw new ValidationError(\n `providerAsExecutor(${args.provider.name}): stream ended without a terminal result/done/status event`,\n )\n }\n yield { kind: 'iteration' }\n const result = resultFromEvents(events, text)\n const spent: Spend = {\n iterations: 1,\n tokens,\n usd,\n // No provider event carries a billing receipt, so the dollar channel stays unproven even\n // when the provider reported a number. A dollar cap must refuse rather than compare.\n usdKnown: false,\n ms: Date.now() - started,\n }\n args.onArtifact({\n outRef: contentRef(`provider:${args.provider.name}`, result),\n out: result,\n spent,\n })\n } finally {\n if (args.options.destroyOnSettle ?? true) await environment.destroy?.()\n }\n}\n\nfunction createInputFromSandboxOptions(\n options: CreateSandboxOptions | undefined,\n): Partial<CreateAgentEnvironmentInput> {\n const profile = options?.backend?.profile\n const backend = options?.backend?.type\n const workspace = {\n ...(options?.environment ? { environment: options.environment } : {}),\n ...(options?.git?.url ? { repoUrl: options.git.url } : {}),\n ...(options?.git?.ref ? { gitRef: options.git.ref } : {}),\n }\n return {\n ...(profile !== undefined ? { profile } : {}),\n ...(backend ? { backend } : {}),\n ...(Object.keys(workspace).length > 0 ? { workspace } : {}),\n ...(options?.resources ? { resources: options.resources as ResourceRequest } : {}),\n ...(options?.env ? { env: options.env } : {}),\n ...(options?.secrets ? { secrets: options.secrets } : {}),\n ...(options?.metadata ? { metadata: options.metadata } : {}),\n ...(options?.name ? { name: options.name } : {}),\n ...(options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\n providerOptions: { sandboxCreateOptions: options ?? {} },\n }\n}\n\nasync function sandboxOptionsFromCreateInput(\n input: CreateAgentEnvironmentInput,\n defaultBackend: BackendType,\n resolveProfile?: SandboxClientProviderOptions['resolveProfile'],\n): Promise<CreateSandboxOptions> {\n const backendType = (input.backend ?? defaultBackend) as BackendType\n const workspace = input.workspace ?? {}\n const environment = sandboxEnvironmentFromWorkspace(workspace)\n const providerOptions = input.providerOptions?.sandboxCreateOptions\n const base =\n providerOptions && typeof providerOptions === 'object'\n ? ({ ...(providerOptions as CreateSandboxOptions) } as CreateSandboxOptions)\n : ({} satisfies CreateSandboxOptions)\n assertSandboxSecretNames(input.secrets)\n assertSandboxSecretNames((base as { secrets?: unknown }).secrets)\n const profile = await sandboxProfileFromReference(input.profile, resolveProfile)\n const { profile: _baseProfile, ...baseBackend } = base.backend ?? {}\n return {\n ...base,\n ...(environment ? { environment } : {}),\n ...(workspace.repoUrl ? { git: { url: workspace.repoUrl, ref: workspace.gitRef } } : {}),\n ...(input.resources ? { resources: input.resources as CreateSandboxOptions['resources'] } : {}),\n ...(input.env ? { env: input.env } : {}),\n ...(Array.isArray(input.secrets) ? { secrets: input.secrets } : {}),\n ...(input.metadata ? { metadata: input.metadata } : {}),\n ...(input.name ? { name: input.name } : {}),\n ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),\n backend: {\n ...baseBackend,\n type: backendType,\n profile,\n },\n }\n}\n\nfunction assertSandboxSecretNames(secrets: unknown): asserts secrets is string[] | undefined {\n if (\n secrets !== undefined &&\n (!Array.isArray(secrets) ||\n secrets.some((secret) => typeof secret !== 'string' || secret.trim().length === 0))\n ) {\n throw new ValidationError(\n 'Tangle Sandbox secret names must be non-empty strings; secret values are unsupported',\n )\n }\n}\n\nfunction sandboxEnvironmentFromWorkspace(\n workspace: NonNullable<CreateAgentEnvironmentInput['workspace']>,\n): string | undefined {\n if (\n workspace.environment !== undefined &&\n workspace.image !== undefined &&\n workspace.environment !== workspace.image\n ) {\n throw new ValidationError(\n 'Tangle Sandbox accepts one environment value; workspace.environment and workspace.image must match',\n )\n }\n return workspace.environment ?? workspace.image\n}\n\nasync function sandboxProfileFromReference(\n profile: AgentProfileRef,\n resolveProfile: SandboxClientProviderOptions['resolveProfile'],\n): Promise<AgentProfile> {\n if (typeof profile !== 'string') return profile\n if (!resolveProfile) {\n throw new ValidationError(\n `Tangle Sandbox requires an inline AgentProfile; named profile \"${profile}\" needs SandboxClientProviderOptions.resolveProfile`,\n )\n }\n return resolveProfile(profile)\n}\n\nfunction environmentAsSandboxInstance(\n environment: AgentEnvironment,\n options: { requireTerminalEvent: boolean },\n): SandboxInstance {\n const box = {\n id: environment.id,\n name: environment.name,\n status: 'running',\n async refresh(): Promise<void> {\n await environment.refresh?.()\n },\n async *streamPrompt(\n message: string | PromptInputPart[],\n promptOptions?: PromptOptions,\n ): AsyncGenerator<SandboxEvent> {\n let terminal = false\n const input = turnInputFromPrompt(message, promptOptions)\n let cancellation: Promise<void> | undefined\n let cancellationStarted = false\n let cancellationFailed = false\n let cancellationError: unknown\n const cancel = () => {\n if (cancellationStarted || !input.sessionId || !environment.session) return\n cancellationStarted = true\n try {\n const session = environment.session(input.sessionId, {\n ...(input.controlRef === undefined ? {} : { controlRef: input.controlRef }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n })\n assertScopedSessionForInput(session, input)\n cancellation = session.cancel().catch((error: unknown) => {\n cancellationFailed = true\n cancellationError = error\n })\n } catch (error) {\n cancellationFailed = true\n cancellationError = error\n }\n }\n input.signal?.addEventListener('abort', cancel, { once: true })\n if (input.signal?.aborted) cancel()\n let streamFailed = false\n let streamError: unknown\n try {\n for await (const event of environment.stream(input)) {\n if (isTerminalEnvironmentEvent(event)) terminal = true\n const usageEvent = usageSandboxEvent(event)\n if (usageEvent) yield usageEvent\n yield sandboxEventFromEnvironmentEvent(event)\n }\n } catch (error) {\n streamFailed = true\n streamError = error\n } finally {\n input.signal?.removeEventListener('abort', cancel)\n if (input.signal?.aborted) {\n cancel()\n await cancellation\n }\n }\n if (input.signal?.aborted) {\n const abortError = new DOMException('Provider session stream aborted', 'AbortError')\n const causes = [\n ...(streamFailed ? [streamError] : []),\n ...(cancellationFailed ? [cancellationError] : []),\n ]\n if (causes.length > 0) {\n Object.defineProperty(abortError, 'cause', {\n value:\n causes.length === 1\n ? causes[0]\n : new AggregateError(causes, 'Provider stream and cancellation failed'),\n })\n }\n throw abortError\n }\n if (streamFailed) throw streamError\n if (cancellationFailed) throw cancellationError\n if (options.requireTerminalEvent && !terminal) {\n throw new ValidationError(\n `providerAsSandboxClient(${environment.provider}): stream ended without a terminal result/done/status event`,\n )\n }\n },\n async prompt(\n message: string | PromptInputPart[],\n promptOptions?: PromptOptions,\n ): Promise<PromptResult> {\n const events: AgentEnvironmentEvent[] = []\n let text = ''\n let usage: TokenUsage | undefined\n let terminal = false\n for await (const event of environment.stream(turnInputFromPrompt(message, promptOptions))) {\n events.push(event)\n if (isTerminalEnvironmentEvent(event)) terminal = true\n text += textFromEnvironmentEvent(event)\n usage = mergeTokenUsage(usage, event.usage)\n }\n if (options.requireTerminalEvent && !terminal) {\n throw new ValidationError(\n `providerAsSandboxClient(${environment.provider}): prompt ended without a terminal result/done/status event`,\n )\n }\n return {\n response: resultFromEvents(events, text).content,\n success: true,\n status: 'success',\n durationMs: 0,\n ...(usage ? { usage } : {}),\n }\n },\n ...(environment.dispatch && environment.session\n ? {\n async dispatchPrompt(message: string | PromptInputPart[], promptOptions?: PromptOptions) {\n const session = await environment.dispatch?.(\n turnInputFromPrompt(message, promptOptions),\n )\n if (!session)\n throw new ValidationError('providerAsSandboxClient: dispatch returned no session')\n return sandboxDispatchResultFromSessionRef(session)\n },\n }\n : {}),\n ...(environment.session\n ? {\n session(id: string, sessionOptions?: { controlRef?: AgentRunControlRef }) {\n return sandboxSessionFromAgentSession(\n environment.session?.(id, sessionOptions),\n sessionOptions?.controlRef,\n )\n },\n }\n : {}),\n ...(environment.read ? { read: environment.read.bind(environment) } : {}),\n ...(environment.write ? { write: environment.write.bind(environment) } : {}),\n ...(environment.exec\n ? {\n exec: environment.exec.bind(environment),\n }\n : {}),\n ...(environment.checkpoint\n ? {\n async checkpoint(checkpointOptions?: CheckpointRequest) {\n const checkpoint = await environment.checkpoint?.(checkpointOptions)\n return { checkpointId: checkpoint?.id, id: checkpoint?.id }\n },\n }\n : {}),\n ...(environment.fork\n ? {\n async fork(checkpointId: string, forkOptions?: ForkRequest) {\n const forked = await environment.fork?.({ id: checkpointId }, forkOptions)\n if (!forked)\n throw new ValidationError('providerAsSandboxClient: fork returned no environment')\n return environmentAsSandboxInstance(forked, options)\n },\n }\n : {}),\n async delete(): Promise<void> {\n await environment.destroy?.()\n },\n }\n return box as unknown as SandboxInstance\n}\n\nfunction sandboxInstanceAsEnvironment(\n box: SandboxInstance,\n providerName: string,\n client: SandboxClient,\n): AgentEnvironment {\n const environment: AgentEnvironment = {\n id: String(box.id),\n provider: providerName,\n ...(typeof box.name === 'string' ? { name: box.name } : {}),\n ...(readBoxMetadata(box) ? { metadata: readBoxMetadata(box) } : {}),\n async status(): Promise<AgentEnvironmentStatus> {\n await maybeRefresh(box)\n return statusFromUnknown(readBoxStatus(box))\n },\n async *stream(input: AgentTurnInput): AsyncIterable<AgentEnvironmentEvent> {\n for await (const event of box.streamPrompt(\n promptFromAgentTurnInput(input),\n promptOptionsFromAgentTurnInput(input),\n )) {\n yield environmentEventFromSandboxEvent(event)\n }\n },\n ...(hasDispatchPrompt(box)\n ? {\n async dispatch(input: AgentTurnInput): Promise<AgentSessionRef> {\n const dispatched = await box.dispatchPrompt(\n promptFromAgentTurnInput(input),\n promptOptionsFromAgentTurnInput(input),\n )\n return sessionRefFromSandboxDispatch(dispatched, providerName)\n },\n }\n : {}),\n ...(hasSession(box)\n ? {\n session(id: string, sessionOptions?: { controlRef?: AgentRunControlRef }): AgentSession {\n return sandboxSessionAsAgentSession(box.session(id), sessionOptions?.controlRef)\n },\n async respondToInteraction(\n command: InteractionResponseCommand,\n options?: { signal?: AbortSignal },\n ): Promise<InteractionAcknowledgement> {\n const response = await box\n .session(command.binding.sessionId)\n .respondToInteraction(command, options)\n return response.acknowledgement\n },\n }\n : {}),\n ...(hasRead(box) ? { read: box.read.bind(box) } : {}),\n ...(hasWrite(box) ? { write: box.write.bind(box) } : {}),\n ...(hasExec(box)\n ? {\n async exec(command: string, options?: ExecRequest): Promise<ExecResult> {\n return execResultFromSandboxExecResult(await box.exec(command, options as never))\n },\n }\n : {}),\n async checkpoint(options?: CheckpointRequest): Promise<CheckpointRef> {\n const result = await box.snapshot({\n ...(options?.name ? { tags: [options.name] } : {}),\n })\n return {\n id: result.snapshotId,\n provider: providerName,\n ...(options?.metadata ? { metadata: options.metadata } : {}),\n }\n },\n async fork(checkpoint: CheckpointRef, options?: ForkRequest): Promise<AgentEnvironment> {\n const forked = await client.create({\n fromSnapshot: checkpoint.id,\n fromSandboxId: String(box.id),\n ...(options?.name ? { name: options.name } : {}),\n ...(options?.metadata ? { metadata: options.metadata } : {}),\n })\n return sandboxInstanceAsEnvironment(forked, providerName, client)\n },\n async placement(): Promise<PlacementInfo> {\n return placementInfoFromLoopPlacement(client.describePlacement?.(box), box)\n },\n async refresh(): Promise<void> {\n await maybeRefresh(box)\n },\n async destroy(): Promise<void> {\n await destroyBox(box)\n },\n }\n return environment\n}\n\nfunction sandboxSessionAsAgentSession(\n session: SandboxSessionLike,\n expectedControlRef?: AgentRunControlRef,\n): AgentSession {\n // SandboxSession has no synchronous controlRef property. The exact ref\n // returned by dispatch is therefore the wrapper's persisted binding, while\n // any ref later exposed by status is still validated below.\n const controlRef = resolveSessionControlRef(session.controlRef, expectedControlRef, {\n allowExpectedWhenActualAbsent: true,\n })\n return {\n id: session.id,\n ...(controlRef === undefined ? {} : { controlRef }),\n async status(): Promise<AgentSessionStatus | null> {\n const status = await session.status()\n if (!status) return null\n assertSandboxStatusBinding(status, controlRef)\n return sessionStatusFromUnknown((status as { status?: unknown }).status)\n },\n async *events(options?: {\n since?: string\n executionId?: string\n signal?: AbortSignal\n }): AsyncIterable<AgentEnvironmentEvent> {\n const executionId = scopedExecutionId(controlRef, options?.executionId)\n for await (const event of session.events({\n ...(options?.since === undefined ? {} : { since: options.since }),\n ...(executionId === undefined ? {} : { executionId }),\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n }))\n yield environmentEventFromSandboxEvent(event)\n },\n async result(options?: { signal?: AbortSignal }): Promise<AgentTurnResult> {\n return agentTurnResultFromPromptResult(\n await awaitAbortable(\n Promise.resolve().then(() =>\n session.result({\n ...(controlRef?.executionId === undefined\n ? {}\n : { executionId: controlRef.executionId }),\n }),\n ),\n options?.signal,\n ),\n )\n },\n async prompt(input: AgentTurnInput): Promise<AgentTurnResult> {\n return agentTurnResultFromPromptResult(\n await session.prompt(\n promptFromAgentTurnInput(input),\n promptOptionsFromAgentTurnInput(input),\n ),\n )\n },\n ...(session.respondToInteraction\n ? {\n async respondToInteraction(\n command: InteractionResponseCommand,\n options?: { signal?: AbortSignal },\n ): Promise<InteractionAcknowledgement> {\n assertInteractionCommandScope(command, controlRef)\n const response = await session.respondToInteraction!(command, options)\n return response.acknowledgement\n },\n }\n : {}),\n ...(session.cancelRun\n ? {\n async cancelRun(\n request: AgentRunCancellationRequest,\n options?: { signal?: AbortSignal },\n ): Promise<AgentRunCancellationAcknowledgement> {\n assertCancellationScope(request, controlRef)\n return session.cancelRun!(request, options)\n },\n }\n : {}),\n cancel(): Promise<void> {\n return session\n .interrupt(\n controlRef?.executionId === undefined\n ? undefined\n : { executionId: controlRef.executionId },\n )\n .then(() => undefined)\n },\n }\n}\n\nfunction sandboxSessionFromAgentSession(\n session: AgentSession | undefined,\n expectedControlRef?: AgentRunControlRef,\n): SandboxSessionLike {\n if (!session) throw new ValidationError('providerAsSandboxClient: session is unavailable')\n const controlRef = resolveSessionControlRef(session.controlRef, expectedControlRef)\n return {\n id: session.id,\n ...(controlRef === undefined ? {} : { controlRef }),\n async status() {\n const status = await session.status()\n if (!status) return null\n return {\n id: session.id,\n status: sandboxSessionStatusFromAgentSessionStatus(status),\n }\n },\n async *events(options?: {\n since?: string\n executionId?: string\n signal?: AbortSignal\n }): AsyncGenerator<SandboxEvent> {\n const executionId = scopedExecutionId(controlRef, options?.executionId)\n for await (const event of session.events({\n ...(options?.since === undefined ? {} : { since: options.since }),\n ...(executionId === undefined ? {} : { executionId }),\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n }))\n yield sandboxEventFromEnvironmentEvent(event)\n },\n async result(options?: { executionId?: string }): Promise<PromptResult> {\n scopedExecutionId(controlRef, options?.executionId)\n return promptResultFromAgentTurnResult(await session.result())\n },\n async prompt(\n message: string | PromptInputPart[],\n options?: PromptOptions,\n ): Promise<PromptResult> {\n return promptResultFromAgentTurnResult(\n await session.prompt(turnInputFromPrompt(message, options)),\n )\n },\n ...(session.respondToInteraction\n ? {\n async respondToInteraction(\n command: InteractionResponseCommand,\n options?: { signal?: AbortSignal },\n ) {\n assertInteractionCommandScope(command, controlRef)\n return {\n acknowledgement: await session.respondToInteraction!(command, options),\n }\n },\n }\n : {}),\n ...(session.cancelRun\n ? {\n async cancelRun(\n request: AgentRunCancellationRequest,\n options?: { signal?: AbortSignal },\n ): Promise<AgentRunCancellationAcknowledgement> {\n assertCancellationScope(request, controlRef)\n return session.cancelRun!(request, options)\n },\n }\n : {}),\n async interrupt(options?: { executionId?: string }) {\n scopedExecutionId(controlRef, options?.executionId)\n await session.cancel()\n return { cancelled: true }\n },\n }\n}\n\nfunction sandboxSessionStatusFromAgentSessionStatus(\n status: AgentSessionStatus,\n): 'queued' | 'running' | 'completed' | 'failed' | 'cancelled' {\n switch (status) {\n case 'pending':\n case 'provisioning':\n return 'queued'\n case 'running':\n return 'running'\n case 'completed':\n return 'completed'\n case 'cancelled':\n return 'cancelled'\n // Sandbox has no neutral stopped state; do not report completion without success proof.\n case 'stopped':\n case 'failed':\n case 'expired':\n case 'unknown':\n return 'failed'\n }\n}\n\nfunction promptResultFromAgentTurnResult(result: AgentTurnResult): PromptResult {\n return {\n response: result.text,\n success: result.success,\n status: result.success ? 'success' : 'failed',\n durationMs: 0,\n ...(result.error ? { error: result.error } : {}),\n ...(result.usage\n ? {\n usage: {\n inputTokens: result.usage.inputTokens,\n outputTokens: result.usage.outputTokens,\n },\n ...(result.usage.cost === undefined ? {} : { costUsd: result.usage.cost }),\n }\n : {}),\n }\n}\n\nfunction environmentEventFromSandboxEvent(event: SandboxEvent): AgentEnvironmentEvent {\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n const normalized = canonicalStreamEventFromSandboxEvent(event)\n return {\n type: String(event.type),\n data,\n ...(event.id ? { id: event.id } : {}),\n ...(normalized ? { normalized } : {}),\n usage: tokenUsageFromData(data),\n providerEvent: event,\n }\n}\n\nfunction sandboxEventFromEnvironmentEvent(event: AgentEnvironmentEvent): SandboxEvent {\n const normalized = event.normalized\n const type = normalized?.type ?? event.type\n const baseData = normalized ? sandboxDataFromNormalizedEvent(event.data, normalized) : event.data\n const usage = event.usage ? tokenUsageData(event.usage) : undefined\n const data = (() => {\n if (!usage) return baseData\n if (isUsageType(type))\n return {\n ...baseData,\n tokensIn: event.usage?.inputTokens,\n tokensOut: event.usage?.outputTokens,\n ...(event.usage?.cost !== undefined ? { costUsd: event.usage.cost } : {}),\n ...usage,\n }\n if (isNestedUsageType(type)) return { ...baseData, usage }\n if (type === 'done') {\n return {\n ...baseData,\n tokenUsage: usage,\n ...(usage.totalCostUsd !== undefined ? { totalCostUsd: usage.totalCostUsd } : {}),\n }\n }\n return baseData\n })()\n return {\n type,\n data,\n ...(event.id ? { id: event.id } : {}),\n }\n}\n\nfunction usageSandboxEvent(event: AgentEnvironmentEvent): SandboxEvent | undefined {\n const type = event.normalized?.type ?? event.type\n if (!event.usage || isUsageType(type) || isNestedUsageType(type) || type === 'done') {\n return undefined\n }\n const usage = tokenUsageData(event.usage)\n if (\n usage.inputTokens === undefined &&\n usage.outputTokens === undefined &&\n usage.totalCostUsd === undefined\n ) {\n return undefined\n }\n return { type: 'llm_call', data: usage }\n}\n\nfunction sandboxDataFromNormalizedEvent(\n rawData: Record<string, unknown>,\n normalized: NonNullable<AgentEnvironmentEvent['normalized']>,\n): Record<string, unknown> {\n const { type: _type, ...normalizedData } = normalized\n return {\n ...rawData,\n ...normalizedData,\n ...(normalized.type === 'message.part.updated' && normalized.part.type === 'text'\n ? { text: normalized.part.text }\n : {}),\n }\n}\n\nfunction tokenUsageData(usage: TokenUsage): Record<string, number> {\n return {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n ...(usage.totalTokens !== undefined ? { totalTokens: usage.totalTokens } : {}),\n ...(usage.cacheReadInputTokens !== undefined\n ? { cacheReadInputTokens: usage.cacheReadInputTokens }\n : {}),\n ...(usage.cacheCreationInputTokens !== undefined\n ? { cacheCreationInputTokens: usage.cacheCreationInputTokens }\n : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cost !== undefined ? { totalCostUsd: usage.cost } : {}),\n }\n}\n\nfunction turnInputFromPrompt(\n message: string | PromptInputPart[],\n options?: PromptOptions,\n): AgentTurnInput {\n return {\n ...(typeof message === 'string' ? { prompt: message } : { parts: message }),\n ...(options?.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options?.model ? { model: options.model } : {}),\n ...(options?.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),\n ...(options?.executionId ? { executionId: options.executionId } : {}),\n ...(options?.lastEventId ? { lastEventId: options.lastEventId } : {}),\n ...(options?.turnId ? { turnId: options.turnId } : {}),\n ...(options?.detach !== undefined ? { detach: options.detach } : {}),\n ...(options?.context ? { context: options.context } : {}),\n ...(options?.runControlRef ? { controlRef: options.runControlRef } : {}),\n ...(options?.backend?.interactions ? { interactions: options.backend.interactions } : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.backend ? { providerOptions: { backend: options.backend } } : {}),\n }\n}\n\nfunction resolveSessionControlRef(\n actual: AgentRunControlRef | undefined,\n expected: AgentRunControlRef | undefined,\n options: { allowExpectedWhenActualAbsent?: boolean } = {},\n): AgentExactRunControlRef | undefined {\n if (expected === undefined) {\n if (actual === undefined) return undefined\n return AgentExactRunControlRefSchema.parse(actual)\n }\n const expectedExact = AgentExactRunControlRefSchema.parse(expected)\n if (actual === undefined) {\n if (options.allowExpectedWhenActualAbsent === true) return expectedExact\n throw new ValidationError('provider session omitted the required exact run control reference')\n }\n const actualExact = AgentExactRunControlRefSchema.safeParse(actual)\n if (!actualExact.success) {\n throw new ValidationError('provider session returned an invalid exact run control reference')\n }\n if (!sameControlCoordinates(actualExact.data, expectedExact)) {\n throw new ValidationError('provider session returned a different exact run control reference')\n }\n return actualExact.data\n}\n\nfunction assertSandboxStatusBinding(\n status: unknown,\n controlRef: AgentExactRunControlRef | undefined,\n): void {\n if (!status || typeof status !== 'object' || controlRef === undefined) return\n const record = status as Record<string, unknown>\n if (record.runControlRef !== undefined) {\n const statusControlRef = AgentExactRunControlRefSchema.parse(record.runControlRef)\n if (!sameControlCoordinates(statusControlRef, controlRef)) {\n throw new ValidationError('sandbox status returned a different exact run control reference')\n }\n }\n for (const key of ['activeExecutionId', 'latestExecutionId']) {\n const executionId = record[key]\n if (executionId !== undefined && executionId !== controlRef.executionId) {\n throw new ValidationError('sandbox status returned a different execution')\n }\n }\n}\n\nfunction assertInteractionCommandScope(\n command: InteractionResponseCommand,\n controlRef: AgentRunControlRef | undefined,\n): void {\n if (controlRef === undefined) return\n if (\n command.binding.runId !== controlRef.runId ||\n command.binding.provider !== controlRef.provider ||\n command.binding.environmentId !== controlRef.environmentId ||\n command.binding.sessionId !== controlRef.sessionId ||\n command.binding.executionId !== controlRef.executionId\n ) {\n throw new ValidationError('interaction response targeted a different execution')\n }\n}\n\nfunction assertCancellationScope(\n request: AgentRunCancellationRequest,\n controlRef: AgentExactRunControlRef | undefined,\n): void {\n if (controlRef === undefined) {\n throw new ValidationError(\n 'durable cancellation requires an exact wrapper run control reference',\n )\n }\n const exactRequest = AgentRunCancellationRequestSchema.parse(request)\n if (!sameControlCoordinates(exactRequest.run, controlRef)) {\n throw new ValidationError('cancellation targeted a different execution')\n }\n}\n\nfunction scopedExecutionId(\n controlRef: AgentRunControlRef | undefined,\n requested: string | undefined,\n): string | undefined {\n if (\n controlRef?.executionId !== undefined &&\n requested !== undefined &&\n controlRef.executionId !== requested\n ) {\n throw new ValidationError('session operation targeted a different execution')\n }\n return controlRef?.executionId ?? requested\n}\n\nfunction assertScopedSessionForInput(session: AgentSession, input: AgentTurnInput): void {\n if (input.executionId === undefined && input.controlRef === undefined) return\n const sessionControlRef = AgentExactRunControlRefSchema.safeParse(session.controlRef)\n if (!sessionControlRef.success) {\n throw new ValidationError(\n 'provider session did not expose an exact run control reference for scoped cancellation',\n )\n }\n const expectedControlRef =\n input.controlRef === undefined\n ? undefined\n : AgentExactRunControlRefSchema.parse(input.controlRef)\n if (\n (input.executionId !== undefined && sessionControlRef.data.executionId !== input.executionId) ||\n (expectedControlRef !== undefined &&\n !sameControlCoordinates(sessionControlRef.data, expectedControlRef))\n ) {\n throw new ValidationError('provider session returned a different exact run control reference')\n }\n}\n\nfunction taskToTurnInput(task: unknown, signal: AbortSignal): AgentTurnInput {\n return { prompt: taskToPrompt(task), signal }\n}\n\nfunction taskToPrompt(task: unknown): string {\n if (typeof task === 'string') return task\n if (task && typeof task === 'object') {\n const record = task as Record<string, unknown>\n for (const key of ['prompt', 'content', 'task', 'message']) {\n if (typeof record[key] === 'string') return record[key]\n }\n }\n return JSON.stringify(task)\n}\n\nfunction resultFromEvents(\n events: AgentEnvironmentEvent[],\n fallbackText: string,\n): { content: string; events: AgentEnvironmentEvent[] } {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n const text = event ? resultTextFromData(event.data) : undefined\n if (text !== undefined) return { content: text, events }\n }\n return { content: fallbackText, events }\n}\n\nfunction textFromEnvironmentEvent(event: AgentEnvironmentEvent): string {\n if (\n typeof event.normalized === 'object' &&\n event.normalized &&\n event.normalized.type === 'message.part.updated'\n ) {\n return typeof event.normalized.delta === 'string' ? event.normalized.delta : ''\n }\n const data = event.data\n for (const key of ['delta', 'chunk', 'content', 'text']) {\n if (typeof data[key] === 'string' && !isTerminalEnvironmentEvent(event)) return data[key]\n }\n return ''\n}\n\nfunction resultTextFromData(data: Record<string, unknown>): string | undefined {\n for (const key of ['finalText', 'text', 'response', 'resultSummary', 'content']) {\n if (typeof data[key] === 'string') return data[key]\n }\n return undefined\n}\n\nfunction isTerminalEnvironmentEvent(event: AgentEnvironmentEvent): boolean {\n if (isTerminalEventShape(event.type, event.data)) return true\n const normalized = event.normalized\n return (\n normalized?.type === 'status' &&\n (normalized.status === 'completed' || normalized.status === 'failed')\n )\n}\n\nfunction isTerminalEventShape(type: string, data: Record<string, unknown>): boolean {\n if (isSandboxTerminalEvent(type)) return true\n // A namespaced completion this provider transport may emit under any prefix. Broader than the\n // named sandbox list on purpose: an unknown `<x>.completed` still ends the stream.\n if (type.endsWith('.completed') || type.endsWith('.failed')) return true\n if (type !== 'status') return false\n return data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled'\n}\n\nfunction isUsageType(type: string): boolean {\n return type === 'llm_call' || type === 'usage' || type === 'cost.usage'\n}\n\n/** A terminal event whose usage rides `data.usage` — the nested shape this transport unwraps. */\nfunction isNestedUsageType(type: string): boolean {\n return isSandboxTerminalEvent(type) && sandboxTerminalUsageField(type) === 'usage'\n}\n\nfunction usageFromEnvironmentEvent(event: AgentEnvironmentEvent): {\n input: number\n output: number\n usd: number\n} {\n const usage = event.usage ?? tokenUsageFromData(event.data)\n return {\n input: finiteNumber(usage?.inputTokens) ?? 0,\n output: (finiteNumber(usage?.outputTokens) ?? 0) + (finiteNumber(usage?.reasoningTokens) ?? 0),\n usd:\n finiteNumber(usage?.cost) ??\n finiteNumber(event.data.costUsd) ??\n finiteNumber(event.data.totalCostUsd) ??\n 0,\n }\n}\n\nfunction tokenUsageFromData(data: Record<string, unknown>): TokenUsage | undefined {\n const usageRecord =\n data.usage && typeof data.usage === 'object'\n ? (data.usage as Record<string, unknown>)\n : data.tokenUsage && typeof data.tokenUsage === 'object'\n ? (data.tokenUsage as Record<string, unknown>)\n : data\n const inputTokens =\n finiteNumber(usageRecord.inputTokens) ??\n finiteNumber(usageRecord.tokensIn) ??\n finiteNumber(usageRecord.prompt_tokens)\n const outputTokens =\n finiteNumber(usageRecord.outputTokens) ??\n finiteNumber(usageRecord.tokensOut) ??\n finiteNumber(usageRecord.completion_tokens)\n const totalTokens = finiteNumber(usageRecord.totalTokens)\n const cacheReadInputTokens = finiteNumber(usageRecord.cacheReadInputTokens)\n const cacheCreationInputTokens = finiteNumber(usageRecord.cacheCreationInputTokens)\n const reasoningTokens = finiteNumber(usageRecord.reasoningTokens)\n const cost =\n finiteNumber(usageRecord.cost) ??\n finiteNumber(usageRecord.costUsd) ??\n finiteNumber(usageRecord.totalCostUsd) ??\n finiteNumber(data.costUsd) ??\n finiteNumber(data.totalCostUsd)\n if (\n inputTokens === undefined &&\n outputTokens === undefined &&\n totalTokens === undefined &&\n cacheReadInputTokens === undefined &&\n cacheCreationInputTokens === undefined &&\n reasoningTokens === undefined &&\n cost === undefined\n )\n return undefined\n return {\n inputTokens: inputTokens ?? 0,\n outputTokens: outputTokens ?? 0,\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n ...(cacheReadInputTokens !== undefined ? { cacheReadInputTokens } : {}),\n ...(cacheCreationInputTokens !== undefined ? { cacheCreationInputTokens } : {}),\n ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),\n ...(cost !== undefined ? { cost } : {}),\n }\n}\n\nfunction mergeTokenUsage(\n left: TokenUsage | undefined,\n right: TokenUsage | undefined,\n): TokenUsage | undefined {\n if (!left) return right\n if (!right) return left\n return {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n ...(left.totalTokens !== undefined || right.totalTokens !== undefined\n ? { totalTokens: (left.totalTokens ?? 0) + (right.totalTokens ?? 0) }\n : {}),\n ...(left.cacheReadInputTokens !== undefined || right.cacheReadInputTokens !== undefined\n ? {\n cacheReadInputTokens:\n (left.cacheReadInputTokens ?? 0) + (right.cacheReadInputTokens ?? 0),\n }\n : {}),\n ...(left.cacheCreationInputTokens !== undefined || right.cacheCreationInputTokens !== undefined\n ? {\n cacheCreationInputTokens:\n (left.cacheCreationInputTokens ?? 0) + (right.cacheCreationInputTokens ?? 0),\n }\n : {}),\n ...(left.reasoningTokens !== undefined || right.reasoningTokens !== undefined\n ? { reasoningTokens: (left.reasoningTokens ?? 0) + (right.reasoningTokens ?? 0) }\n : {}),\n ...(left.cost !== undefined || right.cost !== undefined\n ? { cost: (left.cost ?? 0) + (right.cost ?? 0) }\n : {}),\n }\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction agentTurnResultFromPromptResult(result: PromptResult): AgentTurnResult {\n const record = result as unknown as Record<string, unknown>\n const text =\n typeof record.response === 'string'\n ? record.response\n : typeof record.text === 'string'\n ? record.text\n : typeof record.finalText === 'string'\n ? record.finalText\n : ''\n const success = typeof record.success === 'boolean' ? record.success : true\n return {\n text,\n success,\n ...(typeof record.error === 'string' ? { error: record.error } : {}),\n usage: tokenUsageFromData(record),\n }\n}\n\nfunction sandboxDispatchResultFromSessionRef(session: AgentSessionRef): Record<string, unknown> {\n const controlRef =\n session.controlRef === undefined\n ? undefined\n : AgentExactRunControlRefSchema.parse(session.controlRef)\n const metadataExecutionId = optionalDispatchIdentity(session.metadata?.executionId, 'executionId')\n if (controlRef !== undefined) {\n if (controlRef.sessionId !== session.id) {\n throw new ValidationError(\n 'provider dispatch returned a control reference for another session',\n )\n }\n if (session.provider !== undefined && controlRef.provider !== session.provider) {\n throw new ValidationError(\n 'provider dispatch returned a control reference for another provider',\n )\n }\n if (metadataExecutionId !== undefined && metadataExecutionId !== controlRef.executionId) {\n throw new ValidationError('provider dispatch returned conflicting execution identities')\n }\n }\n const hasStatus = session.metadata && Object.hasOwn(session.metadata, 'status')\n const status = hasStatus ? sessionStatusFromUnknown(session.metadata?.status) : 'running'\n return {\n sessionId: session.id,\n status,\n alreadyExisted: session.metadata?.alreadyExisted === true,\n ...(session.metadata?.dispatched === undefined\n ? {}\n : { dispatched: session.metadata.dispatched === true }),\n ...(controlRef === undefined\n ? metadataExecutionId === undefined\n ? {}\n : { executionId: metadataExecutionId }\n : { executionId: controlRef.executionId, runControlRef: controlRef }),\n }\n}\n\nfunction sessionRefFromSandboxDispatch(dispatched: unknown, providerName: string): AgentSessionRef {\n const record =\n dispatched && typeof dispatched === 'object'\n ? (dispatched as Record<string, unknown>)\n : undefined\n const id = record?.sessionId ?? record?.id\n if (typeof id !== 'string' || id.length === 0) {\n throw new ValidationError('sandboxClientAsProvider: dispatch returned no session id')\n }\n if (!record) {\n throw new ValidationError('sandboxClientAsProvider: dispatch returned no session record')\n }\n const executionId = optionalDispatchIdentity(record.executionId, 'executionId')\n const controlRef =\n record.runControlRef === undefined\n ? undefined\n : AgentExactRunControlRefSchema.parse(record.runControlRef)\n if (controlRef !== undefined) {\n if (controlRef.sessionId !== id || controlRef.provider !== providerName) {\n throw new ValidationError('sandbox dispatch returned a control reference for another session')\n }\n if (executionId !== undefined && controlRef.executionId !== executionId) {\n throw new ValidationError('sandbox dispatch returned conflicting execution identities')\n }\n }\n if (record.alreadyExisted !== undefined && typeof record.alreadyExisted !== 'boolean') {\n throw new ValidationError('sandbox dispatch returned an invalid alreadyExisted flag')\n }\n if (record.dispatched !== undefined && typeof record.dispatched !== 'boolean') {\n throw new ValidationError('sandbox dispatch returned an invalid dispatched flag')\n }\n if (record.status !== undefined && !isSandboxSessionStatus(record.status)) {\n throw new ValidationError('sandbox dispatch returned an invalid session status')\n }\n return {\n id,\n provider: providerName,\n ...(controlRef === undefined ? {} : { controlRef }),\n metadata: {\n ...(record.status ? { status: record.status } : {}),\n ...(executionId === undefined ? {} : { executionId }),\n ...(record.alreadyExisted !== undefined ? { alreadyExisted: record.alreadyExisted } : {}),\n ...(record.dispatched !== undefined ? { dispatched: record.dispatched } : {}),\n },\n }\n}\n\nfunction optionalDispatchIdentity(value: unknown, label: string): string | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'string' || value.length === 0) {\n throw new ValidationError(`sandbox dispatch returned an invalid ${label}`)\n }\n return value\n}\n\nfunction isSandboxSessionStatus(value: unknown): boolean {\n return (\n value === 'queued' ||\n value === 'running' ||\n value === 'completed' ||\n value === 'failed' ||\n value === 'cancelled'\n )\n}\n\nfunction execResultFromSandboxExecResult(result: SandboxExecResult): ExecResult {\n const record = result as unknown as Record<string, unknown>\n const exitCode = finiteNumber(record.exitCode) ?? finiteNumber(record.code)\n if (exitCode === undefined) {\n throw new ValidationError('sandboxClientAsProvider: exec returned no exit code')\n }\n return {\n exitCode,\n stdout: typeof record.stdout === 'string' ? record.stdout : '',\n stderr: typeof record.stderr === 'string' ? record.stderr : '',\n }\n}\n\nfunction statusFromUnknown(status: unknown): AgentEnvironmentStatus {\n if (status === 'pending' || status === 'provisioning' || status === 'running') return status\n if (status === 'stopped' || status === 'failed' || status === 'expired') return status\n if (status === 'completed') return 'stopped'\n if (status === 'cancelled') return 'stopped'\n return 'unknown'\n}\n\nfunction sessionStatusFromUnknown(status: unknown): AgentSessionStatus | null {\n if (status === 'completed' || status === 'cancelled') return status\n return statusFromUnknown(status)\n}\n\nfunction readBoxStatus(box: SandboxInstance): unknown {\n return (box as unknown as { status?: unknown }).status\n}\n\nfunction readBoxMetadata(box: SandboxInstance): Record<string, unknown> | undefined {\n const metadata = (box as unknown as { metadata?: unknown }).metadata\n return metadata && typeof metadata === 'object'\n ? (metadata as Record<string, unknown>)\n : undefined\n}\n\nasync function maybeRefresh(box: SandboxInstance): Promise<void> {\n const refresh = (box as unknown as { refresh?: () => Promise<void> }).refresh\n if (typeof refresh === 'function') await refresh.call(box)\n}\n\nasync function destroyBox(box: SandboxInstance): Promise<void> {\n const deleteBox = (box as unknown as { delete?: () => Promise<void> }).delete\n if (typeof deleteBox === 'function') await deleteBox.call(box)\n}\n\nfunction placementInfoFromLoopPlacement(\n placement: LoopSandboxPlacement | undefined,\n box: SandboxInstance,\n): PlacementInfo {\n if (!placement) return { kind: 'sandbox', sandboxId: String(box.id) }\n return {\n // `in-process` runs in the caller's own process tree, which `PlacementInfo` names `local`.\n kind:\n placement.kind === 'fleet' ? 'fleet' : placement.kind === 'in-process' ? 'local' : 'sandbox',\n ...(placement.sandboxId ? { sandboxId: placement.sandboxId } : { sandboxId: String(box.id) }),\n ...(placement.fleetId ? { fleetId: placement.fleetId } : {}),\n ...(placement.machineId ? { machineId: placement.machineId } : {}),\n }\n}\n\nfunction defaultTangleSandboxCapabilities(options: {\n namedProfiles: boolean\n}): AgentEnvironmentCapabilities {\n return {\n profile: {\n namedProfiles: options.namedProfiles,\n systemPrompt: { ...harnessSystemPromptIntents(undefined) },\n instructions: true,\n tools: true,\n permissions: true,\n mcp: true,\n subagents: true,\n resources: {\n files: true,\n instructions: true,\n tools: true,\n skills: true,\n agents: true,\n commands: true,\n },\n hooks: true,\n modes: true,\n runtimeUpdate: true,\n validation: true,\n },\n streaming: { live: true, replay: true, detach: true, turnIdempotency: true },\n sessions: { continue: true, list: true, messages: true },\n workspace: { read: true, write: true, exec: true, git: true, upload: true, download: true },\n branching: { checkpoint: true, fork: true },\n placement: true,\n usage: true,\n confidential: true,\n }\n}\n\nfunction contentRef(prefix: string, value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n let hash = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n hash ^= str.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return `${prefix}:${(hash >>> 0).toString(16).padStart(8, '0')}`\n}\n\nfunction hasGet(\n client: SandboxClient,\n): client is SandboxClient & { get(id: string): Promise<SandboxInstance | null> } {\n return typeof (client as { get?: unknown }).get === 'function'\n}\n\nfunction hasList(\n client: SandboxClient,\n): client is SandboxClient & { list(options?: unknown): Promise<SandboxInstance[]> } {\n return typeof (client as { list?: unknown }).list === 'function'\n}\n\nfunction hasDispatchPrompt(box: SandboxInstance): box is SandboxInstance & {\n dispatchPrompt(message: string | PromptInputPart[], options?: PromptOptions): Promise<unknown>\n} {\n return typeof (box as { dispatchPrompt?: unknown }).dispatchPrompt === 'function'\n}\n\nfunction hasSession(\n box: SandboxInstance,\n): box is SandboxInstance & { session(id: string): SandboxSessionLike } {\n return typeof (box as { session?: unknown }).session === 'function'\n}\n\nfunction hasRead(box: SandboxInstance): box is SandboxInstance & {\n read(path: string, options?: { sessionId?: string }): Promise<string>\n} {\n return typeof (box as { read?: unknown }).read === 'function'\n}\n\nfunction hasWrite(\n box: SandboxInstance,\n): box is SandboxInstance & { write(path: string, content: string): Promise<void> } {\n return typeof (box as { write?: unknown }).write === 'function'\n}\n\nfunction hasExec(box: SandboxInstance): box is SandboxInstance & {\n exec(command: string, options?: unknown): Promise<SandboxExecResult>\n} {\n return typeof (box as { exec?: unknown }).exec === 'function'\n}\n\ninterface SandboxSessionLike {\n readonly id: string\n readonly controlRef?: AgentRunControlRef\n status(): Promise<unknown | null>\n events(options?: {\n since?: string\n executionId?: string\n signal?: AbortSignal\n }): AsyncIterable<SandboxEvent>\n result(options?: { executionId?: string }): Promise<PromptResult>\n prompt(message: string | PromptInputPart[], options?: PromptOptions): Promise<PromptResult>\n respondToInteraction?(\n command: InteractionResponseCommand,\n options?: { signal?: AbortSignal },\n ): Promise<{ acknowledgement: InteractionAcknowledgement }>\n cancelRun?(\n request: AgentRunCancellationRequest,\n options?: { signal?: AbortSignal },\n ): Promise<AgentRunCancellationAcknowledgement>\n interrupt(options?: { executionId?: string }): Promise<unknown>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,YAAY,QAAqB,UAA2B;CAC1E,MAAM,SAAS,OAAO;CACtB,IAAI,OAAO,WAAW,YAAY,OAAO,SAAS,GAAG,OAAO;CAI5D,IAAI,kBAAkB,SAAS,OAAO,SAAS,gBAAgB,OAAO,QAAQ,SAAS,GACrF,OAAO,OAAO;CAEhB,OAAO;AACT;;AAGA,SAAgB,WAAW,QAAqB,UAAyB;CACvE,MAAM,SAAS,YAAY,QAAQ,QAAQ;CAC3C,MAAM,QAAQ,IAAI,MAAM,OAAO,WAAW,YAAY,OAAO,SAAS,IAAI,SAAS,QAAQ;CAC3F,MAAM,OAAO;CACb,OAAO;AACT;;;;;;;;AAmBA,SAAgB,UAAU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ervise/graph.ts"],"sourcesContent":["/**\n *\n * `runGraph` — agent graphs: profiles as nodes, registry-backed prompt directives as edges.\n *\n * A topology is PLAIN DATA an agent can author in a few lines: nodes are canonical\n * `AgentProfile`s (the ONLY way a node is described — no role-builder functions), edges are typed\n * values carrying versioned {@link PromptHandle} directives, `deliverable` (termination) and\n * `budget` (one conserved pool) are mandatory. Driver↔worker is the two-node cyclic instance;\n * \"agent 3 analyzes 1 and 2 and reports to 1\" is ONE edge, not a framework.\n *\n * NOT A SECOND SCHEDULER. `runGraph` is an interpretation layer over what already runs:\n * `supervise()` is the execution core — the same `supervisorAgent`/`driverAgent` machinery,\n * backend-derived worker path (authorized, classified, recursive), conserved-pool budget, and\n * deliverable-gated settlement every\n * supervised run uses. (`runAgentRounds` is deliberately NOT the substrate here.) What the graph\n * layer ADDS is exactly what a bespoke driver loop never\n * had:\n *\n * 1. **Node pinning** — a spawn names a node (`profile.name` = node id) and the node's canonical\n * profile is what runs; a driver cannot smuggle capabilities into a worker it did not define.\n * 2. **Observable edges** — every delegates/analyzes traversal lands in an EDGE LEDGER\n * (`delivered | stripped | empty | unpropagated`, with byte counts), in memory on\n * the result AND as `edge` events in the run journal. The motivating incident: a filter\n * silently replaced 1,700-char steering with 241 chars of boilerplate for three rounds and\n * NO artifact said so — an unobservable edge cannot be trusted and its directive cannot be\n * optimized.\n * 3. **Directives as data** — edge text lives in the prompt registry (`<surface>/v<n>`), so every\n * edge is a versioned optimization target, never prose hardcoded in a builder function.\n * 4. **Per-edge traversal caps** — the cyclic-graph backstop. A delegates edge whose cap is\n * exhausted REFUSES further traversals (fail loud), so a cycle cannot spin the pool dry.\n * 5. **Continuity as data** — a delegates edge may declare `continuity: 'resume'`, so each spawn\n * after the node's first re-attaches to its latest SETTLED session (the spawn context hands\n * the executor seam `resume: { ofWorker, sequence }`; the kernel keeps identity, ordering,\n * ledger truth, and the one conserved pool). Every ledger row states how its hop continued:\n * `'fresh' | 'resume'` for spawns, `'steer'` for mid-run deliveries — fresh respawns, session\n * resumes, and live steers are all plain data, each a ledgered fact.\n *\n * ORACLES ARE ENVIRONMENT, NEVER WORKERS. Graders/verifiers must not be spawnable in the graph —\n * a delegates edge to them leaks the rubric. An `analyzes` edge names its analyst in one of two\n * forms: a LENS id from the environment's registry (a pure function over trace evidence), or the\n * id of a graph NODE — a tool-equipped analyst AGENT spawned on each matching settle with the\n * node's pinned profile, whose settle output IS the findings. Either way the oracle doctrine\n * holds: an analyst node can never be a delegates target (refused loudly), so no driver can hand\n * it work, and an id living in both the registry and the nodes is refused as ambiguous.\n *\n * @experimental\n */\n\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport type {\n AnalystRegistry,\n AnalyzeOnSettleRoute,\n ContinuityMode,\n CoordinationEvent,\n MakeWorkerAgent,\n} from '../../mcp/tools/coordination'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { harnessRunsAgent } from '../harness-role'\nimport type { ToolLoopChat } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport {\n formatPromptHandle,\n kernelPromptRegistry,\n type PromptHandle,\n type PromptRegistry,\n} from './prompt-registry'\nimport { type SuperviseOptions, supervise, superviseWithTestBrain } from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\n\n// ── The algebra ────────────────────────────────────────────────────────────────\n\n/** A graph node: an id and a canonical `AgentProfile`. The profile is the ONLY way a node is\n * described — its `prompt.systemPrompt` is the standing role (the 0.117 canonical resolution;\n * never a legacy top-level-only reduction), its tools/mcp/resources are its capabilities. */\nexport interface GraphNode {\n readonly id: NodeId\n readonly profile: AgentProfile\n}\n\nexport type GraphEdge =\n /** Work flows down. The delegation directive is DATA → versionable, sweepable, optimizable.\n * Each spawn of `to` by `from` — and each mid-run steer from `from` to a live `to` worker —\n * is one traversal. */\n | {\n readonly kind: 'delegates'\n readonly from: NodeId\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Cyclic-graph backstop: traversals beyond this REFUSE (fail loud). Default\n * {@link defaultEdgeTraversalCap}. */\n readonly maxTraversals?: number\n /** Default continuity for this edge's SPAWN traversals. `'resume'` makes every spawn after\n * the node's first re-attach to its most recent SETTLED worker: a NEW live worker whose\n * spawn context carries `resume: { ofWorker, sequence }` for the executor seam, spending\n * from the same conserved pool — the node's first spawn is effectively `'fresh'`, and a\n * spawn while a prior worker is still live refuses loudly (steer is the live channel).\n * The driver's per-call `spawn_agent` `continuity` argument overrides either way. Omit =\n * `'fresh'` (today's behavior, byte-identical). Caps count resumes exactly like fresh\n * spawns. */\n readonly continuity?: ContinuityMode\n }\n /** Findings flow anywhere: an analyst over N nodes' settled traces, delivered to ONE node.\n * With a LENS analyst the directive wraps the findings for the recipient; with a NODE analyst\n * the directive is the analyst agent's task and the findings are its settle output. */\n | {\n readonly kind: 'analyzes'\n /** The analyst REFERENCE, in one of two forms: a lens id resolved against\n * `RunGraphOptions.analysts` (environment), or the id of a graph NODE with no delegates\n * edge pointing at it — then each matching settle spawns that node's pinned profile as a\n * tool-equipped analyst WORKER (same spawn machinery, conserved budget, trace join) whose\n * task is this edge's directive plus the settled worker's trace evidence and whose settle\n * output is the findings. An id that is both a node and a registry lens is refused. */\n readonly analyst: string\n readonly over: ReadonlyArray<NodeId>\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Observability cap: traversals beyond this are LEDGERED as exhausted (`unpropagated`).\n * Only delegates caps refuse traversal — they are what close the spawn cycle. */\n readonly maxTraversals?: number\n }\n\nexport interface AgentGraph {\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n /** Termination is mandatory, not optional: the independent completion oracle. */\n readonly deliverable: DeliverableSpec<unknown>\n /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated'\n\n/** How one ledgered hop CONTINUED: a spawn traversal stamps its effective spawn mode\n * (`'fresh'` | `'resume'`), and every mid-run delivery into an already-live recipient — a\n * driver steer leg and every analyzes delivery (routed steer or driver-destined finding) —\n * stamps `'steer'`. Zero ambiguity: every row carries exactly one of the three. */\nexport type TraversalContinuity = ContinuityMode | 'steer'\n\n/** One recorded edge traversal — the in-memory row; the journal twin is the `edge` SpawnEvent. */\nexport interface EdgeTraversal {\n /** Stable edge id: `delegates:<from>-><to>` or `analyzes:<analyst>:<over…>-><to>`. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes'\n readonly from: string\n readonly to: string\n /** The resolved directive reference (`<surface>/v<n>`). */\n readonly directive: string\n /** 1-based per-edge ordinal. */\n readonly traversal: number\n readonly outcome: EdgeDeliveryOutcome\n /** How this hop continued — see {@link TraversalContinuity}. */\n readonly continuity: TraversalContinuity\n /** Bytes of directive + payload that actually crossed the edge. */\n readonly bytes: number\n readonly reason?: string\n /** The concrete worker node id, once known. */\n readonly workerId?: string\n}\n\n/** Default per-edge traversal cap — the cyclic-graph backstop when an edge names none. */\nexport const defaultEdgeTraversalCap = 32\n\n/** A delegates edge exhausted its traversal cap and the run produced no winner: the cap, not the\n * task, ended it. Carries the full evidence so failing loud loses nothing. */\nexport class GraphEdgeCapError extends Error {\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly ledger: ReadonlyArray<EdgeTraversal>\n readonly result: SupervisedResult<unknown>\n constructor(\n exhaustedEdges: ReadonlyArray<string>,\n ledger: ReadonlyArray<EdgeTraversal>,\n result: SupervisedResult<unknown>,\n ) {\n super(\n `runGraph: edge traversal cap exhausted on ${exhaustedEdges.join(', ')} and the run ` +\n 'delivered no winner — the cap (the cyclic-graph backstop), not the task, ended this run. ' +\n 'Raise maxTraversals on the edge or fix the cycle; the full edge ledger and the ' +\n 'supervised result ride on this error.',\n )\n this.name = 'GraphEdgeCapError'\n this.exhaustedEdges = exhaustedEdges\n this.ledger = ledger\n this.result = result\n }\n}\n\n// ── Options / result ───────────────────────────────────────────────────────────\n\n/**\n * Every `SuperviseOptions` key, partitioned by what `runGraph` does with it.\n *\n * `runGraph` starts one `supervise()` run, so every option that run honors is a graph option too\n * unless the graph itself owns the value. This used to be an opt-in list written by hand, and the\n * hand lost: 25 of 49 keys never reached `supervise()` from a graph, including `childSettleGraceMs`\n * (a root-driver failure tore down children that had ALREADY computed the deliverable) and\n * `driverRetry` (agent-runtime#963). Each absence was discovered by losing a run.\n *\n * The four lists below must cover `keyof SuperviseOptions` exactly. `everySuperviseOptionIsClassified`\n * below fails to COMPILE, naming the offender, when a key belongs to none of them — so the next\n * option added to `supervise()` cannot go missing here silently. It has to be classified, and\n * classifying it as forwarded is one word.\n */\n\n/** The graph derives these from the `AgentGraph` itself; a caller value would be overwritten. */\nconst GRAPH_OWNED_SUPERVISE_OPTIONS = [\n 'rootDriverFromBackend',\n 'resolveSpawnProfile',\n 'budget',\n 'deliverable',\n 'makeWorkerAgent',\n 'onCoordinationEvent',\n 'analyzeOnSettle',\n 'continuityByProfile',\n] as const\n\n/** Caller-facing on `RunGraphOptions`, but the graph wraps or defaults the value before it goes in:\n * `hooks` composes with the graph's own spawn-binding hook, `authorizeMessage` is wrapped so a\n * narrowed instruction ledgers `stripped`, `authorizeSpawn` runs AFTER the graph has pinned the\n * node (so a product sees the canonical profile, never the driver's stub), `makeLeafAgent` is the\n * caller's leaf override slotted under the graph's pinning, `analysts` rides only with analyze\n * routes, and `journal`/`blobs`/`runId` get graph defaults. */\nconst GRAPH_TRANSFORMED_SUPERVISE_OPTIONS = [\n 'hooks',\n 'authorizeMessage',\n 'authorizeSpawn',\n 'makeLeafAgent',\n 'analysts',\n 'journal',\n 'blobs',\n 'runId',\n] as const\n\n/** Not reachable from a graph, with the reason. `registry` is a NAME COLLISION, not a policy:\n * `RunGraphOptions.registry` is the directive `PromptRegistry` and `SuperviseOptions.registry` is\n * the `SuperviseRegistry` name→value table. Two different types under one name; the graph's wins.\n * Giving the supervise one a graph channel means renaming a public option, so it is recorded here\n * rather than silently dropped. */\nconst GRAPH_REFUSED_SUPERVISE_OPTIONS = ['registry'] as const\n\n/**\n * Forwarded to the root `supervise()` VERBATIM. Everything not owned, transformed, or refused\n * above belongs here — the default is \"a graph honors it\", not \"someone remembered to add it\".\n */\nconst GRAPH_FORWARDED_SUPERVISE_OPTIONS = [\n 'backend',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'isDriverProfile',\n 'router',\n 'driveHarness',\n 'driverRetry',\n 'onDriverAttempt',\n 'childSettleGraceMs',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'extraTools',\n 'executeExtraTool',\n 'perWorker',\n 'maxLiveWorkers',\n 'watchWorkers',\n 'stallAfterMs',\n 'runDir',\n 'probes',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\n] as const\n\ntype ClassifiedSuperviseOption =\n | (typeof GRAPH_OWNED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_TRANSFORMED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_REFUSED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]\n\n/** A `SuperviseOptions` key in none of the four lists makes this assignment fail, and the compiler\n * error names the key. Classify it — `GRAPH_FORWARDED_SUPERVISE_OPTIONS` is usually the answer. */\ntype UnclassifiedSuperviseOption = Exclude<keyof SuperviseOptions, ClassifiedSuperviseOption>\nconst everySuperviseOptionIsClassified: UnclassifiedSuperviseOption extends never\n ? true\n : UnclassifiedSuperviseOption = true\nvoid everySuperviseOptionIsClassified\n\n/** Copy every forwarded option the caller actually set. Absent stays absent: `supervise()` and the\n * graph must not disagree about what \"unset\" means. */\nfunction forwardedSuperviseOptions(\n opts: RunGraphOptions,\n): Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n const forwarded: Record<string, unknown> = {}\n for (const key of GRAPH_FORWARDED_SUPERVISE_OPTIONS) {\n const value = (opts as Record<string, unknown>)[key]\n if (value !== undefined) forwarded[key] = value\n }\n return forwarded as Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]>\n}\n\n/**\n * Options for one `runGraph` run.\n *\n * Extends every forwarded `SuperviseOptions` key, so a graph honors what a `supervise()` run\n * honors WITHOUT anyone restating it here. Only the graph-specific members and the ones whose\n * graph semantics differ are declared below; everything else inherits its type AND its\n * documentation from `SuperviseOptions`, which is the one owner of both.\n */\nexport interface RunGraphOptions\n extends Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n /** WHERE worker nodes run — the executor backend. Provide this OR `makeLeafAgent`. Forwarded to\n * `supervise()`, which derives every authorized LEAF from it; a node declared `role: 'driver'`\n * becomes a nested supervisor instead, whose own leaves are derived the same way. */\n readonly backend?: SuperviseOptions['backend']\n /** WHERE the ROOT node's harness brain runs — forwarded to `supervise()` verbatim (see\n * `SuperviseOptions.driverBackend`). Needed when the root node's profile declares an external\n * harness (`codex`, `claude-code`, `opencode`): that root is driven by the harness, not by the\n * router brain, and automatic execution supports a local `bridge`. Unlike `supervise()`, this\n * does NOT default to `backend`: a graph's `backend` places WORKER nodes, so the root driver\n * is selected only by this field. Omit = no harness driver, which is correct for a root whose\n * `profile.harness` is omitted or `cli-base` (that root runs on the router brain). */\n readonly driverBackend?: SuperviseOptions['driverBackend']\n /** Leaf-execution override (offline tests / advanced). `runGraph` still owns node pinning,\n * directive delivery, and the edge ledger AROUND this seam — only the leaf `act` is yours.\n * Slots INSIDE the kernel's authorized path (`SuperviseOptions.makeLeafAgent`), so a node\n * declared `role: 'driver'` still becomes a nested supervisor even under an offline leaf. */\n readonly makeLeafAgent?: MakeWorkerAgent\n /** The ROOT driver's inference seam — a caller-owned `ToolLoopChat` that makes every root\n * model call. Use it when the root's decisions must be caller-owned orchestration (a\n * deterministic conversation driver, a persona loop with its own LLM calls) rather than a\n * router-derived model call. The graph machinery around the seam is unchanged: node pinning,\n * directive delivery, the edge ledger, and the journal twin all run the same shipped path,\n * and the root profile keeps prompt control (`prompt-control-execution` materialization —\n * `systemPrompt`/`instructions` still apply). What moves to the caller with the brain:\n * model selection and provider-identity validation (`expectedModel` cannot be enforced on a\n * call the runtime did not place) and per-turn usage reporting (a brain that reports no\n * usage meters nothing into the pool). Omit = the router brain derived from the root\n * profile — the unchanged default. Mutually exclusive with `driverBackend`, and refused\n * when the root profile declares an external harness (that root is driven BY the harness). */\n readonly brain?: ToolLoopChat\n /** Caller-side runtime hooks (telemetry, policy, product extensions). Composed AFTER the\n * graph's own spawn-binding hook on the SAME event stream — the graph never swallows the\n * seam supervise() exposes. */\n readonly hooks?: RuntimeHooks\n /** The analyst lens registry `analyzes` edges resolve against. ENVIRONMENT — needed only for\n * lens analysts; an analyzes edge naming a graph NODE as its analyst needs no registry. */\n readonly analysts?: AnalystRegistry\n /** Directive registry. Default: the seeded kernel registry (`kernelPromptRegistry()`).\n *\n * NOT `SuperviseOptions.registry`, which is the `SuperviseRegistry` name→value table for\n * code-valued options. The two share a name and nothing else, and this one wins here — see\n * `GRAPH_REFUSED_SUPERVISE_OPTIONS`. */\n readonly registry?: PromptRegistry\n /** The run journal the edge ledger and every spawn/settle ride. Default: in-memory. */\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly runId?: string\n /** Product authority over every steer/answer instruction (the filter seam). `runGraph` observes\n * what it CHANGES: a narrowed instruction ledgers its steer traversal as `stripped`. */\n readonly authorizeMessage?: SuperviseOptions['authorizeMessage']\n}\n\nexport interface GraphResult<Out = unknown> {\n readonly result: SupervisedResult<Out>\n /** Every edge traversal, in occurrence order — the observable-edge contract. */\n readonly ledger: ReadonlyArray<EdgeTraversal>\n /** Edge ids whose traversal cap was hit — analyzes exhaustion included (observable here, never\n * a refusal). A DELEGATES cap paired with a `no-winner` result THROWS\n * ({@link GraphEdgeCapError}) instead of returning: only delegates caps refuse spawns, so only\n * they can have ended the run. A LIFECYCLE no-winner (`aborted` / `budget-exhausted`) returns\n * normally even with an exhausted delegates cap — the abort or the pool, not the cap, ended\n * that run, and the exhaustion stays observable here. */\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly runId: string\n}\n\n/** `RunGraphOptions` with the brain REQUIRED — the shape the `/testing` entry's\n * `runGraphWithTestBrain` keeps accepting now that `brain` is a production option. */\nexport interface RunGraphTestOptions extends RunGraphOptions {\n readonly brain: ToolLoopChat\n}\n\n// ── Validation ─────────────────────────────────────────────────────────────────\n\ninterface ValidatedGraph {\n readonly root: GraphNode\n readonly workers: ReadonlyMap<NodeId, GraphNode>\n readonly delegatesByWorker: ReadonlyMap<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>\n readonly analyzes: ReadonlyArray<Extract<GraphEdge, { kind: 'analyzes' }>>\n /** Nodes referenced as an analyzes edge's ANALYST (the analyst-agent form): reachable through\n * their analyzes edge (spawned on settle), never through a delegates edge. */\n readonly analystNodes: ReadonlyMap<NodeId, GraphNode>\n}\n\nfunction edgeId(edge: GraphEdge): string {\n return edge.kind === 'delegates'\n ? `delegates:${edge.from}->${edge.to}`\n : `analyzes:${edge.analyst}:${edge.over.join('+')}->${edge.to}`\n}\n\n/** Validate the graph and resolve every directive BEFORE any compute is spent — an invalid\n * topology or an unknown directive is a configuration fault, never a mid-run surprise. */\nfunction validateGraph(\n graph: AgentGraph,\n registry: PromptRegistry,\n analysts: AnalystRegistry | undefined,\n): ValidatedGraph {\n if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {\n throw new ValidationError('runGraph: graph.nodes must be a non-empty array')\n }\n if (!Array.isArray(graph.edges) || graph.edges.length === 0) {\n throw new ValidationError('runGraph: graph.edges must be a non-empty array')\n }\n if (typeof graph.deliverable?.check !== 'function') {\n throw new ValidationError('runGraph: graph.deliverable is mandatory (termination oracle)')\n }\n if (typeof graph.budget !== 'object' || graph.budget === null) {\n throw new ValidationError('runGraph: graph.budget is mandatory (the conserved pool)')\n }\n const byId = new Map<NodeId, GraphNode>()\n for (const node of graph.nodes) {\n if (typeof node.id !== 'string' || node.id.length === 0) {\n throw new ValidationError('runGraph: every node needs a non-empty string id')\n }\n if (byId.has(node.id)) throw new ValidationError(`runGraph: duplicate node id '${node.id}'`)\n const parsed = agentProfileSchema.safeParse(node.profile)\n if (!parsed.success) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has an invalid AgentProfile: ${parsed.error.message}`,\n )\n }\n // The profile NAME is the node identity everywhere downstream: node pinning resolves a\n // spawn's `profile.name` against node ids, and the coordination layer matches analyst\n // routes (`over`/`to`) against the settled worker's PROFILE NAME. A divergent name would\n // make every analyzes edge touching this node silently never match — refuse it up front.\n if (node.profile.name !== node.id) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has profile.name ${JSON.stringify(node.profile.name)} — ` +\n 'profile.name IS the node identity (node pinning and analyst routing match on it) and ' +\n 'must equal the node id',\n )\n }\n byId.set(node.id, node)\n }\n const requireNode = (id: NodeId, where: string): GraphNode => {\n const node = byId.get(id)\n if (!node) throw new ValidationError(`runGraph: ${where} references unknown node '${id}'`)\n return node\n }\n const delegates = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'delegates' }> => edge.kind === 'delegates',\n )\n const analyzes = graph.edges.filter(\n (edge): edge is Extract<GraphEdge, { kind: 'analyzes' }> => edge.kind === 'analyzes',\n )\n if (delegates.length === 0) {\n throw new ValidationError('runGraph: at least one delegates edge is required (who spawns whom)')\n }\n for (const edge of graph.edges) registry.resolve(edge.directive)\n for (const edge of delegates) {\n requireNode(edge.from, edgeId(edge))\n requireNode(edge.to, edgeId(edge))\n if (edge.from === edge.to) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates to itself — the driver↔worker cycle is the ` +\n 'settle-return loop, not a self-edge',\n )\n }\n // The type admits only 'fresh' | 'resume', but a graph is plain data that often arrives\n // through JSON — refuse a nonsense mode here, never let it reach the spawn tool as a string.\n if (\n edge.continuity !== undefined &&\n edge.continuity !== 'fresh' &&\n edge.continuity !== 'resume'\n ) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} has invalid continuity ${JSON.stringify(edge.continuity)} — ` +\n \"a delegates edge's continuity is 'fresh' or 'resume'\",\n )\n }\n }\n // Root: the one node that delegates and is never delegated TO. P0 executes the star/2-node\n // cyclic family (one driver, N workers); nested driver graphs are the recorded P3 absorption.\n const delegatedTo = new Set(delegates.map((edge) => edge.to))\n const roots = [...new Set(delegates.map((edge) => edge.from))].filter(\n (id) => !delegatedTo.has(id),\n )\n if (roots.length !== 1) {\n throw new ValidationError(\n `runGraph: expected exactly ONE root (a node that delegates and is never delegated to), ` +\n `found ${roots.length === 0 ? 'none — delegates edges form a cycle with no entry' : roots.join(', ')}. ` +\n 'P0 executes driver↔worker(s); nested driver graphs are P3.',\n )\n }\n const root = requireNode(roots[0] as string, 'root resolution')\n for (const edge of delegates) {\n if (edge.from !== root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} delegates from a non-root node — P0 executes one driver over ` +\n 'its workers (the 2-node cyclic case, star-generalized); deeper delegation is P3',\n )\n }\n }\n const analystIds = new Set<string>()\n const analystNodes = new Map<NodeId, GraphNode>()\n for (const edge of analyzes) {\n // Continuity is a delegates-edge axis ONLY: analysts (lens or node) are spawned by the\n // analyst-on-settle machinery, each run a fresh session over settled evidence — an analyzes\n // edge carrying continuity would silently mean nothing, so it is refused as data.\n if ((edge as { continuity?: unknown }).continuity !== undefined) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} carries continuity — analysts are spawned by the analyst ` +\n 'machinery (every analyst run is a fresh session over settled evidence), so ' +\n 'continuity is a delegates-edge axis only',\n )\n }\n // The runner's traversal ledger resolves a finding/steer back to its edge BY ANALYST ID\n // alone, so a second edge sharing an analyst would silently absorb the first edge's\n // traversals (last-registered wins). Multi-edge-per-analyst is not yet supported; refuse it\n // rather than mis-ledger it.\n if (analystIds.has(edge.analyst)) {\n throw new ValidationError(\n `runGraph: two analyzes edges share analyst '${edge.analyst}' — one analyzes edge per ` +\n 'analyst lens (traversals are ledgered by analyst id; a second edge would silently ' +\n \"absorb the first's). Register the lens under a second id for a second edge.\",\n )\n }\n analystIds.add(edge.analyst)\n // The analyst REFERENCE has two forms — a registry lens id or a graph node id — and the id\n // itself is what distinguishes them, so an id living in both is refused as ambiguous rather\n // than silently resolved by precedence.\n const analystNode = byId.get(edge.analyst)\n const inRegistry = analysts?.kinds.some((kind) => kind.id === edge.analyst) === true\n if (analystNode !== undefined && inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is BOTH a graph node and a lens in ` +\n 'the analysts registry — the id alone distinguishes the two analyst forms, so this is ' +\n 'ambiguous; rename the node or register the lens under another id',\n )\n }\n if (analystNode !== undefined) {\n // The analyst-AGENT form. Oracle doctrine holds structurally: the analyst node can never\n // receive work — not from the root (a delegates edge to it is refused) and not by being\n // the root (the root delegates by definition).\n if (analystNode.id === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names the ROOT as its analyst — the root is the driver; ` +\n 'give the analyst its own node with no delegates edge pointing at it',\n )\n }\n if (delegatedTo.has(analystNode.id)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} names node '${edge.analyst}' as its analyst, but that node ` +\n 'is a delegates target — oracle doctrine: an analyst is never delegated to. An ' +\n 'analyst NODE is legal only with NO delegates edge pointing at it; give the analyst ' +\n 'its own delegates-free node or pass a lens id from RunGraphOptions.analysts.',\n )\n }\n analystNodes.set(analystNode.id, analystNode)\n } else if (!analysts) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is not a graph node, and no ` +\n 'RunGraphOptions.analysts registry was provided to resolve it as a lens',\n )\n } else if (!inRegistry) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyst '${edge.analyst}' is neither a graph node nor in the ` +\n `analysts registry (known lenses: ${analysts.kinds.map((kind) => kind.id).join(', ') || 'none'})`,\n )\n }\n if (edge.over.length === 0) {\n throw new ValidationError(`runGraph: ${edgeId(edge)} must analyze at least one node`)\n }\n for (const over of edge.over) {\n requireNode(over, edgeId(edge))\n // Analysts observe SETTLED WORKERS, matched by profile name — the root drives and never\n // settles as a worker, so an edge over the root would silently never fire; refuse it.\n if (over === root.id) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes the ROOT — analysts observe settled workers, and ` +\n 'the root never settles as one, so this edge would silently never fire; list ' +\n 'delegates-target nodes only',\n )\n }\n }\n requireNode(edge.to, edgeId(edge))\n }\n // Second pass, once every analyst NODE is known: an analyst run's settlement is a FINDING,\n // never a worker settle, so an analyzes edge OVER an analyst node would silently never fire —\n // refuse it rather than let it rot unobserved.\n for (const edge of analyzes) {\n for (const over of edge.over) {\n if (analystNodes.has(over)) {\n throw new ValidationError(\n `runGraph: ${edgeId(edge)} analyzes '${over}', which is an analyst node — an analyst ` +\n 'run settles as a finding, never as a worker, so this edge would silently never ' +\n 'fire; analyst nodes are not analyzable',\n )\n }\n }\n }\n const workers = new Map<NodeId, GraphNode>()\n const delegatesByWorker = new Map<NodeId, Extract<GraphEdge, { kind: 'delegates' }>>()\n for (const edge of delegates) {\n if (delegatesByWorker.has(edge.to)) {\n throw new ValidationError(\n `runGraph: node '${edge.to}' is the target of two delegates edges — one delegation ` +\n 'directive per worker node (version the directive instead of forking the edge)',\n )\n }\n delegatesByWorker.set(edge.to, edge)\n workers.set(edge.to, requireNode(edge.to, edgeId(edge)))\n }\n // Every non-root node must be reachable by SOME edge, or it can never run. A worker node is\n // reached by its delegates edge; an analyst node by its analyzes edge (spawned on settle).\n for (const node of graph.nodes) {\n if (node.id !== root.id && !workers.has(node.id) && !analystNodes.has(node.id)) {\n throw new ValidationError(\n `runGraph: node '${node.id}' has no delegates edge to it — an unreachable node never runs`,\n )\n }\n }\n return { root, workers, delegatesByWorker, analyzes, analystNodes }\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\nconst byteLength = (text: string): number => Buffer.byteLength(text, 'utf8')\n\nfunction stringifyPayload(payload: unknown): string {\n if (typeof payload === 'string') return payload\n try {\n return JSON.stringify(payload) ?? String(payload)\n } catch {\n return String(payload)\n }\n}\n\n/**\n * Execute an {@link AgentGraph}. The root node becomes the supervisor (`supervise()` — the\n * execution core), each worker node is spawnable BY NODE ID (`spawn_agent` with\n * `profile: { name: '<node id>' }`; the node's canonical profile is pinned by the graph), each\n * delegates directive is appended to the worker profile's `prompt.instructions` per traversal,\n * and each analyzes edge becomes an analyst-on-settle route with a real DESTINATION. Every\n * traversal is ledgered and journaled.\n */\nexport function runGraph(graph: AgentGraph, opts: RunGraphOptions): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/** Alias for graph tests written before `RunGraphOptions.brain` was production. The production\n * entry accepts the same shape; this wrapper only keeps the `/testing` import path working. */\nexport function runGraphWithTestBrain(\n graph: AgentGraph,\n opts: RunGraphTestOptions,\n): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/**\n * The graph supervise run, as its own entry: the engine's `run-graph` preset node executes exactly\n * this, so the preset and `runGraph` are the same code path by construction (agent-runtime#982).\n */\n/**\n * Every refusal a graph earns before any compute, in one place: the authoring contract. `runGraph`\n * calls it FIRST so a malformed graph throws synchronously, exactly as it did before the engine\n * preset (agent-runtime#982) moved execution behind a promise.\n */\nexport function assertRunGraphAuthoring(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof validateGraph> {\n const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const { root } = validated\n // A caller brain and a harness driver are two answers to WHO makes the root's calls: refuse the\n // contradiction before any compute, and refuse a harness-driven root outright — the harness IS\n // that root's brain, so a supplied one would be silently ignored downstream.\n if (brain && opts.driverBackend) {\n throw new ValidationError(\n 'runGraph: brain and driverBackend are mutually exclusive — a caller brain makes the root model calls, a driverBackend places a harness that makes its own',\n )\n }\n if (brain && harnessRunsAgent(root.profile.harness)) {\n throw new ValidationError(\n `runGraph: root node '${root.id}' declares harness '${root.profile.harness}', so the harness drives it — a caller brain applies only to a router-brained root (profile.harness omitted or 'cli-base')`,\n )\n }\n if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n return validated\n}\n\nexport function superviseAgentGraph(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n const registry = opts.registry ?? kernelPromptRegistry()\n const { root, workers, delegatesByWorker, analyzes, analystNodes } = assertRunGraphAuthoring(\n graph,\n opts,\n brain,\n )\n const journal = opts.journal ?? new InMemorySpawnJournal()\n const blobs = opts.blobs ?? new InMemoryResultBlobStore()\n const runId =\n opts.runId ??\n `graph-${canonicalCandidateDigest(graph.nodes.map((n) => n.id)).slice('sha256:'.length, 'sha256:'.length + 12)}`\n const now = opts.now ?? Date.now\n\n // ── Ledger state ──\n const ledger: EdgeTraversal[] = []\n const journaled = new Set<EdgeTraversal>()\n const traversalCounts = new Map<string, number>()\n const exhausted = new Set<string>()\n // The subset of `exhausted` that REFUSED work. Only a delegates cap closes the spawn cycle, so\n // only it can be the reason a run ended winnerless — an analyzes cap refuses nothing.\n const exhaustedDelegates = new Set<string>()\n const journalWrites: Promise<void>[] = []\n let ledgerSeq = 0\n const appendJournal = (entry: EdgeTraversal, nodeIdForEvent: string): Promise<void> => {\n if (journaled.has(entry)) return Promise.resolve()\n journaled.add(entry)\n const write = journal.appendEvent(runId, {\n kind: 'edge',\n id: nodeIdForEvent,\n edge: { kind: entry.kind, from: entry.from, to: entry.to, directive: entry.directive },\n traversal: entry.traversal,\n outcome: entry.outcome,\n continuity: entry.continuity,\n bytes: entry.bytes,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n seq: ledgerSeq++,\n at: new Date(now()).toISOString(),\n })\n journalWrites.push(write)\n return write\n }\n const record = (entry: Omit<EdgeTraversal, 'traversal'>, journalNow: boolean): EdgeTraversal => {\n const count = (traversalCounts.get(entry.edge) ?? 0) + 1\n traversalCounts.set(entry.edge, count)\n const row: EdgeTraversal = { ...entry, traversal: count }\n ledger.push(row)\n if (journalNow) void appendJournal(row, row.workerId ?? `graph:${row.to}`)\n return row\n }\n\n // ── Node pinning + delegates spawn traversals (the authorizeSpawn wrapper) ──\n // Pinning lives in `authorizeSpawn`, which the kernel runs BEFORE it decides whether a child is\n // a leaf or a nested supervisor. That is what lets a node declared `role: 'driver'` become a real\n // supervisor carrying its canonical profile: the kernel's `isDriver` reads the PINNED profile,\n // not the driver-authored `{ name }` stub. (It used to live in `makeWorkerAgent`, a leaf-only\n // seam, which made every node a leaf no matter what its profile declared — #965.)\n const nodeByWorkerId = new Map<string, NodeId>()\n const pendingByAssignment = new Map<string, EdgeTraversal>()\n type SpawnAuthorizationInput = Parameters<NonNullable<SuperviseOptions['authorizeSpawn']>>[0]\n const pinNode = (input: SpawnAuthorizationInput): AgentProfile => {\n const requested =\n typeof (input.profile as { name?: unknown } | undefined)?.name === 'string'\n ? (input.profile as { name: string }).name\n : undefined\n // An analyst-AGENT run: the coordination settle hook — never the driver; the marker is\n // authored by the runtime, not accepted from model arguments — spawns the analyst NODE.\n // Pin the node's canonical profile; the analysis directive travels as the TASK (composed by\n // the coordination layer with the settled worker's trace evidence), so nothing is appended\n // to the profile's instructions here. Its traversal is ledgered on the finding/steer it\n // produces, exactly like a registry analyst's.\n if (input.analyst !== undefined) {\n const analystNode = analystNodes.get(input.analyst)\n if (!analystNode || requested !== analystNode.id) {\n throw new ValidationError(\n `runGraph: analyst run for ${JSON.stringify(input.analyst)} does not name an ` +\n `analyst node of this graph (analyst nodes: ${[...analystNodes.keys()].join(', ') || 'none'})`,\n )\n }\n return analystNode.profile\n }\n const node = requested !== undefined ? workers.get(requested) : undefined\n if (!node) {\n throw new ValidationError(\n `runGraph: spawn_agent named profile ${JSON.stringify(requested)} which is not a worker ` +\n `node of this graph (nodes: ${[...workers.keys()].join(', ')}). Spawn by node id: ` +\n 'profile.name selects the node; the node profile itself is pinned by the graph.',\n )\n }\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const id = edgeId(edge)\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(id) ?? 0\n // The EFFECTIVE spawn mode the coordination layer resolved (per-call override, else this\n // edge's declared default, else fresh) — stamped on the row so the ledger states how each\n // hop continued, never how it was merely configured to.\n const spawnContinuity = input.continuity ?? 'fresh'\n if (used >= cap) {\n exhausted.add(id)\n exhaustedDelegates.add(id)\n record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: 'unpropagated',\n continuity: spawnContinuity,\n bytes: 0,\n reason: `traversal-cap-exhausted (max ${cap})`,\n },\n true,\n )\n throw new ValidationError(\n `runGraph: delegates edge ${id} exhausted its traversal cap (${cap}) — the ` +\n 'cyclic-graph backstop refused this spawn',\n )\n }\n const directiveText = registry.resolve(edge.directive).text\n const taskText = stringifyPayload(input.task)\n const bytes = byteLength(directiveText) + byteLength(taskText)\n const row = record(\n {\n edge: id,\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: bytes === 0 ? 'empty' : 'delivered',\n continuity: spawnContinuity,\n bytes,\n ...(bytes === 0 ? { reason: 'no directive text and no task payload' } : {}),\n },\n false,\n )\n pendingByAssignment.set(input.assignmentId, row)\n // The delegation directive is a STANDING instruction of this traversal: appended to the\n // node's canonical prompt instructions, so the worker runs under node profile + edge\n // directive, and the driver-authored profile contributes ONLY the node selection.\n return directiveText.length === 0\n ? node.profile\n : {\n ...node.profile,\n prompt: {\n ...(node.profile.prompt ?? {}),\n instructions: [\n ...((node.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n directiveText,\n ],\n },\n }\n }\n // The pre-journal gate (a bridge backend's route/admission check) must judge the profile that\n // will run, not the `{ name }` stub — otherwise every graph spawn over a bridge is refused\n // `model-route` before the graph ever pins it. This resolver is PURE: it answers \"which node\"\n // without ledgering, because the gate may refuse and nothing may be journaled for a refusal.\n const resolveSpawnProfile = (authored: AgentProfile): AgentProfile => {\n const requested = typeof authored.name === 'string' ? authored.name : undefined\n const node =\n (requested !== undefined ? workers.get(requested) : undefined) ??\n (requested !== undefined ? analystNodes.get(requested) : undefined)\n // Unknown names fall through to authorizeSpawn, which refuses them with the full message and\n // a ledger row; the gate just sees the stub and lets that later refusal speak.\n return node?.profile ?? authored\n }\n // Graph authority first, then the caller's: a product authorizing spawns sees the CANONICAL\n // node profile (what will actually run), never the driver's `{ name }` stub.\n const graphAuthorizeSpawn: NonNullable<SuperviseOptions['authorizeSpawn']> = (input) => {\n const pinned = pinNode(input)\n if (!opts.authorizeSpawn) return { profile: pinned }\n return opts.authorizeSpawn({ ...input, profile: pinned })\n }\n\n // ── Analyzes edges → analyst-on-settle routes with destinations ──\n // A LENS edge's directive wraps the findings for the recipient (so a driver-destined lens\n // route carries no directive — it becomes the driver brief below). A NODE edge's directive is\n // the analyst AGENT's task, so it always rides the route, wherever the findings go.\n const routes: Array<string | AnalyzeOnSettleRoute> = analyzes.map((edge) => {\n const analystNode = analystNodes.get(edge.analyst)\n if (analystNode) {\n return {\n kind: edge.analyst,\n over: edge.over,\n agent: analystNode.profile,\n directive: registry.resolve(edge.directive).text,\n ...(edge.to === root.id ? {} : { to: edge.to }),\n }\n }\n return edge.to === root.id\n ? { kind: edge.analyst, over: edge.over }\n : {\n kind: edge.analyst,\n over: edge.over,\n to: edge.to,\n directive: registry.resolve(edge.directive).text,\n }\n })\n // Driver-destined analyzes findings are standing knowledge for the ROOT: the findings arrive\n // as bus events. For a lens edge the directive tells the driver what to do with them; for a\n // node edge the directive already went to the analyst agent as its task.\n const driverAnalyzesBriefs = analyzes\n .filter((edge) => edge.to === root.id)\n .map((edge) =>\n analystNodes.has(edge.analyst)\n ? `Findings from analyst '${edge.analyst}' (a tool-equipped analyst agent node, over: ` +\n `${edge.over.join(', ')}) will arrive as finding events.`\n : `Findings from analyst '${edge.analyst}' (over: ${edge.over.join(', ')}) will arrive as ` +\n `finding events.\\n${registry.resolve(edge.directive).text}`,\n )\n\n // ── Edge continuity defaults, threaded to the spawn tool by node id (= profile name) ──\n const continuityByProfile: Record<string, ContinuityMode> = {}\n for (const [nodeId, edge] of delegatesByWorker) {\n if (edge.continuity !== undefined) continuityByProfile[nodeId] = edge.continuity\n }\n\n // ── The driver graph brief: which nodes it may spawn, by exact name ──\n const workerLines = [...workers.values()].map((node) => {\n const edge = delegatesByWorker.get(node.id) as Extract<GraphEdge, { kind: 'delegates' }>\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const description =\n typeof node.profile.description === 'string' && node.profile.description.length > 0\n ? ` — ${node.profile.description}`\n : ''\n const continuityNote =\n edge.continuity === 'resume'\n ? \"; continuity: resume — each spawn after the first re-attaches to this node's latest \" +\n 'settled session (spawn again to continue it; steer while it is live)'\n : ''\n return `- '${node.id}'${description} (delegation cap: ${cap} traversals${continuityNote})`\n })\n const graphBrief = [\n 'AGENT GRAPH: you are the driver node of a fixed topology. You may spawn ONLY these worker',\n \"nodes, by EXACT name (spawn_agent with profile: { name: '<node id>' }; the node's full\",\n 'profile is pinned by the graph — any other profile fields you author are ignored):',\n ...workerLines,\n ...(driverAnalyzesBriefs.length > 0 ? ['', ...driverAnalyzesBriefs] : []),\n ].join('\\n')\n const rootProfile: AgentProfile = {\n ...root.profile,\n prompt: {\n ...(root.profile.prompt ?? {}),\n instructions: [\n ...((root.profile.prompt?.instructions as readonly string[] | undefined) ?? []),\n graphBrief,\n ],\n },\n }\n\n // ── Steer + finding observation (delegates steers, analyzes traversals) ──\n // The filter seam: when the caller's authorizeMessage NARROWS an instruction, the delivered\n // bytes differ from the composed bytes — that steer traversal is `stripped` (the VB incident:\n // authored steering silently replaced by boilerplate, byte-indistinguishable downstream).\n const strippedByDigest = new Map<string, { composedBytes: number }>()\n // Always present: the kernel refuses steer/answer whenever spawn authorization is on (the\n // graph's pinning IS spawn authorization), so a graph with no caller filter passes instructions\n // through unchanged rather than losing its steer channel. Only a caller filter can strip.\n const authorizeMessage: NonNullable<SuperviseOptions['authorizeMessage']> = (input) => {\n if (!opts.authorizeMessage) return { instruction: input.instruction }\n const decision = opts.authorizeMessage(input)\n if (decision.instruction !== input.instruction) {\n strippedByDigest.set(canonicalCandidateDigest(decision.instruction), {\n composedBytes: byteLength(input.instruction),\n })\n }\n return decision\n }\n\n const routedAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n const driverAnalyzesByAnalyst = new Map<string, Extract<GraphEdge, { kind: 'analyzes' }>>()\n for (const edge of analyzes) {\n ;(edge.to === root.id ? driverAnalyzesByAnalyst : routedAnalyzesByAnalyst).set(\n edge.analyst,\n edge,\n )\n }\n const analyzesCapReached = (edge: Extract<GraphEdge, { kind: 'analyzes' }>): boolean => {\n const cap = edge.maxTraversals ?? defaultEdgeTraversalCap\n const used = traversalCounts.get(edgeId(edge)) ?? 0\n if (used < cap) return false\n exhausted.add(edgeId(edge))\n return true\n }\n const ledgerAnalyzes = (\n edge: Extract<GraphEdge, { kind: 'analyzes' }>,\n outcome: EdgeDeliveryOutcome,\n bytes: number,\n reason: string | undefined,\n workerId: string | undefined,\n ): void => {\n const capped = analyzesCapReached(edge)\n record(\n {\n edge: edgeId(edge),\n kind: 'analyzes',\n from: edge.over.join('+'),\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: capped ? 'unpropagated' : outcome,\n // Every analyzes traversal is a mid-run delivery into an already-live recipient (a\n // routed steer leg, or the finding reaching the live driver) — never a spawn.\n continuity: 'steer',\n bytes,\n ...(capped\n ? {\n reason: `traversal-cap-exhausted (max ${edge.maxTraversals ?? defaultEdgeTraversalCap})`,\n }\n : reason !== undefined\n ? { reason }\n : {}),\n ...(workerId !== undefined ? { workerId } : {}),\n },\n true,\n )\n }\n\n const onCoordinationEvent = async (\n _context: unknown,\n _eventId: unknown,\n recordEnvelope: { readonly event: CoordinationEvent },\n ): Promise<void> => {\n const event = recordEnvelope.event\n if (event.type === 'finding') {\n // A routed edge's traversal is ledgered on its STEER (the delivery); the finding event is\n // its audit copy. A driver-destined edge's traversal IS the finding reaching the bus.\n const edge = driverAnalyzesByAnalyst.get(event.finding.analyst)\n if (!edge) return\n const sourceNode = nodeByWorkerId.get(event.finding.fromWorker)\n if (sourceNode === undefined || !edge.over.includes(sourceNode)) return\n // Absent findings (the analyst returned `undefined` — the producer omits the key so the\n // event stays digestable) contribute ZERO bytes, never the text \"undefined\".\n const findingsText =\n event.finding.findings === undefined ? '' : stringifyPayload(event.finding.findings)\n const directiveBytes = byteLength(registry.resolve(edge.directive).text)\n const empty = findingsText.length === 0\n ledgerAnalyzes(\n edge,\n empty ? 'empty' : 'delivered',\n directiveBytes + byteLength(findingsText),\n empty ? 'analyst returned no findings' : undefined,\n event.finding.fromWorker,\n )\n return\n }\n if (event.type === 'steer') {\n const down = event.down\n if (event.analyst !== undefined) {\n const edge = routedAnalyzesByAnalyst.get(event.analyst)\n if (!edge) return\n ledgerAnalyzes(\n edge,\n down.delivered ? 'delivered' : 'unpropagated',\n byteLength(down.instruction),\n down.delivered ? undefined : down.outcome,\n down.toWorker,\n )\n return\n }\n // A driver-authored steer to a live worker node is a delegates traversal too — the\n // mid-run leg of the same edge (the leg the motivating incident lost).\n const nodeId = nodeByWorkerId.get(down.toWorker)\n if (nodeId === undefined) return\n const edge = delegatesByWorker.get(nodeId)\n if (!edge) return\n const stripped = strippedByDigest.get(down.instructionDigest)\n record(\n {\n edge: edgeId(edge),\n kind: 'delegates',\n from: edge.from,\n to: edge.to,\n directive: formatPromptHandle(edge.directive),\n outcome: !down.delivered ? 'unpropagated' : stripped ? 'stripped' : 'delivered',\n // The mid-run leg of the edge: a delivery into the LIVE worker, never a spawn.\n continuity: 'steer',\n bytes: byteLength(down.instruction),\n ...(!down.delivered\n ? { reason: down.outcome }\n : stripped\n ? { reason: `authorization narrowed ${stripped.composedBytes} composed bytes` }\n : {}),\n workerId: down.toWorker,\n },\n true,\n )\n }\n }\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks = {\n onEvent: (event: {\n target?: string\n phase?: string\n payload?: unknown\n }): void | Promise<void> => {\n if (event.target !== 'agent.spawn' || event.phase !== 'after') return\n const payload = event.payload as { childId?: unknown; assignmentId?: unknown } | undefined\n if (typeof payload?.childId !== 'string' || typeof payload.assignmentId !== 'string') return\n const pending = pendingByAssignment.get(payload.assignmentId)\n if (!pending) return\n pendingByAssignment.delete(payload.assignmentId)\n const bound: EdgeTraversal = { ...pending, workerId: payload.childId }\n ledger[ledger.indexOf(pending)] = bound\n nodeByWorkerId.set(payload.childId, bound.to)\n return appendJournal(bound, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\n\n // Every configuration fault above throws SYNCHRONOUSLY (matching `supervise()`'s own\n // contract); only the run itself is asynchronous.\n const start = async (): Promise<GraphResult> => {\n const superviseOptions = {\n // Every forwarded option the caller set, including the ones nobody thought to list here.\n // `backend` rides along: the kernel derives every authorized LEAF from it, under the graph's\n // pinning. The root driver stays an explicit `driverBackend` choice: `rootDriverFromBackend:\n // false` stops supervise() defaulting one from the other, so where workers run never selects\n // where the root runs (the axis split every graph caller relies on).\n ...forwardedSuperviseOptions(opts),\n rootDriverFromBackend: false,\n // Graph-owned values come after the spread: the graph, not the caller, decides these.\n budget: graph.budget,\n deliverable: graph.deliverable,\n authorizeSpawn: graphAuthorizeSpawn,\n resolveSpawnProfile,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent,\n // Lens routes resolve against the registry; agent routes carry their own analyst profile,\n // so a graph whose only analysts are nodes needs no registry at all.\n ...(routes.length > 0\n ? { analyzeOnSettle: routes, ...(opts.analysts ? { analysts: opts.analysts } : {}) }\n : {}),\n ...(Object.keys(continuityByProfile).length > 0 ? { continuityByProfile } : {}),\n authorizeMessage,\n } satisfies SuperviseOptions\n const result =\n brain === undefined\n ? await supervise(rootProfile, graphTask(graph, root), superviseOptions)\n : await superviseWithTestBrain(rootProfile, graphTask(graph, root), {\n ...superviseOptions,\n brain,\n })\n\n // A spawn row is PROVISIONAL until the `agent.spawn` hook (fired synchronously once a worker\n // exists) binds it to a live worker id. A row still unbound here means the factory ran but no\n // NEW worker went live: the spawn was refused after the factory (identity conflict, runtime\n // floor) or a keyed re-spawn deduplicated to an already-completed result (prepare() runs the\n // factory, no hook fires). Both state the same truth every unpropagated row states — the\n // directive never reached a live worker — so rewrite rather than mint a new outcome. Then\n // settle every journal write, so the ledger's journal twin is complete when this returns.\n for (const pending of pendingByAssignment.values()) {\n const refused: EdgeTraversal = {\n ...pending,\n outcome: 'unpropagated',\n bytes: 0,\n reason: `no-live-worker-bound (spawn refused after the factory, or a keyed re-spawn deduplicated to a completed result; ${pending.bytes} composed bytes never crossed)`,\n }\n ledger[ledger.indexOf(pending)] = refused\n await appendJournal(refused, `graph:${refused.to}`)\n }\n pendingByAssignment.clear()\n await Promise.all(journalWrites)\n\n const exhaustedEdges = Object.freeze([...exhausted])\n const frozenLedger = Object.freeze(ledger.map((row) => Object.freeze({ ...row })))\n // A LIFECYCLE ending (caller abort, exhausted budget) is its own complete explanation: the\n // cap did not end that run even when it was exhausted along the way, and blaming it would\n // misattribute the ending (and turn a caller-initiated abort into a throw). The exhaustion\n // stays observable in `exhaustedEdges` either way.\n const lifecycleEnded =\n result.kind === 'no-winner' &&\n (result.reason === 'aborted' || result.reason === 'budget-exhausted')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.size > 0) {\n // Fail LOUD: the backstop, not the task, ended this run. The evidence rides on the error.\n // Only DELEGATES caps refuse spawns, so only they can be the cause named here.\n throw new GraphEdgeCapError(Object.freeze([...exhaustedDelegates]), frozenLedger, result)\n }\n return { result, ledger: frozenLedger, exhaustedEdges, runId }\n }\n\n return start()\n}\n\n/** The root task: the graph's own framing. The deliverable (mandatory) is the termination; the\n * task names what the topology exists to produce. */\nfunction graphTask(graph: AgentGraph, root: GraphNode): string {\n const describe = graph.deliverable.describe\n return (\n describe ?? `Deliver the graph's deliverable by driving your worker nodes (root: '${root.id}').`\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwKA,MAAa,0BAA0B;;;AAIvC,IAAa,oBAAb,cAAuC,MAAM;CAC3C;CACA;CACA;CACA,YACE,gBACA,QACA,QACA;EACA,MACE,6CAA6C,eAAe,KAAK,IAAI,EAAE,2NAIzE;EACA,KAAK,OAAO;EACZ,KAAK,iBAAiB;EACtB,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;AACF;;;;;AA2DA,MAAM,oCAAoC;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;AAkBA,SAAS,0BACP,MAC4E;CAC5E,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,OAAO,mCAAmC;EACnD,MAAM,QAAS,KAAiC;EAChD,IAAI,UAAU,KAAA,GAAW,UAAU,OAAO;CAC5C;CACA,OAAO;AACT;AAgGA,SAAS,OAAO,MAAyB;CACvC,OAAO,KAAK,SAAS,cACjB,aA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