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

# Run commands

> Run a command and wait for its output, or start it in the background: stream its output live, feed it input, stop it with a signal, or keep a server running across sleep.

Running commands is most of what you do with a sandbox: installing packages, running tests, starting a server,
launching an agent. Fibre gives you two ways to do it, and choosing the right one makes your code simpler.

* **Run and wait.** You send a command and Fibre answers when it has finished, with its exit code and its output.
  This is the easiest option, and it suits quick things such as a short script, `ls` or a `git` command.
* **Start it in the background.** Fibre starts the command and answers straight away with a command ID. The
  command then runs for as long as it needs. While it runs, you can watch its output as it is written, send it
  input, or stop it. You can even keep it running after the sandbox goes to sleep. This suits installs, test runs,
  builds, servers and agents.

Here is how the two compare:

| | Run and wait | Background command |
| - | - | - |
| CLI | `fibre exec` | `fibre exec --detach`, then `fibre logs -f` |
| TypeScript, Python | `sbx.run()` | `sbx.spawn()` |
| HTTP | `POST /v1/sandboxes/{id}/exec` | `POST /v1/sandboxes/{id}/commands` |
| Time limit | HTTP exec: 30 seconds. `fibre exec` and `sbx.run()`: none | None, or `timeout_sec` |
| Output | In the answer | Streamed as it is written |
| Input | None | Your program's standard input |
| After a sleep | Not applicable: it has already finished | Programs started with `keep` carry on |

All the examples on this page use the same sandbox, so start by creating it:

```bash title="CLI" run theme={null}
SBX=$(fibre create --lifetime 20m --label docs=commands --json | jq -r .id)
```

```typescript title="TypeScript" run theme={null}
import { Sandbox } from "@fibre-dev/sdk";

const sbx = await Sandbox.create({ lifetime: 1200, labels: { docs: "commands" } });
```

```python title="Python" run theme={null}
from fibre import Sandbox

sbx = Sandbox.create(lifetime=1200, labels={"docs": "commands"})
```

```bash title="curl" run capture=SBX=.id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"lifetime_sec": 1200, "labels": {"docs": "commands"}}'
```

## Run and wait

To run a command and wait for the result, send the command and read the answer:

```bash title="CLI" run theme={null}
fibre exec "$SBX" -- 'echo hello from $(uname -s); python3 --version'   # hello from Linux · Python 3.11.2
```

```typescript title="TypeScript" run theme={null}
const result = await sbx.run("echo hello from $(uname -s); python3 --version");
console.log(result.exitCode, result.stdout); // 0 hello from Linux \n Python 3.11.2
```

```python title="Python" run theme={null}
result = sbx.run("echo hello from $(uname -s); python3 --version")
print(result.exit_code, result.stdout)  # 0 hello from Linux \n Python 3.11.2
```

```bash title="curl" run theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["sh", "-c", "echo hello from $(uname -s); python3 --version"]}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "exit_code": 0,
>   "stdout": "hello from Linux\nPython 3.11.2\n",
>   "stderr": "",
>   "stdout_truncated": false,
>   "stderr_truncated": false
> }
> ```

A few things are worth knowing:

* **A command is a list**: the program first, then its arguments. In the SDKs you can also pass a single string.
  It then runs through the shell (`sh -c`), so pipes, `&&` and `$(...)` all work. Over HTTP, wrap the command
  yourself when you need the shell: `["sh", "-c", "..."]`.
* **A failing command is not an error.** If the command exits with a non-zero code, the call still succeeds and
  you read the code in `exit_code` (`exitCode` in TypeScript). Errors are reserved for problems with the request
  itself, such as an unknown sandbox.
* **Over HTTP, an exec stops after 30 seconds** (the command is stopped and the answer is `504 exec_timeout`) and
  keeps at most 4 MB of each output stream. If the output was
  cut, `stdout_truncated` or `stderr_truncated` is `true`. An exec runs in the sandbox's default directory with the
  sandbox's environment. For anything longer, or to choose a directory or add variables, use a background command.
* **In the SDKs, `sbx.run()` has no time limit**, because it starts a background command and waits for it for
  you. Pass a `timeout` in seconds if you want it stopped after a while, and `cwd` and `env` if you need them.

## Stream a test run as it happens

