# kumobad HTTP API (https://kumoba.dev/http-api)

kumobad speaks HTTP/1.1 on `~/.kumoba/kumobad.sock` and `127.0.0.1:7788`, and serves browser previews on `127.0.0.1:7789` ([Configuration](/configuration) changes these). With `KUMOBAD_TLS_CERT` and `KUMOBAD_TLS_KEY` both TCP listeners speak HTTPS, which is how a client on another machine reaches it ([Run sandboxes on another machine](/guide/remote-daemon)). Every route except `/healthz` and `/v1/preview/...` needs `authorization: Bearer <token>`, where the token is the content of `~/.kumoba/token`.

```sh
curl --unix-socket ~/.kumoba/kumobad.sock -H "authorization: Bearer $(cat ~/.kumoba/token)" http://kumobad/v1/images
```

## Commands [#commands]

`GET /v1/commands` → `{"version": "0.18.0", "commands": [...]}` describes every route below in machine-readable form: `name`, `summary`, `method`, `path`, the `positional` arguments in the order a command line gives them (the path arguments first, then any others, such as the `x` and `y` of `click`), the `rest` argument that takes a trailing list, `input` (`none`, `json` or `bytes`), `output` (`json`, `events`, `bytes` or `terminal`), `in` (whether each argument goes in the path, query, JSON body or raw body) and `inputSchema`, a JSON Schema covering all of them. Three optional fields tell a client how to present a command: `render` is `image` for a PNG to save and report by path and size, or `elements` for a list to print one element per line; `defaultSandbox: true` marks a command whose sandbox id may come from the client's default, `KUMOBA_SANDBOX` in the `kumoba` CLI; and `mcp: false` marks a command that `kumoba mcp` leaves out of its tools, as it moves whole archives or only describes the catalog. Commands with output `terminal` are left out of the tools too. The `kumoba` CLI is built on this route alone, and the schemas can be handed to a model as tool definitions.

