# Public API

This is the HTTP API the SDKs call: create sandboxes, run commands in them, move their files,
sleep, wake, snapshot and fork them, from any language that speaks HTTP. It lives under `/v1` on
your install's API URL.

Send `Authorization: Bearer <key>` with every request. Requests and responses are JSON; exec and
logs stream NDJSON. Each key belongs to one project, and a request acts on that project. Create,
list and revoke keys with `hermitbox key` on the private operator listener.

[control/README.md](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/README.md) covers configuration. For worked examples, use the
[TypeScript](https://docs.hermitbox.dev/v0.3.2/sdk/typescript.md), [Python](https://docs.hermitbox.dev/v0.3.2/sdk/python.md) and
[Rust](https://docs.hermitbox.dev/v0.3.2/sdk/rust.md) SDKs.

## Endpoints

Each table gives the method, the path, the request body's schema in
[the OpenAPI document](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/openapi/hermitbox.openapi.json) and the status a success
returns.

### Project and audit

| Method | Endpoint | Request schema | Success |
| --- | --- | --- | --- |
| GET | `/v1/audit` | — | 200 |
| GET | `/v1/project` | — | 200 |

### Sandboxes and lifecycle

| Method | Endpoint | Request schema | Success |
| --- | --- | --- | --- |
| GET | `/v1/sandboxes/{id}/why` | — | 200 |
| POST | `/v1/sandboxes/{id}/ssh` | SshRegister | 200 |
| DELETE | `/v1/sandboxes/{id}/ssh` | — | 200 |
| GET | `/v1/sandboxes/{id}/metrics/stream` | — | 200 |
| POST | `/v1/sandboxes/{id}/token` | — | 200 |
| POST | `/v1/sandboxes/{id}/network` | — | 200 |
| POST | `/v1/sandboxes` | MakeRequest | 201 |
| GET | `/v1/sandboxes` | — | 200 |
| POST | `/v1/sandboxes/{id}/lifetime` | LifetimeRequest | 200 |
| GET | `/v1/sandboxes/{id}/metrics` | — | 200 |
| GET | `/v1/sandboxes/{id}` | — | 200 |
| DELETE | `/v1/sandboxes/{id}` | — | 200 |
| POST | `/v1/sandboxes/{id}/start` | — | 200 |
| POST | `/v1/sandboxes/{id}/stop` | — | 200 |
| POST | `/v1/sandboxes/{id}/sleep` | — | 200 |
| POST | `/v1/sandboxes/{id}/wake` | — | 200 |
| POST | `/v1/sandboxes/{id}/rest` | — | 200 |
| GET | `/v1/sandboxes/{id}/endpoints` | — | 200 |
| GET | `/v1/sandboxes/{id}/events` | — | 200 |

### Exec and logs

| Method | Endpoint | Request schema | Success |
| --- | --- | --- | --- |
| POST | `/v1/sandboxes/{id}/exec` | ExecRequest | 200 |
| GET | `/v1/sandboxes/{id}/logs` | — | 200 |

### Files and data

| Method | Endpoint | Request schema | Success |
| --- | --- | --- | --- |
| GET | `/v1/sandboxes/{id}/data/content` | — | 200 |
| PUT | `/v1/sandboxes/{id}/data/content` | — | 204 |
| GET | `/v1/sandboxes/{id}/data/list` | — | 200 |
| GET | `/v1/sandboxes/{id}/data/stat` | — | 200 |
| PUT | `/v1/sandboxes/{id}/files/{path}` | — | 200 |
| GET | `/v1/sandboxes/{id}/files/{path}` | — | 200 |
| PUT | `/v1/sandboxes/{id}/file-chunks/{path}` | — | 200 |
| GET | `/v1/sandboxes/{id}/file-chunks/{path}` | — | 200 |

### Snapshots

| Method | Endpoint | Request schema | Success |
| --- | --- | --- | --- |
| POST | `/v1/sandboxes/{id}/snapshots` | — | 201 |
| GET | `/v1/sandboxes/{id}/snapshots` | — | 200 |
| DELETE | `/v1/sandboxes/{id}/snapshots/{snapshot}` | — | 200 |
| POST | `/v1/snapshots/{snapshot}/sandboxes` | MakeRequest | 201 |

### Templates

| Method | Endpoint | Request schema | Success |
| --- | --- | --- | --- |
| POST | `/v1/templates/{name}/versions` | TemplateVersionRequest | 201 |
| GET | `/v1/templates/{name}/versions` | — | 200 |
| POST | `/v1/templates` | TemplateRequest | 201 |
| GET | `/v1/templates` | — | 200 |

### Webhooks

| Method | Endpoint | Request schema | Success |
| --- | --- | --- | --- |
| POST | `/v1/webhooks` | WebhookRequest | 201 |
| GET | `/v1/webhooks` | — | 200 |
| DELETE | `/v1/webhooks/{id}` | — | 200 |
| GET | `/v1/webhooks/{id}/deadletters` | — | 200 |

## Requests and errors

[The OpenAPI document](https://github.com/hermitbox/hermitbox/blob/cdd62e6c07e07c2b649b726729b4d8da6b25a737/control/openapi/hermitbox.openapi.json) defines every request and
response. Exec and logs use `application/x-ndjson`. Exec forwards the agent's stdout and stderr
chunks as they arrive, then a final exit event. A failure after the headers arrives as an error
event.

File writes take JSON `dataBase64`, and reads return a base64 tar archive. File paths are relative
to persistent storage.

Send a stable `Idempotency-Key` when you retry a create or an exec. Reusing a key for different
input is refused. An exec whose outcome is uncertain is never replayed automatically. Lifecycle
operations return the sandbox in the state it reached. Sleep and wake also return its `tier`:
how it slept, or how it woke.

When a TTL expires, access ends at once and upkeep deletes the data. Idle time counts from
activity and live sessions. A template warms each active node once and keeps a stopped snapshot.

Public endpoints include their edge hostname and port. Private endpoints are reachable only on the
private network.

Errors use the node envelope `{error:{code,message,details}}`:

| Status | Meaning |
| --- | --- |
| 401 | Missing key |
| 403 | Forbidden operation |
| 404 | Missing resource |
| 409 | State conflict |
| 410 | Expired TTL |
| 422 | Invalid field |
| 503 | Placement unavailable |

A 503 `no_room` names the tier, what is missing and each node's reason. A create refused because no
node offers what it asks for leaves no sandbox. A create refused only for room stays, and is placed
when a node has room. API v1 changes only by addition.

## Direct sandbox operations

`POST /v1/sandboxes/{id}/token` returns a short-lived sandbox capability and the agent's URL. The
SDKs cache it, then send running processes, terminals, streamed files and runtime expose requests
through the edge straight to `/_hermitbox/`. The project key never reaches the sandbox.
[The agent API](https://docs.hermitbox.dev/v0.3.2/reference/sandbox-agent.md) covers its contract, file URLs, spare ports and network policy.

While compute is stopped or sleeping, the `/data/content`, `/data/list` and `/data/stat` routes
read and write through the node's files feature. Raw content streams as
`application/octet-stream`; JSON requests stay bounded.

## Projects and limits

A project is a set of sandboxes with its own keys and limits. An operator creates one with
`POST /operator/v1/projects` on the private operator listener. The body accepts `name`, `key:true`
and any project limit. The response holds the project, its effective limits and its usage, plus
one new raw key when the body asked for it.

`GET` on the collection lists projects. `GET`, `PATCH` or `DELETE` on `/<project-id>` views,
changes or deletes one. `POST /<project-id>/freeze` stops its sandboxes and refuses public writes;
`/unfreeze` allows new work again without restarting them. `GET /<project-id>/usage` and the public
`GET /v1/project` show units and counts against the effective limits.

`hermitbox project create --max-units 5 --max-running 3 --max-ttl 2h --expires-in 24h` creates a
project, and `hermitbox key create --project <project-id>` prints a key once. `hermitbox project`
`ls`, `get`, `set`, `freeze`, `unfreeze` and `rm` use the same operator listener.

`set` accepts `--max-*` flags, `--allowed-images` comma-separated prefixes and `--expires-in`. A
value of `unlimited` resets a numeric or image limit to inheritance.

Units default to 512 MiB and 250 CPU millis (`HERMITBOX_UNIT_MEMORY_MB`, `HERMITBOX_UNIT_CPU_MILLIS`).
Create accepts `units` (default one) or explicit resources rounded upward to whole units.

`cpuReservationMillis` records the CPU counted at admission; it is not an enforced ceiling.
Container units keep their quotas. Process and Wasm units reserve CPU without a quota, and an
explicit `cpuMillis` ceiling or `cpuWeight` on those tiers returns 422 naming the resource field.

A VM's `cpuMillis` ceiling is its guest's whole vCPUs: a positive multiple of 1000, or 422 on
`resources.cpuMillis`. Units round it down to the whole vCPUs they pay for, and `cpuWeight`
returns 422. When you need a weight, use container isolation.

Node listings include `unitsFree` and regional totals after host and running reservations.

Project limits are `maxUnits`, `maxSandboxes`, `maxRunning` (including suspension with memory held),
`maxUnitsPerSandbox`, `maxTtl`, `maxIdle`, `maxExecTimeout`, `maxSnapshots`, `maxSnapshotBytes`,
`maxEgressPorts`, `allowedImages` and `expiresAt`. A refusal is 403 `limit_exceeded` with
`details:{name,limit,current}`.

A command whose outcome is unknown keeps its compute reservation until a stop is confirmed, so a
retry never exceeds the quota. Snapshot bytes are measured before a snapshot is published.
Lowering an aggregate limit below current usage freezes the excess. When a project expires, its
data is deleted and its keys are revoked. Lists and every resource route are scoped to the
project, and another project's IDs answer 404.

Each limit takes its deployment default from `HERMITBOX_PROJECT_<UPPER_SNAKE_NAME>`, for example
`HERMITBOX_PROJECT_MAX_UNITS` and `HERMITBOX_PROJECT_ALLOWED_IMAGES`. A limit with no default is
unlimited. A non-null project value overrides the default; null restores inheritance. `maxTtl`
and `maxIdle` also fill in a sandbox's timers when the create leaves them out. A project's image
permissions never reach past the host's policy.

## Isolation and software

A create can ask for `container`, `gvisor`, `process`, `vm` or `wasm` isolation. Placement and
template warming need a node that advertises the requested tier. Project usage counts every tier
in units. Sandbox responses report the chosen tier in `isolation` and, once the sandbox is placed
on a reporting node, its `backend` (`engine` and `rootless`).

The container tier accepts any image the host permits. Process and wasm refuse an image with a
422 `invalid_request` naming the field. `packages` is an array of agentOS registry names, for wasm
only, and is sent only after the node advertises `wasm-packages`. Names are not URLs or host
paths.

The no-engine image default and measured comparison are in [tiers.md](https://docs.hermitbox.dev/v0.3.2/reference/tiers.md);
[agentos.md](https://docs.hermitbox.dev/v0.3.2/integrations/agentos.md) describes persistence, software distribution and the agentOS boundary.

## SDK handles and live commands

The TypeScript, Python and Rust SDK READMEs have runnable handle examples. A command starts when
you call it: `run` returns a native promise, task, future or sync result, and `stream` iterates
the output with `lines` and `result`.

Each command gets one idempotency key, and mutations never retry automatically. A stream that ends
without its exit event has an unknown outcome. Public exec and logs forward the agent's frames as
their published v1 records, and a failure after the exec headers arrives as an error event.

`PUT /v1/sandboxes/{id}/file-chunks/{path}` accepts `offset` (a 32 KiB boundary) and `dataBase64`
(up to 32 KiB decoded); `GET` returns a base64 tar member named `data`. These v1 JSON forms stay
for HTTP callers. The SDKs use binary streams instead.

Control forwards binary bytes to the agent, and the node serves the data of a stopped sandbox. A
positional JSON write copies the existing bytes to a private temporary file in control before
replacing them, so memory use stays bounded. Serialize concurrent writers yourself: a write that
spans several requests is not atomic.

Decoded JSON file reads are held to the node's JSON memory bound; binary streams and chunk reads
have no limit on total file size. None of this runs a command in the sandbox or extracts an
archive. Paths stay relative, with no dot segments or symlink components.

## Field surface

Create accepts `env`, `labels`, a `name` unique in the project, `metadata` as a JSON object, an
absolute `workdir`, a numeric `user`, `idle` and `autoDelete`. The requested user must match the
operator's container UID policy; process and wasm refuse a user.

`autoDelete` needs `idle`: when the sandbox goes idle it is deleted instead of keeping its compute
and data. `GET /v1/sandboxes` filters by name, a subset of labels and state. A name stays reserved
until its sandbox is deleted. An SDK lookup by ID or name wakes a sleeping or resting sandbox
unless `wake` is false.

### Lifecycle and metrics

`POST /v1/sandboxes/{id}/lifetime` takes exactly one positive `keepAlive`, `ttl` or `idle` in seconds, bounded by project ceilings and expiry. `keepAlive` extends access and touches activity; `ttl` replaces the deadline from now.

`GET /metrics` returns the node's last sample of CPU, memory, PIDs, throttling, limits, disk and
network, without polling; with `since` it returns up to 2000 one-minute samples.
`GET /metrics/stream` pages through retained history from `since`, then follows new observations
as NDJSON. Set `follow=false` for a finite result.

`hermitbox sandbox top <sandbox-id>` streams these samples in the CLI and accepts `--since` and
`--once`. History lasts as long as the sandbox, and an unavailable counter is null.

The SDKs' `waitUntil` polls the public state. `events` streams NDJSON with `stream=true`, an
optional `since` timestamp and `follow=true`. Each `sandbox.woken` event carries `source`
(`request` or `edge`), `tier` (`resumed`, `booted` or `restored`) and `durationMs`. Without
`stream=true`, events keeps its published v1 JSON shape.

### Processes and shells

The SDK process handle adds `waitForPort` (HTTP or TCP, with path, status and timeout),
`waitForLog`, `waitForExit` and `logs`. A missed deadline is `wait_timeout`; a process that exits
before it is ready is `process_exited`. `run` and `spawn` accept stdin once, as text or bytes.

A sandbox's `processes` and `killAll` list and stop the processes it owns. `shell` opens a stateful
session over serialized pipes, with stderr kept separate and exact exit codes; `close` ends it.
[The agent API](https://docs.hermitbox.dev/v0.3.2/reference/sandbox-agent.md) lists every versioned route and budget.

### Files and Git

The files API adds `exists`, `find` by glob, `grep`, literal replacement at regex matches,
`chmod`, upload and download from the caller's disk with progress callbacks, tar `uploadDir` and
`downloadDir`, and `sync`, which upserts by SHA-256. The CLI's `cp` uses these methods.

Git `clone`, `status`, `diff`, `branch`, `checkout`, `add`, `commit`, `push`, `pull` and `log`
return parsed values along with the raw output. Clone takes path, branch, depth and token; commit
takes author, diff takes staged, and log takes limit.

A token goes through a one-call credential helper scoped to its HTTPS host, never a credential file
on disk. Git clone, push and pull, and the temporary VM bridge they use, default to five minutes,
and each call can override the timeout. They turn off background maintenance and unset every trace
destination.

On wasm, clone metadata lives in the persistent guest filesystem while the checkout stays in the
mounted data. A create with a repository clones before it returns; if that preparation fails, the
sandbox is kept so you can inspect it.

### Template builds

The SDK's `template` method builds from an image or an isolation tier, with copy pairs, env,
workdir, run commands and a ready check. Only a ready check that passes publishes a snapshot
version. A sandbox created from a version runs its start command in the sandbox's data directory,
unless the create sets a workdir.

`POST /v1/templates/{name}/versions` registers a completed snapshot the project owns, with its start
plan; `GET` lists the immutable versions. A snapshot or hidden builder that a version still uses
can't be deleted.

The SDK's `rebuild` uses the same local context. The CLI's `templates` lists versions, and
`template build -f hermitbox.template.ts` imports the file's default plan.

### Egress

Egress rules choose which hosts a sandbox can reach. On the container tier,
`egress:{allow:[hosts],deny:[hosts]}` needs the node to announce the `egress-hostnames` feature
and a firewall installed as root. Deny wins over allow, and a wildcard matches only subdomains.

The bridge sends HTTP and TLS to host gateways, which resolve and pin public destinations at connect
time. It refuses raw IPs, non-public answers and answers naming an address of this host, and it
blocks every other new outbound protocol. TLS passes through with certificate checks intact.

Process sandboxes take `egress` where their node announces `tier-process:egress-hostnames` (kernel
network policy, [bpf.md](https://docs.hermitbox.dev/v0.3.2/reference/bpf.md)). Wasm refuses it and names the tier.

`egressAddresses:{allow:[{prefix,ports?}],deny:[…]}` allows or denies exactly those prefixes and
inclusive port ranges, deny first. It is placed only on a tier announcing `egress-addresses`
(kernel policy on the process tier), and it can't name loopback, link-local, multicast or
IPv4-mapped ranges.

`egressAddresses` refuses rules whose ports, together with those of every wider prefix, come to
more than 24 ranges on one address, and names the prefix. No request can configure firewall
readiness or relax host policy.

## Lifecycle webhooks

A webhook tells your server when a sandbox changes state. `POST /v1/webhooks` takes `url` and
`kinds`; `GET` lists registrations, `DELETE /<webhook-id>` removes one, and
`GET /<webhook-id>/deadletters` shows deliveries that ran out of attempts. Kinds are `created`,
`running`, `sleeping`, `woken`, `resting`, `deleted`, `failed`, `ttl_expired` and `idle_slept`.

Creation returns the secret once; listing never does. The payload is `{id,event,sandboxId,at}`,
with no sandbox env, metadata or secret values. The lifecycle transaction itself enqueues the
delivery, atomically.

To verify a delivery, compute a lowercase hex HMAC-SHA256 with the full UTF-8 secret from creation,
over `hermitbox-timestamp`, a literal dot, then the exact raw body bytes. `hermitbox-signature` is
`v1=` followed by that hex. Compare in constant time, reject stale timestamps, and deduplicate
`hermitbox-id` across retries. The timestamp is in Unix seconds.

Delivery resolves every address once, refuses non-public DNS answers, and pins the chosen
destination while keeping the original HTTPS SNI and Host. It verifies TLS and never follows
redirects. An operator can allow a private receiver of their own with
`HERMITBOX_WEBHOOK_ALLOW_HOSTS`; a project can't.

Each attempt has a ten-second deadline for DNS, connect and response. Delivery makes five attempts
in all, waiting one, two, four and eight minutes between them, with durable leases and dead
letters. A delivery keeps its ID across attempts, and each attempt gets a fresh timestamp and
signature. Return 2xx once you have stored the event durably.

`hermitbox webhook create <url> --kinds created,deleted`, `webhook ls`, `webhook rm <webhook-id>`
and `webhook deadletters <webhook-id>` manage the same project-scoped registrations.

## CLI subcommands

`hermitbox sandbox` adds `ps`, `spawn`, `kill-all`, `wait-port`, `wait-log`, `wait-exit`, `shell`
(interactive or `--command`), `exists`, `find`, `grep`, `replace`, `chmod`, `sync`, `git`,
`keep-alive`, `ttl`, `idle`, `metrics` and `wait`. `exec`, `run` and `spawn` with `--stdin` read
the caller's input once.

Create flags include `--name`, `--labels`, `--metadata`, `--env`, `--workdir`, `--user`,
`--auto-delete` and `--egress`, or a `--spec` JSON file. `sandbox ls` accepts `--name`, `--labels`
and `--state`, and `events` accepts `--since` and `--follow`. Git works in `repo` by default;
`clone --path` changes the directory for that SDK handle only. The [CLI reference](https://docs.hermitbox.dev/v0.3.2/reference/cli.md) has
every command and option.
