# Sandbank Cloud — Sandbox SDK & CLI

You are interacting with Sandbank Cloud, a managed sandbox infrastructure for AI agents.
Base URL: `https://api.sandbank.dev`

## CLI

Install: `npm install -g sandbank`

```bash
sandbank login --api-key <key>              # Save credentials
sandbank create [--image codebox]           # Create sandbox
sandbank list                               # List sandboxes
sandbank get <id>                           # Get details
sandbank exec <id> <command>                # Execute command
sandbank destroy <id>                       # Destroy sandbox
sandbank clone [<id>]                       # Clone (defaults to self inside sandbox)
sandbank keep <id> [--minutes 30]           # Extend timeout
sandbank addons create <type> [--intent ""] # Create addon
sandbank addons list                        # List addons
sandbank snapshot create|list|restore|delete # Manage snapshots
```

All commands support `--json` for structured output.

**Authentication auto-detection:** The CLI reads credentials in this order:
1. `--api-key` flag
2. `SANDBANK_API_KEY` env var
3. `SANDBANK_AGENT_TOKEN` env var (inside sandbox — inherits creator's identity)
4. `~/.sandbank/credentials.json` (saved by `sandbank login`)
5. `--wallet-key` / `SANDBANK_WALLET_KEY` for x402 USDC payment

Inside a sandbox, the CLI works without any configuration — `SANDBANK_AGENT_TOKEN` is auto-injected.

## Authentication

Four modes are supported:

1. **API Token** — Pass `Authorization: Bearer <token>` on every request. Bypasses x402 payment (free access). Higher resource limits (8 vCPU / 8192 MB).
2. **Agent Token** — Box-local control-plane token injected inside the sandbox as `SANDBANK_AGENT_TOKEN`. Pass `Authorization: Bearer <token>`. Represents that box, can manage it, create/list addons, and create new sibling boxes (inheriting the creator's identity and quota).
3. **Box Access Token** — Box-scoped capability token returned by create/clone responses as `access_token`. Pass it as `X-Sandbank-Box-Token: <token>` or `?box_token=<token>` for box-scoped routes.
4. **x402 Payment** — No token needed for `POST /v1/boxes`. Paid endpoints return HTTP 402 with payment details. Pay with USDC on Base (eip155:8453) via the x402 protocol. Resource limits: 2 vCPU / 1024 MB.

Paid endpoints: `POST /v1/boxes` ($0.02), `POST /v1/boxes/:id/keep` ($0.02 with box access token).
All other box-scoped endpoints require an API token, an agent token for that box, or that box's access token.
Each x402 sandbox session lasts 10 minutes. Use `/keep` to extend.

## API Reference

### Create Sandbox

```
POST /v1/boxes
Content-Type: application/json

{
  "image": "codebox",
  "cpu": 2,
  "memory_mb": 1024,
  "ports": [[0, 8080], [0, 7681]],
  "name": "my-sandbox",
  "env": { "MY_API_KEY": "sk-..." }
}
```

Response (201):
```json
{
  "id": "aQscOYX87tSq",
  "status": "running",
  "image": "codebox",
  "cpu": 2,
  "memory_mb": 1024,
  "ports": { "8080": 10042, "7681": 10043 },
  "access_token": "..."
}
```

- `image`: Currently only `codebox` is supported (default). See "Default Image" section below.
- `cpu`: Number of CPU cores (default: 1, max: 2 for x402, 8 for API token)
- `memory_mb`: Memory in MB (default: 512, max: 1024 for x402, 8192 for API token)
- `ports`: Array of `[host, guest]` pairs. Use `0` for host to auto-allocate. Recommended: `[[0, 7681], [0, 8080]]` — 7681 is web terminal (ttyd), 8080 is web service.
- `name`: Optional human-readable name
- `env`: Optional environment variables injected into the sandbox (useful for passing API keys)

> Resource limits depend on auth mode. Values exceeding the limit are clamped silently.

### Execute Command

```
POST /v1/boxes/:id/exec
Content-Type: application/json

{
  "cmd": ["bash", "-c", "echo Hello"],
  "timeout_seconds": 300,
  "working_dir": "/home"
}
```

Response:
```json
{
  "exit_code": 0,
  "stdout": "Hello\n",
  "stderr": ""
}
```

### Extend Timeout (Keep-Alive)

```
POST /v1/boxes/:id/keep
X-Sandbank-Box-Token: <box-access-token>
```

Response: `{ "id": "...", "expires_in_minutes": 10 }`

### Get Sandbox

```
GET /v1/boxes/:id
```

### List Sandboxes

```
GET /v1/boxes
GET /v1/boxes?status=running
```

### Destroy Sandbox

```
DELETE /v1/boxes/:id
```

### Upload Files

```
PUT /v1/boxes/:id/files?path=/dest
Content-Type: application/x-tar

<tar archive body>
```

A tar archive is extracted into the `path` directory. Any other body is written as a
single file at `path` (for example `?path=/root/setup.sh`), with mode 644 unless you
pass `&mode=755`.

### Download Files

```
GET /v1/boxes/:id/files?path=/src
```

Returns a tar archive.

### Start / Stop Sandbox

```
POST /v1/boxes/:id/start
POST /v1/boxes/:id/stop
```

Start a stopped sandbox or stop a running one.

### Clone Box

```
POST /v1/boxes/:id/clone
Content-Type: application/json

{
  "name": "my-clone"
}
```

Response (201):
```json
{
  "id": "clonedBoxId",
  "name": "my-clone",
  "status": "stopped",
  "image": "codebox",
  "cpu": 2,
  "memory_mb": 1024,
  "ports": { "8080": 10050, "7681": 10051 },
  "access_token": "..."
}
```

Creates a COW (copy-on-write) clone of an existing box. The clone is a new independent box with its own ID, sharing the source box's disk data efficiently. The source box is briefly paused (~50ms) during clone — not stopped.

- Clone inherits the source box's full filesystem state (installed tools, files, configs)
- Clone is created in stopped state — call `POST /v1/boxes/:id/start` to run it
- Source box continues running uninterrupted
- Use for: parallel agents, template distribution, branching experiments

### Snapshots

Create a snapshot of the current box state:

```
POST /v1/boxes/:id/snapshots
Content-Type: application/json

{
  "name": "my-snapshot"
}
```

Response (201):
```json
{
  "name": "my-snapshot",
  "snapshotId": "my-snapshot"
}
```

List snapshots:

```
GET /v1/boxes/:id/snapshots
```

Response:
```json
[
  {
    "id": "sohpDf1i",
    "box_id": "aQscOYX87tSq",
    "name": "my-snapshot",
    "created_at": 1774369165,
    "size_bytes": 6553600
  }
]
```

Restore a snapshot:

```
POST /v1/boxes/:id/snapshots/:name/restore
```

Response: `{ "ok": true }`

Delete a snapshot:

```
DELETE /v1/boxes/:id/snapshots/:name
```

Notes:
- Snapshots capture the full VM state (memory + disk)
- Restoring a snapshot returns the box to the exact state when the snapshot was taken
- A snapshot that the current disk depends on cannot be deleted — restore a different snapshot first
- Use for: checkpointing before risky operations, branching experiments, saving known-good states

### Addon Boxes

Create an addon for a parent box:

```
POST /v1/boxes/:id/addons
Authorization: Bearer <agent-token>
Content-Type: application/json

{
  "type": "mailsbox",
  "intent": "Watch for verification code emails and relay them immediately."
}
```

Response (201):
```json
{
  "id": "addonBoxId",
  "type": "mailsbox",
  "parent_id": "parentBoxId",
  "status": "running",
  "relay_name": "mailsbox-ab12cd34"
}
```

List a parent's addons:

```
GET /v1/boxes/:id/addons
```

Notes:

- Addon creation is a privileged control-plane operation.
- Sandbox-local agents should usually use `SANDBANK_AGENT_TOKEN` against their own `SANDBANK_BOX_ID`.
- Box access tokens and x402 payments are not enough for `POST /v1/boxes/:id/addons`.
- Addon creation is idempotent per parent box and addon type.
- Parent ↔ addon coordination happens over the relay. Do not try to access addon boxes directly via HTTP.

### HTTP Proxy

```
GET/POST/... /v1/boxes/:id/proxy/:guestPort/path
```

Proxies HTTP requests to the guest service. Also supports WebSocket upgrade.
For browser clients, pass the box access token as a query parameter: `?box_token=<box-access-token>`.
WebSocket proxy also accepts `?token=<api-token-or-agent-token>` for bearer-token-authenticated clients.

### Terminal Watch Link (read-only)

```
POST   /v1/boxes/:id/terminal/watch   {"terminal_name": "main", "session": "main", "ttl_s": 28800}
DELETE /v1/boxes/:id/terminal/watch?terminal_name=main
```

Returns `{url, expires_at, watchers}`: a capability WebSocket URL
(`wss://<host>/v1/boxes/:id/terminal/ws?token=…`) that an audience can open to watch a tmux
session inside a running box. All fields are optional: `terminal_name` defaults to `main`,
`session` (tmux session) defaults to `TMUX_SESSION_NAME` from `/etc/vibelab/terminal-<name>.env`
or the terminal name, and `ttl_s` defaults to 8 hours (clamped to 60 s – 24 h).

- One live link per (box, terminal): asking again returns the same link, shared by the audience.
- The node agent reads the pane itself (`tmux capture-pane` via exec, about every 700 ms, as the
  terminal's login user) only while someone is watching; nothing has to run inside the box.
- Frames are the terminal relay's JSON frames: `snapshot` (`rows`, `cols`, `payload`) and
  `status` (`upstream`, `spectators`). Anything a viewer sends is dropped.
- At most 200 viewers per link (503 above). `DELETE`, expiry or stopping the box ends the link:
  open viewers are closed with code 4410 and the URL answers 410 from then on.

## Lifecycle Webhooks

Sandbank Cloud can deliver box lifecycle status changes to webhooks. Tenants can configure tenant lifecycle delivery from the Sandbank Panel, backed by the authenticated panel API at `/v1/panel/webhook`. Operator-managed environment configuration remains available for admin delivery and legacy tenant delivery.

There are two webhook audiences:

- Admin webhook: receives full operator-facing lifecycle events, including `node_id`, `source`, and internal `detail` fields.
- Tenant webhook: matched by the box `user_id` and delivered only to that tenant. Tenant payloads omit admin-only fields such as `node_id`, `source`, and `detail`.

Panel-managed tenant webhooks are tenant-scoped and apply to boxes created under that tenant's projects. Legacy environment-managed tenant ids must match the `user_id` stored on boxes. For API-key based tenants, this is the label in `AGENT_API_KEYS`, for example `AGENT_API_KEYS=wanman:key`.

Tenant webhook events:

- `box.error`
- `box.terminated`
- `box.status_changed`

Tenant payload example:

```json
{
  "event": "box.error",
  "audience": "tenant",
  "tenant_id": "wanman",
  "box_id": "box-1",
  "image": "codebox",
  "previous_status": "running",
  "status": "error",
  "reason": "probe_failure",
  "observed_at": "2026-05-01T05:41:00.000Z"
}
```

Tenant webhook requests include `X-Sandbank-Tenant`, `X-Sandbank-Event`, and `X-Sandbank-Delivery`. If a tenant secret is configured, Sandbank also sends `X-Sandbank-Signature: sha256=<hmac-sha256>` where the HMAC is computed over the exact JSON request body. If a token is configured, Sandbank sends `Authorization: Bearer <token>`.

Tenant panel API:

- `GET /v1/panel/webhook` returns the current tenant webhook without exposing the secret or token.
- `PUT /v1/panel/webhook` saves `{ "url", "enabled", "events", "timeout_ms", "secret"?, "token"?, "clear_secret"?, "clear_token"? }`.
- `DELETE /v1/panel/webhook` removes the tenant webhook.

Operator configuration examples:

```bash
ADMIN_BOX_LIFECYCLE_WEBHOOK_URL=https://ops.example.com/webhooks/sandbank
ADMIN_BOX_LIFECYCLE_WEBHOOK_TOKEN=change-me
ADMIN_BOX_LIFECYCLE_WEBHOOK_TIMEOUT_MS=2000
```

Legacy `BOX_LIFECYCLE_WEBHOOK_*` variables are still accepted as fallbacks, but `ADMIN_BOX_LIFECYCLE_WEBHOOK_*` is preferred for new deployments.

```bash
TENANT_BOX_LIFECYCLE_WEBHOOKS='{
  "wanman": {
    "url": "https://wanman.example.com/webhooks/sandbank",
    "secret": "wanman-hmac-secret",
    "token": "optional-bearer-token",
    "events": ["box.error", "box.terminated"],
    "timeout_ms": 1500
  }
}'
TENANT_BOX_LIFECYCLE_WEBHOOK_TIMEOUT_MS=2000
```

## Typical Workflow

1. Create a sandbox with `POST /v1/boxes` (pays $0.02 USDC via x402 or uses an API token)
2. Save the returned `access_token` if you are not using an API token
3. Execute commands with `POST /v1/boxes/:id/exec`
4. Upload/download files as needed
5. Call `POST /v1/boxes/:id/keep` before 10 min timeout if needed
5. Destroy with `DELETE /v1/boxes/:id` when done

### Cloning

1. Create and configure a "template" box
2. Clone it with `POST /v1/boxes/:id/clone` (~100ms, COW)
3. Start the clone with `POST /v1/boxes/:id/start`
4. Use the clone independently
5. Destroy clone when done — template is unaffected

### Sandbox Environment

Codeboxes and agentboxes receive these control-plane environment variables:

- `SANDBANK_API_URL` — HTTP API base URL reachable from inside the sandbox
- `SANDBANK_BOX_ID` — current box ID
- `SANDBANK_AGENT_TOKEN` — box-local control-plane token for this box

## Resource Limits

| | x402 (pay-per-use) | API Token |
|---|---|---|
| Max CPU | 2 vCPU | 8 vCPU |
| Max Memory | 1024 MB | 8192 MB |
| Session | 10 min (extendable) | 30 min (extendable) |
| Max concurrent | 50 | 50 |

## Default Image: codebox

Pre-built development sandbox with AI coding agent support. Based on Ubuntu 24.04.

**AI Coding Agents:**
- **Claude Code** (@anthropic-ai/claude-code)
- **Codex** (@openai/codex)

**Languages & Runtimes:**
- Node.js 22, Bun, Python 3, Go 1.23

**Package Managers:**
- npm, pnpm (via Node.js), uv (Python), go modules

**Dev Tools:**
- git, gh (GitHub CLI), make, build-essential
- ripgrep (rg), fd, tmux, vim, nano
- curl, wget, jq, htop, tree, less, unzip

**Browser Automation:**
- `browser` CLI — headless browser control via accessibility tree (no screenshots needed)
- Two modes:
  - **Default (Lightpanda):** Fast, lightweight. `browser open <url>` — good for reading pages, scraping, simple forms
  - **Chrome (Browserbox):** Real Chrome in a dedicated VM. `browser open --chrome <url>` — for login flows, complex JS/SPAs, OAuth, CAPTCHAs
- Provision a browserbox addon first with `POST $SANDBANK_API_URL/v1/boxes/$SANDBANK_BOX_ID/addons` and `Authorization: Bearer $SANDBANK_AGENT_TOKEN`.
- Once a browserbox addon exists, all subsequent `--chrome` commands auto-route to it. `browser destroy` returns to Lightpanda.
- Workflow: `browser open <url>` → `browser snapshot -i` → `browser click @ref` → repeat
- Chrome workflow: `browser open --chrome <url>` → interact → `browser save <name>` (snapshot VM state) → `browser destroy`
- See `browser --help` for full command reference

**Database (db9):**
- `db9` CLI — serverless PostgreSQL management for AI agents (db9.ai)
- `psql` — standard PostgreSQL client for direct SQL access
- Create databases: `db9 db create --name myapp`
- Execute SQL: `db9 db sql <db> -q "SELECT ..."`
- Branch databases: `db9 branch create <db> --name test`
- Built-in: pgvector, pg_cron, fs9 filesystem, HTTP extension, full-text search
- Auth: `db9 login` or pass DB9_TOKEN env var
- Full docs: read the db9 skill file at `~/.claude/skills/db9.md`

**Ports:**
- 7681: web terminal (ttyd)
- 8080: web service

**Warm pool enabled** — sub-second cold start.

Supported image shorthands are `"codebox"` for the default dev sandbox, `"browserbox"` for lightweight chrome-headless-shell automation, and `"chromebox"` for full Chromium with a persistent profile and CDP on port 9222. You can omit the `image` field to use `"codebox"`.

## Notes

- Sandboxes are KVM-isolated bare-metal instances (not containers)
- Warm pool provides sub-second start times for the codebox image
- Port forwarding maps guest ports to host ports automatically
- WebSocket proxy available at `/v1/boxes/:id/proxy/:port/` with `Upgrade: websocket`
- Default exec timeout is 5 minutes (configurable via `timeout_seconds`)
- Resources exceeding the limit are clamped silently (no error returned)
- Claude Code and Codex are pre-installed — pass your API keys via the `env` field to use them inside the sandbox
