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

# A sandbox tool for your agent framework

> Give an agent built with the AI SDK, OpenAI Agents or any framework one tool that runs its commands in a Fibre sandbox, one sandbox per conversation.

Many agents run inside your own app, built with a framework such as the AI SDK or OpenAI Agents. Those agents
often need to run code, and your app is the wrong place to run code a model wrote.

The solution is to give the agent a **tool** (a function the model can ask your app to call) that runs commands in
a Fibre sandbox. The model writes the commands, the sandbox runs them, and your app never runs model-written code
itself. Each conversation gets its own sandbox, which sleeps between turns while keeping everything the agent
installed and wrote.

**Before you start**, set your Fibre API key in `FIBRE_API_KEY` and `FIBRE_API_URL=https://api.fibre.dev`. For the
steps that call a model, you also need your model provider's API key.

## One sandbox per conversation

Create a sandbox when a conversation starts, and label it with the conversation's ID so that the next turn can
find it again:

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

const conversation = "conv-42";
const sbx = await Sandbox.create({ lifetime: 3600, labels: { conversation } });
```

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

conversation = "conv-42"
sbx = Sandbox.create(lifetime=3600, labels={"conversation": conversation})
```

```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": {"conversation": "conv-42"}}'
```

On every later turn, look the sandbox up by its label instead of creating a new one:

```typescript title="TypeScript" run theme={null}
let found: Sandbox | undefined;
for await (const s of Sandbox.list({ labels: { conversation } })) found ??= s;
console.log(found?.id === sbx.id); // true
```

```python title="Python" run theme={null}
found = next(iter(Sandbox.list(labels={"conversation": conversation})), None)
print(found is not None and found.id == sbx.id)  # True
```

```bash title="curl" run theme={null}
curl -sS "$FIBRE_API_URL/v1/sandboxes?label.conversation=conv-42&limit=1" -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "sandboxes": [
>     {
>       "labels": {
>         "conversation": "conv-42"
>       }
>     }
>   ]
> }
> ```

## The tool's function

The tool itself is a single function. It runs a shell command in the sandbox and returns the exit code and the end
of the output. Returning only the end matters: a command that prints a lot of text would otherwise fill up the
model's context. A command that runs for more than two minutes is stopped, and the model is told why.

```typescript title="TypeScript" run theme={null}
const MAX_OUTPUT = 10_000;

async function runCommand(command: string) {
  try {
    const r = await sbx.run(command, { timeout: 120 });
    return { exitCode: r.exitCode, stdout: r.stdout.slice(-MAX_OUTPUT), stderr: r.stderr.slice(-MAX_OUTPUT) };
  } catch (e) {
    if (e instanceof TimeoutError) return { error: "stopped after 120 seconds" };
    throw e;
  }
}

console.log(await runCommand('python3 -c "print(6 * 7)"')); // { exitCode: 0, stdout: '42\n', stderr: '' }
```

```python title="Python" run theme={null}
MAX_OUTPUT = 10_000


def run_command(command: str) -> dict:
    try:
        r = sbx.run(command, timeout=120)
        return {"exit_code": r.exit_code, "stdout": r.stdout[-MAX_OUTPUT:], "stderr": r.stderr[-MAX_OUTPUT:]}
    except FibreTimeoutError:
        return {"error": "stopped after 120 seconds"}


print(run_command('python3 -c "print(6 * 7)"'))  # {'exit_code': 0, 'stdout': '42\n', '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": ["sh", "-c", "python3 -c \"print(6 * 7)\""]}'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "exit_code": 0,
>   "stdout": "42\n"
> }
> ```

This is the function your app calls each time the model uses the tool.

## Hand it to the framework

Every framework describes a tool in the same way: a name, a description that the model reads to decide when to use
it, the shape of its input, and the function to call. Here is the same tool for the AI SDK and for OpenAI Agents:

```typescript title="AI SDK" norun reason="needs a model key and the ai, @ai-sdk/anthropic and zod packages" theme={null}
import { generateText, isStepCount, tool } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";

const { text } = await generateText({
  model: anthropic("claude-sonnet-5-5"),
  tools: {
    run_command: tool({
      description: "Run a shell command in this conversation's Linux sandbox. Returns the exit code and output.",
      inputSchema: z.object({ command: z.string().describe("the shell command to run") }),
      execute: ({ command }) => runCommand(command),
    }),
  },
  stopWhen: isStepCount(20),
  prompt: "Which Python version is installed? Write a script that prints it, then run the script.",
});
console.log(text);
```

```typescript title="OpenAI Agents" norun reason="needs a model key and the @openai/agents and zod packages" theme={null}
import { Agent, run, tool } from "@openai/agents";
import { z } from "zod";

const agent = new Agent({
  name: "coder",
  instructions: "You work in a Linux sandbox. Use run_command to run shell commands.",
  tools: [
    tool({
      name: "run_command",
      description: "Run a shell command in this conversation's Linux sandbox. Returns the exit code and output.",
      parameters: z.object({ command: z.string() }),
      execute: ({ command }) => runCommand(command),
    }),
  ],
});

const result = await run(agent, "Which Python version is installed? Write a script that prints it, then run the script.");
console.log(result.finalOutput);
```

```python title="OpenAI Agents (Python)" norun reason="needs a model key and the openai-agents package" theme={null}
from agents import Agent, Runner, function_tool


@function_tool(name_override="run_command")
def run_command_tool(command: str) -> dict:
    """Run a shell command in this conversation's Linux sandbox. Returns the exit code and output."""
    return run_command(command)


agent = Agent(
    name="coder",
    instructions="You work in a Linux sandbox. Use run_command to run shell commands.",
    tools=[run_command_tool],
)

result = Runner.run_sync(agent, "Which Python version is installed? Write a script that prints it, then run the script.")
print(result.final_output)
```

Other frameworks, such as Mastra, LangGraph or a loop you wrote yourself, can use the same function. If your agent
edits many files, add tools for [files](https://docs.fibre.dev/sandboxes/files.md) (`sbx.files.read`, `sbx.files.write`). If it needs the web,
add a tool for the sandbox's [browser](https://docs.fibre.dev/connect/browser.md).

## What the model can reach

It is worth being clear about what the model can and cannot reach through this tool:

* **It can only reach the sandbox.** Your Fibre API key stays in your app, inside `runCommand`. The model sends a
  command and gets its output back, but never sees the key.
* **The sandbox has none of your app's secrets or files**, unless you put them there. Anything you do put there,
  the model can read with its next command.
* **The sandbox can reach the internet**, so the agent can install packages and fetch pages. To limit that, see
  [network access](https://docs.fibre.dev/production/network.md).

## Between turns

Between turns, the sandbox goes to sleep after its idle timeout, with its memory and files saved, and the next tool
call wakes it. A conversation can therefore pause for minutes or hours and pick up again with everything in place.
Read more in [sleep, wake and lifetime](https://docs.fibre.dev/sandboxes/sleep-and-wake.md).

## When the conversation ends

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

If you do not delete it, it is deleted automatically when the lifetime it was given ends.


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