# Protocol

https://virtx.sh/docs/reference/protocol/

What a virtx client and server say to each other: the endpoints, the transports, authentication, jobs, images and files.

The virtx protocol is for running virtual machines, either locally or remotely.

A server offers several endpoints, and each speaks its own protocol:

| Endpoint | Protocol | For |
| --- | --- | --- |
| [`/images/oci/v2/`](#images) | OCI Distribution | Images: manifests, blobs and tags |
| [`/images/jobs/`](#image-jobs) | HTTP | Image jobs: read, cancel |
| [`/images/jobs/pull/`](#image-jobs) | HTTP | Starting an image pull from another registry |
| [`/images/jobs/push/`](#image-jobs) | HTTP | Starting an image push to another registry |
| [`/images/jobs/build/`](#image-jobs) | HTTP | Starting an image build |
| [`/images/jobs/{id}/events`](#events) | Event stream | An image job's log and end |
| [`/images/prune`](#image-jobs) | HTTP | Deleting the images nothing uses |
| [`/projects/`](#projects) | HTTP | Project CRUD |
| [`/projects/{name}/members/`](#projects) | HTTP | Project member CRUD |
| [`/volumes/`](#volumes) | HTTP | Volume CRUD |
| [`/volumes/{name}/mounts/`](#mounts) | HTTP | Volume mount CRUD |
| [`/volumes/{name}/files/`](#files) | WebDAV | The files in a volume |
| [`/sandboxes/`](#sandboxes) | HTTP | Sandbox CRUD |
| [`/sandboxes/{id}/files/`](#files) | WebDAV | The files in a sandbox, as its processes see them |
| [`/sandboxes/{id}/jobs/`](#sandbox-jobs) | HTTP | Sandbox jobs: read, signal, cancel |
| [`/sandboxes/{id}/jobs/exec/`](#sandbox-jobs) | HTTP | Starting a process in a sandbox |
| [`/sandboxes/{id}/jobs/{job}/stdin`](#sandbox-jobs) | HTTP | Writing to a process's stdin |
| [`/sandboxes/{id}/jobs/{job}/signal`](#sandbox-jobs) | HTTP | Sending a signal to a process |
| [`/sandboxes/{id}/jobs/{job}/events`](#events) | Event stream | A process's output and end |

Everything is made, read and removed with plain HTTP, each request standing alone.
What runs for a while, such as a build or a process, is a [job](#jobs): started with a `POST`, read with a `GET`, cancelled with a `DELETE`, and its log read as an event stream by any client allowed to, from where it left off.
What a thing holds is moved with an established protocol, so none of these carries bulk data.

Both [transports](#transport) carry HTTP, and every endpoint is reached the same way over either.

## Transport

### TCP

The server listens on TCP and is reached over HTTP at a base URL, such as `https://host/`.
Endpoints are paths under it.
The server SHOULD offer HTTP/2, and MAY also offer HTTP/1.1 and HTTP/3.
Over HTTP/1.1 every event stream read at once holds a connection of its own, so a client reading many SHOULD reach the server over HTTP/2.

The server keeps nothing between requests for the transport's sake.

A server on the local machine SHOULD bind to `127.0.0.1`, not to every interface.

#### Origin

A web page could reach a server through DNS rebinding, so the server MUST check the `Origin` header of every request, the opening of a [port's](#ports) WebSocket included.
It MUST answer `403 Forbidden` to a request whose `Origin` names an origin it does not allow.
A request with no `Origin`, from any non-browser client, is not refused for that.

### Stdio

The client starts the server as a child process, and the server's stdin and stdout together carry one HTTP/2 connection (RFC 9113), with the client as its client.

- The connection starts with prior knowledge (RFC 9113, section 3.3): the client sends the connection preface first, with no TLS and no upgrade. Requests use the `http` scheme. The authority is not checked.
- Neither side writes anything else there: the client MUST NOT to stdin, and the server MUST NOT to stdout.
- The server MAY write UTF-8 text to stderr for a person to read. The client MAY capture, forward or ignore it.
- The connection has one client. The server takes no [credentials](#authentication) and checks no [`Origin`](#origin), and the client reaches every [project](#projects) it has.
- The client ends it by closing the server's stdin, which the OS also does when the client's process ends. The server SHOULD then delete every sandbox and cancel every job, as `DELETE` does, and exit, without waiting for requests in flight to finish. A client MAY kill a server that has not exited within a time it chooses.

## Authentication

Over [TCP](#tcp), a server reachable from other machines SHOULD require credentials on every request, to every endpoint.
A server on the local machine MAY take none, and a server over [stdio](#stdio) takes none.
The credentials SHOULD be an OAuth 2.1 access token, sent as `Authorization: Bearer <token>`.
How the client obtains the token is outside this protocol, but a server MAY say where: `GET /auth` is answered without credentials, `200` with a JSON object.

- `oidc`, if the tokens are an OpenID Connect provider's, is `{"issuer": "...", "client_id": "..."}`: the provider, and the public client to sign in to it as. The token is then the ID token the provider issues that client.
- Without `oidc`, the server names no way to sign in: it takes tokens given out some other way, or none.

A server answers `401 Unauthorized` to a request without valid credentials, and `403 Forbidden` to one whose credentials do not allow it.

## Projects

Everything a server keeps, its images, volumes and sandboxes, belongs to a project, and a project to its members, each in a role.
A request names its project in the `virtx-project` header, the same over either transport.
A server that answers browsers from other [origins](#origin) lists `virtx-project` in its CORS preflight's `Access-Control-Allow-Headers`, or a browser sends no request naming a project.
A request that names none belongs to its sender's own project, `default`, which the server makes the first time it is reached, its sender its owner.

- A project has an `id`, a UUID the server gives it once, and a `name`, which the user whose project it is, its `owner`, gives it.
- A project's name is lower-case letters, digits, `.`, `_` and `-`, up to 128 characters, starts with neither `.` nor `-`, and is no UUID.
- No two projects of one owner share a name: another user's project of the same name is another project.
- `virtx-project`, and `{project}` in the paths below, name a project by its id, or a project of the sender's by its name. `default` names the sender's own, and no request makes a project of that name: it is refused with `400`, `invalid`.
- Projects are apart: the volume `data` of one project is not that of another, and nothing in one is reached from another.
- A request to a project its credentials do not reach, or to one that does not exist, is refused with `403 Forbidden`, `forbidden`, the one not told apart from the other.
- A [port's](#ports) URL names no project: the capability in it alone finds the port.

Each member of a project has a role:

- `member` reaches everything in it, reads it and its members, and leaves it.
- `owner` does what a member does, and also adds, changes and removes members, and removes the project.

A server that takes no [credentials](#authentication), such as one over [stdio](#stdio), has no members: its one client is the host's admin, and owns every project the server keeps.
Those are its own, which it names by name and answers with no `owner`, and those a server with users over the same home keeps for them, which it names by id alone and answers with their `owner`.
The client's `role` in each is `owner`, and the server serves no `/projects/{project}/members/`.

Projects and their members are made, read and removed with the requests below, as [Resources](#resources) says.
They name the project in their path, and take no `virtx-project`.
A server whose projects are kept and managed elsewhere, as one built for a service that has its own, may serve none of them: each is then answered `404`, `not_found`, and a request that names a project in `virtx-project` reaches it as above.

| Request | Body | Answer |
| --- | --- | --- |
| `GET /projects/` | | `200`, array of `{id, name, owner, role}` |
| `POST /projects/` | `{name}` | `201`, `{id, name, owner, role}` |
| `GET /projects/{project}` | | `200`, `{id, name, owner, role}` |
| `DELETE /projects/{project}` | | `204` |
| `GET /projects/{project}/members/` | | `200`, array of `{user, role}` |
| `PUT /projects/{project}/members/{user}` | `{role}` | `201` or `200`, `{user, role}` |
| `DELETE /projects/{project}/members/{user}` | | `204` |

- `role` in a project's answer is the role of who asked; `GET /projects/` answers each project they have one in, their own among them.
- `POST` makes a project of who asked, its owner and its one member. A name of theirs in use is refused with `409`, `exists`.
- `DELETE` of a project removes everything in it, its image jobs cancelled, and is refused with `409`, `in_use`, while a sandbox lives in it. The sender's own is made again, empty, as it is next reached.
- `{user}` is a user as the server names them, such as an email address.
- `PUT` gives `user` the role: `201` adds them, `200` changes theirs.
- `DELETE` of a member takes their role away. A user who is no member is refused with `404`, `not_found`.
- Only an owner adds, changes and removes members, and removes the project, but a member removes themself, leaving it. Anyone else is refused with `403`, `forbidden`.
- A change that takes the `owner` role from the user whose project it is is refused with `409`, `in_use`.

## Resources

Everything but images and files is made, read and removed with the requests below.
A request body is JSON, sent with `Content-Type: application/json`, and so is every response body but an [event stream](#events).
A client ignores a member of a response body it does not know, so a server can add one without breaking a client already released.
`{name}`, `{id}` and `{job}` are each one path segment, percent-encoded.

A `POST` or `PUT` that makes something answers `201 Created` with it, and with its path in `Location`.
A `DELETE` answers `204 No Content` once what it names is gone.

A request that fails is answered with an HTTP error status and a body:

```text
{"error": {"code": "in_use", "message": "volume `dev` is mounted by a sandbox"}}
```

- `code` is a string, from the table below, or another the server gives for its own failures.
- `message` is a string, for a person to read. A client SHOULD NOT tell errors apart by it.
- An error MAY have other members beside them, as RFC 9457's extension members are, each said where the refusal that has it is: `reason` of a [`quota`](#refused-for-now), `written` of a write to a job's [stdin](#sandbox-jobs) cut part-way. A client ignores a member it does not know, and reads one it does from that refusal alone.

| Status | `code` | When |
| --- | --- | --- |
| `400 Bad Request` | `invalid` | The body is not JSON, or not what the request takes, such as a missing or unknown member; or a path segment does not read as what the path takes. Its `message` names the member or segment, what it takes and what was sent, as `cmd: a list, not "ls"`; an object or a list sent is named by its kind alone. A failure inside a member that names its own kind, such as `image`, `auth` or `source`, is told at that member. A body that is not JSON is told where it stops being JSON, with none of it shown. |
| `401 Unauthorized`, `403 Forbidden` | `unauthorized`, `forbidden` | See [Authentication](#authentication), [Projects](#projects) and [Origin](#origin). |
| `404 Not Found` | `not_found` | What the path names does not exist. |
| `405 Method Not Allowed` | `method_not_allowed` | The path takes no such method, such as a `PATCH` of a file, under [Files](#files). |
| `409 Conflict` | `exists`, `in_use`, `ended` | A name already in use, something held by a sandbox, or a job or a sandbox's VM that has ended. |
| `413 Content Too Large` | `too_large` | The body is over the server's limit, which is at least 2 MiB. A file's body, under [Files](#files), has none. |
| `422 Unprocessable Content` | `not_started` | A job that cannot be started, such as a command not found. |
| `429 Too Many Requests` | `quota` | The request is past a limit of the server's, which `reason` names. See [Refused for now](#refused-for-now). |
| `500 Internal Server Error` | `internal` | The server failed on its side. |
| `503 Service Unavailable` | `capacity` | The server has no room for what the request makes, or for a write to a job's [stdin](#sandbox-jobs), for now, and made none of it. See [Refused for now](#refused-for-now). |

### Refused for now

A server MAY turn a request away for now, with `429` or `503` and a `Retry-After` of the seconds to wait before it is sent again:

- `429`, `quota`, has `reason` beside `code` and `message`, naming the limit the request is past. `requests`, the rate of requests, frees up by itself, and a client MAY send the request again after `Retry-After`. Any other `reason`, such as a count of sandboxes, frees up only as the caller closes or deletes something: a client answers it at once rather than waiting.
- `503`, `capacity`, says nothing was made, so a request that makes something MAY be sent again after `Retry-After`. A `503` with another code or none, such as a proxy's own page, may have come after the request was carried out: a client MAY send it again only where a second sending leaves what the first did -- a `GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE` or `PROPFIND` with no `If-Match` or `If-None-Match` -- and takes a `DELETE` so sent again that is answered `404` as done.

virtx's client sends a request again so for 30 seconds at most, its answers' time and the waits between them together, and then answers the last refusal.

### Jobs

A job is something the server does for a while: an [image job](#image-jobs), such as a build, or a [sandbox job](#sandbox-jobs), a process.
Each is a resource of its own, under an id the server gives it, and every job is read as the others are:

- As JSON it is an object with at least `id`, `kind`, such as `"build"` or `"exec"`, and `running`, whether it runs still. What it ended with is beside them once it has ended.
- A `DELETE` of one that runs cancels it, as its kind says, and then removes it. A `DELETE` of one that has ended removes it.
- Its log is its [event stream](#events), at `{job}/events` under its path, and kept as long as the job is.

A client that needs what a job did reads it from the job, or from its last event, not from the lines of its log.

### Events

A job's log is read with `GET`, answered `200` with `Content-Type: text/event-stream`: a stream of [server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html), one entry of the log to each event.

```text
id: 1
data: {"stdout": "hello"}

id: 2
data: {"end": {"code": 0}}
```

- `id` is the entry's number in the log: `1` for the first, and one more for each after it.
- `data` is the entry, one JSON object with one member, written on one line. What its member is named and holds is the job's kind's. A later version of this protocol may add a kind of entry; a client passes over one it does not know, its `id` still counting for `Last-Event-ID`.
- The server sets no other field, and MAY send comments, lines starting with `:`, to keep the connection open. A client ignores any other field, and any event with no `data`.

Every reader gets the whole log, from its first entry, as the job writes it.
A client that sends `Last-Event-ID: n` gets the entries after entry `n` only, so a client whose stream dropped picks up where it left off.
virtx's client does so by itself over TCP: a stream that breaks, or a `502` to `504` asking for it again, has it asked for after the last entry read, up to five times in a row. A stream that ends before its `end` entry, over either transport, is asked for again at once after the last entry read, where it sent any: a stream cut on the way reads on, and one whose job was removed is answered `404`. One that ends with no entry past where it was asked is asked for again only while the job is `running`, as a broken one is: a job removed is answered `404`, and a log of an ended job asked for after its last entry has nothing more, and ends there.

The last entry is `{"end": {...}}`, what the job ended with, and the stream ends after it.
A job that has ended answers its whole log at once, and ends there.
A job removed while a client reads its log ends that stream at its `end`, or where it is if it has none.

A log is kept whole up to the server's limit, and no further: an entry past it is neither kept nor sent, and the first one past it is replaced by `{"truncated": {}}`, once.
The `end` entry is kept and sent anyway.

A slow reader slows only its own stream: the server does not buffer for it beyond the log it keeps.

### Image jobs

An image job copies an image between the server's [images](#images) and another registry, or builds one into them.

| Request | Body | Answer |
| --- | --- | --- |
| `GET /images/jobs/` | | `200`, array of image jobs |
| `POST /images/jobs/pull/` | `{reference, auth?}` | `201`, the job |
| `POST /images/jobs/push/` | `{reference, auth?}` | `201`, the job |
| `POST /images/jobs/build/` | `{recipe, reference}` | `201`, the job |
| `GET /images/jobs/{id}` | | `200`, the job |
| `DELETE /images/jobs/{id}` | | `204` |
| `GET /images/jobs/{id}/events` | | `200`, its [log](#events) |
| `POST /images/prune` | `{}` | `200`, `{images, reclaimed}` |

An image job is `{id, kind, reference, running, digest?, error?}`:

- `kind` is `"pull"`, `"push"` or `"build"`, and `reference` the one it was started with.
- `digest`, once it has succeeded, is that of the image a pull or build left here, as the [images](#images) list it, or of the manifest a push put on the registry.
- `error`, once it has failed, is why, for a person to read.

Its log's entries are `{"log": "..."}`, a line of it, and `{"truncated": {}}`, then `{"end": {"digest": "..."}}` or `{"end": {"error": "..."}}`, as the job has them.

Pull and push copy an image between the server's images and another registry, the one `reference` names, as `docker pull` and `docker push` do: `ghcr.io/owner/name:tag` is `owner/name:tag` at `ghcr.io`, and a reference that names no registry, such as `alpine:3.20`, is at Docker Hub.
Each keeps the reference as it is on the server's side, so what a pull pulls is tagged `reference` here, and a push pushes the image `reference` tags here.
Each skips a blob the other side already has, and moves the tag on the receiving side to the image.

`auth` is the credentials for the other registry, as `{"type": "basic", "username", "password"}`, the password possibly an access token the registry takes in its place, or `{"type": "bearer", "token"}`.
Without it the server goes to the registry anonymously.
The server uses `auth` for that job alone: it MUST NOT keep it beyond the job, show it in the job or its log, write it to a log of its own, or send it to any other host.

A server MAY refuse to connect to a registry, or to a host that registry sends it on to, at an address it does not let its sandboxes reach, such as its own loopback or its private network.
The job then fails, its `error` naming the host.

A build builds an image from `recipe` into the server's images and tags it `reference`, as a push of it would.

Cancelling one stops it:

- A build leaves no tag changed. Layers already built MAY be kept for reuse.
- A pull leaves no tag changed. Blobs already fetched MAY be kept for reuse.
- A push puts no manifest to the other registry. Blobs already pushed there stay.

A cancel that comes once a build or a pull has begun to write its tag waits for that to finish: the job has then ended, as it would have, and the `DELETE` removes it.

The server MAY remove an image job that has ended, once a time it chooses has passed.

`POST /images/prune` deletes each image no reference points at and no sandbox uses, and what only such images held, such as their layers.
`images` is the digest of each image it deleted, and `reclaimed` how many bytes that freed.
It MAY leave what is too new to tell from what a running image job will point a reference at.

### Volumes

A volume is storage kept under a name, apart from any sandbox, and mounted into sandboxes.
Its files are reached at [`/volumes/{name}/files/`](#files).

| Request | Body | Answer |
| --- | --- | --- |
| `GET /volumes/` | | `200`, array of `{name, size}` |
| `POST /volumes/` | `{name?}` | `201`, `{name, size}` |
| `GET /volumes/{name}` | | `200`, `{name, size}` |
| `DELETE /volumes/{name}` | | `204` |

Without `name` the server picks one, and a name in use is refused with `409`, `exists`.
`size` is the bytes the volume's files take on the server.
`DELETE` deletes everything in it, and refuses a volume a sandbox mounts with `409`, `in_use`, from the sandbox's `POST` until its `DELETE`.

#### Mounts

Remote sources, such as Notion or Google Drive, can be mounted at a path inside a volume.
`{path}` is that path, each segment percent-encoded, as in [Files](#files).

| Request | Body | Answer |
| --- | --- | --- |
| `GET /volumes/{name}/mounts/` | | `200`, array of `{path, mount_type}` |
| `PUT /volumes/{name}/mounts/{path}` | `{source}` | `201`, `{path, mount_type}` |
| `DELETE /volumes/{name}/mounts/{path}` | | `204` |

`source` is what is mounted, and the credentials to reach it:

```text
{"type": "notion", "api_key": "..."}
{"type": "gdrive", "client_id": "...", "client_secret": "...", "refresh_token": "..."}
{"type": "onedrive", "client_id": "...", "client_secret": "...", "refresh_token": "..."}
```

`mount_type` is its `type`; its credentials are never answered.
The mount is a directory it creates, not the root and not inside another mount, so its parent must exist and it must not.
`PUT` refuses a path that already has a mount with `409`, `exists`.
`DELETE` takes the mount and its directory away, and leaves the source as it is.

### Sandboxes

A sandbox is a VM booted from an image, with [volumes](#volumes) mounted into it.

| Request | Body | Answer |
| --- | --- | --- |
| `GET /sandboxes/` | | `200`, array of `{id, name?, image, running, ports?, abins?, error?}` |
| `GET /sandboxes/?name={name}` | | `200`, array of the one named so, or of none |
| `POST /sandboxes/` | `{image, name?, network?, ports?, vcpus?, memory_mib?, disk_gib?, gpu?, gpu_memory_mib?, volumes?, abins?}` | `201`, `{id, name?, image, running, ports?, abins?}` |
| `GET /sandboxes/{id}` | | `200`, `{id, name?, image, running, ports?, abins?, error?}` |
| `PATCH /sandboxes/{id}` | `{vcpus?, memory_mib?, disk_gib?}` | `200`, `{vcpus, memory_mib, disk_gib, up}` |
| `DELETE /sandboxes/{id}` | | `204` |

- `image` in the body is `{"type": "tag", "tag": "name:tag"}` or `{"type": "digest", "digest": "algorithm:hex"}`, an image in the server's [images](#images); in the answer, the digest of the image it booted.
- `name`, if given, names it among the sandboxes a listing answers, so a client finds it again with `GET /sandboxes/?name={name}` rather than keeping its id; the answer names it as given. It is letters, digits, `.`, `_` and `-`, not starting with `.` or `-`, and at most 128 characters, as a volume's, compared as written, so case counts; any other is refused with `400`, `invalid`. A name another sandbox has is refused with `409`, `exists`; once that one is deleted, the name is free.
- `network` is whether its processes reach a network at all, and is `true` without it.
- `vcpus`, `memory_mib`, `disk_gib`, `gpu` and `gpu_memory_mib` each leave it to the server without one. The server gives exactly what is asked or refuses; `0` for a number is refused, and so is a `memory_mib` under the least a machine boots in, which the refusal names. `disk_gib` is how much it may write over its image, in GiB, at most `1024`; what it wrote there goes with it. `gpu` `false` forbids a GPU on a server that would attach one, and `gpu_memory_mib` is refused without one.
- `volumes` are mounted into it in order, so a later path may be inside an earlier one, each as `{volume, path, readonly?}`: the volume by name, where it appears to processes, absolute, and whether a write in it fails. A path is read with repeated and trailing `/` dropped, so `//data/` is `/data`; one that is not absolute, has a `.` or `..` segment, or is `/`, and two at one path so read, are refused with `400`.
- `abins` are virtx's own programs it gets, by name, at `/abin`, which goes in front of its `PATH`, each with its `SKILL.md` at `/abin/skills/{name}/`. Without any it has no `/abin`; a name the server has no program by is refused. The answer names them as asked.
- `running` is whether it takes processes: `false` once its VM has exited on its own, and never `true` again. One whose VM the server stopped, as below, is `true`.

Its files are reached at [`/sandboxes/{id}/files/`](#files).

#### Resizing

A server MAY resize a sandbox with its `PATCH`, and one that does not answers it `405`, `method_not_allowed`.
Each member is held to what `POST` holds it to, and one left out stays as it is.

- `vcpus` and `memory_mib` are what its VM boots with from its next boot on. A VM is the size it booted with: the server stops one that is up and in which nothing runs, as below, to boot it again so for what next needs it, and refuses one in use with `409`, `in_use`, changing nothing.
- `disk_gib` grows what it may write over its image, to as large as its VM next boots with, and keeps what it wrote there. A VM that is up is neither stopped for it nor refused, in use or not: a request that changes `disk_gib` alone is answered at once with `up` `true`, and its VM keeps the disk it booted with until it next boots, after it is next stopped. A request that also changes `vcpus` or `memory_mib` is stopped or refused for those, and the disk grows at that same boot. A disk is grown, never shrunk: one smaller than the disk the VM last booted with is refused with `400`, `invalid`, and one down to that size is taken, so a grow not yet made can be taken back. A grow the server cannot make as the VM boots leaves the disk as it was, and the VM boots on it; the size asked for stays, and the grow is tried again at each boot.
- The answer is its size as it is to be, each member as the server gives it, and `up`, whether its VM is up now: one that is, the size it booted with until it boots again.

A sandbox lives until it is deleted: by its `DELETE`, or by the server, which MAY reclaim one on conditions it chooses, such as no activity for a while.
Either stops its VM, kills every job in it that runs, as its [reason](#sandbox-jobs) `sandbox_deleted` says, and closes its ports; what it wrote outside its volumes goes with it, its volumes stay, and every request naming it is answered `404`, `not_found`.
One whose VM has exited is still held until then.

A server MAY stop the VM of a sandbox in which no job runs and nothing is reached through its files or its ports, and boot it again for the next job or request to its files, which then take as long as booting does.
Everything written to its root filesystem is kept across that, as it is for as long as the sandbox lives; what was left running in it, apart from a job, is not.
A connection to one of its ports while its VM is stopped is closed, as one to a port nothing listens on is, and does not boot it.

A server that ends MAY keep its sandboxes for when it is started again over what it kept, and otherwise deletes them as it ends.
It stops the VM of each it keeps, and, started again, knows each as one whose VM it stopped: booted again as above, its files as it left them, its ports at the URLs its `POST` answered, and its `running` as it was.
One it kept and cannot know again, such as one whose image is gone, it MAY still list until its `DELETE`, with `running` `false` and an `error`, a string saying why: every other request about it is refused `409`, `ended`, and its `DELETE` removes what it kept of it.

#### Ports

`ports` in the body are ports in the sandbox to open, each a number, or `{port, label?, protocol?, inbound?}` to say what it is for, how it is reached and whom it lets in: `[5900, {"port": 5173, "label": "dev server", "protocol": "http"}]`.

- `label` is what it is for, free text of up to 128 characters, answered with it.
- `protocol` is `tcp`, the default: TCP, reached as below; or `http`: HTTP served in the sandbox, reached at its `url` as HTTP by a browser as by any client, WebSockets included -- over TLS, from a server reachable from other machines, the sandbox serving plain HTTP. A server that cannot reach a port over HTTP MUST refuse `http` with `400`, `invalid`. A later version of this protocol may add a protocol; a server refuses one it does not know with `400`, `invalid`, and a client keeps one it does not know in an answer as it was sent.
- `inbound` is the port's inbound rules, `[{source, description?}]`, each `source` an IPv4 or IPv6 CIDR or one address: whom it lets in. A server MAY keep them; one that keeps none MUST refuse `inbound` with `400`, `invalid`, rather than open a port to whoever it was meant to keep out. Whom a port given none lets in is the server's to say; `[]` lets in no one.

They are reserved when the sandbox is made, and kept until its `DELETE`. `0` and a port given twice are refused.

The `POST` answers each with where it is reached from, as `{port, url, label?, protocol?, address?, inbound_error?}` -- `protocol` left out for `tcp`, `address` for a port that has none, `inbound_error` for any but one whose rules could not be set -- in the order given.
A `GET` of the sandbox, and of them all, answers each as `{port, label?, protocol?, address?}`, in the same order, until the sandbox's `DELETE`, across a restart of the server that keeps it too: with no `url`, which the `POST` alone answers, since the URLs carry credentials. One with an `error` answers none, since none of its ports is open.

- A server on the client's machine answers a loopback address, such as `http://127.0.0.1:54123`, on a port it picks. Only that machine reaches it.
- A server reachable from other machines answers a URL that carries the credentials it needs, and MUST NOT open a port that is reached without them but at its `address`. The URL is as secret as those credentials, and the client MUST keep it so.
- A server reachable from other machines MAY answer a `tcp` port with an `address` too, `host:port`, such as `tcp.example.com:20001`, where any TCP client reaches it directly, with no WebSocket and no credentials. It is not secret, as the URL is: what listens on the port answers whoever connects there, and authenticates them itself. An `http` port has none, and nor does any on a server on the client's machine. A server that keeps no inbound rules MUST NOT answer one, since the client could not narrow whom it lets in.
- The URL is the server's to form: a client MUST NOT build one or take it apart.
- A connection reaches whatever in the sandbox listens on that port, whichever address it listens on, and is closed when nothing does. Over a remote URL, a `tcp` port's TCP is carried in a WebSocket to that URL, opened with the subprotocol `virtx.tcp`; a server that could not reach the port at all, such as while no VM runs, SHOULD close it with a reason saying why, for a person. An `http` port's URL is an `https` one that a browser opens.
- Ports are the way in, and do not need `network`, which is the way out.
- A server that keeps inbound rules MAY open a port whose rules it could not set, such as past a quota, with `inbound_error`, `{code, message, reason?}` in a refusal's shape, beside its `url`: it lets no one in, and is reached at no `address`, until they are. The sandbox is answered `201` as any is, since a refusal would read as nothing made.

### Sandbox jobs

A sandbox job is a process in a [sandbox](#sandboxes), run beside whatever else runs there.

| Request | Body | Answer |
| --- | --- | --- |
| `GET /sandboxes/{id}/jobs/` | | `200`, array of sandbox jobs |
| `POST /sandboxes/{id}/jobs/exec/` | `{cmd, stdin?, timeout_ms?}` | `201`, the job, or [with its log](#an-exec-answered-with-its-log) |
| `GET /sandboxes/{id}/jobs/{job}` | | `200`, the job |
| `DELETE /sandboxes/{id}/jobs/{job}` | | `204` |
| `POST /sandboxes/{id}/jobs/{job}/signal` | `{signal}` | `204` |
| `POST /sandboxes/{id}/jobs/{job}/stdin` | `{data?, eof?}` | `204` |
| `GET /sandboxes/{id}/jobs/{job}/events` | | `200`, its [log](#events) |

A sandbox job is `{id, kind, pid, cmd, running, code?, reason?}`:

- `kind` is `"exec"`.
- `pid` is its process's pid in the sandbox. The job is named by `id`, not by it, so a pid the sandbox gives again never names another job.
- `cmd` is the argv it was started with, with no shell: `["sh", "-c", "..."]` for one. An empty one is refused.
- `code`, once it has ended, is its exit status, or `128 + signal` for one a signal ended.
- `reason`, once it has ended, is why, where the process did not end by itself and the server says, as below.

A command that cannot be started, such as one not found, is refused with `422`, `not_started`, and makes no job.

#### An exec answered with its log

An exec whose request's `Accept` names `text/event-stream`, with a `q` above `0`, MAY be answered with the job's log as well, saving the client a second request. A range such as `*/*` does not ask for it.

- `201`, with `Content-Type: text/event-stream`, and the job's path in `Location`, as any `201` has.
- As the body, first the job itself, as an event whose `data` is `{"job": {...}}` and which has no `id`; then the job's log, from its first entry: the same events that `GET {job}/events` answers with its `200`, numbered as there, under the exec's own status.

```text
data: {"job": {"id": "...", "kind": "exec", "pid": 7, "cmd": ["echo", "hi"], "running": true}}

id: 1
data: {"stdout": "hi"}

id: 2
data: {"end": {"code": 0}}
```

The job's event is this answer's alone: it is no entry of the job's log, `GET {job}/events` never sends it, and it moves no entry's number, so an entry's `id` here is its number in the log as [Events](#events) has it.
A client reads the job from that first event; where the answer breaks off or ends before it, the client reads the job with `GET` at the path in `Location`, and its log from the first entry.
A client whose answer breaks off after the job, before the log's end, reads the rest with `GET {job}/events`, sending `Last-Event-ID` with the `id` of the last entry it read, or none where it read none, as [Events](#events) says.

A server MAY answer such a request with the job alone, as JSON, as it answers any other: so a client that asks for the log this way MUST accept `application/json` too, and read the job's log with its `GET {job}/events` where the answer is the job alone.

Its log's entries are each an object with one member:

- `{"stdout": "..."}` or `{"stderr": "..."}`: a line the process wrote there, without its line ending, decoded as UTF-8 with each invalid sequence replaced by U+FFFD. A line longer than the server's limit is sent in parts, an entry each.
- `{"truncated": {}}`, as [Events](#events) says.
- `{"end": {"code": n}}`, or `{"end": {"code": 137, "reason": "..."}}`, last: its `code`, and `reason`, as the job has them.

Lines of one stream are in the order the process wrote them; lines of the two, in the order the server read them.

The process ends when it exits, when its `timeout_ms` runs out, when its job is cancelled, when its sandbox is deleted, with its sandbox's VM, or with its server, which keeps its sandbox.
In each of the last five, it and every process it started are killed, as `SIGKILL` does, and its `code` is `137`.
It is killed so too, its `code` `137`, when its memory runs out: past what the server lets one command take, or the VM's, or where it thrashes there, reading back what it had to let go of.
A server MAY say which, in its end and in its job, with `reason`:

- `"timeout"`: its `timeout_ms` ran out.
- `"cancelled"`: its job was cancelled, by its `DELETE` while it ran, which then ends its log with this end before the job is removed. Its sandbox is still there.
- `"sandbox_deleted"`: its sandbox was deleted while it ran, by the sandbox's `DELETE` or by the server, which then ends its log with this end before the job goes with the sandbox.
- `"vm_exited"`: its sandbox's VM exited on its own under it; the sandbox's `running` is then `false`.
- `"oom"`: its memory ran out: it ended `137`, killed, or a process it started killed, for want of memory. A server that holds a command to a memory limit SHOULD say it, so that one is told apart from a `SIGKILL` sent.
- `"restarted"`: its server ended, keeping its sandbox, while it ran, as below.

A later version of this protocol may add a reason. A client keeps one it does not know as it was sent, and reads the job and its end as it would otherwise.

A process that exits, or that a `signal` sent it ends -- `SIGKILL` too, its `code` `137` -- ended by itself, and has no `reason`; without one, a `code` of `137` does not say which.
The job, and its log, are kept until its `DELETE` or its sandbox's, or until its sandbox is reclaimed.
A server MAY keep a number of a sandbox's ended jobs of its choosing, and no more: past it, the one that ended first is removed as another starts, and one that runs never is.
A sandbox [kept](#sandboxes) across its server's end keeps its jobs, as many as the server keeps: started again, the server knows each that had ended as it ended, and each that ran as killed then, its `code` `137` and its `reason` `"restarted"`. A job so kept has its `end` alone for its log.

`signal` sends `signal` to the process and every process it started, and answers once it is sent: what the process does with it, its log says.
`signal` is a name as Linux gives it, such as `"SIGTERM"` or `"SIGKILL"`, and a name the server does not know is refused.
A job that has ended refuses it with `409`, `ended`.

Without `stdin`, or with it `false`, the process's stdin is empty.
With `stdin` `true`, the client writes to it with `POST {job}/stdin`:

- `data` is a string, written to the process's stdin as UTF-8, as it is.
- `eof` `true` closes the process's stdin, after any `data` in the same request.
- The server answers once `data` is in the process's stdin, which takes a pipe's worth before the process reads any, so a process that does not read holds the answer back once that is full.
- A client sends a job's next `stdin` only once the one before it is answered, so they are written in the order sent.
- A server MAY hold only so many writes to one stdin that its process has not read, as when a client gave up on writes before they were answered, and turns away one past that with `503`, `capacity`, and a `Retry-After`: none of its `data` written, and its `eof` not done, so the stdin is as it was and takes the write when it is sent again, once the process has read. It is not `ended`.
- A job started without `stdin`, one whose stdin is closed -- by `eof` or by its process -- and one that has ended refuse it with `409`, `ended`. So does a write its process closed its stdin under part-way, with `written` beside `code` and `message`: how many bytes of `data`, as UTF-8, went in before it closed, so `{"error": {"code": "ended", "message": "...", "written": 65536}}`. No other refusal of a write has `written`.
- An empty `data` writes nothing, and is answered as any write is: `204` while the process's stdin still has a reader.

## Images

The server keeps images as an OCI registry, and `/images/oci/v2/` is its API: the [OCI Distribution Specification](https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md) v1.1, with every path the specification roots at `/v2/` rooted at `/images/oci/v2/` instead.
A client gives `/images/oci` as the registry's base path, since tools that assume `/v2/` at the root do not reach it.

The server MUST support the specification's Pull, Push, Content Discovery and Content Management categories.
It also answers `GET /images/oci/v2/_catalog`, which the specification does not define, with the repositories it holds as `{"repositories": [...]}`, paged by `n` and `last` as tag listing is.

- Repository: the name of an image, an OCI repository name such as `alpine` or `team/base`.
- Tag: a name within a repository, such as `3.20`. It points at one manifest, and can be moved to another.
- Reference: a repository and a tag, as `name:tag` (such as `alpine:3.20`).
- Digest: the hash of a manifest, as `algorithm:hex` (such as `sha256:0123abcd...`). It identifies one image's content and never changes. A tag may point at an image index, and a sandbox then boots the manifest in it for the server's platform.

Images are listed, tagged and removed with the specification's requests:

| To | Request |
| --- | --- |
| List images | `GET /images/oci/v2/_catalog`, then `GET /images/oci/v2/{name}/tags/list` |
| Tag an image | `PUT /images/oci/v2/{name}/manifests/{tag}` with its manifest |
| Untag a reference | `DELETE /images/oci/v2/{name}/manifests/{tag}` |
| Remove an image | `DELETE /images/oci/v2/{name}/manifests/{digest}`, which also removes every tag pointing at it |
| Export an image | `GET` its manifest, and each blob it names |
| Import an image | Push each blob, then `PUT` its manifest by tag |

A sandbox stands on the image it was made from, from its `POST` until its `DELETE`, its VM parked or not, and a build on its base while it runs.
A `DELETE` that would leave an image a sandbox or a build stands on with no tag -- the image's removal, or the untagging of its last tag -- is refused with `409 Conflict` and the code `DENIED`, and removes nothing.
A manifest no tag points at, and a blob no manifest names, MAY be deleted by the server at any time.
A client pushing an image therefore puts its manifest by tag, not by digest alone.

The server copies images to and from other registries with [pull and push jobs](#image-jobs), which take that registry's credentials.
A client that would rather keep them can copy an image itself instead: it fetches the image from that registry and pushes it here, skipping each blob a `HEAD` shows the server already has, or the other way round.

A request that fails is answered with the specification's error codes, in its `{"errors": [...]}` body.

## Files

The files in a volume are reached at `/volumes/{name}/files/` and those in a sandbox at `/sandboxes/{id}/files/`, with [WebDAV](https://www.rfc-editor.org/rfc/rfc4918) (RFC 4918).
The path after the root is the file's path in the volume or sandbox, each segment percent-encoded.
A client resolves a path's `.` and `..` segments before it sends it, as a file's path is read: empty segments are dropped, and each `..` takes the segment before it, so `a/../b` and `a//../b` are both sent as `b`; a path that goes above the root is not sent.
The server refuses with `400 Bad Request` a path, or the `Destination` of a `MOVE` or `COPY` up to its `?` or `#`, with a `.` or `..` segment, plain or percent-encoded, `/` and `\` both separating segments; and one that is not in the root (of a URL, its path alone, with consecutive slashes taken as one). It does so before anything in the volume or sandbox is touched.

The server MUST support WebDAV class 1, and MAY support class 2 (locking).

| To | Request |
| --- | --- |
| Read metadata | `PROPFIND`, `Depth: 0` |
| List a directory | `PROPFIND`, `Depth: 1` |
| Read a file | `GET`, with `Range` for a part of it |
| Write a file | `PUT` |
| Create a directory | `MKCOL` |
| Remove | `DELETE` |
| Rename | `MOVE`, with `Overwrite` |
| Copy | `COPY`, with `Overwrite` |

- `PROPFIND` answers at least `resourcetype`, `getcontentlength`, `getlastmodified` and `getetag`. The server MAY refuse `Depth: infinity`, as RFC 4918 lets it.
- `PUT` replaces the whole file, and creates it if it does not exist. A `PUT` with `Content-Range` is refused with `400 Bad Request`, and a `PATCH` of any kind, such as SabreDAV's partial update, with `405 Method Not Allowed`, `method_not_allowed`, and the `Allow` an `OPTIONS` of its path answers, which leaves `PATCH` out: a file is written whole, and lands whole. Until all of the body has arrived, what was at the path is what is read there, and a `PUT` broken off leaves it. A `PUT` with `If-Match` is refused with `412 Precondition Failed` unless the file's `getetag` is among the tags given, as RFC 9110 says: how a client writes only over the file it read. A `getetag` is an entity-tag in quotes, the same as the file's `ETag` header, and is sent in `If-Match` as it was read. One with `If-None-Match: *` is refused with `412` when anything is at the path: how a client creates a file only if no other did. A `PUT` that answers an `ETag` answers the one a `GET` of the file it wrote does, so a client can send it as `If-Match` on its next write without reading the file again.
- A `PUT` with `If-Match` or `If-None-Match` to a volume or a sandbox is checked before its body is read, and again once all of it has arrived, against the file as it is then, and lands in the same step, so no other write with a condition lands between the two: none from another client of the server, and, to a volume, none from another server over one home. Of two sent at once to one file, one lands, and the other is checked against what it wrote and refused `412` if its condition no longer holds: read the file again, and retry. On one server, the one whose body has all arrived first, and to a sandbox been sent on to it, is checked first. A write to a sandbox holds each volume the sandbox mounts writable as well, so a file in such a volume is held the same whether it is written through the sandbox's files or the volume's, and a `PUT` to a path in it is checked against the volume's own files as it lands. The rest is checked as the sandbox sees the file, which can trail a write through the volume's files by a few seconds: the check before a `PUT`'s body is read, the condition of a `DELETE`, `MOVE` or `COPY`, and a `PUT` to a path the volume's files do not answer for, such as one through a symbolic link. For those few seconds after such a write, a `DELETE` or `MOVE` naming the replaced file's tag can go through, and a `PUT` naming the new one can be refused `412`. A `DELETE`, `MOVE` or `COPY` with either condition is held the same way while it is answered, but one of a directory that fails on a member, answered `207`, may go on with the rest after. A sandbox's processes write its files without asking, and a write without a condition is not held, so either may land between the check and the write.
- `PUT` and `MKCOL` under a directory that does not exist are refused with `409 Conflict`, as RFC 4918 says. `MKCOL` creates one directory, not its parents.
- `DELETE` of a directory removes everything in it. A `DELETE`, `COPY` or `MOVE` of a directory that fails in part answers `207 Multi-Status`, with the status of each path that failed, as RFC 4918 says. `DELETE` or `MOVE` of the root, and `MOVE` or `COPY` onto it, are refused with `403 Forbidden` before anything in it is touched: a volume or sandbox is removed through [Resources](#resources).
- `MOVE` and `COPY` take a `Destination` in the same volume or sandbox, and refuse any other with `400 Bad Request`.
- A request naming a volume or sandbox that does not exist is answered `404 Not Found`.

### A sandbox's files

A sandbox's files are its root filesystem as its processes see it, the volumes mounted into it among them, while its VM runs: what a process writes is read here at once, and what is written here a process reads.

- The server MAY leave out what is not a file to read or write, such as `/proc`, `/sys` and `/dev`, and what is neither a file nor a directory, such as a link or a device: it is not listed, and a request naming it is answered as if nothing were there.
- A file a `PUT` makes is owned as one a process in the sandbox makes is; one it replaces keeps its mode and owner.
- A write to a volume mounted `readonly` is refused with `403 Forbidden`.
- A request to a sandbox whose VM has exited is refused with `409 Conflict`, `ended`.

In a volume, a remote source [mounted](#mounts) at a path is reached at that path, and a request under it goes to the source. It fails, with the status the server chooses, where the source cannot do it, such as a `MOVE` the source does not support.
