# First sandbox

A sandbox is a Linux VM of its own, with its own kernel, memory and disk. The API lives at `https://api.groundbox.dev/v1`. Send your key as `Authorization: Bearer gbx_...`. Sandboxes are on every plan. The free plan starts with $5 of usage; until a card is on file, a team runs 2 sandboxes at a time, 2 vCPU, 4 GB, 1 hour each.

## Start, exec, files

### 1. Start a sandbox

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"cpus": 2, "timeout_minutes": 60}'
```

Defaults: 2 vCPUs (from 1 to 16), 2 GB of RAM per vCPU (up to 4), a 20 GB disk, and it stops after 60 minutes. The longest timeout is 720 hours (43,200 minutes); renew it with `PATCH`. A sandbox is billed for as long as it runs, so set a [spend cap](https://groundbox.dev/docs/api#keys) on the key or the team: at the cap, what is running stops. `on_timeout` sets what the timeout does. Send `Idempotency-Key` so a retry never starts, and bills, two sandboxes. A retry gets the same sandbox as it is now, and its response has the header `Idempotent-Replayed: true`. A first request does not have it. The response has the sandbox `id`, which starts with `sbx_`.

A sandbox of more than 8 vCPUs costs the same per vCPU. A team runs 2 of them at once; one more gets `429 concurrency_limit`. It starts when a box has that many cores free, so it can stay `queued` for a while. It boots cold, also from a template.

`disk_gb` is a minimum. The disk is never smaller than the disk of the image or template the sandbox starts from, so a small `disk_gb` shows a bigger disk in `df`. Ask for more and the disk grows to that size. The price of a running sandbox does not depend on its disk.

### 2. Run a command

```
curl https://api.groundbox.dev/v1/sandboxes/sbx_.../exec \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cmd": "git clone https://github.com/you/app && cd app && npm test"}'
```

The command runs with `sh -c`. You get back the exit code and output:

```
{
  "exit_code": 0,
  "stdout": "...",
  "stderr": "",
  "duration_ms": 41873,
  "timed_out": false
}
```

To get output as it comes, connect a WebSocket to `/sandboxes/{id}/exec/stream`. When a stream fails, its last message is `{"type": "error", "code": "...", "message": "..."}`. The `code` is one of the API's error codes: `conflict` when the sandbox is not running, `bad_request` for a message the stream does not take.

### 3. Move files

```
# Upload a file (up to 32 MiB in one request)
curl -X PUT "https://api.groundbox.dev/v1/sandboxes/sbx_.../files?path=/work/input.json" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  --data-binary @input.json

# A bigger file, up to 100 MB: in parts, in order. Each part says where it starts
# and how big the whole file is; the last one puts the file in place.
split -b 16m data.bin part-
total=$(wc -c < data.bin | tr -d ' '); offset=0
for part in part-*; do
  curl -fsS -X PUT "https://api.groundbox.dev/v1/sandboxes/sbx_.../files?path=/work/data.bin&offset=$offset&total_bytes=$total" \
    -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
    --data-binary @"$part"
  offset=$((offset + $(wc -c < "$part")))
done

# List a folder
curl "https://api.groundbox.dev/v1/sandboxes/sbx_.../files?dir=/work" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"

# Make a folder, with its parents
curl -X POST "https://api.groundbox.dev/v1/sandboxes/sbx_.../files/mkdir?path=/work/out" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"

# One file or folder: type, size, modified time. 404 when it is not there
curl "https://api.groundbox.dev/v1/sandboxes/sbx_.../files/stat?path=/work/input.json" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"

# Delete a file, or a folder and everything in it
curl -X DELETE "https://api.groundbox.dev/v1/sandboxes/sbx_.../files?path=/work/out&recursive=true" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
```

Paths are absolute. An upload makes the parent folders it needs. A file is at most 100 MB, and one request carries at most 32 MiB: send a bigger file in parts, one `PUT` each, in order, with `total_bytes` (the whole file's size) and `offset` (where the part starts). The file appears whole when the last part is in, and that answer says `complete: true`. A part sent from the wrong place answers 409 with `received_bytes`, so you can go on from there; a part at offset 0 starts again. The SDKs' `write_file` and `groundbox sandbox cp` do all of this on their own. A body over a limit answers 413 with a JSON error. `mkdir` on a folder that is already there is fine: it answers `created: false`. `stat` describes a symlink itself, not what it points at. Delete removes a file, a symlink or an empty folder; a folder with files in it needs `recursive=true`, or the call answers 409. Deleting a path that is not there answers `deleted: false`, so a retry is safe.

### 4. Delete it

```
curl -X DELETE https://api.groundbox.dev/v1/sandboxes/sbx_... \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
```

Billing stops when the sandbox is deleted. Delete is for good: the disk is gone. To keep the disk and bring the sandbox back later, stop it instead. A deleted sandbox is not forgotten: `GET /sandboxes/{id}` still answers 200, with `status: "stopped"` and `stop_reason: "deleted"`, so you can read its cost and usage afterwards. Only an id that never existed, or another team's, gets 404. Deleting it again is safe.

### 5. List them

```
# Every sandbox that is not over, with these metadata pairs
curl -g "https://api.groundbox.dev/v1/sandboxes?live=true&metadata[project]=alpha" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"

