@tangle-network/agent-runtime 0.193.1 → 0.194.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-BismttgN.js → activation-BQFIiyUG.js} +3 -3
- package/dist/{activation-BismttgN.js.map → activation-BQFIiyUG.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-BSkZErxD.js → candidate-execution-B6CDW-fp.js} +4 -4
- package/dist/{candidate-execution-BSkZErxD.js.map → candidate-execution-B6CDW-fp.js.map} +1 -1
- package/dist/{conversation-DILnmy84.js → conversation-BXPWMOSd.js} +4 -5
- package/dist/{conversation-DILnmy84.js.map → conversation-BXPWMOSd.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/{coordination-driver-DujHiIGa.js → coordination-driver-iSN-m3VX.js} +281 -244
- package/dist/coordination-driver-iSN-m3VX.js.map +1 -0
- package/dist/{authoring-DWiqKSDY.js → delegate-DCC2muUd.js} +56 -13
- package/dist/delegate-DCC2muUd.js.map +1 -0
- package/dist/delegation-status-BlsbSeOB.js +358 -0
- package/dist/delegation-status-BlsbSeOB.js.map +1 -0
- package/dist/durable.d.ts +2 -2
- package/dist/durable.js +3 -3
- package/dist/{environment-provider-DEwsolvi.js → environment-provider-Dr-wfnHg.js} +422 -8
- package/dist/environment-provider-Dr-wfnHg.js.map +1 -0
- package/dist/{environment-provider-DpPGJfK-.d.ts → environment-provider-adVa6X7a.d.ts} +2 -2
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-DORfp9WX.js → graph-DghidDx5.js} +138 -5
- package/dist/graph-DghidDx5.js.map +1 -0
- package/dist/graph.d.ts +3 -3
- package/dist/graph.js +4 -5
- package/dist/graph.js.map +1 -1
- package/dist/{improve-Bn1zpWHF.d.ts → improve-COGzLCiY.d.ts} +3 -3
- package/dist/{improvement-cycle-BbsiYcpH.js → improvement-cycle-DeS1ZC5B.js} +6 -6
- package/dist/{improvement-cycle-BbsiYcpH.js.map → improvement-cycle-DeS1ZC5B.js.map} +1 -1
- package/dist/{index-DV1lzp9p.d.ts → index-BEPjOPwH.d.ts} +49 -50
- package/dist/{index-Vz-13VZq.d.ts → index-CrBgLCIf.d.ts} +4 -4
- package/dist/{index-RM2oRI9s.d.ts → index-DO6DHgRP.d.ts} +2 -2
- package/dist/index.d.ts +8 -8
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +5 -5
- package/dist/intelligence.js +6 -6
- package/dist/{executable-spec-DxuiDFAU.js → jsonl-file-Bh1Q9nt0.js} +59 -3
- package/dist/jsonl-file-Bh1Q9nt0.js.map +1 -0
- package/dist/kernel.d.ts +6 -6
- package/dist/kernel.js +11 -12
- package/dist/{knowledge-RW1pbZCH.js → knowledge-B5okOzBQ.js} +6 -6
- package/dist/{knowledge-RW1pbZCH.js.map → knowledge-B5okOzBQ.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-CGraqNiA.d.ts → loop-runner-bin-Clc5IAwu.d.ts} +3 -3
- package/dist/{loop-runner-bin-sBwcyQTc.js → loop-runner-bin-U1J6x_UF.js} +3 -3
- package/dist/{loop-runner-bin-sBwcyQTc.js.map → loop-runner-bin-U1J6x_UF.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/{materialization-CekWK6OO.js → materialization-vZssF9Nx.js} +28 -3
- package/dist/materialization-vZssF9Nx.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +4 -4
- package/dist/mcp/index.js +8 -8
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-6jUqkGG7.js → openai-tools-DmvmaG0a.js} +2 -2
- package/dist/{openai-tools-6jUqkGG7.js.map → openai-tools-DmvmaG0a.js.map} +1 -1
- package/dist/{prepare-B5fJ7mLS.js → prepare-C29kNAon.js} +9 -14
- package/dist/prepare-C29kNAon.js.map +1 -0
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{protected-model-port-B0xFSAjt.js → protected-model-port-CKYND416.js} +2 -2
- package/dist/{protected-model-port-B0xFSAjt.js.map → protected-model-port-CKYND416.js.map} +1 -1
- package/dist/{provision-supervisor-CddfH9mg.js → provision-supervisor-CRPbnJiB.js} +6 -8
- package/dist/{provision-supervisor-CddfH9mg.js.map → provision-supervisor-CRPbnJiB.js.map} +1 -1
- package/dist/{redact-D0OzQsyt.js → redact-BOU77QfQ.js} +1013 -24
- package/dist/redact-BOU77QfQ.js.map +1 -0
- package/dist/{researcher-hgPa5p9i.js → researcher-Cp4JRbFp.js} +2 -2
- package/dist/researcher-Cp4JRbFp.js.map +1 -0
- package/dist/{runtime-V91N6sPc.d.ts → runtime-B8x43nGP.d.ts} +5 -4
- package/dist/{runtime-ZM4i-jEF.js → runtime-BVrqSu0-.js} +22 -21
- package/dist/{runtime-ZM4i-jEF.js.map → runtime-BVrqSu0-.js.map} +1 -1
- package/dist/server-D6XmE1Du.js +1311 -0
- package/dist/server-D6XmE1Du.js.map +1 -0
- package/dist/{stream-agent-turn-1ahpdeIo.d.ts → stream-agent-turn-B-gtBlOy.d.ts} +2 -2
- package/dist/{stream-agent-turn-DWWe_7bh.js → stream-agent-turn-DOtEsvCV.js} +3 -3
- package/dist/{stream-agent-turn-DWWe_7bh.js.map → stream-agent-turn-DOtEsvCV.js.map} +1 -1
- package/dist/{structural-rollout-CktnUTCC.js → structural-rollout-BcPXFzVb.js} +16 -43
- package/dist/structural-rollout-BcPXFzVb.js.map +1 -0
- package/dist/{supervise-Dj6zd2C7.js → supervise-C0V3pZXK.js} +154 -1961
- package/dist/supervise-C0V3pZXK.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +13 -13
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{types-CGez_ZHQ.d.ts → types-B_pNTBjK.d.ts} +5 -2
- package/dist/{workspace-archive-yAPDklLV.js → workspace-archive-BCezkeIk.js} +2 -2
- package/dist/{workspace-archive-yAPDklLV.js.map → workspace-archive-BCezkeIk.js.map} +1 -1
- package/package.json +1 -1
- package/skills/codemode/SKILL.md +2 -2
- package/skills/supervise/SKILL.md +24 -6
- package/dist/authoring-DWiqKSDY.js.map +0 -1
- package/dist/coordination-driver-DujHiIGa.js.map +0 -1
- package/dist/environment-provider-DEwsolvi.js.map +0 -1
- package/dist/executable-spec-DxuiDFAU.js.map +0 -1
- package/dist/graph-DORfp9WX.js.map +0 -1
- package/dist/jsonl-file-CDfsCI5s.js +0 -59
- package/dist/jsonl-file-CDfsCI5s.js.map +0 -1
- package/dist/materialization-CekWK6OO.js.map +0 -1
- package/dist/prepare-B5fJ7mLS.js.map +0 -1
- package/dist/redact-D0OzQsyt.js.map +0 -1
- package/dist/researcher-hgPa5p9i.js.map +0 -1
- package/dist/snapshot-CTAf4uuA.js +0 -26
- package/dist/snapshot-CTAf4uuA.js.map +0 -1
- package/dist/spawn-journal-B9eTmVAn.js +0 -999
- package/dist/spawn-journal-B9eTmVAn.js.map +0 -1
- package/dist/structural-rollout-CktnUTCC.js.map +0 -1
- package/dist/supervise-Dj6zd2C7.js.map +0 -1
- package/dist/util-mCNUeboW.js +0 -419
- package/dist/util-mCNUeboW.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"environment-provider-Dr-wfnHg.js","names":["abortError","throwIfAborted"],"sources":["../src/runtime/supervise/abortable.ts","../src/runtime/util.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","/**\n *\n * Internal loop-kernel utilities shared across the kernel, drivers, and the\n * sandbox-acquire layer. Not part of the public barrel surface.\n *\n * @experimental\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { Spend, TokenUsageProvenance } from './supervise/types'\nimport type { LoopTokenUsage } from './types'\n\n/**\n * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);\n * swallows errors (the platform reaps on expiry). Returns `false` when delete\n * threw, `true` otherwise, so callers can surface a leak if they choose.\n */\nexport async function deleteBoxSafe(box: SandboxInstance | undefined): Promise<boolean> {\n if (!box || typeof (box as { delete?: unknown }).delete !== 'function') return true\n try {\n await box.delete()\n return true\n } catch {\n return false\n }\n}\n\n/** Short base36 id for trace correlation. Not cryptographic, not collision-free. */\nexport function randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n\n/** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */\nexport function randomUuid(): string {\n return crypto.randomUUID()\n}\n\n/** Construct an AbortError. Downstream code pattern-matches on `err.name`. */\nexport function abortError(): Error {\n const err = new Error('aborted')\n err.name = 'AbortError'\n return err\n}\n\n/** Throw an AbortError. */\nexport function throwAbort(): never {\n throw abortError()\n}\n\n/** Throw if the signal is already aborted; otherwise no-op. */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortError()\n}\n\n/** True for any error whose `name` is `AbortError` (the cross-kernel abort contract). */\nexport function isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\n/**\n * Sleep that resolves early on abort and always clears its timer so it never\n * keeps the event loop alive. Resolves (does not reject) on abort — callers\n * re-check the signal explicitly after the sleep.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Race a promise against a timeout. Resolves with the value if it settles in\n * time, otherwise resolves with `undefined`. Always clears the timer.\n */\nexport function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n return new Promise<T | undefined>((resolve) => {\n const timer = setTimeout(() => resolve(undefined), ms)\n promise.then(\n (value) => {\n clearTimeout(timer)\n resolve(value)\n },\n () => {\n clearTimeout(timer)\n resolve(undefined)\n },\n )\n })\n}\n\ninterface StringifyOptions {\n /** Pretty-print with 2-space indent. Default false (compact). */\n pretty?: boolean\n /** Truncate to this many chars, appending `…`. Default unbounded. */\n max?: number\n}\n\n/**\n * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).\n * Strings pass through unstringified so a preview of a string output is the\n * string itself, not a quoted re-encoding.\n */\nexport function stringifySafe(value: unknown, opts: StringifyOptions = {}): string {\n let s: string\n try {\n if (typeof value === 'string') {\n s = value\n } else {\n const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)\n s = json ?? String(value)\n }\n } catch {\n s = String(value)\n }\n if (opts.max !== undefined && s.length > opts.max) return `${s.slice(0, opts.max)}…`\n return s\n}\n\n/** A fresh zero token-usage accumulator. */\nexport function zeroTokenUsage(): LoopTokenUsage {\n return { input: 0, output: 0 }\n}\n\n/**\n * Sum the catalog-priced part of a dollar total across spends, as a field to spread.\n *\n * Returns nothing when no input carried one. A fold of pure provider receipts must not gain a\n * `usdEstimated: 0`, which would read as \"this runtime checked and priced none\" on a path that\n * never prices at all.\n */\nexport function usdEstimatedOf(...spends: ReadonlyArray<{ usdEstimated?: number }>): {\n usdEstimated?: number\n} {\n let total = 0\n let priced = false\n for (const spend of spends) {\n if (spend.usdEstimated === undefined) continue\n priced = true\n total += spend.usdEstimated\n }\n return priced ? { usdEstimated: total } : {}\n}\n\n/** A conserved spend with every channel at zero and no completeness claim on it. */\nexport function zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/**\n * The spend of work that HAPPENED and reported no usage receipt.\n *\n * Not the same value as {@link zeroSpend} even though both carry `{0,0}` tokens and `$0`. A bare\n * zero asserts a MEASUREMENT — \"this ran and cost nothing\" — and every consumer downstream reads it\n * that way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay\n * clean, the OTEL span records a priced zero, and a caller's token-denominated ceiling can never\n * fire no matter how much the work really burned. A ceiling that cannot fire is worse than no\n * ceiling, because it reads as protection.\n *\n * `tokensKnown` is the marker the substrate already threads end to end for exactly this case\n * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the\n * zero is labelled a floor rather than a total, and every rollup that touches it reports its\n * balance as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime\n * cannot see what its worker spent.\n *\n * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend\n * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured\n * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.\n */\nexport function unmeteredSpend(ms: number): Spend {\n return {\n iterations: 0,\n tokens: zeroTokenUsage(),\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n }\n}\n\n/** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */\nexport function cloneSpend(spend: Spend): Spend {\n return {\n iterations: spend.iterations,\n tokens: cloneTokenUsage(spend.tokens),\n ...(spend.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: spend.usd,\n ...(spend.usdKnown === false ? { usdKnown: false } : {}),\n ...(spend.usdEstimated !== undefined ? { usdEstimated: spend.usdEstimated } : {}),\n ms: spend.ms,\n ...boxMinutesOf(spend),\n }\n}\n\n/**\n * Sum two conserved spends per channel. Tokens and dollars never fold into each other, an\n * incomplete input keeps the sum incomplete on that channel, and the catalog-priced part of the\n * dollar total is summed separately so `usd - usdEstimated` still names what a provider billed.\n */\nexport function addSpend(a: Spend, b: Spend): Spend {\n const tokens = cloneTokenUsage(a.tokens)\n addTokenUsage(tokens, b.tokens)\n return {\n iterations: a.iterations + b.iterations,\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...usdEstimatedOf(a, b),\n ms: a.ms + b.ms,\n ...boxMinutesOf(a, b),\n ...tokensProvenanceOf(a, b),\n }\n}\n\n/**\n * Fold the token-provenance channel across spends, as a field to spread.\n *\n * Returns nothing when no contributor stated one, because ABSENT already means \"the executor's own\n * live stream\", which is what every path reported before a harness store was readable. A\n * contributor that stated one and a contributor that did not therefore disagree, and the sum is\n * `'mixed'` — the honest answer for a tree whose spend came from two kinds of receipt.\n */\nfunction tokensProvenanceOf(...spends: ReadonlyArray<Spend>): {\n tokensProvenance?: TokenUsageProvenance\n} {\n let folded: TokenUsageProvenance | undefined\n let sawStated = false\n for (const spend of spends) {\n const stated = spend.tokensProvenance ?? 'stream-receipt'\n if (spend.tokensProvenance !== undefined) sawStated = true\n folded = folded === undefined || folded === stated ? stated : 'mixed'\n }\n return !sawStated || folded === undefined || folded === 'stream-receipt'\n ? {}\n : { tokensProvenance: folded }\n}\n\n/**\n * Fold the platform box-time channel across spends, as a field to spread.\n *\n * Returns nothing when no input carried the channel, so a fold over router or cli-bridge work —\n * which runs no box at all — never gains a `boxMinutesProvenance: 'uncaptured'` that would claim\n * a box ran and went unmetered.\n *\n * Three rules, one per field:\n * - `boxMinutes` sums the numbers that are present, and stays ABSENT when none is. A missing\n * measurement never enters the sum as a zero.\n * - `boxMinutesKnown` is sticky-false, like `tokensKnown`: one contributor that could not state\n * its box time makes the whole sum a floor.\n * - `boxMinutesProvenance` degrades. `'observed'` survives only when every contributor that\n * carried a number was observed; one derived number makes the sum `'estimated'`; no number at\n * all is `'uncaptured'`.\n */\nfunction boxMinutesOf(...spends: ReadonlyArray<Spend>): {\n boxMinutes?: number\n boxMinutesKnown?: boolean\n boxMinutesProvenance?: 'observed' | 'estimated' | 'uncaptured'\n} {\n const present = spends.filter((spend) => spend.boxMinutesProvenance !== undefined)\n if (present.length === 0) return {}\n let minutes = 0\n let sawNumber = false\n let known = true\n let observedOnly = true\n for (const spend of present) {\n if (typeof spend.boxMinutes === 'number' && Number.isFinite(spend.boxMinutes)) {\n minutes += spend.boxMinutes\n sawNumber = true\n if (spend.boxMinutesProvenance !== 'observed') observedOnly = false\n }\n if (spend.boxMinutesKnown !== true) known = false\n }\n return {\n ...(sawNumber ? { boxMinutes: roundBoxMinutes(minutes) } : {}),\n boxMinutesKnown: known,\n boxMinutesProvenance: sawNumber ? (observedOnly ? 'observed' : 'estimated') : 'uncaptured',\n }\n}\n\n/**\n * Box minutes at four decimals — a tenth of a second.\n *\n * Fine enough that a box alive for two seconds reports `0.0333` instead of a zero that would read\n * as a measured free box, and coarse enough that summing floats does not print\n * `1.5000000000000002`.\n */\nexport function roundBoxMinutes(minutes: number): number {\n return Number(minutes.toFixed(4))\n}\n\n/** Copy a token subtotal without dropping optional provider cache telemetry. */\nexport function cloneTokenUsage(usage: LoopTokenUsage): LoopTokenUsage {\n const cacheBreakdownUnknown =\n usage.cacheBreakdownKnown === false || (usage.input > 0 && !hasClassifiedCacheBreakdown(usage))\n return {\n input: usage.input,\n output: usage.output,\n ...(usage.tokensKnown === false ? { tokensKnown: false as const } : {}),\n ...(usage.freshInput !== undefined ? { freshInput: usage.freshInput } : {}),\n ...(usage.cacheRead !== undefined ? { cacheRead: usage.cacheRead } : {}),\n ...(usage.cacheWrite !== undefined ? { cacheWrite: usage.cacheWrite } : {}),\n ...(cacheBreakdownUnknown ? { cacheBreakdownKnown: false as const } : {}),\n }\n}\n\n/** True only when every positive prompt token has a consistent cache classification. */\nexport function hasCompleteCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.cacheBreakdownKnown === false) return false\n return hasClassifiedCacheBreakdown(usage)\n}\n\nfunction hasClassifiedCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.input === 0) return true\n if (\n usage.freshInput === undefined ||\n usage.cacheRead === undefined ||\n usage.cacheWrite === undefined\n ) {\n return false\n }\n return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input\n}\n\n/**\n * The token charge for one observation: every token counted ONCE, at the moment it first enters\n * the context — `input − cacheRead + output`.\n *\n * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,\n * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A\n * cache read is content that was already charged when it was written, so it is the one class the\n * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No\n * price weight is involved: this counts work, and money is a separate channel.\n *\n * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate\n * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the\n * records that built it — including an aggregate that mixes classified and unclassified turns,\n * where the unclassified remainder is charged in full and only the reported cache reads are\n * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn\n * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.\n *\n * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it\n * partitions credits nothing, so the charge is never below `output` and a class that overflows its\n * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it\n * never served — that provider can under-report `input` just as easily, and the token channel is an\n * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged\n * in full, so a spend with no readable split charges an upper bound on newly-presented work rather\n * than a measurement, and every caller that enforces a ceiling must report the difference\n * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).\n */\nexport function chargedTokens(usage: LoopTokenUsage): number {\n return usage.input - creditedCacheRead(usage) + usage.output\n}\n\n/** `cacheRead` if the reported classes fit inside `input`, else nothing. */\nfunction creditedCacheRead(usage: LoopTokenUsage): number {\n const { cacheRead } = usage\n if (cacheRead === undefined) return 0\n return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead\n}\n\nfunction classifiedTotal(usage: Partial<LoopTokenUsage>, cacheRead: number): number {\n return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0)\n}\n\n/**\n * The only two members this reads out of a provider prompt-cache report, named rather than taken as\n * an open record: both the typed `PromptCacheUsage` and the open `promptCache` an `llm_call` carries\n * satisfy it, and each value is validated before it is credited.\n */\nexport interface PromptCacheCounters {\n readonly readTokens?: unknown\n readonly writeTokens?: unknown\n}\n\n/** The prompt-cache token classes of one observation, as `LoopTokenUsage` members. */\nexport type PromptCacheTokenClasses = Pick<\n LoopTokenUsage,\n 'freshInput' | 'cacheRead' | 'cacheWrite' | 'cacheBreakdownKnown'\n>\n\n/**\n * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds\n * and `chargedTokens` credits.\n *\n * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`\n * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the\n * three outcomes are different facts that must not collapse into one another:\n *\n * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,\n * because a provider that says nothing about caching has not said the split is unknowable.\n * - **Read and write both reported, and fitting inside `input`** — a complete partition, so\n * `freshInput` is the remainder and the split is known.\n * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured\n * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports\n * no write) still credits the read it measured, while declaring the rest unclassified so the\n * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a\n * partition of a total it exceeds.\n *\n * A counter the provider did not report stays absent. A zero would claim the provider measured no\n * cache, which is a different fact from a provider that did not report.\n */\nexport function promptCacheTokenClasses(\n input: number | undefined,\n promptCache: PromptCacheCounters | undefined,\n): PromptCacheTokenClasses {\n if (promptCache === undefined) return {}\n const read = tokenCount(promptCache.readTokens)\n const write = tokenCount(promptCache.writeTokens)\n if (read === undefined && write === undefined) return {}\n if (input === undefined || (read ?? 0) + (write ?? 0) > input) {\n return { cacheBreakdownKnown: false }\n }\n if (read !== undefined && write !== undefined) {\n return { freshInput: input - read - write, cacheRead: read, cacheWrite: write }\n }\n return {\n ...(read !== undefined ? { cacheRead: read } : {}),\n ...(write !== undefined ? { cacheWrite: write } : {}),\n cacheBreakdownKnown: false,\n }\n}\n\nfunction tokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/**\n * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.\n *\n * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO\n * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a\n * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit\n * at the aggregate a cache read it refuses at the record. That is the one way the charge could come\n * out below the sum of the charges on the records that built it.\n */\nexport function addTokenUsage(acc: LoopTokenUsage, delta: Partial<LoopTokenUsage>): void {\n acc.input += delta.input ?? 0\n acc.output += delta.output ?? 0\n if (delta.tokensKnown === false) acc.tokensKnown = false\n\n const input = delta.input ?? 0\n const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input\n if (fits) {\n if (delta.freshInput !== undefined) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput\n if (delta.cacheRead !== undefined) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead\n if (delta.cacheWrite !== undefined) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite\n }\n\n const classified =\n fits &&\n delta.freshInput !== undefined &&\n delta.cacheRead !== undefined &&\n delta.cacheWrite !== undefined &&\n delta.freshInput + delta.cacheRead + delta.cacheWrite === input\n // A provider that reports prompt input without all three classes leaves the\n // split unknown. Do not let an earlier complete turn make the aggregate look\n // complete after a later unclassified positive-input turn.\n if (delta.cacheBreakdownKnown === false || (input > 0 && !classified)) {\n acc.cacheBreakdownKnown = false\n }\n}\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. On the first `fn` rejection no NEW\n * items are picked up; already-in-flight calls are awaited, then the first\n * error is rethrown. `limit` is clamped to ≥ 1.\n *\n * Used where a burst of provisioning (e.g. forking N child boxes) must respect\n * the loop's concurrency bound instead of firing all N at once.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const bound = Math.max(1, Math.floor(limit))\n const results = new Array<R>(items.length)\n let next = 0\n let failed = false\n const worker = async (): Promise<void> => {\n while (!failed) {\n const i = next\n next += 1\n if (i >= items.length) return\n try {\n results[i] = await fn(items[i] as T, i)\n } catch (err) {\n failed = true\n throw err\n }\n }\n }\n const workerCount = Math.min(bound, items.length)\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n return results\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 AgentInteractiveSession,\n type AgentInteractiveSessionRef,\n AgentInteractiveSessionRefSchema,\n type AgentInteractiveSessionStart,\n AgentInteractiveSessionStartSchema,\n type AgentProfile,\n type AgentProfileValidationResult,\n type AgentRunCancellationAcknowledgement,\n type AgentRunCancellationRequest,\n AgentRunCancellationRequestSchema,\n type AgentRunControlRef,\n agentInteractiveSessionRefMatchesStart,\n canonicalCandidateDigest,\n canonicalWorkspaceCwd,\n harnessSystemPromptIntents,\n type InteractionAcknowledgement,\n type InteractionResponseCommand,\n type TokenUsage,\n WorkspaceRequestSchema,\n workspaceCwdPathForBase,\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 InteractiveSessionHandle,\n PromptInputPart,\n PromptOptions,\n PromptResult,\n SandboxEvent,\n ExecResult as SandboxExecResult,\n SandboxInstance,\n SandboxRuntimeCapabilities,\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 { detachedSnapshot } from './supervise/snapshot'\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, Validator } 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/**\n * Adapt a `SandboxClient` into the shared `AgentEnvironmentProvider` contract.\n * The provider declares the public SDK contract before it creates an environment.\n * Each environment exposes interactive methods only when its deployment declares every required capability.\n * @experimental */\nexport function sandboxClientAsProvider(\n client: SandboxClient,\n options: SandboxClientProviderOptions = {},\n): AgentEnvironmentProvider {\n const providerName = options.name ?? 'tangle-sandbox'\n const providerCapabilities = async (): Promise<AgentEnvironmentCapabilities> => {\n const capabilities = options.capabilities\n ? typeof options.capabilities === 'function'\n ? options.capabilities()\n : options.capabilities\n : defaultTangleSandboxCapabilities({\n namedProfiles: options.resolveProfile !== undefined,\n rediscover: hasGet(client),\n })\n const resolved = await capabilities\n if (hasGet(client)) return resolved\n const { interactiveAgent: _interactiveAgent, ...withoutInteractive } = resolved\n return withoutInteractive\n }\n return {\n name: providerName,\n capabilities: providerCapabilities,\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 providerName,\n ))\n const capabilities = await providerCapabilities()\n const box = await client.create(\n createOptions,\n input.signal === undefined ? undefined : { signal: input.signal },\n )\n return sandboxInstanceAsEnvironment(box, providerName, client, capabilities)\n },\n ...(hasGet(client)\n ? {\n async get(id: string): Promise<AgentEnvironment | null> {\n const capabilities = await providerCapabilities()\n const box = await client.get(id)\n return box\n ? sandboxInstanceAsEnvironment(box, providerName, client, capabilities)\n : 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/**\n * What one provider-executed turn settles on: the visible answer plus the complete event archive\n * the environment streamed. It is the value a `ProviderExecutorOptions.validator` scores.\n *\n * @experimental\n */\nexport interface ProviderLeafOut {\n content: string\n events: AgentEnvironmentEvent[]\n}\n\n/**\n * Per-run Sandbox prompt options for the provider path — the same field, the same name, and the\n * same kernel-owned exclusions as `ExecCtx.promptOptions` on the sandbox path.\n *\n * The kernel owns `sessionId` and `signal`, so neither is declarable: a caller-chosen session id\n * would make every worker share one server session, and the abort channel belongs to the run.\n * `model` is excluded too, and for a different reason: this executor's materialization record\n * names the model from `AgentProfile`, so a turn-level override would make the record state a\n * model the provider did not run. Declare the instrument on `AgentProfile.model`.\n *\n * Everything else is the per-call configuration a portable profile cannot carry. `backend` is the\n * load-bearing one: `backend.model.authMode` plus `authFiles` is how a caller-owned subscription\n * seat reaches the harness inside the environment. Runtime lowers these onto the turn with the one\n * mapper it already uses in the other direction, so a sandbox-shaped provider reads them from\n * `AgentTurnInput.providerOptions.backend` exactly as it reads a sandbox box's prompt options.\n *\n * @experimental\n */\nexport type ProviderPromptOptions = Omit<PromptOptions, 'model' | 'sessionId' | 'signal'>\n\n/** Turn fields the seam's prompt options configure. The kernel owns every other coordinate. */\ntype ProviderTurnDefaults = Omit<\n AgentTurnInput,\n 'model' | 'parts' | 'prompt' | 'sessionId' | 'signal'\n>\n\n/**\n * Lower the seam's prompt options onto turn fields, through the one mapper this module already\n * uses to raise a sandbox prompt into a provider turn. Reusing it is what keeps the two directions\n * from drifting: whatever `turnInputFromPrompt` decides a prompt option configures, the seam\n * declares the same way.\n */\nfunction providerTurnDefaults(\n options: ProviderPromptOptions | undefined,\n context: string,\n): ProviderTurnDefaults | undefined {\n if (options === undefined) return undefined\n if ((options as { model?: unknown }).model !== undefined) {\n throw new ValidationError(\n `${context}: promptOptions.model is refused — this executor's materialization names AgentProfile's model, so a turn-level override would record a model the provider did not run`,\n )\n }\n const {\n prompt: _prompt,\n parts: _parts,\n model: _model,\n sessionId: _sessionId,\n signal: _signal,\n ...turn\n } = turnInputFromPrompt('', options)\n return turn\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 /**\n * Per-run prompt options merged UNDER every streamed turn: a mapped turn's own field wins, and\n * the runtime's abort signal is applied last. `providerOptions` merges one level, so a\n * `taskToTurn` that sets its own provider option cannot silently drop the session credential\n * declared here.\n */\n promptOptions?: ProviderPromptOptions\n /**\n * OPT-IN executable score for this worker, with the SAME contract the sandbox seam's validator\n * has: `validate` runs while the environment is still alive, so `ValidationCtx.box` can read\n * files and run commands in the environment it is scoring. Every other supervised hook fires\n * after teardown and can only read the artifact.\n *\n * The verdict becomes the settled artifact's verdict. Absent, nothing changes and the leaf falls\n * back to its own settle verdict.\n */\n validator?: Validator<ProviderLeafOut>\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/**\n * Merge the declared turn defaults under one mapped turn.\n *\n * `providerOptions` is merged one level rather than replaced: the defaults carry the caller's\n * session credential and a `taskToTurn` that sets an unrelated provider option would otherwise\n * remove it, and a run that silently loses its credential fails inside the environment as an\n * authorization error that names nothing.\n */\nfunction providerTurnWithDefaults(\n defaults: ProviderTurnDefaults | undefined,\n turn: AgentTurnInput,\n signal: AbortSignal,\n): AgentTurnInput {\n if (defaults === undefined) return { ...turn, signal }\n const providerOptions =\n defaults.providerOptions === undefined && turn.providerOptions === undefined\n ? undefined\n : { ...(defaults.providerOptions ?? {}), ...(turn.providerOptions ?? {}) }\n return {\n ...defaults,\n ...turn,\n ...(providerOptions === undefined ? {} : { providerOptions }),\n signal,\n }\n}\n\n/** Adapt an environment provider into an `ExecutorFactory` for `createExecutor`.\n *\n * `createExecutor({ backend: 'provider', provider })` is the composition most callers want; it\n * builds this factory and injects the seam. See `examples/provider-executor/`.\n *\n * Still `@experimental`: the entry point that consumes it, `createExecutor`, carries no stability\n * tag and is therefore experimental by default, so a stable promise here would be reachable only\n * through an experimental symbol.\n *\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 // The stream destroys the environment on settle by default, so a later `teardown` would issue a\n // SECOND delete against a resource that is already gone. That second call is what the provider\n // answered 409 to.\n let destroyed = false\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 onDestroyed: () => {\n destroyed = true\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; detail?: string }> {\n controller.abort()\n // Already released by the stream's own settle path: re-deleting is the double call that\n // produced the 409, and the resource is provably gone, so this is a confirmed teardown.\n if (destroyed || environment === undefined) return { destroyed: true }\n try {\n await environment.destroy?.()\n destroyed = true\n return { destroyed: true }\n } catch (error) {\n // A cleanup this process could not complete is UNCONFIRMED, not a run failure. `destroyed:\n // false` is exactly what the barrier journals as `teardown-unconfirmed`; throwing here\n // would instead surface as a failure of the work the executor already finished.\n return {\n destroyed: false,\n detail: `providerAsExecutor(${provider.name}): environment.destroy() failed — ${error instanceof Error ? error.message : String(error)}`,\n }\n }\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 /** The environment was destroyed here, so `teardown` must not DELETE it a second time — the\n * double delete is what produced the 409 that used to fail a completed run. */\n onDestroyed: () => 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 // READINESS IS THE PROVIDER'S CONTRACT. `create` resolves with an environment that can take a\n // turn, so this streams straight into it and adds no wait of its own. The sandbox seam's\n // `acquireSandbox` exists because a raw `SandboxClient.create` returns before the box is ready;\n // wrapping a second readiness poll around a provider that already honors the contract would hide\n // a provider that does not, and a provider that does not is an upstream defect to report.\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 = providerTurnWithDefaults(\n providerTurnDefaults(args.options.promptOptions, `providerAsExecutor(${args.provider.name})`),\n args.options.taskToTurn?.(args.task, args.profile) ?? taskToTurnInput(args.task, linked),\n linked,\n )\n const events: AgentEnvironmentEvent[] = []\n const tokens = zeroTokenUsage()\n let usd = 0\n let text = ''\n let terminal = false\n // The artifact this turn settled with, once it exists. Its presence is what separates \"the work\n // finished and the resource would not release\" from \"the work never finished\".\n let settled: ExecutorResult<unknown> | undefined\n // The body's own failure, held so the `finally` cannot REPLACE it. A `finally` that throws\n // discards the in-flight exception, so a teardown error would otherwise mask the real cause of a\n // turn that failed for its own reasons.\n let failure: unknown\n let failed = false\n try {\n const toolParts = createSandboxToolPartState()\n for await (const event of environment.stream(turn)) {\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 // Scored HERE, before the `finally` destroys the environment: a validator that reads a file or\n // runs a command needs the environment it is scoring to still exist. Every other supervised\n // hook fires after teardown and can only read the artifact.\n const verdict = await args.options.validator?.validate(result, {\n iteration: 0,\n box: environmentAsSandboxInstance(environment, {\n requireTerminalEvent: args.options.requireTerminalEvent ?? true,\n }),\n signal: linked,\n })\n settled = {\n outRef: contentRef(`provider:${args.provider.name}`, result),\n out: result,\n ...(verdict ? { verdict } : {}),\n spent,\n }\n args.onArtifact(settled)\n } catch (error) {\n failure = error\n failed = true\n } finally {\n if (args.options.destroyOnSettle ?? true) {\n try {\n await environment.destroy?.()\n args.onDestroyed()\n } catch (error) {\n // ONCE THE TURN HAS SETTLED, TEARDOWN CANNOT CHANGE THE OUTCOME. Measured: a second DELETE\n // answered 409, the rejection escaped this `finally`, and a run whose turn had completed\n // (`spent.iterations: 1`, artifact produced) was reported as a failure. The resource fact is\n // recorded beside the result; the result stands.\n //\n // Before the turn settles there is no outcome to protect, so the failure IS the outcome and\n // is rethrown — a create-then-fail-then-leak path must still fail loudly.\n if (settled !== undefined) {\n args.onArtifact({\n ...settled,\n teardown: {\n failed: true,\n error: error instanceof Error ? error.message : String(error),\n at: new Date().toISOString(),\n },\n })\n } else if (!failed) {\n // Nothing settled and the body did not fail on its own: the teardown failure IS the\n // outcome, so a create-then-leak path still fails loudly.\n failure = error\n failed = true\n } else {\n // The body already failed. ITS error is the cause a reader needs; the teardown failure\n // rides along as `cause` rather than displacing it.\n failure =\n failure instanceof Error\n ? Object.assign(failure, { cause: failure.cause ?? error })\n : failure\n }\n }\n }\n }\n if (failed) throw failure\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 cwd =\n options?.cwd === undefined\n ? undefined\n : canonicalWorkspaceCwd({ base: 'repository', path: options.cwd })\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 ...(cwd === undefined ? {} : { cwd }),\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 // Sandbox 0.34 adds the provider-owned \"all\" selector. Keep it in the\n // passthrough options below because the neutral input contract accepts names only.\n ...(Array.isArray(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 providerName = 'tangle-sandbox',\n): Promise<CreateSandboxOptions> {\n const backendType = (input.backend ?? defaultBackend) as BackendType\n const workspace = WorkspaceRequestSchema.parse(input.workspace ?? {})\n const environment = sandboxEnvironmentFromWorkspace(workspace)\n const cwd = workspaceCwdPathForBase(workspace.cwd, 'repository', providerName)\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 ...(cwd === undefined ? {} : { cwd }),\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(\n secrets: unknown,\n): asserts secrets is string[] | 'all' | undefined {\n if (\n secrets !== undefined &&\n secrets !== 'all' &&\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\nasync function sandboxInstanceAsEnvironment(\n box: SandboxInstance,\n providerName: string,\n client: SandboxClient,\n providerCapabilities: AgentEnvironmentCapabilities,\n): Promise<AgentEnvironment> {\n const capabilities = await sandboxEnvironmentCapabilities(box, providerCapabilities)\n const interactiveAgent = capabilities.interactiveAgent\n const environment: AgentEnvironment = {\n id: String(box.id),\n provider: providerName,\n capabilities,\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 ...(interactiveAgent\n ? {\n async startInteractive(\n request: AgentInteractiveSessionStart,\n options?: { signal?: AbortSignal },\n ): Promise<AgentInteractiveSessionRef> {\n const exactRequest = AgentInteractiveSessionStartSchema.parse(request)\n assertSandboxInteractiveBinding(exactRequest.run, box, providerName)\n const result = await box\n .session(exactRequest.run.sessionId)\n .interactive()\n .start(exactRequest, options)\n if (result.state !== 'running') {\n throw new ValidationError('sandbox interactive process settled before attachment')\n }\n const ref = detachedSnapshot(\n AgentInteractiveSessionRefSchema.parse(result.ref),\n 'sandbox interactive start reference',\n )\n if (!agentInteractiveSessionRefMatchesStart(exactRequest, ref)) {\n throw new ValidationError(\n 'sandbox interactive start returned a different exact process',\n )\n }\n return ref\n },\n interactive(ref: AgentInteractiveSessionRef): AgentInteractiveSession {\n const exactRef = detachedSnapshot(\n AgentInteractiveSessionRefSchema.parse(ref),\n 'sandbox interactive reference',\n )\n assertSandboxInteractiveBinding(exactRef.run, box, providerName)\n const session = box.session(exactRef.run.sessionId).interactive({ ref: exactRef })\n const controlledSessions = new Map<string, InteractiveSessionHandle>()\n const controlledSession = (\n control: Parameters<AgentInteractiveSession['attach']>[0]['control'],\n ) => {\n const key = canonicalCandidateDigest(control)\n const existing = controlledSessions.get(key)\n if (existing) return existing\n const created = box\n .session(exactRef.run.sessionId)\n .interactive({ ref: exactRef, control })\n controlledSessions.set(key, created)\n return created\n }\n return {\n ref: exactRef,\n claimControl: (request, options) => session.claimControl(request, options),\n async status(options) {\n const status = await session.status(options)\n if (status === null) {\n throw new ValidationError(\n `sandbox interactive session \"${exactRef.run.sessionId}\" is unavailable`,\n )\n }\n return status\n },\n attach: (request, options) => {\n const controlled = controlledSession(request.control)\n if (typeof controlled.attachAgentTerminal !== 'function') {\n return Promise.reject(\n new ValidationError(\n 'sandbox interactive session does not expose the exact terminal adapter',\n ),\n )\n }\n return controlled.attachAgentTerminal(request, options)\n },\n sendPrompt: (command, options) =>\n controlledSession(command.control).sendPrompt(command, options),\n stop: (command, options) => controlledSession(command.control).stop(command, options),\n }\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, providerCapabilities)\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(events: AgentEnvironmentEvent[], fallbackText: string): ProviderLeafOut {\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\ntype InteractiveAgentCapabilities = NonNullable<AgentEnvironmentCapabilities['interactiveAgent']>\n\nconst completeInteractiveAgentCapabilities: InteractiveAgentCapabilities = {\n start: true,\n control: true,\n status: true,\n attach: true,\n reattach: true,\n sendPrompt: true,\n input: true,\n resize: true,\n stop: true,\n}\n\nasync function sandboxEnvironmentCapabilities(\n box: SandboxInstance,\n providerCapabilities: AgentEnvironmentCapabilities,\n): Promise<AgentEnvironmentCapabilities> {\n const { interactiveAgent: providerInteractive, ...baseCapabilities } = providerCapabilities\n if (!hasCompleteInteractiveAgentCapabilities(providerInteractive)) return baseCapabilities\n let deployed: SandboxRuntimeCapabilities | null\n try {\n deployed = await box.capabilities()\n } catch {\n return baseCapabilities\n }\n if (!hasCompleteInteractiveAgentCapabilities(deployed?.interactiveAgent)) {\n return baseCapabilities\n }\n if (!hasExactInteractiveTerminalAdapter(box)) return baseCapabilities\n return {\n ...baseCapabilities,\n interactiveAgent: { ...completeInteractiveAgentCapabilities },\n }\n}\n\nfunction hasExactInteractiveTerminalAdapter(box: SandboxInstance): boolean {\n if (!hasSession(box)) return false\n try {\n const session = box.session('__runtime-capability-probe__')\n const interactive = (session as { interactive?: (options?: unknown) => unknown }).interactive\n if (typeof interactive !== 'function') return false\n const handle = interactive.call(session)\n return typeof (handle as { attachAgentTerminal?: unknown }).attachAgentTerminal === 'function'\n } catch {\n return false\n }\n}\n\nfunction hasCompleteInteractiveAgentCapabilities(\n value: Partial<InteractiveAgentCapabilities> | undefined,\n): value is InteractiveAgentCapabilities {\n return (\n value?.start === true &&\n value.control === true &&\n value.status === true &&\n value.attach === true &&\n value.reattach === true &&\n value.sendPrompt === true &&\n value.input === true &&\n value.resize === true &&\n value.stop === true\n )\n}\n\nfunction assertSandboxInteractiveBinding(\n run: { provider: string; environmentId: string },\n box: SandboxInstance,\n providerName: string,\n): void {\n if (run.provider !== providerName || run.environmentId !== String(box.id)) {\n throw new ValidationError('sandbox interactive request targets another environment')\n }\n}\n\nfunction defaultTangleSandboxCapabilities(options: {\n namedProfiles: boolean\n rediscover: 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: {\n read: true,\n write: true,\n exec: true,\n git: true,\n upload: true,\n download: true,\n cwdBases: { repository: true, host: false },\n },\n branching: { checkpoint: false, fork: false },\n ...(options.rediscover\n ? { interactiveAgent: { ...completeInteractiveAgentCapabilities } }\n : {}),\n placement: true,\n usage: true,\n confidential: false,\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,SAAgBA,aAAW,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,GAAG,SAAkD;CAC7E,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,YAAiE,CAAC;CACxE,MAAM,gBAAsB;EA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,YAAY;IAAM,MAAM;GAAM;EAC5C;EACA,WAAW;GAAE,YAAY;GAAO,MAAM;EAAM;EAC5C,GAAI,QAAQ,aACR,EAAE,kBAAkB,EAAE,GAAG,qCAAqC,EAAE,IAChE,CAAC;EACL,WAAW;EACX,OAAO;EACP,cAAc;CAChB;AACF;AAEA,SAAS,WAAW,QAAgB,OAAwB;CAC1D,IAAI;CACJ,IAAI;EACF,MAAM,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;CAC7C,QAAQ;EACN,MAAM,OAAO,KAAK;CACpB;CACA,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GAAG;EACtC,QAAQ,IAAI,WAAW,CAAC;EACxB,OAAO,KAAK,KAAK,MAAM,QAAU;CACnC;CACA,OAAO,GAAG,OAAO,IAAI,SAAS,EAAA,CAAG,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;AAC/D;AAEA,SAAS,OACP,QACgF;CAChF,OAAO,OAAQ,OAA6B,QAAQ;AACtD;AAEA,SAAS,QACP,QACmF;CACnF,OAAO,OAAQ,OAA8B,SAAS;AACxD;AAEA,SAAS,kBAAkB,KAEzB;CACA,OAAO,OAAQ,IAAqC,mBAAmB;AACzE;AAEA,SAAS,WACP,KACsE;CACtE,OAAO,OAAQ,IAA8B,YAAY;AAC3D;AAEA,SAAS,QAAQ,KAEf;CACA,OAAO,OAAQ,IAA2B,SAAS;AACrD;AAEA,SAAS,SACP,KACkF;CAClF,OAAO,OAAQ,IAA4B,UAAU;AACvD;AAEA,SAAS,QAAQ,KAEf;CACA,OAAO,OAAQ,IAA2B,SAAS;AACrD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { E as SandboxClient, k as Validator } from "./types-BdolQ6Zi.js";
|
|
2
|
-
import { p as ExecutorFactory, z as Runtime } from "./types-
|
|
2
|
+
import { p as ExecutorFactory, z as Runtime } from "./types-B_pNTBjK.js";
|
|
3
3
|
import { AgentProfile, AgentProfileValidationResult } from "@tangle-network/agent-interface";
|
|
4
4
|
import { BackendType, CreateSandboxOptions, PromptOptions, Sandbox } from "@tangle-network/sandbox";
|
|
5
5
|
import { AgentEnvironment as AgentEnvironment$1, AgentEnvironmentCapabilities, AgentEnvironmentCapabilities as AgentEnvironmentCapabilities$1, AgentEnvironmentEvent, AgentEnvironmentEvent as AgentEnvironmentEvent$1, AgentEnvironmentProvider, AgentEnvironmentProvider as AgentEnvironmentProvider$1, AgentEnvironmentQuery, AgentEnvironmentStatus, AgentEnvironmentSummary, AgentProfileRef, AgentProfileRef as AgentProfileRef$1, AgentSession, AgentSessionRef, AgentSessionStatus as AgentSessionStatus$1, AgentTurnInput, AgentTurnInput as AgentTurnInput$1, AgentTurnResult as AgentTurnResult$1, CheckpointRef, CheckpointRequest, CreateAgentEnvironmentInput, CreateAgentEnvironmentInput as CreateAgentEnvironmentInput$1, ExecRequest, ExecResult, ForkRequest, PlacementInfo, ResourceRequest, WorkspaceRequest } from "@tangle-network/agent-interface/environment-provider";
|
|
@@ -140,4 +140,4 @@ interface ProviderExecutorOptions {
|
|
|
140
140
|
declare function providerAsExecutor(provider: AgentEnvironmentProvider, options?: ProviderExecutorOptions): ExecutorFactory<unknown>;
|
|
141
141
|
//#endregion
|
|
142
142
|
export { createAgentEnvironmentProviderRegistry as A, ProviderAsSandboxClientOptions as C, ResourceRequest as D, ProviderPromptOptions as E, CreateTangleSandboxExactProcessProviderOptions as F, SandboxControlClient as I, createTangleSandboxExactProcessProvider as L, providerAsSandboxClient as M, resolveAgentEnvironmentProvider as N, SandboxClientProviderOptions as O, sandboxClientAsProvider as P, PlacementInfo as S, ProviderLeafOut as T, CheckpointRequest as _, AgentEnvironmentProviderRef as a, ExecResult as b, AgentEnvironmentStatus as c, AgentSession as d, AgentSessionRef as f, CheckpointRef as g, AgentTurnResult$1 as h, AgentEnvironmentProvider$1 as i, providerAsExecutor as j, WorkspaceRequest as k, AgentEnvironmentSummary as l, AgentTurnInput$1 as m, AgentEnvironmentCapabilities$1 as n, AgentEnvironmentProviderRegistry as o, AgentSessionStatus$1 as p, AgentEnvironmentEvent$1 as r, AgentEnvironmentQuery as s, AgentEnvironment$1 as t, AgentProfileRef$1 as u, CreateAgentEnvironmentInput$1 as v, ProviderExecutorOptions as w, ForkRequest as x, ExecRequest as y };
|
|
143
|
-
//# sourceMappingURL=environment-provider-
|
|
143
|
+
//# sourceMappingURL=environment-provider-adVa6X7a.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as createAgentEnvironmentProviderRegistry, C as ProviderAsSandboxClientOptions, D as ResourceRequest, E as ProviderPromptOptions, F as CreateTangleSandboxExactProcessProviderOptions, L as createTangleSandboxExactProcessProvider, M as providerAsSandboxClient, N as resolveAgentEnvironmentProvider, O as SandboxClientProviderOptions, P as sandboxClientAsProvider, S as PlacementInfo, T as ProviderLeafOut, _ as CheckpointRequest, a as AgentEnvironmentProviderRef, b as ExecResult, c as AgentEnvironmentStatus, d as AgentSession, f as AgentSessionRef, g as CheckpointRef, h as AgentTurnResult, i as AgentEnvironmentProvider, j as providerAsExecutor, k as WorkspaceRequest, l as AgentEnvironmentSummary, m as AgentTurnInput, n as AgentEnvironmentCapabilities, o as AgentEnvironmentProviderRegistry, p as AgentSessionStatus, r as AgentEnvironmentEvent, s as AgentEnvironmentQuery, t as AgentEnvironment, u as AgentProfileRef, v as CreateAgentEnvironmentInput, w as ProviderExecutorOptions, x as ForkRequest, y as ExecRequest } from "./environment-provider-
|
|
1
|
+
import { A as createAgentEnvironmentProviderRegistry, C as ProviderAsSandboxClientOptions, D as ResourceRequest, E as ProviderPromptOptions, F as CreateTangleSandboxExactProcessProviderOptions, L as createTangleSandboxExactProcessProvider, M as providerAsSandboxClient, N as resolveAgentEnvironmentProvider, O as SandboxClientProviderOptions, P as sandboxClientAsProvider, S as PlacementInfo, T as ProviderLeafOut, _ as CheckpointRequest, a as AgentEnvironmentProviderRef, b as ExecResult, c as AgentEnvironmentStatus, d as AgentSession, f as AgentSessionRef, g as CheckpointRef, h as AgentTurnResult, i as AgentEnvironmentProvider, j as providerAsExecutor, k as WorkspaceRequest, l as AgentEnvironmentSummary, m as AgentTurnInput, n as AgentEnvironmentCapabilities, o as AgentEnvironmentProviderRegistry, p as AgentSessionStatus, r as AgentEnvironmentEvent, s as AgentEnvironmentQuery, t as AgentEnvironment, u as AgentProfileRef, v as CreateAgentEnvironmentInput, w as ProviderExecutorOptions, x as ForkRequest, y as ExecRequest } from "./environment-provider-adVa6X7a.js";
|
|
2
2
|
export { type AgentEnvironment, type AgentEnvironmentCapabilities, type AgentEnvironmentEvent, type AgentEnvironmentProvider, AgentEnvironmentProviderRef, AgentEnvironmentProviderRegistry, type AgentEnvironmentQuery, type AgentEnvironmentStatus, type AgentEnvironmentSummary, type AgentProfileRef, type AgentSession, type AgentSessionRef, type AgentSessionStatus, type AgentTurnInput, type AgentTurnResult, type CheckpointRef, type CheckpointRequest, type CreateAgentEnvironmentInput, type CreateTangleSandboxExactProcessProviderOptions, type ExecRequest, type ExecResult, type ForkRequest, type PlacementInfo, ProviderAsSandboxClientOptions, ProviderExecutorOptions, ProviderLeafOut, ProviderPromptOptions, type ResourceRequest, SandboxClientProviderOptions, type WorkspaceRequest, createAgentEnvironmentProviderRegistry, createTangleSandboxExactProcessProvider, providerAsExecutor, providerAsSandboxClient, resolveAgentEnvironmentProvider, sandboxClientAsProvider };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as sandboxClientAsProvider, i as resolveAgentEnvironmentProvider, n as providerAsExecutor, o as createTangleSandboxExactProcessProvider, r as providerAsSandboxClient, t as createAgentEnvironmentProviderRegistry } from "./environment-provider-
|
|
1
|
+
import { a as sandboxClientAsProvider, i as resolveAgentEnvironmentProvider, n as providerAsExecutor, o as createTangleSandboxExactProcessProvider, r as providerAsSandboxClient, t as createAgentEnvironmentProviderRegistry } from "./environment-provider-Dr-wfnHg.js";
|
|
2
2
|
export { createAgentEnvironmentProviderRegistry, createTangleSandboxExactProcessProvider, providerAsExecutor, providerAsSandboxClient, resolveAgentEnvironmentProvider, sandboxClientAsProvider };
|