# AWS Lambda MicroVMs (/adapters/aws-lambda) Firecracker-based serverless sandboxes with suspend/resume and idle policies. Control plane via @aws-sdk/client-lambda-microvms; a small runner baked into the image handles exec and files. ## Installation [#installation] `@aws-sdk/client-lambda-microvms` is an optional peer dependency, used for the control plane (launch, suspend, resume, terminate, tokens, image builds). The data plane (exec, files, previews) is plain `fetch` to the MicroVM's endpoint. pnpm bun npm yarn ```bash pnpm add sbox-sdk @aws-sdk/client-lambda-microvms ``` ```bash bun add sbox-sdk @aws-sdk/client-lambda-microvms ``` ```bash npm install sbox-sdk @aws-sdk/client-lambda-microvms ``` ```bash yarn add sbox-sdk @aws-sdk/client-lambda-microvms ``` `templates.build()` also needs `@aws-sdk/client-s3` (imported only when you build). ## How it works [#how-it-works] AWS Lambda MicroVMs give you isolation, lifecycle and a dedicated HTTPS endpoint, but **the in-VM exec/filesystem protocol is defined by your image**. The adapter speaks a small runner protocol, and you bake the reference runner into your MicroVM image once. 1. Build a MicroVM image from a zip (`Dockerfile` at the root + the runner) with `CreateMicrovmImage`, with **lifecycle hooks enabled** → note the image ARN. 2. The adapter calls `RunMicrovm` (idempotent via `clientToken`), mints `CreateMicrovmAuthToken` JWEs scoped to single ports (≤ 60 minutes, refreshed automatically) and uses `Suspend`/`Resume`/`Terminate`. 3. Exec and files are HTTPS requests to the endpoint with `X-aws-proxy-auth` + `X-aws-proxy-port`, served by the runner: streaming `POST /sbox/exec` (NDJSON), `POST /sbox/kill`, `GET|PUT /sbox/files`. The reference runner ships in the package at `sbox-sdk/src/aws-lambda/runner/` (`server.mjs`, `Dockerfile` based on `public.ecr.aws/lambda/microvms:al2023-minimal`, and a README with the exact `create-microvm-image` command). It runs **inside the isolated MicroVM**; executing arbitrary commands is its purpose. ### Building the runner image [#building-the-runner-image] ```bash zip -j sbox-runner.zip Dockerfile server.mjs # Dockerfile at the zip root aws s3 cp sbox-runner.zip s3://YOUR_BUCKET/sbox-runner.zip aws lambda-microvms create-microvm-image \ --name sbox-runner \ --base-image-arn arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1 \ --build-role-arn arn:aws:iam::123456789012:role/MicrovmBuildRole \ --code-artifact '{"uri":"s3://YOUR_BUCKET/sbox-runner.zip"}' \ --hooks '{"port":9000,"microvmHooks":{"run":"ENABLED"}}' ``` The runner serves the data plane on `8080` and the lifecycle hooks on `9000`. `spec.env` and `metadata` reach the MicroVM as `runHookPayload` on the `/run` hook, which **only fires when the image was created with `--hooks`**. The adapter's tokens never include the hooks port. ## Quickstart [#quickstart] ```ts import { createSandboxClient } from "sbox-sdk"; import { awsLambda } from "sbox-sdk/aws-lambda"; const client = createSandboxClient({ provider: awsLambda({ imageIdentifier: "arn:aws:lambda:us-east-1:123456789012:microvm-image:sbox-runner", region: "us-east-1", }), }); const sandbox = await client.create({ env: { MODE: "dev" }, lifecycle: { idleTimeoutMs: 15 * 60_000, onIdle: "pause", autoResume: true, maxAgeMs: 4 * 3600_000, }, }); for await (const ev of sandbox.commands.run("echo $MODE; sleep 1; echo done")) { console.log(ev); } await sandbox.files.write("/tmp/data.txt", "hi"); await sandbox.pause(); // SuspendMicrovm: memory + disk preserved await sandbox.resume(); // ResumeMicrovm await sandbox.destroy(); // TerminateMicrovm ``` `credentials` and `region` resolve through the standard AWS SDK chain when omitted. [`template`](/templates) overrides the image ARN per `create()`. ## Authentication [#authentication] The live tests read `AWS_REGION` and `AWS_LAMBDA_MICROVM_IMAGE_ARN` (credentials from the default chain), plus `AWS_LAMBDA_MICROVM_S3_BUCKET` and `AWS_LAMBDA_MICROVM_BUILD_ROLE_ARN` to run the template build. ## How it maps [#how-it-maps] | Spec field | RunMicrovm | | ------------------------------------------- | ---------------------------------------------------------------------------- | | `template` | `imageIdentifier` (`imageVersion` option pins a version) | | `env`, inline `secrets`, `metadata`, `name` | `runHookPayload` JSON (≤ 16 KB), applied by the runner's `/run` hook | | `lifecycle.maxAgeMs` | `maximumDurationInSeconds` (≤ 8 h) | | `lifecycle.idleTimeoutMs` | `idlePolicy.maxIdleDurationSeconds` (idle = no traffic through the endpoint) | | `lifecycle.autoResume` | `idlePolicy.autoResumeEnabled` | | `lifecycle.onIdle: "destroy"` | `idlePolicy.suspendedDurationSeconds: 1` (terminate right after suspend) | | `network: { mode: "block-all" }` | no egress network connectors | | `idempotencyKey` | `clientToken` | | options | `executionRoleArn`, `logging`, `ingress/egressNetworkConnectors` | MicroVMs have no tags, so `metadata` is remembered by the creating process and served by the runner's `/sbox/info`; `list({ metadata })` only matches sandboxes whose metadata is known to this process. ## Previews [#previews] Every MicroVM port is private. `ports.expose(port)` mints a token scoped to that port and returns header auth plus its expiry: ```ts const p = await sandbox.ports.expose(3000); // { url: "https://", auth: { type: "header", headers: { "X-aws-proxy-auth": "…", "X-aws-proxy-port": "3000" } }, expiresAt } await sandbox.ports.fetch(3000, "/health"); // refreshes the token as needed ``` Browsers can't send these headers on a WebSocket; AWS accepts the token as WebSocket subprotocols instead (`lambda-microvms`, `lambda-microvms.authentication.`, `lambda-microvms.port.`), so `previewBrowserAuth` is `false`. ## Templates [#templates] With `s3Bucket` and `buildRoleArn` set, `templates.build({ source: { dockerfile, context } })` zips the context with the `Dockerfile` at the root, uploads it to S3, calls `CreateMicrovmImage` with hooks enabled (`hooksPort`, default 9000), tags the image with the cache key, and polls `GetMicrovmImageVersion` plus the per-architecture builds (`ListMicrovmImageBuilds` / `GetMicrovmImageBuild`), streaming their states as build events. ```ts const tpl = await client.templates.build({ source: { dockerfile: `FROM public.ecr.aws/lambda/microvms:al2023-minimal RUN dnf install -y nodejs python3 && dnf clean all COPY server.mjs /opt/sbox/server.mjs CMD ["node", "/opt/sbox/server.mjs"]`, context: { "server.mjs": runnerSource }, }, }); const sb = await client.create({ template: tpl }); ``` Your Dockerfile must start the runner. The build role needs `s3:GetObject` on the artifact. ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------------------------------ | :---------: | -------------------------------------------------------------------------------- | | `list` / `region` | native | `nextToken` pagination | | `pause` | native | Suspend preserves memory + disk | | `streaming` / `killProcess` | native | runner NDJSON exec, `/sbox/kill`, `/sbox/ps` | | `exposePort` / `privatePreview` / `proxiedFetch` | native | port-scoped JWE, header auth, `expiresAt` | | `templateBuild` | native | Dockerfile + S3 (`s3Bucket`, `buildRoleArn`) | | `stop` | unsupported | only run / suspend / terminate | | `setTimeout` | unsupported | no API changes lifetime or idle policy after launch | | `egressControl` | unsupported | connectors are fixed at launch (`block-all` at create works) | | `pty` / `ssh` | unsupported | `CreateMicrovmShellAuthToken` exists but its connection protocol is undocumented | | `snapshot` / `fork` / `volumes` | unsupported | the image is the build-time snapshot | Flags: `perCommandEnvCwd: true` (the runner applies cwd/env), `preservesMemoryOnPause: true`, `previewModel: "tunnel"`, `templateSources: ["dockerfile"]`. ## Limitations [#limitations] * Exec/files need the runner in the image; `env` needs the image's `run` hook enabled. * `tokenTtlMinutes` must be 1–60 (AWS's maximum); the factory throws otherwise. * `verify()` is `ListMicrovms({ maxResults: 1 })`. --- # Beam Cloud (/adapters/beam) A sandbox per Beam Cloud container. GPU-capable sandboxes with native streaming exec, processes, filesystem, egress control, brokered secrets, memory snapshots and image builds, via @beamcloud/beam-js. ## Installation [#installation] `@beamcloud/beam-js` (1.1 or newer) is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk @beamcloud/beam-js ``` ```bash bun add sbox-sdk @beamcloud/beam-js ``` ```bash npm install sbox-sdk @beamcloud/beam-js ``` ```bash yarn add sbox-sdk @beamcloud/beam-js ``` ## Authentication [#authentication] The adapter reads `BEAM_TOKEN` and `BEAM_WORKSPACE_ID`, or takes `token` / `workspaceId` options. `@beamcloud/beam-js` keeps its credentials in a process-wide `beamOpts` object and builds its HTTP client once. Only **one Beam token per process** works. A provider configured with a different token fails with a `Validation` error instead of quietly using the first token. ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { beam } from "sbox-sdk/beam"; const client = createSandboxClient({ provider: beam({ token: process.env.BEAM_TOKEN!, workspaceId: process.env.BEAM_WORKSPACE_ID!, }), }); const sandbox = await client.create({ template: "python:3.12-slim", // registry image (Image.fromRegistry) resources: { vcpus: 2, memoryMB: 2048, gpu: "A10G" }, lifecycle: { maxAgeMs: 30 * 60_000 }, // Beam TTL (keepWarmSeconds) env: { APP_ENV: "dev" }, volumes: [{ id: "weights", mountPath: "/mnt/weights" }], secrets: [{ name: "OPENAI_API_KEY", mode: "egress" }], network: { mode: "allow-list", domains: ["api.openai.com", "*.pypi.org"] }, }); // stdout and stderr stream separately; cwd/env are native. for await (const ev of sandbox.commands.run("nvidia-smi", { cwd: "/tmp" })) { if (ev.type === "stdout") process.stdout.write(ev.data); } ``` ### What `create()` maps to [#what-create-maps-to] | sbox | Beam | | ----------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `template` (registry ref) | `Image.fromRegistry(ref)` | | `template` (Beam image id / template ref) | `Image.fromId(id)` | | `name` | the Beam app name (default `"sbox"`, or the `app` option) | | `resources.vcpus` / `memoryMB` | `cpu` / `memory` | | `resources.gpu` / `gpuCount` | `gpu` / `gpuCount` (`T4`, `L4`, `A10G`, `A100-40`, `A100-80`, `H100`, `A6000`, `RTX4090`, `L40S`, `any`) | | `lifecycle.maxAgeMs`, `setTimeout()` | `keepWarmSeconds` / `updateTtl` (a TTL, default 600s) | | `env` | `env` | | `volumes` | `new Volume(id, mountPath)` (created on first mount) | | `secrets` by name | `secrets: [{ name }]` (brokered workspace secrets) | | `secrets` with an inline `value` | plain env var | | `network` | `blockNetwork` / `allowList` | | `ports` | `ports` (public URLs at creation) | | `fromSnapshot` | `Sandbox.createFromSnapshot` (memory) or `Image.fromId` (filesystem) | Settings Beam cannot honor throw `Validation` instead of being dropped: * `lifecycle.idleTimeoutMs`, `onIdle: "pause" | "stop"`, `autoResume` (sandboxes have only a TTL) * `region` * read-only volume mounts * renaming a secret through `envVar` * egress `deny` rules and `inject` * unknown GPU types `metadata` has no Beam equivalent. `getInfo()` returns what this process created the sandbox with, and `{}` after `connect()`. ### Secrets and egress [#secrets-and-egress] Beam secrets are **brokered**. The sandbox only sees a placeholder, and Beam substitutes the real value in HTTPS headers sent to the hosts the secret allows. Create the secret with its host rules, then pass it by name: ```bash beam secret create OPENAI_API_KEY "$OPENAI_API_KEY" --host api.openai.com ``` ```ts await client.create({ secrets: [{ name: "OPENAI_API_KEY", mode: "egress" }] }); ``` `network` and `sandbox.network.setEgressPolicy()` map to `blockNetwork` / `allowList` (`updateNetworkPermissions` at runtime). Allow-lists take hostnames, `*.` wildcards, IPs and CIDRs, up to 64 entries. Hostname rules only apply to ports 443 and 80. ## Previews [#previews] `sandbox.ports.expose(port)` returns Beam's public URL (`https://-.app.beam.cloud`). `ports.list()` maps to `listUrls()`. Beam sandbox URLs are always **public** (`auth: { type: "public" }`), so `privatePreview` is unsupported and `previewBrowserAuth` is `false`. Add authentication inside your app before exposing anything sensitive. ## Snapshots and fork [#snapshots-and-fork] * `snapshots.create()` calls `snapshot()`, which captures **memory and filesystem** (`includesMemory: true`). Boot it with `client.create({ fromSnapshot })`. A memory checkpoint restores with its original configuration, so the rest of the spec is ignored. * `snapshots.create({ mode: "filesystem" })` calls `createImageFromFilesystem()` and returns an `image:` ref (`includesMemory: false`). Booting it applies the full spec on top of that image. * `sandbox.fork({ count })` takes a memory snapshot and boots `count` sandboxes from it. There is no in-place restore, and no API to list or delete snapshots. ## Templates [#templates] `client.templates.build()` builds a Beam image in your workspace: * `{ dockerfile, context }` runs `Image.fromDockerfile`. The Dockerfile and context are written to a temp directory, and Beam syncs that directory as the build context. This needs Node. * `{ image }` runs `Image.fromRegistry`. `registryAuth` is passed as Docker Hub credentials. * `env` runs `withEnvs`. `workdir` and `user` become `WORKDIR` / `USER` lines. * `startCmd` / `readyCmd` throw `Validation`, because Beam sandboxes boot their own entrypoint. ```ts const tpl = await client.templates!.build({ source: { dockerfile: "FROM node:22-slim\nRUN npm i -g pnpm\n", }, }); const sandbox = await client.create({ template: tpl }); ``` Beam images are content-addressed and have no name or tag. Before building, the adapter calls `exists()`, so an identical image is reused even from another process (`status: "cached"`). `templates.get(id)` resolves Beam image ids. A cache key only resolves in the process that built it. Build logs go to the SDK's own console output, and `onEvent` receives the status changes. ## Code interpreter [#code-interpreter] `sandbox.code.runCode(code)` runs Python through `runCode` (non-blocking, so output streams to `onStdout` / `onStderr`). A non-zero exit is parsed into `error` (`ValueError: ...`). There is no stateful kernel, and other languages throw `Validation`. ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ----------------------------------- | :---------: | ------------------------------------------------------------------------ | | `streaming` | native | per-process stdout/stderr streams, kept separate | | `background` | native | `exec` returns immediately; `commands.connect` reattaches by pid | | `killProcess` | native | `listProcesses()` + `process.kill()` | | `codeInterpreter` | native | Python `runCode`; no stateful kernel | | `egressControl` | native | `blockNetwork` / `allowList`, `updateNetworkPermissions` | | `secretsVault` | native | brokered workspace secrets | | `exposePort` | native | public URLs; `listUrls()` | | `snapshot` / `fork` | native | memory checkpoints; filesystem images | | `templateBuild` | native | `dockerfile`, `image` | | `setTimeout` | native | `updateTtl` | | `gpu` | native | `resources.gpu` | | `filesUpload` | native | `fs.writeBytes` | | `list` | unsupported | Beam has no per-sandbox labels to filter by | | `volumes` (registry) | unsupported | the SDK has only `Volume.getOrCreate`; mounting via `spec.volumes` works | | `pause` / `stop` | unsupported | `destroy()` = `terminate()` | | `privatePreview` | unsupported | sandbox URLs are public | | `pty` / `ssh` / `metrics` / `stdin` | unsupported | not in the sandbox API | Flags: `perCommandEnvCwd: true`, `exitCodeNative: true`, `previewModel: "subdomain"`, `templateSources: ["dockerfile", "image"]`. ## Known limitations [#known-limitations] * **Idempotency:** Beam has no idempotency key or label lookup. A `create()` that fails after Beam accepted it can leave an orphaned sandbox, which expires at the end of its TTL. * **Live state:** `getInfo()` reads the workspace container list (`GET /api/v1/gateway/containers`). A sandbox missing from the list is reported as `destroyed`. * **Files:** the native filesystem API covers read, write, list, mkdir, remove and stat. `rename` falls back to `mv` over exec. Writes create missing parent directories. * **stdin:** buffered `stdin` is piped through the shell. There is no interactive `writeStdin`. * **VMs:** Beam's persistent `VM` API (pause/resume with memory, idle actions, SSH, desktop) is not wrapped yet. Use the `VM` class from `@beamcloud/beam-js` directly for now. --- # Blaxel (/adapters/blaxel) Perpetual sandboxes that drop into standby when idle and resume with memory intact. Native streaming exec, snapshots, fork, egress control, private previews and image builds, via @blaxel/core. ## Installation [#installation] `@blaxel/core` (0.3 or newer) is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk @blaxel/core ``` ```bash bun add sbox-sdk @blaxel/core ``` ```bash npm install sbox-sdk @blaxel/core ``` ```bash yarn add sbox-sdk @blaxel/core ``` ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { blaxel } from "sbox-sdk/blaxel"; const client = createSandboxClient({ provider: blaxel({ apiKey: process.env.BL_API_KEY!, workspace: process.env.BL_WORKSPACE!, region: "us-pdx-1", }), }); const sandbox = await client.create({ env: { NODE_ENV: "development" }, lifecycle: { maxAgeMs: 2 * 60 * 60_000 }, // deleted 2h after creation metadata: { team: "agents" }, }); // stdout and stderr stream separately; cwd/env/timeout are native. for await (const ev of sandbox.commands.run("npm test", { cwd: "/app" })) { if (ev.type === "stdout") process.stdout.write(ev.data); } ``` [`template`](/templates) is the sandbox image (default `blaxel/base-image:latest`). A sandbox without a `name` gets one derived from the create call's idempotency key, so a retried `create()` returns the same sandbox instead of a duplicate. ### Lifecycle [#lifecycle] Blaxel puts an idle sandbox into standby by itself and resumes it (memory, processes and files intact) on the next request, so there is no explicit `pause()`. | sbox | Blaxel | | ----------------------------------------------- | ------------------------------------------------- | | `lifecycle.maxAgeMs` / `setTimeout()` | `ttl` (maximum age, minimum 5 minutes) | | `lifecycle.idleTimeoutMs` + `onIdle: "destroy"` | `ttl-idle` expiration policy (minimum 60 seconds) | | `onIdle: "pause"` | the platform default (automatic standby) | | `stop()` | `archive()`: filesystem kept, memory dropped | | `client.connect(id)` | unarchives an archived sandbox | | `destroy()` | `delete()` | ### Snapshots and fork [#snapshots-and-fork] Blaxel snapshots capture memory and running processes (`includesMemory: true`). `snapshots.restore()` rolls the sandbox back **in place** (same name and URLs), and `client.create({ fromSnapshot })` forks a snapshot into a new sandbox. `sandbox.fork()` copies the live state without leaving a snapshot behind. ```ts const snap = await sandbox.snapshots!.create({ name: "after-install" }); const [copy] = await sandbox.fork(); await sandbox.snapshots!.restore(snap); ``` ### Egress control [#egress-control] `network` at create time and `sandbox.network.setEgressPolicy()` at runtime map to Blaxel's egress proxy: `allow-list` → `proxy.allowedDomains`, `deny` → `proxy.forbiddenDomains`, `block-all` → `forbiddenDomains: ["*"]`. Credential injection (`inject`) becomes proxy routing rules with `{{SECRET:name}}` references, so the secret never enters the sandbox. ```ts const sandbox = await client.create({ network: { mode: "allow-list", domains: ["api.github.com", "registry.npmjs.org"], inject: [ { domains: ["api.github.com"], headers: { Authorization: { name: "gh", value: `Bearer ${token}` } }, }, ], }, }); ``` When a create-time policy restricts traffic, the adapter also turns on the `proxy` firewall ruleset so tools that ignore `HTTP(S)_PROXY` are filtered too. Rulesets can only be set at creation; pass `egressFirewall: false` to skip it. Rules are domain-based: CIDR rules throw a `Validation` error. ## Previews and browser auth [#previews-and-browser-auth] `sandbox.ports.expose(port)` creates a Blaxel preview. A private preview (`{ visibility: "private" }`) comes back with a fresh preview token as query auth (`bl_preview_token`), so `browserUrl()` gives a URL a browser can open, including over a WebSocket (`previewBrowserAuth: true`). Tokens live for 24 hours by default (`previewTokenTtlMs`). ```ts import { browserUrl } from "sbox-sdk"; const preview = await sandbox.ports!.expose(3000, { visibility: "private" }); const wsUrl = browserUrl(preview, { protocol: "ws", path: "/socket" }); ``` `sandbox.ports.fetch(port, path)` goes through Blaxel's authenticated port proxy (`proxiedFetch`), so it needs no preview at all. ## Templates [#templates] `client.templates.build()` builds an image in your workspace with Blaxel's `ImageInstance` builder. A build deploys a sandbox named after the template; the result's `id` is the image reference to pass as `template`. The build is tagged with its cache key, so the same spec is never rebuilt. ```ts const tpl = await client.templates!.build({ source: { dockerfile: `FROM node:22-slim RUN apt-get update && apt-get install -y git WORKDIR /app COPY package.json /app/package.json`, context: "./my-app", }, }); const sandbox = await client.create({ template: tpl }); ``` There is no Dockerfile endpoint in the SDK, so the adapter translates the Dockerfile into builder calls: `FROM`, `RUN`, `ENV`, `WORKDIR`, `USER`, `EXPOSE`, `ARG`, `LABEL` and `COPY`/`ADD` from the context are supported. Multi-stage builds, `COPY --from` and `ADD ` are rejected. `CMD` and `ENTRYPOINT` are skipped (with a log line), because Blaxel's sandbox API must stay the entrypoint. `{ image }` sources (with optional `registryAuth`) build from a registry image directly. Building with a context needs Node (files are staged on disk). ## Authentication [#authentication] Credentials passed as options go to the SDK's `initialize()`; nothing is written to `process.env`. Without options the SDK reads `BL_API_KEY` / `BL_WORKSPACE` or the Blaxel CLI login. `initialize()` is process-wide, so two `blaxel()` providers with different credentials in one process share the last one configured. ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------------------------------ | :---------: | ------------------------------------------------------ | | `list` | native | paginated, filtered by labels | | `stop` | native | archive; `connect()` unarchives | | `setTimeout` | native | `updateTtl` (min 5m) | | `pause` | unsupported | standby/resume is automatic | | `streaming` / `background` / `killProcess` | native | `process.exec` callbacks, `streamLogs`, `process.kill` | | `stdin` | native | spawned processes (`writeStdin`) | | `filesUpload` / `filesWatch` | native | `fs.writeBinary`, `fs.watch` | | `exposePort` / `privatePreview` / `proxiedFetch` | native | previews + tokens, `sandbox.fetch` | | `egressControl` | native | egress proxy, `updateNetwork` | | `snapshot` / `fork` | native | memory included | | `volumes` / `region` | native | | | `templateBuild` | native | `dockerfile`, `image` | | `codeInterpreter` / `pty` / `ssh` / `metrics` | unsupported | use [`raw()`](/escape-hatch) | | `secretsVault` / `gpu` | unsupported | inline `secrets` become secret env vars | `perCommandEnvCwd` is `true`; `preservesDiskOnStop` and `preservesMemoryOnPause` (standby) are `true`; `previewModel` is `subdomain`. ## Known limitations [#known-limitations] * `writeStdin` works on `commands.spawn()` processes; `commands.run()` doesn't open a stdin pipe, and there is no way to send EOF. * `secrets` need an inline `value` (they become secret env vars); Blaxel has no named secret store for sandboxes. * `onIdle: "stop"` has no Blaxel equivalent (expiration policies can only delete), so it falls back to standby. * A template build leaves its build sandbox deployed in your workspace (it idles in standby). --- # Cloudflare Sandbox (/adapters/cloudflare) Cloudflare Sandbox SDK 0.12 through a Worker / Durable Object binding. Deprecated; a 1.0 adapter is planned. **Deprecated.** This adapter targets **`@cloudflare/sandbox` 0.12.x**. Cloudflare gives 0.x bug and security fixes only until **2026-12-31**, and Sandbox SDK 1.0 removed this API. A separate 1.0 adapter is planned. Until then, pin `@cloudflare/sandbox@0.12.14` and the `docker.io/cloudflare/sandbox:0.12.14` image. To plan your move, read Cloudflare's [0.x → 1.0 API map](https://developers.cloudflare.com/sandbox/sdk/migrate/api-map/). The adapter logs a one-time warning the first time you call `cloudflare()`. ## Installation [#installation] `@cloudflare/sandbox` is an optional peer dependency, used from inside a Cloudflare Worker. The adapter needs the **Durable Object namespace binding** for your exported Sandbox class. pnpm bun npm yarn ```bash pnpm add sbox-sdk @cloudflare/sandbox@0.12 ``` ```bash bun add sbox-sdk @cloudflare/sandbox@0.12 ``` ```bash npm install sbox-sdk @cloudflare/sandbox@0.12 ``` ```bash yarn add sbox-sdk @cloudflare/sandbox@0.12 ``` ## Authentication [#authentication] There is no API key: the `env.Sandbox` binding from your wrangler config is the credential. `client.verify()` checks that the SDK loads and that `binding` is a Durable Object namespace. It never touches a sandbox, because getting a stub would instantiate one. ## Usage [#usage] Cloudflare is **Worker-only**. It runs against a live Durable Object binding, not a plain Node process: ```ts import { createSandboxClient } from "sbox-sdk"; import { cloudflare } from "sbox-sdk/cloudflare"; export { Sandbox } from "@cloudflare/sandbox"; export default { async fetch(request: Request, env: Env) { const client = createSandboxClient({ provider: cloudflare({ binding: env.Sandbox, sandboxOptions: { transport: "rpc" }, // needed for previews (tunnels) }), }); const sandbox = await client.create({ name: "session-42", env: { NODE_ENV: "production" }, lifecycle: { idleTimeoutMs: 10 * 60_000 }, // sleepAfter metadata: { tenant: "acme" }, // container labels }); const proc = await sandbox.commands.spawn("python -m http.server 8080"); const preview = await sandbox.ports!.expose(8080); // *.trycloudflare.com const exec = await sandbox.code!.runCode("print('hello from the edge')"); return Response.json({ url: preview.url, logs: exec.logs }); }, }; ``` `create()` uses `name` (or the idempotency key) as the Durable Object id, so it has **get-or-create** semantics, and `client.getOrCreate()` is native. It boots the container straight away, so `getInfo()` reports `running`. `getInfo()` reads the live Container state. The base image comes from your Worker's container config at deploy time. `template`, `region` and `volumes` therefore throw `Validation`. ## Previews [#previews] `exposePort()` was **deprecated on 2026-06-09**. Previews now use its 0.12 replacement, [`sandbox.tunnels`](https://developers.cloudflare.com/sandbox/sdk/api/tunnels/), which **requires the RPC transport**: * By default, `ports.expose(port)` opens a **quick tunnel** on a zero-config `https://.trycloudflare.com` URL. * With `namedTunnels: true`, it opens a **named tunnel** on your zone instead, at `p-.`. This needs `CLOUDFLARE_API_TOKEN` (Tunnel Edit, DNS Edit, Zone Read) in the Worker env. `unexpose()` destroys the tunnel, and `ports.list()` lists the tunnels. Tunnel URLs are **public**, so `privatePreview` is unsupported and `previewBrowserAuth` is `false`. The service must listen on `0.0.0.0:`. `ports.fetch()` still proxies through `containerFetch()` without a tunnel. The `hostname` option, which built `exposePort()` URLs, is deprecated and ignored. ## Terminals [#terminals] `sandbox.pty.create()` opens a new execution session and connects to its terminal through `session.terminal()`, a WebSocket upgrade handled inside the Worker. The PTY id is the session id, so `pty.connect(id)` reattaches, and the container replays its buffer. `kill()` closes the socket. `cmd` is run with `exec` once the shell starts. ## Snapshots [#snapshots] `snapshots.create()` uses `createBackup()`, which writes a squashfs archive of **one directory** (`snapshotDir`, default `/workspace`) to R2. This needs the `BACKUP_BUCKET` binding and R2 credentials that the SDK documents. * `snapshots.restore(ref)` restores the backup **in place**. * `client.create({ fromSnapshot })` restores it into the new sandbox after boot. The snapshot id is `:`, so the id alone is enough to restore. Backups are filesystem-only (`includesMemory: false`) and expire after `snapshotTtlSeconds` (3 days by default). 0.12 has no backup list or delete API, so `snapshots.list()` and `snapshots.delete()` are not available. ## Egress [#egress] `network` and `sandbox.network.setEgressPolicy()` drive the Containers outbound proxy's runtime host lists, `setAllowedHosts()` and `setDeniedHosts()`: | sbox | Cloudflare | | ------------ | ---------------------------------------- | | `allow-all` | allowed `["*"]`, denied `deny.domains` | | `allow-list` | allowed `domains`, denied `deny.domains` | | `block-all` | allowed `[]`, denied `["*"]` | Filtering is **by hostname only**. CIDR rules throw `Validation`, and credential injection (`inject`, and `secrets` with `mode: "egress"`) throws `NotSupportedError`. The proxy only sees HTTPS traffic when your Sandbox class sets `interceptHttps = true`, and the container then has to trust Cloudflare's CA. For a hard boundary, also set `enableInternet = false`. ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ---------------------------------------- | :---------: | -------------------------------------------------------------- | | `streaming` / `background` | native | `startProcess` + SSE `streamProcessLogs` | | `killProcess` | native | `killProcess(id)`; `run()` is a process too, so `kill()` works | | `filesWatch` | native | `watch()` (inotify over SSE) | | `filesUpload` | native | base64 `readFile` / `writeFile` | | `pty` | native | `session.terminal()` | | `codeInterpreter` / `statefulKernel` | native | python, javascript, typescript | | `exposePort` | native | `sandbox.tunnels` (public) | | `proxiedFetch` | native | `containerFetch()` | | `egressControl` | native | allowed/denied host lists | | `snapshot` | native | `createBackup` / `restoreBackup` (one directory) | | `stop` | native | the container's disk is discarded | | `setTimeout` | native | `setSleepAfter()`, an **idle** timeout | | `list` | unsupported | Durable Objects are not enumerable | | `volumes` | unsupported | `mountBucket()` mounts a bucket you already have; see below | | `stdin` | unsupported | 0.12 has no stdin API | | `pause` / `fork` / `metrics` | unsupported | | | `privatePreview` / `ssh` / `region` | unsupported | | | `templateBuild` / `gpu` / `secretsVault` | unsupported | | `perCommandEnvCwd` is `true`, and `timeoutMs` is passed to `startProcess`. `previewModel` is `tunnel`. ## Known limitations [#known-limitations] * **No volumes.** `client.volumes` needs provider-level create, list and delete. 0.12 can only mount an existing S3/R2/GCS bucket into a running sandbox, so call `sandbox.raw().mountBucket(bucket, path, options)` directly. * **`metadata` is write-only.** It becomes container labels for analytics, and `getInfo()` only echoes what this handle set. * **`lifecycle.maxAgeMs` is an idle timeout.** `sleepAfter` is the only timer, so `maxAgeMs` (and `ttlMs`) fall back to it when `idleTimeoutMs` is unset. * **`resources` and `ports` are ignored.** The instance type comes from wrangler config, and ports get a tunnel on `expose()`. * **Errors crossing the Durable Object RPC boundary can lose their class.** The adapter maps by `code` / `httpStatus` when present, and by message otherwise. --- # CodeSandbox (/adapters/codesandbox) Deprecated: CodeSandbox sandboxes are now Together Sandbox. Use sbox-sdk/together. This adapter is removed in 0.2.0. CodeSandbox's sandbox product has moved to **Together Sandbox**. Use the [`together`](/adapters/together) adapter (`sbox-sdk/together`) for new work. `sbox-sdk/codesandbox` is deprecated in 0.1.0 and only gets crash and leak fixes. It will be **removed in 0.2.0**. Calling `codesandbox()` logs a one-time deprecation warning. ## Migrating [#migrating] ```ts // before import { codesandbox } from "sbox-sdk/codesandbox"; const client = createSandboxClient({ provider: codesandbox() }); // after import { together } from "sbox-sdk/together"; const client = createSandboxClient({ provider: together() }); ``` Your sandbox code (`commands`, `files`, `ports`, `pause()`/`resume()`) stays the same, because both adapters implement the same interface. ## Installation [#installation] `@codesandbox/sdk` is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk @codesandbox/sdk ``` ```bash bun add sbox-sdk @codesandbox/sdk ``` ```bash npm install sbox-sdk @codesandbox/sdk ``` ```bash yarn add sbox-sdk @codesandbox/sdk ``` ## Authentication [#authentication] `codesandbox()` reads `CSB_API_KEY` when you don't pass `apiKey`. Check the key with `client.verify()`. It lists one sandbox and never creates anything. ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { codesandbox } from "sbox-sdk/codesandbox"; const client = createSandboxClient({ provider: codesandbox({ apiKey: process.env.CSB_API_KEY! }), }); const sandbox = await client.create({ metadata: { team: "a" }, name: "box" }); const res = await sandbox.commands.run("node --version"); console.log(res.stdout); await sandbox.pause(); // hibernate await sandbox.resume(); // wakes the VM and reconnects await sandbox.destroy(); // permanently deletes the sandbox ``` What `create()` does with your spec: * [`template`](/templates) is a sandbox/template id to fork from. It defaults to the universal template. * `name` becomes the sandbox title. * `metadata` is stored as `key=value` tags. CodeSandbox allows at most 10 tags. * `lifecycle.idleTimeoutMs` sets the hibernation timeout. ## Previews [#previews] * `ports.expose(port)` returns `https://-.csb.app` with public auth. * `ports.expose(port, { visibility: "private" })` mints a 24-hour host token. Auth is `{ type: "query", param: "preview_token", token }`. The token only matters if the sandbox's privacy is private. Sandboxes created from a public template have public hosts either way. ## Capabilities [#capabilities] | Capability | Level | Notes | | ---------------------------------------------------------- | :---------: | -------------------------------------------------------- | | `list` | native | walks every page. Status comes from the `running` filter | | `pause` | native | hibernate. `resume()` reconnects a fresh client | | `setTimeout` | native | hibernation timeout | | `streaming` | native | `runBackground` output events, merged into stdout | | `filesUpload` | native | native `client.fs` | | `exposePort` | native | `-.csb.app` | | `privatePreview` | native | host token in the `preview_token` query parameter | | `snapshot`, `fork`, `background`, `pty`, `codeInterpreter` | unsupported | | `perCommandEnvCwd` is `true`, `preservesMemoryOnPause` is `true` and `previewModel` is `subdomain`. ## Known limitations [#known-limitations] * **stdout and stderr are one stream.** CodeSandbox runs commands in a PTY, so everything comes back as `stdout`, with `\r\n` turned into `\n`. * **State is approximate.** The API has no per-sandbox status. A sandbox that isn't running shows as `stopped` in `list()`, because hibernated and shut-down sandboxes can't be told apart. The exception is a sandbox that this handle paused itself, which shows as `paused`. * `timeoutMs` has no native equivalent. The core's backstop kills the command after the timeout. --- # Daytona (/adapters/daytona) Full-featured Daytona sandboxes through the stable v0 surface of @daytona/sdk. Streaming exec, PTY, code interpreter with stateful Python kernels, pause/stop, snapshots, fork, SSH, egress allow lists, vault secrets, volumes, metrics, browser-safe signed previews, and Dockerfile template builds. ## Installation [#installation] `@daytona/sdk` (≥ 2.0) is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk @daytona/sdk ``` ```bash bun add sbox-sdk @daytona/sdk ``` ```bash npm install sbox-sdk @daytona/sdk ``` ```bash yarn add sbox-sdk @daytona/sdk ``` `@daytonaio/sdk` is deprecated; Daytona now publishes `@daytona/sdk`. 2.x ships a stable **v0** API and an alpha **v2** API. The adapter uses **v0** (reached through the root client's `daytona.v0`). Uninstall `@daytonaio/sdk` when you upgrade. ## Authentication [#authentication] Pass `apiKey` (or `jwtToken` + `organizationId`). SDK 2.x ignores `DAYTONA_API_URL`. For a self-hosted or dev API, pass `apiUrl`, and the adapter builds the v0 client against it directly. ## Quickstart [#quickstart] ```ts import { createSandboxClient } from "sbox-sdk"; import { daytona } from "sbox-sdk/daytona"; const client = createSandboxClient({ provider: daytona({ apiKey: process.env.DAYTONA_API_KEY!, target: "us" }), }); const sandbox = await client.create({ template: "debian:12", // image ref → built on the fly; a bare name → Daytona snapshot metadata: { job: "demo" }, lifecycle: { idleTimeoutMs: 15 * 60_000, onIdle: "pause", maxAgeMs: 4 * 3_600_000, }, }); for await (const ev of sandbox.commands.run("echo out; echo err >&2")) { console.log(ev); } const ctx = await sandbox.code.createContext(); // stateful Python kernel await sandbox.code.runCode("x = 41", { context: ctx }); console.log( (await sandbox.code.runCode("print(x + 1)", { context: ctx })).logs.stdout ); await sandbox.pause(); // memory kept await sandbox.resume(); await sandbox.destroy(); ``` `template` is a Daytona **snapshot** name, or a container **image** when it contains `/` or `:`. `fromSnapshot` takes a snapshot name, for example one from `sandbox.snapshots.create()`. ## Options [#options] ## Templates (Dockerfile builds) [#templates-dockerfile-builds] `client.templates.build()` builds a Daytona **snapshot** in your organization. A Dockerfile goes through `Image.fromDockerfile()`, and an `image` source goes through `Image.base()`. The result is passed to `daytona.snapshot.create({ name, image, resources }, { onLogs })`, and build logs stream through `onEvent`. ```ts const tpl = await client.templates.build( { name: "borat-desktop", source: { dockerfile: await readFile("desktop/Dockerfile", "utf8"), context: "./desktop", }, env: { DISPLAY: ":1" }, workdir: "/app", resources: { vcpus: 2, memoryMB: 4096, diskMB: 10_240 }, startCmd: "/usr/local/bin/start-vnc.sh", }, { onEvent: (e) => e.type === "log" && console.log(e.line) } ); const desktop = await client.create({ template: tpl }); ``` * The snapshot is named `-` (just `sbox-` when you don't set a name), so `lookup(cacheKey)` and later builds find it again. * The context is written to a temp directory next to the Dockerfile, so `COPY`/`ADD` work. This needs Node. * `startCmd` becomes the snapshot `entrypoint` (`sh -c …`). `readyCmd` isn't supported and is ignored with a log line. `user` adds a `USER` instruction. * `resources` apply to the snapshot (`cpu`, `memory`/`disk` in GiB, `gpu`). Snapshot sources aren't accepted. `registryAuth` isn't either: configure private registries in the Daytona dashboard. ## Previews and browser auth [#previews-and-browser-auth] * `ports.expose(port)` returns Daytona's standard preview link (`https://-.`). For a private sandbox it carries `auth: { type: "header", headers: { "X-Daytona-Preview-Token": … } }`. That token works for **every** port and can't be revoked, so treat it as a secret. * `ports.expose(port, { visibility: "private" })` returns a **signed preview URL** (`https://-.`) with `auth: { type: "signed-url" }`. The token is in the hostname, so it works from a browser, an iframe, or a **WebSocket** (`flags.previewBrowserAuth: true`). It's scoped to one port and expires after `previewTtlSeconds` (default 3600, max 86 400). Daytona's proxy closes WebSockets opened with it about a minute after expiry. ## Lifecycle [#lifecycle] | `SandboxSpec` | Daytona | | ------------------------- | --------------------------------------------------------------------------- | | `lifecycle.idleTimeoutMs` | `autoStopInterval` (minutes), or `autoPauseInterval` when `onIdle: "pause"` | | `onIdle: "destroy"` | `autoDeleteInterval: 0` (deleted as soon as it stops, including `stop()`) | | `lifecycle.maxAgeMs` | `ttlMinutes`: wall-clock limit since creation, destroys even if stopped | | `setTimeout(ms)` | `setTtl()`: re-anchors the wall-clock TTL from now (**not** the idle timer) | | `autoArchiveInterval` opt | `autoArchiveInterval` (minutes a stopped sandbox waits before archiving) | Daytona counts idle time from SDK activity, not preview traffic. `getInfo()` refreshes from the API and maps every Daytona state (`started`, `pausing`, `archived`, `build_failed`, …) to `SandboxState`. `stop()` keeps the disk, and `pause()` keeps memory. ## Network, secrets and volumes [#network-secrets-and-volumes] * **Egress:** `block-all` → `networkBlockAll`, `allow-list` → `networkAllowList` (CIDRs) and `domainAllowList`, both at create and at runtime (`updateNetworkSettings`). Deny rules and `inject` aren't supported. * **Secrets:** a `SecretRef` without a `value` mounts an existing Daytona vault Secret (`secrets: { [envVar]: name }`). The env var holds a placeholder, and the real value is substituted on egress to the Secret's allowed hosts. An inline `value` becomes a plain env var. * **Volumes:** `client.volumes` wraps `daytona.volume` (no size or region). `spec.volumes` mounts by id or name. Read-only mounts aren't supported. * **Idempotency:** each create gets a deterministic `name` from the idempotency key, so a retried create that hits 409 returns the existing sandbox. `getOrCreate` is native (`daytona.get(name)`, resuming it if stopped). ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------------------------ | :---------: | ------------------------------------------------------------------- | | `list` / `stop` / `pause` / `setTimeout` | native | list filters by labels and state on the server | | `streaming` / `background` / `killProcess` | native | one Daytona session per command; kill deletes the session | | `stdin` | native | `sendSessionCommandInput` | | `pty` | native | `createPty` / `connectPty`, resize | | `filesUpload` | native | streaming upload; `filesWatch` unsupported | | `codeInterpreter` / `statefulKernel` | native | contexts = `codeInterpreter.createContext` (Python only) | | `exposePort` / `privatePreview` | native | signed URLs, `previewBrowserAuth: true` | | `egressControl` / `secretsVault` | native | allow lists only | | `snapshot` / `fork` | native | filesystem snapshots (`includesMemory: false`); fork = CoW clone | | `ssh` | native | token auth: `ssh @ssh.app.daytona.io`; `privateKey` is empty | | `metrics` / `volumes` / `templateBuild` | native | sources: `dockerfile`, `image` | | `gpu` / `region` | native | `resources.gpu` → `gpuType`; `region` → `target` | | `proxiedFetch` / `filesWatch` | unsupported | | Flags: `preservesMemoryOnPause: true`, `preservesDiskOnStop: true`, `perCommandEnvCwd: false` (the core prefixes `cd`/`export`), `exitCodeNative: true`, `previewBrowserAuth: true`, `previewModel: "subdomain"`. ## Known limitations [#known-limitations] * `resources` only apply to image-based creates (`template: "debian:12"`). On snapshot-based creates they throw `Validation`, so set them on the template instead. * Commands run in Daytona sessions, so output arrives through the log stream rather than a raw pipe. Exit codes come from `getSessionCommand`. * `snapshots.create({ mode: "memory" })` throws (Daytona snapshots are filesystem-only). Restoring always boots a new sandbox, so use `client.create({ fromSnapshot })`. * Daytona timeouts are in seconds or minutes. The adapter rounds milliseconds **up**. --- # Docker (/adapters/docker) Local containers through the Docker Engine API, with no npm dependency. Works with OrbStack, Docker Desktop, Colima, Rancher Desktop and Podman. Streaming exec with stdin, a PTY, pause/resume, commit-based snapshots and forks, Dockerfile template builds, volumes and published ports. Use the Docker adapter to run the same sandbox code on your laptop that you run in the cloud. Develop against a local container, then switch the import to a cloud adapter. Desktop agents can also keep a local runtime and a cloud runtime behind one interface. ## Installation [#installation] The adapter has **no dependencies**. It speaks the [Docker Engine API](https://docs.docker.com/reference/api/engine/) over the daemon's unix socket with `node:http`, which it loads lazily on first use. It needs Node (or Bun or Deno with Node compatibility) and a running container runtime. pnpm bun npm yarn ```bash pnpm add sbox-sdk ``` ```bash bun add sbox-sdk ``` ```bash npm install sbox-sdk ``` ```bash yarn add sbox-sdk ``` ### Supported runtimes [#supported-runtimes] | Runtime | Socket the adapter finds | | ---------------------- | --------------------------------------------------------------------------------------------- | | OrbStack | `~/.orbstack/run/docker.sock` | | Docker Engine (Linux) | `/var/run/docker.sock` | | Docker Desktop | `~/.docker/run/docker.sock` (or `/var/run/docker.sock`) | | Colima | `~/.colima/default/docker.sock` | | Rancher Desktop (moby) | `~/.rd/docker.sock` | | Podman (compat API) | `$XDG_RUNTIME_DIR/podman/podman.sock`, `~/.local/share/containers/podman/machine/podman.sock` | Only OrbStack is tested live. The other runtimes serve the same Engine API, but run the [conformance suite](/capabilities) once on yours, especially on Podman, whose Docker-compatible API isn't a perfect copy. ## Connecting to the daemon [#connecting-to-the-daemon] No credentials are needed. The adapter picks an endpoint in this order: 1. The `socketPath` or `host` option. 2. `DOCKER_HOST`: `unix:///path/to.sock` or `tcp://host:2375`. With `DOCKER_TLS_VERIFY=1`, it connects over TLS on port 2376 using `ca.pem`, `cert.pem` and `key.pem` from `DOCKER_CERT_PATH`. 3. The first socket in the table above that exists. Symlinks are resolved, so a `/var/run/docker.sock` that points at OrbStack is reported as OrbStack. | Option | Env var | Description | | ------------ | ------------------- | -------------------------------------------------- | | `socketPath` | | Unix socket path. Overrides everything else. | | `host` | `DOCKER_HOST` | `unix://…` or `tcp://…`. `ssh://` isn't supported. | | | `DOCKER_TLS_VERIFY` | Use TLS for `tcp://`. | | | `DOCKER_CERT_PATH` | Directory that holds the client certificates. | `client.verify()` calls `GET /_ping` and `GET /version`. It never creates anything, and it reports the runtime and engine, for example `OrbStack (Docker Engine - Community 29.8.2, API 1.56)`. ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { docker } from "sbox-sdk/docker"; const client = createSandboxClient({ provider: docker() }); const sandbox = await client.create({ // Any image. The default is debian:bookworm-slim, pulled if missing. template: "node:22-slim", env: { NODE_ENV: "development" }, metadata: { project: "demo" }, resources: { vcpus: 2, memoryMB: 2048 }, ports: [3000], // published at create, on 127.0.0.1: }); for await (const ev of sandbox.commands.run("node -e 'console.log(1+1)'")) { if (ev.type === "stdout") process.stdout.write(ev.data); } await sandbox.files.write( "/app/index.js", "require('http').createServer((q, s) => s.end('hi')).listen(3000)" ); await sandbox.commands.spawn("node /app/index.js"); const preview = await sandbox.ports!.expose(3000); console.log(preview.url); // http://127.0.0.1:55012 await sandbox.destroy(); // DELETE /containers/{id}?force=1&v=1 ``` Every container is created with `Init: true`, so tini reaps zombies and forwards signals. It runs `sleep infinity` as a keep-alive unless the template sets a `startCmd`, or you pass `command: "image"` to run the image's own `CMD`. Containers carry the labels `sbox.managed=true`, `sbox.name`, `sbox.idempotency` and `sbox.meta.` (from `metadata`). `list()` and `getOrCreate()` filter on these labels. ## Example: a desktop sandbox [#example-a-desktop-sandbox] This is the setup for an agent app that drives a Linux desktop (Debian, Chromium, a VNC server and an HTTP control server). It runs locally on Docker and in the cloud on another adapter, with the same spec. ```ts import { readFile } from "node:fs/promises"; import { createSandboxClient } from "sbox-sdk"; import { docker } from "sbox-sdk/docker"; const client = createSandboxClient({ provider: docker() }); const desktop = await client.templates!.build( { name: "agent-desktop", // tagged sbox/agent-desktop:latest source: { context: "./desktop-image", // Dockerfile build context directory dockerfile: await readFile("./desktop-image/Dockerfile", "utf-8"), }, env: { DISPLAY: ":1" }, startCmd: "/opt/desktop/start.sh", // runs as the container's main process readyCmd: "curl -sf http://127.0.0.1:7000/health", // create() waits for it resources: { shmMB: 1024, memoryMB: 4096, vcpus: 2 }, // template defaults }, { onEvent: (e) => e.type === "log" && console.log(e.line) } ); const sandbox = await client.create({ template: desktop, ports: [6080, 7000], // noVNC + control server volumes: [{ id: "agent-home", mountPath: "/home/agent" }], metadata: { app: "agent" }, }); const vnc = await sandbox.ports!.expose(6080); const control = await sandbox.ports!.expose(7000); // vnc.url -> http://127.0.0.1: (vnc.wsUrl -> ws://127.0.0.1:) const res = await sandbox.ports!.fetch(7000, "/screenshot"); ``` * **`resources.shmMB` sets `HostConfig.ShmSize`.** Docker's default `/dev/shm` is 64 MB, and Chromium crashes with it. Give it 1024 MB or more. * **Ports must be declared at create.** Docker can't publish a port on a running container, so `ports.expose(port)` throws a `Validation` error for an undeclared port. * **The rebuild is skipped when nothing changed.** The image is labelled `sbox.cacheKey=`, and a second `build()` with the same Dockerfile, context and options finds it again. ## Templates [#templates] `client.templates.build()` calls `POST /build` with a tar of the context plus the Dockerfile. It streams every progress line to `onEvent` and tags the result `sbox/:latest`, with the labels `sbox.cacheKey`, `sbox.template` and `sbox.startCmd` / `sbox.readyCmd` / `sbox.resources`. The template's `env`, `workdir` and `user` are appended to the Dockerfile as `ENV` / `WORKDIR` / `USER`, so they are baked into the image. | Source | What happens | | ---------------- | ----------------------------------------------------------------------------------------------- | | `{ dockerfile }` | builds with your context (a directory path or in-memory files) | | `{ image }` | pulls it (`registryAuth` is sent as `X-Registry-Auth`), then builds `FROM` it to add the labels | | `{ snapshot }` | builds `FROM` a snapshot image | `templates.get(idOrKey)` finds an image by cache key, by template name (`sbox/:latest`) or by any image reference. Images are only ever built and tagged locally. The adapter **never pushes** to a registry. `template` at create time can also be any plain image reference, for example `"python:3.12-slim"`. It's pulled if it's missing, and the `onPull` option receives the progress. ## Exec, stdin and processes [#exec-stdin-and-processes] `commands.run()` creates an exec and hijacks the HTTP connection from `exec/start`. It demultiplexes Docker's 8-byte-header stream, so stdout and stderr stream separately and in real time. The exit code comes from `GET /exec/{id}/json`. `cwd`, `env` and `user` are passed natively, and `timeoutMs` kills the command and rejects with `Timeout`. `kill(signal)` sends the signal to the command and every process it started. Docker reports exec pids in the daemon's pid namespace, so each command first prints its own in-container pid on a private marker, which the adapter strips from the output. The kill itself runs in a second exec. The default signal is `KILL`. stdin is attached through the hijacked socket: ```ts const h = sandbox.commands.run("python3 -i"); await h.writeStdin("print(6 * 7)\n"); await h.writeStdin(new Uint8Array()); // a zero-length write sends EOF const { stdout } = await h; ``` * **`run()`** closes stdin right after start, unless you call `writeStdin()` before the process starts. A command that reads stdin, such as `apt-get` prompts, therefore sees EOF instead of hanging. * **`spawn()`** keeps stdin open for later writes. End it with a zero-length write. `commands.list()` reads `/proc`. `commands.connect(pid)` works for processes this client spawned, because Docker can't re-attach to another client's exec. ## Files [#files] | Call | Engine API | | ----------------------------------- | ------------------------------------------------------------------------------------------------------ | | `write`/`upload` | `PUT /containers/{id}/archive?path=` with a one-file tar. Missing parent directories are created. | | `read`/`download` | `GET /containers/{id}/archive?path=…`, unpacked by a built-in tar reader. Symlinks are followed. | | `stat`/`exists` | `HEAD /containers/{id}/archive`, which returns the `X-Docker-Container-Path-Stat` header | | `list`, `mkdir`, `remove`, `rename` | exec (`ls`, `mkdir`, `rm`, `mv`) | Binary files of any size round-trip. Files are written with the container user's ownership (`copyUIDGID`). ## PTY [#pty] `sandbox.pty.create()` creates an exec with `Tty: true` and an initial `ConsoleSize`. It runs `bash -l` (or `sh -l`) unless you pass `cmd`. `resize()` calls `POST /exec/{id}/resize`, and `wait()` returns the shell's exit code. ```ts const term = await sandbox.pty!.create({ cols: 120, rows: 40 }); for await (const chunk of term) process.stdout.write(chunk); ``` ## Lifecycle [#lifecycle] | Method | Engine API | Notes | | -------------- | -------------------------------------------- | ----------------------------------- | | `pause()` | `POST /containers/{id}/pause` | cgroup freezer; **memory is kept** | | `stop()` | `POST /containers/{id}/stop` | processes end; **the disk is kept** | | `resume()` | `unpause` or `start`, depending on state | waits for the template's `readyCmd` | | `setTimeout()` | an exec that stops the container after `ttl` | calling it again re-arms the timer | | `destroy()` | `DELETE /containers/{id}?force=1&v=1` | also removes anonymous volumes | `getInfo()` inspects the container each time and maps `State.Status` like this: `running`→`running`, `paused`→`paused`, `created`/`exited`→`stopped`, `restarting`→`creating`, `removing`→`destroyed`, `dead`→`error`. `idempotencyKey` becomes the label `sbox.idempotency` and a deterministic container name. A create with the same key returns the existing container, even when two creates race. `getOrCreate({ name })` looks the name up in the `sbox.name` label and resumes the container if it's stopped or paused. ## Snapshots and forks [#snapshots-and-forks] ```ts const snap = await sandbox.snapshots!.create({ name: "after-setup" }); // snap.id === "sbox-snapshot/:after-setup" const copy = await client.create({ fromSnapshot: snap }); const [a, b] = await sandbox.fork({ count: 2 }); await sandbox.snapshots!.list(); // images labelled with this container's id await sandbox.snapshots!.delete(snap); ``` A snapshot is `POST /commit`, which writes a local image. It captures the **filesystem only** (`includesMemory: false`), and `snapshots.create({ mode: "memory" })` throws `Validation`. Use `pause()` when you need to keep memory. `fork(count)` commits once and starts `count` containers with the parent's resources, ports (new host ports), mounts and metadata. The fork image is removed when the last child is destroyed. Snapshot images keep the image's original `ENV`, so secrets passed as env aren't baked into them. ## Ports and previews [#ports-and-previews] `previewModel` is `"ip"`. Declared ports are bound to `127.0.0.1` on a random host port. Set `bindIp` to change that, but think twice before exposing a sandbox to your LAN. `ports.expose(port)` and `ports.list()` return `{ url: "http://127.0.0.1:", wsUrl: "ws://…", auth: { type: "public" } }`. `ports.fetch(port, path)` goes through the published port. For a port that wasn't declared, it falls back to the container's IP address. That works on Linux and OrbStack, but not on Docker Desktop. There are no private previews: anything on localhost can reach a published port. ## Egress [#egress] | Policy | What the adapter does | | ------------------------------ | ---------------------------------------------------------- | | `block-all` at create | `HostConfig.NetworkMode: "none"` | | `block-all` later | disconnects the container from every network | | `allow-all` | connects the `network` option's network (default `bridge`) | | `allow-list`, `deny`, `inject` | throws `Validation` | Docker only has network **on or off**. It can't filter by domain or CIDR, and it can't inject credentials. Run an egress proxy you control if you need an allow-list. While the network is blocked, declared ports aren't published. `allow-all` publishes them again, possibly on new host ports, so call `ports.expose()` again afterwards. ## Volumes [#volumes] `client.volumes` maps to `/volumes`. A volume's `id` is its name, and mounts use it. An absolute host path in `volumes[].id` becomes a bind mount. ```ts await client.volumes!.create({ name: "agent-home" }); await client.create({ volumes: [{ id: "agent-home", mountPath: "/home/agent" }], }); await client.create({ volumes: [{ id: "/Users/me/project", mountPath: "/work", readOnly: true }], }); ``` `volumes.list()` only shows volumes the adapter created (label `sbox.managed=true`). `sizeMB` is recorded as a label, but the `local` driver doesn't enforce it. ## Metrics [#metrics] `sandbox.metrics()` reads `GET /containers/{id}/stats?stream=false`. `cpuPercent` uses the `docker stats` formula, where 100% equals one full core. `memoryUsedMB` excludes the page cache, and `memoryTotalMB` is the limit. The call takes about a second, because the daemon samples twice. ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------------------------ | :---------: | ----------------------------------------------------- | | `list` / `stop` / `pause` / `setTimeout` | native | `preservesMemoryOnPause` and `preservesDiskOnStop` | | `streaming` / `background` / `killProcess` | native | hijacked exec, demultiplexed; kills the process tree | | `stdin` | native | zero-length `writeStdin` sends EOF | | `pty` | native | `Tty: true` exec + resize | | `filesUpload` | native | tar over `/archive` | | `exposePort` | native | ports declared at create, on `127.0.0.1` | | `proxiedFetch` | native | published port, or the container IP where routable | | `egressControl` | native | on/off only; `allow-list` throws | | `snapshot` / `fork` | native | `commit`, filesystem only | | `templateBuild` | native | `dockerfile`, `image`, `snapshot` sources | | `volumes` | native | named volumes; absolute paths become bind mounts | | `metrics` | native | `/stats` | | `gpu` | native | `DeviceRequests` (needs the NVIDIA container toolkit) | | `privatePreview` | unsupported | published ports are plain localhost | | `ssh` / `codeInterpreter` / `filesWatch` | unsupported | | | `region` / `secretsVault` | unsupported | `secrets` with no `value` are read from the host env | ### How the spec maps [#how-the-spec-maps] | sbox | Docker | | ---------------------------------------- | ---------------------------------------------------------------- | | `template` / `fromSnapshot` | `Image` (pulled if missing) | | `env`, env-mode `secrets` | `Env` | | `metadata` | labels `sbox.meta.` | | `name` / `idempotencyKey` | labels `sbox.name` / `sbox.idempotency`, plus the container name | | `resources.vcpus` / `memoryMB` / `shmMB` | `NanoCpus` / `Memory` / `ShmSize` | | `resources.gpu` / `gpuCount` | `DeviceRequests` (`gpu: "0,1"` selects device ids) | | `ports` | `ExposedPorts` + `PortBindings` (`127.0.0.1`, random host port) | | `volumes` | `Mounts` (`volume`, or `bind` for absolute paths) | | `network: { mode: "block-all" }` | `NetworkMode: "none"` | | `lifecycle.maxAgeMs` | the container stops itself after that long (see `setTimeout`) | ## Known limitations [#known-limitations] * **No egress allow-lists.** See [Egress](#egress). The shared conformance check for `allow-list` is skipped for this adapter. `block-all` and `allow-all` are covered by the adapter's own live tests. * **No idle timeout.** `idleTimeoutMs` and `autoResume` are ignored. `maxAgeMs` and `setTimeout()` always **stop** the container, whatever `onIdle` says. A container can't pause or delete itself from inside. * **`diskMB` and `region` are ignored.** Disk quotas depend on the storage driver. * **No in-place snapshot restore.** Boot a new container with `fromSnapshot`. * **`mode: "egress"` secrets throw `Validation`.** There's no proxy to inject them. * **One client owns its execs.** `commands.connect()` and `pty.connect()` only find sessions this process started. * **Commit pauses the container briefly** while the filesystem is captured. --- # E2B (/adapters/e2b) The reference cloud adapter. Code interpreter, memory pause/resume, memory or filesystem snapshots, fork, PTY, egress rules with secret injection, volumes, and Dockerfile template builds. Backed by @e2b/code-interpreter. ## Installation [#installation] `@e2b/code-interpreter` (≥ 2.9, which bundles `e2b` ≥ 2.64) is an optional peer dependency of `sbox-sdk`. The adapter loads it lazily the first time you use it, so install it next to the SDK: pnpm bun npm yarn ```bash pnpm add sbox-sdk @e2b/code-interpreter ``` ```bash bun add sbox-sdk @e2b/code-interpreter ``` ```bash npm install sbox-sdk @e2b/code-interpreter ``` ```bash yarn add sbox-sdk @e2b/code-interpreter ``` ## Authentication [#authentication] `apiKey` falls back to `E2B_API_KEY`, and `domain` falls back to `E2B_DOMAIN`. Every SDK call (sandboxes, templates, volumes, secrets) goes through one client bound to these options, so a self-hosted or BYOC `domain` applies everywhere. ## Quickstart [#quickstart] ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY }), }); const sandbox = await client.create({ lifecycle: { maxAgeMs: 10 * 60_000, onIdle: "pause", autoResume: true }, metadata: { job: "demo" }, }); const r = await sandbox.commands.run("python3 -c 'print(6 * 7)'"); console.log(r.stdout); // "42\n" // The default template is E2B's code interpreter, so `sandbox.code` works: const exec = await sandbox.code.runCode("import sys; sys.version"); console.log(exec.results[0]?.text); await sandbox.destroy(); ``` `template` takes an E2B template name or id (for example `"base"`, `"my-app:v2"`, or a `TemplateRef` from `client.templates.build()`). `fromSnapshot` takes a snapshot id; on E2B, restoring a snapshot always boots a **new** sandbox, so use `client.create({ fromSnapshot })` (`snapshots.restore()` isn't offered). ## Options [#options] ## Templates (Dockerfile builds) [#templates-dockerfile-builds] `client.templates.build()` builds in **your** E2B team with `Template().fromDockerfile()` + `Template.build()`. Templates stay private to your team: the adapter never publishes them. Builds are cached by content hash. The template is named `-`, so an unchanged spec is found again instead of rebuilt. ```ts const tpl = await client.templates.build( { name: "borat-desktop", source: { dockerfile: await readFile("desktop/Dockerfile", "utf8"), context: "./desktop", // a directory (Node), or { "path": contents } }, user: "root", workdir: "/app", env: { DISPLAY: ":1" }, startCmd: "/usr/local/bin/start-vnc.sh", readyCmd: "curl -sf http://localhost:6080/vnc.html", resources: { vcpus: 2, memoryMB: 4096, diskMB: 8192 }, }, { onEvent: (e) => e.type === "log" && console.log(e.line) } ); const desktop = await client.create({ template: tpl }); ``` * **Sources:** `dockerfile` (+ `context`), `image` (with optional `registryAuth`), or `snapshot` (builds on top of an E2B snapshot with `fromTemplate`). * **Context:** files are written to a temp directory and passed as the builder's `fileContextPath`, so `COPY`/`ADD` work. A Dockerfile build therefore needs Node (or Bun/Deno with `node:fs`). Multi-stage Dockerfiles aren't supported by E2B. * **`startCmd`** runs once during the build and is captured in the memory snapshot, so it's already running when a sandbox boots. If you set `startCmd` without `readyCmd`, the build waits 20 s. Pass a `readyCmd` instead. * **`env`** maps to `setEnvs()`, the same as a Dockerfile `ENV`. **`resources`**: `vcpus` → `cpuCount`, `memoryMB` → `memoryMB`, `diskMB` → `minFreeDiskMb` (minimum free space after the build, best effort). * Build logs stream through `onEvent` (`error`-level lines arrive with `stream: "stderr"`). ## Previews and browser auth [#previews-and-browser-auth] Every port is reachable at `https://-.`. Visibility is set **per sandbox**, not per port: * `e2b({ allowPublicTraffic: false })` creates private sandboxes. Every request must carry the sandbox's traffic token in the `e2b-traffic-access-token` header, and `ports.expose()` returns `auth: { type: "header", headers: { "e2b-traffic-access-token": "…" } }`. * With public traffic, `expose()` returns `auth: { type: "public" }`, and `expose(port, { visibility: "private" })` throws `Validation` instead of handing back a public URL. ```ts const client = createSandboxClient({ provider: e2b({ allowPublicTraffic: false }), }); const sb = await client.create({ template: tpl }); const vnc = await sb.ports.expose(6080, { visibility: "private" }); const res = await sb.ports.fetch(6080, "/vnc.html"); // token header added for you ``` E2B's edge proxy reads the traffic token **only** from the `e2b-traffic-access-token` request header. There is no query-string token, cookie, or signed URL (verified against the proxy source in `e2b-dev/runtime`, `packages/shared/pkg/proxy/ingress.go`). Browsers can't set custom headers on a WebSocket, so `flags.previewBrowserAuth` is `false` and `browserUrl()` throws for private E2B previews. For noVNC in a browser, either use a public sandbox (and treat the URL as a secret) or put a small proxy you control in front that adds the header. `ports.fetch()` uses the adapter's native `proxyFetch`: it goes through E2B's proxy, adds the token header when there is one, and never makes anything public. ## Lifecycle [#lifecycle] | `SandboxSpec` | E2B | | ------------------------- | ----------------------------------------------------------------------------------------------- | | `lifecycle.maxAgeMs` | `timeoutMs` (wall clock; `setTimeout()` extends it) | | `lifecycle.idleTimeoutMs` | used as `timeoutMs` when `maxAgeMs` is unset. E2B has no idle timer: activity doesn't reset it. | | `onIdle: "pause"` | `lifecycle.onTimeout: "pause"` (memory + disk) | | `onIdle: "stop"` | `onTimeout: { action: "pause", mode: "filesystem" }` (disk only; resume reboots) | | `onIdle: "destroy"` | `onTimeout: "kill"` (E2B default) | | `autoResume: true` | `lifecycle.autoResume` (requires `onIdle: "pause"`) | `pause()` keeps memory. `resume()` reconnects, and the id doesn't change. `getInfo()` and `list()` report the live state (`running`, `paused`, and so on). ## Network, secrets and volumes [#network-secrets-and-volumes] * **Egress** (`spec.network`, `sandbox.network.setEgressPolicy`): `allow-list` → `allowOut` + `denyOut: ["0.0.0.0/0"]`, `block-all` → `denyOut: ["0.0.0.0/0"]`, `allow-all` + `deny.cidrs` → `denyOut`. E2B deny rules take CIDRs and IPs only, so `deny.domains` throws `Validation`. Runtime updates replace the whole egress config. * **Credential injection** (`network.inject`) becomes E2B per-host request transforms that use `Secret.fill(name)`. The egress proxy injects the value into outbound **HTTPS** requests, and the secret never enters the sandbox. A `SecretRef` with a `value` is stored (created or updated) as an E2B secret first. A plain string header value is read as the name of an existing E2B secret. An injection host still has to be allowed by the policy. * **`spec.secrets`:** `mode: "env"` needs an inline `value` (E2B secrets are write-only and can't be read back into env vars). `mode: "egress"` with a `value` stores the secret for use in `inject`. * **Volumes:** `client.volumes.create/get/list/delete` wrap E2B's `Volume` (no size or region options). `spec.volumes` maps to `volumeMounts` by volume name (an id is resolved to its name). E2B mounts can't be read-only, so `readOnly: true` throws. ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------------------------ | :---------: | --------------------------------------------------------------------------------- | | `list` / `pause` / `setTimeout` | native | list paginates and filters by metadata and state on the server | | `stop` | unsupported | use `onIdle: "stop"` (filesystem-only auto-pause) or `pause()` | | `background` / `streaming` / `killProcess` | native | stdout and stderr stay separate; `kill` is SIGKILL | | `stdin` | native | `writeStdin` on `commands.spawn()` processes; `commands.run()` keeps stdin closed | | `pty` | native | `pty.create` / `pty.connect`, no SDK session timeout | | `filesWatch` / `filesUpload` | native | streaming upload and download | | `codeInterpreter` / `statefulKernel` | native | needs a code-interpreter template (the default) | | `exposePort` / `privatePreview` | native | private = header auth; `previewBrowserAuth: false` | | `proxiedFetch` | native | through E2B's proxy with the token header | | `egressControl` / `secretsVault` | native | allow/deny lists, runtime updates, secret injection | | `snapshot` / `fork` | native | `mode: "filesystem"` → `includesMemory: false`; fork captures memory | | `volumes` / `templateBuild` | native | sources: `dockerfile`, `image`, `snapshot` | | `metrics` | native | latest sample (may be empty for a few seconds after boot) | | `ssh` / `gpu` / `region` | unsupported | | Flags: `preservesMemoryOnPause: true`, `perCommandEnvCwd: true` (cwd, env and `user` are passed natively), `exitCodeNative: true`, `resumeChangesId: false`, `previewModel: "subdomain"`. ## Known limitations [#known-limitations] * **Private previews are header-only** (see above). Browser WebSockets need a public sandbox or your own proxy. * `resources.memoryMB` / `diskMB` / `shmMB` aren't create-time options on E2B. Memory and disk come from the template (`templates.build({ resources })`). For `shmMB`, the adapter remounts `/dev/shm` as root right after boot, and if that fails, it kills the sandbox and throws. * Named sandboxes (`spec.name`, `getOrCreate`) are stored in the `sbox-name` metadata key. E2B's own `info.name` is the *template* name. * `idempotencyKey` uses E2B's native `Idempotency-Key`. Keys outside `[a-z0-9-]{1,255}` are hashed (SHA-256) so retries still match. E2B keeps keys for 24 h. * `fork()` is all-or-nothing: if any fork fails, the ones that succeeded are killed and the error is thrown. * Commands default to **no** E2B-side timeout (E2B's SDK default is 60 s, which would kill long-running servers). Pass `timeoutMs` to bound a command. --- # Fly Machines (/adapters/fly) A sandbox per Fly Machine over the Machines REST API. Pure fetch, no SDK, so it runs anywhere the core does, including the edge. ## Installation [#installation] No provider SDK required: the adapter talks to the Fly Machines REST API with `fetch` (the client's `fetch`, so tests and proxies can inject their own). pnpm bun npm yarn ```bash pnpm add sbox-sdk ``` ```bash bun add sbox-sdk ``` ```bash npm install sbox-sdk ``` ```bash yarn add sbox-sdk ``` ## Authentication [#authentication] You need an API token (`fly tokens create deploy -a ` or an org token) and an **existing app**: each sandbox is a Machine inside it. The live tests read `FLY_API_TOKEN`, `FLY_APP_NAME` and optionally `FLY_REGION`. ## Quickstart [#quickstart] ```ts import { createSandboxClient } from "sbox-sdk"; import { fly } from "sbox-sdk/fly"; const client = createSandboxClient({ provider: fly({ apiToken: process.env.FLY_API_TOKEN!, appName: process.env.FLY_APP_NAME!, // must already exist region: "iad", }), }); const sandbox = await client.create({ template: "node:22", // any image; default ubuntu:22.04 resources: { vcpus: 2, memoryMB: 1024, diskMB: 8192 }, metadata: { team: "agents" }, }); const res = await sandbox.commands.run("node -v"); console.log(res.stdout); await sandbox.destroy(); ``` `template` is the Machine's container image. Machines boot with `init.exec = ["sleep","inf"]` and `restart: { policy: "no" }`, so plain images (whose `CMD` would exit) stay up and a stopped machine stays stopped. Pass `keepAlive: false` for images that run their own long-lived process. ## How it maps [#how-it-maps] | Spec field | Fly Machines API | | ------------------------ | ---------------------------------------------------------------------------------------------- | | `template` | `config.image` | | `env` | `config.env` | | `metadata` | `config.metadata` (filterable server-side with `metadata.=` on list) | | `resources` | `guest.cpus`, `guest.memory_mb` (rounded up to 256 MB, 1024 for performance), `rootfs.size_gb` | | `region` | `region` | | `ports` | machine `services` (see previews) | | `lifecycle.onIdle` | `services[].autostop` (`pause` → `suspend`, `stop` → `stop`), `autoResume` → `autostart` | | `volumes` | `config.mounts` (Fly allows one volume per machine) | | `secrets` (with `value`) | app secret (`POST /apps/{app}/secrets/{name}`) + `min_secrets_version` | | `idempotencyKey` | `sbox-idem` metadata; a retried create returns the existing machine | The root filesystem uses `rootfs.persist = "always"` (opt out with `persistRootfs: false`), so files survive `stop()`/`resume()` and the restarts caused by config updates. ## Exec and files [#exec-and-files] * `/exec` is buffered and limited to **600 s per command**. `timeoutMs` is passed through (clamped); commands without one get `execTimeoutSec` (default 600). Longer jobs should be started detached (`nohup … &`) and polled. * `kill()` finds the command through `/ps` (every exec carries a unique `$0` marker) and SIGKILLs its process tree from inside the machine. `commands.list()` is `/ps`; `commands.kill(pid)` signals any pid. * File writes send the bytes in the exec request's `stdin` field (never argv), in 768 KiB chunks, so large and binary files round-trip. Reads fall back to chunked `dd` when a response would exceed Fly's output limit. * There is no per-command `cwd`/`env`, so the core wraps the command (`perCommandEnvCwd: false`). ## Previews [#previews] Fly routes per **app**, not per machine: the URL is always `https://.fly.dev` (or `appDomain`). `ports.expose(port)` adds a machine service (the first port on 443, later ones on their own number) and returns: ```ts const p = await sandbox.ports.expose(8080); // { url: "https://my-app.fly.dev", auth: { type: "header", headers: { "fly-force-instance-id": "" } } } await sandbox.ports.fetch(8080, "/health"); // adds the header for you ``` The `fly-force-instance-id` header pins the request to this machine; without it Fly Proxy may route to any machine of the app that serves the same port. Because it is a header, it can't be set from a browser WebSocket (`previewBrowserAuth: false`). It is a routing header, not authentication: the service is public. The app needs a public IP (`fly ips allocate-v6`, or a shared v4). Exposing a port on a running machine updates its config, which **restarts** the machine (files survive thanks to `rootfs.persist`, processes do not). Declare ports up front with `spec.ports` to avoid the restart. ## Volumes and secrets [#volumes-and-secrets] ```ts const vol = await client.volumes.create({ name: "data", sizeMB: 10_240, region: "iad", }); const sb = await client.create({ region: "iad", volumes: [{ id: vol.id, mountPath: "/data" }], }); ``` `secrets: [{ name: "API_KEY", value }]` writes an **app secret**, which every machine in the app can read. A secret without `value` must already exist and is exposed under its own name. ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ----------------------------- | :---------: | ----------------------------------------------- | | `list` / `region` | native | `fly-next-cursor` pagination | | `stop` / `pause` | native | `pause` = suspend (memory kept) | | `killProcess` | native | `/ps` + `kill` inside the machine | | `exposePort` / `proxiedFetch` | native | app URL + `fly-force-instance-id` | | `volumes` / `secretsVault` | native | Fly volumes; app secrets | | `streaming` | emulated | `/exec` is buffered | | `privatePreview` | unsupported | Fly previews are public; the header only routes | | `gpu` | unsupported | the Machines API rejects GPU requests | | `snapshot` / `fork` | unsupported | volume snapshots are not machine snapshots | | `setTimeout` / `background` | unsupported | | | `pty` / `ssh` / `stdin` | unsupported | `/exec` has no interactive stream | Flags: `perCommandEnvCwd: false`, `preservesMemoryOnPause: true`, `preservesDiskOnStop: true` (with `persistRootfs`), `previewModel: "declaredPorts"`. ## Limitations [#limitations] * 600 s per exec call; output is returned only when the command ends. * `lifecycle.idleTimeoutMs` and `maxAgeMs` have no Fly equivalent (Fly Proxy decides when an idle service autostops). * `verify()` calls `GET /apps/{app}` and returns the org slug. --- # Freestyle (/adapters/freestyle) Full Linux KVM VMs from Freestyle through the freestyle SDK. Exec, reattachable PTY sessions, files readable while paused, pause/resume with memory, memory+disk snapshots and fork, style.dev preview domains, allow-only firewall plus TLS egress with header injection, SSH, and snapshot templates (with an emulated Dockerfile build). ## Installation [#installation] `freestyle` (≥ 0.2.20) is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk freestyle ``` ```bash bun add sbox-sdk freestyle ``` ```bash npm install sbox-sdk freestyle ``` ```bash yarn add sbox-sdk freestyle ``` Freestyle now publishes the `freestyle` package. The old `freestyle-sandboxes` package isn't used by this adapter; uninstall it when you switch. ## Authentication [#authentication] | Option | Env var | Required | Description | | --------- | -------------------- | -------- | -------------------------------------------------------------------- | | `apiKey` | `FREESTYLE_API_KEY` | yes | Account API key. The SDK reads the env var when you omit the option. | | `baseUrl` | `FREESTYLE_BASE_URL` | no | API URL override. | `client.verify()` lists one VM, so it never creates anything. ## Quickstart [#quickstart] ```ts import { createSandboxClient } from "sbox-sdk"; import { freestyle } from "sbox-sdk/freestyle"; const client = createSandboxClient({ provider: freestyle({ apiKey: process.env.FREESTYLE_API_KEY! }), }); const sandbox = await client.create({ resources: { vcpus: 8, memoryMB: 16_384 }, // picks freestyle/ubuntu-lg env: { NODE_ENV: "development" }, network: { mode: "allow-list", domains: ["registry.npmjs.org"] }, lifecycle: { idleTimeoutMs: 10 * 60_000 }, }); const r = await sandbox.commands.run("node -v", { cwd: "/tmp" }); console.log(r.stdout, r.exitCode); const term = await sandbox.pty!.create({ cols: 120, rows: 30 }); await term.write("htop\n"); const again = await sandbox.pty!.connect(term.id); // reattach from anywhere const [copy] = await sandbox.fork(); // memory + disk await sandbox.pause(); await sandbox.files.read("/etc/hostname"); // reads work while paused await sandbox.destroy(); ``` `template` and `fromSnapshot` both take a snapshot id or slug, including the public bases (`freestyle/ubuntu`, `freestyle/ubuntu-sm` … `freestyle/ubuntu-2xl`, `freestyle/busybox`). Without one, `resources` pick the smallest Ubuntu base that fits (up to 32 vCPU / 64 GiB); otherwise the platform default is used. ## Options [#options] ## Exec [#exec] * `vm.exec()` is request/response. Output arrives when the command ends (`streaming: "emulated"`), with stdout and stderr separate and the real exit code. * Freestyle has no per-command `cwd`, so the core runs `cd && …` for you (`perCommandEnvCwd: false`). Env vars are passed natively. * `timeoutMs` is passed natively. Without one, the adapter uses `execTimeoutMs` (default five minutes, the platform cap on VMs without the native agent; Freestyle's own default is 30 s). A timeout throws `Timeout`. For longer work, use a PTY or `nohup … &`. * `kill()` works: every command records its shell's pid in `/tmp`, and kill runs a second exec that kills that process tree (`pgrep -P` + `kill -9`). * No background processes, live stdin or process ids (`background`, `stdin`, `killProcess` are unsupported). Use a PTY session for long-running or interactive programs. ## Templates (snapshots) [#templates-snapshots] Freestyle templates are snapshots: set a VM up, snapshot it, boot from the snapshot. `client.templates.build()` accepts: * `{ snapshot }`: boots that snapshot, applies `env`/`workdir`/`startCmd`/`readyCmd`, and snapshots the result. * `{ dockerfile }`: an **emulated build**. Freestyle has no image builder, so the adapter boots a base VM and replays the Dockerfile: * `FROM` must name a VM snapshot, not an OCI image: `ubuntu`/`ubuntu:24.04` (sized by `resources`), `busybox`, `freestyle/`, or a snapshot id. Anything else, such as `python:3.12`, throws `NotSupportedError`. * `RUN` runs through exec as root (or the `USER`), in the current `WORKDIR`, with `ENV` applied. Each step is limited to `execTimeoutMs`. * `COPY`/`ADD` write context files through the filesystem API (no size limit; `--chmod` and `--chown` are honored). Multi-stage builds, `--from`, `RUN --mount` and `ADD ` aren't supported. * `CMD`/`ENTRYPOINT` (or `startCmd`) start under `nohup` before the snapshot. The snapshot captures memory, so the process is already running in every sandbox. `readyCmd` is polled every 2 s for up to 10 minutes first. ```ts const tpl = await client.templates.build( { name: "vite-app", source: { dockerfile: "FROM ubuntu:24.04\nCOPY . /app\nWORKDIR /app\nRUN npm ci\n", context: "./app", }, startCmd: "npm run dev -- --host 0.0.0.0", readyCmd: "curl -fs localhost:5173", }, { onEvent: (e) => e.type === "log" && console.log(e.step, e.line) } ); const sandbox = await client.create({ template: tpl }); ``` The snapshot's slug is `sbox-`, so `lookup(cacheKey)` and later builds reuse it. Build logs arrive per step (exec output comes at the end of each step). The build VM is deleted afterwards, even when a step fails. ## Previews [#previews] `ports.expose(port)` creates a TLS ingress rule that routes a free `style.dev` name (`https://sbox--.style.dev`) to the port, with `auth: { type: "public" }`. Pass `previewDomain` to publish under a domain you've verified with Freestyle. `spec.ports` are published at create. `unexpose()` deletes the rule. Private previews aren't supported: Freestyle gates ingress with forward auth or Freestyle login, not with a per-port token. Put your own auth in front with forward auth through `raw()`. ## Lifecycle [#lifecycle] | `SandboxSpec` | Freestyle | | -------------------------- | --------------------------------------------------------------------------------------------------------------- | | `lifecycle.idleTimeoutMs` | `idleTimeoutSeconds`: pause after that long without network or terminal activity | | `lifecycle.maxAgeMs` | `maxRunSeconds` (pause after one run lasts that long), or `ttlSeconds` with `onIdle: "destroy"` | | `onIdle: "destroy"` + idle | `autoDeleteSeconds: 0`: the VM is ephemeral, deleted whenever it stops running, including an explicit `pause()` | | `setTimeout(ms)` | `update({ ttlSeconds })`: a deletion deadline `ms` from now | `getInfo()` maps every state (`starting` → `creating`, `running`, `pausing` → `suspending`, `paused`, `stopped`). `pause()` keeps memory, and `resume()` is `vm.start()`. `destroy()` deletes the VM, its firewall and TLS rules, and any SSH identities this handle created. VMs wake on their own for exec, writes and inbound traffic. ## Network and secrets [#network-and-secrets] Every Freestyle VM states its egress explicitly. The adapter translates `EgressPolicy`: * `allow-all` (the default): a firewall rule to `{ public: true }`. * `block-all`: no egress rules. Mapped domains and SSH still reach the VM. * `allow-list`: firewall rules for each CIDR, plus a TLS allow rule for each domain (exact, `*.suffix`, or `*`). The edge checks the SNI, and no public firewall grant is needed. * `inject`: a TLS rule per domain whose transform adds the headers at the edge. The secret never enters the VM. `SecretRef` values must be inline (Freestyle has no secret store), and clients in the VM must trust the Freestyle CA the platform installs (`NODE_EXTRA_CA_CERTS=/etc/ssl/certs/ca-certificates.crt` for Node). * `deny` isn't supported: Freestyle rules are allow-only. `setEgressPolicy()` replaces the egress rules this adapter owns (firewall rules tagged `sbox:egress`, and the VM's TLS egress rules) and leaves your other rules alone. A `SecretRef` without a value throws `NotSupportedError`; one with a value becomes an env var. Env vars set at create are stored in `/etc/sbox-env.json` inside the VM and passed to every exec and PTY, including after `connect()` and in forks and template builds. ## SSH [#ssh] `sandbox.ssh!.create()` creates a Freestyle identity scoped to the VM and mints a token. Freestyle SSH puts the token in the username, so the result is `{ host: "beta-ssh.freestyle.sh", port: 22, user: ":", privateKey: "" }`: connect with `ssh @`. The identity is deleted when this handle destroys the VM. ## Snapshots and fork [#snapshots-and-fork] `snapshots.create()` captures memory and disk (`includesMemory: true`), and `client.create({ fromSnapshot })` boots one. `sandbox.fork({ count })` snapshots the VM, creates `count` VMs from it with the same egress policy, metadata and env, then deletes the intermediate snapshot. Injected headers read back as `***`, so a VM you only `connect()`ed to forks without its `inject` rules. There's no in-place restore. ## Capabilities [#capabilities] | Capability | Level | Notes | | ---------------------------------------------------------------------------------------------- | :---------: | ----------------------------------------------------------- | | `list` / `pause` / `setTimeout` | native | list filters by metadata and state on the server, paginated | | `stop` | unsupported | power off from inside the guest | | `streaming` | emulated | exec returns output at the end | | `background` / `killProcess` / `stdin` | unsupported | use a PTY | | `pty` | native | reattachable sessions with scrollback | | `filesUpload` | native | chunked, resumable, verified by sha256 | | `filesWatch` | unsupported | | | `exposePort` | native | `style.dev` or your verified domain | | `privatePreview` | unsupported | forward auth only | | `egressControl` | native | allow-only firewall, TLS domain allows, header injection | | `ssh` | native | token in the username, no key pair | | `snapshot` / `fork` | native | memory + disk | | `templateBuild` | native | snapshot sources; Dockerfile builds are emulated | | `volumes` / `secretsVault` / `metrics` / `gpu` / `region` / `codeInterpreter` / `proxiedFetch` | unsupported | | Flags: `perCommandEnvCwd: false`, `preservesMemoryOnPause: true`, `preservesDiskOnStop: true`, `previewModel: "subdomain"`, `templateSources: ["snapshot", "dockerfile"]`. ## Known limitations [#known-limitations] * `volumes`, `region` and GPUs throw `NotSupportedError` at create. `resources.shmMB` is ignored. * `resources` with a `template` or `fromSnapshot` grow the VM after boot. Freestyle resizes are grow-only, so smaller requests are ignored. * `getOrCreate()` is native: it derives a slug from the name, so a name that isn't slug-safe gets a short hash suffix. * `rename` and `watch` aren't native. `files.rename()` goes through exec. --- # In-Memory (/adapters/memory) An in-memory sandbox backed by Maps — the zero-config default and the conformance fixture. No dependencies, no network, non-persistent. Ideal for tests. ## Installation [#installation] The in-memory adapter has no peer dependencies and no runtime requirements — it's pure JavaScript backed by `Map`s, so it runs unchanged in Node, Bun, Deno, the browser, and edge runtimes. It's built in and is the zero-config default for `createSandboxClient()`. pnpm bun npm yarn ```bash pnpm add sbox-sdk ``` ```bash bun add sbox-sdk ``` ```bash npm install sbox-sdk ``` ```bash yarn add sbox-sdk ``` ## Usage [#usage] The in-memory provider implements the same adapter contract as every cloud provider, but stores files and runs a tiny built-in shell in process instead of touching a network. That makes it the near-universal choice for testing code that uses sbox SDK without standing up a real sandbox — and it doubles as the reference adapter for the [conformance suite](/capabilities). ```ts import { createSandboxClient } from "sbox-sdk"; import { memory } from "sbox-sdk/memory"; // A fresh, empty sandbox. Same surface as the cloud adapters, // so you can swap it in for tests without changing any call sites. const client = createSandboxClient({ provider: memory() }); const sandbox = await client.create(); await sandbox.files.write("/app/hello.txt", "hi"); const text = await (await sandbox.files.read("/app/hello.txt")).text(); // "hi" const res = await sandbox.commands.run("echo hi", { cwd: "/app" }); res.exitCode; // 0 ``` ### Exercising the filesystem polyfills [#exercising-the-filesystem-polyfills] Pass `bareFs: true` to hide the native filesystem methods, forcing the core's exec-based polyfills (`ls`, `mkdir`, `rm`, `mv`, `stat`) to run instead — useful for testing how the core behaves against providers that have no native fs primitives. ```ts import { memory } from "sbox-sdk/memory"; const client = createSandboxClient({ provider: memory({ bareFs: true }) }); ``` ## Authentication [#authentication] ## Options [#options] ## Behavior notes [#behavior-notes] * **Non-persistent.** State lives in the process. Two clients built from separate `memory()` calls don't share data. Not for production. * **Built-in mini-shell.** `commands.run` interprets a small set of POSIX commands (`echo`, `cat`, `ls`, `mkdir`, `rm`, `mv`, `stat`, `env`, …). It is not a full shell — there's no `&&`, pipes, or subshells. * **The `raw()` escape hatch** is the backing in-memory store, so a test can read or reset it directly. ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------------------------ | :---------: | ------------------------------------------------------- | | `list` / `stop` / `pause` / `setTimeout` | native | `setTimeout` is a no-op (memory sandboxes never expire) | | `background` / `streaming` / `killProcess` | native | | | `filesUpload` | native | string / `Uint8Array` only — no stream upload | | `exposePort` | emulated | returns a `127.0.0.1` preview URL | | `snapshot` / `fork` | native | in-process copies of the file map | | `codeInterpreter` / `statefulKernel` | unsupported | `sandbox.code` is `undefined` | | `egressControl` / `ssh` / `proxiedFetch` | unsupported | | --- # Modal (/adapters/modal) Modal sandboxes with streaming exec, first-class GPU, native file API and watch, PTY, filesystem snapshots, egress allow lists with header injection, secrets, volumes, regions, browser-safe connect-token previews, and private image builds. Backed by the modal JS SDK (≥ 0.11). ## Installation [#installation] `modal` (≥ 0.11) is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk modal ``` ```bash bun add sbox-sdk modal ``` ```bash npm install sbox-sdk modal ``` ```bash yarn add sbox-sdk modal ``` ## Authentication [#authentication] Credentials fall back to Modal's standard environment (`MODAL_TOKEN_ID` / `MODAL_TOKEN_SECRET`) or `~/.modal.toml` when you omit the options. Sandboxes and template builds attach to the App named `appName` (default `sbox-sdk`), which is created if missing. ## Quickstart [#quickstart] ```ts import { createSandboxClient } from "sbox-sdk"; import { modal } from "sbox-sdk/modal"; const client = createSandboxClient({ provider: modal({ appName: "my-agent" }), }); const sandbox = await client.create({ template: "python:3.13-slim", // registry image, a Modal image id (im-…), or a TemplateRef resources: { vcpus: 2, memoryMB: 2048, gpu: "A100", gpuCount: 1 }, lifecycle: { maxAgeMs: 30 * 60_000, idleTimeoutMs: 5 * 60_000 }, region: "us-east-1", metadata: { job: "demo" }, }); for await (const ev of sandbox.commands.run("nvidia-smi")) { if (ev.type === "stdout") process.stdout.write(ev.data); } await sandbox.files.write("/tmp/data.bin", new Uint8Array([0, 1, 2])); await sandbox.destroy(); ``` Since 0.11, `create()` blocks until Modal schedules the sandbox, and a lack of capacity throws `QuotaExceeded` (retryable). ## Options [#options] ## Templates (image builds) [#templates-image-builds] `client.templates.build()` builds a Modal **Image** in your workspace and publishes it **privately** (`allowPublic: false`) as `sbox-`, plus your `name` when you set one. That way `lookup(cacheKey)` finds it again and unchanged specs aren't rebuilt. ```ts const tpl = await client.templates.build({ name: "data-tools", source: { dockerfile: "FROM python:3.12-slim\nRUN pip install numpy pandas\n", }, env: { PYTHONUNBUFFERED: "1" }, workdir: "/work", }); const sb = await client.create({ template: tpl }); ``` * **Dockerfile:** the JS SDK has no `fromDockerfile`, so the adapter takes the single `FROM` as `images.fromRegistry(base)` and passes the remaining instructions to `dockerfileCommands()`. `env` / `workdir` / `user` become `ENV` / `WORKDIR` / `USER`. * **Not supported:** `COPY` or `ADD` from build context (the JS SDK can't upload context; `ADD ` and `COPY --from=` are fine), multi-stage builds, and `ARG` before `FROM`. These throw `Validation`. `startCmd` and `readyCmd` don't apply (sandboxes run their own command) and are ignored with a log line. * **Other sources:** `image` (with `registryAuth` → a `REGISTRY_USERNAME` / `REGISTRY_PASSWORD` secret) and `snapshot` (a Modal image id from `snapshots.create()`). * Modal's builder doesn't stream logs through the JS SDK, so `onEvent` gets status events plus one log line per instruction. ## Previews and browser auth [#previews-and-browser-auth] * Ports listed in `spec.ports` are tunneled at create time (`encryptedPorts`). `ports.expose(port)` returns that public tunnel URL. * `ports.expose(port, { visibility: "private" })`, or any port that wasn't declared, returns a **connect token** URL: `auth: { type: "query", param: "_modal_connect_token", token }`. Modal's proxy accepts the token as a query parameter (and then sets a cookie), so it works from a browser and a **WebSocket**: `browserUrl(preview, { protocol: "ws" })`. `flags.previewBrowserAuth` is `true`. Your server receives the verified `X-Verified-User-Data` header. ## Lifecycle [#lifecycle] | `SandboxSpec` | Modal | | ------------------------- | ----------------------------------------------------------------------- | | `lifecycle.maxAgeMs` | `timeoutMs` (Modal's default is **5 minutes**, so set this) | | `lifecycle.idleTimeoutMs` | `idleTimeoutMs`. Modal always **terminates** on idle (`onIdle` ignored) | | `name` / `idempotencyKey` | sandbox `name` (unique per App); a retried create reuses it | | `metadata` | `tags` (`list()` filters by them on the server) | `getInfo()` calls `poll()` (and `getTags()`). Modal sandboxes can't be stopped or restarted, so a finished sandbox reports `destroyed`. `list()` only returns live sandboxes in the App. `getOrCreate` is native (`sandboxes.fromName`). ## Network, secrets and volumes [#network-secrets-and-volumes] * **Egress:** `block-all` → `blockNetwork`. `allow-list` → `outboundCidrAllowlist` + `outboundDomainAllowlist` (a dimension you leave empty gets `[]`). At runtime, `setEgressPolicy` calls `updateNetworkPolicy` (`allow-all` = `["0.0.0.0/0"]` / `["*"]`). Deny rules aren't supported. * **Header injection** (`network.inject`) becomes Modal's `ExperimentalOutboundPolicy`. For a `SecretRef` header, `name` is the Modal Secret, and `envVar` (default `name`) is the key inside it. The adapter writes the header value as `$`, and Modal fills it in outside the sandbox. Plain string values are static headers. Runtime updates only work on sandboxes created with an injection policy. * **Secrets:** a `SecretRef` without a `value` → `secrets.fromName`. With a value → `secrets.fromObject`. Both are injected as env vars. * **Volumes:** `client.volumes` wraps `volumes.fromName` / `delete`, and `list` pages through the control-plane `volumeList`. `spec.volumes` mounts by name or `vo-` id. `readOnly` uses `withMountOptions({ readOnly: true })`. ## Capabilities [#capabilities] | Capability | Level | Notes | | ---------------------------------------- | :---------: | -------------------------------------------------------------------------- | | `list` / `streaming` | native | stdout and stderr stay separate | | `background` / `killProcess` / `stdin` | native | kill = process-tree kill via a pid file under `/tmp/.sbox-proc` | | `pty` | native | `exec({ pty: true })`; resize via `stty`; no reattach (`pty.connect`) | | `filesUpload` / `filesWatch` | native | `sandbox.filesystem` (`readBytes`, `writeBytes`, `watch`, …) | | `exposePort` / `privatePreview` | native | tunnels + connect tokens; `previewBrowserAuth: true` | | `egressControl` / `secretsVault` | native | allow lists, runtime updates, header injection | | `snapshot` | native | `snapshotFilesystem()` → image id; restore with `create({ fromSnapshot })` | | `volumes` / `templateBuild` | native | sources: `dockerfile`, `image`, `snapshot` | | `gpu` / `region` | native | `"A100"` / `"H100:2"`; `regions: [region]` | | `stop` / `pause` / `setTimeout` / `fork` | unsupported | `destroy()` = terminate; pause is experimental (persistent sandboxes only) | | `codeInterpreter` / `ssh` / `metrics` | unsupported | | Flags: `perCommandEnvCwd: true` (`workdir`/`env` passed natively), `exitCodeNative: true`, `previewBrowserAuth: true`, `previewModel: "tunnel"`. ## Known limitations [#known-limitations] * `kill()` needs `/proc`, `grep` and `cut` in the image (any normal Linux image). The core's timeout backstop still applies. * `resources.diskMB` and `shmMB` have no Modal equivalent and are ignored. * Memory snapshots (`mode: "memory"`) need Modal's experimental snapshot flag at create time and aren't offered. * `rename` uses the core's `mv` polyfill (the Modal filesystem API has no move). --- # Morph (/adapters/morph) A sandbox per Morph Cloud instance. Snapshot-first VMs with pause/resume, instant branching and cached setup chains, via the morphcloud SDK. Morph's TypeScript SDK (`morphcloud`) hasn't been updated since October 2025. Only the Python SDK is still maintained. This adapter is kept correct and working on `morphcloud@0.0.20`, but it won't gain new Morph features. If you are starting fresh on Morph, check the state of the TypeScript SDK first. ## Installation [#installation] `morphcloud` is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk morphcloud ``` ```bash bun add sbox-sdk morphcloud ``` ```bash npm install sbox-sdk morphcloud ``` ```bash yarn add sbox-sdk morphcloud ``` ## Authentication [#authentication] `morph()` reads `MORPH_API_KEY` when you don't pass `apiKey`. Check the key with `client.verify()`. It makes one authenticated list call and never creates anything. ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { morph } from "sbox-sdk/morph"; const client = createSandboxClient({ provider: morph({ apiKey: process.env.MORPH_API_KEY! }), }); const sandbox = await client.create({ template: "morphvm-minimal", // a Morph image id, or a snapshot_… id resources: { vcpus: 2, memoryMB: 4096, diskMB: 16384 }, env: { NODE_ENV: "production" }, lifecycle: { maxAgeMs: 30 * 60_000, onIdle: "pause", autoResume: true }, }); for await (const ev of sandbox.commands.run("npm test")) { if (ev.type === "stdout") process.stdout.write(ev.data); // real streaming } await sandbox.pause(); // memory preserved await sandbox.resume(); // same id const [a, b] = await sandbox.fork({ count: 2 }); // instance.branch() ``` Morph is **snapshot-first**: * `template: "snapshot_…"`, `fromSnapshot`, or a built template boots that snapshot directly. * Anything else is a Morph **image id**. The adapter keeps one base snapshot per `(image, vcpus, memory, disk)`, found through a digest and reused on later creates, so creating a sandbox doesn't add a new snapshot each time. * `resources` only apply when booting from an image. A snapshot keeps the resources it was taken with. ### How the spec maps [#how-the-spec-maps] | Spec | Morph | | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `metadata`, `name` | instance metadata (`name` is stored as `sbox-name`) | | `lifecycle.maxAgeMs` | `ttlSeconds` | | `lifecycle.onIdle` | `ttlAction`: `pause` → `pause`, `stop`/`destroy` → `stop` (Morph deletes the instance on stop) | | `lifecycle.autoResume` | `setWakeOn(ssh, http)` | | `env`, inline `secrets` | added to every command (Morph has no per-instance env) | | `ports` | exposed as HTTP services at create | | `idempotencyKey` | stored as metadata. A retry returns the instance that already exists | | `volumes`, `network` (anything except `allow-all`), GPUs, vault secrets | rejected with `Validation` | `lifecycle.idleTimeoutMs` and `region` have no Morph equivalent, so they're ignored. ## Templates [#templates] `client.templates.build()` chains `Snapshot.setup(cmd)`. Morph caches each step by chain hash, so an unchanged prefix of steps is reused. Three sources are accepted: ```ts // 1. A Morph image id (or a snapshot id) as the base await client.templates!.build({ source: { image: "morphvm-minimal" } }); // 2. A snapshot you already have await client.templates!.build({ source: { snapshot: "snapshot_abc" } }); // 3. A restricted Dockerfile: FROM + shell-form RUN only const tpl = await client.templates!.build({ source: { dockerfile: `FROM morphvm-minimal RUN apt-get update && apt-get install -y nodejs RUN npm i -g pnpm`, }, }); const sandbox = await client.create({ template: tpl }); ``` Every other Dockerfile instruction (`COPY`, `ENV`, `WORKDIR`, `CMD` and so on) is rejected with `Validation`. The same goes for registry images, template `env`, `workdir`, `user`, `startCmd` and `readyCmd`. The result is a snapshot tagged with the template cache key, so `templates.get(cacheKey)` finds it again. Setup output goes to the SDK's own stdout and isn't forwarded to `onEvent`. You only get one `log` event per step. ## Previews [#previews] Ports are Morph HTTP services named `sbox-`. ```ts const pub = await sandbox.ports!.expose(3000); // auth: { type: "public" } const priv = await sandbox.ports!.expose(8080, { visibility: "private" }); // priv.auth = { type: "header", headers: { Authorization: "Bearer " } } ``` Morph's private mode (`auth_mode: "api_key"`) checks for your **account API key** in an `Authorization` header. It has no query-token or signed-URL mode, so private previews don't work from a browser (`previewBrowserAuth: false`), and anyone you give the header to holds your full API key. Use public previews for anything that faces a browser. ## Capabilities [#capabilities] | Capability | Level | Notes | | -------------------------------------------------------------------------------------- | :---------: | --------------------------------------------------------------------------- | | `list` | native | filtered on the server by metadata | | `streaming` | native | SSE exec with stdout and stderr kept separate | | `pause` | native | `instance.pause()` / `resume()`. Memory preserved, id unchanged | | `setTimeout` | native | `instance.setTTL()` | | `snapshot` | native | `instance.snapshot()`. The name is stored in metadata. List and delete work | | `fork` | native | `instance.branch()`. The intermediate snapshot is deleted afterwards | | `ssh` | native | `instance.sshKey()` via `ssh.cloud.morph.so` | | `exposePort` | native | `exposeHttpService` | | `privatePreview` | native | header auth with the account API key (see above) | | `templateBuild` | native | `Snapshot.setup()` chains | | `filesUpload` | emulated | exec + base64, in 48 KB chunks so large files round-trip | | `stop` | unsupported | Morph's stop deletes the instance. Use `pause()` or `destroy()` | | `background`, `pty`, `stdin`, `egressControl`, `volumes`, `metrics`, `codeInterpreter` | unsupported | | Flags: * `perCommandEnvCwd: false`: the core adds `cwd`/`env` to the command itself. * `preservesMemoryOnPause: true` and `previewModel: "subdomain"`. * No in-place `snapshots.restore()`. To restore, boot a new sandbox with `client.create({ fromSnapshot })`. ## Known limitations [#known-limitations] * **`connect()` drops `spec.env`.** Env from `create()` is held by the handle that `create()`/`fork()` return. A sandbox you get back with `client.connect(id)` doesn't have it. * **`kill()`** ends the stream right away (exit code 137). It then kills the remote process tree with a second exec that finds processes by a per-command marker env var. A command that clears its own environment can survive this. * **`timeoutMs`** is passed to Morph in whole seconds, rounded up. On timeout the adapter also kills the remote process. * **File I/O** is exec + base64, so a 5 MB write takes about 100 exec round-trips. * `ssh.create()` returns the instance's SSH key with the instance id as the user. The exact gateway username format hasn't been checked against a live account. --- # Northflank (/adapters/northflank) A sandbox per Northflank deployment service, driven through @northflank/js-client. Streaming exec, PTYs, container snapshots, GPUs and metrics. ## Installation [#installation] `@northflank/js-client` is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. Node-only (the SDK uses Node streams and HTTP/2). pnpm bun npm yarn ```bash pnpm add sbox-sdk @northflank/js-client ``` ```bash bun add sbox-sdk @northflank/js-client ``` ```bash npm install sbox-sdk @northflank/js-client ``` ```bash yarn add sbox-sdk @northflank/js-client ``` ## Authentication [#authentication] Create an API token in the Northflank team settings and an existing project. The live tests read `NORTHFLANK_API_TOKEN`, `NORTHFLANK_PROJECT_ID` and optionally `NORTHFLANK_TEAM_ID`, `NORTHFLANK_PLAN`. ## Quickstart [#quickstart] ```ts import { createSandboxClient } from "sbox-sdk"; import { northflank } from "sbox-sdk/northflank"; const client = createSandboxClient({ provider: northflank({ token: process.env.NORTHFLANK_API_TOKEN!, projectId: process.env.NORTHFLANK_PROJECT_ID!, }), }); const sandbox = await client.create({ template: "ubuntu:24.04", resources: { vcpus: 2, memoryMB: 4096 }, lifecycle: { maxAgeMs: 2 * 60 * 60_000 }, // service expires after 2 h }); for await (const ev of sandbox.commands.run("apt-get update")) { if (ev.type === "stdout") process.stdout.write(ev.data); } await sandbox.destroy(); ``` A sandbox is a **deployment service** running the image (`deployment.external.imagePath`) with a `sleep infinity` command. `create()` waits until the deployment is `COMPLETED` (or fails) before returning. ## How it maps [#how-it-maps] | Spec field | Northflank | | -------------------------- | --------------------------------------------------------------------------------------------------------------- | | `template` | `deployment.external.imagePath` (`registryCredentials` for private images) | | `env`, inline `secrets` | `runtimeEnvironment` | | `metadata` | the service description (`sbox:{json}`), so `list()` can filter it | | `resources.vcpus/memoryMB` | smallest fitting `billing.deploymentPlan` (override with `deploymentPlan`) | | `resources.diskMB/shmMB` | `storage.ephemeralStorage.storageSize`, `storage.shmSize` | | `resources.gpu/gpuCount` | `billing.gpu.configuration` | | `lifecycle.maxAgeMs` | `createOptions.expiryTime` (5 min – 7 days; the service is paused, then deleted) | | `ports` | public HTTP ports | | `volumes` | `createOptions.volumesToAttach` (the volume's mount is set to `mountPath`) | | `fromSnapshot` | `deployment.containerSnapshot.restoreFrom` | | `name` / `idempotencyKey` | the service name; without a name it is derived from the idempotency key, so a retried create reuses the service | ## Exec, PTY and files [#exec-pty-and-files] * `commands.run()` streams over `exec.execServiceSession` with separate stdout/stderr and the real exit code; `writeStdin` feeds the session's stdin. * Each command records its shell pid in `/tmp/.sbox-.pid`; `kill()` and `timeoutMs` SIGKILL that process tree. * `sandbox.pty.create()` is a tty exec session (`sendInputToCurrentCommand`, `resizeTerminal`). `pty.connect(id)` works within the same process. * Files use the SDK's streaming copy (`upload/download.serviceStream.files`), which needs `tar` and `cat` in the image. * No per-command `cwd`/`env`: the core wraps the command (`perCommandEnvCwd: false`). ## Previews [#previews] `ports.expose(port)` adds a public HTTP port **without touching the others** (the update endpoint replaces the whole list, so the adapter merges) and returns `https://--.code.run`. `visibility: "private"` protects the port with HTTP basic auth: ```ts const p = await sandbox.ports.expose(3000, { visibility: "private" }); // p.auth = { type: "header", headers: { authorization: "Basic …" } } ``` Basic auth is a header, so a private preview can't be opened from a browser WebSocket (`previewBrowserAuth: false`). ## Snapshots and fork [#snapshots-and-fork] `snapshots.create()` takes a Northflank **container snapshot** (filesystem only, `includesMemory: false`) and waits for it to succeed. `snapshots.restore()` redeploys the service from it, `client.create({ fromSnapshot })` boots a new service from it, and `sandbox.fork()` snapshots and restores into new services. Container snapshots need a cluster with the Kata runtime (sandboxed workloads). gVisor/Kata are a **cluster** setting on Northflank (`sandboxing.defaultSandbox.services` for BYOC clusters), not a per-service option, so the adapter has no runtime-class option. ## Templates [#templates] Northflank builds images from a git repository or a bundle URL, so a raw Dockerfile + local context can't be uploaded. `templates.build()` accepts **`{ image }` only**: the template id is the image path plus any `env`/`startCmd`/`workdir`, encoded into the id so it works across processes. ```ts const tpl = await client.templates.build({ source: { image: "node:22" }, env: { NODE_ENV: "production" }, }); const sb = await client.create({ template: tpl }); ``` ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------------- | :---------: | ------------------------------------------- | | `list` | native | cursor pagination, metadata filter | | `pause` | native | scale to zero; **memory and disk are lost** | | `streaming` / `stdin` / `pty` | native | exec sessions | | `exposePort` / `privatePreview` | native | public port; basic auth when private | | `snapshot` / `fork` | native | container snapshots (Kata clusters) | | `gpu` / `metrics` | native | `billing.gpu`; `metrics.getServiceMetrics` | | `templateBuild` | native | `image` sources only | | `stop` / `setTimeout` | unsupported | `maxAgeMs` is set once at create | | `ssh` | unsupported | the API does not expose an SSH endpoint | | `volumes` / `secretsVault` | unsupported | attach existing volumes via `spec.volumes` | | `region` | unsupported | fixed by the project's cluster | Flags: `perCommandEnvCwd: false`, `preservesMemoryOnPause: false`, `previewModel: "subdomain"`, `templateSources: ["image"]`. ## Limitations [#limitations] * `pause()` scales to zero: the container and its ephemeral disk go away. Mount a volume for data that must survive. * `deployment.ssh.enabled` exists, but the API gives no host/port to connect to, so `ssh` stays unsupported. * Plan selection from `resources` uses a built-in table of Northflank plan ids; pass `deploymentPlan` to pin one. --- # Railway (/adapters/railway) Isolated Debian Linux VMs on Railway, with streaming exec, real kill, background sessions you can reattach to, native files, checkpoints, forks and preview domains. **Beta.** Railway Sandboxes are a beta product, so the SDK surface may change. The adapter targets the official `railway` SDK **3.4 or later** (3.17 recommended). Versions below 3.0 were an unrelated package. ## Installation [#installation] `railway` is an optional peer dependency of `sbox-sdk`. It's loaded lazily the first time you create or connect. pnpm bun npm yarn ```bash pnpm add sbox-sdk railway ``` ```bash bun add sbox-sdk railway ``` ```bash npm install sbox-sdk railway ``` ```bash yarn add sbox-sdk railway ``` ## Authentication [#authentication] The SDK reads credentials from the environment, so all options are optional: * `RAILWAY_TOKEN`: a **project token**. This is the recommended option, because the environment comes with the token. * `RAILWAY_API_TOKEN`: an account or workspace token. It also needs `RAILWAY_ENVIRONMENT_ID` (or the `environmentId` option). The adapter passes `token`, `authType`, `environmentId` and `endpoint` through to **every** SDK call: create, connect, list, checkpoints and verify. ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { railway } from "sbox-sdk/railway"; const client = createSandboxClient({ provider: railway({ token: process.env.RAILWAY_TOKEN, // or RAILWAY_API_TOKEN + environmentId }), }); const sandbox = await client.create({ env: { NODE_ENV: "production" }, resources: { vcpus: 2, memoryMB: 4096 }, region: "us-west2", lifecycle: { idleTimeoutMs: 15 * 60_000 }, // destroyed after 15 idle minutes metadata: { team: "agents" }, }); // exec streams live, and stdout and stderr stay separate. for await (const ev of sandbox.commands.run("npm install", { cwd: "/app" })) { if (ev.type === "stdout") process.stdout.write(ev.data); } // Background processes are durable sessions you can reattach to. const server = await sandbox.commands.spawn("node server.js"); const again = await sandbox.commands.connect(server.id); // replays output await sandbox.commands.kill(server.id, "SIGTERM"); await sandbox.files.write("/work/data.bin", new Uint8Array([1, 2, 3])); await sandbox.destroy(); ``` ## Templates, checkpoints and forks [#templates-checkpoints-and-forks] On Railway, `template` is **not a container image**. It's the name of a **checkpoint**: a saved disk you boot from. Every sandbox starts from Railway's Debian base. ```ts // Save the current disk as a named checkpoint... const snap = await sandbox.snapshots!.create({ name: "deps-installed" }); // ...and boot new sandboxes from it. `template: "deps-installed"` is equivalent. const copy = await client.create({ fromSnapshot: snap }); await sandbox.snapshots!.list(); // every checkpoint in the environment await sandbox.snapshots!.delete(snap); // looked up by key, deleted by id const [child] = await sandbox.fork(); // clones the filesystem (a fresh boot) ``` Checkpoints capture the disk only (`includesMemory: false`). Restoring one boots a new sandbox, so in-place `snapshots.restore()` is not available. ### Building a base: the native recipe builder [#building-a-base-the-native-recipe-builder] Railway has no Dockerfile or registry-image build, so `templateBuild` is **unsupported** and `client.templates` is `undefined`. Instead, Railway builds bases from a recipe, `Sandbox.template()`, and caches the result by recipe hash. To use one, pass it to the factory. It applies to every create that doesn't name a `template` or `fromSnapshot`: ```ts import { Sandbox } from "railway"; import { railway } from "sbox-sdk/railway"; const base = Sandbox.template() .withPackages("git", "python3") .run("pip install uv") .workdir("/app"); const provider = railway({ template: base }); // built once, then cached ``` ## Previews [#previews] Railway publishes HTTP domains **at create time**. To get one, declare its ports in `spec.ports`. Domains need the sandbox on the environment's private network, so you must opt in with `networkIsolation: "PRIVATE"`: ```ts const client = createSandboxClient({ provider: railway({ networkIsolation: "PRIVATE" }), }); const sandbox = await client.create({ ports: [3000] }); const preview = await sandbox.ports!.expose(3000); // { url, wsUrl, auth: { type: "public" } } ``` Some limits apply: * Domains are **public**. There are no private previews, so `privatePreview` is unsupported and `previewBrowserAuth` is `false`. * `expose()` of a port you didn't declare throws `Validation`. * `unexpose()` is not available. ## Secrets [#secrets] An env-mode `SecretRef` that has no `value` becomes a Railway reference to the environment's **shared variables**. Railway resolves it inside the sandbox, so the value never passes through your process: ```ts await client.create({ secrets: [ { name: "OPENAI_API_KEY" }, // -> ${{shared.OPENAI_API_KEY}} { name: "db", envVar: "DB_PASSWORD", value: "inline" }, ], }); ``` Egress-mode (`mode: "egress"`) secrets are not supported. ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------- | :---------: | ------------------------------------------------------------ | | `streaming` | native | `onStdout` / `onStderr`, stderr kept separate | | `background` | native | durable exec sessions; `commands.connect(id)` reattaches | | `killProcess` | native | `ExecHandle.kill(signal)` to the process group | | `stdin` | native | `spawn()` opens stdin (`process.writeStdin`) | | `filesUpload` | native | streaming `files.write` / `files.read({ format: "stream" })` | | `list` | native | see limitations | | `snapshot` | native | named checkpoints (disk only) | | `fork` | native | clones the filesystem | | `exposePort` | native | `declaredPorts`: domains from `spec.ports` | | `region` | native | `spec.region` | | `secretsVault` | native | `${{shared.NAME}}` references | | `privatePreview` | unsupported | domains are public | | `egressControl` | unsupported | ISOLATED = public NAT egress; no filtering | | `pause` / `stop` | unsupported | `destroy()` tears the VM down | | `setTimeout` | unsupported | the idle timeout is fixed at create | | `templateBuild` | unsupported | use the native recipe builder (above) | | `pty` / `ssh` / `metrics` | unsupported | | | `volumes` / `gpu` | unsupported | | | `codeInterpreter` | unsupported | | `perCommandEnvCwd` is `true`, because exec takes `cwd`/`env` natively. `timeoutMs` maps to the SDK's `timeoutSec`. ### How the spec maps [#how-the-spec-maps] | sbox | Railway | | ------------------------------ | --------------------------------------------------------------- | | `template` / `fromSnapshot` | `Sandbox.create(checkpointName, …)` | | `env` | `env` (Railway references allowed) | | `resources.vcpus` / `memoryMB` | `resources.cpu` / `resources.memoryGB` (decimal GB) | | `region` | `region` | | `lifecycle.idleTimeoutMs` | `idleTimeoutMinutes` (rounded up; idle sandboxes are destroyed) | | `ports` | `domains` (needs `networkIsolation: "PRIVATE"`) | | `metadata` / `name` | JSON file at `/etc/sbox/metadata.json` in the sandbox | | `idempotencyKey` | stored in the same file; a retried create reuses the sandbox | The following settings throw `Validation`: * `lifecycle.maxAgeMs` (Railway has no wall-clock limit) * `onIdle: "pause" | "stop"` * a `network` policy other than `allow-all` * `volumes` * `resources.gpu` `diskMB` and `shmMB` are ignored. ## Known limitations [#known-limitations] * **No native labels.** `metadata` and `name` live in a small file inside the sandbox. So `getInfo()` and `list()` read that file for running sandboxes (cached per process), and `list()` costs one connect and one read for each running sandbox it hasn't seen yet. Sandboxes that aren't running report empty metadata. * **`list()` returns one page.** The SDK's `Sandbox.list()` exposes no cursor, so the adapter can't paginate beyond the server's default page. * **`snapshots.list()` is environment-wide.** Railway checkpoints don't record their source sandbox. The list also includes the checkpoints that recipe builds produce, keyed by recipe hash. * **No runtime TTL changes.** To reset the idle countdown, use `sandbox.raw().heartbeat()`. * **Foreground `commands.run()` has no `writeStdin`.** Its stdin closes immediately. Use `spawn()` for interactive input. Buffered `stdin` in options works everywhere. --- # Runloop (/adapters/runloop) Deprecated: a sandbox per Runloop devbox, via @runloop/api-client. Runloop ended customer support on 2026-11-13. Runloop is winding down. Support for existing customers ended on **2026-11-13**. `sbox-sdk/runloop` is deprecated in 0.1.0 and only gets crash and leak fixes. It will be **removed in 0.2.0**. Calling `runloop()` logs a one-time deprecation warning. Move your workloads to another [adapter](/adapters). Your code shouldn't need changes beyond the import and the factory call. ## Installation [#installation] `@runloop/api-client` is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk @runloop/api-client ``` ```bash bun add sbox-sdk @runloop/api-client ``` ```bash npm install sbox-sdk @runloop/api-client ``` ```bash yarn add sbox-sdk @runloop/api-client ``` ## Authentication [#authentication] `runloop()` reads `RUNLOOP_API_KEY` when you don't pass `apiKey`. Check the key with `client.verify()`. It lists one devbox and never creates anything. ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { runloop } from "sbox-sdk/runloop"; const client = createSandboxClient({ provider: runloop({ apiKey: process.env.RUNLOOP_API_KEY! }), }); const sandbox = await client.create({ template: "bpt_123", metadata: { team: "a" }, }); const res = await sandbox.commands.run("python --version"); console.log(res.stdout); const forks = await sandbox.fork({ count: 2 }); // snapshot the disk, boot 2 devboxes await sandbox.pause(); // suspend: memory preserved ``` What `create()` does with your spec: * [`template`](/templates) is a **blueprint id**. A **snapshot id** (`snp…`) or `fromSnapshot` restores that disk state into a new devbox instead. * `name`, `metadata` and `env` are passed through. * It waits with `createAndAwaitRunning`, and throws if the devbox fails to boot. ## Previews [#previews] A devbox has a single V2 tunnel that serves every port. `ports.expose(port)` reuses that tunnel, or enables one if there isn't one yet, and returns: ``` https://{port}-{tunnel_key}.tunnel.runloop.ai ``` `auth` follows the tunnel's mode: * `open` gives `{ type: "public" }`. * `authenticated` gives header auth: `X-Runloop-Tunnel-Authorization: Bearer `. This doesn't work from a browser WebSocket. `removeTunnel` takes no port, so `unexpose()` only removes the tunnel after the last exposed port is gone. ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------- | :---------: | ----------------------------------------------------- | | `list` | native | walks every cursor page | | `pause` | native | suspend/resume (memory preserved) | | `streaming` | emulated | `executeAndAwaitCompletion` returns buffered output | | `filesUpload` | native | binary `uploadFile`, wrapped with `toFile` | | `exposePort` | native | V2 tunnel | | `snapshot` / `fork` | native | `snapshotDisk`. Fork snapshots, then boots N devboxes | | `privatePreview` | unsupported | the tunnel's auth mode is set when it's created | | `stop` | unsupported | `pause` (suspend) or `destroy` (shutdown) | Flags: * `perCommandEnvCwd: false`: the core adds `cwd`/`env` to the command itself. * `preservesMemoryOnPause: true` and `previewModel: "tunnel"`. * No in-place snapshot `restore`. ## Known limitations [#known-limitations] * `kill()` and `timeoutMs` stop the adapter from waiting and end the command with exit code 137 or a `Timeout` error. The remote process **isn't signalled**, so it keeps running until it finishes on its own. * The disk snapshot that `fork()` takes isn't deleted afterwards. --- # Fly Sprites (/adapters/sprites) Named, persistent Firecracker VMs on Fly.io that pause on their own when idle. Streamed exec, detachable TTY sessions, native files, filesystem checkpoints and DNS egress policy, via @fly/sprites. ## Installation [#installation] `@fly/sprites` is an optional peer dependency of `sbox-sdk`. It needs **Node.js 24 or later** and is imported lazily, so importing `sbox-sdk/sprites` stays cheap on older runtimes until you create a sprite. pnpm bun npm yarn ```bash pnpm add sbox-sdk @fly/sprites ``` ```bash bun add sbox-sdk @fly/sprites ``` ```bash npm install sbox-sdk @fly/sprites ``` ```bash yarn add sbox-sdk @fly/sprites ``` ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { sprites } from "sbox-sdk/sprites"; const client = createSandboxClient({ provider: sprites({ token: process.env.SPRITES_TOKEN! }), }); // Sprites are named and persistent: getOrCreate is native. const sandbox = await client.getOrCreate({ name: "agent-42" }); console.log(sandbox.id); // "agent-42" (the sprite name is the id) for await (const ev of sandbox.commands.run("npm install")) { if (ev.type === "stdout") process.stdout.write(ev.data); } await sandbox.files.write("/home/sprite/state.json", '{"v":1}'); const ref = await sandbox.snapshots!.create({ name: "after-install" }); // ...later, roll back in place: await sandbox.snapshots!.restore(ref); ``` `create()` without a `name` derives a deterministic name from the idempotency key (`sbox-`), so a retried create never makes a second sprite. ## Authentication [#authentication] | Option | Env var | Required | Notes | | --------- | ------------------ | :------: | -------------------------------------------------- | | `token` | `SPRITES_TOKEN` | yes | Org token (`sprite auth setup --token`, dashboard) | | `baseURL` | `SPRITES_BASE_URL` | no | Defaults to `https://api.sprites.dev` | `client.verify()` lists one sprite and reports the organization name; it never creates anything. ## Options [#options] ## Spec mapping [#spec-mapping] | `SandboxSpec` field | Sprites | | ------------------------------------------------------- | ----------------------------------------------------------------- | | `name` | sprite name (also stored as the `sbox-name` label) | | `template` | `"default"` or `"dev"` only, mapped to `runtime` | | `env` | sprite `environment` | | `metadata` | labels, encoded as `key=value` (percent-encoded) | | `resources` | `config.cpus`, `config.ramMB`, `config.storageGB` (from `diskMB`) | | `region` | `config.region` | | `network` | network policy, applied right after creation | | `secrets` (inline `value`) | added to `environment` | | `idempotencyKey` | deterministic sprite name when `name` is omitted | | `fromSnapshot`, `volumes`, GPU, secrets without a value | rejected with a `Validation` error | | `lifecycle` | ignored: sprites always pause when idle and wake on demand | ## Lifecycle and states [#lifecycle-and-states] A sprite is **running** while something uses it. About 30 seconds after activity stops it goes **warm** (VM suspended, memory kept), and later **cold** (VM stopped, disk only). Any exec, file call or URL request wakes it. | Sprite status | `SandboxState` | | ------------- | -------------- | | `running` | `running` | | `warm` | `paused` | | `cold` | `stopped` | There is no explicit pause or stop API, so the `pause` and `stop` capabilities are `unsupported`; a sprite in `paused` or `stopped` is still usable directly. `destroy()` deletes the sprite and its checkpoints. ## Previews and browser auth [#previews-and-browser-auth] Each sprite has **one** URL, `https://-.sprites.app`. It routes to port `8080`, or to the first HTTP port opened when nothing listens on 8080. `ports.expose(port)` returns that URL. It does not create per-port hosts. Visibility is **sprite-wide**: * `expose(port)` (public) sets URL auth to `public`, so anyone with the URL can reach it. * `expose(port, { visibility: "private" })` sets URL auth to `sprite` (org members only). The preview carries `auth: { type: "header", headers: { Authorization: "Bearer " } }`. Private previews need an `Authorization` header, which a browser WebSocket cannot send, so `previewBrowserAuth` is `false`. To use a private sprite URL from a browser, proxy it through your backend. The other option is a public URL protected by your own app-level auth. ## Terminals [#terminals] `sandbox.pty.create()` starts a detachable TTY session (a tmux session on the sprite). The PTY id is the server session id, so `sandbox.pty.connect(id)` can reattach from another process, and `commands.list()` shows active sessions. TTY sessions stop when the sprite goes cold. ## Capabilities [#capabilities] | Capability | Level | Notes | | ---------------------------------- | :---------: | ------------------------------------------------------- | | `list` | native | paginated; metadata/state filters applied client-side | | `streaming` / `stdin` | native | WebSocket exec, stdout and stderr kept separate | | `background` / `killProcess` | native | spawned commands, plus exec sessions by id | | `pty` | native | detachable TTY sessions (create/attach/kill) | | `filesUpload` / `filesWatch` | native | Sprites filesystem API | | `exposePort` / `privatePreview` | native | one URL per sprite; sprite-wide visibility; header auth | | `egressControl` | native | DNS allow/deny rules; no CIDRs, no credential injection | | `snapshot` | native | filesystem checkpoints, restored in place | | `region` | native | `config.region` | | `pause` / `stop` / `setTimeout` | unsupported | pausing is automatic | | `templateBuild` | unsupported | no custom images; a checkpoint cannot seed a new sprite | | `fork` / `volumes` / `gpu` | unsupported | | | `ssh` / `metrics` / `secretsVault` | unsupported | Connectors are not wired in | | `codeInterpreter` | unsupported | | Flags: `perCommandEnvCwd: true`, `exitCodeNative: true`, `preservesMemoryOnPause: true` (warm), `preservesDiskOnStop: true` (cold), `previewModel: "subdomain"`, `previewBrowserAuth: false`, `templateSources: []`. ## Snapshots [#snapshots] `snapshots.create({ name })` creates a checkpoint with `name` as its comment and returns its id (`v0`, `v1`, ...). Checkpoints capture the **filesystem only** (`includesMemory: false`), so `mode: "memory"` is rejected. `snapshots.restore(ref)` restores in place: the sprite restarts and active sessions end. `snapshots.list()` lists your checkpoints. `snapshots.delete()` is not available because the SDK has no delete call; use `sprite checkpoint delete` from the CLI. ## Known limitations [#known-limitations] * No custom images: `template` only selects the `default` or `dev` runtime, and checkpoints restore in place only. * One HTTP URL per sprite, with sprite-wide public/private visibility. * `commands.run({ timeoutMs })` is enforced by the core, which kills the command. The Sprites WebSocket exec has no server-side timeout. * `user` in `ExecOptions` is ignored: commands run as the sprite user. * Processes started with `commands.run`/`spawn` stop when the sprite goes cold. Use Sprites Services (`sprite-env services`) for anything that must survive. * Resource config (`cpus`, `ramMB`, `storageGB`) is passed through, but Sprites currently manages these values itself. --- # Superserve (/adapters/superserve) Firecracker microVMs from Superserve (Apache-2.0 core) through @superserve/sdk. Streamed exec over WebSockets, background processes with stdin, pause/resume with memory, memory+disk snapshots and fork, per-port public or token-auth previews, egress allow/deny lists, stand-in-token secrets, volumes, and Dockerfile/image template builds. ## Installation [#installation] `@superserve/sdk` (≥ 0.13) is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk @superserve/sdk ``` ```bash bun add sbox-sdk @superserve/sdk ``` ```bash npm install sbox-sdk @superserve/sdk ``` ```bash yarn add sbox-sdk @superserve/sdk ``` Exec and spawned processes use the SDK's WebSocket session, which needs a global `WebSocket` (Node 22+, Bun, Deno, browsers). ## Authentication [#authentication] | Option | Env var | Required | Description | | --------- | --------------------- | -------- | ---------------------------------------------------------------------------------------------- | | `apiKey` | `SUPERSERVE_API_KEY` | yes | Team API key. The SDK reads the env var when you omit the option. | | `baseUrl` | `SUPERSERVE_BASE_URL` | no | API URL override. By default the region comes from the key (`ss_live_use_…`, `ss_live_usw_…`). | `client.verify()` lists one sandbox, so it never creates anything. ## Quickstart [#quickstart] ```ts import { createSandboxClient } from "sbox-sdk"; import { superserve } from "sbox-sdk/superserve"; const client = createSandboxClient({ provider: superserve({ apiKey: process.env.SUPERSERVE_API_KEY! }), }); const sandbox = await client.create({ template: "superserve/python-3.11", metadata: { job: "demo" }, env: { LOG_LEVEL: "debug" }, lifecycle: { idleTimeoutMs: 10 * 60_000 }, }); for await (const ev of sandbox.commands.run("echo out; echo err >&2")) { console.log(ev); // stdout and stderr arrive separately, then the real exit code } const server = await sandbox.commands.spawn("python3 -m http.server 8000"); const preview = await sandbox.ports!.expose(8000); console.log(preview.url); // https://8000-.sandbox.superserve.ai await sandbox.pause(); // memory and processes are kept await sandbox.resume(); await sandbox.destroy(); ``` `template` is a Superserve template name or id (`superserve/base`, `superserve/node-22`, or one of yours). `fromSnapshot` takes a snapshot id. ## Options [#options] ## Exec [#exec] * `commands.run()` and `commands.spawn()` both use `sandbox.commands.spawn()` (WebSocket), not the one-shot `commands.run()` endpoint, which caps commands at 30 s when no timeout is set. Output streams as it is produced, and stdout and stderr stay separate. * `cwd`, `env`, `user` and `timeoutMs` are passed natively. A command that reaches its timeout exits `124` inside Superserve; the adapter turns that into a `Timeout` error. * `kill()` sends the signal (default `SIGKILL`) to the real process. If the process is still alive after 3 s, the adapter closes the socket, and Superserve stops a session's process when its connection drops. * One-shot commands get EOF on stdin immediately. Spawned processes keep stdin open for `process.writeStdin()`. * `commands.kill(id)` works for processes spawned through the same handle. Superserve sessions can't be reattached, so `commands.connect()` and `commands.list()` aren't available. ## Templates (Dockerfile and image builds) [#templates-dockerfile-and-image-builds] `client.templates.build()` calls `Template.create()` in your team and streams the build log through `onEvent`. ```ts const tpl = await client.templates.build( { name: "agent-env", source: { dockerfile: await readFile("Dockerfile", "utf8"), context: "./" }, env: { NODE_ENV: "production" }, resources: { vcpus: 2, memoryMB: 4096, diskMB: 8192 }, startCmd: "node server.js", readyCmd: "curl -fs localhost:3000/health", }, { onEvent: (e) => e.type === "log" && console.log(e.line) } ); const sandbox = await client.create({ template: tpl }); ``` * A **BuildSpec is a list of steps**, so a Dockerfile is translated: `FROM` → `from`, `RUN` → `run`, `ENV` → `env`, `WORKDIR` → `workdir`, `USER` → `user`, `CMD`/`ENTRYPOINT` → `startCmd`, and `ARG` defaults are substituted. BuildSpec has no copy step, so `COPY`/`ADD` context files are inlined as base64 `run` steps, up to 4 MiB in total. Fetch bigger files in a `RUN`. * Not supported: multi-stage builds, `COPY --from`, `RUN --mount` and `ADD `. `EXPOSE`, `LABEL`, `HEALTHCHECK` and similar are ignored, with a log line. * `{ image }` sources map to `from`. `registryAuth` and snapshot sources aren't supported (boot a snapshot with `create({ fromSnapshot })`). * `startCmd` keeps running in every sandbox, because the template is a memory snapshot. `readyCmd` is polled until it exits 0. * The template is named `-` (`sbox-` without a name), so a rebuild finds it instead of building again. * `resources` belong to the template: Superserve sandboxes can't override vCPU, memory or disk at create. ## Previews and browser auth [#previews-and-browser-auth] New sandboxes use Superserve's strict `public` policy, where only published ports are reachable. * `ports.expose(port)` publishes the port as public: `auth: { type: "public" }`. * `ports.expose(port, { visibility: "private" })` publishes it as private and mints a per-port token, returned as `auth: { type: "query", param, token }` with `expiresAt`. The lifetime is `previewTokenTtlSeconds` (default one day). The edge swaps the query token for a secure host cookie on first navigation, so pages, assets and WebSockets opened from that page work in a browser (`flags.previewBrowserAuth: true`). A machine client can send the same token in a header instead, under the header name the SDK's `getPreviewToken()` returns. * `ports.unexpose(port)` unpublishes the port and revokes its tokens. Preview ports must be 1024–65535. * `spec.ports` are published as public at create. ## Lifecycle [#lifecycle] | `SandboxSpec` | Superserve | | ------------------------- | ---------------------------------------------------------------------------------- | | `lifecycle.maxAgeMs` | `timeoutSeconds`: auto-pause after that much active time (re-armed on each resume) | | `lifecycle.idleTimeoutMs` | `idleTimeoutSeconds` (clamped to 60–604 800) | | `onIdle: "destroy"` | adds `autoDeleteSeconds: 0`: deleted as soon as it pauses (including `pause()`) | | `onIdle: "pause"` / unset | pause (the platform's behavior) | | `setTimeout(ms)` | `update({ timeoutSeconds })`: an auto-pause window, not a deletion deadline | `connect(id)` activates the sandbox, which resumes it if it's paused (Superserve hands out data-plane tokens only for active sandboxes). `getInfo()` fetches live state and maps every status: `starting`/`resuming` → `creating`, `active` → `running`, `pausing` → `suspending`, `paused`/`migrating` → `paused`, `failed` → `error`, `deleted` → `destroyed`. `destroy()` deletes the sandbox. ## Network, secrets and volumes [#network-secrets-and-volumes] * **Egress:** `allow-all` clears the rules (`deny.cidrs` become `denyOut`). `block-all` is `denyOut: ["0.0.0.0/0"]`. `allow-list` is `allowOut` (domains and CIDRs) plus deny-all, and when it has domains the adapter also allows the sandbox's DNS resolvers (`1.1.1.1`, `8.8.8.8`) so names resolve. `deny.domains` isn't supported (deny rules take IPs only). Runtime changes need a running sandbox. * **Secrets:** a `SecretRef` without a `value` binds an existing Superserve secret to `envVar` (`secrets: { [envVar]: name }`). The sandbox sees a **stand-in token**, and Superserve swaps it for the real credential on HTTPS requests to that secret's hosts. An inline `value` with `mode: "env"` becomes a plain env var. * **`EgressPolicy.inject` isn't supported.** Superserve replaces a stand-in token the code sends; it doesn't add headers on its own. Create the secret with `Secret.create({ auth, hosts })` (from `raw()` or the SDK), then bind it by name. * **Volumes:** `client.volumes` wraps `Volume` (size in MiB; region comes from the key). `spec.volumes` mounts by id or name, `readOnly` included. * **Idempotency:** the create's idempotency key is hashed into metadata. A retried create finds the sandbox from the first attempt instead of making another. `getOrCreate` uses the core's list-by-name. ## Snapshots and fork [#snapshots-and-fork] `snapshots.create()` captures memory and disk (`includesMemory: true`). Boot one with `client.create({ fromSnapshot })`. `sandbox.fork({ count })` snapshots, creates `count` sandboxes from the snapshot (running processes continue in each), then deletes the intermediate snapshot. Snapshots can't be restored in place, so `snapshots.restore()` isn't available. ## Capabilities [#capabilities] | Capability | Level | Notes | | ------------------------------------------------------------------------- | :---------: | ------------------------------------------------------------ | | `list` / `pause` / `setTimeout` | native | list filters by metadata and status on the server, paginated | | `stop` | unsupported | Superserve has pause and delete only | | `background` / `streaming` / `killProcess` / `stdin` | native | WebSocket sessions; process ids are scoped to the handle | | `pty` | unsupported | not in the TypeScript SDK | | `filesUpload` | native | `files.write` accepts a `Blob` | | `filesWatch` | unsupported | | | `exposePort` / `privatePreview` | native | per-port public or token access; browser-safe | | `egressControl` | native | allow/deny lists; no `inject` | | `snapshot` / `fork` | native | memory + disk | | `volumes` / `templateBuild` / `secretsVault` | native | | | `codeInterpreter` / `ssh` / `metrics` / `gpu` / `region` / `proxiedFetch` | unsupported | `metrics` exists in the REST API, not the SDK | Flags: `preservesMemoryOnPause: true`, `previewModel: "subdomain"`, `previewBrowserAuth: true`, `templateSources: ["image", "dockerfile"]`. ## Known limitations [#known-limitations] * `resources` and `region` at create throw `NotSupportedError`: set resources on the template, and choose the region with the API key. * Directory listing, `stat`, `mkdir`, `rename` and `remove` go through exec, because the SDK only has file read and write. * The desktop API (`sandbox.desktop`), network log (`getNetworkLog()`) and live memory/CPU resizing are available through `sandbox.raw()`. --- # Tensorlake (/adapters/tensorlake) Firecracker / Cloud Hypervisor microVMs with streamed exec, PTYs, memory snapshots, fork, suspend/resume, versioned volumes, egress control and GPUs, over Tensorlake's HTTP API. ## Installation [#installation] The runtime talks to Tensorlake's HTTP API directly, so **no SDK is needed** to create and drive sandboxes. Template builds are the exception: Tensorlake has no HTTP build API, so `client.templates` lazily imports the optional `tensorlake` package. pnpm bun npm yarn ```bash pnpm add sbox-sdk # only if you build templates: tensorlake ``` ```bash bun add sbox-sdk # only if you build templates: tensorlake ``` ```bash npm install sbox-sdk # only if you build templates: tensorlake ``` ```bash yarn add sbox-sdk # only if you build templates: tensorlake ``` ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { tensorlake } from "sbox-sdk/tensorlake"; const client = createSandboxClient({ provider: tensorlake({ apiKey: process.env.TENSORLAKE_API_KEY! }), }); const sandbox = await client.create({ resources: { vcpus: 2, memoryMB: 4096 }, lifecycle: { idleTimeoutMs: 15 * 60_000, onIdle: "pause" }, }); for await (const ev of sandbox.commands.run("python -c 'print(42)'")) { if (ev.type === "stdout") process.stdout.write(ev.data); } const term = await sandbox.pty!.create({ cols: 120, rows: 32 }); await term.write("ls -la\n"); const snap = await sandbox.snapshots!.create({ mode: "memory" }); const [clone] = await sandbox.fork(); ``` | Option | Env | Notes | | ---------------- | ----------------------- | ----------------------------------------------------------------- | | `apiKey` | `TENSORLAKE_API_KEY` | Required. Project-scoped API key. | | `apiUrl` | `TENSORLAKE_API_URL` | Optional lifecycle API origin. | | `projectId` | `TENSORLAKE_PROJECT_ID` | Only for `client.volumes`. Read from the volume token if omitted. | | `defaultImage` | | Image used when `create()` has no `template`. | | `readyTimeoutMs` | | How long create/resume wait for `running` (default 5 min). | ## Templates [#templates] Dockerfile and image sources are supported. The build runs in your Tensorlake project and is tagged with sbox's content hash, so repeat builds are cache hits. ```ts const ref = await client.templates!.build({ source: { dockerfile, context: "./desktop" }, resources: { vcpus: 2, memoryMB: 4096 }, }); const sandbox = await client.create({ template: ref }); ``` ## Previews [#previews] Ports are served at `https://-.sandbox.tensorlake.ai`. Public ports need no auth. **Private ports require `Authorization: Bearer `**, so they return `auth: { type: "header" }` and `flags.previewBrowserAuth` is `false`: a browser WebSocket can't open them. To open a port from a browser, expose it publicly (and treat the URL as a secret), or put a proxy in front that adds the header. Never ship the API key to a browser. ## Capabilities [#capabilities] * **Native:** streaming exec, background processes, kill, stdin, PTY, files, previews (public and private), egress control, secrets, memory snapshots, fork, suspend/resume (`pause`), metrics, volumes, GPU, templates. * **Unsupported:** `stop` (use `pause`), `setTimeout`, file watch, SSH, region selection, code interpreter, proxied fetch. ## Limitations [#limitations] * Private previews are header-auth only (see above). * `setTimeout` is not supported; set `lifecycle` at create. * Template builds need the `tensorlake` package, which ships a native binding. It isn't available on every platform (for example, there's no darwin-x64 build). --- # Together Sandbox (/adapters/together) Firecracker VMs booted from snapshots on Together AI (the successor to CodeSandbox). Remote Dockerfile builds, streamed execs, PTY, and hibernate/resume, via together-sandbox. ## Installation [#installation] `together-sandbox` is an optional peer dependency of `sbox-sdk`, loaded lazily on first use. pnpm bun npm yarn ```bash pnpm add sbox-sdk together-sandbox ``` ```bash bun add sbox-sdk together-sandbox ``` ```bash npm install sbox-sdk together-sandbox ``` ```bash yarn add sbox-sdk together-sandbox ``` Together Sandbox is allowlist-only: your Together account needs sandbox access. ## Authentication [#authentication] | Option | Env var | Required | Notes | | ----------------- | ------------------- | :------: | ---------------------------------------------------------- | | `apiKey` | `TOGETHER_API_KEY` | yes | Together AI API key | | `baseUrl` | `TOGETHER_BASE_URL` | no | Management API host, without `/v1` | | `defaultTemplate` | — | no | Snapshot alias or id used when `create()` gets no template | ```ts const ok = await client.verify(); // one `sandboxes.list({ limit: 1 })` call, never creates ``` ## Usage [#usage] Every Together sandbox boots from a **snapshot**. There is no default image, so pass a template: a snapshot alias or id, or a `TemplateSpec` that is built on first use. ```ts import { createSandboxClient } from "sbox-sdk"; import { together } from "sbox-sdk/together"; const client = createSandboxClient({ provider: together({ apiKey: process.env.TOGETHER_API_KEY! }), }); const sandbox = await client.create({ template: { source: { dockerfile: "FROM node:22-bookworm\nRUN npm i -g pnpm\n", }, }, resources: { vcpus: 2, memoryMB: 4096 }, metadata: { team: "agents" }, env: { NODE_ENV: "production" }, }); const res = await sandbox.commands.run("node --version"); console.log(res.stdout); ``` ## Templates [#templates] `client.templates.build()` uses `sdk.snapshots.create()`, which builds remotely on Together's image builder. No local Docker is needed. * **Dockerfile:** the build context (a directory or in-memory files) is written to a temp dir and uploaded. `TemplateSpec.env`, `workdir` and `user` are appended as `ENV`, `WORKDIR` and `USER` lines. * **Image:** must be publicly pullable. `registryAuth` is rejected. * **Snapshot:** an existing snapshot id gets an alias. Each built snapshot gets the alias `@` and the tags `sbox-template=1` and `sbox-template-key=`. Together's native `cacheKey` is set to `sbox/`, so rebuilds of one template reuse the remote layer cache. `templates.get()` finds a template by cache key, alias or snapshot id. `templates.delete()` retires the snapshot. ```ts const ref = await client.templates!.build( { name: "borat-desktop", source: { dockerfile: "FROM debian:bookworm\nCOPY . /app\n", context: "./desktop", }, }, { onEvent: (e) => e.type === "log" && console.log(e.step, e.line) } ); const sb = await client.create({ template: ref }); ``` ## Pause, resume and new ids [#pause-resume-and-new-ids] Together's lifecycle is `create → running → terminate`: * `pause()` terminates with a memory snapshot (`terminate({ snapshot: { memory: true } })`). Processes resume intact. * `stop()` terminates with a filesystem-only snapshot. * `resume()` boots a **new sandbox with a new id** from the snapshot aliased `sandbox:`. It keeps the CPU, memory, tags, TTL and termination policy. `capabilities.flags.resumeChangesId` is `true`, so re-read the id after `resume()`: ```ts await sandbox.pause(); await sandbox.resume(); const { id } = await sandbox.getInfo(); // the new id; persist this one ``` The handle you hold keeps working after `resume()`, and `getInfo().id` returns the new id. `sandbox.id` is captured when the handle is built, so it still shows the old id. `client.connect(oldId, { resume: true })` resumes and returns a sandbox bound to the new id. After a resume, the parent's snapshot is retired, so the old id reads as `destroyed`. `getOrCreate` therefore never resumes the same parent twice. `getInfo()` derives the state of a terminated sandbox from its `sandbox:` snapshot: | Together status | `SandboxState` | | -------------------------------- | -------------- | | `starting`, `recovering` | `creating` | | `running` | `running` | | `terminating` | `suspending` | | `failed_to_start`, `unrecovered` | `error` | | `terminated` + memory snapshot | `paused` | | `terminated` + disk snapshot | `stopped` | | `terminated`, no live snapshot | `destroyed` | `destroy()` terminates without a snapshot. On a paused or stopped sandbox, it retires the snapshot instead. ## Spec mapping [#spec-mapping] | Spec field | Together | | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `template` / `fromSnapshot` | `snapshotId` (UUID) or `snapshotAlias` | | `resources.vcpus` / `memoryMB` | `cpu` / `memoryBytes` (disk is not configurable) | | `lifecycle.maxAgeMs` | `ttl` (seconds from creation) | | `lifecycle.onIdle` | `pause` → memory snapshot when the TTL fires; `stop` → disk snapshot; otherwise ephemeral | | `metadata`, `name` | `tags` (`name` → `sbox-name`). Keys: at most 59 of `[A-Za-z0-9._-]`, alphanumeric ends | | `env`, inline `secrets` | merged into every exec and PTY, and persisted in `/var/tmp/.sbox/env.json` so reconnected handles reload them | | `idempotencyKey` | hashed into an `sbox-idem` tag; a retried create reuses the sandbox | | `ports`, `network`, `volumes`, `region`, GPU, vault secrets | rejected with a `Validation` error | `lifecycle.idleTimeoutMs` and `autoResume` have no equivalent: Together has no idle detection and a terminated sandbox never wakes. ## Capabilities [#capabilities] | Capability | Level | Notes | | -------------------------------------------------------------------------- | :---------: | ----------------------------------------------------------------------------------------------------------- | | `list` | native | cursor pages, tag and status filters on the server | | `pause` / `stop` | native | terminate with a memory or disk snapshot; resume returns a new id | | `streaming` / `background` | native | `execs.create` + `streamOutput`; stdout and stderr stay separate | | `killProcess` / `stdin` | native | `execs.delete` / `execs.sendStdin` (text) | | `pty` | native | `execs.create({ pty: true })`; resize via `sendStdin({ type: "resize" })`; `pty.connect(id)` replays output | | `filesWatch` / `filesUpload` | native | `files.watch`; binary-safe writes | | `templateBuild` | native | `dockerfile`, `image`, `snapshot` | | `exposePort` / `privatePreview` | unsupported | the sandbox model has no preview URL yet ("coming soon") | | `snapshot` / `fork` | unsupported | snapshots exist only on terminate, which ends the sandbox | | `egressControl` | unsupported | network policy is inbound-only; outbound rules are not supported yet | | `setTimeout`, `metrics`, `ssh`, `volumes`, `gpu`, `region`, `secretsVault` | unsupported | | Flags: `perCommandEnvCwd: true`, `exitCodeNative: true`, `preservesMemoryOnPause: true`, `preservesDiskOnStop: true`, `resumeChangesId: true`, `previewModel: "none"`. ## Known limitations [#known-limitations] * **File reads go through `base64` in the VM.** `files.read` returns a string, base64 for binary content with no marker. The adapter reads with `base64 -w0 ` instead, as Together's migration guide advises. Writes use the native binary upload. * **Execs run as UID 1000** unless you pass `user` (`"root"`, `"0:0"`). * **Exec timeouts** are enforced by the sbox core, which kills the exec. Together has no native exec timeout. * **Persisted env includes inline secret values** in `/var/tmp/.sbox/env.json`, so they end up in pause/stop snapshots. ## Migrating from the codesandbox adapter [#migrating-from-the-codesandbox-adapter] The `codesandbox` adapter is deprecated. CodeSandbox's SDK became Together Sandbox. | `sbox-sdk/codesandbox` | `sbox-sdk/together` | | -------------------------------------- | ---------------------------------------------------------------------------- | | `codesandbox({ apiKey: CSB_API_KEY })` | `together({ apiKey: TOGETHER_API_KEY })` (CodeSandbox keys don't work) | | `template`: a CSB template/sandbox id | `template`: a snapshot alias/id, or a `TemplateSpec` built from a Dockerfile | | `pause()` (hibernate), same id | `pause()` + `resume()`, **new id**: re-read `getInfo().id` | | `setTimeout()` (hibernation timeout) | `lifecycle.maxAgeMs` at create (TTL from creation, not idle) | | `ports.expose()` (`*.csb.app`) | not available yet | Rebuild your CodeSandbox templates as Dockerfiles. Existing templates and sandboxes can't be imported. --- # Upstash Box (/adapters/upstash-box) Persistent Linux containers from Upstash that pause when idle and wake on the next request. Streamed exec over live sessions, PTY, native files, public URLs, filesystem snapshots and network policy (plus opt-in SSH), via @upstash/box. ## Installation [#installation] `@upstash/box` is an optional peer dependency of `sbox-sdk`, imported lazily the first time you create or connect to a box. Commands run over WebSocket live sessions, so the adapter is **Node-only**. pnpm bun npm yarn ```bash pnpm add sbox-sdk @upstash/box ``` ```bash bun add sbox-sdk @upstash/box ``` ```bash npm install sbox-sdk @upstash/box ``` ```bash yarn add sbox-sdk @upstash/box ``` ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { upstashBox } from "sbox-sdk/upstash-box"; const client = createSandboxClient({ provider: upstashBox({ apiKey: process.env.UPSTASH_BOX_API_KEY! }), }); // Boxes can be named, so getOrCreate is native. const sandbox = await client.getOrCreate({ name: "agent-42", template: "node", }); for await (const ev of sandbox.commands.run("npm install", { cwd: "/workspace/home", })) { if (ev.type === "stdout") process.stdout.write(ev.data); } await sandbox.files.write("/workspace/home/state.json", '{"v":1}'); const ref = await sandbox.snapshots!.create({ name: "after-install" }); // Snapshots seed NEW boxes; they are not restored in place. const copy = await client.create({ fromSnapshot: ref }); ``` `create()` without a `name` but with an idempotency key derives a deterministic name (`sbox-`) and reuses that box on retry, so a retried create never makes a second box. ## Authentication [#authentication] | Option | Env var | Required | Notes | | --------- | ---------------------- | :------: | ----------------------------------------------- | | `apiKey` | `UPSTASH_BOX_API_KEY` | yes | From the Upstash Console, Box section | | `baseUrl` | `UPSTASH_BOX_BASE_URL` | no | Defaults to `https://us-east-1.box.upstash.com` | `client.verify()` lists your account-level Box env vars (values come back masked); it never creates anything. ## Options [#options] ## Spec mapping [#spec-mapping] | `SandboxSpec` field | Upstash Box | | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | `name` | box name (`Box.get` resolves ids and names) | | `template` | runtime: `node`, `python`, `golang`, `ruby`, `rust` or their `-alpine` variants | | `fromSnapshot` | `Box.fromSnapshot` | | `env`, `secrets` (inline `value`) | box `env` | | `metadata` | labels, encoded as `key:value` (at most 5, 20 characters each) | | `resources` | smallest fitting size: `small` 2 vCPU/4 GB, `medium` 4/8, `large` 8/16 | | `network` | network policy; `inject` becomes `attachHeaders` | | `region` | must be `us-east-1` | | `idempotencyKey` | deterministic box name when `name` is omitted | | `lifecycle.onIdle: "pause"` or `"stop"` | accepted: Box pauses idle boxes itself, keeping the disk (rejected with `keepAlive`) | | `lifecycle.maxAgeMs`, `idleTimeoutMs`, `autoResume: false`, `onIdle: "destroy"`, volumes, GPUs, built templates, secrets without a value | rejected with a `Validation` error | ## Lifecycle and states [#lifecycle-and-states] A box pauses itself when idle: the disk persists, running processes stop, and the next request (exec, file call or preview URL hit) wakes it. `sandbox.pause()` and `sandbox.resume()` do the same thing explicitly. Set `keepAlive: true` in the provider options to keep new boxes running (billed at a flat monthly rate by Upstash). Keep-alive boxes can't be paused, so `pause()` and `resume()` throw a `Validation` error on them. | Box status | `SandboxState` | | ----------------- | -------------- | | `creating` | `creating` | | `idle`, `running` | `running` | | `paused` | `paused` | | `error` | `error` | | `deleted` | `destroyed` | ## Previews and browser auth [#previews-and-browser-auth] `ports.expose(port)` creates a public URL, `https://-.preview.box.upstash.com`. With `{ visibility: "private" }` the URL requires a bearer token, and the preview carries `auth: { type: "header", headers: { Authorization: "Bearer " } }`. Browsers can't send that header on a WebSocket, so `previewBrowserAuth` is `false`. `ports.unexpose(port)` deletes the URL. A sandbox created with `previewVisibility: "private"` makes **every** `ports.expose()` private, since the core can't tell an omitted visibility from an explicit `"public"`. Box returns a bearer token only when the URL is created, and asking again issues a new token, which breaks anyone using the old one. So the adapter: * keeps the private previews a handle created, and returns them from `ports.list()` and repeat `expose()` calls without rotating the token; * leaves out of `ports.list()` any protected URL whose token the handle doesn't hold; * throws `Conflict` instead of rotating when asked to privately expose such a port (for example from `ports.fetch()` on a reconnected handle). Call `ports.unexpose(port)` first to issue a new token deliberately. ## SSH (experimental, opt-in) [#ssh-experimental-opt-in] SSH is **off by default**: the `ssh` capability is `unsupported` and `sandbox.ssh` is `undefined`. Box SSH logs in with your **account API key as the password**, so the credentials grant access to your whole Box account, not just one box. Turn it on only when the caller owns the key: ```ts const client = createSandboxClient({ provider: upstashBox({ apiKey: process.env.UPSTASH_BOX_API_KEY!, experimentalSsh: true, }), }); const sandbox = await client.getOrCreate({ name: "agent-42" }); const { command, password } = await sandbox.ssh!.create(); // command: ssh @us-east-1.box.upstash.com, password: your API key ``` To avoid sharing the key, add an SSH key in the Upstash Console and connect with `ssh -i`. ## Capabilities [#capabilities] | Capability | Level | Notes | | ---------------------------------------------- | :---------: | --------------------------------------------------------------------------------- | | `list` | native | first metadata label filtered server-side, the rest client-side | | `streaming` / `stdin` | native | live sessions, stdout and stderr kept separate | | `background` / `killProcess` | native | processes spawned from the same handle | | `pty` | native | TTY live session; not reattachable | | `filesUpload` | native | base64 file API, binary-safe | | `codeInterpreter` | native | stateless `exec.code` for `python`, `js`, `ts` | | `exposePort` / `privatePreview` | native | per-port public URLs; bearer-token auth | | `egressControl` | native | allow-all, deny-all, or domain/CIDR allow-list | | `ssh` | unsupported | opt-in with `experimentalSsh: true`; the password is the API key | | `pause` | native | disk kept, processes stopped | | `snapshot` | native | filesystem only; seeds new boxes, not restorable in place | | `fork` | emulated | snapshot, boot N boxes with the source's network policy, then delete the snapshot | | `stop` / `setTimeout` | unsupported | use `pause` | | `filesWatch` / `statefulKernel` | unsupported | | | `templateBuild` / `volumes` / `gpu` / `region` | unsupported | fixed runtimes in `us-east-1` | | `proxiedFetch` / `metrics` / `secretsVault` | unsupported | | Flags: `perCommandEnvCwd: true`, `exitCodeNative: true`, `preservesMemoryOnPause: false`, `preservesDiskOnStop: true`, `previewModel: "subdomain"`, `previewBrowserAuth: false`, `templateSources: []`. ## Known limitations [#known-limitations] * Node-only, because live sessions authenticate on the WebSocket handshake. * `user` in `ExecOptions` / `PtyOptions` is rejected; commands run as `boxuser`, so prefix `sudo` when you need root. * `commands.run({ timeoutMs })` is enforced by the core, which kills the session. * `killProcess` and `commands.list()` only see processes spawned from the current handle; live sessions can't be reattached after a reconnect. * Pausing (manual or idle) stops running processes, including PTYs and background commands. * `snapshots.restore()` is not available; boot a new box with `fromSnapshot` instead. * `setEgressPolicy` cannot change injected headers after creation. * `fork()` copies the filesystem and the network policy, but not box-level `env` or injected headers (Box never returns them). If any child fails to boot, the others are deleted and the fork throws. * A command whose `signal` is already aborted is never started. --- # Vercel Sandbox (/adapters/vercel) Named, persistent Firecracker microVMs on Vercel. Streaming exec with real kill, a PTY, snapshots and forks, Drives, egress policy with credential injection, and public port URLs. ## Installation [#installation] `@vercel/sandbox` is an optional peer dependency of `sbox-sdk`. It's loaded lazily the first time you create or connect. The adapter targets **`@vercel/sandbox` 4.x**, which needs **Node 22.19 or later**. pnpm bun npm yarn ```bash pnpm add sbox-sdk @vercel/sandbox ``` ```bash bun add sbox-sdk @vercel/sandbox ``` ```bash npm install sbox-sdk @vercel/sandbox ``` ```bash yarn add sbox-sdk @vercel/sandbox ``` ## Authentication [#authentication] Pass all three of `token`, `teamId` and `projectId`, or none of them. With none, the SDK uses `VERCEL_OIDC_TOKEN`. That token is automatic on Vercel, and locally you can get one with `vercel link && vercel env pull`. ## Usage [#usage] ```ts import { createSandboxClient } from "sbox-sdk"; import { vercel } from "sbox-sdk/vercel"; const client = createSandboxClient({ provider: vercel({ token: process.env.VERCEL_TOKEN, teamId: process.env.VERCEL_TEAM_ID, projectId: process.env.VERCEL_PROJECT_ID, }), }); const sandbox = await client.create({ template: "vercel/sandbox/node:24", // a VCR image; omit for vercel/sandbox/universal region: "fra1", resources: { vcpus: 2 }, lifecycle: { maxAgeMs: 30 * 60_000 }, metadata: { team: "agents" }, // Vercel tags, at most 5 ports: [3000], }); for await (const ev of sandbox.commands.run("npm install", { cwd: "/vercel/sandbox", })) { if (ev.type === "stdout") process.stdout.write(ev.data); } const server = await sandbox.commands.spawn("npm run dev"); const preview = await sandbox.ports!.expose(3000); console.log(preview.url); // https://.vercel.run await sandbox.destroy(); // deletes the sandbox and its orphan snapshots ``` Sandboxes are **named and persistent**. The name is the sandbox `id`, so `client.connect(name)` works across processes. A stopped sandbox keeps its filesystem and resumes on the next command: ```ts await sandbox.stop(); // filesystem auto-snapshotted const again = await client.connect(sandbox.id, { resume: true }); // Native get-or-create by name: const ws = await client.getOrCreate({ name: "workspace-42" }); ``` ## Images (templates) [#images-templates] Vercel has **no programmatic build API**. Images come from `docker build` and a push to the [Vercel Container Registry](https://vercel.com/docs/container-registry). So `templateBuild` is **unsupported** and `client.templates` is `undefined`. `template` maps to the SDK's `image`: a managed image (`vercel/sandbox/universal`, `vercel/sandbox/node:24`, …), a repository in your project (`my-repo:v1`), or a fully qualified VCR URL. The legacy runtime names `node22`, `node24` and `node26` map to the matching managed images. `python3.13` still uses the deprecated `runtime` selector, because no managed image pins 3.13. ## Snapshots and forks [#snapshots-and-forks] ```ts const snap = await sandbox.snapshots!.create(); // stops the session; the next call resumes it const copy = await client.create({ fromSnapshot: snap }); // source: { type: "snapshot" } await sandbox.snapshots!.list(); await sandbox.snapshots!.delete(snap); const [child] = await sandbox.fork(); // Sandbox.fork({ sourceSandbox }), copies config + disk ``` Snapshots capture the **disk only** (`includesMemory: false`). Restoring one boots a new sandbox, so in-place `snapshots.restore()` is not available. ## Previews [#previews] Port URLs are `https://.vercel.run`. `ports.expose(port)` adds a port the sandbox didn't declare at create time, through `update({ ports })`, and `unexpose()` removes it. A sandbox can expose at most 15 ports. Vercel's own docs state that exposed ports are reachable through a **public** URL, and there's no private or token-protected mode. So `privatePreview` is unsupported, every preview has `auth: { type: "public" }`, and `previewBrowserAuth` is `false`. Put your own auth in front of anything sensitive. ## Terminals [#terminals] `sandbox.pty.create()` calls `openInteractive()` and drives the returned WebSocket with the same protocol as the `sandbox exec --interactive` CLI. It uses Node's global `WebSocket`, available in Node 22+. ```ts const term = await sandbox.pty!.create({ cols: 120, rows: 40 }); for await (const chunk of term) process.stdout.write(chunk); ``` The interactive session can't be reattached, so `pty.connect(id)` is not available. ## Egress and credential injection [#egress-and-credential-injection] `network` (at create) and `sandbox.network.setEgressPolicy()` map onto Vercel's `networkPolicy`: | sbox | Vercel | | ---------------------------------------- | ------------------------------------------------- | | `mode: "allow-all"` | `"allow-all"` | | `mode: "block-all"` | `"deny-all"` | | `mode: "allow-list"`, `domains`, `cidrs` | `allow: domains`, `subnets.allow` | | `deny.cidrs` | `subnets.deny` | | `deny.domains` | a proxy `response` rule that answers 403 | | `inject: [{ domains, headers }]` | `transform: [{ headers }]` rules on those domains | ```ts await client.create({ network: { mode: "allow-list", domains: ["registry.npmjs.org"], inject: [ { domains: ["api.github.com"], headers: { Authorization: { name: "gh", value: `Bearer ${token}` } }, }, ], }, }); ``` The firewall adds the header, so the secret never enters the sandbox. An injected domain is also allowed. Vercel has no secret vault, so each `SecretRef` needs a `value`, either inline or from a `spec.secrets` entry with the same name. ## Volumes (Drives) [#volumes-drives] `client.volumes` manages [Drives](https://vercel.com/docs/sandbox/concepts/drives). A volume's `id` is the drive **name**, which is what mounts reference: ```ts const data = await client.volumes!.create({ name: "datasets", sizeMB: 10_240, region: "iad1", }); await client.create({ volumes: [{ id: data.id, mountPath: "/data" }] }); ``` `readOnly: true` mounts the drive in Vercel's `snapshot` mode, a point-in-time copy. Writes to it never reach the drive. ## Options [#options] ## Capabilities [#capabilities] | Capability | Level | Notes | | ----------------------------- | :---------: | -------------------------------------------------------------- | | `streaming` / `background` | native | detached `runCommand` + `logs()`, stderr kept separate | | `killProcess` | native | `Command.kill(signal)` | | `stdin` | native | `spawn()` opens stdin (`writeStdin`); `run()` stdin is closed | | `pty` | native | `openInteractive()` WebSocket | | `list` | native | `Sandbox.list`, fully paginated | | `stop` | native | the filesystem persists (`preservesDiskOnStop`) | | `pause` | emulated | `stop()` + resume; no memory (`preservesMemoryOnPause: false`) | | `setTimeout` | native | `update({ timeout })` | | `snapshot` / `fork` | native | disk only | | `egressControl` | native | incl. `deny` and `inject` | | `exposePort` | native | public `vercel.run` URLs | | `volumes` | native | Drives | | `region` | native | `spec.region` | | `metrics` | native | cumulative usage (see below) | | `privatePreview` | unsupported | URLs are public | | `templateBuild` | unsupported | build with Docker, push to VCR | | `codeInterpreter` / `ssh` | unsupported | | | `filesWatch` / `proxiedFetch` | unsupported | | | `gpu` / `secretsVault` | unsupported | | `perCommandEnvCwd` is `true`. `timeoutMs` is passed to `runCommand`, and Vercel's SIGKILL on expiry surfaces as a `Timeout` error. `user: "root"` runs with `sudo`, and any other user runs through `asUser()`. ### How the spec maps [#how-the-spec-maps] | sbox | Vercel | | ----------------------------------------- | -------------------------------------------------------------- | | `template` | `image` | | `fromSnapshot` | `source: { type: "snapshot", snapshotId }` | | `name` / `idempotencyKey` | `name` (`sbox-` when unnamed; a retried create reuses it) | | `env`, env-mode `secrets` | `env` | | `metadata` | `tags` (at most 5) | | `resources.vcpus` / `memoryMB` | `resources.vcpus` (memory is 2048 MB per vCPU, rounded up) | | `region` | `region` | | `lifecycle.maxAgeMs` (or `idleTimeoutMs`) | `timeout` (per session) | | `lifecycle.onIdle: "destroy"` | `persistent: false` | | `network` | `networkPolicy` | | `volumes` | `mounts` | | `ports` | `ports` | `resources.gpu`, `template` together with `fromSnapshot`, and more than 5 tags all throw `Validation`. `diskMB` and `shmMB` are ignored. ## Known limitations [#known-limitations] * **No idle timeout.** `timeout` is a wall-clock limit per session, so `idleTimeoutMs` is treated as one. Persistent sandboxes always auto-resume on the next call, so `autoResume` has no effect. * **Metrics are cumulative.** `metrics()` reports `memoryTotalMB` and a lifetime-average `cpuPercent` (active CPU ÷ wall time × vCPUs). The raw usage counters are in `raw`. Vercel doesn't expose point-in-time memory or disk usage. * **Snapshots stop the session.** The next command resumes it. * **`pause()` needs a persistent sandbox.** On a sandbox created with `onIdle: "destroy"`, the filesystem is discarded when the session stops. * **`commands.list()` is unavailable.** Vercel has no API to list a session's commands. `commands.connect(id)` and `commands.kill(id)` work by command id. --- # Vercel AI SDK (/ai/ai-sdk) Project sandbox tools into the AI SDK's tool() shape as a map for generateText / streamText. Use the ai() plugin with the aiSdk() framework, or the standalone toAISDKTools(). ## Installation [#installation] `ai` is an optional peer dependency, loaded only when you use this adapter. pnpm bun npm yarn ```bash pnpm add sbox-sdk ai ``` ```bash bun add sbox-sdk ai ``` ```bash npm install sbox-sdk ai ``` ```bash yarn add sbox-sdk ai ``` ## Usage [#usage] Pass the `aiSdk()` framework to the `ai()` plugin and `sandbox.tools` is a tool map you pass straight to `generateText` or `streamText`: ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { aiSdk } from "sbox-sdk/ai-sdk"; import { openai } from "@ai-sdk/openai"; import { generateText } from "ai"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), plugins: [ai({ framework: aiSdk() })], }); const sandbox = await client.create({ template: "node" }); const result = await generateText({ model: openai("gpt-4o"), prompt: "Write app.js that prints the current date, then run it.", tools: sandbox.tools, // Record, keyed by tool name stopWhen: ({ steps }) => steps.length > 8, }); ``` `sandbox.tools` is a `Record`, capability-gated to the provider. Each tool's `execute` runs the sandbox operation and returns the result as text the model reads. ## Standalone [#standalone] Build the same map explicitly — useful for filtering or merging with your own tools: ```ts import { toAISDKTools } from "sbox-sdk/ai-sdk"; const tools = { ...toAISDKTools(sandbox, { only: ["sbox_exec", "sbox_fs_read", "sbox_fs_write"], }), ...myOtherTools, }; ``` `toAISDKTools` accepts a live `Sandbox` (capability-gated for you) or a pre-built `ToolSpec[]`. ## Approval [#approval] The stable AI SDK (`ai@5`) has no `needsApproval` field on a tool, so this adapter enforces the [policy](/ai/approval) inside `execute`: a `deny` decision returns a message the model reads, and `ask` awaits `policy.onApprovalRequest` when you provide one. ```ts plugins: [ ai({ framework: aiSdk(), policy: { defaults: { destructive: "ask" }, onApprovalRequest: async (req) => askUser(req.title), }, }), ]; ``` For AI SDK v7's call-site approval, `toolApproval(sandbox)` builds the matching `{ [toolName]: (input) => "user-approval" | undefined }` map from the same policy. ## Notes [#notes] * Peer range: `ai@^5 || ^6`. * Returns each tool's result as text. Mastra agents accept AI SDK tools too — see [Mastra](/ai/mastra). --- # Anthropic / Claude (/ai/anthropic) Project sandbox tools into the Anthropic SDK's runnable-tool shape. One array works with both the toolRunner auto-loop and a manual messages.create loop. Use the ai() plugin with the anthropic() framework, or toAnthropicTools(). ## Installation [#installation] `@anthropic-ai/sdk` is an optional peer dependency. pnpm bun npm yarn ```bash pnpm add sbox-sdk @anthropic-ai/sdk ``` ```bash bun add sbox-sdk @anthropic-ai/sdk ``` ```bash npm install sbox-sdk @anthropic-ai/sdk ``` ```bash yarn add sbox-sdk @anthropic-ai/sdk ``` ## Usage [#usage] Pass the `anthropic()` framework to the `ai()` plugin and `sandbox.tools` is an array of runnable Claude tools. The simplest path is the beta `toolRunner`, which runs the whole tool loop for you: ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { anthropic } from "sbox-sdk/anthropic"; import Anthropic from "@anthropic-ai/sdk"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), plugins: [ai({ framework: anthropic() })], }); const sandbox = await client.create({ template: "node" }); const claude = new Anthropic(); const message = await claude.beta.messages.toolRunner({ model: "claude-sonnet-4-5", max_tokens: 1024, messages: [ { role: "user", content: "Create app.js that prints hello, then run it." }, ], tools: sandbox.tools, }); ``` ## One array, both loops [#one-array-both-loops] Each tool is a *runnable tool* — it is both a tool definition and an executor — so the same `sandbox.tools` array also works with a manual `messages.create` loop: ```ts const res = await claude.beta.messages.create({ model, max_tokens, messages, tools: sandbox.tools, }); for (const block of res.content) { if (block.type === "tool_use") { const tool = sandbox.tools.find((t) => t.name === block.name)!; const output = await tool.run(tool.parse(block.input)); // append a tool_result block with `output`, then continue the conversation } } ``` ## Standalone [#standalone] ```ts import { toAnthropicTools } from "sbox-sdk/anthropic"; const tools = toAnthropicTools(sandbox, { only: ["sbox_exec", "sbox_fs_read"], }); ``` ## Approval [#approval] Claude has no native human-in-the-loop, so this adapter enforces the [policy](/ai/approval) inside each tool's `run`: a `deny` decision short-circuits, and `ask` awaits `policy.onApprovalRequest` when configured. Both return a message Claude reads. ```ts plugins: [ ai({ framework: anthropic(), policy: { defaults: { destructive: "ask" }, onApprovalRequest: async (req) => askUser(req.title), }, }), ]; ``` ## Notes [#notes] * Peer range: `@anthropic-ai/sdk@>=0.40`. The runnable tools use the SDK's beta tool helpers. --- # Approval (/ai/approval) One SandboxPolicy decides allow / ask / deny per tool call. Each framework maps "ask" to its native human-in-the-loop. Destructive actions pause by default. ## Why approval [#why-approval] Sandboxes exist to run untrusted code, and an agent calling `sbox_fs_remove` or `sbox_lifecycle` with `action: "destroy"` is exactly the kind of action you may want a human to confirm. A single `SandboxPolicy` governs every tool, on every framework. ## The default posture [#the-default-posture] Without any configuration, the policy is **destructive-asks**: | Risk | Default | Examples | | ------------- | ------- | ----------------------------------------------------------------------------------------------- | | `safe` | `allow` | `sbox_fs_read`, `sbox_fs_list`, `sbox_lifecycle` → `getInfo` | | `mutating` | `allow` | `sbox_exec`, `sbox_fs_write`, `sbox_run_code`, `sbox_expose_port` | | `destructive` | `ask` | `sbox_fs_remove`, `sbox_lifecycle` → `stop` / `destroy`, `sbox_snapshot` → `restore` / `delete` | So reads, writes, and command execution run freely, while irreversible actions pause for approval. ## Configuring the policy [#configuring-the-policy] ```ts import type { SandboxPolicy } from "sbox-sdk/agent-tools"; const policy: SandboxPolicy = { // Per-risk defaults (merged over the built-ins above). defaults: { mutating: "ask", destructive: "deny" }, // Per-tool overrides — can inspect the actual input. Wins over `defaults`. rules: { sbox_exec: (input) => String((input as { command: string }).command).startsWith("rm ") ? "ask" : "allow", }, // Hard removal — the tool never appears in the produced set. forbid: ["sbox_set_egress"], // Called for "ask" by frameworks without native HITL (see below). onApprovalRequest: async (req) => { return confirmWithHuman(`${req.title} — allow?`); // your UI / queue }, // Observe every decision (logging, metrics, audit trails). audit: (rec) => log.info(rec), }; ``` Pass it to a plugin, a standalone function, or a single `create` call: ```ts plugins: [ai({ framework: aiSdk(), policy })]; // client-wide default toAISDKTools(sandbox, { policy }); // standalone client.create(spec, { policy }); // this sandbox only ``` ## How each framework handles "ask" [#how-each-framework-handles-ask] The policy is authored once; each adapter maps a decision into that framework's native mechanism. | Decision | OpenAI Agents | AI SDK · Mastra · Anthropic · LangChain | | -------- | ------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- | | `allow` | runs | runs | | `ask` | native `needsApproval` → a `RunResult` interruption your host approves/rejects | awaits `policy.onApprovalRequest`; runs if it resolves `true`, otherwise returns a denial the model reads | | `deny` | denial message | denial message | [OpenAI Agents](/ai/openai) has built-in human-in-the-loop, so `ask` surfaces as an interruption on the run result. The other frameworks have no native gate in their current releases, so `ask` calls your `onApprovalRequest` callback. If you don't provide one, `ask` proceeds — human-in-the-loop is opt-in, so the tools never silently block. ## Risk classes [#risk-classes] Risk is a property of the tool (and, for multi-verb tools, the chosen action), not of the provider: * **`safe`** — read-only, no side effects. * **`mutating`** — changes state but is recoverable. * **`destructive`** — irreversible (deletes data, tears down or restores the sandbox). Override the decision for any risk via `defaults`, or for any specific tool via `rules`. --- # LangChain (/ai/langchain) Project sandbox tools into @langchain/core tool() objects as an array for any LangChain agent or LangGraph ToolNode. Use the ai() plugin with the langchain() framework, or toLangChainTools(). ## Installation [#installation] `@langchain/core` is an optional peer dependency. pnpm bun npm yarn ```bash pnpm add sbox-sdk @langchain/core ``` ```bash bun add sbox-sdk @langchain/core ``` ```bash npm install sbox-sdk @langchain/core ``` ```bash yarn add sbox-sdk @langchain/core ``` ## Usage [#usage] Pass the `langchain()` framework to the `ai()` plugin and `sandbox.tools` is an array of structured tools for any LangChain agent: ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { langchain } from "sbox-sdk/langchain"; import { ChatOpenAI } from "@langchain/openai"; import { createReactAgent } from "@langchain/langgraph/prebuilt"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), plugins: [ai({ framework: langchain() })], }); const sandbox = await client.create({ template: "node" }); const agent = createReactAgent({ llm: new ChatOpenAI({ model: "gpt-4o" }), tools: sandbox.tools, // StructuredToolInterface[] }); const result = await agent.invoke({ messages: [ { role: "user", content: "Create app.js that prints hello, then run it." }, ], }); ``` You can also bind the tools to a model directly with `model.bindTools(sandbox.tools)`. ## Standalone [#standalone] ```ts import { toLangChainTools } from "sbox-sdk/langchain"; const tools = toLangChainTools(sandbox, { only: ["sbox_exec", "sbox_fs_read"], }); ``` `toLangChainTools` accepts a live `Sandbox` or a pre-built `ToolSpec[]`. ## Approval [#approval] This adapter enforces the [policy](/ai/approval) inside the tool function via `policy.onApprovalRequest` — `deny` short-circuits, `ask` awaits your callback: ```ts plugins: [ ai({ framework: langchain(), policy: { defaults: { destructive: "ask" }, onApprovalRequest: async (req) => askUser(req.title), }, }), ]; ``` For graph-native human-in-the-loop, wrap the call in a LangGraph `interrupt()`. ## Notes [#notes] * Peer range: `@langchain/core@>=0.3` (Zod 4 supported). * The only required peer is `@langchain/core`; agent runtimes like `@langchain/langgraph` and model packages are yours to choose. --- # Mastra (/ai/mastra) Project sandbox tools into Mastra's createTool() shape, keyed by id for an Agent. Use the ai() plugin with the mastra() framework, or the standalone toMastraTools(). ## Installation [#installation] `@mastra/core` is an optional peer dependency. Use **version 1 or later** — older `0.10.x` releases pin Zod 3 and AI SDK 4 and are incompatible. pnpm bun npm yarn ```bash pnpm add sbox-sdk @mastra/core ``` ```bash bun add sbox-sdk @mastra/core ``` ```bash npm install sbox-sdk @mastra/core ``` ```bash yarn add sbox-sdk @mastra/core ``` ## Usage [#usage] Pass the `mastra()` framework to the `ai()` plugin and `sandbox.tools` is a tool map you register on an `Agent`: ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { mastra } from "sbox-sdk/mastra"; import { Agent } from "@mastra/core/agent"; import { openai } from "@ai-sdk/openai"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), plugins: [ai({ framework: mastra() })], }); const sandbox = await client.create({ template: "node" }); const agent = new Agent({ name: "coder", instructions: "You write and run code in a sandbox.", model: openai("gpt-4o"), tools: sandbox.tools, // Record, keyed by tool id }); const res = await agent.generate( "Create app.js that prints hello, then run it." ); ``` ## Standalone [#standalone] ```ts import { toMastraTools } from "sbox-sdk/mastra"; const tools = toMastraTools(sandbox, { only: ["sbox_exec", "sbox_fs_read"] }); ``` `toMastraTools` accepts a live `Sandbox` or a pre-built `ToolSpec[]`. ## Approval [#approval] Mastra has native suspend/resume, but for v1 this adapter enforces the [policy](/ai/approval) inside `execute` via `policy.onApprovalRequest`, consistent with the other adapters — `deny` short-circuits, `ask` awaits your callback: ```ts plugins: [ ai({ framework: mastra(), policy: { defaults: { destructive: "ask" }, onApprovalRequest: async (req) => askUser(req.title), }, }), ]; ``` ## Notes [#notes] * Peer range: `@mastra/core@^1`. * Mastra is built on the AI SDK and also accepts [AI SDK tools](/ai/ai-sdk) directly, so `ai({ framework: aiSdk() })` output works in a Mastra agent too. The native adapter is preferred for Mastra-native registration. --- # OpenAI Agents (/ai/openai) Project sandbox tools into the OpenAI Agents SDK tool() shape as an array, with native needsApproval human-in-the-loop. Use the ai() plugin with the openaiAgents() framework, or toOpenAITools(). ## Installation [#installation] `@openai/agents` is an optional peer dependency. pnpm bun npm yarn ```bash pnpm add sbox-sdk @openai/agents ``` ```bash bun add sbox-sdk @openai/agents ``` ```bash npm install sbox-sdk @openai/agents ``` ```bash yarn add sbox-sdk @openai/agents ``` ## Usage [#usage] Pass the `openaiAgents()` framework to the `ai()` plugin and `sandbox.tools` is a tool array you pass to `new Agent`: ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { openaiAgents } from "sbox-sdk/openai"; import { Agent, run } from "@openai/agents"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), plugins: [ai({ framework: openaiAgents() })], }); const sandbox = await client.create({ template: "node" }); const agent = new Agent({ name: "coder", instructions: "You write and run code in a sandbox.", tools: sandbox.tools, // Tool[] }); const result = await run( agent, "Create app.js that prints hello, then run it." ); ``` `sandbox.tools` is a `Tool[]`. Schemas are passed with `strict: true`; the SDK converts our optional fields to the nullable-and-required form OpenAI strict mode expects. ## Standalone [#standalone] ```ts import { toOpenAITools } from "sbox-sdk/openai"; const tools = toOpenAITools(sandbox, { only: ["sbox_exec", "sbox_fs_read"] }); ``` ## Approval [#approval] The OpenAI Agents SDK has **native human-in-the-loop**, so this adapter wires the [policy](/ai/approval) into `needsApproval`. An `ask` decision surfaces as a `tool_approval_requested` interruption on the `RunResult` — your host approves or rejects it, then re-runs: ```ts let result = await run(agent, prompt); while (result.interruptions?.length) { for (const interruption of result.interruptions) { if (await humanApproves(interruption)) result.state.approve(interruption); else result.state.reject(interruption); } result = await run(agent, result.state); } ``` A `deny` decision is enforced inside the tool and returns a message the model reads. ## Notes [#notes] * Peer range: `@openai/agents@>=0.12`. --- # Overview (/ai/overview) Turn any sandbox into a set of tools your AI agent can call — one plugin shapes sandbox.tools for your framework, capability-gated to the provider and gated by an approval policy. ## Give your agent a sandbox [#give-your-agent-a-sandbox] The AI layer turns a `Sandbox` into tools an LLM can call — run commands, read and write files, execute code, expose ports — shaped for whichever agent framework you use, with a single approval policy you control. You write the integration once. Pick an **AI-provider plugin**, and the sandbox grows a correctly-typed `sandbox.tools` you hand straight to your framework: ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { aiSdk } from "sbox-sdk/ai-sdk"; import { generateText } from "ai"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), plugins: [ai({ framework: aiSdk() })], }); const sandbox = await client.create({ template: "node" }); // `sandbox.tools` is typed for the AI SDK and already filtered to what E2B supports. const result = await generateText({ model, prompt: "Create app.js that prints hello, then run it.", tools: sandbox.tools, }); ``` The framework you pass to `ai()` **decides the shape** of `sandbox.tools` — a tool map for the AI SDK, an array for OpenAI Agents, runnable tools for Claude. Swap `e2b()` for `vercel()` and the toolset re-shapes itself to the new provider's capabilities, with zero changes to your agent code. ## How it fits together [#how-it-fits-together] One provider-neutral tool registry is projected into every framework. You never hand-write the same tools per framework: ``` Sandbox ──▶ agent-tools (10 capability-gated tools + policy) │ projection (shape only) ┌────────────┼─────────────┬──────────────┬───────────────┐ ▼ ▼ ▼ ▼ ▼ ai-sdk mastra openai anthropic langchain tool() map createTool map tool() array runnable[] tool() array ``` * **[AI providers](/ai/providers)** — install an AI-provider [plugin](/plugins/overview) on the client and `sandbox.tools` is ready to use, typed for your framework. * **[Tools](/ai/tools)** — the 10 canonical tools, each mapped to the core `Sandbox` API and gated by the provider's capabilities. * **[Approval](/ai/approval)** — one `SandboxPolicy` decides `allow` / `ask` / `deny` per call; each framework maps `ask` to its native human-in-the-loop. ## Two ways to use it [#two-ways-to-use-it] Every framework subpath ships both layers: 1. **Plugin (batteries included)** — `plugins: [ai({ framework: aiSdk() })]` → `sandbox.tools`. The shape follows the framework you pass. 2. **Standalone function (composable)** — `toAISDKTools(sandbox)` returns the same tools explicitly, for when you want to filter, merge, or build them yourself. ```ts import { toAISDKTools } from "sbox-sdk/ai-sdk"; const tools = toAISDKTools(sandbox, { policy: { defaults: { destructive: "ask" } }, }); ``` ## Supported frameworks [#supported-frameworks] All used as `ai({ framework: … })`: | Framework | Subpath | Adapter | `sandbox.tools` | | ----------------------------------- | -------------------- | ---------------- | --------------- | | [Vercel AI SDK](/ai/ai-sdk) | `sbox-sdk/ai-sdk` | `aiSdk()` | tool map | | [Mastra](/ai/mastra) | `sbox-sdk/mastra` | `mastra()` | tool map | | [OpenAI Agents](/ai/openai) | `sbox-sdk/openai` | `openaiAgents()` | tool array | | [Anthropic / Claude](/ai/anthropic) | `sbox-sdk/anthropic` | `anthropic()` | runnable tools | | [LangChain](/ai/langchain) | `sbox-sdk/langchain` | `langchain()` | tool array | Each framework SDK is an optional peer dependency — install only the one you use. --- # AI providers (/ai/providers) AI-provider plugins shape sandbox.tools for your framework — capability-gated, policy-aware, and typed. One per client, configurable per sandbox. An **AI-provider plugin** is the first [plugin](/plugins/overview) kind. It grafts a framework-shaped `sandbox.tools` onto every sandbox the client builds. This page covers what's specific to AI providers; for the general plugin mechanism, see [Plugins](/plugins/overview). ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { aiSdk } from "sbox-sdk/ai-sdk"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), plugins: [ai({ framework: aiSdk() })], }); const sandbox = await client.create(); sandbox.tools; // typed for the AI SDK, ready for generateText({ tools }) ``` ## The shape follows the provider *and* the framework [#the-shape-follows-the-provider-and-the-framework] `sandbox.tools` is resolved on two axes at once: * **Capability-gated to the provider** — a tool only appears if the provider supports it. On a provider without a code interpreter, `sbox_run_code` simply isn't there. See [Tools](/ai/tools). * **Typed for the framework** — the framework you pass to `ai()` decides the type: a tool map for the AI SDK, an array for OpenAI Agents, runnable tools for Claude. Swap `e2b()` for `vercel()` and `sandbox.tools` re-shapes to the new provider's capabilities with no change to your agent code. ## One AI-provider per client [#one-ai-provider-per-client] An agent runs in exactly one framework — you hand `sandbox.tools` to a single `generateText(...)` or `new Agent({ tools })` call — so a single shape is correct. The client **throws** if you pass two AI-provider plugins: ```ts // ❌ throws: a client supports one AI-provider plugin createSandboxClient({ provider: e2b(), plugins: [ai({ framework: aiSdk() }), ai({ framework: openaiAgents() })], }); ``` Need two framework shapes from one sandbox (libraries, benchmarks)? Use the standalone `toXTools(sandbox)` functions, or read the provider-neutral registry with `createSandboxTools(sandbox)`. Other [plugin kinds](/plugins/overview#plugin-kinds) stack freely alongside an AI provider. ## Policy per sandbox [#policy-per-sandbox] The framework is fixed on the client, but a sandbox's trust posture often isn't — you may run trusted internal work in one sandbox and untrusted user code in another. Pass per-sandbox overrides as the second argument to `create`: ```ts const client = createSandboxClient({ provider: e2b(), plugins: [ai({ framework: aiSdk(), policy: trustedDefaults })], // default policy }); // Tighten approval for this sandbox only: const box = await client.create(spec, { policy: { defaults: { mutating: "ask", destructive: "deny" } }, }); ``` Overrides apply to `policy`, `only`, and `forbid` — never the framework. See [Approval](/ai/approval). ## Configuring a plugin [#configuring-a-plugin] Every AI-provider plugin accepts the same options as its standalone function — a `policy`, an `only` allow-list, and a `forbid` list: ```ts plugins: [ ai({ framework: aiSdk(), only: ["sbox_exec", "sbox_fs_read", "sbox_fs_write"], policy: { forbid: ["sbox_set_egress"] }, }), ]; ``` See the per-framework pages for each plugin's output shape and approval behavior: [Vercel AI SDK](/ai/ai-sdk), [Mastra](/ai/mastra), [OpenAI Agents](/ai/openai), [Anthropic](/ai/anthropic), [LangChain](/ai/langchain). --- # Tools (/ai/tools) The 10 canonical sandbox tools, each mapped to the core Sandbox API and gated by the provider's capabilities. Authored once, projected into every framework. ## The canonical tools [#the-canonical-tools] Every adapter projects from the same provider-neutral registry. There are ten tools, each mapped to a real `Sandbox` operation: | Tool | Maps to | Always present? | Risk | | ------------------ | ------------------------------------------------------------------ | :---------------------: | ----------- | | `sbox_exec` | `commands.run` | yes | mutating | | `sbox_run_code` | `code.runCode` | needs `codeInterpreter` | mutating | | `sbox_fs_read` | `files.read` | yes | safe | | `sbox_fs_write` | `files.write` | yes | mutating | | `sbox_fs_list` | `files.list` | yes | safe | | `sbox_fs_remove` | `files.remove` | yes | destructive | | `sbox_expose_port` | `ports.expose` | needs `exposePort` | mutating | | `sbox_snapshot` | `snapshots.*` | needs `snapshot` | per-action | | `sbox_lifecycle` | `getInfo` / `setTimeout` / `stop` / `pause` / `resume` / `destroy` | yes | per-action | | `sbox_set_egress` | `network.setEgressPolicy` | needs `egressControl` | mutating | `sbox_snapshot` and `sbox_lifecycle` fold several verbs behind one `action` argument to keep the tool count low (too many tools degrades model selection). Their risk is refined per action — `sbox_lifecycle` with `action: "getInfo"` is `safe`, with `action: "destroy"` is `destructive`. The [`risk`](/ai/approval) class drives the default approval posture. ## Capability gating [#capability-gating] A tool only exists if the provider can do it. `createSandboxTools` filters the set against the sandbox's [capabilities](/general/capabilities): ```ts import { createSandboxClient } from "sbox-sdk"; import { memory } from "sbox-sdk/testing"; import { createSandboxTools } from "sbox-sdk/agent-tools"; const sandbox = await createSandboxClient({ provider: memory() }).create(); createSandboxTools(sandbox).map((t) => t.name); // in-memory provider has no code interpreter or egress control, so: // → sbox_exec, sbox_fs_read, sbox_fs_write, sbox_fs_list, sbox_fs_remove, // sbox_expose_port, sbox_snapshot, sbox_lifecycle // (sbox_run_code and sbox_set_egress are absent) ``` This is why `sandbox.tools` from an [AI-provider plugin](/ai/providers) automatically reflects the provider: a richer provider exposes more tools, with no change to your code. ## The neutral registry [#the-neutral-registry] `createSandboxTools` returns a provider- and framework-agnostic `ToolSpec[]` — the input every framework adapter projects from. You rarely need it directly (the plugins and `toXTools` functions call it for you), but it's there when you want to filter, inspect, or build a custom integration: ```ts import { createSandboxTools } from "sbox-sdk/agent-tools"; const specs = createSandboxTools(sandbox, { only: ["sbox_exec", "sbox_fs_read", "sbox_fs_write"], policy: { forbid: ["sbox_fs_remove"] }, }); ``` Each `ToolSpec` carries a `name`, a model-facing `description`, a Zod `inputSchema`, a `risk` class, and an `execute` that validates its input and **never throws** for a tool-level failure — it returns a result the model can read and react to. ## Results [#results] Tools return their output to the model as text. A failure (a non-zero command, a missing file, a denied call) comes back as a readable message rather than an exception, so the agent loop keeps going and the model can recover. ## Excluded operations [#excluded-operations] A few `Sandbox` operations are deliberately **not** tools because their results can't be serialized to a model: `snapshots.fork` (returns new `Sandbox` objects), `ports.fetch` (returns a `Response`), and raw streaming process handles. Reach for those through the typed [escape hatch](/general/escape-hatch) or the core API directly. --- # Client (/api/client) createSandboxClient is the single entry point — it owns provider selection, idempotency-aware retry and fallback, lifecycle hooks, and disposal. ## `createSandboxClient(options?)` [#createsandboxclientoptions] The single entry point. Pass a provider adapter, or call with no arguments for the zero-config in-memory provider. ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), }); ``` ### Options [#options] | Option | Type | Default | Purpose | | ----------------- | ----------------------------- | ------------------ | -------------------------------------------------------- | | `provider` | `SandboxProvider` | in-memory | The adapter to route to | | `fallback` | `SandboxProvider[]` | `[]` | Backup providers — engages only with an `idempotencyKey` | | `retry` | `RetryPolicy` | `{ retries: 2 }` | `retries`, `delayMs`, `shouldRetry` | | `hooks` | `Hooks` | — | `beforeCreate`, `afterCreate`, `onError` | | `fetch` | `typeof fetch` | `globalThis.fetch` | Injectable transport (test seam) | | `emulate` | `(keyof CapabilityMap)[]` | — | Opt-in lossy emulations | | `defaultMetadata` | `Record` | — | Merged into every `create` | | `plugins` | `SandboxPlugin[]` | `[]` | Augment every sandbox (e.g. the `ai(...)` plugin) | | `telemetry` | `boolean \| TelemetryOptions` | enabled | Anonymous usage data. Pass `false` to opt out | See [Retries & fallback](/retries) for `retry`, `fallback`, and `hooks` in depth. See [Anonymous usage data](/telemetry) for what is collected and how to opt out. ## `SandboxClient` [#sandboxclient] The object returned by `createSandboxClient`. | Member | Signature | Notes | | -------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `create` | `(spec?: SandboxSpec, options?: SandboxCreateOptions) => Promise` | Idempotency-aware; retries + fallback. `options` carries per-sandbox plugin overrides (e.g. AI `policy`) | | `connect` | `(id: string) => Promise` | Reattach to an existing sandbox | | `list` | `(filter?: ListFilter) => AsyncIterable` | Throws `NotSupported` if the provider has no `list` | | `provider` | `string` | Active provider name (readonly) | | `capabilities` | `Capabilities` | `{ map, flags }` read-model (readonly) | | `dispose` | `() => Promise` | Release provider resources | ## `SandboxSpec` [#sandboxspec] The shape passed to `create()`. `template` is mapped per-adapter — see [Templates](/templates). --- # code (/api/code) The code interpreter namespace — run code in a stateful kernel and collect rich results. Gated on the codeInterpreter capability. `sandbox.code` is **capability-gated** — it's typed `undefined` on providers without a code interpreter (E2B and Cloudflare have it; Vercel and memory don't). Guard before use: ```ts if (sandbox.code) { const exec = await sandbox.code.runCode("import numpy as np; print(np.pi)"); console.log(exec.logs.stdout); } ``` ## Methods [#methods] | Method | Signature | | --------------- | ----------------------------------------- | | `runCode` | `(code, opts?) => Promise` | | `createContext` | `(opts?) => Promise` | `runCode` options: `{ context?, language?, onStdout?, onStderr? }`. Pass a `KernelContext` from `createContext` to keep state across calls (a stateful kernel). ## `CodeExecution` [#codeexecution] ```ts interface CodeExecution { results: RichResult[]; // rich MIME outputs (plots, html, ...) logs: { stdout: string[]; stderr: string[] }; error?: { name: string; value: string; traceback?: string }; } interface RichResult { mime: Record; // e.g. { "image/png": "" } text?: string; } ``` ```ts const exec = await sandbox.code.runCode( "import matplotlib.pyplot as plt; plt.plot([1,2,3]); plt.show()" ); for (const r of exec.results) { if (r.mime["image/png"]) save(r.mime["image/png"]); } ``` --- # commands (/api/commands) Run, spawn, stream, and kill processes. commands.run returns a handle that is both a Promise and an AsyncIterable, and never throws on a non-zero exit. `sandbox.commands` is always present. It covers process execution across every adapter. ## `run(cmd, opts?)` [#runcmd-opts] Returns an `ExecHandle` — both a `Promise` and an `AsyncIterable`. `await` it to buffer, or `for await` the **same handle** to stream live. It **never throws on a non-zero exit** — the exit code is data. ```ts // Buffered: const res = await sandbox.commands.run("npm test", { cwd: "/app" }); res.exitCode; // number — non-zero is NOT an error res.stdout; res.stderr; // Streamed (same handle): for await (const ev of sandbox.commands.run(["python", "train.py"])) { if (ev.type === "stdout") process.stdout.write(ev.data); if (ev.type === "exit") console.log(ev.exitCode); } ``` `cmd` is a `string` or `string[]`. The handle also exposes `pid: Promise`, `stdout` / `stderr` as `ReadableStream`s, `kill(signal?)`, and `writeStdin(data)`. ### `ExecOptions` [#execoptions] ### `ExecResult` [#execresult] ```ts interface ExecResult { readonly stdout: string; readonly stderr: string; readonly exitCode: number; readonly exitCodeSynthesized?: boolean; // true when parsed from a $? echo } ``` ### `OutputEvent` [#outputevent] ```ts type OutputEvent = | { type: "stdout"; data: string } | { type: "stderr"; data: string } | { type: "exit"; exitCode: number; signal?: string }; ``` ## Other methods [#other-methods] | Method | Signature | Notes | | --------- | --------------------------------------- | ----------------------------- | | `spawn` | `(cmd, opts?) => Promise` | Long-lived background process | | `connect` | `(processId) => Promise` | Reattach to a running process | | `kill` | `(processId, signal?) => Promise` | | | `list` | `() => Promise` | | `spawn` requires the `background` capability and `kill` requires `killProcess`; `connect` and `list` depend on the adapter implementing them. Each throws `NotSupportedError` on providers that don't support it. --- # files (/api/files) The filesystem namespace — read, write, list, mkdir, remove, rename, stat, exists, upload, download, and watch. Web-standard bodies in, StoredFile out. `sandbox.files` is always present — native where the provider has filesystem primitives, and polyfilled over `exec` where it doesn't. ## Bodies and `StoredFile` [#bodies-and-storedfile] Write bodies are web-standard: `string | Uint8Array | ReadableStream`. Reads return a `StoredFile`: ```ts interface StoredFile { path: string; text(): Promise; bytes(): Promise; stream(): ReadableStream; } ``` ```ts await sandbox.files.write("/app/data.json", JSON.stringify({ ok: true })); const file = await sandbox.files.read("/app/data.json"); const text = await file.text(); ``` ## Methods [#methods] | Method | Signature | | ------------------- | ------------------------------------------------ | | `read` / `download` | `(path) => Promise` | | `write` / `upload` | `(path, data: FileBody) => Promise` | | `list` | `(path) => Promise` | | `mkdir` | `(path, { recursive? }) => Promise` | | `remove` | `(path, { recursive? }) => Promise` | | `rename` | `(from, to) => Promise` | | `stat` | `(path) => Promise` | | `exists` | `(path) => Promise` | | `watch` | `(path, cb, { recursive? }) => Promise` | ## Notes [#notes] * `exists()` returns `false` **only** on `NotFound` — auth and timeout errors still throw. See [Errors](/errors). * `watch()` requires the `filesWatch` capability and throws `NotSupportedError` where it's unsupported. * On providers without native filesystem methods, `list` / `mkdir` / `remove` / `rename` / `stat` are polyfilled by the core via `exec`. ### `FileInfo` & `DirEntry` [#fileinfo--direntry] ```ts interface FileInfo { path: string; type: "file" | "dir" | "symlink"; size: number; mtime?: Date; } interface DirEntry { name: string; path: string; type: "file" | "dir" | "symlink"; } ``` --- # lifecycle (/api/lifecycle) Top-level sandbox lifecycle — getInfo, setTimeout, pause, resume, stop, and destroy. Always present, runtime-gated per provider. Lifecycle methods live directly on the `Sandbox` (not in a namespace). They are **always present** so the swap-one-import promise holds, but **runtime-gated**: calling one a provider doesn't support throws `NotSupportedError`. ## Methods [#methods] | Method | Signature | Capability | | ------------ | ---------------------------------- | -------------------- | | `getInfo` | `() => Promise` | always | | `setTimeout` | `(ttlMs: number) => Promise` | `setTimeout` | | `pause` | `() => Promise` | `pause` | | `resume` | `() => Promise` | (pairs with `pause`) | | `stop` | `() => Promise` | `stop` | | `destroy` | `() => Promise` | always | ```ts const info = await sandbox.getInfo(); info.state; // "running" | "paused" | "stopped" | ... if (sandbox.can("pause")) { await sandbox.pause(); await sandbox.resume(); } await sandbox.setTimeout(120_000); await sandbox.destroy(); ``` ## Pause vs stop semantics [#pause-vs-stop-semantics] What survives depends on the provider's behavioral flags (see [Capabilities](/capabilities)): * `preservesMemoryOnPause` — whether RAM survives a `pause()`. * `preservesDiskOnStop` — whether disk survives a `stop()`. For example, E2B preserves memory on pause; Vercel auto-snapshots the filesystem on stop. Check `sandbox.capabilities.flags` to branch on this rather than assuming. ## Cleanup [#cleanup] Always `destroy()` sandboxes you create, and `dispose()` the client when you're done: ```ts await sandbox.destroy(); await client.dispose(); ``` --- # ports (/api/ports) Expose a port and get a preview URL, list exposures, and proxy a fetch through the sandbox. Gated on the exposePort capability. `sandbox.ports` is **capability-gated** on `exposePort` — native on E2B, Vercel, and Cloudflare; emulated on the in-memory provider. Guard before use: ```ts if (sandbox.ports) { const preview = await sandbox.ports.expose(3000); console.log(preview.url); } ``` ## Methods [#methods] | Method | Signature | Notes | | ---------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `expose` | `(port, { private? }) => Promise` | Returns the preview URL | | `unexpose` | `(port) => Promise` | | | `list` | `() => Promise` | | | `fetch` | `(port, path?, init?) => Promise` | Proxy a request through the sandbox — native proxy where `proxiedFetch` is supported, else via an exposed preview URL | ## `Preview` [#preview] ```ts interface Preview { url: string; port: number; token?: string; } ``` How the `url` is formed depends on the provider's `previewModel` flag — `subdomain` (E2B), `declaredPorts` (Vercel), `wildcardDNS` (Cloudflare), or `ip` (memory). See [Capabilities](/capabilities). --- # Sandbox (/api/sandbox) The object you hold after create() — always-present commands and files namespaces, capability-gated sub-APIs, lifecycle methods, and the raw() escape hatch. A `Sandbox` is what `client.create()` and `client.connect()` return. It groups everything into namespaces, with capability-gated sub-APIs typed `undefined` when the provider can't support them. ## Members [#members] | Member | Type | Presence | | ------------------------------------------ | ----------------------------------- | ----------------------------------------------------------------- | | `id` / `name?` / `provider` | `string` | always | | `capabilities` | `Capabilities` | always | | `commands` | `CommandsAPI` | **always** (universal) | | `files` | `FilesAPI` | **always** (native or polyfilled) | | `ports` | `PortsAPI \| undefined` | gated on `exposePort` | | `code` | `CodeAPI \| undefined` | gated on `codeInterpreter` | | `snapshots` | `SnapshotsAPI \| undefined` | gated on `snapshot` | | `network` | `NetworkAPI \| undefined` | gated on `egressControl` | | `getInfo` / `destroy` | `() => Promise<…>` | always | | `setTimeout` / `stop` / `pause` / `resume` | `(…) => Promise` | present, but throw `NotSupported` where the capability is missing | | `can` | `(cap: K) => this is Sandbox<…>` | runtime check + type guard | | `raw` | `() => Raw` | the native client, typed per adapter | ## Capability gating [#capability-gating] `ports`, `code`, `snapshots`, and `network` are typed `undefined` on providers that don't support them, so a guard is required — and the absence is caught at compile time: ```ts if (sandbox.code) { await sandbox.code.runCode("print(1)"); } ``` For dynamically-chosen providers, `can()` narrows at runtime and the type level: ```ts if (sandbox.can("snapshot")) { await sandbox.snapshots.create({ name: "ckpt" }); } ``` See [Capabilities](/capabilities) for the model, and [Escape hatch](/escape-hatch) for `raw()`. ## `SandboxInfo` [#sandboxinfo] Returned by `getInfo()`: ```ts interface SandboxInfo { readonly id: string; readonly name?: string; readonly state: SandboxState; // "creating" | "running" | "paused" | "stopped" | "destroyed" | "error" | "unknown" readonly provider: string; readonly metadata: Readonly>; readonly createdAt?: Date; readonly raw: unknown; // the original provider payload } ``` --- # snapshots (/api/snapshots) Checkpoint and restore sandbox state, fork a sandbox, and manage snapshot refs. Gated on the snapshot capability. `sandbox.snapshots` is **capability-gated** on `snapshot` — native on E2B and the in-memory provider; unsupported on Vercel and Cloudflare. Guard before use: ```ts if (sandbox.snapshots) { const ref = await sandbox.snapshots.create({ name: "ckpt" }); // ... mutate ... await sandbox.snapshots.restore(ref); } ``` Snapshots are *runtime* checkpoints, distinct from the build-time [`template`](/templates). ## Methods [#methods] | Method | Signature | Notes | | --------- | ----------------------------------------------- | ------------------------------ | | `create` | `({ name? }) => Promise` | | | `restore` | `(ref: SnapshotRef \| string) => Promise` | | | `fork` | `(count?) => Promise` | Gated on the `fork` capability | | `list` | `() => Promise` | | | `delete` | `(ref: SnapshotRef \| string) => Promise` | | ## `SnapshotRef` [#snapshotref] ```ts interface SnapshotRef { id: string; name?: string; provider: string; createdAt?: Date; raw: unknown; // the original provider payload } ``` --- # Errors (/general/errors) Every provider normalizes to one SandboxError taxonomy — a small set of codes, a retryable flag, and the native error preserved on cause. Providers never leak their native SDK errors past the adapter boundary. Everything routes through one normalized taxonomy, so your error handling is written once and works across every provider. ## `SandboxError` [#sandboxerror] The base class. Key fields: | Field | Type | Meaning | | ----------- | ------------------ | --------------------------------------- | | `code` | `SandboxErrorCode` | The normalized category (see below) | | `provider` | `string?` | Which adapter raised it | | `status` | `number?` | Underlying HTTP status, if any | | `retryable` | `boolean` | Whether a retry could plausibly succeed | | `timedOut` | `boolean` | True for timeout/abort | | `aborted` | `boolean` | True when an `AbortSignal` fired | The original error is preserved on `cause`. Use the static `SandboxError.wrap(err, provider?)` to coerce any thrown value into a `SandboxError` (pass-through if it already is one). ## Error codes [#error-codes] ```ts type SandboxErrorCode = | "NotFound" // sandbox / process / file / snapshot id unknown | "Unauthorized" // bad or expired credentials | "Timeout" // op exceeded timeoutMs / TTL | "QuotaExceeded" // provider resource / billing limit | "NotSupported" // capability gap — thrown BEFORE any network call | "Conflict" // idempotency / state conflict | "ProviderNotFound" // unknown provider id | "Validation" // bad options | "AllProvidersFailed" // every provider in the fallback chain failed | "Provider"; // catch-all normalized provider / network failure ``` `Timeout`, `QuotaExceeded`, and `Provider` are **retryable by default**. ## Specialized classes [#specialized-classes] | Class | When | | ------------------------- | ------------------------------------------------------------------------------------- | | `NotSupportedError` | A capability gap — thrown **synchronously, before any network call**. Adds `feature`. | | `ProviderNotFoundError` | Unknown provider id. | | `AllProvidersFailedError` | Every provider in a fallback chain failed; carries `attempts[]`. | ## Rules worth knowing [#rules-worth-knowing] * `commands.run(...)` **never throws on a non-zero exit** — the exit code is data (`result.exitCode`), not an error. * `files.exists()` returns `false` only on `NotFound`; auth and timeout errors still throw. * `NotSupportedError` is thrown up front, before any network call, so an unsupported feature fails fast and cheap. ## Helpers [#helpers] ```ts import { isRetryableError, isRetryableStatus } from "sbox-sdk"; try { await sandbox.commands.run("..."); } catch (err) { if (isRetryableError(err)) { // err is a retryable SandboxError } } isRetryableStatus(429); // true (408 / 409 / 425 / 429 / >= 500) ``` See [Retries & fallback](/retries) for how the client uses `retryable` to drive automatic retry and provider fallback. --- # Escape hatch (/general/escape-hatch) Drop down to the native, per-adapter client for any provider feature outside the unified surface — fully typed, no casting. The unified surface is deliberately small — the namespaces every adapter can implement. When you need a provider feature that isn't part of it, drop down to the native client instead of waiting for it to be wrapped. ## `sandbox.raw()` [#sandboxraw] `raw()` returns the underlying provider client, **typed per adapter** — the native `Sandbox` from `@e2b/code-interpreter` for `e2b()`, from `@vercel/sandbox` for `vercel()`, from `@cloudflare/sandbox` for `cloudflare()`, and the in-memory store for `memory()`. The type flows through from the adapter, so you keep full autocomplete. ```ts import { e2b } from "sbox-sdk/e2b"; const client = createSandboxClient({ provider: e2b({ apiKey }) }); const sandbox = await client.create(); // Unified path: await sandbox.commands.run("echo hi"); // Native E2B client for something we don't model: const native = sandbox.raw(); // typed as E2B's Sandbox ``` ## When to reach for it [#when-to-reach-for-it] There are three layers, in order of preference: 1. **Capability-gated sub-APIs** (`sandbox.code`, `.ports`, `.snapshots`, `.network`) — for features that *are* in the unified model but not on every provider. 2. **`sandbox.raw()`** — for anything the unified surface doesn't model at all. 3. **`.raw` on payloads** — `SandboxInfo.raw` and `SnapshotRef.raw` carry the original provider response for those calls. ## The tradeoff [#the-tradeoff] `raw()` is the **intentional exit from the portability promise**. Every `commands` / `files` / gated call site survives an adapter swap unchanged; the moment you call `raw()`, that line of code is pinned to one provider. That's the right tool for a genuinely provider-unique feature — but it's a one-way door for that call site, which is why it's an explicit, named method rather than something you reach by accident. If you constructed the client with the default dynamically-typed provider, `raw()` is typed `unknown` and you'd cast it yourself. Import a concrete adapter to get the precise native type. --- # Installation (/general/installation) Install sbox-sdk and the optional peer dependency for the adapter you're using — nothing else is bundled. `sbox-sdk` is small and dependency-free at its core — a fetch-only, edge-portable runtime behind a tree of subpath exports. Install the package, then add the peer dependency for the adapter you're wiring up. Anything you don't import is never bundled. pnpm bun npm yarn ```bash pnpm add sbox-sdk ``` ```bash bun add sbox-sdk ``` ```bash npm install sbox-sdk ``` ```bash yarn add sbox-sdk ``` The package ships its own TypeScript types and is published as ESM (`"type": "module"`), targeting modern runtimes — Node 20+, Bun, Deno, and edge/Workers. The core does no `node:` imports, so it runs unchanged across runtimes. ## Adapter peer dependencies [#adapter-peer-dependencies] Adapters are subpath exports — `sbox-sdk/e2b`, `sbox-sdk/vercel`, `sbox-sdk/cloudflare` — and each provider's native SDK is an **optional peer dependency**, loaded lazily on first `create()` / `connect()`. The SDK you don't import is never bundled, so install size and cold-start cost stay proportional to the providers you actually use. Install the peer dep alongside the SDK. For **E2B**: pnpm bun npm yarn ```bash pnpm add sbox-sdk @e2b/code-interpreter ``` ```bash bun add sbox-sdk @e2b/code-interpreter ``` ```bash npm install sbox-sdk @e2b/code-interpreter ``` ```bash yarn add sbox-sdk @e2b/code-interpreter ``` For **Vercel Sandbox**: pnpm bun npm yarn ```bash pnpm add sbox-sdk @vercel/sandbox ``` ```bash bun add sbox-sdk @vercel/sandbox ``` ```bash npm install sbox-sdk @vercel/sandbox ``` ```bash yarn add sbox-sdk @vercel/sandbox ``` For **Cloudflare Sandbox** (inside a Worker): pnpm bun npm yarn ```bash pnpm add sbox-sdk @cloudflare/sandbox ``` ```bash bun add sbox-sdk @cloudflare/sandbox ``` ```bash npm install sbox-sdk @cloudflare/sandbox ``` ```bash yarn add sbox-sdk @cloudflare/sandbox ``` The [in-memory provider](/adapters/memory) needs no peer dependency at all — it's built in and is the zero-config default, ideal for tests. ## Missing a peer dependency? [#missing-a-peer-dependency] Import an adapter without its peer installed and the lazy import throws `ERR_MODULE_NOT_FOUND` naming the missing package — the SDK doesn't vendor or shim provider clients, so the failure is loud and specific rather than a silent fallback. Install the named package and the import resolves. Once your adapter's package is in place, head to [Usage](/usage) to construct a client and run the core namespaces. --- # Lifecycle (/general/lifecycle) Idle timeouts, max age, pause/resume, reconnecting after a restart, get-or-create by name, fork and snapshots. ## Lifecycle policy [#lifecycle-policy] ```ts const sandbox = await client.create({ lifecycle: { idleTimeoutMs: 10 * 60_000, // suspend after 10 min without activity maxAgeMs: 8 * 3600_000, // hard limit from creation onIdle: "pause", // "pause" | "stop" | "destroy" autoResume: true, // wake on inbound traffic / connect }, }); ``` Each adapter maps these to its nearest native setting (see its page). `ttlMs` and `onIdle` at the top level still work but are deprecated aliases for `lifecycle.maxAgeMs` / `lifecycle.onIdle`. ## States [#states] `getInfo().state` is fetched live from the provider: `creating` · `running` · `suspending` · `paused` · `stopped` · `archived` · `destroyed` · `error` · `unknown` ## Pause, stop, resume [#pause-stop-resume] ```ts await sandbox.pause(); // memory kept where flags.preservesMemoryOnPause await sandbox.stop(); // disk kept where flags.preservesDiskOnStop await sandbox.resume(); ``` `resume()` wakes a paused, stopped or archived sandbox, and requires the `pause` or `stop` capability. On providers with `flags.resumeChangesId` (Together, Morph), resuming produces a **new sandbox id**, so reconnect with the id from `getInfo()`. ## Reconnect after an app restart [#reconnect-after-an-app-restart] ```ts // persist sandbox.id somewhere, then later: const sandbox = await client.connect(savedId, { resume: true }); ``` `{ resume: true }` wakes a paused, stopped or archived sandbox before returning it. ## Get or create by name [#get-or-create-by-name] ```ts const desk = await client.getOrCreate({ name: "user-42-desktop", template: ref, }); ``` This is native on providers with named sandboxes. Elsewhere it's emulated with a `sbox-name` metadata tag and `list()`. ## Fork and snapshots [#fork-and-snapshots] ```ts const [clone] = await sandbox.fork(); // gated on `fork` const snap = await sandbox.snapshots!.create({ name: "after-setup", mode: "memory", }); snap.includesMemory; // true = RAM + processes captured const restored = await client.create({ fromSnapshot: snap }); ``` `snapshots.restore(ref)` restores **in place**, and only exists on providers that support it. Booting from a snapshot with `fromSnapshot` is the portable form. --- # llms.txt (/general/llms-txt) The docs are available as plain markdown for LLMs — an llms.txt index, a full-text bundle, and any page as markdown. Feed them to ChatGPT, Claude, Cursor, or your own agent. Every page of these docs is available as clean markdown, plus two aggregate files following the [llms.txt](https://llmstxt.org) convention — so you can give an LLM accurate, current context about sbox SDK instead of letting it guess. ## Endpoints [#endpoints] | URL | What it is | | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | [`/llms.txt`](/llms.txt) | An index of every doc page, with links and one-line descriptions. | | [`/llms-full.txt`](/llms-full.txt) | The entire documentation concatenated into one markdown file. | | `/llms.mdx/` | Any single page as markdown — append the page's path, e.g. [`/llms.mdx/general/usage`](/llms.mdx/general/usage). | ## Using it [#using-it] * **In a chat (ChatGPT, Claude):** paste `https://sbox-sdk.vercel.app/llms.txt` and ask the model to read the index, then fetch the pages it needs — or paste `https://sbox-sdk.vercel.app/llms-full.txt` to load everything at once. * **In an editor agent (Cursor, Copilot):** add `https://sbox-sdk.vercel.app/llms.txt` as a documentation source. * **From any page:** fetch its markdown by prefixing the path with `/llms.mdx` (this page is at `/llms.mdx/general/llms-txt`). For a guided, hands-off setup, the [sbox-sdk skill](/general/skills) packages these instructions for coding agents. --- # Migrating to 0.1 (/general/migration-0-1) What changed between sbox-sdk 0.0.x and 0.1, and how to update. 0.1 is the first renewal release. Most code keeps working. The deprecated forms below still function in 0.1 and will be removed in 0.2. ## Renamed or moved [#renamed-or-moved] | 0.0.x | 0.1 | | ------------------------------------ | ---------------------------------------------- | | `create({ ttlMs })` | `create({ lifecycle: { maxAgeMs } })` | | `create({ onIdle })` | `create({ lifecycle: { onIdle } })` | | `sandbox.snapshots.fork(n)` | `sandbox.fork({ count: n })` (gated on `fork`) | | `sandbox.network.createSsh()` | `sandbox.ssh.create()` (gated on `ssh`) | | `ports.expose(p, { private: true })` | `ports.expose(p, { visibility: "private" })` | | `preview.token` | `preview.auth` | | `import "sbox-sdk/codesandbox"` | `import "sbox-sdk/together"` | ## Behavior changes [#behavior-changes] * `sandbox.resume()` now throws `NotSupportedError` on providers with neither `pause` nor `stop`. * `ports.fetch()` no longer exposes a port publicly as a fallback. Expose the port first, or use a provider with `proxiedFetch` / `privatePreview`. * `ports.expose(p, { visibility: "private" })` throws on providers without `privatePreview` instead of silently returning a public URL. * `commands.run()` with `timeoutMs` now always rejects with a `Timeout` error, even if the provider ignored the timeout. * Env var names are validated (`[A-Za-z_][A-Za-z0-9_]*`). Invalid names throw `Validation`. * Commands with emulated `cwd` no longer run when `cd` fails. * `getInfo().state` is fetched live, so you'll see real states (`paused`, `archived`, …) where you used to get a hard-coded `running`. * Capability tables were corrected for every adapter. Many features moved from `unsupported` to `native`, so `sandbox.pty`, `sandbox.ssh` and `sandbox.network` may now be defined where they weren't before. ## Provider packages [#provider-packages] | Provider | Old peer | New peer | | ---------- | ------------------------ | -------------------------------------------- | | Daytona | `@daytonaio/sdk` | `@daytona/sdk` (≥ 2) | | Vercel | `@vercel/sandbox` 1–2 | `@vercel/sandbox` ≥ 4 (Node ≥ 22.19) | | Cloudflare | `@cloudflare/sandbox` \* | `@cloudflare/sandbox` \~0.12.14 (deprecated) | ## Deprecated adapters [#deprecated-adapters] * **Runloop**: the service is winding down. Removed in 0.2. * **CodeSandbox**: superseded by Together Sandbox (`sbox-sdk/together`). Removed in 0.2. * **Cloudflare**: the 0.x SDK reaches end of life on 2026-12-31. A 1.x adapter is planned. * **Morph**: maintenance-only, because the TypeScript SDK is unmaintained upstream. ## New [#new] Templates (`client.templates`, inline `create({ template: spec })`), PTY (`sandbox.pty`), `sandbox.metrics()`, `client.volumes`, `client.verify()`, `client.getOrCreate()`, `connect(id, { resume })`, preview `wsUrl`/`auth` + `browserUrl()`, egress `deny`/`inject`, `resources.shmMB`. New adapters: `docker`, `superserve`, `tensorlake`, `sprites`, `freestyle`, `together`. --- # Network & secrets (/general/network) Egress allow/deny policies, credential injection that never exposes secrets to the sandbox, and SSH access. ## Egress policy [#egress-policy] Set the policy at create time, or change it at runtime where the provider supports it: ```ts const sandbox = await client.create({ network: { mode: "allow-list", domains: ["pypi.org", "*.github.com"], cidrs: ["10.0.0.0/8"], }, }); await sandbox.network!.setEgressPolicy({ mode: "block-all" }); await sandbox.network!.setEgressPolicy({ mode: "allow-all", deny: { domains: ["evil.example"] }, }); ``` `sandbox.network` is typed `undefined` without the `egressControl` capability. Some providers only toggle the network on and off. `client.capabilities.flags.egressModes` lists the modes a provider accepts; others throw `NotSupportedError` (e.g. Docker has no `allow-list`). ## Credential injection [#credential-injection] Several providers can add credentials to outbound requests at their egress proxy. The secret **never enters the sandbox**, so an agent can call an API without being able to read or exfiltrate the key. ```ts await client.create({ network: { mode: "allow-all", inject: [ { domains: ["api.github.com"], headers: { Authorization: { name: "gh", value: `Bearer ${token}` } }, }, ], }, secrets: [{ name: "OPENAI_API_KEY", mode: "env" }], // a normal env-var secret }); ``` Support varies by provider: E2B, Vercel, Modal and Freestyle implement `inject`, while Superserve brokers credentials differently and rejects it. Check each adapter's page before relying on it. ## SSH [#ssh] ```ts const creds = await sandbox.ssh!.create(); // { host, port, user, privateKey } ``` `sandbox.ssh` is gated on the `ssh` capability. The old `network.createSsh()` still works but is deprecated. --- # Overview (/general/overview) sbox SDK is a unified TypeScript API for agent sandbox providers — one namespaced surface, capability gating, a single error taxonomy, and a typed escape hatch. ## What is sbox SDK? [#what-is-sbox-sdk] A single TypeScript API for running code in ephemeral **sandboxes** that works the same way across [E2B](/adapters/e2b), [Vercel Sandbox](/adapters/vercel), [Cloudflare Sandbox](/adapters/cloudflare), [Daytona](/adapters/daytona), [Modal](/adapters/modal), [Fly Machines](/adapters/fly), [AWS Lambda MicroVMs](/adapters/aws-lambda), [Northflank](/adapters/northflank), [Runloop](/adapters/runloop), [CodeSandbox](/adapters/codesandbox), [Morph](/adapters/morph), [Blaxel](/adapters/blaxel), [Beam](/adapters/beam), and [Railway](/adapters/railway) — plus an in-memory provider for tests and local dev. You hold a `Sandbox` and call into a handful of namespaces that cover the surface you actually use: * `sandbox.commands` — run, spawn, stream, and kill processes. * `sandbox.files` — read, write, list, and manage the filesystem. * `sandbox.code` — run code in a stateful interpreter (where supported). * `sandbox.ports` — expose a port and get a preview URL. * `sandbox.snapshots` — checkpoint and restore filesystem state. * `sandbox.network` — egress policy and SSH (where supported). Lifecycle (`getInfo`, `pause`, `resume`, `stop`, `destroy`, `setTimeout`) lives on the sandbox itself. When you need a provider-specific feature outside this surface, drop down to the native client via [`sandbox.raw()`](/escape-hatch), which stays typed per adapter. ## Why sbox SDK? [#why-sbox-sdk] Every sandbox provider ships its own shape: different process APIs, different filesystem primitives, different error envelopes, different preview-URL models. Switching providers — or supporting more than one — means rewriting the call sites and re-learning the failure model. sbox SDK collapses that into one client and one error type: * **One API** — the same `commands` / `files` / `code` calls across every adapter. The code that runs a command on E2B is the code that runs it on Vercel. * **Capability gating** — each provider declares a static [capability table](/capabilities). Sub-APIs a provider can't do are typed `undefined` (a compile error), and unsupported features throw `NotSupportedError` *before* any network call. * **Honest exec** — `commands.run()` **never throws on a non-zero exit**. The exit code is data. `await` the handle for a buffered result, or `for await` the same handle to stream output live. * **One error taxonomy** — every provider normalizes to [`SandboxError`](/errors) with a small set of codes (`NotFound`, `Unauthorized`, `Timeout`, `NotSupported`, …) and a `retryable` flag. * **Lazy SDK loading** — adapters are subpath exports (`sbox-sdk/e2b`, `sbox-sdk/vercel`, …) and each provider SDK is an optional peer dependency, imported lazily on first use. The SDK you don't import is never bundled. * **Typed escape hatch** — `sandbox.raw()` is the underlying provider client, typed per adapter, so the unified surface never traps you. ## Next steps [#next-steps] * [Installation](/installation) — install the SDK and your adapter's peer dependency. * [Usage](/usage) — construct a client and run the core namespaces. * [API reference](/api/client) — the full client, sandbox, and namespace surface. * [Adapters](/adapters/memory) — per-provider setup, options, and capability tables. --- # Previews & browser access (/general/previews) Expose a sandbox port as https/wss URLs, choose public or private access, and open private previews from a browser (including WebSockets). ```ts const http = await sandbox.ports!.expose(7000); const vnc = await sandbox.ports!.expose(6080, { visibility: "private" }); http.url; // https://... http.wsUrl; // wss://... (same route; filled in for every provider) vnc.auth; // how a client must authenticate (see below) ``` ## The auth model [#the-auth-model] Every `Preview` carries an `auth` field: | `auth.type` | What the client must do | Browser + WebSocket? | | ------------ | ------------------------------------------- | --------------------------------------------- | | `public` | Nothing | ✅ | | `query` | Add `?=` to the URL | ✅ | | `signed-url` | Nothing, the URL already embeds a signature | ✅ | | `header` | Send `auth.headers` on every request | ❌ (browsers can't set headers on a WebSocket) | `expiresAt` is set when the provider's token or signed URL expires. ## Opening a preview from a browser [#opening-a-preview-from-a-browser] `browserUrl()` returns a URL a browser can open with no custom headers. It works for `public`, `query` and `signed-url` previews, and throws `NotSupportedError` for header-only auth. ```ts import { browserUrl } from "sbox-sdk"; const vnc = await sandbox.ports!.expose(6080, { visibility: "private" }); const wsUrl = browserUrl(vnc, { protocol: "ws", path: "/websockify" }); // → wss://6080-abc.example.dev/websockify?token=... ``` Before relying on private previews from a browser, check the provider flag: ```ts client.capabilities.flags.previewBrowserAuth; // true → private previews work in a browser WebSocket ``` ## Server-side fetch [#server-side-fetch] `sandbox.ports.fetch(port, path, init)` sends a request to a port. It uses the provider's native proxy when there is one. Otherwise it reuses an existing preview (or exposes one *privately*) and attaches the auth for you. It **never** makes a port public as a side effect. ## Visibility [#visibility] * `visibility: "public"` (default): anyone with the URL. * `visibility: "private"`: requires the `privatePreview` capability; otherwise it throws `NotSupportedError`. --- # Retries & fallback (/general/retries) The client retries retryable failures with backoff and can fall back across providers — guarded by an idempotency key so a retry never orphans a second sandbox. `createSandboxClient` owns retry and provider fallback. Both are driven by the [`retryable`](/errors) flag on `SandboxError`. ## Retry policy [#retry-policy] By default the client retries up to twice (3 attempts total) on retryable errors, with exponential backoff. Override per-client: ```ts const client = createSandboxClient({ provider: e2b({ apiKey }), retry: { retries: 4, delayMs: (attempt) => attempt * 250, shouldRetry: (err) => isRetryableError(err), }, }); ``` ## Provider fallback [#provider-fallback] Supply a `fallback` chain and the client will try the next provider when one fails: ```ts const client = createSandboxClient({ provider: e2b({ apiKey }), fallback: [vercel({ token, teamId, projectId })], }); ``` Fallback engages **only when you pass an `idempotencyKey`** on the create spec. This is deliberate: without a stable key, a create that failed *after* spawning a VM could leave an orphan when the client moves to the next provider. The key makes the operation safe to re-attempt. ```ts const sandbox = await client.create({ idempotencyKey: "build-job-42", }); ``` If every provider in the chain fails, the client throws `AllProvidersFailedError` with the per-provider `attempts[]`. ## Hooks [#hooks] Observe the lifecycle with hooks — handy for logging which provider served a request, or recording retry attempts: ```ts const client = createSandboxClient({ provider: e2b({ apiKey }), hooks: { beforeCreate: (spec) => { /* ... */ }, afterCreate: ({ id, provider }) => { /* ... */ }, onError: (err, attempt) => { /* ... */ }, }, }); ``` --- # Skills (/general/skills) Install the sbox-sdk agent skill so coding agents (Claude Code, Cursor, Codex, Copilot) can set up and use sbox correctly — or paste the setup prompt directly. ## The sbox-sdk skill [#the-sbox-sdk-skill] `sbox-sdk` ships an **agent skill** — a `SKILL.md` that teaches a coding agent how to install, configure, and use the SDK correctly: picking an adapter, creating a sandbox client, running commands and files, capability gating, the common gotchas, and exposing sandbox tools to an agent framework. It follows the open [skills.sh](https://skills.sh) format and works with Claude Code, Cursor, GitHub Copilot, Gemini, and more. The skill lives in the repo at [`skills/sbox-sdk/SKILL.md`](https://github.com/vivek-k3/sbox-sdk/blob/main/skills/sbox-sdk/SKILL.md). ## Install [#install] The quickest path is the [skills.sh](https://skills.sh) CLI, which installs into whichever agent you use: ```bash npx skills add vivek-k3/sbox-sdk ``` Or wire it up manually for your agent: Drop the skill into your project (or `~/.claude/skills` for global use): ```bash mkdir -p .claude/skills/sbox-sdk curl -o .claude/skills/sbox-sdk/SKILL.md \ https://raw.githubusercontent.com/vivek-k3/sbox-sdk/main/skills/sbox-sdk/SKILL.md ``` Claude Code loads it automatically and activates it when a task involves sandboxes or running code. Save the `SKILL.md` body as a project rule at `.cursor/rules/sbox-sdk.md` (or paste it into **Settings → Rules**), so the setup and usage instructions are in the agent's context. Any agent with skills or custom-instruction support works — install via `npx skills add vivek-k3/sbox-sdk`, or paste the `SKILL.md` contents into the agent's rules / system prompt. ## Or just paste a prompt [#or-just-paste-a-prompt] No skill support? Paste this into your agent to set sbox up in the current project: ```text Set up sbox-sdk (https://sbox-sdk.vercel.app) in this project. 1. Install it with the E2B adapter: npm install sbox-sdk @e2b/code-interpreter 2. Create a client and a sandbox: import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }) }); const sandbox = await client.create({ template: "python-3.12", ttlMs: 60_000 }); 3. Use sandbox.commands.run(cmd) (it never throws on a non-zero exit — read exitCode), sandbox.files.{read,write,list}, and sandbox.code?.runCode(...) where supported. Capability-gated namespaces (code, ports, snapshots, network) are `undefined` when unsupported — guard with `?.` or sandbox.can(cap). Always set a TTL and call sandbox.destroy() when finished. For exact APIs, fetch https://sbox-sdk.vercel.app/llms.txt and the relevant /llms.mdx/... pages. ``` To give an agent framework sandbox tools instead of writing glue code, see [AI agent tools](/ai/overview). ## What the skill covers [#what-the-skill-covers] * Installing the SDK and the right adapter peer dependency. * Creating a client and sandbox; the core `commands` / `files` / `code` / `ports` API. * The gotchas agents get wrong: [capability gating](/general/capabilities), `commands.run` not throwing on a non-zero exit, optional peer deps, TTLs, and cleanup. * Exposing sandbox tools to an agent via the [`ai()` plugin](/ai/providers). * Where to fetch exact signatures — [`/llms.txt`](/general/llms-txt) and per-page markdown. --- # Anonymous usage data (/general/telemetry) sbox SDK collects limited anonymous usage data to understand adoption and improve the SDK. ## What we collect [#what-we-collect] sbox SDK collects limited anonymous usage data by default. We use it to understand adoption, see which parts of the SDK are used, and prioritize improvements. The data is intentionally coarse: * SDK version * runtime and platform * selected provider * operation type, such as creating a sandbox or running a command * success or failure * duration bucket * error category * command exit code Usage data may be sent from any environment where the SDK runs, including local development, CI, tests, previews, and production. This is separate from any analytics you use in your own app. sbox SDK does not read, modify, identify, or share state with your app's analytics client. ## What we never collect [#what-we-never-collect] sbox SDK does not collect: * API keys or credentials * prompts or model inputs * command strings * file paths or file contents * environment variables * stdout or stderr * sandbox ids * project names * metadata values * provider-specific request payloads ## How to opt out [#how-to-opt-out] Set any of these environment variables: ```bash SBOX_TELEMETRY_DISABLED=1 SBOX_DISABLE_TELEMETRY=1 SBOX_TELEMETRY=0 DO_NOT_TRACK=1 ``` Or disable usage data for one client: ```ts import { createSandboxClient } from "sbox-sdk"; const client = createSandboxClient({ telemetry: false, }); ``` Usage data is not automatically disabled in CI, tests, local development, previews, or production. Use one of the opt-out controls above when you do not want it sent. --- # Templates (/general/templates) Build a reusable base image from a Dockerfile, an image or a snapshot, in your own provider account, cached by content hash. A template is the build-time base a sandbox boots from. You can name an existing provider template by id, or have sbox **build one for you** from a Dockerfile, an image, or a snapshot. ```ts // 1. An existing provider template / image / snapshot alias (provider-specific string) await client.create({ template: "python-3.12" }); // 2. Build once, reuse everywhere const ref = await client.templates!.build( { name: "desktop", source: { dockerfile: await readFile("./desktop/Dockerfile", "utf8"), context: "./desktop", }, resources: { vcpus: 2, memoryMB: 4096 }, startCmd: "/usr/local/bin/start-desktop", }, { onEvent: (e) => console.log(e.type === "log" ? e.line : `[${e.status}]`) } ); const sandbox = await client.create({ template: ref }); // 3. Inline: built on first use, reused by content hash afterwards await client.create({ template: { source: { dockerfile, context: "./desktop" } }, onTemplateEvent: (e) => console.log(e), }); ``` ## Sources [#sources] | Source | Meaning | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `{ dockerfile, context? }` | Dockerfile **contents** (not a path). `context` is a local directory (Node) or an in-memory `{ path: body }` map. `.dockerignore` is honored for directories. | | `{ image, registryAuth? }` | A registry reference such as `debian:bookworm-slim`. | | `{ snapshot }` | A provider snapshot id used as the base (providers whose templates *are* snapshots). | Each provider accepts a subset of these: check `client.capabilities.flags.templateSources`. Asking for an unsupported source throws `NotSupportedError` before any network call. ## Caching [#caching] The core computes a **content hash** over the Dockerfile, every context file, the image or snapshot ref, and the `env`/`workdir`/`user`/`startCmd`/`readyCmd`/`resources` fields. The adapter tags the built template with it, so: * a second `build()` or inline `create()` with the same inputs **does not rebuild**. It emits `{ type: "status", status: "cached" }` and returns the existing template. * concurrent creates in the same process share one build. * `{ force: true }` rebuilds anyway. `templateCacheKey(spec)` is exported if you want the hash yourself. ## Privacy [#privacy] Builds run **in your own provider account** (bring-your-own-key). sbox never pushes an image to a public registry. The `docker` adapter tags images locally only. ## Build events [#build-events] ```ts type TemplateBuildEvent = | { type: "status"; status: "cached" | "queued" | "building" | "ready" | "failed"; message?: string; } | { type: "log"; line: string; stream?: "stdout" | "stderr"; step?: string }; ``` ## Managing templates [#managing-templates] ```ts await client.templates!.get("desktop"); // TemplateRef | undefined (by id, alias or cache key) for await (const t of client.templates!.list()) console.log(t.id); await client.templates!.delete(ref); ``` `client.templates` is typed `undefined` on providers without the `templateBuild` capability. ## Templates vs snapshots [#templates-vs-snapshots] A template is the *build-time* base. [Snapshots](/api/snapshots) are *runtime* checkpoints of a live sandbox. To boot from a snapshot, use `client.create({ fromSnapshot: ref })`. --- # Terminals (PTY) (/general/terminals) Interactive pseudo-terminal sessions with resize, reconnect and exit codes. ```ts const term = await sandbox.pty!.create({ cols: 120, rows: 32, cwd: "/app" }); (async () => { for await (const chunk of term) process.stdout.write(chunk); // raw bytes, incl. ANSI })(); await term.write("htop\n"); await term.resize(160, 48); const { exitCode } = await term.wait(); ``` * `sandbox.pty` is typed `undefined` on providers without the `pty` capability. * `pty.connect(term.id)` reattaches to a running session where the provider supports detachable sessions. * `cmd` defaults to the provider's login shell. Use `commands.run()` for non-interactive commands: it keeps stdout and stderr separate and returns the exit code as data. ## Commands: stdin, timeouts, kill [#commands-stdin-timeouts-kill] ```ts await sandbox.commands.run("python -", { stdin: "print(1 + 1)" }); // works on every provider await sandbox.commands.run("make", { timeoutMs: 60_000 }); // rejects with SandboxError("Timeout") const h = sandbox.commands.run("npm run dev"); await h.kill(); ``` `stdin` as a string or bytes is supported everywhere. Where the provider has no native stdin, the core pipes it in through the shell. A `ReadableStream` is buffered first. --- # Usage (/general/usage) Construct a client, create a sandbox, and run the core namespaces — commands, files, code, ports, and lifecycle. ## Construct a client [#construct-a-client] `createSandboxClient()` is the single entry point. Pass a provider adapter, or call it with no arguments for the zero-config in-memory provider — great for tests. ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), }); const sandbox = await client.create({ template: "python-3.12", ttlMs: 60_000 }); ``` ```ts // Zero config — defaults to the in-memory provider: import { createSandboxClient } from "sbox-sdk"; const sandbox = await createSandboxClient().create(); await sandbox.commands.run("echo works offline"); ``` ## Run commands [#run-commands] `commands.run()` returns an `ExecHandle` that is both a `Promise` and an `AsyncIterable`. `await` it to buffer, or `for await` the same handle to stream. ```ts // Buffered — never throws on a non-zero exit; the exit code is data: const res = await sandbox.commands.run("npm test", { cwd: "/app" }); console.log(res.exitCode, res.stdout, res.stderr); // Streamed — the SAME handle, iterated live: for await (const ev of sandbox.commands.run(["python", "train.py"])) { if (ev.type === "stdout") process.stdout.write(ev.data); if (ev.type === "exit") console.log("done", ev.exitCode); } ``` See the [commands reference](/api/commands) for `spawn`, `connect`, `kill`, and `list`. ## Read and write files [#read-and-write-files] Filesystem bodies are web-standard (`string | Uint8Array | ReadableStream`) in, and a `StoredFile` out. ```ts await sandbox.files.write("/app/data.json", JSON.stringify({ ok: true })); const file = await sandbox.files.read("/app/data.json"); const text = await file.text(); await sandbox.files.mkdir("/app/out", { recursive: true }); const entries = await sandbox.files.list("/app"); const there = await sandbox.files.exists("/app/data.json"); ``` See the [files reference](/api/files) for the full method surface. ## Capability-gated namespaces [#capability-gated-namespaces] `code`, `ports`, `snapshots`, and `network` only exist on providers that support them — they're typed `undefined` otherwise, so guard before use. ```ts if (sandbox.code) { const exec = await sandbox.code.runCode("print(1 + 1)"); console.log(exec.logs.stdout); } if (sandbox.ports) { const preview = await sandbox.ports.expose(3000); console.log(preview.url); } ``` For dynamically-chosen providers, `sandbox.can("snapshot")` narrows at both runtime and the type level: ```ts if (sandbox.can("snapshot")) { await sandbox.snapshots.create({ name: "ckpt" }); } ``` ## Lifecycle and cleanup [#lifecycle-and-cleanup] ```ts await sandbox.pause(); await sandbox.resume(); await sandbox.setTimeout(120_000); await sandbox.destroy(); await client.dispose(); ``` Next: read the [capability model](/capabilities), the [error taxonomy](/errors), or the full [API reference](/api/client). --- # Writing a plugin (/plugins/authoring) Build a custom plugin with the SandboxPlugin interface — graft typed properties onto the sandbox, run setup on create, and clean up on destroy. ## The interface [#the-interface] A plugin is a plain object implementing `SandboxPlugin`, imported from `sbox-sdk`. Give it a `name`, then implement any of `extend`, `onCreate`, and `onDestroy`. ```ts import type { SandboxPlugin } from "sbox-sdk"; ``` ## A lifecycle plugin: seed every sandbox [#a-lifecycle-plugin-seed-every-sandbox] `onCreate` runs once the sandbox is built and is awaited before `create()` resolves — ideal for bootstrapping. This plugin writes a set of files into every sandbox: ```ts import type { SandboxPlugin } from "sbox-sdk"; export function seedFiles(files: Record): SandboxPlugin { return { name: "seed-files", kind: "lifecycle", onCreate: async (sandbox) => { for (const [path, content] of Object.entries(files)) { await sandbox.files.write(path, content); } }, }; } ``` ```ts const client = createSandboxClient({ provider: e2b(), plugins: [ seedFiles({ "/app/package.json": "{}", "/app/.env": "NODE_ENV=development", }), ], }); const sandbox = await client.create(); // both files already exist ``` ## An `extend` plugin: graft a typed property [#an-extend-plugin-graft-a-typed-property] `extend` returns properties merged onto the sandbox — synchronously, so they're available immediately. Type the contribution with the `Ext` parameter and it shows up on the sandbox type. This is exactly how the [AI-provider plugins](/ai/providers) add `sandbox.tools`: ```ts import type { SandboxPlugin } from "sbox-sdk"; function withMeta(meta: { project: string; }): SandboxPlugin<{ meta: typeof meta }> { return { name: "with-meta", extend: () => ({ meta }), }; } const client = createSandboxClient({ provider: e2b(), plugins: [withMeta({ project: "demo" })], }); const sandbox = await client.create(); sandbox.meta.project; // typed as string ``` ## Cleanup with `onDestroy` [#cleanup-with-ondestroy] `onDestroy` runs before the sandbox is torn down — flush logs, close connections, stop anything `onCreate` started: ```ts function auditLog(sink: (line: string) => void): SandboxPlugin { return { name: "audit-log", kind: "middleware", onCreate: (sandbox) => sink(`created ${sandbox.id}`), onDestroy: (sandbox) => sink(`destroyed ${sandbox.id}`), }; } ``` ## Notes [#notes] * **Hooks are optional** — a plugin can implement just one. `extend` is synchronous; `onCreate` / `onDestroy` may be async and are awaited. * **`kind` is a hint** — set it to the category your plugin fits. The client allows at most one `ai-provider` plugin; every other kind stacks freely. * **Plugins apply everywhere** — every sandbox from `create()`, `connect()`, and `fork()` runs your plugin's `extend`. * **Per-`create` options** — the second argument to `client.create(spec, options)` reaches your hooks as `ctx.createOptions`, so a plugin can read per-sandbox configuration. --- # Overview (/plugins/overview) Plugins extend every sandbox a client builds — graft properties onto the sandbox, hook its lifecycle, and add cross-cutting behavior. AI tool providers are the first plugin kind. ## What is a plugin? [#what-is-a-plugin] A plugin augments every sandbox a client builds. You pass plugins to `createSandboxClient`, and they apply to every sandbox from `create()` and `connect()` — including [forked](/api/snapshots) children. ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { aiSdk } from "sbox-sdk/ai-sdk"; const client = createSandboxClient({ provider: e2b({ apiKey: process.env.E2B_API_KEY! }), plugins: [ai({ framework: aiSdk() })], // an AI-provider plugin }); ``` The first plugin most people reach for is an **[AI-provider plugin](/ai/providers)**, which grafts a framework-shaped `sandbox.tools` onto the sandbox. But the plugin system is general — middleware, bootstrap, and integration plugins all use the same interface. ## The plugin interface [#the-plugin-interface] A plugin is a small object. Every hook is optional — implement only what you need: ```ts import type { SandboxPlugin } from "sbox-sdk"; interface SandboxPlugin { readonly name: string; /** Discriminant; the client allows at most one "ai-provider" plugin. */ readonly kind?: "ai-provider" | "middleware" | "lifecycle" | "mcp"; /** Synchronous: returns properties merged onto the sandbox object. */ extend?(sandbox: Sandbox, ctx: PluginSetupContext): Ext; /** Async side-effects, awaited after the sandbox is built. */ onCreate?( sandbox: Sandbox & Ext, ctx: PluginSetupContext ): void | Promise; /** Runs before the sandbox is destroyed. */ onDestroy?(sandbox: Sandbox): void | Promise; } ``` * **`extend`** grafts typed properties onto the sandbox — this is how the [`ai()`](/ai/providers) plugin adds `sandbox.tools`. It is synchronous, so the sandbox is ready to use the moment `create()` resolves. * **`onCreate`** runs async side-effects once the sandbox exists — seed files, install dependencies, start a dev server. * **`onDestroy`** runs cleanup before the sandbox is torn down — flush an audit log, stop a server. The properties a plugin contributes via `extend` are **typed**: pass `SandboxPlugin<{ tools: ... }>` and `sandbox.tools` shows up on the sandbox type, with no `any`. ## Plugin kinds [#plugin-kinds] The `kind` field groups plugins by what they do. Today the AI-provider kind ships; the others are reserved and on the roadmap — see the [catalog](/plugins/catalog). | Kind | Purpose | Status | | ------------- | ------------------------------------------------------ | --------- | | `ai-provider` | Shape `sandbox.tools` for an agent framework | Available | | `middleware` | Wrap tool / command calls — audit, redaction, metrics | Planned | | `lifecycle` | Bootstrap a sandbox on create — seed, install, warm up | Planned | | `mcp` | Expose the sandbox over the Model Context Protocol | Planned | The client enforces **at most one `ai-provider` plugin** (an agent runs in one framework, so `sandbox.tools` has one shape). Plugins of other kinds stack freely. ## Next steps [#next-steps] * [Catalog](/plugins/catalog) — every available plugin, and what's planned. * [Writing a plugin](/plugins/authoring) — build your own with the `SandboxPlugin` interface. * [AI providers](/ai/providers) — the first plugin kind, in depth. --- # Capability graph (/general/capabilities/graph) One static table per adapter drives compile-time gating, a runtime read-model, and fail-fast errors. Every capability, every provider — declared.