# Or name the statuses
curl "https://api.groundbox.dev/v1/sandboxes?status=running,paused" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
```

The list is newest first and keeps stopped and failed sandboxes. `live=true` gives only the ones that are not over: every status but `stopped` and `failed`. `status` takes one status or several, separated by commas. `metadata[key]=value` keeps only sandboxes with that pair; give it more than once and all must match. The filters work together. In the CLI: `groundbox sandbox list --live --metadata project=alpha`.

### Run commands as root

Commands run as `runner`, the image's own user. It has `sudo` with no password, so `sudo apt-get install` works in any sandbox. To have every command run as root with no `sudo` in front, create the sandbox with `user: "root"`:

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"user": "root"}'

# Every command in it runs as root: this prints 0.
curl https://api.groundbox.dev/v1/sandboxes/sbx_.../exec \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cmd": "id -u"}'
```

It covers exec, the exec stream, background commands, a schedule's command and the file calls: a file you upload is root's, and mkdir and delete work in any folder. A command keeps your `env`, `PATH` and `cwd`. `HOME` stays `/home/runner`. The user is set when the sandbox is created and does not change: a fork keeps it, and a sandbox started from a snapshot has the user of the sandbox the snapshot was taken of. The sandbox's `user` field says which. A sandbox from a Docker image always runs as root. In the CLI: `groundbox sandbox create --user root`, or `groundbox run --user root -- id -u`.

## Start from a Docker image

Pass `image` to start from a Docker image instead of Groundbox's own: anything that `docker pull` takes, such as `python:3.12-slim` or `ghcr.io/org/app:tag`, an image in your [Groundbox registry](https://groundbox.dev/docs/registry), or a private image on another registry with its login. You do not make a template first.

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image": "python:3.12-slim"}'
```

```
let sandbox = await groundbox.create_sandbox({ image: "python:3.12-slim" });
// The first sandbox from an image waits while the image is turned into a disk.
sandbox = await groundbox.wait_for_sandbox(sandbox.id);
if (sandbox.status === "failed") throw new Error(sandbox.error ?? "the sandbox failed");
const result = await groundbox.run_command(sandbox.id, "python -V");
```

The first sandbox from an image comes back with status `queued` while the image is turned into a disk. That can take a few minutes for a large image. The sandbox moves to `running` when it is done. Its `image` field has the reference, the digest it resolved to and a `status`: `queued`, `building`, `ready` or `failed`. After that, a sandbox from the same image starts as fast as one from a [template](https://groundbox.dev/docs/templates).

A tag is looked up again each time, at most a minute late. When it points at a new digest, the image is turned into a disk again. Name a digest (`python@sha256:...`) to pin one.

- The image's `ENV` variables are set for every command. A sandbox's own `env` wins.
- Commands run as root. The image's `USER` is not used.
- Commands start in the home folder (`/root`, or the image's `HOME`), not in the image's `WORKDIR`. Pass `cwd` to run somewhere else.
- The image's `ENTRYPOINT` and `CMD` are not run. Start your program with a command.
- The image does not need Node.js. Groundbox adds its own tools under `/opt/groundbox`, so exec, streams, resumable and background commands, the command list and files all work on images like `alpine` and `python:3.12-slim`.
- A terminal (`tty: true`) needs the `script` program from util-linux. Debian and Ubuntu images have it. On Alpine, install `util-linux-misc`.
- The image must be built for linux/amd64, and has to fit the sandbox's disk. Ask for a larger `disk_gb` for a large image.
- A private image on another registry needs `image_auth`; see below. An image in your Groundbox registry needs no login.
- A team turns 2 new images into disks at a time, template builds included. A create past that is refused with `429`: try again when one is done.
- `image` cannot be combined with `template`, and a schedule cannot use it. To add packages or files on top of an image, make a [template](https://groundbox.dev/docs/templates) from it.

A sandbox whose image cannot be used ends with status `failed`, and its `error` field says why: the image does not exist or is private, it is too large for the disk, or the build failed or ran past 30 minutes. An image that is not found is refused straight away with `404`. The build's log is the log of the template named in the sandbox's `template` field; see [templates made from images](https://groundbox.dev/docs/templates#images).

### Private images on other registries

For a private image on GitHub's registry (`ghcr.io`), Docker Hub, Amazon ECR, Google Artifact Registry or any registry that speaks the Docker registry API, keep the password or token as a team secret and pass `image_auth`: the username and the secret's name. The key needs the `secrets:use` scope. Templates take the same field for a private base image.

```
# Once: keep the registry token as a team secret (a key with secrets:write).
curl -X PUT https://api.groundbox.dev/v1/secrets/GHCR_TOKEN \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"value": "ghp_..."}'

