Sandboxes
Create and control Firecracker-isolated sandboxes, lifecycle, exec, files, authenticated port exposures, and automatic stop/archive policies.
A sandbox is an isolated Linux machine you drive over the Sandal API. The virtual-machine kind (the default) is its own Firecracker microVM with its own kernel and its own disk; no kernel is shared with other tenants. A lighter container kind is also offered: sandal create --runtime sandbox-linux, createSandbox({ kind: "container" }) in TypeScript, or the Container choice in the Console's create dialog. Sandal runs them on bare metal in the EU (Germany, Finland, Luxembourg); there is no region choice.
How the API is shaped#
There are no sandbox handle objects. Every call is sandal.<namespace>.<verb>(sandboxId, input):
- Every mutation takes an explicit
idempotencyKey. Retrying with the same key and body returns the original result instead of acting twice. - Exec, file, port and snapshot calls take
expectedSandboxRevision; lifecycle verbs (start, stop, archive, recover, fork, delete) takeexpectedRevision. Read the current value with(await sandal.sandboxes.get(id)).revision. - Mutations return
{ sandbox, operation }. Wait for the operation withsandal.sandboxes.waitForOperation(operation.id, { timeoutMs }).
States#
| State | Meaning |
|---|---|
creating | Booting from its template |
running | Live; exec, files and ports work |
paused | Memory-preserving pause (see note below) |
stopped | Machine shut down, disk kept; start boots it again |
archived | Moved to cold storage, compute released; recover brings it back |
failed | Something went wrong; recover can bring it back |
deleted | Gone; on the default template its /workspace volume is crypto-erased (its key destroyed), the rest of its disk on the host is wiped (blocks zeroed before reuse) and its snapshots are deleted. Persistent volumes are kept unless you erase them. Irreversible. |
Create a sandbox#
Omit the template to use the project default (a Debian VM, profile enter-agent-linux, with Python 3, Node.js, git and agent tooling): it never goes stale. A pinned template id stops working when that version is retired; sandal templates list shows the current ids and sandal templates alias list the aliases.
Sizes: xs 1 vCPU / 1 GiB / 10 GiB disk, s 2 / 4 / 20, m 4 / 8 / 40, l 8 / 16 / 80, xl 16 / 32 / 160.
import { randomUUID } from "node:crypto";
import { Sandal } from "@sandal-dev/sdk";
const sandal = new Sandal({
baseUrl: process.env.SANDAL_API_URL ?? "https://api.sandal.dev",
apiToken: process.env.SANDAL_API_KEY!,
// organizationId and projectId are optional: the key alone is enough.
organizationId: process.env.SANDAL_ORGANIZATION_ID!,
projectId: process.env.SANDAL_PROJECT_ID!,
});
const { sandbox, operation } = await sandal.sandboxes.create({
idempotencyKey: randomUUID(),
kind: "virtual-machine",
profile: "enter-agent-linux",
templateId: "<template-id>",
templateDigest: "sha256:cea120929a1542e07611f7fcb6cc9f2ef70aa2a2f26a563997441d2c0cbda4fa",
size: "s",
architecture: "amd64",
name: "my-sandbox",
lifecycle: { expiresAt: new Date(Date.now() + 60 * 60_000) },
});
await sandal.sandboxes.waitForOperation(operation.id, { timeoutMs: 300_000 });
console.log(sandbox.id);Create takes about 1.5-3.6 s end to end at size s (median about 2 s), served from a warm pool. Size m and larger have no warm pool and boot cold in 12-16 s, longer under load (measured on production from an EU client, November 2026). The first create in a brand-new project can take a few seconds longer.
Lifecycle#
Every lifecycle verb has the same shape: current revision in, operation out.
const lifecycle = async (action: "stop" | "start" | "archive" | "recover" | "delete", id: string) => {
const { revision } = await sandal.sandboxes.get(id);
const { operation } = await sandal.sandboxes[action](id, {
idempotencyKey: randomUUID(),
expectedRevision: revision,
});
await sandal.sandboxes.waitForOperation(operation.id, { timeoutMs: 300_000 });
};
await lifecycle("stop", sandbox.id); // disk kept, ~4-5 s
await lifecycle("start", sandbox.id); // ~7-9 s
await lifecycle("archive", sandbox.id); // needs a running sandbox, ~13-16 s
await lifecycle("recover", sandbox.id); // back to running, files intact, ~6-9 s
await lifecycle("delete", sandbox.id); // irreversible, ~12-25 sarchive requires a running sandbox; calling it on a stopped one returns 409 conflict with reason invalid_state. See Snapshots & forks for createSnapshot and fork.
Running commands#
processes.execAndWait submits the command and waits server-side (up to 20 s) for it to finish. Output arrives as base64 chunks in events; if the process is still running, resume with processes.streamEvents. The exit code is on the process record.
const decode = (e: { dataBase64: string }) => Buffer.from(e.dataBase64, "base64").toString("utf8");
const { revision } = await sandal.sandboxes.get(sandbox.id);
const run = await sandal.processes.execAndWait(sandbox.id, {
idempotencyKey: randomUUID(),
command: ["sh", "-c", "for i in 1 2 3; do echo tick $i; sleep 1; done; exit 3"],
expectedSandboxRevision: revision,
});
run.events.forEach((e) => process.stdout.write(decode(e)));
if (!run.terminal) {
for await (const e of sandal.processes.streamEvents(sandbox.id, run.process.id, {
afterSequence: run.nextSequence,
timeoutMs: 120_000,
})) {
process.stdout.write(decode(e));
}
}
const finished = await sandal.processes.get(sandbox.id, run.process.id);
console.log("exit", finished.exitCode); // 3 (can be null for a moment after the stream ends; poll briefly)command is an argv array, not a shell string; wrap it in sh -c when you need shell features. For an interactive terminal, use the CLI: sandal shell <sandbox> opens a PTY shell.
Exec latency for repeated commands on one held SDK handle, on the direct exec path: about 125 ms median on the default Linux template and about 50 ms on the default container image, which offers sandal.exec.v2 (one stream per handle, each command a channel of it); measured from Helsinki on November 29, 2026. Over the API path about 250 ms, and and about 0.4 s for a single sandal exec from the CLI (a new process per call, on the API path unless you pass --direct-exec). The first exec on a fresh sandbox takes about 0.3-1.4 s. The SDKs use the direct path whenever the sandbox's image offers it, which the default Linux template and the default container image do, and fall back to the API path by themselves; since 0.1.0-beta.13 a handle you get later (by id, or from a create that did not wait) finds the direct path on its first command.
Commands run as uid 2000 without sudo on the default template. sandal exec --root, TypeScript exec(cmd, { user: "root" }), Python exec(cmd, user="root") and Go SandalCommandOptions{User: "root"} run as root only on a template that allows it; the default template refuses them with 422 capability_unavailable (CLI exit code 7; the message names tenant-root-v1). A preview template with root and FUSE exists; see Root and FUSE (preview).
API-path execs are kept as process records (history: the last 8 commands, 8 KiB per line). Commands run over the direct exec path are not in a tenant-readable audit log.
Files#
Write and read files directly. Payloads are base64. Transfer through the files API runs at roughly 50-100 KB/s today, so keep files small and fetch large data from inside the sandbox (git clone, curl).
const { revision } = await sandal.sandboxes.get(sandbox.id);
await sandal.files.write(sandbox.id, {
idempotencyKey: randomUUID(),
path: "/workspace/config.json",
offset: 0,
truncate: true,
createParents: true,
dataBase64: Buffer.from(JSON.stringify({ port: 8080 })).toString("base64"),
expectedSandboxRevision: revision,
});
const read = await sandal.files.download(sandbox.id, "/workspace/config.json", { offset: 0, limit: 65_536 });
console.log(Buffer.from(read.dataBase64, "base64").toString("utf8"));
const listing = await sandal.files.list(sandbox.id, "/workspace");
console.log(listing.entries);files also has stat, mkdir, move, delete, search, grep and replace; the CLI mirrors them (sandal files ls|stat|cat|rm|mkdir|mv, sandal upload, sandal download).
For large files the SDKs can mint a signed upload or download URL (TypeScript files.createUploadUrl / createDownloadUrl, Python create_upload_url / create_download_url, Go CreateUploadURL / CreateDownloadURL). A URL lives 60 s to 24 h (expiresInSeconds, default 15 min); the SDKs refuse anything longer before sending, and the API refuses an expired or longer-lived token at use. A deployment may switch signed transfers off: the URL call then answers 422 capability_unavailable (feature file_transfer) with the server's reason, and the upload/download helpers and the CLI fall back to the chunked file API by themselves, so sandal upload and sandal download keep working, but slowly: with signed transfers off, a 24 MiB file took about 8 min up and 3.5 min down on production (21 November 2026). With signed transfers on (the beta deployment since 21 November 2026, 18:40 UTC) the same file takes about 5 s up and 3 s down.
Expose a port#
exposePort gives a process listening inside the sandbox an HTTPS URL. The URL is private by default: every request needs Authorization: Bearer <API key> or a short-lived access token, so it is for your own tooling and agents, not a public link. To share a preview with someone who has no key, create a share link: sandal share <sandbox> <port> [--ttl 1h] [--single-use] (also sandal share ls|revoke|token). A share link lives 24 h at most, can be single-use, and answers 410 once revoked; a revoke does not end a session that is already open (up to 1 h). Custom domains for previews are not available.
// start a server in the background first
const before = await sandal.sandboxes.get(sandbox.id);
await sandal.processes.execAndWait(sandbox.id, {
idempotencyKey: randomUUID(),
command: ["sh", "-c", "cd /workspace && (setsid nohup python3 -m http.server 8080 >/tmp/http.log 2>&1 &); sleep 1"],
expectedSandboxRevision: before.revision,
});
const { revision } = await sandal.sandboxes.get(sandbox.id);
const admitted = await sandal.sandboxes.exposePort(sandbox.id, {
idempotencyKey: randomUUID(),
expectedSandboxRevision: revision,
port: 8080,
protocol: "http",
ttlSeconds: 600,
});
let exposure = admitted.exposure;
while (exposure.state !== "ready") {
if (exposure.state === "failed" || exposure.state === "revoked") throw new Error(exposure.state);
await new Promise((r) => setTimeout(r, 500));
exposure = await sandal.sandboxes.getPortExposure(sandbox.id, exposure.id);
}
// https://api.sandal.dev/v1/sandbox-ports/<route>
const res = await fetch(`${exposure.url}/config.json`, {
headers: { authorization: `Bearer ${process.env.SANDAL_API_KEY}` },
});
console.log(res.status, await res.text());The first request through a new exposure can take a few seconds; later ones are around 0.5 s. Revoke an exposure early with sandboxes.revokePortExposure; otherwise it expires after ttlSeconds.
Lifecycle policy: expiry and automatic stop#
lifecycle.expiresAt is required at create. Optional fields control what happens to an idle sandbox:
| Field | Effect |
|---|---|
autoStopAfterSeconds | Stop after this long idle (no API, process, file, preview or SSH activity) |
autoArchiveAfterSeconds | Archive after it has been stopped this long |
autoDeleteAfterSeconds | Delete after it has been archived (or stopped, when auto-archive is off) this long |
Omitted values inherit the project default; 0 disables one regardless of defaults. Change a running sandbox's policy with sandboxes.updateLifecyclePolicy, and hold an idle sandbox up with sandboxes.keepAlive(id, { idempotencyKey, durationSeconds }) (up to 24 h). The CLI equivalents are sandal lifecycle get|set|defaults and sandal keep-alive.
Footguns:
- Know what counts as idle.
sandal lifecycle get <sandbox>shows the policy and the idle evidence the server sees. If a sandbox must stay up unattended, callkeepAliverather than assuming a background process keeps it alive. - Auto-delete deletes. If your project default sets
autoDeleteAfterSeconds, an idle sandbox is eventually removed with its disk. Checksandal lifecycle defaultsbefore relying on a sandbox as storage.
Network policy#
Pass networkPolicy at create to block internet egress:
networkPolicy: { allowInternet: false }With allowInternet: false, DNS and outbound connections from inside the sandbox fail (verified: curl https://example.com returns Could not resolve host). egress and ingress rule lists are also accepted. The default is allow. Egress rules allow or deny by domain or CIDR (DNS filtering; there is no SNI check), and a change on a running sandbox is enforced in about 3 s. Outbound IPv6 is not available (link-local only). Create with a network policy takes longer (around 21-26 s measured). See Egress.
Secrets#
Secrets reach a sandbox as environment variables. Brokered secrets (preview) keep HTTP(S) credentials outside the sandbox and inject them only into HTTPS requests to the hosts you allow, once the sandbox's secretBrokering state is active, usually within about 10-25 seconds of the sandbox becoming running (until then requests carry the placeholder). From 0.1.0-beta.13 the CLI and SDKs wait for that when they create the sandbox (at most 60 s). See Secrets.
Templates#
Use the catalog templates above. Custom template builds and template aliases exist in the API but are not yet available on the beta deployment. A template with root and FUSE is in preview, not the default: see Root and FUSE (preview).