TypeScript SDK
@sandal-dev/sdk (private beta): configuration from the environment, a Sandbox handle and command/file/push/job helpers, plus the low-level client for every endpoint.
Install#
Private beta: the package is not on npm yet. Install the tarball from your beta bundle:
npm install ./sdk/sandal-typescript-v0.1.0-beta.16.tgzCreate the client#
import { Sandal } from "@sandal-dev/sdk";
const sandal = new Sandal(); // SANDAL_API_KEY alone is enough (org and project come from the key), else the `sandal login` profile
// or explicitly:
const explicit = new Sandal({
baseUrl: "https://api.sandal.dev",
apiToken: process.env.SANDAL_API_KEY!,
// organizationId and projectId are optional overrides:
organizationId: process.env.SANDAL_ORGANIZATION_ID!,
projectId: process.env.SANDAL_PROJECT_ID!,
});One client is bound to one organization and project. Keep the API key on the server; never ship it to a browser. Sandal.fromEnv({ profile, retries, userAgent }) takes options.
Reuse one client for the life of your program. On Node.js the built-in fetch drops an idle connection after about 4 s, so the first request after a longer pause pays a new TLS handshake; pass a keep-alive fetchApi (for example undici's fetch with new Agent({ keepAliveTimeout: 30_000 }), see the SDK's USAGE.md) if that matters: far from the region a new connection costs one or two extra round trips of 0.25-0.5 s each. Idle pooled connections never keep a finished script alive. sandal.close() releases idle direct-exec streams (only opened with directExecPrewarm: true); a finished Node script exits on its own either way.
The short way#
const sb = await sandal.createSandbox({ size: "s" }); // default template, waits until running
try {
const { exitCode, stdout } = await sb.exec("echo hi && uname -a");
await sb.writeText("/workspace/notes.txt", "done\n");
await sb.push("./app"); // git-aware copy to /workspace/app
} finally {
await sb.delete();
}The handle, exec / streamCommand / runCommand, files of any size, push, runJob, expose / share, lifetime, usage, saved snapshots and history are documented once for all three languages on the SDK pages (TypeScript, Python, Go). The rest of this page is the low-level client: one method per endpoint, used by the helpers underneath.
Conventions#
- Idempotency. Every mutation accepts an
idempotencyKey. It is optional: the SDK generates one and its retries reuse it. Pass your own when a retry from your code must not repeat work. - Revisions. Exec, files, ports and snapshots accept
expectedSandboxRevision; lifecycle calls (start, stop, pause, resume, archive, recover, delete, fork) acceptexpectedRevision. Both are optional: the SDK reads the current one and retries once onrevision_conflict. The examples below pass them explicitly to show the wire contract. - Retries. 429, 502, 503, 504 and network failures are retried with backoff and jitter, honouring
Retry-After, with the same idempotency key.retries: falseturns it off. - Operations. Create, lifecycle and fork return
{ sandbox, operation }as soon as the request is admitted. Wait withsandal.sandboxes.waitForOperation(operation.id, { timeoutMs }); it throwsSandalOperationFailedErrorif the operation fails (for examplesandbox_create.quota_exceeded). - Errors. API failures throw
SandalApiErrorwithstatus,code,reason,requestIdandretryable;describeSandalError(error)classifies any failure. See Limits.
import { randomUUID } from "node:crypto";
const key = () => randomUUID();
const revision = async (id: string) => (await sandal.sandboxes.get(id)).revision;Templates#
const template = await sandal.builds.templates.getPublished("<template-id>");
// { templateId, templateDigest: "sha256:…", profile: "enter-agent-linux", architecture: "amd64", … }Template ids change when a template is rebuilt: sandal templates list shows the current ones, and omitting the template (the project default) never goes stale. Catalog ids are retired when the image is respun: a retired id answers 404 resource_not_found (“was retired… omit the template to use the project default”). Omit the template to always get the project's default; the templateId of any sandbox you create names the current one.
Sandboxes#
Create#
const { sandbox, operation } = await sandal.sandboxes.create({
idempotencyKey: key(),
kind: "virtual-machine",
profile: "enter-agent-linux",
templateId: "<template-id>",
templateDigest: "sha256:f311884c8be75a75ada50405624aefff53ebc6611590b7cf9275fe16dc0dee6b",
size: "s", // xs | s | m | l | xl
architecture: "amd64",
name: "agent-1",
lifecycle: { expiresAt: new Date(Date.now() + 60 * 60_000) }, // required hard expiry
networkPolicy: { allowInternet: false }, // optional: block internet egress
});
await sandal.sandboxes.waitForOperation(operation.id, { timeoutMs: 300_000 });Create takes about 1.5-3.6 s until running at size s (warm pool, median about 2 s); size m and larger boot cold in 12-16 s. size is a shortcut for resources; sizes are xs (1 vCPU, 1 GiB, 10 GiB disk), s (2, 4, 20), m (4, 8, 40), l (8, 16, 80) and xl (16, 32, 160).
Read and list#
const current = await sandal.sandboxes.get(sandbox.id);
console.log(current.state, current.revision, current.resources.vcpus, current.resources.memoryMiB);
const page = await sandal.sandboxes.list({ limit: 50 });Lifecycle#
const lifecycle = async (action: "stop" | "start" | "archive" | "recover" | "delete", id: string) => {
const { operation } = await sandal.sandboxes[action](id, {
idempotencyKey: key(),
expectedRevision: await revision(id),
});
await sandal.sandboxes.waitForOperation(operation.id, { timeoutMs: 300_000 });
};
await lifecycle("stop", sandbox.id); // keeps the disk (~3.5 s)
await lifecycle("start", sandbox.id); // (~6.5 s)
await lifecycle("archive", sandbox.id); // cold storage; 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); // deletes the sandbox and wipes its diskpause / resume keep memory on the same host. Automatic policies (autoStopAfterSeconds, autoArchiveAfterSeconds, autoDeleteAfterSeconds) can be set in lifecycle at create time, and read or changed later with sandboxes.getLifecyclePolicy / sandboxes.updateLifecyclePolicy. sandboxes.keepAlive restarts the idle clock.
Processes#
processes.execAndWait starts a command and waits server-side (up to about 20 s) for it to finish, returning the output events so far. Continue a longer process with processes.streamEvents.
const text = (event: { dataBase64: string }) => Buffer.from(event.dataBase64, "base64").toString("utf8");
const started = await sandal.processes.execAndWait(sandbox.id, {
idempotencyKey: key(),
command: ["sh", "-c", "for i in 1 2 3; do echo tick $i; sleep 1; done; exit 3"],
expectedSandboxRevision: await revision(sandbox.id),
});
started.events.forEach((event) => process.stdout.write(text(event)));
if (!started.terminal) {
for await (const event of sandal.processes.streamEvents(sandbox.id, started.process.id, {
afterSequence: started.nextSequence,
timeoutMs: 120_000,
})) process.stdout.write(text(event));
}
const finished = await sandal.processes.get(sandbox.id, started.process.id);
console.log(finished.exitCode); // 3 (can be null for a moment after the last event; poll get() briefly)processes.exec submits without waiting. processes.cancel, processes.signal, processes.writeInput and processes.resizePty manage a running process. A process keeps at most maxOutputBytes of output (16 MiB by default, up to 64 MiB); sandbox.exec(...) rejects with SandalCommandOutputLimitError (its result holds the output so far) when a command passes it.
On a held handle, repeated sb.exec(...) calls take on the direct exec path about 125 ms median on the default Linux template and about 50 ms on the default container image (from Helsinki, November 29, 2026), and about 250 ms over the API path (one EU vantage point, November 2026). The SDK uses the direct path whenever the sandbox's image offers it (the default Linux template and the default container image do) and falls back to the API by itself. Since 0.1.0-beta.16 a handle keeps one direct-exec stream and runs each command as a channel of it (sandal.exec.v2, on by default), so only the first command pays the connection setup; turn it off with directExecMulti: false or SANDAL_DIRECT_EXEC_MULTI=0 (also false, off, no). Where a host or image does not offer it (the default Linux template answers with v1 today), each command opens its own connection as before; a handle you get later (by id, or from a create that did not wait) finds the direct path on its first command. sb.exec(cmd, { user: "root" }) runs as root on templates that allow it (always over the API path); the default template refuses it with 422 capability_unavailable. See Root and FUSE (preview).
Files#
await sandal.files.write(sandbox.id, {
idempotencyKey: key(),
path: "/workspace/hello.txt",
offset: 0,
truncate: true,
createParents: true,
dataBase64: Buffer.from("hello sandal\n").toString("base64"),
expectedSandboxRevision: await revision(sandbox.id),
});
const file = await sandal.files.download(sandbox.id, "/workspace/hello.txt", { offset: 0, limit: 65_536 });
console.log(Buffer.from(file.dataBase64, "base64").toString("utf8"));
const listing = await sandal.files.list(sandbox.id, "/workspace");
const info = await sandal.files.stat(sandbox.id, "/workspace/hello.txt");Writes are chunked: one request carries at most 256 KiB. Large transfers use signed transfer URLs (24 MiB in about 5 s up and 3 s down); where those are switched off the SDK falls back to the much slower chunked API.
Ports#
await sandal.processes.exec(sandbox.id, {
idempotencyKey: key(),
command: ["sh", "-c", "cd /workspace && (setsid nohup python3 -m http.server 8080 >/tmp/http.log 2>&1 &); sleep 1"],
expectedSandboxRevision: await revision(sandbox.id),
});
let { exposure } = await sandal.sandboxes.exposePort(sandbox.id, {
idempotencyKey: key(),
expectedSandboxRevision: await revision(sandbox.id),
port: 8080,
protocol: "http",
ttlSeconds: 600,
});
while (exposure.state !== "ready") {
await new Promise((resolve) => setTimeout(resolve, 500));
exposure = await sandal.sandboxes.getPortExposure(sandbox.id, exposure.id);
}
const response = await fetch(`${exposure.url}/hello.txt`, {
headers: { authorization: `Bearer ${process.env.SANDAL_API_KEY}` },
});The exposure URL is authenticated: requests need Authorization: Bearer <API key>, so share it with sb.share(port) / sb.ports.shareLink(exposure.id) (see Share links). Revoke early with sandboxes.revokePortExposure.
Snapshots and forks#
let { snapshot } = await sandal.sandboxes.createSnapshot(sandbox.id, {
idempotencyKey: key(),
expectedSandboxRevision: await revision(sandbox.id),
});
while (snapshot.state !== "ready") {
await new Promise((resolve) => setTimeout(resolve, 500));
snapshot = await sandal.sandboxes.getSnapshot(sandbox.id, snapshot.id);
}
const fork = await sandal.sandboxes.fork(sandbox.id, {
idempotencyKey: key(),
expectedRevision: await revision(sandbox.id),
name: "agent-1-fork",
lifecycle: { expiresAt: new Date(Date.now() + 60 * 60_000) },
});
await sandal.sandboxes.waitForOperation(fork.operation.id, { timeoutMs: 300_000 });
// fork.sandbox.id is a new, independent sandbox with a copy-on-write copy of the disk.sandboxes.listSnapshots(id) lists a sandbox's snapshots. See Snapshots and forks.
Code interpreter#
On projects where sandal capabilities lists code-interpreter, code.runAndWait runs Python, JavaScript or TypeScript in a stateful context inside the sandbox and returns Jupyter-style results:
const outcome = await sandal.code.runAndWait(sandbox.id, {
idempotencyKey: key(),
language: "python",
code: "import math\nprint('hi')\nmath.sqrt(2)",
onEvent: (event) => event.type === "stdout" && process.stdout.write(event.text ?? ""),
});
console.log(outcome.mainResult?.data["text/plain"]); // "1.4142135623730951"Variables and imports persist between runs of the same context. See Code interpreter.
Not yet available on the beta#
The SDK contains clients for a few parts of the API that the beta deployment does not offer yet: file watch, volume snapshots and telemetry export answer capability_unavailable today, the Xcode builds client has no Mac hosts behind it yet, and the macOSSandboxes client needs a Mac leased to your organisation. Auto-pause (autoResume), bring-your-own egress, browser sessions and template builds are enabled per project during the beta. The current state per feature is on Limits; sandal capabilities shows what your project can do.
Every namespace: sandboxes, processes, files, git, agents, code, languageServers, computer, browsers (createAndConnect, waitForConnection), devices, builds, runnerPools, macOSSandboxes, events.webhooks, telemetry, keys, audit, usage; sandal.raw.* is the generated low-level client.