> For the list of every page, fetch /llms.txt. The API contract is the OpenAPI file linked from the API reference.

# Running commands

`POST /v1/sandboxes/{sandbox_id}/exec` runs a command in a running sandbox. It has three modes:

| Mode | Set | Answer | Use it for |
| --- | --- | --- | --- |
| Blocking | nothing | 200 with JSON when the command exits | Short commands |
| Streamed | `"stream": true` | 200 with server-sent events as output arrives | Watching output live |
| Background | `"background": true` | 202 at once with an exec ID | Anything long |

Next step: run the blocking sample below against a sandbox from [Sandboxes](/run-sandboxes/sandboxes).

The samples use `$SANDBOX` for the sandbox ID.

## Blocking

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command": "echo hello from $(hostname) && python --version"}'
```

```json
{
  "exit_code": 0,
  "stderr": "",
  "stdout": "hello from 000021ca\nPython 3.12.16\n",
  "timed_out": false
}
```

A blocking call took about 0.5 seconds on both providers for a command that returns at once.

A command that fails is still a 200. Read `exit_code`:

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command": "echo to-stdout; echo to-stderr >&2; exit 3"}'
```

```json
{"exit_code": 3, "stderr": "to-stderr\n", "stdout": "to-stdout\n", "timed_out": false}
```

## The command, cwd, env, and user

`command` is a string or a list.

- A string runs through `sh -c`, so pipes, `&&`, and variables work.
- A list runs as given, with no shell.

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "command": ["python", "-c", "import os; print(os.getcwd(), os.environ[\"GREETING\"])"],
    "cwd": "/tmp",
    "env": {"GREETING": "hi"}
  }'
```

```json
{"exit_code": 0, "stderr": "", "stdout": "/tmp hi\n", "timed_out": false}
```

| Field | Meaning |
| --- | --- |
| `cwd` | Working directory. Set it every time: the default differs by provider. |
| `env` | Variables for this command, added to the sandbox's own `env`. |
| `user` | User name or uid to run as. Default is the image's user, which is `root` for most images. |
| `timeout_seconds` | Kill the command after this long. |

Without `cwd`, a command in `python:3.12-slim` started in `/root` on Daytona and in `/` on Modal. An image with a `WORKDIR` started there on both.

`user` works when the user exists in the image:

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command": "id", "user": "nobody"}'
```

```json
{"exit_code": 0, "stderr": "", "stdout": "uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)\n", "timed_out": false}
```

A user that does not exist returns 400:

```json
{"error":{"code":"invalid_request","message":"user does not exist in the sandbox","type":"invalid_request"},"request_id":"req_000077db"}
```

Two mistakes do not return an error status. They come back as a 200 with a nonzero exit code:

| Mistake | Daytona | Modal |
| --- | --- | --- |
| `cwd` that does not exist | exit code 1 | exit code 128 |
| A program that is not installed | exit code 127 | exit code 127 |

`stderr` carries the reason. On Daytona it starts with the path of a wrapper script Meadow uses, for example `/tmp/.meadow-fg.Zur2R3/cmd.sh: 2: cd: can't cd to /does/not/exist`. Strip that prefix before you show the text to a person or a model.

A command killed for using too much memory is also a 200. On a Daytona sandbox with `memory_mb: 1024`, a script that kept allocating memory came back with `exit_code: 137` and `timed_out: false` after about 950 MB, and the sandbox stayed `running`.

