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

# An agent built on the Claude Agent SDK

> Run your own agent, written with Anthropic's Claude Agent SDK, inside a Fibre sandbox, and let the sandbox's sleep keep its session between tasks.

The Claude Agent SDK lets you build your own agent on the same foundation as Claude Code. Your agent can read
files, edit them and run commands, on whatever machine it runs on. That is exactly why that machine should be a
sandbox, not your own server.

Anthropic's hosting guide suggests a separate container for each session, and recommends shutting idle containers
down and rebuilding them from saved sessions to save money. A Fibre sandbox does that part for you: when the agent
is idle, the sandbox sleeps with its memory and files, and the next task wakes it exactly where it was.

**Before you start**, set your Fibre API key in `FIBRE_API_KEY` and `FIBRE_API_URL=https://api.fibre.dev`. For the
steps where the agent 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-agent-sdk --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-agent-sdk" } });
```

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

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

```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-agent-sdk"}}'
```

## Install the SDK

Create a small Node project in the sandbox and install the SDK from npm. This 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 -- 'mkdir -p /work/agent && cd /work/agent && npm init -y > /dev/null && npm install @anthropic-ai/claude-agent-sdk && npm ls --depth 0'
```

```typescript title="TypeScript" run theme={null}
const install = await sbx.run(
  "mkdir -p /work/agent && cd /work/agent && npm init -y >/dev/null && npm install @anthropic-ai/claude-agent-sdk && npm ls --depth 0",
  { timeout: 600 },
);
if (install.exitCode !== 0) throw new Error(install.stderr);
console.log(install.stdout.trim().split("\n").pop()); // └── @anthropic-ai/claude-agent-sdk@…
```

```python title="Python" run theme={null}
install = sbx.run(
    "python3 -m venv /work/agent && /work/agent/bin/pip install -q claude-agent-sdk && /work/agent/bin/pip show claude-agent-sdk | head -n 2",
    timeout=600,
)
if install.exit_code != 0:
    raise RuntimeError(install.stderr)
print(install.stdout.strip().split("\n")[-1])  # Version: …
```

```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", "mkdir -p /work/agent && cd /work/agent && npm init -y >/dev/null && npm install @anthropic-ai/claude-agent-sdk && npm ls --depth 0"]}' | 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}
> @anthropic-ai/claude-agent-sdk@
> ```

## Write the agent

The agent itself is a short program. It reads its task from the `TASK` environment variable and works in the
directory it is started in. When you start it with `--continue`, it resumes the most recent session in that
directory instead of starting a new one.

```bash title="CLI" run theme={null}
fibre exec "$SBX" -i -- sh -c 'cat > /work/agent/agent.mjs' <<'JS'
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: process.env.TASK,
  options: {
    allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"],
    permissionMode: "acceptEdits",
    continue: process.argv.includes("--continue"),
  },
})) {
  if (message.type === "result") console.log(message.subtype === "success" ? message.result : message.subtype);
}
JS
```

```typescript title="TypeScript" run theme={null}
await sbx.files.write(
  "/work/agent/agent.mjs",
  `import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: process.env.TASK,
  options: {
    allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"],
    permissionMode: "acceptEdits",
    continue: process.argv.includes("--continue"),
  },
})) {
  if (message.type === "result") console.log(message.subtype === "success" ? message.result : message.subtype);
}
`,
);
```

```python title="Python" run theme={null}
sbx.files.write("/work/agent/agent.py", """import os, sys
import anyio
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query

async def main():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Edit", "Glob", "Grep", "Bash"],
        permission_mode="acceptEdits",
        continue_conversation="--continue" in sys.argv,
    )
    async for message in query(prompt=os.environ["TASK"], options=options):
        if isinstance(message, ResultMessage):
            print(message.result if message.subtype == "success" else message.subtype)

anyio.run(main)
""")
```

```bash title="curl" run theme={null}
AGENT=$(mktemp)
cat > "$AGENT" <<'EOF'
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: process.env.TASK,
  options: {
    allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"],
    permissionMode: "acceptEdits",
    continue: process.argv.includes("--continue"),
  },
})) {
  if (message.type === "result") console.log(message.subtype === "success" ? message.result : message.subtype);
}
EOF
curl -sS -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/agent/agent.mjs" \
  -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @"$AGENT"
```

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

Now run the agent in the repository. The API key and the task are given to this one command only. There is more
about the key [below](#the-api-key).

```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." \
  -- node /work/agent/agent.mjs
```

```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null}
const task = await sbx.run(["node", "/work/agent/agent.mjs"], {
  cwd: "/work/repo",
  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(task.stdout);
```

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

task = sbx.run(
    ["/work/agent/bin/python", "/work/agent/agent.py"],
    cwd="/work/repo",
    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(task.stdout)
```

```bash title="curl" norun reason="needs your Anthropic API key" theme={null}
jq -n --arg key "$ANTHROPIC_API_KEY" '{
  command: ["node", "/work/agent/agent.mjs"], cwd: "/work/repo",
  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 @-
```

## The next task, later

When the agent has finished, the sandbox goes to sleep after its idle timeout, with its memory and files saved, and
the next command wakes it. The SDK keeps its sessions on the sandbox's disk, so `--continue` picks up the whole
conversation. You do not need a session store of your own, and nothing has to be rebuilt.

```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." \
  -- node /work/agent/agent.mjs --continue
```

```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null}
const again = await Sandbox.get(sbx.id);
const next = await again.run(["node", "/work/agent/agent.mjs", "--continue"], {
  cwd: "/work/repo",
  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(
    ["/work/agent/bin/python", "/work/agent/agent.py", "--continue"],
    cwd="/work/repo",
    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: ["node", "/work/agent/agent.mjs", "--continue"], cwd: "/work/repo",
  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 @-
```

An agent that keeps running between tasks, such as a small server that your app sends tasks to, can sleep too.
Start it with `keep: true`, and the process itself is kept across sleep, even in the middle of a conversation. See
[sleep, wake and lifetime](https://docs.fibre.dev/sandboxes/sleep-and-wake.md).

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