@tangle-network/agent-app 4.0.29 → 4.0.31
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/chat-routes/index.js +5 -5
- package/dist/{chunk-RK2VCJQW.js → chunk-5L3X42ES.js} +2 -2
- package/dist/{chunk-LSUJ2RIC.js → chunk-AG5Q273U.js} +2 -2
- package/dist/{chunk-WXK2AKRZ.js → chunk-DSFMSRWT.js} +11 -9
- package/dist/chunk-DSFMSRWT.js.map +1 -0
- package/dist/{chunk-7TZX2KSH.js → chunk-G3W3EIP4.js} +11 -4
- package/dist/chunk-G3W3EIP4.js.map +1 -0
- package/dist/{chunk-H7NMUXNZ.js → chunk-JLKH2VYF.js} +5 -4
- package/dist/chunk-JLKH2VYF.js.map +1 -0
- package/dist/preset-cloudflare/index.js +1 -1
- package/dist/public-consultation/index.js +4 -4
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/router-turn.js +2 -2
- package/dist/sandbox/index.js +2 -2
- package/dist/turn-trace/index.js +1 -1
- package/dist/turn-trace/recorder.d.ts +2 -1
- package/package.json +1 -1
- package/dist/chunk-7TZX2KSH.js.map +0 -1
- package/dist/chunk-H7NMUXNZ.js.map +0 -1
- package/dist/chunk-WXK2AKRZ.js.map +0 -1
- /package/dist/{chunk-RK2VCJQW.js.map → chunk-5L3X42ES.js.map} +0 -0
- /package/dist/{chunk-LSUJ2RIC.js.map → chunk-AG5Q273U.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sandbox/prompt-trace.ts","../src/sandbox/reuse-state.ts","../src/sandbox/model.ts","../src/sandbox/workspace-sandbox-manager.ts","../src/sandbox/terminal-connection.ts","../src/sandbox/prewarm.ts","../src/sandbox/prompt-profile.ts","../src/sandbox/payload-limits.ts","../src/sandbox/prompt-events.ts","../src/sandbox/runtime-cache.ts","../src/sandbox/prompt-dispatch.ts","../src/sandbox/prompt-result.ts","../src/sandbox/computer-files.ts","../src/sandbox/router-models.ts","../src/sandbox/computer-step.ts","../src/sandbox/sandbox-run-tool.ts","../src/sandbox/sandbox-exec-tool.ts","../src/sandbox/prewarm-claim-d1.ts","../src/sandbox/warm-receipts.ts","../src/chat-routes/route-storage.ts","../src/sandbox/prewarm-route.ts","../src/sandbox/request-cancellation.ts","../src/sandbox/foreground-single-flight.ts","../src/sandbox/warm-lease.ts","../src/sandbox/warm-lease-d1.ts","../src/sandbox/escalation-speculator.ts","../src/sandbox/credentials.ts","../src/sandbox/configuration.ts","../src/sandbox/product-egress.ts","../src/sandbox/router-model-policy.ts","../src/sandbox/existing-box.ts","../src/sandbox/profile-corpus.ts","../src/sandbox/lifecycle-errors.ts","../src/sandbox/runtime-connection.ts","../src/sandbox/app-tools.ts","../src/sandbox/workspace-boxes.ts","../src/sandbox/holder-box.ts","../src/sandbox/workspace-provision.ts","../src/sandbox/box-health.ts","../src/sandbox/workspace-claim.ts","../src/sandbox/prompt-options.ts","../src/sandbox/access.ts"],"sourcesContent":["/**\n * What a sandbox prompt stream tells the turn's trace: one `sandbox.prompt`\n * span for the whole stream, the sidecar's own first-text phases as child\n * spans, one `sandbox.generation` span from the first visible text, and one\n * `tool.call` span for each tool the box agent ran.\n *\n * Every time here is read on this side of the wire, from when each event\n * arrived. Event arrival is quantized by the stream's chunking, so the tool\n * spans carry `approx: true`. The sidecar's phases are offsets on its own\n * clock; only their durations are used, and the wait that no phase holds (the\n * SDK, the API, the orchestrator and the host, both ways) is `sandbox.transit`.\n */\nimport type { TurnSpan, TurnSpanAttrs, TurnTrace } from '../turn-trace/recorder'\nimport { nextCallIndex } from '../turn-trace/traced-fetch'\n\ntype Rec = Record<string, unknown>\nconst asRec = (value: unknown): Rec | undefined => value && typeof value === 'object' && !Array.isArray(value) ? value as Rec : undefined\nconst asNum = (value: unknown): number | undefined => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n\n/** The sidecar's phase order, and what each one's span is called. */\nconst PHASES = ['agent_run_start', 'harness_spawn', 'harness_ready', 'first_model_request', 'first_upstream_byte', 'first_text'] as const\n\ninterface PromptTrace {\n /** Read one raw sandbox event. Never throws. */\n observe(event: unknown): void\n /** End the stream's spans. `error` marks the prompt failed. */\n end(error?: unknown): void\n}\n\nfunction createPromptTrace(trace: TurnTrace, parent: TurnSpan | undefined, meta: TurnSpanAttrs): PromptTrace {\n const startedAt = Date.now()\n const prompt = trace.start('sandbox.prompt', 'sandbox', meta, parent)\n let firstEventAt: number | undefined\n let firstTextAt: number | undefined\n let generation: TurnSpan | undefined\n let phases: { offsets: Rec; spans: unknown[]; warm: boolean | null; model?: string } | undefined\n let events = 0\n const tools = new Map<string, TurnSpan>()\n\n const toolAttrs = (id: string, name: string): TurnSpanAttrs =>\n ({ 'gen_ai.tool.name': name, 'tool.call_id': id, 'call.index': nextCallIndex(trace, 'tool.call'), where: 'sandbox' })\n const startTool = (id: string, name: string) => {\n if (!tools.has(id)) tools.set(id, trace.start('tool.call', 'tool', { ...toolAttrs(id, name), approx: true }, generation ?? prompt))\n }\n\n const observe = (raw: unknown) => {\n try {\n const event = asRec(raw)\n if (!event) return\n const now = Date.now()\n events++\n firstEventAt ??= now\n const type = typeof event.type === 'string' ? event.type : ''\n const data = asRec(event.data)\n if (type === 'result') {\n const report = asRec(data?.firstTextPhases)\n const offsets = asRec(report?.phasesMs)\n if (offsets) {\n phases = {\n offsets,\n spans: Array.isArray(report?.spans) ? report.spans.slice(0, 64) : [],\n warm: typeof report?.harnessWarm === 'boolean' ? report.harnessWarm : null,\n ...(typeof report?.model === 'string' ? { model: report.model } : {}),\n }\n }\n return\n }\n if (type === 'tool_call' || type === 'tool.call') {\n const id = String(data?.id ?? data?.callId ?? data?.callID ?? data?.name ?? '')\n if (id) startTool(id, String(data?.name ?? data?.tool ?? 'tool'))\n return\n }\n if (type === 'tool_result' || type === 'tool.result') {\n const id = String(data?.id ?? data?.callId ?? data?.callID ?? data?.name ?? '')\n tools.get(id)?.end(undefined, data?.error || data?.status === 'error' ? 'tool_error' : undefined)\n return\n }\n if (type !== 'message.part.updated') return\n const part = asRec(data?.part)\n const partType = String(part?.type ?? '')\n if (partType === 'text' && firstTextAt === undefined && ((typeof data?.delta === 'string' && data.delta) || (typeof part?.text === 'string' && part.text))) {\n firstTextAt = now\n generation = prompt.child('sandbox.generation', 'model')\n } else if (partType === 'tool') {\n const id = String(part?.id ?? part?.callID ?? '')\n if (!id) return\n const state = asRec(part?.state)\n const status = String(state?.status ?? part?.status ?? '')\n const ranMs = (asNum(asRec(state?.time)?.end) ?? NaN) - (asNum(asRec(state?.time)?.start) ?? NaN)\n // OpenCode reports a tool part only once it finished, with the box's own start and end: the duration is the box's,\n // the end is when this side heard of it (the two clocks differ, so only the difference is used).\n if (!tools.has(id) && (status === 'completed' || status === 'error') && ranMs >= 0) {\n // A failed tool exports as failed, the same as one whose running part this side saw end in error.\n return void tools.set(id, trace.record('tool.call', 'tool', Math.max(startedAt, now - ranMs), now,\n toolAttrs(id, String(part?.tool ?? 'tool')), generation ?? prompt, status === 'error' ? 'tool_error' : undefined))\n }\n startTool(id, String(part?.tool ?? 'tool'))\n if (status === 'completed' || status === 'error') tools.get(id)?.end(undefined, status === 'error' ? 'tool_error' : undefined)\n }\n } catch {\n // Telemetry never fails a turn.\n }\n }\n\n const end = (error?: unknown) => {\n try {\n // A tool the stream never closed ended with the stream.\n for (const span of tools.values()) span.end({ 'tool.unclosed': true })\n generation?.end()\n if (phases && firstTextAt !== undefined) {\n const firstText = asNum(phases.offsets.first_text)\n // The sidecar's clock starts at `turn_received`; its first text frame is the one this side saw at `firstTextAt`.\n if (firstText !== undefined && firstTextAt - firstText >= startedAt) {\n const origin = firstTextAt - firstText\n prompt.record('sandbox.transit', 'sandbox', startedAt, origin, { note: 'sdk, api, orchestrator and host hops, both ways' })\n for (const raw of phases.spans) {\n const span = asRec(raw)\n const start = asNum(span?.startMs)\n const end = asNum(span?.endMs)\n if (typeof span?.name !== 'string' || !/^[a-zA-Z0-9_.-]{1,100}$/.test(span.name)\n || start === undefined || end === undefined || end < start || end > firstText) continue\n prompt.record(`sidecar.${span.name}`, 'sandbox', origin + start, origin + end)\n }\n let previous = 0\n for (const phase of PHASES) {\n const offset = asNum(phases.offsets[phase])\n if (offset === undefined || offset < previous) continue\n // The provider's first byte is model time; the harness steps before it are the box's.\n prompt.record(`sidecar.${phase}`, phase === 'first_upstream_byte' || phase === 'first_text' ? 'model' : 'sandbox', origin + previous, origin + offset)\n previous = offset\n }\n }\n }\n prompt.set({\n events,\n ...(firstEventAt !== undefined ? { first_event_ms: firstEventAt - startedAt } : {}),\n ...(firstTextAt !== undefined ? { first_text_ms: firstTextAt - startedAt } : {}),\n ...(phases?.warm !== null && phases?.warm !== undefined ? { 'sidecar.harness_warm': phases.warm } : {}),\n ...(phases?.model ? { 'sidecar.model': phases.model } : {}),\n ...Object.fromEntries(PHASES.flatMap((phase) => {\n const offset = asNum(phases?.offsets[phase])\n return offset === undefined ? [] : [[`sidecar.${phase}_ms`, Math.round(offset)]]\n })),\n })\n prompt.end(undefined, error)\n } catch {\n // Telemetry never fails a turn.\n }\n }\n\n return { observe, end }\n}\n\nexport interface TraceSandboxPromptOptions {\n trace: TurnTrace\n /** The span the prompt hangs from. Default: the trace's root. */\n parent?: TurnSpan\n /** Attributes for the `sandbox.prompt` span: the sandbox id, the model, the harness. */\n meta?: TurnSpanAttrs\n}\n\n/**\n * Pass a sandbox prompt stream through unchanged while recording it in the turn's trace (see {@link createPromptTrace}).\n * `streamSandboxPrompt` does this itself when given a `trace`; a product that calls `box.streamPrompt` directly wraps\n * its stream here, and sends `trace.traceId` as the prompt's `traceId` so the Sandbox API records join the turn.\n */\nexport async function* traceSandboxPromptEvents(events: AsyncIterable<unknown>, options: TraceSandboxPromptOptions): AsyncGenerator<unknown> {\n const prompt = createPromptTrace(options.trace, options.parent, options.meta ?? {})\n let failure: unknown\n try {\n for await (const event of events) {\n prompt.observe(event)\n yield event\n }\n } catch (error) {\n failure = error\n throw error\n } finally {\n prompt.end(failure)\n }\n}\n","/**\n * What isolates share about a running box: its id and the checks a reuse may\n * trust (see `ReuseChecks` in `./index`).\n *\n * A Worker request is not promised the isolate that served the last one. Legal's\n * sandbox lane, 8 consecutive turns, found no check from the turn\n * before in any of them, so a trust held only in isolate memory never opened. The\n * state is small and best effort, so it rides the Workers Cache API (one read at\n * the start of a reuse, a write only when a check changed); a miss costs the full\n * verification, as before.\n *\n * Nothing secret is stored: ids, times, and digests of the policy and the\n * runtime environment.\n */\n\nexport interface ReuseChecks {\n /** What tells one run of the box from the next (see `boxIdentity`). */\n identity: string\n /** When the exec probe last passed. */\n alive?: number\n /** The egress policy (normalized) the box was last read at or migrated to. */\n egress?: { key: string; at: number }\n /** The digest of the runtime environment last delivered to the box. */\n env?: { digest: string; at: number }\n /** The deferred corpus the box was last found to hold, by its hash. */\n corpus?: { hash: string; at: number }\n}\n\nexport interface SharedReuseState {\n boxId: string\n checks: ReuseChecks\n}\n\n/** Where isolates keep {@link SharedReuseState}, by box name. Failures are the caller's to swallow. */\nexport interface ReuseStateStore {\n load(name: string): Promise<SharedReuseState | null>\n save(name: string, state: SharedReuseState): Promise<void>\n drop(name: string): Promise<void>\n}\n\n/** The slice of a Workers `Cache` this store uses. */\nexport interface ReuseCacheLike {\n match(request: Request): Promise<Response | undefined>\n put(request: Request, response: Response): Promise<void>\n delete(request: Request): Promise<boolean>\n}\n\nconst CACHE_NAME = 'agent-app-sandbox-reuse'\nconst KEY_ORIGIN = 'https://sandbox-reuse.agent-app.invalid/'\n/** Longer than any check's trust, so the entry never outlives what it records by much. */\nconst ENTRY_MAX_AGE_SECONDS = 15 * 60\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction stamped(value: unknown, field: string): { text: string; at: number } | undefined {\n if (!isRecord(value) || typeof value.at !== 'number' || typeof value[field] !== 'string') return undefined\n return { text: value[field], at: value.at }\n}\n\n/** A stored value that is not exactly the shape this module writes is a miss. */\nfunction parseState(value: unknown): SharedReuseState | null {\n if (!isRecord(value) || typeof value.boxId !== 'string' || !isRecord(value.checks)) return null\n const checks = value.checks\n if (typeof checks.identity !== 'string') return null\n const parsed: ReuseChecks = { identity: checks.identity }\n if (typeof checks.alive === 'number') parsed.alive = checks.alive\n const egress = stamped(checks.egress, 'key')\n if (egress) parsed.egress = { key: egress.text, at: egress.at }\n const env = stamped(checks.env, 'digest')\n if (env) parsed.env = { digest: env.text, at: env.at }\n const corpus = stamped(checks.corpus, 'hash')\n if (corpus) parsed.corpus = { hash: corpus.text, at: corpus.at }\n return { boxId: value.boxId, checks: parsed }\n}\n\n/** A store over a Workers-style cache. The cache is opened on first use. */\nexport function createCacheReuseStore(open: () => Promise<ReuseCacheLike>): ReuseStateStore {\n // Only the resolved handle is kept across requests, never a promise still in flight.\n let cache: ReuseCacheLike | undefined\n const handle = async (): Promise<ReuseCacheLike> => (cache ??= await open())\n const request = (name: string) => new Request(`${KEY_ORIGIN}${encodeURIComponent(name)}`)\n return {\n async load(name) {\n const hit = await (await handle()).match(request(name))\n if (!hit) return null\n return parseState(await hit.json())\n },\n async save(name, state) {\n await (await handle()).put(request(name), new Response(JSON.stringify(state), {\n headers: { 'content-type': 'application/json', 'cache-control': `public, max-age=${ENTRY_MAX_AGE_SECONDS}` },\n }))\n },\n async drop(name) {\n await (await handle()).delete(request(name))\n },\n }\n}\n\n/** The runtime's own cache when it has one (a Worker does), else null. */\nexport function workersReuseStore(): ReuseStateStore | null {\n const storage = (globalThis as { caches?: { open?: (name: string) => Promise<ReuseCacheLike> } }).caches\n if (typeof storage?.open !== 'function') return null\n return createCacheReuseStore(() => storage.open!(CACHE_NAME))\n}\n","import { trimOrNull } from '../runtime/model'\n\n/** Define configuration options for resolving a provider and its model with optional API keys and routing details */\nexport interface ProviderResolutionConfig {\n routerBaseUrl?: string\n apiKey?: string\n providerName?: string\n modelName?: string\n defaultModel?: string\n openaiApiKey?: string\n // Opt-in: a resolvable provider+model WITHOUT an api key still yields model\n // metadata (model/provider/baseUrl, no apiKey) instead of undefined. Keyless\n // metadata makes the sandbox platform mint its OWN per-user router key at\n // create (its requiresRouterKey gate), so turns bill the box's billing owner\n // instead of a product-baked shared key. Requires an explicit providerName —\n // provider inference from key presence cannot fire keyless. Default false:\n // a keyless config resolves to undefined exactly as before.\n allowKeylessModel?: boolean\n // Name of a box environment variable holding the provider key: a stored\n // secret the box is created with. Caller-owned auth by reference, so the\n // platform mints no Router key and the key value never passes through the\n // app. A raw `apiKey` (config or per-turn) takes precedence.\n apiKeyEnv?: string\n // `cli`: the harness CLI owns provider resolution and auth (OpenCode's own\n // provider catalog, e.g. a free model), so the platform mints no Router key\n // and injects no managed credential. Sent as `backend.model.mode`.\n mode?: 'api' | 'cli'\n}\n\n/** Represent a fully configured model with optional API key and base URL for sandbox platform integration */\n/**\n * Spread a {@link ResolvedModel} onto a sandbox backend config as the nested\n * `model` object, the only spelling the SDK, wire and Sandbox API carry since\n * agent-container b6b2f326 deleted the flat fields and their fold: SDK 1.0.128+\n * drops a flat `modelId` from every turn.\n */\nexport function backendModelFields(model: ResolvedModel): {\n model: { model: string; provider: string; apiKey?: string; apiKeyEnv?: string; baseUrl?: string; mode?: 'api' | 'cli' };\n} {\n return { model: {\n model: model.model,\n provider: model.provider,\n ...(model.apiKey !== undefined ? { apiKey: model.apiKey } : {}),\n ...(model.apiKeyEnv !== undefined ? { apiKeyEnv: model.apiKeyEnv } : {}),\n ...(model.baseUrl !== undefined ? { baseUrl: model.baseUrl } : {}),\n ...(model.mode !== undefined ? { mode: model.mode } : {}),\n } }\n}\n\nexport interface ResolvedModel {\n model: string\n provider: string\n // Omitted only under `allowKeylessModel` — keyless metadata tells the\n // sandbox platform to mint its own per-user router key for the box.\n apiKey?: string\n /** A stored-secret reference standing in for `apiKey`; see {@link ProviderResolutionConfig.apiKeyEnv}. */\n apiKeyEnv?: string\n baseUrl?: string\n /** See {@link ProviderResolutionConfig.mode}. */\n mode?: 'api' | 'cli'\n}\n\n/**\n * Why a model failed to resolve into something transportable to the sandbox\n * platform. `no_provider` — a model id exists but no provider name could be\n * derived (no explicit `providerName`, and no key present to infer one from).\n * `no_api_key` — a provider AND model both resolved, but no credential is\n * configured and the caller did not opt into `allowKeylessModel`.\n */\nexport type ModelSelectionError = 'no_provider' | 'no_api_key'\n\n/**\n * Which precedence slot supplied the failed/succeeded model id:\n * `override` — the caller's per-turn `{ model }` argument.\n * `config` — `provider.modelName`.\n * `default` — `provider.defaultModel` (only ever consulted for an\n * openai/openai-compat provider shape).\n */\nexport type ModelSelectionSource = 'override' | 'config' | 'default'\n\n/**\n * A model id was named (by override, config, or default) but is not\n * transportable to the sandbox platform. Carries enough to explain WHY\n * without the caller re-deriving the override/config/default precedence\n * chain itself (that re-derivation is how gtm-agent#665 happened — a caller\n * guessed loudness from the wrong slot and dropped a user-selected model).\n */\nexport type ModelSelectionFailure =\n | { succeeded: false; error: 'no_provider'; model: string; source: ModelSelectionSource }\n | {\n succeeded: false\n error: 'no_api_key'\n model: string\n provider: string\n source: ModelSelectionSource\n }\n\n/**\n * The three-state outcome of resolving a model: `{ succeeded: true, value:\n * undefined }` means NOTHING was requested (the legitimate box-default\n * configuration — not an error); `{ succeeded: true, value: ResolvedModel }`\n * means a fully transportable model resolved; anything else is a\n * {@link ModelSelectionFailure} — a model WAS named but can't be sent.\n */\nexport type ModelSelection =\n | { succeeded: true; value: ResolvedModel | undefined }\n | ModelSelectionFailure\n\n/**\n * Resolve a provider + model configuration into a typed three-state outcome\n * that separates \"nothing requested\" from \"something requested but\n * untransportable\" — the distinction {@link resolveModel} collapses and the\n * one that caused gtm-agent#665 (a validated user-selected model silently\n * dropped, box default substituted, durable row still recording the user's\n * choice).\n *\n * Precedence (identical to the legacy `resolveModel`, byte-for-byte):\n * provider is computed first (`providerName`, else inferred `openai-compat`\n * from a present key, else inferred `openai` from a present\n * `openaiApiKey`, else unresolved); the model id is `override.model` else\n * `config.modelName` else — ONLY when the provider is `openai` or\n * `openai-compat` — `config.defaultModel`; the api key is\n * `override.modelApiKey` else `config.apiKey` else — only for provider\n * `openai` — `config.openaiApiKey`.\n *\n * Two behavioral deltas from the legacy function:\n * 1. Every string field (`routerBaseUrl`, `apiKey`, `providerName`,\n * `modelName`, `defaultModel`, `openaiApiKey`, `override.model`,\n * `override.modelApiKey`) is normalized through {@link trimOrNull} first,\n * so `''` (and whitespace-only strings) are treated as absent instead of\n * poisoning the `??` precedence chain — the issue's second stated defect.\n * This also means a value is trimmed (`' gpt-5 '` resolves to `'gpt-5'`).\n * 2. The outcome is three-state instead of collapsing to `undefined`: no\n * model derivable from any slot → `{ succeeded: true, value: undefined }`\n * (still the legitimate \"let the box pick its own default\" case, NOT an\n * error); a model id resolved but no provider could be derived → a\n * `no_provider` failure; a model + provider resolved but no api key (and\n * `allowKeylessModel` was not set) → a `no_api_key` failure. Both failure\n * arms carry `source` so a caller can apply a loudness policy without\n * re-deriving which precedence slot supplied the model.\n */\nexport function resolveModelSelection(\n config: ProviderResolutionConfig | undefined,\n override?: { model?: string; modelApiKey?: string },\n): ModelSelection {\n const c = config ?? {}\n const explicitBaseUrl = trimOrNull(c.routerBaseUrl)\n const explicitApiKey = trimOrNull(override?.modelApiKey) ?? trimOrNull(c.apiKey)\n const providerName = trimOrNull(c.providerName)\n const openaiApiKey = trimOrNull(c.openaiApiKey)\n const provider =\n providerName ?? (explicitApiKey ? 'openai-compat' : openaiApiKey ? 'openai' : undefined)\n\n const overrideModel = trimOrNull(override?.model)\n const configModel = trimOrNull(c.modelName)\n const defaultModel = trimOrNull(c.defaultModel)\n const modelName =\n overrideModel ??\n configModel ??\n (provider === 'openai' || provider === 'openai-compat' ? defaultModel : null)\n\n if (!modelName) return { succeeded: true, value: undefined }\n\n const source: ModelSelectionSource = overrideModel ? 'override' : configModel ? 'config' : 'default'\n\n if (!provider) return { succeeded: false, error: 'no_provider', model: modelName, source }\n\n const apiKey = explicitApiKey ?? (provider === 'openai' ? openaiApiKey : undefined)\n const apiKeyEnv = apiKey ? null : trimOrNull(c.apiKeyEnv)\n if (!apiKey && !apiKeyEnv && !c.allowKeylessModel) {\n return { succeeded: false, error: 'no_api_key', model: modelName, provider, source }\n }\n\n return {\n succeeded: true,\n value: {\n model: modelName,\n provider,\n ...(apiKey ? { apiKey } : apiKeyEnv ? { apiKeyEnv } : {}),\n ...(explicitBaseUrl ? { baseUrl: explicitBaseUrl } : {}),\n ...(c.mode ? { mode: c.mode } : {}),\n },\n }\n}\n\n/**\n * Resolve and return the appropriate model configuration based on provider\n * settings and optional overrides.\n *\n * Migration note (intentionally NOT tagged `@deprecated`): this is a thin,\n * source-compatible wrapper over {@link resolveModelSelection} that collapses\n * its three-state outcome back down to `ResolvedModel | undefined`, exactly\n * as before. It stays correct for the common case (no explicit model requested, or a\n * fully-transportable one), but it CANNOT distinguish \"nothing was\n * requested\" from \"a named model could not be transported\" — the ambiguity\n * that caused gtm-agent#665. Prefer {@link resolveModelSelection} directly,\n * or {@link requireTransportableModel} for the fail-loud-on-explicit-model\n * policy the internal sandbox callers use. Not tagged `@deprecated`: it\n * remains the correct call for a caller that never sets an explicit\n * override and only wants \"the box's default is fine\" semantics; a hard\n * deprecation is a later-major decision, not this fix's.\n *\n * The only behavior change on this entry point versus before is the\n * empty-string bugfix that comes free through delegation (issue #302's\n * second defect) — every signature and the `undefined` return semantics are\n * unchanged.\n */\nexport function resolveModel(\n config: ProviderResolutionConfig | undefined,\n override?: { model?: string; modelApiKey?: string },\n): ResolvedModel | undefined {\n const selection = resolveModelSelection(config, override)\n return selection.succeeded ? selection.value : undefined\n}\n\n/**\n * Thrown by {@link requireTransportableModel} when a model that was\n * EXPLICITLY requested via a per-turn `{ model }` override cannot be\n * transported to the sandbox platform. The message names the model, which\n * precedence slot supplied it, what's missing, and the fix, and states\n * plainly that the requested model was NOT sent to the box (the failure mode\n * this error exists to make impossible to miss — gtm-agent#665 silently\n * substituted the box default instead of a user-selected model).\n *\n * The error class itself carries no opinion about *when* it should be\n * thrown — it is constructed from any {@link ModelSelectionFailure},\n * regardless of `source`. A caller wanting a stricter policy (e.g. also\n * fail-loud on an untransportable configured `provider.modelName`) can call\n * {@link resolveModelSelection} directly and throw this itself.\n */\nexport class SandboxModelResolutionError extends Error {\n readonly code: ModelSelectionError\n readonly model: string\n readonly provider?: string\n readonly source: ModelSelectionSource\n\n constructor(failure: ModelSelectionFailure, context: string) {\n const missing =\n failure.error === 'no_provider'\n ? 'no provider could be resolved for it'\n : `provider \"${failure.provider}\" resolved but no API key is configured`\n const fix =\n failure.error === 'no_provider'\n ? 'set providerName explicitly (provider cannot be inferred without one)'\n : 'set apiKey (or openaiApiKey when provider is \"openai\"), or pass allowKeylessModel:true to mint a keyless box'\n super(\n `${context}: model \"${failure.model}\" (from ${failure.source}) is not transportable — ` +\n `${missing}. Fix: ${fix}. The requested model was NOT sent to the box.`,\n )\n this.name = 'SandboxModelResolutionError'\n this.code = failure.error\n this.model = failure.model\n if (failure.error === 'no_api_key') this.provider = failure.provider\n this.source = failure.source\n }\n}\n\n/**\n * Shared fail-loud policy for the sandbox platform's three internal model\n * callers (`ensureWorkspaceSandbox`'s `backendModelAtCreate`,\n * `streamSandboxPrompt`, `driveSandboxTurn`): a `ModelSelection` in, a plain\n * `ResolvedModel | undefined` out, so downstream code is unchanged from\n * before this fix.\n *\n * The policy: success delegates straight through. A failure whose `source`\n * is `'override'` means a PER-TURN model was explicitly selected THIS turn\n * (a live, user-driven choice — passed as `{ model }`) and could not be\n * sent; substituting the box default there is exactly the gtm-agent#665\n * defect, so it throws {@link SandboxModelResolutionError} rather than\n * silently falling back.\n *\n * A failure whose `source` is `'config'` or `'default'` means a\n * *configured* `provider.modelName` / `provider.defaultModel` couldn't\n * resolve — nobody made a choice this turn; the value came from board\n * config that may simply describe \"the platform supplies the credential.\"\n * Shipped consumers rely on exactly that: tax-agent ships a shell with\n * `provider: { providerName: 'openai-compat', modelName, routerBaseUrl }`\n * and no `apiKey`/`allowKeylessModel`, with a contract test asserting\n * `ensureWorkspaceSandbox` creation SUCCEEDS with the model silently\n * dropped so the sandbox platform mints its own in-container credential\n * (`apps/web/tests/sandbox-service-contract.test.ts`). A config-loud policy\n * here would break every fresh tax sandbox provisioning and every tax turn.\n * So both `'config'` and `'default'` keep the pre-#302 logged-skip\n * behavior: `console.error` and drop, letting the box use its own default.\n * A product wanting strict enforcement of a configured `provider.modelName`\n * can call {@link resolveModelSelection} directly and apply its own policy.\n */\nexport function requireTransportableModel(\n selection: ModelSelection,\n context: string,\n): ResolvedModel | undefined {\n if (selection.succeeded) return selection.value\n if (selection.source === 'override') {\n throw new SandboxModelResolutionError(selection, context)\n }\n const reason =\n selection.error === 'no_api_key'\n ? `provider \"${selection.provider}\" has no api key`\n : 'no provider resolved'\n if (selection.source === 'config') {\n console.error(\n `[sandbox] ${context}: dropping configured provider.modelName \"${selection.model}\" (${reason}); ` +\n `the box will use its own default model — set allowKeylessModel:true to bake a keyless model, or configure an api key`,\n )\n } else {\n console.error(\n `[sandbox] ${context}: dropping provider.defaultModel \"${selection.model}\" (${reason}); using the box default`,\n )\n }\n return undefined\n}\n","/** Define the shape of a workspace sandbox instance including its connection details and status. */\nexport interface WorkspaceSandboxInstanceLike {\n id: string\n name?: string\n status?: string\n connection?: {\n runtimeUrl?: string\n sidecarUrl?: string\n authToken?: string\n sidecarToken?: string\n authTokenExpiresAt?: string\n } | null\n}\n\n/** Define the context containing workspace and user identifiers for sandbox environment operations. */\nexport interface WorkspaceSandboxEnsureContext {\n workspaceId: string\n userId: string\n}\n\n/** Define configuration options for managing workspace sandboxes. */\nexport interface WorkspaceSandboxManagerOptions<TClient, TBox extends WorkspaceSandboxInstanceLike, TEnsureOptions = void> {\n getClient: (ctx: WorkspaceSandboxEnsureContext) => Promise<TClient> | TClient\n nameForWorkspace: (workspaceId: string, ctx: WorkspaceSandboxEnsureContext) => string\n listSandboxes: (client: TClient, ctx: WorkspaceSandboxEnsureContext) => Promise<TBox[]>\n createSandbox: (args: {\n client: TClient\n ctx: WorkspaceSandboxEnsureContext\n name: string\n options: TEnsureOptions\n listError?: unknown\n }) => Promise<TBox>\n waitForRunning?: (box: TBox, ctx: WorkspaceSandboxEnsureContext) => Promise<void>\n prepareExisting?: (box: TBox, ctx: WorkspaceSandboxEnsureContext, options: TEnsureOptions) => Promise<TBox | void>\n prepareCreated?: (box: TBox, ctx: WorkspaceSandboxEnsureContext, options: TEnsureOptions) => Promise<TBox | void>\n onListError?: (error: unknown, ctx: WorkspaceSandboxEnsureContext) => void\n}\n\n/** Manage workspace sandboxes by ensuring their creation and retrieval for specified users. */\nexport interface WorkspaceSandboxManager<TBox extends WorkspaceSandboxInstanceLike, TEnsureOptions = void> {\n ensureWorkspaceSandbox: (\n workspaceId: string,\n userId: string,\n options?: TEnsureOptions,\n ) => Promise<TBox>\n}\n\n/**\n * Create a generic name-keyed sandbox lifecycle manager for products that\n * drive their own SDK or box types.\n */\nexport function createWorkspaceSandboxManager<TClient, TBox extends WorkspaceSandboxInstanceLike, TEnsureOptions = void>(\n opts: WorkspaceSandboxManagerOptions<TClient, TBox, TEnsureOptions>,\n): WorkspaceSandboxManager<TBox, TEnsureOptions> {\n return {\n async ensureWorkspaceSandbox(workspaceId, userId, options) {\n if (!workspaceId) throw new Error('workspaceId is required')\n if (!userId) throw new Error('userId is required')\n const ctx = { workspaceId, userId }\n const client = await opts.getClient(ctx)\n const name = opts.nameForWorkspace(workspaceId, ctx)\n let listError: unknown\n let existing: TBox[] = []\n\n try {\n existing = await opts.listSandboxes(client, ctx)\n } catch (err) {\n listError = err\n opts.onListError?.(err, ctx)\n }\n\n const found = existing.find((box) => box.name === name)\n if (found) {\n return (await opts.prepareExisting?.(found, ctx, options as TEnsureOptions)) ?? found\n }\n\n const created = await opts.createSandbox({\n client,\n ctx,\n name,\n options: options as TEnsureOptions,\n listError,\n })\n await opts.waitForRunning?.(created, ctx)\n return (await opts.prepareCreated?.(created, ctx, options as TEnsureOptions)) ?? created\n },\n }\n}\n","/**\n * Browser-direct scoped-token terminal connection route (#341/#349).\n *\n * Epic #343 / decision #341: the fleet's terminal transport is browser-direct\n * — the product's server authenticates the request and provisions/resolves\n * the sandbox exactly once, mints a short-lived SDK scoped token\n * (`box.mintScopedToken`), and hands the browser just enough to connect\n * `TerminalView` straight to the sidecar. No worker relays terminal bytes.\n * The deprecated same-origin relay was removed in #350 after the fleet\n * migrated, leaving this as the package's only terminal transport.\n *\n * VERIFIED PLATFORM CONTRACT (`@tangle-network/sandbox` 0.15.2 + the\n * orchestrator/sidecar enforcement source):\n *\n * 1. Only a `scope: 'session-runtime'` token carries the `terminal`\n * capability (`cap: [\"read\", \"workspace\", \"terminal\"]`). `'project'` and\n * `'session'` mint SessionGateway READ tokens (HS256, `typ: \"read\"`, no\n * `cap` claim at all — a different token family the sidecar rejects\n * outright); `'read-only'` carries `cap: [\"read\"]` only. **No scope other\n * than `'session-runtime'` can ever open a terminal**, which is why this\n * route no longer takes `scope` as a parameter — it is pinned.\n * 2. The orchestrator's terminal WS gate fails closed unless the token's\n * `sid` claim EQUALS the `<connectionId>` path segment of\n * `/terminals/<connectionId>/ws`\n * (`verifyScopedSidecarCapability(sidecar, token, \"terminal\", connectionId)`).\n * So `mintScopedToken({ scope: 'session-runtime', sessionId })` MUST be\n * called with `sessionId === connectionId` — the exact id `TerminalView`\n * will dial. That is why this route threads a `connectionId` end to end\n * instead of deriving its own session id.\n * 3. The browser-safe terminal base is the mint result's `sidecarProxyUrl`\n * (`/v1/sidecar-proxy/{id}` on the Sandbox API) — **not**\n * `box.connection.runtimeUrl`. The SDK's own `_attachTerminal` is the\n * reference implementation:\n * `mintScopedToken({ scope: 'session-runtime', sessionId: connectionId })`\n * then dial `${scoped.sidecarProxyUrl}/terminals/${connectionId}/ws`.\n * Pointing `TerminalView` at `runtimeUrl` fails auth regardless of scope —\n * only the sidecar-proxy hop decodes the browser's\n * `bearer.<base64url>` WS subprotocol.\n *\n * HISTORICAL NOTE: an earlier shape of this route (and legal-agent's\n * production route it was modeled on, `scope: 'project'` +\n * `connection.runtimeUrl`) predates the platform's terminal-auth hardening —\n * the terminal capability gate, the scoped-token terminal WS\n * path, and the `sid`-binding fail-closed check.\n * That shape does not authenticate on the current platform\n * and is not a valid spec for the token path anymore.\n *\n * SECURITY POSTURE: unlike the read-only session-gateway streaming token\n * (`box.mintScopedToken({scope:'session'})` paired with\n * `SessionGatewayClient`), the token this route mints grants **command\n * execution** in the sandbox once handed to `TerminalView`. Its safety rests\n * on a **short TTL** (default 15 minutes, the SDK's own max — still a caller\n * parameter) and, structurally, the narrowest scope the platform offers: one\n * box (`ensureSandbox` resolved it for THIS user), one terminal connection\n * (`session-runtime` bound to a single `sid`). Widening the TTL default\n * without an explicit reason is a security regression, not a convenience.\n *\n * Wire contract: the browser passes the response's `sidecarUrl` as\n * `TerminalView`'s `apiUrl` prop, `token` as its token prop, and the\n * response's echoed `connectionId` as `TerminalView`'s `connectionId` prop —\n * the token's `sid` is bound to exactly that id, so any other value fails the\n * WS upgrade. sandbox-ui sends the token as a `bearer.<base64url>` WebSocket\n * subprotocol (browsers cannot set `Authorization` on a WS handshake).\n * `useSandboxTerminalConnection` (`../web-react/sandbox-terminal`) carries\n * `connectionId` through automatically.\n */\n\n/** The structural surface this route needs from an SDK sandbox box — no `@tangle-network/sandbox` class import (invariant 3). */\nexport interface TerminalConnectionBoxLike {\n id: string\n status?: string\n connection?: { runtimeUrl?: string }\n mintScopedToken(opts: {\n scope: string\n sessionId?: string\n ttlMinutes?: number\n }): Promise<{ token: string; expiresAt: Date; sidecarProxyUrl: string }>\n}\n\n/** Configuration for {@link createSandboxTerminalConnectionRoute}. */\nexport interface SandboxTerminalConnectionRouteOptions<TBox extends TerminalConnectionBoxLike, TUser> {\n /**\n * Authenticate the incoming request. Return the authenticated user, or a\n * `Response` to short-circuit the route (e.g. a 401) — that Response is\n * returned to the caller verbatim.\n */\n requireUser(request: Request): Promise<TUser | Response>\n /**\n * Resolve (provisioning if needed) the sandbox this user's terminal should\n * connect to. Domain-specific provisioning (workspace- vs user-scoped,\n * naming, reuse) stays entirely in the product's implementation of this\n * seam — the route only reacts to success/failure.\n */\n ensureSandbox(user: TUser, request: Request): Promise<TBox>\n /** `box.mintScopedToken` TTL in minutes. Default `15` (the SDK's own max). */\n ttlMinutes?: number\n /**\n * Resolve the terminal connection id the minted token's `sid` is bound to\n * — this MUST be the same id `TerminalView` dials\n * (`tabTerminalConnectionId()`), because the orchestrator's terminal WS\n * gate fails closed unless `sid === <connectionId>` in\n * `/terminals/<connectionId>/ws`.\n *\n * `requested` is `new URL(request.url).searchParams.get('connectionId')`.\n * The default resolver returns `requested` unchanged. A product may\n * validate/namespace the id here (e.g. a per-user prefix in a shared box)\n * — if it rewrites the id, the client MUST use the response's echoed\n * `connectionId`, since the sid binding makes any other id fail the WS\n * upgrade.\n *\n * A resolved falsy/empty value fails the request with a 400 before any\n * sandbox work happens.\n */\n resolveConnectionId?: (ctx: {\n request: Request\n user: TUser\n box: TBox\n requested: string | null\n }) => string | null | undefined | Promise<string | null | undefined>\n}\n\nconst DEFAULT_TTL_MINUTES = 15\nconst TERMINAL_SCOPE = 'session-runtime'\n\nfunction defaultResolveConnectionId(ctx: { requested: string | null }): string | null {\n return ctx.requested\n}\n\n/**\n * Build the browser-direct terminal connection route: `GET` handler that\n * authenticates, resolves the sandbox, mints a scoped token pinned to\n * `scope: 'session-runtime'` (the ONLY scope the platform grants the\n * `terminal` capability to), and returns exactly what the browser needs to\n * connect `TerminalView` directly to the sidecar — no worker in the data\n * path once the terminal is open.\n *\n * Response shapes:\n * - `requireUser` returns a `Response` → that `Response`, verbatim.\n * - `ensureSandbox` throws → `500 {error}` (the thrown message surfaced).\n * - `box.connection?.runtimeUrl` missing → `503 {error, status: box.status}`\n * — this is a READINESS gate only; the URL returned to the client on\n * success is always the mint's `sidecarProxyUrl`, never `runtimeUrl`.\n * - resolved connection id is falsy/empty → `400 {error}`.\n * - `box.mintScopedToken` rejects → `503 {error}`.\n * - success → `200 {sidecarUrl, token, expiresAt, status, sandboxId, connectionId}`.\n * `connectionId` is the id the token's `sid` is bound to — the client MUST\n * hand this (not its own) to `TerminalView`.\n */\nexport function createSandboxTerminalConnectionRoute<TBox extends TerminalConnectionBoxLike, TUser>(\n opts: SandboxTerminalConnectionRouteOptions<TBox, TUser>,\n): (request: Request) => Promise<Response> {\n const resolveConnectionId = opts.resolveConnectionId ?? defaultResolveConnectionId\n\n return async function handleSandboxTerminalConnection(request: Request): Promise<Response> {\n const user = await opts.requireUser(request)\n if (user instanceof Response) return user\n\n let box: TBox\n try {\n box = await opts.ensureSandbox(user, request)\n } catch (err) {\n return Response.json(\n { error: err instanceof Error ? err.message : 'Failed to provision sandbox' },\n { status: 500 },\n )\n }\n\n const runtimeUrl = box.connection?.runtimeUrl\n if (!runtimeUrl) {\n return Response.json(\n {\n error: 'Sandbox runtime not ready. The sandbox is still initializing -- retry in a few seconds.',\n status: box.status,\n },\n { status: 503 },\n )\n }\n\n const requested = new URL(request.url).searchParams.get('connectionId')\n const connectionId = await resolveConnectionId({ request, user, box, requested })\n if (!connectionId) {\n return Response.json(\n {\n error:\n \"connectionId is required — pass the same id TerminalView dials (tabTerminalConnectionId()) as the 'connectionId' query parameter\",\n },\n { status: 400 },\n )\n }\n\n let scoped: { token: string; expiresAt: Date; sidecarProxyUrl: string }\n try {\n scoped = await box.mintScopedToken({\n scope: TERMINAL_SCOPE,\n ttlMinutes: opts.ttlMinutes ?? DEFAULT_TTL_MINUTES,\n sessionId: connectionId,\n })\n } catch (err) {\n return Response.json(\n { error: err instanceof Error ? err.message : 'Failed to mint sandbox token' },\n { status: 503 },\n )\n }\n\n return Response.json({\n sidecarUrl: scoped.sidecarProxyUrl,\n token: scoped.token,\n expiresAt: scoped.expiresAt.toISOString(),\n status: box.status,\n sandboxId: box.id,\n connectionId,\n })\n }\n}\n","/**\n * `createSandboxPrewarmer` — \"this user just opened this project; start warming\n * their box\" as a shell primitive, so every agent-app product gets the same\n * answer instead of forking one.\n *\n * WHY THIS IS SHELL, NOT ENGINE. The engine rule asks whether the capability\n * makes sense without a specific app's side channel. \"Warm a box\" does — but\n * `@tangle-network/sandbox` has no notion of a WORKSPACE. It keys boxes by an\n * opaque sandbox id; the workspace→box mapping, the harness match, and the\n * profile materialisation all live in `ensureWorkspaceSandbox` here. A\n * prewarmer is that mapping plus a scheduling policy, so it belongs beside it.\n * It is deliberately NOT a new subpath: it composes `peekWorkspaceSandbox` and\n * `ensureWorkspaceSandbox` directly and needs exactly the peers `/sandbox`\n * already needs, so a separate entry would add a second place to look for \"how\n * do I get a box\" and buy no peer isolation (the reason `/work-product-react`\n * is split out).\n *\n * WHAT IT IS NOT. It does not make cold starts fast — they already are.\n * Measured on the real platform (staging-sandbox, n=5): a box goes\n * from nothing to terminal-ready in 2.34–3.19 s (median 2.73 s), and an\n * already-running box answers in 1.16–2.29 s (median 1.35 s). Prewarming buys\n * ~1.4 s. The reason it matters is not latency: it is that a product which\n * only ever provisions lazily, on a path whose guard never passes, never\n * provisions AT ALL — and the UI then shows a spinner over a box that does not\n * exist and is not being created. That is the failure this primitive removes.\n *\n * ── COST POSTURE (read before adopting) ────────────────────────────────────\n * A warmed box is a REAL charge. It bills from creation until the platform's\n * idle timeout reclaims it — `SandboxRuntimeConfig`'s create-time\n * `idleTimeoutSeconds`, not anything this module sets. A product warming on\n * every project open pays that timeout for every user who opens and bounces.\n * With a 3600 s idle timeout against a ~131 s mean session life, a bounce\n * costs an hour of box time to save ~1.4 s. THAT TRADE IS USUALLY WRONG.\n *\n * So the levers are explicit and the defaults are the cheap ones:\n * - `mode: 'resume-only'` (DEFAULT) never creates a box that does not exist.\n * It only revives one the user already has, so the spend is bounded by\n * boxes the user already caused. This is the safe fleet default.\n * - `mode: 'create-or-resume'` is the owner-requested behaviour — warm on\n * open even for a first-time user. Opt in per product, and lower the\n * shell's `idleTimeoutSeconds` when you do.\n * - `shouldPrewarm(scope)` is the product's own policy hook (paid tier only,\n * returning user only, has-documents only …). Returning false costs nothing.\n * - `failureCooldownMs` stops a hard-failing workspace from retry-storming;\n * every retry is another create attempt, which is more spend.\n * Warm with the SAME harness the next turn will use. `ensureWorkspaceSandbox`\n * DELETES and recreates a name-matched box whose harness differs, so warming\n * `opencode` and then turning `claude-code` pays for two boxes and is slower\n * than not warming at all. The prewarm key includes the harness so the two are\n * never deduped into one.\n *\n * ── SINGLE-FLIGHT (measured, not assumed) ──────────────────────────────────\n * The sandbox platform does NOT dedupe by box name. Two concurrent\n * `POST /v1/sandboxes` with an identical name both returned HTTP 201 and left\n * two running boxes (verified against staging-sandbox). So two\n * tabs, or two isolates, racing a warm genuinely leak a box — a prewarm that\n * races is worse than no prewarm. Hence two layers:\n * 1. an in-process map, which is free and catches same-isolate races\n * (double-mount, two requests on one isolate);\n * 2. a `claim` store the product supplies, which is the only thing that can\n * make this correct ACROSS isolates — the usual deployment target here is\n * Cloudflare Workers, where \"same isolate\" guarantees nothing.\n * `claim` is REQUIRED, with `'single-isolate-only'` as the explicit opt-out,\n * so nobody gets the unsafe behaviour by forgetting a field. Say it out loud\n * or supply a store.\n *\n * ── FAILURE IS LOUD, NEVER FATAL ───────────────────────────────────────────\n * A failed warm degrades to exactly today's lazy path: the next real request\n * calls `ensureWorkspaceSandbox` itself. It never throws into the caller's\n * render path — `completion` RESOLVES with `{ ok: false }` rather than\n * rejecting, because an unhandled rejection handed to `waitUntil` can fail the\n * request it rode in on. But it is never silent: every failure fires\n * `onEvent({ type: 'failed' })` and is readable afterwards through\n * `readiness()` as `{ status: 'failed' }`. The bug class this whole module\n * exists to kill is a soft failure that surfaces as an unusable panel ten\n * minutes later, so a warm that dies must leave a trace a product can render.\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox/core'\nimport type { Harness } from '../harness/index'\nimport {\n ensureWorkspaceSandbox,\n peekWorkspaceSandbox,\n type SandboxRuntimeConfig,\n} from './index'\n\n/** The workspace a warm targets. Mirrors `EnsureWorkspaceSandboxOptions`'\n * identity fields — the prewarmer forwards them verbatim so a warmed box is\n * byte-identical to the one the lazy path would have built. */\nexport interface SandboxPrewarmScope {\n workspaceId: string\n userId?: string\n /** Must match the harness the next turn will use — see the cost note above. */\n harness: Harness\n billingOwnerId?: string\n}\n\n/**\n * Cross-isolate claim. `acquire` must be atomic (a D1 conditional insert, a DO,\n * a KV `put` with `onlyIf`) — a read-then-write is exactly the race this exists\n * to close. `ttlSeconds` bounds a claim leaked by an isolate that died\n * mid-warm; without expiry a single crash wedges a workspace forever.\n */\nexport interface PrewarmClaimStore {\n /** True when THIS caller now owns the right to warm `key`. */\n acquire(key: string, ttlSeconds: number): Promise<boolean>\n /** Best-effort release. A throw here is swallowed — the TTL is the backstop. */\n release(key: string): Promise<void>\n /** Optional: lets `readiness()` report `warming` for a warm running in\n * ANOTHER isolate. Without it, `warming` is only visible in the isolate\n * that started it, and every other one reports `absent`. */\n isHeld?(key: string): Promise<boolean>\n}\n\n/**\n * The ownership proof for one foreground provisioning attempt.\n *\n * `expiresAt` is both the lease deadline and its fencing value. The D1 store\n * advances it when a takeover succeeds, so an expired owner cannot release a\n * successor's lease. Keep this object and pass it back unchanged to\n * `FencedPrewarmClaimStore.releaseLease`.\n */\nexport interface PrewarmClaimLease {\n readonly key: string\n readonly expiresAt: number\n}\n\n/** State needed by a foreground caller that waits for another isolate. */\nexport type PrewarmClaimState =\n | { status: 'held'; expiresAt: number }\n | { status: 'expired'; expiresAt: number }\n | { status: 'absent' }\n\n/** A claim store that can distinguish a completed owner from a crashed owner. */\nexport interface InspectablePrewarmClaimStore extends PrewarmClaimStore {\n isHeld(key: string): Promise<boolean>\n inspect(key: string): Promise<PrewarmClaimState>\n}\n\n/**\n * Fenced claim operations for foreground provisioning.\n *\n * This is separate from `PrewarmClaimStore` so the published boolean\n * `acquire` and key-only `release` methods remain source-compatible. A\n * foreground caller must use the lease returned here and release that lease,\n * not the legacy key-only method.\n */\nexport interface FencedPrewarmClaimStore extends InspectablePrewarmClaimStore {\n /** Atomically acquire a lease or return null when another live lease wins. */\n acquireLease(key: string, ttlSeconds: number): Promise<PrewarmClaimLease | null>\n /** Conditionally release only this lease. A stale lease is a no-op. */\n releaseLease(lease: PrewarmClaimLease): Promise<void>\n}\n\n/** What `prewarm()` decided. Every value except `started` means no box was\n * created and nothing was spent on this call. */\nexport type PrewarmOutcome =\n | 'started'\n | 'already-running'\n | 'already-warming'\n | 'warming-elsewhere'\n | 'declined-by-policy'\n | 'cooling-down'\n | 'absent-and-resume-only'\n\n/** Terminal result of a warm this caller owns. Never a rejection. */\nexport interface PrewarmResult {\n ok: boolean\n boxId?: string\n error?: string\n /** Wall time of the warm itself, for the product's own timing trace. */\n ms: number\n}\n\nexport interface PrewarmDecision {\n outcome: PrewarmOutcome\n /** Present ONLY when `outcome === 'started'`. Hand it to `ctx.waitUntil` so a\n * client disconnect cannot kill the warm. Never rejects. */\n completion?: Promise<PrewarmResult>\n}\n\n/** Readiness for the UI. `ready`/`warming` reuse the vocabulary\n * `createSandboxFileIndexRoute` (`/chat-routes`) and `useFileMentions`\n * (`/web-react`) already speak, so a product renders ONE warming state rather\n * than inventing a second spinner for boxes. */\nexport type SandboxReadiness =\n | { status: 'ready'; boxId: string }\n | { status: 'warming' }\n | { status: 'absent' }\n | { status: 'failed'; error: string; retryAfterMs: number }\n\nexport type PrewarmEvent =\n | { type: 'started'; key: string; workspaceId: string }\n | { type: 'succeeded'; key: string; workspaceId: string; boxId: string; ms: number }\n | { type: 'failed'; key: string; workspaceId: string; error: string; ms: number }\n | { type: 'skipped'; key: string; workspaceId: string; outcome: PrewarmOutcome }\n\nexport interface SandboxPrewarmerOptions {\n /** Cross-isolate single-flight, or the explicit acknowledgement that you are\n * accepting per-isolate dedupe only. No default — see the header. */\n claim: PrewarmClaimStore | 'single-isolate-only'\n /** `'resume-only'` (default) never creates a box that does not exist.\n * `'create-or-resume'` warms from nothing — the expensive one. */\n mode?: 'resume-only' | 'create-or-resume'\n /** Product policy gate. Not called when a box is already running. */\n shouldPrewarm?(scope: SandboxPrewarmScope): boolean | Promise<boolean>\n /** Observability seam. A failed warm MUST be visible somewhere. */\n onEvent?(event: PrewarmEvent): void\n /** Claim lifetime. Default 180 s — comfortably over a cold create. */\n claimTtlSeconds?: number\n /** Suppress re-warming a workspace that just failed. Default 60_000 ms. */\n failureCooldownMs?: number\n /** Clock seam for tests. */\n now?(): number\n}\n\nexport interface SandboxPrewarmer {\n /**\n * Non-blocking warm. The returned promise settles as soon as the DECISION is\n * known (at most one `list()` against the platform, plus a claim `acquire`);\n * the provisioning itself rides on `completion`. On a render path either\n * ignore the returned promise or run the whole call inside `waitUntil` — do\n * not await `completion` before responding.\n */\n prewarm(scope: SandboxPrewarmScope): Promise<PrewarmDecision>\n /** Zero-provisioning status read for a UI. Never creates or resumes. */\n readiness(scope: SandboxPrewarmScope): Promise<SandboxReadiness>\n /** Clear a recorded failure so the next `prewarm` retries immediately. */\n clearFailure(scope: SandboxPrewarmScope): void\n}\n\n/** Identity of a warm. Harness is part of it because `ensureWorkspaceSandbox`\n * destroys and rebuilds a box whose harness does not match. */\nexport function sandboxPrewarmClaimKey(\n scope: Pick<SandboxPrewarmScope, 'workspaceId' | 'harness'>,\n): string {\n return `${scope.workspaceId}::${scope.harness}`\n}\n\nfunction errText(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nexport function createSandboxPrewarmer(\n shell: SandboxRuntimeConfig,\n options: SandboxPrewarmerOptions,\n): SandboxPrewarmer {\n const mode = options.mode ?? 'resume-only'\n const claimTtlSeconds = options.claimTtlSeconds ?? 180\n const failureCooldownMs = options.failureCooldownMs ?? 60_000\n const now = options.now ?? (() => Date.now())\n const claim = options.claim === 'single-isolate-only' ? null : options.claim\n\n const inFlight = new Map<string, Promise<PrewarmResult>>()\n const failures = new Map<string, { error: string; until: number }>()\n\n const emit = (event: PrewarmEvent): void => {\n try {\n options.onEvent?.(event)\n } catch {\n // An observability seam must never take down the warm it is reporting on.\n }\n }\n\n async function releaseClaim(key: string): Promise<void> {\n if (!claim) return\n try {\n await claim.release(key)\n } catch {\n // Best effort by contract — the TTL is what actually guarantees release.\n }\n }\n\n /**\n * Owns the box work for one warm. Resolves; never rejects.\n *\n * Clears `inFlight` in its own `finally`, BEFORE the returned promise\n * settles, so the invariant a caller can rely on is: once `completion`\n * resolves, the key is free. Deferring the delete to a `.finally()` chained\n * outside would leave it queued one microtask later, and a caller that\n * awaits `completion` and immediately re-warms would get a stale\n * `already-warming` instead of a real decision.\n */\n async function runWarm(\n key: string,\n scope: SandboxPrewarmScope,\n holdsClaim: boolean,\n ): Promise<PrewarmResult> {\n const startedAt = now()\n emit({ type: 'started', key, workspaceId: scope.workspaceId })\n try {\n const box: SandboxInstance = await ensureWorkspaceSandbox(shell, {\n workspaceId: scope.workspaceId,\n userId: scope.userId,\n harness: scope.harness,\n billingOwnerId: scope.billingOwnerId,\n })\n const ms = now() - startedAt\n failures.delete(key)\n emit({ type: 'succeeded', key, workspaceId: scope.workspaceId, boxId: box.id, ms })\n return { ok: true, boxId: box.id, ms }\n } catch (err) {\n const ms = now() - startedAt\n const error = errText(err)\n // Recorded, not thrown: the next real request still takes the lazy path,\n // and `readiness()` can now tell the UI the warm failed instead of\n // leaving it to spin over a box that is never coming.\n failures.set(key, { error, until: now() + failureCooldownMs })\n emit({ type: 'failed', key, workspaceId: scope.workspaceId, error, ms })\n return { ok: false, error, ms }\n } finally {\n inFlight.delete(key)\n if (holdsClaim) await releaseClaim(key)\n }\n }\n\n return {\n async prewarm(scope: SandboxPrewarmScope): Promise<PrewarmDecision> {\n const key = sandboxPrewarmClaimKey(scope)\n\n // Synchronous guards first — these run before any `await`, so two calls\n // in one isolate cannot both get past this point.\n if (inFlight.has(key)) {\n emit({ type: 'skipped', key, workspaceId: scope.workspaceId, outcome: 'already-warming' })\n return { outcome: 'already-warming' }\n }\n const failure = failures.get(key)\n if (failure && now() < failure.until) {\n emit({ type: 'skipped', key, workspaceId: scope.workspaceId, outcome: 'cooling-down' })\n return { outcome: 'cooling-down' }\n }\n\n // Reserve the key for THIS isolate before the first await. The reservation\n // is a placeholder the real warm replaces; without it, two concurrent\n // callers would both suspend on `peek` and both proceed.\n let settle: (result: PrewarmResult) => void = () => {}\n const reservation = new Promise<PrewarmResult>((resolve) => {\n settle = resolve\n })\n inFlight.set(key, reservation)\n\n const abandon = (outcome: PrewarmOutcome): PrewarmDecision => {\n inFlight.delete(key)\n settle({ ok: false, error: outcome, ms: 0 })\n emit({ type: 'skipped', key, workspaceId: scope.workspaceId, outcome })\n return { outcome }\n }\n\n try {\n // Cheapest question first: is it already running? Costs one list() and\n // no claim, so the common \"user reopens a warm project\" path spends\n // nothing.\n const peek = await peekWorkspaceSandbox(shell, {\n workspaceId: scope.workspaceId,\n userId: scope.userId,\n })\n if (peek.status === 'running') return abandon('already-running')\n if (peek.status === 'warming') return abandon('already-warming')\n if (peek.status === 'absent' && mode === 'resume-only') {\n return abandon('absent-and-resume-only')\n }\n\n if (options.shouldPrewarm) {\n const allowed = await options.shouldPrewarm(scope)\n if (!allowed) return abandon('declined-by-policy')\n }\n\n let holdsClaim = false\n if (claim) {\n holdsClaim = await claim.acquire(key, claimTtlSeconds)\n if (!holdsClaim) return abandon('warming-elsewhere')\n }\n\n // The key is already reserved above; `runWarm` owns clearing it.\n const warm = runWarm(key, scope, holdsClaim)\n void warm.then(settle)\n return { outcome: 'started', completion: warm }\n } catch (err) {\n // A peek/policy/claim failure is a failed warm like any other: recorded,\n // surfaced, and degraded to the lazy path.\n const error = errText(err)\n inFlight.delete(key)\n failures.set(key, { error, until: now() + failureCooldownMs })\n settle({ ok: false, error, ms: 0 })\n emit({ type: 'failed', key, workspaceId: scope.workspaceId, error, ms: 0 })\n return { outcome: 'cooling-down' }\n }\n },\n\n async readiness(scope: SandboxPrewarmScope): Promise<SandboxReadiness> {\n const key = sandboxPrewarmClaimKey(scope)\n // A running box outranks a recorded failure: the failure may be stale\n // (a later warm, or the lazy path, may have succeeded since).\n const peek = await peekWorkspaceSandbox(shell, {\n workspaceId: scope.workspaceId,\n userId: scope.userId,\n })\n if (peek.status === 'running') return { status: 'ready', boxId: peek.box.id }\n if (peek.status === 'warming') return { status: 'warming' }\n\n if (inFlight.has(key)) return { status: 'warming' }\n if (claim?.isHeld) {\n try {\n if (await claim.isHeld(key)) return { status: 'warming' }\n } catch {\n // An unreadable claim store must not turn a status read into a 500.\n }\n }\n\n const failure = failures.get(key)\n if (failure && now() < failure.until) {\n return { status: 'failed', error: failure.error, retryAfterMs: failure.until - now() }\n }\n\n // A stopped box is not 'absent' to the platform, but to a user staring at\n // a dead terminal the distinction is meaningless: neither can serve them\n // until something warms it.\n return { status: 'absent' }\n },\n\n clearFailure(scope: SandboxPrewarmScope): void {\n failures.delete(sandboxPrewarmClaimKey(scope))\n },\n }\n}\n","import type { SandboxInstance } from '@tangle-network/sandbox'\nimport { parseBackendType } from '@tangle-network/sandbox'\nimport type { AgentProfileMcpServer, AgentProfile, ReasoningEffort } from '@tangle-network/agent-interface'\nimport { mergeAgentProfiles } from '@tangle-network/agent-interface/profile'\nimport { type Harness, DEFAULT_HARNESS, isHarness, assertHarnessModelCompatible } from '../harness/index'\nimport type { SandboxRuntimeConfig } from './configuration'\nimport type { StreamSandboxPromptOptions } from './prompt-options'\nimport { trimOrNull } from '../runtime/model'\nimport { requireTransportableModel, resolveModelSelection, backendModelFields } from './model'\nimport { splitDeferredProfileFiles } from './profile-files'\nimport { assertProfilePromptWithinBudget } from '../profile/budget'\nimport { SHELL_PROMPT_BUDGET_HINT } from './payload-limits'\nimport { fingerprintAgentProfile } from '../profile/fingerprint'\n\n// The SDK's SandboxInstance.streamPrompt/.prompt accept `string | PromptInputPart[]`\n// but the published package does not re-export the PromptInputPart type by name from\n// any of its entry points, so it's derived structurally off the method signature\n// itself — this stays in lockstep with the SDK's actual accepted shape.\n/** Extract a single element type from the array parameter of SandboxInstance's streamPrompt method */\nexport type PromptInputPart = Extract<\n Parameters<SandboxInstance['streamPrompt']>[0],\n readonly unknown[]\n>[number]\n\nfunction historyTranscript(\n history: Array<{ role: 'user' | 'assistant'; content: string }>,\n): string {\n return history\n .map((entry) => `${entry.role === 'assistant' ? 'Assistant' : 'User'}: ${entry.content}`)\n .join('\\n\\n')\n}\n\n/** Build a single string combining conversation history and the current user message */\nexport function flattenHistory(\n message: string,\n history?: Array<{ role: 'user' | 'assistant'; content: string }>,\n): string {\n if (!history?.length) return message\n return `${historyTranscript(history)}\\n\\nUser: ${message}`\n}\n\n/**\n * History-aware equivalent of flattenHistory for multimodal prompt parts: the\n * transcript is folded into the first text part (image/file parts carry no\n * text to prepend to) rather than replacing the message wholesale.\n */\nexport function mergeHistoryIntoParts(\n parts: PromptInputPart[],\n history?: Array<{ role: 'user' | 'assistant'; content: string }>,\n): PromptInputPart[] {\n if (!history?.length) return parts\n const textIndex = parts.findIndex((part) => part.type === 'text')\n if (textIndex === -1) {\n throw new Error('mergeHistoryIntoParts requires at least one text part to carry the history')\n }\n const textPart = parts[textIndex] as Extract<PromptInputPart, { type: 'text' }>\n const merged = [...parts]\n merged[textIndex] = { ...textPart, text: `${historyTranscript(history)}\\n\\nUser: ${textPart.text}` }\n return merged\n}\n\n/** Resolve conflicts and merge extra MCP profiles into the app tool MCP without overwriting existing keys */\nexport function mergeExtraMcp(\n appToolMcp: Record<string, AgentProfileMcpServer>,\n baseProfileMcp: Record<string, AgentProfileMcpServer>,\n extra: Record<string, AgentProfileMcpServer> | undefined,\n): Record<string, AgentProfileMcpServer> {\n for (const key of Object.keys(extra ?? {})) {\n if (key in appToolMcp || key in baseProfileMcp) {\n throw new Error(`extraMcp key '${key}' collides with an existing profile MCP server`)\n }\n }\n return { ...appToolMcp, ...(extra ?? {}) }\n}\n\n/** Attach explicit effort through the portable model contract consumed by providers. */\nexport function attachReasoningEffort(\n profile: AgentProfile,\n _harness: Harness,\n effort: 'auto' | ReasoningEffort | undefined,\n): AgentProfile {\n if (!effort || effort === 'auto') return profile\n return {\n ...profile,\n model: {\n ...profile.model,\n reasoningEffort: effort,\n },\n }\n}\n\nexport interface SandboxPromptTokenLimits {\n maxVisibleOutputTokens?: number\n maxReasoningTokens?: number\n maxTotalOutputTokens?: number\n}\n\nfunction positiveSafeInteger(value: number | undefined, field: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`${field} must be a positive safe integer`)\n }\n return value\n}\n\nfunction lowerCeiling(current: number | undefined, requested: number | undefined): number | undefined {\n if (current === undefined) return requested\n if (requested === undefined) return current\n return Math.min(current, requested)\n}\n\n/** Tighten the profile's provider-enforced token ceilings for one prompt. */\nexport function applyPromptTokenLimits(\n profile: AgentProfile,\n limits: SandboxPromptTokenLimits,\n): AgentProfile {\n const requestedVisible = positiveSafeInteger(\n limits.maxVisibleOutputTokens,\n 'maxVisibleOutputTokens',\n )\n const requestedReasoning = positiveSafeInteger(\n limits.maxReasoningTokens,\n 'maxReasoningTokens',\n )\n const requestedTotal = positiveSafeInteger(\n limits.maxTotalOutputTokens,\n 'maxTotalOutputTokens',\n )\n if (\n requestedVisible === undefined\n && requestedReasoning === undefined\n && requestedTotal === undefined\n ) return profile\n\n const maxTotalOutputTokens = lowerCeiling(\n profile.model?.maxTotalOutputTokens,\n requestedTotal,\n )\n let maxVisibleOutputTokens = lowerCeiling(\n profile.model?.maxVisibleOutputTokens,\n requestedVisible,\n )\n let maxReasoningTokens = lowerCeiling(\n profile.model?.maxReasoningTokens,\n requestedReasoning,\n )\n if (maxTotalOutputTokens !== undefined) {\n if (maxVisibleOutputTokens !== undefined) {\n maxVisibleOutputTokens = Math.min(maxVisibleOutputTokens, maxTotalOutputTokens)\n }\n if (maxReasoningTokens !== undefined) {\n maxReasoningTokens = Math.min(maxReasoningTokens, maxTotalOutputTokens)\n }\n }\n\n return {\n ...profile,\n model: {\n ...(profile.model ?? {}),\n ...(maxVisibleOutputTokens !== undefined ? { maxVisibleOutputTokens } : {}),\n ...(maxReasoningTokens !== undefined ? { maxReasoningTokens } : {}),\n ...(maxTotalOutputTokens !== undefined ? { maxTotalOutputTokens } : {}),\n },\n }\n}\n\n/** Configuration needed to prepare a turn without provisioning a workspace. */\nexport type SandboxPromptConfig = Pick<SandboxRuntimeConfig, 'provider' | 'deferProfileFiles' | 'promptBudget'>\n & Partial<Pick<SandboxRuntimeConfig, 'profile'>>\n\n/** Prepare one effective backend for SDK dispatch or product-specific transport.\n * Supply a server-owned profile, or a shell composer for the default profile.\n * Reuse the returned backend for preflight and dispatch so they inspect identical configuration.\n */\nexport async function resolveSandboxPromptBackend(\n shell: SandboxPromptConfig,\n options: StreamSandboxPromptOptions,\n operation = 'sandbox prompt',\n) {\n const initialHarness = options.harness ?? options.profile?.harness ?? DEFAULT_HARNESS\n if (!isHarness(initialHarness)) throw new Error(`Unsupported sandbox harness: ${initialHarness}`)\n const extraMcp = mergeExtraMcp(\n options.appToolMcp ?? {},\n options.profile?.mcp ?? options.baseProfileMcp ?? {},\n options.extraMcp,\n )\n const compose = (harness: Harness) => {\n if (!shell.profile) throw new Error(`${operation}: supply a profile or a shell profile composer`)\n return shell.profile({ systemPrompt: options.systemPrompt, extraMcp, harness })\n }\n let fullProfile = options.profile\n ? mergeAgentProfiles(options.profile, {\n ...(options.systemPrompt !== undefined ? { prompt: { systemPrompt: options.systemPrompt } } : {}),\n ...(Object.keys(extraMcp).length > 0 ? { mcp: extraMcp } : {}),\n })!\n : compose(initialHarness)\n const harness = options.harness ?? fullProfile.harness ?? DEFAULT_HARNESS\n if (!isHarness(harness)) throw new Error(`Unsupported sandbox harness: ${harness}`)\n // Older composers may place harness-native files. Recompose if their authored\n // preference differs from the default used to discover that preference.\n if (!options.profile && harness !== initialHarness) fullProfile = compose(harness)\n\n const explicitModel = trimOrNull(options.model)\n const profileModel = trimOrNull(fullProfile.model?.default)\n const profileProvider = profileModel && (!explicitModel || explicitModel === profileModel)\n ? trimOrNull(fullProfile.model?.provider)\n : null\n const model = requireTransportableModel(\n resolveModelSelection({\n ...shell.provider,\n providerName: trimOrNull(shell.provider?.providerName) ?? profileProvider ?? undefined,\n }, {\n model: explicitModel ?? profileModel ?? undefined,\n modelApiKey: options.modelApiKey,\n }),\n operation,\n )\n // Profile provider evidence belongs only to its own selected model; the\n // transport provider may instead identify a router serving that vendor.\n if (model) assertHarnessModelCompatible(harness, {\n ...model,\n provider: profileProvider ?? model.provider,\n })\n\n const selectedProfile: AgentProfile = {\n ...fullProfile,\n harness,\n // The materializer compares the profile and transport as provider-qualified\n // identities. Authored provider evidence has already served preflight above.\n ...(model ? { model: { ...fullProfile.model, provider: model.provider, default: model.model } } : {}),\n }\n // The deferred writer owns shell-composed files only. Supplied profiles\n // must retain their resources for the SDK to materialize this turn.\n const executionProfile = shell.deferProfileFiles && !options.profile\n ? splitDeferredProfileFiles(selectedProfile).leanProfile\n : selectedProfile\n const profile = applyPromptTokenLimits(\n attachReasoningEffort(executionProfile, harness, options.effort),\n {\n maxVisibleOutputTokens: options.maxOutputTokens,\n maxReasoningTokens: options.maxReasoningTokens,\n maxTotalOutputTokens: options.maxTotalOutputTokens,\n },\n )\n assertProfilePromptWithinBudget(\n profile, shell.promptBudget ?? {}, `${operation} profile systemPrompt`, SHELL_PROMPT_BUDGET_HINT,\n )\n if (options.onProfileResolved) {\n options.onProfileResolved(await fingerprintAgentProfile(profile, { model: model?.model, harness }))\n }\n return {\n // BackendConfig admits dispatchable backend ids only; parseBackendType\n // fails fast (and type-narrows) for historical-only harness identities\n // such as `forge` instead of letting the platform reject them remotely.\n type: parseBackendType(harness),\n profile,\n ...(model ? backendModelFields(model) : {}),\n ...(options.runtimeAttachments ? { runtimeAttachments: options.runtimeAttachments } : {}),\n ...(options.runtimeSecrets ? { runtimeSecrets: options.runtimeSecrets } : {}),\n ...(options.secretProfileIsolation ? { metadata: { profileSecretIsolation: true as const } } : {}),\n ...(options.interactions ? { interactions: options.interactions } : {}),\n }\n}\n","\n\nimport { DISPATCH_REQUEST_MAX_BYTES } from '../chat-routes/wire'\n\n// ---------------------------------------------------------------------------\n// Provision-time S-cost gates. Both run immediately before `client.create` —\n// each catches an input class that can NEVER produce a working sandbox, so\n// failing at POST-time with actionable detail beats a platform 4xx (or a box\n// that boots and then E2BIGs on every exec).\n\n/** Appended to a prompt-budget throw from any of this module's three choke\n * points. A product that already raised the cap at compose time\n * (`composeAgentProfile(base, channels, overlay, { maxSystemPromptBytes })` —\n * gtm-agent uses 50_000) has to declare the SAME decision on the shell, or the\n * shell's default reads as a contradiction instead of a missing declaration. */\nexport const SHELL_PROMPT_BUDGET_HINT =\n 'If this prompt size is a decision you already made at compose time, mirror it on the shell as ' +\n '`promptBudget: { maxSystemPromptBytes, overBudgetReason }` — the shell gate is the one that sees the profile actually sent.'\n\n/** Gate on the provision body: the platform orchestrator caps the create\n * payload at 256 KiB; 240 KB leaves headroom for transport framing. An\n * over-cap payload fails provisioning 100% of the time (a 282 KB payload\n * shipped once and no sandbox could ever be created). */\nexport const PROVISION_PAYLOAD_MAX_BYTES = 240_000\n\n/** Per-variable env gate: the kernel rejects any single `NAME=value` env entry\n * over MAX_ARG_STRLEN (131072 bytes) with E2BIG, killing every exec inside\n * the box. 120 KB leaves headroom for the name and framing. */\nexport const ENV_VALUE_MAX_BYTES = 120_000\n\n/** Default wait for a box to reach `running`. Overridable per shell via\n * {@link SandboxRuntimeConfig.provisionTimeoutMs}. */\nexport const DEFAULT_PROVISION_TIMEOUT_MS = 120_000\n\n/** Total env gate: the whole environment block shares the payload budget with\n * the profile; past 200 KB the provision body cannot stay under the cap. */\nexport const ENV_TOTAL_MAX_BYTES = 200_000\n\nfunction utf8ByteLength(value: unknown): number {\n return new TextEncoder().encode(typeof value === 'string' ? value : JSON.stringify(value ?? null))\n .byteLength\n}\n\n/** Structural slice of the profile the payload gate reads: it only measures\n * the profile's serialized size and names `resources.files` in the breakdown,\n * so callers composing a payload outside the SDK (products, tests) can pass a\n * plain object without casting through `AgentProfile`. */\nexport interface ProvisionProfileSection {\n resources?: { files?: readonly unknown[] }\n}\n\n/** The provision-payload sections the size gates need to see. Structural so\n * the gate is testable without the SDK's (unexported) create-payload type. */\nexport interface ProvisionPayloadSections {\n env?: Record<string, string>\n /** Secret names, or Sandbox 0.63 host-scoped `SecretBinding` objects; the gate only measures bytes. */\n secrets?: readonly unknown[] | 'all'\n /** `profile` may also be a named-profile string ref (the SDK's\n * `BackendConfig` union) — a string ref is tiny and has no files channel. */\n backend?: { profile?: string | ProvisionProfileSection }\n}\n\n/**\n * Throw when the serialized provision payload exceeds\n * {@link PROVISION_PAYLOAD_MAX_BYTES}. The error carries a per-section byte\n * breakdown (profile/files/env/secrets) so the offending channel is named, not\n * guessed.\n */\nexport function assertProvisionPayloadWithinCap(payload: ProvisionPayloadSections): void {\n const total = utf8ByteLength(payload)\n if (total <= PROVISION_PAYLOAD_MAX_BYTES) return\n const profile = payload.backend?.profile\n const files = (typeof profile === 'string' ? undefined : profile?.resources?.files) ?? []\n const breakdown =\n `profile=${utf8ByteLength(profile ?? null)}B ` +\n `(files=${utf8ByteLength(files)}B), ` +\n `env=${utf8ByteLength(payload.env ?? {})}B, ` +\n `secrets=${utf8ByteLength(payload.secrets ?? [])}B`\n throw new Error(\n `sandbox provision payload is ${total} bytes — over the ${PROVISION_PAYLOAD_MAX_BYTES}-byte gate ` +\n `(the platform caps the create body at 256 KiB; an over-cap payload can never create a sandbox). ` +\n `Breakdown: ${breakdown}. ` +\n `Hint: set deferProfileFiles: true or move content to resources.`,\n )\n}\n\n/**\n * Throw when any single env value exceeds {@link ENV_VALUE_MAX_BYTES} or the\n * whole env block exceeds {@link ENV_TOTAL_MAX_BYTES}, naming the offending\n * variable. This is the E2BIG incident class: the box may even provision, but\n * every exec inside it dies on the oversized entry.\n */\nexport function assertEnvWithinLimits(env: Record<string, string>): void {\n let total = 0\n let largest: { name: string; bytes: number } | null = null\n for (const [name, value] of Object.entries(env)) {\n const bytes = utf8ByteLength(`${name}=${value}`)\n total += bytes\n if (!largest || bytes > largest.bytes) largest = { name, bytes }\n if (bytes > ENV_VALUE_MAX_BYTES) {\n throw new Error(\n `sandbox env var ${name} is ${bytes} bytes — over the ${ENV_VALUE_MAX_BYTES}-byte gate ` +\n `(kernel MAX_ARG_STRLEN is 131072 bytes per env entry; anything larger E2BIGs every exec). ` +\n `Write large content to a file mount or resource instead of an env var.`,\n )\n }\n }\n if (total > ENV_TOTAL_MAX_BYTES) {\n const worst = largest ? ` Largest: ${largest.name} (${largest.bytes}B).` : ''\n throw new Error(\n `sandbox env block is ${total} bytes total — over the ${ENV_TOTAL_MAX_BYTES}-byte gate.${worst} ` +\n `Write large content to a file mount or resource instead of env vars.`,\n )\n }\n}\n\n/**\n * Throw when a dispatch into a secret-isolated session cannot fit the sandbox gateway's\n * {@link DISPATCH_REQUEST_MAX_BYTES} request cap. An isolated dispatch carries its whole profile inline, every file\n * mount's content included, to the profile preparation and to the run; a shared session's file mounts are written\n * to the box separately, so a shared dispatch is not measured here. The measure (prompt plus backend) is a lower\n * bound of what the SDK sends, so a refusal is never a request that could have passed. The error names the\n * largest mounts.\n *\n * GTM, 2026-10-24: one 342 KB program mounted under five names made a 2,065,490-byte isolated profile, and every\n * computer child failed at the gateway with a cause only `console.error` saw.\n */\nexport function assertIsolatedDispatchWithinCap(input: {\n prompt: unknown\n /** The profile sent inline, and the isolation mark `resolveSandboxPromptBackend` sets from `secretProfileIsolation`. */\n backend: {\n profile?: string | { resources?: { files?: ReadonlyArray<{ path?: unknown }> } }\n metadata?: { profileSecretIsolation?: unknown }\n }\n /** A prepared secret revision's receipt; the SDK then sends the full profile too. */\n expectedSecretProfileReceipt?: string\n}): void {\n const isolated = input.backend.metadata?.profileSecretIsolation === true || Boolean(input.expectedSecretProfileReceipt)\n if (!isolated) return\n const total = utf8ByteLength({ parts: input.prompt, backend: input.backend })\n if (total <= DISPATCH_REQUEST_MAX_BYTES) return\n const profile = input.backend.profile\n const files = (typeof profile === 'string' ? undefined : profile?.resources?.files) ?? []\n const largest = files\n .map(file => ({ path: typeof file.path === 'string' ? file.path : '(unnamed)', bytes: utf8ByteLength(file) }))\n .sort((a, b) => b.bytes - a.bytes)\n .slice(0, 5)\n .map(file => `${file.path}=${file.bytes}B`)\n throw new Error(\n `The isolated computer dispatch is ${total} bytes, over the sandbox gateway's ${DISPATCH_REQUEST_MAX_BYTES}-byte ` +\n `request cap, so it was not sent. An isolated session sends every file mount inline. ` +\n `prompt=${utf8ByteLength(input.prompt)}B, profile files=${utf8ByteLength(files)}B` +\n (largest.length ? `; largest: ${largest.join(', ')}` : '') + '. ' +\n 'Mount one program under several names with `aliasOf` in buildSandboxToolFileMounts, or move large content ' +\n 'out of the isolated profile.',\n )\n}\n","import type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { PromptInputPart } from './prompt-profile'\nimport type { StreamSandboxPromptOptions } from './prompt-options'\n\nexport type StreamPromptOptions = Parameters<SandboxInstance['streamPrompt']>[1]\n\ntype DispatchPromptOptions = Parameters<SandboxInstance['dispatchPrompt']>[1]\n\ntype CompletedTurn = NonNullable<Awaited<ReturnType<SandboxInstance['findCompletedTurn']>>>\n\nfunction cachedSandboxPromptEvents(\n cached: CompletedTurn,\n fallbackExecutionId: string,\n): Array<Record<string, unknown>> {\n const cachedResult = cached.result\n const executionId = typeof cachedResult.executionId === 'string' && cachedResult.executionId.trim()\n ? cachedResult.executionId\n : fallbackExecutionId\n const finalText = typeof cachedResult.finalText === 'string'\n ? cachedResult.finalText\n : typeof cachedResult.response === 'string'\n ? cachedResult.response\n : typeof cachedResult.text === 'string'\n ? cachedResult.text\n : undefined\n\n return [\n {\n type: 'result',\n data: {\n ...cachedResult,\n ...(finalText !== undefined && cachedResult.finalText === undefined ? { finalText } : {}),\n sessionId: cached.sessionId,\n executionId,\n },\n },\n {\n type: 'done',\n data: {\n sessionId: cached.sessionId,\n executionId,\n status: 'completed',\n outcome: { type: 'completed' },\n },\n },\n ]\n}\n\n/**\n * Open the durable event lane for one detached prompt.\n *\n * `dispatchPrompt` is the admission boundary: it returns after the sandbox has\n * accepted the run and keeps executing it after this Worker disappears. The\n * SDK's execution replay stream is then the exact execution-scoped surface.\n * Replaying through `streamPrompt` preserves the direct run-event vocabulary;\n * the session bus wraps message parts under `data.properties`.\n */\nexport async function* detachedSandboxPromptEvents(\n box: SandboxInstance,\n prompt: string | PromptInputPart[],\n options: StreamSandboxPromptOptions,\n backend: NonNullable<StreamPromptOptions>['backend'],\n): AsyncGenerator<unknown> {\n const sessionId = options.sessionId?.trim()\n const executionId = options.executionId?.trim()\n if (!sessionId || !executionId) {\n throw new Error('streamSandboxPrompt detach requires stable sessionId and executionId')\n }\n\n options.signal?.throwIfAborted()\n const lastEventId = options.lastEventId?.trim() || undefined\n const turnId = options.turnId?.trim() || executionId\n // A cursor is already proof that this execution was admitted. Re-dispatching\n // before replay would turn a failed terminal session into a new prompt.\n // Only a new send is witnessed, and nothing awaited separates the witness from it.\n if (!lastEventId) options.onDispatch?.()\n const admission = lastEventId\n ? null\n : await box.dispatchPrompt(prompt, {\n sessionId,\n executionId,\n turnId,\n backend,\n keepEvents: true,\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.expectedPublicProfileRequestDigest\n ? { expectedPublicProfileRequestDigest: options.expectedPublicProfileRequestDigest }\n : {}),\n ...(options.expectedSecretProfileReceipt\n ? { expectedSecretProfileReceipt: options.expectedSecretProfileReceipt }\n : {}),\n ...(options.requireVisibleAssistantOutput !== undefined\n ? { requireVisibleAssistantOutput: options.requireVisibleAssistantOutput }\n : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n ...(options.ttlMs !== undefined ? { ttlMs: options.ttlMs } : {}),\n ...(options.trace ? { traceId: options.trace.traceId } : {}),\n } as DispatchPromptOptions)\n // An admission already sent must settle before observation ends. Its product\n // owner can fence an accepted native run; an aborted read is never no-send proof.\n options.signal?.throwIfAborted()\n // A completed-turn cache hit deliberately returns `dispatched: false` and\n // emits no new stream events. Yield its public result directly; the replay\n // buffer may already have aged out by the time a retry reaches this helper.\n if (admission?.dispatched === false) {\n const cached = await box.findCompletedTurn(turnId, { sessionId })\n options.signal?.throwIfAborted()\n if (cached) {\n if (cached.turnId !== turnId || cached.sessionId !== sessionId) {\n throw new Error('sandbox.detached_completed_turn_identity_mismatch')\n }\n yield* cachedSandboxPromptEvents(cached, executionId)\n return\n }\n }\n\n // A different active execution (dispatched: false) is neither admission of this run nor permission to\n // observe its peer; only the exact keyed completed turn above may keep a prior execution id.\n if (admission && (admission.sessionId !== sessionId || admission.executionId !== executionId)) {\n for await (const _ of admission.events ?? []) break\n throw new Error('sandbox.detached_admission_identity_mismatch')\n }\n\n // Not the session bus (`data.properties.part`): the admitted stream, or the SDK's exact execution replay\n // on a resume or an older SDK, keeps the direct prompt vocabulary (`data.part`, terminal `result`).\n yield* admission?.events ?? box.streamPrompt('', {\n sessionId,\n executionId,\n lastEventId: lastEventId || '0',\n ...(options.trace ? { traceId: options.trace.traceId } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n } as StreamPromptOptions)\n}\n\n/**\n * The small event shape consumed by agent-gateway's streaming adapters.\n *\n * Sandbox providers can add fields to their event payloads over time. This\n * adapter deliberately copies only the fields the gateway understands so\n * consumers do not each have to maintain a provider-to-gateway cast.\n */\nexport interface SandboxStreamEvent {\n type?: string\n data?: {\n part?: { type?: string; text?: string }\n delta?: string\n finalText?: string\n code?: string\n message?: string\n details?: Record<string, unknown>\n inputRequired?: { prompt?: string }\n usage?: {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n toolTokens?: number\n toolCallCount?: number\n providerCostUsd?: number\n budgetEnforced?: boolean\n }\n tool?: { name?: string; inputTokens?: number; outputTokens?: number }\n reasoning?: { tokens?: number }\n }\n}\n\nfunction optionalNonNegativeNumber(\n value: unknown,\n field: string,\n): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new Error(`sandbox gateway event ${field} is invalid`)\n }\n return value\n}\n\nfunction optionalNonNegativeSafeInteger(\n value: unknown,\n field: string,\n): number | undefined {\n const number = optionalNonNegativeNumber(value, field)\n if (number !== undefined && !Number.isSafeInteger(number)) {\n throw new Error(`sandbox gateway event ${field} is invalid`)\n }\n return number\n}\n\nfunction optionalGatewayRecord(\n value: unknown,\n field: string,\n): Record<string, unknown> | undefined {\n if (value === undefined) return undefined\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`sandbox gateway event ${field} is invalid`)\n }\n return value as Record<string, unknown>\n}\n\n/** Normalize raw sandbox events for shared agent-gateway consumers. */\nexport function adaptSandboxStream(\n events: AsyncIterable<unknown>,\n): AsyncGenerator<SandboxStreamEvent> {\n return (async function* () {\n for await (const rawEvent of events) {\n if (!rawEvent || typeof rawEvent !== 'object' || Array.isArray(rawEvent)) continue\n\n const event = rawEvent as Record<string, unknown>\n const rawData = event.data\n const dataRecord =\n rawData && typeof rawData === 'object' && !Array.isArray(rawData)\n ? (rawData as Record<string, unknown>)\n : null\n const data: NonNullable<SandboxStreamEvent['data']> = {}\n\n const rawPart = dataRecord?.part\n if (rawPart && typeof rawPart === 'object' && !Array.isArray(rawPart)) {\n const part = rawPart as Record<string, unknown>\n const normalizedPart: NonNullable<\n NonNullable<SandboxStreamEvent['data']>['part']\n > = {}\n if (typeof part.type === 'string') normalizedPart.type = part.type\n if (typeof part.text === 'string') normalizedPart.text = part.text\n if (Object.keys(normalizedPart).length > 0) data.part = normalizedPart\n }\n\n if (typeof dataRecord?.delta === 'string') data.delta = dataRecord.delta\n if (typeof dataRecord?.finalText === 'string') data.finalText = dataRecord.finalText\n if (typeof dataRecord?.code === 'string') data.code = dataRecord.code\n if (typeof dataRecord?.message === 'string') data.message = dataRecord.message\n const rawDetails = dataRecord?.details\n if (rawDetails && typeof rawDetails === 'object' && !Array.isArray(rawDetails)) {\n data.details = rawDetails as Record<string, unknown>\n }\n\n const usageRecord = optionalGatewayRecord(dataRecord?.usage, 'usage')\n if (usageRecord) {\n const usage: NonNullable<NonNullable<SandboxStreamEvent['data']>['usage']> = {}\n for (const field of [\n 'inputTokens',\n 'outputTokens',\n 'reasoningTokens',\n 'toolTokens',\n 'toolCallCount',\n ] as const) {\n const value = optionalNonNegativeSafeInteger(usageRecord[field], `usage.${field}`)\n if (value !== undefined) usage[field] = value\n }\n const providerCostUsd = optionalNonNegativeNumber(\n usageRecord.providerCostUsd,\n 'usage.providerCostUsd',\n )\n if (providerCostUsd !== undefined) usage.providerCostUsd = providerCostUsd\n if (usageRecord.budgetEnforced !== undefined) {\n if (typeof usageRecord.budgetEnforced !== 'boolean') {\n throw new Error('sandbox gateway event usage.budgetEnforced is invalid')\n }\n usage.budgetEnforced = usageRecord.budgetEnforced\n }\n if (Object.keys(usage).length > 0) data.usage = usage\n }\n\n const toolRecord = optionalGatewayRecord(dataRecord?.tool, 'tool')\n if (toolRecord) {\n const tool: NonNullable<NonNullable<SandboxStreamEvent['data']>['tool']> = {}\n if (typeof toolRecord.name === 'string') tool.name = toolRecord.name\n const inputTokens = optionalNonNegativeSafeInteger(toolRecord.inputTokens, 'tool.inputTokens')\n const outputTokens = optionalNonNegativeSafeInteger(toolRecord.outputTokens, 'tool.outputTokens')\n if (inputTokens !== undefined) tool.inputTokens = inputTokens\n if (outputTokens !== undefined) tool.outputTokens = outputTokens\n if (Object.keys(tool).length > 0) data.tool = tool\n }\n\n const reasoningRecord = optionalGatewayRecord(dataRecord?.reasoning, 'reasoning')\n if (reasoningRecord) {\n const tokens = optionalNonNegativeSafeInteger(\n reasoningRecord.tokens,\n 'reasoning.tokens',\n )\n if (tokens !== undefined) data.reasoning = { tokens }\n }\n\n const rawInputRequired = dataRecord?.inputRequired\n if (\n rawInputRequired &&\n typeof rawInputRequired === 'object' &&\n !Array.isArray(rawInputRequired)\n ) {\n const prompt = (rawInputRequired as Record<string, unknown>).prompt\n data.inputRequired = typeof prompt === 'string' ? { prompt } : {}\n }\n\n yield {\n ...(typeof event.type === 'string' ? { type: event.type } : {}),\n ...(Object.keys(data).length > 0 ? { data } : {}),\n }\n }\n })()\n}\n\n// Severed-stream classifier. Generic to any router-backed harness: a final step\n// that finished with error/other/unknown is a truncated turn, not a completed one.\nconst SEVERED_FINISH_REASONS = new Set(['error', 'other', 'unknown'])\n\n/** Define transitions marking the start or finish of a sandbox step with associated details */\nexport type SandboxStepTransition =\n | { kind: 'step-start' }\n | { kind: 'step-finish'; reason: string; severed: boolean }\n\nfunction asPlainRecord(v: unknown): Record<string, unknown> | null {\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null\n}\n\n/** Resolve the severed stream event to a corresponding sandbox step transition or null */\nexport function classifySeveredStream(event: unknown): SandboxStepTransition | null {\n const root = asPlainRecord(event)\n if (!root || root.type !== 'message.part.updated') return null\n const body = asPlainRecord(root.properties) ?? asPlainRecord(root.data) ?? root\n const part = asPlainRecord(body.part)\n if (!part) return null\n if (part.type === 'step-start') return { kind: 'step-start' }\n if (part.type !== 'step-finish') return null\n const reason = typeof part.reason === 'string' && part.reason ? part.reason : 'unknown'\n return { kind: 'step-finish', reason, severed: SEVERED_FINISH_REASONS.has(reason) }\n}\n\n/** A backend result or terminal event, excluding SDK cleanup after observation loss. */\nexport function isTerminalPromptEvent(event: unknown): boolean {\n const root = asPlainRecord(event)\n return root?.type === 'result' || (root?.type === 'done' && asPlainRecord(root.data)?.status !== 'failed')\n}\n\n/** A box agent's ask (or its withdrawal) that the member answers: what a computer step relays to the turn. */\nexport function isComputerInteractionEvent(event: unknown): boolean {\n const type = asPlainRecord(event)?.type\n return type === 'interaction' || type === 'interaction.cancel'\n}\n\n// Interactive-question detector. Returns the question text or null. Used by\n// streamSandboxPrompt when disallowQuestions is set.\n/** Resolve the interactive question text from a structured event or return null if none found */\nexport function detectInteractiveQuestion(event: unknown): string | null {\n const root = asPlainRecord(event)\n if (!root) return null\n const type = typeof root.type === 'string' ? root.type : undefined\n const data = asPlainRecord(root.data)\n const props = asPlainRecord(root.properties)\n const body = props ?? data ?? root\n if (type === 'question.asked' || type === 'question') return firstQuestionText(body)\n // The runtime's structured ask: `interaction` carries an InteractionRequest under\n // `request`, whose `kind` names it and whose `title` is the question.\n if (type === 'interaction') {\n const request = asPlainRecord(body.request) ?? body\n if (request.kind !== 'question') return null\n return typeof request.title === 'string' && request.title ? request.title : firstQuestionText(request)\n }\n const part = asPlainRecord(data?.part) ?? asPlainRecord(body.part)\n const tool =\n (typeof part?.tool === 'string' && part.tool) ||\n (typeof part?.name === 'string' && part.name) ||\n (typeof body.tool === 'string' && body.tool) ||\n undefined\n const isQ =\n type === 'message.part.updated' &&\n (tool === 'question' || asPlainRecord(part)?.type === 'question')\n if (!isQ) return null\n const state = asPlainRecord(asPlainRecord(part)?.state)\n return firstQuestionText(asPlainRecord(state?.input) ?? state ?? part ?? body)\n}\n\nfunction firstQuestionText(value: Record<string, unknown> | null): string {\n const arr = Array.isArray(value?.questions)\n ? value!.questions\n : Array.isArray(asPlainRecord(value?.input)?.questions)\n ? (asPlainRecord(value!.input)!.questions as unknown[])\n : []\n const first = asPlainRecord(arr[0])\n const q =\n (typeof first?.question === 'string' && first.question) ||\n (typeof first?.prompt === 'string' && first.prompt) ||\n undefined\n return q ?? 'interactive question'\n}\n","import { Sandbox } from '@tangle-network/sandbox/core'\nimport { type ReuseChecks, type ReuseStateStore, workersReuseStore } from './reuse-state'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { SandboxClientCredentials } from './credentials'\nimport type { SandboxRuntimeConfig, EnsureWorkspaceSandboxOptions, SandboxScope } from './configuration'\n\ninterface ClientCacheEntry {\n client: Sandbox\n fingerprint: string\n}\n\nlet _cached: ClientCacheEntry | null = null\n\n/**\n * How long a reuse trusts what it last checked on a running box instead of\n * repeating the round trip: the exec probe, the egress read, the runtime\n * environment push, and the spend gate. Every check belongs to one identity of\n * the box (its start time and filesystem incarnation, whichever the platform\n * reports), a box that is not running when read keeps none, and a failed first\n * call on the box drops them all ({@link dropTrustedBox}).\n */\nexport const TRUSTED_REUSE_TTL_MS = 10 * 60_000\n\nconst REUSE_CHECKS_MAX = 1_000\n\nconst reuseChecks = new Map<string, ReuseChecks>()\n\n/** The running box last used under a box name, so a reuse reads it by id instead of listing every running box. A wrong id costs one read: the box read must carry the name. */\nexport const runningBoxIds = new Map<string, string>()\n\n/** Boxes an ensure handed out without an exec probe, because a recent probe of this start had passed. */\nexport const trustedBoxes = new WeakSet<SandboxInstance>()\n\n/** The box name each remembered box id serves, to find its shared state. */\nconst reuseNames = new Map<string, string>()\n\n/** What this isolate last read from or wrote to the shared store, by box name, so an unchanged state is not written again. */\nconst savedShared = new Map<string, string>()\n\nlet defaultReuseStore: ReuseStateStore | null | undefined\n\n/** The store the last ensure used, so a forgotten box is dropped from it too. */\nlet activeReuseStore: ReuseStateStore | null = null\n\n/**\n * What tells one run of a box from the next. The Sandbox API reports no\n * `startedAt` (neither a list row nor a get carries it), so the\n * filesystem incarnation stands in for a restored or replaced filesystem and the\n * start time joins it whenever the platform reports one. A box that is stopped\n * and resumed passes through a status the reuse reads, and resume, delete and a\n * failed probe forget it.\n */\nfunction boxIdentity(box: SandboxInstance): string {\n const startedAt = box.startedAt instanceof Date ? box.startedAt.getTime() : Number.NaN\n return `${Number.isFinite(startedAt) ? startedAt : ''}|${box.filesystemIncarnationId ?? ''}`\n}\n\n/** The checks recorded for this identity of the box. A box with another identity keeps none. */\nexport function checksFor(box: SandboxInstance): ReuseChecks | undefined {\n const checks = reuseChecks.get(box.id)\n if (!checks) return undefined\n if (checks.identity !== boxIdentity(box)) {\n reuseChecks.delete(box.id)\n return undefined\n }\n return checks\n}\n\nexport function recordCheck(box: SandboxInstance, patch: Omit<Partial<ReuseChecks>, 'identity'>): void {\n if (!box.id) return\n const current = checksFor(box) ?? { identity: boxIdentity(box) }\n reuseChecks.delete(box.id)\n reuseChecks.set(box.id, { ...current, ...patch })\n while (reuseChecks.size > REUSE_CHECKS_MAX) {\n const oldest = reuseChecks.keys().next().value\n if (oldest === undefined) break\n reuseChecks.delete(oldest)\n }\n}\n\nexport function forgetBox(boxId: string): void {\n reuseChecks.delete(boxId)\n const name = reuseNames.get(boxId)\n if (name === undefined || !activeReuseStore) return\n savedShared.delete(name)\n // Best effort: a store that cannot drop it costs the other isolates a full check once the entry ages out.\n void Promise.resolve(activeReuseStore.drop(name)).catch(() => undefined)\n}\n\nexport function isRecent(at: number | undefined, ttlMs: number, now = Date.now()): at is number {\n return at !== undefined && Number.isFinite(ttlMs) && ttlMs > 0 && now - at < ttlMs\n}\n\n/**\n * Forget what this isolate trusts about a box after the first real call on it\n * failed. Returns true when the ensure handed the box out without probing it, so\n * the caller may ensure once more and get the full verification; false when the\n * ensure had probed it and the failure is the box's own.\n */\nexport function dropTrustedBox(box: SandboxInstance): boolean {\n forgetBox(box.id)\n return trustedBoxes.delete(box)\n}\n\nexport function getClientFromCreds(creds: SandboxClientCredentials, signal?: AbortSignal): Sandbox {\n // Request lifetimes must never enter the isolate client cache: aborting one\n // caller cannot poison another caller with the same service credentials.\n if (signal) return new Sandbox({ apiKey: creds.apiKey, baseUrl: creds.baseUrl, signal })\n const fingerprint = `${creds.apiKey} ${creds.baseUrl}`\n if (_cached && _cached.fingerprint === fingerprint) return _cached.client\n\n const client = new Sandbox({ apiKey: creds.apiKey, baseUrl: creds.baseUrl })\n _cached = { client, fingerprint }\n return client\n}\n\n// Sync client for non-scoped callers (secretStoreFromClient etc.). Resolves\n// credentials with no scope; throws if the seam returns a Promise — scoped\n// products must use the async ensureWorkspaceSandbox path.\n/** Resolve a synchronous sandbox client from provided runtime configuration credentials */\nexport function getClient(shell: SandboxRuntimeConfig): Sandbox {\n const creds = shell.credentials()\n if (creds && typeof (creds as Promise<unknown>).then === 'function') {\n throw new Error('getClient: scoped (async) credentials require the async sandbox path')\n }\n if (!creds) throw new Error('sandbox credentials are required (apiKey/baseUrl)')\n return getClientFromCreds(creds as SandboxClientCredentials)\n}\n\n/** Reset the process-local sandbox client and liveness-verification caches. */\nexport function resetClientCache(): void {\n _cached = null\n reuseChecks.clear()\n runningBoxIds.clear()\n reuseNames.clear()\n savedShared.clear()\n defaultReuseStore = undefined\n activeReuseStore = null\n}\n\n/** Remember the running box serving a box name, so the next reuse reads it by id. */\nexport function rememberRunningBox(name: string, box: SandboxInstance): SandboxInstance {\n runningBoxIds.delete(name)\n runningBoxIds.set(name, box.id)\n reuseNames.set(box.id, name)\n while (runningBoxIds.size > REUSE_CHECKS_MAX) {\n const oldest = runningBoxIds.keys().next().value\n if (oldest === undefined) break\n runningBoxIds.delete(oldest)\n }\n while (reuseNames.size > REUSE_CHECKS_MAX) {\n const oldest = reuseNames.keys().next().value\n if (oldest === undefined) break\n reuseNames.delete(oldest)\n }\n return box\n}\n\nfunction boxNameFor(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): string {\n const scope: SandboxScope = { workspaceId: options.workspaceId, ...(options.userId ? { userId: options.userId } : {}) }\n return shell.boxKey ? shell.boxKey(scope) : shell.name(options.workspaceId)\n}\n\n/** Whether this isolate probed the workspace's last-used box recently enough that a reuse would skip the probe. */\nexport function hasRecentProbe(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): boolean {\n const probe = shell.livenessProbe\n if (!probe || options.forceNew) return false\n const id = runningBoxIds.get(boxNameFor(shell, options))\n return isRecent(id === undefined ? undefined : reuseChecks.get(id)?.alive, probe.cacheTtlMs ?? TRUSTED_REUSE_TTL_MS)\n}\n\nfunction reuseStoreOf(shell: SandboxRuntimeConfig): ReuseStateStore | null {\n if (shell.reuseState !== undefined) return shell.reuseState\n if (defaultReuseStore === undefined) defaultReuseStore = workersReuseStore()\n return defaultReuseStore\n}\n\n/** Load what another isolate recorded about this workspace's box, unless this isolate already knows it. */\nexport async function hydrateReuseState(shell: SandboxRuntimeConfig, options: EnsureWorkspaceSandboxOptions): Promise<void> {\n if (options.forceNew) return\n const store = reuseStoreOf(shell)\n activeReuseStore = store\n if (!store) return\n const name = boxNameFor(shell, options)\n if (runningBoxIds.has(name)) return\n try {\n const shared = await store.load(name)\n if (!shared) return\n runningBoxIds.set(name, shared.boxId)\n reuseNames.set(shared.boxId, name)\n reuseChecks.set(shared.boxId, shared.checks)\n savedShared.set(name, JSON.stringify(shared))\n } catch {\n // A store that cannot answer is a miss: the reuse verifies in full.\n }\n}\n\n/** Share what this ensure learned about the box, unless the store already holds it. */\nexport async function persistReuseState(shell: SandboxRuntimeConfig, box: SandboxInstance): Promise<void> {\n const store = reuseStoreOf(shell)\n const name = reuseNames.get(box.id)\n const checks = reuseChecks.get(box.id)\n if (!store || name === undefined || !checks) return\n const state = { boxId: box.id, checks }\n const serialized = JSON.stringify(state)\n if (savedShared.get(name) === serialized) return\n try {\n await store.save(name, state)\n savedShared.set(name, serialized)\n } catch {\n // The next ensure in this isolate still trusts what it learned.\n }\n}\n","import type { SandboxSpendHooks, SandboxRuntimeConfig } from './configuration'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport {\n classifySandboxTransientFailure,\n sandboxTransientBackoffMs,\n SandboxTransientDeadlineError,\n} from './transient-failure'\nimport {\n type PromptInputPart,\n resolveSandboxPromptBackend,\n flattenHistory,\n mergeHistoryIntoParts,\n} from './prompt-profile'\nimport type { StreamSandboxPromptOptions } from './prompt-options'\nimport {\n detachedSandboxPromptEvents,\n type StreamPromptOptions,\n classifySeveredStream,\n isTerminalPromptEvent,\n detectInteractiveQuestion,\n} from './prompt-events'\nimport { traceSandboxPromptEvents } from './prompt-trace'\nimport { dropTrustedBox } from './runtime-cache'\nimport { SandboxRunError } from './sandbox-run-error'\nimport { SandboxModelResolutionError } from './model'\nimport { assertIsolatedDispatchWithinCap } from './payload-limits'\n\n/** Fire an activity tap without letting it affect the turn it reports on. */\nexport function emitSandboxActivity(spend: SandboxSpendHooks | undefined, box: SandboxInstance): void {\n if (!spend?.onActivity) return\n try {\n spend.onActivity({ sandboxId: box.id, at: Date.now() })\n } catch {\n // An observability seam must never take down the turn it reports on.\n }\n}\n\n/**\n * How long a refused dispatch is resent. Shorter than the completion\n * Workflow's 10-minute wait for a dispatch to appear, so the request gives up\n * before that Workflow reports the dispatch missing.\n */\nexport const SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS = 8 * 60_000\n\n/**\n * Resend the same execution while the box refuses it with a transient\n * failure and nothing has been delivered yet. The execution id makes a resend\n * idempotent; after the first event a failure is the run's own.\n */\nasync function* resendRefusedDispatch(\n dispatch: () => AsyncIterable<unknown>,\n signal: AbortSignal | undefined,\n): AsyncGenerator<unknown> {\n let delivered = false\n let firstSeenAt: number | undefined\n for (let attempts = 1; ; attempts += 1) {\n try {\n signal?.throwIfAborted()\n for await (const event of dispatch()) {\n delivered = true\n yield event\n }\n return\n } catch (error) {\n const failure = delivered ? null : classifySandboxTransientFailure(error)\n if (!failure || failure.code === 'sandbox.control_plane_transient') throw error\n const at = Date.now()\n firstSeenAt ??= at\n const delayMs = sandboxTransientBackoffMs(attempts)\n if (at + delayMs - firstSeenAt > SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS) {\n throw new SandboxTransientDeadlineError(failure, firstSeenAt, attempts, error)\n }\n console.warn('[sandbox] resending a dispatch the box refused', { code: failure.code, attempt: attempts, delayMs })\n await new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason)\n const timer = setTimeout(resolve, delayMs)\n signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason) }, { once: true })\n })\n }\n }\n}\n\n/** Resolve and stream AI-generated responses from a sandboxed environment based on input messages and options */\nexport async function* streamSandboxPrompt(\n shell: SandboxRuntimeConfig,\n box: SandboxInstance,\n message: string | PromptInputPart[],\n options?: StreamSandboxPromptOptions,\n): AsyncGenerator<unknown> {\n const prompt =\n typeof message === 'string'\n ? flattenHistory(message, options?.history)\n : mergeHistoryIntoParts(message, options?.history)\n let backend: Awaited<ReturnType<typeof resolveSandboxPromptBackend>>\n try {\n options?.signal?.throwIfAborted()\n backend = await resolveSandboxPromptBackend(shell, options ?? {}, 'streamSandboxPrompt')\n assertIsolatedDispatchWithinCap({ prompt, backend, expectedSecretProfileReceipt: options?.expectedSecretProfileReceipt })\n options?.signal?.throwIfAborted()\n } catch (error) {\n // A known local refusal before dispatch differs from losing observation of\n // an admitted execution. Callers can release admission for this outcome.\n if (error instanceof SandboxModelResolutionError) throw error\n throw new SandboxRunError('sandbox_unavailable', error instanceof Error ? error.message : 'The sandbox prompt was not dispatched because its configuration or admission was refused.', { cause: error })\n }\n\n const dispatch = () => {\n if (options?.detach) return detachedSandboxPromptEvents(box, prompt, options, backend)\n // A cursor resumes an execution already sent; only a new send is witnessed.\n if (!options?.lastEventId) options?.onDispatch?.()\n return box.streamPrompt(prompt, {\n sessionId: options?.sessionId,\n executionId: options?.executionId,\n turnId: options?.turnId,\n lastEventId: options?.lastEventId,\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n ...(options?.ttlMs !== undefined ? { ttlMs: options.ttlMs } : {}),\n ...(options?.requireVisibleAssistantOutput !== undefined\n ? { requireVisibleAssistantOutput: options.requireVisibleAssistantOutput }\n : {}),\n ...(options?.expectedPublicProfileRequestDigest\n ? { expectedPublicProfileRequestDigest: options.expectedPublicProfileRequestDigest }\n : {}),\n ...(options?.expectedSecretProfileReceipt\n ? { expectedSecretProfileReceipt: options.expectedSecretProfileReceipt }\n : {}),\n ...(options?.trace ? { traceId: options.trace.traceId } : {}),\n backend,\n } as StreamPromptOptions)\n }\n const stream = options?.lastEventId ? dispatch() : resendRefusedDispatch(dispatch, options?.signal)\n\n emitSandboxActivity(options?.spend, box)\n let severedFinishReason: string | null = null\n const observed = options?.trace\n ? traceSandboxPromptEvents(stream, {\n trace: options.trace,\n ...(options.traceParent ? { parent: options.traceParent } : {}),\n meta: {\n 'sandbox.id': box.id,\n ...(options.model ? { 'gen_ai.request.model': options.model } : {}),\n ...(options.harness ? { 'sandbox.harness': options.harness } : {}),\n ...(options.detach ? { 'sandbox.detached': true } : {}),\n },\n })\n : stream\n let delivered = false\n try {\n for await (const event of observed) {\n delivered = true\n const step = classifySeveredStream(event)\n if (step) severedFinishReason = step.kind === 'step-finish' && step.severed ? step.reason : null\n if (severedFinishReason && isTerminalPromptEvent(event)) {\n throw new Error(`sandbox model stream severed mid-turn (reason=\"${severedFinishReason}\")`)\n }\n if (options?.disallowQuestions) {\n const q = detectInteractiveQuestion(event)\n if (q) {\n throw new Error(`sandbox agent asked an interactive question during an autonomous run: ${q}`)\n }\n }\n yield event\n }\n } catch (error) {\n // The first call on a box handed out without an exec probe is its probe:\n // the next ensure checks it in full.\n if (!delivered && !options?.signal?.aborted) dropTrustedBox(box)\n throw error\n } finally {\n // The box was working right up to here, however this turn ended — a throw,\n // an abandoned generator and a clean finish all bill the same.\n emitSandboxActivity(options?.spend, box)\n }\n // Reconnect-exhausted path: the stream ended on a severed step without a\n // terminal event. A truncated turn must fail loud, not return silently.\n if (severedFinishReason) {\n throw new Error(`sandbox model stream severed mid-turn (reason=\"${severedFinishReason}\")`)\n }\n}\n","import {\n type PromptInputPart,\n flattenHistory,\n resolveSandboxPromptBackend,\n mergeHistoryIntoParts,\n} from './prompt-profile'\nimport type { StreamSandboxPromptOptions } from './prompt-options'\nimport type { SandboxRuntimeConfig } from './configuration'\nimport type { SandboxInstance, TurnDriveResult } from '@tangle-network/sandbox'\nimport { streamSandboxPrompt, emitSandboxActivity } from './prompt-dispatch'\nimport { assertIsolatedDispatchWithinCap } from './payload-limits'\nimport { type Outcome, ok, fail } from './outcome'\nimport { isTerminalPromptEvent } from './prompt-events'\nimport { SandboxRunError } from './sandbox-run-error'\nimport { redactErrorMessage } from '../redact'\n\n/**\n * Stable identity for a streamed text part, so deltas of one part accumulate\n * together and two concurrent parts never overwrite each other. Harnesses spell\n * the id differently and some snapshot updates carry none at all.\n *\n * Deliberately NOT `/stream`'s `getPartKey`, despite the overlapping property\n * lookup: that one resolves a key for any persisted part across every type and\n * falls back to the CONSTANT `'current'`, which merges all id-less parts into a\n * single lane. Here an id-less part must stay distinct — merging two of them\n * would silently drop one candidate answer, the exact failure class this\n * function was changed to fix. Sharing three lines of lookup would also couple\n * `/sandbox` to `/stream`, which are independent subpaths today.\n */\nfunction textPartId(part: Record<string, unknown> | undefined, fallback: string): string {\n for (const key of ['id', 'partId', 'messagePartId']) {\n const value = part?.[key]\n if (typeof value === 'string' && value.trim()) return value\n }\n return fallback\n}\n\n/**\n * The prompt text a harness may replay back as an assistant text part before it\n * answers. Both spellings are collected because `streamSandboxPrompt` dispatches\n * the HISTORY-FOLDED prompt, not the raw message — an echo replays what was sent.\n */\nfunction dispatchedPromptTexts(\n message: string | PromptInputPart[],\n history: StreamSandboxPromptOptions['history'],\n): string[] {\n const raw =\n typeof message === 'string'\n ? message\n : ((message.find((part) => part.type === 'text') as { text?: string } | undefined)?.text ?? '')\n return [...new Set([raw, flattenHistory(raw, history)].map((text) => text.trim()))].filter(Boolean)\n}\n\n/**\n * The last streamed text part that is not a replay of the prompt. Used only when\n * the turn carried no `result` receipt.\n *\n * Two distinct decisions, and only the first is content-based. WHICH parts are\n * eligible is decided by CONTENT — an echo is excluded because it matches the\n * dispatched prompt, at whatever position it arrived. Choosing among the\n * remaining eligible parts is then ordinal, last-wins, because a harness emits\n * reasoning/preamble parts before the answer. That ordering assumption is safe\n * in a way \"skip the first part\" was not: it can only pick the wrong part when a\n * turn produced several genuine non-echo texts and the final one is not the\n * answer, whereas the positional rule mis-fired on the single-answer case that\n * is overwhelmingly the common one.\n */\nfunction lastNonPromptTextPart(parts: Map<string, string>, promptTexts: string[]): string {\n const values = Array.from(parts.values())\n .map((value) => value.trim())\n .filter((value) => value && !promptTexts.includes(value))\n return values.at(-1) ?? ''\n}\n\n/**\n * Aggregate a sandbox prompt event stream down to the turn's one final answer.\n *\n * Exported SEPARATELY from `runSandboxPrompt` because the aggregation is pure —\n * `AsyncIterable<event> -> string` — while the streaming half is not: a product\n * that mounts per-turn MCP servers or resolves its harness per workspace wraps\n * `streamSandboxPrompt` in its own generator. Binding this logic to one stream\n * function is exactly what pushed three products into forking the whole thing,\n * bug and all. Take this over a local copy no matter whose generator you drive.\n *\n * Two rules earn their keep, and both were learned from the naive version:\n *\n * - Text accumulates PER PART ID, never into one running buffer, so two\n * concurrent text parts cannot overwrite each other.\n * - A prompt echo is identified by CONTENT, never by arrival position. The\n * \"skip whichever text part arrives first\" shortcut is wrong on both sandbox\n * lanes: on the delta lane (`box.streamPrompt`, explicit deltas) the first\n * part is the answer's opening token, so the answer silently loses it; and\n * when the echo arrives AFTER the answer, the function returns the caller's\n * own prompt as the agent's reply. Both failures produce a plausible-looking\n * string, the worst shape for the unattended cron/judge turns this exists for.\n *\n * A blank-but-present `result.finalText` is ignored in favour of the streamed\n * text rather than overwriting a real answer with whitespace.\n *\n * A turn with no answer is never returned as an empty string. It throws a\n * `SandboxRunError` that keeps the runtime's own account: `sandbox_unconfirmed`\n * when the stream never confirmed an end, `sandbox_failed` with the redacted\n * failure text the stream reported, else `sandbox_empty`. The error's cause\n * lists the event types the stream carried, so a product's failure log names\n * what the box did.\n *\n * @param events raw sandbox turn events, in order\n * @param message the prompt as handed to the stream, so an echo of it is dropped\n * @param history folded into the dispatched prompt by `streamSandboxPrompt`;\n * pass whatever was passed there, since the echo replays the FOLDED text\n * @param observe called with each raw event before it is folded\n */\nexport async function collectSandboxPromptText(\n events: AsyncIterable<unknown>,\n message: string | PromptInputPart[],\n history?: StreamSandboxPromptOptions['history'],\n /** Sees every raw event as it arrives, so a product can stream progress without forking the fold. */\n observe?: (event: unknown) => void,\n): Promise<string> {\n const { answer, observation } = await collectSandboxPrompt(events, message, history, observe)\n if (!answer) throw noAnswerError(observation)\n return answer\n}\n\n/** What a prompt stream reported besides its text. */\ninterface PromptStreamObservation {\n /** A `result`, or a `done` that is not the SDK's text-less cleanup after losing the stream. */\n terminal: boolean\n /** The first failure the stream reported, redacted. */\n failure?: string\n /** Event types in arrival order, with counts; text parts are keyed by part type. */\n types: Map<string, number>\n}\n\nconst OBSERVED_TYPE_LIMIT = 16\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined\n}\n\nfunction failureText(data: Record<string, unknown> | undefined): string | undefined {\n const error = data?.error\n const text = [record(error)?.message, error, data?.message, data?.code]\n .find((value): value is string => typeof value === 'string' && value.trim().length > 0)\n return text === undefined ? undefined : redactErrorMessage(text)\n}\n\nfunction observePromptEvent(observation: PromptStreamObservation, type: string, data: Record<string, unknown> | undefined): void {\n const key = type === 'message.part.updated' ? `${type}(${String(record(data?.part)?.type ?? 'unknown')})` : type\n if (observation.types.has(key) || observation.types.size < OBSERVED_TYPE_LIMIT) {\n observation.types.set(key, (observation.types.get(key) ?? 0) + 1)\n }\n const status = data?.status\n const failed = type === 'error'\n || (type === 'done' && (status === 'failed' || status === 'cancelled'))\n || (type === 'result' && (data?.success === false || status === 'failed' || status === 'error' || Boolean(data?.error)))\n const text = failed ? failureText(data) : undefined\n // A failed `done` that carries the runtime's code or message is its recorded end; the\n // SDK's cleanup `done` after a lost stream carries neither.\n if (isTerminalPromptEvent({ type, data }) || (type === 'done' && text)) observation.terminal = true\n if (failed && !observation.failure && (text || type !== 'done')) observation.failure = text ?? `${type} event without a message`\n}\n\nfunction noAnswerError(observation: PromptStreamObservation): SandboxRunError {\n const types = Array.from(observation.types, ([type, count]) => `${type}×${count}`).join(', ') || 'no events'\n const cause = new Error(`Sandbox prompt stream carried ${types}; ${observation.terminal ? 'it reached a terminal event' : 'no terminal event'}.`)\n const failure = observation.failure\n if (!observation.terminal) {\n return new SandboxRunError('sandbox_unconfirmed', `The computer stopped reporting before its completion was confirmed. Its work may still be running.${failure ? ` ${failure}` : ''}`, { cause })\n }\n if (failure) return new SandboxRunError('sandbox_failed', `The computer reported a failed execution: ${failure}`, { cause })\n return new SandboxRunError('sandbox_empty', 'The sandbox finished without an answer.', { cause })\n}\n\nasync function collectSandboxPrompt(\n events: AsyncIterable<unknown>,\n message: string | PromptInputPart[],\n history: StreamSandboxPromptOptions['history'],\n observe?: (event: unknown) => void,\n): Promise<{ answer: string; observation: PromptStreamObservation }> {\n let finalText = ''\n const textParts = new Map<string, string>()\n let anonymousTextPart = 0\n const observation: PromptStreamObservation = { terminal: false, types: new Map() }\n\n for await (const rawEvent of events) {\n observe?.(rawEvent)\n const event = rawEvent as { type?: string; data?: Record<string, unknown> }\n if (!event.type) continue\n observePromptEvent(observation, event.type, record(event.data))\n\n if (event.type === 'message.part.updated') {\n const part = event.data?.part as Record<string, unknown> | undefined\n const delta = typeof event.data?.delta === 'string' ? event.data.delta : null\n if (String(part?.type ?? '') === 'text') {\n const partId = textPartId(part, delta ? 'delta' : `text-${anonymousTextPart++}`)\n if (delta) textParts.set(partId, `${textParts.get(partId) ?? ''}${delta}`)\n else if (typeof part?.text === 'string') textParts.set(partId, part.text)\n }\n } else if (event.type === 'result') {\n const resultText = typeof event.data?.finalText === 'string' ? event.data.finalText : null\n if (resultText?.trim()) finalText = resultText\n }\n }\n\n const answer = finalText || lastNonPromptTextPart(textParts, dispatchedPromptTexts(message, history))\n return { answer, observation }\n}\n\n/**\n * Resolve a sandbox prompt by streaming it and aggregating the turn down to one\n * final string. The shell's profile / model / MCP resolution and severed-stream\n * fail-loud come from `streamSandboxPrompt`; the aggregation is\n * `collectSandboxPromptText`, which products driving their own generator should\n * import directly. Unlike that collector, an answer does not excuse a stream\n * that never confirmed its end or that reported a failure. `observe` sees every\n * event as it arrives, for a caller that relays some of them (a box agent's question).\n */\nexport async function runSandboxPrompt(\n shell: SandboxRuntimeConfig,\n box: SandboxInstance,\n message: string | PromptInputPart[],\n options?: StreamSandboxPromptOptions,\n observe?: (event: unknown) => void,\n): Promise<string> {\n const { answer, observation } = await collectSandboxPrompt(streamSandboxPrompt(shell, box, message, options), message, options?.history, observe)\n if (!answer || !observation.terminal || observation.failure) throw noAnswerError(observation)\n return answer\n}\n\n/** Define options to manage deterministic session resumption and turn idempotency in sandboxed drive turns */\nexport interface DriveSandboxTurnOptions extends StreamSandboxPromptOptions {\n /** Deterministic resume key — required. Every tick for the same logical turn\n * MUST reuse it so a crash + re-drive finds the in-flight session instead of\n * starting a second agent run. */\n sessionId: string\n /** Wall-clock cap in ms from the session's start. A still-running session past\n * the cap is cancelled and reported `failed` — bounds an unattended run, such as\n * a turn stalled on an interactive question with no consumer. Omit for no cap. */\n wallCapMs?: number\n}\n\n// One settle → poll → dispatch pass over a detached turn. Delegates to the SDK's\n// `box.driveTurn` (@tangle-network/sandbox ≥ 0.10.5). Sandbox 0.37 admits the\n// turn through the session message lane, so a SessionGateway consumer can observe it.\n// The turn runs fire-and-detached server-side. ONE invocation returns its current\n// state immediately. It never awaits the whole turn in-process, so it does not hold the\n// worker alive for the run's duration (the durability trap the older box.prompt\n// implementation quietly caused).\n//\n// This is the durable path for cron / mission-step / queue callers: re-invoke on\n// your own schedule (Workflow step, DO alarm, queue tick) with the SAME\n// `sessionId` and `turnId`. Dispatch is idempotent on that pair, so a crash +\n// re-drive is a lookup, not a second agent run.\n//\n// The Outcome boundary separates a retryable transport failure from a settled\n// turn: `fail` means the drive call itself threw (network blip — retry the tick);\n// `ok` carries the SDK's discriminated `TurnDriveResult` — inspect `.state`:\n// - `running` → the turn is still executing; re-tick after a delay of your choosing.\n// - `completed` → terminal; `.text` / `.result` hold the payload.\n// - `failed` → terminal and deterministic; re-invoking will not change it (do not retry).\n// - `awaiting_plan_decision`, `blocked_on_approval`, `awaiting_question`,\n// `awaiting_interaction` → the turn settled waiting on a decision. Sandbox\n// 0.45 reports the last three as `failed`.\n/** Resolve a sandbox turn by processing a message with given configuration and options */\nexport async function driveSandboxTurn(\n shell: SandboxRuntimeConfig,\n box: SandboxInstance,\n message: string | PromptInputPart[],\n options: DriveSandboxTurnOptions,\n): Promise<Outcome<TurnDriveResult>> {\n // Configuration failures precede the retryable transport boundary.\n const backend = await resolveSandboxPromptBackend(shell, options, 'driveSandboxTurn')\n const prompt =\n typeof message === 'string'\n ? flattenHistory(message, options.history)\n : mergeHistoryIntoParts(message, options.history)\n assertIsolatedDispatchWithinCap({ prompt, backend, expectedSecretProfileReceipt: options.expectedSecretProfileReceipt })\n try {\n // A tick may dispatch the turn, so each one is witnessed as a possible send.\n options.onDispatch?.()\n const drive = await box.driveTurn(prompt, {\n sessionId: options.sessionId,\n ...(options.turnId ? { turnId: options.turnId } : {}),\n ...(options.wallCapMs !== undefined ? { wallCapMs: options.wallCapMs } : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.expectedPublicProfileRequestDigest\n ? { expectedPublicProfileRequestDigest: options.expectedPublicProfileRequestDigest }\n : {}),\n ...(options.expectedSecretProfileReceipt\n ? { expectedSecretProfileReceipt: options.expectedSecretProfileReceipt }\n : {}),\n // Sandbox 0.37 drives through the session message lane, so a gateway\n // consumer can handle these events. Callers without one should omit\n // interactions so the run stays unattended.\n backend,\n } as Parameters<SandboxInstance['driveTurn']>[1])\n // The autonomous lane needs this most: a detached turn keeps the box\n // billable with nobody watching, and every tick that reports `running` is\n // fresh evidence it is still working. Without it the expectation ceiling\n // rests on whenever the box was last provisioned.\n emitSandboxActivity(options.spend, box)\n return ok(drive)\n } catch (err) {\n return fail(err)\n }\n}\n","/**\n * The files a computer step leaves in the workspace, and what the model may\n * truthfully tell the member about them.\n *\n * A box keeps workspace files under one directory; the app's Vault is a\n * different store, and a file the box agent saves proves nothing about it.\n * So when the step's run has ended, the step lists the box's tree, saves each\n * file changed since the run started through the app's `save`, and appends one receipt line to the\n * answer. That line is the only statement about Vault contents the model may\n * relay ({@link COMPUTER_FILES_GUIDANCE}). Legal learned this in production:\n * a child saved a file outside the Vault and the model said it was saved (#547).\n */\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { isWorkspaceFileExportable } from '../web/file-export'\n\n/** One file the step wrote, at its path relative to the Vault root. */\nexport interface ComputerVaultFile {\n path: string\n content: string\n size: number\n}\n\n/** The app's Vault, as a computer step sees it. */\nexport interface ComputerVault {\n /** Absolute directory on the box that holds the workspace's files. */\n root: string\n /** Store one file the step wrote. A throw leaves it on the computer only, named in the receipt. */\n save(file: ComputerVaultFile, step: { executionId: string }): Promise<void>\n /** Why the Vault cannot hold this file, or null when it can. Default: text kinds up to 512 KB. */\n refuse?(path: string, size: number): string | null\n /** Most files one step saves. Default 20. */\n maxFiles?: number\n}\n\n/** Path relative to the root, mapped to the file's size and modification time. */\nexport type ComputerFileListing =\n | { succeeded: true; files: Record<string, { size: number; mtime: number }> }\n | { succeeded: false; error: string }\n\n/** What one step saved, and what it left on the computer only (with the reason). */\nexport interface ComputerFileReceipt {\n checked: boolean\n saved: string[]\n computerOnly: Array<{ path: string; reason: string }>\n /** The receipt line appended to the step's answer. */\n text: string\n}\n\n/** Appended to the Router model's prompt whenever a computer step copies files into the Vault. */\nexport const COMPUTER_FILES_GUIDANCE =\n 'A file the computer step made is in the workspace vault only when its reply lists the file after \"Workspace vault\"; ' +\n 'for any other file it made, give the exact path from that reply and say it is only on the computer, ' +\n 'and never call a file saved to the vault because the member asked for that.'\n\nconst DEFAULT_MAX_FILES = 20\nconst DEFAULT_MAX_BYTES = 512_000\nconst TEXT_FILE = /\\.(md|markdown|txt|csv|tsv|json|jsonl|html?|xml|ya?ml|toml|svg|css|js|ts|py|sql)$/i\n\nfunction message(error: unknown): string {\n return (error instanceof Error ? error.message : String(error)).slice(0, 300)\n}\n\nfunction defaultRefusal(path: string, size: number): string | null {\n if (!TEXT_FILE.test(path)) return 'not a text file the vault stores'\n if (size > DEFAULT_MAX_BYTES) return `larger than ${DEFAULT_MAX_BYTES / 1000} KB`\n return null\n}\n\n/** Appended to the task the box agent receives, so a member's relative path lands under the Vault root. */\nexport function computerFileContract(root: string, task: string): string {\n return `${task}\\n\\nWhere files go: the workspace's files live under ${root}. `\n + 'Save every file the member will open later there, at the path they gave relative to it '\n + `(proof/a.md is ${root}/proof/a.md), never in your working directory; keep scratch files elsewhere. `\n + 'End your reply with the exact absolute path of every file you saved.'\n}\n\n/** The box's tree under `root`. A tree the box cannot list completely is a failure, never a partial listing. */\nexport async function listComputerFiles(box: SandboxInstance, root: string): Promise<ComputerFileListing> {\n try {\n const tree = await box.fs.tree(root)\n if (tree.stats.truncated) return { succeeded: false, error: 'the workspace tree is too large to list completely' }\n // The sidecar reports the root and every path relative to the box workspace (`/home/agent`): for the root\n // `/home/agent/entities` it echoes root `entities` and file `entities/proof/a.md`. Strip the echoed root whether it\n // arrives relative or absolute; `.` means the paths are already relative (Legal #551 found the doubled path).\n const echoed = tree.root.replace(/\\/+$/, '')\n const prefixes = [`${root.replace(/\\/+$/, '')}/`]\n if (echoed && echoed !== '.') prefixes.unshift(`${echoed}/`)\n const files: Record<string, { size: number; mtime: number }> = {}\n for (const file of tree.files) {\n const prefix = prefixes.find(candidate => file.path.startsWith(candidate))\n files[prefix ? file.path.slice(prefix.length) : file.path.replace(/^\\.\\//, '')] = { size: file.size, mtime: file.mtime }\n }\n return { succeeded: true, files }\n } catch (error) {\n return { succeeded: false, error: message(error) }\n }\n}\n\n// Filesystem mtimes are coarser than the runtime's clock; a file written in the run's first second still counts.\nconst MTIME_TOLERANCE_MS = 1_000\n\n/**\n * Save what the step wrote into the Vault and return its receipt. `since` is when the step's run started, from the\n * runtime's execution ledger (`session.runs()`): the box's own clock, so the files it changed since then are this\n * step's, with no listing kept from before the send. A live call, a reattached call and a later sweep each copy the\n * same files; `vault.save` must be idempotent for a path and content.\n */\nexport async function saveComputerFiles(input: {\n box: SandboxInstance\n vault: ComputerVault\n since: number | undefined\n executionId: string\n}): Promise<ComputerFileReceipt> {\n const { box, vault, since, executionId } = input\n const root = vault.root.replace(/\\/+$/, '')\n const unchecked = (error: string): ComputerFileReceipt => {\n console.warn(JSON.stringify({ event: 'agent_app_computer_files_unchecked', executionId, error }))\n return { checked: false, saved: [], computerOnly: [],\n text: 'Workspace vault: the app could not check which files this step saved, so none is confirmed to be in it.' }\n }\n if (since === undefined || !Number.isFinite(since)) return unchecked('the runtime ledger did not report when the step started')\n const after = await listComputerFiles(box, root)\n if (!after.succeeded) return unchecked(after.error)\n\n const maxFiles = vault.maxFiles ?? DEFAULT_MAX_FILES\n const refuse = vault.refuse ?? defaultRefusal\n const saved: string[] = []\n const computerOnly: Array<{ path: string; reason: string }> = []\n for (const [path, file] of Object.entries(after.files)) {\n if (file.mtime < since - MTIME_TOLERANCE_MS) continue\n if (!isWorkspaceFileExportable(path)) continue\n const refusal = saved.length + computerOnly.length >= maxFiles ? `more than ${maxFiles} files changed` : refuse(path, file.size)\n if (refusal) {\n computerOnly.push({ path, reason: refusal })\n continue\n }\n try {\n await vault.save({ path, content: await box.fs.read(`${root}/${path}`), size: file.size }, { executionId })\n saved.push(path)\n } catch (error) {\n console.error(JSON.stringify({ event: 'agent_app_computer_file_not_saved', executionId, path, error: message(error) }))\n computerOnly.push({ path, reason: 'saving it to the vault failed' })\n }\n }\n console.info(JSON.stringify({ event: 'agent_app_computer_files', executionId, saved: saved.length, computerOnly: computerOnly.length }))\n\n const lines: string[] = []\n if (saved.length > 0) lines.push(`Workspace vault: the app saved ${saved.join(', ')} into it after this step.`)\n if (computerOnly.length > 0) {\n lines.push(`Only on the computer, not in the workspace vault: ${computerOnly.map(file => `${root}/${file.path} (${file.reason})`).join('; ')}.`)\n }\n if (lines.length === 0) lines.push(`Workspace vault: nothing the computer wrote under ${root} in this step was saved into it.`)\n return { checked: true, saved, computerOnly, text: lines.join('\\n') }\n}\n","/**\n * The models a workspace box may call. Platform mints every box's Router key\n * (`auto:sandbox:router:<box>`) under the payer's sandbox policy, and the\n * Sandbox API sends that key with every run in place of any per-turn key. A\n * paying customer's policy names no models (`null`); a company account's\n * (operator, smoke, acceptance, staff) names only its flat-plan models, so a\n * box asked for any other model is refused before it writes a token.\n * `GET /v1/keys/sandbox-router-models` reports that policy for the calling key\n * without returning key material.\n *\n * Creative #739, Legal #546 and GTM each kept a copy of this read; a computer\n * step asked for a model its box key refuses failed every call.\n */\nimport { fail, ok, type Outcome } from './outcome'\n\nexport interface ReadSandboxRouterModelsOptions {\n /** Platform's origin (`TANGLE_PLATFORM_URL`); any path on it is ignored. */\n platformUrl: string\n /** A key of the payer whose sandbox policy applies: the member's linked key, or the owner's sandbox key. */\n apiKey: string\n signal?: AbortSignal\n fetch?: typeof fetch\n}\n\nconst TTL_MS = 10 * 60_000\nconst MAX_ENTRIES = 256\n// Resolved answers only, never a read in flight: a promise's I/O belongs to the request that started it.\nconst answers = new Map<string, { allowedModels: string[] | null; at: number }>()\n\nasync function keyDigest(apiKey: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(apiKey))\n return Array.from(new Uint8Array(digest).slice(0, 16), byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/** Platform's model policy for a box minted under the payer of `apiKey`: the allowed models, or `null` for any. */\nexport async function readSandboxRouterModels(options: ReadSandboxRouterModelsOptions): Promise<Outcome<string[] | null>> {\n const id = await keyDigest(options.apiKey)\n const cached = answers.get(id)\n if (cached && Date.now() - cached.at < TTL_MS) return ok(cached.allowedModels)\n let origin: string\n try { origin = new URL(options.platformUrl).origin } catch {\n return fail(new Error('The sandbox model policy needs a valid Platform URL'))\n }\n let response: Response\n try {\n response = await (options.fetch ?? fetch)(`${origin}/v1/keys/sandbox-router-models`, {\n headers: { Authorization: `Bearer ${options.apiKey}`, Accept: 'application/json' },\n redirect: 'manual',\n signal: options.signal ?? AbortSignal.timeout(5_000),\n })\n } catch (error) {\n return fail(new Error(`The sandbox model policy request failed: ${error instanceof Error ? error.message : String(error)}`))\n }\n if (!response.ok) return fail(Object.assign(new Error(`The sandbox model policy returned HTTP ${response.status}`), { status: response.status }))\n const body = await response.json().catch(() => null) as { success?: unknown; data?: { allowedModels?: unknown } } | null\n const allowed = body?.success === true && body.data && 'allowedModels' in body.data ? body.data.allowedModels : undefined\n if (allowed !== null && !(Array.isArray(allowed) && allowed.every(model => typeof model === 'string' && model.trim()))) {\n return fail(new Error('The sandbox model policy returned an invalid response'))\n }\n const allowedModels = allowed === null ? null : [...new Set(allowed as string[])]\n if (answers.size >= MAX_ENTRIES) answers.delete(answers.keys().next().value!)\n answers.set(id, { allowedModels, at: Date.now() })\n return ok(allowedModels)\n}\n\n/** The first preferred model the policy allows, else the policy's own first model; `null` allows the first preference. */\nexport function modelWithinAllowList(preferred: readonly string[], allowedModels: readonly string[] | null): string | undefined {\n if (allowedModels === null) return preferred[0]\n return preferred.find(model => allowedModels.includes(model)) ?? allowedModels[0]\n}\n","/**\n * `createComputerStep`: what one `sandbox_run` call does on the workspace box,\n * owned once for every app. GTM, Creative and Legal each wrote this step, and\n * each break on 2026-10-24 was in one of those copies (agent-app-lessons.md,\n * \"Computer steps\"). The step:\n *\n * - runs the first of the turn's models the box key allows: the box calls the\n * Router on its own key, whose models are the payer's sandbox policy\n * (`readSandboxRouterModels`), so a model outside it is refused before a token;\n * a run that ends refused for its model (`provider_disabled`, quota) moves to the\n * next allowed one under its own execution id;\n * - takes its session as one value, `{ id, isolated }`, which sets both\n * `secretProfileIsolation` and the send witness;\n * - is as durable as the Sandbox runtime, and keeps no ledger of its own. It sends\n * detached, under a turn id derived from the turn, the session and the tool\n * call: the run outlives this request, and the runtime's admission makes a\n * repeated or reattached call with that turn id the same run. The SDK reads a\n * finished run's answer from the runtime's completed turn, and replays an\n * unfinished one's events to its end; it never sends a second run;\n * - copies what the box agent wrote under the Vault root since its run started\n * (the runtime ledger's start time) into the app's Vault (`files`), whenever it\n * observes the run's end, and appends the receipt line the model may relay;\n * - with `questions`, lets the box agent ask the member: each ask streams to the\n * turn as a `computer_interaction` event, and the member's answer reaches the\n * box through the runtime's interaction registry (the app's interaction route).\n *\n * The product keeps the prompt path when it has its own (`run`); otherwise the\n * step uses agent-app's `runSandboxPrompt` over the product's shell.\n */\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { SandboxRuntimeConfig } from './configuration'\nimport type { StreamSandboxPromptOptions } from './prompt-options'\nimport { runSandboxPrompt } from './prompt-result'\nimport { isComputerInteractionEvent } from './prompt-events'\nimport { SandboxRunError } from './sandbox-run-error'\nimport { COMPUTER_FILES_GUIDANCE, computerFileContract, saveComputerFiles, type ComputerVault } from './computer-files'\nimport { modelWithinAllowList } from './router-models'\nimport { isUpstreamUnavailable } from '../model-resolution/failover'\nimport type { Outcome } from './outcome'\nimport type { SandboxRunToolOptions, SandboxTaskOptions } from './sandbox-run-tool'\n\n/** The box session one computer step runs in. */\nexport interface ComputerStepSession {\n id: string\n /** A secret-isolated native session the product prepared before the send. */\n isolated?: boolean\n}\n\n/** What a product's own prompt path receives for one step. */\nexport interface ComputerStepRun extends SandboxTaskOptions {\n /** Stable for the turn, the session and the tool call: send under it as both execution and turn id, detached, so the\n * runtime's admission makes a repeated call the same run. */\n executionId?: string\n session?: ComputerStepSession\n /** Set only when the box key's policy constrains the turn's models; otherwise run the product's model. */\n model?: string\n /** The send witness: pass it as the prompt's `onDispatch`, or call it exactly at the send. */\n onDispatch(): void\n}\n\nexport interface ComputerStepOptions {\n /** agent-app's prompt path over the product's shell. */\n shell?: SandboxRuntimeConfig\n /** That path's options, other than the ones the step owns. `onDispatch` here observes the step's own witness. */\n prompt?: Omit<StreamSandboxPromptOptions, 'sessionId' | 'executionId' | 'turnId' | 'secretProfileIsolation'\n | 'signal' | 'timeoutMs' | 'trace' | 'traceParent' | 'disallowQuestions' | 'history' | 'detach'>\n /** The product's own prompt path, instead of `shell`. Returns the box agent's final answer. */\n run?(box: SandboxInstance, task: string, step: ComputerStepRun): Promise<string>\n /** `run` passes `step.onDispatch` to a send that calls it (agent-app's `streamSandboxPrompt`, `runSandboxPrompt`\n * and `driveSandboxTurn` do), so a failure before it fired was never sent. Without it, every `run` failure is\n * unconfirmed. The `shell` path always witnesses. */\n runWitnessesDispatch?: boolean\n /** The turn's execution id; with the tool call id it makes the step's turn id. Without it each call sends fresh. */\n parentExecutionId?: string\n /** The session: one value, or prepared per box (a secret-isolated session). A failure there is never sent. Without\n * a session the `shell` path cannot send detached, and the run ends with this request. */\n session?: ComputerStepSession | ((box: SandboxInstance, signal: AbortSignal) => Promise<ComputerStepSession>)\n /** The turn's models in preference order and the box key's allow-list (`readSandboxRouterModels`). */\n models?: {\n preferred: readonly string[]\n allowed(signal: AbortSignal): Promise<Outcome<readonly string[] | null>>\n }\n /** Copy each file the step wrote under the Vault root into the product's Vault. Omit it when the product already\n * reconciles the box's Vault directory after a turn (GTM does). */\n files?: ComputerVault\n /** The product's filesystem contract, applied to every task. */\n frame?(task: string): string\n /** Let the box agent ask the member questions instead of failing on the first one. The `shell` path streams each\n * ask as a `computer_interaction` event; a product `run` emits them itself. */\n questions?: boolean\n}\n\nexport interface ComputerStep {\n runTask: SandboxRunToolOptions['runTask']\n /** What the Router model must be told about this step's answers. */\n guidance?: string\n}\n\nconst ALLOW_LIST_BUDGET_MS = 5_000\n\nasync function digestHex(value: unknown): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(value)))\n return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction errorText(error: unknown): string {\n return (error instanceof Error ? error.message : String(error)).slice(0, 300)\n}\n\n/** The models the step tries in order. `undefined` runs the product's own model; it leads when no policy constrains\n * the turn's models, and each later entry is a fallback for a run its model's provider refused. */\nasync function modelChain(models: ComputerStepOptions['models'], signal: AbortSignal): Promise<Array<string | undefined>> {\n if (!models?.preferred.length) return [undefined]\n const policy = await models.allowed(AbortSignal.any([signal, AbortSignal.timeout(ALLOW_LIST_BUDGET_MS)]))\n .catch((error: unknown): Outcome<never> => ({ succeeded: false, error: error instanceof Error ? error : new Error(String(error)) }))\n if (!policy.succeeded) {\n // An unread policy keeps the product's model; a refusal then names itself in the step's failure.\n console.warn(JSON.stringify({ event: 'agent_app_computer_model_policy_unread', error: errorText(policy.error) }))\n }\n if (!policy.succeeded || policy.value === null) return [undefined, ...models.preferred.slice(1)]\n const allowed = policy.value\n const first = modelWithinAllowList(models.preferred, allowed)\n if (first !== models.preferred[0]) {\n console.info(JSON.stringify({ event: 'agent_app_computer_model_within_policy', requested: models.preferred[0], model: first ?? null }))\n }\n return [...new Set([first, ...models.preferred.filter(model => allowed.includes(model))])]\n}\n\n/** A run that reached its end refused for its model: nothing is left running, and another model may serve. */\nfunction refusedForModel(error: unknown): boolean {\n if (error instanceof SandboxRunError && error.code !== 'sandbox_failed') return false\n for (let cause: unknown = error, depth = 0; cause && depth < 5; cause = (cause as { cause?: unknown }).cause, depth++) {\n if (isUpstreamUnavailable(cause)) return true\n }\n return false\n}\n\n/** When the step's first run started, from the runtime's execution ledger: the box's clock, as its files' times are. */\nasync function runStartedAt(box: SandboxInstance, sessionId: string | undefined, executionIds: readonly string[]): Promise<number | undefined> {\n if (!sessionId || executionIds.length === 0) return undefined\n try {\n const started = (await box.session(sessionId).runs())\n .filter(run => executionIds.includes(run.executionId)).map(run => run.startedAt).filter(Number.isFinite)\n return started.length ? Math.min(...started) : undefined\n } catch (error) {\n console.warn(JSON.stringify({ event: 'agent_app_computer_run_ledger_unread', sessionId, error: errorText(error) }))\n return undefined\n }\n}\n\nexport function createComputerStep(options: ComputerStepOptions): ComputerStep {\n if (!options.run && !options.shell) throw new Error('A computer step needs the product shell or its own run')\n const vault = options.files\n const frame = options.frame ?? ((task: string) => task)\n const runTask: ComputerStep['runTask'] = async (box, task, taskOptions) => {\n const { callId, signal, timeoutMs, trace, span } = taskOptions\n let sent = false\n const witnessed = options.run ? options.runWitnessesDispatch === true : true\n const notSent = (error: unknown): never => {\n if (error instanceof SandboxRunError || signal.aborted) throw error\n throw new SandboxRunError('sandbox_unavailable', 'The computer step was refused before it was sent to the box.', { cause: error })\n }\n const session = typeof options.session === 'function'\n ? await options.session(box, signal).catch(notSent)\n : options.session\n const parent = options.parentExecutionId?.trim()\n const call = callId?.trim()\n // The runtime's admission is keyed by this id: the same turn, session and tool call is the same run.\n const stepId = parent ? await digestHex([parent, session?.id, call || crypto.randomUUID()]) : undefined\n const report = (state: string, extra: Record<string, unknown>) => taskOptions.emit('computer_receipt', {\n stepId: stepId ?? null, sessionId: session?.id ?? null, state, ...extra })\n\n const models = await modelChain(options.models, signal)\n let model = models[0]\n const framed = vault ? computerFileContract(vault.root.replace(/\\/+$/, ''), frame(task)) : frame(task)\n const attempted: string[] = []\n const send = (attemptModel: string | undefined, executionId: string | undefined): Promise<string> => {\n if (executionId) attempted.push(executionId)\n if (options.run) {\n return options.run(box, framed, { ...taskOptions, ...(executionId ? { executionId } : {}),\n ...(session ? { session } : {}), ...(attemptModel ? { model: attemptModel } : {}), onDispatch: () => { sent = true } })\n }\n const prompt = options.prompt ?? {}\n return runSandboxPrompt(options.shell!, box, framed, {\n ...prompt, ...(attemptModel ? { model: attemptModel } : {}),\n ...(executionId ? { executionId, turnId: executionId } : {}),\n ...(session ? { sessionId: session.id } : {}),\n ...(session?.isolated ? { secretProfileIsolation: true as const } : {}),\n // The run outlives this request; a repeated call reattaches to it through the runtime's admission.\n ...(session && executionId ? { detach: true } : {}),\n ...(options.questions\n ? { interactions: { ...prompt.interactions, question: true } }\n : { disallowQuestions: true }),\n signal, timeoutMs,\n ...(trace ? { trace } : {}), ...(span ? { traceParent: span } : {}),\n onDispatch: () => { sent = true; prompt.onDispatch?.() },\n }, options.questions\n ? event => { if (isComputerInteractionEvent(event)) taskOptions.emit('computer_interaction', event) }\n : undefined)\n }\n let answer: string\n for (let attempt = 0; ; attempt++) {\n model = models[attempt]\n try {\n // A fallback is a new run: its own execution id, so a repeat attaches to the same attempt.\n answer = await send(model, stepId && attempt > 0 ? `${stepId}-f${attempt + 1}` : stepId)\n break\n } catch (error) {\n // A run without a witness counts as sent; one refused for its model has ended, so the next may go.\n if ((sent || !witnessed) && attempt + 1 < models.length && !signal.aborted && refusedForModel(error)) {\n console.warn(JSON.stringify({ event: 'agent_app_computer_model_fallback', stepId: stepId ?? null,\n from: model ?? null, to: models[attempt + 1] ?? null, error: errorText(error) }))\n sent = false\n continue\n }\n if (sent || !witnessed) throw error\n return notSent(error)\n }\n }\n // An empty answer stays empty, so the tool reports `sandbox_empty`; a file receipt must not hide it.\n if (!answer.trim()) return answer\n const files = vault\n ? await saveComputerFiles({ box, vault, since: await runStartedAt(box, session?.id, attempted), executionId: stepId ?? 'unnamed-step' })\n : undefined\n const final = files ? `${answer}\\n\\n${files.text}` : answer\n report('settled', { model: model ?? null, saved: files?.saved ?? [], computerOnly: files?.computerOnly.length ?? 0 })\n return final\n }\n return { runTask, ...(vault ? { guidance: COMPUTER_FILES_GUIDANCE } : {}) }\n}\n","/**\n * `createSandboxRunTool`: the `sandbox_run` tool a Router turn calls when the\n * work needs a computer — run code, read a PDF or a sheet, fill a form with a\n * Python toolkit. The conversational turn stays on the Router engine\n * (`./router-turn`); only this call enters the box, and its final answer comes\n * back to the model as the tool result.\n *\n * NEVER SILENT. A box that cannot start, a run that fails and a run that ends\n * with no answer each come back as a typed failure (`sandbox_unavailable`,\n * `sandbox_failed`, `sandbox_empty`) that the model reads and must report. A\n * product that leaves this tool out when it cannot place a box drops the\n * capability without the model or the user knowing; mount the tool and let it\n * fail instead.\n *\n * WARM LEASES. When the product passes `warm`, the call counts as a turn on the\n * box's lease (`leases.turn(key)`), so an `escalation-likely` warm the product\n * signalled is recorded as used. The default name is the one the speculator\n * listens for (`DEFAULT_ESCALATION_TOOLS`). `createHybridTurnProducer` in\n * `/chat-routes` mounts this tool with the turn's single box start.\n */\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { TurnSpan, TurnTrace } from '../turn-trace/recorder'\nimport type { SandboxRuntimeConfig } from './configuration'\nimport type { StreamSandboxPromptOptions } from './prompt-options'\nimport { createComputerStep } from './computer-step'\nimport { SandboxRunError, type SandboxRunFailureCode } from './sandbox-run-error'\nimport { serializeSandboxProvisioningError } from './diagnostics'\nexport { SandboxRunError, type SandboxRunFailureCode } from './sandbox-run-error'\n\n/** The engine's per-call tool context (`RouterTurnToolContext`), kept structural so this module does not import the engine. */\nexport interface SandboxToolContext {\n /** The Router engine's call identity; never derived from task text. */\n callId?: string\n signal?: AbortSignal\n /** The engine-resolved member request, including checkpoint continuation. */\n userMessage?: string\n emit(kind: string, data?: unknown): void\n /** The turn's trace and this call's `tool.call` span (`runRouterTurn` supplies both). The box claim, the box run and the\n * trace id sent to the Sandbox API follow from them; without them nothing is recorded. */\n trace?: TurnTrace\n span?: TurnSpan\n}\n\nexport interface SandboxTaskOptions {\n /** Stable identity of this tool invocation, when the calling engine supplies it. */\n callId?: string\n signal: AbortSignal\n timeoutMs: number\n /** Streams a typed side event from the box run (a progress step, a file written) as the turn's `tool_event`. */\n emit(kind: string, data?: unknown): void\n /** The turn's trace and this call's span, for a runner that streams a prompt (`sandboxPromptRunner` does). */\n trace?: TurnTrace\n span?: TurnSpan\n}\n\nexport interface SandboxRunToolOptions {\n /** The box this call runs in. The product provisions, binds and bills it; this module never\n * creates one. A throw is reported to the model as `sandbox_unavailable`, unless it is a\n * `SandboxRunError`, whose own code and message are kept (an unpaid account, for example). */\n box(signal: AbortSignal): Promise<SandboxInstance>\n /** Runs the task on the box and returns the box agent's final answer: {@link sandboxPromptRunner}\n * for the shell's own prompt path, or the product's runner (skill placement, app-tool MCP, a spend tap). */\n runTask(box: SandboxInstance, task: string, options: SandboxTaskOptions): Promise<string>\n /** The member's original message, preserved verbatim before the Router task. */\n memberRequest?: string\n /** Wall-clock cap for one call, box start included. Default 5 minutes. */\n timeoutMs?: number\n /** Cancels a call in flight, for example the turn's own signal. */\n signal?: AbortSignal\n /** The box's warm lease, so the call is recorded as a turn on it. */\n warm?: { leases: { turn(key: string): Promise<unknown> }; key: string }\n /** Every failure with its cause and the tool call it belongs to. The model only reads the typed message;\n * {@link sandboxRunFailureDetail} is the redacted cause chain to keep. `createHybridTurnProducer` already\n * persists that chain on the turn's warning notice. */\n onFailure?(error: SandboxRunError, call: { callId?: string }): void\n name?: string\n description?: string\n}\n\n/** The tool shape `runRouterTurn` takes (`RouterTurnTool`), kept structural so this module does not import the engine. */\nexport interface SandboxRunTool {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n run(args: Record<string, unknown>, context?: SandboxToolContext): Promise<{ answer: string; ms: number }>\n}\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60_000\nconst TASK_LIMIT = 20_000\n\nexport const SANDBOX_RUN_DESCRIPTION =\n 'Run work that needs a computer in this workspace\\'s sandbox: executing code or scripts, reading or converting ' +\n 'PDFs, spreadsheets and archives, filling forms with the installed toolkits, or editing many files. Describe the ' +\n \"member's requirements, file paths and exact field names, not model-written code; the sandbox agent writes and \" +\n 'runs the code and returns its answer. Takes seconds to minutes, ' +\n 'so use it only when the answer needs the computer.'\n\n/** The redacted cause chain of a computer-step failure, one line, for a durable record: each cause's name, code,\n * status and message, outermost first, credentials and signed URLs removed. */\nexport function sandboxRunFailureDetail(error: unknown): string {\n return serializeSandboxProvisioningError(error).causes\n .map(cause => [cause.name, cause.code !== undefined ? `code=${cause.code}` : '',\n cause.status !== undefined ? `status=${cause.status}` : '', cause.message].filter(Boolean).join(' '))\n .join(' <- ')\n .slice(0, 2_000)\n}\n\n/** The shell's unattended runner: {@link createComputerStep} over the shell, with the session and isolation the\n * prompt names. A supplied execution/turn id seeds the step id with the actual tool callId: different calls stay\n * separate and a retry of that exact call stays idempotent. Without callId, each call sends fresh.\n *\n * Its failure follows the send witness, in a shared and an isolated session alike: a failure before the prompt\n * was handed to the SDK is `sandbox_unavailable` (nothing runs on the box, so the turn may use it again); after\n * it, the step stays unconfirmed. */\nexport function sandboxPromptRunner(shell: SandboxRuntimeConfig, prompt: Omit<StreamSandboxPromptOptions, 'signal' | 'history'> = {}): SandboxRunToolOptions['runTask'] {\n const { executionId, turnId, sessionId, secretProfileIsolation, ...rest } = prompt\n const parent = executionId?.trim() || turnId?.trim()\n return createComputerStep({ shell, prompt: rest, ...(parent ? { parentExecutionId: parent } : {}),\n ...(sessionId ? { session: { id: sessionId, ...(secretProfileIsolation ? { isolated: true } : {}) } } : {}),\n }).runTask\n}\n\nexport function createSandboxRunTool(options: SandboxRunToolOptions): SandboxRunTool {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const runTask = options.runTask\n return {\n name: options.name ?? 'sandbox_run',\n description: options.description ?? SANDBOX_RUN_DESCRIPTION,\n inputSchema: {\n type: 'object',\n properties: { task: { type: 'string', description: 'The member requirements, file paths and exact output field names. The sandbox agent writes and runs the code.' } },\n required: ['task'],\n additionalProperties: false,\n },\n async run(args, context) {\n const fail = (code: SandboxRunFailureCode, message: string, cause?: unknown): never => {\n const error = new SandboxRunError(code, message, cause === undefined ? undefined : { cause })\n options.onFailure?.(error, { ...(context?.callId ? { callId: context.callId } : {}) })\n throw error\n }\n const emit = (kind: string, data?: unknown) => { try { context?.emit(kind, data) } catch { /* a view never fails the call */ } }\n const task = typeof args.task === 'string' ? args.task.trim() : ''\n if (!task || task.length > TASK_LIMIT) {\n return fail('invalid_arguments', `task must be 1 to ${TASK_LIMIT} characters`)\n }\n const started = Date.now()\n const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs),\n ...(options.signal ? [options.signal] : []), ...(context?.signal ? [context.signal] : [])])\n if (options.warm) await options.warm.leases.turn(options.warm.key).catch(() => {})\n // A product's box() may not honour the signal either (a hung provision); the cap still holds.\n const capped = <T,>(work: Promise<T>) => Promise.race([work, new Promise<never>((_, reject) => {\n if (signal.aborted) reject(signal.reason)\n signal.addEventListener('abort', () => reject(signal.reason), { once: true })\n })])\n let box: SandboxInstance\n const claim = context?.span?.child('sandbox.claim', 'sandbox')\n try {\n box = await capped(options.box(signal))\n claim?.end()\n } catch (error) {\n claim?.end(undefined, error instanceof SandboxRunError ? error.code : 'sandbox_unavailable')\n if (error instanceof SandboxRunError) return fail(error.code, error.message, error.cause)\n return fail('sandbox_unavailable', 'The workspace computer could not be acquired. Its availability could not be confirmed.', error)\n }\n emit('box_ready', { ms: Date.now() - started })\n let answer: string\n try {\n // A product runner may not honour the signal; the call still ends at the cap.\n const memberRequest = context?.userMessage ?? options.memberRequest\n const prefix = memberRequest === undefined ? ''\n : `The member's request (verbatim):\\n${memberRequest}\\n\\nYour part of it:\\n`\n // The member contract is never truncated, even when it alone exceeds the task budget.\n const boxTask = prefix + task.slice(0, Math.max(0, TASK_LIMIT - prefix.length))\n answer = await capped(runTask(box, boxTask, {\n signal, timeoutMs: Math.max(1, timeoutMs - (Date.now() - started)), emit,\n ...(context?.callId ? { callId: context.callId } : {}),\n ...(context?.trace ? { trace: context.trace } : {}), ...(context?.span ? { span: context.span } : {}),\n }))\n } catch (error) {\n if (error instanceof SandboxRunError) return fail(error.code, error.message, error.cause)\n const timedOut = signal.aborted && !options.signal?.aborted && !context?.signal?.aborted\n return fail('sandbox_unconfirmed', timedOut\n ? `The computer step did not return an answer within ${Math.round(timeoutMs / 1000)} s. Its completion could not be confirmed.`\n : 'The computer step failed to return an answer. Its completion could not be confirmed.', error)\n }\n if (!answer.trim()) return fail('sandbox_empty', 'The sandbox finished without an answer.')\n return { answer, ms: Date.now() - started }\n },\n }\n}\n","/**\n * `createSandboxExecTool`: the `sandbox_exec` tool a Router turn calls to run\n * one command in the product's box — a toolkit script, a converter, a check —\n * and read its exit code and output. Unlike `sandbox_run` it starts no box\n * agent: the Router model stays in charge and the box only executes.\n *\n * WHY. Tax's Router default lost its Python form toolkit because the lane had\n * no way to reach a box: 685 tool calls, 0 form fills (2026-10). A toolkit\n * the product mounts in the box is reachable from the Router lane only\n * through a command tool.\n *\n * NEVER SILENT. A box that cannot start or be prepared, and a command that\n * cannot run or outruns its cap, come back as a typed `SandboxRunError`\n * (`sandbox_unavailable`, `sandbox_failed`) the model must report. A command\n * that runs and exits non-zero is a result, not a failure: the model reads\n * its exit code and stderr and can correct itself.\n *\n * `prepare` runs once per tool, before the first command (install a runtime,\n * copy the session's documents in). `allow` is the product's command policy.\n */\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { SandboxRunError, type SandboxToolContext } from './sandbox-run-tool'\n\n/** `ExecOptions` from SDK 0.62.2, which sends `traceId` as `x-tangle-trace-id`; spelled here so the tool builds against the pinned older SDK too. */\ntype ExecOptionsWithTrace = NonNullable<Parameters<SandboxInstance['exec']>[1]> & { traceId?: string }\n\nexport interface SandboxExecToolOptions {\n /** The box commands run in. The product provisions, binds and bills it. A throw is\n * `sandbox_unavailable`, unless it is a `SandboxRunError`, which is kept as it is. */\n box(signal: AbortSignal): Promise<SandboxInstance>\n /** Once per tool, before the first command: install a runtime, sync files in. */\n prepare?(box: SandboxInstance, signal: AbortSignal): Promise<void>\n /** Default working directory. */\n cwd?: string\n env?: Record<string, string>\n /** Cap for one command, box start and prepare included. Default 2 minutes. */\n timeoutMs?: number\n /** Characters of stdout and of stderr returned to the model, each; the tail is kept. Default 4 000, so\n * one result stays inside `runRouterTurn`'s default 12 000-character tool-result limit, which keeps the\n * head and would otherwise cut the tail, where errors are. Raise both together. */\n maxOutputChars?: number\n /** The product's command policy: a string refuses the command with that reason. */\n allow?(command: string): string | null\n /** After each command, the files the product wants the model to know about (e.g. its output folder). */\n listFiles?(box: SandboxInstance, signal: AbortSignal): Promise<string[]>\n signal?: AbortSignal\n /** The box's warm lease, so a call is recorded as a turn on it. */\n warm?: { leases: { turn(key: string): Promise<unknown> }; key: string }\n onFailure?(error: SandboxRunError): void\n name?: string\n description?: string\n}\n\nexport interface SandboxExecResult {\n exitCode: number\n stdout: string\n stderr: string\n /** True when stdout or stderr was cut to `maxOutputChars`. */\n truncated: boolean\n ms: number\n files?: string[]\n}\n\nexport interface SandboxExecTool {\n name: string\n description: string\n inputSchema: Record<string, unknown>\n run(args: Record<string, unknown>, context?: SandboxToolContext): Promise<SandboxExecResult>\n}\n\nconst DEFAULT_TIMEOUT_MS = 2 * 60_000\nconst DEFAULT_OUTPUT_CHARS = 4_000\nconst COMMAND_LIMIT = 10_000\n\nexport const SANDBOX_EXEC_DESCRIPTION =\n \"Run one shell command in this workspace's sandbox and get its exit code, stdout and stderr. Use it for the \" +\n 'installed toolkits and scripts, file conversion and checks. A non-zero exit code is a result to read and fix, ' +\n 'not a reason to stop.'\n\nfunction tail(text: string, limit: number): { text: string; cut: boolean } {\n return text.length > limit ? { text: `…${text.slice(-limit)}`, cut: true } : { text, cut: false }\n}\n\nfunction raceAbort<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n return Promise.race([work, new Promise<never>((_, reject) => {\n if (signal.aborted) reject(signal.reason)\n signal.addEventListener('abort', () => reject(signal.reason), { once: true })\n })])\n}\n\nexport function createSandboxExecTool(options: SandboxExecToolOptions): SandboxExecTool {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const outputChars = options.maxOutputChars ?? DEFAULT_OUTPUT_CHARS\n const fail = (code: 'sandbox_unavailable' | 'sandbox_failed' | 'invalid_arguments', message: string, cause?: unknown): never => {\n const error = new SandboxRunError(code, message, cause === undefined ? undefined : { cause })\n options.onFailure?.(error)\n throw error\n }\n let ready: Promise<SandboxInstance> | null = null\n const place = (signal: AbortSignal) => {\n ready ??= (async () => {\n let box: SandboxInstance\n try {\n box = await options.box(signal)\n } catch (error) {\n if (error instanceof SandboxRunError) throw error\n throw new SandboxRunError('sandbox_unavailable', 'The sandbox for this workspace could not start, so the command did not run.', { cause: error })\n }\n try {\n await options.prepare?.(box, signal)\n } catch (error) {\n throw new SandboxRunError('sandbox_unavailable', 'The sandbox could not be prepared for commands, so the command did not run.', { cause: error })\n }\n return box\n })()\n // A failed start is not cached: the next call tries again.\n ready.catch(() => { ready = null })\n return ready\n }\n return {\n name: options.name ?? 'sandbox_exec',\n description: options.description ?? SANDBOX_EXEC_DESCRIPTION,\n inputSchema: {\n type: 'object',\n properties: {\n command: { type: 'string', description: 'One shell command, e.g. `tax-python fill_form.py --form 1040`.' },\n cwd: { type: 'string', description: 'Working directory; defaults to the workspace directory.' },\n },\n required: ['command'],\n additionalProperties: false,\n },\n async run(args, context) {\n const emit = (kind: string, data?: unknown) => { try { context?.emit(kind, data) } catch { /* a view never fails the call */ } }\n const command = typeof args.command === 'string' ? args.command.trim() : ''\n if (!command || command.length > COMMAND_LIMIT) return fail('invalid_arguments', `command must be 1 to ${COMMAND_LIMIT} characters`)\n const refusal = options.allow?.(command)\n if (refusal) return fail('invalid_arguments', refusal)\n const cwd = typeof args.cwd === 'string' && args.cwd.trim() ? args.cwd.trim() : options.cwd\n const started = Date.now()\n const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(options.signal ? [options.signal] : [])])\n if (options.warm) await options.warm.leases.turn(options.warm.key).catch(() => {})\n let box: SandboxInstance\n // A box this tool already placed answers at once; the span says which kind of claim this was.\n const reused = ready !== null\n const claim = context?.span?.child('sandbox.claim', 'sandbox')\n const starting = place(signal)\n try {\n box = await raceAbort(starting, signal)\n } catch (error) {\n claim?.end(undefined, error instanceof SandboxRunError ? error.code : 'sandbox_unavailable')\n // A start that outlived this call's cap may never settle; the next call starts again.\n if (ready === starting) ready = null\n if (error instanceof SandboxRunError) {\n options.onFailure?.(error)\n throw error\n }\n return fail('sandbox_unavailable', 'The sandbox did not start in time, so the command did not run.', error)\n }\n claim?.end({ 'claim.reused': reused })\n emit('box_ready', { ms: Date.now() - started })\n let result: { exitCode: number; stdout: string; stderr: string }\n const execSpan = context?.span?.child('sandbox.exec', 'sandbox')\n try {\n result = await raceAbort(box.exec(command, {\n ...(cwd ? { cwd } : {}),\n ...(options.env ? { env: options.env } : {}),\n timeoutMs: Math.max(1, timeoutMs - (Date.now() - started)),\n // The same id the Router turn sends, so this command's Sandbox API and host records join the turn.\n // SDK 0.62.2 added `traceId` to ExecOptions; an older SDK ignores the field.\n ...(context?.trace ? { traceId: context.trace.traceId } : {}),\n } as ExecOptionsWithTrace), signal)\n execSpan?.end({ 'exec.exit_code': result.exitCode })\n } catch (error) {\n execSpan?.end(undefined, 'exec_failed')\n const timedOut = signal.aborted && !options.signal?.aborted\n return fail('sandbox_failed', timedOut\n ? `The command did not finish within ${Math.round(timeoutMs / 1000)} s.`\n : 'The command could not run in the sandbox.', error)\n }\n const stdout = tail(result.stdout ?? '', outputChars)\n const stderr = tail(result.stderr ?? '', outputChars)\n const files = options.listFiles ? await options.listFiles(box, signal).catch(() => undefined) : undefined\n return { exitCode: result.exitCode, stdout: stdout.text, stderr: stderr.text, truncated: stdout.cut || stderr.cut,\n ms: Date.now() - started, ...(files ? { files } : {}) }\n },\n }\n}\n","import type {\n FencedPrewarmClaimStore,\n PrewarmClaimLease,\n PrewarmClaimState,\n} from './prewarm'\n\n/**\n * `createD1PrewarmClaimStore` — the cross-isolate half of\n * `createSandboxPrewarmer`'s single-flight, implemented once.\n *\n * WHY THIS SHIPS HERE. `SandboxPrewarmerOptions.claim` is REQUIRED and has no\n * default, which is correct — the unsafe behaviour must be said out loud. But\n * \"required with no implementation\" is how five products end up hand-rolling\n * five subtly different atomic leases, and a lease that is subtly wrong is\n * indistinguishable from one that works until two tabs leak a box. Every\n * agent-app product deploys to Cloudflare Workers with a D1 binding, so the\n * store is the same code in all of them: it is mechanism, not domain, and it\n * belongs beside the prewarmer.\n *\n * The measured stake (staging-sandbox): two concurrent\n * `POST /v1/sandboxes` with an identical name BOTH returned HTTP 201 and left\n * two running boxes. The platform does not dedupe by name, so nothing below\n * this line is defensive programming — an unclaimed race genuinely doubles\n * spend.\n *\n * ── ATOMICITY IS THE WHOLE POINT ───────────────────────────────────────────\n * `acquire` is ONE statement. A `SELECT` followed by an `INSERT` is exactly the\n * race this exists to close: both isolates read \"free\", both write, both warm.\n * The upsert's `DO UPDATE ... WHERE expires_at <= now` means an unexpired claim\n * makes the conflict path a no-op, and `RETURNING` then yields no row — so the\n * loser learns it lost from the same statement that would have made it the\n * winner. `RETURNING` is used rather than `meta.changes` because a no-op upsert\n * reporting `changes: 0` is a SQLite detail, whereas \"no row came back\" is the\n * statement telling you directly.\n *\n * Foreground provisioning uses `acquireLease`/`releaseLease`. The lease's\n * returned `expiresAt` is a fencing value: takeover writes a value strictly\n * greater than the expired value, and release changes only the matching value\n * into a signed tombstone. A later acquire advances the absolute value, so a\n * stale release cannot collide even after a same-clock release and reacquire.\n * `inspect` hides the tombstone as `absent`. This uses the published two-column\n * table without changing the legacy `PrewarmClaimStore` methods or requiring a\n * migration.\n *\n * ── STRUCTURAL, NOT A DEPENDENCY ───────────────────────────────────────────\n * The binding is taken as the narrow shape actually used (`prepare().bind()`,\n * `.first()`, `.run()`), per the package's structural-over-hard-dep rule. No\n * `@cloudflare/workers-types` import, so `/sandbox` stays importable in a plain\n * node test. A real `D1Database` satisfies it.\n *\n * ── THE TABLE IS THE PRODUCT'S MIGRATION, NOT A LAZY CREATE ────────────────\n * The store never runs DDL. A `CREATE TABLE IF NOT EXISTS` on every project\n * open costs a round trip on the exact path this feature exists to keep fast,\n * and it hides schema drift instead of failing on it. `PREWARM_CLAIM_TABLE_DDL`\n * is exported so a product pastes it into a real migration. If the table is\n * missing, `acquire` throws — and the prewarmer treats a throwing claim as a\n * failed warm: it records the failure, emits `onEvent({type:'failed'})`, and\n * degrades to the lazy path. Fail-closed and loud, never a silent double-warm.\n */\n\n/** The columns and statements this store uses, and nothing else. A real\n * `D1Database` structurally satisfies it. */\nexport interface PrewarmClaimD1Like {\n prepare(query: string): {\n bind(...values: unknown[]): {\n first<T = Record<string, unknown>>(): Promise<T | null>\n run(): Promise<unknown>\n }\n }\n}\n\nexport interface D1PrewarmClaimStoreOptions {\n /** Defaults to `sandbox_prewarm_claims`. Must be a bare SQL identifier — it\n * is interpolated, because a table name cannot be a bound parameter. */\n table?: string\n /** Clock seam for tests. */\n now?(): number\n}\n\nexport const DEFAULT_PREWARM_CLAIM_TABLE = 'sandbox_prewarm_claims'\n\n/** Paste into a migration. Positive `expires_at` values are epoch MILLISECONDS,\n * matching `Date.now()`. A released fenced claim keeps a negative tombstone so\n * a later lease can advance its fencing value without adding a column. */\nexport const PREWARM_CLAIM_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${DEFAULT_PREWARM_CLAIM_TABLE} (\n key TEXT PRIMARY KEY,\n expires_at INTEGER NOT NULL\n)`\n\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/**\n * A fenced `PrewarmClaimStore` backed by one D1 table.\n *\n * ```ts\n * const prewarmer = createSandboxPrewarmer(shell, {\n * claim: createD1PrewarmClaimStore(env.DB),\n * mode: 'create-or-resume',\n * })\n * ```\n */\nexport function createD1PrewarmClaimStore(\n db: PrewarmClaimD1Like,\n options: D1PrewarmClaimStoreOptions = {},\n): FencedPrewarmClaimStore {\n const table = options.table ?? DEFAULT_PREWARM_CLAIM_TABLE\n // A table name cannot be bound, so it is interpolated — which makes it the\n // one injection surface here. Reject anything that is not a bare identifier\n // at construction time, where the stack still points at the caller.\n if (!SAFE_IDENTIFIER.test(table)) {\n throw new Error(`Invalid prewarm claim table name: ${JSON.stringify(table)}`)\n }\n const now = options.now ?? (() => Date.now())\n\n const acquireSql = `INSERT INTO ${table} (key, expires_at) VALUES (?1, ?2)\nON CONFLICT(key) DO UPDATE SET expires_at = ?2 WHERE ${table}.expires_at <= ?3\nRETURNING key`\n const acquireLeaseSql = `INSERT INTO ${table} (key, expires_at) VALUES (?1, ?2)\nON CONFLICT(key) DO UPDATE SET expires_at = MAX(?2, ABS(${table}.expires_at) + 1)\nWHERE ${table}.expires_at <= ?3\nRETURNING key, expires_at`\n const releaseSql = `DELETE FROM ${table} WHERE key = ?1`\n const releaseLeaseSql = `UPDATE ${table}\nSET expires_at = CASE WHEN expires_at = 0 THEN -1 ELSE -expires_at END\nWHERE key = ?1 AND expires_at = ?2`\n const inspectSql = `SELECT expires_at FROM ${table} WHERE key = ?1`\n\n async function inspect(key: string): Promise<PrewarmClaimState> {\n const row = await db\n .prepare(inspectSql)\n .bind(key)\n .first<{ expires_at: number }>()\n if (!row || row.expires_at < 0) return { status: 'absent' }\n return row.expires_at > now()\n ? { status: 'held', expiresAt: row.expires_at }\n : { status: 'expired', expiresAt: row.expires_at }\n }\n\n return {\n async acquire(key: string, ttlSeconds: number): Promise<boolean> {\n const at = now()\n const row = await db\n .prepare(acquireSql)\n .bind(key, at + ttlSeconds * 1000, at)\n .first<{ key: string }>()\n return row != null\n },\n\n async acquireLease(key: string, ttlSeconds: number): Promise<PrewarmClaimLease | null> {\n const at = now()\n const requestedExpiry = Math.max(1, at + ttlSeconds * 1000)\n const row = await db\n .prepare(acquireLeaseSql)\n .bind(key, requestedExpiry, at)\n .first<{ key: string; expires_at: number }>()\n if (!row) return null\n return Object.freeze({ key: row.key, expiresAt: row.expires_at })\n },\n\n async release(key: string): Promise<void> {\n // Best effort by the `PrewarmClaimStore` contract: the prewarmer swallows\n // a throw here because the TTL is what actually guarantees release.\n await db.prepare(releaseSql).bind(key).run()\n },\n\n async releaseLease(lease: PrewarmClaimLease): Promise<void> {\n await db.prepare(releaseLeaseSql).bind(lease.key, lease.expiresAt).run()\n },\n\n async isHeld(key: string): Promise<boolean> {\n return (await inspect(key)).status === 'held'\n },\n\n inspect,\n }\n}\n","/**\n * Warm receipts: the record that a warm step already ran for exactly the\n * inputs it depends on, so a second warm with the same inputs does no work.\n *\n * A warm step (verify the session, resolve a child key, read the vault heads,\n * build the connected-tool catalog, resume the box) is keyed by what it\n * depends on: identity, workspace, thread, content hash, credential expiry.\n * `createWorkspacePrewarmRoute` looks the key up before it runs the step; an\n * unexpired receipt answers `hit` after one read and the step does not run.\n * The turn reads the same receipt at send to reuse what the warm produced.\n *\n * The receipt store is shared across isolates (D1), because Workers spread one\n * member's requests over many isolates: an in-isolate cache missed on 2 of 3\n * warm turns in Creative staging (connected-tool catalog 928-2,742\n * ms). The route still keeps an in-isolate copy, so a repeat in the same\n * isolate costs no read at all.\n *\n * A receipt's `report` is small JSON the product chooses (a vault head, a\n * catalog digest, a box id). It must never hold a credential: receipts are\n * rows any reader of the table can see.\n */\n\nexport type WarmReceiptReport = Record<string, string | number | boolean | null>\n\nexport interface WarmReceipt {\n /** Epoch ms the step finished. */\n at: number\n /** Epoch ms after which the receipt no longer counts. */\n expiresAt: number\n report?: WarmReceiptReport\n}\n\nexport interface WarmReceiptStore {\n get(id: string): Promise<WarmReceipt | null>\n put(id: string, receipt: WarmReceipt): Promise<void>\n}\n\n/** The receipt id for one step and its key. */\nexport function warmReceiptId(step: string, key: string): string {\n return `${step}:${key}`\n}\n\n/**\n * A warm key from exactly the values a step depends on: the same values give\n * the same key whatever their order, and any change gives a new one. Values\n * are hashed (SHA-256, hex), so a key names no member, path or expiry in the\n * clear. Pass a credential's expiry or revision, never the credential.\n */\nexport async function warmKey(parts: Record<string, string | number | boolean | null>): Promise<string> {\n // A missing value would give every member the same key and serve one member's receipt to another.\n const missing = Object.keys(parts).filter((name) => parts[name] === undefined)\n if (missing.length) throw new Error(`warmKey: ${missing.join(', ')} undefined`)\n const canonical = JSON.stringify(Object.keys(parts).sort().map((name) => [name, parts[name]]))\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonical))\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/** Receipts in one isolate's memory: for tests and single-process hosts. */\nexport function createMemoryWarmReceiptStore(options: { limit?: number } = {}): WarmReceiptStore {\n const limit = options.limit ?? 1_000\n const receipts = new Map<string, WarmReceipt>()\n return {\n async get(id) {\n return receipts.get(id) ?? null\n },\n async put(id, receipt) {\n receipts.delete(id)\n receipts.set(id, receipt)\n for (const old of receipts.keys()) {\n if (receipts.size <= limit) break\n receipts.delete(old)\n }\n },\n }\n}\n\n/** The D1 surface the store uses. A real `D1Database` satisfies it. */\nexport interface WarmReceiptD1Like {\n prepare(query: string): {\n bind(...values: unknown[]): {\n first<T = Record<string, unknown>>(): Promise<T | null>\n run(): Promise<unknown>\n }\n }\n}\n\nexport const DEFAULT_WARM_RECEIPT_TABLE = 'warm_receipts'\n\n/** Paste into a product migration; the store never runs DDL. Times are epoch ms. */\nexport const WARM_RECEIPT_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${DEFAULT_WARM_RECEIPT_TABLE} (\n id TEXT PRIMARY KEY,\n at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL,\n report TEXT\n);\nCREATE INDEX IF NOT EXISTS ${DEFAULT_WARM_RECEIPT_TABLE}_by_expiry ON ${DEFAULT_WARM_RECEIPT_TABLE} (expires_at)`\n\n/** One write in this many also deletes expired rows, so a table keyed by content hashes stays bounded. */\nconst PRUNE_EVERY_WRITES = 64\n\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/**\n * Receipts in one D1 table, shared by every isolate. A missing table throws on\n * the first read, which the route treats as a miss: the step runs, and the\n * failure reaches `onEvent`.\n */\nexport function createD1WarmReceiptStore(db: WarmReceiptD1Like, options: { table?: string; now?: () => number } = {}): WarmReceiptStore {\n const table = options.table ?? DEFAULT_WARM_RECEIPT_TABLE\n if (!SAFE_IDENTIFIER.test(table)) throw new Error(`Invalid warm receipt table name: ${JSON.stringify(table)}`)\n const getSql = `SELECT at, expires_at, report FROM ${table} WHERE id = ?1`\n const putSql = `INSERT INTO ${table} (id, at, expires_at, report) VALUES (?1, ?2, ?3, ?4)\nON CONFLICT(id) DO UPDATE SET at = ?2, expires_at = ?3, report = ?4`\n const pruneSql = `DELETE FROM ${table} WHERE expires_at < ?1`\n const now = options.now ?? (() => Date.now())\n let writes = 0\n return {\n async get(id) {\n const row = await db.prepare(getSql).bind(id).first<{ at: number; expires_at: number; report: string | null }>()\n if (!row) return null\n return {\n at: row.at,\n expiresAt: row.expires_at,\n ...(row.report ? { report: JSON.parse(row.report) as WarmReceiptReport } : {}),\n }\n },\n async put(id, receipt) {\n await db.prepare(putSql).bind(id, receipt.at, receipt.expiresAt, receipt.report ? JSON.stringify(receipt.report) : null).run()\n if (++writes % PRUNE_EVERY_WRITES === 0) await db.prepare(pruneSql).bind(now()).run()\n },\n }\n}\n","/** Shared D1 replay and authenticated workspace locks from the application's bindings. */\nimport { createD1TurnEventStore, type TurnEventStore, type D1LikeForTurns } from '../stream/turn-buffer'\nimport { createDurableTurnLock, type TurnStreamNamespaceLike, type TurnStreamAuth, type TurnStreamLocationHint } from '../turn-stream/adapters'\nimport type { CreateChatTurnRoutesOptions } from './turn-route-contracts'\n\n/** One application binding descriptor, shared by chat admission and workspace prewarm. */\nexport interface ChatTurnStoreBindings {\n db: D1LikeForTurns\n /** The app's D1 region, also used as the placement hint for new lock channels. Default: enam. */\n region?: TurnStreamLocationHint\n lock: { namespace: TurnStreamNamespaceLike; auth: TurnStreamAuth }\n}\n\n/** Keep the workspace-channel identity, authentication and region the same in both routes. */\nexport function createDefaultTurnLock<TContext>(store: Pick<ChatTurnStoreBindings, 'lock' | 'region'>) {\n return createDurableTurnLock<TContext>({ ...store.lock, locationHint: store.region, scopeOf: () => 'workspace' })\n}\n\nexport type ResolvedChatTurnRoutesOptions<TContext, TResource = unknown> = Omit<CreateChatTurnRoutesOptions<TContext, TResource>, 'turnStore' | 'turnLock' | 'produce'> & {\n turnStore: TurnEventStore\n turnLock?: Exclude<CreateChatTurnRoutesOptions<TContext, TResource>['turnLock'], false>\n produce: Exclude<CreateChatTurnRoutesOptions<TContext, TResource>['produce'], undefined | import('./default-backend').ChatTurnDefaultBackend<TContext, TResource>>\n}\n\nexport function turnStorageBindings(options: { turnStore: TurnEventStore | ChatTurnStoreBindings; env?: import('./default-backend').ChatTurnEnvironment }): ChatTurnStoreBindings | undefined {\n if (!('append' in options.turnStore)) return options.turnStore\n const env = options.env\n const namespace = env?.TURN_STREAM ?? env?.TURN_STREAM_DO\n if (!env?.DB || !namespace || !env.TURN_STREAM_AUTH_SECRET) return undefined\n return { db: env.DB, region: env.D1_REGION, lock: { namespace, auth: { secret: env.TURN_STREAM_AUTH_SECRET } } }\n}\n\nexport function resolveTurnStorage<TContext, TResource>(options: CreateChatTurnRoutesOptions<TContext, TResource>) {\n const bindings = turnStorageBindings(options)\n const env = options.env\n const namespace = env?.TURN_STREAM ?? env?.TURN_STREAM_DO\n const lockBindings = bindings ?? (namespace && env?.TURN_STREAM_AUTH_SECRET ? {\n region: env.D1_REGION, lock: { namespace, auth: { secret: env.TURN_STREAM_AUTH_SECRET } },\n } : undefined)\n return {\n turnStore: 'append' in options.turnStore ? options.turnStore : createD1TurnEventStore(options.turnStore.db),\n turnLock: options.turnLock === false ? undefined : options.turnLock ?? (lockBindings ? createDefaultTurnLock<TContext>(lockBindings)\n : env ? { acquire: () => ({ acquired: false as const, response: Response.json({ error: 'Durable turn locking is not configured', code: 'chat.lock_not_configured' }, { status: 503 }) }), release: () => {} } : undefined),\n }\n}\n","/**\n * `createWorkspacePrewarmRoute`: the HTTP face of prewarm-on-open, so every\n * agent-app product warms the same way. The browser half is\n * `useWorkspacePrewarm` in `/web-react`: it POSTs here when a member opens a\n * workspace page in a visible tab, and again when they focus the composer.\n *\n * WHAT THE PRODUCT SUPPLIES. Only `authorize`. It authenticates the member\n * from the request exactly as the product's other routes do and returns the\n * warm to run: a box resume, a profile preparation, or `createSandboxPrewarmer`\n * from this subpath. The route owns everything shared: bot and prefetch\n * refusal, per-key single-flight, a short success memory, timing, and the rule\n * that a warm never reaches the member as an error.\n *\n * WHY THE WARM RUNS INSIDE THE REQUEST. A suspended box takes ~31 s to resume\n * (Hospitality production), past the 30 s that Cloudflare's\n * `waitUntil` grants after a response. Awaiting the warm keeps the request\n * open for as long as the member's tab is, which is exactly as long as a warm\n * is useful. The browser never awaits it for UI.\n *\n * IDEMPOTENCE. The in-process record only collapses concurrent calls within\n * one isolate, and a second call answers `joined` at once instead of awaiting\n * the first: on Workers a warm's I/O belongs to the request that started it, so\n * when that request is cancelled (the member navigates) its promise never\n * settles, and requests awaiting it hung 43-45 s (Hospitality production).\n * A record older than `staleMs` no longer counts. Two isolates can\n * both run the warm, so the product's warm must be safe to repeat: a resume of\n * a running box is a no-op, and a creation needs a claim store (see\n * `createSandboxPrewarmer`).\n *\n * FAILURE. A thrown warm answers 200 `{ outcome: 'failed' }` without the error\n * text, which can name internal hosts. `onEvent` receives the error so the\n * product can log it. The next real turn takes its normal placement path.\n *\n * STEPS AND RECEIPTS. Warm once: `authorize` may return `steps`, each keyed by\n * exactly what it depends on (see `warmKey`). With a `receipts` store, a step\n * whose key holds an unexpired receipt answers `hit` after one read and does not\n * run; a changed key or an expired receipt runs it again (`miss`) and writes a\n * new receipt. Steps run concurrently. The response lists each step's outcome\n * and time, and its `Server-Timing` header carries one `warm.<step>` entry per\n * step with `hit`, `miss`, `joined` or `failed`, so a caller reads every miss.\n */\nimport { formatServerTiming } from '../turn-trace/server-timing'\nimport { warmReceiptId, warmKey, createD1WarmReceiptStore, type WarmReceiptStore } from './warm-receipts'\nimport { createDefaultTurnLock, type ChatTurnStoreBindings } from '../chat-routes/route-storage'\nimport { DEFAULT_TURN_LOCK_LOCATION_HINT } from '../turn-stream/adapters'\n\n/** What the product decided for this request. */\nexport type WorkspacePrewarmAuthorization =\n /** Not signed in, not a member, or a foreign origin: return this response. */\n | { status: 'denied'; response: Response }\n /** A signed-in member the product does not warm for (a role that cannot\n * chat, a box mid-upgrade). Answers 200 so the browser stays quiet. */\n | { status: 'declined'; reason: string }\n /**\n * Run `warm` once per `key` at a time. `key` names what is warmed, such as\n * the box; members who share a box share a key. `warm` may return a small\n * JSON-safe report for the response and `onEvent`.\n */\n | { status: 'allowed'; workspaceId?: string; key: string; warm: () => Promise<WorkspacePrewarmReport | void> }\n /** Run each step whose key has no unexpired receipt. */\n | { status: 'allowed'; workspaceId?: string; steps: readonly WorkspaceWarmStep[] }\n\n/** One warm step, keyed by exactly what it depends on. */\nexport interface WorkspaceWarmStep {\n /** A short name, unique within the response: `session`, `vault_heads`, `tool_catalog`, `box`. */\n name: string\n /** What the step depends on (`warmKey({ userId, workspaceId, vaultHead })`). Members who share the result share the key. */\n key: string\n /** How long a successful run counts. Keep it shorter than the warmed thing's own idle expiry (a box that suspends\n * after 5 idle minutes gets a TTL well under that), because a receipt cannot see the thing go cold. */\n ttlMs: number\n /** Do the work. The report, small JSON and never a credential, is stored on the receipt for the turn to read. */\n run: () => Promise<WorkspacePrewarmReport | void>\n}\n\n/** Why the browser asked: `useWorkspacePrewarm` sends `page-open`, `composer-focus`, or `heartbeat` while the tab stays open. */\nexport type WorkspacePrewarmReason = 'page-open' | 'composer-focus' | 'heartbeat'\n\nexport type WorkspaceWarmStepOutcome = 'hit' | 'miss' | 'joined' | 'failed'\n\nexport interface WorkspaceWarmStepResult {\n name: string\n outcome: WorkspaceWarmStepOutcome\n ms: number\n}\n\nexport type WorkspacePrewarmReport = Record<string, string | number | boolean | null>\n\nexport type WorkspacePrewarmOutcome =\n /** This request ran the warm to completion. */\n | 'warmed'\n /** Another request in this isolate is already running it; this one answered at once. */\n | 'joined'\n /** The same key warmed successfully within `recentMs`; nothing ran. */\n | 'recent'\n | 'declined'\n /** A crawler, link preview, or speculative prefetch; nothing ran. */\n | 'automated'\n | 'failed'\n\nexport interface WorkspacePrewarmResponse {\n outcome: WorkspacePrewarmOutcome\n /** Time this request spent, including any warm it ran. A `joined` answer never waits. */\n ms: number\n reason?: string\n report?: WorkspacePrewarmReport\n /** Each step's outcome, for an authorization that returned `steps`. */\n steps?: WorkspaceWarmStepResult[]\n}\n\nexport type WorkspacePrewarmEvent =\n | { type: 'warmed'; key: string; ms: number; report?: WorkspacePrewarmReport }\n | { type: 'failed'; key: string; ms: number; error: string }\n /** One step of a stepped warm; `failed` carries the error. */\n | { type: 'step'; name: string; key: string; outcome: WorkspaceWarmStepOutcome; ms: number; error?: string }\n\nexport interface CreateWorkspacePrewarmRouteOptions<Context = void> {\n /** The same binding descriptor chat uses. Adds the keyed turn_lock warm by default.\n * An allowed authorization must carry its server-verified workspaceId; request body identity is never used.\n * Receipts default to this database; apply WARM_RECEIPT_TABLE_DDL through the product migration runner. */\n turnStore?: ChatTurnStoreBindings\n /** `context` is whatever the caller passed beside the request, such as a\n * Hono context carrying the Worker's bindings. */\n /** `threadId` is the thread the composer belongs to, when the browser sent one (composer focus). Check the member's access to it before warming anything for it. */\n authorize(input: { request: Request; context: Context; reason: WorkspacePrewarmReason; threadId?: string }): Promise<WorkspacePrewarmAuthorization>\n /** Where step receipts live across isolates (`createD1WarmReceiptStore`). Without it, receipts last for this isolate only. */\n receipts?: WarmReceiptStore\n /** After a successful warm, answer `recent` for this long. Default 30 000 ms. */\n recentMs?: number\n /** A warm started longer ago than this no longer blocks the key: its request\n * may have been cancelled, taking the warm with it. A longer warm still\n * running is repeated, which is safe because warms must be idempotent.\n * Default 45 000 ms (a suspended box resumes in ~31 s). */\n staleMs?: number\n /** Observability for warms this route ran. Errors thrown here are ignored. */\n onEvent?(event: WorkspacePrewarmEvent): void\n /** Clock seam for tests. */\n now?(): number\n}\n\n// Crawlers and link-preview fetchers. Headless browsers are deliberately absent:\n// signed-in QA drives a headless browser through this same path.\nconst AUTOMATED_AGENT =\n /bot\\b|crawler|spider|slurp|facebookexternalhit|embedly|preview|whatsapp|curl\\/|wget\\/|python-requests|go-http-client/i\n\n/** True for crawler user agents and browser speculative prefetch or prerender. */\nexport function isAutomatedPrewarmRequest(request: Request): boolean {\n const purpose = `${request.headers.get('sec-purpose') ?? ''} ${request.headers.get('purpose') ?? ''}`\n if (/prefetch|prerender/i.test(purpose)) return true\n return AUTOMATED_AGENT.test(request.headers.get('user-agent') ?? '')\n}\n\nconst RECENT_LIMIT = 1_000\n\nconst REASONS: readonly WorkspacePrewarmReason[] = ['page-open', 'composer-focus', 'heartbeat']\nconst THREAD_ID = /^[A-Za-z0-9_:.-]{1,128}$/\n\nasync function requestIntent(request: Request): Promise<{ reason: WorkspacePrewarmReason; threadId?: string } | undefined> {\n if (Number(request.headers.get('content-length') ?? 0) > 1_024) return undefined\n try {\n // A clone, so a product's authorize can still read the body.\n const body = (await request.clone().json()) as { reason?: unknown; threadId?: unknown } | null\n const reason = REASONS.find((known) => known === body?.reason) ?? 'page-open'\n const threadId = body?.threadId\n if (threadId !== undefined && (typeof threadId !== 'string' || !THREAD_ID.test(threadId))) return undefined\n return { reason, ...(typeof threadId === 'string' ? { threadId } : {}) }\n } catch {\n return { reason: 'page-open' }\n }\n}\n\nfunction reply(body: WorkspacePrewarmResponse, status = 200): Response {\n const headers: Record<string, string> = { 'Cache-Control': 'private, no-store' }\n if (body.steps?.length) {\n headers['Server-Timing'] = formatServerTiming(body.steps.map((step) => ({ name: `warm.${step.name}`, dur: step.ms, desc: step.outcome })))\n }\n return Response.json(body, { status, headers })\n}\n\n/**\n * Build the handler once per isolate, not per request: its single-flight and\n * success memory live in the returned closure.\n */\nexport function createWorkspacePrewarmRoute<Context = void>(\n options: CreateWorkspacePrewarmRouteOptions<Context>,\n): (request: Request, context: Context) => Promise<Response> {\n const turnLock = options.turnStore ? createDefaultTurnLock(options.turnStore) : undefined\n const receipts = options.receipts ?? (options.turnStore ? createD1WarmReceiptStore(options.turnStore.db) : undefined)\n const recentMs = options.recentMs ?? 30_000\n const now = options.now ?? (() => Date.now())\n const staleMs = options.staleMs ?? 45_000\n // Start times, never promises: no request may await I/O another request owns.\n const inFlight = new Map<string, { at: number }>()\n const recent = new Map<string, number>()\n // Step receipt id -> the epoch ms its receipt stops counting, this isolate's copy of the store.\n const warmUntil = new Map<string, number>()\n // Steps keep their own in-flight marks, so a legacy key can never collide with a step id.\n const stepsInFlight = new Map<string, { at: number }>()\n\n const emit = (event: WorkspacePrewarmEvent): void => {\n try {\n options.onEvent?.(event)\n } catch {\n // Logging must not change the warm's outcome.\n }\n }\n\n const remember = (key: string, at: number, into = recent): void => {\n into.delete(key)\n into.set(key, at)\n // Insertion order is age order, so the oldest entries go first.\n for (const old of into.keys()) {\n if (into.size <= RECENT_LIMIT) break\n into.delete(old)\n }\n }\n\n async function run(key: string, warm: () => Promise<WorkspacePrewarmReport | void>): Promise<WorkspacePrewarmResponse> {\n const started = now()\n try {\n const report = (await warm()) ?? undefined\n const ms = now() - started\n remember(key, now())\n emit({ type: 'warmed', key, ms, ...(report ? { report } : {}) })\n return { outcome: 'warmed', ms, ...(report ? { report } : {}) }\n } catch (err) {\n const ms = now() - started\n emit({ type: 'failed', key, ms, error: err instanceof Error ? err.message : String(err) })\n return { outcome: 'failed', ms }\n }\n }\n\n /** One step: an unexpired receipt in this isolate or the store answers `hit`; otherwise run it and write the receipt. */\n async function runStep(step: WorkspaceWarmStep): Promise<WorkspaceWarmStepResult> {\n const started = now()\n const id = warmReceiptId(step.name, step.key)\n const result = (outcome: WorkspaceWarmStepOutcome, error?: string): WorkspaceWarmStepResult => {\n const ms = now() - started\n emit({ type: 'step', name: step.name, key: step.key, outcome, ms, ...(error ? { error } : {}) })\n return { name: step.name, outcome, ms }\n }\n const local = warmUntil.get(id)\n if (local !== undefined && now() < local) return result('hit')\n const running = stepsInFlight.get(id)\n if (running && now() - running.at < staleMs) return result('joined')\n const mark = { at: now() }\n stepsInFlight.set(id, mark)\n try {\n if (receipts) {\n try {\n const stored = await receipts.get(id)\n if (stored && now() < stored.expiresAt) {\n remember(id, stored.expiresAt, warmUntil)\n return result('hit')\n }\n } catch (err) {\n // An unreadable store is a miss: warms are safe to repeat.\n emit({ type: 'failed', key: id, ms: now() - started, error: err instanceof Error ? err.message : String(err) })\n }\n }\n let report: WorkspacePrewarmReport | undefined\n try {\n report = (await step.run()) ?? undefined\n } catch (err) {\n return result('failed', err instanceof Error ? err.message : String(err))\n }\n const at = now()\n const expiresAt = at + step.ttlMs\n remember(id, expiresAt, warmUntil)\n if (receipts) {\n await receipts.put(id, { at, expiresAt, ...(report ? { report } : {}) }).catch((err: unknown) => {\n emit({ type: 'failed', key: id, ms: now() - started, error: err instanceof Error ? err.message : String(err) })\n })\n }\n return result('miss')\n } finally {\n if (stepsInFlight.get(id) === mark) stepsInFlight.delete(id)\n }\n }\n\n async function runLegacy(key: string, warm: () => Promise<WorkspacePrewarmReport | void>): Promise<WorkspacePrewarmResponse> {\n const started = now()\n const running = inFlight.get(key)\n if (running && now() - running.at < staleMs) return { outcome: 'joined', ms: now() - started }\n const warmedAt = recent.get(key)\n if (warmedAt !== undefined && now() - warmedAt < recentMs) return { outcome: 'recent', ms: now() - started }\n const mark = { at: now() }\n inFlight.set(key, mark)\n try {\n return { ...(await run(key, warm)), ms: now() - started }\n } finally {\n if (inFlight.get(key) === mark) inFlight.delete(key)\n }\n }\n\n return async function prewarm(request: Request, context: Context): Promise<Response> {\n const started = now()\n if (request.method !== 'POST') {\n return new Response(null, { status: 405, headers: { Allow: 'POST' } })\n }\n if (isAutomatedPrewarmRequest(request)) return reply({ outcome: 'automated', ms: 0 })\n\n const intent = await requestIntent(request)\n if (!intent) return reply({ outcome: 'declined', ms: now() - started, reason: 'invalid_thread' })\n let auth: WorkspacePrewarmAuthorization\n try {\n auth = await options.authorize({ request, context, ...intent })\n } catch (err) {\n // An authorization that cannot decide refuses; it never warms.\n emit({ type: 'failed', key: '', ms: now() - started, error: err instanceof Error ? err.message : String(err) })\n return reply({ outcome: 'failed', ms: now() - started })\n }\n if (auth.status === 'denied') return auth.response\n if (auth.status === 'declined') return reply({ outcome: 'declined', ms: now() - started, reason: auth.reason })\n const steps = 'steps' in auth ? [...auth.steps] : []\n let lockFailure: WorkspaceWarmStepResult | undefined\n if (turnLock) {\n if (!auth.workspaceId?.trim()) return reply({ outcome: 'failed', ms: now() - started, reason: 'Lock prewarm requires an authorized workspaceId' })\n const workspaceId = auth.workspaceId\n if (steps.some(step => step.name === 'turn_lock')) return reply({ outcome: 'failed', ms: now() - started, reason: 'turn_lock is owned by the shared prewarm route' })\n try {\n steps.push({ name: 'turn_lock', key: await warmKey({ workspaceId,\n channel: String(options.turnStore!.lock.namespace.idFromName(workspaceId)), region: options.turnStore!.region ?? DEFAULT_TURN_LOCK_LOCATION_HINT }),\n ttlMs: 30_000, run: async () => { await turnLock.warm({ tenantId: workspaceId }); return { lockReady: true } },\n })\n } catch (error) {\n const ms = now() - started\n lockFailure = { name: 'turn_lock', outcome: 'failed', ms }\n emit({ type: 'step', name: 'turn_lock', key: workspaceId, outcome: 'failed', ms,\n error: error instanceof Error ? error.message : String(error) })\n }\n }\n const pendingSteps = Promise.all(steps.map(step => runStep(step))).then(results => lockFailure ? [...results, lockFailure] : results)\n if ('steps' in auth) {\n const results = await pendingSteps\n const outcome: WorkspacePrewarmOutcome = results.some(step => step.outcome === 'failed') ? 'failed'\n : results.some(step => step.outcome === 'miss') ? 'warmed'\n : results.some(step => step.outcome === 'joined') ? 'joined' : 'recent'\n return reply({ outcome, ms: now() - started, steps: results })\n }\n const [legacy, results] = await Promise.all([runLegacy(auth.key, auth.warm), pendingSteps])\n const outcome: WorkspacePrewarmOutcome = legacy.outcome === 'failed' || results.some(step => step.outcome === 'failed') ? 'failed'\n : legacy.outcome === 'warmed' || results.some(step => step.outcome === 'miss') ? 'warmed'\n : legacy.outcome === 'joined' || results.some(step => step.outcome === 'joined') ? 'joined' : legacy.outcome\n return reply({ ...legacy, outcome, ms: now() - started, ...(results.length ? { steps: results } : {}) })\n }\n}\n","/** Settle a caller's read/wait promptly. The operation must forward the signal\n * to its transport; this wrapper alone never proves remote absence. Do not use\n * it to abandon a lease acquisition or a lifecycle ownership transition. */\nexport function awaitSandboxRead<T>(operation: (signal?: AbortSignal) => Promise<T>, signal?: AbortSignal): Promise<T> {\n signal?.throwIfAborted()\n if (!signal) return operation()\n return new Promise<T>((resolve, reject) => {\n const aborted = () => { signal.removeEventListener('abort', aborted); reject(signal.reason) }\n signal.addEventListener('abort', aborted, { once: true })\n Promise.resolve().then(() => { signal.throwIfAborted(); return operation(signal) }).then(\n value => { signal.removeEventListener('abort', aborted); resolve(value) },\n error => { signal.removeEventListener('abort', aborted); reject(error) },\n )\n })\n}\n\n/** Cancel a polling delay without leaving a default timer or listener. */\nexport function waitForSandboxPoll(ms: number, signal?: AbortSignal, wait?: (ms: number) => Promise<void>): Promise<void> {\n signal?.throwIfAborted()\n return new Promise<void>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const finish = (error?: unknown) => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', aborted)\n if (error !== undefined) reject(error)\n else resolve()\n }\n const aborted = () => finish(signal!.reason)\n signal?.addEventListener('abort', aborted, { once: true })\n if (wait) Promise.resolve().then(() => { signal?.throwIfAborted(); return wait(ms) }).then(() => finish(), finish)\n else timer = setTimeout(() => finish(), ms)\n })\n}\n","/**\n * Serialize request-time sandbox provisioning across Worker isolates.\n *\n * Background prewarming can lose a race without delaying a request. A real\n * user turn cannot: its losing request must wait for the owner, adopt the box\n * that became ready, or report why the owner did not leave a usable box.\n *\n * The lease serializes the steps that create billable boxes or change a box's\n * lifecycle. A turn on a box that is already running takes none of them, so it\n * passes `reuse` and takes no lease.\n */\n\nimport type { Harness } from '../harness/index'\nimport type { TurnSpan, TurnTrace } from '../turn-trace/recorder'\nimport type { PeekWorkspaceSandboxOutcome } from './index'\nimport { awaitSandboxRead, waitForSandboxPoll } from './request-cancellation'\nimport {\n sandboxPrewarmClaimKey,\n type FencedPrewarmClaimStore,\n type PrewarmClaimLease,\n} from './prewarm'\n\nexport const DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS = 180\nexport const DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS = 5_000\n\nexport type ReadyRunningSandboxOutcome = Extract<\n PeekWorkspaceSandboxOutcome,\n { status: 'running' }\n> & {\n box: Extract<PeekWorkspaceSandboxOutcome, { status: 'running' }>['box'] & {\n filesystemIncarnationReadiness: 'ready'\n }\n}\n\nexport class SandboxProvisioningFailedElsewhereError extends Error {\n readonly code = 'sandbox.provisioning_failed_elsewhere'\n\n constructor(\n readonly workspaceId: string,\n readonly state: string,\n ) {\n super(\n `Sandbox provisioning for workspace ${workspaceId} failed in another request ` +\n `(state=${state})`,\n )\n this.name = 'SandboxProvisioningFailedElsewhereError'\n }\n}\n\nexport class SandboxFilesystemNotReadyError extends Error {\n readonly code = 'sandbox.filesystem_not_ready'\n readonly retryable = true\n\n constructor(\n readonly workspaceId: string,\n readonly readiness: 'transitioning' | 'missing',\n ) {\n super(`Sandbox filesystem for workspace ${workspaceId} is ${readiness}`)\n this.name = 'SandboxFilesystemNotReadyError'\n }\n}\n\nexport type ForegroundSandboxSingleFlightEvent =\n | { type: 'waiting'; key: string; workspaceId: string }\n | { type: 'release-failed'; key: string; workspaceId: string; error: string }\n\nexport interface ForegroundSandboxSingleFlightOptions<T> {\n claim: FencedPrewarmClaimStore\n /** Cancel this caller's waits. `provision` must forward the same signal to\n * its transport. An aborted owner retains its lease until expiry because a\n * canceled request does not prove the remote lifecycle operation absent. */\n signal?: AbortSignal\n workspaceId: string\n harness: Harness\n /**\n * Take the box that is already running, or resolve undefined. It runs before\n * the lease and must not create, resume, restart, replace or delete a box\n * (`reuseWorkspaceSandbox` is that). The box is used only when no other\n * request holds the lease, because a holder may be changing it.\n */\n reuse?(signal?: AbortSignal): Promise<T | undefined>\n provision(): Promise<T>\n peek(signal?: AbortSignal): Promise<PeekWorkspaceSandboxOutcome>\n adopt(box: ReadyRunningSandboxOutcome): T | Promise<T>\n onEvent?(event: ForegroundSandboxSingleFlightEvent): void\n wait?(ms: number): Promise<void>\n claimTtlSeconds?: number\n pollIntervalMs?: number\n /** The turn's trace: the lease reads and writes are recorded as `sandbox.lease.*` spans. */\n trace?: TurnTrace\n traceParent?: TurnSpan\n}\n\nfunction failedState(peek: PeekWorkspaceSandboxOutcome): string {\n return peek.status === 'not-running' ? peek.state : 'absent'\n}\n\nfunction isReadyRunningSandbox(\n peek: PeekWorkspaceSandboxOutcome,\n): peek is ReadyRunningSandboxOutcome {\n return (\n peek.status === 'running' &&\n peek.box.filesystemIncarnationReadiness === 'ready'\n )\n}\n\nfunction positiveNumber(value: number, name: string): number {\n if (!Number.isFinite(value) || value <= 0) {\n throw new RangeError(`${name} must be a positive finite number`)\n }\n return value\n}\n\nfunction safeErrorText(error: unknown): string {\n try {\n if (error instanceof Error) {\n const message = error.message\n if (typeof message === 'string' && message) return message\n }\n } catch {\n // Error values can be proxies or custom subclasses with hostile getters.\n }\n\n try {\n if (error !== null && (typeof error === 'object' || typeof error === 'function')) {\n const message = Reflect.get(error, 'message')\n if (typeof message === 'string' && message) return message\n }\n } catch {\n // A hostile proxy must not replace the successful provision result.\n }\n\n try {\n const text = typeof error === 'string' ? error : String(error)\n return text || 'unknown error'\n } catch {\n return 'unknown error'\n }\n}\n\n/**\n * Run one foreground provision or adopt the ready result from its current\n * owner. An expired retained claim permits takeover. A released claim without\n * a usable box reports the prior attempt instead of starting a retry storm.\n */\nexport async function runForegroundSandboxSingleFlight<T>(\n options: ForegroundSandboxSingleFlightOptions<T>,\n): Promise<T> {\n options.signal?.throwIfAborted()\n const key = sandboxPrewarmClaimKey(options)\n const ttlSeconds = positiveNumber(\n options.claimTtlSeconds ?? DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,\n 'claimTtlSeconds',\n )\n const pollIntervalMs = positiveNumber(\n options.pollIntervalMs ?? DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS,\n 'pollIntervalMs',\n )\n const wait = (ms: number) => waitForSandboxPoll(ms, options.signal, options.wait)\n\n const emit = (event: ForegroundSandboxSingleFlightEvent): void => {\n try {\n options.onEvent?.(event)\n } catch {\n // Observability cannot decide whether provisioning succeeds.\n }\n }\n\n const timed = <R,>(name: string, work: () => Promise<R>): Promise<R> =>\n options.trace\n ? options.trace.measure(name, 'sandbox', () => work(), undefined, options.traceParent)\n : work()\n\n const provisionAsOwner = async (lease: PrewarmClaimLease): Promise<T> => {\n try {\n options.signal?.throwIfAborted()\n const result = await options.provision()\n options.signal?.throwIfAborted()\n return result\n } finally {\n try {\n if (!options.signal?.aborted) {\n await timed('sandbox.lease.release', () => options.claim.releaseLease(lease))\n }\n } catch (error) {\n emit({\n type: 'release-failed',\n key,\n workspaceId: options.workspaceId,\n error: safeErrorText(error),\n })\n }\n }\n }\n\n if (options.reuse) {\n // One read of the lease, beside the reuse, replaces the lease's two writes.\n const [state, reused] = await awaitSandboxRead(() => Promise.allSettled([\n timed('sandbox.lease.inspect', () => options.claim.inspect(key)),\n options.reuse!(options.signal),\n ]), options.signal)\n options.signal?.throwIfAborted()\n if (reused.status === 'rejected') throw reused.reason\n if (reused.value !== undefined && state.status === 'fulfilled' && state.value.status !== 'held') {\n return reused.value\n }\n }\n\n const initialLease = await timed('sandbox.lease.acquire', () => options.claim.acquireLease(key, ttlSeconds))\n if (initialLease) return provisionAsOwner(initialLease)\n options.signal?.throwIfAborted()\n\n emit({ type: 'waiting', key, workspaceId: options.workspaceId })\n while (true) {\n await wait(pollIntervalMs)\n const [peek, claim] = await awaitSandboxRead(() => Promise.all([\n options.peek(options.signal),\n options.claim.inspect(key),\n ]), options.signal)\n options.signal?.throwIfAborted()\n\n if (claim.status === 'held') continue\n if (peek.status === 'warming') {\n throw new SandboxFilesystemNotReadyError(options.workspaceId, 'transitioning')\n }\n if (isReadyRunningSandbox(peek)) {\n const adopted = await options.adopt(peek)\n options.signal?.throwIfAborted()\n return adopted\n }\n if (peek.status === 'running') {\n throw new SandboxFilesystemNotReadyError(\n options.workspaceId,\n peek.box.filesystemIncarnationReadiness === 'transitioning'\n ? 'transitioning'\n : 'missing',\n )\n }\n\n if (claim.status === 'absent') {\n throw new SandboxProvisioningFailedElsewhereError(\n options.workspaceId,\n failedState(peek),\n )\n }\n const takeoverLease = await options.claim.acquireLease(key, ttlSeconds)\n if (takeoverLease) return provisionAsOwner(takeoverLease)\n }\n}\n","/**\n * `createWarmLeases`: warm a workspace's box shortly before a member needs it,\n * hold it while the conversation continues, and let the platform suspend it\n * afterwards. One primitive for every warm signal, so a page open, a composer\n * focus, an inbound line message and a learned weekly pattern share one\n * dedupe, one budget and one event stream.\n *\n * WHY A LEASE. Always-on keep-warm is off: a warm box must\n * be earned by a signal and must cost a bounded amount when the signal was\n * wrong. Measured on Hospitality (timestamps only): every\n * human first message after 30 min of quiet landed on a suspended box, and the\n * cold first reply took 68 s on the web and 76 s on a line.\n *\n * WHO SUSPENDS. Not this module. `POST /v1/sandboxes/:id/stop` suspends a box\n * even while a turn runs in it (agent-container\n * `routes/projects/lifecycle.ts`), whereas the platform's idle reaper re-checks\n * the sidecar for live work before it suspends. So a lease only ever resumes\n * and, during a burst hold, pings. An unused warm ends when the box's own idle\n * timeout passes; create boxes with `idleTimeoutSeconds` near the warm hold\n * (600 s) to make a wrong warm cost about ten minutes, and tell this module that\n * value through `boxIdleMs` so its accounting matches the platform.\n *\n * WHAT IT COSTS. Each lease that ends without a turn charges the box time it\n * caused (until the box's idle timeout after its last warm activity) to that\n * key's UTC day. Signals listed in `budgetedReasons` are refused once the day's\n * charge reaches `dailyBudgetMs`. A box that was already running when a signal\n * arrived is charged nothing: the warm did not cause that time.\n *\n * PREDICTION. Every turn that arrives after `boxIdleMs` of quiet (a cold\n * arrival) adds to a decayed count for its ten-minute bin of the day and its\n * weekday. Hour-of-week bins were too coarse: one arrival a day in an hour is\n * a 15% chance for any ten-minute warm, so a shift-start ramp never crossed a\n * useful threshold. `sweep()` warms a key when the predicted chance of a cold\n * arrival in the next `holdMs` reaches that key's threshold, at most once per\n * hour, within the budget. The threshold tunes itself: a predicted warm that is used lowers it,\n * one that is wasted raises it.\n *\n * EVENTS. `warm_started`, `warm_hit`, `warm_wasted`, `warm_declined`,\n * `warm_failed` and `warm_abandoned` each carry the key and the reason, so a product can compute hit\n * rate and wasted minutes per workspace from its logs alone.\n */\n\n/** Why a warm was requested. Products may add their own reasons. */\nexport type WarmReason =\n | 'page-open'\n | 'composer-focus'\n | 'line-ingress'\n | 'member-activity'\n | 'predicted'\n | 'scheduled'\n /** A turn is likely to call a sandbox tool (deterministic input rules, or a\n * `sandbox_run` call starting to stream). See `createEscalationSpeculator`. */\n | 'escalation-likely'\n | (string & {})\n\n/** What the product's `warm` did to the box. */\nexport type WarmBoxOutcome =\n /** The box was stopped and is now running: this warm caused its up-time. */\n | 'resumed'\n /** The box was already running: nothing to warm, nothing charged. */\n | 'running'\n /** No box exists for this key. Leases never create boxes. */\n | 'absent'\n /** The platform refused the resume for capacity (HTTP 429: the org is at its\n * concurrent-box limit). A speculative warm must not compete with real work\n * for the last slots, so the key cools down instead of retrying. */\n | 'capacity'\n\nexport type WarmLeaseEvent =\n | { type: 'warm_started'; key: string; reason: WarmReason; outcome: WarmBoxOutcome; ms: number }\n | { type: 'warm_hit'; key: string; reason: WarmReason; leadMs: number }\n | { type: 'warm_wasted'; key: string; reason: WarmReason; minutes: number }\n | { type: 'warm_declined'; key: string; reason: WarmReason; why: 'budget' | 'absent' | 'capacity' }\n | { type: 'warm_failed'; key: string; reason: WarmReason; error: string }\n /** The lease ended without its warm ever reporting: the request running it was\n * cancelled or the isolate died. Whether the box resumed is unknown, so it is\n * counted here rather than charged or dropped. */\n | { type: 'warm_abandoned'; key: string; reason: WarmReason }\n\nexport type WarmSignalOutcome =\n /** This call started a lease and ran the product's warm. */\n | 'started'\n /** A lease was already live (here or in another isolate); its hold was extended. */\n | 'extended'\n | 'declined'\n | 'failed'\n\nexport interface WarmSignalResult {\n outcome: WarmSignalOutcome\n box?: WarmBoxOutcome\n}\n\nexport interface WarmTurnResult {\n /** The turn landed on a box a lease had already warmed. */\n hit: boolean\n /** The turn arrived after `boxIdleMs` of quiet on this key. */\n coldArrival: boolean\n}\n\nexport interface WarmSweepReport {\n ended: number\n wasted: number\n /** Expired leases whose warm never reported an outcome. */\n abandoned: number\n pinged: number\n predicted: number\n /** Keys whose ping or predicted warm threw; the rest of the batch still ran. */\n errors: number\n}\n\n/** One key's row. Times are epoch milliseconds; 0 means never. */\nexport interface WarmLeaseRow {\n key: string\n leaseId: string | null\n reason: string | null\n startedAt: number\n holdUntil: number\n warmAt: number\n usedAt: number\n resumed: boolean\n pingAt: number\n lastTurnAt: number\n day: string\n dayWarmMs: number\n threshold: number\n slots: number[]\n slotsAt: number\n firstSeenAt: number\n predictedAt: number\n /** Signals are refused without calling the product's warm until this time:\n * set after an 'absent' or 'capacity' outcome, cleared by a turn. */\n declinedUntil: number\n /** An ended, unused warm whose box may still be up: settled at the span no\n * turn used, when a turn arrives or its idle window closes. 0 when none. */\n pendingWarmAt: number\n /** The most the pending warm can be charged: until the box's idle timeout. */\n pendingMs: number\n pendingReason: string | null\n}\n\n/** Persistence for leases. `begin` and `markUsed` must be atomic across isolates. */\nexport interface WarmLeaseStore {\n read(key: string): Promise<WarmLeaseRow | null>\n /**\n * Start a lease with `leaseId` when none is live, otherwise extend the live\n * one's hold to at least `holdUntil`. A lease whose warm has not reported by\n * `staleBefore` counts as not live and is taken over, so a warm killed with\n * its request is retried instead of blocking every later signal. Returns the\n * live lease id after the write; the caller started the lease exactly when\n * it equals `leaseId`.\n */\n begin(key: string, leaseId: string, reason: string, now: number, holdUntil: number, staleBefore: number): Promise<string>\n /** Record the result of this lease's warm. No-op for a superseded lease. */\n markWarm(key: string, leaseId: string, warmAt: number, resumed: boolean): Promise<void>\n /**\n * Record a turn: mark the live lease used (first turn only), extend its hold\n * to `holdUntil`, and store `lastTurnAt`. Returns the row as it was BEFORE\n * the write, so the caller can tell a hit and a cold arrival apart.\n */\n markUsed(key: string, now: number, holdUntil: number): Promise<WarmLeaseRow | null>\n /**\n * End `leaseId`, charging `chargeMs` to `day` and setting the predicted-warm\n * threshold when one is given. No-op for a superseded lease.\n */\n end(key: string, leaseId: string, day: string, chargeMs: number, threshold?: number): Promise<void>\n /** Overwrite the prediction fields. Lossy under races by design: it is a statistic. */\n writeProfile(key: string, slots: number[], slotsAt: number, firstSeenAt: number): Promise<void>\n markPinged(key: string, at: number): Promise<void>\n markPredicted(key: string, at: number): Promise<void>\n /** Refuse signals for `key` until `until` (cleared by the next turn). */\n markDeclined(key: string, until: number): Promise<void>\n /** Record an ended, unused warm whose charge is settled later. */\n markPending(key: string, warmAt: number, maxMs: number, reason: string): Promise<void>\n /**\n * Charge the pending warm that started at `warmAt` `chargeMs` to `day` and\n * clear it. Only the first settler of a given warm succeeds (a turn and a\n * sweep may race); returns whether this call settled it.\n */\n settlePending(key: string, warmAt: number, day: string, chargeMs: number): Promise<boolean>\n /** Pending warms whose idle window has closed by `now`. */\n listPendingDue(now: number, limit: number): Promise<WarmLeaseRow[]>\n /** Bounded batches for `sweep`. */\n listExpired(now: number, limit: number): Promise<WarmLeaseRow[]>\n listHeld(now: number, limit: number): Promise<WarmLeaseRow[]>\n listPredictable(now: number, limit: number): Promise<WarmLeaseRow[]>\n}\n\nexport interface WarmLeasesOptions {\n store: WarmLeaseStore\n /** Resume the key's box if it is stopped. Never create one. */\n warm(key: string, reason: WarmReason): Promise<WarmBoxOutcome>\n /**\n * Optional: touch the running box through a path the platform counts as\n * activity (an exec of `true`). Needed only when `burstHoldMs` exceeds\n * `boxIdleMs`; without it a burst hold is just the box's own idle timeout.\n */\n keepAlive?(key: string): Promise<void>\n /** The idle timeout the key's boxes were created with. Default 30 min, the platform default. */\n boxIdleMs?: number\n /** How long a warm waits for its first turn. Default 10 min. */\n holdMs?: number\n /** How long the box stays held after a turn. Default `boxIdleMs` (no pings). */\n burstHoldMs?: number\n /** Unused-warm box time allowed per key per UTC day. Default 30 min. */\n dailyBudgetMs?: number\n /**\n * How long a started warm may go without reporting before the next signal\n * takes the lease over and warms again. Default 2 min, past a slow resume.\n */\n warmDeadlineMs?: number\n /** After a warm finds no box, refuse that key's signals this long. Default 10 min. */\n absentCooldownMs?: number\n /** After a capacity refusal, refuse that key's signals this long. Default 5 min. */\n capacityCooldownMs?: number\n /** Reasons subject to the budget. Default page-open, member-activity, predicted, scheduled, escalation-likely. */\n budgetedReasons?: readonly string[]\n /** Starting predicted-warm threshold, a probability. Default 0.25. */\n initialThreshold?: number\n onEvent?(event: WarmLeaseEvent): void\n now?(): number\n newId?(): string\n}\n\nexport interface WarmLeases {\n /** A signal that a member may need `key`'s box soon. Awaits the warm when it starts one. */\n signal(key: string, reason: WarmReason): Promise<WarmSignalResult>\n /** Call when a turn is admitted for `key`, before its box is placed. */\n turn(key: string): Promise<WarmTurnResult>\n /** End expired leases, ping held boxes, and start predicted warms. Run from a cron. */\n sweep(options?: { limit?: number }): Promise<WarmSweepReport>\n}\n\n/** 144 ten-minute bins of the UTC day, then 7 weekday counts (Monday first). */\nexport const WARM_SLOTS = 151\nconst DAY_BINS = 144\nconst BIN_MS = 10 * 60_000\nconst HOUR_MS = 3_600_000\nconst DAY_MS = 24 * HOUR_MS\nconst SLOT_HALF_LIFE_MS = 14 * DAY_MS\nconst PING_MARGIN_MS = 2 * 60_000\nconst THRESHOLD_FLOOR = 0.05\nconst THRESHOLD_CEILING = 0.95\nconst DEFAULT_BUDGETED = ['page-open', 'member-activity', 'predicted', 'scheduled', 'escalation-likely'] as const\n\n/** UTC ten-minute bin of the day, 0..143. */\nexport function warmBinOf(at: number): number {\n return Math.floor((((at % DAY_MS) + DAY_MS) % DAY_MS) / BIN_MS)\n}\n\n/** UTC weekday, Monday = 0. */\nexport function warmWeekdayOf(at: number): number {\n return (new Date(at).getUTCDay() + 6) % 7\n}\n\nexport function utcDay(at: number): string {\n return new Date(at).toISOString().slice(0, 10)\n}\n\n/** Decay every slot to `at` with a 14-day half-life. */\nexport function decaySlots(slots: readonly number[], from: number, at: number): number[] {\n const factor = from > 0 && at > from ? 0.5 ** ((at - from) / SLOT_HALF_LIFE_MS) : 1\n return Array.from({ length: WARM_SLOTS }, (_, i) => (slots[i] ?? 0) * factor)\n}\n\n/** Record one cold arrival at `at`. */\nexport function addColdArrival(slots: readonly number[], slotsAt: number, at: number): number[] {\n const next = decaySlots(slots, slotsAt, at)\n next[warmBinOf(at)] = (next[warmBinOf(at)] ?? 0) + 1\n next[DAY_BINS + warmWeekdayOf(at)] = (next[DAY_BINS + warmWeekdayOf(at)] ?? 0) + 1\n return next\n}\n\n/**\n * Chance of at least one cold arrival in `[at, at + windowMs)`.\n *\n * Each ten-minute bin's rate is its decayed count over the effective days\n * observed, smoothed over its neighbours (a shift that starts at 07:00 sends\n * its first message anywhere from 06:55 to 07:15), and scaled by how busy the\n * window's weekday is against the average weekday. The weekday factor is\n * smoothed toward 1 because two weeks hold only two of each weekday.\n */\nexport function predictColdArrival(\n row: Pick<WarmLeaseRow, 'slots' | 'slotsAt' | 'firstSeenAt'>,\n at: number,\n windowMs: number,\n): number {\n if (row.firstSeenAt <= 0 || row.slots.length !== WARM_SLOTS) return 0\n const slots = decaySlots(row.slots, row.slotsAt, at)\n const decay = Math.LN2 / SLOT_HALF_LIFE_MS\n const observedMs = Math.max(DAY_MS, at - row.firstSeenAt)\n const days = (1 - Math.exp(-decay * observedMs)) / decay / DAY_MS\n const weekdays = slots.slice(DAY_BINS)\n const meanWeekday = weekdays.reduce((sum, v) => sum + v, 0) / 7\n const bin = (i: number) => slots[((i % DAY_BINS) + DAY_BINS) % DAY_BINS] ?? 0\n let expected = 0\n for (let start = at; start < at + windowMs; ) {\n const index = warmBinOf(start)\n const binEnd = start - (((start % BIN_MS) + BIN_MS) % BIN_MS) + BIN_MS\n const end = Math.min(binEnd, at + windowMs)\n const smoothed = 0.25 * bin(index - 1) + 0.5 * bin(index) + 0.25 * bin(index + 1)\n const weekday = ((weekdays[warmWeekdayOf(start)] ?? 0) + 1) / (meanWeekday + 1)\n expected += (smoothed / days) * weekday * ((end - start) / BIN_MS)\n start = end\n }\n return 1 - Math.exp(-expected)\n}\n\nfunction errText(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\nexport function createWarmLeases(options: WarmLeasesOptions): WarmLeases {\n const { store } = options\n const boxIdleMs = options.boxIdleMs ?? 30 * 60_000\n const holdMs = options.holdMs ?? 10 * 60_000\n const warmDeadlineMs = options.warmDeadlineMs ?? 2 * 60_000\n const absentCooldownMs = options.absentCooldownMs ?? 10 * 60_000\n const capacityCooldownMs = options.capacityCooldownMs ?? 5 * 60_000\n const burstHoldMs = options.burstHoldMs ?? boxIdleMs\n const dailyBudgetMs = options.dailyBudgetMs ?? 30 * 60_000\n const budgeted = new Set<string>(options.budgetedReasons ?? DEFAULT_BUDGETED)\n const initialThreshold = options.initialThreshold ?? 0.25\n const now = options.now ?? (() => Date.now())\n const newId = options.newId ?? (() => crypto.randomUUID())\n\n const emit = (event: WarmLeaseEvent): void => {\n try {\n options.onEvent?.(event)\n } catch {\n // Observability must not change a warm's outcome.\n }\n }\n\n // A pending warm counts in full until it settles: conservative, and while it\n // is pending its box is still up, so another warm would buy nothing.\n const spentToday = (row: WarmLeaseRow | null, at: number): number =>\n (row && row.day === utcDay(at) ? row.dayWarmMs : 0) +\n (row && row.pendingWarmAt > 0 && utcDay(row.pendingWarmAt) === utcDay(at) ? row.pendingMs : 0)\n\n /**\n * The most box time an unused lease can have caused: until the box's idle\n * timeout after its last warm activity (the resume, or a keep-alive ping).\n * Not the hold: later signals extend the hold, but the hold keeps no box up,\n * so a page polled every few minutes once inflated one warm to 50 min.\n */\n function chargeOf(row: WarmLeaseRow): number {\n if (!row.resumed || row.usedAt > 0 || row.warmAt <= 0) return 0\n return Math.max(row.warmAt, row.pingAt) + boxIdleMs - row.warmAt\n }\n\n async function signal(key: string, reason: WarmReason): Promise<WarmSignalResult> {\n const at = now()\n const row = await store.read(key)\n // A recent 'absent' or 'capacity' answer stands until it expires or a turn\n // clears it. Refused silently: on a busy page this fires every few seconds,\n // and each event would be a duplicate of the decline that set it.\n if (row && row.declinedUntil > at && !row.leaseId) return { outcome: 'declined' }\n if (budgeted.has(reason)) {\n if (!(row?.leaseId) && spentToday(row, at) >= dailyBudgetMs) {\n emit({ type: 'warm_declined', key, reason, why: 'budget' })\n return { outcome: 'declined' }\n }\n }\n const leaseId = newId()\n const live = await store.begin(key, leaseId, reason, at, at + holdMs, at - warmDeadlineMs)\n if (live !== leaseId) return { outcome: 'extended' }\n\n let box: WarmBoxOutcome\n try {\n box = await options.warm(key, reason)\n } catch (err) {\n await store.end(key, leaseId, utcDay(at), 0)\n emit({ type: 'warm_failed', key, reason, error: errText(err) })\n return { outcome: 'failed' }\n }\n const warmAt = now()\n if (box === 'absent' || box === 'capacity') {\n await store.end(key, leaseId, utcDay(at), 0)\n await store.markDeclined(key, warmAt + (box === 'absent' ? absentCooldownMs : capacityCooldownMs))\n emit({ type: 'warm_declined', key, reason, why: box })\n return { outcome: 'declined', box }\n }\n await store.markWarm(key, leaseId, warmAt, box === 'resumed')\n emit({ type: 'warm_started', key, reason, outcome: box, ms: warmAt - at })\n return { outcome: 'started', box }\n }\n\n async function turn(key: string): Promise<WarmTurnResult> {\n const at = now()\n const before = await store.markUsed(key, at, at + burstHoldMs)\n const coldArrival = !before || before.lastTurnAt <= 0 || at - before.lastTurnAt > boxIdleMs\n const hit = Boolean(\n before?.leaseId && before.usedAt <= 0 && before.resumed && before.warmAt > 0 && before.warmAt <= at,\n )\n if (hit && before) {\n emit({ type: 'warm_hit', key, reason: before.reason ?? 'unknown', leadMs: at - before.startedAt })\n }\n // A turn inside an ended warm's idle window landed on the box that warm\n // resumed: a hit, and only the span before it was unused.\n let lateHit = false\n if (before && before.pendingWarmAt > 0 && at < before.pendingWarmAt + before.pendingMs) {\n const unused = Math.max(0, at - before.pendingWarmAt)\n if (await store.settlePending(key, before.pendingWarmAt, utcDay(before.pendingWarmAt), unused)) {\n lateHit = true\n const reason = before.pendingReason ?? 'unknown'\n emit({ type: 'warm_hit', key, reason, leadMs: unused })\n if (unused >= 60_000) emit({ type: 'warm_wasted', key, reason, minutes: Math.round(unused / 60_000) })\n }\n }\n if (coldArrival) {\n const slots = addColdArrival(before?.slots ?? [], before?.slotsAt ?? 0, at)\n await store.writeProfile(key, slots, at, before?.firstSeenAt || at)\n }\n return { hit: hit || lateHit, coldArrival }\n }\n\n async function sweep(sweepOptions: { limit?: number } = {}): Promise<WarmSweepReport> {\n const limit = sweepOptions.limit ?? 50\n const at = now()\n const report: WarmSweepReport = { ended: 0, wasted: 0, abandoned: 0, pinged: 0, predicted: 0, errors: 0 }\n\n for (const row of await store.listExpired(at, limit)) {\n if (!row.leaseId) continue\n const charge = chargeOf(row)\n let threshold: number | undefined\n if (row.reason === 'predicted' && row.resumed) {\n const current = row.threshold > 0 ? row.threshold : initialThreshold\n threshold = Math.min(THRESHOLD_CEILING, Math.max(THRESHOLD_FLOOR, current * (row.usedAt > 0 ? 0.85 : 1.3)))\n }\n // An unused warm is not charged here: its box stays up until the idle\n // timeout, and a turn in that window means only part of it was unused.\n await store.end(row.key, row.leaseId, utcDay(row.warmAt || row.startedAt), 0, threshold)\n if (charge > 0) await store.markPending(row.key, row.warmAt, charge, row.reason ?? 'unknown')\n report.ended += 1\n if (row.warmAt <= 0) {\n report.abandoned += 1\n emit({ type: 'warm_abandoned', key: row.key, reason: row.reason ?? 'unknown' })\n }\n }\n\n for (const row of await store.listPendingDue(at, limit)) {\n if (await store.settlePending(row.key, row.pendingWarmAt, utcDay(row.pendingWarmAt), row.pendingMs)) {\n report.wasted += 1\n emit({ type: 'warm_wasted', key: row.key, reason: row.pendingReason ?? 'unknown', minutes: Math.round(row.pendingMs / 60_000) })\n }\n }\n\n if (options.keepAlive && burstHoldMs > boxIdleMs) {\n for (const row of await store.listHeld(at, limit)) {\n const lastActivity = Math.max(row.pingAt, row.lastTurnAt, row.warmAt)\n if (lastActivity + boxIdleMs - PING_MARGIN_MS > at) continue\n if (row.holdUntil <= lastActivity + boxIdleMs) continue\n try {\n await options.keepAlive(row.key)\n await store.markPinged(row.key, at)\n report.pinged += 1\n } catch {\n report.errors += 1\n }\n }\n }\n\n for (const row of await store.listPredictable(at, limit)) {\n if (row.leaseId || at - row.predictedAt < HOUR_MS) continue\n if (row.lastTurnAt > 0 && at - row.lastTurnAt < boxIdleMs) continue\n const threshold = row.threshold > 0 ? row.threshold : initialThreshold\n if (predictColdArrival(row, at, holdMs) < threshold) continue\n await store.markPredicted(row.key, at)\n try {\n const result = await signal(row.key, 'predicted')\n if (result.outcome === 'started') report.predicted += 1\n if (result.outcome === 'failed') report.errors += 1\n } catch {\n report.errors += 1\n }\n }\n return report\n }\n\n return { signal, turn, sweep }\n}\n","import { WARM_SLOTS, type WarmLeaseRow, type WarmLeaseStore } from './warm-lease'\n\n/**\n * `createD1WarmLeaseStore`: the `WarmLeaseStore` every Workers product uses,\n * one row per key in one table.\n *\n * Race-sensitive steps are single statements. `begin` is an upsert whose SET\n * expressions read the old row, so two isolates that signal at once agree on\n * one lease id and only its owner runs the warm. `markUsed` claims the first\n * use with a conditional UPDATE … RETURNING, so two turns cannot both count as\n * the hit. The prediction slots are a decayed statistic and are written\n * without a fence: a lost increment under a race costs nothing.\n *\n * The table is the product's migration (`WARM_LEASE_TABLE_DDL`); the store\n * never runs DDL, for the same reason as `createD1PrewarmClaimStore`.\n */\n\nexport const DEFAULT_WARM_LEASE_TABLE = 'sandbox_warm_lease'\n\n/** Paste into a migration. Times are epoch milliseconds; 0 means never. */\nexport const WARM_LEASE_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${DEFAULT_WARM_LEASE_TABLE} (\n key TEXT PRIMARY KEY,\n lease_id TEXT,\n reason TEXT,\n started_at INTEGER NOT NULL DEFAULT 0,\n hold_until INTEGER NOT NULL DEFAULT 0,\n warm_at INTEGER NOT NULL DEFAULT 0,\n used_at INTEGER NOT NULL DEFAULT 0,\n resumed INTEGER NOT NULL DEFAULT 0,\n ping_at INTEGER NOT NULL DEFAULT 0,\n last_turn_at INTEGER NOT NULL DEFAULT 0,\n day TEXT NOT NULL DEFAULT '',\n day_warm_ms INTEGER NOT NULL DEFAULT 0,\n threshold REAL NOT NULL DEFAULT 0,\n slots TEXT NOT NULL DEFAULT '',\n slots_at INTEGER NOT NULL DEFAULT 0,\n first_seen_at INTEGER NOT NULL DEFAULT 0,\n predicted_at INTEGER NOT NULL DEFAULT 0,\n declined_until INTEGER NOT NULL DEFAULT 0,\n pending_warm_at INTEGER NOT NULL DEFAULT 0,\n pending_ms INTEGER NOT NULL DEFAULT 0,\n pending_reason TEXT\n)`\n\n/** For a table created from an earlier \\`WARM_LEASE_TABLE_DDL\\`: paste into a migration. */\nexport const WARM_LEASE_DECLINED_UNTIL_DDL =\n `ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN declined_until INTEGER NOT NULL DEFAULT 0`\n\n/** For a table created before pending charges: paste each into a migration. */\nexport const WARM_LEASE_PENDING_DDL = [\n `ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN pending_warm_at INTEGER NOT NULL DEFAULT 0`,\n `ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN pending_ms INTEGER NOT NULL DEFAULT 0`,\n `ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN pending_reason TEXT`,\n] as const\n\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/\n\ninterface Row {\n key: string\n lease_id: string | null\n reason: string | null\n started_at: number\n hold_until: number\n warm_at: number\n used_at: number\n resumed: number\n ping_at: number\n last_turn_at: number\n day: string\n day_warm_ms: number\n threshold: number\n slots: string\n slots_at: number\n first_seen_at: number\n predicted_at: number\n declined_until: number\n pending_warm_at: number\n pending_ms: number\n pending_reason: string | null\n}\n\n/** The D1 surface this store uses: `prepare().bind()` with `first`, `run` and `all`. A real `D1Database` satisfies it. */\nexport interface WarmLeaseD1Like {\n prepare(query: string): {\n bind(...values: unknown[]): {\n first<T = Record<string, unknown>>(): Promise<T | null>\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n }\n}\n\nfunction parseSlots(text: string): number[] {\n if (!text) return []\n try {\n const parsed: unknown = JSON.parse(text)\n if (Array.isArray(parsed) && parsed.length === WARM_SLOTS) return parsed.map((v) => Number(v) || 0)\n } catch {\n // A corrupt profile restarts learning; it must not break a turn.\n }\n return []\n}\n\nfunction toRow(row: Row): WarmLeaseRow {\n return {\n key: row.key,\n leaseId: row.lease_id,\n reason: row.reason,\n startedAt: row.started_at,\n holdUntil: row.hold_until,\n warmAt: row.warm_at,\n usedAt: row.used_at,\n resumed: row.resumed === 1,\n pingAt: row.ping_at,\n lastTurnAt: row.last_turn_at,\n day: row.day,\n dayWarmMs: row.day_warm_ms,\n threshold: row.threshold,\n slots: parseSlots(row.slots),\n slotsAt: row.slots_at,\n firstSeenAt: row.first_seen_at,\n predictedAt: row.predicted_at,\n declinedUntil: row.declined_until ?? 0,\n pendingWarmAt: row.pending_warm_at ?? 0,\n pendingMs: row.pending_ms ?? 0,\n pendingReason: row.pending_reason ?? null,\n }\n}\n\nexport function createD1WarmLeaseStore(\n db: WarmLeaseD1Like,\n options: { table?: string } = {},\n): WarmLeaseStore {\n const t = options.table ?? DEFAULT_WARM_LEASE_TABLE\n if (!SAFE_IDENTIFIER.test(t)) throw new Error(`Invalid warm lease table name: ${JSON.stringify(t)}`)\n\n // Every SET expression reads the old row. A lease is free when there is none,\n // or when its warm has not reported by ?6 (the request running it was cancelled).\n const free = `(${t}.lease_id IS NULL OR (${t}.warm_at = 0 AND ${t}.started_at <= ?6))`\n const beginSql = `INSERT INTO ${t} (key, lease_id, reason, started_at, hold_until) VALUES (?1, ?2, ?3, ?4, ?5)\nON CONFLICT(key) DO UPDATE SET\n lease_id = CASE WHEN ${free} THEN ?2 ELSE ${t}.lease_id END,\n reason = CASE WHEN ${free} THEN ?3 ELSE ${t}.reason END,\n started_at = CASE WHEN ${free} THEN ?4 ELSE ${t}.started_at END,\n warm_at = CASE WHEN ${free} THEN 0 ELSE ${t}.warm_at END,\n used_at = CASE WHEN ${free} THEN 0 ELSE ${t}.used_at END,\n resumed = CASE WHEN ${free} THEN 0 ELSE ${t}.resumed END,\n ping_at = CASE WHEN ${free} THEN 0 ELSE ${t}.ping_at END,\n hold_until = MAX(${t}.hold_until, ?5)\nRETURNING lease_id`\n const markWarmSql = `UPDATE ${t} SET warm_at = ?3, resumed = ?4 WHERE key = ?1 AND lease_id = ?2`\n const firstUseSql = `UPDATE ${t} SET used_at = ?2 WHERE key = ?1 AND lease_id IS NOT NULL AND used_at = 0 RETURNING key`\n const turnSql = `INSERT INTO ${t} (key, last_turn_at, hold_until) VALUES (?1, ?2, ?3)\nON CONFLICT(key) DO UPDATE SET last_turn_at = ?2, hold_until = MAX(${t}.hold_until, ?3), declined_until = 0`\n // A charge for an older day than the row holds is dropped: that day's budget is already spent.\n const endSql = `UPDATE ${t} SET\n lease_id = NULL, reason = NULL, started_at = 0, warm_at = 0, used_at = 0, resumed = 0, ping_at = 0,\n day_warm_ms = CASE WHEN day = ?3 THEN day_warm_ms + ?4 WHEN day < ?3 THEN ?4 ELSE day_warm_ms END,\n day = CASE WHEN day < ?3 THEN ?3 ELSE day END,\n threshold = COALESCE(?5, threshold)\nWHERE key = ?1 AND lease_id = ?2`\n const profileSql = `UPDATE ${t} SET slots = ?2, slots_at = ?3, first_seen_at = ?4 WHERE key = ?1`\n const readSql = `SELECT * FROM ${t} WHERE key = ?1`\n\n // D1 accepts numbered `?NNN` placeholders; better-sqlite3, which product test\n // harnesses commonly wrap as D1, rejects them. Statements stay numbered for\n // readability and are expanded to plain `?` with their values in order.\n const q = (sql: string, ...values: unknown[]) => {\n const ordered: unknown[] = []\n const text = sql.replace(/\\?(\\d+)/g, (_, n: string) => {\n ordered.push(values[Number(n) - 1])\n return '?'\n })\n return db.prepare(text).bind(...ordered)\n }\n\n const read = async (key: string): Promise<WarmLeaseRow | null> => {\n const row = await q(readSql, key).first<Row>()\n return row ? toRow(row) : null\n }\n const list = async (sql: string, ...values: unknown[]): Promise<WarmLeaseRow[]> =>\n ((await q(sql, ...values).all<Row>()).results ?? []).map(toRow)\n\n return {\n read,\n\n async begin(key, leaseId, reason, now, holdUntil, staleBefore) {\n const row = await q(beginSql, key, leaseId, reason, now, holdUntil, staleBefore).first<{ lease_id: string }>()\n if (!row) throw new Error('warm lease begin returned no row')\n return row.lease_id\n },\n\n async markWarm(key, leaseId, warmAt, resumed) {\n await q(markWarmSql, key, leaseId, warmAt, resumed ? 1 : 0).run()\n },\n\n async markUsed(key, now, holdUntil) {\n const before = await read(key)\n const claimed = await q(firstUseSql, key, now).first<{ key: string }>()\n await q(turnSql, key, now, holdUntil).run()\n // Another turn claimed the first use between the read and the claim: this one is not the hit.\n if (before && !claimed && before.usedAt <= 0) return { ...before, usedAt: now }\n return before\n },\n\n async end(key, leaseId, day, chargeMs, threshold) {\n await q(endSql, key, leaseId, day, Math.max(0, Math.round(chargeMs)), threshold ?? null).run()\n },\n\n async writeProfile(key, slots, slotsAt, firstSeenAt) {\n const rounded = slots.map((v) => Math.round(v * 1000) / 1000)\n await q(profileSql, key, JSON.stringify(rounded), slotsAt, firstSeenAt).run()\n },\n\n async markPinged(key, at) {\n await q(`UPDATE ${t} SET ping_at = ?2 WHERE key = ?1`, key, at).run()\n },\n\n async markPending(key, warmAt, maxMs, reason) {\n await q(`UPDATE ${t} SET pending_warm_at = ?2, pending_ms = ?3, pending_reason = ?4 WHERE key = ?1`,\n key, warmAt, Math.max(0, Math.round(maxMs)), reason).run()\n },\n\n async settlePending(key, warmAt, day, chargeMs) {\n // Fenced by the warm's start time, so a turn and a sweep cannot both settle it.\n const settled = await q(`UPDATE ${t} SET\n day_warm_ms = CASE WHEN day = ?3 THEN day_warm_ms + ?4 WHEN day < ?3 THEN ?4 ELSE day_warm_ms END,\n day = CASE WHEN day < ?3 THEN ?3 ELSE day END,\n pending_warm_at = 0, pending_ms = 0, pending_reason = NULL\nWHERE key = ?1 AND pending_warm_at = ?2 RETURNING key`, key, warmAt, day, Math.max(0, Math.round(chargeMs))).first<{ key: string }>()\n return settled != null\n },\n\n listPendingDue: (now, limit) =>\n list(`SELECT * FROM ${t} WHERE pending_warm_at > 0 AND pending_warm_at + pending_ms <= ?1 ORDER BY pending_warm_at LIMIT ?2`, now, limit),\n\n async markDeclined(key, until) {\n await q(`UPDATE ${t} SET declined_until = ?2 WHERE key = ?1`, key, until).run()\n },\n\n async markPredicted(key, at) {\n await q(`UPDATE ${t} SET predicted_at = ?2 WHERE key = ?1`, key, at).run()\n },\n\n listExpired: (now, limit) =>\n list(`SELECT * FROM ${t} WHERE lease_id IS NOT NULL AND hold_until <= ?1 ORDER BY hold_until LIMIT ?2`, now, limit),\n\n listHeld: (now, limit) =>\n list(`SELECT * FROM ${t} WHERE hold_until > ?1 ORDER BY ping_at LIMIT ?2`, now, limit),\n\n // Random order so a large fleet is covered across sweeps instead of always checking the same rows.\n listPredictable: (now, limit) =>\n list(\n `SELECT * FROM ${t} WHERE lease_id IS NULL AND first_seen_at > 0 AND predicted_at <= ?1 ORDER BY random() LIMIT ?2`,\n now - 3_600_000,\n limit,\n ),\n }\n}\n","/**\n * `createEscalationSpeculator`: start a turn's sandbox box when the turn is\n * likely to escalate to it, so `sandbox_run` finds the box running instead of\n * paying the resume (p50 6.4 s on escalated turns, agent turn architecture S8).\n *\n * TWO SIGNALS, CHEAPEST FIRST. Deterministic rules on the turn's input fire\n * before the model is called: an attachment a process must read (PDF, sheet,\n * archive, code), a fenced code block, or words that ask for execution. Then,\n * while the reply streams, the start of a call to an escalation tool fires as\n * soon as the model names it, seconds before its arguments finish. Either one\n * calls `warm` once per turn.\n *\n * ALWAYS ON. There is no mode: a turn that can reach the box speculates. The\n * hybrid producer (`createHybridTurnProducer` in `/chat-routes`) passes its own\n * single-flight box start as `warm`, so a speculative start and the tool's own\n * start are one start.\n *\n * NEVER GATES. `warm` is fire-and-forget. A speculation that is wrong costs a\n * box that idles out; it never delays or fails the turn.\n */\n\n/** Why a turn was judged likely to escalate. */\nexport type EscalationHint = 'attachment' | 'code-block' | 'execution-words' | 'tool-call-start'\n\nexport interface EscalationInput {\n text?: string\n attachments?: ReadonlyArray<{ mediaType?: string; name?: string }>\n}\n\n/** The tools that run in the box. The start of a call to one of these warms it. */\nexport const DEFAULT_ESCALATION_TOOLS = ['sandbox_run', 'sandbox_exec'] as const\n\nconst PROCESS_MEDIA = /^(application\\/(pdf|zip|x-zip|gzip|x-tar|vnd\\.openxmlformats|vnd\\.ms-excel|vnd\\.oasis)|text\\/(csv|x-python|x-script))/i\nconst PROCESS_EXTENSIONS = /\\.(pdf|xlsx?|csv|tsv|ods|zip|tar|gz|py|ipynb|js|ts|sh|sql|parquet|json)$/i\nconst EXECUTION_WORDS =\n /\\b(run|execute|compile|convert|parse|extract|install|script|python|notebook|spreadsheet|csv|xlsx|regex|calculate|plot|chart|test suite|build the)\\b/i\n\n/** Pure: the reasons this input suggests the turn will need the box, if any. */\nexport function escalationHints(input: EscalationInput): EscalationHint[] {\n const hints: EscalationHint[] = []\n if ((input.attachments ?? []).some((a) => PROCESS_MEDIA.test(a.mediaType ?? '') || PROCESS_EXTENSIONS.test(a.name ?? ''))) {\n hints.push('attachment')\n }\n const text = input.text ?? ''\n if (/```/.test(text)) hints.push('code-block')\n if (EXECUTION_WORDS.test(text)) hints.push('execution-words')\n return hints\n}\n\nexport interface EscalationSpeculatorOptions {\n /** Start the box. Called at most once per turn; a rejection is swallowed. */\n warm(): Promise<unknown> | void\n escalationTools?: readonly string[]\n /** Observability: called once, when the turn's warm starts. */\n onSpeculate?(hint: EscalationHint): void\n}\n\nexport interface EscalationSpeculator {\n /** Call with the turn's input before the model call. */\n onInput(input: EscalationInput): void\n /** Call with each engine event. Only the start of a call to an escalation tool\n * (`tool_start`, or the loop's `tool_call_start`) is read. */\n onEvent(event: { type: string; toolName?: string }): void\n /** The hint that fired for this turn, if any. */\n readonly fired: EscalationHint | null\n}\n\n/** One speculator per turn. */\nexport function createEscalationSpeculator(options: EscalationSpeculatorOptions): EscalationSpeculator {\n const tools = new Set<string>(options.escalationTools ?? DEFAULT_ESCALATION_TOOLS)\n let fired: EscalationHint | null = null\n\n const speculate = (hint: EscalationHint): void => {\n if (fired) return\n fired = hint\n try {\n options.onSpeculate?.(hint)\n } catch {\n // Observability must not change the turn.\n }\n // Fire and forget: a warm never gates or fails the turn.\n try {\n void Promise.resolve(options.warm()).catch(() => undefined)\n } catch {\n // A warm that throws synchronously is a warm that did not start.\n }\n }\n\n return {\n onInput(input) {\n const hint = escalationHints(input)[0]\n if (hint) speculate(hint)\n },\n onEvent(event) {\n if ((event.type === 'tool_start' || event.type === 'tool_call_start') && event.toolName && tools.has(event.toolName)) {\n speculate('tool-call-start')\n }\n },\n get fired() {\n return fired\n },\n }\n}\n","import { type TangleExecutionEnvironment, trimOrNull, resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define client credentials for accessing the sandbox environment with API key and base URL */\nexport interface SandboxClientCredentials {\n apiKey: string\n baseUrl: string\n}\n\n/**\n * Sandbox credential policy reuses the canonical execution-environment union\n * (development/test/staging/production) so env classification stays in one place\n * (see resolveTangleExecutionEnvironment in runtime/model).\n */\nexport type SandboxCredentialEnvironment = TangleExecutionEnvironment\n\n/** Resolve options for obtaining sandbox client credentials from environment variables and classification */\nexport interface ResolveSandboxClientCredentialsOptions {\n /**\n * Environment object to read from. Defaults to process.env when available.\n */\n env?: Record<string, string | undefined>\n /**\n * Explicit environment classification. Defaults to APP_ENV/NODE_ENV derived\n * behavior: local/development/test use direct env credentials; staging/prod\n * require the provision callback unless allowDirectEnvCredentials opts in.\n */\n environment?: SandboxCredentialEnvironment\n /**\n * Env names that may carry a sandbox-compatible bearer. The first non-empty\n * value wins when direct env credentials are allowed.\n */\n directKeyNames?: readonly string[]\n /**\n * Env names that may carry the sandbox gateway URL. The first non-empty value\n * wins, then defaultBaseUrl.\n */\n baseUrlNames?: readonly string[]\n /**\n * Base URL used when none of baseUrlNames are present.\n */\n defaultBaseUrl?: string\n /**\n * Whether direct env credentials are allowed for this environment. Defaults\n * to true in development/test and false in staging/production.\n */\n allowDirectEnvCredentials?: boolean | ((environment: SandboxCredentialEnvironment) => boolean)\n /**\n * Product-owned provision path, usually minting a per-user sandbox key from a\n * linked platform account. Called before direct env credentials in\n * staging/production and after direct env credentials in development/test.\n */\n provision?: (\n context: {\n environment: SandboxCredentialEnvironment\n env: Record<string, string | undefined>\n },\n ) => SandboxClientCredentials | null | undefined | Promise<SandboxClientCredentials | null | undefined>\n}\n\nconst DEFAULT_SANDBOX_DIRECT_KEY_NAMES = [\n 'TCLOUD_SANDBOX_API_KEY',\n 'SANDBOX_API_KEY',\n 'TANGLE_API_KEY',\n] as const\n\nconst DEFAULT_SANDBOX_BASE_URL_NAMES = ['SANDBOX_GATEWAY_URL', 'SANDBOX_API_URL'] as const\n\nfunction normalizeBaseUrl(value: string): string {\n return value.trim().replace(/\\/v1\\/?$/, '').replace(/\\/+$/, '')\n}\n\nfunction processEnv(): Record<string, string | undefined> {\n return typeof process === 'undefined' ? {} : process.env\n}\n\nfunction directEnvCredentialsAllowed(\n environment: SandboxCredentialEnvironment,\n allow: ResolveSandboxClientCredentialsOptions['allowDirectEnvCredentials'],\n): boolean {\n if (typeof allow === 'function') return allow(environment)\n if (typeof allow === 'boolean') return allow\n return environment === 'development' || environment === 'test'\n}\n\nfunction resolveSandboxBaseUrl(\n env: Record<string, string | undefined>,\n names: readonly string[],\n defaultBaseUrl: string | undefined,\n): string {\n for (const name of names) {\n const value = trimOrNull(env[name])\n if (value) return normalizeBaseUrl(value)\n }\n const value = trimOrNull(defaultBaseUrl)\n if (value) return normalizeBaseUrl(value)\n throw new Error(\n `Sandbox base URL is required (set one of ${names.join(', ')} or pass defaultBaseUrl).`,\n )\n}\n\nfunction resolveDirectSandboxCredentials(\n env: Record<string, string | undefined>,\n keyNames: readonly string[],\n baseUrlNames: readonly string[],\n defaultBaseUrl: string | undefined,\n): SandboxClientCredentials | null {\n for (const name of keyNames) {\n const apiKey = trimOrNull(env[name])\n if (!apiKey) continue\n return {\n apiKey,\n baseUrl: resolveSandboxBaseUrl(env, baseUrlNames, defaultBaseUrl),\n }\n }\n return null\n}\n\n/** Resolve sandbox client credentials based on environment and provided options asynchronously */\nexport async function resolveSandboxClientCredentials(\n options: ResolveSandboxClientCredentialsOptions = {},\n): Promise<SandboxClientCredentials> {\n const env = options.env ?? processEnv()\n const environment = options.environment ?? resolveTangleExecutionEnvironment(env)\n const keyNames = options.directKeyNames ?? DEFAULT_SANDBOX_DIRECT_KEY_NAMES\n const baseUrlNames = options.baseUrlNames ?? DEFAULT_SANDBOX_BASE_URL_NAMES\n const directAllowed = directEnvCredentialsAllowed(environment, options.allowDirectEnvCredentials)\n const direct = () =>\n directAllowed\n ? resolveDirectSandboxCredentials(env, keyNames, baseUrlNames, options.defaultBaseUrl)\n : null\n\n if (environment === 'development' || environment === 'test') {\n const credentials = direct()\n if (credentials) return credentials\n }\n\n const provisioned = await options.provision?.({ environment, env })\n if (provisioned) {\n return {\n apiKey: provisioned.apiKey,\n baseUrl: normalizeBaseUrl(provisioned.baseUrl),\n }\n }\n\n const credentials = direct()\n if (credentials) return credentials\n\n const directHint = directAllowed\n ? ` or set one of ${keyNames.join(', ')}`\n : ''\n throw new Error(\n `Sandbox credentials are required for ${environment} (provide a provision callback${directHint}).`,\n )\n}\n","import type { SandboxInstance, EgressPolicy, StorageConfig, ProvisionEvent } from '@tangle-network/sandbox'\nimport type { SandboxExistingBoxStage } from './lifecycle-errors'\nimport type { AgentProfileFileMount, AgentProfileMcpServer, AgentProfile } from '@tangle-network/agent-interface'\nimport type { Harness } from '../harness/index'\nimport type { SandboxClientCredentials } from './credentials'\nimport type { SandboxPermissionLevel } from './access'\nimport type { ProviderResolutionConfig } from './model'\nimport type { ReuseStateStore } from './reuse-state'\nimport type { Outcome } from './outcome'\nimport type { ComposeProfileBudget } from '../profile/budget'\nimport type { TurnTrace, TurnSpan } from '../turn-trace/recorder'\n\n/**\n * Configure sandbox resources and lifecycle limits.\n * Set `advisory` for application defaults that the Sandbox API may clamp to account limits.\n * Omit it when the requested allocation must be honored or rejected.\n */\nexport interface SandboxResourceConfig {\n image: string\n cpuCores: number\n memoryMB: number\n diskGB: number\n /** Let the Sandbox API clamp these resource defaults to the account's limits. */\n advisory?: boolean\n maxLifetimeSeconds: number\n idleTimeoutSeconds: number\n}\n\n/** Define the context for building a sandbox including workspace, integrations, and optional user ID */\nexport interface SandboxBuildContext {\n workspaceId: string\n connectedIntegrationIds: string[]\n userId?: string\n}\n\n// Scope handed to per-identity seams. workspaceId is always present; userId is\n// present when the lifecycle op carries one. Workspace-keyed products ignore userId.\n/** Define a scope containing workspace and optional user identifiers for sandbox environments */\nexport interface SandboxScope {\n workspaceId: string\n userId?: string\n}\n\n// Snapshot RESTORE-on-create. Returned alongside storage; undefined => fresh box.\n/** Define the specification for restoring a sandbox from a snapshot or another sandbox ID */\nexport interface SandboxRestoreSpec {\n fromSnapshot: string\n fromSandboxId: string\n}\n\n/** Describe the failure details when resuming a stopped sandbox instance */\nexport interface StoppedSandboxResumeFailure {\n box: SandboxInstance\n error: Error\n scope: SandboxScope\n boxKey: string\n}\n\n/** Describe a sandbox that disappeared after the platform listed it. */\nexport interface MissingSandboxFailure extends StoppedSandboxResumeFailure {\n stage: SandboxExistingBoxStage\n}\n\n/** Define the structure for resuming a stopped sandbox with replacement key and optional restore options */\nexport interface StoppedSandboxResumeRecovery {\n // Used for both the replacement sandbox name and idempotency key.\n replacementBoxKey: string\n // undefined preserves the configured restore seam; null creates without one.\n restore?: SandboxRestoreSpec | null\n}\n\n/** Configure runtime exec verification before reusing a sandbox. */\nexport interface LivenessProbeConfig {\n /** Process timeout passed to the Sandbox SDK. Defaults to 5 seconds.\n * SDK readiness and transport deadlines also apply. */\n execTimeoutMs?: number\n /**\n * Reuse a successful liveness result for this many milliseconds for the\n * same box id and identity (start time and filesystem incarnation). Defaults to 10 minutes; set to 0 to probe on\n * every reuse.\n *\n * Only the exec probe is cached. Runtime readiness, deferred-file\n * materialization, and bootstrap (unless {@link SandboxRuntimeConfig.bootstrapDigest}\n * names a build this box already ran it under) still run on every reuse, and the egress\n * policy and runtime environment are checked as {@link SandboxRuntimeConfig.egressPolicy}\n * and {@link SandboxRuntimeConfig.runtimeEnv} describe. A box that dies during\n * this window is surfaced by the first call on it: a caller whose first call\n * fails passes the box to {@link dropTrustedBox} and ensures once more, which\n * probes it and restarts it in place. The cache never triggers box deletion.\n */\n cacheTtlMs?: number\n}\n\n/** Define options for composing a user profile including prompts, files, servers, and name */\nexport interface ProfileComposeOptions {\n systemPrompt?: string\n extraFiles?: AgentProfileFileMount[]\n extraMcp?: Record<string, AgentProfileMcpServer>\n name?: string\n /**\n * The harness this profile is being composed for.\n *\n * Where a resource lands is harness-specific — skills resolve to\n * `.opencode/skills/`, `.claude/skills/`, `.pi/skills/`, and so on\n * (`skillDirForHarness`), and some harnesses take no cwd skills at all.\n * Without this, an app composing a profile cannot place a harness-native\n * resource and is pushed into hardcoding one harness's path, which then\n * silently disagrees with the path its own prompt cites: the agent is told\n * to read a directory nothing was written to and its skills are invisible.\n * Prefer declaring `resources.skills` and letting the platform place them;\n * use this when composing paths directly.\n */\n harness: Harness\n}\n\n/** Define runtime configuration methods for sandbox environments including credentials, metadata, and permissions */\nexport interface SandboxRuntimeConfig {\n // Widened to accept an optional scope and be async so a per-user key can be\n // minted. The sync, no-arg form still satisfies the type (back-compat).\n credentials: (\n scope?: SandboxScope,\n ) => SandboxClientCredentials | null | Promise<SandboxClientCredentials | null>\n name: (workspaceId: string) => string\n metadata: (harness: Harness) => Record<string, unknown>\n connectedIntegrationIds: (workspaceId: string) => Promise<string[]>\n /**\n * Creation-only environment. Use runtimeEnv for expiring app credentials.\n * Values remain private; profiles reference their names through secret-ref.\n * Workspace-wide values cannot carry per-user or per-resource authority.\n */\n env: (ctx: SandboxBuildContext) => Promise<Record<string, string>>\n /**\n * Workspace app credentials resolved on creation and before every reuse,\n * resume, or recovery. Fresh values override env in the creation payload.\n * The SDK updates retained runtimes before bootstrap and refuses runtime-managed keys.\n * A resume receives only the keys the platform names as required to rebuild a runtime.\n * Throw when required credentials cannot be minted; renewal failure preserves\n * the sandbox and prevents dispatch. Requires the matching Sandbox runtime.\n * Values equal to the last ones delivered to the same box identity, within\n * 10 minutes, are resolved again but not sent again.\n */\n runtimeEnv?: (scope: SandboxScope) => Promise<Record<string, string>>\n files: (ctx: SandboxBuildContext) => Promise<AgentProfileFileMount[]>\n secrets: (workspaceId: string) => Promise<string[]>\n profile: (options: ProfileComposeOptions) => AgentProfile\n permissionRole?: (workspaceRole: string) => SandboxPermissionLevel\n resources?: SandboxResourceConfig\n provider?: ProviderResolutionConfig\n\n /**\n * Portable directory where the sandbox starts its agent processes.\n *\n * The value is relative to the sandbox workspace. The sandbox platform\n * validates it and applies it when the box is created.\n */\n cwd?: string\n\n /**\n * Product-declared outbound network policy. Applied when a sandbox is\n * created. A reused or resumed sandbox is returned only when its explicit\n * policy already matches; existing mismatches are rejected without updating\n * or deleting the sandbox unless migration is explicitly enabled below.\n * A match read within 10 minutes stands for the same box identity, except\n * that a `strict` or `blocked` policy is read again whenever a reuse would send\n * the box credentials (a changed {@link runtimeEnv}, or a {@link bootstrap}).\n */\n egressPolicy?: EgressPolicy\n /**\n * Update an existing box to {@link egressPolicy} before reuse when its\n * recorded policy is absent or different. This is an explicit fleet\n * migration switch: the updated policy is read back and must match before\n * the box is returned. It never deletes the box.\n */\n migrateEgressPolicy?: boolean\n\n /**\n * Where Worker isolates share what a reuse last checked on a box (its id, the\n * exec probe, the egress read, the runtime environment delivered). A request is\n * not promised the isolate that served the last one, so without a shared store\n * a reuse often finds nothing to trust. Default: the runtime's Cache API when\n * it has one; `null` keeps the state in the isolate. Holds ids, times and\n * digests only.\n */\n reuseState?: ReuseStateStore | null\n // BYOS3/R2 snapshot storage. Returns undefined => key omitted entirely\n // (fail-closed when creds absent). Product owns bucket/endpoint/credentials/prefix.\n storage?: (ctx: SandboxBuildContext) => StorageConfig | undefined\n // Snapshot RESTORE-on-create. undefined => fresh box. Called only when a box\n // is about to be created, so a product can resolve the restore point lazily\n // (listing snapshots is a Sandbox API round trip a reused box never needs).\n restore?: (ctx: SandboxBuildContext) => SandboxRestoreSpec | undefined | Promise<SandboxRestoreSpec | undefined>\n // Per-identity box NAME. Defaults to name(scope.workspaceId) when absent.\n boxKey?: (scope: SandboxScope) => string\n // Per-workspace child-key mint: overrides the resolved model apiKey before create.\n // Applied only when a model is resolved and its provider is openai-compat.\n childKeyMint?: (scope: SandboxScope) => Promise<Outcome<string>>\n // One-shot post-running bootstrap, on BOTH create and reuse paths (idempotency\n // is the closure's job — it owns the marker check).\n bootstrap?: (box: SandboxInstance, scope: SandboxScope) => Promise<Outcome<void>>\n /**\n * The served build this bootstrap belongs to, such as the deploy sha. A box\n * that ran {@link bootstrap} under the same build, harness, egress policy and\n * scope keeps a marker file for it, and a reuse that finds a marker younger\n * than 24 hours skips the bootstrap; a new release runs it once more on every\n * box. If something deletes what the bootstrap wrote, the box is repaired at\n * the next release or within a day, not on the next start, so a bootstrap that\n * must repair on every start declares no build, and neither does a per-turn\n * lifecycle. Declare the build id, never a hash of the bootstrap's own files.\n * Without it, the bootstrap runs on every reuse.\n */\n bootstrapDigest?: (scope: SandboxScope) => string | Promise<string>\n // Reuse health gate + sidecar liveness probe.\n livenessProbe?: LivenessProbeConfig\n // Enable browser terminal endpoints on newly-created sandboxes.\n webTerminalEnabled?: boolean\n // default true: try stopped-resume before create.\n resumeStopped?: boolean\n /**\n * How long to wait for a box to reach `running`, in ms. Default 120_000.\n *\n * Raise it when a cold create legitimately takes longer than that — a large\n * vault restore, a heavy image, a loaded fleet. The failure it prevents is\n * ugly: every attempt burns the full wait, times out, and the NEXT attempt\n * starts the same slow create from scratch, so a workspace whose provision\n * takes 130s never succeeds no matter how many times a user retries.\n */\n provisionTimeoutMs?: number\n // Opt in to replacing a box the platform cannot bring up.\n //\n // Default false, and the default is the conservative one on purpose: a\n // replacement is a delete, and delete DEPROVISIONS the persistent workspace\n // (#299). An app whose durable state lives in the box's filesystem must not\n // set this — losing the box loses the user's work.\n //\n // Set it when the box is a CACHE of state held elsewhere (a vault, a DB, an\n // object store) and can be rebuilt. Then a box that cannot be started is\n // abandoned and re-created once, instead of leaving the workspace unable to\n // run for as long as the box stays unbringable — which, without this, is\n // forever: the box key is derived from the workspace, so every later attempt\n // resumes the same dead box and fails identically.\n replaceUnbringableBox?: boolean\n // Product-owned retention/recovery policy after a stopped box fails to resume.\n // Return ok(null) to preserve the original resume error. A replacement key is\n // required before this shell creates a new box, so it cannot resolve the\n // failed stopped box through the original idempotency identity.\n recoverStoppedSandbox?: (\n failure: StoppedSandboxResumeFailure,\n ) => Promise<Outcome<StoppedSandboxResumeRecovery | null>>\n /**\n * Replace a sandbox resource or backing container that disappears after listing.\n *\n * The shell calls this for a sandbox resource 404 or an exact resume 500 that\n * wraps a host-agent container 404. It excludes runtime 404 and unrelated\n * reuse failures. Return a fresh key without deleting the stale sandbox record.\n */\n recoverMissingSandbox?: (\n failure: MissingSandboxFailure,\n ) => Promise<Outcome<StoppedSandboxResumeRecovery | null>>\n // default false: bake resolveModel() into the backend's model fields at create.\n backendModelAtCreate?: boolean\n // default false: write the profile's `resources.files` INTO the box after it\n // reaches running (via `box.exec`), instead of inlining them in the create\n // payload. The orchestrator caps the provision body at 256 KiB; a large\n // file corpus (skills, tool scripts) blows that cap. Deferring it keeps the\n // provision body small and uncapped in corpus size, and lands real files on\n // disk — which is also the only path that works for harnesses whose backend\n // does not materialize the provider-neutral `resources.files` channel.\n //\n // Only `kind: 'inline'` files are deferred; non-inline refs (e.g. github)\n // stay in the create payload so the orchestrator resolves them. Runs on the\n // create AND resume/reuse paths (idempotent overwrite). Inline files are\n // Removed from create and per-turn profiles; the deferred writer owns them.\n deferProfileFiles?: boolean\n // Byte budget on the system prompt of the profile this shell actually SENDS\n // (provision + every turn). Defaults to the same 40 KB cap\n // `composeAgentProfile` applies; set `warnOnly` + `overBudgetReason` to\n // downgrade it. Wired here because the composer is opt-in: a product may\n // hand-build its profile, or carry its real prompt only on the PER-TURN\n // backend, and then the compose-time gate never runs on the bytes the model\n // sees. An over-budget prompt degrades toward empty answers, which is\n // indistinguishable from a broken stream — so it fails loud instead.\n promptBudget?: ComposeProfileBudget\n}\n\n/** Define default resource limits and settings for sandbox environments */\nexport const DEFAULT_SANDBOX_RESOURCES: SandboxResourceConfig = {\n image: 'universal',\n cpuCores: 2,\n memoryMB: 4096,\n diskGB: 10,\n maxLifetimeSeconds: 86400,\n idleTimeoutSeconds: 3600,\n}\n\n/** Define options for ensuring a workspace sandbox with provisioning and progress handling */\nexport interface EnsureWorkspaceSandboxOptions {\n workspaceId: string\n /** This caller's lifetime. A cancellation aborts SDK transport and forbids\n * further lifecycle/recovery steps; it does not prove a remote create absent. */\n signal?: AbortSignal\n userId?: string\n harness: Harness\n // When set, both the running-reuse and stopped-resume short-circuits are\n // skipped and any name-matched box is removed before create. Replacement\n // fails if removal remains pending after the SDK's bounded wait. This is the\n // ONLY way a liveness-failed box is discarded: a failed probe triggers a\n // state-preserving stop→resume recovery (or a SandboxRecoveryFailedError),\n // never a delete — delete deprovisions the persistent workspace (#299).\n forceNew?: boolean\n // Real-time provisioning progress from the SDK's SSE stream, forwarded from\n // the `waitFor('running')` calls on the resume and cold-create paths. Callers\n // surface it as live \"warming up\" status. Only fires while a box is actually\n // being provisioned; a reused running box emits nothing.\n onProgress?: (event: ProvisionEvent) => void\n // Billing owner for the created box, forwarded VERBATIM on the create\n // payload. The sandbox platform honors it only when the create-auth\n // principal is a trusted first-party service; the box's usage then bills\n // this platform user's wallet (the platform's per-user router-key mint)\n // instead of the service account that authenticated the create. Omitted =>\n // platform default (billing owner = create-auth principal) — unchanged.\n billingOwnerId?: string\n // Optional consumer-side spend verification. Omitted, nothing here changes:\n // no extra call, no extra await, no behavior difference. Wired, it is the one\n // seam where a product both refuses to provision past a compute cap and\n // records that a box is now billable against it.\n //\n // Structural on purpose. `@tangle-network/agent-app/spend` supplies an\n // implementation (`createSandboxSpendHooks`), but this module takes no\n // dependency on it — /spend composes /sandbox, and importing back the other\n // way would invert the layering.\n spend?: SandboxSpendHooks\n /** Optional stage timing for the steps of an ensure (`sandbox.ensure.*`), so a\n * product can see which round trip a slow acquisition spent its time in.\n * Omitted, nothing is measured. */\n measure?: <T>(stage: string, operation: () => Promise<T>) => Promise<T>\n /**\n * The turn's trace. The ensure is recorded as one `sandbox.claim` span whose children are the\n * `sandbox.ensure.*` steps (`credentials`, `get_running` or `list_running`, `finalize` for a reused box,\n * with `egress` and `liveness` unless a recent check stood in for them; `list_stopped`,\n * `resume` for a stopped one; `create`, `wait_running`, `bootstrap` for a new one), so a slow claim names\n * the step it waited on. The spend seam's two calls are recorded beside the claim as\n * `sandbox.spend.before_provision` and `sandbox.spend.observe`. Omitted, nothing is recorded;\n * `measure` is unchanged and still called.\n */\n trace?: TurnTrace\n /** The span the claim hangs from. Default: the trace's root. */\n traceParent?: TurnSpan\n}\n\n/** What `/sandbox` reports once a box is provisioned, reused, or resumed. */\nexport interface SandboxProvisionedObservation {\n readonly workspaceId: string\n readonly userId?: string\n /** The platform's sandbox id — the join key to every settlement row. */\n readonly sandboxId: string\n /** The deterministic box key this workspace resolves to. */\n readonly boxKey?: string | undefined\n /** The idle timeout this box was asked to run with, seconds. */\n readonly idleTimeoutSeconds: number\n /** The max lifetime it was asked to run with, seconds, when one was asked for. */\n readonly maxLifetimeSeconds?: number | undefined\n readonly at: number\n}\n\n/**\n * Optional spend-verification seam on `ensureWorkspaceSandbox`.\n *\n * The two halves have deliberately opposite failure contracts.\n * `beforeProvision` is a GATE: it runs before anything is created and its throw\n * propagates, because refusing to provision is the whole point of a budget cap.\n * `onProvisioned` is an OBSERVER: its failures are swallowed, because\n * bookkeeping must never take down the provisioning it is bookkeeping.\n */\nexport interface SandboxSpendHooks {\n /**\n * Runs before any create, resume, restart or deletion of a box, and before a\n * reuse unless this isolate probed that box recently (10 minutes by default,\n * {@link LivenessProbeConfig.cacheTtlMs}): a reuse of a box it has been using\n * is gated when its probe expires, not on every turn. Throw to refuse provisioning.\n */\n beforeProvision?(input: { workspaceId: string; userId?: string }): Promise<void> | void\n /**\n * Runs after a box is available, except for a reuse that trusted a recent\n * probe: the ensure that ran that probe reported the box, and `onActivity`\n * carries its use since. Throwing here cannot fail the provision.\n */\n onProvisioned?(observation: SandboxProvisionedObservation): Promise<void> | void\n /**\n * The box is doing work. Fired by the turn primitives at the start of a turn\n * and again when it settles.\n *\n * Deliberately SYNCHRONOUS and unawaited — this sits on the turn path, and a\n * store write must not add latency to it or hold a stream open. An\n * implementation that persists should enqueue and return; errors are\n * swallowed here as they are for `onProvisioned`.\n *\n * Wiring it is what keeps the expectation ceiling honest for long turns:\n * without it, `lastActivityAt` only advances when a box is provisioned, so a\n * three-hour turn leaves the ceiling three hours too tight and manufactures a\n * discrepancy out of the product's own silence.\n */\n onActivity?(input: { sandboxId: string; at: number }): void\n}\n","import type { EgressPolicy } from '@tangle-network/sandbox'\n\n/**\n * Build the standard outbound policy for a product sandbox.\n *\n * Product code supplies its public origin and only the extra product-specific\n * destinations. The model capability registry is named explicitly because a\n * strict product sandbox must not inherit the platform's broad developer list.\n */\nfunction isWellFormedDomainPattern(pattern: string): boolean {\n if (!pattern || pattern.startsWith('.') || pattern.includes('..')) return false\n const labels = pattern.split('.')\n if (labels.some((label) => label.length === 0)) return false\n\n for (let index = 1; index < labels.length; index += 1) {\n if (labels[index]!.includes('*')) return false\n }\n\n const head = labels[0]!\n if (head === '*' || head === '**') return labels.length >= 2\n return !head.includes('*')\n}\n\n/** Hosts required when a product installs its pinned Python tooling at boot. */\nexport const PYPI_EGRESS_DOMAINS = ['pypi.org', 'files.pythonhosted.org', 'pypi.python.org'] as const\n\nexport function buildProductEgressPolicy(\n publicOrigin: string | URL,\n extraDomains: readonly string[] = [],\n): EgressPolicy {\n const origin = typeof publicOrigin === 'string' ? new URL(publicOrigin) : publicOrigin\n if (origin.protocol !== 'http:' && origin.protocol !== 'https:') {\n throw new Error(`Product egress origin must use http or https: ${origin.protocol}`)\n }\n if (!origin.hostname) throw new Error('Product egress origin must include a hostname')\n\n const domains = new Set<string>([origin.hostname.toLowerCase(), 'models.dev'])\n for (const value of extraDomains) {\n const domain = value.trim().toLowerCase().replace(/\\.$/, '')\n if (\n !domain\n || domain.includes('://')\n || domain.includes('/')\n || domain.includes(':')\n || !isWellFormedDomainPattern(domain)\n ) {\n throw new Error(`Product egress domain must be a hostname or wildcard: ${value}`)\n }\n domains.add(domain)\n }\n\n return {\n mode: 'strict',\n allowDomains: [...domains],\n includeImplicitDomains: false,\n }\n}\n","/**\n * The models a workspace box may call. Platform mints every box's Router key\n * (`auto:sandbox:router:<box>`) under the payer's sandbox policy, and the\n * Sandbox API sends that key with every run in place of any per-turn key. A\n * paying customer's policy names no models; a company account's (operator,\n * smoke, acceptance, staff) names only the flat-plan models and the Router's\n * synthetic model, so a box asked for any other model is refused before it\n * produces a token. `GET /v1/keys/sandbox-router-models` reports that policy\n * for the calling key without returning key material.\n */\n\nexport type SandboxModelPolicy =\n | { ok: true; allowedModels: string[] | null }\n | { ok: false; error: string }\n\nconst POLICY_TTL_MS = 10 * 60_000\nconst cache = new Map<string, { policy: { ok: true; allowedModels: string[] | null }; at: number }>()\n\nasync function keyDigest(apiKey: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(apiKey))\n return Array.from(new Uint8Array(digest).slice(0, 16), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Platform's model policy for a box minted under the payer of `apiKey`, cached\n * per key for ten minutes. A missing Platform URL, a failed request or an\n * invalid answer is a refusal, never an open policy.\n */\nexport async function readSandboxModelPolicy(\n apiKey: string,\n options: { platformUrl: string | undefined; signal?: AbortSignal },\n): Promise<SandboxModelPolicy> {\n const id = await keyDigest(apiKey)\n const cached = cache.get(id)\n if (cached && Date.now() - cached.at < POLICY_TTL_MS) return cached.policy\n const raw = options.platformUrl?.trim()\n if (!raw) return { ok: false, error: 'TANGLE_PLATFORM_URL is required to read the sandbox model policy' }\n let response: Response\n try {\n response = await fetch(`${new URL(raw).origin}/v1/keys/sandbox-router-models`, {\n headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' },\n redirect: 'manual',\n signal: options.signal ?? AbortSignal.timeout(5_000),\n })\n } catch (error) {\n return { ok: false, error: `sandbox model policy request failed: ${error instanceof Error ? error.message : String(error)}` }\n }\n if (!response.ok) return { ok: false, error: `sandbox model policy returned HTTP ${response.status}` }\n const body = await response.json().catch(() => null) as { success?: unknown; data?: { allowedModels?: unknown } } | null\n const allowed = body?.success === true && body.data && 'allowedModels' in body.data ? body.data.allowedModels : undefined\n if (allowed !== null && !(Array.isArray(allowed) && allowed.every((model) => typeof model === 'string' && model.trim()))) {\n return { ok: false, error: 'sandbox model policy returned an invalid response' }\n }\n const policy = { ok: true as const, allowedModels: allowed === null ? null : [...new Set(allowed as string[])] }\n cache.set(id, { policy, at: Date.now() })\n return policy\n}\n\n/**\n * The first preferred model the policy allows, else the policy's own first\n * model. A policy that names none allows the first preference.\n */\nexport function sandboxModelWithinPolicy(preferred: readonly string[], allowedModels: readonly string[] | null): string | undefined {\n if (allowedModels === null) return preferred[0]\n return preferred.find((model) => allowedModels.includes(model)) ?? allowedModels[0]\n}\n","import type { SandboxRuntimeConfig, SandboxScope } from './configuration'\nimport { assertEnvWithinLimits, DEFAULT_PROVISION_TIMEOUT_MS } from './payload-limits'\nimport type { SandboxInstance, EgressPolicy } from '@tangle-network/sandbox'\nimport { type Outcome, ok, fail } from './outcome'\nimport { createHash } from 'node:crypto'\nimport { checksFor, isRecent, TRUSTED_REUSE_TTL_MS, recordCheck } from './runtime-cache'\nimport {\n readDeferredCorpusMarker,\n materializeDeferredFilesForExistingBox,\n deferredProfileWriteFailed,\n} from './profile-corpus'\nimport { Sandbox } from '@tangle-network/sandbox/core'\nimport { type SandboxExistingBoxStage, SandboxEgressPolicyMismatchError } from './lifecycle-errors'\nimport type { Harness } from '../harness/index'\nimport { plannedHostRestart, readDuringPlannedHostRestart } from './transient-failure'\n\nexport async function resolveWorkspaceRuntimeEnv(\n shell: SandboxRuntimeConfig,\n scope: SandboxScope,\n): Promise<Record<string, string>> {\n const env = await shell.runtimeEnv?.(scope) ?? {}\n assertEnvWithinLimits(env)\n return env\n}\n\ntype EgressRead = Awaited<ReturnType<SandboxInstance['egress']['get']>>\n\n/**\n * Round trips of a reused box that do not depend on its liveness, started with\n * the liveness probe so they overlap it. The egress read and the corpus marker\n * are only reads: the policy is still asserted (and migrated) in finalize, and\n * an unknown marker means the corpus is written as before. The runtime env is\n * sent early only when the egress assertion cannot change where credentials\n * may go (see {@link egressGatesCredentials}); otherwise it waits for it.\n * A read or push this isolate completed within {@link TRUSTED_REUSE_TTL_MS} on\n * the same box identity is not repeated, subject to the credential rule in\n * {@link prefetchExistingBoxReads}.\n */\ninterface ExistingBoxPrefetch {\n egress?: Promise<Outcome<EgressRead>>\n /** The box's egress was verified recently enough that this reuse reads and asserts nothing. */\n egressVerified?: boolean\n corpusMarker?: Promise<string | null>\n /** The renewal already sent to the box; finalize waits for it instead of sending another. */\n runtimeEnv?: Promise<Outcome<void>>\n /** The box already holds this runtime environment, so nothing is sent. */\n envDelivered?: boolean\n /** Settles when the minted environment has decided the fields above. */\n decided: Promise<void>\n}\n\ntype ReuseMeasure = <T>(stage: string, operation: () => Promise<T>) => Promise<T>\n\nfunction runtimeEnvDigest(env: Record<string, string>): string {\n return createHash('sha256').update(JSON.stringify(canonicalizeJson(env)), 'utf8').digest('hex')\n}\n\nfunction hasDeliveredEnv(box: SandboxInstance, env: Record<string, string>): boolean {\n const delivered = checksFor(box)?.env\n return isRecent(delivered?.at, TRUSTED_REUSE_TTL_MS) && delivered?.digest === runtimeEnvDigest(env)\n}\n\nfunction hasRecentEgress(box: SandboxInstance, desired: EgressPolicy): boolean {\n const verified = checksFor(box)?.egress\n return isRecent(verified?.at, TRUSTED_REUSE_TTL_MS) && verified?.key === normalizedEgressPolicy(desired)\n}\n\nasync function pushRuntimeEnv(\n box: SandboxInstance,\n env: Record<string, string>,\n measure?: ReuseMeasure,\n deadline?: number,\n): Promise<Outcome<void>> {\n try {\n const push = () => box.setRuntimeEnv(env)\n const deliver = async () => {\n if (deadline === undefined) await push()\n else await readDuringPlannedHostRestart(push, deadline)\n }\n await (measure ? measure('runtime_env_push', deliver) : deliver())\n recordCheck(box, { env: { digest: runtimeEnvDigest(env), at: Date.now() } })\n return ok(undefined)\n } catch (cause) {\n return fail(cause)\n }\n}\n\n/**\n * Start the reads of a reused box. A recent egress read stands in for a new one\n * when the policy is `open` (a stale verdict can only cost the box its reach) or\n * when this reuse sends the box no credentials: the environment it would send is\n * already there and the shell has no bootstrap. A `strict` or `blocked` verdict\n * never stands in for the read that gates credentials, so a changed environment\n * or a bootstrap waits for a fresh read.\n */\nexport function prefetchExistingBoxReads(\n shell: SandboxRuntimeConfig,\n box: SandboxInstance,\n runtimeEnv: Promise<Record<string, string>>,\n measure: ReuseMeasure,\n): ExistingBoxPrefetch {\n const desired = shell.egressPolicy\n const readEgress = () => measure('egress', async () => {\n try {\n return ok(await box.egress.get())\n } catch (cause) {\n return fail(cause)\n }\n })\n const egressRecent = desired !== undefined && hasRecentEgress(box, desired)\n const prefetch: ExistingBoxPrefetch = { decided: Promise.resolve() }\n if (desired && !egressRecent) prefetch.egress = readEgress()\n if (shell.deferProfileFiles && !isRecent(checksFor(box)?.corpus?.at, TRUSTED_REUSE_TTL_MS)) {\n prefetch.corpusMarker = readDeferredCorpusMarker(box)\n }\n // A mint failure rejects `runtimeEnv` and the reuse stops before finalize, so\n // nothing was sent; the renewal itself is settled here and never rejects.\n prefetch.decided = runtimeEnv.then((env) => {\n const delivered = Object.keys(env).length === 0 || hasDeliveredEnv(box, env)\n prefetch.envDelivered = delivered\n if (desired && egressRecent) {\n if (desired.mode === 'open' || (delivered && !shell.bootstrap)) prefetch.egressVerified = true\n else prefetch.egress = readEgress()\n }\n if (!delivered && !egressGatesCredentials(desired)) {\n prefetch.runtimeEnv = pushRuntimeEnv(box, env, measure)\n }\n }, () => undefined)\n return prefetch\n}\n\n/**\n * Whether the egress assertion must finish before credentials reach a reused\n * box. `open` is the most permissive mode, so no policy the box can hold lets\n * credentials go anywhere `open` would not; asserting it only restores the\n * box's reach (a migration from a narrower policy). `strict` and `blocked`\n * bound where credentials can be sent, so they are asserted first.\n */\nfunction egressGatesCredentials(desired: EgressPolicy | undefined): boolean {\n return desired !== undefined && desired.mode !== 'open'\n}\n\nfunction recordVerifiedEgress(box: SandboxInstance, desired: EgressPolicy): void {\n recordCheck(box, { egress: { key: normalizedEgressPolicy(desired), at: Date.now() } })\n}\n\n// All retained-box paths renew credentials before the product bootstrap.\nexport async function finalizeExistingBox(\n shell: SandboxRuntimeConfig,\n client: Sandbox,\n box: SandboxInstance,\n stage: SandboxExistingBoxStage,\n name: string,\n workspaceId: string,\n userId: string | undefined,\n harness: Harness,\n scope: SandboxScope,\n runtimeEnv: Record<string, string>,\n prefetch: Omit<ExistingBoxPrefetch, 'decided'> = {},\n): Promise<SandboxInstance> {\n const deadline = Date.now() + (shell.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS)\n if (!prefetch.egressVerified) {\n await assertExistingBoxEgress(box, shell.egressPolicy, shell.migrateEgressPolicy, stage, name, deadline, prefetch.egress)\n }\n const written = await materializeDeferredFilesForExistingBox(\n shell,\n client,\n box,\n stage,\n name,\n workspaceId,\n userId,\n harness,\n prefetch.corpusMarker,\n )\n if (!written.succeeded) {\n throw deferredProfileWriteFailed(stage, name, written.error)\n }\n const finalBox = written.value\n if (prefetch.runtimeEnv) {\n // Liveness may be cached or omitted. Await only the typed restart signal\n // within the existing budget, after the previous push has settled.\n let renewed = await prefetch.runtimeEnv\n if (!renewed.succeeded && plannedHostRestart(renewed.error)) {\n renewed = await pushRuntimeEnv(finalBox, runtimeEnv, undefined, deadline)\n }\n if (!renewed.succeeded) throw renewed.error\n } else if (!prefetch.envDelivered && Object.keys(runtimeEnv).length > 0) {\n const renewed = await pushRuntimeEnv(finalBox, runtimeEnv, undefined, deadline)\n if (!renewed.succeeded) throw renewed.error\n }\n await bootstrapBox(shell, finalBox, scope, harness, stage, name, false)\n return finalBox\n}\n\n/** Where a box records the bootstrap keys it ran: one empty file per key in the agent's home, so a record lasts as\n * long as the box's filesystem and is gone when the home is wiped or the box is replaced. */\nconst BOOTSTRAP_MARKERS = '\"$HOME/.agent-app/bootstrapped\"'\n/** A marker older than this no longer stands in for the bootstrap, which bounds how long files the bootstrap wrote and\n * something later deleted can go unrepaired: a day, or the next release, whichever comes first. */\nconst BOOTSTRAP_MARKER_MAX_AGE_MINUTES = 24 * 60\n\n/**\n * Run the product bootstrap unless this box ran it under the same key within a day: the build the product declares\n * ({@link SandboxRuntimeConfig.bootstrapDigest}), the harness, the egress policy and the scope. Reading the marker is\n * one exec; the bootstrap it stands for is several. A fresh box has none to read. The marker is written only after the\n * bootstrap succeeds, and a failed write costs the next reuse a bootstrap. With no declared build, every call runs it.\n */\nexport async function bootstrapBox(\n shell: SandboxRuntimeConfig,\n box: SandboxInstance,\n scope: SandboxScope,\n harness: Harness,\n stage: string,\n name: string,\n fresh: boolean,\n): Promise<void> {\n const bootstrap = shell.bootstrap\n if (!bootstrap) return\n const key = await bootstrapKey(shell, scope, harness)\n if (key !== undefined && !fresh && await hasBootstrapMarker(box, key)) return\n const boot = await bootstrap.call(shell, box, scope)\n if (!boot.succeeded) {\n throw new Error(`bootstrap failed on ${stage} box ${name}`, { cause: boot.error })\n }\n if (key !== undefined) await writeBootstrapMarker(box, key)\n}\n\nasync function bootstrapKey(shell: SandboxRuntimeConfig, scope: SandboxScope, harness: Harness): Promise<string | undefined> {\n if (!shell.bootstrapDigest) return undefined\n const build = await shell.bootstrapDigest(scope)\n if (!build) return undefined\n const egress = shell.egressPolicy ? normalizedEgressPolicy(shell.egressPolicy) : null\n return createHash('sha256')\n .update(JSON.stringify([build, harness, egress, scope.workspaceId, scope.userId ?? null]), 'utf8').digest('hex')\n}\n\nasync function hasBootstrapMarker(box: SandboxInstance, key: string): Promise<boolean> {\n try {\n const fresh = `find ${BOOTSTRAP_MARKERS} -maxdepth 1 -name ${key} -mmin -${BOOTSTRAP_MARKER_MAX_AGE_MINUTES} 2>/dev/null`\n return (await box.exec(`test -n \"$(${fresh})\"`)).exitCode === 0\n } catch {\n return false\n }\n}\n\n/**\n * Remove this box's bootstrap markers, so its next start runs the bootstrap again. Call it when a turn fails on\n * something the bootstrap provides (a runtime it installs, a folder it creates): without it, the box would stay\n * broken until the next release or for up to a day. Best effort; returns whether the box confirmed the removal.\n */\nexport async function forgetBootstrap(box: SandboxInstance): Promise<boolean> {\n try {\n return (await box.exec(`rm -rf ${BOOTSTRAP_MARKERS}`)).exitCode === 0\n } catch {\n return false\n }\n}\n\nasync function writeBootstrapMarker(box: SandboxInstance, key: string): Promise<void> {\n try {\n await box.exec(`mkdir -p ${BOOTSTRAP_MARKERS} && : > ${BOOTSTRAP_MARKERS}/${key}`)\n } catch {\n // The next reuse finds no marker and bootstraps again.\n }\n}\n\nfunction canonicalizeJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalizeJson)\n if (value === null || typeof value !== 'object') return value\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)\n .map(([key, entry]) => [key, canonicalizeJson(entry)]),\n )\n}\n\nfunction normalizedEgressPolicy(policy: EgressPolicy): string {\n const normalized: Record<string, unknown> = { ...policy }\n if (policy.mode === 'strict') {\n // Entries arrive as bare domains or `{ domain, allowPrivateIps }` records;\n // canonicalize both shapes so an equivalent record and bare entry compare\n // equal while differing private-IP allowances still mismatch.\n normalized.allowDomains = [...new Set(\n (policy.allowDomains ?? [])\n .map((entry) => {\n if (typeof entry === 'string') {\n const domain = entry.trim().toLowerCase()\n return domain ? JSON.stringify({ domain, allowPrivateIps: [] }) : null\n }\n const domain = entry.domain.trim().toLowerCase()\n return domain\n ? JSON.stringify({ domain, allowPrivateIps: [...new Set(entry.allowPrivateIps)].sort() })\n : null\n })\n .filter((entry): entry is string => entry !== null),\n )].sort()\n normalized.includeImplicitDomains = policy.includeImplicitDomains !== false\n } else {\n // `allowDomains` and `includeImplicitDomains` are ignored in open and\n // blocked modes, and the platform keeps a box's old strict list attached\n // after a migration to open. Comparing them refused a box that already had\n // exactly the policy asked for, and every reuse of that box after.\n delete normalized.allowDomains\n delete normalized.includeImplicitDomains\n }\n return JSON.stringify(canonicalizeJson(normalized))\n}\n\nfunction existingBoxEgressError(\n operation: 'read' | 'migration',\n box: SandboxInstance,\n stage: SandboxExistingBoxStage,\n name: string,\n cause: unknown,\n): Error {\n const error = cause instanceof Error ? cause : new Error(String(cause))\n const status = (error as { status?: unknown }).status\n const suffix = operation === 'migration' ? '/egress' : ''\n return Object.assign(\n new Error(`egress policy ${operation} failed on ${stage} box ${name}: ${error.message}`, {\n cause: error,\n }),\n {\n origin: 'sandbox-api',\n endpoint: `/v1/sandboxes/${encodeURIComponent(box.id)}${suffix}`,\n ...(typeof status === 'number' || typeof status === 'string' ? { status } : {}),\n },\n )\n}\n\nasync function assertExistingBoxEgress(\n box: SandboxInstance,\n desired: EgressPolicy | undefined,\n migrate: boolean | undefined,\n stage: SandboxExistingBoxStage,\n name: string,\n deadline: number,\n prefetched?: Promise<Outcome<Awaited<ReturnType<SandboxInstance['egress']['get']>>>>,\n): Promise<void> {\n if (!desired) return\n let current: Awaited<ReturnType<SandboxInstance['egress']['get']>>\n const read = prefetched ? await prefetched : undefined\n if (read?.succeeded) {\n current = read.value\n } else {\n if (read && !read.succeeded && !plannedHostRestart(read.error)) {\n throw existingBoxEgressError('read', box, stage, name, read.error)\n }\n // A cached or omitted probe may not have observed the host return.\n // Wait for the typed refusal to clear before asserting current policy.\n try {\n current = (await readDuringPlannedHostRestart(() => box.egress.get(), deadline)).value\n } catch (cause) {\n throw existingBoxEgressError('read', box, stage, name, cause)\n }\n }\n const matchingPolicy = normalizedEgressPolicy(current.policy) === normalizedEgressPolicy(desired)\n const explicitSource = current.source !== 'platform'\n if (matchingPolicy && explicitSource) {\n recordVerifiedEgress(box, desired)\n return\n }\n\n if (migrate) {\n try {\n await box.egress.update(desired)\n const migrated = await box.egress.get()\n const migratedPolicy = normalizedEgressPolicy(migrated.policy) === normalizedEgressPolicy(desired)\n if (migratedPolicy && migrated.source !== 'platform') {\n recordVerifiedEgress(box, desired)\n return\n }\n current = migrated\n } catch (cause) {\n throw existingBoxEgressError('migration', box, stage, name, cause)\n }\n }\n\n throw new SandboxEgressPolicyMismatchError(\n stage,\n name,\n current.policy,\n current.source,\n desired,\n )\n}\n","import type { AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport { createHash } from 'node:crypto'\nimport type { SandboxRuntimeConfig, SandboxBuildContext } from './configuration'\nimport { Sandbox } from '@tangle-network/sandbox/core'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { SandboxExistingBoxStage } from './lifecycle-errors'\nimport type { Harness } from '../harness/index'\nimport { type Outcome, ok } from './outcome'\nimport { splitDeferredProfileFiles } from './profile-files'\nimport { checksFor, isRecent, TRUSTED_REUSE_TTL_MS, recordCheck } from './runtime-cache'\nimport { writeDeferredFilesWithRuntimeAuthRefresh } from './runtime-connection'\n\nexport function deferredProfileWriteFailed(stage: 'new' | 'reused' | 'resumed', name: string, cause: Error): Error {\n return new Error(`deferred file write failed on ${stage} box ${name}: ${cause.message}`, { cause })\n}\n\n// Resolve the shell's deferred (inline) profile files and write them into a\n// box that already exists (reuse/resume paths). No-op unless the shell opts\n// into deferProfileFiles. Idempotent overwrite — a redeploy with new skills\n// refreshes the corpus on the next ensure call.\n// Box-metadata key holding the content hash of the deferred corpus that was\n// written to the box at CREATE. On reuse, an unchanged hash means the skills are\n// already on disk, so the (large, file-API) re-write can be skipped.\nexport const DEFERRED_CORPUS_HASH_KEY = 'agentAppDeferredCorpusHash'\n\n/** Stable content hash of the deferred file corpus (path + inline content).\n * Unchanged corpus ⇒ same hash; a new/edited/removed skill ⇒ different hash.\n * Exported for the reuse-skip test. */\nexport function deferredCorpusHash(files: AgentProfileFileMount[]): string {\n const norm = files\n .map((f) => ({\n p: f.path,\n c: f.resource.kind === 'inline' ? ((f.resource as { content?: string }).content ?? '') : `ref:${f.resource.kind}`,\n }))\n .sort((a, b) => (a.p < b.p ? -1 : a.p > b.p ? 1 : 0))\n return createHash('sha256').update(JSON.stringify(norm), 'utf8').digest('hex')\n}\n\nexport async function materializeDeferredFilesForExistingBox(\n shell: SandboxRuntimeConfig,\n client: Sandbox,\n box: SandboxInstance,\n stage: SandboxExistingBoxStage,\n name: string,\n workspaceId: string,\n userId: string | undefined,\n harness: Harness,\n corpusMarker?: Promise<string | null>,\n): Promise<Outcome<SandboxInstance>> {\n if (!shell.deferProfileFiles) return ok(box)\n const connectedIntegrationIds = await shell.connectedIntegrationIds(workspaceId)\n const buildCtx: SandboxBuildContext = {\n workspaceId,\n connectedIntegrationIds,\n ...(userId ? { userId } : {}),\n }\n const files = await shell.files(buildCtx)\n const fullProfile = shell.profile({ extraFiles: files, harness })\n const { deferredFiles } = splitDeferredProfileFiles(fullProfile)\n if (deferredFiles.length === 0) return ok(box)\n // Skip the whole re-write when the corpus is UNCHANGED since the box was\n // created with it. The skill corpus is large and the bulk goes through the\n // file API (writeMany) UNCONDITIONALLY, so re-writing it on every reuse adds\n // seconds of latency to each turn. The create payload stamps the corpus hash\n // into box metadata; a matching hash means the skills are already on disk.\n // Fail-safe: a missing or mismatched hash (e.g. a redeploy with new skills, or\n // a box created before this optimization) WRITES — a stale skip is never\n // risked. Reads metadata only, so no extra exec/round-trip.\n const corpusHash = deferredCorpusHash(deferredFiles)\n const stampedHash = (box.metadata as Record<string, unknown> | undefined)?.[DEFERRED_CORPUS_HASH_KEY]\n if (typeof stampedHash === 'string' && stampedHash === corpusHash) return ok(box)\n // The create-time stamp goes stale on the first release that changes the\n // corpus, and without this the box rewrote the whole corpus on every reuse\n // after it (a ~0.7 s file batch per GTM turn). The marker is\n // written only after a corpus write succeeds and lives on the same disk as\n // the files, so a lost disk loses both and the corpus is written again.\n // What this isolate last found on the box stands in for reading the marker\n // again for as long as it trusts a probe of the same box identity.\n const found = checksFor(box)?.corpus\n if (isRecent(found?.at, TRUSTED_REUSE_TTL_MS) && found?.hash === corpusHash) return ok(box)\n if ((await (corpusMarker ?? readDeferredCorpusMarker(box))) === corpusHash) {\n recordCheck(box, { corpus: { hash: corpusHash, at: Date.now() } })\n return ok(box)\n }\n const written = await writeDeferredFilesWithRuntimeAuthRefresh(client, box, deferredFiles, stage, name)\n if (written.succeeded) {\n await writeDeferredCorpusMarker(written.value, corpusHash)\n recordCheck(written.value, { corpus: { hash: corpusHash, at: Date.now() } })\n }\n return written\n}\n\n/** Where a reused box records the deferred corpus it last received in full,\n * relative to /home/agent like every file-API profile write. */\nconst DEFERRED_CORPUS_MARKER_PATH = '.agent-app/deferred-corpus-hash'\n\nconst DEFERRED_CORPUS_HASH_RE = /^[0-9a-f]{64}$/\n\n/** The corpus hash a box last recorded, or null when it is absent or unreadable. */\nexport async function readDeferredCorpusMarker(box: SandboxInstance): Promise<string | null> {\n if (typeof box.read !== 'function') return null\n try {\n const value = (await box.read(`/home/agent/${DEFERRED_CORPUS_MARKER_PATH}`)).trim()\n return DEFERRED_CORPUS_HASH_RE.test(value) ? value : null\n } catch {\n return null\n }\n}\n\n/** Best effort: a failed marker write only costs the next reuse a corpus rewrite. */\nasync function writeDeferredCorpusMarker(box: SandboxInstance, corpusHash: string): Promise<void> {\n if (typeof box.fs?.writeMany !== 'function') return\n try {\n await box.fs.writeMany([{ path: DEFERRED_CORPUS_MARKER_PATH, content: corpusHash }])\n } catch {\n // The corpus itself is on disk; the next reuse writes it and the marker again.\n }\n}\n","import type { SandboxInstance, EgressPolicy } from '@tangle-network/sandbox'\n\nexport type SandboxExistingBoxStage = 'reused' | 'resumed'\n\nexport type SandboxEgressPolicySource = Awaited<\n ReturnType<SandboxInstance['egress']['get']>\n>['source']\n\n/**\n * Thrown when an existing sandbox cannot be proven to have the requested\n * outbound network policy. The sandbox is preserved and its policy is not\n * changed. The caller explicitly decides whether to preserve, migrate, or\n * replace the sandbox.\n */\nexport class SandboxEgressPolicyMismatchError extends Error {\n readonly stage: SandboxExistingBoxStage\n readonly boxName: string\n readonly currentPolicy: EgressPolicy\n readonly currentSource: SandboxEgressPolicySource\n readonly desiredPolicy: EgressPolicy\n\n constructor(\n stage: SandboxExistingBoxStage,\n boxName: string,\n currentPolicy: EgressPolicy,\n currentSource: SandboxEgressPolicySource,\n desiredPolicy: EgressPolicy,\n ) {\n super(\n `egress policy mismatch on ${stage} box ${boxName}: ` +\n `current ${currentPolicy.mode} policy from ${currentSource} does not explicitly match ` +\n `desired ${desiredPolicy.mode} policy; the existing box was preserved and egress was not updated.`,\n )\n this.name = 'SandboxEgressPolicyMismatchError'\n this.stage = stage\n this.boxName = boxName\n this.currentPolicy = currentPolicy\n this.currentSource = currentSource\n this.desiredPolicy = desiredPolicy\n }\n}\n\n/** Represent an error thrown when sandbox runtime authentication refresh fails for a specific stage and name */\nexport class SandboxRuntimeAuthRefreshError extends Error {\n constructor(stage: SandboxExistingBoxStage, name: string, detail: string, cause?: unknown) {\n super(`${stage} sandbox auth refresh failed for ${name}: ${detail}`, { cause })\n this.name = 'SandboxRuntimeAuthRefreshError'\n }\n}\n\n/** Which step of the state-preserving stop→resume recovery failed. `stop` with a\n * driver-unsupported cause means the platform cannot restart this box (the\n * `tangle` driver exposes create/delete only); `probe` means the box restarted\n * but is still unresponsive. */\nexport type SandboxRecoveryPhase = 'stop' | 'resume' | 'probe'\n\n/**\n * Thrown when an unresponsive box could not be recovered by a state-preserving\n * restart. Contract: this error is only ever thrown with the workspace intact —\n * recovery never deletes. The caller decides what to do next (retry, surface to\n * the user, or explicitly replace via `forceNew`).\n */\nexport class SandboxRecoveryFailedError extends Error {\n readonly boxKey: string\n readonly stage: SandboxExistingBoxStage\n readonly phase: SandboxRecoveryPhase\n constructor(\n stage: SandboxExistingBoxStage,\n boxKey: string,\n phase: SandboxRecoveryPhase,\n detail: string,\n cause?: unknown,\n ) {\n super(\n `${stage} sandbox ${boxKey} failed liveness recovery at ${phase}: ${detail}. ` +\n `The workspace is preserved; pass forceNew to replace the box.`,\n { cause },\n )\n this.name = 'SandboxRecoveryFailedError'\n this.boxKey = boxKey\n this.stage = stage\n this.phase = phase\n }\n}\n\n/**\n * Thrown instead of restarting a box that failed the reuse gate because it is\n * not connectable (runtime URL missing or edge readiness failed) while its\n * runtime reports running sessions. A restart would end those sessions, so the\n * box is left running and only the request that asked for it fails. The box is\n * not replaced either; retry once its sessions finish.\n */\nexport class SandboxBoxBusyError extends Error {\n readonly boxKey: string\n readonly stage: SandboxExistingBoxStage\n readonly runningSessions: number\n constructor(stage: SandboxExistingBoxStage, boxKey: string, runningSessions: number, detail: string) {\n super(\n `${stage} sandbox ${boxKey} is not connectable (${detail}) but is serving ${runningSessions} running ` +\n `session${runningSessions === 1 ? '' : 's'}, so it was not restarted. Retry when they finish.`,\n )\n this.name = 'SandboxBoxBusyError'\n this.boxKey = boxKey\n this.stage = stage\n this.runningSessions = runningSessions\n }\n}\n","import type { SandboxConnection, SandboxInstance } from '@tangle-network/sandbox'\nimport { Sandbox } from '@tangle-network/sandbox/core'\nimport { type SandboxExistingBoxStage, SandboxRuntimeAuthRefreshError } from './lifecycle-errors'\nimport { type Outcome, ok, fail } from './outcome'\nimport { isRuntimeAuthRefreshDenied, isRuntimeExecAuthError } from './exec-failure'\nimport type { AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport { writeProfileFilesToBox } from './profile-files'\nimport { waitForSandboxPoll } from './request-cancellation'\n\nconst RUNTIME_AUTH_REFRESH_SKEW_MS = 60_000\n\nconst RUNTIME_CONNECTION_WAIT_MS = 30_000\n\nconst RUNTIME_CONNECTION_POLL_MS = 1_000\n\n// `sidecarUrl` is a product/forward-compat field the orchestrator may set on\n// the connection ahead of the SDK declaring it — the v0.6 `SandboxConnection`\n// exposes only `runtimeUrl`. Read it through a typed augmentation rather than an\n// ad-hoc cast (a plain `SandboxConnection` satisfies the optional field), and\n// fall back to the SDK runtime URL. The product-facing `WorkspaceSandboxInstanceLike`\n// carries the same field for consumers driving their own box types.\ntype RuntimeConnectionFields = SandboxConnection & {\n sidecarUrl?: string\n authToken?: string\n sidecarToken?: string\n authTokenExpiresAt?: string | number | Date\n sidecarTokenExpiresAt?: string | number | Date\n}\n\nexport function sandboxRuntimeUrl(box: SandboxInstance): string | undefined {\n const connection: RuntimeConnectionFields | undefined = box.connection\n return connection?.sidecarUrl ?? connection?.runtimeUrl\n}\n\nfunction runtimeAuthExpiresAtMs(value: string | number | Date | undefined): number | undefined {\n if (value instanceof Date) return value.getTime()\n if (typeof value === 'number') return value\n if (typeof value !== 'string' || value.trim() === '') return undefined\n const parsed = Date.parse(value)\n return Number.isNaN(parsed) ? undefined : parsed\n}\n\nfunction hasFreshRuntimeExecAuth(box: SandboxInstance, now = Date.now()): boolean {\n const connection: RuntimeConnectionFields | undefined = box.connection\n const token = connection?.authToken ?? connection?.sidecarToken\n if (!sandboxRuntimeUrl(box) || !token) return false\n const expiresAt = runtimeAuthExpiresAtMs(\n connection?.authTokenExpiresAt ?? connection?.sidecarTokenExpiresAt,\n )\n return expiresAt === undefined || expiresAt > now + RUNTIME_AUTH_REFRESH_SKEW_MS\n}\n\nexport function sandboxEdgeFailed(box: SandboxInstance): boolean {\n // `edgeStatus`/`edgeError` are declared on the SDK's `SandboxConnection`, so no cast.\n const connection = box.connection\n return connection?.edgeStatus === 'failed' || Boolean(connection?.edgeError)\n}\n\nexport async function refreshRuntimeConnection(\n client: Sandbox,\n box: SandboxInstance,\n): Promise<SandboxInstance> {\n client.signal?.throwIfAborted()\n let current = box\n if (sandboxRuntimeUrl(current)) return current\n\n const deadline = Date.now() + RUNTIME_CONNECTION_WAIT_MS\n while (Date.now() < deadline) {\n // Tolerate transient refresh/get failures (5xx, network blips) while the\n // orchestrator is still attaching the connection: swallow and retry. A box\n // that never surfaces a runtime URL is returned as-is so the caller's\n // readiness gate (isReusableBox) sends it into state-preserving recovery\n // (or fails loud) — rather than this poll throwing a hard provisioning\n // failure on a recoverable hiccup.\n try {\n await current.refresh()\n if (sandboxRuntimeUrl(current)) return current\n\n const latest = await client.get(current.id)\n if (latest) current = latest\n if (sandboxRuntimeUrl(current)) return current\n } catch {\n client.signal?.throwIfAborted()\n // transient — fall through to the poll delay and retry\n }\n\n await waitForSandboxPoll(RUNTIME_CONNECTION_POLL_MS, client.signal)\n }\n\n return current\n}\n\nasync function bestEffortRefreshRuntimeExecAuth(\n client: Sandbox,\n box: SandboxInstance,\n stage: SandboxExistingBoxStage,\n name: string,\n): Promise<Outcome<SandboxInstance>> {\n client.signal?.throwIfAborted()\n let current = box\n\n try {\n await current.refresh()\n if (hasFreshRuntimeExecAuth(current)) return ok(current)\n } catch (err) {\n client.signal?.throwIfAborted()\n if (isRuntimeAuthRefreshDenied(err)) {\n return fail(\n new SandboxRuntimeAuthRefreshError(\n stage,\n name,\n 'runtime exec auth refresh was unauthorized',\n err,\n ),\n )\n }\n }\n\n try {\n const latest = await client.get(current.id)\n if (latest) current = latest\n if (hasFreshRuntimeExecAuth(current)) return ok(current)\n } catch (err) {\n client.signal?.throwIfAborted()\n if (isRuntimeAuthRefreshDenied(err)) {\n return fail(\n new SandboxRuntimeAuthRefreshError(\n stage,\n name,\n 'runtime exec auth re-fetch was unauthorized',\n err,\n ),\n )\n }\n }\n\n return ok(current)\n}\n\nasync function refreshRuntimeExecAuth(\n client: Sandbox,\n box: SandboxInstance,\n stage: SandboxExistingBoxStage,\n name: string,\n): Promise<Outcome<SandboxInstance>> {\n client.signal?.throwIfAborted()\n let current = box\n let lastError: unknown\n const deadline = Date.now() + RUNTIME_CONNECTION_WAIT_MS\n\n while (Date.now() < deadline) {\n try {\n await current.refresh()\n if (hasFreshRuntimeExecAuth(current)) return ok(current)\n\n const latest = await client.get(current.id)\n if (latest) current = latest\n if (hasFreshRuntimeExecAuth(current)) return ok(current)\n } catch (err) {\n client.signal?.throwIfAborted()\n lastError = err\n }\n\n await waitForSandboxPoll(RUNTIME_CONNECTION_POLL_MS, client.signal)\n }\n\n const detail = sandboxRuntimeUrl(current)\n ? 'runtime exec credentials are missing or expired after refresh'\n : 'runtime connection is missing after refresh'\n return fail(new SandboxRuntimeAuthRefreshError(stage, name, detail, lastError))\n}\n\nexport async function writeDeferredFilesWithRuntimeAuthRefresh(\n client: Sandbox,\n box: SandboxInstance,\n files: AgentProfileFileMount[],\n stage: SandboxExistingBoxStage,\n name: string,\n): Promise<Outcome<SandboxInstance>> {\n let writeBox = box\n\n if (!hasFreshRuntimeExecAuth(writeBox)) {\n const refreshed = await bestEffortRefreshRuntimeExecAuth(client, writeBox, stage, name)\n if (!refreshed.succeeded) return fail(refreshed.error)\n writeBox = refreshed.value\n }\n\n const first = await writeProfileFilesToBox(writeBox, files)\n if (first.succeeded) return ok(writeBox)\n if (!isRuntimeExecAuthError(first.error)) return fail(first.error)\n\n const refreshed = await refreshRuntimeExecAuth(client, writeBox, stage, name)\n if (!refreshed.succeeded) return fail(refreshed.error)\n\n const second = await writeProfileFilesToBox(refreshed.value, files)\n if (second.succeeded) return ok(refreshed.value)\n if (!isRuntimeExecAuthError(second.error)) return fail(second.error)\n\n return fail(\n new SandboxRuntimeAuthRefreshError(\n stage,\n name,\n 'runtime exec remained unauthorized after auth refresh',\n second.error,\n ),\n )\n}\n","import { type AppToolName, type AppToolContext, type ToolHeaderNames, buildAppToolMcpServer } from '../tools/index'\nimport type { AgentProfileMcpServer, AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport { shellSingleQuote } from './shell-path'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { type Outcome, fail, ok } from './outcome'\n\n/** Describe an application tool with its name, unique key, and description */\nexport interface AppToolDescriptor {\n tool: AppToolName\n key: string\n description: string\n}\n\n/** Define options for building MCP server configurations in the app tool environment */\nexport interface BuildAppToolMcpServersOptions {\n tools: AppToolDescriptor[]\n baseUrl: string\n /**\n * NAME of the box-environment variable holding the capability token — never\n * the token itself. Every emitted `Authorization` header is a `secret-ref` to\n * this key, which the sandbox resolves privately; see\n * `BuildHttpMcpServerOptions.tokenEnvKey` in `../tools/mcp`.\n *\n * The key must name a variable the box carries — placed by\n * {@link SandboxRuntimeConfig.env} at creation, refreshed by\n * {@link SandboxRuntimeConfig.runtimeEnv} before retained-box bootstrap, or\n * injected from the platform secret store via\n * {@link SandboxRuntimeConfig.secrets}.\n */\n tokenEnvKey: string\n ctx: AppToolContext\n headerNames?: ToolHeaderNames\n}\n\n/** Build a mapping of MCP server profiles keyed by tool identifiers from provided options */\nexport function buildAppToolMcpServers(\n options: BuildAppToolMcpServersOptions,\n): Record<string, AgentProfileMcpServer> {\n const entries: Record<string, AgentProfileMcpServer> = {}\n for (const { tool, key, description } of options.tools) {\n // No cast: since the tagged-config contract (agent-interface 0.38.0) the\n // builder's own return type IS an AgentProfileMcpServer. The cast that used\n // to sit here is what let the pre-0.38.0 plain-string shape ship.\n entries[key] = buildAppToolMcpServer({\n tool,\n baseUrl: options.baseUrl,\n tokenEnvKey: options.tokenEnvKey,\n ctx: options.ctx,\n description,\n headerNames: options.headerNames,\n })\n }\n return entries\n}\n\n/**\n * One tool name on a sandbox PATH: a program mounted from its own bytes, or a second name for a program another\n * entry in the same call mounts. An alias mounts a small shell shim instead of a copy, so a program that answers to\n * several names (one that dispatches on its invoked name) is sent once.\n */\nexport type SandboxToolSpec =\n | { name: string; content: string; executable?: boolean; aliasOf?: undefined }\n | {\n name: string\n /** The entry in this call whose program this name runs. The shim runs it through a link that carries this\n * name, so the program reads it as `basename \"$0\"` (`os.path.basename(sys.argv[0])` in Python) and finds\n * its own file and siblings through `realpath`. */\n aliasOf: string\n content?: undefined\n executable?: undefined\n }\n\n/** Define options for resolving sandbox tool paths including appName, baseDir, and binDir */\nexport interface SandboxToolPathOptions {\n appName: string\n baseDir?: string\n binDir?: string\n}\n\n/** Define options for building sandbox tool file mounts including tool specifications and paths */\nexport interface BuildSandboxToolFileMountsOptions extends SandboxToolPathOptions {\n tools: readonly SandboxToolSpec[]\n}\n\nconst DEFAULT_SANDBOX_TOOL_BASE_DIR = '/home/agent/tools'\n\nconst SAFE_TOOL_SEGMENT = /^[A-Za-z0-9._-]+$/\n\nfunction normalizeSandboxToolSegment(value: string, label: string): string {\n const segment = value.trim()\n if (!segment || segment === '.' || segment === '..' || !SAFE_TOOL_SEGMENT.test(segment)) {\n throw new Error(`${label} must contain only letters, numbers, dots, underscores, or hyphens.`)\n }\n return segment\n}\n\nfunction normalizeSandboxToolDir(value: string, label: string): string {\n const dir = value.trim().replace(/\\/+$/, '')\n if (!dir || !dir.startsWith('/') || dir.includes('\\0') || dir.includes('\\n')) {\n throw new Error(`${label} must be an absolute sandbox path.`)\n }\n return dir === '' ? '/' : dir\n}\n\n/** Resolve the root directory path for a sandbox tool based on provided options */\nexport function sandboxToolRootDir(options: SandboxToolPathOptions): string {\n const appName = normalizeSandboxToolSegment(options.appName, 'sandbox tool appName')\n const baseDir = normalizeSandboxToolDir(\n options.baseDir ?? DEFAULT_SANDBOX_TOOL_BASE_DIR,\n 'sandbox tool baseDir',\n )\n return `${baseDir}/${appName}`\n}\n\n/** Resolve the binary directory path for a sandbox tool based on provided options */\nexport function sandboxToolBinDir(options: SandboxToolPathOptions): string {\n normalizeSandboxToolSegment(options.appName, 'sandbox tool appName')\n if (options.binDir) return normalizeSandboxToolDir(options.binDir, 'sandbox tool binDir')\n return `${sandboxToolRootDir(options)}/bin`\n}\n\n/** Resolve the file system path to a specified sandbox tool based on given options */\nexport function sandboxToolPath(options: SandboxToolPathOptions & { toolName: string }): string {\n const toolName = normalizeSandboxToolSegment(options.toolName, 'sandbox tool name')\n return `${sandboxToolBinDir(options)}/${toolName}`\n}\n\n/** One program's bytes under two names are always avoidable with `aliasOf`; below this size a copy is a shim. */\nconst DUPLICATE_PROGRAM_MIN_BYTES = 4_096\n\n/** The shim an alias mounts: a link named for the alias, then `exec` through it, so the program sees that name. */\nfunction sandboxToolAliasShim(alias: string, program: string): string {\n return [\n '#!/bin/sh',\n `# ${alias} runs ${program} under its own name. Mounted by buildSandboxToolFileMounts (aliasOf).`,\n `program=${shellSingleQuote(program)}`,\n `link=\"\\${TMPDIR:-/tmp}/sandbox-tool-aliases\\${program}.d/${alias}\"`,\n '[ -L \"$link\" ] || { mkdir -p \"${link%/*}\" && { ln -s \"$program\" \"$link\" 2>/dev/null || [ -L \"$link\" ]; }; } || {',\n ` echo \"${alias}: cannot create its alias link under \\${TMPDIR:-/tmp}\" >&2`,\n ' exit 126',\n '}',\n 'exec \"$link\" \"$@\"',\n '',\n ].join('\\n')\n}\n\n/**\n * Build file mounts for sandbox tools based on provided options and tool configurations.\n *\n * An `aliasOf` entry mounts a shim that runs the named entry's program under its own name, so the program's bytes\n * are mounted once. Two entries carrying the same program of 4 KB or more are refused: a secret-isolated session\n * sends every mount inline in one request capped at 1 MiB, and GTM's five copies of one 342 KB program made\n * every computer step fail there (2026-10-24).\n */\nexport function buildSandboxToolFileMounts(\n options: BuildSandboxToolFileMountsOptions,\n): AgentProfileFileMount[] {\n const programs = new Map<string, string>()\n const byContent = new Map<string, string>()\n for (const tool of options.tools) {\n if (tool.aliasOf !== undefined) continue\n const name = normalizeSandboxToolSegment(tool.name, 'sandbox tool name')\n if (tool.executable !== false) programs.set(name, sandboxToolPath({ ...options, toolName: name }))\n const first = byContent.get(tool.content)\n if (first !== undefined && new TextEncoder().encode(tool.content).byteLength >= DUPLICATE_PROGRAM_MIN_BYTES) {\n throw new Error(\n `sandbox tools ${first} and ${name} mount the same program; mount it once and declare ${name} as ` +\n `{ name: '${name}', aliasOf: '${first}' }.`,\n )\n }\n if (first === undefined) byContent.set(tool.content, name)\n }\n return options.tools.map((tool) => {\n const name = normalizeSandboxToolSegment(tool.name, 'sandbox tool name')\n const path = sandboxToolPath({ ...options, toolName: name })\n if (tool.aliasOf === undefined) {\n return { path, resource: { kind: 'inline' as const, name, content: tool.content }, executable: tool.executable ?? true }\n }\n const program = programs.get(normalizeSandboxToolSegment(tool.aliasOf, 'sandbox tool aliasOf'))\n if (!program) {\n throw new Error(`sandbox tool ${name} is an alias of ${tool.aliasOf}, which is not an executable program in this call.`)\n }\n return { path, resource: { kind: 'inline' as const, name, content: sandboxToolAliasShim(name, program) }, executable: true }\n })\n}\n\n/**\n * Build the `SANDBOX_TOOL_BIN_DIRS` entry that puts these apps' tool bin dirs on\n * a sandbox PATH. Declare it in the same box env as the mounts from\n * {@link buildSandboxToolFileMounts}: the mounts place the executables, this\n * places the directory that makes a bare tool name resolve.\n *\n * Every sandbox PATH builder appends these directories at the TAIL, after the\n * Nix, npm, and image entries, so a tool never shadows a platform or system\n * binary of the same name. That placement is identical for a non-interactive\n * exec, a sidecar-spawned CLI, and an SSH shell, which is why this variable and\n * not a shell rc file is the mechanism: an exec reads no rc file, and the SSH\n * shell environment assigns PATH absolutely.\n *\n * Entries come from {@link sandboxToolBinDir}, so the value can never name a\n * directory the mounts did not use — a caller that hand-writes the literal\n * instead drifts silently the moment a base dir changes. Order is preserved,\n * and two apps that resolve to one directory collapse to the FIRST position it\n * appeared in.\n *\n * A `:` in a resolved bin dir throws here. The character separates entries both\n * in this variable and in PATH itself, so such a directory is unrepresentable\n * rather than merely awkward: joining it would split one absolute path into a\n * leading path and a relative remainder, and the runtime rejects a relative\n * segment by failing the whole box. Throwing names the offending directory\n * instead.\n *\n * The consuming half lives in agent-container: `resolveSandboxToolBinDirs`\n * parses this value and every PATH builder appends it at the tail — sidecar\n * exec and PTY through `packages/shared/src/cache-env.ts`, an SSH session\n * through `packages/shared/src/ssh-bootstrap.ts`, and a spawned CLI through\n * `packages/sdk-cli-runner/src/cli-process.ts`, each with its own tests. This\n * package has no sandbox runtime, so tail placement is pinned there, not here.\n */\nexport function buildSandboxToolBinDirsEnv(\n apps: readonly SandboxToolPathOptions[],\n): { SANDBOX_TOOL_BIN_DIRS: string } {\n if (apps.length === 0) {\n throw new Error(\n 'buildSandboxToolBinDirsEnv: name at least one app whose tool bin dir belongs on PATH.',\n )\n }\n const binDirs = new Set<string>()\n for (const app of apps) {\n const binDir = sandboxToolBinDir(app)\n if (binDir.includes(':')) {\n throw new Error(\n `sandbox tool bin dir ${binDir} contains ':', which separates entries in ` +\n 'SANDBOX_TOOL_BIN_DIRS and in PATH. Place the tools under a colon-free directory.',\n )\n }\n binDirs.add(binDir)\n }\n return { SANDBOX_TOOL_BIN_DIRS: [...binDirs].join(':') }\n}\n\n/**\n * Build a shell script that creates the sandbox tool binary directory.\n * {@link buildSandboxToolBinDirsEnv}, not this script, puts that directory on a\n * sandbox PATH.\n *\n * The `mkdir -p` makes the directory exist before a tool mount lands in it.\n */\nexport function buildSandboxToolBinDirScript(options: SandboxToolPathOptions): string {\n return ['set -eu', `mkdir -p ${shellSingleQuote(sandboxToolBinDir(options))}`].join('\\n')\n}\n\n/** Build a shell script that creates the sandbox tool binary directory.\n *\n * @deprecated Renamed to {@link buildSandboxToolBinDirScript}, and the script\n * no longer appends the bin dir to PATH in `~/.profile`, `~/.bashrc` and\n * `~/.zshrc`. Those edits never reached the contexts that run a tool: an exec\n * and a spawned CLI read no rc file, and the SSH shell assigns PATH\n * absolutely, which discards an appended entry. Put the directory on PATH with\n * {@link buildSandboxToolBinDirsEnv} instead. This name forwards to the new\n * one so an existing import keeps resolving; removal is a major.\n */\nexport function buildSandboxToolPathSetupScript(options: SandboxToolPathOptions): string {\n return buildSandboxToolBinDirScript(options)\n}\n\n/**\n * Create the sandbox tool binary directory in a running box.\n * {@link buildSandboxToolBinDirsEnv}, not this call, puts it on a sandbox PATH.\n */\nexport async function ensureSandboxToolBinDir(\n box: SandboxInstance,\n options: SandboxToolPathOptions,\n): Promise<Outcome<void>> {\n try {\n const res = await box.exec(buildSandboxToolBinDirScript(options))\n if (res.exitCode !== 0) {\n return fail(\n new Error(\n `ensureSandboxToolBinDir: failed to create the tool bin dir ${sandboxToolBinDir(options)} ` +\n `(exit ${res.exitCode}): ${res.stderr.slice(0, 500)}`,\n ),\n )\n }\n return ok(undefined)\n } catch (err) {\n return fail(new Error('ensureSandboxToolBinDir: exec failed', { cause: err }))\n }\n}\n\n/** Create the sandbox tool binary directory in a running box.\n *\n * @deprecated Renamed to {@link ensureSandboxToolBinDir}, and the call no\n * longer appends the bin dir to PATH in `~/.profile`, `~/.bashrc` and\n * `~/.zshrc`. Those edits never reached the contexts that run a tool: an exec\n * and a spawned CLI read no rc file, and the SSH shell assigns PATH\n * absolutely, which discards an appended entry. Put the directory on PATH with\n * {@link buildSandboxToolBinDirsEnv} instead. This name forwards to the new\n * one so an existing import keeps resolving; removal is a major.\n */\nexport async function runSandboxToolPathSetup(\n box: SandboxInstance,\n options: SandboxToolPathOptions,\n): Promise<Outcome<void>> {\n return ensureSandboxToolBinDir(box, options)\n}\n","import { Sandbox } from '@tangle-network/sandbox/core'\nimport { type Outcome, ok, fail } from './outcome'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { forgetBox, getClientFromCreds } from './runtime-cache'\nimport type { SandboxRuntimeConfig, SandboxScope } from './configuration'\n\nexport async function listRunning(\n client: Sandbox,\n name: string,\n): Promise<Outcome<SandboxInstance | null>> {\n try {\n const running = await client.list({ status: 'running' })\n return ok(running.find((s) => s.name === name) ?? null)\n } catch (err) {\n return fail(err)\n }\n}\n\n/**\n * The running box this isolate last used under `name`, read by id. Null when it\n * is gone, stopped, renamed, or answers without the metadata a reuse decides on;\n * the caller then lists, which is the authority.\n */\nexport async function getRunningBox(\n client: Sandbox,\n id: string,\n name: string,\n): Promise<SandboxInstance | null> {\n try {\n const box = await client.get(id)\n if (!box || box.name !== name || box.status !== 'running') return null\n if (typeof box.metadata?.harness !== 'string') return null\n return box\n } catch {\n return null\n }\n}\n\nexport async function listStopped(\n client: Sandbox,\n name: string,\n): Promise<Outcome<SandboxInstance | null>> {\n try {\n const stopped = await client.list({ status: 'stopped' })\n return ok(stopped.find((s) => s.name === name) ?? null)\n } catch (err) {\n return fail(err)\n }\n}\n\nexport async function deleteBox(box: SandboxInstance): Promise<Outcome<void>> {\n try {\n const acknowledgement = await box.delete({ until: 'removed' })\n forgetBox(box.id)\n // Creation reuses this box's name as its idempotency key.\n if (acknowledgement.removal === 'pending') {\n return fail(new Error(`sandbox ${box.id} removal is still pending; retry replacement after removal completes`))\n }\n return ok(undefined)\n } catch (err) {\n return fail(err)\n }\n}\n\n/** Scope + the client and box key every workspace-scoped sandbox call needs.\n * One place resolves credentials and derives the box name, so the ensure and\n * peek paths cannot drift on which key a workspace's box lives under. */\nexport async function resolveWorkspaceSandboxClient(\n shell: SandboxRuntimeConfig,\n workspaceId: string,\n userId: string | undefined,\n signal?: AbortSignal,\n): Promise<{ scope: SandboxScope; client: Sandbox; name: string }> {\n const scope: SandboxScope = { workspaceId, ...(userId ? { userId } : {}) }\n const creds = await shell.credentials(scope)\n signal?.throwIfAborted()\n if (!creds) throw new Error('sandbox credentials are required (apiKey/baseUrl)')\n return {\n scope,\n client: getClientFromCreds(creds, signal),\n name: shell.boxKey ? shell.boxKey(scope) : shell.name(workspaceId),\n }\n}\n\n/** What a peek can find. `warming` means the control plane is running while\n * the filesystem incarnation is still transitioning. `not-running` carries\n * the platform's own state string (`stopped`, `starting`, `failed`, …) —\n * narrowing it to a union here would drop states the platform adds later,\n * and every caller wants it for a log. */\nexport type PeekWorkspaceSandboxOutcome =\n | { status: 'running'; box: SandboxInstance }\n | { status: 'warming'; readiness: 'transitioning'; box: SandboxInstance }\n | { status: 'not-running'; state: string; box: SandboxInstance }\n | { status: 'absent' }\n\n/**\n * Read-only twin of {@link ensureWorkspaceSandbox}: report whether a\n * workspace's box exists and is fully ready, WITHOUT provisioning, resuming,\n * or bootstrapping anything.\n *\n * This is what a read-mostly path needs — a file-index route's `authorize`\n * seam, a stale-lock reconciliation, a status badge. Calling `ensure` from one\n * of those spins a box up as a side effect of a read (legal-agent #509), and\n * costs the caller a cold start it never asked for.\n *\n * Matching is on BOTH the box key and the display name, IN THAT ORDER.\n * `client.get(id)` is a direct read by the platform's opaque sandbox id, not by\n * the deterministic key a product derives from a workspace, so a lookup that\n * has not seen the box before has to list and match (`ensureWorkspaceSandbox`\n * reads a box it has seen by id).\n * Provisioning here always stamps `name` with the box key, so the key is the\n * authoritative match; the display-name pass exists only to adopt boxes on a\n * host that predates that convention. The order matters: a single unordered\n * `find` returns whichever the platform happens to list first, so a stopped\n * display-name box could shadow a running box-key one and report\n * `not-running` for a live workspace.\n *\n * Unlike `ensure`, this lists ALL statuses in one call: distinguishing \"no box\"\n * from \"box is stopped\" is the whole point, and a status-filtered list cannot.\n *\n * A `client.list()` rejection propagates RAW, unlike the `Outcome`-wrapping\n * helpers `ensure` uses internally. That is deliberate: there is no honest\n * outcome to map a listing failure onto — it is not `absent` and not\n * `not-running`, and inventing one would have callers act on a status the\n * platform never reported. Callers that must tolerate it say so explicitly\n * (the stale-turn-lock policy documents \"a throw is treated as unreachable\").\n */\nexport async function peekWorkspaceSandbox(\n shell: SandboxRuntimeConfig,\n options: { workspaceId: string; userId?: string; signal?: AbortSignal },\n): Promise<PeekWorkspaceSandboxOutcome> {\n options.signal?.throwIfAborted()\n const { client, name } = await resolveWorkspaceSandboxClient(shell, options.workspaceId, options.userId, options.signal)\n const displayName = shell.name(options.workspaceId)\n const boxes = await client.list()\n const match = boxes.find((box) => box.name === name) ?? boxes.find((box) => box.name === displayName)\n if (!match) return { status: 'absent' }\n if (match.status !== 'running') return { status: 'not-running', state: match.status, box: match }\n if (match.filesystemIncarnationReadiness === 'transitioning') {\n return { status: 'warming', readiness: 'transitioning', box: match }\n }\n if (match.filesystemIncarnationReadiness !== 'ready') {\n throw new Error(`sandbox ${match.id} is running without filesystem incarnation readiness`)\n }\n return { status: 'running', box: match }\n}\n","import type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { HolderBoxReport } from '../turn-stream/adapters'\n\n/** The cap on reading a held lock's box: the read runs inside a member's request. */\nexport const HOLDER_BOX_READ_TIMEOUT_MS = 5_000\n\n/**\n * Read the box a held lock's turn ran work on, for `reconcileTurnLockFromStoreAndBox`. Live work is the sidecar's own\n * verdict (`hasActiveExecution`, computed against its execution tracker, kept by the SDK in `info.raw`): a finished\n * session can keep a stale `activeExecutionId`, and the SDK reads a session without a status as running. The id counts\n * only when an older sidecar sends no verdict, and that fallback is logged. `find` must never provision or resume a box;\n * a box that is absent or not running runs nothing. No answer within the cap is `timeout`, a failed read is\n * `unreachable` (logged with its class), and the policy then applies its own bound instead of the lock's TTL.\n */\nexport async function readHolderBoxSessions(\n find: () => Promise<Pick<SandboxInstance, 'status' | 'sessions'> | null | undefined>,\n): Promise<HolderBoxReport> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const read = (async () => {\n const box = await find()\n if (!box || box.status !== 'running') return { live: 0, sessions: 0 }\n const sessions = await box.sessions()\n let unjudged = 0\n const live = sessions.filter(({ info }) => {\n const verdict = (info as { raw?: { hasActiveExecution?: unknown } }).raw?.hasActiveExecution\n if (typeof verdict === 'boolean') return verdict\n unjudged += 1\n return !!info.activeExecutionId\n })\n if (unjudged > 0) {\n console.warn('[turn-lock] holder box sessions carry no execution verdict; counting their active execution id', {\n class: 'sidecar_verdict_absent', sessions: unjudged })\n }\n return { live: live.length, sessions: sessions.length }\n })()\n try {\n return await Promise.race([read, new Promise<'timeout'>((resolve) => { timer = setTimeout(() => resolve('timeout'), HOLDER_BOX_READ_TIMEOUT_MS) })])\n } catch (error) {\n console.warn('[turn-lock] holder box read failed', { class: 'box_unreachable', error: error instanceof Error ? error.name : 'unknown' })\n return 'unreachable'\n } finally {\n clearTimeout(timer)\n }\n}\n","import { Sandbox } from '@tangle-network/sandbox/core'\nimport {\n type StoppedSandboxResumeFailure,\n type StoppedSandboxResumeRecovery,\n type SandboxRuntimeConfig,\n type MissingSandboxFailure,\n type EnsureWorkspaceSandboxOptions,\n type SandboxRestoreSpec,\n DEFAULT_SANDBOX_RESOURCES,\n type SandboxBuildContext,\n} from './configuration'\nimport { type Outcome, ok } from './outcome'\nimport { SandboxRecoveryFailedError } from './lifecycle-errors'\nimport { serializeSandboxProvisioningError, isSandboxApiSandboxMissingFailure } from './diagnostics'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { parseBackendType } from '@tangle-network/sandbox'\nimport { resolveWorkspaceSandboxClient, getRunningBox, listRunning, listStopped, deleteBox } from './workspace-boxes'\nimport {\n DEFAULT_PROVISION_TIMEOUT_MS,\n assertEnvWithinLimits,\n SHELL_PROMPT_BUDGET_HINT,\n assertProvisionPayloadWithinCap,\n} from './payload-limits'\nimport { runningBoxIds, forgetBox, trustedBoxes, rememberRunningBox } from './runtime-cache'\nimport { resolveWorkspaceRuntimeEnv, prefetchExistingBoxReads, finalizeExistingBox, bootstrapBox } from './existing-box'\nimport { refreshRuntimeConnection } from './runtime-connection'\nimport { isReusableBox, recoverUnresponsiveBox, resumeStoppedBox } from './box-health'\nimport { splitDeferredProfileFiles, writeProfileFilesToBox } from './profile-files'\nimport type { AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport { requireTransportableModel, resolveModelSelection, backendModelFields } from './model'\nimport { DEFERRED_CORPUS_HASH_KEY, deferredCorpusHash, deferredProfileWriteFailed } from './profile-corpus'\nimport { assertProfilePromptWithinBudget } from '../profile/budget'\n\n// The SDK narrows `backend.type` to its own BackendType union and\n// `initialUsers[].role` to PermissionLevel — neither symbol is exported. The\n// create payload is assembled with the product's Harness/role strings, which\n// are a superset surface; the localized cast at the boundary is the only place\n// this widening is allowed, and the runtime contract (the sidecar boots the\n// named harness) is what enforces correctness.\ntype CreatePayload = Parameters<Sandbox['create']>[0]\n\nasync function requestSandboxReplacement<TFailure extends StoppedSandboxResumeFailure>(\n recover: ((failure: TFailure) => Promise<Outcome<StoppedSandboxResumeRecovery | null>>) | undefined,\n failure: TFailure,\n label: string,\n): Promise<StoppedSandboxResumeRecovery> {\n if (!recover) throw failure.error\n const recovery = await recover(failure)\n if (!recovery.succeeded) throw recovery.error\n if (!recovery.value) throw failure.error\n\n const replacementBoxKey = recovery.value.replacementBoxKey.trim()\n if (!replacementBoxKey || replacementBoxKey === failure.boxKey) {\n throw new Error(\n `${label} must return a fresh replacement box key for ${failure.boxKey}`,\n { cause: failure.error },\n )\n }\n return { ...recovery.value, replacementBoxKey }\n}\n\nasync function requestMissingSandboxReplacement(\n shell: SandboxRuntimeConfig,\n failure: MissingSandboxFailure,\n): Promise<StoppedSandboxResumeRecovery> {\n // Probe causes diagnose failed liveness; they do not authorize replacement.\n if (failure.error instanceof SandboxRecoveryFailedError && failure.error.phase === 'probe') {\n throw failure.error\n }\n const diagnostics = serializeSandboxProvisioningError(failure.error)\n if (!isSandboxApiSandboxMissingFailure(diagnostics)) throw failure.error\n return requestSandboxReplacement(\n shell.recoverMissingSandbox,\n failure,\n 'missing sandbox recovery',\n )\n}\n\n/**\n * `reuseOnly` stops before any step that creates, resumes, restarts, replaces or\n * deletes a box and returns undefined there; every other step is a read or the\n * idempotent renewal a reuse always made. `gate` is the spend gate: it runs\n * before the first such step, and before a reuse whose probe was not trusted.\n */\nexport async function provisionWorkspaceSandbox(\n shell: SandboxRuntimeConfig,\n options: EnsureWorkspaceSandboxOptions,\n gate: () => Promise<void>,\n reuseOnly: boolean,\n): Promise<SandboxInstance | undefined> {\n const execTimeoutMs = shell.livenessProbe?.execTimeoutMs\n // Match the supported SDK command-timeout range before any lifecycle mutation.\n if (execTimeoutMs !== undefined && (\n !Number.isInteger(execTimeoutMs) || execTimeoutMs < 100 || execTimeoutMs > 600_000\n )) {\n throw new Error('livenessProbe.execTimeoutMs must be an integer between 100 and 600000')\n }\n const { workspaceId, userId, harness, forceNew, onProgress, billingOwnerId, signal } = options\n const measure = async <T>(stage: string, operation: () => Promise<T>): Promise<T> => {\n signal?.throwIfAborted()\n const result = await (options.measure ? options.measure(`sandbox.ensure.${stage}`, operation) : operation())\n signal?.throwIfAborted()\n return result\n }\n const resolved = await measure('credentials', () => resolveWorkspaceSandboxClient(shell, workspaceId, userId, signal))\n const { scope, client } = resolved\n let name = resolved.name\n let recoveryRestore: SandboxRestoreSpec | null | undefined\n let replacementRequested = false\n const resources = shell.resources ?? DEFAULT_SANDBOX_RESOURCES\n const resumeTimeout = shell.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS\n\n // Stage 1 — running-box reuse (skipped on forceNew). The box this isolate used\n // last is read by id; only when that misses is every running box listed.\n let existing: Outcome<SandboxInstance | null> = ok(null)\n const knownId = forceNew ? undefined : runningBoxIds.get(name)\n if (knownId) {\n const known = await measure('get_running', () => getRunningBox(client, knownId, name))\n if (known) {\n existing = ok(known)\n } else {\n runningBoxIds.delete(name)\n forgetBox(knownId)\n }\n }\n if (reuseOnly && !(existing.succeeded && existing.value)) return undefined\n if (!(existing.succeeded && existing.value)) {\n existing = await measure('list_running', () => listRunning(client, name))\n }\n if (forceNew && existing.succeeded && !existing.value) {\n existing = await listStopped(client, name)\n }\n if (forceNew && !existing.succeeded) throw existing.error\n if (existing.succeeded && existing.value) {\n const found = existing.value\n if (forceNew) {\n const dropped = await deleteBox(found)\n if (!dropped.succeeded) {\n throw new Error(`forceNew: sandbox ${name} could not be deleted`, { cause: dropped.error })\n }\n } else if (found.metadata?.harness === harness) {\n // Resolve app credentials before any restart so a mint failure leaves the\n // existing sandbox running and intact. Reading the runtime connection\n // restarts nothing, so it runs alongside the mint.\n const runtimeEnvMint = measure('runtime_env', () => resolveWorkspaceRuntimeEnv(shell, scope))\n const prefetch = prefetchExistingBoxReads(shell, found, runtimeEnvMint, measure)\n const [envResult, readyResult] = await Promise.allSettled([\n runtimeEnvMint,\n measure('refresh', () => refreshRuntimeConnection(client, found)),\n ])\n if (envResult.status === 'rejected') throw envResult.reason\n await prefetch.decided\n const runtimeEnv = envResult.value\n // A refusal from the spend gate is the caller's answer, not a box fault to recover from.\n const refusal: { error?: unknown; refused: boolean } = { refused: false }\n const gateBeforeUse = async (): Promise<void> => {\n try {\n await gate()\n } catch (error) {\n refusal.refused = true\n refusal.error = error\n throw error\n }\n }\n try {\n if (readyResult.status === 'rejected') throw readyResult.reason\n const ready = readyResult.value\n if ((await measure('liveness', () => isReusableBox(ready, shell.livenessProbe, resumeTimeout))).succeeded) {\n if (!trustedBoxes.has(ready)) await gateBeforeUse()\n const finalBox = await measure('finalize', () => finalizeExistingBox(shell, client, ready, 'reused', name, workspaceId, userId, harness, scope, runtimeEnv, prefetch))\n if (trustedBoxes.has(ready)) trustedBoxes.add(finalBox)\n return rememberRunningBox(name, finalBox)\n }\n if (reuseOnly) return undefined\n await gateBeforeUse()\n // The prefetched reads never reject; a recovered box is read again in finalize.\n // Unresponsive (or never-connectable) box with the RIGHT harness: recover\n // in place — stop→resume preserves the workspace — and fail loud if the\n // box is still dead. Deleting here wiped user workspaces (#299); delete\n // is reachable only via forceNew now.\n const recovered = await recoverUnresponsiveBox(\n client,\n ready,\n shell.livenessProbe,\n 'reused',\n name,\n resumeTimeout,\n runtimeEnv,\n onProgress,\n )\n return rememberRunningBox(name, await finalizeExistingBox(shell, client, recovered, 'reused', name, workspaceId, userId, harness, scope, runtimeEnv))\n } catch (cause) {\n signal?.throwIfAborted()\n if (refusal.refused) throw refusal.error\n if (reuseOnly) return undefined\n const error = cause instanceof Error ? cause : new Error(String(cause))\n const recovery = await requestMissingSandboxReplacement(shell, {\n box: found,\n error,\n scope,\n boxKey: name,\n stage: 'reused',\n })\n name = recovery.replacementBoxKey\n recoveryRestore = recovery.restore\n replacementRequested = true\n }\n } else {\n if (reuseOnly) return undefined\n await gate()\n const dropped = await deleteBox(found)\n if (!dropped.succeeded) {\n throw new Error(\n `sandbox ${name} ` +\n `(was ${String(found.metadata?.harness ?? 'unknown')}, want ${harness}) ` +\n `could not be deleted`,\n { cause: dropped.error },\n )\n }\n }\n }\n\n // Stage 2 — stopped-box resume (skipped on forceNew or resumeStopped===false).\n if (reuseOnly) return undefined\n await gate()\n signal?.throwIfAborted()\n if (!replacementRequested && !forceNew && shell.resumeStopped !== false) {\n const stopped = await measure('list_stopped', () => listStopped(client, name))\n if (!stopped.succeeded) throw stopped.error\n if (stopped.value) {\n const stoppedBox = stopped.value\n const runtimeEnv = await measure('runtime_env', () => resolveWorkspaceRuntimeEnv(shell, scope))\n const resumed = await measure('resume', () => resumeStoppedBox(stoppedBox, resumeTimeout, runtimeEnv, onProgress))\n if (!resumed.succeeded) {\n signal?.throwIfAborted()\n const recovery = await requestSandboxReplacement(\n shell.recoverStoppedSandbox,\n { box: stopped.value, error: resumed.error, scope, boxKey: name },\n 'stopped sandbox recovery',\n )\n name = recovery.replacementBoxKey\n recoveryRestore = recovery.restore\n } else {\n try {\n const box = await refreshRuntimeConnection(client, resumed.value)\n if ((await isReusableBox(box, shell.livenessProbe, resumeTimeout)).succeeded) {\n return rememberRunningBox(name, await finalizeExistingBox(shell, client, box, 'resumed', name, workspaceId, userId, harness, scope, runtimeEnv))\n }\n // The box resumed but is unresponsive: one full stop→resume cycle is\n // the state-preserving recovery; still-dead fails loud. Never delete —\n // that wipes the workspace (#299).\n const recovered = await recoverUnresponsiveBox(\n client,\n box,\n shell.livenessProbe,\n 'resumed',\n name,\n resumeTimeout,\n runtimeEnv,\n onProgress,\n )\n return rememberRunningBox(name, await finalizeExistingBox(shell, client, recovered, 'resumed', name, workspaceId, userId, harness, scope, runtimeEnv))\n } catch (cause) {\n signal?.throwIfAborted()\n const error = cause instanceof Error ? cause : new Error(String(cause))\n const recovery = await requestMissingSandboxReplacement(shell, {\n box: stopped.value,\n error,\n scope,\n boxKey: name,\n stage: 'resumed',\n })\n name = recovery.replacementBoxKey\n recoveryRestore = recovery.restore\n }\n }\n }\n }\n\n // Stage 3 — create fresh.\n signal?.throwIfAborted()\n const { payload, deferredFiles } = await measure('payload', () => prepareWorkspacePayload(shell, workspaceId, userId, scope, harness, name, recoveryRestore, resources, billingOwnerId, signal))\n\n // The client signal aborts each request; the create's own signal also ends\n // its Retry-After pacing between POSTs, so a canceled caller sends no later create.\n let box = await measure('create', () => signal ? client.create(payload, { signal }) : client.create(payload))\n\n await measure('wait_running', () => box.waitFor('running', {\n timeoutMs: shell.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS,\n ...(signal ? { signal } : {}),\n ...(onProgress ? { onProgress } : {}),\n }))\n box = await measure('refresh_connection', () => refreshRuntimeConnection(client, box))\n\n if (deferredFiles.length > 0) {\n const written = await writeProfileFilesToBox(box, deferredFiles)\n if (!written.succeeded) {\n throw deferredProfileWriteFailed('new', name, written.error)\n }\n }\n\n if (shell.bootstrap) await measure('bootstrap', () => bootstrapBox(shell, box, scope, harness, 'new', name, true))\n return rememberRunningBox(name, box)\n}\n\nasync function prepareWorkspacePayload(\n shell: SandboxRuntimeConfig,\n workspaceId: EnsureWorkspaceSandboxOptions['workspaceId'],\n userId: EnsureWorkspaceSandboxOptions['userId'],\n scope: Parameters<typeof resolveWorkspaceRuntimeEnv>[1],\n harness: EnsureWorkspaceSandboxOptions['harness'],\n name: string,\n recoveryRestore: SandboxRestoreSpec | null | undefined,\n resources: NonNullable<SandboxRuntimeConfig['resources']>,\n billingOwnerId: EnsureWorkspaceSandboxOptions['billingOwnerId'],\n signal?: AbortSignal,\n) {\n signal?.throwIfAborted()\n const connectedIntegrationIds = await shell.connectedIntegrationIds(workspaceId)\n signal?.throwIfAborted()\n const buildCtx: SandboxBuildContext = {\n workspaceId,\n connectedIntegrationIds,\n ...(userId ? { userId } : {}),\n }\n const [secrets, creationEnv, runtimeEnv, files] = await Promise.all([\n shell.secrets(workspaceId),\n shell.env(buildCtx),\n resolveWorkspaceRuntimeEnv(shell, scope),\n shell.files(buildCtx),\n ])\n signal?.throwIfAborted()\n const env = { ...creationEnv, ...runtimeEnv }\n const fullProfile = shell.profile({ extraFiles: files, harness })\n // When deferring, strip inline files from the create payload and write them\n // into the box after it reaches running. Keeps the provision body under the\n // orchestrator's 256 KiB cap and lands real files on disk.\n const { leanProfile, deferredFiles } = shell.deferProfileFiles\n ? splitDeferredProfileFiles(fullProfile)\n : { leanProfile: fullProfile, deferredFiles: [] as AgentProfileFileMount[] }\n const profile = leanProfile\n\n const role = userId && shell.permissionRole ? shell.permissionRole('developer') : undefined\n\n // Bake the model at create when opted in. childKeyMint overrides the apiKey\n // per-workspace; a typed mint failure falls through to the parent key (logged).\n let model = shell.backendModelAtCreate\n ? requireTransportableModel(resolveModelSelection(shell.provider), `backendModelAtCreate for ${name}`)\n : undefined\n if (model && shell.childKeyMint && model.provider === 'openai-compat') {\n const minted = await shell.childKeyMint(scope)\n signal?.throwIfAborted()\n if (minted.succeeded) model = { ...model, apiKey: minted.value }\n else {\n console.error(\n `[sandbox] childKeyMint failed for ${workspaceId}; using parent key:`,\n minted.error.message,\n )\n }\n }\n\n const storage = shell.storage?.(buildCtx)\n const restore = recoveryRestore === undefined ? await shell.restore?.(buildCtx) : recoveryRestore\n signal?.throwIfAborted()\n\n const payload = {\n name,\n image: resources.image,\n // Stamp the deferred-corpus hash so a later REUSE can skip re-writing an\n // unchanged skill corpus (materializeDeferredFilesForExistingBox reads it).\n metadata: {\n ...shell.metadata(harness),\n ...(deferredFiles.length > 0 ? { [DEFERRED_CORPUS_HASH_KEY]: deferredCorpusHash(deferredFiles) } : {}),\n },\n idempotencyKey: name,\n // Passed through untyped (the SDK payload type predates it); the platform\n // authz-gates it server-side and ignores it when unsupported.\n ...(billingOwnerId ? { billingOwnerId } : {}),\n ...(userId ? { permissions: { initialUsers: [{ userId, role }] } } : {}),\n env,\n secrets,\n // Fail fast for historical-only harness identities (`forge`) here too,\n // matching resolveSandboxPromptBackend's dispatch seam.\n backend: { type: parseBackendType(harness), profile, ...(model ? backendModelFields(model) : {}) },\n ...(storage ? { storage } : {}),\n ...(restore ? restore : {}),\n ...(shell.egressPolicy ? { egressPolicy: shell.egressPolicy } : {}),\n ...(shell.cwd !== undefined ? { cwd: shell.cwd } : {}),\n ...(shell.webTerminalEnabled ? { webTerminalEnabled: true } : {}),\n maxLifetimeSeconds: resources.maxLifetimeSeconds,\n idleTimeoutSeconds: resources.idleTimeoutSeconds,\n resources: {\n cpuCores: resources.cpuCores,\n memoryMB: resources.memoryMB,\n diskGB: resources.diskGB,\n ...(resources.advisory !== undefined ? { advisory: resources.advisory } : {}),\n },\n } as CreatePayload\n\n // S-cost gates: an oversized env entry (E2BIG class), an over-cap provision\n // body, or a system prompt past the degradation cliff — fail loud here,\n // before the POST, with the offending section named. The prompt gate is\n // separate from the payload gate on purpose: the 122,659-byte prompt that\n // produced empty answers is a THIRD of the 240 KB payload cap, so the\n // payload gate never sees it.\n assertEnvWithinLimits(env)\n assertProfilePromptWithinBudget(\n profile,\n shell.promptBudget ?? {},\n `provision profile systemPrompt for ${name}`,\n SHELL_PROMPT_BUDGET_HINT,\n )\n // `?? {}` only narrows the SDK parameter's `| undefined`; the literal above\n // is always defined. The structural sections type needs no cast.\n assertProvisionPayloadWithinCap(payload ?? {})\n return { payload, deferredFiles }\n}\n","import type { SandboxInstance, ProvisionEvent } from '@tangle-network/sandbox'\nimport type { LivenessProbeConfig } from './configuration'\nimport { type Outcome, ok, fail } from './outcome'\nimport { isRecent, checksFor, TRUSTED_REUSE_TTL_MS, forgetBox, trustedBoxes, recordCheck } from './runtime-cache'\nimport { sandboxEdgeFailed, sandboxRuntimeUrl, refreshRuntimeConnection } from './runtime-connection'\nimport { SANDBOX_BACKING_CONTAINER_MISSING_CODE, isLegacySandboxBackingContainerMissingMessage } from './diagnostics'\nimport { Sandbox } from '@tangle-network/sandbox/core'\nimport { type SandboxExistingBoxStage, SandboxBoxBusyError, SandboxRecoveryFailedError } from './lifecycle-errors'\nimport { plannedHostRestart, readDuringPlannedHostRestart } from './transient-failure'\n\n// The SDK owns the exec deadline. Await settlement before starting recovery;\n// an application timeout race would leave the original request in flight.\nasync function isBoxAlive(\n box: SandboxInstance,\n probe: LivenessProbeConfig | undefined,\n deadline: number,\n): Promise<Outcome<void>> {\n if (!probe) return ok(undefined)\n try {\n const { value: alive } = await readDuringPlannedHostRestart(\n () => box.exec('echo alive', { timeoutMs: probe.execTimeoutMs ?? 5000 }),\n deadline,\n )\n if (alive.exitCode !== 0 || alive.stdout.trim() !== 'alive') {\n return fail(new Error('alive check did not return a successful alive marker'))\n }\n return ok(undefined)\n } catch (cause) {\n if (plannedHostRestart(cause)) throw cause\n return fail(new Error('alive check failed', { cause }))\n }\n}\n\nfunction hasRecentLivenessVerification(\n box: SandboxInstance,\n probe: LivenessProbeConfig,\n now = Date.now(),\n): boolean {\n return isRecent(checksFor(box)?.alive, probe.cacheTtlMs ?? TRUSTED_REUSE_TTL_MS, now)\n}\n\n// Decide whether an existing (reused or resumed) box is safe to hand back.\n// `refreshRuntimeConnection` has already polled for the runtime URL, so a box\n// that still has none never became connectable and must not be silently\n// reused — downstream exec/terminal traffic would fail against it. A failed\n// edge is likewise unusable. Only when the connection is present do we spend\n// an exec round-trip on the liveness probe. A box that fails this gate is\n// RECOVERED (stop→resume, workspace intact) or fails loud — never deleted.\nexport async function isReusableBox(\n box: SandboxInstance,\n probe: LivenessProbeConfig | undefined,\n restartTimeoutMs = probe?.execTimeoutMs ?? 5000,\n): Promise<Outcome<void>> {\n if (sandboxEdgeFailed(box) || !sandboxRuntimeUrl(box)) {\n forgetBox(box.id)\n return fail(new Error(sandboxEdgeFailed(box) ? 'runtime edge readiness failed' : 'runtime URL is missing'))\n }\n if (!probe) return ok(undefined)\n if (hasRecentLivenessVerification(box, probe)) {\n trustedBoxes.add(box)\n return ok(undefined)\n }\n const alive = await isBoxAlive(box, probe, Date.now() + restartTimeoutMs)\n if (alive.succeeded) recordCheck(box, { alive: Date.now() })\n else forgetBox(box.id)\n return alive\n}\n\n// Resume a stopped box and wait for it to reach running.\nfunction stoppedBoxResumeError(box: SandboxInstance, cause: unknown): unknown {\n const error = cause instanceof Error ? cause : new Error(String(cause))\n const code = (error as { code?: unknown }).code\n if (code === SANDBOX_BACKING_CONTAINER_MISSING_CODE) return cause\n if (code !== undefined && code !== 'SERVER_ERROR') return cause\n if (!isLegacySandboxBackingContainerMissingMessage(error.message)) return cause\n\n const status = typeof cause === 'object' && cause !== null\n ? (cause as { status?: unknown }).status\n : undefined\n if (typeof status !== 'number' && typeof status !== 'string') return cause\n const wrapped = new Error(error.message, { cause: error })\n wrapped.name = error.name\n\n return Object.assign(wrapped, {\n status,\n origin: 'sandbox-api',\n endpoint: `/v1/sandboxes/${encodeURIComponent(box.id)}/resume`,\n ...(typeof code === 'number' || typeof code === 'string' ? { code } : {}),\n })\n}\n\nexport async function resumeStoppedBox(\n box: SandboxInstance,\n timeoutMs: number,\n runtimeEnv: Record<string, string>,\n onProgress?: (event: ProvisionEvent) => void,\n): Promise<Outcome<SandboxInstance>> {\n // A resume is the lifecycle step callers label a turn by, and the waits\n // below report no progress for a stopped box, so report it here.\n const report = (status: ProvisionEvent['status'], message: string) => {\n try {\n onProgress?.({ step: 'container-start', status, message, timestamp: new Date().toISOString() })\n } catch {\n // A progress observer cannot interfere with the resume.\n }\n }\n try {\n forgetBox(box.id)\n report('started', 'Resuming the stopped sandbox')\n await resumeWithRequiredRuntimeEnv(box, timeoutMs, runtimeEnv)\n await box.waitFor('running', { timeoutMs, ...(onProgress ? { onProgress } : {}) })\n report('completed', 'The stopped sandbox is running again')\n return ok(box)\n } catch (cause) {\n report('error', 'The stopped sandbox could not be resumed')\n return fail(stoppedBoxResumeError(box, cause))\n }\n}\n\n// Sandbox resume takes `env` only for public keys whose values the platform\n// withholds at rest, and uses them only to rebuild a removed runtime; any\n// other key is refused (400 RESUME_ENV_KEY_NOT_ACCEPTED). A rebuild that lacks\n// values names them (409 RESUME_ENV_REQUIRED, `missingEnvKeys`). So resume\n// without env and supply exactly the named keys from the fresh runtime env.\n// finalizeExistingBox then delivers every fresh value through setRuntimeEnv.\nasync function resumeWithRequiredRuntimeEnv(\n box: SandboxInstance,\n timeoutMs: number,\n runtimeEnv: Record<string, string>,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs\n try {\n await box.resume({ timeoutMs })\n } catch (cause) {\n const missingEnvKeys = resumeEnvRequiredKeys(cause)\n if (!missingEnvKeys?.length || missingEnvKeys.some((key) => runtimeEnv[key] === undefined)) throw cause\n await box.resume({\n timeoutMs: Math.max(1, deadline - Date.now()),\n env: Object.fromEntries(missingEnvKeys.map((key) => [key, runtimeEnv[key]!])),\n })\n }\n}\n\n// Matched by code so SDK versions without ResumeEnvRequiredError still load.\nfunction resumeEnvRequiredKeys(cause: unknown): string[] | undefined {\n if (typeof cause !== 'object' || cause === null) return undefined\n const { code, missingEnvKeys } = cause as { code?: unknown; missingEnvKeys?: unknown }\n if (code !== 'RESUME_ENV_REQUIRED' || !Array.isArray(missingEnvKeys)) return undefined\n return missingEnvKeys.filter((key): key is string => typeof key === 'string')\n}\n\n// How many sessions a stop would end, from the runtime's own session list, or\n// undefined when the runtime does not answer. Listing sessions spawns nothing,\n// so a busy box answers it when it misses the exec probe. A session counts as\n// running on the same evidence the SDK uses to refuse a second dispatch:\n// running, an active execution, or queued with an admitted execution. The SDK\n// owns the request deadline; settlement is awaited so no stop is issued while\n// the answer is still in flight.\nasync function runningSessionCount(box: SandboxInstance, deadline: number): Promise<{ running?: number; waited: boolean }> {\n try {\n const { value: sessions, waited } = await readDuringPlannedHostRestart(() => box.sessions(), deadline)\n return { waited, running: sessions.filter(({ info }) =>\n info.status === 'running' ||\n Boolean(info.activeExecutionId) ||\n (info.status === 'queued' && Boolean(info.latestExecutionId)),\n ).length }\n } catch (error) {\n if (plannedHostRestart(error)) throw error\n return { waited: false }\n }\n}\n\n// State-preserving recovery for a box that failed the reuse gate: stop (keeps\n// the workspace — the platform's suspend path never scrubs storage), resume,\n// then re-probe. `box.delete()` is DEPROVISIONING — it wipes the persistent\n// workspace (sessions, uncommitted files, everything outside the product's own\n// DB) — so it must never be a recovery action (#299: a single slow exec or a\n// crashed harness process used to destroy a user's workspace). This restarts\n// the container, which also reboots a dead sidecar/harness process. Every\n// failure throws SandboxRecoveryFailedError with the workspace intact —\n// including on the `tangle` driver, where stop is unsupported and the throw\n// carries the platform's rejection as its cause.\n//\n// The stop also ends every session on the box, so it is only issued when the\n// runtime reports no running session. A box that misses the probe while busy\n// (a loaded 2-core box can miss it while healthy, #934) is returned as is when\n// it is connectable, and otherwise fails only this request with\n// SandboxBoxBusyError. A runtime that cannot list its sessions gives no such\n// evidence, and the box is restarted as before.\nexport async function recoverUnresponsiveBox(\n client: Sandbox,\n box: SandboxInstance,\n probe: LivenessProbeConfig | undefined,\n stage: SandboxExistingBoxStage,\n name: string,\n resumeTimeout: number,\n runtimeEnv: Record<string, string>,\n onProgress?: (event: ProvisionEvent) => void,\n): Promise<SandboxInstance> {\n const deadline = Date.now() + resumeTimeout\n const { running, waited } = await runningSessionCount(box, deadline)\n // The missed probe preceded a planned swap, not a dead runtime. Observe\n // the same runtime again before deciding whether a restart is necessary.\n if (waited && (await isReusableBox(box, probe, Math.max(1, deadline - Date.now()))).succeeded) return box\n if (running) {\n if (sandboxRuntimeUrl(box) && !sandboxEdgeFailed(box)) return box\n throw new SandboxBoxBusyError(\n stage,\n name,\n running,\n sandboxEdgeFailed(box) ? 'runtime edge readiness failed' : 'runtime URL is missing',\n )\n }\n try {\n await box.stop()\n } catch (err) {\n throw new SandboxRecoveryFailedError(\n stage,\n name,\n 'stop',\n 'the platform could not stop the box for a state-preserving restart',\n err,\n )\n }\n const resumed = await resumeStoppedBox(box, resumeTimeout, runtimeEnv, onProgress)\n if (!resumed.succeeded) {\n throw new SandboxRecoveryFailedError(\n stage,\n name,\n 'resume',\n 'the box did not reach running after a state-preserving restart',\n resumed.error,\n )\n }\n const recovered = await refreshRuntimeConnection(client, resumed.value)\n const reusable = await isReusableBox(recovered, probe, resumeTimeout)\n if (!reusable.succeeded) {\n throw new SandboxRecoveryFailedError(\n stage,\n name,\n 'probe',\n `the box is still unresponsive after a state-preserving restart: ${reusable.error.message}`,\n reusable.error,\n )\n }\n return recovered\n}\n","import {\n type SandboxRuntimeConfig,\n type EnsureWorkspaceSandboxOptions,\n DEFAULT_SANDBOX_RESOURCES,\n} from './configuration'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { hydrateReuseState, hasRecentProbe, trustedBoxes, persistReuseState } from './runtime-cache'\nimport { provisionWorkspaceSandbox } from './workspace-provision'\nimport { SandboxRecoveryFailedError } from './lifecycle-errors'\nimport {\n serializeSandboxProvisioningError,\n isSandboxHostCapacityFailure,\n isSandboxBoxConfigFailure,\n} from './diagnostics'\n\n/** Reuse a workspace sandbox, or remove its previous runtime before provisioning a replacement. */\nexport async function ensureWorkspaceSandbox(\n shell: SandboxRuntimeConfig,\n options: EnsureWorkspaceSandboxOptions,\n): Promise<SandboxInstance> {\n const box = await claimWorkspaceSandbox(shell, options, false)\n if (!box) throw new Error('ensureWorkspaceSandbox: a claim that may provision returned no box')\n return box\n}\n\n/**\n * Reuse the workspace's running box if this isolate used it recently, or return\n * undefined. It never creates, resumes, restarts, replaces or deletes a box, so\n * a caller can run it without the provisioning lease that serializes those\n * steps (see `runForegroundSandboxSingleFlight`'s `reuse`); undefined means the\n * box needs one of them (or this isolate has no recent probe of it), and the\n * caller takes the lease and calls {@link ensureWorkspaceSandbox}.\n */\nexport async function reuseWorkspaceSandbox(\n shell: SandboxRuntimeConfig,\n options: EnsureWorkspaceSandboxOptions,\n): Promise<SandboxInstance | undefined> {\n options.signal?.throwIfAborted()\n if (options.forceNew) return undefined\n await hydrateReuseState(shell, options)\n options.signal?.throwIfAborted()\n if (!hasRecentProbe(shell, options)) return undefined\n return claimWorkspaceSandbox(shell, options, true)\n}\n\n/** The spend gate, run at most once per ensure and timed under the turn's trace when it has one. */\nfunction spendGate(options: EnsureWorkspaceSandboxOptions): () => Promise<void> {\n let gated: Promise<void> | undefined\n return () => {\n const before = options.spend?.beforeProvision\n if (!before) return Promise.resolve()\n const run = () => before({\n workspaceId: options.workspaceId,\n ...(options.userId ? { userId: options.userId } : {}),\n })\n return gated ??= Promise.resolve(options.trace\n ? options.trace.measure('sandbox.spend.before_provision', 'sandbox', run, undefined, options.traceParent)\n : run())\n }\n}\n\nasync function claimWorkspaceSandbox(\n shell: SandboxRuntimeConfig,\n options: EnsureWorkspaceSandboxOptions,\n reuseOnly: boolean,\n): Promise<SandboxInstance | undefined> {\n options.signal?.throwIfAborted()\n const { trace } = options\n // A budget refusal must land before any box is created, resumed or kept alive,\n // so it runs ahead of the first attempt and the unbringable-box replacement\n // below. A box this isolate probed recently has passed the gate in that\n // ensure; it is asked again when that probe expires, and before any lifecycle\n // step, so a reuse pays for it once per probe and not once per turn.\n const gate = spendGate(options)\n await hydrateReuseState(shell, options)\n options.signal?.throwIfAborted()\n if (!hasRecentProbe(shell, options)) await gate()\n const claim = trace?.start('sandbox.claim', 'sandbox', { 'workspace.harness': options.harness }, options.traceParent)\n // Each ensure step is a child of the claim, and the caller's own `measure` still sees it.\n const traced: EnsureWorkspaceSandboxOptions = trace && claim\n ? {\n ...options,\n measure: <T,>(stage: string, operation: () => Promise<T>): Promise<T> => {\n const run = () => trace.measure(stage, 'sandbox', () => operation(), undefined, claim)\n return options.measure ? options.measure(stage, run) : run()\n },\n }\n : options\n try {\n const box = await bringUpWorkspaceSandbox(shell, traced, gate, reuseOnly)\n options.signal?.throwIfAborted()\n if (!box) {\n claim?.end({ 'sandbox.reuse_declined': true })\n return undefined\n }\n claim?.end({ 'sandbox.id': box.id, ...(trustedBoxes.has(box) ? { 'sandbox.probe_trusted': true } : {}) })\n // A box handed out on a recent probe was observed by the ensure that probed it.\n if (!trustedBoxes.has(box)) await observeProvisionedBox(shell, options, box)\n options.signal?.throwIfAborted()\n await persistReuseState(shell, box)\n options.signal?.throwIfAborted()\n return box\n } catch (error) {\n claim?.end(undefined, error)\n throw error\n }\n}\n\n/**\n * Report a now-billable box to the spend seam.\n *\n * Awaited rather than fired and forgotten: an expectation ledger with holes\n * reports boxes it simply failed to record as `unknown-box`, and an alert that\n * cries wolf is worse than no alert. The cost is one local write on a path that\n * already makes at least one platform round trip, so it is not the term that\n * decides provisioning latency.\n *\n * Errors are swallowed — the box is up, and failing the caller because\n * bookkeeping failed would trade a real capability for a record of it.\n */\nasync function observeProvisionedBox(\n shell: SandboxRuntimeConfig,\n options: EnsureWorkspaceSandboxOptions,\n box: SandboxInstance,\n): Promise<void> {\n const onProvisioned = options.spend?.onProvisioned\n if (!onProvisioned) return\n const resources = shell.resources ?? DEFAULT_SANDBOX_RESOURCES\n const observe = async (): Promise<void> => {\n await onProvisioned({\n workspaceId: options.workspaceId,\n ...(options.userId ? { userId: options.userId } : {}),\n sandboxId: box.id,\n boxKey: box.name,\n idleTimeoutSeconds: resources.idleTimeoutSeconds,\n maxLifetimeSeconds: resources.maxLifetimeSeconds,\n at: Date.now(),\n })\n }\n try {\n await (options.trace\n ? options.trace.measure('sandbox.spend.observe', 'sandbox', observe, undefined, options.traceParent)\n : observe())\n } catch {\n // An observability seam must never take down the provision it reports on.\n }\n}\n\nasync function bringUpWorkspaceSandbox(\n shell: SandboxRuntimeConfig,\n options: EnsureWorkspaceSandboxOptions,\n gate: () => Promise<void>,\n reuseOnly: boolean,\n): Promise<SandboxInstance | undefined> {\n try {\n return await provisionWorkspaceSandbox(shell, options, gate, reuseOnly)\n } catch (err) {\n options.signal?.throwIfAborted()\n // A box the platform cannot bring up is not a transient failure: the box\n // key is derived from the workspace, so every later call resumes the same\n // dead box and fails the same way. Left alone the workspace never runs\n // again. Replacing it is a delete, so it happens only where the shell has\n // declared the box rebuildable — and only once, so a replacement that dies\n // the same way surfaces the error instead of looping.\n if (!shell.replaceUnbringableBox) throw err\n if (options.forceNew) throw err\n if (!isUnbringableBoxError(err)) throw err\n return await provisionWorkspaceSandbox(shell, { ...options, forceNew: true }, gate, reuseOnly)\n }\n}\n\n/**\n * True when the platform cannot bring this box up where it lives.\n *\n * Two shapes reach here. `SandboxRecoveryFailedError` is the substrate's own\n * verdict after it tried a state-preserving restart and failed. A host-capacity\n * rejection is the same verdict one layer earlier: a box is pinned to a host,\n * and a full host rejects every resume for every box on it until something else\n * there goes away. Neither is transient, and neither is fixed by trying again\n * at the same key.\n */\nfunction isUnbringableBoxError(error: unknown): boolean {\n if (error instanceof SandboxRecoveryFailedError) return true\n const diagnostics = serializeSandboxProvisioningError(error)\n return isSandboxHostCapacityFailure(diagnostics) || isSandboxBoxConfigFailure(diagnostics)\n}\n","import type { AgentProfile, ReasoningEffort, AgentProfileMcpServer } from '@tangle-network/agent-interface'\nimport type { Harness } from '../harness/index'\nimport type { ProfileFingerprint } from '../profile/fingerprint'\nimport type { SandboxSpendHooks } from './configuration'\nimport type { TurnTrace, TurnSpan } from '../turn-trace/recorder'\n\n/** Define options for configuring and controlling a streaming sandbox prompt session */\nexport interface StreamSandboxPromptOptions {\n /** Complete server-owned profile for this turn. Skips the shell's default composer.\n * Credentials, admission, session identity, and interactions remain execution options.\n * Explicit turn selections override this profile; otherwise its model and harness win\n * over shell defaults. Never populate this field from an untrusted request body. */\n profile?: AgentProfile\n sessionId?: string\n executionId?: string\n /** Stable idempotency key for one logical dispatch. Reuse it with the same\n * `sessionId` when a caller may retry the initial request. */\n turnId?: string\n lastEventId?: string\n systemPrompt?: string\n model?: string\n modelApiKey?: string\n history?: Array<{ role: 'user' | 'assistant'; content: string }>\n harness?: Harness\n effort?: 'auto' | ReasoningEffort\n /** Provider-enforced visible answer ceiling for this turn. */\n maxOutputTokens?: number\n /** Provider-enforced hidden reasoning ceiling for this turn. */\n maxReasoningTokens?: number\n /** Provider-enforced combined answer and reasoning ceiling for this turn. */\n maxTotalOutputTokens?: number\n appToolMcp?: Record<string, AgentProfileMcpServer>\n baseProfileMcp?: Record<string, AgentProfileMcpServer>\n extraMcp?: Record<string, AgentProfileMcpServer>\n /** Runtime-owned MCP tools for this turn, outside the authored profile. */\n runtimeAttachments?: { mcp: Record<string, AgentProfileMcpServer> }\n /** Per-turn secret values used by runtime attachments; never stored in the profile or sandbox environment. */\n runtimeSecrets?: Record<string, string>\n /** Mark a backend prepared for a secret-isolated native session. The caller creates\n * that session and prepares its exact backend before dispatch. */\n secretProfileIsolation?: true\n /** SDK-issued digest of the prepared public backend request. */\n expectedPublicProfileRequestDigest?: `sha256:${string}`\n /** SDK-issued receipt for the prepared secret native profile revision. */\n expectedSecretProfileReceipt?: `hmac-sha256:${string}`\n /** The send witness: called synchronously just before this execution is handed to the SDK, once per send\n * attempt and never for a `lastEventId` resume. It is the same in a shared and a secret-isolated session, so\n * never pass it only for one mode. A failure before its first call was never sent and holds no run on the box;\n * after it, the run may exist and is reconciled, not retried. */\n onDispatch?: () => void\n signal?: AbortSignal\n timeoutMs?: number\n /**\n * Execution time limit for this run, in milliseconds. Unset, the runtime\n * falls back to `timeoutMs`, then to its one-hour default, so a turn that\n * must run longer than an hour names it here. The runtime refuses a value\n * above its deployment maximum before the run starts. `timeoutMs` stays the\n * shorter first-output budget.\n */\n ttlMs?: number\n requireVisibleAssistantOutput?: boolean\n // When true, an interactive question event throws instead of yielding.\n // Use this for detached runs whose caller has no consumer to answer it.\n disallowQuestions?: boolean\n // Per-turn question/permission/plan channel toggles, forwarded VERBATIM into the\n // backend config. agent-app does not validate kinds per harness — the sidecar fails\n // session init loudly for unsupported ones; a local matrix would drift. Honored on\n // both streaming and driveTurn paths.\n interactions?: { question?: boolean; permission?: boolean; plan?: boolean }\n // Streaming helper only: detach the run from THIS stream's lifetime. When true, the helper admits the\n // run through `dispatchPrompt`, then reads its exact execution through the\n // SDK replay stream. A Worker restart or browser refresh therefore cannot\n // cancel the server-side run. Reuse `sessionId` + `executionId` + `turnId` on\n // retries; `lastEventId` resumes the same execution instead of dispatching\n // another one.\n // Omit for a run where closing the tab should stop burning tokens.\n detach?: boolean\n // Observe the EXACT profile handed to the sandbox SDK for this turn — after\n // the system-prompt override, the MCP merge, and reasoning-effort attachment\n // — as a ProfileFingerprint. This is the seam an eval/backtest uses to PROVE\n // it executed the shipped profile instead of re-deriving one and asserting\n // nothing. Invoked once, before the first event is yielded.\n onProfileResolved?: (fingerprint: ProfileFingerprint) => void\n // Optional spend-verification activity tap. Omitted, nothing changes. Takes\n // the SAME object `ensureWorkspaceSandbox` does, so a product builds one and\n // wires it in both places; only `onActivity` is read here.\n spend?: SandboxSpendHooks\n /**\n * The turn's trace (`@tangle-network/agent-app/turn-trace`). Its id is sent as `traceId`, the\n * `x-tangle-trace-id` the Sandbox API, orchestrator, sidecar and the Router's dispatch rows all record, and\n * the stream is recorded as a `sandbox.prompt` span: the sidecar's first-text phases, the generation and\n * each tool the box agent ran. Omitted, the SDK mints a trace id the app does not keep.\n */\n trace?: TurnTrace\n /** The span the prompt hangs from. Default: the trace's root. */\n traceParent?: TurnSpan\n}\n\nexport interface SandboxPromptExecutionLimits {\n maxOutputTokens?: number\n maxReasoningTokens?: number\n}\n\nexport function sandboxPromptExecutionOptions(\n limits: SandboxPromptExecutionLimits | undefined,\n effort: StreamSandboxPromptOptions['effort'],\n): Pick<StreamSandboxPromptOptions, 'effort' | 'maxOutputTokens' | 'maxReasoningTokens' | 'maxTotalOutputTokens'> {\n return {\n effort: limits?.maxReasoningTokens === 0 ? 'none' : effort,\n ...(limits?.maxOutputTokens !== undefined ? {\n maxOutputTokens: limits.maxOutputTokens,\n maxTotalOutputTokens: limits.maxOutputTokens,\n } : {}),\n ...(limits?.maxReasoningTokens ? { maxReasoningTokens: limits.maxReasoningTokens } : {}),\n }\n}\n","import type { SandboxInstance, ScopedTokenScope, MintScopedTokenOptions } from '@tangle-network/sandbox'\nimport { type Outcome, ok, fail } from './outcome'\nimport type { SandboxRuntimeConfig } from './configuration'\nimport { getClient } from './runtime-cache'\n\n// Mirrors the SDK's PermissionLevel union (not re-exported by\n// @tangle-network/sandbox). The product's role-mapping seam must produce one of\n// these; binding the seam's return type to the union makes a wrong mapping a\n// compile error rather than a runtime 400 from the orchestrator.\n/** Define permission levels for sandbox access and control */\nexport type SandboxPermissionLevel = 'owner' | 'admin' | 'developer' | 'viewer'\n\n/** Map workspace roles to corresponding sandbox permission levels */\nexport interface MemberSyncSeam {\n roleToSandboxRole: (workspaceRole: string) => SandboxPermissionLevel\n}\n\n/**\n * Sandbox member permissions are not served. The SDK's `box.permissions` called `/permissions/users*` on the\n * sidecar, which never served it, so every add, update and remove failed with 404; `@tangle-network/sandbox` 0.64\n * removed the API (agent-container b9c65980). These keep their signatures so callers compile, and fail with\n * an error whose `code` is `sandbox_member_permissions_unsupported`, without a network call: the outcome callers already saw,\n * now named. Access to a workspace box is decided by the product's own authorization, not per-box member rows.\n */\nclass SandboxMemberPermissionsUnsupportedError extends Error {\n readonly code = 'sandbox_member_permissions_unsupported'\n constructor() {\n super('Sandbox member permissions are not served by the platform; @tangle-network/sandbox 0.64 removed box.permissions.')\n this.name = 'SandboxMemberPermissionsUnsupportedError'\n }\n}\n\n/** Always fails with {@link SandboxMemberPermissionsUnsupportedError}; see its note. */\nexport async function syncSandboxMemberAdd(\n _box: SandboxInstance,\n _seam: MemberSyncSeam,\n _userId: string,\n _role: string,\n): Promise<Outcome<void>> {\n return fail(new SandboxMemberPermissionsUnsupportedError())\n}\n\n/** Always fails with {@link SandboxMemberPermissionsUnsupportedError}; see its note. */\nexport async function syncSandboxMemberRemove(\n _box: SandboxInstance,\n _userId: string,\n): Promise<Outcome<void>> {\n return fail(new SandboxMemberPermissionsUnsupportedError())\n}\n\n/** Always fails with {@link SandboxMemberPermissionsUnsupportedError}; see its note. */\nexport async function syncSandboxMemberRole(\n _box: SandboxInstance,\n _seam: MemberSyncSeam,\n _userId: string,\n _role: string,\n): Promise<Outcome<void>> {\n return fail(new SandboxMemberPermissionsUnsupportedError())\n}\n\n/**\n * Write-only secret port: create, replace, and delete a secret by name.\n *\n * There is no read method. The platform's secrets API returns names and\n * timestamps only — a stored value is never served back, it is injected into\n * the sandbox as an environment variable. A `get` here could only ever return\n * a value this process already held, so the port does not offer one.\n */\nexport interface SecretStore {\n create: (name: string, value: string) => Promise<void>\n update: (name: string, value: string) => Promise<void>\n delete: (name: string) => Promise<void>\n}\n\n/** Resolve a SecretStore interface using the provided SandboxRuntimeConfig shell */\nexport function secretStoreFromClient(shell: SandboxRuntimeConfig): SecretStore {\n const client = getClient(shell)\n return {\n create: async (name, value) => {\n await client.secrets.create(name, value)\n },\n // Replace in place, guarded by the row's updatedAt: a concurrent writer\n // cannot clobber a successor, and a failure leaves the PREVIOUS value\n // live (the platform re-keys matching boxes on the update).\n update: async (name, value) => {\n const current = await client.secrets.list().then(rows => rows.find(row => row.name === name))\n if (!current) {\n await client.secrets.create(name, value)\n return\n }\n await client.secrets.update(name, value, {\n expectedUpdatedAt: current.updatedAt.toISOString(),\n })\n },\n delete: async (name) => {\n await client.secrets.delete(name)\n },\n }\n}\n\n/** Resolve storing a secret by creating it, or replacing it when it exists */\nexport async function storeSecret(\n store: SecretStore,\n name: string,\n value: string,\n): Promise<Outcome<void>> {\n try {\n await store.create(name, value)\n return ok(undefined)\n } catch {\n try {\n await store.update(name, value)\n return ok(undefined)\n } catch (err) {\n return fail(\n new Error(\n `Failed to store sandbox secret ${name}. The previous value remains live; a concurrent writer may have replaced it first (retry resolves by expectedUpdatedAt).`,\n { cause: err },\n ),\n )\n }\n }\n}\n\n/** Delete a secret by name from the given secret store and return the operation outcome */\nexport async function deleteSecret(store: SecretStore, name: string): Promise<Outcome<void>> {\n try {\n await store.delete(name)\n return ok(undefined)\n } catch (err) {\n return fail(err)\n }\n}\n\n/** Represent a token with its expiration date and associated scope */\nexport interface ScopedTokenResult {\n token: string\n expiresAt: Date\n scope: ScopedTokenScope\n}\n\n/**\n * Mint a scoped token for an already-provisioned box (e.g. to hand a terminal\n * proxy a narrowed credential). Uses the SDK's native `box.mintScopedToken`,\n * which normalizes `expiresAt` to a Date — no hand-rolled wire call.\n */\nexport async function mintSandboxScopedToken(\n box: SandboxInstance,\n options: MintScopedTokenOptions,\n): Promise<Outcome<ScopedTokenResult>> {\n try {\n const token = await box.mintScopedToken(options)\n return ok({ token: token.token, expiresAt: token.expiresAt, scope: token.scope })\n } catch (err) {\n return fail(err)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,IAAM,QAAQ,CAAC,UAAoC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAI,QAAe;AAChI,IAAM,QAAQ,CAAC,UAAuC,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS,IAAI,QAAQ;AAGlI,IAAM,SAAS,CAAC,mBAAmB,iBAAiB,iBAAiB,uBAAuB,uBAAuB,YAAY;AAS/H,SAAS,kBAAkB,OAAkB,QAA8B,MAAkC;AAC3G,QAAM,YAAY,KAAK,IAAI;AAC3B,QAAM,SAAS,MAAM,MAAM,kBAAkB,WAAW,MAAM,MAAM;AACpE,MAAI;AACJ,MAAI;AACJ,MAAI;AACJ,MAAI;AACJ,MAAI,SAAS;AACb,QAAM,QAAQ,oBAAI,IAAsB;AAExC,QAAM,YAAY,CAAC,IAAY,UAC5B,EAAE,oBAAoB,MAAM,gBAAgB,IAAI,cAAc,cAAc,OAAO,WAAW,GAAG,OAAO,UAAU;AACrH,QAAM,YAAY,CAAC,IAAY,SAAiB;AAC9C,QAAI,CAAC,MAAM,IAAI,EAAE,EAAG,OAAM,IAAI,IAAI,MAAM,MAAM,aAAa,QAAQ,EAAE,GAAG,UAAU,IAAI,IAAI,GAAG,QAAQ,KAAK,G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AC;AAC5F,UAAI,CAAC,SAAS;AACZ,cAAM,OAAO,QAAQ,OAAO,MAAM,KAAK;AACvC;AAAA,MACF;AACA,YAAM,OAAO,QAAQ,OAAO,MAAM,OAAO;AAAA,QACvC,mBAAmB,QAAQ,UAAU,YAAY;AAAA,MACnD,CAAC;AAAA,IACH;AAAA,IACA,QAAQ,OAAO,SAAS;AACtB,YAAM,OAAO,QAAQ,OAAO,IAAI;AAAA,IAClC;AAAA,EACF;AACF;AAGA,eAAsB,YACpB,OACA,MACA,OACwB;AACxB,MAAI;AACF,UAAM,MAAM,OAAO,MAAM,KAAK;AAC9B,WAAO,GAAG,MAAS;AAAA,EACrB,QAAQ;AACN,QAAI;AACF,YAAM,MAAM,OAAO,MAAM,KAAK;AAC9B,aAAO,GAAG,MAAS;AAAA,IACrB,SAAS,KAAK;AACZ,aAAO;AAAA,QACL,IAAI;AAAA,UACF,kCAAkC,IAAI;AAAA,UACtC,EAAE,OAAO,IAAI;AAAA,QACf;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAGA,eAAsB,aAAa,OAAoB,MAAsC;AAC3F,MAAI;AACF,UAAM,MAAM,OAAO,IAAI;AACvB,WAAO,GAAG,MAAS;AAAA,EACrB,SAAS,KAAK;AACZ,WAAO,KAAK,GAAG;AAAA,EACjB;AACF;AAcA,eAAsB,uBACpB,KACA,SACqC;AACrC,MAAI;AACF,UAAM,QAAQ,MAAM,IAAI,gBAAgB,OAAO;AAC/C,WAAO,GAAG,EAAE,OAAO,MAAM,OAAO,WAAW,MAAM,WAAW,OAAO,MAAM,MAAM,CAAC;AAAA,EAClF,SAAS,KAAK;AACZ,WAAO,KAAK,GAAG;AAAA,EACjB;AACF;","names":["end","cache","message","harness","message","message","fail","message","DEFAULT_TIMEOUT_MS","fail","message","SAFE_IDENTIFIER","results","outcome","message","errText","SAFE_IDENTIFIER","value","credentials","keyDigest","createHash","refreshed","createHash","domain","parseBackendType","message","box","parseBackendType"]}
|