# Then name it (a key with sandboxes:write and secrets:use).
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"image": "ghcr.io/acme/app:1", "image_auth": {"username": "bot", "password_secret": "GHCR_TOKEN"}}'
```

```
printf %s "$GHCR_TOKEN" | groundbox secrets set GHCR_TOKEN
groundbox sandbox create --image ghcr.io/acme/app:1 --image-auth bot:GHCR_TOKEN
groundbox templates create app --image ghcr.io/acme/app:1 --image-auth bot:GHCR_TOKEN --pip requests
```

```
const sandbox = await groundbox.create_sandbox({
  image: "ghcr.io/acme/app:1",
  image_auth: { username: "bot", password_secret: "GHCR_TOKEN" },
});
```

```
sandbox = gb.create_sandbox(
    image="ghcr.io/acme/app:1",
    image_auth={"username": "bot", "password_secret": "GHCR_TOKEN"},
)
```

- The username is what `docker login -u` takes. GitHub: any name, with a token that has `read:packages`. Docker Hub: your user name, with an access token. ECR: `AWS`, with the output of `aws ecr get-login-password`. Artifact Registry: `oauth2accesstoken`, with `gcloud auth print-access-token`, or `_json_key` with a service account key.
- ECR and Artifact Registry access tokens expire (12 hours and 1 hour). Groundbox does not refresh them: set the secret again before it runs out, from a scheduled job of your own, or use a key that does not expire. A sandbox from an image already turned into a disk needs no login, so only a new image or a new tag needs a fresh token.
- The login is checked before anything is made. A refused one answers `400` with `details.reason` `registry_auth_failed`; an image the registry does not have answers `404`, as without a login.
- The password is opened only to ask the registry for the image's digest and, in the memory of the machine that pulls the image, for the pull. It is never in a response, a log, the sandbox or the template, and it is not on the image's disk. The disk made from a private image is your team's alone: another team naming the same image goes to the registry with its own login.

## Commands

A command is a shell line or a list of arguments. `cmd` runs with `sh -c`. `args` is a program and its arguments, run with no shell: nothing in them is expanded, split or quoted. Send one of the two.

```
curl https://api.groundbox.dev/v1/sandboxes/sbx_.../exec \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"args": ["git", "commit", "-m", "Fix the $PATH bug; ship it"]}'
```

### Input and output

Send `stdin` (text) or `stdin_base64` (any bytes) with the call. The command reads it, then end-of-file. Set `encoding` to `base64` to get `stdout` and `stderr` back as base64, byte for byte.

```
curl https://api.groundbox.dev/v1/sandboxes/sbx_.../exec \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"args": ["python3", "-"], "stdin": "print(6 * 7)\n"}'
```

### Streams and long commands

`POST /exec` waits for the command, for up to 60 minutes. To read output as it is printed, to send input as you go, or to run for longer, use the stream: a WebSocket at `/exec/stream`. The SDK and the CLI speak it for you.

```
const command = groundbox.stream_command(
  sandbox.id,
  ["python3", "-u", "train.py"],
  { resumable: true, timeout_s: 6 * 3600 },
  { onStdout: (text) => process.stdout.write(text) },
);
const { exit_code } = await command.done;
```

A resumable command keeps running when the connection drops. The SDK reconnects and reads on from where it was, so each line arrives once. A resumable command can run for as long as its sandbox does. A command that is not resumable ends with its connection, and can run for 60 minutes. Both kinds are in the sandbox's command history.

A resumable command can take input too. Text and bytes both work. Input written while the connection was down is sent once it is back.

```
const repl = groundbox.stream_command(sandbox.id, "python3 -i", { stdin: true, resumable: true }, {
  onStdout: (text) => process.stdout.write(text),
});
repl.write("print(6 * 7)\n");
repl.write(new Uint8Array([0x65, 0x78, 0x69, 0x74, 0x28, 0x29, 0x0a])); // bytes work too
repl.end();
```

### A terminal

Start a stream command with `tty: true` and it runs on a terminal of its own in the sandbox. Prompts, colours, line editing and full-screen programs like `vim` and `htop` work. Give it the size of your window, send what is typed as input, and send `resize` when the window changes. `groundbox sandbox shell` does all of this for you.

```
const shell = groundbox.stream_command(
  sandbox.id,
  "bash -il",
  { stdin: true, tty: { rows: process.stdout.rows, cols: process.stdout.columns }, resumable: true, hangup_s: 300 },
  { onStdout: (text) => process.stdout.write(text) },
);
process.stdin.setRawMode(true);
process.stdin.on("data", (keys) => shell.write(keys));
process.stdout.on("resize", () => shell.resize(process.stdout.rows, process.stdout.columns));
const { exit_code } = await shell.done;
```

A terminal has one stream, so the command's errors arrive with its output. A resumable terminal is a session: it survives a dropped connection, and the SDK picks it up where it was. `hangup_s` ends the session when nobody has been attached for that many seconds. The sandbox's image needs the `script` program from util-linux, which Debian and Ubuntu images have. Nothing else here needs anything in the image: resumable and background commands work in any image, with or without Node.js. The command history needs Node.js in the sandbox: a sandbox made from a Docker image always has Groundbox's own, and the default image has it.

### Background commands

`POST /commands` starts a command and answers at once with its id, which starts with `ex_`. The command runs on with nobody connected. Use it for servers, watchers and long jobs.

```
curl https://api.groundbox.dev/v1/sandboxes/sbx_.../commands \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cmd": "npm run dev", "cwd": "/home/runner/app", "timeout_s": 86400}'
```

Its output is kept in the sandbox. Read it from any position, as often as you like. To follow it live, or to send it input, attach to it on the stream.

```
# What it printed so far. "seq" in the answer is where to read on from.
curl "https://api.groundbox.dev/v1/sandboxes/sbx_.../commands/ex_.../output?seq=0" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
```

### List and kill

`GET /commands` lists what the sandbox runs and ran, newest first. `running` is the number of commands running now. Kill sends `SIGKILL` unless you name another signal.

```
# What runs now
curl "https://api.groundbox.dev/v1/sandboxes/sbx_.../commands?state=running" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"

