Baseten

Hosted microVMs with streamed commands, native binary files, private previews, image builds and regional persistent volumes.

Installation

Use Node 22 or newer. The experimental provider SDK is pinned exactly; importing this adapter or reading capabilities does not load it.

pnpm add sbox-sdk @basetenlabs/sandbox@0.5.0

Baseten recommends undici for its own default transport: 7.19+ on Node 22/24, or 8.x on Node 26+. This adapter passes the sbox client's fetch into the SDK, so undici is optional and its automatic loader is bypassed. You can supply an HTTP/2 or proxy-aware fetch through createSandboxClient({ fetch }).

Authentication

Pass apiKey from BASETEN_API_KEY. Accounts belonging to multiple teams also need teamId, conventionally BASETEN_TEAM_ID. The SDK exchanges the account API key for a sandbox access token. Runtime requests use that token; preview tokens are separate credentials.

Optional factory settings are image, region, baseUrl, and previewTokenTtlMs. The CLI/live suite reads BASETEN_IMAGE, BASETEN_REGION, and BASETEN_BASE_URL. Factory options do not read environment variables themselves. client.verify() authenticates the first list page with page size 1 and never creates a sandbox.

Usage

import { createSandboxClient } from "sbox-sdk";
import { baseten } from "sbox-sdk/baseten";

const client = createSandboxClient({
  provider: baseten({
    apiKey: process.env.BASETEN_API_KEY!,
    teamId: process.env.BASETEN_TEAM_ID,
  }),
});
const sandbox = await client.getOrCreate({
  name: "agent-project",
  env: { PROJECT: "demo" },
  metadata: { project: "demo" },
  resources: { memoryMB: 4096, vcpus: 2 },
  lifecycle: { maxAgeMs: 3_600_000, idleTimeoutMs: 600_000, onIdle: "destroy" },
});
try {
  for await (const event of sandbox.commands.run(
    "printf hello; printf warning >&2",
    {
      cwd: "/tmp",
      env: { TASK: "build" },
      timeoutMs: 30_000,
    }
  )) {
    if (event.type === "stdout") process.stdout.write(event.data);
    if (event.type === "stderr") process.stderr.write(event.data);
  }
  await sandbox.files.write("/tmp/binary.dat", new Uint8Array([0, 255, 128]));
} finally {
  await sandbox.destroy();
}

The default image is baseten/base-image:latest. SDK creation returns a deployment record; a new sandbox can still report creating while deploying. Runtime calls need a DEPLOYED sandbox. Use getInfo() to inspect live status. Automatic standby still reports running; the next runtime request wakes it with files and processes preserved.

Unnamed creates derive a deterministic name from the core retry key and use native create-if-absent. getOrCreate() uses the same native operation for explicit names and preserves an existing sandbox's configuration. Deletion calls the control plane DELETE API, which finishes asynchronously.

Commands and files

Exec uses native NDJSON streaming, keeping stdout and stderr separate and reporting the process exit code. timeoutMs is passed through in milliseconds; the provider rounds up to whole seconds, and the core has its own timeout backstop. Native cwd/env and writable stdin are supported. spawn(), process listing and termination work by process name. Only SIGTERM and SIGKILL are accepted; per-command users are rejected. The core pipes buffered stdin into the shell; interactive handles use the SDK's native stdin endpoints.

Files use readBytes/writeBytes; the SDK uploads files over 5 MiB in multipart chunks. Upload/download accept binary content, while downloads are buffered. Directory listing/removal and file watching use the SDK. Rename/stat use the core's shell polyfills. Native mkdir creates parents even when recursive creation wasn't requested.

Previews

Start the application yourself, binding to the sandbox's HOST environment variable. Then expose its port:

await sandbox.commands.spawn('python3 -m http.server 3000 --bind "$HOST"');
const preview = await sandbox.ports!.expose(3000, { visibility: "private" });
// preview.auth = { type: "query", param: "preview_token", token: "..." }
const url = new URL(preview.url);
if (preview.auth?.type === "query") {
  url.searchParams.set(preview.auth.param, preview.auth.token);
}
console.log(url.toString());

Private previews use preview_token in the query string and support browser navigation through the provider's cookie exchange. The core derives a wss: URL, but private browser WebSocket handshakes have not been verified. previewBrowserAuth stays false until that behavior is confirmed. Tokens expire after 1 hour by default. Listing private previews may create/reuse a token. Treat token-bearing URLs as credentials. Default expose() visibility is public, as in the core API; request private visibility explicitly. Re-exposing an existing adapter preview updates its access setting. Port 80 is reserved; port 443 must be private.

Image builds

Images build in your team's account. No public registry push is performed.

const image = await client.templates!.build({
  source: {
    dockerfile: `FROM baseten/base-image:latest
RUN mkdir -p /workspace
WORKDIR /workspace`,
  },
});
const sandboxFromImage = await client.create({ template: image });

Dockerfiles are passed intact, including multistage instructions and build context. They must preserve the sandbox API server as the entrypoint; starting from Baseten's image keeps that setup. For { source: { image: "python:3.12-slim" } }, the SDK ImageBuilder adds the sandbox API and entrypoint. Image sources accept template env, workdir, and user; put these directly in Dockerfiles for Dockerfile sources. Registry credentials, template resource defaults, startCmd, readyCmd, and snapshot sources are rejected.

Image records have no caller labels. Repository names combine an 8-character alias prefix and 40 characters of the cache hash. Lookup by full cache key or returned repository ID works across client instances. Use the returned reference for lookup; the original human alias is not a persistent lookup key. Build events report building/ready status; the SDK push method does not stream build logs. Build logs remain available through the provider SDK's image client and the Baseten dashboard.

