# Sandal documentation (full) Generated from https://sandal.dev/docs. Index: https://sandal.dev/llms.txt --- # Introduction > Sandboxes, Full VMs, browsers, desktops and GitHub Actions runners for AI agents and code, from one CLI, one SDK and one Console. Windows VMs, Windows and arm64 runners and Android devices in preview. Source: https://sandal.dev/docs ## What Sandal is Sandal is the execution layer for AI agents. Every time your code (or your agent) needs to *run something*, a shell command, a test suite, a browser, an untrusted snippet of Python from an LLM, it needs somewhere safe to run it. That's Sandal. Under the hood, every sandbox is its own [Firecracker or Cloud Hypervisor microVM](https://sandal.dev/docs/architecture) with its own kernel, on bare-metal hosts we operate. Stopped sandboxes cost no compute. Rates are on the [pricing page](https://sandal.dev/pricing). ## What works today - [Sandboxes](/docs/sandboxes): Linux microVMs for agent code: exec, files, preview URLs, pause/resume, stop/start, snapshots and forks. Size s runs in about 2 s from a warm pool; commands on a held SDK handle take about 155-175 ms. - [Full VMs](/docs/full-vms): A complete Linux VM (Cloud Hypervisor, systemd, cloud-init) in about 15-19 s. - [Browsers and desktops](/docs/browsers): Remote Chrome or Lightpanda over CDP (ready in 6-12 s; enabled per project in the beta) and Linux desktops for computer use (about 17-22 s). - [GitHub Actions runners](/docs/runners): Linux x64 runners via one runs-on label (sandal-ubuntu-24.04). Windows Server and Linux arm64 are in preview. - [Secrets](/docs/secrets): Project secrets by reference: as an environment value, or brokered (preview) so the sandbox only ever sees a placeholder. In preview, enabled per project: [Windows VMs](https://sandal.dev/docs/windows-vms) with RDP through `sandal rdp`, Windows and arm64 [runners](https://sandal.dev/docs/runners), [Android devices](https://sandal.dev/docs/simulators), and a [root + FUSE sandbox template](https://sandal.dev/docs/root-and-fuse). Available on request: [iOS Simulators](https://sandal.dev/docs/simulators) (iOS 27.2, iPhone 17, eu-central; small capacity during the beta), and macOS VMs (macOS 27.2 with Xcode 27.0) on a Mac leased to your organisation alone, in eu-central, where you build and test for macOS ([ask us](mailto:hello@sandal.dev?subject=Sandal%20macOS%20VMs)). Not available yet: macOS runners, iOS Simulator tests inside a macOS VM, and the Xcode builds API. ## Try it The [quickstart](https://sandal.dev/docs/quickstart) gets you from one API key to a running sandbox, a command and a link anyone can open, in the CLI, TypeScript, Python or Go. Sandal is in **private beta**: the CLI and SDKs are not on npm, PyPI or the Go proxy yet. [Request access](mailto:hello@sandal.dev?subject=Sandal%20beta%20access) and we send you the install bundle. > **Do not install “sandal” from a public registry:** > `npm install sandal`, `npx sandal …` and `pip install sandal` install unrelated third-party packages. Only install the beta files we send you. ```bash export SANDAL_API_KEY=... # Console → API Keys: the only setting sandal create # the project's default template, size s sandal exec -- python3 -c "print('hello from', __import__('platform').node())" # runs in `current` sandal delete current --yes ``` ## Where to go next - [Quickstart](https://sandal.dev/docs/quickstart): install, one API key, your first sandbox and share link - [Give Sandal to your coding agent](https://sandal.dev/docs/agents): one page an agent can follow, plus [`/llms.txt`](https://sandal.dev/llms.txt) and [`/llms-full.txt`](https://sandal.dev/llms-full.txt) - [Integrations](https://sandal.dev/docs/integrations): OpenAI Agents SDK, Claude Agent SDK, LangChain, Vercel AI SDK - [Migrate from E2B, Daytona or Modal](https://sandal.dev/docs/migrate-from-e2b) - [Sandboxes](https://sandal.dev/docs/sandboxes): exec, files, ports, lifecycle, fork - [Architecture](https://sandal.dev/docs/architecture): how the microVMs, snapshots and metering work - [Pricing](https://sandal.dev/docs/pricing): how usage is metered (rates live on [/pricing](https://sandal.dev/pricing)) --- # Quickstart > One environment variable, five commands: a running sandbox, a command, and a link anyone can open. Then the same from TypeScript, Python and Go. Source: https://sandal.dev/docs/quickstart ## 1. Install Sandal is in **private beta**. The CLI and SDKs are not on npm, PyPI or the Go proxy yet: [request access](mailto:hello@sandal.dev?subject=Sandal%20beta%20access) and we send you an install bundle (`0.1.0-beta.16`) and add you to an organization with a project. > **Do not install “sandal” from a public registry:** > `npm install sandal`, `npx sandal …` and `pip install sandal` install **unrelated third-party packages**. Only install the files from your bundle. From the bundle's CLI folder, install the binary for your platform (one file, no runtime needed) and turn on the shell integration: ```bash mkdir -p ~/.local/bin install -m 755 sandal-darwin-arm64 ~/.local/bin/sandal # Intel Mac: sandal-darwin-x64, Linux: sandal-linux-x64 or sandal-linux-arm64 export PATH="$HOME/.local/bin:$PATH" eval "$(sandal shell-init zsh)" # bash: sandal shell-init bash sandal --version # 0.1.0-beta.16 ``` ## 2. One variable: your API key Create a key in **Console → API Keys** and export it. That is the only setting: the CLI and every SDK find the key's organization and project themselves. ```bash export SANDAL_API_KEY=... # from Console → API Keys ``` On your own machine you can sign in with the browser instead: `sandal login` (confirm the code, pick a project; `sandal logout` removes the session). `sandal whoami` shows what you are using. `SANDAL_ORGANIZATION_ID` and `SANDAL_PROJECT_ID` still work as overrides, for a key that can see more than one project. ## 3. Five commands to a link anyone can open ```bash sandal create # running in about 2 s sandal exec -- python3 -c "print('hello from', __import__('platform').node())" sandal exec --detach -- python3 -m http.server 8000 # a web server in the background sandal share current 8000 # prints a link: open it in your browser sandal delete current --yes ``` - `sandal create` uses your project's default template and size `s` (2 vCPU, 4 GiB, 20 GiB disk). No template id needed; `--size m`, `--name`, `--desktop` and `--runtime general-linux-vm` (a Full VM) are optional. - `current` is the last sandbox you created in this shell (the shell integration from step 1). Without it, pass the id that `sandal create` printed. - `exec` streams the output and exits with the remote exit code. `--detach` prints a process id for `sandal exec logs|wait|kill`. - `sandal share` exposes the port and prints a share link that anyone can open for one hour, without an API key. `--ttl 30m` (1 min to 24 h) and `--single-use` change that; see [Share links](https://sandal.dev/docs/sharing). - Outside a terminal (scripts, `| jq`), every command prints JSON, and `delete` needs `--yes`. ## 4. The same from TypeScript ```bash npm install ./sandal-typescript-v0.1.0-beta.16.tgz # from your bundle's SDK folder; Node.js 20+ ``` ```ts title="quickstart.mjs" import { Sandal } from "@sandal-dev/sdk"; const sandal = new Sandal(); // reads SANDAL_API_KEY (or the `sandal login` profile) const sb = await sandal.createSandbox(); // waits until it is running: default template, size s try { const result = await sb.exec("python3 -c 'print(2 + 2)'"); console.log(result.exitCode, result.stdout.trim()); // 0 4 await sb.startCommand("python3 -m http.server 8000"); const { url } = await sb.share(8000); // a link anyone can open for 1 hour console.log("open", url); await new Promise((resolve) => setTimeout(resolve, 60_000)); // one minute to look at it } finally { await sb.delete(); } ``` Run it with `node quickstart.mjs`. ## 5. The same from Python ```bash python3 -m venv .venv && . .venv/bin/activate pip install ./sandal_sdk-0.1.0b16-py3-none-any.whl # from your bundle's SDK folder; Python 3.11+ ``` ```python title="quickstart.py" import asyncio from sandal import Sandal async def main() -> None: sandal = Sandal() # reads SANDAL_API_KEY (or the `sandal login` profile) try: async with await sandal.create_sandbox() as sb: # deleted when the block ends result = await sb.exec("python3 -c 'print(2 + 2)'") print(result.exit_code, result.stdout.strip()) # 0 4 await sb.start_command("python3 -m http.server 8000") link = await sb.share(8000) print("open", link.url, flush=True) await asyncio.sleep(60) # one minute to look at it finally: await sandal.close() asyncio.run(main()) ``` A blocking client with the same methods is `SandalSync`. ## 6. The same from Go ```bash tar xzf sandal-go-v0.1.0-beta.16.tar.gz # from your bundle's SDK folder; Go 1.23+ go mod edit -require=sandal.dev/go@v0.0.0 -replace=sandal.dev/go=./sandal-go-v0.1.0-beta.16 go mod tidy ``` ```go title="main.go" package main import ( "context" "fmt" "log" "strings" "time" sandal "sandal.dev/go" ) func main() { ctx := context.Background() client, err := sandal.NewSandalFromEnv(sandal.SandalEnvOptions{}) // reads SANDAL_API_KEY if err != nil { log.Fatal(err) } sb, err := client.CreateSandbox(ctx, sandal.SandalCreateSandboxOptions{}) // default template, size s if err != nil { log.Fatal(err) } defer sb.Delete(ctx, sandal.SandalLifecycleOptions{}) result, err := sb.Exec(ctx, []string{"python3", "-c", "print(2 + 2)"}, nil) if err != nil { log.Fatal(err) } fmt.Println(result.Status, strings.TrimSpace(result.Stdout)) // 0 4 if _, err := sb.StartCommand(ctx, []string{"python3", "-m", "http.server", "8000"}, nil); err != nil { log.Fatal(err) } shared, err := sb.Share(ctx, 8000, sandal.SandalExposeOptions{}) // a link anyone can open for 1 hour if err != nil { log.Fatal(err) } fmt.Println("open", shared.URL) time.Sleep(time.Minute) // one minute to look at it } ``` Run it with `go run .`. > **Verified:** > Every command and program on this page was run as written against production on November 29, 2026, with the `0.1.0-beta.16` clients and only `SANDAL_API_KEY` set (only the one-minute wait shortened): TypeScript, Python and Go each printed `0 4`, and the share link opened (HTTP 200 in a client that keeps cookies, like a browser). The CLI commands were run the same day. ## What to expect Measured on the production deployment in November 2026, from one client in Europe (Helsinki). SDK commands use the direct exec path where the sandbox's image offers it (the default Linux template and the default container image do) and the API otherwise; a one-shot `sandal exec` uses the API path: | Step | Typical | | --- | --- | | `create` (Linux sandbox, size `s`, warm pool) | about 1.5-3.5 s | | `create --size m` and larger (no warm pool yet) | 12-16 s | | `create --runtime general-linux-vm` (Full VM) | 15-19 s | | `create --desktop` (Linux desktop) | 17-22 s | | First command on a fresh sandbox | about 0.3-1.4 s | | Later commands on one SDK handle | about 125 ms median (about 50 ms on the default container image) | | One `sandal exec` from the CLI (a new process each time) | about 0.4-0.6 s | | `sandal share` | about 1-2 s | | `delete` | about 1 s | A create that has to wait says why (`queued`, `waiting_for_capacity`, `waiting_for_quota`, `provisioning`) on stderr, or as `pendingReason` in JSON and in the SDKs' `onProgress` / `on_progress`. ## Next steps - [Sandboxes](https://sandal.dev/docs/sandboxes): files, terminals, lifecycle, snapshots and forks - [Secrets](https://sandal.dev/docs/secrets): keep API keys out of the sandbox - [Give Sandal to your coding agent](https://sandal.dev/docs/agents) and the [integrations](https://sandal.dev/docs/integrations) - [CLI reference](https://sandal.dev/docs/cli), [TypeScript SDK](https://sandal.dev/docs/sdk-typescript), [Python SDK](https://sandal.dev/docs/sdk-python), [Go SDK](https://sandal.dev/docs/sdk-go) - [Limits](https://sandal.dev/docs/limits): `sandal limits --all` shows your quota --- # Give Sandal to your coding agent > One page a coding agent (Claude Code, Codex, Cursor) can follow to create Sandal sandboxes, run code in them, open previews and clean up. Also served as /SKILL.md. Source: https://sandal.dev/docs/agents Paste this into your agent, or point it at [`https://sandal.dev/SKILL.md`](https://sandal.dev/SKILL.md). The whole docs set for agents is [`/llms.txt`](https://sandal.dev/llms.txt) (index) and [`/llms-full.txt`](https://sandal.dev/llms-full.txt) (every page). ```text Use Sandal (https://sandal.dev/SKILL.md) to run code in isolated cloud sandboxes. ``` ## Rules for the agent 1. Check the CLI first: `sandal status --check` (exit 1 = not signed in). `SANDAL_API_KEY` in the environment is enough to be signed in. If the CLI is missing or not signed in, stop and ask the user; never install a package called `sandal` from npm or PyPI (those are unrelated projects). 2. Create without a template: `sandal create --name ` uses the project's default template, size `s` (2 vCPU, 4 GiB). Use `--size m|l` for heavy builds, `--runtime general-linux-vm` for a full VM with systemd, `--desktop` for computer use. 3. Read JSON, not text: when stdout is not a terminal every command prints JSON (JSON Lines for `create`; take `.id` from the line whose `event` is `ready`). 4. Run commands with `sandal exec -- ` (one string with shell syntax runs through `/bin/sh -lc`). The exit code is the remote one. For servers and long jobs use `--detach`, then `sandal exec logs --follow` or `sandal exec wait `. 5. Move files with `sandal push ` (git-aware, lands in `/workspace/`) or `sandal upload` / `sandal download`; `sandal files cat ` prints one file. 6. Previews: `sandal share ` prints a link a human can open without a key (1 hour by default, `--ttl` up to 24 h, `--single-use`). `sandal ports expose ` gives a private `url` that needs the API key as a bearer token. 7. Always clean up: `sandal delete --yes`. Stop instead (`sandal stop `) only when the user wants the disk kept; stopped sandboxes cost no compute. 8. Errors are typed: exit 2 usage, 3 auth, 4 not found, 5 conflict, 6 quota, 7 unavailable (`--fail-fast` makes create answer at once when no host is free), 8 timeout. The message names the reason and often a hint; report it to the user instead of retrying blindly. ## Minimal session ```bash id=$(sandal create --name agent-task --json | jq -r 'select(.event=="ready") | .id') sandal push "$id" ./repo sandal exec "$id" -- bash -lc 'cd /workspace/repo && npm ci && npm test' sandal delete "$id" --yes ``` ## What is not available today Say so instead of trying: root or `sudo` on the default template (`sandal exec --root` answers `capability_unavailable`, exit 7; a [root + FUSE template](https://sandal.dev/docs/root-and-fuse) is in preview), FUSE / S3 mounts on the default template, outbound IPv6, memory snapshots, volume snapshots, OpenTelemetry export, a per-sandbox network log. In preview only (enabled per project): Windows and Linux arm64 runners, Windows VMs, Android devices, brokered secrets. Not available yet: macOS runners, iOS Simulator tests inside a macOS VM, the Xcode builds API. iOS Simulators exist as their own product (`sandal devices ios …`; private beta, on request) with small capacity, so check `sandal devices capabilities` first. macOS VMs exist, but only on a Mac leased to the organisation, so do not create one unless the user asks for it. ## From code instead of the CLI The TypeScript (`@sandal-dev/sdk`), Python (`sandal-sdk`, import `sandal`) and Go (`sandal.dev/go`) SDKs read `SANDAL_API_KEY` and have the same verbs: `createSandbox()` / `create_sandbox()`, `exec`, `startCommand` / `start_command`, `writeText` / `write_text`, `expose`, `share`, `delete`. See the [quickstart](https://sandal.dev/docs/quickstart) and the [integrations](https://sandal.dev/docs/integrations) for agent frameworks. The MCP server `sandal-mcp` (part of the CLI) runs locally over stdio: [MCP server](https://sandal.dev/docs/mcp). --- # Sandboxes > Create and control Firecracker-isolated sandboxes, lifecycle, exec, files, authenticated port exposures, and automatic stop/archive policies. Source: https://sandal.dev/docs/sandboxes 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. > **Private beta:** > The SDKs and CLI are in private beta and not yet published to npm/PyPI/Go. Request access (hello@sandal.dev) and we send you the packages. Setup and credentials are in the [Quickstart](https://sandal.dev/docs/quickstart). ## How the API is shaped There are no sandbox handle objects. Every call is `sandal..(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) take `expectedRevision`. Read the current value with `(await sandal.sandboxes.get(id)).revision`. - Mutations return `{ sandbox, operation }`. Wait for the operation with `sandal.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. | > **Pause and resume:** > `pause`/`resume` freeze and continue memory and running processes on the same sandbox (pause about 0.7-1 s, resume about 1-2.5 s on production). `stop`/`start` keep the disk only: a started sandbox boots from disk, and running processes are gone. There are no memory snapshots. `archive`/`recover` keep only the disk snapshot. For idle sandboxes see [Auto-stop and auto-pause](https://sandal.dev/docs/auto-pause). ## 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. **TypeScript** ```ts 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: "", 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); ``` **Python** ```python import asyncio, os, uuid from datetime import datetime, timedelta, timezone from sandal import Sandal, SandboxTarget from sandal.models.sandbox_cpu_architecture import SandboxCpuArchitecture from sandal.models.sandbox_lifecycle_policy_input import SandboxLifecyclePolicyInput from sandal.models.sandbox_size import SandboxSize TEMPLATE = "" DIGEST = "sha256:cea120929a1542e07611f7fcb6cc9f2ef70aa2a2f26a563997441d2c0cbda4fa" async def main(): sandal = Sandal(SandboxTarget( base_url=os.environ.get("SANDAL_API_URL", "https://api.sandal.dev"), api_token=os.environ["SANDAL_API_KEY"], # organization_id and project_id are optional: the key alone is enough. organization_id=os.environ["SANDAL_ORGANIZATION_ID"], project_id=os.environ["SANDAL_PROJECT_ID"], )) try: admitted = await sandal.sandboxes.create( idempotency_key=str(uuid.uuid4()), kind="virtual-machine", template_id=TEMPLATE, template_digest=DIGEST, size=SandboxSize("s"), architecture=SandboxCpuArchitecture("amd64"), name="my-sandbox", lifecycle=SandboxLifecyclePolicyInput( expires_at=datetime.now(timezone.utc) + timedelta(hours=1) ), ) await sandal.sandboxes.wait_for_operation(admitted.operation.id, timeout_seconds=300) print(admitted.sandbox.id) finally: await sandal.close() asyncio.run(main()) ``` **Go** ```go // import sandal "sandal.dev/go" client, err := sandal.NewSandal(sandal.Target{ BaseURL: "https://api.sandal.dev", APIToken: os.Getenv("SANDAL_API_KEY"), // OrganizationID and ProjectID are optional: the key alone is enough. OrganizationID: os.Getenv("SANDAL_ORGANIZATION_ID"), ProjectID: os.Getenv("SANDAL_PROJECT_ID"), }) if err != nil { return err } size := sandal.SandboxSize("s") architecture := sandal.SANDBOXCPUARCHITECTURE_AMD64 name := "my-sandbox" admitted, _, err := client.Sandboxes.Create(ctx, sandal.SandalSandboxCreateInput{ Kind: sandal.SANDBOXKIND_VIRTUAL_MACHINE, TemplateID: "", TemplateDigest: "sha256:cea120929a1542e07611f7fcb6cc9f2ef70aa2a2f26a563997441d2c0cbda4fa", Size: &size, Architecture: &architecture, Name: &name, Lifecycle: *sandal.NewSandboxLifecyclePolicyInput(time.Now().Add(time.Hour)), Identity: sandal.SandalMutationIdentity{IdempotencyKey: "create-my-sandbox-1"}, }) if err != nil { return err } _, _, err = client.Sandboxes.WaitForOperation(ctx, admitted.Operation.Id, sandal.SandalOperationWaitOptions{Timeout: 5 * time.Minute, PollInterval: 500 * time.Millisecond}) ``` 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. > **Template digests:** > A catalog template has the same digest in every project (the container template has kind `container` and needs no `profile` in the SDKs). Once a project has created from a template, `sandal.builds.templates.getPublished(templateId)` returns its `{ templateDigest, profile, architecture }`; in a brand-new project it can answer `404 resource_not_found` until that first create, so passing the digest explicitly always works. ## Lifecycle Every lifecycle verb has the same shape: current revision in, operation out. **TypeScript** ```ts 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 s ``` **Python** ```python async def lifecycle(action: str, sandbox_id: str): current = await sandal.sandboxes.get(sandbox_id) admitted = await getattr(sandal.sandboxes, action)( sandbox_id, expected_revision=current.revision, idempotency_key=str(uuid.uuid4()) ) await sandal.sandboxes.wait_for_operation(admitted.operation.id, timeout_seconds=300) await lifecycle("stop", sandbox_id) await lifecycle("start", sandbox_id) await lifecycle("archive", sandbox_id) # needs a running sandbox await lifecycle("recover", sandbox_id) await lifecycle("delete", sandbox_id) ``` `archive` requires a running sandbox; calling it on a stopped one returns `409 conflict` with reason `invalid_state`. See [Snapshots & forks](https://sandal.dev/docs/snapshots-and-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. **TypeScript** ```ts 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) ``` **Python** ```python import base64 current = await sandal.sandboxes.get(sandbox_id) admitted = await sandal.processes.exec( sandbox_id, command=["sh", "-c", "for i in 1 2 3; do echo tick $i; sleep 1; done; exit 3"], expected_sandbox_revision=current.revision, idempotency_key=str(uuid.uuid4()), ) async for event in sandal.processes.stream_events(sandbox_id, admitted.process.id, timeout_ms=120_000): print(base64.b64decode(event.data_base64).decode("utf-8", "replace"), end="") process = await sandal.processes.get(sandbox_id, admitted.process.id) print("exit", process.exit_code) # can be None for a moment; 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 ` 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)](https://sandal.dev/docs/root-and-fuse). 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`). **TypeScript** ```ts 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); ``` **Python** ```python current = await sandal.sandboxes.get(sandbox_id) await sandal.files.write( sandbox_id, path="/workspace/config.json", data_base64=base64.b64encode(b'{"port": 8080}').decode(), offset=0, truncate=True, create_parents=True, expected_sandbox_revision=current.revision, idempotency_key=str(uuid.uuid4()), ) read = await sandal.files.download(sandbox_id, "/workspace/config.json", offset=0, limit=65_536) print(base64.b64decode(read.data_base64).decode()) listing = await sandal.files.list(sandbox_id, "/workspace") print(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 ` 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 [--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. **TypeScript** ```ts // 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/ const res = await fetch(`${exposure.url}/config.json`, { headers: { authorization: `Bearer ${process.env.SANDAL_API_KEY}` }, }); console.log(res.status, await res.text()); ``` **Python** ```python import httpx current = await sandal.sandboxes.get(sandbox_id) admitted = await sandal.sandboxes.expose_port( sandbox_id, expected_sandbox_revision=current.revision, port=8080, protocol="http", ttl_seconds=600, idempotency_key=str(uuid.uuid4()), ) exposure = admitted.exposure while exposure.state.value != "ready": await asyncio.sleep(0.5) exposure = await sandal.sandboxes.get_port_exposure(sandbox_id, exposure.id) async with httpx.AsyncClient(timeout=30) as http: res = await http.get(f"{exposure.url}/config.json", headers={"authorization": f"Bearer {os.environ['SANDAL_API_KEY']}"}) print(res.status_code, 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 ` shows the policy and the idle evidence the server sees. If a sandbox must stay up unattended, call `keepAlive` rather 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. Check `sandal lifecycle defaults` before relying on a sandbox as storage. ## Network policy Pass `networkPolicy` at create to block internet egress: ```ts 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](https://sandal.dev/docs/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](https://sandal.dev/docs/secrets#creating-waits-for-brokering). ## 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)](https://sandal.dev/docs/root-and-fuse). --- # Root and FUSE (preview) > A preview sandbox template where commands can run as root and FUSE works, for example to mount an S3 bucket. What works, how to keep a mount up across commands, and the limits. Source: https://sandal.dev/docs/root-and-fuse > **Preview:** > This template is a preview: it is not the default, it is enabled per project, and how it works may change. [Ask us](mailto:hello@sandal.dev?subject=Sandal%20root%20and%20FUSE%20preview) to switch it on for your project. ## What it is On the default template, commands run as an unprivileged user (uid 2000) without `sudo`, and a root command is refused: `sandal exec --root` answers `422 capability_unavailable`, the CLI exits with code 7, and the message names the missing capability (`tenant-root-v1`) and the next step. The preview template, named **Preview: root + FUSE**, is the same Debian sandbox with two additions: - **Root on request.** A command you start as root runs as uid 0 with `HOME=/root`. It can install packages with `apt` and write anywhere, for example `/usr/local`. Commands you start normally still run as the unprivileged user. - **FUSE.** `/dev/fuse` and `fusermount3` are available, so FUSE filesystems such as `rclone mount` work. Create a sandbox from it with its template id (we send it to you when we switch the preview on for your project): ```bash sandal create --template ``` ## Run a command as root ```bash sandal exec --root -- id # uid=0(root) sandal exec --root -- sh -c 'apt-get update && apt-get install -y rclone' ``` The SDKs take the same option per command: TypeScript `sb.exec(cmd, { user: "root" })`, Python `sb.exec(cmd, user="root")`, Go `sandal.SandalCommandOptions{User: "root"}`. Root commands always go over the API path, not the direct exec path, and `--root` cannot be combined with `--secret` or a live terminal (`-it`). ## Mount an S3 bucket Start the FUSE daemon **detached** from the command that mounts it: in its own session (`setsid`), in the background (`--daemon`), with its input and output redirected. The mount then stays up after that `exec` ends, and every later `exec` sees it, including commands that do not run as root: ```bash # an rclone config for your bucket, copied in as a file (keys never go on a command line) sandal cp ./rclone.conf :/workspace/rclone.conf sandal exec --root -- sh -c 'mkdir -p /mnt/bucket && setsid rclone mount --config /workspace/rclone.conf s3:my-bucket /mnt/bucket --allow-other --vfs-cache-mode writes --daemon /tmp/mount.log 2>&1' sandal exec -- ls /mnt/bucket # a later exec, as the normal user ``` `rclone.conf` holds a standard rclone S3 remote named `s3` (`type = s3`, your provider, keys and region). `--allow-other` lets users other than root use the mount. If the daemon stays attached to the `exec` instead (started in the foreground, or holding the command's output), that `exec` never finishes and is ended at its timeout, together with the mount. Plain `nohup … &` without `setsid` did not keep a background process alive in our tests. ## Limits - **Where a mount is visible.** A detached mount is visible to later execs, terminals and file operations, but not to SSH sessions. - **Mounts do not survive** a stop and start, a pause and resume, or a fork: mount again afterwards. - **Fewer hosts.** These sandboxes run only on hosts that support the template, so there is less capacity than for the default template, and a create may wait (`waiting_for_capacity`). - **The first create can take minutes.** The first create on a host that has not run the template yet took about 4 minutes in our tests; later creates took about 30 seconds (November 28, 2026). There is no warm pool for it yet. - **Brokered secrets** were verified on this template on November 28, 2026; as everywhere, [wait for `active`](https://sandal.dev/docs/secrets#wait-for-active-before-the-first-request) before the first request to a credential host. - **Preview.** The template id changes when the template is updated, and the behaviour may change before it is generally available. > **Verified:** > On November 28, 2026, on production: `sandal exec --root` ran as uid 0 with `HOME=/root`, `apt` installed packages, and an `rclone` S3 mount made as root accepted writes and in-place edits that appeared in the bucket. A mount started detached (`setsid`, `--daemon`) in one root `exec` was used by a later `exec` as the normal user, also over the direct exec path, and was still mounted a minute later. The same root call through the TypeScript and Python SDKs ran as uid 0. On the default template the call was refused with exit code 7. --- # GitHub Actions Runners > Ephemeral GitHub Actions runners, one VM per job: Linux x64 today, Windows and Linux arm64 in preview; macOS runners are not available yet. In private beta. Source: https://sandal.dev/docs/runners > **Private beta:** > Sandal runners are in private beta and are enabled per project. The Sandal CLI and SDKs are not yet published to npm, PyPI or Go, so there is nothing to install from a public registry. [Request access](mailto:hello@sandal.dev?subject=Sandal%20runners%20beta) and we set up a runner pool for your GitHub organization with you and send you the beta packages. ## Swap one label Sandal runners register with GitHub as just-in-time, single-use runners. Your workflow keeps its steps, actions and secrets; only `runs-on` changes. ```yaml title=".github/workflows/ci.yml" jobs: test: runs-on: sandal-ubuntu-24.04 steps: - uses: actions/checkout@v4 - run: pnpm install --frozen-lockfile - run: pnpm test ``` Turn runners on once for the GitHub account you connected in the Console (Console → CI → GitHub, or `sandal runners enable`). A job only lands on Sandal when its label is one of the labels below; labels outside the `sandal` namespace (`ubuntu-latest`, `self-hosted`, `macOS`) are left alone. ## Labels The live list, with availability, is public: `sandal runners labels` works without signing in (add `--upcoming` for preview labels), or `GET https://api.sandal.dev/v1/runner-labels`. Signed in, it also lists the macOS images your project can see. | Label | Machine | Status | | --- | --- | --- | | `sandal-ubuntu-24.04` (default; also `sandal`, `sandal-ubuntu-latest`) | Ubuntu 24.04 x64, 4 vCPU / 8 GiB | Available | | `sandal-ubuntu-24.04-2` (`sandal-small`) | 2 vCPU / 4 GiB | Available | | `sandal-ubuntu-24.04-8` (`sandal-large`) | 8 vCPU / 16 GiB | Available | | `sandal-ubuntu-24.04-16` (`sandal-xlarge`) | 16 vCPU / 32 GiB | Available | | `sandal-windows-latest` (= `sandal-windows-2025`), `sandal-windows-latest-8` | Windows Server 2025 x64, 4 vCPU / 16 GiB or 8 / 32 | Preview: enabled per project | | `sandal-windows-2022`, `sandal-windows-2022-8` | Windows Server 2022 x64, 4 vCPU / 16 GiB or 8 / 32 | Preview: enabled per project | | `sandal-ubuntu-24.04-arm`, `sandal-ubuntu-24.04-arm-8` | Ubuntu 24.04 arm64, 4 vCPU / 16 GiB or 8 / 32 | Preview: enabled per project | | `sandal-macos-latest` (`sandal-macos-latest-4`), `sandal-macos-latest-8` | macOS with Xcode, Apple silicon, 4 vCPU / 8 GiB or 8 / 16 | Not available yet | A job whose label is not available to your project is not started and nothing is billed; the label list says why (`unavailableReason`). The public list shows the preview labels as not available, because they are switched on per project. > **Windows and Linux arm64 runners are in preview:** > They run in a rented VM per job (not a microVM), so they take longer than Linux x64 to start. Windows Server 2025 and Linux arm64 start from pre-built images; `sandal-windows-2022` has no pre-built image yet and starts slowest. [Ask us](mailto:hello@sandal.dev?subject=Sandal%20Windows%20and%20arm64%20runners) to switch them on for your project. ## One job, one VM Every job gets a fresh VM, created when the job is queued and destroyed when it finishes. Sandal registers a single-use runner with GitHub for that job only, so nothing sits idle and registered between builds, and no state carries over from one job to the next. - **Linux** jobs run in their own microVM with its own kernel. - **Windows and Linux arm64** jobs (preview) run in their own rented VM, deleted when the job ends. - **macOS** runners are not available yet. - **Fork and untrusted runs** never share a VM with another job. Runs from public repositories are off by default (`sandal runners public`). **When a runner fails to start.** If a Linux runner fails to start, Sandal retries automatically: a job is never left without a runner because of a single failure. When the VM for the runner cannot be created, or stops before its runner has registered with GitHub, Sandal tries again while the job stays queued: after 15 s, 30 s, 1 min, 2 min and 4 min, then every 5 minutes, for up to about 1.5 hours. Only then does the job end, with the failure code `runner_capacity_exhausted`: Sandal could not start a runner for this job after repeated attempts. Sandal also checks GitHub every minute for queued jobs, so a job whose webhook never reached Sandal is still picked up. This covers private and internal repositories; for public repositories the [public-runs setting](#one-job-one-vm) applies. **When a job loses its runner.** GitHub can hand an idle runner to any queued job with matching labels, so the runner Sandal started for your job may run another of your jobs instead. When that happens, or when the runner's VM is lost while it starts, Sandal starts a fresh runner for the waiting job automatically, up to 6 runners per job. Only after that does the job end with `runner_capacity_exhausted`. After a fresh runner is started, `sandal runners jobs get` can show a later created time for the job. **Bursts.** Many jobs queued at once each get their runner registered without a throttle on Sandal's side; GitHub's own API limits still apply. ## Caches Linux jobs start from a clean VM, so dependency caches work the way they do on GitHub-hosted runners: `actions/cache` and `setup-*` caches go to GitHub. Per-repository cache volumes that a job mounts (and that survive across jobs) are coming; the `sandal runners caches list | purge` commands already exist for them. ## Inspect jobs Workflow step logs stay in GitHub. Sandal keeps its own lifecycle log per job (queued, VM started, runner registered, finished) and the queue-to-online latency of the pool: ```bash sandal runners jobs list sandal runners jobs get sandal runners jobs logs sandal runners jobs cancel # deregisters the runner and destroys the VM ``` `jobs list` and `jobs get` show when the job started on its runner (STARTED). When a job lost its runner and Sandal is starting a fresh one for it, they say so, for example `runner reassigned, starting a fresh one (attempt 2)`. The SDKs expose the same data as `sandal.runnerPools` and `sandal.runnerJobs` ([TypeScript SDK](https://sandal.dev/docs/sdk-typescript)). ## Pricing Metered per minute; rates are on the [rate card](https://sandal.dev/pricing#rates). How runner usage is metered: [Pricing](https://sandal.dev/docs/pricing). --- # Devices > iOS Simulators and Android devices (preview) in the cloud, driven from the CLI, the SDKs or the Console. Source: https://sandal.dev/docs/simulators > **iOS Simulators: private beta. Android: preview:** > iOS Simulators are available on request in the private beta, with small capacity ([ask us](mailto:hello@sandal.dev?subject=Sandal%20iOS%20Simulators)). Android devices are in preview and enabled per project ([ask us](mailto:hello@sandal.dev?subject=Sandal%20Android%20devices)). `sandal devices capabilities` shows what your project can create right now. ## iOS Simulators An iOS Simulator session is a simulator (iOS 27.2, iPhone 17) on an Apple silicon Mac that Sandal runs only for simulators, in `eu-central`, created on demand and deleted when you are done. Use it to install and run your app, drive it from an agent or a test, and read what it logged. iOS Simulator tests are not supported inside a macOS VM; they are served here: install your simulator build and drive it from your test or agent. What works: - Install a simulator build of your app (`.app`, or a `.zip` / `.tar.gz` of one), launch it by bundle id, open a URL or deep link - Tap, type, screenshots (PNG or JPEG) and the UI tree; video clips (`record --duration`) - List the installed apps, read the simulator's unified log, list crash reports - From the API and SDKs, also: uninstall an app, and copy a file into or out of an app's container ```bash sandal devices ios create # iPhone 17, iOS 27.2, eu-central; waits until active sandal devices apps upload MyApp.app # once; prints an asset id sandal devices install --asset --launch sandal devices ios open-url myapp://settings sandal devices ios tap 0.5 0.5 # normalized 0..1 from the top-left sandal devices ios screenshot --output shot.png sandal devices ios apps # installed apps (--system adds Apple's) sandal devices ios logs # unified log (--follow to stream) sandal devices ios crash-reports sandal devices ios delete --yes ``` More: `devices ios type | launch | ui-tree | record | push | network | snapshot`. `devices install --file ` uploads and installs in one step. | Step | Typical | | --- | --- | | `create` from a warm simulator | about 7-10 s | | `create` without a warm simulator | about 45 s | | Screenshot | about 2-3 s (the first one in a session can take about 5 s) | | Install and launch an uploaded app | about 3-6 s | | Tap, type, open URL, list apps, crash reports | about 0.5-0.7 s | | Logs | about 1.5 s | | Delete until destroyed | about 7 s | Measured on production on November 28-29, 2026 from our build server in Helsinki, one session at a time (CLI `0.1.0-beta.16` and the SDK). Known limits in the beta: one region (`eu-central`) and one device profile; few simulators run at a time, so a create can wait for a free one (`sandal devices capabilities` shows the free and warm slots). There are no physical iPhones. ## Android devices (preview) ### What an Android device is A device session is an Android emulator (Android 17, AOSP x86_64, **no Google Play services**) on a Sandal host, created on demand and deleted when you are done. You drive it from the CLI or SDK, or watch and tap it in the Console's live view. What works in the preview: - Tap, swipe, type and keys (home, back, enter, volume …), open a URL or deep link - Screenshots (about 2.5 s, PNG or JPEG) and the UI tree - Install an APK, APKS or AAB and launch it; `adb shell` on the server, or a local `adb` forward - logcat, read or followed live; the clipboard - Video: clips up to 60 s and start/stop spans up to 5 min (H.264, 60 fps) - Live view in the browser (H.264, input acknowledged in about 0.1 s) ### See what your project can create ```bash sandal devices capabilities ``` ```text PLATFORM OS DEVICES REGIONS SLOTS android 37 Sandal Phone [540x1200, default], Sandal Phone HD [720x1600], eu-central 3 (1 warm) Sandal Phone Full HD [1080x2400], Sandal Tablet [1920x1200] ``` ### Create and drive one ```bash sandal devices android create # Sandal Phone, about 14-18 s from the warm slot sandal devices android tap 0.5 0.5 # normalized 0..1 from the top-left sandal devices android screenshot --output shot.png sandal devices android open-url https://sandal.dev sandal devices android record --duration 10s # an MP4 clip sandal devices android delete ``` More: `devices android swipe | type | key | launch | install --launch | logs --follow | shell | adb | ui-tree | clipboard`. `sandal devices start` creates a device, installs an app and opens a URL in one step. ### What to expect Measured on production on November 27, 2026 (Sandal Phone): | Step | Typical | | --- | --- | | `create` from the warm slot | 13-18 s | | `create` without a warm slot (other profiles, or a second device at once) | about 1 minute | | Tap | 0.4-0.7 s | | Screenshot | about 2.5 s | | Install and launch an APK | 2.4-3.6 s | | Live view, first picture | about 3 s | | Delete until destroyed | 10-20 s | ### Known issues in the preview - One preview host and one region (`eu-central`): up to 3 devices run on it at a time (shared), and only one starts from the warm slot. - The recording window runs about 5 s early: the last seconds before stop are missing, so recordings are not frame-accurate to your start and stop. - A screenshot or a recording stop right after another operation can fail with a retryable conflict; try again. - The HD, Full HD and Tablet profiles are slower: the hosts have no GPU. ## From the SDK The TypeScript SDK exposes device sessions as `sandal.devices`, the Python SDK as `sandal.devices` and the Go SDK as `Devices`: the same operations as the CLI, plus uninstall and file copy on iOS. ## Pricing See [pricing](https://sandal.dev/pricing) for current rates. ## Next steps - [Sandboxes](https://sandal.dev/docs/sandboxes), general-purpose compute for the rest of your agent's work - [Computer use](https://sandal.dev/docs/computer-use), a Linux desktop your agent can see and drive - [Runners](https://sandal.dev/docs/runners), GitHub Actions runners > **Verified:** > The iOS commands above were run against production on November 29, 2026 with the `0.1.0-beta.16` CLI and only `SANDAL_API_KEY` set: upload, create 7.5 s, install and launch 5.8 s, screenshots 2.7 s and 1.9 s, tap, type, open-url, ui-tree, launch, apps, logs, crash-reports, a 3 s recording, delete. Uninstall and copying files in and out were run through the SDK (`0.1.0-beta.13`) the same day. > > The Android commands above were run against production on November 27, 2026 with the `0.1.0-beta.12` CLI and only `SANDAL_API_KEY` set: create 18 s, tap 0.7 s, screenshot 2.6 s (540x1200 PNG), open-url 1.1 s, a 10 s recording, delete. --- # Xcode Builds > Remote Xcode builds in ephemeral VMs on Apple silicon, driven from the API. The builds API is not available yet; macOS builds and tests (swift build, swift test, xcodebuild for macOS) run today inside a macOS VM. Source: https://sandal.dev/docs/xcode-builds > **Not available yet:** > The Xcode builds API on this page is not available yet; no project can run a build through it today. This page describes how it will work. To hear when it opens, write to [hello@sandal.dev](mailto:hello@sandal.dev?subject=Sandal%20Xcode%20builds). The Sandal SDKs are not yet published to npm, PyPI or Go. > > What works today: inside a macOS VM (macOS 27.2 with Xcode 27.0, on a Mac leased to your organisation alone) you can build and test for macOS yourself: `swift build`, `swift test`, and `xcodebuild build` / `xcodebuild test` with a macOS destination. iOS Simulator tests are not supported inside a macOS VM; they are served by [iOS Simulators](https://sandal.dev/docs/simulators), which run on their own Sandal Macs. [Ask us](mailto:hello@sandal.dev?subject=Sandal%20macOS%20VMs) to set up a macOS VM. ## Overview Xcode builds need a Mac. Sandal will run each build inside its own ephemeral macOS VM on Apple silicon hosts: one build per VM, destroyed when the build finishes. You get a clean VM, your source and a build, without maintaining a Mac build farm. It is designed for: - CI builds, tests and archives without racking Mac minis - Agent-driven iOS development, an agent that writes Swift and needs to know whether it compiles - Building an app straight onto an [iOS Simulator](https://sandal.dev/docs/simulators) session for review ## How a build will work A build will be one API request (`sandal.builds.xcode.create` in the TypeScript SDK). The request describes: | Field | What it is | | --- | --- | | `action` | `build`, `test`, `archive`, `export` or `analyze` | | `scheme` | The Xcode scheme to build | | `destination` | The value you would pass to `xcodebuild -destination` | | `source` | Either a Git repository at a specific revision, or a source bundle you uploaded | | `xcodeImageId` / `xcodeVersion` | Which macOS image and Xcode to build with | | `cacheScope` | `none`, `project` or `organization` | | `exportMethod` | `app-store-connect`, `ad-hoc`, `development` or `enterprise` (for `export`) | | `signingSecretRef` | A reference to signing material stored in the Sandal Vault, never the material itself | | `attachDeviceSessionId` | Install the result onto a running iOS Simulator session | Once the builds API opens, `sandal macos images` in the beta CLI lists the macOS images and Xcode versions your project can use. ## Source upload Uploaded sources are content-addressed and chunked: you declare a manifest, upload only the chunks the server does not already have, then commit (`beginSourceUpload`, `putSourceChunk`, `commitSourceUpload`). Unchanged chunks from an earlier upload are reused, so a small diff uploads a small amount of data. ## Progress and artifacts A build moves through phases (`queued`, `preparing`, `syncing`, `resolving`, `building`, `exporting`, `attaching`, `finalizing`). Read its event log with `listEvents` (resumable by sequence) or follow it live with `streamEvents`; `cancel` stops the build and destroys its VM. Artifacts are announced in the event log as they are produced: `app`, `ipa`, `archive` (`.xcarchive`), `xcresult`, `dsym`, `log` and a `manifest`. ## Signing Certificates and provisioning profiles are never part of a build request. The request carries only a Vault reference (`signingSecretRef`), which Sandal will resolve when the build runs inside its own VM. ## Pricing See [pricing](https://sandal.dev/pricing) for current rates. ## Next steps - [Devices](https://sandal.dev/docs/simulators), iOS Simulator sessions and Android devices - [Runners](https://sandal.dev/docs/runners), GitHub Actions runners (macOS runners are not available yet) - [Pricing](https://sandal.dev/docs/pricing), full platform pricing --- # Code Interpreter > Stateful Python, JavaScript and TypeScript execution with rich results for LLM tool calls, a thin layer over Sandal sandboxes. Source: https://sandal.dev/docs/code-interpreter ## Overview The code interpreter is not a separate product. It is the `code` namespace on a Sandal sandbox, tuned for LLM tool calling: short, stateful runs where variables and imports persist between calls, stdout streams back as it happens, and results (DataFrames, plots, JSON) come back as MIME bundles instead of scraped terminal text. It runs inside a sandbox from the project default template (see [Sandboxes](https://sandal.dev/docs/sandboxes#create-a-sandbox) for creating one). A run takes 0.6-0.8 s on the beta deployment. Use `sandal capabilities` to confirm `code-interpreter` is enabled for your project. > **Private beta:** > The SDKs are in private beta and not yet published to npm/PyPI/Go. Request access (hello@sandal.dev) and we send you the packages. ## Why not just exec? `processes.execAndWait(id, { command: ["python3", "script.py"], ... })` starts a fresh process every time: no shared variables, no shared imports. `code.runAndWait` runs in a persistent **context**, so each call sees what earlier calls defined. **TypeScript** ```ts import { randomUUID } from "node:crypto"; import { Sandal } from "@sandal-dev/sdk"; const sandal = new Sandal({ baseUrl: "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 sandboxId = process.argv[2]; // a running enter-agent-linux sandbox const first = await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), language: "python", code: "import math, sys\nprint('python', sys.version.split()[0])\n[math.sqrt(n) for n in range(4)]", onEvent: (event) => event.type === "stdout" && process.stdout.write(event.text ?? ""), }); console.log(first.mainResult?.data["text/plain"]); await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), language: "python", code: "x = 21" }); const second = await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), language: "python", code: "x * 2" }); console.log(second.mainResult?.data["text/plain"]); // "42" ``` **Python** ```python import asyncio, os, sys, uuid from sandal import Sandal, SandboxTarget async def main(sandbox_id: str): sandal = Sandal(SandboxTarget( base_url="https://api.sandal.dev", api_token=os.environ["SANDAL_API_KEY"], # organization_id and project_id are optional: the key alone is enough. organization_id=os.environ["SANDAL_ORGANIZATION_ID"], project_id=os.environ["SANDAL_PROJECT_ID"], )) try: await sandal.code.run_and_wait( sandbox_id, idempotency_key=str(uuid.uuid4()), language="python", code="x = 21" ) outcome = await sandal.code.run_and_wait( sandbox_id, idempotency_key=str(uuid.uuid4()), language="python", code="print('hi')\nx * 2" ) print(outcome.stdout) # "hi\n" print(outcome.main_result.data["text/plain"]) # "42" finally: await sandal.close() asyncio.run(main(sys.argv[1])) ``` `x` from the first call is still in scope for the second. An LLM iterating on an analysis does not have to reload its data every turn. ## Contexts Each language has a default context (`default-python`, `default-javascript`, `default-typescript`) used when you pass only `language`. Create named contexts when you want independent state, their own working directory, or their own environment: ```ts const { context: a } = await sandal.code.createContext(sandboxId, { idempotencyKey: randomUUID(), language: "python", cwd: "/workspace", }); const { context: b } = await sandal.code.createContext(sandboxId, { idempotencyKey: randomUUID(), language: "python" }); await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), contextId: a.id, code: "x = 1" }); await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), contextId: b.id, code: "x = 2" }); const r = await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), contextId: a.id, code: "x" }); console.log(r.mainResult?.data["text/plain"]); // "1" const { contexts } = await sandal.code.listContexts(sandboxId); await sandal.code.restartContext(sandboxId, a.id, { idempotencyKey: randomUUID() }); // discard state, keep the sandbox await sandal.code.deleteContext(sandboxId, b.id, { idempotencyKey: randomUUID() }); ``` An execution is a sandbox process. `sandal.code.interrupt(sandboxId, executionId, { idempotencyKey })` cancels a long run (KeyboardInterrupt / SIGINT) and the context survives; a kernel that ignores the interrupt is restarted. ## Streaming output `onEvent` receives every event as it arrives. Event types are `start`, `stdout`, `stderr`, `result`, `error` and `end`: ```ts const outcome = await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), language: "python", code: "import time\nfor i in range(5):\n print(i, flush=True)\n time.sleep(1)", onEvent: (event) => { if (event.type === "stdout") process.stdout.write(event.text ?? ""); if (event.type === "stderr") process.stderr.write(event.text ?? ""); }, }); ``` That is the shape you would forward to a chat UI while the model's tool call executes. If `runAndWait` hits its own `timeoutMs` first, the outcome has `terminal: false`; resume with `sandal.code.streamEvents(sandboxId, outcome.execution.id, { afterSequence: outcome.nextSequence })`. ## Rich results Results are MIME bundles: `text/plain`, `text/html`, `image/png` (base64, matplotlib figures), `application/json`, and `application/vnd.sandal.table+json` for pandas DataFrames. ```ts const outcome = await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), language: "python", code: "import matplotlib.pyplot as plt\nplt.plot([1, 2, 3], [4, 1, 2])\nplt.show()", }); for (const result of outcome.results) { const png = result.data["image/png"]; if (typeof png === "string") { // render as `data:image/png;base64,${png}` } } if (outcome.error) { console.log(outcome.error.name, outcome.error.value, outcome.error.traceback); } ``` Errors are structured (`name`, `value`, `traceback`), so a supervising agent can decide whether to retry, patch the code, or surface the failure without parsing stderr. Code is limited to 64 KiB per run. Which Python libraries are preinstalled depends on the template; install what you need with `pip` through `processes.execAndWait`. ## LLM tool-calling integration `code.runAndWait` fits behind a single tool definition: give the model a `run_code` tool, execute what it sends, return the result, repeat. ```ts import Anthropic from "@anthropic-ai/sdk"; import { randomUUID } from "node:crypto"; import { Sandal } from "@sandal-dev/sdk"; const anthropic = new Anthropic(); const sandal = new Sandal({ baseUrl: "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 sandboxId = process.argv[2]; const tools = [ { name: "run_code", description: "Execute Python code in a persistent, stateful interpreter and return its output.", input_schema: { type: "object" as const, properties: { code: { type: "string" } }, required: ["code"] }, }, ]; const messages: Anthropic.MessageParam[] = [ { role: "user", content: "Compute the first 20 Fibonacci numbers and their sum." }, ]; while (true) { const response = await anthropic.messages.create({ model: "claude-sonnet-4-5", max_tokens: 1024, tools, messages }); messages.push({ role: "assistant", content: response.content }); const calls = response.content.filter((block) => block.type === "tool_use"); if (calls.length === 0) break; // final answer const results: Anthropic.ToolResultBlockParam[] = []; for (const call of calls) { const outcome = await sandal.code.runAndWait(sandboxId, { idempotencyKey: randomUUID(), language: "python", code: (call.input as { code: string }).code, }); const text = outcome.error ? `Error: ${outcome.error.name}: ${outcome.error.value}` : `${outcome.stdout}${String(outcome.mainResult?.data["text/plain"] ?? "")}`; results.push({ type: "tool_result", tool_use_id: call.id, content: text }); } messages.push({ role: "user", content: results }); } ``` The sandbox side does not change when you switch model providers; any framework that expects a `(name, args) => result` tool works the same way. ## Everything else is a sandbox Because `code` runs inside a sandbox, the rest of the sandbox API is available on the same instance: `files.write` to drop a CSV in place, `processes.execAndWait` to `pip install` a library, `sandboxes.exposePort` for a server the model started, `sandboxes.stop` between sessions. See [Sandboxes](https://sandal.dev/docs/sandboxes) for those calls; note that `stop` ends the interpreter processes, so context state does not survive a stop. ## Next steps - [Sandboxes](https://sandal.dev/docs/sandboxes), the underlying compute primitive - [Snapshots & forks](https://sandal.dev/docs/snapshots-and-forks), branch a prepared environment - [Pricing](https://sandal.dev/docs/pricing) --- # Full VMs > A complete Linux virtual machine (Cloud Hypervisor) with systemd and cloud-init, created from every SDK and the CLI. Source: https://sandal.dev/docs/full-vms A **Full VM** is a sandbox that runs a stock Linux distribution (Debian 13) as a complete virtual machine on Cloud Hypervisor: its own kernel, `systemd` as PID 1, `cloud-init`, and the usual lifecycle (stop, start, reboot, pause, resume, snapshot, fork). Use it when your workload needs a real init system, services, or kernel features that the default microVM (`enter-agent-linux`) does not give you. > **Beta bundle:** > The examples use the 0.1.0-beta.16 clients from your beta bundle: TypeScript `@sandal-dev/sdk`, Python `sandal-sdk` (import `sandal`), Go `sandal.dev/go`, CLI `@sandal-dev/cli`. `SANDAL_API_KEY` alone is enough: the organization and project are resolved from the key (`SANDAL_ORGANIZATION_ID` / `SANDAL_PROJECT_ID` are optional overrides). See the [quickstart](https://sandal.dev/docs/quickstart#2-one-variable-your-api-key). ## Create a Full VM Ask for the `general-linux-vm` runtime. Without a template, the server uses the project's default Full VM template. **TypeScript** ```ts import { Sandal } from "@sandal-dev/sdk"; const sandal = Sandal.fromEnv(); const vm = await sandal.createSandbox({ runtime: "general-linux-vm", name: "my-vm", ttlSeconds: 3600 }); try { const r = await vm.exec(["sh", "-c", "systemctl is-system-running; . /etc/os-release; echo $PRETTY_NAME"]); console.log(r.stdout); // running / Debian GNU/Linux 13 (trixie) await vm.writeText("/workspace/hello.txt", "hello from a Full VM"); console.log(await vm.readText("/workspace/hello.txt")); } finally { await vm.delete(); } ``` **Python** ```python import asyncio from sandal import Sandal async def main(): async with Sandal.from_env() as sandal: vm = await sandal.create_sandbox(profile="general-linux-vm", name="my-vm", lifetime_seconds=3600) try: r = await vm.exec(["sh", "-c", "systemctl is-system-running; . /etc/os-release; echo $PRETTY_NAME"]) print(r.stdout) await vm.write_text("/workspace/hello.txt", "hello from a Full VM") print(await vm.read_text("/workspace/hello.txt")) finally: await vm.delete() asyncio.run(main()) ``` **Go** ```go package main import ( "context" "fmt" "time" sandal "sandal.dev/go" ) func main() { ctx := context.Background() client, err := sandal.NewSandalFromEnv(sandal.SandalEnvOptions{}) if err != nil { panic(err) } runtime := sandal.SANDBOXRUNTIMEPROFILE_GENERAL_LINUX_VM name := "my-vm" vm, err := client.CreateSandbox(ctx, sandal.SandalCreateSandboxOptions{Name: &name, Runtime: &runtime, Lifetime: time.Hour}) if err != nil { panic(err) } defer vm.Delete(ctx, sandal.SandalLifecycleOptions{}) r, err := vm.Exec(ctx, []string{"sh", "-c", "systemctl is-system-running; . /etc/os-release; echo $PRETTY_NAME"}, nil) if err != nil { panic(err) } fmt.Print(r.Stdout) } ``` **CLI** ```bash ID=$(sandal create --runtime general-linux-vm --name my-vm --ttl 1h --json | jq -r 'select(.event=="ready") | .id') sandal exec $ID -- sh -c 'systemctl is-system-running; . /etc/os-release; echo $PRETTY_NAME' sandal ssh $ID # interactive SSH session sandal reboot $ID # restarts the operating system; disks are kept sandal delete $ID ``` The TypeScript `runtime` option also accepts a `templateAlias` of your own Full VM template, or checks that a pinned `template` really is a Full VM. Combining `runtime: "general-linux-vm"` with `kind: "container"` is refused before any request is sent. ## What you get - Debian 13 with `systemd` running and `cloud-init` finished when the sandbox reports `running`. - A non-root default user (uid 2000). `sudo` is not configured in the default template, and exec as root (`sandal exec --root`, `user: "root"` in the SDKs) is refused there with `422 capability_unavailable` (CLI exit code 7; the message names `tenant-root-v1`). No root-capable template is generally offered yet; a root + FUSE sandbox template is in [preview](https://sandal.dev/docs/root-and-fuse). - `exec` commands run without `HOME` set and without `/proc`, so `ps` and `~` paths do not work there; use absolute paths (for example `/workspace/...`) and `systemctl`. - The files API works inside `/workspace` (also `/home/enter/workspace`); other paths answer `400`. Use `exec` for the rest of the filesystem. - Sizes `xs` to `xl` as for every sandbox. A running Full VM can grow in place (`sandboxes.resize`, CPU, memory and root disk; grow only). ## Lifecycle and speed Measured on production at size `s` (November 2026): | Action | Time | | --- | --- | | Create to running (SDK or CLI) | 15-19 s (about 29 s on a host that has not booted the template yet) | | First exec / warm exec | about 0.5 s / 0.3 s | | Stop / start (disk kept) | 1-3 s / about 6 s | | Reboot (new boot id) | about 6 s | | Pause / resume (memory kept, same VM) | about 0.7-1 s / 1-2.5 s | | Snapshot / fork | about 9 s / 15-25 s | ## Limits - No persistent volumes and no desktop on a Full VM yet; use the default VM runtime for those ([Volumes](https://sandal.dev/docs/volumes), [Computer use](https://sandal.dev/docs/computer-use)). - `sandal capabilities` (or `sandboxSystem.capabilities`) lists `general-linux-vm` among the runtime profiles where Full VMs are available. A project without it gets `capability_unavailable` (feature `general-linux-vm`); nothing is created or billed. --- # Windows VMs > Preview: a Windows Server VM for your project, billed per minute and deleted at its lifetime cap, with RDP through the Sandal relay (sandal rdp). Source: https://sandal.dev/docs/windows-vms > **Preview:** > Windows VMs are in preview and enabled per project. [Ask us](mailto:hello@sandal.dev?subject=Sandal%20Windows%20VMs) to switch them on for yours. A Windows VM is a whole Windows Server machine for one person or one agent: you sign in over RDP, through Sandal, without opening a port to the internet. It has a lifetime cap and is deleted when the cap is reached, so a forgotten VM does not run forever. ## Create one and connect ```bash sandal windows-vms create --lifetime 60m # prints the Administrator password ONCE sandal windows-vms get # state: running, rdp ready: yes sandal rdp # RDP bridge on 127.0.0.1:13389 ``` Point any RDP client at the address `sandal rdp` prints (`xfreerdp /v:127.0.0.1:13389 /u:Admin`, or Windows App / Microsoft Remote Desktop) and sign in as `Admin` with the password from `create`. Sandal never returns that password again and the CLI does not store it: keep it in your password manager. ```text vm: wvm_e63d… name: dw2-win state: running runtime: windows-server-2025 size: win-4x16 (4 vCPU, 16 GiB) region: eu-central expires: 2026-11-27T04:51:50.651Z (deleted automatically) rdp ready: yes ``` `sandal rdp` authorizes RDP for `--ttl` (5 min to 8 h, default 60 min) and gives every connection a fresh one-use token; your API key never leaves the CLI. Ctrl-C stops the bridge and revokes the access it created. ```bash sandal windows-vms list sandal windows-vms delete # deletes the VM and its disk; usage stops now ``` ## Options | Option | Values | | --- | --- | | `--size` | `win-4x16` (4 vCPU, 16 GiB; default) or `win-8x32` (8 vCPU, 32 GiB); 64 GiB disk | | `--runtime` | `2025` (Windows Server 2025, default) or `2022` | | `--lifetime` | 15 min to 12 h (default 60 min); the VM is deleted when it is reached | | `--name` | lowercase letters, digits and `-`, up to 40 | ## What to expect Measured on production on November 27, 2026 (Windows Server 2025, `win-4x16`): | Step | Time | | --- | --- | | `create` returns | 7-25 s | | state `running` | about 30-60 s after create | | `rdp ready` and a working RDP sign-in | about 2.5-3 min after create | | `delete` | 2-3 s | ## Limits in the preview - Windows VMs have RDP only: no snapshots, forks, pause or resize, and no public ingress. Use a [Linux sandbox](https://sandal.dev/docs/sandboxes) for those. - One region (`eu-central`). - From the SDKs: TypeScript `sandal.windowsVms`, Python `sandal.windows_vms`, Go `WindowsVms`. The CLI examples on this page are the verified path. > **Verified:** > Run against production on November 27, 2026 with the `0.1.0-beta.12` CLI and only `SANDAL_API_KEY` set: create, `get`, `list`, `sandal rdp` with an NLA sign-in by an RDP client (and the bridge's access revoked on Ctrl-C), then `delete`. --- # Browsers > Remote headless browser sessions (Chrome or Lightpanda) you drive over CDP with Playwright or Puppeteer, with an optional live view. Source: https://sandal.dev/docs/browsers A **browser session** is a managed remote browser. You create one, connect to it over the Chrome DevTools Protocol (CDP) with Playwright, Puppeteer or any CDP client, and release it when you are done. Two engines: | Engine | Use it for | | --- | --- | | `chrome` | full Chromium: screenshots, scrolling, extensions-free automation, live view | | `lightpanda` | fast, lightweight page loads and scraping (no rendering, no screenshots, no live view) | **How long until ready** (production, November 2026): about 6-12 s for either engine when the host is idle. Under load it is slower, because a new session waits behind other sessions being torn down on the same host. With two sessions starting at a time, Chrome took p50 21 s / p95 57 s and Lightpanda p50 18 s / p95 38 s. We are working on this. Once a session is ready, connecting over CDP takes about 1 s, loading a page 0.2-0.4 s and releasing about 0.5 s. Since 0.1.0-beta.6 the SDKs check a starting session at most 1 s apart (it was 3 s), so your code sees it ready about 1.5 s after the server does (p95 1.9 s, was p50 2.6 s / p95 4.0 s). > **Enabled per project during the beta:** > Browser sessions are switched on per project. Elsewhere a create answers `capability_unavailable`. Examples use the 0.1.0-beta.16 clients; `SANDAL_API_KEY` alone is enough (see the [quickstart](https://sandal.dev/docs/quickstart#2-one-variable-your-api-key)). ## Create, connect, release **TypeScript** ```ts // npm install ./sdk/sandal-typescript-v0.1.0-beta.16.tgz playwright-core import { chromium } from "playwright-core"; import { Sandal, connectSandalBrowser, sandalPlaywrightAdapter } from "@sandal-dev/sdk"; const sandal = Sandal.fromEnv(); const session = await sandal.browsers.createAndConnect({ browserSessionCreateRequest: { engine: "chrome" }, lifetimeMs: 10 * 60_000 }); try { const attached = await connectSandalBrowser({ connection: session.connection, sessionId: session.sessionId, gatewayOrigin: "wss://api.sandal.dev", authorization: `Bearer ${process.env.SANDAL_API_KEY}`, adapter: sandalPlaywrightAdapter(chromium), }); try { const context = attached.browser.contexts()[0] ?? (await attached.browser.newContext()); const page = context.pages()[0] ?? (await context.newPage()); await page.goto("https://en.wikipedia.org/wiki/Sandal"); console.log(await page.title()); await page.screenshot({ path: "page.png" }); } finally { await attached.disconnect(); } } finally { await sandal.browsers.release({ sessionId: session.sessionId }); } ``` **Python** ```python import asyncio from sandal import Sandal async def main(): async with Sandal.from_env() as sandal: session_id, connection = await sandal.browsers.create_and_connect({"engine": "lightpanda"}, lifetime_s=600) try: # connection.web_socket_url is the CDP endpoint for your client (for example Playwright's # connect_over_cdp with the header Authorization: Bearer $SANDAL_API_KEY). print(session_id, connection.state) finally: await sandal.browsers.release(session_id=session_id) asyncio.run(main()) ``` **Go** ```go package main import ( "context" "fmt" "time" sandal "sandal.dev/go" ) func main() { ctx := context.Background() client, err := sandal.NewSandalFromEnv(sandal.SandalEnvOptions{}) if err != nil { panic(err) } request := sandal.NewBrowserSessionCreateRequest(time.Now().Add(10 * time.Minute).UnixMilli()) request.SetEngine(sandal.BROWSERSESSIONENGINE_CHROME) sessionID, connection, err := client.Browsers.CreateAndConnect(ctx, *request, sandal.SandalBrowserCreateOptions{}) if err != nil { panic(err) } defer client.Browsers.Release(ctx, sessionID).Execute() fmt.Println(sessionID, connection.WebSocketUrl) // connect a Go CDP client (e.g. chromedp) here } ``` **CLI** ```bash sandal browsers --help # create-session, get-session, list-sessions, release-session, ... sandal browsers list-sessions --json ``` ## Live view and CDP There are two ways in, and they do different jobs: - **CDP** is for code. Playwright, Puppeteer or any CDP client connects to `connection.webSocketUrl` with your API key and drives the browser: any URL the page itself can open, scripts, screenshots, network interception. - **Live view** is for a person. The Console's **Browsers** page streams the session's Chrome tab as video and lets you **Take control**: click, type, scroll and enter an address. From code, `sandal.browsers.liveViewTicket({ sessionId })` mints a single-use ticket for the live view where it is enabled. Live view works for Chrome only. The live view address bar takes **http and https addresses only**. A `data:`, `file:`, `javascript:` or `chrome:` address is refused with "Enter an http or https address". CDP has no such rule: your automation can open a `data:` page. ## Limits and good practice - Always release sessions: an unreleased session runs until its expiry. - One CDP client per session at a time. - Lightpanda does not render pixels: no screenshots, no live view. - A session that cannot start reports `failed` (it is cleaned up for you); create a new one. --- # Computer use > Linux desktop sandboxes an agent can see and drive - screenshots, clicks, typing, recordings and a live view for humans. Source: https://sandal.dev/docs/computer-use A **desktop sandbox** boots a Linux desktop (1280x800) with Chromium. The `computer` API lets an agent take screenshots and send mouse and keyboard input; a short-lived **live view** URL lets a person watch or take over in the browser; **recordings** capture a session as MP4. > **Beta bundle:** > Examples use the 0.1.0-beta.16 clients (`@sandal-dev/sdk`, `sandal-sdk`, `sandal.dev/go`, `@sandal-dev/cli`); `SANDAL_API_KEY` alone is enough (see the [quickstart](https://sandal.dev/docs/quickstart#2-one-variable-your-api-key)). ## Create a desktop and drive it **TypeScript** ```ts import { writeFileSync } from "node:fs"; import { Sandal } from "@sandal-dev/sdk"; const sandal = Sandal.fromEnv(); const desk = await sandal.createSandbox({ desktop: true, name: "agent-desktop", ttlSeconds: 3600 }); try { // The desktop session comes up a second or two after the sandbox is running. while (!/ready/i.test(JSON.stringify(await sandal.computer.status(desk.id)))) await new Promise((r) => setTimeout(r, 1000)); await sandal.computer.openUrl(desk.id, "https://example.com/"); await sandal.computer.click(desk.id, 640, 400); await sandal.computer.typeText(desk.id, "hello"); await sandal.computer.actions(desk.id, [{ kind: "hotkey", keys: ["ctrl", "l"] }]); const shot = await sandal.computer.screenshot(desk.id, { format: "png" }); writeFileSync("desktop.png", shot.data); const view = await sandal.computer.view(desk.id, { ttlSeconds: 300 }); console.log("watch live:", view.url); // a one-person link; treat it like a password } finally { await desk.delete(); } ``` **Python** ```python import asyncio from sandal import Sandal async def main(): async with Sandal.from_env() as sandal: desk = await sandal.create_sandbox(desktop=True, name="agent-desktop", lifetime_seconds=3600) try: while "ready" not in str(await sandal.computer.status(desk.id)).lower(): await asyncio.sleep(1) await sandal.computer.open_url(desk.id, "https://example.com/") await sandal.computer.click(desk.id, 640, 400) await sandal.computer.type_text(desk.id, "hello") shot = await sandal.computer.screenshot(desk.id, format="png") open("desktop.png", "wb").write(shot.data) view = await sandal.computer.view(desk.id, ttl_seconds=300) print("watch live:", view.url) finally: await desk.delete() asyncio.run(main()) ``` **Go** ```go package main import ( "context" "os" "time" sandal "sandal.dev/go" ) func main() { ctx := context.Background() client, err := sandal.NewSandalFromEnv(sandal.SandalEnvOptions{}) if err != nil { panic(err) } desktop := true desk, err := client.CreateSandbox(ctx, sandal.SandalCreateSandboxOptions{Desktop: &desktop, Lifetime: time.Hour}) if err != nil { panic(err) } defer desk.Delete(ctx, sandal.SandalLifecycleOptions{}) time.Sleep(3 * time.Second) // the desktop session follows the sandbox by a second or two if _, _, err := client.Computer.OpenURL(ctx, desk.ID, "https://example.com/", sandal.SandalMutationIdentity{}); err != nil { panic(err) } png := sandal.SANDBOXCOMPUTERIMAGEFORMAT_PNG shot, _, err := client.Computer.Screenshot(ctx, desk.ID, sandal.SandalComputerScreenshotInput{Format: &png}) if err != nil { panic(err) } _ = os.WriteFile("desktop.png", shot.Data, 0o644) } ``` **CLI** ```bash ID=$(sandal create --desktop --name agent-desktop --ttl 1h --json | jq -r 'select(.event=="ready") | .id') sandal desktop $ID # prints (and opens) a live-view link for this desktop sandal delete $ID ``` ## Recordings `computer.startRecording(id, { maxDurationSeconds })` starts an MP4 recording; `stopRecording` finishes it and `downloadRecording` returns the bytes (`deleteAfterRead: true` removes it afterwards). Python and Go have the same calls (`start_recording`, `StartRecording`, ...). ## Speed Measured on production (November 2026): desktop ready 17-22 s after create; PNG screenshot about 0.4 s (JPEG quality 70 about 1.4 s); open URL and click about 0.4 s; typing and hotkeys about 1.3 s. ## Limits - Desktops run on the default VM runtime, not on [Full VMs](https://sandal.dev/docs/full-vms). - A live-view URL is a short-lived credential for one browser: do not paste it into shared channels. - A project without the `desktop` / `computer-use` capability gets `capability_unavailable`; nothing is created. --- # Snapshots & forks > On-demand disk snapshots, copy-on-write forks, and recovering a sandbox from a snapshot. Source: https://sandal.dev/docs/snapshots-and-forks A **snapshot** is an immutable copy of a sandbox's disk that you create on demand. A **fork** is a new sandbox that starts from a parent's disk state. Both are disk-level: neither copies live memory or running processes. > **Private beta:** > The snippets below assume a `sandal` client and a running sandbox, created as shown in [Sandboxes](https://sandal.dev/docs/sandboxes). The SDKs are in private beta and not yet published to npm/PyPI/Go; request access at hello@sandal.dev. ## Create a snapshot `createSnapshot` returns immediately with a snapshot in a pending state. Poll `getSnapshot` until it is `ready` (7-11 s measured at size `s`). A saved snapshot keeps its source sandbox pinned: you cannot delete the source while the snapshot exists. **TypeScript** ```ts import { randomUUID } from "node:crypto"; const { revision } = await sandal.sandboxes.get(sandboxId); const admitted = await sandal.sandboxes.createSnapshot(sandboxId, { idempotencyKey: randomUUID(), expectedSandboxRevision: revision, }); let snapshot = await sandal.sandboxes.getSnapshot(sandboxId, admitted.snapshot.id); while (snapshot.state !== "ready") { if (snapshot.state === "failed") throw new Error(`snapshot failed: ${snapshot.failureCode}`); await new Promise((r) => setTimeout(r, 500)); snapshot = await sandal.sandboxes.getSnapshot(sandboxId, snapshot.id); } console.log(snapshot.id); const { snapshots } = await sandal.sandboxes.listSnapshots(sandboxId); ``` **Python** ```python current = await sandal.sandboxes.get(sandbox_id) snapshot = ( await sandal.sandboxes.create_snapshot( sandbox_id, expected_sandbox_revision=current.revision, idempotency_key=str(uuid.uuid4()) ) ).snapshot while snapshot.state.value != "ready": if snapshot.state.value == "failed": raise RuntimeError("snapshot failed") await asyncio.sleep(0.5) snapshot = await sandal.sandboxes.get_snapshot(sandbox_id, snapshot.id) print(snapshot.id) listing = await sandal.sandboxes.list_snapshots(sandbox_id) ``` From the CLI: `sandal snapshot create ` (waits until ready), `sandal snapshot list `, `sandal snapshot get`. ### What a snapshot contains - The sandbox's filesystem: everything you wrote, installed packages, build artifacts, virtualenvs, `node_modules`. ### What it does not contain - **Memory and processes.** Restoring or forking from a snapshot boots the machine fresh: snapshots and forks are disk-level. Memory is kept only by `pause`/`resume` on the same sandbox; there are no memory snapshots, and `stop`/`start` keeps only the disk. - **Open network connections.** Anything mid-request must be retried. - **Environment you only exported in a shell.** If it was never written to disk, it is not in the snapshot. Snapshots are taken when you ask for them. Automatic periodic snapshots are not a feature you can rely on today. ## Recover from a snapshot `recover` brings an archived or failed sandbox back to running. Pass `snapshotId` to roll the sandbox back to a specific ready snapshot of its own: ```ts const { revision } = await sandal.sandboxes.get(sandboxId); const { operation } = await sandal.sandboxes.recover(sandboxId, { idempotencyKey: randomUUID(), expectedRevision: revision, snapshotId: snapshot.id, // optional; omit to recover the latest state }); await sandal.sandboxes.waitForOperation(operation.id, { timeoutMs: 300_000 }); ``` Archive followed by recover keeps files intact (verified in all three SDKs; recover takes 6-9 s). The CLI equivalent is `sandal recover `, optionally from a snapshot. ## Fork a sandbox A fork is a new sandbox with its own id, starting from the parent's disk. Without a `sourceSnapshotId`, the server captures the parent's current state first, so every completed write is in the fork. The parent keeps running. **TypeScript** ```ts const { revision } = await sandal.sandboxes.get(parentId); const forked = await sandal.sandboxes.fork(parentId, { idempotencyKey: randomUUID(), expectedRevision: revision, name: "child-a", lifecycle: { expiresAt: new Date(Date.now() + 60 * 60_000) }, }); await sandal.sandboxes.waitForOperation(forked.operation.id, { timeoutMs: 300_000 }); console.log(forked.sandbox.id); // a new, running sandbox with the parent's files ``` **Python** ```python from datetime import datetime, timedelta, timezone from sandal.models.sandbox_lifecycle_policy_input import SandboxLifecyclePolicyInput current = await sandal.sandboxes.get(parent_id) forked = await sandal.sandboxes.fork( parent_id, expected_revision=current.revision, idempotency_key=str(uuid.uuid4()), name="child-a", lifecycle=SandboxLifecyclePolicyInput(expires_at=datetime.now(timezone.utc) + timedelta(hours=1)), ) await sandal.sandboxes.wait_for_operation(forked.operation.id, timeout_seconds=300) print(forked.sandbox.id) ``` Optional inputs: `sourceSnapshotId` forks a specific ready snapshot instead of the current state. CLI: `sandal fork --name `. Fork currently takes 10-15 s end to end (measured on production), so it pays off when setup is the expensive part: do `pip install` / `npm install` / a repo clone once, then fork per experiment. Each fork counts against your concurrent-workload quota (64 per project today; see [Limits](https://sandal.dev/docs/limits)), and forking needs room for both parent and child. ### What a fork inherits - **Disk contents, yes.** If the parent's disk holds credentials (an API key in a config file, an SSH key), those bytes are copied. Rotate anything sensitive per child if forks should have separate blast radii. - **Memory, processes, open connections, no.** The child boots fresh from the copied disk. A computation in progress in the parent does not continue in the child. - **Port exposures, no.** The child has its own id; expose its ports separately. - **Lifecycle, no.** The child has its own `lifecycle` (pass it at fork time) and its own revision. Memory-level ("live") fork and memory snapshots are not available. Volume snapshots are not available either (`422`). ## Failure policy - A snapshot that fails ends in state `failed` with a `failureCode`; earlier ready snapshots are unaffected. - `archive` is reversible (`recover`); `delete` is not. - Automatic deletion only happens if a lifecycle policy asks for it: `autoDeleteAfterSeconds` on the sandbox or inherited from the project default. Check `sandal lifecycle get ` and `sandal lifecycle defaults` before relying on an idle sandbox to keep its data. See [Sandboxes](https://sandal.dev/docs/sandboxes#lifecycle-policy-expiry-and-automatic-stop). If the platform ever discards sandbox state without a `delete` call or a lifecycle policy that asked for it, that is a bug. Report it to hello@sandal.dev. --- # Persistent volumes > Block volumes that outlive a sandbox - attach, mount, detach, move to another sandbox, list and erase per project. Source: https://sandal.dev/docs/volumes A **persistent volume** is a block device (btrfs, 1 GiB to 64 TiB) mounted at a path you choose. Its data survives stop/start, detaching and the deletion of its sandbox: a sandbox delete keeps its persistent volumes (listed with `sandboxDeleted: true`; reattach them to another stopped sandbox or erase them at the project level) until you erase them. Pass `deleteAttachedVolumes: true` to erase them together with the sandbox; a volume moved in from another sandbox is always kept. > **Beta bundle:** > Examples use the 0.1.0-beta.16 clients (`@sandal-dev/sdk`, `sandal-sdk`, `sandal.dev/go`, `@sandal-dev/cli`); `SANDAL_API_KEY` alone is enough (see the [quickstart](https://sandal.dev/docs/quickstart#2-one-variable-your-api-key)). ## Rules - **Attach to a stopped sandbox.** Attaching to a running sandbox answers `409` ("stop it first"); the volume is mounted at the next start. - **A delete keeps them.** Deleting a sandbox detaches its persistent volumes and keeps them as project volumes (they still count against the project's disk quota). To erase them with it: TypeScript `sandbox.delete({ deleteAttachedVolumes: true })`, Python `await sandbox.delete(delete_attached_volumes=True)`, Go `sb.Delete(ctx, sandal.SandalLifecycleOptions{DeleteAttachedVolumes: true})`, CLI `sandal delete --yes --delete-volumes`. - **One sandbox at a time.** Attaching a volume that is attached elsewhere answers `409` naming the other sandbox; detach it first. - **Forks do not carry volumes.** A fork has only its own workspace disk. - Volumes are not available on [Full VMs](https://sandal.dev/docs/full-vms) yet. ## Attach a new volume and use it **TypeScript** ```ts import { Sandal } from "@sandal-dev/sdk"; const sandal = Sandal.fromEnv(); const sb = await sandal.createSandbox({ name: "with-volume", ttlSeconds: 3600 }); await sb.stop(); await sandal.sandboxes.attachVolume(sb.id, { mountPath: "/data", sizeGiB: 10 }); await sb.start(); await sb.exec(["sh", "-c", "echo kept > /data/state.txt && sync"]); await sb.stop(); await sb.start(); console.log((await sb.exec(["cat", "/data/state.txt"])).stdout); // kept ``` **Python** ```python import asyncio from sandal import Sandal async def main(): async with Sandal.from_env() as sandal: sb = await sandal.create_sandbox(name="with-volume", lifetime_seconds=3600) await sb.stop() await sandal.sandboxes.attach_volume(sb.id, mount_path="/data", size_gib=10) await sb.start() await sb.exec(["sh", "-c", "echo kept > /data/state.txt && sync"]) await sb.stop() await sb.start() print((await sb.exec(["cat", "/data/state.txt"])).stdout) # kept asyncio.run(main()) ``` **Go** ```go package main import ( "context" "fmt" "time" sandal "sandal.dev/go" ) func main() { ctx := context.Background() client, err := sandal.NewSandalFromEnv(sandal.SandalEnvOptions{}) if err != nil { panic(err) } sb, err := client.CreateSandbox(ctx, sandal.SandalCreateSandboxOptions{Lifetime: time.Hour}) if err != nil { panic(err) } if _, err := sb.Stop(ctx, sandal.SandalLifecycleOptions{}); err != nil { panic(err) } if _, _, err := client.Sandboxes.AttachVolume(ctx, sb.ID, sandal.SandalVolumeAttachmentCreateInput{MountPath: "/data", SizeGiB: 10}); err != nil { panic(err) } if _, err := sb.Start(ctx, sandal.SandalLifecycleOptions{}); err != nil { panic(err) } r, err := sb.Exec(ctx, []string{"sh", "-c", "df -h /data | tail -1"}, nil) if err != nil { panic(err) } fmt.Print(r.Stdout) } ``` **CLI** ```bash sandal volumes list # every volume of the project, attached or not sandal volumes delete # erase a detached volume (irreversible) sandal volumes erasure # state of that erasure ``` ## Detach, move, erase - `sandboxes.detachVolume(sandboxId, { volumeId })` detaches it (the sandbox must be stopped); `sandboxes.reattachVolume(otherSandboxId, { volumeId })` attaches the same volume to another stopped sandbox. - A volume whose sandbox was deleted (detached first or not) stays in the project list as `available` with `sandboxDeleted: true` until you erase it: `sandal volumes delete ` or the Console's Storage page. Erasure takes a few seconds. - The project list is `sandboxes.listProjectVolumes` (TypeScript `sandal.raw.sandbox.sandboxes.sandboxesListProjectVolumes(...)`, Python `sandal.sandboxes.list_project_volumes(...)`). ## Speed Measured on production (November 2026): attach a new 1 GiB volume 7-9 s, start with it 6-7 s, detach about 14 s, reattach to another sandbox about 7 s, erase under 8 s. ## Not yet available Volume snapshots and restore (`volume-snapshots` in `sandal capabilities` reads unavailable). --- # Auto-stop and auto-pause > Stop idle sandboxes automatically, and (where enabled) wake them again on the next API call or preview request with their disk kept. Source: https://sandal.dev/docs/auto-pause **Auto-stop** stops a sandbox after it has been idle for a while (`autoStopAfterSeconds`); its disk is kept and `start` boots it again. **Auto-pause** adds `autoResume: true`: the next API call (exec, files, ...) or authenticated preview request wakes it without an explicit `start`. > **Auto-pause is enabled per project during the beta:** > In a project without it, a create or lifecycle update with `autoResume: true` is refused with `capability_unavailable` (feature `auto-resume`): "Wake on traffic (autoResume) is not yet available in this project." Nothing is created. Leave `autoResume` out (the sandbox then stays stopped until you start it) or [ask us](mailto:hello@sandal.dev) to enable it. Auto-stop alone works in every project. ## What wakes a sandbox | Traffic | Wakes it | | --- | --- | | API calls on the sandbox (exec, files, processes, ...) | yes | | Authenticated requests to an exposed preview URL | yes | | SSH | no (start it first: `sandal start `) | ## Create with auto-stop and auto-pause **TypeScript** ```ts import { Sandal, SandalApiError } from "@sandal-dev/sdk"; const sandal = Sandal.fromEnv(); try { const sb = await sandal.createSandbox({ autoStopAfterSeconds: 600, autoResume: true, ttlSeconds: 24 * 3600 }); console.log("auto-pause on", sb.id); } catch (error) { if (error instanceof SandalApiError && error.code === "capability_unavailable" && error.details.feature === "auto-resume") { const sb = await sandal.createSandbox({ autoStopAfterSeconds: 600, ttlSeconds: 24 * 3600 }); // auto-stop only console.log("auto-pause not enabled in this project; auto-stop only", sb.id); } else throw error; } ``` **Python** ```python import asyncio from sandal import Sandal, SandalApiError async def main(): async with Sandal.from_env() as sandal: try: sb = await sandal.create_sandbox(auto_stop_after_seconds=600, auto_resume=True, lifetime_seconds=86400) except SandalApiError as error: if error.code != "capability_unavailable": raise sb = await sandal.create_sandbox(auto_stop_after_seconds=600, lifetime_seconds=86400) # auto-stop only print(sb.id) asyncio.run(main()) ``` **Go** ```go package main import ( "context" "errors" "fmt" "time" sandal "sandal.dev/go" ) func main() { ctx := context.Background() client, err := sandal.NewSandalFromEnv(sandal.SandalEnvOptions{}) if err != nil { panic(err) } wake := true options := sandal.SandalCreateSandboxOptions{AutoStopAfter: 10 * time.Minute, AutoResume: &wake, Lifetime: 24 * time.Hour} sb, err := client.CreateSandbox(ctx, options) var api *sandal.SandalAPIError if errors.As(err, &api) && api.Code == "capability_unavailable" { options.AutoResume = nil // auto-stop only sb, err = client.CreateSandbox(ctx, options) } if err != nil { panic(err) } fmt.Println(sb.ID) } ``` **CLI** ```bash sandal create --auto-stop 10m --auto-resume --name idle-ok # in a project without auto-pause: exit 7, "Wake on traffic (autoResume) is not yet available in this project." sandal lifecycle set --auto-stop 30m --auto-resume on sandal lifecycle defaults --auto-stop 30m # project default for new sandboxes ``` ## Memory and processes - `pause` / `resume` keep memory and running processes on the same sandbox (pause about 0.7-1 s, resume about 1-2.5 s on production). - A stopped sandbox, including one stopped by auto-stop, boots from its disk: memory and running processes are gone. There are no memory snapshots. Treat in-memory state as a speed-up, not as durable storage: write what matters to disk or a [volume](https://sandal.dev/docs/volumes). - Forks and restores from a snapshot are disk-level ([Snapshots & forks](https://sandal.dev/docs/snapshots-and-forks)). --- # Bring your own egress > Send a sandbox's outbound traffic through your own proxy, WireGuard peer, Tailscale exit node or a dedicated IP, with a kill switch. Source: https://sandal.dev/docs/egress By default a sandbox's outbound traffic leaves through Sandal's shared egress. **Bring-your-own egress** routes all of it through an exit you control instead, so websites and APIs see your address: | Exit | You provide | Stored as | | --- | --- | --- | | HTTP / SOCKS5 proxy | `http://user:pass@host:port` (or `socks5://...`) | a project secret | | WireGuard | a full-tunnel `wg-quick` config | a project secret | | Tailscale exit node | an OAuth client (or auth key) + the exit node's name or IP | a project secret | | Dedicated IP | nothing: one exclusive static IP for the whole project (country, optionally city) | - | **Kill switch:** while the exit is down, nothing leaves the sandbox, and never through Sandal's own address. Exec, files and ports keep working. `sandal egress ` shows the exit, its state and the measured exit IP. > **Enabled per project during the beta:** > Each exit kind is switched on per project. Elsewhere a create or update with that exit answers `capability_unavailable`; nothing is created. [Ask us](mailto:hello@sandal.dev) to enable it. ## Connect once (project default) The quickest path: make an exit the **project default**. Every sandbox created afterwards without its own exit leaves through it; existing sandboxes keep theirs, and a create can opt out (`sandal create --no-egress-default`, `egressDefault: "skip"` in the SDKs). ```bash # Tailscale, in one step: checks the OAuth client, stores it sealed on this machine, sets the project default printf '%s\n%s\n' "$TS_OAUTH_CLIENT_ID" "$TS_OAUTH_CLIENT_SECRET" | sandal egress tailscale connect --exit-node my-exit-node # Or any exit kind printf %s 'http://user:pass@proxy.example:8080' | sandal secrets create my-proxy --value-stdin sandal egress default set --egress-proxy my-proxy sandal egress default # show it sandal egress default clear # back to Sandal's shared egress for new sandboxes ``` For Tailscale, create the OAuth client in the Tailscale admin console (Settings, OAuth clients) with scope `auth_keys` (write) and the tag (default `tag:sandal-sandbox`), plus `devices:core` (read) if Sandal should check the exit node. The tag needs `tagOwners` and one grant to `autogroup:internet`. Each sandbox joins your tailnet as its own ephemeral tagged node. ## Per sandbox **TypeScript** ```ts import { Sandal } from "@sandal-dev/sdk"; const sandal = Sandal.fromEnv(); // secretId/version of a project secret that holds http://user:pass@host:port (sandal secrets create ...) const sb = await sandal.createSandbox({ name: "via-my-proxy", egress: { proxy: { type: "http", urlRef: { secretId: process.env.PROXY_SECRET_ID!, version: "1" } } }, }); console.log(await sandal.sandboxes.getEgress(sb.id)); // exit, state, measured exit IP console.log((await sb.exec(["curl", "-s", "https://ifconfig.me"])).stdout); ``` **Python** ```python import asyncio, os from sandal import Sandal async def main(): async with Sandal.from_env() as sandal: sb = await sandal.create_sandbox( name="via-my-proxy", egress={"proxy": {"type": "http", "urlRef": {"secretId": os.environ["PROXY_SECRET_ID"], "version": "1"}}}, ) print(await sandal.sandboxes.get_egress(sb.id)) print((await sb.exec(["curl", "-s", "https://ifconfig.me"])).stdout) asyncio.run(main()) ``` **Go** ```go package main import ( "context" "fmt" "os" "time" sandal "sandal.dev/go" ) func main() { ctx := context.Background() client, err := sandal.NewSandalFromEnv(sandal.SandalEnvOptions{}) if err != nil { panic(err) } proxy := sandal.NewSandboxEgressProxy("http", *sandal.NewSandboxEgressSecretReference(os.Getenv("PROXY_SECRET_ID"), "1")) sb, err := client.CreateSandbox(ctx, sandal.SandalCreateSandboxOptions{Lifetime: time.Hour, Egress: &sandal.SandboxEgressInput{Proxy: proxy}}) if err != nil { panic(err) } r, err := sb.Exec(ctx, []string{"curl", "-s", "https://ifconfig.me"}, nil) if err != nil { panic(err) } fmt.Println(r.Stdout) } ``` **CLI** ```bash sandal create --name via-my-proxy --egress-proxy my-proxy # http CONNECT; --egress-proxy-type socks5 sandal create --name via-wg --egress-wireguard my-wg-config sandal create --name via-ts --egress-tailscale my-ts-key --egress-exit-node my-exit-node sandal create --name via-dedicated --egress-dedicated-ip us/new_york # or a country code, or auto sandal egress set --egress-proxy my-proxy # switch a running sandbox in place sandal egress --events # exit, state, exit IP and recent events sandal egress clear ``` ## Notes - Secrets are referenced, never sent in clear: the CLI seals them on your machine before upload. - A dedicated IP is exclusive to your project and stays the same for every sandbox that uses it; the first use picks it from the country (and city) you name. ## When an exit is refused The sandbox keeps its kill switch (no traffic leaves another way) and `sandal egress ` shows `failed` with a code: | `failureCode` | Meaning | | --- | --- | | `egress.invalid-upstream` | The exit itself is not acceptable: a malformed proxy URL or WireGuard file, or (from API 13.59) a WireGuard `Endpoint` or a Tailscale login server on a private, link-local, cloud-metadata, CGNAT or loopback address, or a local-only name (`.local`, `.internal`, `.lan`, a single label). Point it at a public address or name. | | `egress.secret-unavailable` | The secret the exit references cannot be read in this project (deleted, or a different project). | | `egress.proxy-type-mismatch` | `--egress-proxy-type` does not match the stored URL's scheme. | | `egress.tailscale-key-unavailable` | The Tailscale credential could not mint a key for this sandbox. | | `egress.tailscale-oauth-requires-saas` | A Tailscale OAuth client works with Tailscale's own control server only; use an auth key for Headscale. | | `egress.dedicated-ip-unavailable` / `-exhausted` / `-limit` | Dedicated IPs are not enabled for the organization, none is free in that location, or the organization's IP limit is reached. | The gateway checks the exit again when it connects (it resolves names then), so a name that later resolves to a private address is refused too. --- # Share links > Show a server running in a sandbox to someone without an API key: a time-bounded, optionally single-use link you can revoke, from one command. Source: https://sandal.dev/docs/sharing A sandbox port is **private** by default: its preview URL needs your API key (or a short-lived access token). A **share link** is for a person without a key: they open it in a browser and see the port, until the link expires or you revoke it. ```bash sandal exec --detach -- python3 -m http.server 8000 sandal share 8000 # a link for one hour sandal share 8000 --ttl 30m --single-use ``` ```text https://api.sandal.dev/v1/share/… exposure: sandbox-port.1dd6… expires: 2026-11-27T04:50:29.349Z share-link: shl_ed74… ``` `sandal share` exposes the port first if it is not exposed yet (the same as `sandal ports expose --share`), then prints the link. | Option | Meaning | | --- | --- | | `--ttl` | Link lifetime, 1 minute to 24 hours (default 1 hour), never longer than the port exposure | | `--single-use` | Only the first person who confirms the link gets in | | `--protocol tcp` | For TCP ports (and servers without share links) you get a one-browser token link instead (`?sandal_token=`, at most 1 hour) | ## List and revoke ```bash sandal share ls # ID, STATE, USE, OPENS, LAST OPENED, EXPIRES sandal share revoke # the link answers 410 Gone from now on sandal share token # a one-browser link with an access token ``` Revoking a link stops new visits within seconds. A browser that already opened it keeps its session until that session ends, which can take up to an hour. To cut off people who already opened the link, revoke the port exposure (`sandal ports revoke`): that ends every session at once. ## From the SDKs `share(port)` exposes the port and returns the link (`url`), in TypeScript `sb.share(8000)`, Python `await sb.share(8000)` and Go `sb.Share(ctx, 8000, sandal.SandalExposeOptions{})`; the [quickstart](https://sandal.dev/docs/quickstart) runs all three. ## Limits today - Links last at most 24 hours; there are no permanent public ports and no custom domains yet. - A link opens HTTP ports in a browser. API clients should use the private preview URL with the API key instead. > **Verified:** > Run against production on November 27, 2026 with the `0.1.0-beta.12` CLI: the link opened (HTTP 200) in 0.7-1.7 s from another network, `share ls` listed it, and after `share revoke` it answered 410. Re-checked on November 28, 2026: new opens answered 410 within about 1.3 s of the revoke, a browser session opened before it still worked a minute later, and revoking the port exposure ended that session in under a second. --- # Secrets > Project secrets, delivered to a sandbox as an environment value or brokered: the sandbox sees a placeholder and Sandal adds the real key only to HTTPS requests to the hosts you allow (preview). Source: https://sandal.dev/docs/secrets A **secret** is a value your sandboxes need but you do not want in code: an API key, a token, a password. Secrets belong to a project, are sealed before they leave your machine, and are versioned. A sandbox gets a secret **by reference** at create time, in one of two ways: | Delivery | What the sandbox sees | Good for | Status | | --- | --- | --- | --- | | `environment` | The real value, in an environment variable | Any secret: database passwords, SSH keys, tokens your code reads | Available | | `brokered` | A placeholder (`sdl_ph_…`) in the variable. Sandal adds the real value only to HTTPS requests to the secret's hosts | HTTP API keys you do not want an agent to be able to read or leak | Preview | > **Brokered delivery is in preview:** > The sandbox only ever holds a placeholder; Sandal adds the real value to HTTPS requests to the secret's hosts once `secretBrokering` is `active`. A sandbox can be `running` some seconds before that (about 6-25 s in our measurements). From `0.1.0-beta.13` the CLI and SDKs wait for it when they create the sandbox, so the sandbox you get back is normally already `active` ([details below](#creating-waits-for-brokering)). Whenever the state is `pending` or `unavailable`, requests carry the placeholder. Make the first request to a credential host only after `active` ([why](#wait-for-active-before-the-first-request)). ## Create a secret The value comes from standard input or a file, never from an argument: ```bash # an HTTP credential for a known provider: brokered by default printf '%s' "$OPENAI_API_KEY" | sandal secrets create openai --value-stdin --preset openai # any HTTPS API: name the host and how the key is sent printf '%s' "$MY_API_KEY" | sandal secrets create my-api --value-stdin \ --host api.example.com --header Authorization --format 'Bearer {}' # a value your code reads from the environment printf '%s' "$DB_PASSWORD" | sandal secrets create db-password --value-stdin --delivery environment sandal secrets ls # ID, NAME, TYPE, VERSION, DELIVERY, LAST USED (never the value) sandal secrets presets # anthropic, openai, openrouter, gemini, github, github-git, gitlab, huggingface, npm, pypi, dockerhub ``` An HTTP credential (`--preset` or `--host`) is brokered only, unless you add `--env-allowed`. A secret without hosts is delivered as an environment value. `sandal secrets rotate --value-stdin --expected-version ` writes a new version (`n` is the current one, so two rotations cannot race); `sandal secrets show ` lists versions and hosts, `sandal secrets events ` its audit trail. ## Give it to a sandbox Pass `--secret NAME=` with the delivery you want. Without `@version`, the sandbox gets the secret's current version; `NAME=sec_…@2` pins one. ```bash sandal create --secret OPENAI_API_KEY=sec_...:brokered # placeholder in the sandbox sandal create --secret DB_PASSWORD=sec_...:environment # the value in the sandbox ``` Then ask how the sandbox's secrets are delivered: ```bash sandal secrets status ``` ```text sandbox: sandbox.d0f4… secrets: environment (1 ref, not brokered) names: DB_PASSWORD message: This Sandbox's secrets are delivered as environment values; none is brokered. ``` For a sandbox with brokered secrets, `sandal secrets status` and `sandal get` also list each secret's state: ```text secrets: brokered - active for 1 of 2 (B unavailable: requests carry the placeholder) names: A, B SECRET STATE SINCE A active 2026-11-29T15:37:01.078Z B unavailable 2026-11-29T15:37:10.197Z ``` `sandal get ` shows the same in its `secrets:` row. In the SDKs the sandbox carries it as `secretBrokering` (`state`, `reason`, `message`, and the state of each brokered secret). ## Creating waits for brokering A new sandbox's brokered secrets can go live some seconds after it starts. `sandal create` and the SDKs' create calls (`createSandbox()`, `create_sandbox()`, `CreateSandbox()`) wait until brokering is no longer `pending`, for at most 60 s; from `0.1.0-beta.16` every other wait does too (a create that did not wait followed by `waitUntilRunning()`, the operation wait, the jobs and commands helpers). In our run on November 29, 2026 a create with two brokered secrets returned in about 22 s, with both `active`. What you get back: - `active`: you get the sandbox as usual, ready to use. - `unavailable`, or still `pending` after 60 s: you still get the sandbox, with a warning that names each secret that is not active and carries the server's reason (CLI: a `secrets: warning:` line on stderr; TypeScript: a `SandalSecretBrokeringWarning` process warning; Python: a `SandalSecretBrokeringWarning` warning; Go: `SecretBrokeringWarning` on the sandbox). Requests carry the placeholder until it turns `active`. Opt out with `--no-wait-secrets`, `waitForSecretBrokering: false`, `wait_for_secret_brokering=False` or `NoSecretBrokeringWait: true`; you can wait later on the handle with `waitForSecretBrokering()` / `wait_for_secret_brokering()` / `WaitForSecretBrokering()`. Older clients return as soon as the sandbox is `running`: check `sandal secrets status` before you rely on brokering. ## Wait for active before the first request Send the first request to a secret's host only once `secretBrokering` is `active`. If a process in the sandbox looked up or connected to that host earlier, its requests keep going straight to the host with the placeholder, even after the state says `active`: the sandbox's DNS cache and that process's open connections still point at the host itself, not at the broker, until the cached answer expires (up to 5 minutes). If that happened, flush the sandbox's DNS cache first, on a template that allows root (`sandal exec --root -- resolvectl flush-caches`), then restart the process: a restart alone gets the same cached answer. Without root, wait until the cached answer expires (up to 5 minutes), then restart the process. A process that the sandbox's image starts at boot can call the host before brokering is active, so today it can race the broker: start such processes yourself after `active` instead. ## Brokering states | State | Meaning | | --- | --- | | `pending` | The broker is being set up for this sandbox. Requests still carry the placeholder | | `active` | The real value is added to HTTPS requests to the secret's hosts. Every other host sees the placeholder | | `unavailable` | Brokering stopped or cannot start. `reason` and `message` say why, for example `broker.grant-revoked` after the secret was revoked or destroyed | There is no state for environment-only sandboxes; `secrets status` says `environment` instead. Each brokered secret also has its own state: after you revoke one of two brokered secrets, the sandbox says `active for 1 of 2` and names the revoked one as `unavailable` (the other one is still injected). ## What brokering does, and what it does not - **The key stays outside.** The sandbox's environment, processes and files hold only the placeholder. Sandal's broker terminates TLS for the secret's hosts only (the sandbox trusts a Sandal broker certificate for them) and substitutes the header, basic-auth or query value. Responses are scrubbed of the real value. - **Only the hosts you allow.** Up to 16 hosts per secret, exact names or `*.` wildcards, never IP addresses. A request to any other host carries the placeholder. - **Revoking is fast.** `sandal secrets revoke ` stops injection within about 10 seconds; requests then carry the placeholder. Deleting the secret (`sandal secrets rm --destroy`) makes requests that need it fail; they do not fall back to anything. - **HTTP(S) only.** SSH keys, database passwords and other non-HTTP secrets use `environment` delivery. - **HTTP/3 falls back.** UDP 443 (QUIC) to a brokered host is dropped, so clients use HTTP/2 or HTTP/1.1 over TCP. - **No per-request log yet.** The broker keeps counters, and `sandal secrets events ` shows a secret's lifecycle and delivery events, but there is no per-request audit or network log. - **Forks inherit.** A fork gets the same brokered secrets as its source. ## Clean up ```bash sandal secrets revoke # stop live grants now sandal secrets rm # destroyed after 24 h sandal secrets rm --destroy # destroyed now ``` > **Verified:** > The commands on this page were run against production on November 27, 2026 with the `0.1.0-beta.12` CLI. The environment sandbox received its value. Brokered injection was verified on the same day: the real value reached the bound host, the sandbox held only the placeholder, and `secretBrokering` turned `active` about 7-25 s after the sandbox was `running`. On November 28, 2026 the `0.1.0-beta.13` TypeScript SDK and CLI returned a brokered sandbox only once it was `active` (about 21 s after the create started), and the first request from it reached the bound host with the real value. Re-checked on November 28, 2026 on the default template and the [root + FUSE preview](https://sandal.dev/docs/root-and-fuse): with the first request after `active`, the real value arrived every time; a request sent about 1 s after `running` carried the placeholder, and kept doing so after `active` until a fresh DNS lookup. On November 29, 2026 the `0.1.0-beta.16` CLI showed the per-secret table above: both secrets `active` when the create returned, and the revoked one `unavailable` within the 15 s we waited after the revoke. --- # Integrations > Use Sandal as the code-execution tool of your agent framework: OpenAI Agents SDK, Claude Agent SDK, LangChain / LangGraph, Vercel AI SDK, and MCP clients. Source: https://sandal.dev/docs/integrations Every integration is the same idea: create one sandbox per agent run, give the agent a tool that writes code into it and runs it, delete the sandbox at the end. Nothing the agent runs touches your machine. - [OpenAI Agents SDK](/docs/integration-openai-agents): function_tool backed by a sandbox (Python). - [Claude Agent SDK](/docs/integration-claude-agent-sdk): In-process MCP tool, built-in tools off (TypeScript). - [LangChain and LangGraph](/docs/integration-langchain): @tool for any chat model or LangGraph agent (Python). - [Vercel AI SDK](/docs/integration-vercel-ai): tool() for generateText / streamText (TypeScript). ## MCP clients (Claude Code, Cursor, Codex) The CLI ships `sandal-mcp`, an MCP server with tools for sandboxes, files, commands and previews. It runs **locally only** today (stdio, or HTTP on loopback); there is no hosted MCP URL and no OAuth yet, so web chat apps that only take remote MCP servers cannot use it. Setup: [MCP server](https://sandal.dev/docs/mcp). ## Coding agents Give a coding agent the [agent guide](https://sandal.dev/docs/agents) (also at [`/SKILL.md`](https://sandal.dev/SKILL.md)) and it can drive the CLI itself. --- # OpenAI Agents SDK > Give an OpenAI Agents SDK agent a Sandal sandbox as its code-execution tool (Python). Source: https://sandal.dev/docs/integration-openai-agents The agent gets one tool, `run_python`, and every call runs in the same isolated sandbox, so files and installed packages persist between calls for the length of the run. The sandbox is deleted when the `async with` block ends. Install the Sandal SDK from your [beta bundle](https://sandal.dev/docs/quickstart#1-install) and sign in once with `sandal login` (the SDK reads that profile), or set `SANDAL_API_KEY` (the key alone is enough). ```bash pip install openai-agents # plus the sandal-sdk wheel from your bundle ``` ```python title="agent.py" import asyncio from agents import Agent, Runner, function_tool from sandal import Sandal async def main() -> None: sandal = Sandal() # the `sandal login` profile, or the SANDAL_* variables try: async with await sandal.create_sandbox() as sb: # one sandbox per agent run, deleted at the end @function_tool async def run_python(code: str) -> str: """Run Python 3 code in an isolated Sandal sandbox and return its exit code and output.""" await sb.write_text("/workspace/main.py", code) result = await sb.exec("python3 /workspace/main.py") return f"exit {result.exit_code}\n{result.stdout}{result.stderr}" agent = Agent( name="Coder", instructions="Answer by writing and running Python with the run_python tool.", tools=[run_python], ) result = await Runner.run(agent, "What is the 30th Fibonacci number? Compute it.") print(result.final_output) finally: await sandal.close() asyncio.run(main()) ``` Run it with `OPENAI_API_KEY` set: `python agent.py`. Verified against Sandal CLI/SDK `0.1.0-beta.10` on 2026-11-25: the tool was called directly and ran `print(sum(range(10)))` in a real sandbox (`exit 0`, `45`). The model call itself needs your own model provider key. Tested with `openai-agents` 0.26.0. --- # Claude Agent SDK > Run a Claude Agent SDK agent whose code runs in a Sandal sandbox instead of on your machine (TypeScript). Source: https://sandal.dev/docs/integration-claude-agent-sdk The Claude Agent SDK runs Claude Code as a library, with built-in Bash and file tools that act on the machine it runs on. To run the agent's code in an isolated sandbox instead, give it a Sandal tool through an in-process MCP server and turn the built-in tools off (`tools: []`). Install the Sandal SDK from your [beta bundle](https://sandal.dev/docs/quickstart#1-install) and sign in once with `sandal login` (the SDK reads that profile), or set `SANDAL_API_KEY` (the key alone is enough). ```bash npm install @anthropic-ai/claude-agent-sdk zod # plus the Sandal SDK (see above) ``` ```ts title="agent.mjs" import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk"; import { Sandal } from "@sandal-dev/sdk"; import { z } from "zod"; const sandal = new Sandal(); // the `sandal login` profile, or the SANDAL_* variables const sb = await sandal.createSandbox(); const runPython = tool( "run_python", "Run Python 3 code in an isolated Sandal sandbox and return its exit code and output.", { code: z.string() }, async ({ code }) => { await sb.writeText("/workspace/main.py", code); const r = await sb.exec("python3 /workspace/main.py"); return { content: [{ type: "text", text: `exit ${r.exitCode}\n${r.stdout}${r.stderr}` }] }; }, ); const sandalTools = createSdkMcpServer({ name: "sandal", version: "1.0.0", tools: [runPython] }); try { for await (const message of query({ prompt: "What is the 30th Fibonacci number? Compute it with run_python.", options: { mcpServers: { sandal: sandalTools }, allowedTools: ["mcp__sandal__run_python"], tools: [], // no built-in Bash/Read/Write: code runs only in the sandbox }, })) { if (message.type === "result" && message.subtype === "success") console.log(message.result); } } finally { await sb.delete(); } ``` Run it with `ANTHROPIC_API_KEY` set: `node agent.mjs`. Verified against Sandal CLI/SDK `0.1.0-beta.10` on 2026-11-25: the tool was called directly and ran `print(sum(range(10)))` in a real sandbox (`exit 0`, `45`). The model call itself needs your own model provider key. Tested with `@anthropic-ai/claude-agent-sdk` 0.3.332 and `zod` 4. The Sandal MCP server `sandal-mcp` (from the CLI) can also be added to Claude Code itself; it runs locally over stdio, see [MCP server](https://sandal.dev/docs/mcp). --- # LangChain and LangGraph > A Sandal sandbox as a LangChain tool, for LangChain agents and LangGraph graphs (Python). Source: https://sandal.dev/docs/integration-langchain A LangChain `@tool` that runs code in one Sandal sandbox. Bind it to any chat model or pass it to a LangGraph agent. Install the Sandal SDK from your [beta bundle](https://sandal.dev/docs/quickstart#1-install) and sign in once with `sandal login` (the SDK reads that profile), or set `SANDAL_API_KEY` (the key alone is enough). ```bash pip install langchain-core langgraph # plus the Sandal SDK (see above) ``` ```python title="sandal_tool.py" from langchain_core.tools import tool from sandal import SandalSync sandal = SandalSync() # the `sandal login` profile, or the SANDAL_* variables sb = sandal.create_sandbox() @tool def run_python(code: str) -> str: """Run Python 3 code in an isolated Sandal sandbox and return its exit code and output.""" sb.write_text("/workspace/main.py", code) result = sb.exec("python3 /workspace/main.py") return f"exit {result.exit_code}\n{result.stdout}{result.stderr}" # Bind it to any chat model, e.g. with LangGraph: # from langgraph.prebuilt import create_react_agent # agent = create_react_agent(model, tools=[run_python]) # agent.invoke({"messages": [("user", "What is the 30th Fibonacci number? Compute it.")]}) print(run_python.invoke({"code": "print(sum(range(10)))"})) sb.delete() sandal.close() ``` Verified against Sandal CLI/SDK `0.1.0-beta.10` on 2026-11-25: the tool was called directly and ran `print(sum(range(10)))` in a real sandbox (`exit 0`, `45`). The model call itself needs your own model provider key. Tested with `langchain-core` 1.8.5. --- # Vercel AI SDK > A Sandal sandbox as an AI SDK tool for generateText / streamText agents (TypeScript). Source: https://sandal.dev/docs/integration-vercel-ai An AI SDK `tool()` that runs code in one Sandal sandbox; `stopWhen` lets the model call it several times. Install the Sandal SDK from your [beta bundle](https://sandal.dev/docs/quickstart#1-install) and sign in once with `sandal login` (the SDK reads that profile), or set `SANDAL_API_KEY` (the key alone is enough). ```bash npm install ai zod # plus the Sandal SDK (see above) ``` ```ts title="agent.mjs" import { generateText, stepCountIs, tool } from "ai"; import { Sandal } from "@sandal-dev/sdk"; import { z } from "zod"; const sandal = new Sandal(); // the `sandal login` profile, or the SANDAL_* variables const sb = await sandal.createSandbox(); const runPython = tool({ description: "Run Python 3 code in an isolated Sandal sandbox and return its exit code and output.", inputSchema: z.object({ code: z.string() }), execute: async ({ code }) => { await sb.writeText("/workspace/main.py", code); const r = await sb.exec("python3 /workspace/main.py"); return { exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr }; }, }); try { const { text } = await generateText({ model: "openai/gpt-5", // any AI SDK model; a provider string uses the AI Gateway tools: { run_python: runPython }, stopWhen: stepCountIs(5), prompt: "What is the 30th Fibonacci number? Compute it with run_python.", }); console.log(text); } finally { await sb.delete(); } ``` Verified against Sandal CLI/SDK `0.1.0-beta.10` on 2026-11-25: the tool was called directly and ran `print(sum(range(10)))` in a real sandbox (`exit 0`, `45`). The model call itself needs your own model provider key. Tested with `ai` 7.0.182 and `zod` 4. --- # Migrate from E2B > Move an E2B sandbox integration to Sandal: call-by-call mapping (TypeScript), a before/after, and what Sandal does not have yet. Source: https://sandal.dev/docs/migrate-from-e2b E2B and Sandal both give each sandbox its own microVM, so most code moves one call at a time. The biggest differences: a Sandal create needs no template (the project default is used), and a preview URL is either keyed (`expose`) or a share link (`share`). > **Compare first:** > Feature by feature and on price: [Sandal vs E2B](https://sandal.dev/compare/e2b). ## 1. Install and sign in Follow the [quickstart](https://sandal.dev/docs/quickstart) steps 1 and 2: install the CLI and SDK, then `sandal login`. The SDKs read that profile; in CI set `SANDAL_API_KEY` (the key alone is enough; organization and project ids are optional overrides). ## 2. API mapping | E2B | Sandal | | --- | --- | | `Sandbox.create()` / `Sandbox.create("tpl")` | `sandal.createSandbox()` / `createSandbox({ template })` | | `Sandbox.connect(id)` | `sandal.sandbox(id)` | | `sandbox.commands.run(cmd)` | `sb.exec(cmd)` (`exitCode`, `stdout`, `stderr`) | | `commands.run(cmd, { background: true })` | `sb.startCommand(cmd)` | | `sandbox.files.write(path, data)` / `files.read(path)` | `sb.writeText(path, text)` / `sb.readText(path)` (`writeBytes` / `readBytes` for binary) | | `sandbox.getHost(port)` | `sb.expose(port)` (needs your key) or `sb.share(port)` (link, no key) | | `sandbox.betaPause()` / resume on connect | `sb.pause()` / `sb.resume()` | | `sandbox.setTimeout(ms)` | `sb.extend(...)` (CLI: `sandal extend --for 12h`) | | `sandbox.kill()` | `sb.delete()` | | `e2b template build` | template builds (`sandal templates build`) or a setup script (`sandal create --setup-file`) | | Code Interpreter `runCode()` (Jupyter kernel) | `sb.exec("python3 script.py")`, or the [code interpreter](https://sandal.dev/docs/code-interpreter) with persistent contexts on projects that have it enabled | ## 3. Before and after **Before** ```ts import { Sandbox } from "e2b"; const sandbox = await Sandbox.create(); try { await sandbox.files.write("/home/user/main.py", "print(6 * 7)"); const r = await sandbox.commands.run("python3 /home/user/main.py"); console.log(r.exitCode, r.stdout); await sandbox.commands.run("python3 -m http.server 8000", { background: true }); console.log("https://" + sandbox.getHost(8000)); } finally { await sandbox.kill(); } ``` **After** ```ts import { Sandal } from "@sandal-dev/sdk"; const sandal = new Sandal(); const sb = await sandal.createSandbox(); try { await sb.writeText("/workspace/main.py", "print(6 * 7)"); const r = await sb.exec("python3 /workspace/main.py"); console.log(r.exitCode, r.stdout); await sb.startCommand("python3 -m http.server 8000"); console.log((await sb.share(8000)).url); } finally { await sb.delete(); } ``` The working directory is `/workspace` (E2B: `/home/user`). Python: the same names in snake_case (`create_sandbox`, `write_text`, `start_command`), see the [Python SDK](https://sandal.dev/docs/sdk-python). ## What Sandal does not have yet Said plainly, so you can plan around it (no dates promised): - **Root in the guest.** On the default template commands run as uid 2000 without `sudo`; exec as root (`sandal exec --root`, `user: "root"`) is refused with `422 capability_unavailable`. A [root + FUSE template](https://sandal.dev/docs/root-and-fuse) is in preview; no root-capable template is generally offered yet. - **FUSE and S3 mounts.** The default template has no `/dev/fuse`, so `s3fs` / `mountpoint-s3` cannot run there, and there is no native bucket mount. Use [persistent volumes](https://sandal.dev/docs/volumes) or copy objects in and out, or ask for the [root + FUSE preview template](https://sandal.dev/docs/root-and-fuse). - **Memory snapshots.** Not offered: pause/resume keeps memory on the same sandbox only; snapshots and forks are disk-only. - **Region choice.** Sandal runs in the EU only (Germany, Finland, Luxembourg). - **Outbound IPv6.** IPv4 only today. - **Volume snapshots** and **OpenTelemetry export** are not offered yet. --- # Migrate from Daytona > Move a Daytona sandbox integration to Sandal: call-by-call mapping (TypeScript), a before/after, and what Sandal does not have yet. Source: https://sandal.dev/docs/migrate-from-daytona Daytona sandboxes and Sandal sandboxes have the same lifecycle (create, run, stop/start, archive, delete), so the move is mostly renaming. Sandal runs each sandbox as a microVM with its own kernel. > **Compare first:** > Feature by feature and on price: [Sandal vs Daytona](https://sandal.dev/compare/daytona). ## 1. Install and sign in Follow the [quickstart](https://sandal.dev/docs/quickstart) steps 1 and 2: install the CLI and SDK, then `sandal login`. The SDKs read that profile; in CI set `SANDAL_API_KEY` (the key alone is enough; organization and project ids are optional overrides). ## 2. API mapping | Daytona | Sandal | | --- | --- | | `new Daytona()` | `new Sandal()` | | `daytona.create()` / `create({ snapshot })` | `sandal.createSandbox()` / `createSandbox({ template })` | | `daytona.get(id)` | `sandal.sandbox(id)` | | `sandbox.process.executeCommand(cmd)` | `sb.exec(cmd)` (`exitCode`, `stdout`, `stderr`) | | `sandbox.process.codeRun(code)` | `sb.writeText(path, code)` + `sb.exec("python3 " + path)` | | sessions / async commands | `sb.startCommand(cmd)`; CLI `sandal exec --detach` + `exec logs|wait|kill` | | `sandbox.fs.uploadFile(buf, path)` / `downloadFile(path)` | `sb.writeBytes(path, data)` / `sb.readBytes(path)`; `sb.push(dir)` for a folder | | `sandbox.getPreviewLink(port)` | `sb.expose(port)` (needs your key) or `sb.share(port)` (link, no key) | | `sandbox.stop()` / `start()` / `archive()` | `sb.stop()` / `sb.start()` / `sb.archive()` | | `sandbox.delete()` | `sb.delete()` | | `sandbox.git.clone(url, path)` | environments with repositories (`sandal env add-repo`) or `sandal git clone` | ## 3. Before and after **Before** ```ts import { Daytona } from "@daytonaio/sdk"; const daytona = new Daytona(); const sandbox = await daytona.create(); try { await sandbox.fs.uploadFile(Buffer.from("print(6 * 7)"), "main.py"); const r = await sandbox.process.executeCommand("python3 main.py"); console.log(r.exitCode, r.result); await sandbox.process.executeCommand("nohup python3 -m http.server 8000 &"); console.log((await sandbox.getPreviewLink(8000)).url); } finally { await sandbox.delete(); } ``` **After** ```ts import { Sandal } from "@sandal-dev/sdk"; const sandal = new Sandal(); const sb = await sandal.createSandbox(); try { await sb.writeText("/workspace/main.py", "print(6 * 7)"); const r = await sb.exec("python3 /workspace/main.py"); console.log(r.exitCode, r.stdout); await sb.startCommand("python3 -m http.server 8000"); console.log((await sb.share(8000)).url); } finally { await sb.delete(); } ``` ## What Sandal does not have yet Said plainly, so you can plan around it (no dates promised): - **Root in the guest.** On the default template commands run as uid 2000 without `sudo`; exec as root (`sandal exec --root`, `user: "root"`) is refused with `422 capability_unavailable`. A [root + FUSE template](https://sandal.dev/docs/root-and-fuse) is in preview; no root-capable template is generally offered yet. - **FUSE and S3 mounts.** The default template has no `/dev/fuse`, so `s3fs` / `mountpoint-s3` cannot run there, and there is no native bucket mount. Use [persistent volumes](https://sandal.dev/docs/volumes) or copy objects in and out, or ask for the [root + FUSE preview template](https://sandal.dev/docs/root-and-fuse). - **Memory snapshots.** Not offered: pause/resume keeps memory on the same sandbox only; snapshots and forks are disk-only. - **Region choice.** Sandal runs in the EU only (Germany, Finland, Luxembourg). - **Outbound IPv6.** IPv4 only today. - **Volume snapshots** and **OpenTelemetry export** are not offered yet. --- # Migrate from Modal > Move Modal Sandboxes to Sandal: call-by-call mapping (Python), a before/after, and what Sandal does not have yet. Source: https://sandal.dev/docs/migrate-from-modal Modal Sandboxes are defined next to a Modal app and an image built in code. On Sandal there is no app object: a sandbox starts from the default template of your project (Debian with Python 3, Node.js and git), and you customise it with a setup script, an environment or a template build. Sandal has no GPUs. > **Compare first:** > Feature by feature and on price: [Sandal vs Modal](https://sandal.dev/compare/modal). ## 1. Install and sign in Follow the [quickstart](https://sandal.dev/docs/quickstart) steps 1 and 2: install the CLI and SDK, then `sandal login`. The SDKs read that profile; in CI set `SANDAL_API_KEY` (the key alone is enough; organization and project ids are optional overrides). ## 2. API mapping | Modal | Sandal | | --- | --- | | `modal.App.lookup(...)` + `modal.Sandbox.create(app=app, image=img)` | `await sandal.create_sandbox()` (no app; `template=` for a custom image) | | `modal.Image.debian_slim().pip_install(...)` | a setup script (`sandal create --setup-file setup.sh`), an environment (`sandal env`), or a template build | | `modal.Sandbox.from_id(id)` | `sandal.sandbox(id)` | | `sb.exec("python", "-c", code)` + `p.wait()` / `p.stdout.read()` | `await sb.exec(...)` returns `exit_code`, `stdout`, `stderr` when it ends | | a long-running `sb.exec(...)` | `await sb.start_command(cmd)`; CLI `sandal exec --detach` | | `sb.open(path, "w")` / `"r"` | `await sb.write_text(path, text)` / `await sb.read_text(path)` | | `encrypted_ports=[8000]` + `sb.tunnels()[8000].url` | `await sb.expose(8000)` (needs your key) or `await sb.share(8000)` (link, no key) | | `sb.snapshot_filesystem()` | `await sb.snapshot()` and `fork`, or `sandal snapshot save` + `sandal create --from ` | | `timeout=` | hard expiry on create (`--ttl`, CLI default 24 h) and `extend` | | `sb.terminate()` | `await sb.delete()` | | `gpu=...` | not offered | ## 3. Before and after **Before** ```python import modal app = modal.App.lookup("demo", create_if_missing=True) sb = modal.Sandbox.create(app=app, image=modal.Image.debian_slim(), encrypted_ports=[8000]) try: p = sb.exec("python", "-c", "print(6 * 7)") p.wait() print(p.returncode, p.stdout.read()) sb.exec("python", "-m", "http.server", "8000") print(sb.tunnels()[8000].url) finally: sb.terminate() ``` **After** ```python import asyncio from sandal import Sandal async def main() -> None: sandal = Sandal() try: async with await sandal.create_sandbox() as sb: r = await sb.exec("python3 -c 'print(6 * 7)'") print(r.exit_code, r.stdout) await sb.start_command("python3 -m http.server 8000") print((await sb.share(8000)).url) finally: await sandal.close() asyncio.run(main()) ``` A blocking client with the same methods is `SandalSync`, closer to the synchronous Modal style. ## What Sandal does not have yet Said plainly, so you can plan around it (no dates promised): - **Root in the guest.** On the default template commands run as uid 2000 without `sudo`; exec as root (`sandal exec --root`, `user="root"`) is refused with `422 capability_unavailable`. A [root + FUSE template](https://sandal.dev/docs/root-and-fuse) is in preview; no root-capable template is generally offered yet. - **FUSE and S3 mounts.** The default template has no `/dev/fuse`, so `s3fs` / `mountpoint-s3` cannot run there, and there is no native bucket mount. Use [persistent volumes](https://sandal.dev/docs/volumes) or copy objects in and out, or ask for the [root + FUSE preview template](https://sandal.dev/docs/root-and-fuse). - **Memory snapshots.** Not offered: pause/resume keeps memory on the same sandbox only; snapshots and forks are disk-only. - **Region choice.** Sandal runs in the EU only (Germany, Finland, Luxembourg). - **Outbound IPv6.** IPv4 only today. - **Volume snapshots** and **OpenTelemetry export** are not offered yet. --- # 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. Source: https://sandal.dev/docs/sdk-typescript ## Install Private beta: the package is not on npm yet. Install the tarball from your [beta bundle](https://sandal.dev/docs/quickstart#1-install): ```bash npm install ./sdk/sandal-typescript-v0.1.0-beta.16.tgz ``` > **Check the package name:** > `npm install sandal` and `npx sandal …` install an **unrelated third-party package**. Our packages are `@sandal-dev/cli` and `@sandal-dev/sdk`. ## Create the client ```ts 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 ```ts 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](https://sandal.dev/docs/sdk-typescript), [Python](https://sandal.dev/docs/sdk-python), [Go](https://sandal.dev/docs/sdk-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) accept `expectedRevision`. Both are optional: the SDK reads the current one and retries once on `revision_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: false` turns it off. - **Operations.** Create, lifecycle and fork return `{ sandbox, operation }` as soon as the request is admitted. Wait with `sandal.sandboxes.waitForOperation(operation.id, { timeoutMs })`; it throws `SandalOperationFailedError` if the operation fails (for example `sandbox_create.quota_exceeded`). - **Errors.** API failures throw `SandalApiError` with `status`, `code`, `reason`, `requestId` and `retryable`; `describeSandalError(error)` classifies any failure. See [Limits](https://sandal.dev/docs/limits). ```ts import { randomUUID } from "node:crypto"; const key = () => randomUUID(); const revision = async (id: string) => (await sandal.sandboxes.get(id)).revision; ``` ## Templates ```ts const template = await sandal.builds.templates.getPublished(""); // { 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 ```ts const { sandbox, operation } = await sandal.sandboxes.create({ idempotencyKey: key(), kind: "virtual-machine", profile: "enter-agent-linux", templateId: "", 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 ```ts 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 ```ts 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 disk ``` `pause` / `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`. ```ts 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)](https://sandal.dev/docs/root-and-fuse). ## Files ```ts 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 ```ts 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 `, so share it with `sb.share(port)` / `sb.ports.shareLink(exposure.id)` (see [Share links](https://sandal.dev/docs/sharing)). Revoke early with `sandboxes.revokePortExposure`. ## Snapshots and forks ```ts 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](https://sandal.dev/docs/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: ```ts 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](https://sandal.dev/docs/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](https://sandal.dev/docs/limits#not-yet-available-on-the-beta-deployment); `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. --- # Python SDK > sandal (private beta): async and blocking Python clients with configuration from the environment, a Sandbox handle and helpers, plus the low-level client for every endpoint. Source: https://sandal.dev/docs/sdk-python ## Install Private beta: the package is not on PyPI yet. Install the wheel from your [beta bundle](https://sandal.dev/docs/quickstart#1-install) (Python 3.11+); you import it as `sandal`: ```bash python3 -m venv .venv .venv/bin/pip install ./sdk/python/sandal_sdk-0.1.0b16-py3-none-any.whl ``` > **Check the package name:** > Never `pip install sandal`: that is an **unrelated third-party package** that also uses the import name `sandal`, so do not install both into one environment. Our distribution is `sandal-sdk`. ## Create the client `Sandal` is async (`asyncio`, httpx); `SandalSync` is its blocking twin with the same methods. Close the client when you are done, or use it as a context manager. ```python import asyncio from sandal import Sandal, SandalSync, SandboxTarget async def main() -> None: async with Sandal() as sandal: # SANDAL_API_KEY alone is enough, else the `sandal login` profile sb = await sandal.create_sandbox(size="s") try: print((await sb.exec("echo hi && uname -a")).stdout) await sb.write_text("/workspace/notes.txt", "done\n") await sb.push("./app") # git-aware copy to /workspace/app finally: await sb.delete() asyncio.run(main()) with SandalSync() as sandal: # blocking: same calls without await print(sandal.create_sandbox().exec("python3 -c 'print(6*7)'").stdout) # organization_id and project_id are optional overrides; the key alone is enough. explicit = Sandal(SandboxTarget(base_url="https://api.sandal.dev", api_token=key, organization_id=org, project_id=project)) ``` The helpers (`create_sandbox`, `exec`, `stream_command`, `run_command`, files of any size, `push`, `run_job`, `expose` / `share`, lifetime, usage, saved snapshots, history) are documented once for all three languages on the SDK pages ([TypeScript](https://sandal.dev/docs/sdk-typescript), [Python](https://sandal.dev/docs/sdk-python), [Go](https://sandal.dev/docs/sdk-go)). The rest of this page is the low-level client: one method per endpoint. ## Conventions - **Idempotency.** Every mutation accepts `idempotency_key`; it is optional (an omitted key is a random UUID, reused by retries). - **Revisions.** `expected_sandbox_revision` (exec, files, ports, snapshots) and `expected_revision` (lifecycle) are optional; the SDK reads the current one and retries once on `revision_conflict`. The examples below pass them explicitly to show the wire contract. - **Retries.** 429, 502, 503, 504 and network failures, 3 retries by default, honouring `Retry-After`; tune with `SandalRetryPolicy`. - **Operations.** Create, lifecycle and fork return an object with `.sandbox` and `.operation`. Wait with `await sandal.sandboxes.wait_for_operation(operation.id, timeout_seconds=300)`; a failed operation raises `SandalOperationFailedError`. - **Errors.** API failures raise `SandalApiError` (also the generated `ApiException`) with `code`, `status`, `reason`, `request_id`, `retry_after_seconds` and `retryable`, and a subclass per status (`SandalNotFoundError`, `SandalConflictError`, ...). See [Limits](https://sandal.dev/docs/limits). ```python import uuid def key() -> str: return str(uuid.uuid4()) async def revision(sandal, sandbox_id: str) -> int: return (await sandal.sandboxes.get(sandbox_id)).revision ``` ## Templates ```python published = await sandal.builds.templates.get_published("") print(published.template_digest, published.profile, published.architecture) ``` 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 ```python from datetime import datetime, timedelta, timezone from sandal.models.sandbox_cpu_architecture import SandboxCpuArchitecture from sandal.models.sandbox_lifecycle_policy_input import SandboxLifecyclePolicyInput from sandal.models.sandbox_network_policy_input import SandboxNetworkPolicyInput from sandal.models.sandbox_size import SandboxSize created = await sandal.sandboxes.create( idempotency_key=key(), kind="virtual-machine", template_id="", template_digest="sha256:f311884c8be75a75ada50405624aefff53ebc6611590b7cf9275fe16dc0dee6b", size=SandboxSize("s"), # xs | s | m | l | xl architecture=SandboxCpuArchitecture("amd64"), name="agent-1", lifecycle=SandboxLifecyclePolicyInput(expires_at=datetime.now(timezone.utc) + timedelta(hours=1)), network_policy=SandboxNetworkPolicyInput(allow_internet=False), # optional: block internet egress ) await sandal.sandboxes.wait_for_operation(created.operation.id, timeout_seconds=300) sandbox_id = created.sandbox.id ``` 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. ### Lifecycle ```python async def lifecycle(action: str, sandbox_id: str) -> None: admitted = await getattr(sandal.sandboxes, action)( sandbox_id, expected_revision=await revision(sandal, sandbox_id), idempotency_key=key() ) await sandal.sandboxes.wait_for_operation(admitted.operation.id, timeout_seconds=300) await lifecycle("stop", sandbox_id) # keeps the disk await lifecycle("start", sandbox_id) await lifecycle("archive", sandbox_id) # cold storage; needs a running sandbox await lifecycle("recover", sandbox_id) # back to running, files intact await lifecycle("delete", sandbox_id) # deletes the sandbox and wipes its disk ``` `pause` and `resume` take the same arguments and keep memory on the same host. `get_lifecycle_policy`, `update_lifecycle_policy` and `keep_alive` manage automatic stop/archive/delete. ## Processes ```python import base64 started = await sandal.processes.exec( sandbox_id, command=["sh", "-c", "for i in 1 2 3; do echo tick $i; sleep 1; done; exit 3"], expected_sandbox_revision=await revision(sandal, sandbox_id), idempotency_key=key(), ) async for event in sandal.processes.stream_events(sandbox_id, started.process.id, timeout_ms=120_000): print(base64.b64decode(event.data_base64).decode("utf-8", "replace"), end="") process = await sandal.processes.get(sandbox_id, started.process.id) print(process.exit_code) # 3 (can be None for a moment after the last event; poll get() briefly) ``` `processes.cancel`, `processes.signal`, `processes.write_input` and `processes.resize_pty` manage a running process. A process keeps at most `max_output_bytes` of output (16 MiB by default, up to 64 MiB); `sb.exec(...)` raises `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 `direct_exec_multi=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)](https://sandal.dev/docs/root-and-fuse). ## Files ```python await sandal.files.write( sandbox_id, path="/workspace/hello.txt", data_base64=base64.b64encode(b"hello sandal\n").decode(), offset=0, truncate=True, create_parents=True, expected_sandbox_revision=await revision(sandal, sandbox_id), idempotency_key=key(), ) read = await sandal.files.download(sandbox_id, "/workspace/hello.txt", offset=0, limit=65_536) print(base64.b64decode(read.data_base64).decode()) ``` One write 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 ```python exposure = ( await sandal.sandboxes.expose_port( sandbox_id, expected_sandbox_revision=await revision(sandal, sandbox_id), port=8080, protocol="http", ttl_seconds=600, idempotency_key=key(), ) ).exposure while exposure.state.value != "ready": await asyncio.sleep(0.5) exposure = await sandal.sandboxes.get_port_exposure(sandbox_id, exposure.id) print(exposure.url) # requests need `Authorization: Bearer ` ``` To share a preview without a key, use `sb.share(port)` (a time-bounded, revocable share link; see [Share links](https://sandal.dev/docs/sharing)). ## Snapshots and forks ```python snapshot = ( await sandal.sandboxes.create_snapshot( sandbox_id, expected_sandbox_revision=await revision(sandal, sandbox_id), idempotency_key=key() ) ).snapshot while snapshot.state.value != "ready": await asyncio.sleep(0.5) snapshot = await sandal.sandboxes.get_snapshot(sandbox_id, snapshot.id) forked = await sandal.sandboxes.fork( sandbox_id, expected_revision=await revision(sandal, sandbox_id), idempotency_key=key(), name="agent-1-fork", lifecycle=SandboxLifecyclePolicyInput(expires_at=datetime.now(timezone.utc) + timedelta(hours=1)), ) await sandal.sandboxes.wait_for_operation(forked.operation.id, timeout_seconds=300) ``` ## Code interpreter On projects where `sandal capabilities` lists `code-interpreter`: ```python outcome = await sandal.code.run_and_wait( sandbox_id, idempotency_key=key(), language="python", code="import math\nprint('hi')\nmath.sqrt(2)", ) print(outcome.main_result.data["text/plain"] if outcome.main_result else None) ``` ## 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 macOS 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](https://sandal.dev/docs/limits#not-yet-available-on-the-beta-deployment); `sandal capabilities` shows what your project can do. Every namespace: `sandboxes`, `processes`, `files`, `git`, `agents`, `code`, `language_servers`, `computer`, `browsers`, `devices`, `builds`, `events.webhooks`, `telemetry`, `keys`, `audit`; `sandal.raw` holds the generated APIs. --- # Go SDK > sandal.dev/go (private beta): configuration from the environment, a Sandbox handle and iterator-based helpers, plus the low-level client for every endpoint. Source: https://sandal.dev/docs/sdk-go ## Install Private beta: the module `sandal.dev/go` (Go 1.23+) is not on the Go proxy yet. Point it at the source from your [beta bundle](https://sandal.dev/docs/quickstart#1-install): ```bash go mod edit -require=sandal.dev/go@v0.1.0-beta.16 -replace=sandal.dev/go=./sdk/go/sandal-go-v0.1.0-beta.16 go mod tidy ``` ## Create the client ```go import ( "context" "fmt" "log" sandal "sandal.dev/go" ) client, err := sandal.NewSandalFromEnv(sandal.SandalEnvOptions{}) // SANDAL_API_KEY alone is enough, else the `sandal login` profile if err != nil { log.Fatal(err) } // or explicitly (OrganizationID and ProjectID are optional overrides): client, err = sandal.NewSandal(sandal.Target{ BaseURL: "https://api.sandal.dev", APIToken: key, OrganizationID: org, ProjectID: project, }) ``` Every call takes a `context.Context`; cancelling it stops waits, retries and streams. ## The short way ```go sb, err := client.CreateSandbox(ctx, sandal.SandalCreateSandboxOptions{}) // default template, waits until running if err != nil { log.Fatal(err) } defer sb.Delete(ctx, sandal.SandalLifecycleOptions{}) res, err := sb.Exec(ctx, sandal.ShellCommand("echo hi && uname -a"), nil) fmt.Println(res.Status, res.Stdout) _, err = sb.Push(ctx, "./app", "") // git-aware copy to /workspace/app ``` The handle, `Exec` / `StreamCommand` / `RunCommand` (`iter.Seq2` frames), 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](https://sandal.dev/docs/sdk-typescript), [Python](https://sandal.dev/docs/sdk-python), [Go](https://sandal.dev/docs/sdk-go)). The rest of this page is the low-level client: one method per endpoint. Facade methods return `(result, *http.Response, error)`. API failures unwrap to `*sandal.SandalAPIError` with `errors.As` (`Code`, `Status`, `Reason`, `RequestID`, `RetryAfter`, `Retryable()`); see [Limits](https://sandal.dev/docs/limits). ## Conventions - **Idempotency.** Mutations carry `Identity: sandal.SandalMutationIdentity{IdempotencyKey: "…"}`. A zero identity gets a random key, reused by retries. - **Revisions.** `ExpectedSandboxRevision` (exec, files, ports, snapshots) and `ExpectedRevision` (lifecycle inputs) are read for you when zero, with one retry on `revision_conflict`. The examples below pass them explicitly to show the wire contract. - **Retries.** `SandalRetryPolicy` (default 3): 429, 502, 503, 504 and network failures, honouring `Retry-After`. - **Operations.** Create, lifecycle and fork return a result with `.Operation.Id`; wait with `client.Sandboxes.WaitForOperation`. ```go func key() sandal.SandalMutationIdentity { b := make([]byte, 16) _, _ = rand.Read(b) // crypto/rand return sandal.SandalMutationIdentity{IdempotencyKey: fmt.Sprintf("%x", b)} } func revision(ctx context.Context, client *sandal.Sandal, id string) int32 { sandbox, _, err := client.Sandboxes.Get(ctx, id, "") if err != nil { log.Fatal(err) } return int32(sandbox.Revision) } func wait(ctx context.Context, client *sandal.Sandal, operationID string) error { _, _, err := client.Sandboxes.WaitForOperation(ctx, operationID, sandal.SandalOperationWaitOptions{Timeout: 5 * time.Minute, PollInterval: 500 * time.Millisecond}) return err } ``` ## Templates ```go published, _, err := client.Builds.Templates.GetPublished(ctx, "", "") // published.TemplateDigest, published.Profile, published.Architecture ``` 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 ```go size, arch, name := sandal.SandboxSize("s"), sandal.SANDBOXCPUARCHITECTURE_AMD64, "agent-1" created, _, err := client.Sandboxes.Create(ctx, sandal.SandalSandboxCreateInput{ Kind: sandal.SANDBOXKIND_VIRTUAL_MACHINE, // SANDBOXKIND_CONTAINER for the container template TemplateID: "", TemplateDigest: "sha256:f311884c8be75a75ada50405624aefff53ebc6611590b7cf9275fe16dc0dee6b", Size: &size, // xs | s | m | l | xl Architecture: &arch, Name: &name, Lifecycle: *sandal.NewSandboxLifecyclePolicyInput(time.Now().Add(time.Hour)), // hard expiry NetworkPolicy: sandal.NewSandboxNetworkPolicyInput(false), // optional: block internet egress Identity: key(), }) if err != nil { log.Fatal(err) } if err := wait(ctx, client, created.Operation.Id); err != nil { log.Fatal(err) } id := created.Sandbox.Id ``` Lifecycle verbs share one input type: ```go input := sandal.SandalLifecycleMutationInput{ExpectedRevision: revision(ctx, client, id), Identity: key()} stopped, _, err := client.Sandboxes.Stop(ctx, id, input) // also Start, Archive, Delete // then: wait(ctx, client, stopped.Operation.Id) recovered, _, err := client.Sandboxes.Recover(ctx, id, sandal.SandalRecoverInput{ SandalLifecycleMutationInput: sandal.SandalLifecycleMutationInput{ExpectedRevision: revision(ctx, client, id), Identity: key()}, }) ``` Archive needs a running sandbox. `client.Sandboxes.List(ctx, sandal.SandalSandboxListInput{})` lists the project's sandboxes. ## Processes ```go started, _, err := client.Processes.Exec(ctx, id, sandal.SandalExecInput{ Command: []string{"sh", "-c", "for i in 1 2 3; do echo tick $i; sleep 1; done; exit 3"}, ExpectedSandboxRevision: revision(ctx, client, id), Identity: key(), }) if err != nil { log.Fatal(err) } _, err = client.Processes.StreamEvents(ctx, id, started.Process.Id, sandal.SandalProcessEventStreamOptions{Timeout: 2 * time.Minute}, func(event sandal.SandboxProcessEvent) error { data, err := base64.StdEncoding.DecodeString(event.DataBase64) os.Stdout.Write(data) return err }) process, _, err := client.Processes.Get(ctx, id, started.Process.Id, "") if process.ExitCode.IsSet() && process.ExitCode.Get() != nil { fmt.Println("exit code", *process.ExitCode.Get()) // 3 (poll Get briefly if not set yet) } ``` A process keeps at most `MaxOutputBytes` of output (16 MiB by default, up to 64 MiB). When a command passes it, `sb.Exec` / `ExecCommand` return the output so far together with a `*sandal.SandalCommandOutputLimitError` (check with `errors.As`). 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: &off` 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. `sandal.SandalCommandOptions{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)](https://sandal.dev/docs/root-and-fuse). ## Files ```go _, _, err = client.Files.Write(ctx, id, sandal.SandalFileWriteInput{ Path: "/workspace/hello.txt", DataBase64: base64.StdEncoding.EncodeToString([]byte("hello sandal\n")), Offset: 0, Truncate: true, CreateParents: true, ExpectedSandboxRevision: revision(ctx, client, id), Identity: key(), }) offset, limit := int64(0), int64(65536) file, _, err := client.Files.Download(ctx, id, "/workspace/hello.txt", sandal.SandalFileReadInput{Offset: &offset, Limit: &limit}) data, _ := base64.StdEncoding.DecodeString(file.DataBase64) ``` One write 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 ```go exposed, _, err := client.Sandboxes.ExposePort(ctx, id, sandal.SandalPortExposureCreateInput{ ExpectedSandboxRevision: revision(ctx, client, id), Port: 8080, Protocol: sandal.SANDBOXPORTEXPOSUREPROTOCOL_HTTP, TtlSeconds: 600, Identity: key(), }) exposure := &exposed.Exposure for exposure.State != "ready" { time.Sleep(500 * time.Millisecond) exposure, _, err = client.Sandboxes.GetPortExposure(ctx, id, exposed.Exposure.Id, "") } url := *exposure.Url.Get() // requests need `Authorization: Bearer ` ``` ## Snapshots and forks ```go snap, _, err := client.Sandboxes.CreateSnapshot(ctx, id, sandal.SandalSnapshotCreateInput{ ExpectedSandboxRevision: revision(ctx, client, id), Identity: key(), }) // poll client.Sandboxes.GetSnapshot(ctx, id, snap.Snapshot.Id, "") until State == "ready" forkName := "agent-1-fork" forked, _, err := client.Sandboxes.Fork(ctx, id, sandal.SandalForkInput{ SandalLifecycleMutationInput: sandal.SandalLifecycleMutationInput{ExpectedRevision: revision(ctx, client, id), Identity: key()}, Name: &forkName, Lifecycle: sandal.NewSandboxLifecyclePolicyInput(time.Now().Add(time.Hour)), }) // then: wait(ctx, client, forked.Operation.Id); forked.Sandbox.Id is the new sandbox ``` ## 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 macOS 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](https://sandal.dev/docs/limits#not-yet-available-on-the-beta-deployment); `sandal capabilities` shows what your project can do. Every facade: `Sandboxes`, `Processes`, `Files`, `Git`, `Agents`, `Code`, `LanguageServers`, `Computer`, `Browsers`, `Devices`, `Builds`, `Events`, `Telemetry`, `Keys`, `Audit`. --- # CLI > The sandal CLI (private beta): sign in with your browser, then create, exec into, copy files to, expose, snapshot and fork sandboxes from your terminal. Source: https://sandal.dev/docs/cli ## Install Private beta: the CLI is not on npm yet. Install the single-file binary from your [beta bundle](https://sandal.dev/docs/quickstart#1-install), or the npm package file that is in the same bundle (`sandal-dev-cli-0.1.0-beta.16.tgz`, Node.js 24+, also gives `sandal-mcp`): ```bash install -m 755 cli/bin/sandal-darwin-arm64 ~/.local/bin/sandal # Intel Mac: sandal-darwin-x64 npm install -g ./sandal-dev-cli-0.1.0-beta.16.tgz # alternative: from the bundle's CLI + MCP folder sandal version # 0.1.0-beta.16 ``` > **Check the package name:** > `npm install sandal` and `npx sandal …` install an **unrelated third-party package**. Our packages are `@sandal-dev/cli` and `@sandal-dev/sdk`. ## Sign in `sandal login` signs you in through the Sandal Console with a browser (device authorization). In a terminal it opens the Console page, prints the URL and a short code, and waits until you confirm the code there. Confirm only if you just ran `sandal login` yourself. The CLI then stores a **CLI session** (a one-hour access token plus a rotating refresh token) in a named profile and refreshes it automatically before it expires. It also picks the project for the profile: `--project `, else the profile's current project (same organization), else the project named `Default`, else the only one. Credentials live in `~/.config/sandal/config.json` (or `$SANDAL_CONFIG_DIR/config.json`, or under `$XDG_CONFIG_HOME/sandal/`), written with mode 0600; the CLI refuses a config file that is group- or world-readable. A browser sign-in replaces an API key stored in the same profile. If the code expires or is denied, run `sandal login --new`. ```bash sandal login # opens the browser, shows the code, waits sandal login --no-browser # print the URL and code without opening a browser sandal whoami # resolved target, credential, scopes and expiry sandal profile list sandal profile use sandal sessions list # CLI sessions of your account sandal logout # revokes this profile's session and removes it (or removes its API key) ``` | Flag | Meaning | | --- | --- | | `--no-browser` | Print the URL and code without opening a browser | | `--project ` | Use this project instead of the default choice | | `--profile `, `--api-url ` | Store the session in this profile; sign in against another API | | `--new` | Replace a pending sign-in code (a rerun otherwise shows the same code) | | `--json` | Print the URL, code and `expiresAt` and exit without waiting | | `--json --wait` | Print the same, then wait for the browser step | Agents, scripts and machines without a browser can split the flow in two: `sandal login --json` prints the URL and code and exits, a person approves in the Console, then `sandal onboard --wait --json` stores the session. Account commands (`orgs`, `projects`, `api-keys`, `billing`, `sessions`) need a browser sign-in; an API key cannot manage the account. **CI and other non-interactive use** keeps the API key. Create a project API key in the Console and pipe it in; the key is read from stdin (`--key-stdin` or `--api-key-stdin`) or from a hidden prompt (`--key`), validated against the API, and stored in the profile. Without a terminal on stdin, `sandal login` reads the key from stdin on its own. Or skip `login` and set `SANDAL_API_KEY`. ```bash printf '%s' "$SANDAL_API_KEY" | sandal login --key-stdin # organization and project come from the key ``` API keys are never accepted as command-line arguments. Environment variables override the profile: `SANDAL_API_KEY`, `SANDAL_ORGANIZATION_ID`, `SANDAL_PROJECT_ID`, `SANDAL_API_URL` (default `https://api.sandal.dev`) and `SANDAL_PROFILE`. `SANDAL_API_KEY` alone is enough: the organization and project are resolved from the key, and the two id variables are optional overrides. ## Global options | Option | Meaning | | --- | --- | | `--json` | Print machine-readable JSON (every command) | | `-p, --profile ` | Profile from the config file (or `SANDAL_PROFILE`) | | `--api-url ` | API origin (or `SANDAL_API_URL`) | | `--organization ` | Organization id (or `SANDAL_ORGANIZATION_ID`) | | `--project ` | Project id (or `SANDAL_PROJECT_ID`) | | `-h, --help` | Help for any command, e.g. `sandal create --help` | Exit codes: `0` ok, `1` failed, `2` usage or config, `3` auth, `4` not found, `5` conflict, `6` quota, `7` unavailable, `8` timeout, `9` network. `sandal exec` and `sandal shell` pass the remote exit code through. ## Sandboxes ### `sandal create` Create a sandbox and wait until it is running. Without `--template` it uses the project's default template. On a terminal it prints a table; piped or with `--json` it prints JSON Lines (the `ready` event carries the sandbox). ```bash sandal create --size s --name dev sandal create --cpu 4 --memory 8192 --disk 40 --ttl 8h sandal create --size m --auto-stop 30m --env FOO=bar ``` | Option | Meaning | | --- | --- | | `-t, --template ` | Published template id (default: the project default template) | | `--template-digest ` | Pin the exact template digest | | `-n, --name ` | Display name | | `--size ` | `xs` 1/1/10, `s` 2/4/20, `m` 4/8/40, `l` 8/16/80, `xl` 16/32/160 (vCPU / GiB RAM / GiB disk) | | `--cpu`, `--memory `, `--disk `, `--cpu-class` | Explicit resources instead of a size (defaults 2 vCPU, 4096 MiB, 20 GiB, burstable) | | `--ttl ` | Hard expiry (default `24h`) | | `--auto-stop`, `--auto-archive`, `--auto-delete ` | Automatic lifecycle policy | | `--auto-resume` | With `--auto-stop`: wake on API or preview traffic (not SSH) with the disk kept (switched on per project during the beta) | | `-e, --env ` | Initialization environment (repeatable) | | `--no-wait`, `--wait-timeout ` | Return after admission / bound the wait (default 300) | | `--idempotency-key ` | Retry-safe mutation identity (default: random) | Without `--template` the project's default template is used (see the [Quickstart](https://sandal.dev/docs/quickstart#3-five-commands-to-a-link-anyone-can-open)). A pinned catalog id stops working when it is retired (`404`, “was retired”); omitting the template never goes stale. ### `sandal list` / `sandal get` ```bash sandal list # ID NAME STATE KIND TEMPLATE CPU MEM AGE (deleted sandboxes hidden) sandal list --state running --json sandal get ``` ### Lifecycle ```bash sandal stop # keeps the disk sandal start sandal pause # keeps memory sandal resume sandal archive # cold storage; needs a running sandbox sandal recover # from archive or failure (optionally --snapshot ) sandal delete # deletes the sandbox and wipes its disk; returns once the delete is accepted (--wait: until teardown finishes) sandal fork --name dev-2 # copy-on-write fork into a new sandbox (or --snapshot ) sandal lifecycle get # policy, idle evidence, next automatic transition sandal lifecycle set --auto-stop 1h # off | inherit | duration sandal lifecycle defaults --auto-archive 7d # project defaults sandal keep-alive --for 2h # restart the idle clock and hold it (max 24h) ``` ## Processes ```bash sandal exec -- npm test # streams output, exits with the remote exit code sandal exec --cwd /workspace -e CI=1 -- sh -c 'make && make test' sandal exec --detach -- python3 -m http.server 3000 # prints the process id sandal logs -f sandal shell # interactive PTY shell ``` `sandal exec` options: `-w, --cwd` (default `/workspace`), `-e, --env NAME=value`, `--secret NAME=secretId@version` (Vault reference), `--timeout 30m`, `-t, --tty`, `-d, --detach`, `--shell` (run the string through `/bin/sh -lc`), `--root` (run as root; the default template refuses it with `422 capability_unavailable`, exit code `7`, and the message names `tenant-root-v1` and up to three ready templates of your project that declare it; see [Root and FUSE (preview)](https://sandal.dev/docs/root-and-fuse)), `--direct-exec` (use the direct exec path for this one command; without it a single `sandal exec` uses the API path, which is slightly faster for one call). Each `sandal exec` is a new process: a single command takes about 0.4 s median. For many short commands, hold one SDK handle instead (on the direct path, about 125 ms median per command on the default Linux template and about 50 ms on the default container image, measured from Helsinki on November 29, 2026). ## Files ```bash sandal cp ./hello.txt :/workspace/hello.txt sandal cp -r ./src :/workspace/src sandal cp :/workspace/out.txt . sandal upload ./hello.txt /workspace/hello.txt sandal download /workspace/out.txt - # '-' prints to stdout sandal files ls /workspace sandal files cat /workspace/hello.txt sandal files stat|rm|mkdir|mv ... sandal files find '**/*.ts' --path /workspace sandal files grep TODO --path /workspace --include '*.ts' sandal files replace oldName newName --path /workspace --dry-run ``` Large transfers use signed transfer URLs (24 MiB in about 5 s up and 3 s down); where those are switched off the CLI falls back to the much slower chunked API. ## Ports ```bash sandal ports expose 3000 --ttl 1h # prints the exposure and its URL curl -H "Authorization: Bearer $SANDAL_API_KEY" / sandal ports get sandal ports revoke ``` Exposure URLs (`url`) require `Authorization: Bearer `. For a link anyone can open, add `--share` (or `sandal ports token`); revoke it with `sandal ports share-links revoke`. The shortcut for share links: ```bash sandal share 3000 --ttl 1h --single-use # exposes the port if needed and prints a share link sandal share ls sandal share revoke # the link answers 410 from then on sandal share token # a one-browser link with an access token ``` A share link lives 24 h at most, can be single-use and is revocable; a revoke does not end a session that is already open (up to 1 h). See [Share links](https://sandal.dev/docs/sharing). ## Snapshots ```bash sandal snapshot create # waits until ready sandal snapshot list sandal snapshot get sandal fork --snapshot --name from-snapshot ``` ## Git ```bash sandal git clone https://github.com/acme/app.git /workspace/app --depth 1 sandal git status /workspace/app ``` Private repositories take credentials by Vault reference (`--credential secretId@version`), never inline tokens. `git branches`, `commit`, `push`, `pull` and `checkout` are also available. ```bash sandal git diff --path /workspace/app --base main # per-file +/- (add --file for its patch) sandal git deliver --run -m "Fix the bug" --title "Fix the bug" --body @PR.md --draft sandal git connections create --provider github --app-id 123456 --installation-id 78901234 --private-key @app.pem sandal git grants list-project --state active ``` `git deliver` commits, pushes and opens or updates a pull request. Connections and grants are the git credential broker (`sandal git connections`); delivery is `sandal git deliver --help`. Both are rolling out and off by default. ## Agents ```bash sandal agents start --provider claude --key ANTHROPIC_API_KEY --prompt "Fix the flaky test" --follow sandal agents start --provider codex --key OPENAI_API_KEY --repo acme/web --prompt-file task.md sandal agents follow # live, resumable (--cursor), --poll for long polling sandal steer --run "Use the existing retry helper instead" sandal agent interrupt sandal agents list --state failed --all # every run of the project sandal prompt "…" # conversational shorthand; --resume cnv_… / --new sandal conversations sandal agent models # harnesses, models, efforts ``` Everything about runs, keys, streaming and failure codes is in `sandal agent --help`. ## Browser IDE ```bash sandal ide open --path /home/enter/workspace # VS Code in your browser; --no-browser prints the link sandal ide status sandal ide stop ``` Browser IDE: beta, off by default (`sandal ide --help`). ## Webhooks ```bash sandal webhooks create https://example.com/hook --event run.completed,run.failed --secret-file ./secret sandal webhooks deliveries --status exhausted sandal webhooks redeliver sandal webhooks rotate --overlap 86400 ``` See [Webhooks](https://sandal.dev/docs/webhooks). ## Project ```bash sandal capabilities # features and limits enabled for this project sandal templates list # templates with what their image declares (CAPABILITIES, e.g. tenant-root-v1) sandal templates get