# End one, and everything it started
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../commands/ex_.../kill \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"signal": "SIGTERM"}'
```

```
const server = await groundbox.start_command(sandbox.id, "npm run dev", { cwd: "/home/runner/app" });

// Later, from any process: read what it printed, or follow it live.
const { stdout, seq } = await groundbox.get_command_output(sandbox.id, server.id);
const live = groundbox.attach_command(sandbox.id, server.id, { seq }, { onStdout: (text) => process.stdout.write(text) });

const { data, running } = await groundbox.list_commands(sandbox.id);
await groundbox.kill_command(sandbox.id, server.id);
```

### Command history

Every command run in a sandbox is recorded there: `POST /exec`, the stream (resumable or not), background commands, and the dashboard's Commands tab, whether it came from the CLI, an SDK, MCP or your own code. That is how you see what an agent did. Each command has its id, the command line, its folder, `status` (`running`, `finished` or `failed`), exit code, duration, start time, `kind` (`run` or `background`) and `source` (`dashboard`, `cli`, `sdk`, `mcp` or `api`). Filter by `status` and `kind`, and page with `cursor`. `POST /exec` answers with the command's `exec_id`, so its entry is easy to find.

```
# Everything that ran in the sandbox, newest first: failed runs only, 50 at a time
curl "https://api.groundbox.dev/v1/sandboxes/sbx_.../commands?status=failed&kind=run&limit=50" \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"

# The next page: the answer's next_cursor
curl "https://api.groundbox.dev/v1/sandboxes/sbx_.../commands?cursor=eyJzdGFydGVkX2F0Ijo..." \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
```

```
groundbox sandbox commands sbx_... --status failed --limit 20
groundbox sandbox command sbx_... ex_... --output
```

The sandbox keeps the last 32 MB of each command's output until 60 minutes after it ended, then the last 64 KB of it. It keeps the newest 500 commands that ended. `output_truncated` says only the end of a command's output is kept, and a read of its output says `truncated`. The history lives in the sandbox, not in our database: a fork has its source's, and it is deleted with the sandbox. Recording happens in the same call that runs the command, so it adds no round trip.

The command line you send is kept as you sent it, so do not put secrets in it: pass them in `env` or as team secrets. Values of `env` and of team secrets are never written down. In an image with no Node.js the commands still run, but are not recorded, and the list says why in `unavailable_reason`.

## Fork

Fork a running sandbox. The copy has the same files and running processes, and its own id. A sandbox with volumes cannot be forked or paused; it can be stopped and started. To start many sandboxes with the same setup, build it once as a [template](https://groundbox.dev/docs/templates).

```
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../fork \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

A fork with `count` answers with a fork group. `groundbox sandbox fork-group get <group_id>` reads it and `groundbox sandbox fork-group rm <group_id>` deletes it and its copies.

## Time machine

A running sandbox can keep a timeline of save points: its memory, its disk and every running process, as they were at that moment. Rewind to any of them, or fork one into many copies. After the first, a save point holds only the memory pages and disk blocks changed since the one before, so a minute of history usually costs megabytes, and the sandbox stands still for milliseconds while it is taken (each point says how long, as `pause_ms`). Points every 2 seconds at the most often; the oldest go first past `keep` or your team's storage. They are deleted with the sandbox, unless you keep one as a snapshot. Save points are on every plan.

