# Public API

Hermitbox's public HTTP API lives under `/v1` on your install's API URL. Authenticate every request with `Authorization: Bearer <key>`; requests and responses are JSON, and exec and logs stream NDJSON.

Create, list and revoke keys with `hermitbox key` on the private operator listener; the key chooses the project. See [control/README.md](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/control/README.md) for configuration, and the [TypeScript](https://docs.hermitbox.dev/v0.2.1/sdk/typescript.md) and [Python](https://docs.hermitbox.dev/v0.2.1/sdk/python.md) SDKs for examples.

## Endpoints

### 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

Requests and responses are defined in [the OpenAPI document](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/control/openapi/hermitbox.openapi.json). Exec and logs use `application/x-ndjson`. Exec forwards live agent stdout and stderr chunks, a final exit event, and an error event for a failure after headers.

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

Use a stable `Idempotency-Key` for retried create or exec requests; reusing one for different input is refused. An exec with an uncertain outcome is never replayed automatically. Lifecycle operations return the reached sandbox and, for sleep and wake, its tier.

TTL expires access immediately, and upkeep deletes data. Idle is evaluated from activity and live sessions. Templates warm each active node once and retain a stopped snapshot.

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

Errors have the node envelope `{error:{code,message,details}}`. Invalid fields answer 422, missing keys 401, forbidden operations 403, missing resources 404, state conflicts 409, expired TTL 410 and unavailable placement 503. API v1 evolves additively.

## Direct sandbox operations

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

The `/data/content`, `/data/list` and `/data/stat` routes use the node files feature while compute is stopped or sleeping. Raw content streams as `application/octet-stream`; JSON requests stay bounded.

## Projects and limits

An operator creates a project with `POST /operator/v1/projects` on the private operator listener.
The body accepts `name`, `key:true` and any project limit; the response includes the project,
effective limits, usage, and one new raw key only when requested.

`GET` on the collection lists projects, and `GET`, `PATCH` or `DELETE` on `/<project-id>` views,
changes or deletes one. `POST /<project-id>/freeze` stops its sandboxes and refuses public writes;
`/unfreeze` permits new work without restarting them. `GET /<project-id>/usage` and public
`GET /v1/project` show units and counts against 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 admission CPU, not an enforced ceiling. Container units retain their quotas. Process and Wasm units reserve CPU without a quota; explicit `cpuMillis` ceilings or `cpuWeight` requests on those tiers return 422 with the resource field identified.

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. Use container isolation when a weight is required.

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}`.

Unknown command outcomes retain their compute reservation until a confirmed stop, so a retry never
exceeds quota. Snapshot bytes are measured before publication. Lower aggregate limits freeze
excess usage; expiry deletes owned data and revokes keys. Lists and all resource routes are
project-scoped, and foreign IDs answer 404.

Each limit has `HERMITBOX_PROJECT_<UPPER_SNAKE_NAME>` as its deployment default, for example
`HERMITBOX_PROJECT_MAX_UNITS` and `HERMITBOX_PROJECT_ALLOWED_IMAGES`. Missing defaults are unlimited.
Non-null project columns override defaults; null restores inheritance. `maxTtl` and `maxIdle` also
supply omitted sandbox timers. Public image permissions always remain bounded by host policy.

## Isolation and software

Creation accepts `container`, `gvisor`, `process`, `vm` or `wasm` isolation. Placement and template
warming need a node that advertises the requested tier. Project usage counts all tiers in units.
Sandbox responses report the selected tier in `isolation`.

Container accepts host-permitted images. Process and wasm refuse images with a field-specific
422 `invalid_request`. `packages` is an array of agentOS registry names, available only for wasm
and 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.2.1/reference/tiers.md);
[agentos.md](https://docs.hermitbox.dev/v0.2.1/integrations/agentos.md) describes persistence, software distribution and the agentOS boundary.

## SDK handles and live commands

The TypeScript and Python SDK READMEs contain executable handle examples. Commands start on
call: `run` returns a native promise or task, or a sync result, and `stream` iterates output with
`lines` and `result`.

Each command receives one idempotency key, and mutations never retry automatically. A stream ending
without its exit has an unknown outcome. Public exec and logs forward agent frames into their
published v1 records; failures after exec headers use 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 representations
remain for HTTP callers; SDKs use binary streams directly.

Control forwards binary bytes to the agent, with stopped data served by the node. Positional JSON
writes spool existing bytes to a private control temp file before replacement, keeping RAM bounded.
Callers must serialize concurrent writers; multi-request writes are not atomic.

Decoded JSON file reads use the node-owned JSON memory bound; binary streams and chunk reads have no
total file bound. No sandbox command or archive extraction is involved. Paths remain relative,
without dot segments or symlink components.

## Field surface

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

`autoDelete` requires `idle` and deletes after idle instead of retaining compute and data. `GET /v1/sandboxes` filters by name, label subset and state. Names remain reserved until deletion. SDK ID or name lookup wakes sleeping or resting data 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 last node CPU, memory, disk and network sample without polling; `since` returns up to 2000 minute samples. `GET /metrics/stream` pages through retained history from `since`, then follows current observations as NDJSON. Set `follow=false` for a finite result.

The CLI streams these samples with `hermitbox sandbox top <sandbox-id>` and accepts `--since` and `--once`. History persists for the lifetime of the sandbox, and unavailable counters are null.

SDK `waitUntil` polls public state. `events` uses NDJSON with `stream=true`, an optional `since` timestamp and `follow=true`. Plain v1 events still returns its published JSON shape.

### Processes and shells

The SDK process handle adds `waitForPort` (HTTP or TCP, path, status and timeout), `waitForLog`, `waitForExit` and `logs`. A deadline is `wait_timeout`; exit before readiness is `process_exited`. `run` and `spawn` accept one-shot stdin text or bytes.

Sandbox `processes` and `killAll` inspect and stop owned processes. `shell` opens a serialized stateful pipe session with separate stderr and exact exit codes; `close` ends it. See [agent.md](https://docs.hermitbox.dev/v0.2.1/reference/sandbox-agent.md) for all versioned routes and budgets.

### Files and Git

Files add `exists`, `find` glob, `grep` and literal replacement at regex matches, `chmod`, caller-disk upload and download with progress callbacks, tar `uploadDir` and `downloadDir`, and SHA-256 upsert `sync`. CLI `cp` uses these methods.

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

Tokens use an HTTPS host-scoped one-call credential helper, never a persisted credential file. Git clone, push and pull and their transient VM bridge default to five minutes with per-call timeout overrides, disable background maintenance and unset all trace destinations.

Wasm clone metadata uses the persistent guest filesystem while checkout data stays mounted. Repo creation clones before returning and retains the sandbox identity if preparation fails.

### Template builds

The SDK `template` method builds from image or isolation with copy pairs, env and workdir, run commands and ready; only a successful ready publishes a snapshot version. Creating from a version runs start in the sandbox data directory unless an explicit workdir is set.

`POST /v1/templates/{name}/versions` registers an owned completed snapshot and its start plan; `GET` lists immutable versions. A referenced snapshot and hidden builder cannot be deleted while versions use them.

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

### Egress

Container `egress:{allow:[hosts],deny:[hosts]}` requires the announced `egress-hostnames` node feature and a root-installed firewall. Deny overrides allow, and a wildcard matches only subdomains.

The bridge redirects HTTP and TLS to host gateways, resolves and pins public destinations at connect time, refuses raw IPs, non-public answers and answers naming an address of this host, and blocks other new outbound protocols. TLS passes through with certificate checks intact.

Process sandboxes take it where their node announces `tier-process:egress-hostnames` (kernel network policy, [bpf.md](https://docs.hermitbox.dev/v0.2.1/reference/bpf.md)); wasm refuses it with the tier named.

`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 cannot name loopback, link-local, multicast or IPv4-mapped ranges.