Volumes and metrics

const volume = await client.volumes!.create({
  name: "project-data",
  sizeMB: 1024,
  region: "us-pdx-1",
});
const sandboxWithVolume = await client.create({
  region: volume.region,
  volumes: [{ id: volume.id, mountPath: "/data" }],
});
console.log(await sandboxWithVolume.metrics());
await sandboxWithVolume.destroy();
// Wait for asynchronous deletion/unmount to finish before deleting the volume.
await client.volumes!.delete(volume);

Volumes are regional, persist after sandbox deletion, and support at most one mount in one sandbox at a time. Metrics use the SDK's generated management client with CURRENT mode. Memory bytes become MiB; CPU percent is normalized against the documented memory/CPU size table when known. Missing samples stay undefined and the original metric response is retained in raw.

Options

Prop

Type

Capabilities

CapabilityLevelNotes
streaming / backgroundnativeNDJSON execStream, stderr kept separate
killProcessnativeSIGTERM and SIGKILL by process name
stdinnativenative stdin endpoints on every started process
listnativecursor-paginated, filtered after the fetch
setTimeoutnativereplaces the max-age with a DATE policy, keeps the idle policy
filesUpload / filesWatchnativereadBytes / writeBytes (multipart over 5 MiB) and fs.watch
exposePort / privatePreviewnativepublic previews, or private ones with a preview_token query parameter
regionnativespec.region or the region option
templateBuildnativeDockerfile or registry image, built in your team's account
volumesnativeregional volumes, one mount per sandbox
metricsnativeCURRENT mode of the management API
stop / pauseunsupportedstandby is automatic; there is no explicit stop or pause
snapshot / forkunsupported
pty / sshunsupported
gpu / secretsVaultunsupported
egressControl / proxiedFetchunsupportedthe HTTP proxy can be bypassed, so it cannot enforce the egress policy
codeInterpreter / statefulKernelunsupported

perCommandEnvCwd and exitCodeNative are true. previewBrowserAuth is false until private browser WebSockets are confirmed. Automatic standby still reports running, and a runtime call wakes the sandbox with files and processes preserved.

Create contract

  • idempotency: "exact". Sandbox names are unique per team and create() always sends one: your name, or sbox-<hash of the idempotency key> when unnamed. An unnamed create uses native create-if-absent, so a retried or racing request gets the same sandbox. A named create that comes back 409 is resolved through a sbox-idempotency-key label: the same key returns the existing sandbox, a different request keeps the Conflict. The label shows up in sandbox.metadata.
  • vcpus is approximate. CPU is tied to memory, so only the documented pairs are accepted: 1 vCPU / 2048 MB, 2 / 4096, 4 / 8192, 6 / 16384, 8 / 32768, 16 / 65536 and 32 / 131072. vcpus alone picks that memory size, and any other value throws Validation.
  • memoryMB, idleTimeoutMs and maxAgeMs are exact. Memory is passed through (1024 to 262144 MB). Timeouts become TTL_IDLE and TTL_MAX_AGE expiration policies with the exact millisecond value. Expiration always deletes the sandbox.
  • diskMB, shmMB and gpu are rejected. SDK 0.5.0 has no create field for them.
  • No limits. The SDK documents no port, label or timeout limits. The one-volume cap and the reserved ports (80, and 443 for private previews only) are enforced by Baseten rather than declared.
  • sizes map onto memory tiers. size: "small" is 1 vCPU / 2 GB, "medium" 2 / 4 GB, "large" 4 / 8 GB and "xlarge" 8 vCPU / 32 GB. The presets carry no disk size, because Baseten has none, and xlarge has twice the default ladder's memory because Baseten has no 8 vCPU / 16 GB tier.

How the spec maps

sboxBaseten
template / templateRefimage (default baseten/base-image:latest)
name / idempotencyKeyname (sbox-<hash> when unnamed) plus a sbox-idempotency-key label
envenvs with secret: false
secrets with an inline valueenvs with secret: true (masked on read)
metadatalabels
resources.vcpus / memoryMBmemory (CPU follows from the documented size table)
regionregion
lifecycle.maxAgeMsTTL_MAX_AGE expiration policy, action DELETE
lifecycle.idleTimeoutMsTTL_IDLE expiration policy, action DELETE
volumesvolumes (at most one)
portsports with protocol HTTP
fromSnapshot, network other than allow-all, named or egress secrets, onIdle: "pause" or "stop", autoResume: falsethrow Validation

Known limitations

  • Expiration only deletes. setTimeout(ms) sets deletion relative to now and preserves idle expiry. idleTimeoutMs deletes the sandbox even when onIdle is not set. Explicit pause/stop-on-idle and autoResume: false are rejected.
  • CPU allocation is tied to memory in SDK 0.5.0. Custom CPU exists in newer REST docs but is absent from this SDK's published types.
  • Environment secrets require inline values and are marked secret. Named vault and egress secrets are rejected.
  • Restrictive network policies are rejected. Baseten's HTTP proxy bypasses private addresses and can be bypassed by clients. Use the raw SDK explicitly if proxy-specific behavior is acceptable.
  • create() returns as soon as Baseten accepts the request, so a new sandbox can still report creating. Check getInfo() before the first command.
  • Live cloud execution, preview WebSockets and resource/account limits require real account validation. The offline suite includes live: true MiniShell conformance and real published SDK transport probes; it does not substitute for a paid live run.

See the official lifecycle, configuration, previews, and image documentation.

On this page