```
# A save point every 5 seconds, keeping the newest 30
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../timeline \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" -H "content-type: application/json" \
  -d '{"interval_s": 5, "keep": 30}'

# One now, with a label; the answer has its id (snap_...) and how long the sandbox stood still
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../snapshots \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" -H "content-type: application/json" \
  -d '{"label": "before the migration"}'

# Back to it: memory, disk and every process as they were. Same sandbox id.
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../restore \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" -H "content-type: application/json" \
  -d '{"snapshot_id": "snap_..."}'

# 10 copies of that moment, each with FORK_INDEX in its env (copies count toward your team's sandboxes at once)
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../fork \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" -H "content-type: application/json" \
  -d '{"count": 10, "snapshot_id": "snap_..."}'
```

```
import { Groundbox } from "@groundbox/sdk";

const sandbox = new Groundbox().sandbox("sbx_...");
await sandbox.timeline.enable({ interval_s: 5 });
const point = await sandbox.snapshot("app loaded");
await sandbox.restore(point.id);
const group = await sandbox.fork(10, { onProgress: (g) => console.log(g.progress) });
// groundbox sandbox fork sbx_... --count 10   |   MCP: snapshot, action save_point, rewind or fork_universes
```

A rewind keeps the sandbox's id: what it did since the point is gone, and open connections to it reconnect (streamed commands pick up where they were). A fork with `count` answers with a fork group at once; `GET /v1/fork-groups/{id}` shows the copies coming up, and `DELETE /v1/fork-groups/{id}` ends them all. The copies share the moment's memory until they write to it, each has its own address, hostname and machine id, and `FORK_INDEX` (0 to count - 1) tells each which one it is, in every command's env and in `/run/groundbox/fork.env`. Up to 50 copies per fork. Copies count toward your team's sandboxes at once (20 once a card is on file, 2 before), so a larger fork needs a higher limit: ask us.

A paused sandbox keeps its save points. Fork it from one with `snapshot_id`; without one it has to be resumed first. To drop a single save point of a running sandbox, call `DELETE /v1/sandboxes/{id}/snapshots/{snapshot_id}`. Every save point is whole on its own, so the ones after it, and sandboxes forked from it, are not touched.

## Snapshots

A snapshot is a save point that outlives its sandbox. `POST /v1/snapshots` with a `sandbox_id` keeps the sandbox as it is now; add `snapshot_id` to keep one of its save points instead, which also works while the sandbox is paused. The snapshot belongs to your team and stays when the sandbox is deleted.

`POST /v1/sandboxes` with `snapshot_id` starts a new sandbox from it: the same memory, disk and running processes, with its own id, address and hostname. Start as many as you like. The new sandbox has the snapshot's size, so leave `cpus`, `memory_gb` and `disk_gb` out. Its `env` is added to the commands you run in it; processes that were already running keep the environment they had.

```
# Keep the sandbox as it is now. The answer has the snapshot's id (snap_...)
curl -X POST https://api.groundbox.dev/v1/snapshots \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" -H "content-type: application/json" \
  -d '{"sandbox_id": "sbx_...", "label": "deps installed"}'

# A new sandbox from it, also after the first one is deleted
curl -X POST https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" -H "content-type: application/json" \
  -d '{"snapshot_id": "snap_..."}'

# The team's snapshots, and deleting one
curl https://api.groundbox.dev/v1/snapshots \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
curl -X DELETE https://api.groundbox.dev/v1/snapshots/snap_... \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
```

- `GET /v1/snapshots` lists them with the sandbox each was taken of, its size, label and creation time; `?sandbox_id=` narrows it to one sandbox. `DELETE /v1/snapshots/{id}` deletes one.
- Deleting a snapshot does not touch sandboxes already started from it, and deleting a sandbox does not touch its snapshots.
- Storage is $0.05 per GB-month, the same as a paused sandbox, on every plan. A snapshot's `size_bytes` is the memory in use plus what the sandbox added to its disk; the image it started from is not counted. A team keeps up to 50 snapshots and 100 GB together.
- A snapshot that no sandbox was started from for a month is deleted; its `expires_at` says when. Starting a sandbox from it moves that date on.
- `memory` on a snapshot says whether it holds memory and processes. When it does not, or the memory cannot be loaded any more, the sandbox boots from the snapshot's disk: the files are there, the processes are not. The sandbox's `start` is `warm` when memory came back and `cold` when only the disk did.
- A sandbox with volumes or a desktop cannot be started from a snapshot, and a sandbox with volumes cannot be kept as one.