There is no terminal (TTY) mode. `"tty": true` returns 400 `unknown field in exec request`. For an interactive shell, use [SSH](/run-sandboxes/files-ports-and-ssh#ssh).

## Timeouts and exit codes

Blocking and streamed commands are killed after 60 seconds unless you set `timeout_seconds`. A background command has no default timeout.

No single request to the hosted beta lasts longer than 60 minutes, whatever `timeout_seconds` says. At 60 minutes the load balancer in front of Meadow cuts the request and answers 504 with the text `stream timeout`. That response is not JSON and has no `x-request-id`, and it does not tell you how the command ended. Seen on 2026-11-25: a blocking command that was silent for 59 minutes returned in full, and one that was silent for 60 minutes got the 504. Run anything that can take longer as a background command and read it with `wait_seconds`.

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command": "echo started; sleep 30", "timeout_seconds": 2}'
```

On Daytona:

```json
{"exit_code": 143, "stderr": "", "stdout": "started\n", "timed_out": true}
```

On Modal:

```json
{"exit_code": 124, "stderr": "", "stdout": "started\n", "timed_out": true}
```

The exit code of a timed-out command differs by provider and by mode. Read `timed_out`, or `status: timed_out` on a background command, and never the exit code.

A timeout ends the command and the processes it started.

## Processes a command leaves running

A command that exits by itself leaves the processes it started in the background running. This holds for blocking, streamed and background commands, on Daytona and on Modal. `docker exec` and both providers' own exec calls behave the same way.

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command": "nohup python3 -m http.server 8000 > /tmp/server.log 2>&1 &"}'
```

The command exits at once and the server keeps answering on port 8000 for later commands. This is on the hosted beta since 2026-11-28. It was run on both providers against a build that has the change.

- The process runs until it exits, the sandbox ends, or you `DELETE` the background command that started it. It has no exec ID of its own and does not keep the sandbox from going idle.
- A timeout ends the command and every process in its process group.
- `DELETE /v1/sandboxes/{sandbox_id}/execs/{exec_id}`, on a running command or one that has already exited, ends every process that carries the command's `MEADOW_EXEC_ID` environment variable and, while one of those is still in the command's session, the rest of that session. That covers `nohup ... &`, `setsid ...` and a child that cleared its environment but stayed in the session. A process that cleared its environment and left the session is not ended: end it with another command, such as `pkill`. For a command that has already exited, the call still returns its final state unchanged.
- Redirect the output of a process you leave running, as the example does. If it keeps the command's `stdout` or `stderr` open, the command still finishes when it exits by itself: Meadow waits up to about one second for that output and then stops recording. What the process writes later is discarded. Its writes succeed, so it does not block and gets no `SIGPIPE`.

## Streamed

```bash
curl -sS -N -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "command": "for i in 1 2 3; do echo line $i; sleep 1; done; echo oops >&2; exit 2",
    "stream": true
  }'
```

The response has `content-type: text/event-stream`. Each line arrived about one second after the last:

```text
event: stdout
data: "line 1\n"

event: stdout
data: "line 2\n"

event: stdout
data: "line 3\n"

event: stderr
data: "oops\n"

event: exit
data: {"exit_code":2}
```

| Event | `data` |
| --- | --- |
| `stdout`, `stderr` | A JSON string. Decode it to get the text. |
| `exit` | `{"exit_code": 2}`, plus `"timed_out": true` when the command was killed at its timeout. Always the last event. |
| `error` | The usual error body, with `retry` `check_outcome` and `outcome` `unknown`. The stream broke and the exit code is unknown. The command started before the first event, so it may have run, and sending the call again runs it again. |

The same call in Python, with `requests`. Each `data` line is JSON, so decode it:

```python
import json
import os

import requests

BASE = os.environ["MEADOW_BASE_URL"]
HEADERS = {"Authorization": f"Bearer {os.environ['MEADOW_API_KEY']}"}
SANDBOX = os.environ["SANDBOX"]

body = {
    "command": "for i in 1 2 3; do echo line $i; sleep 1; done; echo oops >&2; exit 2",
    "stream": True,
}
with requests.post(f"{BASE}/v1/sandboxes/{SANDBOX}/exec", headers=HEADERS, json=body, stream=True, timeout=120) as resp:
    resp.raise_for_status()
    event, exit_code = None, None
    for line in resp.iter_lines(decode_unicode=True):
        if line.startswith("event:"):
            event = line[len("event:"):].strip()
        elif line.startswith("data:"):
            data = json.loads(line[len("data:"):])
            if event in ("stdout", "stderr"):
                print(event, repr(data))
            elif event == "exit":
                exit_code = data["exit_code"]
            elif event == "error":
                raise RuntimeError(data["error"]["message"])

if exit_code is None:
    raise RuntimeError("the stream ended without an exit event")
print("exit code", exit_code)
```

```text
stdout 'line 1\n'
stdout 'line 2\n'
stdout 'line 3\n'
stderr 'oops\n'
exit code 2
```

A stream that ends without an `exit` event did not finish cleanly. A dropped connection loses the rest of the output, and you cannot attach again. For work you cannot afford to lose, use a background command.

## Background commands

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-bg-1" \
  -d '{"command": "for i in $(seq 1 8); do echo step $i; sleep 1; done", "background": true}'
```

```json
{
  "exit_code": null,
  "finished_at": null,
  "id": "exec_00004ac2",
  "started_at": "2026-11-23T22:19:18.468Z",
  "status": "running",
  "stderr": "",
  "stderr_offset": 0,
  "stdout": "",
  "stdout_offset": 0
}
```

The command runs inside the sandbox whether or not you stay connected. Use this mode for an agent run, a test suite, a build, or a server. A blocking or streamed call is cut when your connection drops or when the Meadow server that holds it is replaced during a deploy. A background command is not.

Send `Idempotency-Key` on every background start that you might retry. Without it, each start runs the command again. With it, a repeat with the same body returns the first command, and the same key with a different body returns 409.

### Read output

```bash
curl -sS "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/execs/exec_00004ac2?wait_seconds=5" \
  -H "Authorization: Bearer $MEADOW_API_KEY"
```

```json
{
  "exit_code": null,
  "finished_at": null,
  "id": "exec_00004ac2",
  "started_at": "2026-11-23T22:19:18.468Z",
  "status": "running",
  "stderr": "",
  "stderr_offset": 0,
  "stdout": "step 1\nstep 2\n",
  "stdout_offset": 14
}
```

Pass the returned offsets on the next call to get only new output:

```bash
curl -sS "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/execs/exec_00004ac2?stdout_offset=14&wait_seconds=30" \
  -H "Authorization: Bearer $MEADOW_API_KEY"
```

```json
{"exit_code": null, "status": "running", "stdout": "step 3\n", "stdout_offset": 21}
```

`wait_seconds` (0 to 60) holds the request until there is new output or the command ends. It returns as soon as either happens. Loop until `status` is no longer `running`:

```json
{
  "exit_code": 0,
  "finished_at": "2026-11-23T22:19:26.796Z",
  "status": "exited",
  "stdout": "step 5\nstep 6\nstep 7\nstep 8\n",
  "stdout_offset": 56
}
```

| `status` | Meaning |
| --- | --- |
| `running` | Still going. |
| `exited` | Ended by itself. `exit_code` is set. |
| `timed_out` | Killed at `timeout_seconds`. |
| `killed` | Killed by your kill call. With a null `exit_code`, the sandbox was deleted or timed out before the command ended, or before Meadow could read its result. |
| `failed` | Meadow could not learn how the command ended. `failure_reason` says why. `state_lost`: the command's state inside the sandbox (its files under `/tmp/.meadow-exec`, or the process that supervises it) was gone for more than 2 minutes. `sandbox_lost`: the provider lost the sandbox while the command was running, and the sandbox reads `failed` with `provider_lost`. `provider_unreachable`: for 10 minutes the provider could not find this command's sandbox on any call about it, while it reported the sandbox as running. `exit_code` is null in all three cases, and the command itself may have finished. |

`state_lost` was seen on the hosted beta: after `/tmp/.meadow-exec` was removed in a Daytona sandbox, reads returned 502 `background exec state is unavailable in sandbox; retry` for about two and a half minutes, and then the command read `failed` with `failure_reason` `state_lost`. `sandbox_lost` and `provider_unreachable` are on the hosted beta since 2026-11-27. Before, a command whose sandbox the provider lost read `killed` with a null `exit_code`. New status values and reasons can appear, so treat any status other than `running` as final.

A long command is not ended by one wrong answer from a provider. If a provider answers "not found" for the sandbox during a read, a kill, a stdin write or a background start, Meadow asks the provider again, up to three times over about 6 seconds. If the sandbox is still there, the call returns 502 with `error.code` `sandbox_unreachable` and `Retry-After: 2`, and every command keeps running: send the call again. A read of a command that has already ended is the exception: it returns 200 with the status, the exit code and the kept last 256 KiB of each stream. A foreground or streamed command gets the same 502. Only when the provider confirms the loss do the commands read `failed` with `sandbox_lost`.

The 502 does not go on for ever. If every call about one background command fails this way for 10 minutes, that command reads `failed` with `provider_unreachable`. Other commands and the sandbox are not changed. A call that reaches the command starts the count again. This too is on the hosted beta since 2026-11-27. Before, one such answer marked every background command of the sandbox `killed` while the sandbox still read `running`. No provider gave such an answer in the sample runs on the hosted beta, so these two paragraphs are read from the server's code and its tests.

Each read returns at most 1 MiB of each stream. Keep reading from the new offset until `stdout` and `stderr` come back empty.

The whole loop in Python: start the command, then read by offset until it has ended and a read comes back empty.

```python
import os
import uuid

import requests

BASE = os.environ["MEADOW_BASE_URL"]
HEADERS = {"Authorization": f"Bearer {os.environ['MEADOW_API_KEY']}"}
SANDBOX = os.environ["SANDBOX"]

start = requests.post(
    f"{BASE}/v1/sandboxes/{SANDBOX}/exec",
    headers={**HEADERS, "Idempotency-Key": str(uuid.uuid4())},
    json={"command": "for i in $(seq 1 5); do echo step $i; sleep 1; done", "background": True, "timeout_seconds": 300},
    timeout=30,
)
start.raise_for_status()
run = start.json()
print("started", run["id"][:13])

stdout_offset, stderr_offset = 0, 0
while True:
    read = requests.get(
        f"{BASE}/v1/sandboxes/{SANDBOX}/execs/{run['id']}",
        headers=HEADERS,
        params={"stdout_offset": stdout_offset, "stderr_offset": stderr_offset, "wait_seconds": 30},
        timeout=90,
    )
    read.raise_for_status()
    run = read.json()
    print(run["stdout"], end="")
    stdout_offset, stderr_offset = run["stdout_offset"], run["stderr_offset"]
    if run["status"] != "running" and not run["stdout"] and not run["stderr"]:
        break

print(run["status"], run["exit_code"])
```

```text
started exec_00000526
step 1
step 2
step 3
step 4
step 5
exited 0
```

Keep the exec ID. There is no call that lists the commands of a sandbox: `GET /v1/sandboxes/{sandbox_id}/execs` returns 404 `route not found`. If you lose the ID, send the start again with the same `Idempotency-Key` and the same body. The response is the first command, with its ID, and nothing runs twice.

### Send input

Start the command with `"stdin": true`. It cannot be turned on later, and it works in background mode only.

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/exec" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "command": ["python", "-u", "-c", "import sys\nfor line in sys.stdin:\n    print(\"got\", line.strip().upper())"],
    "background": true,
    "stdin": true
  }'
```

Write to it. Include the newline if the command reads lines. The response is 204:

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/execs/exec_0000621b/stdin" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"data": "hello\n"}'
```

Read the reply with the read call:

```json
{"exit_code": null, "status": "running", "stdout": "got HELLO\n", "stdout_offset": 10}
```

Send `"close": true` to end the input. The command sees end of file:

```bash
curl -sS -X POST "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/execs/exec_0000621b/stdin" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"data": "bye\n", "close": true}'
```

```json
{"exit_code": 0, "status": "exited", "stdout": "got BYE\n", "stdout_offset": 18}
```

One write carries at most 512 KiB. A larger one returns 400 with `stdin data exceeds maximum write size`. Writing to a command that has ended returns 409 with `exec is not running`. Writing to a command started without `stdin` returns 400 with `exec was not started with stdin enabled`.

### Kill

```bash
curl -sS -X DELETE "$MEADOW_BASE_URL/v1/sandboxes/$SANDBOX/execs/exec_0000bcd5" \
  -H "Authorization: Bearer $MEADOW_API_KEY"
