> ## Documentation Index
> Fetch the complete documentation index at: https://docs.styne.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Run commands

> Run a process in a sandbox and read its output as it is produced.

**You need** a running sandbox ([Quickstart](https://docs.styne.ai/quickstart.md)).

`POST /sandboxes/{id}/exec` runs one process in a sandbox and streams its output. The request and the answer are both
JSON lines (NDJSON) on the same connection.

## Start a command

The first line of the body starts the process:

```json theme={"theme":"css-variables"}
{ "cmd": "sh", "args": ["-c", "echo $NODE_ENV; pwd"], "cwd": "/tmp", "env": { "NODE_ENV": "test" }, "timeoutMs": 30000 }
```

`cmd` is the program, started without a shell; its arguments go in `args`. `argv` (the program first, then its
arguments) is an alternative to `cmd` and `args`. Optional: `cwd` (default `/root`), `env` (also named `envs` or
`envVars`), `user` (a user that exists in the template; the default is root), `timeoutMs`, `stdin` (keep stdin open) and
`pty` (`{"rows": 24, "cols": 80}`). Unknown fields are refused with `400 invalid_argument`, and a body with neither `cmd`
nor `argv` answers `400`. For a shell line, run the shell: `{ "cmd": "sh", "args": ["-c", "node -v && python3 -V"] }`;
a `cmd` of `"node -v"` is the program named `node -v`, which does not exist. Such a call, or one with a `user` the
sandbox does not have, answers `400 invalid_argument` with the program or user in `message`, before any line is streamed.

Later lines of the body talk to the running process: `{"stdin": "<base64>"}`, `{"closeStdin": true}`, `{"signal": 15}`
and `{"resize": {"rows": 40, "cols": 100}}`.

## Read the output

The answer is `200` and a stream of lines:

| Line | Meaning |
| - | - |
| `{"started": {"pid": 105}}` | the process is running |
| `{"stdout": "<base64>"}`, `{"stderr": "<base64>"}` | a chunk of output, as it is produced |
| `{"exit": {"exitCode": 0, "signal": 0, "timedOut": false}}` | the process ended |
| `{"error": {...}}` | the stream broke; the same fields as an [error](https://docs.styne.ai/errors.md), joined to the call by `request_id` |

A non-zero exit code is a normal `exit` line, not an HTTP error. A command that outlives `timeoutMs` is killed: the
`exit` line has `"timedOut": true` and `"signal": 9`, and an `error` line with `error_code` `command_timeout` follows.
An error before the process starts (an unknown sandbox, a paused one, a missing program) arrives as an HTTP error or as
an `error` line instead of `started`. The status is `200` once the stream has begun, so read the last line.

## Command history

Every command run in a sandbox is kept, whether it came through `exec`, `POST /sandboxes/{id}/commands` or the E2B
process API: its id (`commandId`), `pid`, `argv`, `cwd`, start and end time, status (`running`, `exited` or `failed`),
exit code, signal and the last 1 MiB of its stdout and of its stderr. The record stays readable after the process ended
and across pause and resume. A sandbox keeps its last 1000 commands and at most 16 MiB of output; the oldest finished
commands go first, and a running command is never dropped. A finished command is also stored, with the last 16 KiB
of each stream, for the last 200 commands of the sandbox and 6 hours: an API restart keeps it and every API instance lists
it. A command that is still running shows only on the instance that runs it. The history goes when the sandbox is
deleted.

```text theme={"theme":"css-variables"}
GET /sandboxes/{id}/command-history?limit=50&status=exited
GET /sandboxes/{id}/command-history/{commandId}
GET /sandboxes/{id}/command-history/{commandId}/logs?stream=stderr&encoding=base64
```

The list is newest first with `total`; `limit` is 1 to 1000 (default 50). `logs` answers the command with `stdout` and
`stderr` as text (invalid UTF-8 is replaced), or as base64 with `encoding=base64`; `stream` limits it to `stdout` or
`stderr`. `stdoutBytes` and `stderrBytes` count everything the command wrote and `stdoutTruncated` and
`stderrTruncated` say that the kept tail is shorter.

## Run a command over REST

`POST /sandboxes/{id}/commands` takes the start line of `exec` (`cmd` and `args`, or `argv`; `envs`, `cwd`, `user`,
`timeoutMs`) and `detached`. Without `detached` it answers `200` when the command ended, with its record and its
`stdout` and `stderr`. With `"detached": true` it answers `202` as soon as the process runs, with its `commandId` and
`pid`, and the command keeps running with no connection held.

```text theme={"theme":"css-variables"}
GET    /sandboxes/{id}/commands/{pid}          status, running or ended
GET    /sandboxes/{id}/commands/{pid}/stream   NDJSON frames of exec: replay of the kept output, then live, last exit
DELETE /sandboxes/{id}/commands/{pid}?signal=15   15 (default) or 9; 409 once the command ended
```

`{pid}` names the running command with that pid, else the newest one that had it.

### Resume a stream with the cursor

Every frame of a command stream carries `cursor`, the position after it (`<stdout bytes>.<stderr bytes>`). Start the
stream there with `?cursor=` and it goes on after the bytes the cursor counts, without a second `started` frame:

```text theme={"theme":"css-variables"}
GET /sandboxes/{id}/commands/{pid}/stream?cursor=1204.0
```

On the `/v1` API the same position is the SSE `id` of each event, and a client that reconnects sends it as
`Last-Event-ID`; the SDKs do this in `vm.follow(...)` (Python `vm.follow(...)`, TypeScript `vm.follow(...)`), which also
reconnects when the connection drops or the API is released. Status, stream, logs and signals of a running command
are answered by every API instance, so a release of the API changes none of it, and a running command keeps the
previous instance up for up to 30 minutes while the new one serves it. The stream replays every byte from where its
cursor is: the API keeps the last 1 MiB of each output stream, and a reader whose cursor is older (from the start, or
because it read more slowly than the command wrote) reads the older bytes from the sandbox, which keeps the whole
output of a detached command on its disk, then goes on with the newest. A slow reader slows nothing but itself.

The sandbox keeps the first 512 MiB of each output stream of a detached command (stdout and stderr each), for up to
one hour after the command ended, and only while its disk has at least 1 GiB free. Past 512 MiB, or on a disk with
less room, it keeps only the newest 8 to 12 MiB and drops older output as new output comes; a reader still streaming the command
holds its place, so the command waits for that reader instead of dropping what it has not read. A reader that asks
for output the sandbox no longer has gets a `gap` frame first (`{"gap": {"stream": "stdout", "from": 0, "bytes":
98951424, "reason": "the sandbox no longer keeps this output"}, "cursor": ...}`; on `/v1` the SSE event `gap`) naming
the bytes it missed and why, then the output goes on from the oldest byte kept. Output is never skipped without a
`gap` frame. To read a command's output as it is written, however long it is, stream the command when you start it
(`stream: true` on `/v1`, or `POST .../exec`). Standard input of a running command
is accepted only by the instance that started it.

## Operations

| Method | Path | What it does |
| - | - | - |
| `POST` | `/sandboxes/{id}/exec` | Run a command and stream its output |
| `POST` | `/sandboxes/{id}/commands` | Run a command to its exit, or start it detached |
| `GET` | `/sandboxes/{id}/commands/{pid}` | Read a command's status by pid |
| `GET` | `/sandboxes/{id}/commands/{pid}/stream` | Replay and follow a command's output |
| `DELETE` | `/sandboxes/{id}/commands/{pid}` | Signal a running command |
| `POST` | `/sandboxes/{id}/commands/{pid}/input` | Write text to a running command's stdin, and close it with eof |
| `GET` | `/sandboxes/{id}/command-history` | List the sandbox's commands, newest first |
| `GET` | `/sandboxes/{id}/command-history/{cid}` | Read one command of the history |
| `GET` | `/sandboxes/{id}/command-history/{cid}/logs` | Read a command's stdout and stderr, also after it ended |
| `POST` | `/sandboxes/{id}/code` | Run code in a kernel context; answers its output, results and error |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.