```
import { Groundbox } from "@groundbox/sdk";

const groundbox = new Groundbox();
const snapshot = await groundbox.keep_snapshot({ sandbox_id: "sbx_...", label: "deps installed" });
await groundbox.delete_sandbox("sbx_...");
const sandbox = await groundbox.create_sandbox({ snapshot_id: snapshot.id });
const { data } = await groundbox.list_snapshots();
await groundbox.delete_snapshot(snapshot.id);
// groundbox snapshot keep sbx_...   |   groundbox sandbox create --snapshot snap_...   |   MCP: snapshot (action keep or delete), snapshot_info (action list)
```

## Pause and resume

A paused sandbox keeps its memory and disk and is billed for storage only, at $0.05 per GB-month. Resume brings it back as it was.

```
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../pause \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"

curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../resume \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
```

## Stop and start

Stop shuts a sandbox down cleanly and keeps only its disk. Memory and running processes are not kept. Start boots a fresh VM from that disk: a cold boot, with the same id, env, metadata, volumes and network rules.

```
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../stop \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"

curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../start \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY"
```

Three ways to put a sandbox away:

- **Pause** keeps memory, processes and disk. Resume brings it back as it was.
- **Stop** keeps the disk only. Start boots it again; anything that was running has to be started again.
- **Delete** ends it for good. Nothing is kept.

- A stopped sandbox is billed for storage only, at the same rate as a paused one: $0.05 per GB-month.
- Stopped and paused sandboxes count toward the same limit for a team, and share the 30-day rule: one that is not started or resumed in that time is deleted.
- Its status reads `shutting_down`, then `shut_down`. The status `stopped` means something else: the sandbox has ended and cannot come back (a deleted sandbox reads `stopped`). Start takes it through `starting` to `running`, and `shut_down_at` says when it was stopped.
- Each call fits one state. Start on a paused sandbox, or resume on a stopped one, answers `409` and names the call to use.
- A sandbox with volumes cannot be paused, but it can be stopped and started. Its volumes are attached again on start.
- Start answers `503 no_capacity` when the machine that keeps the disk has no room right now. The sandbox stays stopped; try again later.

### At the timeout

By default a sandbox that reaches its timeout is deleted. Set `on_timeout` when you create it to choose: `"delete"` (the default), `"stop"` to shut it down and keep its disk, or `"pause"` to pause it. Both work on every plan. The sandbox's `on_timeout` field shows what it will do.

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cpus": 2, "timeout_minutes": 60, "on_timeout": "stop"}'
```

In the SDKs: `stop_sandbox(id)` and `start_sandbox(id)`. In the CLI: `groundbox sandbox stop <id>` and `groundbox sandbox start <id>`. For agents, the MCP tool `sandbox` with action `stop` or `start`.

## Idle pause and wake on request

Set `idle_timeout_seconds` and the sandbox is paused when nothing has used it for that long. Its memory and processes are kept, and it is billed for storage only while it sleeps. The next request that needs it wakes it: the request waits while the sandbox resumes, then goes through. Off by default. The least is 30 seconds.

```
# Pause after 5 idle minutes. The next request wakes it.
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"idle_timeout_seconds": 300}'

# Change it, or turn it off with null.
curl -X PATCH https://api.groundbox.dev/v1/sandboxes/sbx_... \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"idle_timeout_seconds": 60, "idle_cpu_percent": 20}'

# Pause by hand, and let the next request wake it.
curl -X POST https://api.groundbox.dev/v1/sandboxes/sbx_.../pause \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"wake_on_request": true}'
```

What counts as activity:

- A command, an exec stream, a file call, a desktop action, a save point or an update.
- A connection that is still open: a running command, a terminal, a desktop view.
- A command started through the API that is still running, also after its caller disconnected.
- Preview traffic, and a preview connection that is still open.

A command counts for as long as it runs. To let a sandbox sleep while a server stays up in it, start the server so that the command returns: `nohup npm run dev > /tmp/dev.log 2>&1 &`. The server is paused with the rest and goes on when the sandbox wakes.

CPU use inside the sandbox does not count. To keep a background job running, set `idle_cpu_percent`: the sandbox is then not idle while it uses more than that share of one core. Reading the sandbox (`GET /v1/sandboxes/{id}`, its usage) is not activity and does not wake it.

What wakes it:

- A sandbox paused by its idle timeout wakes on the next command, exec stream, file call, desktop action or fork, and on a request to one of its previews. Set `wake_on_request: false` to keep it paused until you resume it.
- A sandbox you paused yourself stays paused until you resume it. Pause with `wake_on_request: true` to have the next request wake it instead.
- The sandbox shows which it is: `pause_reason` is `idle` or `manual`, and `wakes_on_request` says whether a request will wake it.

A wake is a resume. It needs credit and room under your sandbox limit, and answers with the same errors when it has neither. The timeout (`timeout_minutes`) still applies: it counts from the last start or wake, so a sandbox that never goes idle stops at its timeout, and each wake starts it again. After a start or a wake the sandbox stays up for at least 60 seconds. A sandbox left paused for a long time is deleted, however it was paused.

An idle pause needs what a pause needs. A sandbox with volumes cannot be paused, so `idle_timeout_seconds` is refused for it. A fork keeps its source's idle pause; the copies of a fork with `count` do not, and can be given one with an update. When your team already keeps as many paused sandboxes as it may, an idle sandbox stays up.

## Scheduled runs

A schedule is a cron expression, a sandbox spec and a command. Each run gets a fresh sandbox, which is destroyed when the command exits.

```
curl https://api.groundbox.dev/v1/schedules \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cron": "0 3 * * *", "timezone": "UTC", "cmd": "./run-evals.sh", "sandbox": {"cpus": 4}}'
```

```
groundbox schedules create --cron "0 3 * * *" --name nightly --timezone Europe/Berlin --cpus 4 -- ./nightly.sh
groundbox schedules list
groundbox schedules rm <schedule_id>
```

`create` also takes `--memory-gb N`, `--template NAME` and `--secret NAME`. API: `POST /v1/schedules` (`schedules:write`), `GET /v1/schedules` (`schedules:read`) and `DELETE /v1/schedules/{id}` (`schedules:write`), which stops it; a run already started goes on. SDKs: `schedule_command`, `list_schedules` and `delete_schedule`. MCP: the `command` tool's `schedule` and `delete_schedule` actions, and `command_info` with action `schedules`.

## Egress rules

Set `allow_hosts` to choose the hosts a sandbox can reach. Everything else is blocked.

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cpus": 2, "allow_hosts": ["github.com", "*.npmjs.org", "140.82.112.0/20"]}'
```