Background commands are at their best with work that takes a while, because you can watch it as it happens
instead of waiting in the dark. In this example the sandbox gets a small Python project, installs `pytest`, and runs
the tests while you watch each result arrive.

**1. Put the project in the sandbox**

```bash title="CLI" run theme={null}
fibre exec "$SBX" -i -- sh -c 'mkdir -p /work && cat > /work/calc.py' <<'PY'
def add(a, b):
    return a + b

def divide(a, b):
    return a / b
PY

fibre exec "$SBX" -i -- sh -c 'cat > /work/test_calc.py' <<'PY'
import time, pytest
from calc import add, divide

def test_add():
    assert add(2, 3) == 5

def test_divide():
    assert divide(10, 4) == 2.5

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        divide(1, 0)

def test_slow_integration():
    time.sleep(2)
    assert add(add(1, 2), 3) == 6
PY
```

```typescript title="TypeScript" run theme={null}
await sbx.files.write("/work/calc.py", [
  "def add(a, b):",
  "    return a + b",
  "",
  "def divide(a, b):",
  "    return a / b",
].join("\n") + "\n");

await sbx.files.write("/work/test_calc.py", [
  "import time, pytest",
  "from calc import add, divide",
  "",
  "def test_add():",
  "    assert add(2, 3) == 5",
  "",
  "def test_divide():",
  "    assert divide(10, 4) == 2.5",
  "",
  "def test_divide_by_zero():",
  "    with pytest.raises(ZeroDivisionError):",
  "        divide(1, 0)",
  "",
  "def test_slow_integration():",
  "    time.sleep(2)",
  "    assert add(add(1, 2), 3) == 6",
].join("\n") + "\n");
```

```python title="Python" run theme={null}
sbx.files.write("/work/calc.py", "\n".join([
    "def add(a, b):",
    "    return a + b",
    "",
    "def divide(a, b):",
    "    return a / b",
]) + "\n")

sbx.files.write("/work/test_calc.py", "\n".join([
    "import time, pytest",
    "from calc import add, divide",
    "",
    "def test_add():",
    "    assert add(2, 3) == 5",
    "",
    "def test_divide():",
    "    assert divide(10, 4) == 2.5",
    "",
    "def test_divide_by_zero():",
    "    with pytest.raises(ZeroDivisionError):",
    "        divide(1, 0)",
    "",
    "def test_slow_integration():",
    "    time.sleep(2)",
    "    assert add(add(1, 2), 3) == 6",
]) + "\n")
```

```bash title="curl" run theme={null}
printf 'def add(a, b):\n    return a + b\n\ndef divide(a, b):\n    return a / b\n' | \
  curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/calc.py" \
  -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @-

printf 'import time, pytest\nfrom calc import add, divide\n\ndef test_add():\n    assert add(2, 3) == 5\n\ndef test_divide():\n    assert divide(10, 4) == 2.5\n\ndef test_divide_by_zero():\n    with pytest.raises(ZeroDivisionError):\n        divide(1, 0)\n\ndef test_slow_integration():\n    time.sleep(2)\n    assert add(add(1, 2), 3) == 6\n' | \
  curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/test_calc.py" \
  -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @-
```

**2. Install pytest**

