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
modal (≥ 0.11) is an optional peer dependency of sbox-sdk, loaded lazily on first use.
pnpm add sbox-sdk modalAuthentication
A token id + secret (or Modal's standard environment).
| Option | Env var | Required | Description |
|---|---|---|---|
tokenId | MODAL_TOKEN_ID | required | Modal token id. |
tokenSecret | MODAL_TOKEN_SECRET | required | Modal token secret. |
environment | MODAL_ENVIRONMENT | optional | Modal environment name. |
appName | — | optional | App to attach sandboxes to (created if missing). Defaults to "sbox-sdk". |
image | — | optional | Default container image when a spec omits `template`. |
Credentials fall back to the standard Modal environment (MODAL_TOKEN_ID / MODAL_TOKEN_SECRET) when the options are omitted.
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
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
Prop
Type
Templates (image builds)
client.templates.build() builds a Modal Image in your workspace and publishes it privately (allowPublic: false) as sbox-<first 16 hex of the cache key>, plus your name when you set one. That way lookup(cacheKey) finds it again and unchanged specs aren't rebuilt.
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 singleFROMasimages.fromRegistry(base)and passes the remaining instructions todockerfileCommands().env/workdir/userbecomeENV/WORKDIR/USER. - Not supported:
COPYorADDfrom build context (the JS SDK can't upload context;ADD <url>andCOPY --from=are fine), multi-stage builds, andARGbeforeFROM. These throwValidation.startCmdandreadyCmddon't apply (sandboxes run their own command) and are ignored with a log line. - Other sources:
image(withregistryAuth→ aREGISTRY_USERNAME/REGISTRY_PASSWORDsecret) andsnapshot(a Modal image id fromsnapshots.create()). - Modal's builder doesn't stream logs through the JS SDK, so
onEventgets status events plus one log line per instruction.
Previews and browser auth
- Ports listed in
spec.portsare 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.previewBrowserAuthistrue. Your server receives the verifiedX-Verified-User-Dataheader.
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
- Egress:
block-all→blockNetwork.allow-list→outboundCidrAllowlist+outboundDomainAllowlist(a dimension you leave empty gets[]). At runtime,setEgressPolicycallsupdateNetworkPolicy(allow-all=["0.0.0.0/0"]/["*"]). Deny rules aren't supported. - Header injection (
network.inject) becomes Modal'sExperimentalOutboundPolicy. For aSecretRefheader,nameis the Modal Secret, andenvVar(defaultname) is the key inside it. The adapter writes the header value as$<key>, 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
SecretRefwithout avalue→secrets.fromName. With a value →secrets.fromObject. Both are injected as env vars. - Volumes:
client.volumeswrapsvolumes.fromName/delete, andlistpages through the control-planevolumeList.spec.volumesmounts by name orvo-id.readOnlyuseswithMountOptions({ readOnly: true }).
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
kill()needs/proc,grepandcutin the image (any normal Linux image). The core's timeout backstop still applies.resources.diskMBandshmMBhave no Modal equivalent and are ignored.- Memory snapshots (
mode: "memory") need Modal's experimental snapshot flag at create time and aren't offered. renameuses the core'smvpolyfill (the Modal filesystem API has no move).
Vercel Sandbox
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.
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.