@finalai/sandbox-router-agent-provider 0.1.2 → 0.1.4
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.
|
@@ -64,7 +64,7 @@ const BUILD_SCRUB_PATHS = [
|
|
|
64
64
|
"$HOME/.docker/config.json",
|
|
65
65
|
"$HOME/.netrc"
|
|
66
66
|
];
|
|
67
|
-
const ARTIFACT_KEY_VERSION =
|
|
67
|
+
const ARTIFACT_KEY_VERSION = 2;
|
|
68
68
|
const PORT_TOKEN_TTL_S = 60 * 60;
|
|
69
69
|
const PORT_ENDPOINT_RENEW_MS = 5 * 6e4;
|
|
70
70
|
const RUNNING_POLL_MAX_MS = 5e3;
|
|
@@ -166,7 +166,11 @@ const createRoutedSandboxProvider = (config) => {
|
|
|
166
166
|
};
|
|
167
167
|
const imageFromArtifact = (stored) => {
|
|
168
168
|
if (stored == null) return void 0;
|
|
169
|
-
|
|
169
|
+
if (typeof stored !== "string") return routerImage.fromJSON(stored);
|
|
170
|
+
if (stored.startsWith("simg_")) return stored;
|
|
171
|
+
const resolved = routerImageOf(stored);
|
|
172
|
+
if (resolved == null) return void 0;
|
|
173
|
+
return typeof resolved === "string" ? resolved : routerImage.fromJSON(resolved);
|
|
170
174
|
};
|
|
171
175
|
const sizeOf = (machine) => {
|
|
172
176
|
const limit = machine?.vcpu;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/provider.ts"],
|
|
4
|
-
"sourcesContent": ["import { Capability, FilesAccess, ScreenAccess, ShellAccess } from '@finalai/agent-protocol';\nimport { jsonObjectSchema, type JsonObject, type JsonValue } from '@finalai/agent-provider';\nimport {\n defineSandboxProvider,\n materializeSandboxSeeds,\n NetworkPolicy,\n platformProcessEnvironment,\n PortProtocol,\n ProcessInspectionOperation,\n SandboxSnapshotOperation,\n reportPlatformNetworkPolicy,\n SandboxCapability,\n sandboxSeedArtifact,\n sandboxSeedArtifactSchema,\n sandboxSeedFiles,\n sandboxSeedFilesForAttach,\n sandboxSeedIdentity,\n withPlatformEgressHosts,\n writePlatformFiles,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type ProcessInspectionResultIface,\n type SandboxEnvironmentImplementationIface,\n type SandboxPrepareContextIface,\n type SandboxProviderContextIface,\n type SandboxProviderHandleIface,\n type SandboxProviderIface,\n type SandboxResourceContextIface,\n type SandboxSetupIface,\n type SandboxSnapshotResponseIface,\n} from '@finalai/agent-provider/sandbox';\nimport { bytesToBase64 } from '@finalai/agent-provider/sandbox/bytes';\nimport {\n Capability as RouterCapability,\n DesktopState,\n IdleAction,\n ImageBuildState,\n image as routerImage,\n PortAuth,\n ProcessSignal,\n SandboxState,\n type CreateSandboxOptionsIface,\n type ImageBuilderIface,\n type ImageSpecIface,\n type LifecycleOptionsIface,\n type RoutingOptionsIface,\n type SnapshotInfoIface,\n type SandboxHandleIface,\n type SandboxRouterIface,\n} from '@finalai/sandbox-router';\nimport * as z from 'zod';\nimport { createComputerUseEndpoint, type ComputerUseCommandIface } from \"./computer-use.mjs\";\nimport {\n ROUTED_SANDBOX_PROVIDER,\n routedEnvironmentSchema,\n routedNeedsBuild,\n type RoutedBuildIface,\n type RoutedEnvironmentIface,\n type RoutedMachineIface,\n} from \"./environment.mjs\";\nimport { routerNetworkOf } from \"./network.mjs\";\nimport {\n createRouterSession,\n isRouterNotFound,\n isRouterUnsupported,\n readOnlySession,\n resolvePosixPath,\n statOf,\n entryTypeOf,\n} from \"./session.mjs\";\n\n// The `routed` sandbox: an agent sandbox created and driven through the Sandbox Router, on\n// whichever provider the host's routing selects. A sandbox is one router sandbox: `create`\n// records it and the first `attach` makes it, so creating a sandbox boots nothing. An\n// environment with build steps is built once on a builder sandbox and snapshotted; its\n// sandboxes start from the snapshot. The setup's network policy is a create option; its\n// repositories, steps and services are applied by the platform through the handle.\n\nexport const WORKSPACE_ROOT = '/workspaces';\n// The label naming the platform sandbox a router sandbox serves.\nexport const SANDBOX_LABEL = 'agent-sandbox';\n\nconst DEFAULT_IDLE_TIMEOUT_SECONDS = 15 * 60;\nconst IDLE_TIMEOUT_MARGIN_SECONDS = 5 * 60;\nconst BUILDER_IDLE_TIMEOUT_SECONDS = 2 * 60 * 60;\n// Builds run from here.\nconst BUILD_ROOT = '/tmp/agent-sandbox-build';\n// Removed from a builder before its snapshot: the build's own files and credentials a step may\n// have left in the home directory.\nconst BUILD_SCRUB_PATHS = [\n '/tmp/*',\n '$HOME/.bash_history',\n '$HOME/.git-credentials',\n '$HOME/.config/gh/hosts.yml',\n '$HOME/.npmrc',\n '$HOME/.pypirc',\n '$HOME/.cargo/credentials',\n '$HOME/.cargo/credentials.toml',\n '$HOME/.docker/config.json',\n '$HOME/.netrc',\n];\n// Bumped when the meaning of the build inputs changes (forces rebuilds).\nconst ARTIFACT_KEY_VERSION = 1;\n// How long a port endpoint's token lasts, and how long before it expires it is renewed.\nconst PORT_TOKEN_TTL_S = 60 * 60;\nconst PORT_ENDPOINT_RENEW_MS = 5 * 60_000;\nconst RUNNING_POLL_MAX_MS = 5_000;\n// How long a build waits for its snapshot to be ready.\nconst SNAPSHOT_READY_WAIT_MS = 30 * 60_000;\n// The vCPUs a sandbox bursts to when neither its environment nor the host names any (the\n// router's default size).\nconst DEFAULT_CPU_LIMIT = 2;\n// The label naming the build a builder sandbox runs.\nconst BUILD_LABEL = 'agent-sandbox-build';\n// Largest snapshot read of one file, and most entries one directory read returns.\nconst SNAPSHOT_READ_MAX_BYTES = 1024 * 1024;\nconst SNAPSHOT_DIRECTORY_LIMIT = 1000;\n\nexport interface RoutedSandboxLogIface {\n (message: string, fields?: Record<string, string | number | boolean | null>): void;\n}\n\nexport interface RoutedSandboxProviderConfigIface {\n // The name the provider is registered under (default `routed`).\n name?: string;\n // The router a call acts through: the host supplies credentials that act for the call's\n // project (`ctx.projectId`), such as `createSandboxRouter({ apiKey: () => tokenFor(ctx) })`.\n router: (ctx: SandboxProviderContextIface) => SandboxRouterIface;\n // Routing and provider options for every create.\n routing?: RoutingOptionsIface;\n providerOptions?: Record<string, unknown>;\n // The image of an environment that names none; absent, the provider's default image.\n defaultImage?: string;\n // Image names environments may use, as router images (a spec or a registered `simg_\u2026` id).\n images?: Record<string, ImageBuilderIface | ImageSpecIface | string>;\n // Defaults for what an environment leaves out.\n machine?: RoutedMachineIface;\n // The vCPUs a sandbox is guaranteed; it bursts to its machine's `vcpu` when the host has idle\n // CPU (capability `burst`). Absent, it is guaranteed its `vcpu`.\n cpuRequest?: number;\n // The maximum lifetime of agent sandboxes, in the router's lifecycle terms. Left out, the\n // provider's default applies; null turns it off where the provider allows. A provider whose\n // default deletes the sandbox loses its files, so set it for those.\n maxLifetime?: LifecycleOptionsIface['max'];\n // How long the token a port endpoint carries lasts (default an hour), on providers whose port\n // tokens expire (capability `portTokens`); renewed before it ends.\n portTokenTtlS?: number;\n region?: string;\n // Labels every sandbox carries, besides `agent-sandbox`.\n labels?: Record<string, string>;\n // The computer-use MCP server desktop images run; without it, sandboxes offer no computer use.\n computerUse?: ComputerUseCommandIface;\n // How long attach waits for a sandbox to run (default 5 min), polled from runningPollMs\n // (default 250 ms), doubling to 5 s.\n runningWaitMs?: number;\n runningPollMs?: number;\n log?: RoutedSandboxLogIface;\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport enum RoutedSandboxErrorCode {\n ArtifactUnavailable = 'artifact_unavailable',\n SandboxGone = 'sandbox_gone',\n SandboxNotRunning = 'sandbox_not_running',\n InvalidEnvironment = 'invalid_environment',\n BuildFailed = 'build_failed',\n}\n\nexport interface RoutedSandboxErrorIface extends Error {\n code: RoutedSandboxErrorCode;\n}\n\nconst routedSandboxError = (\n code: RoutedSandboxErrorCode,\n message: string,\n): RoutedSandboxErrorIface =>\n Object.assign(new Error(message), { name: 'RoutedSandboxError', code });\n\n// What sandboxes start from: an image (a registered id or a spec; null for the provider's\n// default), or the snapshot an environment's build was captured as.\nconst artifactSchema = sandboxSeedArtifactSchema.extend({\n version: z.literal(1),\n key: z.string(),\n image: z.union([z.string(), jsonObjectSchema]).nullable(),\n base: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('image') }),\n z.object({ kind: z.literal('snapshot'), snapshotId: z.string() }),\n ]),\n});\n\nconst networkPolicySchema = z.object({\n mode: z.nativeEnum(NetworkPolicy),\n allow: z.array(z.string()).optional(),\n});\n\nconst stateSchema = z.object({\n version: z.literal(1),\n // The router sandbox; null until the first attach creates it.\n sandboxId: z.string().nullable(),\n // The setup's network policy, enforced from the sandbox's first boot.\n network: networkPolicySchema,\n // Ports the setup's services listen on.\n ports: z.array(z.number().int()).default([]),\n});\n\nexport type RoutedSandboxArtifact = z.infer<typeof artifactSchema>;\nexport type RoutedSandboxState = z.infer<typeof stateSchema>;\n\nexport interface RoutedSandboxSessionIface extends NetworkSandboxSessionIface {\n // What this sandbox's handle offers (the host reports it).\n readonly capabilities: readonly SandboxCapability[];\n}\n\nexport type RoutedSandboxProviderIface = SandboxProviderIface<\n JsonValue,\n RoutedSandboxArtifact,\n RoutedSandboxState,\n RoutedSandboxSessionIface\n>;\n\nconst sha256Hex = async (text: string): Promise<string> => {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n};\n\nconst canonicalJson = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n if (value != null && typeof value === 'object')\n return `{${Object.entries(value)\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)\n .join(',')}}`;\n return JSON.stringify(value);\n};\n\n// A router image as an artifact stores it.\nconst storedImageOf = (image: ImageSpecIface | string | null): string | JsonObject | null =>\n image == null || typeof image === 'string'\n ? image\n : jsonObjectSchema.parse(JSON.parse(JSON.stringify(image)));\n\nconst errorText = (cause: unknown): string =>\n cause instanceof Error ? cause.message : String(cause);\n\n// The setup's network as a router sandbox enforces it from creation: every host, none, or an\n// allowlist. The router has no per-host deny list, so a setup naming one is refused at create\n// rather than run unenforced.\nexport const routedNetworkPolicyOf = (setup: SandboxSetupIface | null): NetworkPolicyIface => {\n const network = setup?.network;\n if (network == null) return { mode: NetworkPolicy.AllowAll };\n if ((network.deny ?? []).length > 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.InvalidEnvironment,\n 'A routed sandbox cannot deny individual hosts; list the hosts to allow instead',\n );\n if (network.allow == null) return { mode: NetworkPolicy.AllowAll };\n return network.allow.length === 0\n ? { mode: NetworkPolicy.DenyAll }\n : { mode: NetworkPolicy.Allowlist, allow: [...network.allow] };\n};\n\n// The base's identity: a hash of the build-time inputs only, so identical environments share\n// one snapshot.\nconst artifactKeyOf = async (inputs: {\n image: string | null;\n build: RoutedBuildIface | undefined;\n machine: RoutedMachineIface | undefined;\n}): Promise<string> => {\n if (!routedNeedsBuild(inputs.build)) {\n const hex = await sha256Hex(canonicalJson({ v: ARTIFACT_KEY_VERSION, image: inputs.image }));\n return `img-${hex.slice(0, 16)}`;\n }\n const hex = await sha256Hex(\n canonicalJson({\n v: ARTIFACT_KEY_VERSION,\n image: inputs.image,\n build: { steps: inputs.build?.steps ?? [], verify: inputs.build?.verify ?? [] },\n machine: inputs.machine ?? null,\n }),\n );\n return `snap-${hex.slice(0, 16)}`;\n};\n\n// A setup session serves no ports and leaves the sandbox's lifecycle alone.\nconst noNetwork = {\n ports: [],\n getPortEndpoint: async (): Promise<never> => {\n throw new Error('setup sessions expose no ports');\n },\n stop: async () => undefined,\n destroy: async () => undefined,\n};\n\nconst defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport const createRoutedSandboxProvider = (\n config: RoutedSandboxProviderConfigIface,\n): RoutedSandboxProviderIface => {\n const log: RoutedSandboxLogIface = config.log ?? (() => undefined);\n const now = config.now ?? (() => Date.now());\n const sleep = config.sleep ?? defaultSleep;\n const runningWaitMs = config.runningWaitMs ?? 5 * 60_000;\n\n // A name as the router image it stands for; null for the provider's default image.\n const routerImageOf = (name: string | null): ImageSpecIface | string | null => {\n if (name == null) return null;\n const alias = config.images?.[name];\n if (alias != null)\n return typeof alias === 'string' || !('toJSON' in alias) ? alias : alias.toJSON();\n if (name.startsWith('simg_')) return name;\n return routerImage.from(name).toJSON();\n };\n\n // A stored image: a registered id, or a spec checked again.\n const imageFromArtifact = (\n stored: RoutedSandboxArtifact['image'],\n ): ImageBuilderIface | string | undefined => {\n if (stored == null) return undefined;\n return typeof stored === 'string' ? stored : routerImage.fromJSON(stored);\n };\n\n const sizeOf = (machine: RoutedMachineIface | undefined) => {\n const limit = machine?.vcpu;\n const request = config.cpuRequest;\n return {\n cpu:\n request == null\n ? limit\n : {\n request: Math.min(request, limit ?? DEFAULT_CPU_LIMIT),\n limit: limit ?? DEFAULT_CPU_LIMIT,\n },\n memoryMib: machine?.memoryMb,\n diskGib: machine?.diskGb,\n };\n };\n\n const routed = (\n options: Omit<CreateSandboxOptionsIface, 'routing' | 'providerOptions'>,\n ): CreateSandboxOptionsIface => ({\n ...options,\n routing: config.routing,\n providerOptions: config.providerOptions,\n });\n\n // The router sandbox, or null when it no longer exists.\n const findSandbox = async (\n router: SandboxRouterIface,\n id: string,\n ): Promise<SandboxHandleIface | null> => {\n try {\n const sandbox = await router.sandboxes.get(id);\n return sandbox.info.state === SandboxState.Deleted ? null : sandbox;\n } catch (cause) {\n if (isRouterNotFound(cause)) return null;\n throw cause;\n }\n };\n\n // Commands and file calls need a running sandbox (they never wake one), so nothing touches\n // it before this resolves.\n const awaitSandboxRunning = async (\n sandbox: SandboxHandleIface,\n timeoutMs: number,\n ): Promise<void> => {\n const deadline = now() + timeoutMs;\n let pollMs = config.runningPollMs ?? 250;\n let info = sandbox.info;\n for (;;) {\n if (info.state === SandboxState.Running) return;\n if (info.state === SandboxState.Deleted || info.state === SandboxState.Failed)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxGone,\n `sandbox ${sandbox.id} is ${info.state}${info.nativeError == null ? '' : `: ${info.nativeError}`}`,\n );\n const left = deadline - now();\n if (left <= 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxNotRunning,\n `sandbox ${sandbox.id} was not running within ${Math.round(timeoutMs / 1000)} s (it is ${info.state})`,\n );\n await sleep(Math.min(pollMs, left));\n pollMs = Math.min(pollMs * 2, RUNNING_POLL_MAX_MS);\n info = await sandbox.refresh();\n }\n };\n\n const mcpClosers = new Map<string, Set<() => Promise<void>>>();\n const closeMcp = async (sandboxId: string) => {\n const results = await Promise.allSettled(\n [...(mcpClosers.get(sandboxId) ?? [])].map((close) => close()),\n );\n for (const result of results) if (result.status === 'rejected') throw result.reason;\n };\n\n const settledFailures = (failures: unknown[], message: string) => {\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw new AggregateError(failures, message);\n };\n\n // The desktop's state, or null for a provider or image without one.\n const desktopState = async (sandbox: SandboxHandleIface): Promise<DesktopState | null> => {\n try {\n return (\n await Promise.race([\n sandbox.desktop.status(),\n new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error('desktop status timed out')), 2_000),\n ),\n ])\n ).state;\n } catch {\n return null;\n }\n };\n\n // A build's snapshot once it is ready, or null when it is gone or failed (a failed one is\n // deleted). A provider that cannot read snapshots has them ready when `snapshot()` returns.\n const readySnapshot = async (\n router: SandboxRouterIface,\n snapshotId: string,\n ): Promise<string | null> => {\n const deadline = now() + SNAPSHOT_READY_WAIT_MS;\n let pollMs = config.runningPollMs ?? 250;\n for (;;) {\n let info: SnapshotInfoIface;\n try {\n info = await router.snapshots.get(snapshotId);\n } catch (cause) {\n if (isRouterNotFound(cause)) return null;\n if (isRouterUnsupported(cause)) return snapshotId;\n throw cause;\n }\n if (info.state === 'ready') return snapshotId;\n if (info.state === 'failed') {\n await deleteSnapshot(router, snapshotId);\n return null;\n }\n const left = deadline - now();\n if (left <= 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n `sandbox snapshot ${snapshotId} was not ready within ${Math.round(SNAPSHOT_READY_WAIT_MS / 60_000)} min`,\n );\n await sleep(Math.min(pollMs, left));\n pollMs = Math.min(pollMs * 2, RUNNING_POLL_MAX_MS);\n }\n };\n\n const deleteSnapshot = async (router: SandboxRouterIface, snapshotId: string) => {\n try {\n await router.snapshots.delete(snapshotId);\n } catch (error) {\n if (!isRouterNotFound(error))\n log('routed_sandbox.snapshot_delete_failed', { snapshotId, error: errorText(error) });\n }\n };\n\n // A snapshot an earlier build of this key left, for a key the artifact cache lost or a build\n // another prepare ran meanwhile: the newest ready one (waiting for one still being captured).\n // Failed ones are deleted. Found by name, which every provider keeps (not all label\n // snapshots); a provider may suffix a name already taken.\n const builtSnapshot = async (router: SandboxRouterIface, key: string): Promise<string | null> => {\n let listed: SnapshotInfoIface[];\n try {\n listed = await router.snapshots.list({ provider: config.routing?.provider });\n } catch (cause) {\n if (isRouterUnsupported(cause)) return null;\n throw cause;\n }\n const newestFirst = listed\n .filter((snapshot) => snapshot.name === key || snapshot.name.startsWith(`${key}-`))\n .sort((a, b) => (b.createdAt ?? '').localeCompare(a.createdAt ?? ''));\n for (const snapshot of newestFirst) {\n if (snapshot.state === 'failed') await deleteSnapshot(router, snapshot.id);\n else if ((await readySnapshot(router, snapshot.id)) != null) return snapshot.id;\n }\n return null;\n };\n\n const buildHandle = async (args: {\n ctx: Pick<SandboxResourceContextIface, 'platformEgressHosts'>;\n sandbox: SandboxHandleIface;\n env: () => Promise<Record<string, string>>;\n ports: readonly number[];\n // A viewer's handle: it changes nothing, and stopping it leaves the sandbox alone.\n passive: boolean;\n }): Promise<SandboxProviderHandleIface<RoutedSandboxSessionIface>> => {\n const { sandbox } = args;\n const endpoints = new Map<\n number,\n { url: string; headers: Record<string, string>; renewAtMs: number }\n >();\n // The port's URL and the credential programs send with it, renewed before it expires.\n const portEndpoint = async (port: number) => {\n const cached = endpoints.get(port);\n if (cached != null && cached.renewAtMs > now()) return cached;\n // A provider whose port tokens cannot expire refuses a lifetime, so only those with\n // `portTokens` are asked for one.\n const access = await sandbox.ports.url(\n port,\n sandbox.info.capabilities.includes(RouterCapability.PortTokens)\n ? { ttlS: config.portTokenTtlS ?? PORT_TOKEN_TTL_S }\n : {},\n );\n const headers: Record<string, string> = {};\n if (access.auth === PortAuth.Bearer && access.token != null)\n headers.authorization = `Bearer ${access.token}`;\n else if (access.auth === PortAuth.Header && access.token != null && access.header != null)\n headers[access.header] = access.token;\n else if (access.auth === PortAuth.Cookie)\n throw new Error(`port ${port} is reached only through a browser session`);\n const expiresAtMs = access.expiresAt == null ? null : Date.parse(access.expiresAt);\n const endpoint = {\n url: access.url,\n headers,\n renewAtMs:\n expiresAtMs == null ? Number.POSITIVE_INFINITY : expiresAtMs - PORT_ENDPOINT_RENEW_MS,\n };\n endpoints.set(port, endpoint);\n return endpoint;\n };\n const session = createRouterSession({\n sandbox,\n description: `routed sandbox ${sandbox.id}`,\n workspaceRoot: WORKSPACE_ROOT,\n baseEnv: args.env,\n network: {\n ports: [...args.ports],\n getPortEndpoint: async ({ port, protocol }) => {\n const endpoint = await portEndpoint(port);\n const url =\n protocol === PortProtocol.Ws ? endpoint.url.replace(/^http/, 'ws') : endpoint.url;\n return { url, headers: { ...endpoint.headers } };\n },\n stop: async () => {\n const failures: unknown[] = [];\n for (const finish of [() => closeMcp(sandbox.id), () => sandbox.stop()])\n try {\n await finish();\n } catch (cause) {\n if (!isRouterNotFound(cause)) failures.push(cause);\n }\n settledFailures(failures, 'Sandbox stop or MCP cleanup failed');\n },\n destroy: async () => {\n const failures: unknown[] = [];\n for (const finish of [() => closeMcp(sandbox.id), () => sandbox.delete()])\n try {\n await finish();\n } catch (cause) {\n if (!isRouterNotFound(cause)) failures.push(cause);\n }\n settledFailures(failures, 'Sandbox delete or MCP cleanup failed');\n },\n },\n });\n const desktop = await desktopState(sandbox);\n const desktopUp = desktop === DesktopState.Running || desktop === DesktopState.Starting;\n const computerUse =\n args.passive || !desktopUp || config.computerUse == null\n ? null\n : createComputerUseEndpoint({ sandbox, server: config.computerUse, cwd: WORKSPACE_ROOT });\n const closeComputerUse = async () => {\n try {\n await computerUse?.close();\n } catch (error) {\n log('computer_use.close_failed', { sandboxId: sandbox.id, error: errorText(error) });\n }\n const closers = mcpClosers.get(sandbox.id);\n closers?.delete(closeComputerUse);\n if (closers?.size === 0) mcpClosers.delete(sandbox.id);\n };\n if (computerUse != null) {\n const closers = mcpClosers.get(sandbox.id) ?? new Set<() => Promise<void>>();\n closers.add(closeComputerUse);\n mcpClosers.set(sandbox.id, closers);\n }\n const capabilities = [SandboxCapability.Files, SandboxCapability.Ports];\n if (desktopUp) capabilities.push(SandboxCapability.Screen);\n if (computerUse != null) capabilities.push(SandboxCapability.ComputerUse);\n if (!args.passive)\n capabilities.push(\n SandboxCapability.Process,\n SandboxCapability.DurableProcesses,\n SandboxCapability.NetworkPolicy,\n );\n const full: RoutedSandboxSessionIface = {\n ...session,\n setNetworkPolicy: async (policy) => {\n if (args.passive) throw new Error('this sandbox handle is read-only');\n await sandbox.network.set(routerNetworkOf(withPlatformEgressHosts(args.ctx, policy)));\n },\n capabilities,\n };\n if (computerUse != null) full.computerUse = async () => computerUse.endpoint;\n // View-only unless input control is asked for, which the host grants with execute access.\n if (desktopUp)\n full.screen = async (options) => {\n const screen = await sandbox.desktop.screen({ viewOnly: options?.viewOnly !== false });\n if (screen.token == null || screen.expiresAt == null)\n throw new Error('the screen session has no token or expiry');\n return { url: screen.url, token: screen.token, expiresAt: screen.expiresAt };\n };\n return {\n sandbox: args.passive ? readOnlySession(full) : full,\n onSandboxStop: closeComputerUse,\n onSandboxDelete: async () => {\n const failures: unknown[] = [];\n for (const finish of [closeComputerUse, () => sandbox.delete()])\n try {\n await finish();\n } catch (cause) {\n if (!isRouterNotFound(cause)) failures.push(cause);\n }\n settledFailures(failures, 'Sandbox delete or MCP cleanup failed');\n },\n onRuntimeShutdown: closeComputerUse,\n };\n };\n\n // Runs build.steps, then build.verify, on a builder sandbox of the environment's image and\n // snapshots it; sandboxes start from the snapshot.\n const build = async (args: {\n ctx: SandboxPrepareContextIface;\n router: SandboxRouterIface;\n image: ImageSpecIface | string | null;\n build: RoutedBuildIface;\n machine: RoutedMachineIface | undefined;\n region: string | null;\n key: string;\n }): Promise<{ snapshotId: string }> => {\n const { ctx, router, key } = args;\n // One builder per attempt: a retry after a failed build starts clean.\n const builder = await router.sandboxes.create(\n routed({\n image: args.image ?? undefined,\n ...sizeOf(args.machine),\n lifecycle: {\n idle: { afterS: BUILDER_IDLE_TIMEOUT_SECONDS, action: IdleAction.Delete },\n autoResume: false,\n },\n labels: { ...config.labels, [BUILD_LABEL]: key },\n region: args.region ?? undefined,\n }),\n );\n ctx.log?.(`building sandbox snapshot ${key} on ${builder.id}`);\n try {\n const run = (command: string, timeoutMs?: number) =>\n builder.run(command, { cwd: BUILD_ROOT, timeoutMs, autoResume: false });\n await builder.files.mkdir(BUILD_ROOT, { recursive: true });\n const steps = [\n ...args.build.steps.map((step) => ({ step, label: 'build step' })),\n ...args.build.verify.map((step) => ({ step, label: 'verify step' })),\n ];\n for (const [index, { step, label }] of steps.entries()) {\n ctx.log?.(`${label} ${index + 1}/${steps.length}`);\n const result = await run(`set -eu\\n${step.run}`, step.timeoutMinutes * 60_000);\n if (result.exitCode !== 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.BuildFailed,\n `${label} ${index + 1} failed (exit ${result.exitCode ?? result.signal ?? result.reason}): ${result.stderr.trim().slice(-2000)}`,\n );\n }\n const scrubbed = await builder.run(\n `rm -rf ${BUILD_SCRUB_PATHS.join(' ')} \"$HOME/.ssh\" \"$HOME/.aws\" \"$HOME/.config/gcloud\" \"$HOME/.azure\"`,\n { cwd: '/', autoResume: false },\n );\n if (scrubbed.exitCode !== 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.BuildFailed,\n `could not clean the builder before its snapshot: ${scrubbed.stderr.trim().slice(-2000)}`,\n );\n // Retained until deleted: sandboxes start from it for as long as the artifact is cached.\n // Named for the build, so a later prepare finds it again.\n const { snapshotId } = await builder.snapshot({ name: key, retain: true });\n if ((await readySnapshot(router, snapshotId)) == null)\n throw routedSandboxError(\n RoutedSandboxErrorCode.BuildFailed,\n `sandbox snapshot ${snapshotId} of ${key} failed`,\n );\n ctx.log?.(`captured sandbox snapshot ${key} as ${snapshotId}`);\n return { snapshotId };\n } finally {\n // The snapshot holds the build; the builder is not part of it.\n try {\n await builder.delete();\n } catch (error) {\n log('routed_sandbox.builder_delete_failed', {\n sandboxId: builder.id,\n error: errorText(error),\n });\n }\n }\n };\n\n const environment = (\n rawOptions?: JsonValue,\n ): SandboxEnvironmentImplementationIface<\n RoutedSandboxArtifact,\n RoutedSandboxState,\n RoutedSandboxSessionIface\n > => {\n const parsed = routedEnvironmentSchema.safeParse(rawOptions ?? {});\n if (!parsed.success)\n throw routedSandboxError(\n RoutedSandboxErrorCode.InvalidEnvironment,\n `invalid routed environment: ${parsed.error.message}`,\n );\n const options: RoutedEnvironmentIface = parsed.data;\n const imageName = options.image ?? config.defaultImage ?? null;\n const image = routerImageOf(imageName);\n const machine = options.machine ?? config.machine;\n const region = options.region ?? config.region ?? null;\n // Outlasts the platform's own idle parking, so the platform parks first.\n const idleTimeoutFor = (ctx: SandboxResourceContextIface): number =>\n options.idleTimeoutSeconds ??\n (ctx.lifecycle.parkAfterIdleMs == null\n ? DEFAULT_IDLE_TIMEOUT_SECONDS\n : Math.ceil(ctx.lifecycle.parkAfterIdleMs / 1000) + IDLE_TIMEOUT_MARGIN_SECONDS);\n const seedsFor = (ctx: SandboxPrepareContextIface): Record<string, string> =>\n sandboxSeedFiles({ files: ctx.files, resources: ctx.resources });\n const keyFor = async (files: Record<string, string>): Promise<string> => {\n const baseKey = await artifactKeyOf({ image: imageName, build: options.build, machine });\n return Object.keys(files).length === 0\n ? baseKey\n : `${baseKey}-s${await sha256Hex(sandboxSeedIdentity(files))}`;\n };\n\n const stateOf = (raw: JsonValue): RoutedSandboxState => {\n const state = stateSchema.safeParse(raw);\n if (!state.success)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxGone,\n 'this sandbox was recorded by another sandbox provider; create it again',\n );\n return state.data;\n };\n\n // The running router sandbox a read about an existing sandbox may use, never waking it.\n const runningSandbox = async (\n ctx: SandboxProviderContextIface,\n state: RoutedSandboxState,\n ): Promise<SandboxHandleIface | null> => {\n if (state.sandboxId == null) return null;\n const sandbox = await findSandbox(config.router(ctx), state.sandboxId);\n return sandbox?.info.state === SandboxState.Running ? sandbox : null;\n };\n\n // A parked sandbox's disk, which does not change until it boots again: named by the event\n // that parked it.\n const parkedDisk = async (\n sandbox: SandboxHandleIface,\n ): Promise<{ id: string; capturedAt: string }> => {\n const { events } = await sandbox.events({ limit: 20 });\n const parked = events.find(\n (event) => event.state === SandboxState.Paused || event.state === SandboxState.Stopped,\n );\n return parked == null\n ? {\n id: `${sandbox.id}:${sandbox.info.generation ?? 0}`,\n capturedAt: sandbox.info.createdAt,\n }\n : { id: `${sandbox.id}:${parked.id}`, capturedAt: parked.at };\n };\n\n return {\n // Reads a parked sandbox's workspace without waking it (capability `coldFiles`). Null while\n // it runs, before its first attach, or where the provider cannot read a parked disk.\n readSnapshot: async (ctx, rawState, request) => {\n const state = stateOf(rawState);\n const path = resolvePosixPath(WORKSPACE_ROOT, request.path ?? WORKSPACE_ROOT);\n if (path !== WORKSPACE_ROOT && !path.startsWith(`${WORKSPACE_ROOT}/`))\n throw new Error('snapshot path is outside the workspace');\n if (state.sandboxId == null) return null;\n const sandbox = await findSandbox(config.router(ctx), state.sandboxId);\n if (sandbox == null) throw new Error(`sandbox ${state.sandboxId} no longer exists`);\n const { info } = sandbox;\n const parked = info.state === SandboxState.Paused || info.state === SandboxState.Stopped;\n if (!parked || !info.capabilities.includes(RouterCapability.ColdFiles)) {\n // A later range of a snapshot read must not fall through to a live disk.\n if (request.snapshotId != null)\n throw new Error('the sandbox ran since this snapshot; read it again');\n if (info.state === SandboxState.Failed)\n throw new Error(`sandbox ${sandbox.id} failed; its files cannot be read`);\n return null;\n }\n const snapshot = await parkedDisk(sandbox);\n if (request.snapshotId != null && request.snapshotId !== snapshot.id)\n throw new Error('the sandbox ran since this snapshot; read it again');\n const base = { root: WORKSPACE_ROOT, path, snapshot };\n const cold = { autoResume: false };\n let response: SandboxSnapshotResponseIface;\n if (request.operation === SandboxSnapshotOperation.Stat) {\n const entry = await sandbox.files.stat(path, cold);\n response = {\n ...base,\n result: { operation: request.operation, stat: entry == null ? null : statOf(entry) },\n };\n } else if (request.operation === SandboxSnapshotOperation.ReadDirectory) {\n const page = await sandbox.files.listPage(path, {\n limit: SNAPSHOT_DIRECTORY_LIMIT,\n ...cold,\n });\n response = {\n ...base,\n result: {\n operation: request.operation,\n entries: page.entries.map((entry) => ({\n name: entry.name,\n path: entry.path,\n type: entryTypeOf(entry.kind),\n size: entry.size,\n })),\n truncated: page.nextCursor != null,\n },\n };\n } else {\n const entry = await sandbox.files.stat(path, cold);\n if (entry == null) throw new Error(`${path} does not exist in the snapshot`);\n const offset = request.offset ?? 0;\n const bytes =\n offset >= entry.size\n ? new Uint8Array()\n : await sandbox.files.read(path, {\n offset,\n length: Math.min(\n request.length ?? SNAPSHOT_READ_MAX_BYTES,\n SNAPSHOT_READ_MAX_BYTES,\n ),\n ...cold,\n });\n response = {\n ...base,\n result: {\n operation: request.operation,\n offset,\n size: entry.size,\n contentBase64: bytesToBase64(bytes),\n truncated: offset + bytes.byteLength < entry.size,\n },\n };\n }\n // The sandbox may have woken during the read; what was read is then not this snapshot.\n const after = await sandbox.refresh();\n if (after.state !== info.state || (await parkedDisk(sandbox)).id !== snapshot.id)\n throw new Error('the sandbox ran during this snapshot read; read it again');\n return response;\n },\n capabilities: async () => ({\n [Capability.Files]: FilesAccess.Write,\n [Capability.Shell]: ShellAccess.Execute,\n ...(config.computerUse == null ? {} : { [Capability.ComputerUse]: ScreenAccess.Control }),\n }),\n processes: async (ctx, rawState, request): Promise<ProcessInspectionResultIface> => {\n const sandbox = await runningSandbox(ctx, stateOf(rawState));\n if (request.operation === ProcessInspectionOperation.Available)\n return { available: sandbox != null, canStop: true };\n if (sandbox == null) throw new Error('this sandbox is not running');\n if (request.operation === ProcessInspectionOperation.List) {\n const listed = await sandbox.processes.list({ autoResume: false });\n return {\n status: 'available',\n processes: listed.map((entry) => {\n const startedAtMs = entry.startedAt == null ? 0 : Date.parse(entry.startedAt);\n return {\n id: entry.processId,\n bootId: sandbox.id,\n command: entry.command,\n leaderPid: entry.pid,\n state: entry.running ? 'running' : 'exited',\n keepsAwake: false,\n createdAtMs: startedAtMs,\n updatedAtMs: startedAtMs,\n endedAtMs: null,\n cpuUsec: null,\n memoryBytes: null,\n memoryPeakBytes: null,\n ioReadBytes: null,\n ioWriteBytes: null,\n processCount: null,\n };\n }),\n nextCursor: null,\n };\n }\n if (request.operation === ProcessInspectionOperation.Stop) {\n if (request.bootId !== sandbox.id) return { stopped: false };\n try {\n const process = await sandbox.attach(request.processId);\n await process.kill(ProcessSignal.Kill);\n process.detach();\n return { stopped: true };\n } catch (cause) {\n if (isRouterNotFound(cause)) return { stopped: false };\n throw cause;\n }\n }\n throw new Error('process details are not available through the Sandbox Router');\n },\n artifactKey: async (ctx) => keyFor(seedsFor(ctx)),\n // Builds the snapshot an environment with build steps needs, or prepares its image so it\n // is ready ahead of the first attach.\n prepare: async (ctx) => {\n const seedFiles = seedsFor(ctx);\n const key = await keyFor(seedFiles);\n const seedArtifact = await sandboxSeedArtifact(ctx, seedFiles);\n const router = config.router(ctx);\n if (routedNeedsBuild(options.build) && options.build != null) {\n const baseKey = await keyFor({});\n const cached = artifactSchema.safeParse(await ctx.artifacts?.get(baseKey));\n // A cached base is used while its snapshot is ready; one that is gone is built again.\n if (\n cached.success &&\n cached.data.base.kind === 'snapshot' &&\n (await readySnapshot(router, cached.data.base.snapshotId)) != null\n )\n return { ...cached.data, key, ...seedArtifact };\n const snapshotId =\n (await builtSnapshot(router, baseKey)) ??\n (\n await build({\n ctx,\n router,\n image,\n build: options.build,\n machine,\n region,\n key: baseKey,\n })\n ).snapshotId;\n const built: RoutedSandboxArtifact = {\n version: 1,\n key: baseKey,\n image: storedImageOf(image),\n seedFiles: {},\n base: { kind: 'snapshot', snapshotId },\n };\n await ctx.artifacts?.put(baseKey, built);\n return { ...built, key, ...seedArtifact };\n }\n let stored: RoutedSandboxArtifact['image'] = null;\n if (typeof image === 'string') stored = image;\n else if (image != null) {\n const record = await router.images.prepare({\n image,\n providers: config.routing?.provider == null ? undefined : [config.routing.provider],\n providerOptions: config.providerOptions,\n });\n const failed = record.builds.filter((entry) => entry.state === ImageBuildState.Failed);\n if (failed.length > 0 && failed.length === record.builds.length)\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n `image ${imageName} failed to build: ${failed.map((entry) => `${entry.provider} ${entry.errorCode ?? 'failed'}`).join(', ')}`,\n );\n // A registered image is created from by its id; a local router keeps the spec.\n stored = record.id.startsWith('simg_') ? record.id : storedImageOf(image);\n }\n ctx.log?.(`sandbox base ${key} is image ${imageName ?? 'default'}`);\n return { version: 1, key, image: stored, ...seedArtifact, base: { kind: 'image' } };\n },\n // Records the sandbox; the first attach creates it. The setup's network policy is checked\n // now so a policy the router cannot enforce never boots.\n create: async (_ctx, { setup }) => {\n const network = routedNetworkPolicyOf(setup);\n const ports = [\n ...new Set(\n (setup?.services ?? []).flatMap((service) =>\n service.port == null ? [] : [service.port],\n ),\n ),\n ];\n return { state: { version: 1, sandboxId: null, network, ports }, region };\n },\n awaitRunning: async (ctx, rawState, awaitOptions) => {\n const state = stateOf(rawState);\n if (state.sandboxId == null)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxNotRunning,\n 'this sandbox has not started yet',\n );\n const sandbox = await findSandbox(config.router(ctx), state.sandboxId);\n if (sandbox == null)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxGone,\n `sandbox ${state.sandboxId} is gone`,\n );\n await awaitSandboxRunning(sandbox, awaitOptions.timeoutMs);\n },\n attach: async (ctx, { artifact: rawArtifact, state: rawState }) => {\n const state = stateOf(rawState);\n const artifact = artifactSchema.safeParse(rawArtifact);\n if (!artifact.success)\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n 'this sandbox base was prepared by another sandbox provider; prepare it again',\n );\n const base = artifact.data.base;\n if (routedNeedsBuild(options.build) && base.kind !== 'snapshot')\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n `sandbox base ${artifact.data.key} was prepared without its build steps; prepare it again`,\n );\n const router = config.router(ctx);\n const env = platformProcessEnvironment(ctx, {});\n const policy = withPlatformEgressHosts(ctx, state.network);\n const network = routerNetworkOf(policy);\n const existing =\n state.sandboxId == null ? null : await findSandbox(router, state.sandboxId);\n let sandbox: SandboxHandleIface;\n let booted: boolean;\n if (existing != null) {\n sandbox = existing;\n if (existing.info.state === SandboxState.Failed)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxGone,\n `sandbox ${existing.id} failed${existing.info.nativeError == null ? '' : `: ${existing.info.nativeError}`}; its disk is kept for recovery through the router`,\n );\n if (existing.info.state === SandboxState.Paused)\n booted = (await existing.resume()).coldRestart;\n else if (existing.info.state === SandboxState.Stopped) {\n await existing.start();\n booted = true;\n } else booted = existing.info.state === SandboxState.Creating;\n } else {\n // A sandbox the state named but that no longer exists comes back empty: the attach\n // reports a fresh disk.\n booted = true;\n const source =\n base.kind === 'snapshot' ? base.snapshotId : canonicalJson(artifact.data.image);\n // A retry of this attach makes the same request; one after the sandbox was deleted, a\n // new one.\n const idempotencyKey = `agent-sandbox-${(await sha256Hex(`${ctx.sandboxId}:${state.sandboxId ?? 'first'}:${source}`)).slice(0, 32)}`;\n try {\n sandbox = await router.sandboxes.create(\n routed({\n ...(base.kind === 'snapshot'\n ? { snapshot: base.snapshotId }\n : { image: imageFromArtifact(artifact.data.image) }),\n ...sizeOf(machine),\n network,\n lifecycle: {\n // Idle must keep files: the sandbox is deleted only by its owner.\n idle: { afterS: idleTimeoutFor(ctx), action: IdleAction.Pause },\n autoResume: true,\n ...(config.maxLifetime === undefined ? {} : { max: config.maxLifetime }),\n },\n labels: { ...config.labels, [SANDBOX_LABEL]: ctx.sandboxId },\n region: region ?? undefined,\n idempotencyKey,\n }),\n );\n } catch (cause) {\n if (base.kind === 'snapshot' && isRouterNotFound(cause))\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n `sandbox snapshot ${base.snapshotId} is gone; prepare it again`,\n );\n throw cause;\n }\n }\n const fresh = existing == null;\n log('routed_sandbox.attached', { sandboxId: sandbox.id, fresh, booted });\n try {\n await awaitSandboxRunning(sandbox, runningWaitMs);\n // A reused sandbox keeps whatever policy it last ran under; it gets the setup's again.\n if (!fresh) await sandbox.network.set(network);\n await reportPlatformNetworkPolicy(ctx, policy);\n // The platform's files and seeds are written through the provider's own session,\n // never through a host's grant.\n const setup = createRouterSession({\n sandbox,\n description: `setup of ${sandbox.id}`,\n workspaceRoot: WORKSPACE_ROOT,\n baseEnv: env,\n network: noNetwork,\n });\n await writePlatformFiles(ctx, setup);\n // A new disk gets the workspace seeds once.\n if (fresh) {\n const seedMarker = `${WORKSPACE_ROOT}/.final/workspace-prepared/${await sha256Hex(artifact.data.key)}`;\n if ((await setup.stat({ path: seedMarker })) == null) {\n await materializeSandboxSeeds({\n sandbox: setup,\n root: WORKSPACE_ROOT,\n files: await sandboxSeedFilesForAttach(ctx, artifact.data),\n });\n await setup.writeTextFile({ path: seedMarker, content: 'complete' });\n }\n }\n const handle = await buildHandle({\n ctx,\n sandbox,\n env,\n ports: state.ports,\n passive: false,\n });\n return {\n handle,\n region: sandbox.info.region,\n state: { ...state, sandboxId: sandbox.id },\n fresh,\n booted,\n };\n } catch (error) {\n // No state reaches the caller on failure; remove only a sandbox this attach created.\n if (fresh) {\n try {\n await sandbox.delete();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n `sandbox ${sandbox.id} attach and cleanup failed`,\n );\n }\n }\n throw error;\n }\n },\n attachPassive: async (ctx, { state: rawState }) => {\n const state = stateOf(rawState);\n const sandbox = await runningSandbox(ctx, state);\n if (sandbox == null)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxNotRunning,\n 'sandbox is not running for passive access',\n );\n return buildHandle({\n ctx,\n sandbox,\n env: platformProcessEnvironment(ctx, {}),\n ports: state.ports,\n passive: true,\n });\n },\n // The sandbox pauses on its own idle lifecycle; nothing to do.\n detach: async (_ctx, { state }) => stateOf(state),\n park: async (ctx, { state: rawState }) => {\n const state = stateOf(rawState);\n if (state.sandboxId == null) return state;\n const sandboxId = state.sandboxId;\n const failures: unknown[] = [];\n try {\n await closeMcp(sandboxId);\n } catch (cause) {\n failures.push(cause);\n }\n const atRest = (current: SandboxHandleIface | null) =>\n current == null ||\n current.info.state === SandboxState.Paused ||\n current.info.state === SandboxState.Stopped ||\n current.info.state === SandboxState.Failed;\n try {\n const router = config.router(ctx);\n const current = await findSandbox(router, sandboxId);\n if (atRest(current)) log('routed_sandbox.park_at_rest', { sandboxId });\n else if (current != null) {\n try {\n await current.pause();\n } catch (error) {\n // Parked if it came to rest meanwhile (an idle pause, a delete); otherwise the\n // pause did not happen and park is retried.\n if (!atRest(await findSandbox(router, sandboxId))) throw error;\n log('routed_sandbox.park_at_rest', { sandboxId });\n }\n }\n } catch (cause) {\n failures.push(cause);\n }\n settledFailures(failures, 'Sandbox pause failed');\n return state;\n },\n delete: async (ctx, { state: rawState }) => {\n const state = stateOf(rawState);\n const router = config.router(ctx);\n const failures: unknown[] = [];\n if (state.sandboxId != null)\n try {\n await closeMcp(state.sandboxId);\n } catch (cause) {\n failures.push(cause);\n }\n // Every router sandbox this platform sandbox had, including one an interrupted attach\n // created before its id was recorded.\n try {\n const { deleted } = await router.sandboxes.deleteByLabels({\n labels: { [SANDBOX_LABEL]: ctx.sandboxId },\n });\n log('routed_sandbox.delete', { deleted: deleted.join(',') });\n if (state.sandboxId != null && !deleted.includes(state.sandboxId)) {\n const sandbox = await findSandbox(router, state.sandboxId);\n await sandbox?.delete();\n }\n } catch (cause) {\n if (!isRouterNotFound(cause)) failures.push(cause);\n }\n settledFailures(failures, 'Sandbox delete or MCP cleanup failed');\n },\n };\n };\n\n return defineSandboxProvider({\n name: config.name ?? ROUTED_SANDBOX_PROVIDER,\n stateProtocolVersion: 1,\n environment,\n });\n};\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,YAAY,aAAa,cAAc,mBAAmB;AACnE,SAAS,wBAAyD;AAClE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAYK;AACP,SAAS,qBAAqB;AAC9B;AAAA,EACE,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,OASK;AACP,YAAY,OAAO;AACnB,SAAS,iCAA+D;AACxE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AASA,MAAM,iBAAiB;AAEvB,MAAM,gBAAgB;AAE7B,MAAM,+BAA+B,KAAK;AAC1C,MAAM,8BAA8B,IAAI;AACxC,MAAM,+BAA+B,IAAI,KAAK;AAE9C,MAAM,aAAa;AAGnB,MAAM,oBAAoB;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,uBAAuB;AAE7B,MAAM,mBAAmB,KAAK;AAC9B,MAAM,yBAAyB,IAAI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ectSchema, type JsonObject, type JsonValue } from '@finalai/agent-provider';\nimport {\n defineSandboxProvider,\n materializeSandboxSeeds,\n NetworkPolicy,\n platformProcessEnvironment,\n PortProtocol,\n ProcessInspectionOperation,\n SandboxSnapshotOperation,\n reportPlatformNetworkPolicy,\n SandboxCapability,\n sandboxSeedArtifact,\n sandboxSeedArtifactSchema,\n sandboxSeedFiles,\n sandboxSeedFilesForAttach,\n sandboxSeedIdentity,\n withPlatformEgressHosts,\n writePlatformFiles,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type ProcessInspectionResultIface,\n type SandboxEnvironmentImplementationIface,\n type SandboxPrepareContextIface,\n type SandboxProviderContextIface,\n type SandboxProviderHandleIface,\n type SandboxProviderIface,\n type SandboxResourceContextIface,\n type SandboxSetupIface,\n type SandboxSnapshotResponseIface,\n} from '@finalai/agent-provider/sandbox';\nimport { bytesToBase64 } from '@finalai/agent-provider/sandbox/bytes';\nimport {\n Capability as RouterCapability,\n DesktopState,\n IdleAction,\n ImageBuildState,\n image as routerImage,\n PortAuth,\n ProcessSignal,\n SandboxState,\n type CreateSandboxOptionsIface,\n type ImageBuilderIface,\n type ImageSpecIface,\n type LifecycleOptionsIface,\n type RoutingOptionsIface,\n type SnapshotInfoIface,\n type SandboxHandleIface,\n type SandboxRouterIface,\n} from '@finalai/sandbox-router';\nimport * as z from 'zod';\nimport { createComputerUseEndpoint, type ComputerUseCommandIface } from \"./computer-use.mjs\";\nimport {\n ROUTED_SANDBOX_PROVIDER,\n routedEnvironmentSchema,\n routedNeedsBuild,\n type RoutedBuildIface,\n type RoutedEnvironmentIface,\n type RoutedMachineIface,\n} from \"./environment.mjs\";\nimport { routerNetworkOf } from \"./network.mjs\";\nimport {\n createRouterSession,\n isRouterNotFound,\n isRouterUnsupported,\n readOnlySession,\n resolvePosixPath,\n statOf,\n entryTypeOf,\n} from \"./session.mjs\";\n\n// The `routed` sandbox: an agent sandbox created and driven through the Sandbox Router, on\n// whichever provider the host's routing selects. A sandbox is one router sandbox: `create`\n// records it and the first `attach` makes it, so creating a sandbox boots nothing. An\n// environment with build steps is built once on a builder sandbox and snapshotted; its\n// sandboxes start from the snapshot. The setup's network policy is a create option; its\n// repositories, steps and services are applied by the platform through the handle.\n\nexport const WORKSPACE_ROOT = '/workspaces';\n// The label naming the platform sandbox a router sandbox serves.\nexport const SANDBOX_LABEL = 'agent-sandbox';\n\nconst DEFAULT_IDLE_TIMEOUT_SECONDS = 15 * 60;\nconst IDLE_TIMEOUT_MARGIN_SECONDS = 5 * 60;\nconst BUILDER_IDLE_TIMEOUT_SECONDS = 2 * 60 * 60;\n// Builds run from here.\nconst BUILD_ROOT = '/tmp/agent-sandbox-build';\n// Removed from a builder before its snapshot: the build's own files and credentials a step may\n// have left in the home directory.\nconst BUILD_SCRUB_PATHS = [\n '/tmp/*',\n '$HOME/.bash_history',\n '$HOME/.git-credentials',\n '$HOME/.config/gh/hosts.yml',\n '$HOME/.npmrc',\n '$HOME/.pypirc',\n '$HOME/.cargo/credentials',\n '$HOME/.cargo/credentials.toml',\n '$HOME/.docker/config.json',\n '$HOME/.netrc',\n];\n// Bumped when the meaning of the build inputs changes (forces rebuilds). 2: keys must differ from\n// other providers' artifacts a host kept under the same environment (they named images, not\n// router images).\nconst ARTIFACT_KEY_VERSION = 2;\n// How long a port endpoint's token lasts, and how long before it expires it is renewed.\nconst PORT_TOKEN_TTL_S = 60 * 60;\nconst PORT_ENDPOINT_RENEW_MS = 5 * 60_000;\nconst RUNNING_POLL_MAX_MS = 5_000;\n// How long a build waits for its snapshot to be ready.\nconst SNAPSHOT_READY_WAIT_MS = 30 * 60_000;\n// The vCPUs a sandbox bursts to when neither its environment nor the host names any (the\n// router's default size).\nconst DEFAULT_CPU_LIMIT = 2;\n// The label naming the build a builder sandbox runs.\nconst BUILD_LABEL = 'agent-sandbox-build';\n// Largest snapshot read of one file, and most entries one directory read returns.\nconst SNAPSHOT_READ_MAX_BYTES = 1024 * 1024;\nconst SNAPSHOT_DIRECTORY_LIMIT = 1000;\n\nexport interface RoutedSandboxLogIface {\n (message: string, fields?: Record<string, string | number | boolean | null>): void;\n}\n\nexport interface RoutedSandboxProviderConfigIface {\n // The name the provider is registered under (default `routed`).\n name?: string;\n // The router a call acts through: the host supplies credentials that act for the call's\n // project (`ctx.projectId`), such as `createSandboxRouter({ apiKey: () => tokenFor(ctx) })`.\n router: (ctx: SandboxProviderContextIface) => SandboxRouterIface;\n // Routing and provider options for every create.\n routing?: RoutingOptionsIface;\n providerOptions?: Record<string, unknown>;\n // The image of an environment that names none; absent, the provider's default image.\n defaultImage?: string;\n // Image names environments may use, as router images (a spec or a registered `simg_\u2026` id).\n images?: Record<string, ImageBuilderIface | ImageSpecIface | string>;\n // Defaults for what an environment leaves out.\n machine?: RoutedMachineIface;\n // The vCPUs a sandbox is guaranteed; it bursts to its machine's `vcpu` when the host has idle\n // CPU (capability `burst`). Absent, it is guaranteed its `vcpu`.\n cpuRequest?: number;\n // The maximum lifetime of agent sandboxes, in the router's lifecycle terms. Left out, the\n // provider's default applies; null turns it off where the provider allows. A provider whose\n // default deletes the sandbox loses its files, so set it for those.\n maxLifetime?: LifecycleOptionsIface['max'];\n // How long the token a port endpoint carries lasts (default an hour), on providers whose port\n // tokens expire (capability `portTokens`); renewed before it ends.\n portTokenTtlS?: number;\n region?: string;\n // Labels every sandbox carries, besides `agent-sandbox`.\n labels?: Record<string, string>;\n // The computer-use MCP server desktop images run; without it, sandboxes offer no computer use.\n computerUse?: ComputerUseCommandIface;\n // How long attach waits for a sandbox to run (default 5 min), polled from runningPollMs\n // (default 250 ms), doubling to 5 s.\n runningWaitMs?: number;\n runningPollMs?: number;\n log?: RoutedSandboxLogIface;\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport enum RoutedSandboxErrorCode {\n ArtifactUnavailable = 'artifact_unavailable',\n SandboxGone = 'sandbox_gone',\n SandboxNotRunning = 'sandbox_not_running',\n InvalidEnvironment = 'invalid_environment',\n BuildFailed = 'build_failed',\n}\n\nexport interface RoutedSandboxErrorIface extends Error {\n code: RoutedSandboxErrorCode;\n}\n\nconst routedSandboxError = (\n code: RoutedSandboxErrorCode,\n message: string,\n): RoutedSandboxErrorIface =>\n Object.assign(new Error(message), { name: 'RoutedSandboxError', code });\n\n// What sandboxes start from: an image (a registered id or a spec; null for the provider's\n// default), or the snapshot an environment's build was captured as.\nconst artifactSchema = sandboxSeedArtifactSchema.extend({\n version: z.literal(1),\n key: z.string(),\n image: z.union([z.string(), jsonObjectSchema]).nullable(),\n base: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('image') }),\n z.object({ kind: z.literal('snapshot'), snapshotId: z.string() }),\n ]),\n});\n\nconst networkPolicySchema = z.object({\n mode: z.nativeEnum(NetworkPolicy),\n allow: z.array(z.string()).optional(),\n});\n\nconst stateSchema = z.object({\n version: z.literal(1),\n // The router sandbox; null until the first attach creates it.\n sandboxId: z.string().nullable(),\n // The setup's network policy, enforced from the sandbox's first boot.\n network: networkPolicySchema,\n // Ports the setup's services listen on.\n ports: z.array(z.number().int()).default([]),\n});\n\nexport type RoutedSandboxArtifact = z.infer<typeof artifactSchema>;\nexport type RoutedSandboxState = z.infer<typeof stateSchema>;\n\nexport interface RoutedSandboxSessionIface extends NetworkSandboxSessionIface {\n // What this sandbox's handle offers (the host reports it).\n readonly capabilities: readonly SandboxCapability[];\n}\n\nexport type RoutedSandboxProviderIface = SandboxProviderIface<\n JsonValue,\n RoutedSandboxArtifact,\n RoutedSandboxState,\n RoutedSandboxSessionIface\n>;\n\nconst sha256Hex = async (text: string): Promise<string> => {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n};\n\nconst canonicalJson = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n if (value != null && typeof value === 'object')\n return `{${Object.entries(value)\n .filter(([, entry]) => entry !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`)\n .join(',')}}`;\n return JSON.stringify(value);\n};\n\n// A router image as an artifact stores it.\nconst storedImageOf = (image: ImageSpecIface | string | null): string | JsonObject | null =>\n image == null || typeof image === 'string'\n ? image\n : jsonObjectSchema.parse(JSON.parse(JSON.stringify(image)));\n\nconst errorText = (cause: unknown): string =>\n cause instanceof Error ? cause.message : String(cause);\n\n// The setup's network as a router sandbox enforces it from creation: every host, none, or an\n// allowlist. The router has no per-host deny list, so a setup naming one is refused at create\n// rather than run unenforced.\nexport const routedNetworkPolicyOf = (setup: SandboxSetupIface | null): NetworkPolicyIface => {\n const network = setup?.network;\n if (network == null) return { mode: NetworkPolicy.AllowAll };\n if ((network.deny ?? []).length > 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.InvalidEnvironment,\n 'A routed sandbox cannot deny individual hosts; list the hosts to allow instead',\n );\n if (network.allow == null) return { mode: NetworkPolicy.AllowAll };\n return network.allow.length === 0\n ? { mode: NetworkPolicy.DenyAll }\n : { mode: NetworkPolicy.Allowlist, allow: [...network.allow] };\n};\n\n// The base's identity: a hash of the build-time inputs only, so identical environments share\n// one snapshot.\nconst artifactKeyOf = async (inputs: {\n image: string | null;\n build: RoutedBuildIface | undefined;\n machine: RoutedMachineIface | undefined;\n}): Promise<string> => {\n if (!routedNeedsBuild(inputs.build)) {\n const hex = await sha256Hex(canonicalJson({ v: ARTIFACT_KEY_VERSION, image: inputs.image }));\n return `img-${hex.slice(0, 16)}`;\n }\n const hex = await sha256Hex(\n canonicalJson({\n v: ARTIFACT_KEY_VERSION,\n image: inputs.image,\n build: { steps: inputs.build?.steps ?? [], verify: inputs.build?.verify ?? [] },\n machine: inputs.machine ?? null,\n }),\n );\n return `snap-${hex.slice(0, 16)}`;\n};\n\n// A setup session serves no ports and leaves the sandbox's lifecycle alone.\nconst noNetwork = {\n ports: [],\n getPortEndpoint: async (): Promise<never> => {\n throw new Error('setup sessions expose no ports');\n },\n stop: async () => undefined,\n destroy: async () => undefined,\n};\n\nconst defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport const createRoutedSandboxProvider = (\n config: RoutedSandboxProviderConfigIface,\n): RoutedSandboxProviderIface => {\n const log: RoutedSandboxLogIface = config.log ?? (() => undefined);\n const now = config.now ?? (() => Date.now());\n const sleep = config.sleep ?? defaultSleep;\n const runningWaitMs = config.runningWaitMs ?? 5 * 60_000;\n\n // A name as the router image it stands for; null for the provider's default image.\n const routerImageOf = (name: string | null): ImageSpecIface | string | null => {\n if (name == null) return null;\n const alias = config.images?.[name];\n if (alias != null)\n return typeof alias === 'string' || !('toJSON' in alias) ? alias : alias.toJSON();\n if (name.startsWith('simg_')) return name;\n return routerImage.from(name).toJSON();\n };\n\n // A stored image: a registered id, or a spec checked again. A stored name (not a `simg_` id) is\n // resolved again as an environment's image name would be.\n const imageFromArtifact = (\n stored: RoutedSandboxArtifact['image'],\n ): ImageBuilderIface | string | undefined => {\n if (stored == null) return undefined;\n if (typeof stored !== 'string') return routerImage.fromJSON(stored);\n if (stored.startsWith('simg_')) return stored;\n const resolved = routerImageOf(stored);\n if (resolved == null) return undefined;\n return typeof resolved === 'string' ? resolved : routerImage.fromJSON(resolved);\n };\n\n const sizeOf = (machine: RoutedMachineIface | undefined) => {\n const limit = machine?.vcpu;\n const request = config.cpuRequest;\n return {\n cpu:\n request == null\n ? limit\n : {\n request: Math.min(request, limit ?? DEFAULT_CPU_LIMIT),\n limit: limit ?? DEFAULT_CPU_LIMIT,\n },\n memoryMib: machine?.memoryMb,\n diskGib: machine?.diskGb,\n };\n };\n\n const routed = (\n options: Omit<CreateSandboxOptionsIface, 'routing' | 'providerOptions'>,\n ): CreateSandboxOptionsIface => ({\n ...options,\n routing: config.routing,\n providerOptions: config.providerOptions,\n });\n\n // The router sandbox, or null when it no longer exists.\n const findSandbox = async (\n router: SandboxRouterIface,\n id: string,\n ): Promise<SandboxHandleIface | null> => {\n try {\n const sandbox = await router.sandboxes.get(id);\n return sandbox.info.state === SandboxState.Deleted ? null : sandbox;\n } catch (cause) {\n if (isRouterNotFound(cause)) return null;\n throw cause;\n }\n };\n\n // Commands and file calls need a running sandbox (they never wake one), so nothing touches\n // it before this resolves.\n const awaitSandboxRunning = async (\n sandbox: SandboxHandleIface,\n timeoutMs: number,\n ): Promise<void> => {\n const deadline = now() + timeoutMs;\n let pollMs = config.runningPollMs ?? 250;\n let info = sandbox.info;\n for (;;) {\n if (info.state === SandboxState.Running) return;\n if (info.state === SandboxState.Deleted || info.state === SandboxState.Failed)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxGone,\n `sandbox ${sandbox.id} is ${info.state}${info.nativeError == null ? '' : `: ${info.nativeError}`}`,\n );\n const left = deadline - now();\n if (left <= 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxNotRunning,\n `sandbox ${sandbox.id} was not running within ${Math.round(timeoutMs / 1000)} s (it is ${info.state})`,\n );\n await sleep(Math.min(pollMs, left));\n pollMs = Math.min(pollMs * 2, RUNNING_POLL_MAX_MS);\n info = await sandbox.refresh();\n }\n };\n\n const mcpClosers = new Map<string, Set<() => Promise<void>>>();\n const closeMcp = async (sandboxId: string) => {\n const results = await Promise.allSettled(\n [...(mcpClosers.get(sandboxId) ?? [])].map((close) => close()),\n );\n for (const result of results) if (result.status === 'rejected') throw result.reason;\n };\n\n const settledFailures = (failures: unknown[], message: string) => {\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw new AggregateError(failures, message);\n };\n\n // The desktop's state, or null for a provider or image without one.\n const desktopState = async (sandbox: SandboxHandleIface): Promise<DesktopState | null> => {\n try {\n return (\n await Promise.race([\n sandbox.desktop.status(),\n new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error('desktop status timed out')), 2_000),\n ),\n ])\n ).state;\n } catch {\n return null;\n }\n };\n\n // A build's snapshot once it is ready, or null when it is gone or failed (a failed one is\n // deleted). A provider that cannot read snapshots has them ready when `snapshot()` returns.\n const readySnapshot = async (\n router: SandboxRouterIface,\n snapshotId: string,\n ): Promise<string | null> => {\n const deadline = now() + SNAPSHOT_READY_WAIT_MS;\n let pollMs = config.runningPollMs ?? 250;\n for (;;) {\n let info: SnapshotInfoIface;\n try {\n info = await router.snapshots.get(snapshotId);\n } catch (cause) {\n if (isRouterNotFound(cause)) return null;\n if (isRouterUnsupported(cause)) return snapshotId;\n throw cause;\n }\n if (info.state === 'ready') return snapshotId;\n if (info.state === 'failed') {\n await deleteSnapshot(router, snapshotId);\n return null;\n }\n const left = deadline - now();\n if (left <= 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n `sandbox snapshot ${snapshotId} was not ready within ${Math.round(SNAPSHOT_READY_WAIT_MS / 60_000)} min`,\n );\n await sleep(Math.min(pollMs, left));\n pollMs = Math.min(pollMs * 2, RUNNING_POLL_MAX_MS);\n }\n };\n\n const deleteSnapshot = async (router: SandboxRouterIface, snapshotId: string) => {\n try {\n await router.snapshots.delete(snapshotId);\n } catch (error) {\n if (!isRouterNotFound(error))\n log('routed_sandbox.snapshot_delete_failed', { snapshotId, error: errorText(error) });\n }\n };\n\n // A snapshot an earlier build of this key left, for a key the artifact cache lost or a build\n // another prepare ran meanwhile: the newest ready one (waiting for one still being captured).\n // Failed ones are deleted. Found by name, which every provider keeps (not all label\n // snapshots); a provider may suffix a name already taken.\n const builtSnapshot = async (router: SandboxRouterIface, key: string): Promise<string | null> => {\n let listed: SnapshotInfoIface[];\n try {\n listed = await router.snapshots.list({ provider: config.routing?.provider });\n } catch (cause) {\n if (isRouterUnsupported(cause)) return null;\n throw cause;\n }\n const newestFirst = listed\n .filter((snapshot) => snapshot.name === key || snapshot.name.startsWith(`${key}-`))\n .sort((a, b) => (b.createdAt ?? '').localeCompare(a.createdAt ?? ''));\n for (const snapshot of newestFirst) {\n if (snapshot.state === 'failed') await deleteSnapshot(router, snapshot.id);\n else if ((await readySnapshot(router, snapshot.id)) != null) return snapshot.id;\n }\n return null;\n };\n\n const buildHandle = async (args: {\n ctx: Pick<SandboxResourceContextIface, 'platformEgressHosts'>;\n sandbox: SandboxHandleIface;\n env: () => Promise<Record<string, string>>;\n ports: readonly number[];\n // A viewer's handle: it changes nothing, and stopping it leaves the sandbox alone.\n passive: boolean;\n }): Promise<SandboxProviderHandleIface<RoutedSandboxSessionIface>> => {\n const { sandbox } = args;\n const endpoints = new Map<\n number,\n { url: string; headers: Record<string, string>; renewAtMs: number }\n >();\n // The port's URL and the credential programs send with it, renewed before it expires.\n const portEndpoint = async (port: number) => {\n const cached = endpoints.get(port);\n if (cached != null && cached.renewAtMs > now()) return cached;\n // A provider whose port tokens cannot expire refuses a lifetime, so only those with\n // `portTokens` are asked for one.\n const access = await sandbox.ports.url(\n port,\n sandbox.info.capabilities.includes(RouterCapability.PortTokens)\n ? { ttlS: config.portTokenTtlS ?? PORT_TOKEN_TTL_S }\n : {},\n );\n const headers: Record<string, string> = {};\n if (access.auth === PortAuth.Bearer && access.token != null)\n headers.authorization = `Bearer ${access.token}`;\n else if (access.auth === PortAuth.Header && access.token != null && access.header != null)\n headers[access.header] = access.token;\n else if (access.auth === PortAuth.Cookie)\n throw new Error(`port ${port} is reached only through a browser session`);\n const expiresAtMs = access.expiresAt == null ? null : Date.parse(access.expiresAt);\n const endpoint = {\n url: access.url,\n headers,\n renewAtMs:\n expiresAtMs == null ? Number.POSITIVE_INFINITY : expiresAtMs - PORT_ENDPOINT_RENEW_MS,\n };\n endpoints.set(port, endpoint);\n return endpoint;\n };\n const session = createRouterSession({\n sandbox,\n description: `routed sandbox ${sandbox.id}`,\n workspaceRoot: WORKSPACE_ROOT,\n baseEnv: args.env,\n network: {\n ports: [...args.ports],\n getPortEndpoint: async ({ port, protocol }) => {\n const endpoint = await portEndpoint(port);\n const url =\n protocol === PortProtocol.Ws ? endpoint.url.replace(/^http/, 'ws') : endpoint.url;\n return { url, headers: { ...endpoint.headers } };\n },\n stop: async () => {\n const failures: unknown[] = [];\n for (const finish of [() => closeMcp(sandbox.id), () => sandbox.stop()])\n try {\n await finish();\n } catch (cause) {\n if (!isRouterNotFound(cause)) failures.push(cause);\n }\n settledFailures(failures, 'Sandbox stop or MCP cleanup failed');\n },\n destroy: async () => {\n const failures: unknown[] = [];\n for (const finish of [() => closeMcp(sandbox.id), () => sandbox.delete()])\n try {\n await finish();\n } catch (cause) {\n if (!isRouterNotFound(cause)) failures.push(cause);\n }\n settledFailures(failures, 'Sandbox delete or MCP cleanup failed');\n },\n },\n });\n const desktop = await desktopState(sandbox);\n const desktopUp = desktop === DesktopState.Running || desktop === DesktopState.Starting;\n const computerUse =\n args.passive || !desktopUp || config.computerUse == null\n ? null\n : createComputerUseEndpoint({ sandbox, server: config.computerUse, cwd: WORKSPACE_ROOT });\n const closeComputerUse = async () => {\n try {\n await computerUse?.close();\n } catch (error) {\n log('computer_use.close_failed', { sandboxId: sandbox.id, error: errorText(error) });\n }\n const closers = mcpClosers.get(sandbox.id);\n closers?.delete(closeComputerUse);\n if (closers?.size === 0) mcpClosers.delete(sandbox.id);\n };\n if (computerUse != null) {\n const closers = mcpClosers.get(sandbox.id) ?? new Set<() => Promise<void>>();\n closers.add(closeComputerUse);\n mcpClosers.set(sandbox.id, closers);\n }\n const capabilities = [SandboxCapability.Files, SandboxCapability.Ports];\n if (desktopUp) capabilities.push(SandboxCapability.Screen);\n if (computerUse != null) capabilities.push(SandboxCapability.ComputerUse);\n if (!args.passive)\n capabilities.push(\n SandboxCapability.Process,\n SandboxCapability.DurableProcesses,\n SandboxCapability.NetworkPolicy,\n );\n const full: RoutedSandboxSessionIface = {\n ...session,\n setNetworkPolicy: async (policy) => {\n if (args.passive) throw new Error('this sandbox handle is read-only');\n await sandbox.network.set(routerNetworkOf(withPlatformEgressHosts(args.ctx, policy)));\n },\n capabilities,\n };\n if (computerUse != null) full.computerUse = async () => computerUse.endpoint;\n // View-only unless input control is asked for, which the host grants with execute access.\n if (desktopUp)\n full.screen = async (options) => {\n const screen = await sandbox.desktop.screen({ viewOnly: options?.viewOnly !== false });\n if (screen.token == null || screen.expiresAt == null)\n throw new Error('the screen session has no token or expiry');\n return { url: screen.url, token: screen.token, expiresAt: screen.expiresAt };\n };\n return {\n sandbox: args.passive ? readOnlySession(full) : full,\n onSandboxStop: closeComputerUse,\n onSandboxDelete: async () => {\n const failures: unknown[] = [];\n for (const finish of [closeComputerUse, () => sandbox.delete()])\n try {\n await finish();\n } catch (cause) {\n if (!isRouterNotFound(cause)) failures.push(cause);\n }\n settledFailures(failures, 'Sandbox delete or MCP cleanup failed');\n },\n onRuntimeShutdown: closeComputerUse,\n };\n };\n\n // Runs build.steps, then build.verify, on a builder sandbox of the environment's image and\n // snapshots it; sandboxes start from the snapshot.\n const build = async (args: {\n ctx: SandboxPrepareContextIface;\n router: SandboxRouterIface;\n image: ImageSpecIface | string | null;\n build: RoutedBuildIface;\n machine: RoutedMachineIface | undefined;\n region: string | null;\n key: string;\n }): Promise<{ snapshotId: string }> => {\n const { ctx, router, key } = args;\n // One builder per attempt: a retry after a failed build starts clean.\n const builder = await router.sandboxes.create(\n routed({\n image: args.image ?? undefined,\n ...sizeOf(args.machine),\n lifecycle: {\n idle: { afterS: BUILDER_IDLE_TIMEOUT_SECONDS, action: IdleAction.Delete },\n autoResume: false,\n },\n labels: { ...config.labels, [BUILD_LABEL]: key },\n region: args.region ?? undefined,\n }),\n );\n ctx.log?.(`building sandbox snapshot ${key} on ${builder.id}`);\n try {\n const run = (command: string, timeoutMs?: number) =>\n builder.run(command, { cwd: BUILD_ROOT, timeoutMs, autoResume: false });\n await builder.files.mkdir(BUILD_ROOT, { recursive: true });\n const steps = [\n ...args.build.steps.map((step) => ({ step, label: 'build step' })),\n ...args.build.verify.map((step) => ({ step, label: 'verify step' })),\n ];\n for (const [index, { step, label }] of steps.entries()) {\n ctx.log?.(`${label} ${index + 1}/${steps.length}`);\n const result = await run(`set -eu\\n${step.run}`, step.timeoutMinutes * 60_000);\n if (result.exitCode !== 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.BuildFailed,\n `${label} ${index + 1} failed (exit ${result.exitCode ?? result.signal ?? result.reason}): ${result.stderr.trim().slice(-2000)}`,\n );\n }\n const scrubbed = await builder.run(\n `rm -rf ${BUILD_SCRUB_PATHS.join(' ')} \"$HOME/.ssh\" \"$HOME/.aws\" \"$HOME/.config/gcloud\" \"$HOME/.azure\"`,\n { cwd: '/', autoResume: false },\n );\n if (scrubbed.exitCode !== 0)\n throw routedSandboxError(\n RoutedSandboxErrorCode.BuildFailed,\n `could not clean the builder before its snapshot: ${scrubbed.stderr.trim().slice(-2000)}`,\n );\n // Retained until deleted: sandboxes start from it for as long as the artifact is cached.\n // Named for the build, so a later prepare finds it again.\n const { snapshotId } = await builder.snapshot({ name: key, retain: true });\n if ((await readySnapshot(router, snapshotId)) == null)\n throw routedSandboxError(\n RoutedSandboxErrorCode.BuildFailed,\n `sandbox snapshot ${snapshotId} of ${key} failed`,\n );\n ctx.log?.(`captured sandbox snapshot ${key} as ${snapshotId}`);\n return { snapshotId };\n } finally {\n // The snapshot holds the build; the builder is not part of it.\n try {\n await builder.delete();\n } catch (error) {\n log('routed_sandbox.builder_delete_failed', {\n sandboxId: builder.id,\n error: errorText(error),\n });\n }\n }\n };\n\n const environment = (\n rawOptions?: JsonValue,\n ): SandboxEnvironmentImplementationIface<\n RoutedSandboxArtifact,\n RoutedSandboxState,\n RoutedSandboxSessionIface\n > => {\n const parsed = routedEnvironmentSchema.safeParse(rawOptions ?? {});\n if (!parsed.success)\n throw routedSandboxError(\n RoutedSandboxErrorCode.InvalidEnvironment,\n `invalid routed environment: ${parsed.error.message}`,\n );\n const options: RoutedEnvironmentIface = parsed.data;\n const imageName = options.image ?? config.defaultImage ?? null;\n const image = routerImageOf(imageName);\n const machine = options.machine ?? config.machine;\n const region = options.region ?? config.region ?? null;\n // Outlasts the platform's own idle parking, so the platform parks first.\n const idleTimeoutFor = (ctx: SandboxResourceContextIface): number =>\n options.idleTimeoutSeconds ??\n (ctx.lifecycle.parkAfterIdleMs == null\n ? DEFAULT_IDLE_TIMEOUT_SECONDS\n : Math.ceil(ctx.lifecycle.parkAfterIdleMs / 1000) + IDLE_TIMEOUT_MARGIN_SECONDS);\n const seedsFor = (ctx: SandboxPrepareContextIface): Record<string, string> =>\n sandboxSeedFiles({ files: ctx.files, resources: ctx.resources });\n const keyFor = async (files: Record<string, string>): Promise<string> => {\n const baseKey = await artifactKeyOf({ image: imageName, build: options.build, machine });\n return Object.keys(files).length === 0\n ? baseKey\n : `${baseKey}-s${await sha256Hex(sandboxSeedIdentity(files))}`;\n };\n\n const stateOf = (raw: JsonValue): RoutedSandboxState => {\n const state = stateSchema.safeParse(raw);\n if (!state.success)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxGone,\n 'this sandbox was recorded by another sandbox provider; create it again',\n );\n return state.data;\n };\n\n // The running router sandbox a read about an existing sandbox may use, never waking it.\n const runningSandbox = async (\n ctx: SandboxProviderContextIface,\n state: RoutedSandboxState,\n ): Promise<SandboxHandleIface | null> => {\n if (state.sandboxId == null) return null;\n const sandbox = await findSandbox(config.router(ctx), state.sandboxId);\n return sandbox?.info.state === SandboxState.Running ? sandbox : null;\n };\n\n // A parked sandbox's disk, which does not change until it boots again: named by the event\n // that parked it.\n const parkedDisk = async (\n sandbox: SandboxHandleIface,\n ): Promise<{ id: string; capturedAt: string }> => {\n const { events } = await sandbox.events({ limit: 20 });\n const parked = events.find(\n (event) => event.state === SandboxState.Paused || event.state === SandboxState.Stopped,\n );\n return parked == null\n ? {\n id: `${sandbox.id}:${sandbox.info.generation ?? 0}`,\n capturedAt: sandbox.info.createdAt,\n }\n : { id: `${sandbox.id}:${parked.id}`, capturedAt: parked.at };\n };\n\n return {\n // Reads a parked sandbox's workspace without waking it (capability `coldFiles`). Null while\n // it runs, before its first attach, or where the provider cannot read a parked disk.\n readSnapshot: async (ctx, rawState, request) => {\n const state = stateOf(rawState);\n const path = resolvePosixPath(WORKSPACE_ROOT, request.path ?? WORKSPACE_ROOT);\n if (path !== WORKSPACE_ROOT && !path.startsWith(`${WORKSPACE_ROOT}/`))\n throw new Error('snapshot path is outside the workspace');\n if (state.sandboxId == null) return null;\n const sandbox = await findSandbox(config.router(ctx), state.sandboxId);\n if (sandbox == null) throw new Error(`sandbox ${state.sandboxId} no longer exists`);\n const { info } = sandbox;\n const parked = info.state === SandboxState.Paused || info.state === SandboxState.Stopped;\n if (!parked || !info.capabilities.includes(RouterCapability.ColdFiles)) {\n // A later range of a snapshot read must not fall through to a live disk.\n if (request.snapshotId != null)\n throw new Error('the sandbox ran since this snapshot; read it again');\n if (info.state === SandboxState.Failed)\n throw new Error(`sandbox ${sandbox.id} failed; its files cannot be read`);\n return null;\n }\n const snapshot = await parkedDisk(sandbox);\n if (request.snapshotId != null && request.snapshotId !== snapshot.id)\n throw new Error('the sandbox ran since this snapshot; read it again');\n const base = { root: WORKSPACE_ROOT, path, snapshot };\n const cold = { autoResume: false };\n let response: SandboxSnapshotResponseIface;\n if (request.operation === SandboxSnapshotOperation.Stat) {\n const entry = await sandbox.files.stat(path, cold);\n response = {\n ...base,\n result: { operation: request.operation, stat: entry == null ? null : statOf(entry) },\n };\n } else if (request.operation === SandboxSnapshotOperation.ReadDirectory) {\n const page = await sandbox.files.listPage(path, {\n limit: SNAPSHOT_DIRECTORY_LIMIT,\n ...cold,\n });\n response = {\n ...base,\n result: {\n operation: request.operation,\n entries: page.entries.map((entry) => ({\n name: entry.name,\n path: entry.path,\n type: entryTypeOf(entry.kind),\n size: entry.size,\n })),\n truncated: page.nextCursor != null,\n },\n };\n } else {\n const entry = await sandbox.files.stat(path, cold);\n if (entry == null) throw new Error(`${path} does not exist in the snapshot`);\n const offset = request.offset ?? 0;\n const bytes =\n offset >= entry.size\n ? new Uint8Array()\n : await sandbox.files.read(path, {\n offset,\n length: Math.min(\n request.length ?? SNAPSHOT_READ_MAX_BYTES,\n SNAPSHOT_READ_MAX_BYTES,\n ),\n ...cold,\n });\n response = {\n ...base,\n result: {\n operation: request.operation,\n offset,\n size: entry.size,\n contentBase64: bytesToBase64(bytes),\n truncated: offset + bytes.byteLength < entry.size,\n },\n };\n }\n // The sandbox may have woken during the read; what was read is then not this snapshot.\n const after = await sandbox.refresh();\n if (after.state !== info.state || (await parkedDisk(sandbox)).id !== snapshot.id)\n throw new Error('the sandbox ran during this snapshot read; read it again');\n return response;\n },\n capabilities: async () => ({\n [Capability.Files]: FilesAccess.Write,\n [Capability.Shell]: ShellAccess.Execute,\n ...(config.computerUse == null ? {} : { [Capability.ComputerUse]: ScreenAccess.Control }),\n }),\n processes: async (ctx, rawState, request): Promise<ProcessInspectionResultIface> => {\n const sandbox = await runningSandbox(ctx, stateOf(rawState));\n if (request.operation === ProcessInspectionOperation.Available)\n return { available: sandbox != null, canStop: true };\n if (sandbox == null) throw new Error('this sandbox is not running');\n if (request.operation === ProcessInspectionOperation.List) {\n const listed = await sandbox.processes.list({ autoResume: false });\n return {\n status: 'available',\n processes: listed.map((entry) => {\n const startedAtMs = entry.startedAt == null ? 0 : Date.parse(entry.startedAt);\n return {\n id: entry.processId,\n bootId: sandbox.id,\n command: entry.command,\n leaderPid: entry.pid,\n state: entry.running ? 'running' : 'exited',\n keepsAwake: false,\n createdAtMs: startedAtMs,\n updatedAtMs: startedAtMs,\n endedAtMs: null,\n cpuUsec: null,\n memoryBytes: null,\n memoryPeakBytes: null,\n ioReadBytes: null,\n ioWriteBytes: null,\n processCount: null,\n };\n }),\n nextCursor: null,\n };\n }\n if (request.operation === ProcessInspectionOperation.Stop) {\n if (request.bootId !== sandbox.id) return { stopped: false };\n try {\n const process = await sandbox.attach(request.processId);\n await process.kill(ProcessSignal.Kill);\n process.detach();\n return { stopped: true };\n } catch (cause) {\n if (isRouterNotFound(cause)) return { stopped: false };\n throw cause;\n }\n }\n throw new Error('process details are not available through the Sandbox Router');\n },\n artifactKey: async (ctx) => keyFor(seedsFor(ctx)),\n // Builds the snapshot an environment with build steps needs, or prepares its image so it\n // is ready ahead of the first attach.\n prepare: async (ctx) => {\n const seedFiles = seedsFor(ctx);\n const key = await keyFor(seedFiles);\n const seedArtifact = await sandboxSeedArtifact(ctx, seedFiles);\n const router = config.router(ctx);\n if (routedNeedsBuild(options.build) && options.build != null) {\n const baseKey = await keyFor({});\n const cached = artifactSchema.safeParse(await ctx.artifacts?.get(baseKey));\n // A cached base is used while its snapshot is ready; one that is gone is built again.\n if (\n cached.success &&\n cached.data.base.kind === 'snapshot' &&\n (await readySnapshot(router, cached.data.base.snapshotId)) != null\n )\n return { ...cached.data, key, ...seedArtifact };\n const snapshotId =\n (await builtSnapshot(router, baseKey)) ??\n (\n await build({\n ctx,\n router,\n image,\n build: options.build,\n machine,\n region,\n key: baseKey,\n })\n ).snapshotId;\n const built: RoutedSandboxArtifact = {\n version: 1,\n key: baseKey,\n image: storedImageOf(image),\n seedFiles: {},\n base: { kind: 'snapshot', snapshotId },\n };\n await ctx.artifacts?.put(baseKey, built);\n return { ...built, key, ...seedArtifact };\n }\n let stored: RoutedSandboxArtifact['image'] = null;\n if (typeof image === 'string') stored = image;\n else if (image != null) {\n const record = await router.images.prepare({\n image,\n providers: config.routing?.provider == null ? undefined : [config.routing.provider],\n providerOptions: config.providerOptions,\n });\n const failed = record.builds.filter((entry) => entry.state === ImageBuildState.Failed);\n if (failed.length > 0 && failed.length === record.builds.length)\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n `image ${imageName} failed to build: ${failed.map((entry) => `${entry.provider} ${entry.errorCode ?? 'failed'}`).join(', ')}`,\n );\n // A registered image is created from by its id; a local router keeps the spec.\n stored = record.id.startsWith('simg_') ? record.id : storedImageOf(image);\n }\n ctx.log?.(`sandbox base ${key} is image ${imageName ?? 'default'}`);\n return { version: 1, key, image: stored, ...seedArtifact, base: { kind: 'image' } };\n },\n // Records the sandbox; the first attach creates it. The setup's network policy is checked\n // now so a policy the router cannot enforce never boots.\n create: async (_ctx, { setup }) => {\n const network = routedNetworkPolicyOf(setup);\n const ports = [\n ...new Set(\n (setup?.services ?? []).flatMap((service) =>\n service.port == null ? [] : [service.port],\n ),\n ),\n ];\n return { state: { version: 1, sandboxId: null, network, ports }, region };\n },\n awaitRunning: async (ctx, rawState, awaitOptions) => {\n const state = stateOf(rawState);\n if (state.sandboxId == null)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxNotRunning,\n 'this sandbox has not started yet',\n );\n const sandbox = await findSandbox(config.router(ctx), state.sandboxId);\n if (sandbox == null)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxGone,\n `sandbox ${state.sandboxId} is gone`,\n );\n await awaitSandboxRunning(sandbox, awaitOptions.timeoutMs);\n },\n attach: async (ctx, { artifact: rawArtifact, state: rawState }) => {\n const state = stateOf(rawState);\n const artifact = artifactSchema.safeParse(rawArtifact);\n if (!artifact.success)\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n 'this sandbox base was prepared by another sandbox provider; prepare it again',\n );\n const base = artifact.data.base;\n if (routedNeedsBuild(options.build) && base.kind !== 'snapshot')\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n `sandbox base ${artifact.data.key} was prepared without its build steps; prepare it again`,\n );\n const router = config.router(ctx);\n const env = platformProcessEnvironment(ctx, {});\n const policy = withPlatformEgressHosts(ctx, state.network);\n const network = routerNetworkOf(policy);\n const existing =\n state.sandboxId == null ? null : await findSandbox(router, state.sandboxId);\n let sandbox: SandboxHandleIface;\n let booted: boolean;\n if (existing != null) {\n sandbox = existing;\n if (existing.info.state === SandboxState.Failed)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxGone,\n `sandbox ${existing.id} failed${existing.info.nativeError == null ? '' : `: ${existing.info.nativeError}`}; its disk is kept for recovery through the router`,\n );\n if (existing.info.state === SandboxState.Paused)\n booted = (await existing.resume()).coldRestart;\n else if (existing.info.state === SandboxState.Stopped) {\n await existing.start();\n booted = true;\n } else booted = existing.info.state === SandboxState.Creating;\n } else {\n // A sandbox the state named but that no longer exists comes back empty: the attach\n // reports a fresh disk.\n booted = true;\n const source =\n base.kind === 'snapshot' ? base.snapshotId : canonicalJson(artifact.data.image);\n // A retry of this attach makes the same request; one after the sandbox was deleted, a\n // new one.\n const idempotencyKey = `agent-sandbox-${(await sha256Hex(`${ctx.sandboxId}:${state.sandboxId ?? 'first'}:${source}`)).slice(0, 32)}`;\n try {\n sandbox = await router.sandboxes.create(\n routed({\n ...(base.kind === 'snapshot'\n ? { snapshot: base.snapshotId }\n : { image: imageFromArtifact(artifact.data.image) }),\n ...sizeOf(machine),\n network,\n lifecycle: {\n // Idle must keep files: the sandbox is deleted only by its owner.\n idle: { afterS: idleTimeoutFor(ctx), action: IdleAction.Pause },\n autoResume: true,\n ...(config.maxLifetime === undefined ? {} : { max: config.maxLifetime }),\n },\n labels: { ...config.labels, [SANDBOX_LABEL]: ctx.sandboxId },\n region: region ?? undefined,\n idempotencyKey,\n }),\n );\n } catch (cause) {\n if (base.kind === 'snapshot' && isRouterNotFound(cause))\n throw routedSandboxError(\n RoutedSandboxErrorCode.ArtifactUnavailable,\n `sandbox snapshot ${base.snapshotId} is gone; prepare it again`,\n );\n throw cause;\n }\n }\n const fresh = existing == null;\n log('routed_sandbox.attached', { sandboxId: sandbox.id, fresh, booted });\n try {\n await awaitSandboxRunning(sandbox, runningWaitMs);\n // A reused sandbox keeps whatever policy it last ran under; it gets the setup's again.\n if (!fresh) await sandbox.network.set(network);\n await reportPlatformNetworkPolicy(ctx, policy);\n // The platform's files and seeds are written through the provider's own session,\n // never through a host's grant.\n const setup = createRouterSession({\n sandbox,\n description: `setup of ${sandbox.id}`,\n workspaceRoot: WORKSPACE_ROOT,\n baseEnv: env,\n network: noNetwork,\n });\n await writePlatformFiles(ctx, setup);\n // A new disk gets the workspace seeds once.\n if (fresh) {\n const seedMarker = `${WORKSPACE_ROOT}/.final/workspace-prepared/${await sha256Hex(artifact.data.key)}`;\n if ((await setup.stat({ path: seedMarker })) == null) {\n await materializeSandboxSeeds({\n sandbox: setup,\n root: WORKSPACE_ROOT,\n files: await sandboxSeedFilesForAttach(ctx, artifact.data),\n });\n await setup.writeTextFile({ path: seedMarker, content: 'complete' });\n }\n }\n const handle = await buildHandle({\n ctx,\n sandbox,\n env,\n ports: state.ports,\n passive: false,\n });\n return {\n handle,\n region: sandbox.info.region,\n state: { ...state, sandboxId: sandbox.id },\n fresh,\n booted,\n };\n } catch (error) {\n // No state reaches the caller on failure; remove only a sandbox this attach created.\n if (fresh) {\n try {\n await sandbox.delete();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n `sandbox ${sandbox.id} attach and cleanup failed`,\n );\n }\n }\n throw error;\n }\n },\n attachPassive: async (ctx, { state: rawState }) => {\n const state = stateOf(rawState);\n const sandbox = await runningSandbox(ctx, state);\n if (sandbox == null)\n throw routedSandboxError(\n RoutedSandboxErrorCode.SandboxNotRunning,\n 'sandbox is not running for passive access',\n );\n return buildHandle({\n ctx,\n sandbox,\n env: platformProcessEnvironment(ctx, {}),\n ports: state.ports,\n passive: true,\n });\n },\n // The sandbox pauses on its own idle lifecycle; nothing to do.\n detach: async (_ctx, { state }) => stateOf(state),\n park: async (ctx, { state: rawState }) => {\n const state = stateOf(rawState);\n if (state.sandboxId == null) return state;\n const sandboxId = state.sandboxId;\n const failures: unknown[] = [];\n try {\n await closeMcp(sandboxId);\n } catch (cause) {\n failures.push(cause);\n }\n const atRest = (current: SandboxHandleIface | null) =>\n current == null ||\n current.info.state === SandboxState.Paused ||\n current.info.state === SandboxState.Stopped ||\n current.info.state === SandboxState.Failed;\n try {\n const router = config.router(ctx);\n const current = await findSandbox(router, sandboxId);\n if (atRest(current)) log('routed_sandbox.park_at_rest', { sandboxId });\n else if (current != null) {\n try {\n await current.pause();\n } catch (error) {\n // Parked if it came to rest meanwhile (an idle pause, a delete); otherwise the\n // pause did not happen and park is retried.\n if (!atRest(await findSandbox(router, sandboxId))) throw error;\n log('routed_sandbox.park_at_rest', { sandboxId });\n }\n }\n } catch (cause) {\n failures.push(cause);\n }\n settledFailures(failures, 'Sandbox pause failed');\n return state;\n },\n delete: async (ctx, { state: rawState }) => {\n const state = stateOf(rawState);\n const router = config.router(ctx);\n const failures: unknown[] = [];\n if (state.sandboxId != null)\n try {\n await closeMcp(state.sandboxId);\n } catch (cause) {\n failures.push(cause);\n }\n // Every router sandbox this platform sandbox had, including one an interrupted attach\n // created before its id was recorded.\n try {\n const { deleted } = await router.sandboxes.deleteByLabels({\n labels: { [SANDBOX_LABEL]: ctx.sandboxId },\n });\n log('routed_sandbox.delete', { deleted: deleted.join(',') });\n if (state.sandboxId != null && !deleted.includes(state.sandboxId)) {\n const sandbox = await findSandbox(router, state.sandboxId);\n await sandbox?.delete();\n }\n } catch (cause) {\n if (!isRouterNotFound(cause)) failures.push(cause);\n }\n settledFailures(failures, 'Sandbox delete or MCP cleanup failed');\n },\n };\n };\n\n return defineSandboxProvider({\n name: config.name ?? ROUTED_SANDBOX_PROVIDER,\n stateProtocolVersion: 1,\n environment,\n });\n};\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,YAAY,aAAa,cAAc,mBAAmB;AACnE,SAAS,wBAAyD;AAClE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAYK;AACP,SAAS,qBAAqB;AAC9B;AAAA,EACE,cAAc;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,OASK;AACP,YAAY,OAAO;AACnB,SAAS,iCAA+D;AACxE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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EAAE,SAAS,QAAQ,KAAK,GAAG,EAAE,CAAC;AAC3D,cAAI,MAAM,aAAa,QAAQ,CAAC,QAAQ,SAAS,MAAM,SAAS,GAAG;AACjE,kBAAM,UAAU,MAAM,YAAY,QAAQ,MAAM,SAAS;AACzD,kBAAM,SAAS,OAAO;AAAA,UACxB;AAAA,QACF,SAAS,OAAO;AACd,cAAI,CAAC,iBAAiB,KAAK,EAAG,UAAS,KAAK,KAAK;AAAA,QACnD;AACA,wBAAgB,UAAU,sCAAsC;AAAA,MAClE;AAAA,IACF;AAAA,EACF;AAEA,SAAO,sBAAsB;AAAA,IAC3B,MAAM,OAAO,QAAQ;AAAA,IACrB,sBAAsB;AAAA,IACtB;AAAA,EACF,CAAC;AACH;",
|
|
6
6
|
"names": ["RoutedSandboxErrorCode", "hex"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@finalai/sandbox-router-agent-provider",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A sandbox provider for the agent stack over the Sandbox Router: agent sandboxes on any provider the router reaches, implementing the public sandbox provider contract.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"dependencies": {
|
|
28
28
|
"@finalai/agent-protocol": "0.23.3",
|
|
29
29
|
"@finalai/agent-provider": "0.20.3",
|
|
30
|
-
"@finalai/sandbox-router": "0.2.
|
|
30
|
+
"@finalai/sandbox-router": "0.2.3",
|
|
31
31
|
"zod": "4.6.6"
|
|
32
32
|
},
|
|
33
33
|
"engines": {
|