```

```json
{
  "exit_code": 143,
  "finished_at": "2026-11-23T22:19:40.451Z",
  "id": "exec_0000bcd5",
  "status": "killed",
  "stderr": "",
  "stdout": "",
  "stdout_offset": 0
}
```

The kill answer carries no output. Read the command again to get what it printed before it died. Killing twice is safe and returns the same answer. A kill ends the command and the processes it started.

Only background commands have an ID, so only they can be killed. A blocking or streamed command stops at its timeout, so set `timeout_seconds` to fit the work.

## Output caps and the truncated flags

| Mode | Kept per stream | When output passes the cap |
| --- | --- | --- |
| Blocking and streamed | 4 MiB | The call still returns 200 with the first 4 MiB. |
| Background | 16 MiB | Later output is dropped and the offset stops at 16777216. |

When a stream is cut, the body carries `stdout_truncated: true` or `stderr_truncated: true`, and the response has the header `x-meadow-stdout-truncated: true` or `x-meadow-stderr-truncated: true`. The flags are absent when nothing was cut.

A blocking command that printed 5 MiB:

```json
{"exit_code": 0, "timed_out": false, "stdout_truncated": true, "stdout": "<4194304 characters>"}
```

A command that writes more should write to a file. Fetch the file with the [files call](/run-sandboxes/files-ports-and-ssh).

The full background output can be read for one hour after the command ends, while the sandbox is running. Meadow also keeps the last 256 KiB of each stream for 24 hours after the command ends, including for a command that was still running when you deleted the sandbox or it timed out. After the hour, and after the sandbox is gone, the read call returns the status, the exit code and that kept part. Offsets still count from the start of the stream, so a read from offset 0 of a longer output starts at the kept part and has `stdout_truncated` set. After 24 hours the output is empty. Nothing is kept when the provider lost the sandbox before Meadow could read it. Seen on the hosted beta, on Daytona: a command that printed 400,000 bytes was read from offset 0 after its sandbox was deleted, and the response held the last 262,144 characters with `stdout_truncated: true` and `stdout_offset: 400000`. A command that ended on its own before the delete keeps its real status and exit code, also when nobody read it first: Meadow reads the result of up to 8 unread commands, newest first, just before it deletes the provider sandbox. For a few seconds after the delete call such a command can read `killed` with a null `exit_code`, until that read has run. This is on the hosted beta since 2026-11-27. Before, on both providers, a command that had ended and had not been read before the delete read `killed` with a null `exit_code` afterwards, and a command read once before the delete kept `exited` and its exit code. Do: read a background command to its end before you delete the sandbox when you start more than 8 of them.

## Errors

| Status | Message | Cause |
| --- | --- | --- |
| 409 | `sandbox is not running` | The sandbox is `creating`, `terminating`, `terminated`, or `failed`. |
| 400 | `stream and background cannot both be true` | Pick one mode. |
| 400 | `stdin can only be used with background: true` | |
| 400 | `unknown field in exec request` | A field name is wrong. `error.param` names it. The fields are `command`, `cwd`, `env`, `user`, `timeout_seconds`, `stream`, `background`, and `stdin`. |
| 400 | `wait_seconds must be between 0 and 60` | |
| 404 | `exec not found` | The exec ID is wrong, or belongs to another sandbox. |

Provider differences and rarer cases, such as images without `sh` on Modal, are in [Known limits](/reference/known-limits#running-sandboxes).

## API reference

Operations on this page: [`execInSandbox`](/reference/api-reference#execinsandbox), [`getExec`](/reference/api-reference#getexec), [`writeExecStdin`](/reference/api-reference#writeexecstdin), [`killExec`](/reference/api-reference#killexec).