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.0Baseten 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
| Capability | Level | Notes |
|---|---|---|
streaming / background | native | NDJSON execStream, stderr kept separate |
killProcess | native | SIGTERM and SIGKILL by process name |
stdin | native | native stdin endpoints on every started process |
list | native | cursor-paginated, filtered after the fetch |
setTimeout | native | replaces the max-age with a DATE policy, keeps the idle policy |
filesUpload / filesWatch | native | readBytes / writeBytes (multipart over 5 MiB) and fs.watch |
exposePort / privatePreview | native | public previews, or private ones with a preview_token query parameter |
region | native | spec.region or the region option |
templateBuild | native | Dockerfile or registry image, built in your team's account |
volumes | native | regional volumes, one mount per sandbox |
metrics | native | CURRENT mode of the management API |
stop / pause | unsupported | standby is automatic; there is no explicit stop or pause |
snapshot / fork | unsupported | |
pty / ssh | unsupported | |
gpu / secretsVault | unsupported | |
egressControl / proxiedFetch | unsupported | the HTTP proxy can be bypassed, so it cannot enforce the egress policy |
codeInterpreter / statefulKernel | unsupported |
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 andcreate()always sends one: yourname, orsbox-<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 back409is resolved through asbox-idempotency-keylabel: the same key returns the existing sandbox, a different request keeps theConflict. The label shows up insandbox.metadata.vcpusisapproximate. 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.vcpusalone picks that memory size, and any other value throwsValidation.memoryMB,idleTimeoutMsandmaxAgeMsareexact. Memory is passed through (1024 to 262144 MB). Timeouts becomeTTL_IDLEandTTL_MAX_AGEexpiration policies with the exact millisecond value. Expiration always deletes the sandbox.diskMB,shmMBandgpuarerejected. 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. sizesmap 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, andxlargehas twice the default ladder's memory because Baseten has no 8 vCPU / 16 GB tier.
How the spec maps
| sbox | Baseten |
|---|---|
template / templateRef | image (default baseten/base-image:latest) |
name / idempotencyKey | name (sbox-<hash> when unnamed) plus a sbox-idempotency-key label |
env | envs with secret: false |
secrets with an inline value | envs with secret: true (masked on read) |
metadata | labels |
resources.vcpus / memoryMB | memory (CPU follows from the documented size table) |
region | region |
lifecycle.maxAgeMs | TTL_MAX_AGE expiration policy, action DELETE |
lifecycle.idleTimeoutMs | TTL_IDLE expiration policy, action DELETE |
volumes | volumes (at most one) |
ports | ports with protocol HTTP |
fromSnapshot, network other than allow-all, named or egress secrets, onIdle: "pause" or "stop", autoResume: false | throw Validation |
Known limitations
- Expiration only deletes.
setTimeout(ms)sets deletion relative to now and preserves idle expiry.idleTimeoutMsdeletes the sandbox even whenonIdleis not set. Explicit pause/stop-on-idle andautoResume: falseare 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 reportcreating. CheckgetInfo()before the first command.- Live cloud execution, preview WebSockets and resource/account limits require real account validation. The offline suite includes
live: trueMiniShell 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.