Installing a package can take longer than the 30 seconds an exec allows, so it runs as a background command and
you wait for it to finish. It takes about 10 seconds. (The package goes into a virtual environment, which the
default image's Python requires.)

```bash title="CLI" run theme={null}
fibre exec "$SBX" --timeout 5m -- 'python3 -m venv /work/.venv && /work/.venv/bin/pip install -q pytest'
```

```typescript title="TypeScript" run theme={null}
const install = await sbx.run("python3 -m venv /work/.venv && /work/.venv/bin/pip install -q pytest", { timeout: 300 });
console.log(install.exitCode); // 0
```

```python title="Python" run theme={null}
install = sbx.run("python3 -m venv /work/.venv && /work/.venv/bin/pip install -q pytest", timeout=300)
print(install.exit_code)  # 0
```

```bash title="curl" run capture=INSTALL=.command_id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["sh", "-c", "python3 -m venv /work/.venv && /work/.venv/bin/pip install -q pytest"]}'
```

Over HTTP, starting the command answers at once with its ID and `"status": "running"`. To wait for it, follow
its output until it ends. (The next sections explain this output stream in detail.)

```bash title="curl: wait for it" run theme={null}
curl -sSN "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$INSTALL/logs?follow=1" \
  -H "Authorization: Bearer $FIBRE_API_KEY" | tail -n 1
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "event": "end",
>   "status": "exited",
>   "exit_code": 0
> }
> ```

**3. Run the tests and watch**

```bash title="CLI" run theme={null}
TESTS=$(fibre exec "$SBX" --cwd /work --detach --json -- /work/.venv/bin/pytest -v --color=no | jq -r .command_id)

fibre logs "$SBX" "$TESTS" -f   # each piece arrives as pytest writes it
```

```typescript title="TypeScript" run theme={null}
const tests = await sbx.spawn(["/work/.venv/bin/pytest", "-v", "--color=no"], { cwd: "/work" });

for await (const chunk of tests.output()) {
  process.stdout.write(chunk.data); // each piece arrives as pytest writes it
}

const done = await tests.wait();
console.log(done.status, done.exitCode); // exited 0
```

```python title="Python" run theme={null}
import sys

tests = sbx.spawn(["/work/.venv/bin/pytest", "-v", "--color=no"], cwd="/work")

for chunk in tests.output():
    sys.stdout.write(chunk.data)  # each piece arrives as pytest writes it

done = tests.wait()
print(done.status, done.exit_code)  # exited 0
```

```bash title="curl" run capture=TESTS=.command_id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["/work/.venv/bin/pytest", "-v", "--color=no"], "cwd": "/work"}'
```

```bash title="curl: stream it" run theme={null}
curl -sSN "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$TESTS/logs?follow=1" \
  -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> 4 passed in
> ```
>
> Here is the stream exactly as it arrived, one JSON object per line. The first piece came at once. The second one
> came two seconds later, when the slow test finished:
>
> ```json title="stream" theme={null}
> {"data":"============================= test session starts ==============================\nplatform linux -- Python 3.11.2, pytest-9.2.0, pluggy-1.7.0 -- /work/.venv/bin/python3\ncachedir: .pytest_cache\nrootdir: /work\ncollecting ... collected 4 items\n\ntest_calc.py::test_add PASSED                                            [ 25%]\ntest_calc.py::test_divide PASSED                                         [ 50%]\ntest_calc.py::test_divide_by_zero PASSED                                 [ 75%]\ntest_calc.py::test_slow_integration ","offset":0,"stream":"stdout"}
> {"data":"PASSED                               [100%]\n\n============================== 4 passed in 2.02s ===============================\n","offset":517,"stream":"stdout"}
> {"event":"end","exit_code":0,"status":"exited"}
> ```

Output reaches you in the pieces the program writes, at the moment it writes them. You see the test run as it
happens, not only once it is over.

## The output stream

A background command's output is read from `GET /v1/sandboxes/{id}/commands/{command_id}/logs`. Rather than one
big JSON document, the answer is a series of small JSON objects, one per line (a format called NDJSON). This lets
Fibre send you each piece of output as soon as it exists. There are three kinds of line:

| Line | When | Fields |
| - | - | - |
| Output | Each piece the command writes, as it writes it | `stream` (`stdout` or `stderr`), `offset` (bytes of that stream before this piece), `data` |
| Output, binary | The piece is not valid UTF-8 | the same, with `"encoding": "base64"` and `data` in base64 |
| End | Once, after the command ends | `"event": "end"`, `status`, `exit_code` |

You can control the stream with these query parameters:

| Query | Meaning |
| - | - |
| `follow=1` | Keep the answer open and send output as it is written, until the command ends. Without it: what is there now, then the end line if it has ended |
| `stdout_offset`, `stderr_offset` | Start each stream from this byte. Use them to read only what is new, or to pick up after a dropped connection with no gap and no repeat |

In the SDKs, `command.output()` handles all of this for you. It follows the stream by default, and if the
connection drops, it reconnects and continues from where it left off.

## Check on a command

You can ask about a background command at any time, for example to see whether it has finished and with which exit
code:

```bash title="CLI" run theme={null}
fibre commands "$SBX"   # … exited 0 … /work/.venv/bin/pytest -v --color=no
```

```typescript title="TypeScript" run theme={null}
const again = await sbx.command(tests.id);
console.log(again.status, again.exitCode); // exited 0
```

```python title="Python" run theme={null}
again = sbx.command(tests.id)
print(again.status, again.exit_code)  # exited 0
```

```bash title="curl" run theme={null}
curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$TESTS" -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "command_id": "…",
>   "command": ["/work/.venv/bin/pytest", "-v", "--color=no"],
>   "status": "exited",
>   "exit_code": 0,
>   "started_at": "…",
>   "ended_at": "…",
>   "stdout_bytes": "…",
>   "stderr_bytes": 0,
>   "stdin": false,
>   "keep": false,
>   "pid": null,
>   "log": null
> }
> ```

A command's `status` is one of these:

| `status` | Means |
| - | - |
| `running` | Still running |
| `exited` | Ended by itself; `exit_code` is its code |
| `killed` | Stopped by a `kill` or by its `timeout_sec`; `exit_code` is what it returned (143 after `TERM`) |
| `detached` | A kept command, running on its own (see [keep a program running](#keep-a-program-running)) |
| `lost` | Fibre lost track of it before it ended (rare) |

The status also tells you when the command started and ended (`started_at`, `ended_at`) and how much output it has
written (`stdout_bytes`, `stderr_bytes`). To see every command in the sandbox, oldest first, call
`GET /v1/sandboxes/{id}/commands`, or `sbx.commands()` in the SDKs.

## Feed it input: drive a Python REPL

Some programs wait for input while they run: an interactive interpreter, a database shell, an agent that reads
instructions. To talk to one, start it with `stdin: true`. You can then write to its standard input as often as
you like while it runs.

In this example, a Python interpreter runs each line as it arrives, just as if you were typing into it:

```bash title="CLI" run theme={null}
printf 'x = 6 * 7\nprint(x)\nimport platform; print(platform.python_version())\n' \
  | fibre exec "$SBX" -i -- python3 -u -i -q   # 42 · 3.11.2: the end of input ends the interpreter
```

```typescript title="TypeScript" run theme={null}
const repl = await sbx.spawn(["python3", "-u", "-i", "-q"], { stdin: true });

await repl.write("x = 6 * 7\nprint(x)\n");
await repl.write("import platform; print(platform.python_version())\n");
await repl.closeStdin(); // end of input: the interpreter exits

const out = await repl.wait();
console.log(out.stdout); // 42 \n 3.11.2
```

```python title="Python" run theme={null}
repl = sbx.spawn(["python3", "-u", "-i", "-q"], stdin=True)

repl.write("x = 6 * 7\nprint(x)\n")
repl.write("import platform; print(platform.python_version())\n")
repl.close_stdin()  # end of input: the interpreter exits

out = repl.wait()
print(out.stdout)  # 42 \n 3.11.2
```

```bash title="curl" run capture=REPL=.command_id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["python3", "-u", "-i", "-q"], "stdin": true}'
```

```bash title="curl: write, then close" run theme={null}
printf 'x = 6 * 7\nprint(x)\n' | curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$REPL/stdin" \
  -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @-
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$REPL/stdin/close" -H "Authorization: Bearer $FIBRE_API_KEY"
curl -sSN "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$REPL/logs?follow=1" -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> {"data":"42\n","offset":0,"stream":"stdout"}
> ```

* **What you write is passed on exactly as it is**, including any binary data. The answer tells you how many bytes
  were written, for example `{"written": 19}`.
* **Closing standard input tells the program there is no more input** (an end-of-file). Most programs then finish
  their work and exit, as the interpreter does here.
* **The interpreter's `>>>` prompts go to `stderr`**, so `stdout` contains only the results.

The same approach works for any program that reads its input: a shell, `psql`, a language server, or an agent
that takes its instructions on standard input.

## Stop a command

To stop a background command, send it a **signal**, as you would with `kill` on your own machine. The signal goes
to the command and to every process it started, so nothing is left running behind it.

By default Fibre sends `TERM`, which politely asks the program to stop. If anything is still running 5 seconds
later, Fibre sends `KILL`, which cannot be ignored. If your program needs to clean up before it exits, send `INT`
instead (the same signal as pressing Ctrl-C), and give it the chance to finish:

```bash title="CLI" run theme={null}
JOB=$(fibre exec "$SBX" --detach --json -- python3 -u -c "
import time
try:
    time.sleep(300)
except KeyboardInterrupt:
    print('caught Ctrl-C, saving state and exiting')
" | jq -r .command_id)

sleep 1
fibre kill "$SBX" "$JOB" --signal INT   # like Ctrl-C: the program can clean up
fibre logs "$SBX" "$JOB"                # caught Ctrl-C, saving state and exiting
```

```typescript title="TypeScript" run theme={null}
const job = await sbx.spawn(["python3", "-u", "-c", [
  "import time",
  "try:",
  "    time.sleep(300)",
  "except KeyboardInterrupt:",
  "    print('caught Ctrl-C, saving state and exiting')",
].join("\n")]);

await new Promise((r) => setTimeout(r, 1000));
await job.kill({ signal: "INT" }); // like Ctrl-C: the program can clean up

const stopped = await job.wait();
console.log(stopped.status, stopped.stdout); // killed caught Ctrl-C, saving state and exiting
```

```python title="Python" run theme={null}
import time

job = sbx.spawn(["python3", "-u", "-c", "\n".join([
    "import time",
    "try:",
    "    time.sleep(300)",
    "except KeyboardInterrupt:",
    "    print('caught Ctrl-C, saving state and exiting')",
])])

time.sleep(1)
job.kill(signal="INT")  # like Ctrl-C: the program can clean up

stopped = job.wait()
print(stopped.status, stopped.stdout)  # killed caught Ctrl-C, saving state and exiting
```

```bash title="curl" run capture=JOB=.command_id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["sleep", "300"]}'
```

```bash title="curl: stop it" run theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$JOB/kill" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d '{}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "command_id": "…",
>   "command": ["sleep", "300"],
>   "status": "killed",
>   "exit_code": 143,
>   "started_at": "…",
>   "ended_at": "…",
>   "stdout_bytes": 0,
>   "stderr_bytes": 0,
>   "stdin": false,
>   "keep": false,
>   "pid": null,
>   "log": null
> }
> ```

These are the options for stopping a command:

| Option | Default | |
| - | - | - |
| `signal` | `TERM` | One of `TERM`, `INT`, `HUP`, `QUIT`, `USR1`, `USR2`, `KILL` |
| `grace_s` (`grace` in the SDKs) | `5` | Seconds before `KILL` if it is still running; `0` sends nothing after the signal |

If you already know how long a command should be allowed to run, set `timeout_sec` when you start it (`timeoutSec`
in `spawn()`). When the time is up, Fibre stops it in the same way, and its status becomes `killed`.

## Keep a program running

Some programs are meant to run indefinitely: a dev server, a database, a bot. They should keep running after the
call that started them, and they should still be running after the sandbox has slept and woken up again. To
achieve that, start them with `keep: true`:

```bash title="CLI" run theme={null}
fibre exec "$SBX" --cwd /work --detach --keep --json -- python3 -m http.server 8000   # "status": "detached", "pid": 21, "log": "/tmp/…"

fibre exec "$SBX" -- 'curl -s localhost:8000 | head -n 3'   # <!DOCTYPE HTML> …
```

```typescript title="TypeScript" run theme={null}
const server = await sbx.spawn(["python3", "-m", "http.server", "8000"], { cwd: "/work", keep: true });
console.log(server.status, server.pid, server.log); // detached 21 /tmp/fibre-command-….log

const page = await sbx.run("curl -s localhost:8000 | head -n 3");
console.log(page.stdout); // <!DOCTYPE HTML> …
```

```python title="Python" run theme={null}
server = sbx.spawn(["python3", "-m", "http.server", "8000"], cwd="/work", keep=True)
print(server.status, server.pid, server.log)  # detached 21 /tmp/fibre-command-….log

page = sbx.run("curl -s localhost:8000 | head -n 3")
print(page.stdout)  # <!DOCTYPE HTML> …
```

```bash title="curl" run capture=SERVER=.command_id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["python3", "-m", "http.server", "8000"], "cwd": "/work", "keep": true}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "command_id": "…",
>   "command": ["python3", "-m", "http.server", "8000"],
>   "status": "detached",
>   "exit_code": null,
>   "started_at": "…",
>   "ended_at": null,
>   "stdout_bytes": 0,
>   "stderr_bytes": 0,
>   "stdin": false,
>   "keep": true,
>   "pid": "…",
>   "log": "…"
> }
> ```

* **A kept command runs on its own**, so its status is `detached`. Its output is written to the file named in
  `log`, inside the sandbox, which you can read with the [files API](https://docs.fibre.dev/sandboxes/files.md). `pid` is its process ID.
* **It carries on across sleep and wake.** On the `standard` runtime, this is only true for programs started with
  `keep`. On the `vm` runtime every process survives a sleep. [Sleep and wake](https://docs.fibre.dev/sandboxes/sleep-and-wake.md) explains
  why.
* **You stop it with `kill`**, like any other command.
* **To reach it from the internet**, create the sandbox with an `exposed_port`. See
  [public URLs](https://docs.fibre.dev/connect/public-urls.md).

```bash title="curl: stop the server" run theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$SERVER/kill" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d '{}'
```

## Working directory and environment

Two options set the context a command runs in. **`cwd`** is the directory it starts in. **`env`** adds environment
variables for this one command, on top of the sandbox's own variables:

```bash title="CLI" run theme={null}
fibre exec "$SBX" --cwd /tmp --env GREETING=hi -- 'echo "$PWD says $GREETING"'   # /tmp says hi
```

```typescript title="TypeScript" run theme={null}
const where = await sbx.run('echo "$PWD says $GREETING"', { cwd: "/tmp", env: { GREETING: "hi" } });
console.log(where.stdout); // /tmp says hi
```

```python title="Python" run theme={null}
where = sbx.run('echo "$PWD says $GREETING"', cwd="/tmp", env={"GREETING": "hi"})
print(where.stdout)  # /tmp says hi
```

```bash title="curl" run capture=ENVCMD=.command_id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["sh", "-c", "echo \"$PWD says $GREETING\""], "cwd": "/tmp", "env": {"GREETING": "hi"}}'
```

```bash title="curl: its output" run theme={null}
curl -sSN "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$ENVCMD/logs?follow=1" -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> /tmp says hi
> ```

This is the right place for secrets that one command needs, such as a model API key for an agent. Fibre keeps the
values of `env` out of its logs and records, so the key reaches only that command and the programs it starts.

## After the sandbox sleeps

Commands and sleep work together in a few ways that are worth understanding:

* **A running command keeps the sandbox awake.** A sandbox never goes to sleep in the middle of a test run or an
  install.
* **Commands belong to the sandbox's current awake period.** Once the sandbox sleeps (which only happens after its
  commands have ended), the list of commands, their status and their output are cleared. Calls about them then
  answer `409 not_running`. Programs started with `keep`, and their log files, are not affected. If you need a
  command's output later, write it to a file.
* **Starting a command wakes a sleeping sandbox first**, like any other call. You do not need to wake it yourself.

## Limits

For reference, these are the limits that apply to commands:

| | |
| - | - |
| HTTP exec | 30 seconds; 4 MB of each stream |
| Background command | No time limit, or `timeout_sec`; output kept for the awake period |
| Signals | `TERM`, `INT`, `HUP`, `QUIT`, `USR1`, `USR2`, `KILL` |
| A write to stdin | Up to 8 MB per call |

## Errors

If a command call fails, the answer's `code` tells you why:

| Status | Code | When |
| - | - | - |
| 400 | `command_required` | `command` is missing or not a list of strings |
| 404 | `command_not_found` | No command with that ID in this awake period |
| 404 | `sandbox_not_found` | No sandbox with that ID |
| 409 | `not_running` | The sandbox is asleep: its commands ended with its last awake period |
| 409 | `keep_unavailable` | `keep` on a sandbox whose image runs its own entrypoint |

## Clean up

```bash title="CLI" run theme={null}
fibre delete "$SBX"
```

```typescript title="TypeScript" run theme={null}
await sbx.delete();
```

```python title="Python" run theme={null}
sbx.delete()
```

```bash title="curl" run theme={null}
curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY"
```

## Related

> [card] [Files](https://docs.fibre.dev/sandboxes/files.md)
>
> Put code and data into a sandbox, and take results out.

> [card] [Sleep and wake](https://docs.fibre.dev/sandboxes/sleep-and-wake.md)
>
> What keeps a sandbox awake, and what survives a sleep.

> [card] [Serve an app](https://docs.fibre.dev/connect/public-urls.md)
>
> Make a kept server reachable at the sandbox's HTTPS address.

> [card] [Claude Code in a sandbox](https://docs.fibre.dev/build-with-ai/claude-code.md)
>
> Run a coding agent as a background command.


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