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

# Claude Code in a sandbox

> Install Claude Code in a Fibre sandbox, give it a repository, run a task headless, read what it changed, and come back to the same session later.

Claude Code is Anthropic's coding agent. It can run without an interactive terminal, using `claude -p`, which means
it can work inside a sandbox. There it gets a Linux machine of its own, with the repository, the tools and the shell
it needs, and nothing it does can touch your computer.

Between tasks, the sandbox sleeps with its memory and files. The next task then finds the agent, its session and its
work exactly where they were.

**Before you start**, set your Fibre API key in `FIBRE_API_KEY` and `FIBRE_API_URL=https://api.fibre.dev`. For the
steps where Claude Code talks to Claude, you also need an Anthropic API key in `ANTHROPIC_API_KEY`.

## Start a sandbox

```bash title="CLI" run theme={null}
SBX=$(fibre create --lifetime 1h --label example=claude-code --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: "claude-code" } });
```

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

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

```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": "claude-code"}}'
```

## Install Claude Code

Anthropic's installer puts the `claude` program in `~/.local/bin`. It takes about 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 -- 'curl -fsSL https://claude.ai/install.sh | bash && ~/.local/bin/claude --version'   # 2.1.329 (Claude Code)
```

```typescript title="TypeScript" run theme={null}
const install = await sbx.run("curl -fsSL https://claude.ai/install.sh | bash && ~/.local/bin/claude --version", { timeout: 600 });
if (install.exitCode !== 0) throw new Error(install.stderr);
console.log(install.stdout.trim().split("\n").pop()); // 2.1.329 (Claude Code)
```

```python title="Python" run theme={null}
install = sbx.run("curl -fsSL https://claude.ai/install.sh | bash && ~/.local/bin/claude --version", timeout=600)
if install.exit_code != 0:
    raise RuntimeError(install.stderr)
print(install.stdout.strip().split("\n")[-1])  # 2.1.329 (Claude Code)
```

```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", "curl -fsSL https://claude.ai/install.sh | bash && ~/.local/bin/claude --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
> ```

To avoid installing it in every new sandbox, install it once and save that sandbox as a
[snapshot](https://docs.fibre.dev/setup/snapshots.md). New sandboxes created from the snapshot already have Claude Code.

## 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
> }
> ```

A private repository works the same way. Use a token in the URL, or write a deploy key into the sandbox.

## Run a task

The task is passed in `TASK`, and the key in `ANTHROPIC_API_KEY`. Both are given to this one command only (there is
more about the key [below](#the-api-key)). `--allowedTools` lists what Claude Code may do without asking for
permission. Since nobody is there to answer its questions, anything not on that list is simply refused.

```bash title="CLI" norun reason="needs your Anthropic API key" theme={null}
fibre exec "$SBX" --cwd /work/repo --timeout 30m \
  --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" --env TASK="Rewrite the README as a short project description with a usage section." \
  -- '~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash"'
```

```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null}
const task = await sbx.run(
  ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash" --output-format json'],
  {
    env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY!, TASK: "Rewrite the README as a short project description with a usage section." },
    timeout: 1800,
  },
);
console.log(JSON.parse(task.stdout).result);
```

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

task = sbx.run(
    ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash" --output-format json'],
    env={"ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"], "TASK": "Rewrite the README as a short project description with a usage section."},
    timeout=1800,
)
print(json.loads(task.stdout)["result"])
```

```bash title="curl" norun reason="needs your Anthropic API key" theme={null}
jq -n --arg key "$ANTHROPIC_API_KEY" '{
  command: ["sh", "-c", "cd /work/repo && ~/.local/bin/claude -p \"$TASK\" --allowedTools \"Read,Edit,Bash\" --output-format json"],
  env: {ANTHROPIC_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 @-
```

With `--output-format json`, the last line of output is a single JSON object. It holds Claude Code's answer in
`result`, the session's ID in `session_id`, and the cost in `total_cost_usd`. 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
> }
> ```

You can read any file it wrote with `sbx.files.read`, or let it commit its work and push a branch from the sandbox.

## The next task, later

If you leave the sandbox alone, it goes to sleep after its idle timeout, with its memory and files saved. The next
command wakes it, and the repository, the installed agent and Claude Code's own session history are all still
there. `--continue` picks up the conversation exactly where it stopped:

```bash title="CLI" norun reason="needs your Anthropic API key" theme={null}
fibre exec "$SBX" --cwd /work/repo --timeout 30m --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" --env TASK="Now add a contributing section." \
  -- '~/.local/bin/claude -p "$TASK" --continue --allowedTools "Read,Edit,Bash"'
```

```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null}
const again = await Sandbox.get(sbx.id);
const next = await again.run(
  ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --continue --allowedTools "Read,Edit,Bash" --output-format json'],
  { env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY!, TASK: "Now add a contributing section." }, timeout: 1800 },
);
```

```python title="Python" norun reason="needs your Anthropic API key" theme={null}
again = Sandbox.get(sbx.id)
nxt = again.run(
    ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --continue --allowedTools "Read,Edit,Bash" --output-format json'],
    env={"ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"], "TASK": "Now add a contributing section."},
    timeout=1800,
)
```

```bash title="curl" norun reason="needs your Anthropic API key" theme={null}
jq -n --arg key "$ANTHROPIC_API_KEY" '{
  command: ["sh", "-c", "cd /work/repo && ~/.local/bin/claude -p \"$TASK\" --continue --allowedTools \"Read,Edit,Bash\" --output-format json"],
  env: {ANTHROPIC_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 rather than the most recent one, use `--resume <session_id>`. To keep the sandbox
past the lifetime it was given, extend or remove it with `sbx.update({ lifetime })`. Read more in
[sleep, wake and lifetime](https://docs.fibre.dev/sandboxes/sleep-and-wake.md).

## The API key

Claude Code needs your Anthropic 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 Claude Code runs while it works can read it**, including tests, install scripts and code in the
  repository. Treat the key as visible to that repository's code. Use a key you can revoke, with a spending limit,
  and avoid giving a high-spending key to a sandbox that runs code you do not trust.
* **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.