# REST API

The onshore.sh REST API: E2B-compatible sandbox routes and the /v1 extensions for templates, agent runs, AI accounts and webhooks.

The onshore.sh API is compatible with the E2B REST API, so the official E2B SDKs work unchanged.
Routes that E2B has no word for live under `/v1`.

Most of the time you do not call the API by hand: use [`ons`](https://onshore.sh/docs/reference/cli) or the
[E2B SDKs](https://onshore.sh/docs/guides/migrate-from-e2b). This page is for the times you do.

## Base URL and authentication

```text
https://api.onshore.sh
```

Send your API key in the `X-API-Key` header on every call. Create a key in the console
(see [API keys](https://onshore.sh/docs/account/api-keys)).

```bash
curl -s https://api.onshore.sh/v2/sandboxes -H "X-API-Key: $ONS_API_KEY"
```

`ONS_API_KEY` is an environment variable that holds your key. Export it first, and never paste
the key itself on a command line or in a script you commit.

`GET /.well-known/onshore` needs no key. It returns `domain`, `apiUrl` and `version`. Its former
path, `/.well-known/minisandbox`, returns the same document.

```bash
curl -s https://api.onshore.sh/.well-known/onshore
```

## Errors

Every error has the E2B body: the HTTP status and a message that says what happened and what to
do next.

```json
{"code": 429, "message": "max_running_minivms limit reached … · kill or pause miniVMs you no longer use"}
```

| Status | Meaning                                                                                                                                                                                                          |
| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | A value outside your limits (timeout, vCPU, memory), or a field onshore.sh does not implement set to a non-default value. The message names the field.                                                           |
| `401`  | Missing, unknown or revoked API key.                                                                                                                                                                             |
| `402`  | Your organization is out of credit or on hold (`reason: organization_on_hold`), or has no payment method yet (`reason: payment_method_required`). See [Billing](https://onshore.sh/docs/account/billing).        |
| `403`  | Your organization is suspended (`reason: organization_suspended`). Also an egress name outside what you may reach (`egress_exceeds_template`, `egress_presets_only`), or a self token on a route it may not use. |
| `404`  | Unknown miniVM, a miniVM you did not create, or one that was killed.                                                                                                                                             |
| `409`  | Wrong state: pausing a paused miniVM, a timeout on a paused one, resuming a running one, an egress change while it is pausing or resuming.                                                                       |
| `429`  | A count or rate limit. The message names the limit and its value.                                                                                                                                                |
| `503`  | No capacity right now, or a miniVM that is moving or unreachable.                                                                                                                                                |

Most `429` and `503` answers carry a `Retry-After` header (seconds) and a stable `reason` in the
body, next to `code` and `message`. The E2B SDKs wait and retry on their own.

Common reasons: `create_rate_limit`, `max_running_minivms`, `max_paused_minivms`,
`egress_rate_limit`, `capacity_exhausted`, `cpu_saturated` (every host that
fits is short of CPU), `template_not_ready`, `snapshot_unrestorable` (no host could restore a
paused miniVM yet; it stays paused), `hybrid_runner_unknown` (a Hybrid miniVM has no runner to
reach it on yet), `egress_not_applied` (an egress change is stored, not applied yet),
`minivm_moving`, `minivm_lost`.

## miniVMs (E2B-compatible)

The E2B API calls a miniVM a "sandbox". These routes behave as the E2B SDKs expect, with the
[documented differences](https://onshore.sh/docs/guides/migrate-from-e2b#what-is-different).

| Route                                          | What it does                                                                                         |
| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `POST /v2/sandboxes`                           | Create a miniVM. Alias: `POST /sandboxes`.                                                           |
| `GET /v2/sandboxes`                            | List the running and paused miniVMs your key created. Alias: `GET /sandboxes`.                       |
| `POST /v1/sandboxes/batch`                     | Create several miniVMs at once, all or none. See [Several at once](#several-at-once).                |
| `GET /sandboxes/{id}`                          | One miniVM.                                                                                          |
| `DELETE /sandboxes/{id}`                       | Kill it.                                                                                             |
| `PATCH /v1/sandboxes/{id}`                     | Change its name and labels (JSON merge patch). See [Names and labels](#names-and-labels).            |
| `POST /sandboxes/{id}/timeout`                 | Set a new deadline, counted from now.                                                                |
| `POST /sandboxes/{id}/refreshes`               | Same, with `{"duration": <seconds>}`.                                                                |
| `POST /sandboxes/{id}/pause`                   | Pause it.                                                                                            |
| `POST /v2/sandboxes/{id}/connect`              | Connect to it, resuming it if it is paused. Alias: `POST /sandboxes/{id}/connect`.                   |
| `POST /sandboxes/{id}/resume`                  | Resume a paused miniVM (older E2B route).                                                            |
| `PUT /sandboxes/{id}/egress-credentials`       | Send egress credential values again. See [Egress credentials](#egress-credentials).                  |
| `PUT /sandboxes/{id}/network`                  | Replace its egress list, E2B's way (`updateNetwork`). See [Egress at run time](#egress-at-run-time). |
| `GET /v2/sandboxes/{id}/egress`                | Its effective egress allow list. See [Egress at run time](#egress-at-run-time).                      |
| `PATCH /v2/sandboxes/{id}/egress`              | Add or remove egress names of a running or paused miniVM.                                            |
| `POST /v2/sandboxes/{id}/egress/requests`      | Ask for names its egress does not allow. See [Egress requests](#egress-requests).                    |
| `GET /v2/sandboxes/{id}/egress/requests/{rid}` | One egress request and its answer.                                                                   |
| `GET /v2/sandboxes/{id}/egress/denials`        | The names its egress refused, newest first (30 days).                                                |
| `GET /v2/egress/requests`                      | The egress requests of your key's miniVMs, newest first.                                             |
| `POST /v2/egress/requests/{rid}/approve`       | Approve an egress request.                                                                           |
| `POST /v2/egress/requests/{rid}/deny`          | Deny an egress request.                                                                              |
| `GET /sandboxes/{id}/metrics`                  | CPU, memory and disk samples.                                                                        |
| `GET /sandboxes/metrics`                       | The newest sample of several miniVMs.                                                                |
| `GET /sandboxes/{id}/logs`                     | Always empty: onshore.sh never sees your miniVM's output. Alias: `GET /v2/sandboxes/{id}/logs`.      |

### Create a miniVM

```bash
curl -s https://api.onshore.sh/v2/sandboxes \
  -H "X-API-Key: $ONS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"templateID": "base", "timeout": 600, "metadata": {"task": "demo"}}'
```

Body fields:

| Field                   | Meaning                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `templateID`            | The template to start from. `base` is your organization's default template.                                                                                                                                                                                                                                                                                                    |
| `timeout`               | Lifetime in seconds.                                                                                                                                                                                                                                                                                                                                                           |
| `metadata`              | Your own `key: value` labels. Keys starting with `msb.` are reserved; see below.                                                                                                                                                                                                                                                                                               |
| `name`                  | onshore.sh extension. The miniVM's name, see [Names and labels](#names-and-labels).                                                                                                                                                                                                                                                                                            |
| `labels`                | onshore.sh extension. Its labels, `{"<key>": "<value>"}`, see [Names and labels](#names-and-labels).                                                                                                                                                                                                                                                                           |
| `envVars`               | Environment variables of the miniVM. They win over the template's of the same name.                                                                                                                                                                                                                                                                                            |
| `cpuCount`              | vCPUs, within your limits. Memory comes from the template.                                                                                                                                                                                                                                                                                                                     |
| `autoPause`             | `true`: pause instead of kill when the timeout ends.                                                                                                                                                                                                                                                                                                                           |
| `autoPauseIdle`         | onshore.sh extension. Seconds without activity before the miniVM pauses: `0` for never, else 60 to 86400. Your organization's default when unset.                                                                                                                                                                                                                              |
| `allow_internet_access` | `false` closes all egress for this miniVM. `true` is refused when the template allows no egress and the create adds none.                                                                                                                                                                                                                                                      |
| `egress`                | onshore.sh extension. `{"mode": "closed"}` closes egress. `allow`: only these names or presets, each one the template allows (else `403 egress_exceeds_template`). `add`: names or presets the template does not allow, within your organization's ceiling (else `403 egress_presets_only`). See [Egress](https://onshore.sh/docs/guides/egress#change-egress-for-one-minivm). |
| `network`               | E2B's `allowOut` (domain names: a name the template allows narrows the list, another is added within your ceiling) and `denyOut` (only `["0.0.0.0/0"]`). Send `egress` or `allowOut`, not both. `allowPublicTraffic: true` is refused; every other field must be unset.                                                                                                        |
| `secure`                | Accepted. An `envdAccessToken` is always issued, whatever its value.                                                                                                                                                                                                                                                                                                           |
| `egressCredentials`     | onshore.sh extension, see [Egress credentials](#egress-credentials).                                                                                                                                                                                                                                                                                                           |
| `selfToken`             | onshore.sh extension, see [Self token](#self-token).                                                                                                                                                                                                                                                                                                                           |

Any other field must be unset or at its default: the `400` message names it.

The answer is `201` with `sandboxID`, `templateID`, `alias`, `clientID`, `envdVersion`,
`envdAccessToken`, `trafficAccessToken` and `domain`.

Reserved metadata keys:

- `msb.ai_account=<name>` binds that [AI account](https://onshore.sh/docs/guides/agent-runs) instead of your
  defaults. `msb.ai_account=none` binds none.
- `msb.github_repos=<owner/name>,<owner/name>` gives the miniVM a GitHub token for those
  repositories only, through your organization's GitHub App. While no App is installed, a public
  repository is cloned read-only, with no token.
- `msb.label.<key>=<value>` sets the label `<key>`, and `name` sets the name, for the E2B SDKs.
  See [Names and labels](#names-and-labels).

Any other `msb.` key is refused with `400`.

#### Idempotency

Send an `Idempotency-Key` header (1 to 255 visible ASCII characters) to retry a create safely.
For 24 hours, the same key with the same body returns the same miniVM and does not count toward
your create rate. Another body with the same key answers `422`. A key whose miniVM was killed
answers `409`.

Every create answer carries your key's create rate in `RateLimit-Limit`, `RateLimit-Remaining`
and `RateLimit-Reset`.

#### Several at once

`POST /v1/sandboxes/batch` takes a create body plus `count` (1 to 50). It admits the whole batch
or nothing. It answers `200` with `{"sandboxes": [...]}`: one create answer per miniVM, or
`{"error": {...}}` for one that failed.

```bash
curl -s https://api.onshore.sh/v1/sandboxes/batch \
  -H "X-API-Key: $ONS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"templateID": "base", "timeout": 600, "count": 5}'
```

### List miniVMs

```bash
curl -s "https://api.onshore.sh/v2/sandboxes?state=running,paused&limit=50" \
  -H "X-API-Key: $ONS_API_KEY"
```

A key lists only the miniVMs it created. Query parameters:

| Parameter   | Meaning                                                                                                           |
| ----------- | ----------------------------------------------------------------------------------------------------------------- |
| `state`     | `running`, `paused`, comma-separated. Add `killed` to also list ended miniVMs, each with `endAt` and `endReason`. |
| `metadata`  | URL-encoded `key=value&key=value`. Every pair must match.                                                         |
| `label`     | `<key>=<value>`, repeatable. Every label must match. See [Names and labels](#names-and-labels).                   |
| `limit`     | 1 to 100.                                                                                                         |
| `nextToken` | The `x-next-token` header of the previous page. It is absent on the last page.                                    |
| `template`  | Only miniVMs of this template.                                                                                    |

### Get, pause, resume, kill

```bash
curl -s https://api.onshore.sh/sandboxes/<sandbox-id> -H "X-API-Key: $ONS_API_KEY"
curl -s -X POST https://api.onshore.sh/sandboxes/<sandbox-id>/pause -H "X-API-Key: $ONS_API_KEY"
curl -s -X POST https://api.onshore.sh/v2/sandboxes/<sandbox-id>/connect \
  -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" -d '{"timeout": 600}'
curl -s -X DELETE https://api.onshore.sh/sandboxes/<sandbox-id> -H "X-API-Key: $ONS_API_KEY"
```

`<sandbox-id>` is the `sandboxID` of the create answer.

- `GET` returns `cpuCount`, `memoryMB`, `diskSizeMB`, `startedAt`, `endAt`, `state` (`running` or
  `paused`), `name`, `labels`, `metadata`, and, when paused, `pauseReason`: `api`, `timeout`, `idle`,
  `memory_pressure`, `maintenance`, `hold` (your organization is on hold) or `egress_unapplied`
  (an egress removal did not reach its host in time). See [Lifecycle](https://onshore.sh/docs/guides/lifecycle#why-a-minivm-was-paused).
- `pause` answers `204`, or `409` if the miniVM is already paused.
- `connect` answers `200` when the miniVM was running and `201` after resuming it. A `timeout`
  becomes the new deadline. When an AI account bound to the miniVM could not be kept over the
  pause, the answer carries `msb.aiAccountsLost: [{"accountId", "reason"}]`: the miniVM runs
  without it. `resume` carries it too. Both take `egressCredentials` and answer with its state:
  see [Egress credentials](#egress-credentials).
- `DELETE` answers `204` once the deletion receipt is stored (at most 10 seconds), then `404`.

See [Lifecycle](https://onshore.sh/docs/guides/lifecycle) for timeouts, auto-pause and retention.

### Names and labels

A miniVM may have a `name` (1 to 64 characters, not unique) and up to 16 `labels` (key 1 to 63
of letters, digits, `.`, `_`, `-`, `/`, starting with a letter or digit; value at most 128
visible ASCII characters). Every member of your organization sees them: never put a secret or
personal data in them.

```bash
curl -s -X PATCH https://api.onshore.sh/v1/sandboxes/<sandbox-id> \
  -H "X-API-Key: $ONS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "<name>", "labels": {"<key>": "<value>", "<old-key>": null}}'
```

- `<name>` is the new name, `<key>` and `<value>` a label to set, `<old-key>` a label to remove.
- The body is a JSON merge patch: `null` clears the name or removes a label, `"labels": null`
  removes every label, and what you leave out is kept. It answers `200` with the miniVM as the
  list returns it.
- `400` when there is nothing to change or the result breaks a rule. `409` on a miniVM that has
  ended. Only the key that created the miniVM may change it; a self token gets `403`.
- Create takes `name` and `labels`, and the E2B metadata keys `name` and `msb.label.<key>`.
  The list filters with `label=<key>=<value>` and every item carries `name` and `labels`.

See [Name and label miniVMs](https://onshore.sh/docs/guides/names-and-labels).

### Egress at run time

```bash
curl -s https://api.onshore.sh/v2/sandboxes/<sandbox-id>/egress -H "X-API-Key: $ONS_API_KEY"
curl -s -X PATCH https://api.onshore.sh/v2/sandboxes/<sandbox-id>/egress \
  -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" \
  -d '{"add": ["api.example.com", "pypi"], "remove": ["<name>"]}'
```

`<name>` is a name to remove. Names are domain names (`*.domain` for subdomains) or preset names.

- `GET` answers `managed`, `mode` (`list` or `closed`), `allow` (the effective list), `template`,
  `added`, `removed`, `system` (hosts always kept: the API of a self token, the AI accounts'),
  `ceiling` (`names`, or `presets` when support limited your organization), `generation` and
  `pending` (a paused miniVM's change waits for its resume). A self token may read its own.
- `PATCH` takes `add` and `remove`, and answers `200` with the new view: once the host applied
  it on a running miniVM, at once with `pending: true` on a paused one. API keys only.
- `PUT /sandboxes/{id}/network` is E2B's `updateNetwork`: `{allowOut?, denyOut?,
  allow_internet_access?}` replaces the list relative to the template (no field: the template's
  list again), and answers `204`.
- At most 10 changes per minute per miniVM (`429 egress_rate_limit`) and 256 names, system hosts
  included. Open egress (`*`) is refused with `400 egress_open_unavailable`, IP addresses with
  `400`.
- `409`: `egress_system_host`, `egress_host_has_credential`, `egress_update_unsupported` (Hybrid
  pools, older runners), `egress_not_managed` (a miniVM created before this existed),
  `egress_open_unavailable` (an older miniVM that allows every name), `minivm_moving`. `503 egress_not_applied`: the change is stored and keeps being sent to the host.

Details and the error table: [Egress](https://onshore.sh/docs/guides/egress#change-egress-while-a-minivm-runs).

### Egress requests

Code in a miniVM asks for names with `msb-egress request`, which calls:

```bash
curl -s https://api.onshore.sh/v2/sandboxes/<sandbox-id>/egress/requests \
  -H "Authorization: Bearer $MSB_SELF_TOKEN" -H "Content-Type: application/json" \
  -d '{"domains": ["api.example.com"], "reason": "<reason>", "expiresIn": 900}'
```

`<reason>` is one line of 1 to 280 characters. `domains` holds 1 to 10 names or presets (no
`*.domain`). `expiresIn` is 60 to 3600 seconds (default 900). An API key may call it too.

- The answer is a request: `id` (`egr_…`), `sandboxID`, `domains`, `expanded` (the exact hosts
  each entry opens), `reason`, `state`, `createdAt`, `expiresAt`, and once decided `decidedBy`
  (`key`, `user` or `rule`), `approved`, `message`, `decidedAt`.
- `200` `approved` when every name is already allowed. `201` `refused` (`refusedReason:
  egress_presets_only`) under a presets ceiling. `201` `approved` when your auto-approve rules
  cover every name. Otherwise `201` `pending`.
- `GET /v2/sandboxes/{id}/egress/requests/{rid}?wait=<seconds>` reads one, waiting up to 30
  seconds for it to leave `pending`. A pending request past `expiresAt` reads `expired`.
- Limits per miniVM: one request per 10 seconds (`429 egress_rate_limit`), 10 pending
  (`429 egress_requests_pending`), 500 a day (`429 egress_request_limit`).

Decide with an API key (a self token gets `403 self_token_forbidden`):

```bash
curl -s "https://api.onshore.sh/v2/egress/requests?state=pending" -H "X-API-Key: $ONS_API_KEY"
curl -s -X POST https://api.onshore.sh/v2/egress/requests/<request-id>/approve \
  -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" -d '{"always": false}'
curl -s -X POST https://api.onshore.sh/v2/egress/requests/<request-id>/deny \
  -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" -d '{"message": "<message>"}'
```

- `<request-id>` is the request's `id`. `<message>` is told to the miniVM, at most 280
  characters.
- The list takes `state`, `sandbox` and `cursor` (100 a page, `nextCursor`).
- `approve` takes an optional `domains` subset, and widens the list exactly like a `PATCH`
  `add`. It answers `{request, egress}`. `always: true` also adds the names to your
  organization's auto-approve rules: only a key an owner created (`403 owners_only`).
- A request already decided or expired answers `409 egress_request_decided`.

The domains and reason come from inside the miniVM: treat them as untrusted. Requests are kept
30 days.

`GET /v2/sandboxes/{id}/egress/denials` answers `{denials: [{name, count, firstAt, lastAt}],
suppressed}`: the names the miniVM's DNS refused because its list does not cover them, at most
256, kept 30 days. `suppressed` counts the refusals not listed. A self token may read its own.

### Metrics

```bash
curl -s "https://api.onshore.sh/sandboxes/<sandbox-id>/metrics?start=<unix-seconds>" \
  -H "X-API-Key: $ONS_API_KEY"
```

`<unix-seconds>` is the start of the window, as a Unix timestamp. `end` is optional. You get at
most the newest 1000 samples, oldest first, from the last 7 days.
`GET /sandboxes/metrics?sandbox_ids=<id>,<id>` returns the newest sample of up to 100 running
miniVMs. See [Metrics](https://onshore.sh/docs/guides/metrics).

### Egress credentials

`egressCredentials` on a create is a list of up to 16 `{host, header, value}` entries. The
platform adds `header: value` to the miniVM's HTTPS requests to `host`. Code in the miniVM sends
the placeholder `msb-egress-credential` instead and never sees the value. At rest, the values
exist only inside the encrypted snapshot of a pause, deleted with it.

A pause keeps the values. When they are lost (a platform restart, a reset, a fork child, and the
other cases in [Egress](https://onshore.sh/docs/guides/egress#after-a-pause)), `GET /sandboxes/{id}` shows
`egressCredentials.state: "missing"`, and requests that need a value get
`503 msb_credential_unavailable`. Send the values again:

```bash
body=$(jq -n '{credentials: [{host: "api.example.com", header: "authorization", value: ("Bearer " + (env.EXAMPLE_TOKEN // "" | if . == "" then error("EXAMPLE_TOKEN is not set") else . end))}]}') &&
  printf '%s' "$body" | curl -s -X PUT https://api.onshore.sh/sandboxes/<sandbox-id>/egress-credentials \
    -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" --data @-
```

The examples need [`jq`](https://jqlang.org). `EXAMPLE_TOKEN` is an exported environment variable
holding the secret, read by `jq` from its environment; when it is unset or empty, `jq` stops with an
error and `curl` does not run. `printf` is a shell builtin and `curl` reads the body on stdin, so
the credential value never appears in the process list (the `X-API-Key` header still does). Each
entry names the host and header of a credential given at create or added to the running miniVM.
Details and limits:
[Egress](https://onshore.sh/docs/guides/egress#egress-credentials).

A resume or connect takes the same entries in its body:

```bash
body=$(jq -n '{egressCredentials: [{host: "api.example.com", header: "authorization", value: ("Bearer " + (env.EXAMPLE_TOKEN // "" | if . == "" then error("EXAMPLE_TOKEN is not set") else . end))}]}') &&
  printf '%s' "$body" | curl -s -X POST https://api.onshore.sh/v2/sandboxes/<sandbox-id>/connect \
    -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" --data @-
```

- The list replaces every value the miniVM holds, added ones included, before its code runs: list
  every credential you still need. `[]` clears them (the state becomes `missing`); leaving
  `egressCredentials` out keeps them.
- Where the server does not keep values, they are sent just after the resume, so the miniVM's code
  may briefly run without them.
- `POST /sandboxes/{id}/resume` takes the same field. On a Hybrid pool, send the values with
  the `PUT` above once the miniVM runs.
- For a miniVM with egress credentials, the answer carries
  `egressCredentials: {state, rules}`, as `GET /sandboxes/{id}` does.

To add a credential to a running miniVM, reached on a route only, send
`POST /v2/sandboxes/{id}/egress-credentials/routes` with an API key:

```bash
body=$(jq -n '{host: "api.example.com", header: "authorization", route: "example", value: ("Bearer " + (env.EXAMPLE_TOKEN // "" | if . == "" then error("EXAMPLE_TOKEN is not set") else . end))}') &&
  curl -s -X POST https://api.onshore.sh/v2/sandboxes/<sandbox-id>/egress-credentials/routes \
    -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" --data @- <<<"$body"
```

The example needs [`jq`](https://jqlang.org). `EXAMPLE_TOKEN` is an exported environment variable
holding the secret, read by `jq` from its environment; when it is unset or empty, `jq` stops with
an error and `curl` does not run. `curl` reads the body on stdin, so the value never appears in the
process list (the `X-API-Key` header still does). The value is at most 8 KiB.

It answers `201` with the rule and the miniVM's `egressCredentials`. Code in the miniVM then calls
`http://172.16.0.1:8080/r/example/`. `upstreamPrefix` (for example `/v1`) forwards to a path prefix
of the host. `DELETE /v2/sandboxes/{id}/egress-credentials/routes/<route>` removes it (`204`).
`GET /sandboxes/{id}` lists the rules with their `route`, `upstreamPrefix` and `origin` (`create` or
`runtime`). A paused miniVM answers `409`. `409 egress_route_pending` means an earlier add of the
same route that failed is still being cleaned up: retry in a minute.
`409 egress_credential_update_unsupported` means this deployment cannot add credentials to a
running miniVM: recreate it with `--egress-credential` (API `egressCredentials` at create).
Details and limits: [Add a credential to a running
miniVM](https://onshore.sh/docs/guides/egress#add-a-credential-to-a-running-minivm).

### Self token

A create with `selfToken: true` (and `autoPause: true`) lets code in the miniVM manage its own
lifetime. The miniVM gets `MSB_SELF_TOKEN`, `MSB_SELF_API` and `MSB_SANDBOX_ID` in its
environment. Sent as `Authorization: Bearer <token>`, the token works on these routes of that
miniVM only:

| Route                                                                                         | Rule                                                                                            |
| --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `GET /sandboxes/{self}`                                                                       | Its own details, without tokens.                                                                |
| `POST /sandboxes/{self}/timeout`                                                              | 1 to 3600 seconds, up to a maximum of 12 hours since the last action of an API key.             |
| `POST /sandboxes/{self}/pause`                                                                | Pause itself.                                                                                   |
| `GET /v2/sandboxes/{self}/egress`, `GET /v2/sandboxes/{self}/egress/denials`                  | Its egress list and the names it was refused.                                                   |
| `POST /v2/sandboxes/{self}/egress/requests`, `GET /v2/sandboxes/{self}/egress/requests/{rid}` | Ask for names and read its own requests. It never approves, denies or changes its list (`403`). |

One call per 10 seconds per miniVM, except reads of its egress list, requests and denials: 12 a
minute (`429 self_token_rate_limit`; long-poll with `wait`). `ons create --agents` turns it on for [agent runs](https://onshore.sh/docs/guides/agent-runs).

## Templates

Build templates with [`ons template`](https://onshore.sh/docs/guides/templates). These routes let you read and roll
them back.

| Route                                                   | What it does                                                                  |
| ------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `GET /v1/templates`                                     | Your organization's templates, with the current version.                      |
| `GET /v1/templates/{name}/versions`                     | Every version of a template, with its `envdVersion`.                          |
| `POST /v1/templates/{name}/rollback`                    | Make an older ready version current: `{"version": <number>}`.                 |
| `GET /v1/templates/{name}/versions/{number}/provenance` | The build record of a version.                                                |
| `POST /v1/templates/{name}/builds`                      | Create a build. `ons template build` computes its body for you.               |
| `GET /v1/builds/inputs`                                 | The pinned inputs `ons template build` needs to compute a build's digest.     |
| `POST /v1/builds/{id}/start`                            | Start a created build. `ons template build` calls it for you.                 |
| `GET /v1/builds/{id}`                                   | A build's status and phase.                                                   |
| `GET /v1/builds/{id}/logs`                              | A build's log, streamed as NDJSON while it runs.                              |
| `DELETE /templates/{id}`                                | Delete a template (E2B route, by id or name). Refused while a miniVM uses it. |

```bash
curl -s https://api.onshore.sh/v1/templates -H "X-API-Key: $ONS_API_KEY"
curl -s -X POST https://api.onshore.sh/v1/templates/<template-name>/rollback \
  -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" -d '{"version": 2}'
```

`<template-name>` is the `name` of your `minisandbox.yaml`.

Starting a build takes several calls with digests that `ons template build` computes for you. Use
`ons` to build.

## Agent runs

> **Note:** **Preview.** Agent runs work today. The API may still change.

An agent run is one coding agent session (Claude Code, Codex or OpenCode) in a miniVM. The API
keeps only ids, states, labels and cursors. Prompts, messages and results stay in the miniVM.
See [Agent runs](https://onshore.sh/docs/guides/agent-runs). 600 calls a minute per key.

| Route                            | What it does                                                                            |
| -------------------------------- | --------------------------------------------------------------------------------------- |
| `POST /v1/agent-runs`            | Create a run in a miniVM: `{sandboxID, harness, labels?, once?, permissions?, sinks?}`. |
| `GET /v1/agent-runs`             | List runs, newest first. Never wakes a miniVM.                                          |
| `GET /v1/agent-runs/{id}`        | One run.                                                                                |
| `POST /v1/agent-runs/wait`       | Wait (long poll) until runs reach a state.                                              |
| `GET /v1/agent-runs/events`      | Stream state changes as server-sent events.                                             |
| `POST /v1/agent-runs/{id}/close` | Mark a run `done`.                                                                      |

States: `starting`, `working`, `needs_input`, `idle`, then the final `done`, `failed` and
`canceled`. A failed run has a `reason` (`disk_full`, `oom`, `ai_auth`, `rate_limited`,
`model_error`, `harness_exit`, `start_timeout`, `protocol_error`, `vm_lost`); see
[Failure reasons](https://onshore.sh/docs/guides/agent-runs#failure-reasons). A `needs_input` run has a
`request: {id, kind}`, `kind` `permission`, `question` or `egress`.

A run also carries `paused: {reason}` while its organization's hold keeps the miniVM paused
(`out_of_credits` or `on_hold`), `stalled: {since}` while it works without activity,
`lastActivityAt` and `diskUsedPct` (the disk share at its last disk warning).

The miniVM must be created for runs (`ons create --agents`), else the create answers
`409 AGENTS_NOT_ENABLED`. At most 8 open runs per miniVM, 16 labels and 4 sinks per run. `once:
true` closes the run at its first idle. `sinks` names [result sinks](https://onshore.sh/docs/guides/agent-runs#post-results-on-a-pull-request)
of the template. An organization on hold or suspended cannot create a run: `402`
(`payment_method_required` or `organization_on_hold`) or `403 organization_suspended`.

### List

```bash
curl -s "https://api.onshore.sh/v1/agent-runs?label=batch=42&state=needs_input" \
  -H "X-API-Key: $ONS_API_KEY"
```

`label` is repeatable and every one must match. `limit` is 1 to 200 (default 50); pass `next`
from the answer as `after` for the next page.

### Wait

```bash
curl -s https://api.onshore.sh/v1/agent-runs/wait \
  -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" \
  -d '{"labels": {"batch": "42"}, "until": ["needs_input", "idle", "failed", "canceled", "paused"], "mode": "any", "timeout_s": 60}'
```

The answer is `{matched, cursor, timed_out}`. A run already in an `until` state matches at once.
A call holds at most about 40 seconds, then answers `timed_out: true`. Wait again with the
`cursor` it returned (`c_<n>`): a run that passed through an `until` state since that cursor
matches too, so you miss nothing. `mode` is `any` or `all`. A wait never wakes a miniVM.

Besides the states, `until` may name `paused` (a run its organization's hold paused, with
`paused: {reason}`) and `stalled` (a working run without activity, with `stalled: {since}`). A wait
that does not name `stalled` is not answered by a stall.

### Events

```bash
curl -sN "https://api.onshore.sh/v1/agent-runs/events?label=batch=42&cursor=<cursor>" \
  -H "X-API-Key: $ONS_API_KEY"
```

`<cursor>` is a cursor you got before (`c_<n>`); leave it out to start live. Each event has
`id: c_<n>`, `event: agent_run.<state>` and JSON data with `cursor`, `run`, `sandboxID`, `state`,
`reason`, `stopReason`, `request`, `labels` and `at`. Reconnect with `Last-Event-ID` to resume
after the last event you handled. `follow=false` ends the stream once it has caught up. A followed
stream ends after an hour. Events are kept 30 days.

`types` (comma-separated) picks event types. Besides the states it takes:

| Type                                                                                              | When                                                                                                      |
| ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `agent_run.paused`, `agent_run.resumed`                                                           | Its organization's hold paused the run's miniVM, then it runs again.                                      |
| `agent_run.stalled`                                                                               | A working run became stalled.                                                                             |
| `agent_run.disk_warning`                                                                          | The miniVM's disk passed 85 % used (`diskUsedPct`), at most once per run in 10 minutes.                   |
| `egress.requested`                                                                                | A miniVM asked for egress: `{sandboxID, run?, request, domains, reason, expiresAt}`.                      |
| `egress.changed`                                                                                  | A miniVM's egress changed: `{sandboxID, run?, generation, added, removed, actorKind, request?, pending}`. |
| `egress.denied`                                                                                   | A miniVM's egress refused a name: `{sandboxID, run?, name, count, firstAt, lastAt}`.                      |
| `devices.device_ready`, `devices.device_failed`, `devices.device_lost`, `devices.device_released` | [Cloud device](https://onshore.sh/docs/devices#events) events, where cloud devices are offered.           |

A stream gets the `egress.*` and `devices.*` events only when `types` names them. `sandbox=`
(comma-separated miniVM ids) keeps only those miniVMs' events.

At most 20 open waits and streams per key.

## AI accounts and GitHub

These routes back [`ons auth`](https://onshore.sh/docs/reference/cli) and `ons github`. Run those commands rather than
calling the routes: they read keys from a hidden prompt, never from the command line.

| Route                               | What it does                                                     |
| ----------------------------------- | ---------------------------------------------------------------- |
| `GET /v1/ai/accounts`               | Your AI accounts.                                                |
| `POST /v1/ai/accounts`              | Add an API key account.                                          |
| `POST /v1/ai/accounts/oauth`        | Start connecting a subscription in the browser (`ons auth add`). |
| `POST /v1/ai/accounts/oauth/{flow}` | Finish connecting it (`ons auth add`).                           |
| `DELETE /v1/ai/accounts/{id}`       | Revoke one.                                                      |
| `POST /v1/ai/accounts/{id}/default` | Make it a default.                                               |
| `GET /v1/ai/accounts/{id}/usage`    | Requests and statuses of the last 30 days.                       |
| `POST /v1/sandboxes/{id}/ai/block`  | Stop a miniVM's AI access at once.                               |
| `GET /v1/github`                    | The GitHub App installation and the repositories it reaches.     |
| `POST /v1/github/connect`           | Start connecting the GitHub App (`ons github`).                  |
| `GET /v1/github/connect/{flow}`     | Where a GitHub App connection stands (`ons github`).             |

## Webhooks

A webhook is an HTTPS endpoint of yours that onshore.sh calls when a run needs input, goes idle
or ends, and for the other event types you pick. Use it instead of holding a wait open. Webhooks
are API only: there is no `ons` command. 60 calls a minute per key, at most 10 webhooks per key.

| Route                           | What it does                                |
| ------------------------------- | ------------------------------------------- |
| `POST /v1/webhooks`             | Create a webhook endpoint.                  |
| `GET /v1/webhooks`              | List your webhook endpoints.                |
| `GET /v1/webhooks/{id}`         | One webhook endpoint.                       |
| `DELETE /v1/webhooks/{id}`      | Delete a webhook endpoint.                  |
| `POST /v1/webhooks/{id}/rotate` | Rotate a webhook endpoint's signing secret. |

### Create a webhook

```bash
curl -s https://api.onshore.sh/v1/webhooks \
  -H "X-API-Key: $ONS_API_KEY" -H "Content-Type: application/json" \
  -d '{"url": "<url>", "events": ["agent_run.needs_input", "agent_run.idle", "agent_run.failed", "agent_run.canceled"], "labels": {"batch": "42"}}'
```

`<url>` is your endpoint, for example `https://ci.example.com/onshore`.

- **`url`**: `https://`, on port 443 or 1024 to 65535, with no user, password or fragment, at
  most 2048 bytes. Its host must resolve to public addresses only.
- **`events`**: at most 32 of `agent_run.needs_input`, `idle`, `failed`, `canceled`, `done`,
  `paused`, `resumed`, `stalled`, `disk_warning` (the `agent_run.` prefix is optional),
  `egress.requested`, `egress.changed`, `egress.denied`, and, where cloud devices are offered,
  the [cloud device events](https://onshore.sh/docs/devices#events). Left out: the five run states `needs_input`, `idle`,
  `failed`, `canceled` and `done`.
- **`labels`**: optional. A run's labels must hold all of them.

The answer is `201` with the webhook's `id` (`wh_…`) and its signing `secret` (`whsec_…`). **The
secret is shown only here**: store it in your secret manager. Your webhooks get the events of the
runs and miniVMs of the key that created them. A revoked or expired key's webhooks get nothing
more.

### What you receive

Each delivery is a `POST` of `{"type": "<type>", "timestamp": "<time>", "data": {…}}`, where `<type>` is the event type and `<time>` the event's time (RFC 3339). `data` is the
event of the [event stream](#events): ids, state, reason, request `{id, kind}`, labels and cursor,
never the run's content. Read the result with `ons agent result`.

Requests are signed the [Standard Webhooks](https://www.standardwebhooks.com/) way, so any of its
libraries verifies them. The headers are `webhook-id`, `webhook-timestamp` and
`webhook-signature` (`v1,<signature>`: a base64 HMAC-SHA256 of `<id>.<timestamp>.<body>`, keyed
with the base64 key after `whsec_`).

- Refuse a bad signature and a timestamp more than 5 minutes off.
- Delivery is at least once and unordered. Drop a `webhook-id` you already handled, and order by
  the event's `cursor`.
- Answer with a `2xx`. Anything else, a redirect included, is retried after 5 s, 30 s, 2 min,
  10 min, 30 min, 1 h, 2 h, 4 h, then every 6 h, and given up 24 hours after the event.
- An attempt has 2 seconds to resolve your host and 5 seconds for the request. The answer's body
  is never read.

After an outage, catch up with the [event stream](#events) or `ons agent events --from <cursor>`,
where `<cursor>` is the last `cursor` you handled.

`GET /v1/webhooks/{id}` shows the deliveries of the last 30 days (`pending`, `delivered`,
`gaveUp`) and the last attempt with its `error`: `not_public`, `connect`, `timeout`, `status`,
`redirect`, `secret` or `key_revoked`.

### Rotate the secret

```bash
curl -s -X POST https://api.onshore.sh/v1/webhooks/<webhook-id>/rotate -H "X-API-Key: $ONS_API_KEY"
```

`<webhook-id>` is the webhook's `id` (`wh_…`). The answer holds the new `secret`. The previous one
keeps signing for 24 hours, so deliveries carry two signatures, space-separated, until
`previousSecretExpiresAt`. Another rotation in that time answers `409 ROTATION_IN_PROGRESS`.

## Cloud devices

[Cloud devices](https://onshore.sh/docs/devices) have their own routes under `/v1/ext/devices`. `ons device` and the
`device` command in the miniVM call them for you.

## What the API never returns

The API never carries your miniVM's commands, files or output. Those go straight to the miniVM,
at `https://<port>-<sandbox-id>.onshore.sh`, which the E2B SDKs and `ons` call for you.

Markdown version: https://onshore.sh/docs/reference/api.md
