> ## 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.

# Codex in a sandbox

> Install OpenAI's Codex CLI in a Fibre sandbox, run a task on a repository with codex exec, read the result, and resume the same session later.

Codex is OpenAI's coding agent. Its `codex exec` command runs Codex without an interactive terminal: it works
through a task on its own, prints its progress to `stderr`, and prints its final message to `stdout`.

If you run it in a Fibre sandbox, Codex gets a Linux machine of its own for the repository, its builds and its
tests, well away from your computer. Between tasks the sandbox sleeps with its memory and files, so the next task
can carry on in the same session.

This page shows the whole process, from an empty sandbox to a finished change.

**Before you start**, set your Fibre API key in `FIBRE_API_KEY` and `FIBRE_API_URL=https://api.fibre.dev`. For
the steps where Codex talks to its model, you also need an OpenAI API key in `CODEX_API_KEY`.

## Start a sandbox

```bash title="CLI" run theme={null}
SBX=$(fibre create --lifetime 1h --label example=codex --json | jq -r .id)
```

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

const sbx = await Sandbox.create({ lifetime: 3600, labels: { example: "codex" } });
```

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

sbx = Sandbox.create(lifetime=3600, labels={"example": "codex"})
```

```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": 3600, "labels": {"example": "codex"}}'
```

## Install Codex