Errors are JSON: `{"error": "<code>", "message": "<detail>"}` with an HTTP status. Some also carry `reason`, a stable tag for the case when one code covers several: `sandbox_not_found` (404 `not_found`, no sandbox with that id; the message names it), `not_started` and `busy` (409 `conflict`: the sandbox is stopped, or another call holds its disk), `desktop_not_started` (409 `conflict`: the sandbox runs, but its desktop does not; [start it](#desktop) first), `no_desktop` (422 `guest_error`: the sandbox has no desktop to drive, as with the `test` image or a macOS sandbox), `unknown_image` and `invalid_cursor` (400 `invalid_request`; an unknown image's message lists the images there are), `outcome_unknown` (500 `internal`: kumobad lost track of the call partway, so it may or may not have taken effect, as when the sandbox's worker ends during a command; check before you repeat it), and, from a fleet, `no_matching_host` (409 `conflict`: no available host that serves the image carries every `placement` label) `may_exist` (503 `host_unavailable` with `"mayExist": true`: the fleet had connected to the host for a create, a `run` or an import, but no complete answer came, so look for the sandbox there before trying again) and `outcome_unknown` (503 `host_unavailable`: the fleet had connected to the host for any other call except a `GET`, but no complete answer came, or the host answered a change with something that is not JSON, so check its effect before repeating it). A [fleet](#fleet) relays a host's `reason` unchanged. A kumobad from 0.14 or earlier sends no `reason`, so branch on `error` first. A request body that is not JSON, or does not fit the call, is 400 `invalid_request` whose message names the field and the type it expects, or the line and column where the JSON breaks, and never quotes a value from the body. `error` is one of these codes:

| Status | `error` | When |
| --- | --- | --- |
| 400 | `invalid_request` | The body, a path or query argument, a cursor or a `label` filter is not valid, the query has a parameter the route does not take, or the daemon refuses a value, such as an unknown image |
| 401 | `unauthorized` | The bearer token is missing or wrong. A kumobad from 0.14 or earlier sends no `message` with it |
| 403 | `forbidden` | A preview token is invalid or expired |
| 404 | `not_found` | No such sandbox or route. The preview listener answers this for anything but a preview |
| 408 | `request_timeout` | The request body did not arrive in time: 30 s for a JSON or preview body, and an upload that sends nothing for 60 s |
| 409 | `conflict` | The sandbox is in the wrong state for the call: not started, or busy with another operation |
| 409 | `draining` | The host is [draining](#drain): it creates no sandboxes, and with `strict` starts no stopped ones |
| 409 | `not_idle` | A [stop with `ifIdleForMs`](#start-and-stop) found the sandbox in use or recently active, and left it running |
| 413 | `request_too_large` | The request body is over its limit: 1 MiB for a JSON body, 10 MiB for a preview |
| 422 | `exceeds_host_memory` | With `KUMOBAD_ADMIT_BY_MEMORY=1`, the sandbox asks for more memory than the host's whole memory budget, so it can never run there. The message names the budget. Retrying does not help; ask for less memory or use a bigger host |
| 422 | `guest_error` | The command or file operation failed inside the VM, or the image lacks what the call needs, such as a desktop or shell support |
| 426 | `upgrade_required` | A `shell` request without the `kumoba-shell.v1` upgrade |
| 429 | `capacity` | Every running slot is in use: `KUMOBAD_MAX_RUNNING` sandboxes are running or starting, two macOS sandboxes already run, or, with `KUMOBAD_ADMIT_BY_MEMORY=1`, the new sandbox's memory does not fit in the memory budget. The reply carries `Retry-After: 5` |
| 507 | `disk_full` | A create, a create with `start` or `/v1/run` would leave less free disk than `KUMOBAD_MIN_FREE_DISK_MIB`, or does not fit at all. Nothing was copied. It does not go away on its own: delete or [prune](#prune-stopped-sandboxes) stopped sandboxes, or free space on the host. With `KUMOBAD_PRUNE_STOPPED_ON_DISK_PRESSURE_MS` set, kumobad first deletes stopped sandboxes older than that and answers 507 only when they could not make room. A fleet names the hosts short of disk in `diskFullHosts` |
| 500 | `internal` | The daemon failed, such as a guest connection that broke |
| 503 | `host_unavailable` | From a [fleet](#fleet) only: the sandbox's host did not answer, failed its health checks, or is refused, or no host is available |
| 502 | `bad_gateway` | A preview's port or live view in the sandbox could not be reached, or sent a reply kumobad cannot read |
| 504 | `gateway_timeout` | A preview's app sent no response headers within 30 s |

Earlier releases answered these three preview failures with `internal`. Later releases may add codes; go by the status for one you do not know.

## Images [#images]

`GET /v1/images` → `{"images": ["default", "test"]}`

## Capacity [#capacity]

`GET /v1/capacity` → `{"running": 3, "maxRunning": 4, "maxRunningSource": {"mode": "fixed"}, "memoryMibInUse": 12288, "disk": {"freeBytes": 61203550208, "totalBytes": 214748364800, "stoppedSandboxBytes": 32212254720, "minFreeBytes": 0}, "draining": false, "drainStrict": false}`

`running` counts the running slots in use: sandboxes that run, boot, or have a slot held for a create with `start` that is still copying its disk. `maxRunning` is the limit `KUMOBAD_MAX_RUNNING` sets, and `maxRunningSource` says how kumobad got it: `{"mode": "fixed"}` for a number or the default, or for `auto`

```json
{"mode": "auto", "hostMemoryMib": 65536, "memoryFrom": "host", "reservedMib": 2048, "sandboxMib": 8192, "hostCpus": 4, "cpusFrom": "host", "sandboxCpus": 2}
```

where `hostMemoryMib` is the memory counted, `memoryFrom` is `host` or `cgroup` (a lower cgroup memory limit on Linux), and `reservedMib` and `sandboxMib` are `KUMOBAD_RESERVED_MEMORY_MIB` and `KUMOBAD_SANDBOX_MEMORY_MIB`. `hostCpus` is the CPUs counted, `cpusFrom` is `host` or `cgroup` (a lower cgroup CPU quota on Linux), and `sandboxCpus` is `KUMOBAD_SANDBOX_CPUS`; the limit is the smaller of the two counts. kumobad 0.9 leaves `maxRunningSource` out, and kumobad 0.13 and earlier leave out the three CPU fields, since they size `auto` from memory alone. `draining` says whether the host is [draining](#drain), and `drainStrict` whether that drain also refuses starts. On a Mac the reply also has `macosRunning` and `macosMaxRunning` for macOS sandboxes, which take a slot of each kind. `memoryMibInUse` adds up the `memoryMib` of the sandboxes `running` counts. With [`KUMOBAD_ADMIT_BY_MEMORY=1`](/configuration) the reply also has `memoryMibBudget`, the memory those sandboxes may use together; a start is admitted only while `memoryMibInUse` plus its own memory stays within it. kumobad 0.10 leaves both out. `disk` describes the filesystem of `KUMOBAD_STATE_DIR`: `freeBytes` and `totalBytes` as `df` shows them for an unprivileged user, `stoppedSandboxBytes` the blocks stopped sandboxes' files hold, which deleting them frees (on a filesystem with clones, blocks a sandbox shares with its image are counted but stay in use), and `minFreeBytes` the `KUMOBAD_MIN_FREE_DISK_MIB` a create must leave. kumobad measures a sandbox's files when it stops, so reading `disk` costs no directory walk. It is left out when the filesystem cannot be read, and by kumobad 0.10. Use it to wait or queue instead of creating blindly; the numbers can change before your next call, so a create can still answer 429.

## Host info [#host-info]

`GET /v1/info` describes this kumobad host, for a client that manages several:

```json
{
  "hostId": "d371e8385e751d26",
  "hostname": "kumoba-1",
  "version": "0.9.0",
  "guestProtocolVersion": 3,
  "diskMode": "layer",
  "images": [{"name": "default", "kind": "linux", "digest": "sha256:50eb0be2...", "baseReady": true}],
  "platform": {"os": "linux", "arch": "x86_64", "hypervisor": "kvm", "hypervisorAvailable": true, "cpus": 16, "memoryMib": 64000},
  "limits": {
    "maxRunning": 4,
    "defaults": {"cpu": 2, "memoryMib": 4096},
    "max": {"cpu": 8, "memoryMib": 16384}
  },
  "labels": {"zone": "a", "proxy": "corp"},
  "draining": false,
  "drainStrict": false,
  "disk": {"freeBytes": 61203550208, "totalBytes": 214748364800, "stoppedSandboxBytes": 32212254720, "minFreeBytes": 0}
}
```

- `hostId` is made once and kept in `KUMOBAD_STATE_DIR/host-id`, beside the sandboxes it names, so it survives restarts and upgrades and changes only with the state directory. It is lowercase letters, digits and `-`, never `.`. An admin may write their own id into that file; kumobad refuses to start if the file holds anything else. A copy of the state directory carries the id with it, so two hosts made from one VM or machine image that already ran kumobad, or from an rsync of the directory, report the same `hostId`. Leave `KUMOBAD_STATE_DIR` out of images you clone, or delete `host-id` before imaging, and each host makes its own on first start.
- `version` is the kumoba version and `guestProtocolVersion` the guest agent protocol it speaks, so a client can refuse a host it does not support.
- `diskMode` says how a new sandbox gets its disk: `reflink` (a clone, on Linux filesystems that can clone files, such as XFS and Btrfs), `layer` (a copy-on-write layer over a shared copy of the image, on a Mac and on Linux filesystems such as ext4; kumobad 0.15 and earlier used `reflink` on a Mac) or `copy` (a full copy for every sandbox, with `KUMOBAD_DISK_MODE=copy`). See [Disks](/architecture#disks). kumobad 0.10 leaves it out.
- With `reflink` and `layer`, a Linux image has `baseReady`: whether kumobad already holds the shared copy of the image's current version. Until it does, the next create copies the image first, which takes as long as copying the image does. kumobad makes the copy in the background when it starts and after the image changes, unless that would leave less than `KUMOBAD_MIN_FREE_DISK_MIB` plus 2 GiB free on the state directory's disk. A macOS image and the `copy` mode leave `baseReady` out.
- Each image's `kind` is `linux` for a disk file and `macos` for a macOS image directory; a sandbox of a `macos` image takes one of the host's macOS slots too.
- Each image's `digest` is `sha256:` of its disk file, or for a macOS image directory of the lines `<file> <sha256>` for `root.raw`, `aux.img` and `machine.json` in that order. kumobad hashes images one at a time in the background: every image when it starts, and an image whose files changed (size, modification or change time) on the next `/v1/info` after the change. It keeps the results in `KUMOBAD_STATE_DIR/image-digests.json`, so a restart does not hash again. `digest` is `null` while the image is being hashed or waits behind other images, and while its files are missing.
- `platform.hypervisor` is `kvm` on Linux and `hvf` (Hypervisor.framework) on a Mac; `hypervisorAvailable` says whether kumobad can use it right now (`/dev/kvm` opens for reading and writing, or `kern.hv_support` is 1). `cpus` counts the CPUs kumobad may run on and `memoryMib` the memory it may use: the host's, or on Linux a lower cgroup CPU quota or memory limit, as `KUMOBAD_MAX_RUNNING=auto` counts them.
- `limits.maxRunning` is `KUMOBAD_MAX_RUNNING`; on a Mac `limits.macosMaxRunning` is the two-VM limit for macOS sandboxes. `defaults` is what a create without `cpu` or `memoryMib` gets, and `max` the most a create accepts. A macOS image ignores both: its sandboxes get the CPUs and memory its `machine.json` sets.
- `labels` come from `KUMOBAD_HOST_LABELS`.
- `draining` says whether the host is [draining](#drain), and `drainStrict` whether that drain also refuses starts.
- `disk` is the same as in [`/v1/capacity`](#capacity).

A kumobad from 0.9 or earlier answers 404 `not_found`.

## Drain [#drain]

`POST /v1/drain` → `{"draining": true, "strict": false}` takes the host out of service, for an upgrade or to retire it, whichever client asks. While it drains, `POST /v1/sandboxes` (with or without `start`) and `POST /v1/run` answer 409 `draining` at once and create nothing; a create with `start` or a run already waiting for a slot gets that answer as soon as the drain begins. Running sandboxes, their commands, shells, file transfers, previews and live views carry on, and so does a create that had already passed that point. Starting a stopped sandbox still works, unless the drain was asked with `?strict=true`; it then answers 409 `draining` too. Each call sets the drain's strictness from its own `strict`, so a `POST /v1/drain` without it turns a strict drain into a plain one; read `drainStrict` first to keep it. kumobad logs each change as `{"event": "drain", "draining": ..., "strict": ..., "source": "api"}`, and `"source": "startup"` when it starts draining.

`DELETE /v1/drain` → `{"draining": false}` puts the host back in service.

A drain lasts until `DELETE /v1/drain` or until kumobad stops; it is not written to disk. To have kumobad come back draining after maintenance, start it with `KUMOBAD_DRAIN_ON_START=1`, or `KUMOBAD_DRAIN_ON_START=strict` for a strict drain. `/v1/capacity` and `/v1/info` report `draining` and `drainStrict`. A kumobad from 0.9 or earlier answers 404 `not_found`.

## Sandboxes [#sandboxes]

### Create [#create]

`POST /v1/sandboxes`

```json
{
  "image": "default",
  "labels": {"project": "demo"},
  "cpu": 2,
  "memoryMib": 4096,
  "autoStopMinutes": 15,
  "autoDeleteMinutes": null,
  "network": {"mode": "allowlist", "hosts": ["api.github.com"]},
  "start": true,
  "waitMs": 0
}
```

Only `image` is required. `network.mode` is `open`, `allowlist` or `blocked`. In `allowlist` mode `hosts` lists what the sandbox may reach; see [Allowlist entries](#allowlist-entries). `autoStopMinutes: 0` disables auto-stop. `autoDeleteMinutes` removes a stopped sandbox after that many minutes; `null` keeps it. A `labels` key must not be empty or contain `:`, since a `label` filter could never match it; create, `PATCH` and `/v1/run` answer such a key with 400 `invalid_request`.

#### Allowlist entries [#allowlist-entries]

| Entry | Matches |
| --- | --- |
| `git.example.com` | That host name |
| `*.example.com` | Its subdomains, not `example.com` itself |
| `203.0.113.7`, `[2001:db8::7]` | That address |
| `10.20.0.0/16`, `[2001:db8::/32]` | Addresses in that range |

An entry without a port allows ports 80 and 443. Add `:port` to allow that one port instead: `git.example.com:7999`, `*.example.com:8443`, `10.20.0.0/16:8443`. An IPv6 address or range always goes in brackets, with or without a port: `[2001:db8::7]`, `[2001:db8::7]:8443`, `[2001:db8::/32]:443`. Without brackets `2001:db8::7:8443` could be an address or an address and a port, so an unbracketed IPv6 entry is refused with a message that shows both forms. Host names are matched case-insensitively and a trailing `.` is ignored. A range must name its first address (`10.20.0.0/16`, not `10.20.0.1/16`), and an address written as IPv4-mapped IPv6 (`[::ffff:10.20.0.1]`) counts as the IPv4 address. An allowlist holds up to 128 grants of each kind: host names, `*.domain` wildcards without a port, `*.domain:port` wildcards, and addresses and ranges. A host name, address or range without a port counts as two grants, one per port, and repeated entries count before duplicates are merged. Anything else, such as a port outside 1 to 65535, a prefix too long for the address, an IPv6 zone (`fe80::1%eth0`) or a numeric host like `2130706433`, is 400 `invalid_request` naming the entry.

Programs in the guest reach these through the proxy at `127.0.0.1:3128` that `HTTPS_PROXY` names; a program that does not use an HTTP proxy, such as `ssh` or a database client, has to open its connection with an HTTP `CONNECT` through it.

Names and addresses are matched separately. A host name or `*.domain` entry matches a connection the guest makes to a name, and an address or range entry matches one it makes to an IP address (`CONNECT 10.20.1.5:443`, `https://[2001:db8::7]/`). A name is never allowed because it resolves into a listed range, so an address entry never makes kumobad look up a name the allowlist does not cover, and the host's DNS cannot be used to send data to a name the sandbox was not given. To reach an internal service by name, list the name.

Entries never widen the host's rules. A sandbox reaches a public IPv4 address on whatever port its allowlist names, so `0.0.0.0/0:25` reaches port 25 everywhere on the public internet. Every other destination also needs the operator's `KUMOBAD_ALLOW_PRIVATE_HOSTS`, which applies to every sandbox on the host: a private IPv4 address, and any IPv6 address at all, is reachable only when that setting and the sandbox's allowlist both allow the address and the port. An operator entry without a port opens ports 80 and 443 only; `10.20.0.0/16:5432` opens one port and `10.20.0.0/16:*` every port. This holds for names too: a name entry such as `db.corp.example:5432` that resolves into `10.20.0.0/16` needs the operator to open port 5432 there. The addresses in [Always blocked](#always-blocked) stay blocked even when the operator opens a range that contains them. kumobad resolves names to IPv4 only, so IPv6 is reached by address. In `open` mode the guest still reaches hosts by name only; a connection to an IP address is denied.

#### Always blocked [#always-blocked]

No allowlist and no `KUMOBAD_ALLOW_PRIVATE_HOSTS` entry opens these, by address or through a name that resolves to them, in any mode:

| Range | What it is |
| --- | --- |
| `0.0.0.0/8`, `127.0.0.0/8`, `[::/96]` | This host, loopback, IPv4-compatible IPv6 |
| `169.254.0.0/16` | Link-local, including the AWS, GCP and Azure instance metadata address `169.254.169.254` |
| `168.63.129.16` | Azure WireServer |
| `100.100.100.200` | Alibaba Cloud metadata |
| `192.0.0.0/24`, `224.0.0.0/4`, `240.0.0.0/4` | IETF protocol assignments, multicast, reserved and broadcast |
| `[::ffff:0:0/96]`, `[::ffff:0:0:0/96]` | IPv4-mapped and IPv4-translated (SIIT) IPv6 |
| `[64:ff9b::/96]`, `[64:ff9b:1::/48]` | NAT64 well-known and local-use prefixes |
| `[2001::/32]`, `[2002::/16]` | Teredo, 6to4 |
| `[fe80::/10]`, `[fec0::/10]`, `[ff00::/8]` | IPv6 link-local, site-local, multicast |
| `[fd00:ec2::/32]`, `[fd20:ce::254]` | AWS and GCP IPv6 metadata and services |
| This host's own addresses | Every IPv4 and IPv6 address on the host's interfaces |

An IPv4-mapped address is checked as its IPv4 address. A network-specific NAT64 prefix, one your network uses in place of `64:ff9b::/96`, reaches every IPv4 address through it, metadata included, so never put one inside an opened IPv6 range.

Without `start` the new sandbox is **stopped**. With `"start": true` kumobad holds a running slot before it copies the image's disk, then boots the sandbox and answers once it has started. When no slot is free it answers 429 `capacity` at once, with nothing created. `waitMs` (only with `start`, at most 600000) waits up to that many milliseconds for a slot first; slots go to waiting requests in the order they asked, and with `KUMOBAD_ADMIT_BY_MEMORY=1` a large sandbox that waits for memory is not passed by smaller ones behind it. A sandbox that asks for more memory than the whole memory budget answers 422 `exceeds_host_memory` at once, with or without `start`. If the boot fails, or the client disconnects before the answer, kumobad deletes the sandbox, so a failed create with `start` leaves no disk behind. A client that disconnects while its disk is still copying gives its slot back at once, and the copy is deleted when it finishes. Until the answer has been handed to the client, the sandbox is recorded as `"ephemeral": true`, so if kumobad stops before then it deletes the sandbox when it starts again. A macOS image waits for both kinds of slot without holding one while it waits for the other. On a Mac a macOS sandbox can still fail its boot with 429 when VMs of other apps hold Apple's two-VM limit; that is only known once the VM starts. A kumobad from 0.8 or earlier answers `start` and `waitMs` with 400 `invalid_request` and the message `` unknown field `start` ``.

A create and `POST /v1/run` also take `placement`, a JSON object such as `{"zone": "a"}` that a fleet of kumobad hosts uses to pick a host. A single kumobad accepts and ignores it, so the same request works against either; anything other than an object is 400 `invalid_request`.

Returns a summary, `"state": "started"` with `start` and `"stopped"` without:

```json
{
  "id": "6a0b...",
  "image": "default",
  "labels": {"project": "demo"},
  "cpu": 2,
  "memoryMib": 4096,
  "autoStopMinutes": 15,
  "autoDeleteMinutes": null,
  "network": {"mode": "allowlist", "hosts": ["api.github.com"]},
  "createdAtMs": 1760000000000,
  "lastActivityAtMs": 1760000000000,
  "activeOperations": 0,
  "openPreviews": 0,
  "state": "started"
}
```

`startedAtMs` is when the sandbox last finished booting; it appears after the first start. `stoppedAtMs` is when it last stopped, exact also when the guest shut down or crashed on its own; it appears only while the sandbox is stopped after a start. kumobad saves both with the sandbox, so they survive a restart. [Events](#events) has the full history.

`networkChangedAtMs` is when the sandbox's network policy last changed, the `atMs` of that change's `network_changed` [event](#events). It is absent until the first change after the sandbox was created or imported, and a `PATCH` with the policy it already has leaves it as it is. kumobad saves it with the sandbox, so it survives a restart; an export does not carry it.

`activeOperations` counts what is open in the sandbox right now: commands, shells, file transfers and preview or live view connections; `openPreviews` is how many of those are preview or live view connections. A plain preview request counts while it and its response are in flight; a streaming response, such as Server-Sent Events, counts until it ends, and an upgraded connection, such as a WebSocket or a live view, for its whole life. So a live view someone has watched quietly for an hour counts the whole hour, while `lastActivityAtMs` only moves when an operation starts or ends. kumobad does not auto-stop a sandbox while `activeOperations` is above 0. A kumobad from 0.9 or earlier leaves both out.

### List, get, update, delete [#list-get-update-delete]

- `GET /v1/sandboxes?label=key:value&label=k2:v2&limit=100` → `{"sandboxes": [...], "truncated": false}`. Every `label` filter must match. Newest first, by creation time; with more matches than `limit` (default 1000), the newest `limit` come back and `truncated` is true. A `label` that is not `key:value` with a non-empty key, such as `key=value`, is answered with 400 `invalid_request`. So are a `limit` that is not a whole number of 0 or more and any other query parameter, such as `labels`.
- `GET /v1/sandboxes?idle=true&idleForMs=600000` lists only started sandboxes with no open operation and no activity for at least `idleForMs` milliseconds (default 0), the same test auto-stop applies, so a client freeing a slot can pick one nobody is using. It combines with `label` and `limit`. `idle=false` lists every sandbox, as without it; `idleForMs` without `idle=true` is 400 `invalid_request`, and a kumobad from 0.9 or earlier refuses `idle` the same way.
- `GET /v1/sandboxes/{id}` → summary.
- `PATCH /v1/sandboxes/{id}` with `{"labels": {...}, "autoStopMinutes": 30, "network": {...}}` (all optional) → summary. `network` takes effect at once, also on a started sandbox, and is kept for later starts; nothing restarts and the disk is kept. See [Change the network of a started sandbox](#change-the-network-of-a-started-sandbox). `"dropUnreachableSecrets": true` with `network` removes the secrets the new policy no longer reaches in the same call; see [Narrow the network and drop secrets in one call](#narrow-the-network-and-drop-secrets-in-one-call).

#### Change the network of a started sandbox [#change-the-network-of-a-started-sandbox]

A `PATCH` with `network` on a started sandbox replaces the policy kumobad's egress proxy enforces for it without stopping it. The call answers once the new policy is in force: every connection the guest opens after that is checked against it alone, and its access log entries record the decision under it. A connection that was being checked while the policy changed is decided by one policy or the other, never by a mix of both, and if that was the old one and the new one denies it, it is refused or closed like any other.

Open connections that the new policy no longer allows are closed before the call answers, so an allowlist change takes away access that is already in use, not only new access. A connection one change refuses stays closed even if the next change, sent right after, would allow it again. The wait covers only connections this change or an earlier one closes, so other changes arriving meanwhile can't hold up its answer. kumobad saves the new policy with the sandbox's settings before it applies it: if it can't save them, the call fails and the old policy stays; if it stops after saving and before applying, it applies the saved policy when it starts again. A client that disconnects while waiting for the answer doesn't undo the change. Bytes forwarded before the change are not taken back. Open connections it still allows carry on. A change that took effect is recorded as a `network_changed` [event](#events) and in the summary's `networkChangedAtMs`; a call that was refused, or that failed and kept the old policy, records nothing. Two edge cases: if kumobad stops between applying a change and recording it, the summary has the new `networkChangedAtMs` with no event; and after a call that answered 500 because kumobad could not tell which settings were in force, its next start applies the saved policy and records a `network_changed` at that time, whose `previousMode` may name a policy that never took effect. Opening up can close connections too: `open` mode allows names on port 443 only, so moving from `allowlist` to `open` closes tunnels to IP addresses and to other ports. A closed connection's access log entry, written when it ends, has `"decision": "revoked"` and the bytes it moved; one that ends on its own keeps `allowed`. In `open` mode, a plain HTTP request still in progress is closed when the sandbox leaves `open`.

Every mode can be switched to every other while started, whatever mode the sandbox started with. `blocked` closes every open connection and refuses new ones at the egress proxy, before any DNS lookup. If installing the proxy's CA certificate in the guest failed when a sandbox started with `blocked`, as on an image without `/etc/ssl/certs/ca-certificates.crt`, turning its network on answers 422 `guest_error`, since such an image can't start with a network either; it stays `blocked`. kumobad 0.11 and 0.12 answer turning on the network of a sandbox started with `blocked` with 409 `conflict` until it is stopped and started again. A started sandbox with secrets can switch to `blocked` without `dropUnreachableSecrets` and keeps them, since nothing then leaves it, which makes `blocked` an emergency stop; this is the one change that may leave secrets unreachable. Such a sandbox can't be started again until its network is `open` or `allowlist` or its secrets are removed, and a start says so with 400 `invalid_request`, naming both ways out. A stopped sandbox with secrets can't switch to `blocked` without the flag (400, nothing changed). Any other new policy, on a started or a stopped sandbox, must still allow a destination of each attached secret, or the call answers 400 `invalid_request` and the old policy stays. Only secrets bound to at least one environment variable count; a secret with an empty `envVars` is never injected, so it never blocks a network change and `dropUnreachableSecrets` leaves it in place.

#### Narrow the network and drop secrets in one call [#narrow-the-network-and-drop-secrets-in-one-call]

To take a host away from a sandbox that has a secret for it, for example when an administrator removes the host, send `"dropUnreachableSecrets": true` with the new `network`:

```json
{"network": {"mode": "allowlist", "hosts": ["pypi.org"]}, "dropUnreachableSecrets": true}
```

kumobad removes each secret none of whose hosts the new policy allows, and applies the policy, as one change. The answer is the summary with `droppedSecrets`, the names it removed, empty when none were:

```json
{"id": "...", "network": {"mode": "allowlist", "hosts": ["pypi.org"]}, "state": "started", "droppedSecrets": ["gh"]}
```

- It is all or nothing. If the call fails, the policy, the secrets and their placeholders stay as they were. If it succeeds, the removed secrets are gone and the new policy is in force when it answers.
- No request carries a removed secret after the call answers. kumobad unbinds the secrets before it switches the policy, so in between the sandbox has the old policy with fewer secrets, never more. A request that took a removed secret's value before that goes to one of that secret's hosts, which the new policy refuses, so its connection is closed before the answer, even if another update opens that host again at once.
- `blocked` reaches nothing, so with `blocked` every secret is removed. That works on a stopped sandbox too, which otherwise can't switch to `blocked` while it has secrets.
- An event `{"type": "secrets_dropped", "secrets": ["gh"]}` records the names, never the values; see [Events](#events). A call that removed nothing records none. When the policy changed too, its `network_changed` event comes just before it.
- `dropUnreachableSecrets` without `network` is 400 `invalid_request`. Calls on the same sandbox, such as `PUT .../secrets` and `POST /v1/secrets/delete`, wait for each other, so a secret set while the update runs is checked against the new policy. A kumobad from 0.12 or earlier answers 400 `invalid_request` with `` unknown field `dropUnreachableSecrets` `` and changes nothing.
- `DELETE /v1/sandboxes/{id}` → `{"deleted": true}`. Stops the VM if needed and removes its disk.

### Prune stopped sandboxes [#prune-stopped-sandboxes]

`POST /v1/sandboxes/prune-stopped?olderThanMs=86400000` deletes every stopped sandbox, and its disk, that stopped at least `olderThanMs` milliseconds ago (one that never started counts from when it was created), oldest first, and answers

```json
{"dryRun": false, "sandboxes": [{"id": "...", "createdAtMs": 1764460800000, "stoppedAtMs": 1764464400000, "bytes": 10737418240}], "freedBytes": 10737418240}
```

listing what it deleted, with `bytes` as `stoppedSandboxBytes` counts them; on a filesystem with clones `bytes` and `freedBytes` are an upper bound, since blocks a sandbox shares with its image stay in use. It deletes your data, so it only runs when asked: `olderThanMs` is required (`0` takes every stopped sandbox), and `dryRun=true` lists what it would delete without deleting anything. It leaves running and booting sandboxes alone, those busy with another call, and a create with `start` or a `/v1/run` that has not answered yet. Each deleted sandbox gets a `deleted` event, as a `DELETE` does. kumobad can also prune by itself when a create is short of disk, with [`KUMOBAD_PRUNE_STOPPED_ON_DISK_PRESSURE_MS`](/configuration#daemon-kumobad). A prune whose client hangs up still finishes, so every sandbox it deleted is gone from the list too. It needs the token like every other call. `host` is for a [fleet](#fleet), where it picks the host to prune; a single kumobad takes its own `hostId` there and refuses any other with 400 `invalid_request`, so a call meant for one host never prunes another. `kumoba prune-stopped --older-than-ms 86400000 --dry-run` is the CLI form. A kumobad from 0.10 or earlier answers 404 `not_found`.

### Export and import [#export-and-import]

`GET /v1/sandboxes/{id}/export` streams a stopped sandbox as an archive (`application/vnd.kumoba.sandbox`, with `Content-Length`), and `POST /v1/sandboxes/import` with that archive as the body creates a stopped sandbox from it on this host or another, with a new id. The archive holds the sandbox's whole disk as the guest sees it, so a sandbox on a copy-on-write layer arrives as a disk of its own and the receiving host needs no matching image. It also holds the labels, the network policy, `autoStopMinutes`, `autoDeleteMinutes`, `cpu`, `memoryMib`, the image name and `createdAtMs`, `startedAtMs` and `stoppedAtMs`, so auto-delete and pruning keep their clocks. Secrets and host mounts stay behind, as for a restart: set the secrets again on the new host. Holes in the disk are left out, so the archive is about the size of what the disk holds. Because the disk arrives whole, the new sandbox takes that much space on its host even where the old one shared most of it with its image. Import answers the new sandbox's summary, and records a `created` event.

- Export answers 409 `conflict` while the sandbox is running or booting: stop it first, and 400 for a macOS sandbox, which can't be exported yet. The sandbox is busy while the export streams, so a start or delete answers 409 until it ends. A sandbox whose VM was killed exports what its disk held when it stopped, as after a power cut. A host that is down can't export anything, so move sandboxes off a host before you retire it.
- The export carries the sandbox's stop time in the `kumoba-stopped-at-ms` header (0 for one never started). `DELETE /v1/sandboxes/{id}?ifStoppedAtMs=N` deletes the sandbox only if it is still stopped with that stop time, and otherwise answers 409 and keeps it, so a move never deletes a sandbox that ran again after its export.
- Import reads the whole archive before it publishes the sandbox, and checks it on the way: it refuses with 400 `invalid_request` an archive that is not one, comes from another guest protocol or CPU architecture, has a disk larger than any image on the host or not a whole number of 512-byte sectors, or whose records, sizes, settings or checksum do not add up, and leaves nothing behind. It counts the data the archive declares against `KUMOBAD_MIN_FREE_DISK_MIB` before it writes anything (507 `disk_full`), answers 422 `exceeds_host_memory` for a sandbox larger than the host's memory budget, and 409 `draining` on a draining host, like a create. A refused import answers before the whole archive is sent and then closes the connection. The summary shows when the sandbox arrived as `importedAtMs`. `?movedFrom=KEY` stores a key the summary shows as `movedFrom`; a fleet move uses it to find a copy whose reply was lost.
- The CLI forms are `kumoba export ID -o sandbox.kumoba` and `kumoba import content=@sandbox.kumoba`; both stream instead of holding the archive in memory. A kumobad from 0.10 or earlier answers 404 `not_found`.

### Start and stop [#start-and-stop]

- `POST /v1/sandboxes/{id}/start` → summary with `"state": "started"`. Boots the VM and waits for the guest agent. With no running slot free it answers 429 `capacity` at once. While it boots, listing and getting the sandbox answer at once with `"state": "stopped"`; it reads `started` once the boot completes. Stopping or deleting it, or running a command in it, waits for the boot to finish first.
- `POST /v1/sandboxes/{id}/stop` → summary with `"state": "stopped"`. The disk is kept.
- `POST /v1/sandboxes/{id}/stop?ifIdleForMs=600000` stops the sandbox only if it is still idle when the stop takes it: no open operation and no activity for at least `ifIdleForMs` milliseconds, the test `GET /v1/sandboxes?idle=true` and auto-stop use. Otherwise it answers 409 `not_idle` and leaves the sandbox running. A command, shell, file transfer, preview or live view counts from the moment it takes the sandbox, so a stop taken after it never cuts it off, even with `ifIdleForMs=0`; one that asks for the sandbox after the stop waits for it and finds the sandbox stopped. Use it to free a slot without the race between an idle listing and a plain stop. A sandbox that is already stopped answers 200 as with a plain stop. A kumobad from 0.10 or earlier answers 400 `invalid_request` for the parameter.

Every exec, file or preview call counts as activity for auto-stop.

## Running commands [#running-commands]

`POST /v1/sandboxes/{id}/exec`

```json
{
  "argv": ["/bin/sh", "-c", "echo hello"],
  "cwd": "/workspace",
  "env": {"A": "1"},
  "timeoutMs": 600000,
  "user": "kumoba"
}
```

A bare `argv[0]` such as `python3` is looked up on the guest's `PATH` through `/usr/bin/env`; an absolute path runs as is. `user` defaults to root; `cwd` defaults to the user's home. The response is `application/x-ndjson`, one event per line, streamed as the process runs:

```
{"type":"stdout","data":"aGVsbG8K"}
{"type":"stderr","data":"..."}
{"type":"exit","exitCode":0,"timedOut":false}
```

`data` is base64. The final event is either `exit` (`exitCode` is `null` and `timedOut` is `true` when the timeout hit; `signal` is set when a signal ended the process) or `{"type":"error","error":"<code>","message":"..."}` when the command could not be started or did not finish, with `error` one of the codes above, such as `guest_error`, and `reason` when it has one, such as `not_started` for a sandbox stopped during the command or `outcome_unknown` (a kumobad from 0.14 or earlier sends neither `error` nor `reason`). Closing the connection kills the process group inside the guest.

### One-shot [#one-shot]

`POST /v1/run` takes the exec fields plus the create fields (`image`, default `"default"`, `cpu`, `memoryMib`, `labels`, `network`, `waitMs`, `placement`). Like a create with `start`, it holds a running slot before it copies the disk, so at the limit it answers 429 `capacity` at once. It creates a sandbox, starts it, streams the command's events exactly like exec, and deletes the sandbox when the command ends or the client disconnects, including a disconnect while the sandbox is still booting. The stream starts with `{"type":"sandbox","id":"..."}`. The sandbox's summary carries `"ephemeral": true` while it exists, and if kumobad stops during a run it deletes that sandbox when it starts again.

## Shell [#shell]

`POST /v1/sandboxes/{id}/shell` opens an interactive terminal. Send it with `connection: upgrade` and `upgrade: kumoba-shell.v1`, and a JSON body:

```json
{"argv": [], "cwd": "/workspace", "env": {}, "user": "kumoba", "rows": 40, "cols": 120}
```

An empty `argv` starts the user's login shell. kumobad answers `101 Switching Protocols`; from then on both sides exchange frames of one type byte, a 4-byte big-endian length and a payload:

| Type | Direction | Payload |
| --- | --- | --- |
| 1 data | both | Terminal bytes |
| 2 resize | client to kumobad | Rows and columns, 2 bytes each, big-endian |
| 3 eof | client to kumobad | None; ends input as Ctrl-D does |
| 4 exit | kumobad to client | The shell's exit status, 4-byte signed big-endian; 128 + the signal for a signal |

Closing the connection ends the shell. A request without the upgrade gets `426 upgrade_required`, and a sandbox whose image predates kumoba 0.3 gets `422`.

## Files [#files]

- `PUT /v1/sandboxes/{id}/files?path=/abs/path[&user=name]` with the raw bytes as the body → `{"written": <bytes>}`. Missing parent directories are created first, as `user`, or as root when `user` is left out. A file operation as `user` has the permissions of a command run as `user`, supplementary groups included, so a directory that `user` can write to only through a group it belongs to in the guest's group database accepts the write. In sandboxes from images built by an older kumoba release, file operations use only the primary group of `user`. A new directory belongs to the uid of `user`. Its group is the primary group of `user`, except on macOS and under a setgid parent on Linux, where it takes the group of the directory it is created in. Its mode follows the guest umask: `0755` with the default umask `022`. Symbolic links among the parents are followed, but the target itself must not be a symbolic link. A write that fails can leave the empty parent directories it created behind. The file is created `0644` as `user`.

  The bytes go to a hidden file next to the target, which takes the target's place only after the last byte is on disk. Programs in the sandbox see the old file or the new one, never part of the upload, and an upload that fails or is cut off leaves the old file as it was. Until then only its owner can read the hidden file. A replaced file keeps its mode and owner, but not its ACLs or extended attributes. Four cases are written in place instead, as before: a file with more than one hard link, a file in a directory `user` cannot write to, a file in a directory `user` cannot list, and a file whose owner `user` cannot keep. Images built by an older kumoba release also write in place. If the sandbox is force stopped or crashes during an upload, a `.kumoba-upload-*` file can be left next to the target; delete it by hand. If the new file is in place but the guest cannot sync its directory, the upload still succeeds and the guest logs the error.

  An upload whose body sends nothing for 60 seconds is answered `408`. Each sandbox runs at most 8 uploads at a time; more wait until one finishes, so uploads never take the guest connections that commands, previews and the desktop need.
- `GET /v1/sandboxes/{id}/files?path=/abs/path[&user=name]` → the raw bytes, `application/octet-stream`. `Content-Length` and `x-file-size` carry the file's size. If reading the file fails partway, for example because the sandbox stops, kumobad closes the connection before that many bytes, so the client sees a failed transfer instead of a short file. Daemons before this release ended the body cleanly instead; compare the bytes received with `x-file-size` to catch that.
- `GET /v1/sandboxes/{id}/files/list?path=/abs/dir[&user=name]` → `{"entries": [{"name": "a.txt", "kind": "file", "size": 5}, ...]}`. `kind` is `file`, `directory` or `other`.

Reads and lists run with the user's permissions when `user` is given, supplementary groups included.

## Secrets [#secrets]

`PUT /v1/sandboxes/{id}/secrets`

```json
{
  "secrets": [
    {"name": "gh", "value": "ghp_...", "hosts": ["api.github.com"], "envVars": ["GITHUB_TOKEN"]}
  ]
}
```

Replaces the sandbox's secret set. Returns `{"mountedEnvVars": ["GITHUB_TOKEN"]}`. Names and environment variables must each appear once in the set; a variable listed for two secrets is 400 `invalid_request` naming it. Inside the guest each listed variable holds a placeholder; HTTPS requests to a listed host have the placeholder swapped for the value in request headers, and responses from those hosts are scrubbed of the value. Values must be at least 8 bytes. Sending an empty list detaches everything.

`POST /v1/secrets/delete` with `{"names": ["gh"]}` removes secrets by name from every sandbox → `{"deletedNames": ["gh"]}`.

## Port previews [#port-previews]

`POST /v1/sandboxes/{id}/preview` with `{"port": 8080, "ttlSeconds": 600}` → `{"url": "http://127.0.0.1:7789/v1/preview/<token>/", "path": "/v1/preview/<token>/", "expiresAtMs": ...}`. `url` is set when the daemon has a preview listener (`KUMOBAD_PREVIEW_LISTEN`, or `KUMOBAD_PREVIEW_URL` behind a proxy), and is `null` otherwise.

Previews on the preview listener render in a browser: the guest's `content-type`, `content-encoding` and `location` pass through. That listener is a separate origin from the API and answers nothing but previews, so a page from a sandbox cannot reach the API. The same preview path on the API listener is download-only: `content-disposition: attachment`, `content-security-policy: sandbox` and `application/octet-stream`.

## Desktop [#desktop]

`POST /v1/sandboxes/{id}/desktop` with `{"user": "kumoba", "ttlSeconds": 3600, "viewer": "stream"}` (all optional) starts Xvfb, xfce and the live views in an image that has them, and → `{"url": "http://127.0.0.1:7789/v1/preview/<token>/", "path": "...", "expiresAtMs": ..., "processes": {"xvfb": true, ...}, "viewer": "stream"}`. Opening `url` shows the desktop live, with keyboard and mouse. `viewer` chooses the page: `stream`, the default, is kumoba's own viewer, and `vnc` is noVNC, whose link ends in `vnc.html?autoconnect=1&resize=remote&path=...`. An image without the stream viewer gets `vnc` either way, and the response says which one the link opens. For a Linux sandbox kumobad then waits up to 20 s for the desktop to draw its first screen, so a screenshot taken next shows it, and adds `"painted": true`; when the screen is still one colour after 20 s it answers anyway, with `"painted": false` and a `warning`. An image without a desktop answers 422. For a macOS sandbox nothing is started in the guest: the link opens the stream viewer on the screen as it is read on the host, `user` and `viewer` are ignored, and `processes` is `{"view": true}`.

With the stream viewer the response also has `watchUrl` and `watchPath`, a link with the same lifetime that only watches: the page shows the desktop, and the engine ignores its keyboard, mouse and clipboard, whatever the page sends. The access is signed into the token, so a watch link can't be edited into a full one, and kumobad opens the stream with a watch token it keeps to itself. In a Linux sandbox `processes.watch` says whether the image's desktop helper started the engine with that token; when it didn't, as with images from 0.7.1 and earlier, or when the link opens `vnc`, the response leaves `watchUrl` and `watchPath` out rather than return a link that controls the desktop. kumobad passes a watch link's stream on only when the engine's WebSocket answer says it granted watching, so one whose engine has since been started without the token is answered `409` instead. A watch link opens only the viewer's page, its scripts and the stream, with `GET`, and kumobad passes on only answers in which the engine says it granted watching, so another app on the port gets nothing from it either. Port 6090 of a Linux sandbox is the live view's: a preview of it from `POST /v1/sandboxes/{id}/preview` reaches the engine with its control token, like the desktop link.

Requests to `GET|POST|... /v1/preview/<token>/<anything>` are relayed to that port inside the guest, including WebSocket upgrades, without a bearer token. A request body is read in full before kumobad opens a connection to the app, and reaches the guest with its `content-length`, also when the client sent it chunked; a body over 10 MiB is refused with 413 and the app never sees the request. The response streams back as the guest sends it, with no size limit, so large files, Server-Sent Events and long polls work. The guest has 30 s to send the response headers (504 otherwise), and a response that stays silent for 120 s, or ends before its declared `content-length`, is cut off with a connection error instead of being passed on as complete. A WebSocket or other upgraded connection is closed after 1 hour with no data in either direction, or 30 s after one side closes its end if nothing more arrives in that time. The token is an HMAC over the sandbox id, port, expiry, whether it opens the live view, whether that view is read on the host for a macOS sandbox and whether it only watches, so it cannot be reused for another sandbox, for another target or after it expires. Hop-by-hop and host-identifying headers are stripped in both directions, and responses carry `content-disposition: attachment` for types a browser would otherwise render, so a page served from a sandbox cannot script against the daemon's origin.

### Screenshots and input [#screenshots-and-input]

These routes see and drive the desktop of a started Linux sandbox whose desktop is running, through the image's desktop helper, the same one the [TypeScript SDK](/typescript) uses. They don't start the desktop: before `POST /v1/sandboxes/{id}/desktop` they answer 409 `conflict` with `reason` `desktop_not_started`. An image without a desktop, such as `test`, and a macOS sandbox answer 422 `guest_error` with `reason` `no_desktop`. Every route takes an optional `user`, the guest user to act as; without it, kumobad acts as the user who started the desktop, so the screen, input and accessibility tree all belong to that user's session. Points are pixels from the top left corner of the screen.

| Route | Body or query | Reply |
| --- | --- | --- |
| `GET /v1/sandboxes/{id}/desktop/screenshot` | `?settle=true` waits up to 3 s until two captures 300 ms apart match and are not all one colour | The screen as a PNG, `content-type: image/png` |
| `POST /v1/sandboxes/{id}/desktop/click` | `{"x": 300, "y": 200, "button": "left", "double": false}`; `button` is `left`, `middle` or `right` | The click it made, as `{"x", "y", "button", "double"}` |
| `POST /v1/sandboxes/{id}/desktop/hover` | `{"x": 300, "y": 200}` | `{"x", "y"}` |
| `POST /v1/sandboxes/{id}/desktop/drag` | `{"fromX": 10, "fromY": 20, "toX": 300, "toY": 200, "button": "left"}` | The drag it made |
| `POST /v1/sandboxes/{id}/desktop/scroll` | `{"x": 500, "y": 400, "direction": "down", "amount": 3}`; `amount` is 1 to 50 wheel steps, 3 by default | The scroll it made |
| `POST /v1/sandboxes/{id}/desktop/type` | `{"text": "hello\n"}`, up to 10,000 characters typed at the focused field; a newline presses Return | `{"typed": 6}`, the number of characters |
| `POST /v1/sandboxes/{id}/desktop/key` | `{"key": "ctrl+l"}`: one key, such as `Return`, `Tab`, `Escape` or `F5`, or keys joined with `+`. Common names such as `Enter`, `ArrowLeft` and `PageUp` work in any case, and a letter after a modifier is the same key in either case | `{"key": "ctrl+l"}` |
| `GET /v1/sandboxes/{id}/desktop/ui-tree` | `?limit=200&maxDepth=30`: up to `limit` elements (1 to 2000), from an accessibility tree walked `maxDepth` levels deep (1 to 64) | `{"elements": [...], "truncated": false}` |

`ui-tree` reads the desktop's accessibility tree and keeps the elements a person could see and act on: those with a name and a box on the screen. Each element is `{"role": "push button", "name": "Send", "center": {"x": 812, "y": 440}, "bounds": {"x": 780, "y": 428, "width": 64, "height": 24}, "depth": 2}`, in the order of the tree, with `depth` counting the listed elements that hold it. `center` is the point to click. A name has its whitespace collapsed and is cut at 120 characters. `truncated` is `true` when there were more than `limit` elements, or the tree went deeper than `maxDepth`.

`settle` helps a client that acts and then looks: it returns once the screen holds still, or after 3 s with the last capture. A screen of one colour, such as a desktop still starting, never counts as still. A screen that keeps changing, such as a playing video, may never match, and then it takes the full 3 s. A failing action answers 422 `guest_error` with the helper's error, and 504 `gateway_timeout` if it runs out of time.

## Access log [#access-log]

`GET /v1/access-log?sinceMs=<epoch ms>&untilMs=<epoch ms>&limit=<n>[&cursor=<token>]` → `{"entries": [...], "truncated": false, "nextCursor": null}`

Every connection the egress proxy handled, in the order it was recorded (close to completion time), for sandboxes of any state:

```json
{
  "sandboxId": "6a0b...",
  "labels": {"project": "demo"},
  "host": "api.github.com",
  "port": 443,
  "decision": "allowed",
  "bytesIn": 18233,
  "bytesOut": 912,
  "startedAtMs": 1760000000000,
  "completedAtMs": 1760000000412
}
```

`host` is the name the guest asked for, or the address for a connection to an IP address (`10.20.1.5`, `2001:db8::7` without brackets, an IPv4-mapped address shown as IPv4). `decision` is `denied` for allowlist misses and for attempts at private, link-local or metadata addresses (a `blocked` sandbox's refused attempts are not recorded), and `failed` when the destination was allowed but could not be reached: its DNS lookup failed or got no answer within 5 seconds, the connection failed, or the upstream proxy failed. Both carry zero bytes. `revoked` is a connection that was allowed and then closed because the sandbox's network changed while it was open; it carries the bytes it moved. A sandbox gets at most 10000 records per hour; beyond that, and whenever the daemon cannot keep up, the gap is reported as a `dropped` marker (`"decision": "dropped"`, empty host, port 0, `"dropped": <count>`) rather than lost silently. `bytesIn` is what reached the guest, `bytesOut` what it sent. Defaults: the last two hours, 10000 entries; `limit` caps at 50000. When `truncated` is true, repeat the call with `cursor=<nextCursor>` and the same window to get the next page; the cursor is a position in the log, so pages never skip or repeat entries. The cap is 10000 records per decision (`allowed`, `denied`, `failed`, `revoked`) per sandbox per hour, so a flood of permitted traffic cannot push denials out of the log. kumobad keeps 72 hours of entries as hourly files under `<state>/access`.

## Events [#events]

`GET /v1/events[?cursor=<token>][&limit=<n>]` → `{"events": [...], "truncated": false, "nextCursor": "9f3c2a1b7d4e6f80:1760000000000:12", "reset": false, "gap": false}`

Every sandbox being created, started, stopped or deleted, every change of a sandbox's network policy (`"type": "network_changed"`), and every update that removed secrets with `dropUnreachableSecrets` (`"type": "secrets_dropped"` with their names in `secrets`), in the order kumobad recorded it:

```json
{
  "type": "stopped",
  "sandboxId": "6a0b...",
  "labels": {"project": "demo"},
  "atMs": 1760000000412,
  "reason": "auto_stop"
}
```

- `started` is when the boot finished. `stopped` carries a `reason`: `api` (a stop call, or a delete of a running sandbox), `auto_stop`, `guest_exit` (the guest shut down cleanly and its VM process exited with status 0), `crash` (the VM process ended any other way, with another exit status or a signal, for example when it was killed on the host) or `shutdown` (kumobad stopped it while shutting down on SIGTERM or Ctrl-C). A stop call keeps its `api` reason, and finishes, when the client disconnects or gives up first. A sandbox that was running when kumobad itself died gets `crash` at kumobad's next start, stamped with the latest sign that it was still running: its start, the last time its VM process wrote to its `worker.log` (on Linux it writes there when it outlives kumobad), or kumobad's own heartbeat, a file under `<state>` it touches every 30 seconds. So a power loss is placed within 30 seconds of the moment it happened.
- `deleted` carries `"reason": "disk_pressure"` when kumobad deleted the sandbox itself to make room for a create (`KUMOBAD_PRUNE_STOPPED_ON_DISK_PRESSURE_MS`), and no `reason` for a delete, a prune or `autoDeleteMinutes`.
- `network_changed` carries `previousMode` and `mode`, the sandbox's `network.mode` before and after, which can be the same, as for an allowlist that lost a host, and `revoked`, true when the change closed at least one established connection the new policy no longer allows, each of which then has a `revoked` [access log](#access-log) entry; a connection still being set up at that moment may be refused or closed without making it true, and a stopped sandbox has none, so it is always false there. Its `atMs` is the summary's `networkChangedAtMs`: the moment just before the new policy took effect, so a connection the change closed ends at or after it. A `PATCH` whose policy is the same as the current one records none. When kumobad starts and applies a saved policy the sandbox never took, it records one then, with `revoked` false; see [Change the network of a started sandbox](#change-the-network-of-a-started-sandbox) for when that happens. A kumobad from 0.12 or earlier records none, and skips these lines if it is started on a newer state directory.
- `atMs` is when it happened. For a stop it is when the VM process exited, taken the moment kumobad sees the exit rather than at its next check. `labels` are the sandbox's labels at that time.
- The feed is in recorded order, not `atMs` order: a stop is stamped with the moment the VM exited and can be recorded just after a later event, and a clock change on the host moves `atMs` but never the order. Order by the feed, and use `atMs` for durations.
- Without `cursor` the feed starts at the oldest kept event. Pass `nextCursor` back as `cursor` to read on. It is a position in this host's feed, so pages never skip or repeat events, and it stays valid across kumobad restarts. A page with no new events returns the cursor you sent, so a client can keep polling with it; `nextCursor` is `null` only when a page is empty and there is no cursor to return, as before the first event. `truncated` is true when more events are waiting. `limit` defaults to 1000 and caps at 10000. A `cursor` kumobad cannot read is 400 `invalid_request`.
- Each cursor names the event log it came from. A cursor from another host, or from before the state directory was recreated, is not read as a position: the page starts at the oldest kept event and says `"reset": true`. When events after the cursor were deleted by the retention, the page reads on from the oldest kept event and says `"gap": true` once; its `nextCursor` moves past what was deleted, so the next page does not repeat it. A reader that was caught up when its events aged out gets no gap.
- kumobad keeps 72 hours of events, those of deleted sandboxes included, as hourly files under `<state>/events`, and syncs each event to disk as it writes it. If an event cannot be written, the call that caused it still succeeds, and a `dropped` marker for that sandbox (`"type": "dropped"`, `"dropped": <count>`) takes its place once writing works again. When kumobad starts, a sandbox's saved start and stop times are checked against its last event, so a run whose saved state was not updated is neither left open nor closed twice.
- Once kumobad begins shutting down it answers create and start with 503 `unavailable`, so no sandbox starts after the final `stopped` events. A VM that exits after that, for example because the service manager signalled it too, is recorded as `shutdown`; a stop call already in progress keeps `api`. kumobad waits at most 60 seconds for its sandboxes to stop and then records the rest as stopped at that moment.

## Pairing [#pairing]

`POST /v1/pair` with `{"pairingToken": "...", "csr": "-----BEGIN CERTIFICATE REQUEST-----...", "name": "fleet-a"}` (`name` optional, default `kumobad-fleet`, 1 to 64 letters, digits, `-`, `_` or `.`) → `{"certificate", "caCertificate", "token", "hostId", "name", "notAfterMs"}`. It needs no bearer token: the one-time token from a pairing code authorizes it, and it is the only request a TLS connection without a client certificate may make. It works only on a host set up with `kumobad host init` (404 `not_found` otherwise). A token that is wrong, used or expired is 403 `forbidden`; a CSR that does not parse or whose signature fails is 400 and leaves the token unused; after 5 refused tokens within a minute from one address (one /64 for IPv6), further wrong tokens from it answer 429 `rate_limited` with `Retry-After`, while a valid token always pairs; while the client CA on disk differs from the one kumobad has loaded (after `kumobad host init --force` and before `SIGHUP`) it answers 503 `unavailable` and leaves the token unused. kumobad closes the connection after every reply. See [Set up a host for a fleet](/guide/remote-daemon#set-up-a-host-for-a-fleet).

## Health [#health]

`GET /healthz` → `{"ok": true}`, no authentication, on every listener. kumobad closes the connection after this reply, after a 401, after a preview link it refuses (403) and after the preview listener's 404, so a client without a token or a valid link cannot hold a connection open.

## Metrics [#metrics]

`GET /metrics` → the host's metrics in the Prometheus text format (`text/plain; version=0.0.4`). It needs the bearer token like every other call, so it is served on the same listeners with the same rules: loopback TCP and the Unix socket by default, and TLS on any other address. Point Prometheus at the API listener with the token in a file:

```yaml
scrape_configs:
  - job_name: kumobad
    authorization:
      credentials_file: /etc/prometheus/kumobad.token
    static_configs:
      - targets: ["127.0.0.1:7788"]
```

With TLS, add `scheme: https` and a `tls_config` with `ca_file`, and with client certificates `cert_file` and `key_file` too.

| Metric | Type | Meaning |
| --- | --- | --- |
| `kumobad_info{version, host_id}` | gauge | Always 1 |
| `kumobad_running`, `kumobad_max_running` | gauge | Running slots in use and the limit, as in `/v1/capacity` (macOS adds `kumobad_macos_running` and `kumobad_macos_max_running`) |
| `kumobad_sandboxes{state}` | gauge | Sandboxes by `state`: `running` or `stopped` |
| `kumobad_active_operations`, `kumobad_open_previews` | gauge | The sums of every sandbox's `activeOperations` and `openPreviews` |
| `kumobad_draining`, `kumobad_drain_strict` | gauge | 1 while the host drains, and while that drain is strict |
| `kumobad_disk_free_bytes`, `kumobad_disk_total_bytes` | gauge | Free and total bytes of the filesystem that holds `KUMOBAD_STATE_DIR`; absent when it cannot be read |
| `kumobad_sandboxes_created_total`, `kumobad_sandboxes_started_total`, `kumobad_sandboxes_deleted_total` | counter | The `created`, `started` and `deleted` events of the event feed |
| `kumobad_sandboxes_stopped_total{reason}` | counter | `stopped` events by `reason`: `api`, `auto_stop`, `guest_exit`, `crash` or `shutdown`. Crashes are `reason="crash"` |
| `kumobad_capacity_refusals_total` | counter | Requests answered 429 `capacity` |
| `kumobad_boot_failures_total` | counter | Starts that failed while booting the guest, such as a boot timeout. A start refused before it booted (429, a pending disk operation) is not counted |
| `kumobad_boot_cancellations_total` | counter | Boots abandoned because the request that began them ended first, such as a client that hung up |
| `kumobad_boot_seconds` | histogram | From the start of a boot to a running guest, for starts that succeeded |
| `kumobad_disk_copy_seconds` | histogram | Preparing a new sandbox's disk from its image, for every create. A create with `start` takes this plus a boot |

Counters start at 0 when kumobad starts. No metric carries a sandbox id or a sandbox's labels.

## Fleet [#fleet]

`kumobad fleet` ([Run a fleet of hosts](/guide/fleet)) answers this API for many hosts, with these differences:

- **Ids.** Sandbox ids are `<hostId>.<sandboxId>`, in every reply that carries one: summaries, lists, the `sandbox` event of `/v1/run` and `sandboxId` in the access log. Every call on an id goes to that host. An id without a known host answers 404 `not_found`; a host that does not answer, failed its last health checks or is refused answers 503 `host_unavailable`. A call that is waiting for a host's answer ends with 503 `host_unavailable` as soon as the host fails its health checks, so a host that hangs does not hold calls forever. Once the fleet has connected to the host (after the TLS handshake), a call other than a `GET` may have reached it, so a 503 from then on, whether the answer broke off, never came or the host failed its health checks meanwhile, has the reason `outcome_unknown`; a 2xx answer to such a call that is not JSON is that 503 too, where a `GET` gets 502 `bad_gateway`. A 503 for a call that never got that far has no reason and is safe to repeat. A create, a `run` or an import the host may have taken, including one it answered with something that is not JSON, answers 503 `host_unavailable` with `"mayExist": true` and `may_exist`, since repeating it makes a second sandbox. JSON answers the fleet rewrites (summaries, links) must also arrive within 30 s; once a streamed answer has started, such as an `exec` stream, a shell or a preview, it runs for as long as the host sends it.
- **Placement.** `POST /v1/sandboxes` and `POST /v1/run` take an optional `"placement": {"key": "value"}`. With `start`, and for `/v1/run`, the fleet picks among hosts that are healthy, not draining, on an accepted version, serve the image and carry every placement label, the one with the most free slots, trying hosts that report free disk above their `minFreeBytes` before those that do not; on a host's 429, 422 `exceeds_host_memory`, 507 `disk_full`, `draining` or 503, or when the fleet could not connect to it, it tries the next one; when every host it tried was short of disk it answers 507 `disk_full` at once, even with `waitMs`, with those hosts' ids in `diskFullHosts` so a client can prune them, and when some were short of disk and others did not answer, 503 `host_unavailable`. It skips hosts whose `memoryMibBudget` is smaller than the sandbox's `memoryMib` and ranks hosts that report a budget by the smaller of their free slots and how many such sandboxes their free memory holds; when no host's budget can ever hold the sandbox it answers 422 `exceeds_host_memory` at once. When a host received the request but no complete answer came, the fleet does not try another host, since the sandbox may exist there: it answers 503 `host_unavailable` naming the host with `"mayExist": true`, so look for the sandbox on that host (by its labels) before creating again. A 503 without `mayExist` never reached a host. When all are full it answers 429 `capacity` with `Retry-After: 5`, or keeps trying until `waitMs` has passed. A create without `start` goes to the host with the most free slots. When no host serves the image it answers 400 `invalid_request` (503 `host_unavailable` when only unavailable hosts serve it), when none carries the labels 409 `conflict` with `reason` `no_matching_host`, when all that could are draining 409 `draining`, and when no host is available 503 `host_unavailable`.
- **Previews.** Preview paths are `/v1/preview/<hostId>/<token>/...` on the fleet's own listeners. The fleet forwards them to the host's preview URL, WebSocket upgrades included, without the fleet's token, and rewrites the host's redirects to keep the host in the path. `expose` and `desktop` return `path`, `url`, `watchPath` and `watchUrl` in that shape, with `url` under the fleet's preview URL; for the noVNC viewer the `path` parameter of its link, which names the WebSocket it opens, carries the host too. On the fleet's API listener, as on kumobad's, a preview answer is a download (`application/octet-stream`, `content-security-policy: sandbox`, `content-disposition: attachment`) that never runs in the API's origin; only the preview listener serves it as a page.
- **`GET /v1/capacity`** sums `running` and `maxRunning` (and the macOS pair and `memoryMibInUse`) over healthy hosts, and `memoryMibBudget` when every one of them reports it; it has no top-level `disk`, since each host has its own, so read each host's `disk` under `hosts`. It sets `draining` when no healthy host is active, and lists every host under `hosts` with its `hostId`, `state` and its own capacity fields.
- **`GET /v1/sandboxes`** asks every host with the same filters and merges the answers newest first, cut to `limit`. `truncated` is also true when a host did not answer; those hosts are listed in `unavailableHosts`.
- **`GET /v1/access-log`** merges every host's page. `nextCursor` holds a position per host, so pages never skip or repeat entries, and each host contributes up to `limit` entries per page. Entries come host by host, in each host's recorded order, not sorted by time across hosts. Hosts that did not answer are listed in `unavailableHosts` and keep their position in `nextCursor`: `truncated` says whether the hosts that answered have more, and `nextCursor` stays set while a host is still owed its pages, so calling again with it later picks them up. A host removed from the fleet is dropped from the cursor and named once in `removedHosts`. The CLI prints the cursor to resume with when hosts did not answer.
- **`GET /v1/events`** merges every host's feed. `nextCursor` holds each host's position, so pages never skip or repeat events and a client keeps polling with it as with one kumobad; a host added later starts from its oldest kept event. Events come host by host, each host's in its recorded order; the fleet does not sort them by `atMs` across hosts. `reset` and `gap` are true when they are for any host, and `resetHosts` and `gapHosts` name those hosts. A host that did not answer is listed in `unavailableHosts` and keeps its position, so its events arrive once it answers again; a host removed from the fleet is dropped from the cursor and named once in `removedHosts`.
- **`POST /v1/secrets/delete`** goes to every host. When one did not answer it answers 503 `host_unavailable` with `deletedNames`, `deletedOnHosts` and `failedHosts` (each with `hostId` and `message`); repeat the call to delete the rest.
- **`POST /v1/sandboxes/prune-stopped`** runs each host's own prune, so a host keeps every safety it has alone: running, booting and busy sandboxes stay, only those stopped for at least `olderThanMs` go, and `dryRun=true` deletes nothing. The fleet checks `olderThanMs` and `dryRun` before it asks any host. With `host=HOST_ID` it prunes that host only: an id the fleet does not know answers 400 `invalid_request`, a host that failed its last health checks or is refused 503 `host_unavailable`, and an error the host gives, such as 404 from a kumobad of 0.10 or earlier, comes back as the host sent it. Without `host` it prunes every host at once. Either way a reply that pruned looks like one host's, with ids as `<hostId>.<sandboxId>`, `sandboxes` oldest first across hosts and `freedBytes` summed, plus `hosts`, one `{"hostId", "freedBytes"}` per host that pruned, and `failedHosts`, one entry per host that did not, with `hostId`, `message`, the host's `status` when it answered with an error, and `"mayHavePruned": true` when the request reached the host but no complete answer came, so some of its sandboxes may be gone (never on a dry run); the `message` then says so too. A host whose answer has a different `dryRun` than the call asked counts as failed. Without `host` the fleet waits at most 30 s for each host, so one slow host does not hold every other host's report; prune a host that ran out of time alone. With `host` it waits for as long as the host passes its health checks, like a call on one sandbox, and an answer that is lost answers 503 `host_unavailable` with `mayHavePruned` and a `message` that points at the host's `deleted` events. Without `host` it answers 200 when at least one host pruned, so the list of what was deleted always reaches the client, and 503 `host_unavailable` with the same fields when none did, whose `message` says when some hosts may have pruned. Pruning again is safe: it deletes only what is stopped and old enough at that moment, and every deletion is a `deleted` event in `GET /v1/events`.
- **Merged reads** (`/v1/capacity`, `/v1/sandboxes`, `/v1/access-log`, `/v1/events`, `/v1/secrets/delete`) wait at most 30 s for each host, and treat a host that has not answered by then as unavailable.
- **`GET /v1/images`** lists every image a healthy host serves.
- **`GET /metrics`** reads every active or draining host's `/metrics` (5 s per host) and serves those series with a `host` label, the host's id, beside the fleet's own:
  - `kumobad_fleet_host_state{host, state}`: 1 for the host's current state (`active`, `draining`, `unhealthy` or `refused`) and 0 for the others.
  - `kumobad_fleet_host_running`, `kumobad_fleet_host_max_running` and `kumobad_fleet_host_draining`: each active or draining host's capacity and drain as of its last health check, so they are there for hosts that serve no `/metrics` too.
  - `kumobad_fleet_host_metrics_up{host}`: 1 when the fleet read that host's `/metrics` for this scrape. A host on 0.10.0 has none, and an unhealthy or refused one is not asked. The fleet checks each host's answer before using it and leaves out the whole answer, with 0 here, when it is not `text/plain`, is larger than 4 MiB, does not parse as the Prometheus text format, or names a `kumobad_fleet_` family. A `host` label a host sends itself becomes `exported_host`. When hosts disagree on a family's type, the first host's type wins and the others' samples of that family are left out.
  - `kumobad_fleet_capacity_refusals_total`: creates and runs the fleet answered 429 `capacity` because no host could take them. A 429 a host gives on a call the fleet forwards, such as a start, counts only in that host's `kumobad_capacity_refusals_total`, which also counts the 429s it gave the fleet before the fleet placed the sandbox on another host.
  - `kumobad_fleet_info{version}`: always 1.
- **`GET /v1/info`, `POST /v1/drain` and `DELETE /v1/drain`** answer 400 `invalid_request`. Read the hosts with `GET /v1/fleet/hosts` instead, and drain one with `kumobad fleet drain`.
- **`GET /v1/fleet/hosts`** (fleet only) → `{"hosts": [...]}`, one entry per host:

```json
{
  "hostId": "d371e8385e751d26",
  "url": "https://host-a.example.com:7788",
  "previewUrl": "https://host-a.example.com:7789",
  "labels": {"zone": "a", "rack": "r1"},
  "state": "active",
  "version": "0.10.0",
  "guestProtocolVersion": 3,
  "hypervisorAvailable": true,
  "images": ["default"],
  "draining": false,
  "drainStrict": false,
  "capacity": {"running": 1, "maxRunning": 4},
  "lastError": null
}
```

`state` is `active`, `draining`, `unhealthy` (its last health checks failed) or `refused` (a version the fleet does not take, a different `hostId` than when it was added, or credentials it cannot read). `labels` are the host's own merged with the fleet's, the fleet's winning.