# HTTP API

> The JSON API each deployment serves, which the CLI and SDKs use: the admin key, every endpoint, request and response bodies, streamed and background commands, files, agents and their events, nodes, errors, and the OpenAPI document.

Your deployment serves a JSON API at its own URL, `https://cloudex-api.<your-subdomain>.workers.dev`. The CLI and the [SDKs](https://cloudex.build/docs/sdk.md) are clients of it. There is no shared Cloudex API; each deployment has its own.

## Authentication

Every request under `/v1` needs a key as a bearer token, except `/v1/health`, `/v1/openapi.json`, the two device sign-in calls and the [node agent's routes](#nodes):

```http
Authorization: Bearer <admin key or token>
```

The key is the deployment's admin key or an [access token](https://cloudex.build/docs/tokens.md). `cloudex deploy` creates the admin key and stores it as a Worker secret; `cloudex status --show-key` prints the API URL and the key this computer uses. The admin key gives full control of every sandbox, so keep it on your computer or a server, not in a web page, and give everything else a token with the role it needs.

The [dashboard](https://cloudex.build/docs/dashboard.md) calls the same API with a session cookie instead. A request with the cookie must also carry `X-Cloudex: 1` and, when the browser sends one, the deployment's own `Origin`; anything else gets `403`. Clients other than the dashboard should send a bearer key.

A missing or wrong key, or a revoked or expired token, gets `401` with an `error` that starts `unauthorized`. A token whose role doesn't allow a call gets `403`, and an own-only token naming a sandbox it didn't make gets `404`, as if there were none. `GET /v1/me` says who the key belongs to.

## The OpenAPI document

Each deployment describes itself at `<API URL>/v1/openapi.json`, an OpenAPI 3.1 document with every endpoint, request body and response. It needs no key. Its `info.version` is the deployment's version.

```sh
curl https://cloudex-api.<your-subdomain>.workers.dev/v1/openapi.json
```

## Endpoints

`{ref}` is a sandbox's id, such as `cx-7f3a2k`, or its name.

| Method | Path | Does |
|---|---|---|
| `GET` | `/v1/health` | The deployment's version, preview domain and whether backups are on. No key needed. |
| `GET` | `/v1/openapi.json` | The OpenAPI document. No key needed. |
| `GET` | `/v1/sandboxes` | List sandboxes, newest first |
| `POST` | `/v1/sandboxes` | Create and start a sandbox; answers `201` once it's running |
| `GET` | `/v1/sandboxes/{ref}` | Get a sandbox |
| `PATCH` | `/v1/sandboxes/{ref}` | Rename a sandbox, or change its idle time |
| `DELETE` | `/v1/sandboxes/{ref}` | Delete a sandbox and its backups. On a node that's offline, only with `force=true`. |
| `POST` | `/v1/sandboxes/{ref}/stop` | Save the disk, back up `/home` and stop |
| `POST` | `/v1/sandboxes/{ref}/resume` | Start a stopped sandbox from its save, or from its backup |
| `POST` | `/v1/sandboxes/{ref}/fork` | Make sandboxes that start from a copy of this one's disk; answers `201` with the forks |
| `POST` | `/v1/sandboxes/{ref}/saves` | Save a running sandbox's disk under a name; answers `201` with the [save](https://cloudex.build/docs/saves.md) |
| `GET` | `/v1/saves` | List the named saves, newest first |
| `GET` | `/v1/saves/{name}` | Get a named save |
| `DELETE` | `/v1/saves/{name}` | Delete a named save |
| `POST` | `/v1/saves/{name}/sandboxes` | Start sandboxes from a named save; answers `201` with them |
| `POST` | `/v1/sandboxes/{ref}/exec` | Run a command with `bash -lc` and wait for it, or with `stream` get its output as it comes. See [Commands](#commands). |
| `POST` | `/v1/sandboxes/{ref}/commands` | Start a command in the background; answers `201` once it runs |
| `GET` | `/v1/sandboxes/{ref}/commands` | List the background commands, newest first |
| `GET` | `/v1/sandboxes/{ref}/commands/{cmd}` | Get a background command |
| `GET` | `/v1/sandboxes/{ref}/commands/{cmd}/output` | Read its output from a byte offset, waiting for more with `wait` |
| `POST` | `/v1/sandboxes/{ref}/commands/{cmd}/kill` | Send it, and what it started, a signal |
| `DELETE` | `/v1/sandboxes/{ref}/commands/{cmd}` | Remove a finished command's record and output |
| `GET` | `/v1/sandboxes/{ref}/files?path=` | A path's details, and a directory's entries. See [Files](#files). |
| `DELETE` | `/v1/sandboxes/{ref}/files?path=` | Delete a file, or with `recursive=true` a directory |
| `GET` | `/v1/sandboxes/{ref}/files/content?path=` | Download a file |
| `PUT` | `/v1/sandboxes/{ref}/files/content?path=` | Upload a file |
| `GET` | `/v1/sandboxes/{ref}/files/archive?path=` | Download a directory as a tar.gz |
| `PUT` | `/v1/sandboxes/{ref}/files/archive?path=` | Unpack a tar.gz into a directory |
| `POST` | `/v1/sandboxes/{ref}/hosts` | Get an HTTPS link to a port on the preview domain |
| `GET` | `/v1/sandboxes/{ref}/hosts` | List the links handed out that still work |
| `DELETE` | `/v1/sandboxes/{ref}/hosts` | Revoke every link to the sandbox, the desktop's too |
| `DELETE` | `/v1/sandboxes/{ref}/hosts/{port}` | Revoke a port's link |
| `POST` | `/v1/sandboxes/{ref}/desktop` | Start the desktop, installing it the first time, or resize it |
| `DELETE` | `/v1/sandboxes/{ref}/desktop` | Stop the desktop and the programs on it |
| `GET` | `/v1/sandboxes/{ref}/tcp/{port}` | A WebSocket carrying a TCP connection to a port in the sandbox |
| `GET` | `/v1/sandboxes/{ref}/direct?port=` | Where to connect to a port: through `tcp`, or straight to the sandbox's node with a ticket. The CLI's ssh uses it; see [Direct connections](https://cloudex.build/docs/nodes.md#direct-connections). A token's 65th ticket for one sandbox within a minute gets `429`. |
| `GET` | `/v1/sandboxes/{ref}/terminal` | A WebSocket to a shell under a terminal. See [Terminal over WebSocket](#terminal-over-websocket). |
| `GET` | `/v1/sandboxes/{ref}/desktop/vnc` | A WebSocket to the desktop's VNC server, for a VNC client such as noVNC |
| `GET` | `/v1/sandboxes/{ref}/settings` | The sandbox's variable names, file paths and repo; never values |
| `PATCH` | `/v1/sandboxes/{ref}/settings` | Set environment variables and files, or remove them with `null`; see [Settings](https://cloudex.build/docs/settings.md) |
| `POST` | `/v1/sandboxes/{ref}/agents` | Start Claude Code or Codex on a task; answers `201` at once. See [Agents](#agents). |
| `GET` | `/v1/sandboxes/{ref}/agents` | List the sandbox's agents, newest first |
| `GET` | `/v1/sandboxes/{ref}/agents/{agent}` | Get an agent |
| `GET` | `/v1/sandboxes/{ref}/agents/{agent}/events` | Read an agent's events, waiting for new ones with `wait` |
| `POST` | `/v1/sandboxes/{ref}/agents/{agent}/messages` | Send a message, which starts the next turn |
| `POST` | `/v1/sandboxes/{ref}/agents/{agent}/interrupt` | Stop the running turn and drop queued messages |
| `GET` | `/v1/keys` | List the stored [provider keys](https://cloudex.build/docs/keys.md), by their last 4 characters |
| `PUT` | `/v1/keys/{provider}` | Store or replace the key for a [provider](https://cloudex.build/docs/keys.md): `anthropic`, `openai`, `openrouter`, `google`, `groq`, `mistral`, `xai` or `deepseek` |
| `DELETE` | `/v1/keys/{provider}` | Remove a provider's key |
| `GET` | `/v1/me` | Who the key belongs to: `{"role", "ownOnly", "token"}`, with `token` `null` for the admin key |
| `POST` | `/v1/tokens` | Make an [access token](https://cloudex.build/docs/tokens.md); answers `201` with its `secret`, which nothing shows again |
| `GET` | `/v1/tokens` | List the tokens, newest first |
| `DELETE` | `/v1/tokens/{id}` | Revoke a token; it stops working at once |
| `POST` | `/v1/auth/device` | Start a device sign-in ([RFC 8628](https://www.rfc-editor.org/rfc/rfc8628)). No key needed. |
| `POST` | `/v1/auth/token` | Collect the token once the sign-in is approved. No key needed. |
| `GET` | `/v1/auth/device` | List the sign-ins waiting for approval |
| `POST` | `/v1/auth/device/approve` | Approve a sign-in by its `user_code` |
| `POST` | `/v1/auth/device/deny` | Refuse a sign-in by its `user_code` |
| `POST` | `/v1/auth/links` | A link that signs a browser in to the [dashboard](https://cloudex.build/docs/dashboard.md) once, within 60 seconds, with the caller's role. `{"path"}` is the page it opens: `/`, `/saves`, `/access` or `/s/{sandbox}/…`. A dashboard session can't make one (`403`). |
| `POST` | `/v1/auth/session` | The dashboard's login page signing in. No key needed. A pasted dashboard session gets `403`. |
| `DELETE` | `/v1/auth/session` | Sign the dashboard out. No key needed. |
| `GET` | `/v1/nodes` | List the [nodes](https://cloudex.build/docs/nodes.md), with whether each is online now; `live=false` answers from the index without asking each node |
| `POST` | `/v1/nodes` | Add a node; answers `201` with its join token and the command that installs its agent |
| `GET` | `/v1/nodes/{node}` | Get a node by name or id; for admins, with a round trip to its agent while it's online |
| `DELETE` | `/v1/nodes/{node}` | Remove a node, or forget a removed one; `force=true` when it still has sandboxes |

[Tokens](https://cloudex.build/docs/tokens.md#roles) reach the endpoints their role allows: `read` the `GET`s, except preview links and the TCP bridge; `user` everything but tokens, provider keys, sign-in approvals, and adding and removing nodes, which are for `admin`.

## Request bodies

All bodies are JSON. Fields with a default can be left out, and so can a body whose fields are all optional.

| Endpoint | Fields |
|---|---|
| Create | `name`: 2 to 32 lowercase letters, digits and hyphens, starting with a letter, not ending with a hyphen, and not starting with `cx-`. `size`: `standard-1` to `standard-4`, default `standard-2`. `idleMinutes`: 0 to 360, default 30; 0 leaves only Cloudflare's 6-hour limit, and on a node means never. `node`: a [node](https://cloudex.build/docs/nodes.md)'s name or id, to run it there. `cpus` (from 0.25) and `memoryMb` (from 512), only with `node` and at most the node's own; by default the size's, at most the node's CPUs and half its memory. `env`: `{"NAME": "value"}`, up to 100. `files`: `{"~/.npmrc": "contents"}`, up to 20, in the home directory. `repo`: an `https://` URL, with `#branch` if you like, or `{"url", "dir", "branch"}`. A URL with a user name or token in it is refused; for a private repo, set `GH_TOKEN` in `env`. |
| Update | `name`, as for Create. `idleMinutes`: 0 to 360, which applies at once, counting from now. Give at least one. |
| Resume | `fromBackup`: `true` restores `/home` from the newest backup onto a fresh image; default `false`. `size`: run on this size from now on; the disk must fit it. |
| Fork | `count`: 1 to 10, default 1. `name`: with a count above 1, forks are named `<name>-1`, `<name>-2` and so on. `size` and `idleMinutes` default to the original's. A fork stays where its original is. For a sandbox on a node, `cpus` and `memoryMb` set the forks' limits there and default to the original's, `node` may only name that node, and `size` is refused (`400`). For a sandbox on Cloudflare, `node`, `cpus` and `memoryMb` are refused (`400`). |
| Save | `name` (required), as for Create. A taken name's save is replaced once the new one is done. |
| Start from a save | The same fields as Fork. `size` and `idleMinutes` default to those of the sandbox that was saved. `node`, `cpus` and `memoryMb` start them on a node, as for Create. |
| Add node | `name` (required): as for a sandbox's name, but not starting with `nd-`. Adding a name that never joined, or was removed, gives it a new token; a name in use is a `409`. |
| Exec | `cmd` (required): shell code. `root`: run as root, default `false`. `cwd`: working directory, default the user's home; a relative one, or one starting with `~`, is in the home directory. `timeoutSec`: 1 to 3600, default 600. `stream`: answer with the output as it comes; default `false`. |
| Start command | `cmd` (required), `root` and `cwd`, as for Exec. `timeoutSec`: 0, the default, for no limit, up to 30 days. |
| Kill command | `signal`: `TERM`, the default, `INT`, `HUP` or `KILL`. |
| Hosts | `port` (required): 1 to 65535 |
| Desktop | `size`: `WIDTHxHEIGHT`. Without it, a new desktop starts at `1280x720` and a running one keeps its size. |
| Settings | `env` and `files`, as for Create; `null` removes a variable or file. Variables and files together take up to 1 MB. |
| Create token | `name` (required): up to 100 characters. `role`: `admin`, `user` or `read`, default `user`. `ownOnly`: only the sandboxes it makes, default `false`. `expiresInSec`: 60 up to 10 years; leave it out for a token that doesn't expire. |
| Device sign-in | `name` (required): what the token will be called. `role`: the role asked for; the approver decides. `429` when 20 sign-ins are waiting, or 3 from the same address. Answers `device_code`, `user_code`, `verification_uri`, `expires_in` (600) and `interval` (5). |
| Collect | `device_code` (required). Until a decision, `400` with `error` `authorization_pending`, or `slow_down` when asked sooner than `interval`; then `access_denied` or `expired_token`, or the token, once, as `{"access_token", "token_type": "Bearer", "token"}`. Form-encoded bodies work too. |
| Approve | `user_code` (required). `role`, default `user`, or `read` if `read` was asked for; `admin` only when given. `ownOnly`, default `false`. `expiresInSec`, default 90 days; a dashboard session from it never lasts longer. |
| Set key | `key` (required): the API key, 8 to 1000 characters without spaces. The deployment tries it with the provider first, and answers `400` when the provider rejects it. |
| Start agent | `prompt` (required): the task, up to 1 MB. `agent`: `claude`, `codex` or `opencode`, default `claude`. `cwd`: the directory to work in, default the home directory; a relative one, or one starting with `~/`, is in the home directory. `model`: the agent's model, `provider/model` for OpenCode, default its own. |
| Message | `prompt` (required). `interrupt`: stop the running turn and drop queued messages first, default `false` |

## Responses

Sandbox endpoints return a sandbox object, or a list of them. Times are Unix timestamps in milliseconds.

```json
{
  "id": "cx-7f3a2k",
  "name": "web",
  "size": "standard-2",
  "state": "running",
  "idleMinutes": 30,
  "createdAt": 1793300000000,
  "updatedAt": 1793300042000,
  "startedAt": 1793300042000,
  "stoppedAt": null,
  "savedAt": null,
  "savedBytes": null,
  "backupAt": null,
  "backupBytes": null,
  "backupError": null,
  "notice": null,
  "forkedFrom": null,
  "fromSave": null,
  "providerKeys": ["anthropic"],
  "error": null,
  "placement": { "provider": "cloudflare" },
  "isolation": "vm"
}
```

| Field | Meaning |
|---|---|
| `state` | `starting`, `running`, `stopping`, `stopped` or `error` |
| `savedAt`, `savedBytes` | The last save, and how much it held. A save after a resume holds only what changed. |
| `backupAt`, `backupBytes`, `backupError` | The newest backup of `/home`, or why the last one failed |
| `notice` | Something to know about the last start, such as a restore from backup |
| `forkedFrom` | The id of the sandbox this one is a fork of |
| `fromSave` | The name of the [named save](https://cloudex.build/docs/saves.md) this one started from |
| `providerKeys` | The providers whose [keys](https://cloudex.build/docs/keys.md) this run uses |
| `error` | Why the last start or save failed |
| `placement` | Where it runs: `{"provider": "cloudflare"}`, or on a node `{"provider": "node", "node": {"id", "name", "online", "state", "lastSeenAt"}, "cpus", "memoryMb"}`. `node.state` is `revoked` once the node was removed, and `node` is `null` once it was forgotten. A deployment before v0.2.2 leaves it out. |
| `isolation` | How it's kept apart: `vm` on Cloudflare; on a node `sysbox`, `docker` (plain Docker, for trusted code only) or `none` (a node joined with `--unisolated`, for testing). See [Isolation](https://cloudex.build/docs/nodes.md#isolation). |

The list, `GET /v1/sandboxes`, comes from an index and leaves out the backup fields, `notice`, `forkedFrom`, `fromSave` and `providerKeys`. Get a sandbox by itself for those.

The other endpoints return:

| Endpoint | Response |
|---|---|
| Health | `{"ok": true, "version": "v0.2.3", "previewZone": "example.com", "backups": true}`; `previewZone` is `null` without preview links |
| Exec | `exitCode`, `stdout`, `stderr`, `timedOut` and `ms`. Each stream is cut at 1 MiB. With `stream`, see [Commands](#commands). |
| Command | `id` (`cm-` and 8 characters), `cmd`, `root`, `cwd`, `state` (`running`, `exited`, `killed` or `lost`), `exitCode`, `signal` (such as `TERM`), `timedOut`, `timeoutSec`, `startedAt`, `endedAt` and `outputBytes` |
| Command output | `data`, `offset`, `next` and `command` |
| File | `path`, `type` (`file`, `dir`, `symlink` or `other`), `size`, `mode` (octal, such as `"644"`), `mtime` in ms, and a symlink's `target`. A directory adds `entries`, the same without `path` but with `name`, up to 10,000, and `truncated`. |
| Hosts | `{"url": "https://3000-cx-7f3a2k-<token>.example.com"}`. The list: `[{"port": 3000, "url": "…", "createdAt": 1793300000000}]`. A revoke: `{"revoked": [3000], "all": false}`, with `all` `true` for every link. |
| Desktop | `port`, `path`, `size`, `installed` and `started`. The viewer is at `<link to port>/<path>`, where the link comes from Hosts. |
| Delete | `{"deleted": "cx-7f3a2k"}` |
| Saves | `name`, `id` (`sv-` and 10 characters, new each time the name is saved), `sandbox` (the id it was made from), `kind` (`disk`, or `home` for a save of `/home` only from an image before v0.1.15), `size` and `idleMinutes` (the defaults for sandboxes started from it), `files` and `rawBytes` (the paths it holds and their size), `bytes` (its size in R2), `createdAt` and `ms`. `node`: the node it was made on, `{"id", "name"}`, or `null` for Cloudflare. A new save also has `replaced`: whether it replaced an earlier save of the name. Delete answers `{"deleted": "base"}`. |
| Nodes | See [Nodes](#nodes). Add answers `{"node", "joinToken", "expiresAt", "install"}`; remove answers `{"revoked": "nd-…"}`, or `{"deleted": "nd-…"}` when it forgets a removed node. |
| Keys | List: `[{"provider": "anthropic", "hint": "…wxyz", "updatedAt": 1793300000000}]`. Set answers with one such object, and delete with `{"deleted": "anthropic"}`. The key itself is never returned. |

## Errors

Errors come back as JSON with a message meant for people, and an HTTP status:

```json
{ "error": "the name web is taken" }
```

| Status | When |
|---|---|
| `400` | The body isn't valid, preview links are off for `hosts`, or the provider rejected a key being set. On a node: `cpus` or `memoryMb` without `node` or over the node's, or `size` or `fromBackup` on resume. |
| `401` | The admin key is missing or wrong |
| `403` | The token's role doesn't allow the call, or an own-only token asked for a node whose isolation is plain Docker or none |
| `404` | No sandbox, agent or node has that id or name, a resume from backup finds no backup, or the provider is unknown or has no key to delete |
| `409` | A name is taken, or the sandbox is in the wrong state, such as `exec` on a stopped sandbox. For a state, the message says what to do. Also a node that hasn't joined yet, or one removed while it still has sandboxes, without `force`. |
| `410` | The sandbox's node was removed: only delete works |
| `413` | From a sandbox on a node, a request to `cloudex.internal` or a provider with a body over 100 MB |
| `500` | Saving the disk failed during a stop; the sandbox keeps running |
| `501` | Named saves on a deployment without R2 |
| `502` | A node's agent couldn't do what was asked, such as making a machine; the message gives its reason |
| `503` | The sandbox didn't start. On a node: the node is offline, which the message names with when it was last seen, its isolation self-test fails, or it's still pulling the sandbox image. |

## Nodes

A [node](https://cloudex.build/docs/nodes.md) is a Linux machine of your own that runs sandboxes. `GET /v1/nodes/{node}` answers:

```json
{
  "id": "nd-k2m4p6q8",
  "name": "box",
  "state": "online",
  "createdAt": 1793300000000,
  "lastSeenAt": 1793300042000,
  "version": "v0.2.3",
  "protocol": 1,
  "arch": "amd64",
  "runtime": "docker",
  "isolation": { "firewall": "pass", "unisolated": false, "checkedAt": 1793300030000, "failed": [] },
  "cpus": 8,
  "memoryMb": 31872,
  "diskFreeGb": 212,
  "colo": "IAD",
  "continent": "NA",
  "locationHint": "enam",
  "machines": 2,
  "revokedAt": null,
  "publicKey": "Jq0Xy…=",
  "direct": { "port": 7022, "addrs": ["192.168.1.20", "100.101.102.103"], "state": "listening" },
  "rttMs": 41,
  "image": { "ref": "ghcr.io/lucataco/cloudex-base:v0.2.3@sha256:…", "state": "present" },
  "forks": { "images": 1, "gb": 1.1, "store": "overlay2", "secPerGb": 2.3 },
  "orphans": [],
  "pendingDeletes": []
}
```

| Field | Meaning |
|---|---|
| `state` | `pending` until its agent joins, `online` while its agent is connected, `offline`, or `revoked` after it was removed |
| `version`, `protocol` | Its agent's version and protocol |
| `runtime` | `docker`, or `sysbox` when Docker on it has Sysbox |
| `isolation` | `firewall`: the last self-test's result, `pass`, `fail` or `unchecked`; `unisolated`: joined with `--unisolated`, for testing only; `checkedAt` and the checks that `failed` |
| `cpus`, `memoryMb`, `diskFreeGb` | What the machine has; `diskFreeGb` is Docker's free disk |
| `colo`, `continent`, `locationHint` | Where its agent's connection reaches Cloudflare, and the region its sandboxes' Durable Objects are made in |
| `machines` | Sandboxes on it |
| `publicKey` | Its Ed25519 public key, in base64, which its direct port's TLS certificate carries; absent before it joins and once it's removed |
| `direct` | Its [direct port](https://cloudex.build/docs/nodes.md#direct-connections): the `port`, the `addrs` it's published on, its `state`, `listening`, `off` or `failed`, and the `error` when there is one; `off` with `--direct off`. For admins only, and absent for an agent older than v0.2.3. |
| `forks` | Only from `GET /v1/nodes/{node}`: its [fork images](https://cloudex.build/docs/nodes.md#disk), how many and the GB they hold, Docker's image `store` (`overlay2`, `containerd` or `other`), and about how many seconds a fork's copy takes per GiB written, while a running original is paused. Absent for an agent older than v0.2.3. |
| `rttMs`, `image`, `orphans`, `pendingDeletes`, `clockSkewSec` | Only from `GET /v1/nodes/{node}`, and `rttMs`, `orphans` and `pendingDeletes` only for admins (they name other users' sandboxes): a round trip to the agent while it's online; the sandbox image and whether it's `present`, `pulling` (with `progress`), `missing` or `refused`; machines of no sandbox, left alone; sandboxes deleted while it was offline, whose machines it removes when it's back; and its clock's difference from the deployment's, in seconds |

Everything about a node but its id comes from its agent. Treat it as text.

The routes under `/v1/node/`, singular (`join`, `connect`, `streams` and `egress`), are for the node's agent, `cloudex-node`. They take no key: each request is signed with the node's own key, over the method, the path, the node's id and a nonce, or carries a ticket its control connection was given. A key joins one node only. A removed node's own agent gets `410` with `"revoked": true`, and stops its sandboxes. They aren't a public API, and they can change between versions.

## Agents

An agent is Claude Code or Codex working on a task in a sandbox with no terminal; see [Agents from code](https://cloudex.build/docs/agents.md#from-code). Each message is one turn of the agent's conversation. The sandbox must be running, and the agent's state lives on its disk.

```json
{
  "id": "ag-k3v9x2m1",
  "agent": "claude",
  "state": "running",
  "cwd": "/home/cloudex/app",
  "model": null,
  "turns": 2,
  "queued": 0,
  "events": 41,
  "sessionId": "5b3a6b60-0c55-4d7e-9a1e-2f0f6f0c1d2e",
  "lastMessage": "All 112 tests pass.",
  "lastExitCode": 0,
  "error": null,
  "createdAt": 1793300000000,
  "updatedAt": 1793300042000
}
```

| Field | Meaning |
|---|---|
| `state` | `running` while a turn runs or messages are queued, `idle` otherwise |
| `turns`, `queued` | Turns started so far, and messages waiting for the running one |
| `events` | Events so far; the next one's `seq` is this plus 1 |
| `sessionId` | The agent's own conversation id: Claude Code's session or Codex's thread |
| `lastMessage`, `lastExitCode`, `error` | The agent's final message in the last finished turn, its exit code, and why the turn failed |

`GET .../events?after=<seq>&wait=<seconds>` returns the events after `after`, up to about 512 KiB, with `next`, the `after` for the next call, and the agent. With `wait` (up to 60), it holds the request until there's an event after `after`, the agent goes idle, or the time passes, so a client can follow an agent by calling it in a loop until the agent is idle and `next` reaches `events`.

```json
{
  "events": [
    { "seq": 1, "turn": 1, "at": 1793300000100, "type": "prompt", "text": "make the tests pass" },
    { "seq": 2, "turn": 1, "at": 1793300001200, "type": "event", "event": { "type": "system", "subtype": "init", "session_id": "5b3a6b60-…" } },
    { "seq": 3, "turn": 1, "at": 1793300042000, "type": "end", "exitCode": 0, "interrupted": false, "error": null }
  ],
  "next": 3,
  "agent": { "id": "ag-k3v9x2m1", "state": "idle", "…": "…" }
}
```

| Event `type` | Has |
|---|---|
| `prompt` | `text`: the message that started the turn |
| `event` | `event`: one of the agent's own JSON events, as Claude Code's `stream-json` or Codex's `exec --json` printed it |
| `output` | `text`: a line of output that isn't JSON. A line over 256 KiB is cut to 4 KiB, with `truncated`. |
| `end` | `exitCode`, `interrupted`, and `error` when the turn failed |

## Commands

`POST /exec` runs a command with `bash -lc`, as the `cloudex` user in its home directory unless `root` is set, and answers when it ends. A timeout stops the command and everything it started.

With `"stream": true`, it answers at once with `application/x-ndjson`, one event per line as the output comes, uncut:

```json
{"type":"stdout","data":"building\n"}
{"type":"stderr","data":"warning: ...\n"}
{"type":"keepalive"}
{"type":"exit","exitCode":0,"timedOut":false,"ms":5120}
```

Output is UTF-8 text; bytes that aren't valid UTF-8 become U+FFFD, so read binary files through [Files](#files). `keepalive` comes every 15 seconds while the command prints nothing; skip it. A stream that breaks off ends with `{"type":"error","error":"..."}`. Closing the stream stops the command.

`POST /commands` starts a command in the background, with the same fields and no time limit unless `timeoutSec` sets one. Its standard output and standard error go to one log on the sandbox's disk. Read it with `GET /commands/{cmd}/output?after=<offset>&wait=<seconds>`: it answers with the log from byte `after`, up to 1 MiB, as `data`, and `next`, the offset to pass next time. With `wait`, up to 60, it holds until there's more output or the command ends. A character split at the end of a read comes whole in the next. `command` is the command as it stands; it has ended when `state` isn't `running` and `next` has reached `outputBytes`.

A stop ends running commands, which then show as `lost`. While a command prints output, it counts as activity for [idle stop](https://cloudex.build/docs/sandboxes.md#idle-stop).

## Files

The files calls take the path in the `path` query parameter. A relative path, or one starting with `~`, is in the `cloudex` user's home directory, and answers give absolute paths. They act as the `cloudex` user, so the sandbox's permissions apply, unless `root=true`. A missing path gets `404`, and one the user can't read or write gets `403`.

- `GET /files/content` answers with the file's bytes, and `PUT /files/content` replaces the file whole with the request body, making its directory if need be. A new file gets mode 644 and an existing one keeps its mode, unless `mode`, in octal, says otherwise. Writing to a symlink writes its target.
- `GET /files/archive` answers with a tar.gz of a directory's contents, or of one file, leaving out files the user can't read. `PUT /files/archive` unpacks a tar.gz from the request body into the directory, making it if need be, and answers with its `path` and the number of `entries`.
- `GET /files` answers with a path's details; `DELETE /files` deletes it, and a directory only with `recursive=true`.

Cloudflare limits a request body to 100 MB on most plans, so an upload is at most that.

## Long requests

Create, resume and fork answer once the sandboxes are running. That can take a minute or more when a Cloudflare host fetches the image for the first time, or a sandbox resumes a large save. Stop can take a few minutes for a full disk. Give your HTTP client a long timeout; the CLI waits up to 20 minutes.

Exec, command and file calls, requests through a preview link, and data sent over a TCP WebSocket count as activity for [idle stop](https://cloudex.build/docs/sandboxes.md#idle-stop).

The TCP, terminal and desktop WebSockets check the token or session that opened them about once a minute, and close with code `4401` once it's revoked or expires, or the session signs out. The admin key isn't checked again.

## TCP over WebSocket

`GET /v1/sandboxes/{ref}/tcp/{port}` upgrades to a WebSocket that carries a TCP connection to `port` in the sandbox, as binary messages each way. `cloudex ssh` uses it for port 22, and `cloudex desktop` for the desktop's port. A port nothing listens on gets `502`. With `?key=<SSH public key>`, the key is first added to the `cloudex` user's `authorized_keys`.

## Terminal over WebSocket

`GET /v1/sandboxes/{ref}/terminal` upgrades to a WebSocket to a login shell in the sandbox, under a terminal (a pty), as the `cloudex` user or with `?root=true` as root. The dashboard's terminal uses it.

- **Query:** `cols` and `rows` set the size, and `session=<name>` runs the shell in that tmux session, made if it's new, so that connecting again gets the same shell back.
- **The terminal's bytes:** binary messages, each way.
- **Text messages** are JSON:
  - you send `{"resize":[cols,rows]}`;
  - `{"ping":1}` counts as activity for idle stop, which the shell's output alone doesn't;
  - `{"kill":1}` ends the tmux session;
  - the sandbox sends `{"exit":code}` when the shell ends, then closes.

Closing the socket hangs up the shell, as closing an SSH session does. A tmux session stays until it's killed or its shell exits.

## Examples

```sh
API=https://cloudex-api.<your-subdomain>.workers.dev
KEY=...   # from: cloudex status --show-key

curl -s "$API/v1/health"

curl -s -H "Authorization: Bearer $KEY" "$API/v1/sandboxes"

curl -s -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"name": "web", "size": "standard-3"}' "$API/v1/sandboxes"

curl -s -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"cmd": "uname -a"}' "$API/v1/sandboxes/web/exec"

curl -s -X POST -H "Authorization: Bearer $KEY" "$API/v1/sandboxes/web/stop"
```

## From inside a sandbox

Inside a sandbox, on Cloudflare or a node, `http://cloudex.internal/v1/sandboxes/self` answers without the admin key, for that sandbox only: `GET` it, `PATCH` it, `POST /stop` (`202`, and the sandbox stops a few seconds later), and `POST`, `GET` and `DELETE` its `/hosts`, with the same bodies as above. Each request needs the run's token, from the file `/run/cloudex/self-token`, in an `X-Cloudex-Self` header; only root and the `cloudex` user can read the file, so an app in the sandbox that fetches URLs for its visitors can't be made to use the API. Requests from web pages, any other sandbox and any other endpoint get `403` or `404`. The [`cloudex` command in a sandbox](https://cloudex.build/docs/sandboxes.md#inside-the-sandbox) uses it.
