# Sandbox API
Base URL: `https://sandbox.keln.ai` · Auth: `Authorization: Bearer sk-keln-…`
The Sandbox API lets you create isolated Linux sandboxes, run commands with streamed output, manage
files, and stop sandboxes when you finish. It uses the same API keys as the inference API.
See the [Sandboxes guides](../sandboxes/index.md) for examples. This reference documents the endpoints,
parameters, response fields, and error codes.
```bash
curl https://sandbox.keln.ai/v1/sandboxes \
-H "Authorization: Bearer $KELN_API_KEY" \
-H "Content-Type: application/json" \
-d '{"timeout_s": 600, "metadata": {"job": "nightly"}}'
```
## Conventions
- JSON fields use snake_case. Timestamps are integer Unix seconds.
- Unknown fields return `400 invalid_parameter`, identifying the field.
- Every error includes a `code`. See [Errors](#errors).
- Request bodies are limited to 1 MB (`413 body_too_large`). Streaming file uploads have no size limit.
- An `env` object can contain up to 64 KB across variable names and values.
- No request fails because a timer ran out. A slow start returns `202` with state `starting`, and
requests to a starting sandbox wait until it is running.
- You can still read, list, pause, and stop sandboxes if an API key or account is blocked. Keln stops
sandboxes associated with blocked keys.
- The API is additive. New fields, endpoints, enum values, and event types may appear. Clients should
ignore values they do not recognize.
### Idempotency
`POST /v1/sandboxes` and `POST /v1/sandboxes/{sandbox_id}/commands` take an
`Idempotency-Key` header containing 1 to 255 characters. Retrying with the same key and request body
returns the original result for 24 hours. Reusing the key with a different body returns
`409 idempotency_key_reused`. Retrying while the original request is still processing returns
`409 idempotency_key_in_use`.
For commands, keys are scoped to each sandbox. A retry doesn't run the command again. It returns the
existing command for background requests or replays events from the beginning or from `Last-Event-ID`.
### Streams
Streams use Server-Sent Events (SSE). Keln sends a `: ping` comment every 15 seconds when a stream
is idle. Each workspace can have up to 256 open streams (`429 too_many_streams`). Background commands
do not count toward this limit, but open terminal WebSockets do.
### Lists
`GET /v1/sandboxes` supports `limit` (1 to 100, default 20) and `after` for pagination. Pass the
previous response's `next_cursor` as `after`. Responses include `has_more` and `next_cursor`.
## Endpoints
| Endpoint | Does |
|---|---|
| [`POST /v1/sandboxes`](#create-a-sandbox) | Create a sandbox |
| [`GET /v1/sandboxes`](#list-sandboxes) | List sandboxes |
| [`GET /v1/sandboxes/{sandbox_id}`](#get-a-sandbox) | Get a sandbox |
| [`PATCH /v1/sandboxes/{sandbox_id}`](#change-network-or-ports) | Change a running sandbox's network or ports |
| [`DELETE /v1/sandboxes/{sandbox_id}`](#stop-a-sandbox) | Stop a sandbox |
| [`POST /v1/sandboxes/{sandbox_id}/timeout`](#set-a-new-expiry) | Set a new expiry |
| [`POST /v1/sandboxes/{sandbox_id}/pause`](#pause-a-sandbox) | Pause a sandbox |
| [`POST /v1/sandboxes/{sandbox_id}/resume`](#resume-a-sandbox) | Resume a paused sandbox |
| [`GET /v1/sandbox-templates`](#list-templates) | List templates |
| [`POST /v1/sandboxes/{sandbox_id}/snapshot`](#save-a-sandbox-as-an-image) | Save a running sandbox as an image |
| [`GET /v1/images`](#list-images) | List images |
| [`GET /v1/images/{image_id}`](#get-an-image) | Get an image |
| [`DELETE /v1/images/{image_id}`](#delete-an-image) | Delete an image |
| [`POST /v1/sandboxes/{sandbox_id}/commands`](#run-a-command) | Run a command |
| [`GET /v1/sandboxes/{sandbox_id}/commands`](#list-and-get-commands) | List commands |
| [`GET /v1/sandboxes/{sandbox_id}/commands/{command_id}`](#list-and-get-commands) | Get a command |
| [`DELETE /v1/sandboxes/{sandbox_id}/commands/{command_id}`](#kill-a-command) | Kill a command |
| [`GET /v1/sandboxes/{sandbox_id}/commands/{command_id}/events`](#attach-to-a-commands-events) | Attach to a command's events |
| [`POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/stdin`](#write-to-stdin) | Write to stdin |
| [`POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/stdin/close`](#close-stdin) | Close stdin |
| [`POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/signal`](#send-a-signal) | Send a signal |
| [`GET /v1/sandboxes/{sandbox_id}/files`](#read-a-file) | Read a file |
| [`PUT /v1/sandboxes/{sandbox_id}/files`](#write-a-file) | Write a file |
| [`DELETE /v1/sandboxes/{sandbox_id}/files`](#delete-a-file) | Delete a file |
| [`GET /v1/sandboxes/{sandbox_id}/files/list`](#list-a-directory) | List a directory |
| [`GET /v1/sandboxes/{sandbox_id}/files/stat`](#describe-a-path) | Describe a path |
| [`POST /v1/sandboxes/{sandbox_id}/files/mkdir`](#make-a-directory) | Make a directory |
| [`POST /v1/sandboxes/{sandbox_id}/files/move`](#move-or-rename) | Move or rename a file or directory |
| [`POST /v1/sandboxes/{sandbox_id}/terminals`](#start-a-terminal) | Start a terminal |
| [`GET /v1/sandboxes/{sandbox_id}/terminals`](#list-and-get-terminals) | List terminals |
| [`GET /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}`](#list-and-get-terminals) | Get a terminal |
| [`DELETE /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}`](#end-a-terminal) | End a terminal |
| [`POST /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}/resize`](#resize-a-terminal) | Resize a terminal |
| [`GET /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}/ws`](#attach-to-a-terminal) | Attach to a terminal over WebSocket |
## Sandboxes
### The sandbox object
```json
{
"id": "sbx_4k2v9q0m7c1x8z5n3b6d",
"object": "sandbox",
"state": "running",
"template": "base",
"cpu": 2,
"memory_mb": 2048,
"disk_mb": 10240,
"created_at": 1793740800,
"started_at": 1793740801,
"expires_at": 1793741400,
"ended_at": null,
"end_reason": null,
"paused_at": null,
"metadata": { "job": "nightly" },
"network": { "internet": true },
"ports": [],
"port_token": null
}
```
| Field | Meaning |
|---|---|
| `id` | `sbx_` and 20 characters. |
| `state` | `starting`, `running`, `paused` or `stopped`. Keln may add new states. |
| `template`, `cpu`, `memory_mb`, `disk_mb` | What the sandbox started from, and its size in vCPUs and MiB. |
| `created_at` | When you created it. |
| `started_at` | When it began running, or `null`. Billing starts here. |
| `expires_at` | When it stops. |
| `ended_at` | When it stopped, or `null`. |
| `end_reason` | Why it stopped, or `null`: `deleted`, `timeout`, `out_of_memory`, `insufficient_balance`, `suspended`, `budget_exhausted`, `pause_expired` or `failed`. Keln may add new reasons. |
| `paused_at` | When it was paused, while it is `paused`. Billing stopped here. |
| `metadata` | Your labels, returned as given. |
| `network` | Its [network policy](#the-network-object). |
| `ports` | Its open ports, each with `port`, `public` and `url`. |
| `port_token` | The secret a private port's requests carry as `X-Keln-Port-Token`. It is set once the sandbox has a port, and it stays the same for the sandbox's life. |
### Create a sandbox
`POST /v1/sandboxes` creates a sandbox from a template, or from one of your [images](#images). The request body is optional. Your balance
must cover the first 5 minutes at the selected size. Billing begins when the sandbox is running.
| Field | Default | Contract |
|---|---|---|
| `template` | `base` | A template from [`GET /v1/sandbox-templates`](#list-templates). |
| `image` | none | One of your `ready` [images](#images), instead of `template`. The sandbox starts with its files, at its size unless `cpu` or `memory_mb` is set. |
| `cpu` | the template's size | vCPUs, 1 to 4. |
| `memory_mb` | the template's size | Memory in MiB, 1,024 to 16,384, and 1,024 to 8,192 per vCPU. |
| `timeout_s` | 300 | Seconds from creation until the sandbox stops, 1 to 86,400. |
| `env` | none | Environment variables. Every command gets them, and a command's own `env` wins. |
| `metadata` | none | Your labels, usable as a list filter. Up to 50 keys, keys up to 40 characters, values up to 500. |
| `network` | internet on | A [network object](#the-network-object). |
The API usually returns `201` with state `running`. If startup takes longer, it returns `202` with
state `starting`. You can poll `GET /v1/sandboxes/{sandbox_id}` or send a command or file request,
which waits until the sandbox is ready.
### The network object
| Field | Default | Contract |
|---|---|---|
| `internet` | `true` | Outbound internet access, DNS included. `false` blocks everything not in `allow`. |
| `allow` | none | Domains, IPv4 addresses or IPv4 CIDRs reachable even with `internet` set to `false`. |
| `deny` | none | Domains, IPv4 addresses or IPv4 CIDRs that are always blocked. `deny` wins over `allow`. |
### List sandboxes
`GET /v1/sandboxes` returns sandboxes newest first. By default, it includes sandboxes in the
`starting`, `running`, and `paused` states.
| Query parameter | Contract |
|---|---|
| `state` | Filter by state. Repeat it or comma-separate it for several. |
| `metadata[key]=value` | Filter by metadata. Several filters must all match. |
| `limit` | 1 to 100, default 20. |
| `after` | The `next_cursor` of the previous page. |
```bash
curl --get https://sandbox.keln.ai/v1/sandboxes \
-H "Authorization: Bearer $KELN_API_KEY" \
--data-urlencode "metadata[job]=nightly" \
--data-urlencode "state=running,paused"
```
```json
{ "object": "list", "data": [], "has_more": false, "next_cursor": null }
```
### Get a sandbox
`GET /v1/sandboxes/{sandbox_id}` returns the sandbox, including stopped sandboxes with `ended_at`
and `end_reason` populated.
### Change network or ports
`PATCH /v1/sandboxes/{sandbox_id}` replaces the network configuration, the ports list, or both, while
the sandbox is running.
Include at least one of these fields. If the sandbox is starting, the request waits until it is
running. The response contains the updated sandbox.
| Field | Contract |
|---|---|
| `network` | A whole [network object](#the-network-object). Its missing fields take their defaults. A network change returns once the new policy is in force for new connections, about a second after the call. |
| `ports` | The complete list of open ports. Each entry has `port` (1 to 65535, required) and `public` (default `false`). `[]` closes every port. Port 9501 is reserved. A newly opened port is available within a second. A change that closes a port or makes it private returns once it is in force, about a second after the call. |
### Stop a sandbox
`DELETE /v1/sandboxes/{sandbox_id}` stops the sandbox, deletes its contents, and ends billing.
Deleting an already stopped sandbox returns `200` without changing it.
### Set a new expiry
`POST /v1/sandboxes/{sandbox_id}/timeout` sets `expires_at` to now plus `timeout_s`, shorter or longer
than before. A sandbox runs at most 24 hours from `created_at`, or from its last resume. A timeout past
that returns `400 invalid_parameter` and names the latest allowed expiry. A paused sandbox returns
`409 sandbox_paused`: its resume sets the next expiry.
```json
{ "timeout_s": 1800 }
```
### Pause a sandbox
`POST /v1/sandboxes/{sandbox_id}/pause` pauses the sandbox with its memory, running processes and files
kept, until it is resumed. Billing stops at this moment. A paused sandbox holds no place in the
workspace's concurrency limit. Keln keeps it for 30 days, then stops it with `end_reason`
`pause_expired`. A workspace keeps at most 100 sandboxes paused (`429 paused_limit`).
While it is paused, calls to it return `409 sandbox_paused`, and its preview ports stop responding. Keln
cuts open network connections, terminals and command streams, and they do not survive the pause.
Running commands carry on from where they were once it is resumed.
Pausing takes about a second. The first pause of a sandbox can take about 2 seconds for each GiB of
memory. Keln waits for a starting sandbox. Pausing a paused sandbox returns `200` with it unchanged. A
blocked key or a suspended account may still pause, as it may stop.
### Resume a sandbox
`POST /v1/sandboxes/{sandbox_id}/resume` runs a paused sandbox again under the same id, as it was when
it was paused. Billing starts again when it runs. It takes a place in the workspace's concurrency limit
again (`429 concurrency_limit`), and the wallet must cover its first 5 minutes
(`402 insufficient_balance`).
| Field | Default | Contract |
|---|---|---|
| `timeout_s` | a create's default | 1 to 86,400. `expires_at` stays, or moves to now plus `timeout_s` when that is later. |
A sandbox runs at most 24 hours from its last resume. Keln returns `200` with the sandbox `running`,
usually within a second, or else `202` with it `starting`. Resuming a running sandbox returns `200`
with it unchanged.
### List templates
`GET /v1/sandbox-templates` returns available templates and their default resource sizes.
```json
{
"object": "list",
"data": [
{ "object": "sandbox_template", "name": "base", "cpu": 2, "memory_mb": 2048, "disk_mb": 10240 }
]
}
```
## Images
An image saves a running sandbox's disk so new sandboxes start from it. See [Images](../sandboxes/images.md) for
what an image keeps, pricing and limits.
### The image object
```json
{
"id": "img_7q2m4x9c1v8b0n5k3j6h",
"object": "image",
"state": "ready",
"sandbox_id": "sbx_4k2v9q0m7c1x8z5n3b6d",
"template": "base",
"cpu": 2,
"memory_mb": 2048,
"disk_mb": 10240,
"size_bytes": 1088902505,
"created_at": 1794535200,
"ready_at": 1794535203,
"error": null,
"metadata": { "name": "data-tools" }
}
```
| Field | Description |
|---|---|
| `state` | `creating`, `ready` or `failed`. `deleted` appears only in the answer to a delete. |
| `sandbox_id` | The sandbox it was saved from. |
| `template` | The template that sandbox started from. |
| `cpu`, `memory_mb`, `disk_mb` | The default size of a sandbox started from it. |
| `size_bytes` | Its stored size, which storage is billed on; `null` until `ready`. |
| `error` | For a failed image, `{code, message}`: `snapshot_failed` or `sandbox_stopped`. |
### Save a sandbox as an image
`POST /v1/sandboxes/{sandbox_id}/snapshot` saves a running sandbox and answers `202` with the image `creating`. The
body is optional: `{"metadata": {...}}`. It accepts `Idempotency-Key`. Start sandboxes from a `ready` image with
`image` on [Create a sandbox](#create-a-sandbox).
### List images
`GET /v1/images` lists images newest first. Without `state`, it returns `creating`, `ready` and `failed` images;
`state` filters them, comma-separated. It pages like the other [lists](#lists).
### Get an image
`GET /v1/images/{image_id}` returns the image.
### Delete an image
`DELETE /v1/images/{image_id}` deletes the image and answers `200` with it `deleted`. Storage billing ends at once.
Sandboxes started from it keep running. After the delete, the image answers `404 image_not_found`.
## Commands
### The command object
```json
{
"id": "cmd_8x1c4v7b2n5m9k3j6h0g",
"object": "command",
"sandbox_id": "sbx_4k2v9q0m7c1x8z5n3b6d",
"state": "exited",
"argv": ["bash", "-lc", "echo hello"],
"exit_code": 0,
"signal": null,
"oom_killed": false,
"stdin": false,
"started_at": 1793740802,
"ended_at": 1793740802
}
```
| Field | Meaning |
|---|---|
| `id` | `cmd_` and 20 characters. |
| `state` | `running` or `exited`. |
| `argv` | What ran. A `command` shows as `["bash", "-lc", "<command>"]`. |
| `exit_code` | The exit code, or `null`. |
| `signal` | The number of the signal that ended it, if one did. |
| `oom_killed` | Whether it was killed for using too much memory. |
| `stdin` | Whether stdin is open for writing. |
| `started_at`, `ended_at` | Unix seconds. `ended_at` is `null` while it runs. |
### Run a command
`POST /v1/sandboxes/{sandbox_id}/commands` executes `command` through `bash -lc` or runs `argv`
directly. Provide exactly one of these fields.
| Field | Default | Contract |
|---|---|---|
| `command` | | A shell command line, run as `bash -lc <command>`. |
| `argv` | | A program and its arguments, run directly. |
| `cwd` | the user's home | Working directory, absolute. |
| `env` | none | Environment variables. They win over the sandbox's `env`. |
| `user` | `user` | `user` or `root`. |
| `timeout_s` | none | Maximum running time in seconds, at least 1. When it's reached, the command is stopped. Pausing the sandbox also pauses the timer. Without a timeout, the command runs until it exits or the sandbox stops. |
| `stdin` | `false` | Keep stdin open for writing. Otherwise stdin is closed. |
| `background` | `false` | Return `201` with the command at once instead of streaming its events. |
By default, the API returns `200` with an event stream (`text/event-stream`). The command keeps running if
the stream drops. The command's id is also in the `Keln-Command-Id` response header, so a stream that
drops before `started` can be resumed. Keln refuses a streamed command past the workspace's open-stream
limit before it starts (`429 too_many_streams`).
A `cwd` that is missing or is not a directory returns `400 invalid_parameter` with `param: cwd`. An
`argv` program that is missing or not permitted returns the same code with `param: argv`. Through
`command`, a missing program is bash's exit code 127.
### Command events
Each event has an `event` name and JSON `data`. `id` is the event's position in the command's stream
(1, 2, 3…), stable across reattaches; an `error` event has none. Keln may add new event types, so skip the
ones you do not know.
| Event | `data` | Meaning |
|---|---|---|
| `started` | `command_id`, `pid` | The command started. |
| `stdout`, `stderr` | `data`, `ts` | Output bytes as base64, and the capture time in Unix milliseconds. |
| `exit` | `exit_code`, `signal`, `oom_killed` | The command ended. |
| `error` | `error` | A failure after the stream began, as the same object as an HTTP error. It ends the stream, and the command itself may still be running. |
```text
id: 1
event: started
data: {"command_id": "cmd_8x1c4v7b2n5m9k3j6h0g", "pid": 41}
id: 2
event: stdout
data: {"data": "aGVsbG8K", "ts": 1793740800123}
id: 3
event: exit
data: {"exit_code": 0, "signal": null, "oom_killed": false}
```
Output arrives line by line. [Output format](../sandboxes/commands.md#output-format) says what that
changes.
### List and get commands
`GET /v1/sandboxes/{sandbox_id}/commands` lists running and exited commands, newest first, as
`{"object": "list", "data": [...]}`.
`GET /v1/sandboxes/{sandbox_id}/commands/{command_id}` returns one command.
### Kill a command
`DELETE /v1/sandboxes/{sandbox_id}/commands/{command_id}` sends SIGKILL and returns the command. Killing
an exited command returns `200` with it unchanged.
### Attach to a command's events
`GET /v1/sandboxes/{sandbox_id}/commands/{command_id}/events` returns the same stream as a run, from the
start, or after the event named by the `Last-Event-ID` header. For an exited command, the stream
replays its events and ends with `exit`.
### Write to stdin
`POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/stdin` writes the raw request body
(`application/octet-stream`) to the command's stdin, and returns `204`. It needs `stdin: true` at start.
### Close stdin
`POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/stdin/close` sends end-of-file and returns `204`.
Closing a closed stdin also returns `204`.
### Send a signal
`POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/signal` sends a signal and returns the command.
| Field | Contract |
|---|---|
| `signal` | A number from 1 to 64, or a name: `SIGHUP`, `SIGINT`, `SIGQUIT`, `SIGKILL`, `SIGUSR1`, `SIGUSR2`, `SIGTERM`, `SIGCONT`, `SIGSTOP` or `SIGTSTP`, with or without the `SIG` prefix. |
## Files
Every path is absolute. The read, write, delete, list and stat calls take it in the `path` query
parameter, so URL-encode it. `mkdir` and `move` take paths in the JSON body.
### Read a file
`GET /v1/sandboxes/{sandbox_id}/files?path=` streams the file's bytes
(`application/octet-stream`).
### Write a file
`PUT /v1/sandboxes/{sandbox_id}/files?path=` writes the raw request body to the file, streamed. Keln
replaces an existing file. A directory at the path returns `409 is_a_directory`.
```json
{ "object": "file", "path": "/home/user/main.py", "size": 12 }
```
`size` is the number of bytes written.
### Delete a file
`DELETE /v1/sandboxes/{sandbox_id}/files?path=` deletes a file or a symbolic link, and returns `204`. It
removes a link, not what it points to. A directory, empty or not, returns `409 is_a_directory`. Delete
it with a command (`rm -r`).
### List a directory
`GET /v1/sandboxes/{sandbox_id}/files/list?path=` returns the directory entries.
```json
{
"object": "list",
"path": "/home/user",
"data": [
{ "name": "main.py", "path": "/home/user/main.py", "type": "file", "size": 12, "modified_at": 1793740900 }
]
}
```
`type` is `file` or `dir`. A symbolic link lists as `file`.
### Describe a path
`GET /v1/sandboxes/{sandbox_id}/files/stat?path=` returns information about the path, following
symbolic links. A missing path returns `404 file_not_found`.
```json
{ "object": "file_stat", "path": "/home/user/main.py", "type": "file", "size": 12, "modified_at": 1793740900 }
```
`type` is `file`, `dir` or `other` (a device, socket or pipe). `size` is in bytes, for a file.
### Make a directory
`POST /v1/sandboxes/{sandbox_id}/files/mkdir` makes the directory and any missing parents, as the
sandbox's user, and returns it in the same shape as `stat`. If the directory already exists, the API
returns its current information. A file in the way returns `409 not_a_directory`.
| Field | Contract |
|---|---|
| `path` | Required. Absolute. |
### Move or rename
`POST /v1/sandboxes/{sandbox_id}/files/move` moves `from` to `to`, as the sandbox's user, and returns
what is now at `to` in the same shape as `stat`.
| Field | Default | Contract |
|---|---|---|
| `from` | | Required. Absolute. |
| `to` | | Required. Absolute. The new path itself, not a directory to move into. |
| `overwrite` | `false` | Replace an existing `to`. Non-empty directories cannot be overwritten. |
An existing `to` returns `409 path_exists` unless `overwrite` is `true`. The parent directory of `to`
must exist. Otherwise the call returns `404 file_not_found` with `param: to`.
## Terminals
### The terminal object
```json
{
"id": "term_0123456789abcdefghij",
"object": "terminal",
"sandbox_id": "sbx_4k2v9q0m7c1x8z5n3b6d",
"state": "running",
"cols": 80,
"rows": 24,
"exit_code": null,
"created_at": 1793740900,
"ended_at": null
}
```
### Start a terminal
`POST /v1/sandboxes/{sandbox_id}/terminals` starts a program on a pseudo-terminal, as the sandbox's
user. `sudo` gives root. The body is optional, and the response is `201` with the terminal.
| Field | Default | Contract |
|---|---|---|
| `command` | | A shell line, run through `bash -lc`. |
| `argv` | | The program and its arguments, run directly. |
| `cwd` | the user's home | Absolute. |
| `env` | none | Environment variables. |
| `cols` | 80 | 1 to 1000. |
| `rows` | 24 | 1 to 1000. |
Send `command`, or `argv`, or neither for a login shell.
### List and get terminals
`GET /v1/sandboxes/{sandbox_id}/terminals` returns the sandbox's terminals, oldest first, as
`{"object": "list", "data": [...]}`. `GET /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}` returns
one terminal.
### Resize a terminal
`POST /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}/resize` takes `cols` and `rows`, both required,
1 to 1000. It does the same as a resize frame on the socket, and returns the terminal at its new size.
### End a terminal
`DELETE /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}` ends the terminal's program and returns the
terminal. Ending an exited terminal returns `200` with it unchanged.
### Attach to a terminal
`GET /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}/ws` is a WebSocket upgrade, authorized like
every call with `Authorization: Bearer`. Every message is a binary frame whose first byte says what it
is:
| Direction | First byte | Rest of the frame |
|---|---|---|
| Client to server | `0x00` | Input bytes. |
| Client to server | `0x01` | The new size: columns and rows, each a big-endian 16-bit integer. |
| Server to client | `0x00` | Output bytes. |
| Server to client | `0x03` | The exit code, a big-endian 32-bit integer. The server then closes the socket. |
Keln ignores text frames and unknown first bytes. You can attach to a terminal again after a disconnect;
to receive all of a program's output, keep a socket attached. An open socket counts
toward the workspace's 256 open streams.
## Preview URLs
Each open port is available at its `url`, `https://<port>-<id without sbx_>.keln.run`, for any HTTP method
and for WebSocket upgrades. A public port is open to anyone with the URL. A private port, the default,
needs the sandbox's `port_token` in an `X-Keln-Port-Token` header. The `Authorization` header isn't
forwarded to the program on the port.
A sandbox's previews hold at most 256 connections open at once, and one client address at most 64
(`429 too_many_connections`). A preview socket's messages are at most 1 MiB each way.
## Errors
All errors use the following format. Use `code` to identify the specific error and `type` for its
category. `message` provides a human-readable explanation, and `param` identifies the affected
request field when applicable.
```json
{
"error": {
"type": "invalid_request_error",
"code": "invalid_parameter",
"message": "Unknown field `timeout`.",
"param": "timeout"
}
}
```
The types are `invalid_request_error`, `authentication_error`, `permission_error`, `not_found_error`,
`conflict_error`, `payment_required_error`, `rate_limit_error`, `api_error` and `unavailable_error`. Keln
may add new codes and types.
| Status | `code` | Meaning |
|---|---|---|
| `400` | `invalid_json` | The body is not valid JSON. |
| `400` | `invalid_parameter` | A field is wrong or unknown. `param` names it. |
| `400` | `unknown_template` | No such template. |
| `400` | `invalid_path` | A path is missing or not absolute. |
| `400` | `unsupported_parameter` | The request names a field the Sandbox API doesn't support. `param` names it. |
| `401` | `invalid_api_key` | The API key is missing or invalid. |
| `401` | `invalid_port_token` | A preview URL's private port needs a valid `X-Keln-Port-Token`. |
| `402` | `insufficient_balance` | The balance does not cover the first 5 minutes of this sandbox. |
| `402` | `key_budget_exhausted` | This API key's budget for the period is spent. |
| `403` | `key_source_not_allowed` | This key may not be used from this address. |
| `403` | `account_suspended` | The account is suspended. |
| `403` | `key_suspended` | The key is suspended. |
| `403` | `sandboxes_not_enabled` | Sandboxes are not enabled for this workspace. |
| `403` | `images_not_enabled` | Images are not enabled for this workspace. |
| `403` | `permission_denied` | The sandbox's user may not access the file's path. |
| `404` | `sandbox_not_found` | No such sandbox for this workspace. |
| `404` | `image_not_found` | No such image for this workspace. |
| `404` | `command_not_found` | No such command in this sandbox. |
| `404` | `file_not_found` | The path doesn't exist. |
| `404` | `terminal_not_found` | No such terminal in this sandbox. |
| `404` | `route_not_found` | No such endpoint. |
| `404` | `port_not_found` | A preview URL's sandbox is not running, or it does not expose this port. |
| `409` | `sandbox_not_running` | The sandbox has stopped, or (saving an image) it is paused. |
| `409` | `snapshot_in_progress` | An image of this sandbox is still being saved: another save or a pause waits for it. |
| `409` | `image_not_ready` | The image is still `creating`, or it failed. |
| `409` | `sandbox_paused` | The sandbox is paused. Resume it first. |
| `409` | `sandbox_resuming` | The sandbox is resuming. Pause it once it runs. |
| `409` | `idempotency_key_reused` | This key was used with a different body. |
| `409` | `idempotency_key_in_use` | A request with this key is still running. |
| `409` | `stdin_not_open` | The command's stdin is not open. |
| `409` | `command_exited` | The command has exited. |
| `409` | `not_a_directory` | A file is in the way of a directory. |
| `409` | `is_a_directory` | The path is a directory. |
| `409` | `path_exists` | `to` exists, and `overwrite` is not `true`. |
| `413` | `body_too_large` | The body is over 1 MB. Use `PUT …/files` for file uploads. |
| `429` | `rate_limited` | Too many requests. |
| `429` | `concurrency_limit` | The workspace has its limit of running sandboxes. |
| `429` | `daily_limit` | The workspace has used its sandbox time for the day. |
| `429` | `too_many_streams` | The workspace has 256 streams open. |
| `429` | `too_many_terminals` | This sandbox has as many terminals as it can run. |
| `429` | `paused_limit` | The workspace has 100 paused sandboxes. |
| `429` | `image_limit` | The workspace holds 20 images that are `creating` or `ready`. |
| `429` | `too_many_connections` | A preview has reached its connection limit. |
| `502` | `backend_error` | The call didn't complete. Safe to retry. |
| `503` | `temporarily_unavailable` | Temporarily unavailable. Safe to retry. |
| `503` | `capacity_unavailable` | The sandbox can't start right now. Safe to retry. |
| `503` | `sandboxes_disabled` | Starting and running sandboxes is unavailable right now. Reading, listing and stopping still work. |
| `503` | `port_unreachable` | A preview URL's port did not respond. |
| `503` | `pause_failed` | The sandbox could not be paused. It keeps running. |
| `503` | `resume_failed` | The sandbox could not be resumed. It stays paused. |
`429` and `503` responses include a `Retry-After` header when a retry time is available.
## Limits
See the [Sandboxes overview](../sandboxes/index.md#limits) for all limits.
Sandbox API
Base URL: https://sandbox.keln.ai · Auth: Authorization: Bearer sk-keln-…
The Sandbox API lets you create isolated Linux sandboxes, run commands with streamed output, manage
files, and stop sandboxes when you finish. It uses the same API keys as the inference API.
See the Sandboxes guides for examples. This reference documents the endpoints,
parameters, response fields, and error codes.
Request bodies are limited to 1 MB (413 body_too_large). Streaming file uploads have no size limit.
An env object can contain up to 64 KB across variable names and values.
No request fails because a timer ran out. A slow start returns 202 with state starting, and
requests to a starting sandbox wait until it is running.
You can still read, list, pause, and stop sandboxes if an API key or account is blocked. Keln stops
sandboxes associated with blocked keys.
The API is additive. New fields, endpoints, enum values, and event types may appear. Clients should
ignore values they do not recognize.
Idempotency
POST /v1/sandboxes and POST /v1/sandboxes/{sandbox_id}/commands take an
Idempotency-Key header containing 1 to 255 characters. Retrying with the same key and request body
returns the original result for 24 hours. Reusing the key with a different body returns
409 idempotency_key_reused. Retrying while the original request is still processing returns
409 idempotency_key_in_use.
For commands, keys are scoped to each sandbox. A retry doesn't run the command again. It returns the
existing command for background requests or replays events from the beginning or from Last-Event-ID.
Streams
Streams use Server-Sent Events (SSE). Keln sends a : ping comment every 15 seconds when a stream
is idle. Each workspace can have up to 256 open streams (429 too_many_streams). Background commands
do not count toward this limit, but open terminal WebSockets do.
Lists
GET /v1/sandboxes supports limit (1 to 100, default 20) and after for pagination. Pass the
previous response's next_cursor as after. Responses include has_more and next_cursor.
starting, running, paused or stopped. Keln may add new states.
template, cpu, memory_mb, disk_mb
What the sandbox started from, and its size in vCPUs and MiB.
created_at
When you created it.
started_at
When it began running, or null. Billing starts here.
expires_at
When it stops.
ended_at
When it stopped, or null.
end_reason
Why it stopped, or null: deleted, timeout, out_of_memory, insufficient_balance, suspended, budget_exhausted, pause_expired or failed. Keln may add new reasons.
paused_at
When it was paused, while it is paused. Billing stopped here.
The secret a private port's requests carry as X-Keln-Port-Token. It is set once the sandbox has a port, and it stays the same for the sandbox's life.
Create a sandbox
POST /v1/sandboxes creates a sandbox from a template, or from one of your images. The request body is optional. Your balance
must cover the first 5 minutes at the selected size. Billing begins when the sandbox is running.
The API usually returns 201 with state running. If startup takes longer, it returns 202 with
state starting. You can poll GET /v1/sandboxes/{sandbox_id} or send a command or file request,
which waits until the sandbox is ready.
The network object
Field
Default
Contract
internet
true
Outbound internet access, DNS included. false blocks everything not in allow.
allow
none
Domains, IPv4 addresses or IPv4 CIDRs reachable even with internet set to false.
deny
none
Domains, IPv4 addresses or IPv4 CIDRs that are always blocked. deny wins over allow.
List sandboxes
GET /v1/sandboxes returns sandboxes newest first. By default, it includes sandboxes in the
starting, running, and paused states.
Query parameter
Contract
state
Filter by state. Repeat it or comma-separate it for several.
metadata[key]=value
Filter by metadata. Several filters must all match.
GET /v1/sandboxes/{sandbox_id} returns the sandbox, including stopped sandboxes with ended_at
and end_reason populated.
Change network or ports
PATCH /v1/sandboxes/{sandbox_id} replaces the network configuration, the ports list, or both, while
the sandbox is running.
Include at least one of these fields. If the sandbox is starting, the request waits until it is
running. The response contains the updated sandbox.
Field
Contract
network
A whole network object. Its missing fields take their defaults. A network change returns once the new policy is in force for new connections, about a second after the call.
ports
The complete list of open ports. Each entry has port (1 to 65535, required) and public (default false). [] closes every port. Port 9501 is reserved. A newly opened port is available within a second. A change that closes a port or makes it private returns once it is in force, about a second after the call.
Stop a sandbox
DELETE /v1/sandboxes/{sandbox_id} stops the sandbox, deletes its contents, and ends billing.
Deleting an already stopped sandbox returns 200 without changing it.
Set a new expiry
POST /v1/sandboxes/{sandbox_id}/timeout sets expires_at to now plus timeout_s, shorter or longer
than before. A sandbox runs at most 24 hours from created_at, or from its last resume. A timeout past
that returns 400 invalid_parameter and names the latest allowed expiry. A paused sandbox returns
409 sandbox_paused: its resume sets the next expiry.
{"timeout_s":1800}
Pause a sandbox
POST /v1/sandboxes/{sandbox_id}/pause pauses the sandbox with its memory, running processes and files
kept, until it is resumed. Billing stops at this moment. A paused sandbox holds no place in the
workspace's concurrency limit. Keln keeps it for 30 days, then stops it with end_reasonpause_expired. A workspace keeps at most 100 sandboxes paused (429 paused_limit).
While it is paused, calls to it return 409 sandbox_paused, and its preview ports stop responding. Keln
cuts open network connections, terminals and command streams, and they do not survive the pause.
Running commands carry on from where they were once it is resumed.
Pausing takes about a second. The first pause of a sandbox can take about 2 seconds for each GiB of
memory. Keln waits for a starting sandbox. Pausing a paused sandbox returns 200 with it unchanged. A
blocked key or a suspended account may still pause, as it may stop.
Resume a sandbox
POST /v1/sandboxes/{sandbox_id}/resume runs a paused sandbox again under the same id, as it was when
it was paused. Billing starts again when it runs. It takes a place in the workspace's concurrency limit
again (429 concurrency_limit), and the wallet must cover its first 5 minutes
(402 insufficient_balance).
Field
Default
Contract
timeout_s
a create's default
1 to 86,400. expires_at stays, or moves to now plus timeout_s when that is later.
A sandbox runs at most 24 hours from its last resume. Keln returns 200 with the sandbox running,
usually within a second, or else 202 with it starting. Resuming a running sandbox returns 200
with it unchanged.
List templates
GET /v1/sandbox-templates returns available templates and their default resource sizes.
creating, ready or failed. deleted appears only in the answer to a delete.
sandbox_id
The sandbox it was saved from.
template
The template that sandbox started from.
cpu, memory_mb, disk_mb
The default size of a sandbox started from it.
size_bytes
Its stored size, which storage is billed on; null until ready.
error
For a failed image, {code, message}: snapshot_failed or sandbox_stopped.
Save a sandbox as an image
POST /v1/sandboxes/{sandbox_id}/snapshot saves a running sandbox and answers 202 with the image creating. The
body is optional: {"metadata": {...}}. It accepts Idempotency-Key. Start sandboxes from a ready image with
image on Create a sandbox.
List images
GET /v1/images lists images newest first. Without state, it returns creating, ready and failed images;
state filters them, comma-separated. It pages like the other lists.
Get an image
GET /v1/images/{image_id} returns the image.
Delete an image
DELETE /v1/images/{image_id} deletes the image and answers 200 with it deleted. Storage billing ends at once.
Sandboxes started from it keep running. After the delete, the image answers 404 image_not_found.
What ran. A command shows as ["bash", "-lc", "<command>"].
exit_code
The exit code, or null.
signal
The number of the signal that ended it, if one did.
oom_killed
Whether it was killed for using too much memory.
stdin
Whether stdin is open for writing.
started_at, ended_at
Unix seconds. ended_at is null while it runs.
Run a command
POST /v1/sandboxes/{sandbox_id}/commands executes command through bash -lc or runs argv
directly. Provide exactly one of these fields.
Field
Default
Contract
command
A shell command line, run as bash -lc <command>.
argv
A program and its arguments, run directly.
cwd
the user's home
Working directory, absolute.
env
none
Environment variables. They win over the sandbox's env.
user
user
user or root.
timeout_s
none
Maximum running time in seconds, at least 1. When it's reached, the command is stopped. Pausing the sandbox also pauses the timer. Without a timeout, the command runs until it exits or the sandbox stops.
stdin
false
Keep stdin open for writing. Otherwise stdin is closed.
background
false
Return 201 with the command at once instead of streaming its events.
By default, the API returns 200 with an event stream (text/event-stream). The command keeps running if
the stream drops. The command's id is also in the Keln-Command-Id response header, so a stream that
drops before started can be resumed. Keln refuses a streamed command past the workspace's open-stream
limit before it starts (429 too_many_streams).
A cwd that is missing or is not a directory returns 400 invalid_parameter with param: cwd. An
argv program that is missing or not permitted returns the same code with param: argv. Through
command, a missing program is bash's exit code 127.
Command events
Each event has an event name and JSON data. id is the event's position in the command's stream
(1, 2, 3…), stable across reattaches; an error event has none. Keln may add new event types, so skip the
ones you do not know.
Event
data
Meaning
started
command_id, pid
The command started.
stdout, stderr
data, ts
Output bytes as base64, and the capture time in Unix milliseconds.
exit
exit_code, signal, oom_killed
The command ended.
error
error
A failure after the stream began, as the same object as an HTTP error. It ends the stream, and the command itself may still be running.
Output arrives line by line. Output format says what that
changes.
List and get commands
GET /v1/sandboxes/{sandbox_id}/commands lists running and exited commands, newest first, as
{"object": "list", "data": [...]}.
GET /v1/sandboxes/{sandbox_id}/commands/{command_id} returns one command.
Kill a command
DELETE /v1/sandboxes/{sandbox_id}/commands/{command_id} sends SIGKILL and returns the command. Killing
an exited command returns 200 with it unchanged.
Attach to a command's events
GET /v1/sandboxes/{sandbox_id}/commands/{command_id}/events returns the same stream as a run, from the
start, or after the event named by the Last-Event-ID header. For an exited command, the stream
replays its events and ends with exit.
Write to stdin
POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/stdin writes the raw request body
(application/octet-stream) to the command's stdin, and returns 204. It needs stdin: true at start.
Close stdin
POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/stdin/close sends end-of-file and returns 204.
Closing a closed stdin also returns 204.
Send a signal
POST /v1/sandboxes/{sandbox_id}/commands/{command_id}/signal sends a signal and returns the command.
Field
Contract
signal
A number from 1 to 64, or a name: SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGUSR1, SIGUSR2, SIGTERM, SIGCONT, SIGSTOP or SIGTSTP, with or without the SIG prefix.
Files
Every path is absolute. The read, write, delete, list and stat calls take it in the path query
parameter, so URL-encode it. mkdir and move take paths in the JSON body.
Read a file
GET /v1/sandboxes/{sandbox_id}/files?path= streams the file's bytes
(application/octet-stream).
Write a file
PUT /v1/sandboxes/{sandbox_id}/files?path= writes the raw request body to the file, streamed. Keln
replaces an existing file. A directory at the path returns 409 is_a_directory.
DELETE /v1/sandboxes/{sandbox_id}/files?path= deletes a file or a symbolic link, and returns 204. It
removes a link, not what it points to. A directory, empty or not, returns 409 is_a_directory. Delete
it with a command (rm -r).
List a directory
GET /v1/sandboxes/{sandbox_id}/files/list?path= returns the directory entries.
type is file or dir. A symbolic link lists as file.
Describe a path
GET /v1/sandboxes/{sandbox_id}/files/stat?path= returns information about the path, following
symbolic links. A missing path returns 404 file_not_found.
type is file, dir or other (a device, socket or pipe). size is in bytes, for a file.
Make a directory
POST /v1/sandboxes/{sandbox_id}/files/mkdir makes the directory and any missing parents, as the
sandbox's user, and returns it in the same shape as stat. If the directory already exists, the API
returns its current information. A file in the way returns 409 not_a_directory.
Field
Contract
path
Required. Absolute.
Move or rename
POST /v1/sandboxes/{sandbox_id}/files/move moves from to to, as the sandbox's user, and returns
what is now at to in the same shape as stat.
Field
Default
Contract
from
Required. Absolute.
to
Required. Absolute. The new path itself, not a directory to move into.
overwrite
false
Replace an existing to. Non-empty directories cannot be overwritten.
An existing to returns 409 path_exists unless overwrite is true. The parent directory of to
must exist. Otherwise the call returns 404 file_not_found with param: to.
POST /v1/sandboxes/{sandbox_id}/terminals starts a program on a pseudo-terminal, as the sandbox's
user. sudo gives root. The body is optional, and the response is 201 with the terminal.
Field
Default
Contract
command
A shell line, run through bash -lc.
argv
The program and its arguments, run directly.
cwd
the user's home
Absolute.
env
none
Environment variables.
cols
80
1 to 1000.
rows
24
1 to 1000.
Send command, or argv, or neither for a login shell.
List and get terminals
GET /v1/sandboxes/{sandbox_id}/terminals returns the sandbox's terminals, oldest first, as
{"object": "list", "data": [...]}. GET /v1/sandboxes/{sandbox_id}/terminals/{terminal_id} returns
one terminal.
Resize a terminal
POST /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}/resize takes cols and rows, both required,
1 to 1000. It does the same as a resize frame on the socket, and returns the terminal at its new size.
End a terminal
DELETE /v1/sandboxes/{sandbox_id}/terminals/{terminal_id} ends the terminal's program and returns the
terminal. Ending an exited terminal returns 200 with it unchanged.
Attach to a terminal
GET /v1/sandboxes/{sandbox_id}/terminals/{terminal_id}/ws is a WebSocket upgrade, authorized like
every call with Authorization: Bearer. Every message is a binary frame whose first byte says what it
is:
Direction
First byte
Rest of the frame
Client to server
0x00
Input bytes.
Client to server
0x01
The new size: columns and rows, each a big-endian 16-bit integer.
Server to client
0x00
Output bytes.
Server to client
0x03
The exit code, a big-endian 32-bit integer. The server then closes the socket.
Keln ignores text frames and unknown first bytes. You can attach to a terminal again after a disconnect;
to receive all of a program's output, keep a socket attached. An open socket counts
toward the workspace's 256 open streams.
Preview URLs
Each open port is available at its url, https://<port>-<id without sbx_>.keln.run, for any HTTP method
and for WebSocket upgrades. A public port is open to anyone with the URL. A private port, the default,
needs the sandbox's port_token in an X-Keln-Port-Token header. The Authorization header isn't
forwarded to the program on the port.
A sandbox's previews hold at most 256 connections open at once, and one client address at most 64
(429 too_many_connections). A preview socket's messages are at most 1 MiB each way.
Errors
All errors use the following format. Use code to identify the specific error and type for its
category. message provides a human-readable explanation, and param identifies the affected
request field when applicable.
{"error":{"type":"invalid_request_error","code":"invalid_parameter","message":"Unknown field `timeout`.","param":"timeout"}}
The types are invalid_request_error, authentication_error, permission_error, not_found_error,
conflict_error, payment_required_error, rate_limit_error, api_error and unavailable_error. Keln
may add new codes and types.
Status
code
Meaning
400
invalid_json
The body is not valid JSON.
400
invalid_parameter
A field is wrong or unknown. param names it.
400
unknown_template
No such template.
400
invalid_path
A path is missing or not absolute.
400
unsupported_parameter
The request names a field the Sandbox API doesn't support. param names it.
401
invalid_api_key
The API key is missing or invalid.
401
invalid_port_token
A preview URL's private port needs a valid X-Keln-Port-Token.
402
insufficient_balance
The balance does not cover the first 5 minutes of this sandbox.
402
key_budget_exhausted
This API key's budget for the period is spent.
403
key_source_not_allowed
This key may not be used from this address.
403
account_suspended
The account is suspended.
403
key_suspended
The key is suspended.
403
sandboxes_not_enabled
Sandboxes are not enabled for this workspace.
403
images_not_enabled
Images are not enabled for this workspace.
403
permission_denied
The sandbox's user may not access the file's path.
404
sandbox_not_found
No such sandbox for this workspace.
404
image_not_found
No such image for this workspace.
404
command_not_found
No such command in this sandbox.
404
file_not_found
The path doesn't exist.
404
terminal_not_found
No such terminal in this sandbox.
404
route_not_found
No such endpoint.
404
port_not_found
A preview URL's sandbox is not running, or it does not expose this port.
409
sandbox_not_running
The sandbox has stopped, or (saving an image) it is paused.
409
snapshot_in_progress
An image of this sandbox is still being saved: another save or a pause waits for it.
409
image_not_ready
The image is still creating, or it failed.
409
sandbox_paused
The sandbox is paused. Resume it first.
409
sandbox_resuming
The sandbox is resuming. Pause it once it runs.
409
idempotency_key_reused
This key was used with a different body.
409
idempotency_key_in_use
A request with this key is still running.
409
stdin_not_open
The command's stdin is not open.
409
command_exited
The command has exited.
409
not_a_directory
A file is in the way of a directory.
409
is_a_directory
The path is a directory.
409
path_exists
to exists, and overwrite is not true.
413
body_too_large
The body is over 1 MB. Use PUT …/files for file uploads.
429
rate_limited
Too many requests.
429
concurrency_limit
The workspace has its limit of running sandboxes.
429
daily_limit
The workspace has used its sandbox time for the day.
429
too_many_streams
The workspace has 256 streams open.
429
too_many_terminals
This sandbox has as many terminals as it can run.
429
paused_limit
The workspace has 100 paused sandboxes.
429
image_limit
The workspace holds 20 images that are creating or ready.
429
too_many_connections
A preview has reached its connection limit.
502
backend_error
The call didn't complete. Safe to retry.
503
temporarily_unavailable
Temporarily unavailable. Safe to retry.
503
capacity_unavailable
The sandbox can't start right now. Safe to retry.
503
sandboxes_disabled
Starting and running sandboxes is unavailable right now. Reading, listing and stopping still work.
503
port_unreachable
A preview URL's port did not respond.
503
pause_failed
The sandbox could not be paused. It keeps running.
503
resume_failed
The sandbox could not be resumed. It stays paused.
429 and 503 responses include a Retry-After header when a retry time is available.