Codex is installed from npm, and the sandbox's default image already has Node. The install takes about half a
minute, which is longer than an exec allows, so it runs as a [background command](https://docs.fibre.dev/sandboxes/running-commands.md).

```bash title="CLI" run theme={null}
fibre exec "$SBX" --timeout 10m -- 'npm install -g @openai/codex && codex --version'   # codex-cli 0.171.0
```

```typescript title="TypeScript" run theme={null}
const install = await sbx.run("npm install -g @openai/codex && codex --version", { timeout: 600 });
if (install.exitCode !== 0) throw new Error(install.stderr);
console.log(install.stdout.trim().split("\n").pop()); // codex-cli 0.171.0
```

```python title="Python" run theme={null}
install = sbx.run("npm install -g @openai/codex && codex --version", timeout=600)
if install.exit_code != 0:
    raise RuntimeError(install.stderr)
print(install.stdout.strip().split("\n")[-1])  # codex-cli 0.171.0
```

```bash title="curl" run theme={null}
CMD=$(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", "npm install -g @openai/codex && codex --version"]}' | jq -r .command_id)
curl -sSN "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$CMD/logs?follow=1" -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> "exit_code":0
> ```

## Give it a repository

```bash title="CLI" run theme={null}
fibre exec "$SBX" -- git clone --depth 1 https://github.com/octocat/Hello-World /work/repo
```

```typescript title="TypeScript" run theme={null}
const clone = await sbx.run(["git", "clone", "--depth", "1", "https://github.com/octocat/Hello-World", "/work/repo"]);
if (clone.exitCode !== 0) throw new Error(clone.stderr);
```

```python title="Python" run theme={null}
clone = sbx.run(["git", "clone", "--depth", "1", "https://github.com/octocat/Hello-World", "/work/repo"])
if clone.exit_code != 0:
    raise RuntimeError(clone.stderr)
```

```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": ["git", "clone", "--depth", "1", "https://github.com/octocat/Hello-World", "/work/repo"]}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "exit_code": 0
> }
> ```

## Run a task

By default, `codex exec` is only allowed to read files. Codex has a flag for running inside a machine that is
already isolated, `--dangerously-bypass-approvals-and-sandbox`, which lets it edit files and run commands freely.
The Fibre sandbox is exactly that kind of machine, so whatever Codex does stays inside it.

The key is passed as `CODEX_API_KEY`, to this one command only, as Codex's documentation recommends. There is more
about the key [below](#the-api-key).

```bash title="CLI" norun reason="needs your OpenAI API key" theme={null}
fibre exec "$SBX" --cwd /work/repo --timeout 30m \
  --env CODEX_API_KEY="$CODEX_API_KEY" --env TASK="Rewrite the README as a short project description with a usage section." \
  -- 'codex exec --dangerously-bypass-approvals-and-sandbox "$TASK"'
```

```typescript title="TypeScript" norun reason="needs your OpenAI API key" theme={null}
const task = await sbx.run(
  ["sh", "-c", 'cd /work/repo && codex exec --dangerously-bypass-approvals-and-sandbox "$TASK"'],
  {
    env: { CODEX_API_KEY: process.env.CODEX_API_KEY!, TASK: "Rewrite the README as a short project description with a usage section." },
    timeout: 1800,
  },
);
console.log(task.stdout); // Codex's final message
```

```python title="Python" norun reason="needs your OpenAI API key" theme={null}
import os

task = sbx.run(
    ["sh", "-c", 'cd /work/repo && codex exec --dangerously-bypass-approvals-and-sandbox "$TASK"'],
    env={"CODEX_API_KEY": os.environ["CODEX_API_KEY"], "TASK": "Rewrite the README as a short project description with a usage section."},
    timeout=1800,
)
print(task.stdout)  # Codex's final message
```

```bash title="curl" norun reason="needs your OpenAI API key" theme={null}
jq -n --arg key "$CODEX_API_KEY" '{
  command: ["sh", "-c", "cd /work/repo && codex exec --dangerously-bypass-approvals-and-sandbox \"$TASK\""],
  env: {CODEX_API_KEY: $key, TASK: "Rewrite the README as a short project description with a usage section."}
}' | curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d @-
```

If you want more detail, add `--json` to get one JSON event per line, including every command Codex ran and every
file it changed. Or add `--output-last-message <file>` to save the final message in a file. With curl, follow the
command's output in the same way as in the install step.

## See what it changed

```bash title="CLI" run theme={null}
fibre exec "$SBX" -- git -C /work/repo diff --stat
```

```typescript title="TypeScript" run theme={null}
const diff = await sbx.run(["git", "-C", "/work/repo", "diff", "--stat"]);
console.log(diff.stdout);
```

```python title="Python" run theme={null}
diff = sbx.run(["git", "-C", "/work/repo", "diff", "--stat"])
print(diff.stdout)
```

```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": ["git", "-C", "/work/repo", "diff", "--stat"]}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "exit_code": 0
> }
> ```

## The next task, later

When Codex has finished, the sandbox goes to sleep after its idle timeout, with its memory and files saved. The
next command wakes it up. Codex keeps its sessions on the sandbox's disk, so `codex exec resume --last` carries on
the most recent session, with everything Codex already learned about the repository.

```bash title="CLI" norun reason="needs your OpenAI API key" theme={null}
fibre exec "$SBX" --cwd /work/repo --timeout 30m --env CODEX_API_KEY="$CODEX_API_KEY" --env TASK="Now add a contributing section." \
  -- 'codex exec resume --last --dangerously-bypass-approvals-and-sandbox "$TASK"'
```

```typescript title="TypeScript" norun reason="needs your OpenAI API key" theme={null}
const again = await Sandbox.get(sbx.id);
const next = await again.run(
  ["sh", "-c", 'cd /work/repo && codex exec resume --last --dangerously-bypass-approvals-and-sandbox "$TASK"'],
  { env: { CODEX_API_KEY: process.env.CODEX_API_KEY!, TASK: "Now add a contributing section." }, timeout: 1800 },
);
```

```python title="Python" norun reason="needs your OpenAI API key" theme={null}
again = Sandbox.get(sbx.id)
nxt = again.run(
    ["sh", "-c", 'cd /work/repo && codex exec resume --last --dangerously-bypass-approvals-and-sandbox "$TASK"'],
    env={"CODEX_API_KEY": os.environ["CODEX_API_KEY"], "TASK": "Now add a contributing section."},
    timeout=1800,
)
```

```bash title="curl" norun reason="needs your OpenAI API key" theme={null}
jq -n --arg key "$CODEX_API_KEY" '{
  command: ["sh", "-c", "cd /work/repo && codex exec resume --last --dangerously-bypass-approvals-and-sandbox \"$TASK\""],
  env: {CODEX_API_KEY: $key, TASK: "Now add a contributing section."}
}' | curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d @-
```

To continue a particular session instead, use `codex exec resume <session id>`.

## The API key

The agent needs your model provider's API key, so it is worth understanding exactly where that key goes:

* **Only the command you give it to can see it**, along with the programs that command starts. Other commands
  in the sandbox do not get it, Fibre does not write it into the sandbox's files, and Fibre's API never returns
  it.
* **Everything Codex runs while it works can read it**, including tests, install scripts and code in the
  repository. Treat it as
  visible to that repository's code. Use a key you can revoke, with a spending limit.
* **Do not put the key in the sandbox's own environment** (`env` in the SDK, or `env_vars` in the API, when you
  create the sandbox). Every command in the sandbox would then get it.

## Delete it

```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"
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "deleted": true
> }
> ```


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