> ## Documentation Index
> Fetch the complete documentation index at: https://docs.controlplane.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent API

> Reference for the HTTP API an agent sandbox serves at its endpoint: token auth, session scoping, process and PTY streams, filesystem and file transfer routes, preview codes and the port proxy, and the worker environment settings.

An [agent sandbox](https://docs.controlplane.com/concepts/sandbox.md) (a sandbox of type `worker`) runs the agent API daemon, `devboxd`, as its only process on port `49983`. That port is the workload's one listener, so the workload endpoint (the `status.endpoint` value on the workload) is the API itself. There is no IDE, no terminal page, and no sign-in on an agent sandbox: the sandbox token gates everything.

This page documents that API. Most clients do not need the sandbox token at all: the platform's [`-sessions` routes](https://docs.controlplane.com/reference/sandbox/sessions) and the `cpln sandbox` commands proxy session lifecycle, logs, metrics, processes, signals, and preview codes with the caller's Control Plane token. The daemon API is for the agent loop itself: running commands, streaming output, moving files, and opening previews, at the worker's endpoint and with the session or sandbox token.

## Agent API authentication

Every request carries a token in the `X-Access-Token` header. Two kinds of token exist:

| Token | Where it comes from | What it authorizes |
| :- | :- | :- |
| Sandbox token | `spec.sandbox.token` on the workload (generated by the server when omitted on create; read it back from the workload with `connect` permission, or from the Console connect panel). Injected into the container as `DEVBOXD_TOKEN`. | Everything on the worker: every session, every route. |
| Session token | The `token` field of a session create answer, returned once. | Only operations that carry that session's id. Carrying another session's id, or no session at all, is `403`. |

A token that matches nothing is `401`. Comparisons are constant-time. Every route also accepts the token as `Authorization: Bearer`. Routes that take a browser (previews and the port proxy) also accept it as a cookie, and set that cookie from a one-time code; see [Previews](#previews-and-the-port-proxy). A token in a URL (`?access_token=`) is refused with `401`, because URLs end up in logs.

Three routes carry no auth: `/_health` (readiness; answers with `X-Devboxd-Version` and `X-Devboxd-Commit` headers), `/_metrics` (JSON cpu, memory, and disk of the worker), and the Prometheus exposition on the separate metrics port `49984` at `/metrics`, which only the platform's in-cluster scraper reaches.

> [!WARNING]
>
> The sandbox token is a bearer credential for the whole worker. Hand agents a session token where you can, and keep the sandbox token in the orchestrator that creates sessions.

## Session scoping of Agent API routes

Every process, PTY, filesystem, and archive route accepts an optional `session=<id>`: as a query parameter everywhere, and additionally as a `"session"` field in the body of the JSON routes. Raw-body routes (`/_files`, `/_api/fs/archive`) take it as a query parameter only.

A scoped call behaves as if issued from inside the session:

* Execs run inside the session's isolation unit with `cwd` defaulting to the session workspace and the session's `envs` merged in.
* Filesystem and archive paths resolve inside the workspace; an escape outside it is `403`.
* Process selectors (tags and pids) see only that session's processes.

A call without a session runs at the worker level, outside any session, with the sandbox token only.

## Agent API routes

### Session routes

| Method and route | Purpose |
| :- | :- |
| `POST /_api/sessions` | Create a session. Body and answer are documented in the [sessions reference](https://docs.controlplane.com/reference/sandbox/sessions.md#session-create-fields). Answers `201`; the session token is returned once. Sandbox token only. |
| `GET /_api/sessions[?include=ended]` | List live sessions with the worker's `capacity` block; `include=ended` adds ended sessions from the logs. Sandbox token only. |
| `PATCH /_api/sessions/{id}` | Change the session's timeout. Body `{timeoutSeconds}`; `0` clears it; the maximum is `604800`. |
| `DELETE /_api/sessions/{id}` | Delete a session (`204`, idempotent). Sandbox token, or the session's own. |
| `GET /_api/sessions/{id}/logs` | The session log; `?follow=true` streams new lines as server-sent events. Query parameters are in the [sessions reference](https://docs.controlplane.com/reference/sandbox/sessions.md#session-logs). |
| `GET /_api/sessions/{id}/metrics` | The session's resource series. |
| `POST /_api/sessions/{id}/preview-code` | A one-time code that opens this session's preview in a browser: `{code, param: "preview_code", expiresInSeconds: 60}`. Sandbox token, or the session's own. `429` when the session already holds 8 unspent codes. |
| `ANY /_s/{id}/{port}/...` | Preview proxy into the session; see [Previews](#previews-and-the-port-proxy). |

The logs and metrics routes answer CORS, so a browser page holding a token can read them directly.

### Process routes

| Method and route | Body | Purpose |
| :- | :- | :- |
| `POST /_api/process/start` | `{cmd, args, envs, cwd, user, tag, pty: {cols, rows}, log, session}` | Start a process and stream its lifecycle as server-sent events: `start`, `data`, `end`, and `keepalive`. `log: true` keeps this process's output in the session log. `pty` allocates a terminal. |
| `GET /_api/process/connect?selector=` | | Attach to a running process (live stream), or fetch the retained exit of one that already ended. |
| `GET /_api/process/list[?session=]` | | List processes, scoped to a session when given. |
| `POST /_api/process/input` | `{selector, …}` | Write to a process's stdin. |
| `POST /_api/process/stdin/close` | `{selector}` | Close a process's stdin. |
| `POST /_api/process/signal` | `{selector, signal}` | Send `SIGTERM` or `SIGKILL` (the only signals accepted). |
| `POST /_api/process/update` | `{selector, pty: {cols, rows}}` | Resize a PTY process. |
| `GET /_api/process/io?selector=` | WebSocket | Interactive stdin and stdout. Binary frames are raw keystrokes; text frames are JSON controls `{"type": "input", "b64": "…"}`, `{"type": "resize", "cols": n, "rows": n}`, `{"type": "terminate"}`. |

A `selector` is a process tag or pid. Processes are detached from the client that started them: dropping the stream never kills the process, and a later `connect` receives the retained exit code. The keepalive interval of a stream is client-tunable with `?keepalive_s=` (default 30).

### PTY routes

A terminal-shaped surface over the same process manager, for agents that drive an interactive shell.

| Method and route | Body | Purpose |
| :- | :- | :- |
| `POST /_api/pty/start` | `{cmd?, args?, envs?, cwd?, user?, tag?, cols?, rows?, session?}` | Start a PTY. Without `cmd` it runs an interactive shell at 80 by 24: inside a session, `bash` when the session's image has it and `sh` otherwise. Answers `{pid, tag}`. |
| `POST /_api/pty/input` | `{selector, b64}` | Write base64 keystrokes. |
| `POST /_api/pty/resize` | `{selector, cols, rows}` | Resize. |
| `POST /_api/pty/terminate` | `{selector}` | `SIGKILL` the PTY's process group. |
| `POST /_api/pty/terminate_all` | | Kill every PTY; answers `{terminated: n}`. Non-PTY processes are untouched. |
| `GET /_api/pty/list` | | `{ptys: [{pid, tag, cmd, args, cwd, user, cols, rows}]}`. |

Stream a PTY through `GET /_api/process/io?selector=` (WebSocket) or `GET /_api/process/connect` (server-sent events). PTY output is never written to the session log. `cpln sandbox session connect` is a terminal over this surface.

### Filesystem routes

| Method and route | Purpose |
| :- | :- |
| `/_api/fs/stat`, `/_api/fs/mkdir`, `/_api/fs/move`, `/_api/fs/remove` | One entry each; `stat` answers an `EntryInfo`. |
| `/_api/fs/list` | A directory listing with a `depth`. |
| `GET /_api/fs/watch` | A live server-sent event stream of changes under a path (an armed `start` frame, then events and keepalives). |
| `/_api/fs/watcher/create`, `/_api/fs/watcher/events`, `/_api/fs/watcher/remove` | The polling form of watching: create a watcher, poll its events, remove it. This form survives the worker being suspended and resumed. |
| `GET /_api/fs/archive?path=<dir>` | Streams a raw `application/x-tar` of the tree. |
| `POST /_api/fs/archive?path=<dir>[&username=]` | Extracts a raw tar body there. Entries that escape the directory and symlinks are rejected; `username` chowns extracted entries (validated with the `run_as` rules). |

### File transfer routes

| Method and route | Purpose |
| :- | :- |
| `GET /_files?path=<file>` | Download a file. |
| `POST /_files?path=<file>` | Upload a file as a multipart form or a raw body. Parent directories are created. `507` when the disk is full. |

`cpln cp --session` moves files and directories through these routes and the archive routes.

### Previews and the port proxy

| Route | Audience | Purpose |
| :- | :- | :- |
| `/_s/<session>/<port>/...` | Browsers and agents | Proxies to that port inside the session (its own address when it has a network namespace). Access per session: `token` (default) or `public`, chosen at session create. Details in the [sessions reference](https://docs.controlplane.com/reference/sandbox/sessions.md#preview-urls). |
| `/_port/<n>/...` | Browsers and agents | Proxies to `127.0.0.1:<n>` on the worker itself, outside any session, preserving method, body, headers, and WebSocket upgrades. Requires the sandbox token. |
| `POST /_api/preview-code` | Orchestrators | A one-time code for `/_port/<n>/`, like the per-session one. Sandbox token only. |

A browser opens either proxy with a **one-time code**: open the URL with `?preview_code=<code>` within 60 seconds of minting it. The daemon sets a cookie (scoped to `/_s/<session>/` for a session preview, derived from the token for the port proxy), spends the code, and redirects a `GET` to the same URL without it. WebSocket upgrades and requests with a body are proxied with the parameter stripped. Codes are spent on first use, so a code read from a URL or an access log opens nothing. An agent calling from code sends the token in the header instead and needs no code.

The daemon's own ports (`49983` and `49984`) are never proxyable (`403`).

> [!WARNING]
>
> `DEVBOXD_PORT_PROXY_PUBLIC=true` on the worker container opens `/_port/<n>/` without a token, for public preview URLs. Every port bound to localhost on the worker (dev servers, debuggers, anything on `127.0.0.1`) then becomes reachable by anyone holding the endpoint URL. Set it only when that is the intent; per-session previews with `preview: public` are the narrower choice.

### Internal routes

`/_init` bootstraps the daemon's plaintext token and `/_freeze` and `/_unfreeze` are reserved for the platform; they are guarded to loopback and are not part of the client surface.

## Agent API run\_as

The `user` field on process, PTY, and session create picks the Unix identity a command runs as:

* The default is the session's default user, `devuser`, on the worker's own root filesystem.
* The daemon runs as root in the standard image, so the named user must exist; an unknown user is `400`. The child gets that user's uid, gid, supplementary groups, and `HOME`, `USER`, and `LOGNAME`.
* In an image session (a session created with `image`), execs run as the image's root unless `user` is a numeric `"uid:gid"` such as `"1000:1000"`, because the worker's user names mean nothing in a foreign root filesystem.

Session containers carry the Docker default capability set minus host-facing ones, so root inside a session can switch identity (`su`, `setpriv`).

## Worker environment settings

These environment variables configure the daemon. Set them on the worker's first container (`spec.containers[0].env`) when a default does not fit. `DEVBOXD_TOKEN` and `DEVBOXD_MAX_SESSIONS` are derived by the platform and cannot be set by you.

| Variable | Default | Meaning |
| :- | :- | :- |
| `DEVBOXD_TOKEN` | derived | The sandbox token. Derived from `spec.sandbox.token` by the platform; a different value is rejected with a pointer at `spec.sandbox.token`. |
| `DEVBOXD_MAX_SESSIONS` | derived | The most sessions the worker admits. Derived from `spec.sandbox.scaling.maxSessions` (default 20). |
| `DEVBOXD_TOKEN_HASH` | | A hash of the token, accepted in place of the plaintext `DEVBOXD_TOKEN` in custom images. |
| `DEVBOXD_API_PORT` | `49983` | The API listener. The sandbox transform injects this port on the container and probes `/_health` on it. |
| `DEVBOXD_METRICS_PORT` | `49984` | The Prometheus exposition port the platform scrapes; `0` turns it off. |
| `DEVBOXD_PORT_PROXY_PUBLIC` | `false` | Opens `/_port/<n>/` without a token. See the warning above. |
| `DEVBOXD_SESSION_NET` | `10.200.0.0/16` | The range sessions take their `/30` from. |
| `DEVBOXD_SESSION_LOG_MAX_MB` | `50` | Log cap per session. |
| `DEVBOXD_SESSION_LOG_TOTAL_MB` | `2048` | Log cap over all ended sessions; oldest ended pruned first. |
| `DEVBOXD_SESSION_LOG_RETAIN_DAYS` | `7` | Days an ended session's log is kept. |
| `DEVBOXD_BOX_ACTIVE_CPU` | `0.02` | The share of one core the worker itself (outside sessions) must use to count as working for scale to zero. |
| `DEVBOXD_IMAGE_CACHE_MB` | 30% of the worker's disk | The size of the unpacked image cache. The least recently used images are evicted first, and never an image a running session uses. |
| `DEVBOXD_SESSION_MEMORY_RESERVE_MB` | `256` | Memory held back from each session's allocation. |
| `DEVBOXD_MEMORY_RESERVE_MB` | `128` | Memory held back for the worker itself. |
| `DEVBOXD_ORG_REGISTRY` | derived | Overrides the org registry host used to validate `imageAuth` of kind `cpln`; derived from the injected `CPLN_ORG` and `CPLN_ENDPOINT` by default. |

## Standard agent sandbox image

`build.cpln.io/public/agentbox-base:v1` is the image the server injects when an agent sandbox is created without containers (4 CPU and 8 GiB unless sized). It contains:

* `devboxd` as PID 1 on `:49983`, the only listener.
* `git`, `curl`, `python3` with `pip` and `venv`, `sudo`, and `rclone` for cloud mounts.
* `runc` and gVisor's `runsc`, the two nested runtimes sessions can pick.
* A non-root `devuser` whose home is the sandbox's home volume, mounted at `/home/devuser`.

Any image that runs `devboxd` on port `49983` can serve as a worker; the standard dev image cannot, because it runs the daemon in a mode that tracks activity only.

## Agent API examples

The examples assume `EP` is the worker's endpoint and `TOKEN` is the sandbox token or the session's token.

Start a command in a session and stream its output as server-sent events:

```bash theme={null}
curl -sN -X POST "$EP/_api/process/start" \
  -H "X-Access-Token: $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"session": "task-1", "cmd": "python3", "args": ["-c", "print(42)"], "tag": "hello"}'
```

Upload a file into the session workspace, then read it back:

```bash theme={null}
curl -s -X POST "$EP/_files?session=task-1&path=data.csv" \
  -H "X-Access-Token: $TOKEN" \
  --data-binary @data.csv

curl -s "$EP/_files?session=task-1&path=data.csv" -H "X-Access-Token: $TOKEN"
```

List the processes of a session and stop one by tag:

```bash theme={null}
curl -s "$EP/_api/process/list?session=task-1" -H "X-Access-Token: $TOKEN"

curl -s -X POST "$EP/_api/process/signal" \
  -H "X-Access-Token: $TOKEN" -H "Content-Type: application/json" \
  -d '{"session": "task-1", "selector": "hello", "signal": "SIGTERM"}'
```

Fetch a preview of a dev server the session runs on port 3000, from code:

```bash theme={null}
curl -s "$EP/_s/task-1/3000/" -H "X-Access-Token: $TOKEN"
```

Open the same preview in a browser with a one-time code:

```bash theme={null}
curl -s -X POST "$EP/_api/sessions/task-1/preview-code" -H "X-Access-Token: $TOKEN"
# {"code":"…","param":"preview_code","expiresInSeconds":60}
# open $EP/_s/task-1/3000/?preview_code=<code> within 60 seconds
```

Run a command at the worker level, outside any session, with the sandbox token (this is the replacement for `cpln workload exec`, which does not work on a privileged worker):

```bash theme={null}
curl -sN -X POST "$EP/_api/process/start" \
  -H "X-Access-Token: $SANDBOX_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"cmd": "/bin/sh", "args": ["-lc", "df -h /home/devuser"], "user": "devuser"}'
```

## Agent API example: an orchestrator

The pattern for a backend that runs many tasks: create sessions with your Control Plane token through the platform API, hand each task its session token, retry on `429`, and delete when done. In Python with `requests`:

```python theme={null}
import base64, json, os, sys, time, requests

API, ORG, SANDBOX = "https://api.cpln.io", "my-org", "my-agent"
GVC = os.environ["SANDBOX_GVC"]  # the org's sandbox GVC, from GET /org/{org}/gvc/-sandbox
CPLN = {"Authorization": f"Bearer {os.environ['CPLN_TOKEN']}"}

def open_session(task_id, image):
    """A session for one task; waits out a full sandbox."""
    while True:
        r = requests.post(f"{API}/org/{ORG}/gvc/{GVC}/workload/{SANDBOX}/-sessions",
                          headers=CPLN, json={"id": task_id, "image": image, "runtime": "runsc", "logOutput": True})
        if r.status_code != 429:
            r.raise_for_status()
            return r.json()
        time.sleep(int(r.headers.get("Retry-After", "15")))

def run(session, cmd, args):
    """Runs a command in the session, prints its output, returns the exit code."""
    ep, hdr = session["endpoint"], {"X-Access-Token": session["token"]}
    with requests.post(f"{ep}/_api/process/start", headers=hdr, stream=True,
                       json={"session": session["id"], "cmd": cmd, "args": args}) as r:
        r.raise_for_status()
        for line in r.iter_lines():
            if not line.startswith(b"data: "):
                continue
            ev = json.loads(line[6:])
            if ev["event"] == "data":
                sys.stdout.write(base64.b64decode(ev["b64"]).decode(errors="replace"))
            elif ev["event"] == "end":
                return ev.get("exitCode")

session = open_session("task-1", "python:3.12-slim")
ep, hdr = session["endpoint"], {"X-Access-Token": session["token"]}
with open("task.py", "rb") as f:
    requests.post(f"{ep}/_files", params={"session": session["id"], "path": "task.py"}, headers=hdr, data=f).raise_for_status()
code = run(session, "python3", ["task.py"])
result = requests.get(f"{ep}/_files", params={"session": session["id"], "path": "result.json"}, headers=hdr)
requests.delete(f"{ep}/_api/sessions/{session['id']}", headers=hdr)
print("exit", code, "result", result.text)
```

Notes for a real one:

* The sandbox token stays in this backend; agents only ever see `session["token"]`.
* Session ids are yours to choose, so use your task id; a duplicate answers `409`.
* The first call after a quiet period may take a few seconds while the sandbox wakes.
* When one sandbox is not enough, create sessions by identity through `/org/{org}/gvc/<sandbox-gvc>/-sessions` instead of by name and let the platform spread them over several (the sandbox GVC's name comes from `GET /org/{org}/gvc/-sandbox`); see [Scale by identity](https://docs.controlplane.com/guides/sandbox/scaling-workers.md).