Rules whose ports, with those of every wider prefix, come to more than 24 ranges on one address are refused on `egressAddresses`, naming the prefix. The request cannot configure firewall readiness or relax host policy.

## Lifecycle webhooks

`POST /v1/webhooks` takes `url` and `kinds`; `GET` lists, `DELETE /<webhook-id>` removes, and `GET /<webhook-id>/deadletters` inspects exhausted delivery. 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. A lifecycle transaction enqueues delivery atomically.

Verify `hermitbox-signature` as `v1=` plus lowercase hex HMAC-SHA256 using the full UTF-8 creation secret over `hermitbox-timestamp` + a literal dot + the exact raw body bytes. Compare in constant time, reject stale timestamps, and deduplicate `hermitbox-id` across retries. The timestamp is Unix seconds.

Delivery resolves all addresses once, refuses non-public DNS, pins the chosen destination with original HTTPS SNI and Host, verifies TLS and never follows redirects. An operator can explicitly allow an owned private receiver with `HERMITBOX_WEBHOOK_ALLOW_HOSTS`; projects cannot.

Delivery has a ten-second DNS, connect and response deadline, five total attempts, one, two, four and eight-minute delays, durable leases and dead letters. Delivery IDs remain stable, and each attempt gets a fresh timestamp and signature. Receivers should return 2xx after durable acceptance.

`hermitbox webhook create <url> --kinds created,deleted`, `webhook ls`, `webhook rm <webhook-id>` and `webhook deadletters <webhook-id>` operate on the same 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` and `keep-alive`, `ttl`, `idle`, `metrics` and `wait`. `exec`, `run` and `spawn` with `--stdin` read caller input once.

Create flags include `--name`, `--labels`, `--metadata`, `--env`, `--workdir`, `--user`, `--auto-delete` and `--egress`, or `--spec` JSON. `sandbox ls` accepts `--name`, `--labels` and `--state`, and `events` accepts `--since` and `--follow`. Git uses `repo` by default; `clone --path` changes only that SDK handle.