Set `deny_hosts` for the opposite: the sandbox reaches everything but these.

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cpus": 2, "deny_hosts": ["*.tracker.example.net", "203.0.113.0/24"]}'
```

An entry in either list is one of four things.

- A host name, like `github.com`. It matches that name only.
- A wildcard, like `*.npmjs.org`. It matches every name under the domain, at any depth. It does not match the domain itself, so list `npmjs.org` too if you need it.
- An IPv4 address, like `203.0.113.7`.
- An IPv4 network, like `140.82.112.0/20`.

You can set both lists. A denied entry wins: allow `*.example.com` and deny `internal.example.com` to carve one name out. Change either list while the sandbox runs. The change applies at once, and `null` removes a list.

```
curl -X PATCH https://api.groundbox.dev/v1/sandboxes/sbx_8f3k2m9x1q7w \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"allow_hosts": ["github.com"], "deny_hosts": null}'
```

In the CLI it is `--allow-host` and `--deny-host` on `sandbox create`, and `groundbox sandbox egress <id>` to see or change the rules later. The SDKs have `set_egress`, and the MCP server has the `sandbox` tool's `egress` action.

### DNS

A sandbox with egress rules has its DNS answered by Groundbox, whichever DNS server it asks. With an allowlist, only the names on the list resolve. Any other name gets no answer and the lookup never leaves Groundbox, so a sandbox cannot pass data out in lookups of names you did not list. With a deny list, the denied names do not resolve.

What the rules do not do:

- A lookup under an allowed wildcard reaches that domain's own name servers. Allow a wildcard only for a domain you trust with what the sandbox knows.
- The rules match hosts, not URLs or ports. A sandbox that may reach a host may send it anything.
- Names are matched to addresses. Two names on one address, as behind a shared CDN, are allowed or denied together.
- A deny list of names holds against ordinary DNS. A sandbox with only a deny list can still reach an encrypted DNS service or connect to an address it already knows. Deny the address or network to close that, or use an allowlist when the sandbox must be sealed.
- Sandboxes have no IPv6 route out, so the rules are IPv4 only.

## Secrets

A secret is a named value your team keeps with Groundbox: an API token, a password. Set it once. The value is stored encrypted and cannot be read back, by the API, the CLI or the dashboard.

```
curl -X PUT https://api.groundbox.dev/v1/secrets/NPM_TOKEN \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"value": "npm_..."}'
```

A sandbox gets a secret in one of two ways. As a variable, the value is inside the sandbox. As a binding to a host, the value stays outside it and is added to the sandbox's HTTPS requests to that host.

Give a sandbox secrets by name. Every command in it gets them as environment variables. `secrets` uses the secret's name as the variable name. `env_from_secrets` picks another variable name.

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cpus": 2, "secrets": ["NPM_TOKEN"], "env_from_secrets": {"PGPASSWORD": "DB_PASSWORD"}}'
```

- The sandbox keeps only the names. The value is read each time a command starts, so a replaced secret is used from the next command.
- A fork uses the same secrets as its source. A schedule's sandbox spec takes the same two fields.
- A template takes `secrets` for its build: the build's steps get them as variables. They are not written to the template, its sandboxes do not get them, and the build log shows the secret's name in place of its value.
- If a secret is deleted, the next command in a sandbox that uses it fails with 409 and names the secret. Set it again and the sandbox works again.
- A command's own `env` wins over a secret of the same variable name.