The artifact

One static table per adapter drives compile-time gating, a runtime read-model, and fail-fast errors. It's queryable in your code — and here it is in full. --- # Capabilities (/general/capabilities) Each provider declares a static capability table. It drives compile-time type gating, a runtime read-model, and fail-fast errors before any network call. The unified surface is the common shape every adapter implements, but providers differ at the edges: some have a code interpreter, some can pause, some expose ports natively, some only emulate it. sbox SDK makes that difference **declarative and queryable** instead of something you discover by catching an error. Each provider declares a static `CapabilityMap` — one of three levels per feature: * `native` — first-class support. * `emulated` — supported, but polyfilled by the core (e.g. exec-based filesystem ops). * `unsupported` — not available; the sub-API is typed `undefined` and throws before any network call. ## Three layers from one table [#three-layers-from-one-table] A single declaration drives all three of these: ### 1. Compile-time gating [#1-compile-time-gating] Sub-APIs gated on an `unsupported` capability are typed `undefined`. Calling them is a **compile error**, so whole classes of "this provider can't do that" never reach runtime. ```ts // `code` only exists on providers with a code interpreter (e.g. E2B): if (sandbox.code) { const exec = await sandbox.code.runCode("import numpy"); } ``` ### 2. Runtime read-model [#2-runtime-read-model] Every sandbox and client exposes a frozen `capabilities` read-model: ```ts sandbox.capabilities.map.snapshot; // "native" | "emulated" | "unsupported" sandbox.capabilities.flags.previewModel; // "subdomain" | "declaredPorts" | ... ``` ### 3. Fail-fast enforcement [#3-fail-fast-enforcement] Unsupported features throw `NotSupportedError` **synchronously, before any network call** — no wasted round trip, no ambiguous provider error. ## Dynamic narrowing with `can()` [#dynamic-narrowing-with-can] For code that picks a provider at runtime, `sandbox.can(cap)` is a type guard that narrows at both the runtime and type level: ```ts if (sandbox.can("snapshot")) { // `sandbox.snapshots` is now non-undefined here. await sandbox.snapshots.create({ name: "ckpt" }); } ``` ## The capability map [#the-capability-map] The static table covers 25 capabilities across lifecycle, exec, filesystem, code, network, and snapshots: | Group | Capabilities | | -------------- | ---------------------------------------------------------------------- | | **lifecycle** | `list`, `stop`, `pause`, `setTimeout` | | **exec** | `background`, `streaming`, `killProcess`, `pty`, `stdin` | | **filesystem** | `filesWatch`, `filesUpload` | | **code** | `codeInterpreter`, `statefulKernel` | | **network** | `exposePort`, `privatePreview`, `egressControl`, `ssh`, `proxiedFetch` | | **snapshot** | `snapshot`, `fork`, `volumes` | | **meta** | `gpu`, `region`, `secretsVault`, `metrics` | ## Behavioral flags [#behavioral-flags] Some differences aren't present/absent — they change semantics. These are `capabilities.flags`: | Flag | Meaning | | ------------------------ | --------------------------------------------------------------------------------------- | | `preservesMemoryOnPause` | RAM survives a pause | | `preservesDiskOnStop` | Disk survives a stop | | `perCommandEnvCwd` | If `false`, the core wraps exec in `sh -c 'cd … && KEY=v …'` | | `exitCodeNative` | If `false`, the core synthesizes the exit code via a `$?` echo | | `previewModel` | How exposed-port URLs are formed (`subdomain`, `declaredPorts`, `wildcardDNS`, `ip`, …) | ## Per-provider matrix [#per-provider-matrix] For the full `native` / `emulated` / `unsupported` breakdown across every adapter, see the interactive [capability graph](/general/capabilities/graph) — or each adapter's **Capabilities** section: [memory](/adapters/memory), [E2B](/adapters/e2b), [Vercel](/adapters/vercel), [Cloudflare](/adapters/cloudflare), [Daytona](/adapters/daytona), [Modal](/adapters/modal), [Fly](/adapters/fly), [AWS Lambda](/adapters/aws-lambda), [Northflank](/adapters/northflank), [Runloop](/adapters/runloop), [CodeSandbox](/adapters/codesandbox), [Morph](/adapters/morph), [Blaxel](/adapters/blaxel), [Beam](/adapters/beam), [Railway](/adapters/railway). --- # Catalog (/plugins/catalog) Every plugin that ships with sbox SDK, and what's on the roadmap. AI tool providers are available today; middleware, lifecycle, and MCP plugins are next. ## Available [#available] ### AI providers [#ai-providers] The first plugin kind. The single [`ai()`](/ai/providers) plugin grafts a framework-shaped `sandbox.tools` onto the sandbox; you pick the framework by passing its adapter. See the **AI** group in the sidebar for each framework, or [AI providers](/ai/providers) for the shared behavior. | Framework | Adapter | Import | `sandbox.tools` | | ----------------------------------- | ---------------- | -------------------- | --------------- | | [Vercel AI SDK](/ai/ai-sdk) | `aiSdk()` | `sbox-sdk/ai-sdk` | tool map | | [Mastra](/ai/mastra) | `mastra()` | `sbox-sdk/mastra` | tool map | | [OpenAI Agents](/ai/openai) | `openaiAgents()` | `sbox-sdk/openai` | tool array | | [Anthropic / Claude](/ai/anthropic) | `anthropic()` | `sbox-sdk/anthropic` | runnable tools | | [LangChain](/ai/langchain) | `langchain()` | `sbox-sdk/langchain` | tool array | ```ts import { createSandboxClient } from "sbox-sdk"; import { e2b } from "sbox-sdk/e2b"; import { ai } from "sbox-sdk/ai"; import { aiSdk } from "sbox-sdk/ai-sdk"; const client = createSandboxClient({ provider: e2b(), plugins: [ai({ framework: aiSdk() })], }); ``` ## Coming soon [#coming-soon] The plugin interface reserves these kinds. They aren't shipped yet — they're where the system is headed, and you can build any of them today with [a custom plugin](/plugins/authoring). | Plugin | Kind | What it will do | | ----------------------------------------- | ------------ | ---------------------------------------------------------------------- | | [Middleware](/plugins/catalog/middleware) | `middleware` | Wrap tool and command calls — audit, redaction, metrics. | | [Lifecycle](/plugins/catalog/lifecycle) | `lifecycle` | Bootstrap a sandbox on `create()` — seed files, install deps, warm up. | | [MCP server](/plugins/catalog/mcp) | `mcp` | Expose the sandbox's tools over the Model Context Protocol. | Have a plugin idea? [Open an issue](https://github.com/vivek-k3/sbox-sdk/issues), or write it yourself — the interface is small and stable. --- # Lifecycle (coming soon) (/plugins/catalog/lifecycle) Lifecycle plugins will bootstrap a sandbox on create — seed files, install dependencies, warm a dev server. Planned — build your own today. Planned — not shipped yet. Lifecycle plugins (`kind: "lifecycle"`) will bootstrap each sandbox when it's created — seed files, install dependencies, or warm up a dev server, so the sandbox is ready the moment `create()` resolves. The plugin interface already supports this via the `onCreate` hook, so you can build one today — see [Writing a plugin](/plugins/authoring), which includes a `seedFiles` example. --- # MCP server (coming soon) (/plugins/catalog/mcp) An MCP plugin will expose the sandbox's tools over the Model Context Protocol for any MCP client. Planned. Planned — not shipped yet. An MCP plugin (`kind: "mcp"`) will expose the sandbox's [tools](/ai/tools) over the [Model Context Protocol](https://modelcontextprotocol.io), so any MCP client — Claude Desktop, Cursor, VS Code — can drive the sandbox. Because the tools come from the same provider-neutral registry the AI providers use, the MCP server projects from exactly the same source. Until it ships, you can reach the tools directly with [`createSandboxTools(sandbox)`](/ai/tools). --- # Middleware (coming soon) (/plugins/catalog/middleware) Middleware plugins will wrap tool and command calls for audit, redaction, and metrics. Planned — build your own today. Planned — not shipped yet. Middleware plugins (`kind: "middleware"`) will wrap tool and command calls to add cross-cutting behavior without touching the tools themselves: * **Audit** — record every call, with its [approval decision](/ai/approval), to your logger or store. * **Redaction** — strip secrets from tool inputs and outputs before they reach the model. * **Metrics** — emit timing and usage counters per tool. You can build any of these today — see [Writing a plugin](/plugins/authoring).