API keys have three scopes for this. `secrets:write` sets and deletes. `secrets:read` lists names. `secrets:use` lets a key give secrets to a sandbox, a schedule or a template, as variables or as bindings. A key that only runs commands needs none of them.

In the CLI: `groundbox secrets set NAME` reads the value from stdin, `groundbox secrets list`, and `--secret NAME` or `--bind-secret HOST=NAME` on `sandbox create`. The dashboard has a Secrets tab under Sandboxes.

What to know about secrets as variables:

- A secret given as a variable is inside the sandbox. Code that runs there can read it, print it or send it anywhere the sandbox can reach.
- Pair secrets with an allowlist, so a token can only travel to the hosts that need it. Or bind the secret to its host instead.
- Command output is not filtered. If a command prints a secret, the output has it.
- Processes that were not started through the API, such as a desktop's browser, do not get secrets.

### Secret bindings

A binding keeps a secret out of the sandbox. The box's secrets proxy adds it as a header to the sandbox's HTTPS requests to one host. Code in the sandbox calls the API as usual and never sees the value, so it cannot print it or send it anywhere else.

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "cpus": 2,
    "secret_bindings": [
      {"host": "api.openai.com", "secret": "OPENAI_KEY", "env_placeholder": "OPENAI_API_KEY"},
      {"host": "api.anthropic.com", "secret": "ANTHROPIC_KEY", "header": "x-api-key", "format": "{value}", "env_placeholder": "ANTHROPIC_API_KEY"}
    ]
  }'
```

Each binding takes:

- `host`: an exact host name, or a wildcard of one label: `*.example.com` covers `a.example.com`, not `a.b.example.com`. IP addresses and private names (`localhost`, `.internal`, `.local` and the like) are refused.
- `secret`: the name of a team secret.
- `header`: the header to set. `Authorization` by default.
- `format`: the header's value, with `{value}` where the secret goes. `Bearer {value}` by default.
- `env_placeholder` (optional): a variable the sandbox gets with the value `groundbox-secrets-proxy-placeholder`, for SDKs that will not start without a key. The proxy puts the real value in the header.

A sandbox takes up to 10 bindings, and the key needs `secrets:use`. A schedule's sandbox spec takes `secret_bindings` too. In the CLI it is `--bind-secret`, once per binding, with options after commas:

```
groundbox sandbox create --bind-secret api.openai.com=OPENAI_KEY
groundbox sandbox create --bind-secret 'api.anthropic.com=ANTHROPIC_KEY,header=x-api-key,format={value},env=ANTHROPIC_API_KEY'
```

How it works:

- The sandbox's DNS answers a bound host with the proxy's address. Every other host resolves and connects exactly as before: it is not proxied, not decrypted, and gets no added latency.
- The proxy ends TLS only for bound hosts, with a certificate from the sandbox's own CA. That CA can only sign the bound hosts, and it is put in the sandbox's trust store at boot. Commands also get `NODE_EXTRA_CA_CERTS`, `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE` and `CURL_CA_BUNDLE` pointing at it.
- The proxy then opens its own TLS connection to the real host and checks its certificate in full. HTTP/1.1, HTTP/2 (gRPC too) and WebSocket upgrades work.
- The proxy masks the value as `*`s in response headers and in response bodies that are not compressed, so an endpoint that echoes the request does not hand it back. Compressed bodies and WebSocket frames are not scanned.
- A replaced secret is used from the next request. If a bound secret is deleted, requests to its host fail with 502 and a body that names the secret.
- A fork keeps its source's bindings, and so do pause and resume.
- A binding lets its host through an allowlist without listing it. If a deny list covers the host, the deny list wins and the create is refused.
- It is opt-in. A sandbox without bindings has no proxy in its path and no extra CA. CI jobs are unchanged.

What bindings do not do:

- A client that pins certificates, or ignores both the system trust store and those variables, fails TLS to a bound host. Some Rust builds with webpki-roots do, and so does Java without the certificate in its keystore.
- Only HTTPS is proxied. A plain `http://` request to a bound host gets no header.
- Code that connects to a hardcoded IP address, or looks names up over DNS-over-HTTPS, goes around the proxy. Its requests simply carry no credential.

## Flex

Set `flex: true` for half price ($0.02 per vCPU-hour) on work that can wait: batch agent runs, evals, data jobs, scheduled runs. In the CLI it is `--flex`.

```
curl https://api.groundbox.dev/v1/sandboxes \
  -H "Authorization: Bearer $GROUNDBOX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"cpus": 4, "flex": true}'
```

A flex sandbox starts when a box has spare room after full-price work, so it may stay `queued` for a while. Its timeout counts from when it starts. One that has not started in 24 hours fails. A running flex sandbox is never stopped to make room.
