# Fibre > This file is very large and may be truncated. For an index of this content, please refer to https://docs.fibre.dev/llms.txt instead. > Sandboxes for agents and the code they write: start one, run commands in it, let it sleep with its memory and wake on the next call. # Create an API key Source: https://docs.fibre.dev/api-reference/api-keys/create-an-api-key /api-reference/openapi.json post /v1/auth/api-keys Create a key, limited to `scopes`, bound to one sandbox with `resource`, and expiring after `expires_in_sec`. The key is in the answer once; only a digest is kept. A key can create keys only with `keys.write`, and never one broader or longer-lived than itself. # List API keys Source: https://docs.fibre.dev/api-reference/api-keys/list-api-keys /api-reference/openapi.json get /v1/auth/api-keys Your account's keys: name, prefix, scopes, binding, expiry and last use. Never the keys themselves. # Revoke an API key Source: https://docs.fibre.dev/api-reference/api-keys/revoke-an-api-key /api-reference/openapi.json delete /v1/auth/api-keys/{id} Revoke a key. It stops working at once. # Add funds Source: https://docs.fibre.dev/api-reference/billing/add-funds /api-reference/openapi.json post /v1/billing/topup A link to a checkout page that adds money to the balance. # Get spend Source: https://docs.fibre.dev/api-reference/billing/get-spend /api-reference/openapi.json get /v1/billing/usage/summary Spend today, this week, this month, and this month's projection, in US dollars. # Get the billing account Source: https://docs.fibre.dev/api-reference/billing/get-the-billing-account /api-reference/openapi.json get /v1/billing/account Plan, status, credit, balance, auto top-up, limits, today's usage against them, and storage. # Get usage Source: https://docs.fibre.dev/api-reference/billing/get-usage /api-reference/openapi.json get /v1/billing/usage Awake hours and cost in a period, this month unless you pass `from` and `to`. # List awake sandboxes Source: https://docs.fibre.dev/api-reference/billing/list-awake-sandboxes /api-reference/openapi.json get /v1/billing/current The billing sessions open now: every sandbox awake and being charged. # List ledger entries Source: https://docs.fibre.dev/api-reference/billing/list-ledger-entries /api-reference/openapi.json get /v1/billing/ledger Every charge and payment, newest first, with how much came from plan credit and how much from the balance. # Open the billing portal Source: https://docs.fibre.dev/api-reference/billing/open-the-billing-portal /api-reference/openapi.json post /v1/billing/portal A link to manage the card and download invoices. # Set auto top-up Source: https://docs.fibre.dev/api-reference/billing/set-auto-top-up /api-reference/openapi.json put /v1/billing/auto-topup Turn automatic top-up on or off, with the balance that triggers it and the amount it adds. # Start a checkout Source: https://docs.fibre.dev/api-reference/billing/start-a-checkout /api-reference/openapi.json post /v1/billing/checkout A link to a checkout page to start or change a plan. # Close the browser Source: https://docs.fibre.dev/api-reference/browser-and-desktop/close-the-browser /api-reference/openapi.json delete /v1/sandboxes/{id}/browser Revoke every link to the browser, close their connections and stop the browser. The sandbox keeps running. # Get a desktop link Source: https://docs.fibre.dev/api-reference/browser-and-desktop/get-a-desktop-link /api-reference/openapi.json post /v1/sandboxes/{id}/desktop A single-use link to watch and use the sandbox's desktop (a sandbox created with `needs: ["desktop"]`). It expires if nobody opens it within `expires_in` seconds. # Get browser links Source: https://docs.fibre.dev/api-reference/browser-and-desktop/get-browser-links /api-reference/openapi.json post /v1/sandboxes/{id}/browser Start the sandbox's browser if needed and return two links: `cdp_url` for your code (a credential: keep it on your server) and `live_view_url` for a person to watch. They work for an hour, or `ttl_sec`. # Close a command's input Source: https://docs.fibre.dev/api-reference/commands/close-a-commands-input /api-reference/openapi.json post /v1/sandboxes/{id}/commands/{cid}/stdin/close Close the command's standard input: it reads end-of-file. # Get a command Source: https://docs.fibre.dev/api-reference/commands/get-a-command /api-reference/openapi.json get /v1/sandboxes/{id}/commands/{cid} A command's status and exit code. # List commands Source: https://docs.fibre.dev/api-reference/commands/list-commands /api-reference/openapi.json get /v1/sandboxes/{id}/commands The commands of the sandbox's current awake period, oldest first. After a sleep they are gone. # Read a command's output Source: https://docs.fibre.dev/api-reference/commands/read-a-commands-output /api-reference/openapi.json get /v1/sandboxes/{id}/commands/{cid}/logs The command's output as newline-delimited JSON: one object per piece of output (`stream`, `offset`, `data`; `encoding: "base64"` when not UTF-8), then `{"event": "end", "status", "exit_code"}` once it has ended. With `follow=1` the answer stays open and streams output as it is written. Start from `stdout_offset` and `stderr_offset` to read only what is new. # Start a command Source: https://docs.fibre.dev/api-reference/commands/start-a-command /api-reference/openapi.json post /v1/sandboxes/{id}/commands Start a command in the background and answer at once with its status. It runs until it ends, is killed, or reaches `timeout_sec`; a running command keeps the sandbox awake. With `stdin: true` you can write to it; with `keep: true` it runs on its own and carries on across sleep (status `detached`, output in the file named in `log`). A sleeping sandbox is woken first. # Stop a command Source: https://docs.fibre.dev/api-reference/commands/stop-a-command /api-reference/openapi.json post /v1/sandboxes/{id}/commands/{cid}/kill Send a signal to the command and every process it started (`TERM` unless you choose another), then `KILL` to whatever is left after `grace_s` seconds (5). # Write to a command Source: https://docs.fibre.dev/api-reference/commands/write-to-a-command /api-reference/openapi.json post /v1/sandboxes/{id}/commands/{cid}/stdin Write the request body, as it is, to the command's standard input (up to 8 MB per call). The command must have been started with `stdin: true`. # Errors Source: https://docs.fibre.dev/api-reference/errors Every error code the Fibre API answers with: its HTTP status, what it means, and what to do. Every error has the same fields: `error` (a sentence), `code` (stable, safe to match on), `request_id` (for support) and `docs_url` (this page, at the code). How to handle them in code, and which to retry: [errors, retries and limits](/production/errors-and-limits). ## General | Code | Status | Meaning | | - | - | - | | `invalid_request` | 400 | The request is malformed or a parameter is wrong | | `unauthorized` | 401 | The request is not authenticated | | `forbidden` | 403 | The credentials do not allow this | | `not_found` | 404 | Nothing exists at this path or with this name | | `conflict` | 409 | The request conflicts with the resource's current state | | `payload_too_large` | 413 | The request body is larger than allowed | | `rate_limited` | 429 | Too many requests: wait and retry | | `internal` | 500 | Something failed inside Fibre; the request id identifies it | | `unavailable` | 503 | A part of Fibre is unavailable for now: retry later | | `invalid_json` | 400 | The body is not valid JSON | | `validation_failed` | 400 | The body does not match the route's schema; `details` names the fields | ## Authentication and keys | Code | Status | Meaning | | - | - | - | | `missing_credentials` | 401 | No `Authorization: Bearer …` header | | `invalid_api_key` | 401 | The API key is malformed, unknown, revoked or expired | | `invalid_token` | 401 | The access token is invalid or expired | | `insufficient_scope` | 403 | The API key's scopes do not cover this route; `required` names the scope | | `key_resource_bound` | 403 | The API key is limited to one sandbox | | `key_broader` | 403 | A key cannot grant more than the key that creates it | | `unknown_scope` | 400 | A requested scope does not exist; `areas` lists the valid areas | | `api_key_not_found` | 404 | No API key with this id | | `key_resource_not_found` | 404 | No sandbox with this ID to bind the key to | ## Sandboxes | Code | Status | Meaning | | - | - | - | | `sandbox_not_found` | 404 | No sandbox with this id in the organization | | `sandbox_limit` | 429 | The organization keeps as many sandboxes as its plan allows, awake or asleep: delete some first | | `size_too_large` | 400 | The requested CPU and memory are larger than the largest size | | `needs_vm` | 400 | A listed need (`docker`, `fuse`, …) runs only on runtime `vm`, but the runtime is `standard` | | `init_needs_vm` | 400 | `init` (systemd as PID 1) runs only on runtime `vm` | | `runtime_conflict` | 400 | `runtime` and the older `runtime_type` name different runtimes: send `runtime` only | | `vm_unavailable` | 503 | No host that runs VMs is available: retry later, or use runtime `standard` if no need requires a VM | | `invalid_cursor` | 400 | The `cursor` is not one this list returned: pass `next_cursor` as it came | | `invalid_idempotency_key` | 400 | `Idempotency-Key` must be 1 to 255 printable characters without spaces | | `idempotency_key_reused` | 422 | This `Idempotency-Key` was used with another request in the last 24 h: use a new key | | `idempotency_key_in_progress` | 409 | The first request with this `Idempotency-Key` is still running: retry later | | `snapshot_fields_fixed` | 400 | A sandbox started from a snapshot takes these fields from the snapshot | | `create_failed` | 503 | Creating the sandbox failed and nothing was left behind: retry | | `start_failed` | 503 | The sandbox failed to start: check the image and its entrypoint | | `engine_error` | 503 | The sandbox failed to start: retry, or check the image and its entrypoint | | `no_capacity` | 503 | No host has room for this sandbox now: retry later | | `not_running` | 409 | The sandbox is asleep or not running | | `command_required` | 400 | `command` must be a non-empty array of strings | | `exec_failed` | 502 | The command could not be run in the sandbox | | `exec_timeout` | 504 | The command ran past exec's 30 s limit and was stopped: start long commands in the background | | `engine_unreachable` | 502 | The sandbox's host did not answer: retry | ## Commands | Code | Status | Meaning | | - | - | - | | `command_not_found` | 404 | No command with this id in the sandbox's current awake period | ## Files | Code | Status | Meaning | | - | - | - | | `path_required` | 400 | The `path` parameter is required | | `invalid_path` | 400 | The path is not valid | | `file_not_found` | 404 | No file or directory at this path | | `file_is_directory` | 400 | The path is a directory, not a file | | `file_not_directory` | 400 | A part of the path is a file, not a directory | | `file_permission_denied` | 403 | The sandbox's user may not read or write this path | | `file_exists` | 409 | Something exists at this path already | | `directory_not_empty` | 409 | The directory is not empty: delete it with `recursive=true` | | `file_too_large` | 413 | The file is larger than allowed | | `upload_aborted` | 400 | The upload ended before its last byte; nothing was written | | `disk_full` | 507 | The sandbox's disk is full | | `files_unsupported` | 501 | This file operation is not supported on this sandbox | ## Secrets | Code | Status | Meaning | | - | - | - | | `secret_not_found` | 404 | No stored secret with this name: set it first (`POST /v1/secrets`) | ## Snapshots and images | Code | Status | Meaning | | - | - | - | | `snapshot_not_found` | 404 | No snapshot with this name in the organization | | `snapshot_exists` | 409 | A snapshot with this name exists | | `snapshot_source_not_found` | 404 | No sandbox to take the snapshot of | | `snapshot_source_unsupported` | 400 | A snapshot cannot be taken of this sandbox | | `snapshot_in_use` | 409 | Sandboxes still restore from this snapshot | | `snapshot_failed` | 502 | Taking the snapshot failed | | `snapshot_timeout` | 504 | The snapshot is still uploading: retry later | | `image_required` | 400 | No image or snapshot named, and this deployment has no default image | | `image_not_owned` | 403 | The image belongs to another organization | | `keep_unavailable` | 409 | keep needs Fibre's keep-alive as the sandbox's first process: this sandbox runs its own entrypoint | | `desktop_unavailable` | 503 | The desktop did not come up after the create (the image is not a Fibre desktop image, or it failed to start) | | `browser_unavailable` | 409 | The sandbox's browser cannot start: its image has none (use the default image, or one built from it), or Chrome did not come up | | `browser_unreachable` | 502 | The sandbox's browser did not answer through its tunnel | | `image_registry_refused` | 400 | Images from this registry are not allowed | | `image_not_found` | 404 | The image does not exist in its registry | | `image_access_denied` | 403 | The registry refused access to the image: check the registry credentials | | `image_too_large` | 413 | The image is larger than allowed | | `image_rate_limited` | 429 | The image's registry is rate limiting pulls: retry later | | `image_pull_failed` | 502 | Pulling the image failed | | `image_pull_timeout` | 502 | Pulling the image took too long | | `build_limit` | 429 | The organization has as many builds running as allowed | ## Billing and limits | Code | Status | Meaning | | - | - | - | | `payment_required` | 402 | Out of credit: add funds or turn on auto top-up | | `subscription_required` | 402 | Choose a plan or start the trial to run sandboxes | | `trial_limit` | 402 | The trial does not allow this: choose a plan | | `spend_limit` | 402 | The organization's spend limit is reached | | `invalid_plan` | 400 | No plan with this id | | `invalid_amount` | 400 | The amount is outside the allowed range | | `billing_provider_error` | 502 | The payment provider returned an error: retry | | `billing_error` | 503 | Recording the billing session failed: retry | | `billing_not_configured` | 503 | Billing is not available on this deployment | | `org_limit` | 429 | The organization already uses as much of the machines that could run this sandbox as one organization may: stop some first | ## Webhooks | Code | Status | Meaning | | - | - | - | | `webhook_url` | 400 | The webhook URL is refused (not https, or a private address) | ## Retrying `429` and `5xx` codes are temporary: retry with backoff. Everything else needs a change on your side first. # Delete a file Source: https://docs.fibre.dev/api-reference/files/delete-a-file /api-reference/openapi.json delete /v1/sandboxes/{id}/files Delete a file, or a directory with `recursive=true`. # Inspect a file Source: https://docs.fibre.dev/api-reference/files/inspect-a-file /api-reference/openapi.json get /v1/sandboxes/{id}/files/stat One file or directory: type, size, mode, time; with `checksum=sha256`, its hash. # List a directory Source: https://docs.fibre.dev/api-reference/files/list-a-directory /api-reference/openapi.json get /v1/sandboxes/{id}/files One level of a directory: each entry's name, type, size, mode, time and owner. # Read a file Source: https://docs.fibre.dev/api-reference/files/read-a-file /api-reference/openapi.json get /v1/sandboxes/{id}/files/content The file's bytes, as the response body. # Write a file Source: https://docs.fibre.dev/api-reference/files/write-a-file /api-reference/openapi.json put /v1/sandboxes/{id}/files/content Write the request body to the file, creating missing directories and replacing a file already there. Any content, as large as the sandbox's free disk. # API reference Source: https://docs.fibre.dev/api-reference/introduction The Fibre HTTP API: base URL, authentication, request and response formats, status codes, errors, safe retries, pagination and streaming. Every endpoint has its own page with a live playground. Everything Fibre does is available through one HTTP API. The [SDKs](/sdks/overview) are built on top of it, and you can also call it directly from any programming language. This page explains the rules that apply to every request. After it, **each endpoint has its own page** in this section, listing its parameters, its request body, every possible response with its status code, and a playground where you can send a real request with your own key. ## Base URL ```text theme={null} https://api.fibre.dev ``` Send every request to this address. Every path starts with `/v1`. ## Authentication Every request must include your API key, sent as a *bearer token* in the `Authorization` header: ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes?limit=1" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "sandboxes": "…" > } > ``` Keys start with `fb_live_`. You can create keys that are limited to certain actions, to one sandbox, or to a set lifetime: see [API keys](/get-started/api-keys). The only request that works without a key is [`GET /v1/pricing`](/api-reference/pricing/get-pricing). ## Requests and responses The API follows a few consistent conventions: | | | | - | - | | Request bodies | JSON, with `Content-Type: application/json`. File uploads and command input are raw bytes | | Responses | JSON. A file's content, and command output (newline-delimited JSON), are the exceptions | | Times | ISO 8601, in UTC: `2026-11-21T02:31:07.512Z` | | IDs | Sandboxes `sbx-` and 10 hex characters; commands, keys, webhooks and builds are UUIDs | | Durations | Seconds, in fields ending `_sec` | | Sizes | Bytes in fields ending `_bytes`, MB in `_mb`, GB in `_gb` | | Money | US dollars, in fields ending `_usd` | ## Status codes The HTTP status code tells you at a glance whether a request worked and, if not, what kind of problem occurred: | Status | Means | | - | - | | `200`, `201`, `202` | Done (`201`: created; `202`: accepted, finishes in the background) | | `400`, `422` | The request is wrong: fix it, do not retry | | `401` | No key, or a wrong, revoked or expired one | | `402` | Billing: out of credit, no plan, or outside the trial | | `403` | The key may not do this | | `404` | Not found, or not yours | | `409` | The resource's state does not allow it now | | `413` | Too large | | `429` | A limit: wait, or free capacity, then retry | | `5xx` | Temporary: retry with backoff | ## Errors When a request fails, the answer always has the same JSON shape: ```json title="error" theme={null} { "error": "Sandbox 'sbx-0000000000' not found", "code": "sandbox_not_found", "request_id": "req_8c2f1a9e04b7d311", "docs_url": "https://…/api-reference/errors#sandbox_not_found" } ``` In your code, check `code`, which never changes, rather than `error`, which is a sentence meant for people and may be reworded. If you ask us about a failure, include the `request_id`: it lets us find your exact request. Every code is listed in the [error list](/api-reference/errors), and [errors, retries and limits](/production/errors-and-limits) explains how to handle them. ## Safe retries If a request to create a sandbox times out, you cannot tell whether the sandbox was created. To retry safely, send an `Idempotency-Key` header with `POST /v1/sandboxes`. **If you send the same key again within 24 hours, Fibre returns the first sandbox** instead of creating another one. Use a new key for each sandbox you mean to create. ## Pagination Lists can be long, so they are returned one page at a time. `GET /v1/sandboxes` returns up to `limit` items (50 by default, at most 200). When there are more, the answer includes a `next_cursor`. Send it back as `cursor` to get the next page. The last page has no `next_cursor`. ## Streaming Some answers arrive gradually rather than all at once. When you read [a command's output](/api-reference/commands/read-a-commands-output) with `follow=1`, the connection stays open and Fibre sends one JSON object per line as the command writes output, ending with an `end` line. Read the answer line by line, for example with `curl -N` or a streaming `fetch`. ## Waking Sandboxes go to sleep when they are idle. Calls that need a sleeping sandbox (exec, commands, files, browser, desktop) wake it first and then answer, so they take a moment longer than usual. Simply reading a sandbox's details (`GET /v1/sandboxes/{id}`) does not wake it. # Get pricing Source: https://docs.fibre.dev/api-reference/pricing/get-pricing /api-reference/openapi.json get /v1/pricing Sizes with their CPU, memory, disk and price per awake hour; plans; the price above plan limits; storage. No key needed. # Create a sandbox Source: https://docs.fibre.dev/api-reference/sandboxes/create-a-sandbox /api-reference/openapi.json post /v1/sandboxes Start a sandbox and answer once it is running. With no body, it runs Fibre's default image on the `standard` runtime and can run commands at once. Send an `Idempotency-Key` header to make retries safe: a repeat with the same key within 24 hours returns the first sandbox instead of creating another. To start from a snapshot, send `snapshot`; only `lifetime_sec`, `idle_timeout_sec` and `labels` may be set with it. # Delete a sandbox Source: https://docs.fibre.dev/api-reference/sandboxes/delete-a-sandbox /api-reference/openapi.json delete /v1/sandboxes/{id} Delete a sandbox, its files and its saved memory. This cannot be undone. # Get a sandbox Source: https://docs.fibre.dev/api-reference/sandboxes/get-a-sandbox /api-reference/openapi.json get /v1/sandboxes/{id} One sandbox. Reading a sleeping sandbox does not wake it: its `status` is `standby`. # List sandboxes Source: https://docs.fibre.dev/api-reference/sandboxes/list-sandboxes /api-reference/openapi.json get /v1/sandboxes Your sandboxes, newest first, asleep or awake. Filter by labels with `label.=` (several narrow the list). When there are more than `limit`, the answer has `next_cursor`: pass it as `cursor` for the next page. # Run a command Source: https://docs.fibre.dev/api-reference/sandboxes/run-a-command /api-reference/openapi.json post /v1/sandboxes/{id}/exec Run a command and wait for it, up to 30 seconds, keeping at most 4 MB of each output stream. A sleeping sandbox is woken first. A non-zero `exit_code` is a result, not an error. For longer commands, input or streaming, use [Start a command](/api-reference/commands/start-a-command). # Update a sandbox Source: https://docs.fibre.dev/api-reference/sandboxes/update-a-sandbox /api-reference/openapi.json patch /v1/sandboxes/{id} Change what can change while a sandbox lives: its lifetime (counted from now, or `null` to remove it so the sandbox is kept until deleted), its idle timeout, and its labels (the whole set is replaced). # Delete a secret Source: https://docs.fibre.dev/api-reference/secrets/delete-a-secret /api-reference/openapi.json delete /v1/secrets/{name} Delete a secret. Sandboxes that named it start without it from then on; commands that name it are refused. # Get a secret Source: https://docs.fibre.dev/api-reference/secrets/get-a-secret /api-reference/openapi.json get /v1/secrets/{name} One secret's name, version and times (never its value). # List secrets Source: https://docs.fibre.dev/api-reference/secrets/list-secrets /api-reference/openapi.json get /v1/secrets Your account's secrets: their names, versions and times, never their values. # Set a secret Source: https://docs.fibre.dev/api-reference/secrets/set-a-secret /api-reference/openapi.json post /v1/secrets Store a secret, encrypted: create it, or replace its value, which makes a new version. The value is never answered again, by this call or any other. Names are UPPER_SNAKE_CASE; values up to 65,536 characters. Give it to sandboxes by name with `secrets`, on [Start a command](/api-reference/commands/start-a-command) or on [Create a sandbox](/api-reference/sandboxes/create-a-sandbox). # Delete a snapshot Source: https://docs.fibre.dev/api-reference/snapshots/delete-a-snapshot /api-reference/openapi.json delete /v1/snapshots/{name} Delete a snapshot. Refused while sandboxes started from it still exist. # Get a snapshot Source: https://docs.fibre.dev/api-reference/snapshots/get-a-snapshot /api-reference/openapi.json get /v1/snapshots/{name} One snapshot. # List snapshots Source: https://docs.fibre.dev/api-reference/snapshots/list-snapshots /api-reference/openapi.json get /v1/snapshots Your account's snapshots, each with its size and what it costs a month. # Take a snapshot Source: https://docs.fibre.dev/api-reference/snapshots/take-a-snapshot /api-reference/openapi.json post /v1/snapshots Take a snapshot of a running sandbox: its files, memory and running programs. The source keeps running. New sandboxes start from it with `POST /v1/sandboxes {"snapshot": name}`. A snapshot is kept until deleted and counts toward the account's storage; the answer has its `size_bytes` and `monthly_cost_usd`. # Create a webhook Source: https://docs.fibre.dev/api-reference/webhooks/create-a-webhook /api-reference/openapi.json post /v1/webhooks Add an endpoint that receives signed `POST` requests for the `events` you choose (all of them if you leave it out). The signing `secret` is in the answer once. # Delete a webhook Source: https://docs.fibre.dev/api-reference/webhooks/delete-a-webhook /api-reference/openapi.json delete /v1/webhooks/{id} Remove an endpoint. Pending deliveries to it stop. # List deliveries Source: https://docs.fibre.dev/api-reference/webhooks/list-deliveries /api-reference/openapi.json get /v1/webhooks/{id}/deliveries The endpoint's last 50 deliveries, newest first: status, attempts, your server's last answer and error. # List webhooks Source: https://docs.fibre.dev/api-reference/webhooks/list-webhooks /api-reference/openapi.json get /v1/webhooks Your account's webhook endpoints. # Rotate a webhook secret Source: https://docs.fibre.dev/api-reference/webhooks/rotate-a-webhook-secret /api-reference/openapi.json post /v1/webhooks/{id}/rotate A new signing secret, in the answer once. The old one keeps signing alongside it for 24 hours. # Test a webhook Source: https://docs.fibre.dev/api-reference/webhooks/test-a-webhook /api-reference/openapi.json post /v1/webhooks/{id}/test Send a `ping` event to the endpoint now. # A sandbox tool for your agent framework Source: https://docs.fibre.dev/build-with-ai/agent-frameworks 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](/sandboxes/files) (`sbx.files.read`, `sbx.files.write`). If it needs the web, add a tool for the sandbox's [browser](/connect/browser). ## 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](/production/network). ## 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](/sandboxes/sleep-and-wake). ## 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. # An agent built on the Claude Agent SDK Source: https://docs.fibre.dev/build-with-ai/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](/sandboxes/running-commands). ```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](/sandboxes/sleep-and-wake). ## 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 > } > ``` # Claude Code in a sandbox Source: https://docs.fibre.dev/build-with-ai/claude-code 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](/sandboxes/running-commands). ```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](/setup/snapshots). 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 `. 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](/sandboxes/sleep-and-wake). ## 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 > } > ``` # Codex in a sandbox Source: https://docs.fibre.dev/build-with-ai/codex 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](/sandboxes/running-commands). ```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 ` 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 `. ## 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 > } > ``` # Use Fibre from your coding agent Source: https://docs.fibre.dev/build-with-ai/coding-agents Give Claude Code, Codex, Cursor or any other coding agent the Fibre docs, so it can write Fibre code for you: an MCP server to search them, an index written for language models, a Markdown copy of every page, and a prompt to paste. Coding agents such as Claude Code, Codex and Cursor are very good at writing code against an API, as long as they can read its documentation. If your agent can read these docs, you can simply ask it for what you want, for example "run my tests in a Fibre sandbox" or "give each user of my app their own sandbox", and it will write the code for you. > [!NOTE] > > This page is about your agent **writing code** that uses Fibre. To let your agent **use sandboxes itself**, to run > your tests, builds and servers away from your machine, add Fibre's own MCP server instead: see > [MCP server and skill](/build-with-ai/mcp-server). There are three ways to give your agent the docs. You only need one of them: | Way | What it is | Best for | | - | - | - | | **The docs' MCP server** | A small service your agent connects to. It lets the agent search the docs and read any page whenever it needs to | Agents that support MCP: Claude Code, Codex, Cursor, VS Code | | **`llms.txt`** | A plain-text index of every page, written for language models | Any agent that can fetch a URL | | **Copy a page** | The Markdown of one page, pasted into the conversation | A quick question about one topic | ## Connect the docs' MCP server MCP (Model Context Protocol) is a standard way for an AI agent to use outside tools. These docs run an MCP server at this address: ```text theme={null} https://docs.fibre.dev/mcp ``` Once your agent is connected to it, the agent gets two tools: one that **searches the docs**, and one that **reads a full page**. It uses them on its own while it works, so it always writes code against the current API. To add it, run the command for your agent: ```bash title="Claude Code" norun reason="adds the server to your own agent" theme={null} claude mcp add --transport http fibre-docs https://docs.fibre.dev/mcp ``` ```bash title="Codex" norun reason="adds the server to your own agent" theme={null} codex mcp add fibre-docs --url https://docs.fibre.dev/mcp ``` If you use **Cursor** or **VS Code**, you do not need a command. Open the menu at the top of any page of these docs and choose **Connect to Cursor** or **Connect to VS Code**. For any other agent, the same menu has **Copy MCP install command** and **Copy MCP server URL**, which you can paste into your agent's settings. You can check that the server answers with a single request. It lists the two tools: ```bash title="curl" run theme={null} curl -sS -X POST https://docs.fibre.dev/mcp \ -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' ``` > [accordion] Output > > ```text title="output" expected theme={null} > search_fibre > ``` ## Point your agent at `llms.txt` `llms.txt` is a convention for giving language models a map of a documentation site. These docs publish two versions: * **[`/llms.txt`](https://docs.fibre.dev/llms.txt)** lists every page with a one-line description. Give this to your agent first, so it knows what exists and can fetch the pages it needs. * **[`/llms-full.txt`](https://docs.fibre.dev/llms-full.txt)** contains all of the docs in one file. It is useful when your agent cannot fetch pages one by one. Every page is also available as plain Markdown. Add `.md` to the end of its address, for example [`/get-started/quickstart.md`](https://docs.fibre.dev/get-started/quickstart.md). ## Copy a single page For a quick question about one topic, open the menu at the top of the page you are reading. **Copy page** copies it as Markdown, ready to paste into any chat. **Open in Claude** and **Open in ChatGPT** start a new conversation with the page already included. ## A prompt to paste If you would like a starting point, paste this prompt into your agent and then describe what you want to build after it. It tells the agent where to read and asks it to clean up after itself: ```text theme={null} Use Fibre to run code in an isolated sandbox. Read https://docs.fibre.dev/llms.txt and the quickstart first. Use the TypeScript SDK (@fibre-dev/sdk) or the Python SDK (fibre-sdk); my API key is in FIBRE_API_KEY. Give every sandbox a lifetime and labels, delete it when the work is done, and show me each command's output. ``` ## Run the agent itself inside a sandbox Everything above is about your agent *writing code that uses* Fibre. You can also do the opposite: run the coding agent itself **inside** a Fibre sandbox. The agent then works on a copy of your repository in a machine of its own, where it can install packages and run commands freely without touching your computer. These pages show how, step by step: * **[Claude Code](/build-with-ai/claude-code)**: Anthropic's coding agent, run without a terminal. * **[Codex](/build-with-ai/codex)**: OpenAI's coding agent. * **[OpenCode](/build-with-ai/opencode)**: an open-source agent that works with many models. * **[Claude Agent SDK](/build-with-ai/claude-agent-sdk)**: build your own agent and run it in a sandbox. * **[Agent frameworks](/build-with-ai/agent-frameworks)**: give an agent in your own app a tool that runs its commands in a sandbox. When an agent runs inside a sandbox, give it a [key that only works on that sandbox](/get-started/api-keys#a-key-for-one-sandbox). That way, even if the agent misbehaves, it cannot reach your other sandboxes. ## Next * **[Quickstart](/get-started/quickstart)**: the calls your agent will make, explained step by step. * **[Concepts](/get-started/concepts)**: the words your agent will meet in these docs. # Give your coding agent sandboxes Source: https://docs.fibre.dev/build-with-ai/mcp-server Add Fibre's MCP server to Claude Code, Codex, Cursor or OpenCode with one command, so your agent can run tests, builds, servers and untrusted code in sandboxes instead of on your machine. Add the Fibre skill so it knows when and how. Your coding agent runs commands on your computer: installs, test suites, scripts it just wrote. With Fibre's MCP server, it can run them in a **Fibre sandbox** instead, a clean Linux machine of its own in the cloud. Your machine stays as it was, the agent can install anything it needs, it can run several things side by side, and when it starts a server you get a public URL you can open or share. **MCP** (Model Context Protocol) is the standard way for an agent to use outside tools. The Fibre CLI includes an MCP server: you add it to your agent once, and from then on the agent starts it by itself and sees tools such as `create_sandbox`, `run_command` and `get_url`. > [!NOTE] > > This page is about your agent **using** sandboxes. To have your agent **write code** that uses Fibre, give it these > docs instead: see [use Fibre from your coding agent](/build-with-ai/coding-agents). ## Before you start The MCP server is part of the [Fibre CLI](/sdks/cli). Install it and sign in once: ```bash title="Terminal" norun reason="installs on your own machine" theme={null} curl -fsSL https://fibre.dev/install.sh | sh fibre login ``` The server uses the key you signed in with, so **no API key goes into your agent's settings**, where it could end up in a file you share. ## Add it to your agent Run the command for your agent. Each one adds the server for all your projects; add `--project` to add it only for the project in the current folder. ```bash title="Claude Code" norun reason="changes your agent's settings" theme={null} fibre mcp add claude ``` ```bash title="Codex" norun reason="changes your agent's settings" theme={null} fibre mcp add codex ``` ```bash title="Cursor" norun reason="changes your agent's settings" theme={null} fibre mcp add cursor ``` ```bash title="OpenCode" norun reason="changes your agent's settings" theme={null} fibre mcp add opencode ``` For Claude Code, Codex and OpenCode, this runs the agent's own `mcp add` command for you, so the server is set up exactly the way that agent expects. For Cursor, it adds the server to `~/.cursor/mcp.json` and keeps every other server in the file. Start a new session of your agent afterwards: agents read their MCP servers when a session starts. ### Any other agent Most agents that support MCP read the same JSON block. `fibre mcp config` prints it for you to paste into the agent's settings. With `--project`, the command is plain `fibre`, which suits a settings file you commit and share: ```bash title="Terminal" run theme={null} fibre mcp config --project ``` > [accordion] Output > > ```json title="output" expected theme={null} > { > "mcpServers": { > "fibre": { > "command": "fibre", > "args": [ > "mcp" > ] > } > } > } > ``` ## Add the Fibre skill A **skill** is a short guide an agent reads when a task calls for it. The Fibre skill tells your agent when a sandbox is the better place to run something, the usual steps, and the rules that keep it cheap, such as deleting sandboxes when the work is done. It also covers the CLI, the TypeScript and Python SDKs and the HTTP API, for agents that write code against Fibre. ```bash title="Terminal" norun reason="writes to your home folder" theme={null} fibre skill install ``` This writes the skill to `~/.agents/skills/fibre`, which Codex, Cursor, OpenCode and VS Code read, and to `~/.claude/skills/fibre`, which Claude Code reads. With `--project`, it goes into the current project instead, so you can commit it for your team. ## Try it Ask your agent in plain words. For example: * "Run the test suite in a Fibre sandbox and tell me what fails." * "Try this pull request's install script in a sandbox before I run it here." * "Start the app in a sandbox and give me a link I can send to the designer." * "Run these five benchmark configurations in parallel sandboxes and compare them." A typical run looks like this: the agent creates a sandbox, uploads your project folder, runs the command, reads the output, fixes what it needs to, and deletes the sandbox at the end. ## The tools | Tool | What it does | | - | - | | `create_sandbox` | Starts a sandbox, with the same options as the API: image, size, runtime, labels, lifetime, port, network rules | | `list_sandboxes`, `get_sandbox` | Finds sandboxes and shows one | | `delete_sandbox` | Deletes a sandbox with its files | | `run_command` | Runs a command line and returns its exit code and output | | `get_command`, `kill_command` | Reads more output of a long or background command; stops one | | `write_file`, `read_file`, `list_files` | Works with files in the sandbox | | `upload`, `download` | Copies a file or a whole folder between your project and a sandbox, in one call | | `get_url` | The sandbox's public HTTPS address | | `create_snapshot` | Saves a sandbox with its memory, so new ones start from that state | The tools that delete something are marked as destructive, and the ones that only read are marked read-only, so your agent can treat them differently when it asks for your approval. ### Long commands Some agents stop waiting for a tool after about a minute. So `run_command` waits up to 45 seconds by default. If the command is still running then, it keeps running in the sandbox, and the result tells the agent its ID. The agent then reads the rest with `get_command`, from where it left off, until the command ends. For servers and watchers, the agent starts the command in the background and gets the ID straight away. Long output is cut in the middle, keeping the start and the end, so one noisy build does not fill the agent's context. ## What the agent can reach * **Your files:** `upload` and `download` work only inside the folder the agent started the server in, which is usually your project. A path outside it is refused. * **Your account:** the server can do what your signed-in key can do. To give an agent less, create a key with fewer permissions (see [API keys](/get-started/api-keys)) and set it for the server only, as `FIBRE_API_KEY` in the server's `env` in your agent's settings. * **Your spending:** sandboxes cost money while they run, and their storage while they sleep. Each one the agent creates is kept until it is deleted, unless the agent gives it a lifetime, and the skill tells the agent to delete sandboxes it no longer needs. `fibre list` shows every sandbox you have. ## Check that it works `fibre mcp` is what your agent runs. You can start it yourself to see that it signs in and starts: ```bash title="Terminal" norun reason="waits for an agent on its input" theme={null} fibre mcp ``` It prints a line saying the MCP server is ready, and then waits for an agent on its input; press Ctrl-C to stop it. If a tool answers that Fibre is not signed in, run `fibre login` again. To call the tools by hand, the MCP Inspector starts the server and lists them in your browser: ```bash title="Terminal" norun reason="opens a browser" theme={null} npx @modelcontextprotocol/inspector fibre mcp ``` # OpenCode in a sandbox Source: https://docs.fibre.dev/build-with-ai/opencode Install OpenCode in a Fibre sandbox, run a task on a repository with opencode run and the model of your choice, and continue the session later. OpenCode is an open-source coding agent that works with many different models. Its `opencode run` command gives OpenCode a single task without opening its interface. If you run it in a Fibre sandbox, OpenCode gets a Linux machine of its own for the repository, well away from your computer. Between tasks the sandbox sleeps with its memory and files, so the next task can continue the same session. **Before you start**, set your Fibre API key in `FIBRE_API_KEY` and `FIBRE_API_URL=https://api.fibre.dev`. For the steps where OpenCode talks to a model, you also need that model provider's API key. The example uses Anthropic (`ANTHROPIC_API_KEY`). For OpenAI it would be `OPENAI_API_KEY`: each provider reads its own variable. ## Start a sandbox ```bash title="CLI" run theme={null} SBX=$(fibre create --lifetime 1h --label example=opencode --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: "opencode" } }); ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(lifetime=3600, labels={"example": "opencode"}) ``` ```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": "opencode"}}' ``` ## Install OpenCode OpenCode is installed from npm, and the sandbox's default image already has Node. The install takes under a minute, which is longer than an exec allows, so it runs as a [background command](/sandboxes/running-commands). ```bash title="CLI" run theme={null} fibre exec "$SBX" --timeout 10m -- 'npm install -g opencode-ai && opencode --version' # 1.19.6 ``` ```typescript title="TypeScript" run theme={null} const install = await sbx.run("npm install -g opencode-ai && opencode --version", { timeout: 600 }); if (install.exitCode !== 0) throw new Error(install.stderr); console.log(install.stdout.trim().split("\n").pop()); // 1.19.6 ``` ```python title="Python" run theme={null} install = sbx.run("npm install -g opencode-ai && opencode --version", timeout=600) if install.exit_code != 0: raise RuntimeError(install.stderr) print(install.stdout.strip().split("\n")[-1]) # 1.19.6 ``` ```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 opencode-ai && opencode --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 `-m` chooses the model, written as `provider/model`. Once a provider's key is set, `opencode models anthropic` lists the models that provider offers. `--auto` approves the actions OpenCode would otherwise stop and ask about, since nobody is there to answer. That is safe here, because the Fibre sandbox keeps whatever OpenCode does inside it. The key is given to this one command only; there is more about it [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." \ -- 'opencode run --auto -m anthropic/claude-sonnet-5-5 "$TASK"' ``` ```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null} const task = await sbx.run( ["sh", "-c", 'cd /work/repo && opencode run --auto -m anthropic/claude-sonnet-5-5 "$TASK"'], { 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( ["sh", "-c", 'cd /work/repo && opencode run --auto -m anthropic/claude-sonnet-5-5 "$TASK"'], 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: ["sh", "-c", "cd /work/repo && opencode run --auto -m anthropic/claude-sonnet-5-5 \"$TASK\""], 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 @- ``` Add `--format json` to get one JSON event per line instead of plain text. 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 OpenCode has finished, the sandbox goes to sleep after its idle timeout, with its memory and files saved, and the next command wakes it. OpenCode keeps its sessions on the sandbox's disk, so `--continue` carries on the last one. ```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." \ -- 'opencode run --continue --auto -m anthropic/claude-sonnet-5-5 "$TASK"' ``` ```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 && opencode run --continue --auto -m anthropic/claude-sonnet-5-5 "$TASK"'], { 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 && opencode run --continue --auto -m anthropic/claude-sonnet-5-5 "$TASK"'], 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 && opencode run --continue --auto -m anthropic/claude-sonnet-5-5 \"$TASK\""], 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 instead, use `--session `. ## 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 OpenCode 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 > } > ``` # Browser Source: https://docs.fibre.dev/connect/browser A real Chromium in every sandbox: drive it with Playwright or Puppeteer from inside the sandbox or from your own code, watch it live, and keep its tabs and logins across sleep. Many tasks need a real web browser: agents that browse the web, scrapers, end-to-end tests, or bots that log in and fill in forms. Running that browser on your own machine or servers is awkward and risky. **Every sandbox on Fibre's default image has a browser of its own**: Chromium, with Playwright and ChromeDriver already installed, and support for Puppeteer. There are two ways to use it, depending on where your code runs: | | Script inside the sandbox | Drive it from your code | | - | - | - | | Where your code runs | In the sandbox, next to the browser | In your app or on your laptop | | How it connects | Playwright launches Chromium directly | Over the DevTools protocol, with `cdp_url` | | Good for | Scraping jobs, test suites, an agent's own scripts | An agent in your app that controls a page step by step | | Watch it live | With the live view | With the live view | ## Run a browser script inside the sandbox The quickest way to start is to write a Playwright script, run it inside the sandbox, and read its output. This example opens Hacker News, reads the five top stories, and takes a screenshot of the page. **1. Start a sandbox** ```bash title="CLI" run theme={null} SBX=$(fibre create --size medium --lifetime 15m --label docs=browser --json | jq -r .id) ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ size: "medium", lifetime: 900, labels: { docs: "browser" } }); ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(size="medium", lifetime=900, labels={"docs": "browser"}) ``` ```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 '{"size": "medium", "lifetime_sec": 900, "labels": {"docs": "browser"}}' ``` **2. Write the script** ```bash title="CLI" run theme={null} fibre exec "$SBX" -i -- sh -c 'mkdir -p /work && cat > /work/top.cjs' <<'JS' const { chromium } = require("playwright"); (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto("https://news.ycombinator.com"); const stories = await page.$$eval(".titleline > a", (links) => links.slice(0, 5).map((a) => ({ title: a.textContent, url: a.href }))); await page.screenshot({ path: "/work/front-page.png" }); console.log(JSON.stringify(stories, null, 2)); await browser.close(); })(); JS ``` ```typescript title="TypeScript" run theme={null} await sbx.files.write("/work/top.cjs", ` const { chromium } = require("playwright"); (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto("https://news.ycombinator.com"); const stories = await page.$$eval(".titleline > a", (links) => links.slice(0, 5).map((a) => ({ title: a.textContent, url: a.href }))); await page.screenshot({ path: "/work/front-page.png" }); console.log(JSON.stringify(stories, null, 2)); await browser.close(); })(); `); ``` ```python title="Python" run theme={null} sbx.files.write("/work/top.cjs", """ const { chromium } = require("playwright"); (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto("https://news.ycombinator.com"); const stories = await page.$$eval(".titleline > a", (links) => links.slice(0, 5).map((a) => ({ title: a.textContent, url: a.href }))); await page.screenshot({ path: "/work/front-page.png" }); console.log(JSON.stringify(stories, null, 2)); await browser.close(); })(); """) ``` ```bash title="curl" run theme={null} cat <<'EOF' | curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/top.cjs" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- const { chromium } = require("playwright"); (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto("https://news.ycombinator.com"); const stories = await page.$$eval(".titleline > a", (links) => links.slice(0, 5).map((a) => ({ title: a.textContent, url: a.href }))); await page.screenshot({ path: "/work/front-page.png" }); console.log(JSON.stringify(stories, null, 2)); await browser.close(); })(); EOF ``` Playwright and its Chromium are already installed in the default image, so `require("playwright")` works without an `npm install`. **3. Run it and read the result** ```bash title="CLI" run theme={null} fibre exec "$SBX" --timeout 2m -- node /work/top.cjs | jq '.[0]' # {"title": "…", "url": "https://…"} fibre cp "$SBX:/work/front-page.png" front-page.png ``` ```typescript title="TypeScript" run theme={null} const run = await sbx.run(["node", "/work/top.cjs"], { timeout: 120 }); const stories = JSON.parse(run.stdout); console.log(stories[0]); // { title: '…', url: 'https://…' } const png = await sbx.files.readBytes("/work/front-page.png"); console.log(`screenshot: ${png.byteLength} bytes`); ``` ```python title="Python" run theme={null} import json run = sbx.run(["node", "/work/top.cjs"], timeout=120) stories = json.loads(run.stdout) print(stories[0]) # {'title': '…', 'url': 'https://…'} png = sbx.files.read_bytes("/work/front-page.png") print(f"screenshot: {len(png)} bytes") ``` ```bash title="curl" run capture=TOP=.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": ["node", "/work/top.cjs"]}' ``` ```bash title="curl: the result" run theme={null} curl -sSN "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$TOP/logs?follow=1" -H "Authorization: Bearer $FIBRE_API_KEY" curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/front-page.png" \ -H "Authorization: Bearer $FIBRE_API_KEY" -o front-page.png ``` > [accordion] Output > > ```text title="output" expected theme={null} > "exit_code":0 > ``` > > The script prints the five stories as JSON: > > ```json title="stories" theme={null} > [ > { > "title": "…", > "url": "https://…" > } > ] > ``` > [!TIP] > > You can use Python in the same way. Install Playwright with `pip install playwright` in a > [virtual environment](/sandboxes/sizes#install-what-is-missing), then point it at the installed browser with > `executable_path="/usr/local/bin/google-chrome"`. ## Drive the browser from your code Sometimes the agent runs in **your own app**, not in the sandbox. It then needs to control the browser remotely, one step at a time: look at the page, decide what to do, click. For that, ask the sandbox for its browser. You get back two links: ```bash title="CLI" run theme={null} LINKS=$(fibre browser "$SBX" --json) CDP=$(echo "$LINKS" | jq -r .cdp_url) echo "$LINKS" | jq -r .live_view_url # open it to watch ``` ```typescript title="TypeScript" run theme={null} const { cdpUrl, liveViewUrl, expiresAt } = await sbx.browser(); console.log(liveViewUrl); // open it to watch ``` ```python title="Python" run theme={null} links = sbx.browser() cdp_url, live_view_url = links.cdp_url, links.live_view_url print(live_view_url) # open it to watch ``` ```bash title="curl" run capture=CDP=.cdp_url theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/browser" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d '{}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "cdp_url": "…", > "live_view_url": "…", > "expires_at": "…" > } > ``` | Link | For | Who may have it | | - | - | - | | `cdp_url` | Your code: Playwright `connectOverCDP`, Puppeteer `connect` | **Only your backend. It is a password**: whoever has it controls the browser | | `live_view_url` | A person: shows the screen, passes on clicks and keys | Safe to show to your user | `cdp_url` uses the Chrome DevTools Protocol (CDP), the standard way for automation tools to control Chrome. Connect to it with Playwright from your own machine or server: ```typescript title="TypeScript" norun reason="needs Playwright installed where your code runs" theme={null} import { chromium } from "playwright"; const browser = await chromium.connectOverCDP(cdpUrl); const context = browser.contexts()[0]; // the browser's own context: its cookies and logins const page = context.pages()[0] ?? (await context.newPage()); await page.goto("https://github.com/login"); await page.fill("#login_field", process.env.GH_USER!); // … your agent decides the next step from page content or a screenshot ``` ```python title="Python" norun reason="needs Playwright installed where your code runs" theme={null} import os from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.connect_over_cdp(cdp_url) context = browser.contexts[0] # the browser's own context: its cookies and logins page = context.pages[0] if context.pages else context.new_page() page.goto("https://github.com/login") page.fill("#login_field", os.environ["GH_USER"]) # … your agent decides the next step from page content or a screenshot ``` **Use the browser's existing context, as above, rather than creating a new one.** The existing context is where the browser keeps its cookies and logins, and it is what survives a sleep. The DevTools address also answers the standard discovery requests, so any tool that speaks CDP can find the browser: ```bash title="CLI" run theme={null} curl -sS "${CDP/ws/http}/json/version" | jq -r .Browser # Chrome/1… ``` ```typescript title="TypeScript" run theme={null} const version = await fetch(`${cdpUrl.replace(/^ws/, "http")}/json/version`).then((r) => r.json()); console.log(version.Browser); // Chrome/1… ``` ```python title="Python" run theme={null} import json from urllib.request import urlopen version = json.load(urlopen(cdp_url.replace("ws", "http", 1) + "/json/version")) print(version["Browser"]) # Chrome/1… ``` ```bash title="curl" run theme={null} curl -sS "${CDP/ws/http}/json/version" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "Browser": "…", > "webSocketDebuggerUrl": "…" > } > ``` The links work for an hour. To choose a different duration, pass `{"ttl_sec": …}` (between 60 seconds and a day, but never past the sandbox's lifetime, if it has one). You can ask for fresh links at any time. ## Watch it live Open `live_view_url` in any browser. **You see the page exactly as the agent sees it, and you can click and type into it yourself.** You could show it to your user while their agent books a flight for them, or open it yourself to find out why a script is stuck. The live view only shows the screen and passes on clicks and key presses. It cannot run code or reach the DevTools, so it is safe to share. ## Logins that last The browser is part of the sandbox, so **when the sandbox sleeps, the browser sleeps with it**, together with its open tabs, cookies, local storage and the page it was on. The next connection finds it exactly as it was. That makes **"log in once, reuse for days"** simple. Give each user a sandbox for the site they want automated. The user logs in once through the live view, and from then on your agent uses that logged-in session. Between uses, the sandbox sleeps: nothing for compute, and its saved state counts towards your storage. ## A browser from the start If you know you will need the browser, ask for it when you create the sandbox with `"needs": ["browser"]`. The browser then starts together with the sandbox, and the create answer already includes the links under `browser`. Such a sandbox uses the `vm` runtime unless you choose another one, because **browsers run faster there**. ```bash title="CLI" run theme={null} READY=$(fibre create --needs browser --lifetime 10m --label docs=browser --json | jq -r .id) fibre get "$READY" # runtime: vm (needs:browser) ``` ```typescript title="TypeScript" run theme={null} const ready = await Sandbox.create({ needs: ["browser"], lifetime: 600, labels: { docs: "browser" } }); console.log(ready.runtime, ready.runtimeReason); // vm needs:browser ``` ```python title="Python" run theme={null} ready = Sandbox.create(needs=["browser"], lifetime=600, labels={"docs": "browser"}) print(ready.runtime, ready.runtime_reason) # vm needs:browser ``` ```bash title="curl" run capture=B=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"needs": ["browser"], "lifetime_sec": 600, "labels": {"docs": "browser"}}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "runtime": "vm", > "runtime_reason": "needs:browser", > "browser": { > "cdp_url": "…", > "live_view_url": "…", > "expires_at": "…" > } > } > ``` ## Close it When you no longer need the browser, close it with `closeBrowser()` (or `DELETE /v1/sandboxes/{id}/browser`). This cancels every link, closes their connections and stops the browser. The sandbox itself keeps running. ## Good to know A few details about how the browser behaves: | | | | - | - | | Browsers per sandbox | One, shared by every connection | | Sleep | A sandbox with its browser open sleeps once **no client is connected** and nothing else happens for its idle timeout | | Image | Needs Fibre's default image, or your own image with Chrome at the usual path | | Inside the sandbox | `CHROME_PATH`, `PUPPETEER_EXECUTABLE_PATH` point at the installed browser | ## Clean up ```bash title="CLI" run theme={null} fibre delete "$SBX" "$READY" rm -f front-page.png ``` ```typescript title="TypeScript" run theme={null} await sbx.delete(); await ready.delete(); ``` ```python title="Python" run theme={null} sbx.delete() ready.delete() ``` ```bash title="curl" run theme={null} for id in "$SBX" "$B"; do curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$id" -H "Authorization: Bearer $FIBRE_API_KEY"; echo done rm -f front-page.png ``` ## Related > [card] [Desktop](/connect/desktop) > > A whole desktop, not only a browser, for computer-use agents. > [card] [Public URLs](/connect/public-urls) > > Test your own app with the browser in the same sandbox. # Desktop Source: https://docs.fibre.dev/connect/desktop A full Linux desktop with a browser, a terminal and VS Code, that a person watches in their own browser and an agent drives with screenshots, clicks and keys. For computer-use agents and apps that have no API. Some work has no API. Think of an old admin panel, a desktop application, a website that blocks automation, or a task you want a **computer-use model** to carry out the way a person would, by looking at the screen and clicking. For that kind of work, a sandbox can have **a complete desktop**. It gives you: * **A familiar desktop** with windows and a taskbar, a **browser**, a **terminal** and **VS Code**. * **A link that a person opens in their own browser** to watch the desktop and take over when needed. * **Screenshots, clicks and keystrokes** that your agent sends as ordinary commands. Like everything else in a sandbox, **the desktop goes to sleep with its windows still open**, and wakes up exactly as it was. ## Start a desktop Ask for a desktop with `"needs": ["desktop"]` when you create the sandbox: ```bash title="CLI" run theme={null} DESK=$(fibre create --needs desktop --lifetime 15m --label docs=desktop --json | jq -r .id) fibre get "$DESK" --json | jq -r .runtime # vm ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const desk = await Sandbox.create({ needs: ["desktop"], lifetime: 900, labels: { docs: "desktop" } }); console.log(desk.runtime); // vm ``` ```python title="Python" run theme={null} from fibre import Sandbox desk = Sandbox.create(needs=["desktop"], lifetime=900, labels={"docs": "desktop"}) print(desk.runtime) # vm ``` ```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 '{"needs": ["desktop"], "lifetime_sec": 900, "labels": {"docs": "desktop"}}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "runtime": "vm", > "runtime_reason": "needs:desktop", > "desktop_url": "…", > "desktop_expires_in": 300 > } > ``` The call answers **once the desktop is up and ready**, and the answer includes a link to it. A desktop always uses the `vm` runtime. ## Watch it, or hand it to a person Open `desktop_url` in your browser. You see the sandbox's screen and can use it with your own mouse and keyboard, as if you were sitting in front of it. Desktop links have a few safety rules: * **Each link works once.** Whoever opens it first gets the desktop, and nobody else can reuse that link. * **An unopened link expires** after `desktop_expires_in` seconds (300, so five minutes). * **You can ask for a new link at any time**, for yourself or for a user who needs to step in: ```bash title="CLI" run theme={null} fibre desktop "$DESK" # https://… (works once; expires in 300 s if not opened) ``` ```typescript title="TypeScript" run theme={null} const link = await desk.desktop(); console.log(link.url, link.expiresIn); // https://… 300 ``` ```python title="Python" run theme={null} link = desk.desktop() print(link.url, link.expires_in) # https://… 300 ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/desktop" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d '{}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "url": "…", > "expires_in": 300 > } > ``` > [!TIP] > > **Bring a person in when the agent needs help.** When your agent reaches a CAPTCHA, a two-factor login prompt, or > a decision it should not make alone, send the user a fresh link. They deal with it on the same desktop, close the > tab, and the agent carries on from there. ## Let an agent drive it A computer-use agent works in a loop: **it looks at the screen, decides what to do, acts, and looks again.** On Fibre, each of those steps is a single command run in the sandbox. The desktop's screen is display `:1`, which is why the commands below start with `DISPLAY=:1`. **1. Look: take a screenshot** ```bash title="CLI" run theme={null} fibre exec "$DESK" -- 'DISPLAY=:1 scrot -o /tmp/screen.png' fibre cp "$DESK:/tmp/screen.png" screen.png # send it to your model ``` ```typescript title="TypeScript" run theme={null} await desk.run("DISPLAY=:1 scrot -o /tmp/screen.png"); const screen = await desk.files.readBytes("/tmp/screen.png"); console.log(`${screen.byteLength} bytes of PNG`); // send these to your model ``` ```python title="Python" run theme={null} desk.run("DISPLAY=:1 scrot -o /tmp/screen.png") screen = desk.files.read_bytes("/tmp/screen.png") print(f"{len(screen)} bytes of PNG") # send these to your model ``` ```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", "DISPLAY=:1 scrot -o /tmp/screen.png && echo saved"]}' curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/tmp/screen.png" \ -H "Authorization: Bearer $FIBRE_API_KEY" -o screen.png file screen.png ``` > [accordion] Output > > ```text title="output" expected theme={null} > PNG image data > ``` **2. Act: click and type** `xdotool` is a standard Linux tool that moves the mouse, clicks and types, exactly as a person would: ```bash title="CLI" run theme={null} fibre exec "$DESK" -- "DISPLAY=:1 xdotool mousemove 640 400 click 1" # click at x=640, y=400 fibre exec "$DESK" -- "DISPLAY=:1 xdotool type 'hello from an agent'" # type text fibre exec "$DESK" -- "DISPLAY=:1 xdotool key ctrl+l" # press keys ``` ```typescript title="TypeScript" run theme={null} await desk.run("DISPLAY=:1 xdotool mousemove 640 400 click 1"); // click at x=640, y=400 await desk.run("DISPLAY=:1 xdotool type 'hello from an agent'"); // type text await desk.run("DISPLAY=:1 xdotool key ctrl+l"); // press keys ``` ```python title="Python" run theme={null} desk.run("DISPLAY=:1 xdotool mousemove 640 400 click 1") # click at x=640, y=400 desk.run("DISPLAY=:1 xdotool type 'hello from an agent'") # type text desk.run("DISPLAY=:1 xdotool key ctrl+l") # press keys ``` ```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", "DISPLAY=:1 xdotool mousemove 640 400 click 1 && DISPLAY=:1 xdotool type \"hello from an agent\" && echo done"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "done\n" > } > ``` **3. Put it in a loop with your model** Now connect the two with a model. Each time round the loop, the model looks at the latest screenshot and replies with the next action, and your code turns that action into a command. Here is a sketch of the loop, with the call to your model left for you to fill in: ```typescript title="TypeScript" norun reason="needs a computer-use model and its API key" theme={null} for (let step = 0; step < 30; step++) { await desk.run("DISPLAY=:1 scrot -o /tmp/screen.png"); const screenshot = await desk.files.readBytes("/tmp/screen.png"); const action = await askModel({ task: "Open the browser and find today's weather in Paris", screenshot }); if (action.type === "done") break; if (action.type === "click") await desk.run(`DISPLAY=:1 xdotool mousemove ${action.x} ${action.y} click 1`); if (action.type === "type") await desk.run(`DISPLAY=:1 xdotool type ${JSON.stringify(action.text)}`); if (action.type === "key") await desk.run(`DISPLAY=:1 xdotool key ${action.keys}`); } ``` ```python title="Python" norun reason="needs a computer-use model and its API key" theme={null} import shlex for step in range(30): desk.run("DISPLAY=:1 scrot -o /tmp/screen.png") screenshot = desk.files.read_bytes("/tmp/screen.png") action = ask_model(task="Open the browser and find today's weather in Paris", screenshot=screenshot) if action["type"] == "done": break if action["type"] == "click": desk.run(f"DISPLAY=:1 xdotool mousemove {action['x']} {action['y']} click 1") if action["type"] == "type": desk.run(f"DISPLAY=:1 xdotool type {shlex.quote(action['text'])}") if action["type"] == "key": desk.run(f"DISPLAY=:1 xdotool key {action['keys']}") ``` ## What is on the desktop The desktop comes with these applications and tools: | | | | - | - | | Desktop | A full Linux desktop with a taskbar and windows | | Apps | Chromium, a terminal, a file manager, **VS Code** (in the browser) | | Computer-use tools | `scrot` for screenshots, `xdotool` for mouse and keyboard | | Screen | Display `:1` | ## Sleep A desktop goes to sleep once **nobody is watching it** and nothing has been done through Fibre (no exec, command or file call) for its idle timeout. Programs running on the desktop by themselves do not keep it awake. Opening a new link, or making any call, wakes it **with the same windows, tabs and editor** as before. ## Clean up ```bash title="CLI" run theme={null} fibre delete "$DESK" rm -f screen.png ``` ```typescript title="TypeScript" run theme={null} await desk.delete(); ``` ```python title="Python" run theme={null} desk.delete() ``` ```bash title="curl" run theme={null} curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" rm -f screen.png ``` ## Related > [card] [Browser](/connect/browser) > > If you only need a browser, it is lighter and faster. > [card] [Runtimes](/sandboxes/runtimes) > > Desktops run on the `vm` runtime. Find out what that means. # Public URLs and ports Source: https://docs.fibre.dev/connect/public-urls Every sandbox has its own HTTPS address. Serve an app, an API or a preview from it, share the link, and let it sleep: the next visitor wakes it with the app still running. Every sandbox has **its own HTTPS address**, which you find in its `url` field. If a program inside the sandbox listens on the sandbox's **exposed port**, anyone can reach that program at the address, from anywhere, over a secure connection with a valid certificate. You do not need to set up a server, a domain or a certificate yourself. This is useful in many situations: * **Show a user the app their agent just built**, live, while the agent keeps working on it. * **Share a preview** of a branch with a teammate or a reviewer. * **Receive webhooks** from services such as GitHub, Stripe or Slack in a sandbox you are testing. * **Run a small API or bot** without deploying it anywhere. And because a sandbox sleeps when nobody uses it, **a preview that nobody is looking at costs nothing for compute**. When the next visitor arrives, the sandbox wakes up and the app is still running. ## Serve an app This example serves a small web app with one page and one JSON endpoint. It only uses Node, which is already installed, and listens on port 3000. Follow the steps to get it running at a public address. **1. Start a sandbox that serves port 3000** ```bash title="CLI" run theme={null} SBX=$(fibre create --port 3000 --idle-timeout 1m --lifetime 20m --label docs=public-url --json | jq -r .id) fibre url "$SBX" # https://sbx-….fibre.run ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ exposedPort: 3000, idleTimeout: 60, lifetime: 1200, labels: { docs: "public-url" }, }); console.log(sbx.url); // https://sbx-….fibre.run ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(exposed_port=3000, idle_timeout=60, lifetime=1200, labels={"docs": "public-url"}) print(sbx.url) # https://sbx-….fibre.run ``` ```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 '{"exposed_port": 3000, "idle_timeout_sec": 60, "lifetime_sec": 1200, "labels": {"docs": "public-url"}}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "hostname": "…", > "url": "…" > } > ``` **2. Put the app in** ```bash title="CLI" run theme={null} fibre exec "$SBX" -i -- sh -c 'mkdir -p /app && cat > /app/server.js' <<'JS' const http = require("http"); const started = new Date().toISOString(); let visits = 0; http.createServer((req, res) => { if (req.url === "/api/status") { res.writeHead(200, { "content-type": "application/json" }); return res.end(JSON.stringify({ ok: true, started, visits })); } visits++; res.writeHead(200, { "content-type": "text/html" }); res.end("

Hello from a fibre sandbox

Visit #" + visits + "

"); }).listen(3000); JS ``` ```typescript title="TypeScript" run theme={null} await sbx.files.write("/app/server.js", ` const http = require("http"); const started = new Date().toISOString(); let visits = 0; http.createServer((req, res) => { if (req.url === "/api/status") { res.writeHead(200, { "content-type": "application/json" }); return res.end(JSON.stringify({ ok: true, started, visits })); } visits++; res.writeHead(200, { "content-type": "text/html" }); res.end("

Hello from a fibre sandbox

Visit #" + visits + "

"); }).listen(3000); `); ``` ```python title="Python" run theme={null} sbx.files.write("/app/server.js", """ const http = require("http"); const started = new Date().toISOString(); let visits = 0; http.createServer((req, res) => { if (req.url === "/api/status") { res.writeHead(200, { "content-type": "application/json" }); return res.end(JSON.stringify({ ok: true, started, visits })); } visits++; res.writeHead(200, { "content-type": "text/html" }); res.end("

Hello from a fibre sandbox

Visit #" + visits + "

"); }).listen(3000); """) ``` ```bash title="curl" run theme={null} cat <<'EOF' | curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/app/server.js" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- const http = require("http"); const started = new Date().toISOString(); let visits = 0; http.createServer((req, res) => { if (req.url === "/api/status") { res.writeHead(200, { "content-type": "application/json" }); return res.end(JSON.stringify({ ok: true, started, visits })); } visits++; res.writeHead(200, { "content-type": "text/html" }); res.end("

Hello from a fibre sandbox

Visit #" + visits + "

"); }).listen(3000); EOF ``` **3. Start the server so it keeps running** `keep: true` makes the server a program that keeps running on its own, even across sleep and wake. The second line waits until the server answers before moving on. ```bash title="CLI" run theme={null} fibre exec "$SBX" --detach --keep -- node /app/server.js fibre exec "$SBX" --timeout 60 -- 'until curl -sf -o /dev/null localhost:3000/api/status; do sleep 1; done' ``` ```typescript title="TypeScript" run theme={null} await sbx.spawn(["node", "/app/server.js"], { keep: true }); await sbx.run("until curl -sf -o /dev/null localhost:3000/api/status; do sleep 1; done", { timeout: 60 }); ``` ```python title="Python" run theme={null} sbx.spawn(["node", "/app/server.js"], keep=True) sbx.run("until curl -sf -o /dev/null localhost:3000/api/status; do sleep 1; done", timeout=60) ``` ```bash title="curl" run theme={null} curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["node", "/app/server.js"], "keep": true}' curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["sh", "-c", "until curl -sf -o /dev/null localhost:3000/api/status; do sleep 1; done"]}' ``` **4. Open it from anywhere** ```bash title="CLI" run theme={null} URL=$(fibre url "$SBX") curl -sS "$URL/"; echo #

Hello from a fibre sandbox

Visit #1

curl -sS "$URL/api/status" # {"ok":true,"started":"2026-…","visits":1} ``` ```typescript title="TypeScript" run theme={null} const page = await fetch(sbx.url).then((r) => r.text()); console.log(page); //

Hello from a fibre sandbox

Visit #1

const status = await fetch(`${sbx.url}/api/status`).then((r) => r.json()); console.log(status); // { ok: true, started: '2026-…', visits: 1 } ``` ```python title="Python" run theme={null} import json from urllib.request import urlopen page = urlopen(sbx.url).read().decode() print(page) #

Hello from a fibre sandbox

Visit #1

status = json.load(urlopen(f"{sbx.url}/api/status")) print(status) # {'ok': True, 'started': '2026-…', 'visits': 1} ``` ```bash title="curl" run theme={null} URL=$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .url) curl -sS "$URL/" echo curl -sS "$URL/api/status" ``` > [accordion] Output > > ```text title="output" expected theme={null} > Hello from a fibre sandbox > ``` **Paste the `url` into your browser, or send it to someone.** They see the app, over HTTPS, without setting anything up. ## A visitor wakes it This sandbox was created to sleep after one quiet minute. Wait for it to fall asleep, then **simply visit the URL again**. You do not need to call the API or wake the sandbox first. The first request waits a moment while the sandbox wakes up, then gets its answer from the same server, which still remembers its earlier visits. ```bash title="CLI" run theme={null} until [ "$(fibre get "$SBX" --json | jq -r .status)" = standby ]; do sleep 5; done echo "asleep, costing nothing; now a visitor arrives:" curl -sS "$URL/api/status" # the same "started", visits 1: the same server, woken ``` ```typescript title="TypeScript" run theme={null} while ((await sbx.refresh()).status !== "standby") await new Promise((r) => setTimeout(r, 5000)); console.log(sbx.status); // standby: costing nothing const afterSleep = await fetch(`${sbx.url}/api/status`).then((r) => r.json()); console.log(afterSleep.started === status.started, afterSleep.visits); // true 1 ``` ```python title="Python" run theme={null} import time while sbx.refresh().status != "standby": time.sleep(5) print(sbx.status) # standby: costing nothing after_sleep = json.load(urlopen(f"{sbx.url}/api/status")) print(after_sleep["started"] == status["started"], after_sleep["visits"]) # True 1 ``` ```bash title="curl" run theme={null} for i in $(seq 1 40); do [ "$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .status)" = standby ] && break sleep 5 done echo "asleep; now a visitor arrives:" URL=$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .url) curl -sS "$URL/api/status" ``` > [accordion] Output > > ```text title="output" expected theme={null} > "ok":true > ``` **The `started` time is the same as before the sleep.** That shows the server was resumed, not restarted. Anything it held in memory, such as user sessions, caches or a loaded model, is still there. ## Live connections The address carries more than ordinary page loads: * **WebSockets work**, so features such as live reload, chat and terminals in the browser all work. * **Streaming responses**, such as server-sent events, reach the visitor as your app writes them. * **An open connection keeps the sandbox awake.** A user watching a live page is never cut off because the sandbox went to sleep. ## Who can open it > [!WARNING] > > **The `url` is public.** Anyone who has the address can open the app, without a Fibre key. The address is long and > hard to guess, but treat it like a shared link: add your own sign-in to anything private, and never serve secrets > from it. If you do not want a sandbox reachable from the internet, simply do not run anything on its exposed port. When nothing is listening there, the address answers with an error and reaches nothing inside the sandbox. ## Good to know These details answer the questions that usually come up: | | | | - | - | | The address | `https://--.fibre.run`, fixed for the sandbox's life, in `url` and `hostname` | | The port | One per sandbox: `exposed_port` (8000 unless you set it), chosen at create | | Listen on | Any address in the sandbox; `0.0.0.0` is the safe choice for frameworks that ask | | HTTPS | Always, with a valid certificate; your app speaks plain HTTP inside | | Sleeping sandbox | The first request wakes it and waits; requests arriving together share one wake | | Ready | With your own `image` or `entrypoint`, the create call answers once the port answers | > [!TIP] > > **Development servers** such as Vite, Next.js and webpack often listen only on `localhost` and reject requests for > unknown hostnames. Start them with `--host 0.0.0.0`, and add the sandbox's hostname to the framework's list of > allowed hosts if it has one (for Vite, `server.allowedHosts`). [Preview environments](/use-cases/dev-server) shows > a complete example. ## 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] [Preview environments](/use-cases/dev-server) > > A preview per pull request, from a repo. > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > What a sleeping app keeps, and what wakes it. > [card] [Run commands](/sandboxes/running-commands) > > Keep servers running with `keep`. > [card] [Browser](/connect/browser) > > Test the app with a real browser in the same sandbox. # Use sandboxes from a web app Source: https://docs.fibre.dev/connect/web-apps Let the people using your web app run code, preview apps and watch agents in Fibre sandboxes, while your API key stays on your server: the pattern, a small server in TypeScript and Python, previews in a page, live output and CORS. Many apps built on Fibre have a web page in front: a coding playground, an app builder that shows a live preview, a data tool that runs Python for its users, or a dashboard that watches agents at work. The people using the page never talk to Fibre directly. **Your server does**, and the page talks to your server. > [!WARNING] > > **Never put your Fibre API key in code that runs in a browser.** Anyone who opens the page can read it, and with it > they could create sandboxes on your account. Keep the key on your server, and give the browser only what it needs. ## The pattern 1. **The browser asks your server** to do something for the signed-in user: run this code, start my preview. 2. **Your server finds that user's sandbox**, or creates one, using labels such as `{"user": "42"}` (see [a sandbox per user](/use-cases/sandbox-per-user)), and makes the Fibre calls with your key. 3. **Your server answers the browser** with the result: the command's output, or the address of a preview. This keeps every decision on your side: who may run what, how much, and for how long. ## A small server Here is a server with one route, `POST /api/run`, that runs a user's Python in their own sandbox and returns the output. It finds the sandbox by the user's ID and creates it on first use. Add your own sign-in check where the comment says so: ```typescript title="TypeScript (Node)" norun reason="runs in your own server" theme={null} import { createServer } from "node:http"; import { Sandbox } from "@fibre-dev/sdk"; // FIBRE_API_KEY is set on the server, never in the page async function sandboxFor(userId: string): Promise { for await (const s of Sandbox.list({ labels: { app: "playground", user: userId } })) return s; return Sandbox.create({ labels: { app: "playground", user: userId }, idleTimeout: 120, lifetime: 86400 }); } createServer(async (req, res) => { if (req.method !== "POST" || req.url !== "/api/run") return void res.writeHead(404).end(); const userId = "42"; // your sign-in: the user of this request let body = ""; for await (const chunk of req) body += chunk; const { code } = JSON.parse(body); const sbx = await sandboxFor(userId); const r = await sbx.run(["python3", "-c", code], { timeout: 30 }); res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ stdout: r.stdout, stderr: r.stderr, exitCode: r.exitCode })); }).listen(8080); ``` ```python title="Python (FastAPI)" norun reason="runs in your own server" theme={null} from fastapi import FastAPI from pydantic import BaseModel from fibre import Sandbox # FIBRE_API_KEY is set on the server, never in the page app = FastAPI() def sandbox_for(user_id: str) -> Sandbox: for s in Sandbox.list(labels={"app": "playground", "user": user_id}): return s return Sandbox.create(labels={"app": "playground", "user": user_id}, idle_timeout=120, lifetime=86400) class Run(BaseModel): code: str @app.post("/api/run") def run(body: Run): user_id = "42" # your sign-in: the user of this request sbx = sandbox_for(user_id) r = sbx.run(["python3", "-c", body.code], timeout=30) return {"stdout": r.stdout, "stderr": r.stderr, "exit_code": r.exit_code} ``` The page then calls your route like any other: ```javascript title="In the page" norun reason="runs in a browser" theme={null} const answer = await fetch("/api/run", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code: "print(6 * 7)" }), }).then((r) => r.json()); console.log(answer.stdout); // 42 ``` Because each user has their own sandbox, which sleeps between requests, a user who runs code again finds the variables, files and packages of their last run still there. ## Show an app running in a sandbox When the sandbox serves an app, such as a preview of what the user is building, create it with `exposed_port` and start the app in the background. Its **public `url`** can go straight into the page, for example in an `iframe`: ```html title="In the page" norun reason="runs in a browser" theme={null} ``` Your server returns the URL to the page. Keep in mind that **anyone who has the URL can open the app**, as with any public address, and a visit wakes a sleeping sandbox. See [public URLs](/connect/public-urls). ## Show output as it happens For long commands, such as an install, a build or an agent at work, the page should show output while it is being written. Your server starts the command in the background, follows its output, and passes each piece on to the browser, for example as [server-sent events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) or over a WebSocket: ```typescript title="TypeScript (Node)" norun reason="runs in your own server" theme={null} // inside a route handler, after finding the user's sandbox res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); const build = await sbx.spawn("npm run build", { cwd: "/work/app" }); for await (const chunk of build.output()) res.write(`data: ${JSON.stringify(chunk)}\n\n`); res.end(`data: ${JSON.stringify({ exitCode: (await build.wait()).exitCode })}\n\n`); ``` See [run commands](/sandboxes/running-commands) for following, reattaching and stopping commands. ## Calls from the page to the sandbox's app (CORS) If code in your page calls the app inside a sandbox directly, at its `url`, the browser treats that as a request to another site and asks the app whether it allows it. That is the app's decision: **set CORS headers in the app that runs in the sandbox**, as you would for any API on another domain. For example, a Node app can answer with `Access-Control-Allow-Origin: https://your-app.example` and the methods and headers it accepts, and answer `OPTIONS` requests itself. ## Watching an agent's browser or desktop If an agent works in a sandbox's [browser](/connect/browser), its **live view link** shows the browser and passes on clicks and keys, and nothing else, so it is safe to show to a person in your page. Keep the browser's DevTools address (`cdp_url`) on your server: it gives full control of the browser. A [desktop](/connect/desktop) link works once, for the first person who opens it. # API keys Source: https://docs.fibre.dev/get-started/api-keys Every request carries an API key. Create one, limit it to some areas, to one sandbox or to a lifetime, list and revoke keys, and what each error means. An **API key** is how Fibre knows who is making a request. Every request you send includes a key, in the `Authorization` header, and Fibre uses it to decide which account the request belongs to and what it is allowed to do. A key does not have to be all-powerful. You can create keys that can only do certain things, keys that only work on one sandbox, and keys that stop working after a set time. This page shows how, and why you would want to. ## Use your key Create your first key in the dashboard, under **API keys**. It starts with `fb_live_`. **Copy it as soon as it is created: Fibre shows it only once** and keeps only a fingerprint of it, so it cannot be shown again. If you lose it, create a new one. Send the key as a bearer token. The SDKs read it from the `FIBRE_API_KEY` environment variable, or you can pass it in yourself: ```bash title="curl" norun reason="shows the header; every example on these docs sends it" theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes" -H "Authorization: Bearer $FIBRE_API_KEY" ``` ```bash title="CLI" norun reason="shows where the CLI takes its key" theme={null} # the CLI uses FIBRE_API_KEY when it is set, else the key you saved with `fibre login`; or pass one fibre list --api-key "$MY_FIBRE_KEY" ``` ```typescript title="TypeScript" norun reason="shows the client options" theme={null} import { Fibre, Sandbox } from "@fibre-dev/sdk"; // reads FIBRE_API_KEY by default; or pass a key const fibre = new Fibre({ apiKey: process.env.MY_FIBRE_KEY }); const sbx = await Sandbox.create({}, fibre); ``` ```python title="Python" norun reason="shows the client options" theme={null} import os from fibre import Fibre, Sandbox # reads FIBRE_API_KEY by default; or pass a key fibre = Fibre(api_key=os.environ["MY_FIBRE_KEY"]) sbx = Sandbox.create(client=fibre) ``` A key from the dashboard can do everything your account can do. That is convenient on your own machine, but risky anywhere else. For a CI job, a script or an agent, it is much safer to create **a key that can do only what that job needs**. If such a key leaks, the damage is limited to what it was allowed to do. ## A key for one job **1. Create it with scopes and an expiry** Two settings narrow a key down: * **`scopes`** lists what the key may do. `sandboxes.read`, for example, lets it look at sandboxes but not create or change them. All the scopes are listed [further down](#scopes). * **`expires_in_sec`** sets when the key stops working. This creates a key that can only read sandboxes, and only for the next hour: ```bash title="CLI" run theme={null} CI=$(fibre key create ci-read-only --scope sandboxes.read --expires 1h --json) CI_ID=$(echo "$CI" | jq -r .id) CI_KEY=$(echo "$CI" | jq -r .key) ``` ```typescript title="TypeScript" run theme={null} import { Fibre, PermissionDeniedError, Sandbox } from "@fibre-dev/sdk"; const fibre = new Fibre(); const ci = await fibre.json<{ id: string; key: string }>("POST", "/v1/auth/api-keys", { body: { name: "ci-read-only", scopes: ["sandboxes.read"], expires_in_sec: 3600 }, }); ``` ```python title="Python" run theme={null} from fibre import Fibre, PermissionDeniedError, Sandbox fibre = Fibre() ci = fibre.json("POST", "/v1/auth/api-keys", json={"name": "ci-read-only", "scopes": ["sandboxes.read"], "expires_in_sec": 3600}) ``` ```bash title="curl" run capture=KEY=.key theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/auth/api-keys" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"name": "ci-read-only", "scopes": ["sandboxes.read"], "expires_in_sec": 3600}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "name": "ci-read-only", > "key": "…", > "scopes": ["sandboxes.read"], > "resource": null, > "expires_at": "…" > } > ``` **2. Use it** Now try the new key. Listing sandboxes is a read, so it works. Starting a sandbox is a write, so Fibre refuses it and says which scope was missing: ```bash title="CLI" run theme={null} fibre list --api-key "$CI_KEY" fibre create --api-key "$CI_KEY" --json || true # {"error": {"code": "insufficient_scope", …}} ``` ```typescript title="TypeScript" run theme={null} const readOnly = new Fibre({ apiKey: ci.key }); for await (const s of Sandbox.list({}, readOnly)) console.log(s.id); try { await Sandbox.create({}, readOnly); } catch (e) { if (!(e instanceof PermissionDeniedError)) throw e; console.log(e.status, e.code); // 403 insufficient_scope } ``` ```python title="Python" run theme={null} read_only = Fibre(api_key=ci["key"]) for s in Sandbox.list(client=read_only): print(s.id) try: Sandbox.create(client=read_only) except PermissionDeniedError as e: print(e.status, e.code) # 403 insufficient_scope ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "code": "insufficient_scope", > "required": "sandboxes.write", > "granted": ["sandboxes.read"] > } > ``` > [!NOTE] > > A key can create other keys only if it has the `keys.write` scope. Even then, it can never create a key that can do > more than itself, or one that lives longer than itself. So a limited key can never be used to make an unlimited > one. ## A key for one sandbox When an agent runs **inside** a sandbox, it often needs to use Fibre itself: to read its own files, start a background command, or extend its own lifetime. Giving it your main key would let it reach every sandbox you own. Instead, **bind a key to that one sandbox** with the `resource` field. The bound key works on that sandbox and nothing else, and it is revoked automatically when the sandbox is deleted. Here is the whole flow: **1. Start a sandbox** ```bash title="CLI" run theme={null} SBX=$(fibre create --lifetime 10m --label docs=keys --json | jq -r .id) ``` ```typescript title="TypeScript" run theme={null} const sbx = await Sandbox.create({ lifetime: 600, labels: { docs: "keys" } }); ``` ```python title="Python" run theme={null} sbx = Sandbox.create(lifetime=600, labels={"docs": "keys"}) ``` ```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": 600, "labels": {"docs": "keys"}}' ``` **2. Create a key bound to it** ```bash title="CLI" run theme={null} AGENT_KEY=$(fibre key create "agent-$SBX" --scope 'sandboxes.*' --sandbox "$SBX" --json | jq -r .key) ``` ```typescript title="TypeScript" run theme={null} const agent = await fibre.json<{ key: string }>("POST", "/v1/auth/api-keys", { body: { name: `agent-${sbx.id}`, scopes: ["sandboxes.*"], resource: sbx.id }, }); ``` ```python title="Python" run theme={null} agent = fibre.json("POST", "/v1/auth/api-keys", json={"name": f"agent-{sbx.id}", "scopes": ["sandboxes.*"], "resource": sbx.id}) ``` ```bash title="curl" run capture=AGENT_KEY=.key theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/auth/api-keys" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d "{\"name\": \"agent-$SBX\", \"scopes\": [\"sandboxes.*\"], \"resource\": \"$SBX\"}" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "key": "…", > "scopes": ["sandboxes.*"], > "resource": "…" > } > ``` **3. Hand it to the program inside** Pass the key to the program inside the sandbox as an environment variable of the command that starts it. Only that command, and the programs it starts, can see it: ```bash title="CLI" run theme={null} fibre exec "$SBX" --env FIBRE_API_KEY="$AGENT_KEY" -- 'test -n "$FIBRE_API_KEY" && echo has its key' ``` ```typescript title="TypeScript" run theme={null} const { stdout } = await sbx.run('test -n "$FIBRE_API_KEY" && echo has its key', { env: { FIBRE_API_KEY: agent.key } }); console.log(stdout); // has its key ``` ```python title="Python" run theme={null} print(sbx.run('test -n "$FIBRE_API_KEY" && echo has its key', env={"FIBRE_API_KEY": agent["key"]}).stdout) # has its key ``` **4. It reaches its own sandbox, and nothing else** ```bash title="CLI" run theme={null} fibre get "$SBX" --api-key "$AGENT_KEY" --json | jq -r .status # running fibre create --api-key "$AGENT_KEY" --json || true # {"error": {"code": "key_resource_bound", …}} ``` ```typescript title="TypeScript" run theme={null} const own = new Fibre({ apiKey: agent.key }); console.log((await Sandbox.get(sbx.id, own)).status); // running try { await Sandbox.create({}, own); } catch (e) { if (!(e instanceof PermissionDeniedError)) throw e; console.log(e.code); // key_resource_bound } ``` ```python title="Python" run theme={null} own = Fibre(api_key=agent["key"]) print(Sandbox.get(sbx.id, client=own).status) # running try: Sandbox.create(client=own) except PermissionDeniedError as e: print(e.code) # key_resource_bound ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \ -H "Authorization: Bearer $AGENT_KEY" -H "Content-Type: application/json" \ -d '{"command": ["echo", "only this one"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "only this one\n" > } > ``` If the key is used for anything outside its sandbox, such as listing all sandboxes, Fibre refuses it: ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes" -H "Authorization: Bearer $AGENT_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "code": "key_resource_bound" > } > ``` If the key asks for a different sandbox by its ID, Fibre answers `404 sandbox_not_found`, as if that sandbox did not exist. The key cannot even learn which other sandboxes you have. ## List and revoke keys You can list all the keys of your account at any time. The list shows each key's name, its first few characters (`prefix`, so you can recognise it), its scopes and when it was last used. It never shows the key itself. To revoke a key, delete it. **A revoked key stops working immediately.** ```bash title="CLI" run theme={null} fibre key list fibre key revoke "$CI_ID" fibre delete "$SBX" # its bound key goes with it ``` ```typescript title="TypeScript" run theme={null} const { keys } = await fibre.json<{ keys: { id: string; name: string; prefix: string }[] }>("GET", "/v1/auth/api-keys"); console.log(keys.map((k) => `${k.name} ${k.prefix}`)); await fibre.json("DELETE", `/v1/auth/api-keys/${ci.id}`); await sbx.delete(); // its bound key goes with it ``` ```python title="Python" run theme={null} keys = fibre.json("GET", "/v1/auth/api-keys")["keys"] print([f"{k['name']} {k['prefix']}" for k in keys]) fibre.json("DELETE", f"/v1/auth/api-keys/{ci['id']}") sbx.delete() # its bound key goes with it ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/auth/api-keys" -H "Authorization: Bearer $FIBRE_API_KEY" \ | jq '.keys[] | {id, name, prefix, scopes, resource, last_used_at}' ``` ```bash title="curl: revoke one" run theme={null} ID=$(curl -sS "$FIBRE_API_URL/v1/auth/api-keys" -H "Authorization: Bearer $FIBRE_API_KEY" \ | jq -r '.keys[] | select(.name == "ci-read-only") | .id' | head -n 1) curl -sS -X DELETE "$FIBRE_API_URL/v1/auth/api-keys/$ID" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "deleted": true, > "id": "…" > } > ``` ```bash title="curl: delete the sandbox" run theme={null} curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" ``` ## Scopes A scope combines an **area** of the API with what the key may do there: * `sandboxes.read` lets the key look, for example list sandboxes or read their status. Any `GET` request needs `.read`. * `sandboxes.write` lets the key make changes, for example create, update or delete sandboxes, or run commands. Every other request needs `.write`. * `sandboxes.*` allows both, and `*` on its own allows everything in every area. These are the areas: | Area | Covers | | - | - | | `sandboxes` | Sandboxes and everything in them: exec, commands, files, browser, desktop | | `snapshots` | Snapshots | | `images` | Images | | `builds` | Image builds | | `webhooks` | Webhooks | | `keys` | API keys | | `secrets` | Stored secrets: set, list and delete them. A sandbox or command that names a secret needs `secrets.read` | | `billing` | Usage, balance and payments | | `org` | Your organization's details (`GET /v1/org`) | ## Errors If a request is refused because of its key, the answer tells you why: | Status | Code | What happened | | - | - | - | | 401 | `missing_credentials` | No `Authorization: Bearer …` header | | 401 | `invalid_api_key` | The key is wrong, revoked, expired, or its sandbox was deleted | | 403 | `insufficient_scope` | The key's scopes do not cover this call; the answer names `required` and `granted` | | 403 | `key_resource_bound` | A key bound to one sandbox was used for something else | | 403 | `key_broader` | A new key would be able to do more than the key creating it | | 400 | `unknown_scope` | A scope that does not exist; the answer lists the areas | | 404 | `key_resource_not_found` | `resource` names no sandbox of yours | | 404 | `api_key_not_found` | No key with that ID | ## Keep keys safe A few habits keep your account safe: * **Keep keys out of your code.** Read them from environment variables or a secret manager, and never commit them to a repository. * **Give each job its own key.** A CI pipeline, a script and an agent should each have a separate key, with only the scopes and the lifetime they need. Then one leak affects one job. * **Inside a sandbox, use a bound key.** It cannot reach anything beyond that sandbox. * **If a key leaks, revoke it.** Nothing else needs to change: create a new key and carry on. # Concepts Source: https://docs.fibre.dev/get-started/concepts Every word the Fibre docs use, defined once: sandbox, size, runtime, image, snapshot, exec and commands, sleep and wake, lifetime, labels, address, API key. This page explains the ideas behind Fibre, in the order you will meet them. Each idea gets a few sentences and a link to the page that covers it in depth. If you read only one page before you start building, make it this one. ## Sandbox A **sandbox** is an isolated Linux machine that you start with a single API call. It has its own processes, its own files, its own network and its own HTTPS address. Code running in one sandbox cannot see or touch your systems, or any other sandbox. You usually create one sandbox per unit of work: one per user of your app, one per agent task, or one per conversation. Each sandbox has an ID such as `sbx-1a2b3c4d5e`, which you use in every call that concerns it. [More about sandboxes](/sandboxes/overview). ## Size, runtime and image When you create a sandbox, three choices decide what kind of machine it is. You can leave all three out and get sensible defaults. * **Size** is how much machine you get: `xsmall`, `small` (the default), `medium`, `large` or `xlarge`. Each size has a fixed amount of CPU, memory and disk, and its own price per hour. [Sizes and prices](/get-started/pricing). * **Runtime** is how the sandbox runs. `standard` suits almost everything: code, tools, tests and browsers. `vm` is a full virtual machine with its own Linux kernel, for software that needs one, such as Docker or systemd. Both cost the same. [More about runtimes](/sandboxes/runtimes). * **Image** is the set of files the sandbox starts with. Fibre's default image already has a shell, Python, Node, git and a browser. You can also use any public image, or build your own. [More about images](/setup/images). ## Running code: exec and commands There are two ways to run something in a sandbox, and the difference matters: * An **exec** runs a command and waits for it to finish, then gives you its output. It is the simplest option, and it stops the command after 30 seconds. Use it for quick things. * A **command** runs in the background for as long as it needs. You can watch its output as it is written, send it input, stop it, or keep it running even while the sandbox sleeps. Use it for installs, test runs, servers and agents. [More about running commands](/sandboxes/running-commands). ## Files The **files** API lets you read, write, list and delete files in a sandbox directly, without going through a shell. It is how you put code and data in, and take results out. [More about files](/sandboxes/files). ## Sleep and wake This is what makes Fibre different from a regular server. When nothing has happened in a sandbox for a while (5 minutes, unless you choose another **idle timeout**), the sandbox **goes to sleep**. Its memory is saved together with everything else, and you stop paying for compute. The next time anything uses the sandbox (a command, a file call, or someone opening its address) it **wakes up** exactly where it was. Running programs carry on, data in memory is still there, and open browser tabs are still open. You do not need to write any code to save or restore state. [More about sleep and wake](/sandboxes/sleep-and-wake). ## Lifetime Sleep is not deletion, and neither is time passing: **a sandbox is kept until you delete it**, asleep or awake. Fibre never deletes one on its own. If you want a sandbox to delete itself, give it a **lifetime**, from 60 seconds up to 10 years, counted from when you set it. You can change or remove the lifetime at any time. [More about lifetime](/sandboxes/sleep-and-wake#lifetime). ## Snapshots A **snapshot** is a sandbox saved together with its memory and its running programs. When you start a new sandbox from a snapshot, it begins exactly as the snapshot was: dependencies already installed, servers already running. Snapshots let you do slow setup work once instead of in every sandbox. [More about snapshots](/setup/snapshots). ## Labels **Labels** are key-value tags that you attach to a sandbox, such as `user: 42` or `task: fix-login`. You can list sandboxes by label, so you never need to store sandbox IDs in your own database: you simply ask for "the sandboxes of user 42". [Finding sandboxes again](/sandboxes/overview#find-it-again). ## Address Every sandbox has its own HTTPS address, in its `url` field. If a program in the sandbox listens on the sandbox's exposed port, anyone with the address can reach it in a browser. This is how you show a user the app an agent built, or share a preview. [More about public URLs](/connect/public-urls). ## API keys and your organization Your code signs in with an **API key**. A key can be limited: to certain kinds of action, to a single sandbox, or to a set lifetime. A key that only works on one sandbox is the safe way to let an agent inside that sandbox use Fibre. [More about API keys](/get-started/api-keys). Your **organization** is your account. Sandboxes, keys, usage and billing all belong to it. ## States At any moment, a sandbox's `status` is one of these: | Status | What it means | Billed | | - | - | - | | `running` | Awake. Commands, files and its address all respond | Per second | | `standby` | Asleep, with its memory saved. The next call wakes it | Nothing for compute | A sandbox that has been deleted, or whose lifetime has ended, no longer exists. Asking for it returns `404 sandbox_not_found`. ## Quick reference | Word | In one line | | - | - | | **Sandbox** | An isolated Linux machine, started with one call | | **Size** | How much CPU, memory and disk it has | | **Runtime** | `standard`, or `vm` for a full virtual machine | | **Image** | The files it starts with | | **Exec** | Run a command and wait, up to 30 seconds | | **Command** | Run something in the background, as long as needed | | **Sleep / wake** | Pauses with its memory when idle, resumes on the next call | | **Lifetime** | Optional: when it is deleted automatically. Without one, it is kept until you delete it | | **Snapshot** | A saved sandbox that new sandboxes start from | | **Labels** | Your own tags, for finding sandboxes again | | **Address** | Its HTTPS URL | | **API key** | How your code signs in | ## See them on a real sandbox Create a sandbox and look at its answer: you will find most of the ideas above as fields. ```bash title="CLI" run theme={null} SBX=$(fibre create --lifetime 5m --label docs=concepts --json | jq -r .id) fibre get "$SBX" # its status, runtime, size, public URL and when it is deleted fibre delete "$SBX" ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ lifetime: 300, labels: { docs: "concepts" } }); console.log(sbx.status, sbx.runtime, sbx.url, sbx.expiresAt); await sbx.delete(); ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(lifetime=300, labels={"docs": "concepts"}) print(sbx.status, sbx.runtime, sbx.url, sbx.expires_at) sbx.delete() ``` ```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": 300, "labels": {"docs": "concepts"}}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "runtime": "standard", > "idle_timeout_sec": 300, > "expires_at": "…", > "labels": { > "docs": "concepts" > }, > "url": "…" > } > ``` ```bash title="curl: delete it" run theme={null} curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" ``` ## Next > [card] [Quickstart](/get-started/quickstart) > > Put these ideas to work: start a sandbox and run code in it. > [card] [Pricing and limits](/get-started/pricing) > > What each size costs, the plans, and every limit. # Pricing and limits Source: https://docs.fibre.dev/get-started/pricing What a sandbox costs per awake hour at each size, a worked monthly cost, the plans, the free trial, and the main limits. Fibre charges for compute **by the second, and only while a sandbox is awake**. When a sandbox has nothing to do, it goes to sleep on its own, and a sleeping sandbox costs nothing for compute. This is why you can give every user or every task its own sandbox without paying for machines that sit idle. This page explains what each size costs, how storage and plans work, and lists the main limits. ## Sizes and prices The size of a sandbox decides how much CPU, memory and disk it has, and its price per hour of awake time. You choose the size when you create the sandbox. | Size | vCPU | Memory | Disk | Per awake hour | | - | - | - | - | - | | `xsmall` | 1 | 2 GB | 10 GB | \$0.0075 | | `small` (the default) | 2 | 4 GB | 10 GB | \$0.015 | | `medium` | 4 | 8 GB | 20 GB | \$0.030 | | `large` | 8 | 16 GB | 40 GB | \$0.060 | | `xlarge` | 16 | 32 GB | 80 GB | \$0.165 | Both [runtimes](/sandboxes/runtimes), `standard` and `vm`, cost the same for a given size. Network traffic is included in the price. > [card] What a month costs > > Say a `medium` sandbox is awake 3 hours a day for a 30-day month. That is 90 awake hours, and 90 × $0.030 = **$2.70\*\*. For the other 21 hours of each day it is asleep and costs nothing for compute. ## Storage When a sandbox sleeps, Fibre saves its memory and files so that it can wake up exactly where it was. That saved state, together with any [snapshots](/setup/snapshots) you keep, counts towards your storage. Every account includes **20 GB**, and storage beyond that costs **\$0.10 per GB per month**. ## Plans A plan sets how many sandboxes you can keep, awake or asleep, and how many you can start or wake each day. **The plan's price comes back to you as credit**, which pays for awake time and storage. Credit you do not use rolls over for up to 3 months. | Per month | Credit | Sandboxes kept | Starts and wakes a day | | - | - | - | - | | \$20 | \$20 | 100 | 200 | | \$100 | \$100 | 300 | 840 | | \$500 | \$500 | 1,000 | 1,680 | | \$2,000 | \$2,000 | 2,000 | 2,400 | * **Sandboxes kept** counts every sandbox you have, awake or asleep. When you reach it, creating another is refused (`429 sandbox_limit`) until you delete one or move to a larger plan. * Starts and wakes above the daily number still happen straight away. They are never queued. Each one above the number costs **\$0.03**. * Awake time beyond your credit is paid from a prepaid balance. You can turn on automatic top-up so the balance never runs out. ## Free trial The free trial lasts 7 days and includes \$20 of awake time. A card is needed to start it. During the trial you can keep up to 2 sandboxes, use the `xsmall`, `small` and `medium` sizes, and start up to 100 sandboxes a day. ## Limits These are the main limits. Each one is explained on the page about that feature, and the full list is in [errors, retries and limits](/production/errors-and-limits#limits). | | Limit | | - | - | | Exec | Stops after 30 seconds; [background commands](/sandboxes/running-commands) run as long as the sandbox lives | | Lifetime | None unless you set one: kept until you delete it. 60 seconds to 10 years; change or remove it at any time | | Idle timeout | 5 minutes by default; any number of seconds up to a day, or `0` to never sleep | | Disk | By size, 10 to 80 GB | | Labels | Up to 16 per sandbox | | Browser | One per sandbox | | API keys | Expire after up to 365 days, or never | | API requests | 1,200 reads and 600 other requests a minute on the \$20 plan; more on the larger plans | ## Next > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > What a sleeping sandbox keeps, and how to keep one awake if you need to. > [card] [Quickstart](/get-started/quickstart) > > Your first sandbox in four steps. # Quickstart Source: https://docs.fibre.dev/get-started/quickstart Your first sandbox in four steps: get a key, start a sandbox, run code in it, then let it sleep or delete it. This page takes you from nothing to a working sandbox in four short steps. You will create an API key, start a sandbox, run a small Python program inside it, and then decide whether to keep it or delete it. It takes a few minutes. Every step shows the same thing four ways: with the **CLI**, the **TypeScript SDK**, the **Python SDK** and plain **`curl`**, so you can follow along in whichever you prefer. **1. Get an API key** Every request to Fibre needs an API key, so that Fibre knows which account it is for. Sign up at [fibre.dev](https://fibre.dev), open **API keys** in the dashboard, and create a key. It starts with `fb_live_`. **Copy it straight away: it is shown only once.** Then make it available to your shell, together with the address of the API: ```bash title="Terminal" norun reason="your own key goes here" theme={null} export FIBRE_API_KEY="fb_live_…" export FIBRE_API_URL="https://api.fibre.dev" ``` If you are using the CLI, install it; if you are using TypeScript or Python, add the SDK to your project. They all read the same two variables, so there is nothing else to configure: ```bash title="CLI" norun reason="installs on your own machine" theme={null} curl -fsSL https://fibre.dev/install.sh | sh ``` ```bash title="TypeScript" norun reason="installs into your own project" theme={null} npm install @fibre-dev/sdk ``` ```bash title="Python" norun reason="installs into your own project" theme={null} pip install fibre-sdk ``` **2. Start a sandbox** ```bash title="CLI" run theme={null} SBX=$(fibre create --lifetime 10m --json | jq -r .id) fibre get "$SBX" # sbx-… running ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ lifetime: 600 }); console.log(sbx.id, sbx.status); // sbx-… running ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(lifetime=600) print(sbx.id, sbx.status) # sbx-… running ``` ```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": 600}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "runtime": "standard" > } > ``` The call waits until the sandbox is running, then answers. There is no "pending" state to check on. The answer includes the sandbox's `id` (it looks like `sbx-1a2b3c4d5e`). Keep it: every other call refers to the sandbox by this ID. Here is what you get when you leave the other options out: | You get | | | - | - | | Image | Linux with a shell, Python, Node, git and a browser | | Lifetime | 600 seconds, as asked (without one, it is kept until you delete it) | | Sleep | After 5 minutes with nothing happening | **3. Run code in it** A sandbox is a full Linux machine, so you can put files in it and run programs, just as you would on your own computer. Here we write a small Python script into the sandbox, then run it and read its output: ```bash title="CLI" run theme={null} fibre exec "$SBX" -i -- sh -c 'cat > /tmp/hello.py' <<'PY' import platform print("hello from", platform.system()) PY fibre exec "$SBX" -- python3 /tmp/hello.py # hello from Linux ``` ```typescript title="TypeScript" run theme={null} await sbx.files.write("/tmp/hello.py", "import platform\nprint('hello from', platform.system())\n"); const result = await sbx.run(["python3", "/tmp/hello.py"]); console.log(result.exitCode, result.stdout); // 0 hello from Linux ``` ```python title="Python" run theme={null} sbx.files.write("/tmp/hello.py", "import platform\nprint('hello from', platform.system())\n") result = sbx.run(["python3", "/tmp/hello.py"]) print(result.exit_code, result.stdout) # 0 hello from Linux ``` ```bash title="curl" run theme={null} printf 'import platform\nprint("hello from", platform.system())\n' | \ curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/tmp/hello.py" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["python3", "/tmp/hello.py"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "hello from Linux\n" > } > ``` > [!TIP] > > This way of running a command (an *exec*) waits for the command to finish, and stops it if it takes longer than 30 > seconds. That is perfect for quick commands. For longer work such as installs, test runs and servers, use > [background commands](/sandboxes/running-commands) instead. **4. Let it sleep, or delete it** You do not need to stop a sandbox when you take a break. **If nothing happens in it for 5 minutes, it goes to sleep on its own.** While it sleeps, its memory, programs and files are all kept, and you pay nothing for compute. The next call you make to it wakes it up, exactly where it was. When you have finished with the sandbox for good, 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 > } > ``` If you forget to delete this one, it is deleted automatically when its lifetime ends, after 600 seconds. A sandbox without a lifetime is kept until you delete it. ## Next > [card] [Concepts](/get-started/concepts) > > The words these docs use, each explained in a few lines. > [card] [Run commands](/sandboxes/running-commands) > > Run long commands, watch their output live, and keep programs running. > [card] [Files](/sandboxes/files) > > Move files and folders in and out of a sandbox. > [card] [Secrets](/production/secrets) > > Store API keys once and give them to the commands that need them. > [card] [Give your agent sandboxes](/build-with-ai/mcp-server) > > Add Fibre's MCP server to Claude Code, Codex, Cursor or OpenCode in one command. > [card] [From your coding agent](/build-with-ai/coding-agents) > > Let your agent read these docs and write the code. # FAQ Source: https://docs.fibre.dev/help/faq Short answers to the questions developers ask most about Fibre: what a sandbox is, sleep and cost, limits, security, agents, and how Fibre fits next to your own infrastructure. > [accordion] What is a sandbox? > > An isolated Linux machine you start with one API call. It has its own processes, files, network and HTTPS address. > Your code, your agent or your users run anything in it without touching your systems or each other. > [accordion] How fast does a sandbox start? > > The create call answers when the sandbox is running, with no pending state to poll. A copy of a > [snapshot](/setup/snapshots) starts with its programs already running, so there is no setup time either. > [accordion] What does a sleeping sandbox cost? > > Nothing for compute. Its saved state counts towards the storage included with your account (20 GB), then \$0.10 per > GB-month. See [pricing](/get-started/pricing). > [accordion] What survives a sleep? > > Memory, files and programs: the same process, with its variables, answers after a wake. On `standard`, start > long-lived programs with `keep: true`; on `vm`, every process is kept. See [sleep and wake](/sandboxes/sleep-and-wake). > [accordion] How long can a sandbox live? > > As long as you want: a sandbox is kept until you delete it, asleep while nothing happens in it. If you give it a > lifetime, it is deleted when that ends; you can change or remove the lifetime at any time. > [accordion] Can I run Docker inside a sandbox? > > Yes, on the `vm` runtime: create it with `needs: ["docker"]`. Docker Compose works too. See > [Docker and Compose](/use-cases/docker). > [accordion] Standard or VM: which should I use? > > Leave it out and Fibre picks from what you ask for. `standard` suits code, tools, tests and browsers; `vm` gives the > sandbox its own kernel for Docker, systemd and kernel features. Same price. See [runtimes](/sandboxes/runtimes). > [accordion] Is it safe to run code a model wrote? > > That is what sandboxes are for. Each one is isolated from your systems and from other sandboxes. For untrusted code, > also restrict its [network](/production/network) and keep long-lived secrets out of it. See > [security and isolation](/production/security). > [accordion] Can my agent use Fibre directly? > > Yes. Give it a [key bound to its own sandbox](/get-started/api-keys#a-key-for-one-sandbox) so it can manage that > sandbox and nothing else, or point your coding agent at these docs through their [MCP server](/build-with-ai/coding-agents). > [accordion] Which agents can run inside a sandbox? > > Any that runs on Linux: Claude Code, Codex, OpenCode and agents you build with an SDK are shown step by step under > [Build with AI](/build-with-ai/coding-agents). > [accordion] Can a sandbox serve a website? > > Yes. Set `exposed_port`, and whatever listens there is live at the sandbox's HTTPS `url`. A visitor wakes a > sleeping sandbox. See [public URLs](/connect/public-urls). > [accordion] How many sandboxes can I run? > > By plan, you can keep from 100 to 2,000 sandboxes, awake or asleep. When you reach your plan's number, creating > another is refused until you delete some or move to a larger plan. See [limits](/production/errors-and-limits#limits). > [accordion] Which languages are installed? > > Python 3.11 and Node.js 22, with git, curl and a Chromium browser, on the default image. Install anything else, or > start from any public image. See [sizes and installed tools](/sandboxes/sizes). > [accordion] Is there a Python SDK? > > Yes: `pip install fibre-sdk`, for Python 3.11 and later, with a regular and an `asyncio` API. Every page of these > docs shows it in a Python tab. See the [Python SDK](/sdks/python). # Troubleshooting Source: https://docs.fibre.dev/help/troubleshooting The problems developers hit most, what causes each, and the fix: sandboxes that do not start, commands that stop, packages that will not install, servers that do not answer at their URL, and programs missing after a wake. ## A sandbox from my own image does not start **What you see:** the create call fails after a while (`start_failed`, or an error about a port not ready). **Why:** with your own `image`, Fibre treats it as a server: it runs the image's command and waits for it to answer on `exposed_port` (8000). A base image like `python:3.12-slim` runs nothing that listens, or exits at once. **Fix:** for an image you run commands in, add `"ready": "process"`. For an app image, set `exposed_port` to the port it listens on. See [bring your own image](/sandboxes/sizes#bring-your-own-image). ## My command stops after 30 seconds **Why:** `POST /v1/sandboxes/{id}/exec` waits at most 30 seconds. A command still running then is stopped, and the answer is `504 exec_timeout`. **Fix:** use a [background command](/sandboxes/running-commands) (`POST /v1/sandboxes/{id}/commands`), which has no time limit, and follow its output. In the SDKs, `sbx.run()` already does this. ## `pip install` fails with "externally managed environment" **Why:** the default image's system Python refuses packages installed outside a virtual environment. **Fix:** `python3 -m venv /work/.venv && /work/.venv/bin/pip install …`. It takes a second. See [install what is missing](/sandboxes/sizes#install-what-is-missing). ## My dev server does not answer at the sandbox's URL Check, in order: 1. **The sandbox was created with `exposed_port`** set to the port the server listens on (8000 unless set). 2. **The server listens on `0.0.0.0`**, not only `localhost`: `--host 0.0.0.0` for Vite, Next.js and most dev servers. 3. **The framework accepts the sandbox's hostname.** Vite answers "Blocked request" otherwise: set `__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS` to the sandbox's `hostname`, or `server.allowedHosts`. 4. **It is still running.** Start servers with `keep: true`, and check with `curl -s localhost:` from an exec. See [public URLs](/connect/public-urls). ## A program I started is gone after the sandbox woke up **Why:** on the `standard` runtime, only the sandbox's main program and commands started with `keep: true` carry on across sleep. A plain command still running at the sleep is not restored. **Fix:** start long-lived programs with `keep: true`, or use the `vm` runtime, where every process is kept. See [what is kept](/sandboxes/sleep-and-wake#what-is-kept). ## Command calls answer `409 not_running` **Why:** the sandbox is asleep. Commands belong to its awake period, so their list, status and output are gone after a sleep. **Fix:** read results before the sandbox can sleep (a running command keeps it awake), or write them to a file and read it with the [files API](/sandboxes/files), which wakes the sandbox. ## My sandbox never sleeps **Why:** something keeps it busy: a running command, a program using CPU, open network traffic (including an open browser tab on its URL or a connected browser client), or `idle_timeout_sec: 0`. **Fix:** check `GET /v1/billing/current` for what is awake, and the sandbox's `idle_timeout_sec`. End background commands you no longer need. See [when it sleeps](/sandboxes/sleep-and-wake#when-it-sleeps). ## Code in my sandbox cannot reach a site **Why:** the sandbox was created with a `network` allow list that does not include the site, or `{"block": true}`. **Fix:** add the host (and any host it redirects to, such as a CDN) to `allow` on a new sandbox. See [network access](/production/network). ## Docker says it cannot connect to the daemon **Why:** Docker needs the `vm` runtime, and the daemon must be running. **Fix:** create the sandbox with `needs: ["docker"]`, start `dockerd` (as the entrypoint, or in the background), and wait for `docker info` to succeed before using it. See [Docker and Compose](/use-cases/docker). ## `429 sandbox_limit` **Why:** your account keeps as many sandboxes as its plan allows. Sleeping sandboxes count too. **Fix:** delete sandboxes you no longer need (`Sandbox.list({ labels })` finds them), or move to a larger plan. See [limits](/production/errors-and-limits#limits). ## `429 org_limit` **Why:** your sandboxes already use as much of the capacity that could run this one as one account may. **Fix:** stop or delete sandboxes you no longer need, or ask for a smaller size. ## Still stuck? Note the `request_id` from the error, the sandbox ID and what you expected, and contact support. The `request_id` lets us find the exact request. # Introduction Source: https://docs.fibre.dev/index Fibre gives every AI agent, user and task its own Linux machine in one API call. It sleeps with its memory when work stops and wakes exactly where it was, so you pay only for the seconds it works. Every agent that writes code needs somewhere to run it. Your servers are the wrong place, and a fresh container for every step forgets everything the agent just did. **Fibre gives each agent, user or task its own Linux machine, in one API call.** It comes with a shell, Python, Node, git and a browser, and it is isolated from your systems and from every other sandbox. When the work stops, the sandbox **goes to sleep with its memory intact** and costs nothing for compute. The next call wakes it exactly where it was: the same processes, the same variables, the same open browser tabs. ```bash title="CLI" run theme={null} fibre run --rm --lifetime 10m -- python3 -c "print('hello from Fibre')" ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ lifetime: 600 }); const { stdout } = await sbx.run(["python3", "-c", "print('hello from Fibre')"]); console.log(stdout); // hello from Fibre await sbx.delete(); ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(lifetime=600) r = sbx.run(["python3", "-c", "print('hello from Fibre')"]) print(r.stdout) # hello from Fibre sbx.delete() ``` ```bash title="curl" run theme={null} SBX=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"lifetime_sec": 600}' | jq -r .id) curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["python3", "-c", "print(\"hello from Fibre\")"]}' curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "hello from Fibre\n" > } > ``` That is a whole sandbox's life: start, run, delete. The [quickstart](/get-started/quickstart) walks through it with your own key in four steps. ## How a sandbox lives ```mermaid theme={null} flowchart LR A["Create
one API call"] --> B["Running
commands, files, its URL"] B -- "nothing happening
for a few minutes" --> C["Asleep
memory saved, no compute cost"] C -- "the next call or visit" --> B B --> D["Deleted
by you, or at a lifetime you set"] C --> D ``` 1. **Create** a sandbox when a user signs up, a task starts or a conversation opens. The call returns once it is running. 2. **Work in it**: run commands and stream their output, move files in and out, serve an app at its own HTTPS address, drive its browser. 3. **Let it sleep.** When nothing has happened for a few minutes, it sleeps on its own. There is nothing to save or shut down. 4. **Come back any time.** The next call, or a visit to its URL, wakes it with everything where it was. 5. **Delete it** when the job is truly done. Until then it is kept, or give it a lifetime and it deletes itself. ## Why build on Fibre > [card] [Memory survives sleep](/sandboxes/sleep-and-wake) > > A dev server, a loaded dataset, an agent's session, a logged-in browser: all still there after a wake. **No cold > starts to engineer around**, and no state to save and restore. > [card] [Pay for awake seconds only](/get-started/pricing) > > Billed per second while a sandbox works, nothing for compute while it sleeps. A sandbox per user, active 30 > minutes a day on 20 days a month, costs about **\$0.30**. > [card] [Real machines, two kinds](/sandboxes/runtimes) > > `standard` for code, tests and browsers; `vm`, a full virtual machine with its own kernel, for **Docker, > Compose and systemd**. Same API, same price. > [card] [Made for agents](/get-started/api-keys) > > An [MCP server](/build-with-ai/mcp-server) that gives your coding agent sandboxes, keys that work on **one > sandbox only**, network allow lists for untrusted code, and signed webhooks. ## What developers build with it > [card] [A code interpreter for your AI app](/use-cases/run-code) > > A model writes Python; a sandbox per conversation runs it and returns the output and charts. > [card] [A coding agent on your repo](/use-cases/coding-agent) > > Claude Code or Codex fixes a bug in a machine of its own; you review the diff. > [card] [A sandbox per user](/use-cases/sandbox-per-user) > > A workspace for every user of your product, with no compute cost while they are away. > [card] [Many agents in parallel](/use-cases/parallel) > > One prepared environment, a copy per task, all running at once. > [card] [Preview environments](/use-cases/dev-server) > > A live link for every pull request, updating as the code changes. > [card] [Browser automation](/connect/browser) > > A real Chromium for Playwright, with a live view and logins that last. See [all use cases](/use-cases/overview), each a complete program you can run. ## Start here > [card] [Quickstart](/get-started/quickstart) > > Your first sandbox, step by step. > [card] [Concepts](/get-started/concepts) > > The words and states, in one page. > [card] [From your coding agent](/build-with-ai/coding-agents) > > Let Claude Code, Codex or Cursor write the code. ## At a glance | | | | - | - | | Start | One API call; it answers when the sandbox is running | | Billing | Per second, only while awake | | Sleep | After 5 minutes with nothing happening; you choose shorter, longer or never | | Lifetime | None unless you set one: kept until you delete it. Up to 10 years, changed or removed at any time | | Sizes | `xsmall` 1 vCPU / 2 GB to `xlarge` 16 vCPU / 32 GB, from \$0.0075 an hour; `small` (2 vCPU / 4 GB) unless you choose. See [pricing and limits](/get-started/pricing) | | Default image | Linux with a shell, Python 3.11, Node 22, git and Chromium; or your own image | | Clients | The [TypeScript](/sdks/typescript) and [Python](/sdks/python) SDKs, the [CLI](/sdks/cli) and the [HTTP API](/api-reference/introduction) | # Best practices Source: https://docs.fibre.dev/production/best-practices How to use Fibre well in production: one sandbox per unit of work, reused through sleep, with lifetimes, labels, safe retries, snapshots for fast starts, secrets by name, and nothing left running by accident. Fibre sandboxes are cheap to start and cost nothing for compute while they sleep, so the right patterns are a little different from the ones you may know from servers or containers. This page collects the practices that make an app on Fibre fast, cheap and safe. Each one links to the page that shows it working. ## Give each unit of work its own sandbox, and reuse it Decide what one sandbox is for: one user of your app, one conversation with an agent, one task, one test run. Then **keep using that sandbox for as long as that unit of work lasts**, instead of creating a new one for each step. A sandbox that is not in use goes to sleep with its memory, files and running programs, and costs nothing for compute while it sleeps. The next call wakes it exactly where it was, with dependencies still installed and data still loaded. Creating a fresh sandbox each time throws all of that away and makes every step pay for setup again. To find a sandbox again later, give it **labels** that say what it belongs to, such as `{"user": "42"}`, and look it up by label. See [a sandbox per user](/use-cases/sandbox-per-user). ## Set an idle timeout that fits, and a lifetime if you want one * **Lifetime:** a sandbox is kept until you delete it. Give it a lifetime only when it should delete itself, such as a sandbox per conversation that may be abandoned. A lifetime counts from when you set it, and you can extend or remove it. * **Idle timeout:** how long a sandbox waits with nothing happening before it sleeps, 5 minutes unless you set it. Shorter saves money; longer keeps it awake through pauses. A sandbox serving a page to people can sleep after a minute: the next visitor wakes it. See [sleep and wake](/sandboxes/sleep-and-wake). ## Clean up, and check that you did Delete a sandbox when its work is done: one you do not delete is kept, and its storage counts towards your bill. Run your clean-up in a `finally` block (or with `with` in Python), so a failure in the middle does not leave sandboxes behind. Every so often, list sandboxes by label and delete the ones whose work has ended. [Usage](/production/usage) shows what is running and what it costs. ## Make retries safe Networks fail, and a request can succeed even though its answer never reaches you. The SDKs retry temporary failures for you. If you call the API yourself, send an **`Idempotency-Key`** header when you create a sandbox, so that sending the same request twice creates only one sandbox. See [errors, retries and limits](/production/errors-and-limits). ## Start from a snapshot when setup takes time If every sandbox needs the same slow preparation, such as cloning a repository, installing dependencies or loading a model, do it once in one sandbox and **save it as a [snapshot](/setup/snapshots)**. New sandboxes start from the snapshot already prepared, with its memory and running programs. For a prepared filesystem without memory, build an [image](/setup/images) from a Dockerfile instead. ## Run long work in the background A quick command can run and wait. Installs, test suites, builds and agents can take minutes: start them as **background commands** and follow their output as it is written. They have no time limit, keep the sandbox awake while they run, and you can reattach to them by ID from anywhere. Start servers with `keep` so they carry on across sleep and wake. See [run commands](/sandboxes/running-commands). ## Keep secrets out of code and out of reach Store API keys and passwords as [secrets](/production/secrets) and give them **by name to the one command** that needs them. Never print a secret, never put one in `env_vars`, and never put your account's API key in a sandbox: give code inside a sandbox a [key for that one sandbox](/get-started/api-keys#a-key-for-one-sandbox) instead. ## Limit what untrusted code can reach For code written by a model or uploaded by a user, limit the sandbox's [network](/production/network) to what the code needs, such as a package index, or block it entirely. Code that cannot reach anywhere cannot send anything anywhere, whatever it found. ## Reconnect after a wake Programs keep running across a sleep, but the services they talk to do not wait for them. Use your database and HTTP clients' reconnect or health-check options, so that the first call after a wake opens a fresh connection when the old one has been closed. See [connections to other services](/sandboxes/sleep-and-wake#connections-to-other-services). ## Fan out within your limits Many sandboxes can run at the same time, which is what makes evals, test sharding and parallel agents fast. Your plan sets how many sandboxes you can keep, awake or asleep. When you start a large batch, delete each sandbox when its task is done, start the batch in waves or through a queue, and handle `sandbox_limit` by waiting for earlier tasks to finish and trying again. See [parallel work](/use-cases/parallel) and [errors, retries and limits](/production/errors-and-limits). ## Keep results somewhere that outlives the sandbox A sandbox is a place to do work, not to store it. Copy out the results you need, push code to its repository, or write output to your own storage before the sandbox is deleted. See [keep work for longer](/sandboxes/sleep-and-wake#keep-work-for-longer). # Errors, retries and limits Source: https://docs.fibre.dev/production/errors-and-limits Handle Fibre's errors well in production: the error shape, which errors to retry and how, safe retries with idempotency keys, and every limit in one place. In production, some calls will fail. The network might drop for a moment, you might reach a limit, or a sandbox might already have been deleted. **Handling errors well mostly comes down to one decision: should your code try again, or should it stop and fix something?** This page gives you what you need to make that decision in code. ## Every error looks the same Whatever goes wrong, Fibre answers with the same kind of JSON, so you can handle every error in one place: ```bash title="CLI" run expect-exit=3 theme={null} fibre get sbx-0000000000 --json # {"error": {"code": "sandbox_not_found", …}}, exit code 3 ``` ```typescript title="TypeScript" run theme={null} import { FibreError, NotFoundError, Sandbox } from "@fibre-dev/sdk"; try { await Sandbox.get("sbx-0000000000"); } catch (e) { if (e instanceof NotFoundError) console.log("gone:", e.code, e.requestId); // gone: sandbox_not_found req_… else throw e; } ``` ```python title="Python" run theme={null} from fibre import NotFoundError, Sandbox try: Sandbox.get("sbx-0000000000") except NotFoundError as e: print("gone:", e.code, e.request_id) # gone: sandbox_not_found req_… ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes/sbx-0000000000" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "error": "…", > "code": "sandbox_not_found", > "request_id": "…", > "docs_url": "…" > } > ``` | Field | Use it for | | - | - | | `code` | **Your logic.** Stable names like `sandbox_not_found`, safe to `switch` on. Never parse `error` | | `error` | A sentence for a person: logs, alerts | | `request_id` | **Support.** Include it when you ask us about a failure; it finds the exact request | | `docs_url` | The code's entry in the [error list](/api-reference/errors) | | others | Some errors add fields: `details` (which body fields are wrong), `required` and `granted` (scopes), `limit` | In the SDKs, every error is a `FibreError` with `status`, `code`, `requestId` and `docsUrl` (`request_id` and `docs_url` in Python). Each kind of error also has its own class, so you can catch only the ones you care about: | Class | Status | | - | - | | `ValidationError` | 400, 422 | | `AuthenticationError` | 401 | | `PaymentRequiredError` | 402 | | `PermissionDeniedError` | 403 | | `NotFoundError` | 404 | | `ConflictError` | 409 | | `RateLimitError` | 429, with `retryAfter` in seconds | | `ServerError` | 5xx | | `ConnectionError`, `TimeoutError` | No answer arrived | ## Retry, or not? The HTTP status tells you which kind of problem you have, and whether trying again can help: | Status | Retry? | What to do | | - | - | - | | 400, 422 | **No** | Your request is wrong. Read `code` and `details`, fix it | | 401, 403 | **No** | Wrong, expired or too narrow key. See [API keys](/get-started/api-keys#errors) | | 402 | **No** | Billing: add funds, turn on auto top-up, or choose a plan | | 404 | **No** | It does not exist (deleted, expired, or never yours). Treat as final | | 409 | **Sometimes** | A state conflict. `idempotency_key_in_progress`: wait and retry. Others: fix the state first | | 429 | **Yes, later** | A limit. Wait (`Retry-After` when given) or free capacity, then retry | | 500, 502, 503, 504 | **Yes** | Temporary. Retry with backoff: 1 s, 2 s, 4 s, up to about a minute | | No answer | **Yes**, if the call is safe to repeat | See below | **The SDKs already retry for you.** When a connection drops, or Fibre answers `429`, `502`, `503` or `504`, the SDK tries again twice, waiting a little longer each time, as long as the call is safe to repeat. To change how many times, use `new Fibre({ maxRetries })`, or `Fibre(max_retries=…)` in Python. ## Retrying a create safely One case needs special care: **a request to create a sandbox that times out**. You cannot tell whether the sandbox was created or not, and simply trying again could create a second one that you pay for. To avoid that, send an `Idempotency-Key` header. **If you retry with the same key, Fibre returns the first sandbox instead of creating another:** ```bash title="curl" norun reason="shows the header; the create page runs the same call" theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Idempotency-Key: user-42-task-7" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"labels": {"user": "42", "task": "7"}}' ``` * **Base the key on what you are creating**, for example `user-42-task-7`, or a random ID that you store with the job. * **A key is remembered for 24 hours.** Using the same key with a different request is refused (`422 idempotency_key_reused`). * **In the SDKs, `Sandbox.create()` sends a key for you**, so the SDK's own retries never create a second sandbox. There is more about this in [retry without making two](/sandboxes/overview#retry-without-making-two). ## A retry helper If you make calls outside the SDK, or want to wait longer than its built-in retries do, a small helper like this one retries temporary errors and gives up on everything else: ```typescript title="TypeScript" norun reason="a helper for your own code" theme={null} import { FibreError, ConnectionError, TimeoutError } from "@fibre-dev/sdk"; const RETRY = new Set([429, 500, 502, 503, 504]); export async function withRetry(call: () => Promise, attempts = 5): Promise { for (let i = 0; ; i++) { try { return await call(); } catch (e) { const temporary = e instanceof ConnectionError || e instanceof TimeoutError || (e instanceof FibreError && RETRY.has(e.status)); if (!temporary || i === attempts - 1) throw e; const wait = (e as any).retryAfter ?? Math.min(2 ** i, 30) + Math.random(); await new Promise((r) => setTimeout(r, wait * 1000)); } } } ``` ```python title="Python" norun reason="a helper for your own code" theme={null} import random import time from fibre import FibreConnectionError, FibreError, FibreTimeoutError RETRY = {429, 500, 502, 503, 504} def with_retry(call, attempts=5): for i in range(attempts): try: return call() except FibreError as e: temporary = isinstance(e, (FibreConnectionError, FibreTimeoutError)) or e.status in RETRY if not temporary or i == attempts - 1: raise wait = getattr(e, "retry_after", None) or min(2**i, 30) + random.random() time.sleep(wait) ``` ## Limits Here is every limit in one place: | | Limit | | - | - | | **Sandboxes kept** | By plan: 100, 300, 1,000 or 2,000, awake or asleep. Above it a create is refused (`429 sandbox_limit`) | | **Starts and wakes a day** | By plan: 200, 840, 1,680 or 2,400. Above it, \$0.03 each | | **API requests** | Per account, each minute: 1,200 reads (`GET`) and 600 other requests on the \$20 plan; 3×, 10× and 20× that on the larger plans. Above it `429 rate_limited`, with `retry_after_ms` | | Lifetime | None unless you set one: kept until you delete it. 60 seconds to 10 years; change or remove it at any time | | Idle timeout | 0 (never sleep) to a day; 300 seconds unless set | | Sizes | Up to 16 vCPU, 32 GB memory, 80 GB disk | | Labels | 16 per sandbox; keys up to 63 characters, values up to 128 | | List page | 50 sandboxes, up to 200 with `limit` | | HTTP exec | 30 seconds; 4 MB of output per stream | | Background command | No time limit, or `timeout_sec` | | Write to a command's input | 8 MB per call | | Files | Up to the sandbox's free disk | | Network allow list | 200 entries | | Browser | One per sandbox | | Shells | 5 open at once per user | | Secrets | 50 named per sandbox or command | | API keys | Expire after up to 365 days, or never | | Idempotency keys | 1 to 255 characters, kept 24 hours | | Webhook endpoints | 10 per account; 10 seconds to answer; 7 attempts | | Build context | 2 GB | | Free trial | 2 sandboxes kept, `xsmall`, `small` and `medium` sizes, 100 starts a day | ## Related > [card] [All error codes](/api-reference/errors) > > Every error code, its HTTP status and what it means. > [card] [Usage and billing](/production/usage) > > See how close you are to your plan's limits today. # Network access Source: https://docs.fibre.dev/production/network Decide what a sandbox can reach on the internet: everything, only the sites you list, or nothing. Run untrusted or AI-generated code that can install packages but cannot send your data anywhere else. By default a sandbox can reach the whole internet. It can clone repositories, install packages and call APIs, which is exactly what most agents need. Sometimes, though, you run code you cannot fully trust: a file a user uploaded, code a model has just written, or a dependency nobody has checked. If that code can reach the whole internet, it could **send whatever it finds to anyone**, such as environment variables, API keys or your users' files. The `network` option lets you decide what a sandbox can reach: | `network` | The sandbox can reach | | - | - | | leave it out | Everything | | `{"allow": ["pypi.org", "*.github.com"]}` | **Only** those names and addresses | | `{"block": true}` | Nothing at all | You set it when you create the sandbox. **Everything else keeps working as usual**: you can still run commands, read files and use the sandbox's address. Only the connections that the sandbox itself tries to make to the outside world are limited. ## Let code install packages, and nothing else A common setup for code written by a model: it may install Python packages from PyPI, the Python package index, and **reach nothing else**. **1. Create the sandbox with an allow list** ```bash title="CLI" run theme={null} SBX=$(fibre create --allow pypi.org,files.pythonhosted.org --lifetime 10m --label docs=network --json | jq -r .id) fibre get "$SBX" --json | jq .network # {"allow": ["pypi.org", "files.pythonhosted.org"]} ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ network: { allow: ["pypi.org", "files.pythonhosted.org"] }, lifetime: 600, labels: { docs: "network" }, }); console.log(sbx.data.network); // { allow: [ 'pypi.org', 'files.pythonhosted.org' ] } ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(network={"allow": ["pypi.org", "files.pythonhosted.org"]}, lifetime=600, labels={"docs": "network"}) print(sbx.data["network"]) # {'allow': ['pypi.org', 'files.pythonhosted.org']} ``` ```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 '{"network": {"allow": ["pypi.org", "files.pythonhosted.org"]}, "lifetime_sec": 600, "labels": {"docs": "network"}}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "network": { > "allow": ["pypi.org", "files.pythonhosted.org"] > } > } > ``` **2. Installing from PyPI works** ```bash title="CLI" run theme={null} fibre exec "$SBX" -- 'python3 -m venv /work/.venv && /work/.venv/bin/pip install -q requests && echo installed' ``` ```typescript title="TypeScript" run theme={null} const install = await sbx.run("python3 -m venv /work/.venv && /work/.venv/bin/pip install -q requests && echo installed", { timeout: 300 }); console.log(install.stdout); // installed ``` ```python title="Python" run theme={null} install = sbx.run("python3 -m venv /work/.venv && /work/.venv/bin/pip install -q requests && echo installed", timeout=300) print(install.stdout) # installed ``` ```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 requests && echo installed"]}' ``` ```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" ``` > [accordion] Output > > ```text title="output" expected theme={null} > installed > ``` **3. Anything else is refused** Now the code tries to send data to another server. The connection is refused, and nothing leaves the sandbox: ```bash title="CLI" run theme={null} fibre exec "$SBX" -- "/work/.venv/bin/python -c \"import requests; requests.post('https://example.com', data='secrets', timeout=10)\" 2>&1 | tail -n 1 || true" # requests.exceptions.ConnectionError: … ``` ```typescript title="TypeScript" run theme={null} const leak = await sbx.run( `/work/.venv/bin/python -c "import requests; requests.post('https://example.com', data='secrets', timeout=10)" 2>&1 | tail -n 1 || true`, ); console.log(leak.stdout); // requests.exceptions.ConnectionError: … ``` ```python title="Python" run theme={null} leak = sbx.run( "/work/.venv/bin/python -c \"import requests; requests.post('https://example.com', data='secrets', timeout=10)\" 2>&1 | tail -n 1 || true" ) print(leak.stdout) # requests.exceptions.ConnectionError: … ``` ```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", "curl -sS -m 10 https://example.com > /dev/null && echo reached || echo refused"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "refused\n" > } > ``` ## What an allow list can hold An allow list can hold up to 200 entries, of four kinds: | Entry | Matches | Example | | - | - | - | | A name | That name exactly | `api.openai.com` | | `*.` and a name | Every name under it, not the name itself | `*.githubusercontent.com` | | An IPv4 address | That address | `203.0.113.10` | | A CIDR range | Every address in it | `203.0.113.0/24` | These lists come up often: | To | Allow | | - | - | | Install Python packages | `pypi.org`, `files.pythonhosted.org` | | Install npm packages | `registry.npmjs.org` | | Clone from GitHub | `github.com`, `*.githubusercontent.com` | | Call a model API | the provider's API host, such as `api.anthropic.com` or `api.openai.com` | > [!TIP] > > **Start with a short list and add to it only when needed.** Run the job once. If it fails because it could not > reach a host, the error names that host. Add it only if the code really needs it. ## No network at all Some code needs no network at all: a calculation, a parser for user input, a data transformation. For that kind of work, cut the network off completely with `{"block": true}`: ```bash title="CLI" run theme={null} SEALED=$(fibre create --no-network --lifetime 5m --label docs=network --json | jq -r .id) fibre exec "$SEALED" -- 'curl -sS -m 5 https://pypi.org > /dev/null && echo reached || echo no network' # no network fibre exec "$SEALED" -- python3 -c 'print(sum(i * i for i in range(10**6)))' # 333332833333500000 fibre delete "$SEALED" ``` ```typescript title="TypeScript" run theme={null} const sealed = await Sandbox.create({ network: { block: true }, lifetime: 300, labels: { docs: "network" } }); const tryIt = await sealed.run("curl -sS -m 5 https://pypi.org > /dev/null && echo reached || echo no network"); console.log(tryIt.stdout); // no network const math = await sealed.run(["python3", "-c", "print(sum(i * i for i in range(10**6)))"]); console.log(math.stdout); // 333332833333500000 await sealed.delete(); ``` ```python title="Python" run theme={null} sealed = Sandbox.create(network={"block": True}, lifetime=300, labels={"docs": "network"}) try_it = sealed.run("curl -sS -m 5 https://pypi.org > /dev/null && echo reached || echo no network") print(try_it.stdout) # no network math = sealed.run(["python3", "-c", "print(sum(i * i for i in range(10**6)))"]) print(math.stdout) # 333332833333500000 sealed.delete() ``` ```bash title="curl" run capture=SEALED=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"network": {"block": true}, "lifetime_sec": 300, "labels": {"docs": "network"}}' ``` ```bash title="curl: try to reach out" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SEALED/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["sh", "-c", "curl -sS -m 5 https://pypi.org > /dev/null && echo reached || echo no network"]}' curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SEALED" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "no network\n" > } > ``` **You can still do everything from the outside**: put files in, run commands and read the results. The sandbox simply cannot open any connection of its own. ## Good to know A few rules about how network settings work: | | | | - | - | | When | Set at create. To change it, create a new sandbox (a [snapshot](/setup/snapshots) makes that instant) | | Direction | Limits connections **from** the sandbox. Calls you make to it, and visitors to its `url`, work as usual | | Names | Matched as the code asks for them; the addresses behind an allowed name are allowed | | Default | No `network`: the whole internet | ## Errors An invalid `network` setting is refused when you create the sandbox: | Status | Code | When | | - | - | - | | 400 | `validation_failed` | Both `allow` and `block`, or an entry that is not a name, `*.name`, IPv4 address or CIDR | ## 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] [Security and isolation](/production/security) > > What keeps each sandbox separate from the others. > [card] [API keys](/get-started/api-keys) > > A key that can only reach one sandbox. # Secrets Source: https://docs.fibre.dev/production/secrets Store API keys, tokens and passwords once, encrypted, and give them to sandboxes by name: to the one command that needs a secret, or to every command in a sandbox. Values are never shown again. Code in a sandbox often needs a secret: a model provider's API key for an agent, a token to clone a private repository, a password for a test database. You could paste the value into every request, but then it lives in your code, in your scripts and in your shell history. Instead, **store the secret in Fibre once**, under a name such as `OPENAI_API_KEY`, and give it to a sandbox **by name**. Fibre keeps the value encrypted and adds it as an environment variable only where you ask for it: | You name the secret on | Who gets it | | - | - | | A command (`secrets` on a command) | **That command only.** The next command does not see it | | A sandbox (`secrets` when you create it) | Every command that runs in that sandbox | A sandbox that names no secret gets none. A stored value is **write-only**: once it is set, Fibre never shows it again, not in the API, the SDKs or the CLI. You can only replace it or delete it. ## Store a secret Give it a name in `UPPER_SNAKE_CASE`, which becomes the name of the environment variable, and the value. In the CLI, `fibre secret set OPENAI_API_KEY` asks for the value without showing it, or reads it from a pipe, so the value never appears on the command line: ```bash title="CLI" run theme={null} printf %s "example-key-0123456789" | fibre secret set OPENAI_API_KEY ``` ```typescript title="TypeScript" run theme={null} import { Sandbox, Secret } from "@fibre-dev/sdk"; const secret = await Secret.set("OPENAI_API_KEY", "example-key-0123456789"); // in your code: read it from your own config console.log(secret.name, secret.version); // OPENAI_API_KEY 1 ``` ```python title="Python" run theme={null} from fibre import Sandbox, Secret secret = Secret.set("OPENAI_API_KEY", "example-key-0123456789") # in your code: read it from your own config print(secret.name, secret.version) # OPENAI_API_KEY 1 ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/secrets" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"name": "OPENAI_API_KEY", "value": "example-key-0123456789"}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "name": "OPENAI_API_KEY", > "version": 1, > "created_at": "…", > "updated_at": "…" > } > ``` The answer has the name, a version and two times. It never has the value. ## Give a secret to one command This is the safest way to use a secret, and the one to reach for first: **only the command that needs the secret gets it**, and nothing else that runs in the sandbox before or after can read it. First, a sandbox to work in. It names no secrets: ```bash title="CLI" run theme={null} SBX=$(fibre create --lifetime 10m --label docs=secrets --json | jq -r .id) ``` ```typescript title="TypeScript" run theme={null} const sbx = await Sandbox.create({ lifetime: 600, labels: { docs: "secrets" } }); ``` ```python title="Python" run theme={null} sbx = Sandbox.create(lifetime=600, labels={"docs": "secrets"}) ``` ```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": 600, "labels": {"docs": "secrets"}}' ``` Now run a command that names the secret. Inside the sandbox it is an ordinary environment variable. This program only reports how long the key is, because output is the one place a secret could leak by accident: ```bash title="CLI" run theme={null} fibre exec "$SBX" --secret OPENAI_API_KEY -- \ python3 -c "import os; print('key loaded:', len(os.environ['OPENAI_API_KEY']), 'characters')" # key loaded: 22 characters fibre exec "$SBX" -- sh -c 'echo "the next command: ${OPENAI_API_KEY:-no key}"' # the next command: no key ``` ```typescript title="TypeScript" run theme={null} const check = "import os; print('key loaded:', len(os.environ['OPENAI_API_KEY']), 'characters')"; const withKey = await sbx.run(["python3", "-c", check], { secrets: ["OPENAI_API_KEY"] }); console.log(withKey.stdout); // key loaded: 22 characters const next = await sbx.run('echo "the next command: ${OPENAI_API_KEY:-no key}"'); console.log(next.stdout); // the next command: no key ``` ```python title="Python" run theme={null} check = "import os; print('key loaded:', len(os.environ['OPENAI_API_KEY']), 'characters')" with_key = sbx.run(["python3", "-c", check], secrets=["OPENAI_API_KEY"]) print(with_key.stdout) # key loaded: 22 characters nxt = sbx.run('echo "the next command: ${OPENAI_API_KEY:-no key}"') print(nxt.stdout) # the next command: no key ``` ```bash title="curl" run theme={null} CID=$(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", "-c", "import os; print(\"key loaded:\", len(os.environ[\"OPENAI_API_KEY\"]), \"characters\")"], "secrets": ["OPENAI_API_KEY"]}' \ | jq -r .command_id) curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/commands/$CID/logs?follow=1" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```text title="output" expected theme={null} > key loaded: 22 characters > ``` In the API, `secrets` works on [Start a command](/api-reference/commands/start-a-command), alongside `env`. A name cannot be both in `secrets` and in `env`. ## Give a secret to a whole sandbox Some programs run for a long time and need a secret the whole time, such as a server you start in the background or an agent that runs many commands. Name the secret when you **create** the sandbox, and every command in it gets the value. The sandbox's details list the secrets it uses, by name only: ```bash title="CLI" run theme={null} AGENT=$(fibre create --secret OPENAI_API_KEY --lifetime 10m --label docs=secrets --json | jq -r .id) fibre get "$AGENT" --json | jq -c .secrets # ["OPENAI_API_KEY"] fibre exec "$AGENT" -- sh -c 'echo "key loaded: ${#OPENAI_API_KEY} characters"' # key loaded: 22 characters ``` ```typescript title="TypeScript" run theme={null} const agent = await Sandbox.create({ secrets: ["OPENAI_API_KEY"], lifetime: 600, labels: { docs: "secrets" } }); console.log(agent.secrets); // [ 'OPENAI_API_KEY' ] const inside = await agent.run('echo "key loaded: ${#OPENAI_API_KEY} characters"'); console.log(inside.stdout); // key loaded: 22 characters ``` ```python title="Python" run theme={null} agent = Sandbox.create(secrets=["OPENAI_API_KEY"], lifetime=600, labels={"docs": "secrets"}) print(agent.secrets) # ['OPENAI_API_KEY'] inside = agent.run('echo "key loaded: ${#OPENAI_API_KEY} characters"') print(inside.stdout) # key loaded: 22 characters ``` ```bash title="curl" run capture=AGENT=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"secrets": ["OPENAI_API_KEY"], "lifetime_sec": 600, "labels": {"docs": "secrets"}}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "secrets": ["OPENAI_API_KEY"] > } > ``` Fibre stores only the **names** with the sandbox. It reads the values each time the sandbox starts, so they are never saved with it. > [!WARNING] > > **A snapshot keeps a sandbox's memory, and memory includes what its running programs hold.** If a program in the > sandbox had a secret when you saved a [snapshot](/setup/snapshots), copies of that snapshot start with that program > and its secret. Save snapshots before your programs load secrets, or from a sandbox that never had them, and name > secrets on the copies instead. ## Change or delete a secret To change a value, **set it again** with the same name. Its version goes up, and from then on: * **Commands that name it** get the new value straight away. * **New sandboxes that name it** start with the new value. * **A sandbox that got it when it was created** keeps the value it started with. Create a new sandbox, or name the secret on its commands, to use the new one. You can list your secrets at any time. You see names, versions and times, never values: ```bash title="CLI" run theme={null} printf %s "example-key-9876543210" | fibre secret set OPENAI_API_KEY # version 2 fibre secret list ``` ```typescript title="TypeScript" run theme={null} await Secret.set("OPENAI_API_KEY", "example-key-9876543210"); for (const s of await Secret.list()) console.log(s.name, s.version); // OPENAI_API_KEY 2 ``` ```python title="Python" run theme={null} Secret.set("OPENAI_API_KEY", "example-key-9876543210") for s in Secret.list(): print(s.name, s.version) # OPENAI_API_KEY 2 ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/secrets" -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"name": "OPENAI_API_KEY", "value": "example-key-9876543210"}' > /dev/null curl -sS "$FIBRE_API_URL/v1/secrets" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "secrets": [ > { > "name": "OPENAI_API_KEY", > "version": 2, > "created_at": "…", > "updated_at": "…" > } > ] > } > ``` When you no longer need a secret, delete it. Commands that name it from then on are refused with `secret_not_found`, and sandboxes that named it start without it. Here we also clean up the two sandboxes: ```bash title="CLI" run theme={null} fibre delete "$SBX" "$AGENT" fibre secret delete OPENAI_API_KEY ``` ```typescript title="TypeScript" run theme={null} await sbx.delete(); await agent.delete(); await (await Secret.get("OPENAI_API_KEY")).delete(); ``` ```python title="Python" run theme={null} sbx.delete() agent.delete() Secret.get("OPENAI_API_KEY").delete() ``` ```bash title="curl" run theme={null} curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$AGENT" -H "Authorization: Bearer $FIBRE_API_KEY" curl -sS -X DELETE "$FIBRE_API_URL/v1/secrets/OPENAI_API_KEY" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "name": "OPENAI_API_KEY", > "deleted": true > } > ``` ## Who can use secrets Naming a secret puts its value into a sandbox, so Fibre treats it like reading the secret: | Key | Can set, list and delete secrets | Can name secrets on a sandbox or a command | | - | - | - | | Your account's key, or a key with the `secrets.*` scope | Yes | Yes | | A key with `secrets.read` | List only | Yes | | A key without a `secrets` scope | No | No: `insufficient_scope` | | **A key for one sandbox** (made with `resource`) | No | **No**: `key_resource_bound` | The last row matters for agents. An agent working inside a sandbox should hold a [key for that one sandbox](/get-started/api-keys#a-key-for-one-sandbox). With it, the agent can run its own commands, but it **cannot pull any of your secrets** into its sandbox. Give the agent the secrets it needs yourself, when you create its sandbox or start its commands, from your own code. ## Good practice * **Name secrets on the command that needs them**, rather than on the whole sandbox, so that nothing else in the sandbox can read them. * **Never print a secret.** Command output is returned to whoever runs the command and may end up in logs, and in a model's context when an agent runs it. * **Remember that code in a sandbox can send what it can read.** For untrusted or model-written code that uses a secret, also limit the sandbox's [network](/production/network) to the services the secret is for, such as `api.openai.com`. * **Use a separate key per purpose**, such as one model key for your agents and another for evals, so you can change or revoke one without touching the others. * **Change secrets from time to time**, and at once if one may have leaked: set the new value, then revoke the old one at its provider. ## Limits | | | | - | - | | Name | `UPPER_SNAKE_CASE`: capital letters, digits and `_`, starting with a letter or `_`; up to 255 characters | | Value | 1 to 65,536 characters of text | | Names per sandbox or per command | Up to 50 | | Errors | `secret_not_found` (with the `missing` names), `validation_failed`, `insufficient_scope`, `key_resource_bound` | See the [API reference](/api-reference/secrets/set-a-secret) for every field. # Security and isolation Source: https://docs.fibre.dev/production/security What keeps one sandbox from another and from your account, how keys and secrets are handled, and the settings that make it safe to run untrusted and AI-generated code. Sandboxes exist to run code that **you do not fully trust**: code a model wrote, files a user uploaded, packages an agent decided to install. This page explains how Fibre keeps that code contained, and which settings you can use to contain it even further. It ends with a short checklist for running untrusted code. ## What Fibre isolates Fibre keeps several boundaries in place for you, without any setting: | Boundary | What it means for you | | - | - | | **Sandbox from sandbox** | Each sandbox has its own processes, files, memory and network. Code in one cannot see, signal or connect to another, yours or anyone else's | | **Sandbox from Fibre** | Code in a sandbox cannot reach Fibre's own systems, its API with your account's rights, or the machine underneath | | **Runtime** | `standard` runs every sandbox behind an isolation layer of its own. `vm` gives each sandbox **its own kernel** in a hardware virtual machine | | **Resources** | Each sandbox gets its size's CPU, memory and disk. One sandbox running away cannot starve the others | | **Account from account** | Your sandboxes, images, snapshots and keys are visible to your account only | ## What you control On top of Fibre's own boundaries, a few settings and habits make a big difference. ### Keys * **Give each job its own key**, with only the [scopes](/get-started/api-keys#scopes) it needs and the shortest lifetime that works. If one key leaks, only that job is affected. * **Inside a sandbox, use a key bound to that sandbox** (with `resource`). An agent holding it can manage its own sandbox and nothing else, and the key stops working when the sandbox is deleted. See [a key for one sandbox](/get-started/api-keys#a-key-for-one-sandbox). * **Never put your account's main key in a sandbox.** Any program running there could read it. ### Secrets in sandboxes Your agent may need a secret, such as a model API key or a database password. **Store it in Fibre** and give it to the command that needs it by name: it reaches that command only, Fibre keeps it encrypted, and its value is never shown again. A sandbox that names no secret gets none. See [secrets](/production/secrets). Avoid putting secrets in `env_vars` when you create a sandbox: those are visible to every command in it, and they are copied into snapshots made from the sandbox. > [!WARNING] > > **Keep in mind that anything code in a sandbox can read, it could also send somewhere.** If untrusted code has to > work with a secret, limit its network (see below), or make the calls that need the secret from your own server, so > the sandbox never sees it at all. ### Users inside a sandbox Commands run as `root` inside the sandbox. That is root of the sandbox's own machine, which is isolated from Fibre's hosts and from every other sandbox, so it can install packages and change any file in the sandbox, and nothing beyond it. Some programs refuse to run as root, and sometimes you want a tool to have less power than the agent that started it. Create an ordinary user in the sandbox and run those commands as that user: ```bash title="CLI" run theme={null} SBX=$(fibre create --lifetime 5m --label docs=security --json | jq -r .id) fibre exec "$SBX" -- whoami # root fibre exec "$SBX" -- sh -c 'useradd -m app && su app -c whoami' # app fibre delete "$SBX" ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ lifetime: 300, labels: { docs: "security" } }); console.log((await sbx.run("whoami")).stdout); // root console.log((await sbx.run("useradd -m app && su app -c whoami")).stdout); // app await sbx.delete(); ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(lifetime=300, labels={"docs": "security"}) print(sbx.run("whoami").stdout) # root print(sbx.run("useradd -m app && su app -c whoami").stdout) # app sbx.delete() ``` ```bash title="curl" run theme={null} SBX=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" -H "Authorization: Bearer $FIBRE_API_KEY" \ -H "Content-Type: application/json" -d '{"lifetime_sec": 300, "labels": {"docs": "security"}}' | jq -r .id) 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", "useradd -m app && su app -c whoami"]}' curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "app\n" > } > ``` ### Network By default a sandbox can reach the whole internet. For untrusted code, **allow only the hosts it really needs**, or none at all: ```json title="create body" theme={null} { "network": { "allow": ["pypi.org", "files.pythonhosted.org"] } } ``` [Network access](/production/network) has a full example: code that can install packages but cannot send your data anywhere else. ### Public URLs A sandbox's [`url`](/connect/public-urls) is public: anyone who has the address can reach whatever the sandbox serves on its exposed port. Only serve what you mean to share, and add your own sign-in to anything private. ### Browser and desktop links `cdp_url` gives full control of the sandbox's browser, so **treat it like a password** and keep it on your server. `live_view_url` and desktop links only show the screen and pass on clicks, so they are safe to show a user. Desktop links also work only once. ## How Fibre handles your data This is how Fibre treats the sensitive things you give it: | | | | - | - | | **API keys** | Shown once. Fibre stores only a digest; a lost key cannot be recovered, only replaced | | **Registry logins** | Encrypted at rest, never returned, used only to pull your images | | **Webhook secrets** | Shown once; every delivery is signed so you can verify it came from Fibre | | **A sandbox's files and memory** | Kept while it exists, including while it sleeps | | **After delete** | The sandbox, its files and its saved memory are gone and cannot be restored. Images and snapshots you made stay until you delete them | ## A checklist for untrusted code When you run code you do not trust, follow these steps: 1. **Use a fresh sandbox for each job**, and delete it when the job is done. Starting from a [snapshot](/setup/snapshots) keeps this fast. 2. **Set a network allow list**, or `{"block": true}` if the code needs no network at all. 3. **Keep long-lived secrets out of the sandbox.** If the code must call an API, give it a short-lived key with narrow scopes. 4. **Give the sandbox a short lifetime**, so that a forgotten sandbox ends by itself. 5. **Use the `standard` runtime** unless the job needs Docker or another kernel feature. Both runtimes are isolated; `vm` adds a kernel of its own. 6. **Take results out through the files API**, and check them before your app uses them. ## Related > [card] [Network access](/production/network) > > Allow lists and fully offline sandboxes. > [card] [API keys](/get-started/api-keys) > > Scoped, bound and expiring keys. # Usage and billing Source: https://docs.fibre.dev/production/usage Know what your sandboxes cost while they run: spend today, this month and projected, what is awake right now, your plan's limits, credit and balance, and every charge in the ledger. When you start sandboxes for every user and every task, your costs follow how much they are used. You will want to **see those costs as they happen, not only when the invoice arrives**, for example on an internal dashboard, in a daily message to your team, or as an alert when spending suddenly rises. The billing API gives you the numbers you need. | You want | Call | | - | - | | Spend today, this week, this month, projected | `GET /v1/billing/usage/summary` | | What is awake right now, and costing money | `GET /v1/billing/current` | | Plan, limits, credit, balance, storage | `GET /v1/billing/account` | | Spend broken down for a period | `GET /v1/billing/usage` | | Every charge and payment | `GET /v1/billing/ledger` | To call it, use an API key with the `billing.read` scope. A key from the dashboard has it already. ## How much am I spending? The summary gives you your spending so far today, this week and this month, and an estimate for the whole month: ```bash title="CLI" run theme={null} fibre usage # today, this month, projected, your plan and its limits ``` ```typescript title="TypeScript" run theme={null} import { Fibre } from "@fibre-dev/sdk"; const fibre = new Fibre(); const spend = await fibre.json<{ today: number; this_month: number; projected_month: number }>("GET", "/v1/billing/usage/summary"); console.log(`$${spend.today} today, $${spend.this_month} this month, ~$${spend.projected_month} by month end`); ``` ```python title="Python" run theme={null} from fibre import Fibre fibre = Fibre() spend = fibre.json("GET", "/v1/billing/usage/summary") print(f"${spend['today']} today, ${spend['this_month']} this month, ~${spend['projected_month']} by month end") ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/billing/usage/summary" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "today": "…", > "this_week": "…", > "this_month": "…", > "projected_month": "…" > } > ``` Amounts are in US dollars. `projected_month` estimates the whole month by assuming you keep spending at this month's pace so far. > [!TIP] > > **A daily spending message takes only a few lines of code.** Call this every morning and post `today` and > `projected_month` to your team's chat. A sudden jump in `today` is usually the first sign of a sandbox that never > goes to sleep. ## What is awake right now? Only awake sandboxes cost money for compute. This call lists every sandbox that is awake, and being charged, right now: ```typescript title="TypeScript" run theme={null} const { sessions } = await fibre.json<{ sessions: any[] }>("GET", "/v1/billing/current"); console.log(`${sessions.length} awake`); ``` ```python title="Python" run theme={null} sessions = fibre.json("GET", "/v1/billing/current")["sessions"] print(f"{len(sessions)} awake") ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/billing/current" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "sessions": "…" > } > ``` If this list is long at a time when your users are not active, look for sandboxes with `idle_timeout_sec: 0`, or for programs that keep them busy. See [what keeps a sandbox awake](/sandboxes/sleep-and-wake#when-it-sleeps). ## My plan, credit and limits The billing account shows your plan, how much credit and balance you have left, and how close you are to your plan's limits today: ```bash title="CLI" run theme={null} fibre usage --json | jq '.account | {plan, limits, storage}' ``` ```typescript title="TypeScript" run theme={null} const account = await fibre.json("GET", "/v1/billing/account"); console.log(account.plan, account.limits, account.storage); // tier_20 { sandboxes: 100, … } { gb: …, included_gb: 20 } ``` ```python title="Python" run theme={null} account = fibre.json("GET", "/v1/billing/account") print(account["plan"], account["limits"], account["storage"]) # tier_20 {'sandboxes': 100, …} {'gb': …, 'included_gb': 20} ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/billing/account" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "plan": "…", > "status": "…", > "credit_usd": "…", > "wallet_usd": "…", > "available_usd": "…", > "auto_topup": "…", > "limits": { > "sandboxes": "…", > "wakes_per_day": "…", > "above_limits": "…" > }, > "usage_today": { > "sandboxes": "…", > "awake": "…", > "wakes_today": "…", > "paid_wakes_today": "…" > }, > "storage": { > "gb": "…", > "included_gb": 20 > } > } > ``` Here is what each part of the answer means: | Field | Means | | - | - | | `plan`, `status` | Your plan and whether it is `active`, `trialing` or `canceled` | | `credit_usd` | This period's plan credit left | | `wallet_usd` | Your prepaid balance, used once credit runs out | | `available_usd` | What you can spend now: credit plus balance | | `auto_topup` | Whether the balance refills itself, when (`threshold_usd`) and by how much (`amount_usd`) | | `limits` | Sandboxes kept and starts and wakes per day on your plan, and the price above them | | `usage_today` | Sandboxes kept and awake now, and starts and wakes today: how close you are to those limits | | `storage` | Saved state and snapshots, against your included 20 GB | ## Breakdown and ledger Two more calls give you the detail behind the totals: * **`GET /v1/billing/usage`** adds up awake hours and cost for a period. It covers this month unless you pass `from` and `to`. * **`GET /v1/billing/ledger`** lists every charge and payment, newest first. Each entry shows how much was paid from plan credit and how much from your balance. ```typescript title="TypeScript" run theme={null} const usage = await fibre.json("GET", "/v1/billing/usage"); console.log(usage.total, usage.period); // { hours: …, cost: … } { from: '2026-11-01…', to: '…' } const { entries } = await fibre.json<{ entries: any[] }>("GET", "/v1/billing/ledger", { query: { limit: 5 } }); for (const e of entries) console.log(e.at, e.kind, e.amount_usd); ``` ```python title="Python" run theme={null} usage = fibre.json("GET", "/v1/billing/usage") print(usage["total"], usage["period"]) # {'hours': …, 'cost': …} {'from': '2026-11-01…', 'to': '…'} for e in fibre.json("GET", "/v1/billing/ledger", params={"limit": 5})["entries"]: print(e["at"], e["kind"], e["amount_usd"]) ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/billing/ledger?limit=2" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "entries": "…" > } > ``` > > A single ledger entry looks like this: > > ```json title="entry" theme={null} > { > "kind": "usage", > "ref": "c5cf6de5-0a48-4723-9e11-9dd49914dc9b:5", > "amount_usd": -0.000005, > "from_credit_usd": 0, > "from_wallet_usd": 0.000005, > "details": { > "session": "c5cf6de5-0a48-4723-9e11-9dd49914dc9b" > }, > "at": "2026-11-21T01:33:18.000Z" > } > ``` Because awake time is counted by the second, a single entry can be a small fraction of a cent. ## Paying You can change your plan, update your card, download invoices and add money in the dashboard, under **billing**. If you would rather build these into your own app, the same actions are available in the API: | Call | Does | | - | - | | `POST /v1/billing/checkout` | A checkout link to start or change a plan | | `POST /v1/billing/portal` | A link to manage the card and download invoices | | `POST /v1/billing/topup` | Add money to the balance | | `PUT /v1/billing/auto-topup` | Turn automatic top-up on or off, with its threshold and amount | > [!WARNING] > > **If your credit and balance both run out and automatic top-up is off, your sandboxes are put to sleep, and new > ones are refused** with `402 payment_required` until money arrives. Nothing is deleted. For anything your users > depend on, turn on automatic top-up. ## Related > [card] [Pricing and limits](/get-started/pricing) > > The price of each size, the plans and the free trial. > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > Sleep is the biggest factor in what you spend. # Webhooks Source: https://docs.fibre.dev/production/webhooks Get a signed HTTP request when a sandbox is ready, goes to sleep, crashes or is deleted, and when a build finishes, instead of polling. Verify the signature, handle retries, test and inspect deliveries. Your app often needs to **react** when something happens to a sandbox. You might want to show "ready" in your interface, bill a user when their session ends, alert someone when a sandbox crashes, or deploy when an image build finishes. You could ask Fibre about every sandbox over and over (this is called *polling*), but that is slow and wasteful. **Webhooks turn this around: Fibre tells you.** You give Fibre the address of an endpoint on your server, once. From then on, whenever something happens, Fibre sends a `POST` request to that address describing the event. Each request is signed so you can check it really came from Fibre, it is retried until your server accepts it, and every delivery is recorded. ## Events These are the events Fibre can send you: | Event | When | `data` | | - | - | - | | `sandbox.ready` | A sandbox started, **or woke from sleep** | `name` (its ID), `restored` (`true` after a wake) | | `sandbox.stopped` | It went to sleep | `name`, `reason` (`idle` when it slept on its own) | | `sandbox.crashed` | Its main program died, or it ran out of disk | `name`, `reason` | | `sandbox.deleted` | It was deleted, or its lifetime ended | `name`, `reason` | | `build.succeeded` | An image build finished | `build_id`, `image` | | `build.failed` | An image build failed | `build_id`, `error` | | `ping` | You asked for a test | `webhook_id` | Every request has a JSON body with the same shape: ```json title="body" theme={null} { "id": "6f1c8e0a-…", "type": "sandbox.ready", "created_at": "2026-11-21T02:31:07.512Z", "data": { "kind": "sandbox", "name": "sbx-1a2b3c4d5e", "restored": true } } ``` It also carries three headers: | Header | Value | | - | - | | `Fibre-Event-Id` | The event's `id`: **the same on every retry**, so you can drop duplicates | | `Fibre-Event-Type` | The event's `type` | | `Fibre-Signature` | `t=,v1=`: proof the request came from Fibre | ## Verify the signature Your endpoint is reachable from the internet, so anyone could send it a request that looks like a Fibre event. **Always check the signature before trusting a webhook.** Here is how it works. When you create the webhook, Fibre gives you a **secret** that only you and Fibre know. For each request, Fibre computes an HMAC-SHA256 of the timestamp, a dot, and the raw body (`"."`), using that secret as the key, and puts the result in the `Fibre-Signature` header. Your server computes the same value with its copy of the secret. If the two match, the request is genuine. Checking the timestamp too protects you against someone replaying an old request. Here is a complete handler in TypeScript and in Python: ```typescript title="TypeScript (Express)" norun reason="runs in your own server" theme={null} import express from "express"; import { createHmac, timingSafeEqual } from "node:crypto"; const SECRET = process.env.FIBRE_WEBHOOK_SECRET!; // shown once, when you create the webhook const app = express(); app.post("/fibre/webhooks", express.raw({ type: "application/json" }), (req, res) => { const header = req.get("Fibre-Signature") ?? ""; const t = header.match(/t=(\d+)/)?.[1]; const sigs = [...header.matchAll(/v1=([0-9a-f]+)/g)].map((m) => m[1]); const expected = createHmac("sha256", SECRET).update(`${t}.${req.body}`).digest("hex"); const valid = sigs.some((s) => s.length === expected.length && timingSafeEqual(Buffer.from(s), Buffer.from(expected))); const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300; // refuse replays older than 5 minutes if (!valid || !fresh) return res.status(400).send("bad signature"); const event = JSON.parse(req.body.toString()); if (alreadyHandled(event.id)) return res.sendStatus(200); // a retry of one you processed if (event.type === "sandbox.ready") markReady(event.data.name); if (event.type === "sandbox.stopped") endBillingSession(event.data.name); if (event.type === "sandbox.crashed") alertOnCall(event.data); res.sendStatus(200); // answer fast; do slow work after }); ``` ```python title="Python (Flask)" norun reason="runs in your own server" theme={null} import hashlib, hmac, json, os, re, time from flask import Flask, request SECRET = os.environ["FIBRE_WEBHOOK_SECRET"].encode() app = Flask(__name__) @app.post("/fibre/webhooks") def fibre_webhook(): header = request.headers.get("Fibre-Signature", "") t = re.search(r"t=(\d+)", header).group(1) sigs = re.findall(r"v1=([0-9a-f]+)", header) expected = hmac.new(SECRET, f"{t}.".encode() + request.get_data(), hashlib.sha256).hexdigest() if not any(hmac.compare_digest(s, expected) for s in sigs) or abs(time.time() - int(t)) > 300: return "bad signature", 400 event = json.loads(request.get_data()) # … handle event["type"] once per event["id"] return "", 200 ``` > [!WARNING] > > **Compute the signature over the raw body, exactly as it arrived.** If you parse the JSON first and convert it back > to text, the bytes change and the signature will not match. In Express, use `express.raw()` on this route, as > shown above. ## Try it end to end You can see real deliveries without deploying anything, because a sandbox has a public address and can act as your receiver. This small receiver checks each request's signature and writes down what arrived. **1. Start a receiver** ```typescript title="TypeScript" run theme={null} import { Fibre, Sandbox } from "@fibre-dev/sdk"; const fibre = new Fibre(); const receiver = await Sandbox.create({ exposedPort: 3000, lifetime: 900, labels: { docs: "webhooks" } }); await receiver.files.write("/app/receiver.js", ` const http = require("http"), fs = require("fs"), crypto = require("crypto"); http.createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { const secret = fs.existsSync("/app/secret") ? fs.readFileSync("/app/secret", "utf8").trim() : ""; const header = req.headers["fibre-signature"] || ""; const t = (header.match(/t=(\\d+)/) || [])[1]; const expected = crypto.createHmac("sha256", secret).update(t + "." + body).digest("hex"); const valid = header.includes("v1=" + expected); fs.appendFileSync("/app/received.log", JSON.stringify({ type: req.headers["fibre-event-type"], valid }) + "\\n"); res.writeHead(valid ? 200 : 400); res.end(); }); }).listen(3000); `); await receiver.spawn(["node", "/app/receiver.js"], { keep: true }); await receiver.run("until curl -s -o /dev/null localhost:3000; do sleep 1; done", { timeout: 60 }); ``` ```python title="Python" run theme={null} from fibre import Fibre, Sandbox fibre = Fibre() receiver = Sandbox.create(exposed_port=3000, lifetime=900, labels={"docs": "webhooks"}) receiver.files.write("/app/receiver.js", r""" const http = require("http"), fs = require("fs"), crypto = require("crypto"); http.createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { const secret = fs.existsSync("/app/secret") ? fs.readFileSync("/app/secret", "utf8").trim() : ""; const header = req.headers["fibre-signature"] || ""; const t = (header.match(/t=(\d+)/) || [])[1]; const expected = crypto.createHmac("sha256", secret).update(t + "." + body).digest("hex"); const valid = header.includes("v1=" + expected); fs.appendFileSync("/app/received.log", JSON.stringify({ type: req.headers["fibre-event-type"], valid }) + "\n"); res.writeHead(valid ? 200 : 400); res.end(); }); }).listen(3000); """) receiver.spawn(["node", "/app/receiver.js"], keep=True) receiver.run("until curl -s -o /dev/null localhost:3000; do sleep 1; done", timeout=60) ``` ```bash title="curl" run capture=RECV=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"exposed_port": 3000, "lifetime_sec": 900, "labels": {"docs": "webhooks"}}' ``` ```bash title="curl: the receiver program" run theme={null} cat <<'EOF' | curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$RECV/files/content?path=/app/receiver.js" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- const http = require("http"), fs = require("fs"), crypto = require("crypto"); http.createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { const secret = fs.existsSync("/app/secret") ? fs.readFileSync("/app/secret", "utf8").trim() : ""; const header = req.headers["fibre-signature"] || ""; const t = (header.match(/t=(\d+)/) || [])[1]; const expected = crypto.createHmac("sha256", secret).update(t + "." + body).digest("hex"); const valid = header.includes("v1=" + expected); fs.appendFileSync("/app/received.log", JSON.stringify({ type: req.headers["fibre-event-type"], valid }) + "\n"); res.writeHead(valid ? 200 : 400); res.end(); }); }).listen(3000); EOF curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$RECV/commands" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["node", "/app/receiver.js"], "keep": true}' curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$RECV/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["sh", "-c", "until curl -s -o /dev/null localhost:3000; do sleep 1; done"]}' ``` **2. Register the webhook** Now tell Fibre where to send events. `events` chooses which events you want; leave it out to receive all of them. **The answer includes the `secret`, and this is the only time you will see it**, so store it where your server can read it. Here, it is written to a file in the receiver. ```typescript title="TypeScript" run theme={null} const hook = await fibre.json<{ id: string; secret: string }>("POST", "/v1/webhooks", { body: { url: `${receiver.url}/fibre/webhooks`, events: ["sandbox.ready", "sandbox.stopped", "sandbox.crashed", "sandbox.deleted"] }, }); await receiver.files.write("/app/secret", hook.secret); ``` ```python title="Python" run theme={null} hook = fibre.json("POST", "/v1/webhooks", json={ "url": f"{receiver.url}/fibre/webhooks", "events": ["sandbox.ready", "sandbox.stopped", "sandbox.crashed", "sandbox.deleted"], }) receiver.files.write("/app/secret", hook["secret"]) ``` ```bash title="curl" run capture=HOOK=.id theme={null} URL=$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$RECV" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .url) CREATED=$(curl -sS -X POST "$FIBRE_API_URL/v1/webhooks" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d "{\"url\": \"$URL/fibre/webhooks\", \"events\": [\"sandbox.ready\", \"sandbox.stopped\", \"sandbox.crashed\", \"sandbox.deleted\"]}") # store the secret where the receiver reads it echo "$CREATED" | jq -r .secret | curl -sS -o /dev/null -X PUT \ "$FIBRE_API_URL/v1/sandboxes/$RECV/files/content?path=/app/secret" -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- echo "$CREATED" | jq 'del(.secret)' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "url": "…", > "events": ["sandbox.ready", "sandbox.stopped", "sandbox.crashed", "sandbox.deleted"], > "enabled": true, > "created_at": "…" > } > ``` > > The real answer also includes `secret`, which is left out above. **3. Send a test, and cause a real event** A test sends a `ping` event to your endpoint straight away. To see real events as well, start a sandbox and then delete it: that sends `sandbox.ready` and then `sandbox.deleted`. ```typescript title="TypeScript" run theme={null} await fibre.json("POST", `/v1/webhooks/${hook.id}/test`); const worker = await Sandbox.create({ lifetime: 300, labels: { docs: "webhooks" } }); await worker.delete(); await new Promise((r) => setTimeout(r, 5000)); console.log(await receiver.files.read("/app/received.log")); // {"type":"ping","valid":true} // {"type":"sandbox.ready","valid":true} // {"type":"sandbox.deleted","valid":true} ``` ```python title="Python" run theme={null} import time fibre.json("POST", f"/v1/webhooks/{hook['id']}/test") worker = Sandbox.create(lifetime=300, labels={"docs": "webhooks"}) worker.delete() time.sleep(5) print(receiver.files.read("/app/received.log")) # {"type":"ping","valid":true} # {"type":"sandbox.ready","valid":true} # {"type":"sandbox.deleted","valid":true} ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/webhooks/$HOOK/test" -H "Authorization: Bearer $FIBRE_API_KEY" echo W=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" -H "Authorization: Bearer $FIBRE_API_KEY" \ -H "Content-Type: application/json" -d '{"lifetime_sec": 300, "labels": {"docs": "webhooks"}}' | jq -r .id) curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$W" -H "Authorization: Bearer $FIBRE_API_KEY" sleep 5 curl -sS "$FIBRE_API_URL/v1/sandboxes/$RECV/files/content?path=/app/received.log" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Output > > ```text title="output" expected theme={null} > {"type":"sandbox.deleted","valid":true} > ``` **Every delivery arrived, and every signature was valid.** ## Retries Your endpoint must answer with a **`2xx` status within 10 seconds**. Anything else counts as a failure: an error status, no answer in time, or a refused connection. After a failure, Fibre tries again, waiting longer each time: | Attempt | After the previous one | | - | - | | 2 | 30 seconds | | 3 | 2 minutes | | 4 | 10 minutes | | 5 | 1 hour | | 6 | 6 hours | | 7, the last | 24 hours | Every attempt for the same event carries **the same `Fibre-Event-Id`**. Fibre guarantees that each event arrives at least once, but occasionally it may arrive twice, for example if your `200` answer was lost on its way back. So **remember the IDs you have handled, and skip an event you have already processed.** > [!TIP] > > **Answer first, and do the work afterwards.** Save the event and return `200` immediately, then do the slow part > (sending emails, billing, deploying) in a background job. If your handler takes longer than 10 seconds, Fibre treats > it as a failure and sends the event again, even though your handler did its job. ## See what was delivered When something goes wrong, it helps to see what Fibre sent and how your server replied. You can list an endpoint's last 50 deliveries, newest first: ```typescript title="TypeScript" run theme={null} const { deliveries } = await fibre.json<{ deliveries: any[] }>("GET", `/v1/webhooks/${hook.id}/deliveries`); for (const d of deliveries) console.log(d.type, d.status, d.attempts, d.last_status); // sandbox.deleted succeeded 1 200 ``` ```python title="Python" run theme={null} for d in fibre.json("GET", f"/v1/webhooks/{hook['id']}/deliveries")["deliveries"]: print(d["type"], d["status"], d["attempts"], d["last_status"]) # sandbox.deleted succeeded 1 200 ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/webhooks/$HOOK/deliveries" -H "Authorization: Bearer $FIBRE_API_KEY" | jq '.deliveries[0]' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "event_id": "…", > "type": "…", > "status": "succeeded", > "attempts": 1, > "last_status": 200, > "last_error": null, > "next_attempt_at": "…", > "delivered_at": "…", > "created_at": "…" > } > ``` A delivery's `status` is `pending` (waiting for its next attempt), `succeeded`, or `failed` (every attempt has been used). `last_error` says what went wrong, such as `HTTP 500` or a timeout. ## Rotate the secret If you think a secret may have leaked, replace it with a new one. **The old secret keeps working for 24 hours alongside the new one**, so you have time to update your server without missing a single event. During those 24 hours, `Fibre-Signature` carries two `v1=` values, one for each secret, and a match with either one is enough. ```typescript title="TypeScript" run theme={null} const { secret } = await fibre.json<{ secret: string }>("POST", `/v1/webhooks/${hook.id}/rotate`); ``` ```python title="Python" run theme={null} secret = fibre.json("POST", f"/v1/webhooks/{hook['id']}/rotate")["secret"] ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/webhooks/$HOOK/rotate" -H "Authorization: Bearer $FIBRE_API_KEY" | jq 'keys' ``` ## Delete To stop receiving events at an endpoint, delete it: ```typescript title="TypeScript" run theme={null} await fibre.json("DELETE", `/v1/webhooks/${hook.id}`); await receiver.delete(); ``` ```python title="Python" run theme={null} fibre.json("DELETE", f"/v1/webhooks/{hook['id']}") receiver.delete() ``` ```bash title="curl" run theme={null} curl -sS -X DELETE "$FIBRE_API_URL/v1/webhooks/$HOOK" -H "Authorization: Bearer $FIBRE_API_KEY" curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$RECV" -H "Authorization: Bearer $FIBRE_API_KEY" ``` ## Good to know A few limits and rules: | | | | - | - | | Endpoints | Up to 10 per account; each gets every event you picked | | URLs | Public `https://` or `http://` addresses; private and internal addresses are refused | | Timeout | 10 seconds per attempt | | Attempts | 7 over about 31 hours, then the delivery is `failed` | | Order | Not guaranteed: use `created_at` if order matters | ## Related > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > Understand what `sandbox.ready` with `restored`, and `sandbox.stopped`, tell you. > [card] [Images and builds](/setup/images) > > `build.succeeded` tells you an image is ready to run. # Files Source: https://docs.fibre.dev/sandboxes/files Get code and data into a sandbox and results out of it: write, read, list, inspect and delete files over the API, any size, text or binary, without a shell. Almost every job you give a sandbox has the same shape: **you put something in, it runs, and you take something out.** A repository and a prompt go in, and a diff comes out. A spreadsheet goes in, and a report comes out. A test suite goes in, and a test report comes out. The files API is how things move in and out. You send a file's content as the body of the request and name the path in the address. Because of that, it works for **any content, text or binary, up to the size of the sandbox's disk**, and you never have to worry about escaping special characters in a shell command. If the sandbox is asleep, the call wakes it first. These are the five operations: | You want to | TypeScript and Python | HTTP | | - | - | - | | Write a file | `sbx.files.write(path, content)` | `PUT /v1/sandboxes/{id}/files/content?path=` | | Read a file | `sbx.files.read(path)`; for bytes, `readBytes(path)` (`read_bytes` in Python) | `GET /v1/sandboxes/{id}/files/content?path=` | | List a directory | `sbx.files.list(path)` | `GET /v1/sandboxes/{id}/files?path=` | | Inspect one entry | `sbx.files.stat(path)` | `GET /v1/sandboxes/{id}/files/stat?path=` | | Delete | `sbx.files.remove(path)` | `DELETE /v1/sandboxes/{id}/files?path=` | ## In, run, out: a sales report Here is a small but complete round trip. A CSV file of sales and a Python script go into the sandbox. The script adds up the sales per region, and a JSON report comes back out. **1. Start a sandbox** ```bash title="CLI" run theme={null} SBX=$(fibre create --lifetime 10m --label docs=files --json | jq -r .id) ``` ```typescript title="TypeScript" run theme={null} import { NotFoundError, Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ lifetime: 600, labels: { docs: "files" } }); ``` ```python title="Python" run theme={null} from fibre import NotFoundError, Sandbox sbx = Sandbox.create(lifetime=600, labels={"docs": "files"}) ``` ```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": 600, "labels": {"docs": "files"}}' ``` **2. Put the data and the script in** ```bash title="CLI" run theme={null} fibre exec "$SBX" -i -- sh -c 'mkdir -p /work && cat > /work/sales.csv' <<'CSV' region,product,amount north,widget,1200 north,gadget,800 south,widget,450 south,gadget,2300 west,widget,990 CSV fibre exec "$SBX" -i -- sh -c 'cat > /work/report.py' <<'PY' import csv, json, collections totals = collections.Counter() for row in csv.DictReader(open('/work/sales.csv')): totals[row['region']] += int(row['amount']) best = max(totals, key=totals.get) json.dump({'totals': dict(totals), 'best_region': best}, open('/work/report.json', 'w'), indent=2) print('report written') PY ``` ```typescript title="TypeScript" run theme={null} await sbx.files.write("/work/sales.csv", [ "region,product,amount", "north,widget,1200", "north,gadget,800", "south,widget,450", "south,gadget,2300", "west,widget,990", ].join("\n") + "\n"); const written = await sbx.files.write("/work/report.py", [ "import csv, json, collections", "totals = collections.Counter()", "for row in csv.DictReader(open('/work/sales.csv')):", " totals[row['region']] += int(row['amount'])", "best = max(totals, key=totals.get)", "json.dump({'totals': dict(totals), 'best_region': best}, open('/work/report.json', 'w'), indent=2)", "print('report written')", ].join("\n") + "\n"); console.log(written.size, written.sha256); // 317 3f5c… ``` ```python title="Python" run theme={null} sbx.files.write("/work/sales.csv", "\n".join([ "region,product,amount", "north,widget,1200", "north,gadget,800", "south,widget,450", "south,gadget,2300", "west,widget,990", ]) + "\n") written = sbx.files.write("/work/report.py", "\n".join([ "import csv, json, collections", "totals = collections.Counter()", "for row in csv.DictReader(open('/work/sales.csv')):", " totals[row['region']] += int(row['amount'])", "best = max(totals, key=totals.get)", "json.dump({'totals': dict(totals), 'best_region': best}, open('/work/report.json', 'w'), indent=2)", "print('report written')", ]) + "\n") print(written["size"], written["sha256"]) # 317 3f5c… ``` ```bash title="curl" run theme={null} printf 'region,product,amount\nnorth,widget,1200\nnorth,gadget,800\nsouth,widget,450\nsouth,gadget,2300\nwest,widget,990\n' | \ curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/sales.csv" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- cat <<'EOF' | curl -sS -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/report.py" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- import csv, json, collections totals = collections.Counter() for row in csv.DictReader(open('/work/sales.csv')): totals[row['region']] += int(row['amount']) best = max(totals, key=totals.get) json.dump({'totals': dict(totals), 'best_region': best}, open('/work/report.json', 'w'), indent=2) print('report written') EOF ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "path": "/work/report.py", > "size": "…", > "sha256": "…" > } > ``` You do not need to create `/work` first: **missing directories are created for you**. If a file already exists at the path, it is replaced. The answer includes the file's `sha256` checksum, so you can confirm that what arrived is exactly what you sent. **3. Run it** ```bash title="CLI" run theme={null} fibre exec "$SBX" -- python3 /work/report.py # report written ``` ```typescript title="TypeScript" run theme={null} const run = await sbx.run(["python3", "/work/report.py"]); console.log(run.stdout); // report written ``` ```python title="Python" run theme={null} run = sbx.run(["python3", "/work/report.py"]) print(run.stdout) # report written ``` ```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": ["python3", "/work/report.py"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "report written\n" > } > ``` **4. Take the result out** ```bash title="CLI" run theme={null} fibre cp "$SBX:/work/report.json" report.json jq -c '.best_region, .totals' report.json # "south" · {"north":2000,"south":2750,"west":990} ``` ```typescript title="TypeScript" run theme={null} const report = JSON.parse(await sbx.files.read("/work/report.json")); console.log(report.best_region, report.totals); // south { north: 2000, south: 2750, west: 990 } ``` ```python title="Python" run theme={null} import json report = json.loads(sbx.files.read("/work/report.json")) print(report["best_region"], report["totals"]) # south {'north': 2000, 'south': 2750, 'west': 990} ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/report.json" \ -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "totals": { > "north": 2000, > "south": 2750, > "west": 990 > }, > "best_region": "south" > } > ``` With `curl`, add `-o report.json` to save the file to your disk instead of printing it. ## See what is there After an agent or a build has run, you often do not know exactly which files it created. **List the directory to see what is there:** ```bash title="CLI" run theme={null} fibre exec "$SBX" -- ls -l /work ``` ```typescript title="TypeScript" run theme={null} const { entries, truncated } = await sbx.files.list("/work"); for (const e of entries) console.log(e.type, e.size, e.name); // file 101 sales.csv · file 317 report.py · file 111 report.json ``` ```python title="Python" run theme={null} listing = sbx.files.list("/work") for e in listing["entries"]: print(e["type"], e["size"], e["name"]) # file 101 sales.csv · file 317 report.py · file 111 report.json ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/files?path=/work" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "path": "/work", > "entries": "…", > "truncated": false > } > ``` > > Each entry: > > ```json title="entries" theme={null} > [ > { > "name": "link", > "type": "symlink", > "target": "report.json", > "size": 11, > "mode": "0777", > "mtime": 1795223873, > "uid": 0, > "gid": 0 > }, > { > "name": "report.json", > "type": "file", > "size": 111, > "mode": "0644", > "mtime": 1795223873, > "uid": 0, > "gid": 0 > }, > { > "name": "sub", > "type": "dir", > "size": 40, > "mode": "0755", > "mtime": 1795223873, > "uid": 0, > "gid": 0 > } > ] > ``` * **A listing covers one level at a time.** To look inside a subdirectory, list it separately. * **`type` is `file`, `dir` or `symlink`.** A symlink also has a `target`, the path it points to. `mtime` is the time it was last changed, in Unix seconds, and `mode` is its permissions in octal. * **Large directories are cut off at `limit` entries** (10,000 unless you set it). When that happens, `truncated` is `true`. Sometimes you only want to know about a file without downloading it, for example **to check that a large download finished correctly**. Ask for its details and its checksum instead: ```bash title="CLI" run theme={null} fibre exec "$SBX" -- sha256sum /work/report.json ``` ```typescript title="TypeScript" run theme={null} const info = await sbx.files.stat("/work/report.json", { checksum: "sha256" }); console.log(info.size, info.sha256); ``` ```python title="Python" run theme={null} info = sbx.files.stat("/work/report.json", checksum="sha256") print(info["size"], info["sha256"]) ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/files/stat?path=/work/report.json&checksum=sha256" \ -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "name": "report.json", > "type": "file", > "size": "…", > "sha256": "…" > } > ``` ## A whole folder at once A project usually has many files. Rather than sending them one by one, **pack the folder into a single archive, send it, and unpack it inside the sandbox.** That is one request instead of hundreds: ```bash title="CLI" norun reason="copies a folder from your own machine" theme={null} fibre cp ./my-project "$SBX:/work/app" # a whole folder, packed and unpacked for you ``` ```typescript title="TypeScript" norun reason="packs a folder on your own machine" theme={null} import { execFileSync } from "node:child_process"; const archive = execFileSync("tar", ["czf", "-", "-C", "./my-project", "."]); // bytes await sbx.files.write("/work/project.tgz", archive); await sbx.run("mkdir -p /work/app && tar xzf /work/project.tgz -C /work/app && rm /work/project.tgz"); ``` ```python title="Python" norun reason="packs a folder on your own machine" theme={null} import subprocess archive = subprocess.run(["tar", "czf", "-", "-C", "./my-project", "."], capture_output=True, check=True).stdout # bytes sbx.files.write("/work/project.tgz", archive) sbx.run("mkdir -p /work/app && tar xzf /work/project.tgz -C /work/app && rm /work/project.tgz") ``` ```bash title="curl" norun reason="packs a folder on your own machine" theme={null} tar czf - -C ./my-project . | \ curl -sS -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/project.tgz" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- 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", "mkdir -p /work/app && tar xzf /work/project.tgz -C /work/app && rm /work/project.tgz"]}' ``` To bring a whole folder back out, do the same in reverse. Pack it inside the sandbox with `tar czf /tmp/out.tgz -C /work/app .`, then read `/tmp/out.tgz` (with `readBytes` in TypeScript, `read_bytes` in Python, or `-o out.tgz` with `curl`). > [!TIP] > > If your code is in a Git repository, you do not need to upload it at all. Run `git clone` inside the sandbox: it > has `git` installed and can reach the internet. ## Binary files and scripts Files are passed through **byte for byte**, so images, archives, SQLite databases and model weights all arrive unchanged. In the SDKs, `write` accepts either a string or bytes, and `readBytes` (`read_bytes` in Python) gives you bytes back. You can also set a file's permissions while you write it, with `mode`. For example, `755` makes a script executable, so you can run it directly: ```bash title="CLI" run theme={null} printf '#!/bin/sh\necho ran as a program\n' | fibre exec "$SBX" -i -- sh -c 'cat > /work/hello.sh && chmod 755 /work/hello.sh' fibre exec "$SBX" -- /work/hello.sh # ran as a program ``` ```typescript title="TypeScript" run theme={null} await sbx.files.write("/work/hello.sh", "#!/bin/sh\necho ran as a program\n", { mode: "755" }); console.log((await sbx.run("/work/hello.sh")).stdout); // ran as a program ``` ```python title="Python" run theme={null} sbx.files.write("/work/hello.sh", "#!/bin/sh\necho ran as a program\n", mode="755") print(sbx.run("/work/hello.sh").stdout) # ran as a program ``` ```bash title="curl" run theme={null} printf '#!/bin/sh\necho ran as a program\n' | \ curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/hello.sh&mode=755" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["/work/hello.sh"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "ran as a program\n" > } > ``` ## Delete To delete a file, or a directory with everything in it: ```bash title="CLI" run theme={null} fibre exec "$SBX" -- rm -rf /work ``` ```typescript title="TypeScript" run theme={null} await sbx.files.remove("/work", { recursive: true }); ``` ```python title="Python" run theme={null} sbx.files.remove("/work", recursive=True) ``` ```bash title="curl" run theme={null} curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX/files?path=/work&recursive=true" \ -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "deleted": true, > "path": "/work" > } > ``` **Deleting a directory requires `recursive=true`.** Without it, Fibre refuses to delete a directory that still has files in it (`409 directory_not_empty`). This protects you from wiping out a whole tree with a typo. ## When a file is not there Asking for a file that does not exist returns `404` with the code `file_not_found`. In the SDKs, this is a `NotFoundError` that you can catch: ```bash title="CLI" run expect-exit=3 theme={null} fibre cp "$SBX:/work/report.json" report.json # error: … (file_not_found), exit code 3 ``` ```typescript title="TypeScript" run theme={null} try { await sbx.files.read("/work/report.json"); } catch (e) { if (!(e instanceof NotFoundError)) throw e; console.log(e.code); // file_not_found } ``` ```python title="Python" run theme={null} try: sbx.files.read("/work/report.json") except NotFoundError as e: print(e.code) # file_not_found ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/report.json" \ -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "code": "file_not_found", > "error": "…" > } > ``` ## Errors These are the errors the files API can return, and what each one means: | Status | Code | When | | - | - | - | | 400 | `invalid_path` | The path is not absolute, or not valid | | 400 | `file_is_directory` | Reading or writing a directory as if it were a file | | 400 | `file_not_directory` | A part of the path is a file, not a directory | | 400 | `upload_aborted` | The upload ended early; nothing was written | | 403 | `file_permission_denied` | The sandbox's user may not read or write this path | | 404 | `file_not_found` | Nothing at that path | | 409 | `directory_not_empty` | Deleting a directory with files in it, without `recursive=true` | | 413 | `file_too_large` | More than the file may hold | | 507 | `disk_full` | The sandbox's disk is full: delete files, or use a bigger size | ## Good to know A few rules to keep in mind: | | | | - | - | | Paths | **Absolute** (`/work/app.py`), never relative | | Size | Up to the sandbox's free disk: 10 to 80 GB by [size](/get-started/pricing#sizes-and-prices) | | Sleep | Files are kept across sleep and wake, with everything else | | Deleted sandbox | Its files are gone with it: **take results out before you delete** | | Listing | One directory level per call; 10,000 entries unless you set `limit` | ## Clean up ```bash title="CLI" run theme={null} fibre delete "$SBX" rm -f report.json ``` ```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] [Run commands](/sandboxes/running-commands) > > Run the code you just put in, and watch its output live. > [card] [Create and configure](/sandboxes/overview) > > A sandbox's size decides how much disk space it has. # Create and configure Source: https://docs.fibre.dev/sandboxes/overview Start a sandbox for a user, a task or a conversation: pick its size, image and environment, tag it so you can find it again, retry safely, update it and delete it. A sandbox is **one isolated Linux machine for one job**: a user's workspace, an agent's task, a conversation, a test run. You create it when the job starts, tag it with your own IDs, and delete it when the job is done. In between, it sleeps by itself whenever nothing is happening, so **you can keep thousands around and pay only for the ones doing work**. This page follows a sandbox through that life: how to create one, how to find it again later, what you can change while it runs, how to retry safely, and how to delete it. ## Create one The simplest sandbox needs no options at all. You get Fibre's default image (Linux with a shell, Python, Node, git and a browser), ready for you to run commands in: ```bash title="CLI" run theme={null} FIRST=$(fibre create --json | jq -r .id) fibre get "$FIRST" # sbx-… running https://sbx-….fibre.run fibre delete "$FIRST" ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const first = await Sandbox.create(); console.log(first.id, first.status, first.url); // sbx-… running https://sbx-….fibre.run await first.delete(); ``` ```python title="Python" run theme={null} from fibre import Sandbox first = Sandbox.create() print(first.id, first.status, first.url) # sbx-… running https://sbx-….fibre.run first.delete() ``` ```bash title="curl" run capture=FIRST=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d '{}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "runtime": "standard", > "runtime_reason": "default", > "idle_timeout_sec": 300, > "ready": "process", > "labels": {}, > "created_at": "…", > "expires_at": "…", > "hostname": "…", > "url": "…" > } > ``` ```bash title="curl: delete it" run theme={null} curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$FIRST" -H "Authorization: Bearer $FIBRE_API_KEY" ``` **The call waits until the sandbox is running, and then answers.** You do not need to check back to see whether it has started. Keep the `id` from the answer, because every other call refers to the sandbox by it. ## A sandbox for one user's task In a real app you usually set a few things when you create a sandbox: * **Its size**, so it has enough CPU and memory for the work. * **Environment variables**, so the code inside knows its context. * **Labels that tie it to your own records**, such as the user and the task, so you can find it again later. * **When it should sleep, and when it should be deleted.** Here is a workspace for user 42, who is working on a task called `fix-login`: ```bash title="CLI" run theme={null} SBX=$(fibre create \ --size small \ --env APP_ENV=preview --env USER_ID=42 \ --label user=42 --label task=fix-login \ --idle-timeout 2m \ --lifetime 1h \ --json | jq -r .id) fibre exec "$SBX" -- 'echo "$APP_ENV for user $USER_ID"' # preview for user 42 ``` ```typescript title="TypeScript" run theme={null} const sbx = await Sandbox.create({ size: "small", // 2 vCPU, 4 GB: enough for most agents env: { APP_ENV: "preview", USER_ID: "42" }, // visible to every command inside labels: { user: "42", task: "fix-login" }, // yours, to find it again idleTimeout: 120, // sleep after 2 quiet minutes lifetime: 3600, // delete after an hour unless extended }); const who = await sbx.run('echo "$APP_ENV for user $USER_ID"'); console.log(who.stdout); // preview for user 42 ``` ```python title="Python" run theme={null} sbx = Sandbox.create( size="small", # 2 vCPU, 4 GB: enough for most agents env={"APP_ENV": "preview", "USER_ID": "42"}, # visible to every command inside labels={"user": "42", "task": "fix-login"}, # yours, to find it again idle_timeout=120, # sleep after 2 quiet minutes lifetime=3600, # delete after an hour unless extended ) who = sbx.run('echo "$APP_ENV for user $USER_ID"') print(who.stdout) # preview for user 42 ``` ```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 '{ "size": "small", "env_vars": {"APP_ENV": "preview", "USER_ID": "42"}, "labels": {"user": "42", "task": "fix-login"}, "idle_timeout_sec": 120, "lifetime_sec": 3600 }' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "image": "…", > "cpu_cores": 2, > "memory_mb": 4096, > "disk_gb": 10, > "runtime": "standard", > "runtime_reason": "default", > "init": null, > "created_at": "…", > "expires_at": "…", > "idle_timeout_sec": 120, > "ready": "process", > "network": null, > "labels": { > "user": "42", > "task": "fix-login" > }, > "hostname": "…", > "url": "…" > } > ``` ## Every option Every option is optional: leave any of them out to get the default. Where the SDKs use a different name, it is shown in brackets. | Option | Default | What it does | | - | - | - | | `image` | Fibre's default image | The filesystem it starts from: a public image (`python:3.12-slim`), or one you [built](/setup/images) | | `size` | `small` | `xsmall`, `small`, `medium`, `large` or `xlarge`. See [pricing](/get-started/pricing#sizes-and-prices) | | `cpu_cores`, `memory_mb` | | An exact amount instead of a size: 0.25 to 16 cores, 256 MB to 32 GB. Billed as the smallest size that covers both | | `runtime` | `standard` | `standard` or `vm`. Leave it out and Fibre picks from `needs`. See [runtimes](/sandboxes/runtimes) | | `needs` | | What it must be able to do: `docker`, `fuse`, `cgroups`, `loop`, `iptables` (these pick `vm`), `browser`, `desktop` (started for you) | | `init` | | `"systemd"`: the image's systemd runs as the first process (`vm` only) | | `env_vars` (`env`) | | Environment variables for every command in the sandbox | | `entrypoint` | the image's | The command the sandbox runs as its main program | | `exposed_port` (`exposedPort`) | `8000` | The port its `url` serves. See [serve an app](/connect/public-urls) | | `ready` | `process` on the default image, with `init`, or for a desktop; `port` with your own `image` or `entrypoint` | When it counts as running. `process`: as soon as it runs, kept alive for you to run commands in. `port`: once its program answers on `exposed_port` | | `lifetime_sec` (`lifetime`) | none | Seconds until it is deleted automatically: 60 up to 10 years. Without it, the sandbox is kept until you delete it. Change or remove it later | | `idle_timeout_sec` (`idleTimeout`; `idle_timeout` in Python) | `300` | Quiet seconds before it sleeps: up to 86400; **`0` never sleeps** | | `network` | open | `{"allow": ["pypi.org", "*.github.com"]}` to reach only those; `{"block": true}` for no network | | `labels` | | Up to 16 key-value tags of yours | | `snapshot` | | Start as a copy of a [snapshot](/setup/snapshots): a sandbox saved with its memory | > [!NOTE] > > A sandbox started from a snapshot takes its image, size, runtime and environment from that snapshot. When you use > `snapshot`, you can only set `lifetime_sec`, `idle_timeout_sec` and `labels` yourself. ## Find it again Your app needs a way to find a user's sandbox the next time they show up. You could store each sandbox's ID in your own database, but there is a simpler way: **labels**. Because you tagged the sandbox with `user: 42`, you can simply ask Fibre for "the sandboxes of user 42" and get it back, with nothing stored on your side. ```bash title="CLI" run theme={null} fibre list --label user=42 # sbx-… running … user=42,task=fix-login fibre get "$SBX" ``` ```typescript title="TypeScript" run theme={null} for await (const s of Sandbox.list({ labels: { user: "42" } })) { console.log(s.id, s.status, s.labels.task); // sbx-… running fix-login } const same = await Sandbox.get(sbx.id); console.log(same.url, same.expiresAt); ``` ```python title="Python" run theme={null} for s in Sandbox.list(labels={"user": "42"}): print(s.id, s.status, s.labels["task"]) # sbx-… running fix-login same = Sandbox.get(sbx.id) print(same.url, same.expires_at) ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/sandboxes?label.user=42&limit=10" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "sandboxes": [ > { > "id": "…", > "status": "running", > "labels": { > "user": "42", > "task": "fix-login" > } > } > ] > } > ``` A few details about listing: * **Several labels narrow the list.** `?label.user=42&label.task=fix-login` returns only sandboxes that have both. * **Results come newest first, 50 per page** (you can ask for up to 200 with `limit`). When there are more, the answer includes a `next_cursor`. Pass it back as `?cursor=` to get the next page. In the SDKs, `Sandbox.list()` does the paging for you. * **To get one sandbox by its ID**, call `GET /v1/sandboxes/{id}`. This works for sleeping sandboxes too, and it does not wake them: you simply see `"status": "standby"`. Label keys can use lowercase letters, digits, `.`, `_` and `-`, and can be up to 63 characters long. Values can be up to 128 characters. ## Change it while it lives Most settings are fixed once a sandbox is created. Three things can change while it runs: **how long it lives, how quickly it goes to sleep, and its labels.** This is useful, for example, to give a busy user's sandbox more time, or to mark a task as ready for review: ```bash title="CLI" run theme={null} fibre update "$SBX" --lifetime 2h # two more hours, from now fibre update "$SBX" --idle-timeout 10m # sleep after 10 quiet minutes fibre update "$SBX" --label user=42 --label task=fix-login --label state=review ``` ```typescript title="TypeScript" run theme={null} await sbx.update({ lifetime: 7200 }); // two more hours, from now await sbx.update({ idleTimeout: 600 }); // sleep after 10 quiet minutes await sbx.update({ labels: { user: "42", task: "fix-login", state: "review" } }); console.log(sbx.expiresAt, sbx.labels.state); // 2026-… review ``` ```python title="Python" run theme={null} sbx.update(lifetime=7200) # two more hours, from now sbx.update(idle_timeout=600) # sleep after 10 quiet minutes sbx.update(labels={"user": "42", "task": "fix-login", "state": "review"}) print(sbx.expires_at, sbx.labels["state"]) # 2026-… review ``` ```bash title="curl" run theme={null} curl -sS -X PATCH "$FIBRE_API_URL/v1/sandboxes/$SBX" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{ "lifetime_sec": 7200, "idle_timeout_sec": 600, "labels": {"user": "42", "task": "fix-login", "state": "review"} }' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "expires_at": "…", > "idle_timeout_sec": 600, > "labels": { > "user": "42", > "task": "fix-login", > "state": "review" > } > } > ``` > [!WARNING] > > Sending `labels` **replaces the whole set of labels**. To add one label, send it together with the labels you > want to keep, as in the example above. A new lifetime counts **from the moment you set it**, from 60 seconds up to 10 years. To remove it, so the sandbox is kept until you delete it, send `"lifetime_sec": null` (`lifetime: null` in TypeScript, `lifetime=None` in Python, `fibre update --no-lifetime` in the CLI). ## Retry without making two Networks sometimes drop answers. If your request to create a sandbox times out, you cannot tell whether the sandbox was created or not. If you simply try again, you might end up with two sandboxes, and pay for both. The fix is an **idempotency key**: a unique value of your choosing, sent in the `Idempotency-Key` header. If Fibre sees the same key twice, it does not create a second sandbox. It returns the first one instead. This example sends the same request twice with the same key, and gets one sandbox back both times: ```bash title="curl" run theme={null} KEY=$(uuidgen) A=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" -H "Idempotency-Key: $KEY" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d '{"lifetime_sec": 300}' | jq -r .id) B=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" -H "Idempotency-Key: $KEY" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" -d '{"lifetime_sec": 300}' | jq -r .id) [ "$A" = "$B" ] && echo "one sandbox, asked for twice" curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$A" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Output > > ```text title="output" expected theme={null} > one sandbox, asked for twice > ``` * **Use a new key for each sandbox you mean to create.** A random UUID works well. Fibre remembers each key for 24 hours. * **Reusing a key with a different request is refused** (`422 idempotency_key_reused`), so a key can never be mixed up with another create. * **The SDKs do this for you.** Every `Sandbox.create()` sends its own key, so the SDK's automatic retries never create a second sandbox. ## 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} > { > "id": "…", > "deleted": true > } > ``` **Deleting a sandbox is final.** The machine, its files and its saved memory are all removed, and they cannot be recovered. Asking for the sandbox afterwards returns `404 sandbox_not_found`. **Fibre never deletes a sandbox on its own.** One you do not delete is kept, asleep while nothing happens in it, and its storage counts towards your bill, unless you gave it a [lifetime](/sandboxes/sleep-and-wake#lifetime). To clean up everything that belongs to one user, list their sandboxes by label and delete each one: ```bash title="CLI" norun reason="shows the clean-up loop; the page's sandboxes are already deleted" theme={null} fibre delete $(fibre list --label user=42 --json | jq -r '.[].id') ``` ```typescript title="TypeScript" norun reason="shows the clean-up loop; the page's sandboxes are already deleted" theme={null} for await (const s of Sandbox.list({ labels: { user: "42" } })) await s.delete(); ``` ```python title="Python" norun reason="shows the clean-up loop; the page's sandboxes are already deleted" theme={null} for s in Sandbox.list(labels={"user": "42"}): s.delete() ``` > [!TIP] > > If a user might come back, **it is usually better to let the sandbox sleep than to delete it.** A sleeping > sandbox costs nothing for compute and wakes up with everything in place. Delete a sandbox when the user clearly > says they are done, for example by deleting their project, rather than on a timer. ## Errors Every error has a message, a stable `code`, and a `request_id`. | Status | Code | What to do | | - | - | - | | 400 | `validation_failed` | A field is wrong; `details` says which | | 400 | `needs_vm` | A need such as `docker` was asked on `"runtime": "standard"`: drop `runtime`, or use `vm` | | 400 | `init_needs_vm` | `init` needs `"runtime": "vm"` | | 400 | `size_too_large` | More CPU or memory than the largest size | | 400 | `snapshot_fields_fixed` | A copy of a snapshot was given a field it takes from the snapshot | | 402 | `payment_required`, `subscription_required`, `trial_limit` | Billing: add funds, choose a plan, or stay inside the trial's limits | | 403 | `image_not_owned` | The image belongs to another organization | | 404 | `image_not_found`, `snapshot_not_found` | No such image or snapshot | | 404 | `sandbox_not_found` | No sandbox with that ID: deleted, expired, or never yours | | 422 | `idempotency_key_reused` | That key was used with a different request | | 429 | `sandbox_limit` | You keep as many sandboxes as your plan allows, awake or asleep: delete some, or upgrade | | 429 | `org_limit` | Your sandboxes use as much capacity as one account may: stop or delete some | | 503 | `create_failed`, `no_capacity` | Nothing was left behind: **retry** (with the same `Idempotency-Key`) | ## Related > [card] [Run commands](/sandboxes/running-commands) > > Now that it runs, make it do something. > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > What a sandbox keeps while it sleeps. > [card] [Runtimes](/sandboxes/runtimes) > > When you need Docker or a full VM. > [card] [API keys](/get-started/api-keys) > > A key that works on one sandbox only. # Run commands Source: https://docs.fibre.dev/sandboxes/running-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' # … ``` ```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); // … ``` ```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) # … ``` ```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](/sandboxes/files). `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](/sandboxes/sleep-and-wake) 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](/connect/public-urls). ```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](/sandboxes/files) > > Put code and data into a sandbox, and take results out. > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > What keeps a sandbox awake, and what survives a sleep. > [card] [Serve an app](/connect/public-urls) > > Make a kept server reachable at the sandbox's HTTPS address. > [card] [Claude Code in a sandbox](/build-with-ai/claude-code) > > Run a coding agent as a background command. # Runtimes: standard and VM Source: https://docs.fibre.dev/sandboxes/runtimes Two ways a sandbox can run: standard for code, tools and browsers; vm, a full virtual machine with its own kernel, for Docker, systemd and kernel features. Same calls, same price. A **runtime** is the way a sandbox runs underneath. Fibre has two of them, and every sandbox uses one. In practice you rarely choose one by name: **you describe what the sandbox needs to do, and Fibre picks the runtime that can do it.** * **`standard`** is the default. It runs code, scripts, package installs, tests, dev servers and browsers, which covers what most agents and apps need. * **`vm`** is a full virtual machine with **its own Linux kernel**. Some software needs a kernel of its own to work, for example **Docker**, services managed by systemd, mounting filesystems, or firewall rules. For that kind of work, `vm` is the runtime to use. Both runtimes use the same API, sleep and wake in the same way, and **cost the same for each size**. Moving a workload from one to the other is a one-word change. ## Which one do I need? Find what you want to do in the left column. The last column shows what to put in your create request: | You want to | Runtime | Ask for it with | | - | - | - | | Run code, tests, a dev server, a coding agent | `standard` | Nothing: it is the default | | Drive a browser with Playwright or Puppeteer | either | `"needs": ["browser"]` | | **Run Docker or Docker Compose inside** | `vm` | `"needs": ["docker"]` | | Run services under systemd, as on a server | `vm` | `"init": "systemd"` | | Mount FUSE filesystems or loop devices | `vm` | `"needs": ["fuse"]`, `["loop"]` | | Set firewall rules or cgroup limits inside | `vm` | `"needs": ["iptables"]`, `["cgroups"]` | | Give an agent a desktop to see and click | `vm` | `"needs": ["desktop"]` | ## Say what you need The easiest way to get the right runtime is to list what the sandbox needs in `needs`. Fibre then picks the runtime that has it, and the answer tells you which runtime it picked and why: ```bash title="CLI" run theme={null} PROBE=$(fibre create --needs docker --lifetime 5m --label docs=runtimes --json | jq -r .id) fibre get "$PROBE" # runtime: vm (needs:docker) fibre delete "$PROBE" ``` ```typescript title="TypeScript" run theme={null} import { FibreError, Sandbox } from "@fibre-dev/sdk"; const probe = await Sandbox.create({ needs: ["docker"], lifetime: 300, labels: { docs: "runtimes" } }); console.log(probe.runtime, probe.runtimeReason); // vm needs:docker await probe.delete(); ``` ```python title="Python" run theme={null} from fibre import FibreError, Sandbox probe = Sandbox.create(needs=["docker"], lifetime=300, labels={"docs": "runtimes"}) print(probe.runtime, probe.runtime_reason) # vm needs:docker probe.delete() ``` ```bash title="curl" run capture=PROBE=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"needs": ["docker"], "lifetime_sec": 300, "labels": {"docs": "runtimes"}}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "runtime": "vm", > "runtime_reason": "needs:docker" > } > ``` ```bash title="curl: delete it" run theme={null} curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$PROBE" -H "Authorization: Bearer $FIBRE_API_KEY" ``` The `runtime_reason` field explains the choice: | `runtime_reason` | Means | | - | - | | `default` | Nothing asked for a VM: `standard` | | `needs:docker` (or another need) | That need requires a VM | | `requested` | You named the runtime yourself | | `snapshot` | It is a copy of a snapshot, and runs where the snapshot was made | ## Docker inside a sandbox Because a `vm` sandbox has its own kernel, it can run Docker. That means **an agent can build and run containers** just as it would on a laptop: start a database for its tests, build the project's image, or run `docker compose up`. In this example, a sandbox starts from Docker's official image, which runs the Docker daemon. Then it starts Redis in a container and stores and reads a value, to show that everything works. **1. Start a VM sandbox with Docker** ```typescript title="TypeScript" run theme={null} const sbx = await Sandbox.create({ image: "docker:27-dind", needs: ["docker"], entrypoint: ["sh", "-c", "dind dockerd > /var/log/dockerd.log 2>&1"], // the Docker daemon is its main program size: "medium", lifetime: 900, labels: { docs: "runtimes" }, }); console.log(sbx.runtime); // vm ``` ```python title="Python" run theme={null} sbx = Sandbox.create( image="docker:27-dind", needs=["docker"], entrypoint=["sh", "-c", "dind dockerd > /var/log/dockerd.log 2>&1"], # the Docker daemon is its main program size="medium", lifetime=900, labels={"docs": "runtimes"}, ) print(sbx.runtime) # vm ``` ```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 '{ "image": "docker:27-dind", "needs": ["docker"], "entrypoint": ["sh", "-c", "dind dockerd > /var/log/dockerd.log 2>&1"], "size": "medium", "lifetime_sec": 900, "labels": {"docs": "runtimes"} }' ``` **2. Run a container and use it** Downloading a container image can take longer than the 30 seconds an exec allows, so this runs as a [background command](/sandboxes/running-commands) that you wait for. The command first waits until the Docker daemon is ready. ```typescript title="TypeScript" run theme={null} const redis = await sbx.run([ "until docker info > /dev/null 2>&1; do sleep 1; done", // wait for the daemon "docker run -d --name cache redis:7-alpine > /dev/null", "sleep 2", "docker exec cache redis-cli set greeting 'hello from a container'", "docker exec cache redis-cli get greeting", ].join(" && "), { timeout: 300 }); console.log(redis.stdout); // OK \n hello from a container ``` ```python title="Python" run theme={null} redis = sbx.run(" && ".join([ "until docker info > /dev/null 2>&1; do sleep 1; done", # wait for the daemon "docker run -d --name cache redis:7-alpine > /dev/null", "sleep 2", "docker exec cache redis-cli set greeting 'hello from a container'", "docker exec cache redis-cli get greeting", ]), timeout=300) print(redis.stdout) # OK \n hello from a container ``` ```bash title="curl" run capture=CMD=.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", "until docker info > /dev/null 2>&1; do sleep 1; done && docker run -d --name cache redis:7-alpine > /dev/null && sleep 2 && docker exec cache redis-cli set greeting \"hello from a container\" && docker exec cache redis-cli get greeting"]}' ``` ```bash title="curl: its output" run theme={null} 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} > hello from a container > ``` **3. Delete it** ```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" ``` > [!TIP] > > **On `vm`, sleep keeps every process, including your containers.** If a sandbox with a running `docker compose` > stack goes to sleep, the next call finds the whole stack still up, with all its data. ## systemd, like a server On a typical Linux server, **systemd** is the first program that starts, and it starts and supervises all the others. With `"init": "systemd"`, a `vm` sandbox works the same way: the image's systemd runs first, and any services you enable start with the machine and come back after every wake. The result is a sandbox that behaves like a small server. You need an image that includes systemd: ```typescript title="TypeScript" norun reason="needs an image whose first process can be systemd" theme={null} const machine = await Sandbox.create({ image: "", runtime: "vm", init: "systemd" }); ``` ```python title="Python" norun reason="needs an image whose first process can be systemd" theme={null} machine = Sandbox.create(image="", runtime="vm", init="systemd") ``` ```bash title="curl" norun reason="needs an image whose first process can be systemd" theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"image": "", "runtime": "vm", "init": "systemd"}' ``` ## Naming the runtime yourself You can also choose the runtime directly, with `"runtime": "standard"` or `"runtime": "vm"`. If you then ask for something that runtime cannot provide, Fibre refuses the request rather than quietly ignoring the need. This way a sandbox always either has what you asked for, or does not start at all: ```bash title="CLI" run expect-exit=3 theme={null} fibre create --runtime standard --needs docker # error: … (needs_vm), exit code 3 ``` ```typescript title="TypeScript" run theme={null} try { await Sandbox.create({ runtime: "standard", needs: ["docker"] }); } catch (e) { if (!(e instanceof FibreError)) throw e; console.log(e.status, e.code); // 400 needs_vm } ``` ```python title="Python" run theme={null} try: Sandbox.create(runtime="standard", needs=["docker"]) except FibreError as e: print(e.status, e.code) # 400 needs_vm ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"runtime": "standard", "needs": ["docker"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "code": "needs_vm", > "error": "…", > "request_id": "…" > } > ``` ## What differs, and what does not For reference, here is everything that differs between the two runtimes, and everything that stays the same: | | `standard` | `vm` | | - | - | - | | Its own Linux kernel | No | **Yes** | | Docker, systemd, FUSE, loop, iptables, cgroups | No | **Yes** | | Processes after a sleep | The main program and those started with `keep` | **All of them** | | [Snapshots](/setup/snapshots) | Yes | Yes, once its commands have ended | | API, SDK, files, commands | The same | The same | | Sleep, wake, lifetime, labels | The same | The same | | Price per size | The same | The same | ## Errors These errors are about runtimes: | Status | Code | When | | - | - | - | | 400 | `needs_vm` | A need that requires a VM, with `"runtime": "standard"` | | 400 | `init_needs_vm` | `init` without `"runtime": "vm"` | ## Related > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > What each runtime keeps across a sleep. > [card] [Browser](/connect/browser) > > A browser for Playwright, on either runtime. > [card] [Desktop](/connect/desktop) > > A full desktop on a VM. > [card] [Sizes and what is installed](/sandboxes/sizes) > > CPU, memory and disk for each size. # Sizes and what is installed Source: https://docs.fibre.dev/sandboxes/sizes The four sandbox sizes with their CPU, memory, disk and price; what Fibre's default image has installed; how to install more, and how to bring your own image. Before you run your first real workload, two questions come up: **how big should the sandbox be, and what is already installed in it?** This page answers both, and shows how to add anything that is missing. ## Sizes A sandbox's size decides how much CPU, memory and disk it gets. Bigger sizes do heavy work faster, and cost more per hour while they are awake: | Size | vCPU | Memory | Disk | Per awake hour | Good for | | - | - | - | - | - | - | | `xsmall` | 1 | 2 GB | 10 GB | \$0.0075 | An agent framework's tool calls, bots and webhooks, a small code interpreter | | `small` (the default) | 2 | 4 GB | 10 GB | \$0.015 | Scripts, a code interpreter, most single agents | | `medium` | 4 | 8 GB | 20 GB | \$0.030 | A coding agent on a real repo, a dev server, a browser | | `large` | 8 | 16 GB | 40 GB | \$0.060 | Builds, test suites, Docker Compose stacks | | `xlarge` | 16 | 32 GB | 80 GB | \$0.165 | Heavy compiles, data work, many containers | You are billed per second while the sandbox is awake, and nothing for compute while it sleeps. Both runtimes cost the same. To choose a size, pass it when you create the sandbox, then check what you got: ```bash title="CLI" run theme={null} SBX=$(fibre create --size medium --lifetime 10m --label docs=sizes --json | jq -r .id) fibre exec "$SBX" -- 'nproc && free -g && df -h /' # 4 cores, 8 GB of memory, a 20 GB disk ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ size: "medium", lifetime: 600, labels: { docs: "sizes" } }); const cpu = await sbx.run("nproc && free -g | awk '/Mem:/ {print $2 \" GB\"}' && df -h / | awk 'NR==2 {print $2}'"); console.log(cpu.stdout); // 4 · 8 GB · 20G ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(size="medium", lifetime=600, labels={"docs": "sizes"}) cpu = sbx.run("nproc && free -g | awk '/Mem:/ {print $2 \" GB\"}' && df -h / | awk 'NR==2 {print $2}'") print(cpu.stdout) # 4 · 8 GB · 20G ``` ```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 '{"size": "medium", "lifetime_sec": 600, "labels": {"docs": "sizes"}}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "running", > "cpu_cores": 4, > "memory_mb": 8192, > "disk_gb": 20 > } > ``` > [!TIP] > > **Start small and grow if you need to.** Since a sleeping sandbox costs nothing for compute, the size only matters for the > work it does while awake. If you notice an agent's builds running out of memory, create its next sandbox one size > up. ### An exact amount If none of the sizes fits, you can ask for an exact amount instead: `cpu_cores` (from 0.25 to 16) and `memory_mb` (from 256 to 32768). The sandbox is then billed as the smallest size that covers both. For example, 3 cores and 6 GB is billed as `medium`. ## What the default image has If you do not choose an image, the sandbox starts from Fibre's default image. It is Debian Linux, with the tools an agent usually reaches for first already installed: | | | | - | - | | **Languages** | Python 3.11 (`python3`, `python`, `pip`, `venv`), Node.js 22 (`node`, `npm`, `npx`) | | **Tools** | `git`, `curl`, `bash`, and the usual Linux commands | | **Browser** | Chromium, with Playwright and ChromeDriver, ready for [browser automation](/connect/browser) | | **User** | `root`, in `/root`: install anything | | **Network** | Open to the internet unless you [restrict it](/sandboxes/overview#every-option) | You can check the versions yourself with a single command: ```bash title="CLI" run theme={null} fibre exec "$SBX" -- 'python3 --version && node --version && git --version && whoami' ``` ```typescript title="TypeScript" run theme={null} const versions = await sbx.run("python3 --version && node --version && git --version && whoami"); console.log(versions.stdout); // Python 3.11.2 · v22.… · git version 2.… · root ``` ```python title="Python" run theme={null} versions = sbx.run("python3 --version && node --version && git --version && whoami") print(versions.stdout) # Python 3.11.2 · v22.… · git version 2.… · root ``` ```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 --version && node --version && git --version && whoami"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "…", > "stderr": "" > } > ``` ## Install what is missing Inside the sandbox you are the `root` user and the network is open, so you can install anything you need, with the usual tools: `pip` for Python, `npm` for Node and `apt-get` for system packages. **Installs often take longer than the 30 seconds an exec allows**, so run them as [background commands](/sandboxes/running-commands). In the SDKs, `sbx.run()` does that for you: ```bash title="CLI" run theme={null} # Python packages: into a virtual environment fibre exec "$SBX" -- 'python3 -m venv /work/.venv && /work/.venv/bin/pip install -q requests' fibre exec "$SBX" -- /work/.venv/bin/python -c 'import requests; print(requests.__version__)' # Node packages fibre exec "$SBX" -- 'mkdir -p /work/app && cd /work/app && npm init -y > /dev/null && npm install --silent zod' # System packages fibre exec "$SBX" -- 'apt-get update -qq && apt-get install -y -qq jq > /dev/null' fibre exec "$SBX" -- jq --version # jq-1.6 ``` ```typescript title="TypeScript" run theme={null} // Python packages: into a virtual environment await sbx.run("python3 -m venv /work/.venv && /work/.venv/bin/pip install -q requests", { timeout: 300 }); console.log((await sbx.run("/work/.venv/bin/python -c 'import requests; print(requests.__version__)'")).stdout); // Node packages await sbx.run("mkdir -p /work/app && cd /work/app && npm init -y > /dev/null && npm install --silent zod", { timeout: 300 }); // System packages await sbx.run("apt-get update -qq && apt-get install -y -qq jq > /dev/null", { timeout: 300 }); console.log((await sbx.run("jq --version")).stdout); // jq-1.6 ``` ```python title="Python" run theme={null} # Python packages: into a virtual environment sbx.run("python3 -m venv /work/.venv && /work/.venv/bin/pip install -q requests", timeout=300) print(sbx.run("/work/.venv/bin/python -c 'import requests; print(requests.__version__)'").stdout) # Node packages sbx.run("mkdir -p /work/app && cd /work/app && npm init -y > /dev/null && npm install --silent zod", timeout=300) # System packages sbx.run("apt-get update -qq && apt-get install -y -qq jq > /dev/null", timeout=300) print(sbx.run("jq --version").stdout) # jq-1.6 ``` ```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 requests && apt-get update -qq && apt-get install -y -qq jq > /dev/null && jq --version"]}' ``` ```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 2 ``` > [accordion] Output > > ```text title="output" expected theme={null} > jq- > ``` > [!WARNING] > > **Install Python packages into a virtual environment.** On the default image, the system's Python refuses a plain > `pip install` and reports an "externally managed environment". Creating a virtual environment with > `python3 -m venv` takes a second and avoids the problem, as the example above shows. > [!TIP] > > Installing the same things in every new sandbox wastes minutes each time. **Do it once and save the result**, > either as a [snapshot](/setup/snapshots) (new sandboxes start with everything installed and already running) or > as your own [image](/setup/images). ## Bring your own image You are not limited to the default image. Any image from a public registry, such as Docker Hub, can be the starting point for a sandbox. Name it in `image`, and add `"ready": "process"` (explained below): ```bash title="CLI" run theme={null} fibre run --rm --image python:3.12-slim --process-ready --lifetime 5m --label docs=sizes -- python --version # Python 3.12.… fibre delete "$SBX" ``` ```typescript title="TypeScript" run theme={null} const py = await Sandbox.create({ image: "python:3.12-slim", ready: "process", lifetime: 300, labels: { docs: "sizes" } }); console.log((await py.run("python --version")).stdout); // Python 3.12.… await py.delete(); await sbx.delete(); ``` ```python title="Python" run theme={null} py = Sandbox.create(image="python:3.12-slim", ready="process", lifetime=300, labels={"docs": "sizes"}) print(py.run("python --version").stdout) # Python 3.12.… py.delete() sbx.delete() ``` ```bash title="curl" run capture=PY=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"image": "python:3.12-slim", "ready": "process", "lifetime_sec": 300, "labels": {"docs": "sizes"}}' ``` ```bash title="curl: check, then clean up" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$PY/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["python", "--version"]}' curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$PY" -H "Authorization: Bearer $FIBRE_API_KEY" curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0 > } > ``` * **The first sandbox from a new image takes a little longer**, because Fibre has to download the image. Later sandboxes from the same image start quickly. * **`"ready": "process"` tells Fibre the sandbox is ready as soon as it starts**, and Fibre keeps it running so you can run commands in it. That is what you want for a general-purpose image such as `python`, `node` or `ubuntu`. * **The browser features need Chromium**, which the default image includes. A custom image without Chromium can still run code and commands, but not the [browser](/connect/browser). > [!WARNING] > > **Without `"ready": "process"`, Fibre treats your image as a server**: it runs the image's own command and waits > for it to answer on its port (`exposed_port`, 8000 unless you set it). A base image whose command exits at once, > or never listens, fails to start. Use `"ready": "process"` for sandboxes you run commands in, and `exposed_port` > for images that [serve an app](/connect/public-urls). ## Related > [card] [Pricing and limits](/get-started/pricing) > > Plans, storage and a worked monthly cost. > [card] [Runtimes](/sandboxes/runtimes) > > When the workload needs Docker or a full VM. # Sleep, wake and lifetime Source: https://docs.fibre.dev/sandboxes/sleep-and-wake An idle sandbox sleeps with its memory and wakes on the next call, with its programs, data and open files where they were. What is kept, what wakes it, how to tune it, and what it costs. Most of a sandbox's life is spent waiting: for the user's next message, the next pull request, the next test run. **Fibre does not charge you for that waiting.** When nothing has happened in a sandbox for a while, it goes to sleep. When the next call comes, it wakes up **exactly where it was**, with the same running programs, the same data in memory and the same open files. This is different from most machines you may have used. Stopping a server normally throws away everything in memory, and starting it again means booting from scratch. A Fibre sandbox keeps its memory while it sleeps, so waking it is more like opening a laptop lid than switching on a computer. Keeping memory across a sleep changes how you can build: * **There is no slow start to design around.** A dev server that took a long time to start is already running after a wake. An agent's process still holds its conversation. A dataset loaded into memory is still loaded. * **You do not write code to save and restore state.** Nothing needs to be written to disk before a sleep, and nothing needs to be rebuilt after a wake. * **One sandbox per user becomes affordable.** If a thousand users each work ten minutes an hour, you pay for ten minutes an hour each, not for a thousand machines running all the time. ## See it: memory survives a sleep The best way to understand this is to see it. In this example, a small server loads two million rows into memory and counts the requests it receives. We call it, let the sandbox fall asleep, and then call it again. **If memory really survives the sleep, the count carries on from where it was, and the data is not loaded a second time.** **1. Start a sandbox that sleeps after one quiet minute** ```bash title="CLI" run theme={null} SBX=$(fibre create --idle-timeout 1m --lifetime 15m --label docs=sleep --json | jq -r .id) ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ idleTimeout: 60, lifetime: 900, labels: { docs: "sleep" } }); ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(idle_timeout=60, lifetime=900, labels={"docs": "sleep"}) ``` ```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 '{"idle_timeout_sec": 60, "lifetime_sec": 900, "labels": {"docs": "sleep"}}' ``` **2. Run a server that holds data in memory** ```bash title="CLI" run theme={null} fibre exec "$SBX" -i -- sh -c 'mkdir -p /work && cat > /work/server.py' <<'PY' import http.server, json, os, time DATA = list(range(2_000_000)) # loaded once, lives in memory LOADED_AT = time.strftime('%H:%M:%S') hits = 0 class Handler(http.server.BaseHTTPRequestHandler): def do_GET(self): global hits hits += 1 body = json.dumps({'pid': os.getpid(), 'loaded_at': LOADED_AT, 'rows_in_memory': len(DATA), 'hits': hits}) self.send_response(200); self.end_headers(); self.wfile.write(body.encode()) def log_message(self, *args): pass http.server.HTTPServer(('127.0.0.1', 8000), Handler).serve_forever() PY fibre exec "$SBX" --detach --keep -- python3 /work/server.py # wait until it has loaded its data and answers (this is request 1) fibre exec "$SBX" --timeout 60 -- 'until curl -sf -o /dev/null localhost:8000; do sleep 1; done' BEFORE=$(fibre exec "$SBX" -- curl -sf localhost:8000) echo "$BEFORE" # {"pid": 21, "loaded_at": "14:02:11", "rows_in_memory": 2000000, "hits": 2} ``` ```typescript title="TypeScript" run theme={null} await sbx.files.write("/work/server.py", [ "import http.server, json, os, time", "DATA = list(range(2_000_000)) # loaded once, lives in memory", "LOADED_AT = time.strftime('%H:%M:%S')", "hits = 0", "class Handler(http.server.BaseHTTPRequestHandler):", " def do_GET(self):", " global hits", " hits += 1", " body = json.dumps({'pid': os.getpid(), 'loaded_at': LOADED_AT, 'rows_in_memory': len(DATA), 'hits': hits})", " self.send_response(200); self.end_headers(); self.wfile.write(body.encode())", " def log_message(self, *args): pass", "http.server.HTTPServer(('127.0.0.1', 8000), Handler).serve_forever()", ].join("\n") + "\n"); await sbx.spawn(["python3", "/work/server.py"], { keep: true }); // wait until it has loaded its data and answers (this is request 1) await sbx.run("until curl -sf -o /dev/null localhost:8000; do sleep 1; done", { timeout: 60 }); const ask = () => sbx.run("curl -sf localhost:8000").then((r) => JSON.parse(r.stdout)); const before = await ask(); console.log(before); // { pid: 21, loaded_at: '14:02:11', rows_in_memory: 2000000, hits: 2 } ``` ```python title="Python" run theme={null} import json sbx.files.write("/work/server.py", "\n".join([ "import http.server, json, os, time", "DATA = list(range(2_000_000)) # loaded once, lives in memory", "LOADED_AT = time.strftime('%H:%M:%S')", "hits = 0", "class Handler(http.server.BaseHTTPRequestHandler):", " def do_GET(self):", " global hits", " hits += 1", " body = json.dumps({'pid': os.getpid(), 'loaded_at': LOADED_AT, 'rows_in_memory': len(DATA), 'hits': hits})", " self.send_response(200); self.end_headers(); self.wfile.write(body.encode())", " def log_message(self, *args): pass", "http.server.HTTPServer(('127.0.0.1', 8000), Handler).serve_forever()", ]) + "\n") sbx.spawn(["python3", "/work/server.py"], keep=True) # wait until it has loaded its data and answers (this is request 1) sbx.run("until curl -sf -o /dev/null localhost:8000; do sleep 1; done", timeout=60) def ask(): return json.loads(sbx.run("curl -sf localhost:8000").stdout) before = ask() print(before) # {'pid': 21, 'loaded_at': '14:02:11', 'rows_in_memory': 2000000, 'hits': 2} ``` ```bash title="curl" run theme={null} cat <<'EOF' | curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$SBX/files/content?path=/work/server.py" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- import http.server, json, os, time DATA = list(range(2_000_000)) # loaded once, lives in memory LOADED_AT = time.strftime('%H:%M:%S') hits = 0 class Handler(http.server.BaseHTTPRequestHandler): def do_GET(self): global hits hits += 1 body = json.dumps({'pid': os.getpid(), 'loaded_at': LOADED_AT, 'rows_in_memory': len(DATA), 'hits': hits}) self.send_response(200); self.end_headers(); self.wfile.write(body.encode()) def log_message(self, *args): pass http.server.HTTPServer(('127.0.0.1', 8000), Handler).serve_forever() EOF curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/commands" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["python3", "/work/server.py"], "keep": true}' # wait until it has loaded its data and answers (this is request 1) curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["sh", "-c", "until curl -sf -o /dev/null localhost:8000; do sleep 1; done"]}' curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["curl", "-sf", "localhost:8000"]}' | jq -r .stdout ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "pid": "…", > "loaded_at": "…", > "rows_in_memory": 2000000, > "hits": 2 > } > ``` `keep: true` starts the server as a program that keeps running on its own, independently of the call that started it. See [keep a program running](/sandboxes/running-commands#keep-a-program-running). **3. Leave it alone until it sleeps** There is nothing to call here. Because this sandbox was created with a one-minute idle timeout, it goes to sleep on its own after a quiet minute, and its `status` changes from `running` to `standby`. The code below simply watches for that: ```bash title="CLI" run theme={null} until [ "$(fibre get "$SBX" --json | jq -r .status)" = standby ]; do sleep 5; done fibre get "$SBX" --json | jq -r .status # standby ``` ```typescript title="TypeScript" run theme={null} while ((await sbx.refresh()).status !== "standby") await new Promise((resolve) => setTimeout(resolve, 5000)); console.log(sbx.status); // standby ``` ```python title="Python" run theme={null} import time while sbx.refresh().status != "standby": time.sleep(5) print(sbx.status) # standby ``` ```bash title="curl" run theme={null} for i in $(seq 1 40); do status=$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .status) [ "$status" = standby ] && break sleep 5 done echo "$status" ``` > [accordion] Output > > ```text title="output" expected theme={null} > standby > ``` **From this moment on, you are not paying for compute.** **4. Call it again** There is no separate "wake" call. You simply use the sandbox again, and Fibre wakes it before answering: ```bash title="CLI" run theme={null} AFTER=$(fibre exec "$SBX" -- curl -sf localhost:8000) echo "$AFTER" # {"pid": 21, "loaded_at": "14:02:11", "rows_in_memory": 2000000, "hits": 3} [ "$(echo "$AFTER" | jq .pid)" = "$(echo "$BEFORE" | jq .pid)" ] && echo "the same process, with its memory" ``` ```typescript title="TypeScript" run theme={null} const after = await ask(); console.log(after); // { pid: 21, loaded_at: '14:02:11', rows_in_memory: 2000000, hits: 3 } console.log(after.pid === before.pid, after.loaded_at === before.loaded_at); // true true ``` ```python title="Python" run theme={null} after = ask() print(after) # {'pid': 21, 'loaded_at': '14:02:11', 'rows_in_memory': 2000000, 'hits': 3} print(after["pid"] == before["pid"], after["loaded_at"] == before["loaded_at"]) # True True ``` ```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": ["curl", "-sf", "localhost:8000"]}' | jq -r .stdout ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "pid": "…", > "loaded_at": "…", > "rows_in_memory": 2000000, > "hits": 3 > } > ``` **Look at `hits`: it is 3, not 1.** The answer came from the same process (the same `pid`) that loaded its data at the same time (the same `loaded_at`). The server was not restarted: it was resumed, and the two million rows were never loaded again. ## What is kept Here is what a sandbox keeps while it sleeps: | | Across a sleep | | - | - | | **Memory** | Kept: variables, caches, loaded models and datasets | | **Processes** | Kept on `vm`. On `standard`: the sandbox's main program and everything started with `keep` | | **Files** | Kept, including open files and their positions | | **Browser** | Kept: tabs, logins, cookies, the page you were on | | **Its address** | The same `url` and the same `id` | | **Environment** | The same image, variables and labels | | **Connections to other machines** | Not always: see below | > [!NOTE] > > There is one difference between the two [runtimes](/sandboxes/runtimes). On `standard`, a program you started > with a plain exec or command, and which is still running when the sandbox goes to sleep, is **not** there after > the wake. So start anything that should keep running with `keep: true`. On `vm`, every process is kept, and you > do not need to think about it. ### Connections to other services Programs inside the sandbox keep their state across a sleep, but **the services they were talking to do not wait for them**. A database connection, a message queue, or a pool of HTTP connections that was open when the sandbox fell asleep may have been closed by the other side by the time it wakes. The first query on such a connection then fails with an error such as "connection reset" or "server closed the connection". Most client libraries can handle this for you. Turn on the option that checks or retries a connection before using it, for example `pool_pre_ping=True` in SQLAlchemy, a keep-alive or retry option in your HTTP client, or simply reconnect when a call fails with a connection error. Connections that arrive at the sandbox, such as visitors to its `url`, are not affected: each new visitor wakes it and is served. ## When it sleeps A sandbox goes to sleep when nothing has happened in it for its **idle timeout**, which is 300 seconds (5 minutes) unless you choose another value. Fibre counts any of these as "something happening": * **A command or exec is running**, or a shell or terminal is open. * **Its programs are using the CPU.** * **Network traffic is flowing, in either direction.** This matters for agents: an agent waiting for a model's answer has a connection open, so **it is never put to sleep in the middle of a thought**. Only when all of these have been quiet for the whole idle timeout does the sandbox go to sleep. ## What wakes it Any call that needs the sandbox wakes it, with no extra step on your side: | Call | Wakes it | | - | - | | An exec or a new command | Yes | | A files call | Yes | | An HTTP request to its `url` | Yes: the first visitor waits a moment, then gets the page | | Opening its browser or desktop link | Yes | | `GET /v1/sandboxes/{id}` (reading its status) | **No**: you can watch a sleeping sandbox without waking it | The call that wakes a sandbox simply takes a moment longer than usual. If several calls arrive while it is waking, they all wait for that same wake, and nothing is started twice. ## Tune it You decide how quickly a sandbox goes to sleep. Set the idle timeout when you create the sandbox, or change it at any time. Here, setting it to `0` means the sandbox never sleeps: ```bash title="CLI" run theme={null} fibre update "$SBX" --idle-timeout 0 # never sleep ``` ```typescript title="TypeScript" run theme={null} await sbx.update({ idleTimeout: 0 }); // never sleep ``` ```python title="Python" run theme={null} sbx.update(idle_timeout=0) # never sleep ``` ```bash title="curl" run theme={null} curl -sS -X PATCH "$FIBRE_API_URL/v1/sandboxes/$SBX" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"idle_timeout_sec": 0}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "idle_timeout_sec": 0 > } > ``` Which value to choose depends on how the sandbox is used: | `idle_timeout_sec` | Good for | | - | - | | `30` to `120` | Chat and agent turns: sleep quickly between messages, save the most | | `300` (default) | Interactive work: survives a coffee, sleeps over lunch | | `1800` and up | Sessions where even a short wake would be noticed | | `0` | **Always on**: a bot, a queue worker, a server that must answer instantly. Billed for every second | ## Lifetime Sleeping is not the same as being deleted, and neither is time passing: **a sandbox is kept until you delete it**, asleep or awake. Fibre never deletes one on its own. While it exists, its saved state counts towards your [storage](/get-started/pricing#storage). If you want a sandbox to delete itself, give it a **lifetime**: from 60 seconds up to 10 years, when you create it or later. It is deleted when the lifetime ends, whether it is asleep or awake at that moment. Each new lifetime counts from the moment you set it: ```bash title="CLI" run theme={null} fibre update "$SBX" --lifetime 30m # deleted 30 minutes from now ``` ```typescript title="TypeScript" run theme={null} await sbx.update({ lifetime: 1800 }); console.log(sbx.expiresAt); // 30 minutes from now ``` ```python title="Python" run theme={null} sbx.update(lifetime=1800) print(sbx.expires_at) # 30 minutes from now ``` ```bash title="curl" run theme={null} curl -sS -X PATCH "$FIBRE_API_URL/v1/sandboxes/$SBX" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"lifetime_sec": 1800}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "expires_at": "…" > } > ``` To remove the lifetime, so the sandbox is kept until you delete it, send `null`: ```bash title="CLI" run theme={null} fibre update "$SBX" --no-lifetime # kept until you delete it ``` ```typescript title="TypeScript" run theme={null} await sbx.update({ lifetime: null }); console.log(sbx.expiresAt); // null ``` ```python title="Python" run theme={null} sbx.update(lifetime=None) print(sbx.expires_at) # None ``` ```bash title="curl" run theme={null} curl -sS -X PATCH "$FIBRE_API_URL/v1/sandboxes/$SBX" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"lifetime_sec": null}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "expires_at": null > } > ``` > [!TIP] > > A workspace per user needs no lifetime: it sleeps while they are away and is there when they come back. If you > would rather have Fibre delete the workspaces of users who never return, give each one a lifetime and **extend it > each time the user shows up**. ### When it is deleted When you delete it, or when a lifetime you set ends, a sandbox is gone for good: its running programs are stopped, and its files, its memory and its address are deleted. This cannot be undone, and nothing is kept for you to restore. ### Keep work after deleting it A sandbox keeps its work for as long as you keep the sandbox. To keep what it produced after you delete it: * **Copy the results out** before it ends: read the files you need, or pack a folder and download it (see [files](/sandboxes/files)), or push code to its repository from inside the sandbox. * **Save it as a [snapshot](/setup/snapshots)** to start new sandboxes exactly as it is now, memory included. A snapshot outlives the sandbox it came from. ## What it costs | State | Compute | Storage | | - | - | - | | Awake (`running`) | The size's price, **per second** | Not charged separately | | Asleep (`standby`) | **Nothing** | Its saved state counts towards your included 20 GB | | Deleted or expired | Nothing | Nothing | Here is an example. A support agent's sandbox on the `medium` size works for 4 minutes in each hour of an 8-hour day. It is awake for 32 minutes in total, which costs \*\*about $0.016 a day**. If the same sandbox were left awake all day, it would cost $0.72 a day. See [pricing](/get-started/pricing). ## 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] [Run commands](/sandboxes/running-commands) > > Start programs that carry on across sleep with `keep`. > [card] [Runtimes](/sandboxes/runtimes) > > On `vm`, every process survives a sleep, not only the kept ones. > [card] [Serve an app](/connect/public-urls) > > A site that sleeps when nobody visits and wakes on the next request. > [card] [Pricing and limits](/get-started/pricing) > > What awake time costs at each size. # CLI Source: https://docs.fibre.dev/sdks/cli Use Fibre from your terminal: install one program, sign in, start sandboxes, run commands with their output live, open a shell, and copy files in and out. Every command also speaks JSON for scripts and agents. The Fibre CLI is a single program called `fibre`. It lets you do from your terminal everything you would otherwise do with the API or an SDK: start a sandbox, run commands in it and watch their output, open an interactive shell, copy files and folders in and out, and clean up afterwards. It is just as useful in scripts and CI, and for coding agents, because every command can print its result as JSON. ## Install The CLI is a standalone program, so you do not need Node.js or anything else installed. Run the command for your system: ```bash title="macOS and Linux" norun reason="installs on your own machine" theme={null} curl -fsSL https://fibre.dev/install.sh | sh ``` ```powershell title="Windows" norun reason="installs on your own machine" theme={null} irm https://fibre.dev/install.ps1 | iex ``` ```bash title="npm" norun reason="installs on your own machine" theme={null} npm install -g @fibre-dev/cli ``` The install scripts download the right program for your system and **check its SHA-256 checksum** before installing it, so a damaged or altered download is never installed. Check that it works: ```bash title="Terminal" run theme={null} fibre --version ``` > [accordion] Output > > ```text title="output" expected theme={null} > 0.1.0 > ``` ## Sign in The CLI needs an API key, just like the SDKs. Run `fibre login`, create a key in the dashboard under **API keys**, and paste it when asked. The CLI checks the key with Fibre and saves it for the next commands, in a file only you can read. ```bash title="Terminal" norun reason="asks for your own key" theme={null} fibre login ``` In CI and scripts, there is nothing to save: set the `FIBRE_API_KEY` environment variable and every command uses it. `fibre whoami` shows which key and account the CLI is using. ## Start a sandbox and work in it `fibre create` starts a sandbox and prints its details. It accepts the same options as the API, written as flags: `--size`, `--image`, `--label`, `--lifetime`, `--idle-timeout` and more. Here we ask for JSON, so a script can read the ID: ```bash title="Terminal" run capture=SBX=.id theme={null} fibre create --label project=docs --lifetime 20m --json ``` > [accordion] Output > > ```json title="output" expected theme={null} > { > "id": "…", > "status": "running", > "runtime": "standard", > "labels": { > "project": "docs" > } > } > ``` **`fibre exec` runs a command in the sandbox as if it ran on your machine.** Its output appears in your terminal as it is written, and `fibre exec` exits with the command's own exit code, so it works in scripts and in `&&` chains. Put the command after `--`: ```bash title="Terminal" run theme={null} fibre exec "$SBX" -- python3 -c "import platform; print('hello from', platform.system())" ``` > [accordion] Output > > ```text title="output" expected theme={null} > hello from Linux > ``` A few more things you can do with a running sandbox: | You want to | Command | | - | - | | Open an interactive shell | `fibre shell ` | | Pass your input to a command | `cat data.csv \| fibre exec -i -- python3 load.py` | | Run something in the background | `fibre exec --detach -- npm run build`, then `fibre logs -f` | | Keep a server running, even across sleep | `fibre exec --detach --keep -- node server.js` | | See its public address, or open it | `fibre url `, `fibre open ` | ## Copy files in and out `fibre cp` copies a file or a whole folder. Write the sandbox side as `:/path`: ```bash title="Terminal" run theme={null} mkdir -p demo && echo "print('copied in')" > demo/main.py fibre cp demo "$SBX:/work/demo" fibre exec "$SBX" -- python3 /work/demo/main.py ``` > [accordion] Output > > ```text title="output" expected theme={null} > copied in > ``` Copying out works the same way, with the sandbox first: `fibre cp :/work/report.json .` ## Run one command in a fresh sandbox When you only need a sandbox for one command, `fibre run` does it all: it starts a sandbox, runs the command with its output live, and exits with the command's exit code. With `--rm`, it deletes the sandbox afterwards. ```bash title="Terminal" run theme={null} fibre run --rm -- python3 -c "print(sum(range(101)))" ``` > [accordion] Output > > ```text title="output" expected theme={null} > 5050 > ``` ## Clean up ```bash title="Terminal" run theme={null} fibre delete "$SBX" rm -rf demo ``` ## For scripts and agents Three things make the CLI easy to use from code: * **`--json` works on every command.** The result is printed as JSON, and so are errors, under `"error"`. * **Exit codes are stable:** `0` success, `1` a failure, `2` a usage error, `3` an API error, `4` not signed in or a rejected key. `fibre run` and `fibre exec` exit with the command's own code. * **There is no colour or animation** when the output is not a terminal, or when `NO_COLOR` is set. To let a coding agent use sandboxes through tools instead of commands, add Fibre's MCP server to it: see [MCP server and skill](/build-with-ai/mcp-server). ## All commands | Command | What it does | | - | - | | `fibre login`, `logout`, `whoami` | Sign in with an API key, sign out, show the account in use | | `fibre create` | Start a sandbox | | `fibre list`, `get`, `update`, `delete` | Find, inspect, change and delete sandboxes | | `fibre run -- ` | Start a sandbox and run one command in it | | `fibre exec -- ` | Run a command in a sandbox | | `fibre shell ` | Open an interactive shell | | `fibre cp ` | Copy files and folders in and out | | `fibre commands`, `logs`, `kill` | Background commands: list them, read their output, stop them | | `fibre url`, `open`, `browser`, `desktop` | Addresses and links | | `fibre snapshot create`, `list`, `delete` | Snapshots | | `fibre secret set`, `list`, `delete` | Secrets; give one to a command with `fibre exec --secret NAME` | | `fibre key create`, `list`, `revoke` | API keys | | `fibre usage` | Your spending and your plan's limits | | `fibre mcp add `, `mcp config` | Give a coding agent Fibre's tools: see [MCP server and skill](/build-with-ai/mcp-server) | | `fibre skill install` | Install the Fibre skill for your coding agents | `fibre --help` describes every option. # SDKs Source: https://docs.fibre.dev/sdks/overview Official Fibre clients: the TypeScript and Python SDKs and the CLI. Each wraps the HTTP API with typed calls, streaming, retries and errors you can catch. An **SDK** (software development kit) is a library for your programming language that makes the [HTTP API](/api-reference/introduction) easier to use. Instead of building HTTP requests by hand, you work with sandboxes as objects: you create one, run commands in it, stream their output, and read its files. The SDKs also take care of the details for you: they send your API key, retry failed requests safely, handle streaming output, and turn errors into exceptions you can catch. If the SDK does not have a method for something yet, you can still make that call through its built-in HTTP client. These are the ways to use Fibre today: > [card] [TypeScript](/sdks/typescript) > > `@fibre-dev/sdk`, for Node 20+, Bun and Deno. **Available now.** > [card] [Python](/sdks/python) > > `fibre-sdk`, for Python 3.11+, with sync and `asyncio` clients. **Available now.** > [card] [CLI](/sdks/cli) > > `fibre` on your terminal: start sandboxes, run commands, open a shell. **Available now.** > [card] [HTTP API](/api-reference/introduction) > > Any language, with `curl` or your HTTP client. Every page of these docs shows it. > [card] [MCP server](/build-with-ai/mcp-server) > > Part of the CLI: give Claude Code, Codex, Cursor or OpenCode tools to create sandboxes and run code in them. ## The same thing in each Here is the same small program, which starts a sandbox, runs a command and deletes the sandbox, with the TypeScript SDK, the Python SDK and plain HTTP: ```bash title="CLI" run theme={null} fibre run --rm --lifetime 5m -- 'echo hello from $(hostname)' ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ lifetime: 300 }); const { stdout } = await sbx.run("echo hello from $(hostname)"); console.log(stdout); await sbx.delete(); ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(lifetime=300) print(sbx.run("echo hello from $(hostname)").stdout) sbx.delete() ``` ```bash title="curl" run theme={null} SBX=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" -H "Authorization: Bearer $FIBRE_API_KEY" \ -H "Content-Type: application/json" -d '{"lifetime_sec": 300}' | jq -r .id) 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 $(hostname)"]}' curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "…" > } > ``` Every client reads your API key from the `FIBRE_API_KEY` environment variable. See [API keys](/get-started/api-keys) to create one. # Python SDK Source: https://docs.fibre.dev/sdks/python Install the Python SDK and use it by task: create sandboxes, run and stream commands, move files, serve apps, use snapshots and browsers, work with asyncio, handle errors, and make any API call. The Python SDK, `fibre-sdk`, lets you work with sandboxes as objects in your code. It reads your API key from the environment, gives you command output as it is written, retries temporary failures safely, and turns errors into typed exceptions. It runs on **Python 3.11 or later**, has a regular API and an `asyncio` one with the same methods, and depends only on `httpx2`. This page is organised by task. Each section shows a short example and links to the guide that explains the feature in depth. At the end you will find a table of every method. ## Install and configure Add the SDK to your project and make your API key available: ```bash title="Terminal" norun reason="installs into your own project" theme={null} pip install fibre-sdk export FIBRE_API_KEY="fb_live_…" ``` The package is called `fibre-sdk`, and you import it as `fibre`. For most programs, that is all the setup needed. Calls such as `Sandbox.create()` automatically use a client built from `FIBRE_API_KEY` (and from `FIBRE_API_URL`, which defaults to `https://api.fibre.dev`). If you need different settings, for example a different key, create a `Fibre` client yourself and pass it as `client=`: ```python title="Python" norun reason="shows the client options" theme={null} import os from fibre import Fibre, Sandbox fibre = Fibre( api_key=os.environ["MY_KEY"], # FIBRE_API_KEY by default timeout=60, # seconds per request (streams are not limited) max_retries=2, # on dropped connections, 429, 502, 503, 504 ) sbx = Sandbox.create(size="small", client=fibre) ``` ## Create, run, delete The basic flow is to create a sandbox, run something in it and read the result: ```python title="Python" run theme={null} from fibre import Fibre, NotFoundError, Sandbox, Secret, Snapshot sbx = Sandbox.create(size="small", lifetime=900, idle_timeout=120, labels={"docs": "sdk", "user": "42"}) r = sbx.run("python3 -c 'print(2 ** 10)'") print(r.exit_code, r.stdout) # 0 1024 ``` * **A command can be a string or a list.** A string runs through the shell (`sh -c`), so pipes and `&&` work. A list is the program followed by its arguments. * **`run()` waits for the command to finish**, with no time limit unless you pass `timeout=`. A non-zero exit code is returned as a result, not raised as an error. * **`cwd` and `env`** set the directory and the environment variables for that one command. * **Durations are in seconds** everywhere: `lifetime`, `idle_timeout`, `timeout`. When a sandbox is only needed for a block of code, use it in a `with` statement and it is deleted at the end, even if the code raises: ```python title="Python" run theme={null} with Sandbox.create(lifetime=300, labels={"docs": "sdk"}) as scratch: print(scratch.run("uname -s").stdout) # Linux ``` Read more in [create and configure](/sandboxes/overview). ## Stream output as it happens For longer commands, `spawn()` starts the command in the background and returns straight away. You can then read its output with `output()`, piece by piece, as the command writes it: ```python title="Python" run theme={null} build = sbx.spawn("for i in 1 2 3; do echo step $i; sleep 1; done") for chunk in build.output(): print(chunk.data, end="") # step 1 … step 2 … step 3 done = build.wait() print(done.exit_code) # 0 ``` `chunk.stream` tells you whether a piece came from `stdout` or `stderr`. `chunk.data` is text, and `chunk.raw` holds the exact bytes, for programs that write binary output. If the connection drops, `output()` reconnects and continues from where it left off. ## Run a server in the background A server should keep running after the call that started it, and through sleep and wake. Start it with `keep=True`: ```python title="Python" run theme={null} server = sbx.spawn(["python3", "-m", "http.server", "8000"], keep=True) print(server.status, server.pid) # detached 23 server.kill() ``` ## Write to a program's input Start a command with `stdin=True` to send it input while it runs: ```python title="Python" run theme={null} py = sbx.spawn(["python3", "-u", "-i", "-q"], stdin=True) py.write("print(sum(range(100)))\n") py.close_stdin() print(py.wait().stdout) # 4950 ``` Read more in [run commands](/sandboxes/running-commands). ## Files Every sandbox has a `files` property for reading and writing its files directly: ```python title="Python" run theme={null} import json sbx.files.write("/work/data.json", json.dumps({"hello": "world"})) print(json.loads(sbx.files.read("/work/data.json"))) # {'hello': 'world'} print([e["name"] for e in sbx.files.list("/work")["entries"]]) # ['data.json'] data = sbx.files.read_bytes("/work/data.json") # bytes, for binary files sbx.files.remove("/work", recursive=True) ``` `write()` accepts text or bytes. Read more in [files](/sandboxes/files). ## Find sandboxes again List sandboxes by their labels, get one by its ID, and change what can change: ```python title="Python" run theme={null} for s in Sandbox.list(labels={"user": "42"}): print(s.id, s.status) same = Sandbox.get(sbx.id) same.update(lifetime=1800, labels={"docs": "sdk", "user": "42", "state": "active"}) print(same.expires_at, same.labels["state"]) # 2026-… active ``` ## Serve an app Create the sandbox with `exposed_port`, start a server on that port, and it is available at the sandbox's `url`: ```python title="Python" norun reason="the public URLs page runs the same calls" theme={null} app = Sandbox.create(exposed_port=3000) app.spawn(["node", "server.js"], keep=True) print(app.url) # https://sbx-….fibre.run: open it anywhere ``` Read more in [public URLs](/connect/public-urls). ## Snapshots Take a snapshot of a prepared sandbox, its whole state with memory, so new ones start ready: ```python title="Python" norun reason="the snapshots page runs the same calls" theme={null} snapshot = prepared.snapshot(name="my-stack") # new sandboxes start running, where it was copy = Sandbox.create(snapshot="my-stack") for s in Snapshot.list(): print(s.name, s.size_bytes, s.monthly_cost_usd) Snapshot.get("my-stack").delete() ``` Read more in [snapshots](/setup/snapshots), including [what they cost](/setup/snapshots#what-it-costs). ## Browser and desktop Get links to a sandbox's browser, or to its desktop: ```python title="Python" norun reason="the browser and desktop pages run the same calls" theme={null} links = sbx.browser() # connect Playwright to links.cdp_url sbx.close_browser() desk = Sandbox.create(needs=["desktop"]) link = desk.desktop() # link.url: a single-use link to watch and use it ``` Read more in [browser](/connect/browser) and [desktop](/connect/desktop). ## Secrets Store a secret once, then give it to the one command that needs it, by name. Inside the sandbox it is an environment variable; its value is never returned by the API: ```python title="Python" norun reason="the secrets page runs the same calls" theme={null} import os Secret.set("OPENAI_API_KEY", os.environ["OPENAI_API_KEY"]) sbx.run("python3 agent.py", secrets=["OPENAI_API_KEY"]) # this command only agent = Sandbox.create(secrets=["OPENAI_API_KEY"]) # every command in it ``` Read more in [secrets](/production/secrets). ## asyncio `AsyncSandbox` has the same methods as `Sandbox`, for code that uses `asyncio`: you `await` the calls, read output with `async for`, and use `async with` to delete a sandbox at the end. It is the natural way to run many sandboxes at the same time: ```python title="Python" run theme={null} import asyncio from fibre import AsyncSandbox async def square(n: int) -> str: async with await AsyncSandbox.create(lifetime=300, labels={"docs": "sdk"}) as one: r = await one.run(["python3", "-c", f"print({n} ** 2)"]) return r.stdout.strip() async def main() -> None: print(await asyncio.gather(*(square(n) for n in range(1, 4)))) # ['1', '4', '9'] asyncio.run(main()) ``` The async classes are `AsyncSandbox`, `AsyncCommand`, `AsyncFiles`, `AsyncSnapshot`, `AsyncSecret` and `AsyncFibre`. ## Errors When a call fails, the SDK raises a `FibreError` with `status`, `code`, `request_id` and `docs_url`. Each kind of error has its own class, so you can catch exactly the ones you expect: ```python title="Python" run theme={null} sbx.delete() try: Sandbox.get(sbx.id) except NotFoundError as e: print(e.status, e.code) # 404 sandbox_not_found ``` | Class | When | | - | - | | `ValidationError` | 400, 422: the request is wrong | | `AuthenticationError` | 401: no key, or a bad one | | `PaymentRequiredError` | 402: billing | | `PermissionDeniedError` | 403: the key may not do this | | `NotFoundError` | 404 | | `ConflictError` | 409: the state does not allow it | | `RateLimitError` | 429, with `retry_after` | | `ServerError` | 5xx | | `FibreConnectionError`, `FibreTimeoutError` | No answer, or a command past its `timeout` | The last two have `Fibre` in their names so that they do not hide Python's own `ConnectionError` and `TimeoutError`. Read more in [errors, retries and limits](/production/errors-and-limits). ## Any API call If the SDK does not have a method for a call yet, use the client's `json()` method. It still sends your key, retries temporary failures and raises typed errors: ```python title="Python" run theme={null} fibre = Fibre() pricing = fibre.json("GET", "/v1/pricing") print(pricing["sizes"]["medium"]["per_hour"]) # 0.03 ``` Pass the body as `json=`, the query as `params=` and raw bytes as `content=`. `fibre.request()` gives you the raw response, and `fibre.stream()` one you read as it arrives. ## Methods For reference, here is every class and method in the SDK: | `Sandbox` | Does | | - | - | | `Sandbox.create(**options)` | Start a sandbox; returns when it runs | | `Sandbox.get(id)` | One sandbox by ID | | `Sandbox.list(labels=…)` | Iterate over sandboxes, newest first, paging for you | | `sbx.run(cmd, cwd=…, env=…, secrets=…, timeout=…)` | Run and wait; returns `exit_code`, `stdout`, `stderr` | | `sbx.spawn(cmd, cwd=…, env=…, secrets=…, keep=…, stdin=…, timeout_sec=…)` | Start in the background; returns a `Command` | | `sbx.command(id)`, `sbx.commands()` | Find commands again | | `sbx.files` | `write`, `read`, `read_bytes`, `list`, `stat`, `remove` | | `sbx.update(lifetime=…, idle_timeout=…, labels=…)` | Change what can change; `lifetime=None` removes the lifetime | | `sbx.refresh()` | Re-read its status | | `sbx.snapshot(name=…)` | Take a snapshot: its whole state, with memory | | `sbx.browser(ttl=…)`, `sbx.close_browser()` | Links to its browser; close it | | `sbx.desktop()` | A link to its desktop | | `sbx.delete()`, `with Sandbox.create() as sbx:` | Delete it | | Properties | `id`, `status`, `runtime`, `runtime_reason`, `url`, `hostname`, `labels`, `secrets`, `expires_at`, `idle_timeout`, `data` | | `Command` | Does | | - | - | | `output(follow=…)` | Its output as it is written (an iterator of chunks with `stream`, `data` and `raw`) | | `wait(timeout=…)` | Wait for the end; returns `exit_code`, `status`, `stdout`, `stderr` | | `write(data)`, `close_stdin()` | Feed its standard input | | `kill(signal=…, grace=…)` | Stop it: `TERM`, then `KILL` after `grace` seconds | | `refresh()` | Re-read its status | | Properties | `id`, `status`, `exit_code`, `pid`, `log` | | `Snapshot` | Does | | - | - | | `Snapshot.get(name)`, `Snapshot.list()` | Find snapshots | | `snapshot.delete()` | Delete one (after the sandboxes started from it) | | Properties | `name`, `source` (the sandbox it was taken of), `size_bytes`, `monthly_cost_usd`, `created_at` | | `Secret` | Does | | - | - | | `Secret.set(name, value)` | Store a secret, or replace its value | | `Secret.get(name)`, `Secret.list()` | Find secrets (never their values) | | `secret.delete()` | Delete one | | Properties | `name`, `version`, `created_at`, `updated_at` | | `Fibre` | Does | | - | - | | `Fibre(api_key=…, base_url=…, timeout=…, max_retries=…)` | A configured client | | `fibre.json(method, path, json=…, params=…, headers=…)` | Any API call, JSON in and out | # TypeScript SDK Source: https://docs.fibre.dev/sdks/typescript Install the TypeScript SDK and use it by task: create sandboxes, run and stream commands, move files, serve apps, use snapshots and browsers, handle errors, and make any API call. The TypeScript SDK, `@fibre-dev/sdk`, lets you work with sandboxes as objects in your code. It reads your API key from the environment, gives you command output as it is written, retries temporary failures safely, and turns errors into typed exceptions. It runs on **Node 20 or later, Bun and Deno**, and has no dependencies. This page is organised by task. Each section shows a short example and links to the guide that explains the feature in depth. At the end you will find a table of every method. ## Install and configure Add the SDK to your project and make your API key available: ```bash title="Terminal" norun reason="installs into your own project" theme={null} npm install @fibre-dev/sdk export FIBRE_API_KEY="fb_live_…" ``` For most programs, that is all the setup needed. Calls such as `Sandbox.create()` automatically use a client built from `FIBRE_API_KEY` (and from `FIBRE_API_URL`, which defaults to `https://api.fibre.dev`). If you need different settings, for example a different key, create a `Fibre` client yourself and pass it as the last argument: ```typescript title="TypeScript" norun reason="shows the client options" theme={null} import { Fibre, Sandbox } from "@fibre-dev/sdk"; const fibre = new Fibre({ apiKey: process.env.MY_KEY, // FIBRE_API_KEY by default timeout: 60, // seconds per request (streams are not limited) maxRetries: 2, // on dropped connections, 429, 502, 503, 504 }); const sbx = await Sandbox.create({ size: "small" }, fibre); ``` ## Create, run, delete The basic flow is to create a sandbox, run something in it and read the result: ```typescript title="TypeScript" run theme={null} import { Fibre, NotFoundError, Sandbox, Secret, Snapshot } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ size: "small", lifetime: 900, idleTimeout: 120, labels: { docs: "sdk", user: "42" }, }); const r = await sbx.run("python3 -c 'print(2 ** 10)'"); console.log(r.exitCode, r.stdout); // 0 1024 ``` * **A command can be a string or an array.** A string runs through the shell (`sh -c`), so pipes and `&&` work. An array is the program followed by its arguments. * **`run()` waits for the command to finish**, with no time limit unless you pass `{ timeout }`. A non-zero exit code is returned as a result, not thrown as an error. * **`cwd` and `env`** set the directory and the environment variables for that one command. Read more in [create and configure](/sandboxes/overview). ## Stream output as it happens For longer commands, `spawn()` starts the command in the background and returns straight away. You can then read its output with `output()`, piece by piece, as the command writes it: ```typescript title="TypeScript" run theme={null} const build = await sbx.spawn("for i in 1 2 3; do echo step $i; sleep 1; done"); for await (const chunk of build.output()) process.stdout.write(chunk.data); // step 1 … step 2 … step 3 const done = await build.wait(); console.log(done.exitCode); // 0 ``` `chunk.stream` tells you whether a piece came from `stdout` or `stderr`. If the connection drops, `output()` reconnects and continues from where it left off. ## Run a server in the background A server should keep running after the call that started it, and through sleep and wake. Start it with `keep: true`: ```typescript title="TypeScript" run theme={null} const server = await sbx.spawn(["python3", "-m", "http.server", "8000"], { keep: true }); console.log(server.status, server.pid); // detached 23 await server.kill(); ``` ## Write to a program's input Start a command with `stdin: true` to send it input while it runs: ```typescript title="TypeScript" run theme={null} const py = await sbx.spawn(["python3", "-u", "-i", "-q"], { stdin: true }); await py.write("print(sum(range(100)))\n"); await py.closeStdin(); console.log((await py.wait()).stdout); // 4950 ``` Read more in [run commands](/sandboxes/running-commands). ## Files Every sandbox has a `files` property for reading and writing its files directly: ```typescript title="TypeScript" run theme={null} await sbx.files.write("/work/data.json", JSON.stringify({ hello: "world" })); console.log(JSON.parse(await sbx.files.read("/work/data.json"))); // { hello: 'world' } const { entries } = await sbx.files.list("/work"); console.log(entries.map((e) => e.name)); // [ 'data.json' ] const bytes = await sbx.files.readBytes("/work/data.json"); // Uint8Array, for binary files await sbx.files.remove("/work", { recursive: true }); ``` Read more in [files](/sandboxes/files). ## Find sandboxes again List sandboxes by their labels, get one by its ID, and change what can change: ```typescript title="TypeScript" run theme={null} for await (const s of Sandbox.list({ labels: { user: "42" } })) console.log(s.id, s.status); const same = await Sandbox.get(sbx.id); await same.update({ lifetime: 1800, labels: { docs: "sdk", user: "42", state: "active" } }); console.log(same.expiresAt, same.labels.state); // 2026-… active ``` ## Serve an app Create the sandbox with `exposedPort`, start a server on that port, and it is available at the sandbox's `url`: ```typescript title="TypeScript" norun reason="the public URLs page runs the same calls" theme={null} const app = await Sandbox.create({ exposedPort: 3000 }); await app.spawn(["node", "server.js"], { keep: true }); console.log(app.url); // https://sbx-….fibre.run: open it anywhere ``` Read more in [public URLs](/connect/public-urls). ## Snapshots Take a snapshot of a prepared sandbox, its whole state with memory, so new ones start ready: ```typescript title="TypeScript" norun reason="the snapshots page runs the same calls" theme={null} const snapshot = await prepared.snapshot({ name: "my-stack" }); // new sandboxes start running, where it was const copy = await Sandbox.create({ snapshot: "my-stack" }); for (const s of await Snapshot.list()) console.log(s.name, s.sizeBytes, s.monthlyCostUsd); await (await Snapshot.get("my-stack")).delete(); ``` Read more in [snapshots](/setup/snapshots), including [what they cost](/setup/snapshots#what-it-costs). ## Browser and desktop Get links to a sandbox's browser, or to its desktop: ```typescript title="TypeScript" norun reason="the browser and desktop pages run the same calls" theme={null} const { cdpUrl, liveViewUrl } = await sbx.browser(); // connect Playwright to cdpUrl await sbx.closeBrowser(); const desk = await Sandbox.create({ needs: ["desktop"] }); const { url } = await desk.desktop(); // a single-use link to watch and use it ``` Read more in [browser](/connect/browser) and [desktop](/connect/desktop). ## Secrets Store a secret once, then give it to the one command that needs it, by name. Inside the sandbox it is an environment variable; its value is never returned by the API: ```typescript title="TypeScript" norun reason="the secrets page runs the same calls" theme={null} await Secret.set("OPENAI_API_KEY", process.env.OPENAI_API_KEY!); await sbx.run("python3 agent.py", { secrets: ["OPENAI_API_KEY"] }); // this command only const agent = await Sandbox.create({ secrets: ["OPENAI_API_KEY"] }); // every command in it ``` Read more in [secrets](/production/secrets). ## Errors When a call fails, the SDK throws a `FibreError` with `status`, `code`, `requestId` and `docsUrl`. Each kind of error has its own class, so you can catch exactly the ones you expect: ```typescript title="TypeScript" run theme={null} await sbx.delete(); try { await Sandbox.get(sbx.id); } catch (e) { if (!(e instanceof NotFoundError)) throw e; console.log(e.status, e.code); // 404 sandbox_not_found } ``` | Class | When | | - | - | | `ValidationError` | 400, 422: the request is wrong | | `AuthenticationError` | 401: no key, or a bad one | | `PaymentRequiredError` | 402: billing | | `PermissionDeniedError` | 403: the key may not do this | | `NotFoundError` | 404 | | `ConflictError` | 409: the state does not allow it | | `RateLimitError` | 429, with `retryAfter` | | `ServerError` | 5xx | | `ConnectionError`, `TimeoutError` | No answer | Read more in [errors, retries and limits](/production/errors-and-limits). ## Any API call If the SDK does not have a method for a call yet, use the client's `json()` method. It still sends your key, retries temporary failures and throws typed errors: ```typescript title="TypeScript" run theme={null} const fibre = new Fibre(); const pricing = await fibre.json<{ sizes: Record }>("GET", "/v1/pricing"); console.log(pricing.sizes.medium.per_hour); // 0.03 ``` `fibre.fetch()` gives you the raw `Response`, for streams and binary bodies. ## Methods For reference, here is every class and method in the SDK: | `Sandbox` | Does | | - | - | | `Sandbox.create(options)` | Start a sandbox; resolves when it runs | | `Sandbox.get(id)` | One sandbox by ID | | `Sandbox.list({ labels })` | Iterate over sandboxes, newest first, paging for you | | `sbx.run(cmd, { cwd, env, secrets, timeout })` | Run and wait; returns `exitCode`, `stdout`, `stderr` | | `sbx.spawn(cmd, { cwd, env, secrets, keep, stdin, timeoutSec })` | Start in the background; returns a `Command` | | `sbx.command(id)`, `sbx.commands()` | Find commands again | | `sbx.files` | `write`, `read`, `readBytes`, `list`, `stat`, `remove` | | `sbx.update({ lifetime, idleTimeout, labels })` | Change what can change; `lifetime: null` removes the lifetime | | `sbx.refresh()` | Re-read its status | | `sbx.snapshot({ name })` | Take a snapshot: its whole state, with memory | | `sbx.browser({ ttl })`, `sbx.closeBrowser()` | Links to its browser; close it | | `sbx.desktop()` | A link to its desktop | | `sbx.delete()` | Delete it | | Properties | `id`, `status`, `runtime`, `runtimeReason`, `url`, `hostname`, `labels`, `secrets`, `expiresAt`, `idleTimeout`, `data` | | `Command` | Does | | - | - | | `output({ follow })` | Its output as it is written (async iterator of `{ stream, data }`) | | `wait({ timeout })` | Wait for the end; returns `exitCode`, `status`, `stdout`, `stderr` | | `write(data)`, `closeStdin()` | Feed its standard input | | `kill({ signal, grace })` | Stop it: `TERM`, then `KILL` after `grace` seconds | | `refresh()` | Re-read its status | | Properties | `id`, `status`, `exitCode`, `pid`, `log` | | `Snapshot` | Does | | - | - | | `Snapshot.get(name)`, `Snapshot.list()` | Find snapshots | | `snapshot.delete()` | Delete one (after the sandboxes started from it) | | Properties | `name`, `from`, `sizeBytes`, `monthlyCostUsd`, `createdAt` | | `Secret` | Does | | - | - | | `Secret.set(name, value)` | Store a secret, or replace its value | | `Secret.get(name)`, `Secret.list()` | Find secrets (never their values) | | `secret.delete()` | Delete one | | Properties | `name`, `version`, `createdAt`, `updatedAt` | | `Fibre` | Does | | - | - | | `new Fibre({ apiKey, baseUrl, timeout, maxRetries, fetch })` | A configured client | | `fibre.json(method, path, { body, query, headers })` | Any API call, JSON in and out | | `fibre.fetch(method, path, options)` | Any API call, raw `Response` | # Images and builds Source: https://docs.fibre.dev/setup/images Choose what a sandbox starts from: Fibre's default image, any public image, an image you build on Fibre from a Dockerfile, or an image from your own registry. An **image** is the set of files a sandbox starts with: the operating system, the languages and tools, and anything else installed in advance. If you have used Docker, it is the same idea, and the same images work. You choose a sandbox's image with the `image` option when you create it. There are several kinds to choose from: | Start from | `image` | When | | - | - | - | | Fibre's default image | leave it out | Most agents and scripts: Python, Node, git and a browser are ready | | A public image | `"python:3.12-slim"`, `"node:22"`, `"ubuntu:24.04"` | A specific language version or distribution | | **An image you build on Fibre** | the `image` of a finished build | Your app or your agent's toolchain, from your own Dockerfile | | A private image | `"ghcr.io/acme/agent:1.4"` | Your registry, with [credentials](/setup/registries) stored once | > [!NOTE] > > If you plan to **run commands in** the sandbox (rather than use it to serve an app), add `"ready": "process"`. > Without it, Fibre runs the image's own startup command and waits for it to answer on its port. See > [sizes and installed tools](/sandboxes/sizes#bring-your-own-image) for the details. ## Build an image from a Dockerfile A **Dockerfile** is a recipe for an image: start from this base, install these packages, copy in this code. Fibre can build an image from a Dockerfile for you. **You do not need Docker on your machine, or a registry to store the result.** You send the Dockerfile and the files it uses, Fibre builds the image, and the image is then ready to use in your account's sandboxes. This example builds a small web API written with FastAPI, a popular Python framework, and then runs it in a sandbox that serves it at a public address. **1. Write the app and its Dockerfile** ```bash title="Terminal" run theme={null} mkdir -p hello-api cat > hello-api/main.py <<'EOF' from fastapi import FastAPI app = FastAPI() @app.get("/") def hello(): return {"message": "built and served on Fibre"} EOF cat > hello-api/Dockerfile <<'EOF' FROM python:3.12-slim RUN pip install --no-cache-dir fastapi uvicorn WORKDIR /app COPY main.py . CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] EOF ``` ```typescript title="TypeScript" run theme={null} import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { execFileSync } from "node:child_process"; import { Fibre, Sandbox } from "@fibre-dev/sdk"; mkdirSync("hello-api", { recursive: true }); writeFileSync("hello-api/main.py", [ "from fastapi import FastAPI", "", "app = FastAPI()", "", '@app.get("/")', "def hello():", ' return {"message": "built and served on Fibre"}', ].join("\n") + "\n"); writeFileSync("hello-api/Dockerfile", [ "FROM python:3.12-slim", "RUN pip install --no-cache-dir fastapi uvicorn", "WORKDIR /app", "COPY main.py .", 'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]', ].join("\n") + "\n"); ``` ```python title="Python" run theme={null} from pathlib import Path from fibre import Fibre, Sandbox Path("hello-api").mkdir(exist_ok=True) Path("hello-api/main.py").write_text("\n".join([ "from fastapi import FastAPI", "", "app = FastAPI()", "", '@app.get("/")', "def hello():", ' return {"message": "built and served on Fibre"}', ]) + "\n") Path("hello-api/Dockerfile").write_text("\n".join([ "FROM python:3.12-slim", "RUN pip install --no-cache-dir fastapi uvicorn", "WORKDIR /app", "COPY main.py .", 'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]', ]) + "\n") ``` **2. Send it to Fibre** Send the folder containing the Dockerfile as a single archive. (This folder is called the **build context**: the Dockerfile can only use files that are inside it.) ```bash title="curl" run capture=BUILD=.id theme={null} tar -C hello-api -czf - . | curl -sS -X POST "$FIBRE_API_URL/v1/builds" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/x-tar" --data-binary @- ``` ```typescript title="TypeScript" run theme={null} const fibre = new Fibre(); const context = execFileSync("tar", ["-C", "hello-api", "-czf", "-", "."]); let build = await fibre.json<{ id: string; status: string; image: string | null }>("POST", "/v1/builds", { raw: context, headers: { "content-type": "application/x-tar" }, }); console.log(build.id, build.status); // 7c1e… building ``` ```python title="Python" run theme={null} import subprocess fibre = Fibre() context = subprocess.run(["tar", "-C", "hello-api", "-czf", "-", "."], capture_output=True, check=True).stdout build = fibre.json("POST", "/v1/builds", content=context, headers={"content-type": "application/x-tar"}) print(build["id"], build["status"]) # 7c1e… building ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "…" > } > ``` The build runs on Fibre while you wait or do something else. This one takes about 15 seconds. **If you send exactly the same files and Dockerfile as an earlier build, Fibre does not build again.** It answers straight away with `"status": "succeeded"`, the earlier image, and `"cached": true`. **3. Follow the build** ```bash title="curl" run theme={null} curl -sSN "$FIBRE_API_URL/v1/builds/$BUILD/logs?follow=1" -H "Authorization: Bearer $FIBRE_API_KEY" | tail -n 1 ``` ```typescript title="TypeScript" run theme={null} while (build.status === "building") { await new Promise((r) => setTimeout(r, 3000)); build = await fibre.json("GET", `/v1/builds/${build.id}`); } console.log(build.status, build.image); // succeeded build/… ``` ```python title="Python" run theme={null} import time while build["status"] == "building": time.sleep(3) build = fibre.json("GET", f"/v1/builds/{build['id']}") print(build["status"], build["image"]) # succeeded build/… ``` > [accordion] Output > > ```text title="output" expected theme={null} > "status":"succeeded" > ``` The build log streams one JSON line for each piece of build output, followed by an `end` line with the final status. It works just like a [command's output](/sandboxes/running-commands#the-output-stream). **4. Run it** When the build has succeeded, its `image` field holds the name of the new image. Pass that name to a sandbox. This image runs a web server on port 8000, so the sandbox is reported as ready **once the app answers**, and the sandbox's address then serves the API: ```bash title="curl" run capture=IMAGE=.image theme={null} curl -sS "$FIBRE_API_URL/v1/builds/$BUILD" -H "Authorization: Bearer $FIBRE_API_KEY" ``` ```typescript title="TypeScript" run theme={null} const api = await Sandbox.create({ image: build.image!, exposedPort: 8000, lifetime: 600, labels: { docs: "images" } }); console.log(await fetch(api.url).then((r) => r.json())); // { message: 'built and served on Fibre' } await api.delete(); ``` ```python title="Python" run theme={null} import json from urllib.request import urlopen api = Sandbox.create(image=build["image"], exposed_port=8000, lifetime=600, labels={"docs": "images"}) print(json.load(urlopen(api.url))) # {'message': 'built and served on Fibre'} api.delete() ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "id": "…", > "status": "succeeded", > "image": "…", > "dockerfile": "Dockerfile", > "target": null, > "size_bytes": "…", > "cached": "…", > "builder": "…", > "builder_reason": "…", > "error": null, > "created_at": "…", > "started_at": "…", > "finished_at": "…" > } > ``` ```bash title="curl: start it and call it" run theme={null} SBX=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d "{\"image\": \"$IMAGE\", \"exposed_port\": 8000, \"lifetime_sec\": 600, \"labels\": {\"docs\": \"images\"}}" | jq -r .id) URL=$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .url) curl -sS "$URL/" curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$SBX" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Output > > ```text title="output" expected theme={null} > built and served on Fibre > ``` ### Build options You can adjust a build with these query parameters on `POST /v1/builds`: | Parameter | Default | | | - | - | - | | `dockerfile` | `Dockerfile` | Its path inside the context | | `target` | the last stage | Build up to a named stage of a multi-stage Dockerfile | | `build_arg` | | `KEY=VALUE`, repeated for each argument (up to 64) | | `no_cache` | `false` | `true` builds again even if an identical build exists | While it runs and after it ends, a build has one of these statuses: | Build `status` | Means | | - | - | | `building` | Running | | `succeeded` | Done: `image` is set | | `failed` | `error` says why; the log has the details | | `canceled` | Stopped with `DELETE /v1/builds/{id}` | > [!TIP] > > **Order the steps of your Dockerfile from the least to the most often changed**: system packages first, then > dependencies, then your own code. Fibre reuses every step that has not changed, so if you only change `main.py`, > only the last step is rebuilt. A build runs in a sandbox of its own and is billed like one while it runs. The build context can be up to 2 GB. ## Image or snapshot? Both images and snapshots give new sandboxes a head start, so it is worth knowing which to use. The difference is **memory**: an image keeps only files, while a snapshot also keeps running programs and everything in memory. | | Image | [Snapshot](/setup/snapshots) | | - | - | - | | Keeps files and installed packages | ✓ | ✓ | | Keeps running programs and memory | | ✓ | | A new sandbox starts | Fresh: its own command runs from the start | Exactly where the source was | | Made from | A registry, or a Dockerfile built on Fibre | A running sandbox | | Best for | Toolchains, app images, reproducible environments | Warm servers, preloaded data, instant workspaces | ## Errors | Status | Code | When | | - | - | - | | 403 | `image_not_owned` | The image belongs to another account | | 404 | `image_not_found` | The image does not exist in its registry | | 413 | `payload_too_large` | The build context is over 2 GB | ## Clean up ```bash title="Terminal" run theme={null} rm -rf hello-api ``` ```typescript title="TypeScript" run theme={null} rmSync("hello-api", { recursive: true, force: true }); ``` ```python title="Python" run theme={null} import shutil shutil.rmtree("hello-api", ignore_errors=True) ``` ## Related > [card] [Snapshots](/setup/snapshots) > > Save a sandbox's whole state and start new sandboxes from it, programs already running. > [card] [Private registries](/setup/registries) > > Run images from your own registry. # Private registries Source: https://docs.fibre.dev/setup/registries Store a registry login once, then start sandboxes from your private images on GitHub, Docker Hub or your own registry, without putting credentials in every request. A **registry** is a place where images are stored, such as Docker Hub or GitHub Container Registry. Public images can be used by anyone, but your own images, such as your app or your agent's toolchain, often live in a **private registry** that needs a login. Fibre lets you store that login **once for each registry**. After that, every sandbox in your account can start from your private images, and you never need to send the credentials when you create a sandbox. ## Store a login Fibre only ever downloads images, so give it a token that can **read packages and nothing more**. That way, the token cannot be used to change your images even if it leaked. Store the login like this: ```typescript title="TypeScript" run theme={null} import { Fibre } from "@fibre-dev/sdk"; const fibre = new Fibre(); await fibre.json("PUT", "/v1/registries/ghcr.io", { body: { username: "acme-bot", password: process.env.GHCR_TOKEN ?? "ghp_example_token" }, }); ``` ```python title="Python" run theme={null} import os from fibre import Fibre fibre = Fibre() fibre.json("PUT", "/v1/registries/ghcr.io", json={"username": "acme-bot", "password": os.environ.get("GHCR_TOKEN", "ghp_example_token")}) ``` ```bash title="curl" run theme={null} curl -sS -X PUT "$FIBRE_API_URL/v1/registries/ghcr.io" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d "{\"username\": \"acme-bot\", \"password\": \"${GHCR_TOKEN:-ghp_example_token}\"}" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "registry": "ghcr.io", > "username": "acme-bot", > "created_at": "…" > } > ``` What to use for each registry: | Registry | Name in the path | Username | Password | | - | - | - | - | | GitHub Container Registry | `ghcr.io` | Your GitHub user or bot | A token with `read:packages` | | Docker Hub | `docker.io` | Your Docker Hub user | An access token | | Your own | `registry.acme.dev`, `registry.acme.dev:5000` | As your registry expects | As your registry expects | If you store a login again for the same registry, it replaces the old one. The answer is then `200` instead of `201`. ## Use your images Now name your private image as you would with `docker pull`. Fibre sees which registry it comes from and uses the login you stored: ```bash title="CLI" norun reason="needs an image in your own private registry" theme={null} fibre create --image ghcr.io/acme/agent-toolchain:1.4 --process-ready ``` ```typescript title="TypeScript" norun reason="needs an image in your own private registry" theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ image: "ghcr.io/acme/agent-toolchain:1.4", ready: "process" }); ``` ```python title="Python" norun reason="needs an image in your own private registry" theme={null} from fibre import Sandbox sbx = Sandbox.create(image="ghcr.io/acme/agent-toolchain:1.4", ready="process") ``` ```bash title="curl" norun reason="needs an image in your own private registry" theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"image": "ghcr.io/acme/agent-toolchain:1.4", "ready": "process"}' ``` ## See and remove logins You can see which registries have a stored login, the username, and when each login was last used. **The password is never shown again** by any call. To remove a login, delete it: ```typescript title="TypeScript" run theme={null} const { registries } = await fibre.json<{ registries: { registry: string; username: string }[] }>("GET", "/v1/registries"); console.log(registries); // [ { registry: 'ghcr.io', username: 'acme-bot', … } ] await fibre.json("DELETE", "/v1/registries/ghcr.io"); ``` ```python title="Python" run theme={null} registries = fibre.json("GET", "/v1/registries")["registries"] print(registries) # [{'registry': 'ghcr.io', 'username': 'acme-bot', …}] fibre.json("DELETE", "/v1/registries/ghcr.io") ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/registries" -H "Authorization: Bearer $FIBRE_API_KEY" echo curl -sS -X DELETE "$FIBRE_API_URL/v1/registries/ghcr.io" -H "Authorization: Bearer $FIBRE_API_KEY" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "registry": "ghcr.io", > "deleted": true > } > ``` > > The list, before the login was deleted, looked like this: > > ```json title="list" theme={null} > { > "registries": [ > { > "registry": "ghcr.io", > "username": "acme-bot", > "created_at": "2026-11-21T02:10:44.118Z", > "last_used_at": null > } > ] > } > ``` ## How the login is kept Fibre treats stored logins as secrets: * **They are encrypted when stored**, and never shown again after you save them. * **They are only used to download an image** from that registry, when a sandbox starts from one. * **Each account has one login per registry.** If different teams need different logins, give them separate accounts, or use a shared bot account at the registry. > [!TIP] > > To change the token, create a new one at the registry and store it here. The next download uses it. If you ever > need to cut off access at once, revoke the token at the registry. ## Errors These errors relate to registries: | Status | Code | When | | - | - | - | | 400 | `image_registry_refused` | The registry's address is not one Fibre may reach | | 400 | `validation_failed` | `username` or `password` missing | | 403 | `image_access_denied` | The registry refused the stored login for that image | | 404 | `image_not_found` | No such image or tag in the registry | ## Related > [card] [Images and builds](/setup/images) > > Or build the image on Fibre, with no registry at all. > [card] [Snapshots](/setup/snapshots) > > Start new sandboxes from a prepared one. # Snapshots Source: https://docs.fibre.dev/setup/snapshots Set a sandbox up once (dependencies installed, data loaded, servers running), take a snapshot of its whole state with its memory, and start as many sandboxes from it as you need, each already running and ready to work. Before a new sandbox can do real work, it usually needs the same setup: clone the repository, install dependencies, download a model, start a server. If every sandbox does that from scratch, each one spends **minutes of waiting, and of paid compute, before any real work starts**. A **snapshot** removes that wait. You prepare one sandbox exactly the way you want it, take a snapshot of it, and then start new sandboxes from the snapshot. A snapshot keeps the sandbox's **whole state: its files, its running programs and their memory**. **Each new sandbox starts exactly where the snapshot was: the files are in place, the programs are running, and the data is already in memory.** The setup happens once, and every sandbox after that is ready to work immediately. Here is the difference: | Without a snapshot | With a snapshot | | - | - | | Create → clone → install → start the server → **work** | Create from the snapshot → **work** | | Setup repeated for every user and every task | Setup done once | | Each sandbox may install slightly different versions | Every sandbox identical | ## Take a snapshot In this example, the snapshot is of a small app whose dependencies are installed and whose server is **already running, with data loaded into memory**. **1. Prepare a sandbox** Start a sandbox and do all the slow work you want to save your future sandboxes from: install, build, load data, start servers. ```bash title="CLI" run theme={null} BASE=$(fibre create --port 3000 --lifetime 30m --label docs=snapshots --json | jq -r .id) fibre exec "$BASE" -i -- sh -c 'mkdir -p /app && cat > /app/server.js' <<'JS' const http = require("http"); const { z } = require("zod"); // a dependency, installed below const bootedAt = new Date().toISOString(); const catalog = Array.from({ length: 100000 }, (_, i) => ({ id: i, price: (i % 97) + 0.99 })); // warm data http.createServer((req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ bootedAt, items: catalog.length, zod: typeof z.string })); }).listen(3000); JS fibre exec "$BASE" -- 'cd /app && npm init -y > /dev/null && npm install --silent zod' fibre exec "$BASE" --cwd /app --detach --keep -- node /app/server.js fibre exec "$BASE" --timeout 60 -- 'until curl -sf -o /dev/null localhost:3000; do sleep 1; done' ``` ```typescript title="TypeScript" run theme={null} import { Sandbox, Snapshot } from "@fibre-dev/sdk"; const base = await Sandbox.create({ exposedPort: 3000, lifetime: 1800, labels: { docs: "snapshots" } }); await base.files.write("/app/server.js", ` const http = require("http"); const { z } = require("zod"); // a dependency, installed below const bootedAt = new Date().toISOString(); const catalog = Array.from({ length: 100000 }, (_, i) => ({ id: i, price: (i % 97) + 0.99 })); // warm data http.createServer((req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ bootedAt, items: catalog.length, zod: typeof z.string })); }).listen(3000); `); await base.run("cd /app && npm init -y > /dev/null && npm install --silent zod", { timeout: 300 }); await base.spawn(["node", "/app/server.js"], { cwd: "/app", keep: true }); await base.run("until curl -sf -o /dev/null localhost:3000; do sleep 1; done", { timeout: 60 }); ``` ```python title="Python" run theme={null} from fibre import Sandbox, Snapshot base = Sandbox.create(exposed_port=3000, lifetime=1800, labels={"docs": "snapshots"}) base.files.write("/app/server.js", """ const http = require("http"); const { z } = require("zod"); // a dependency, installed below const bootedAt = new Date().toISOString(); const catalog = Array.from({ length: 100000 }, (_, i) => ({ id: i, price: (i % 97) + 0.99 })); // warm data http.createServer((req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ bootedAt, items: catalog.length, zod: typeof z.string })); }).listen(3000); """) base.run("cd /app && npm init -y > /dev/null && npm install --silent zod", timeout=300) base.spawn(["node", "/app/server.js"], cwd="/app", keep=True) base.run("until curl -sf -o /dev/null localhost:3000; do sleep 1; done", timeout=60) ``` ```bash title="curl" run capture=BASE=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"exposed_port": 3000, "lifetime_sec": 1800, "labels": {"docs": "snapshots"}}' ``` ```bash title="curl: install and start the app" run theme={null} cat <<'EOF' | curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$BASE/files/content?path=/app/server.js" \ -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @- const http = require("http"); const { z } = require("zod"); const bootedAt = new Date().toISOString(); const catalog = Array.from({ length: 100000 }, (_, i) => ({ id: i, price: (i % 97) + 0.99 })); http.createServer((req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ bootedAt, items: catalog.length, zod: typeof z.string })); }).listen(3000); EOF INSTALL=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$BASE/commands" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["sh", "-c", "cd /app && npm init -y > /dev/null && npm install --silent zod"]}' | jq -r .command_id) curl -sSN "$FIBRE_API_URL/v1/sandboxes/$BASE/commands/$INSTALL/logs?follow=1" \ -H "Authorization: Bearer $FIBRE_API_KEY" > /dev/null curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$BASE/commands" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["node", "/app/server.js"], "cwd": "/app", "keep": true}' curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$BASE/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["sh", "-c", "until curl -sf localhost:3000; do sleep 1; done"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "…" > } > ``` **2. Take the snapshot** ```bash title="CLI" run theme={null} fibre snapshot create docs-node-app --from "$BASE" ``` ```typescript title="TypeScript" run theme={null} const snapshot = await base.snapshot({ name: "docs-node-app" }); console.log(snapshot.name, snapshot.sizeBytes, snapshot.monthlyCostUsd); // docs-node-app 4… 0.0… ``` ```python title="Python" run theme={null} snapshot = base.snapshot(name="docs-node-app") print(snapshot.name, snapshot.size_bytes, snapshot.monthly_cost_usd) # docs-node-app 4… 0.0… ``` ```bash title="curl" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/snapshots" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d "{\"name\": \"docs-node-app\", \"from\": \"$BASE\"}" ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "name": "docs-node-app", > "from": "…", > "image": "…", > "cpu_cores": "…", > "memory_mb": "…", > "exposed_port": 3000, > "size_bytes": "…", > "monthly_cost_usd": "…", > "created_at": "…" > } > ``` Taking a snapshot does not stop the sandbox: **it keeps running**. Snapshot names can use lowercase letters, digits and `-`. **3. Start sandboxes from it** Now create sandboxes from the snapshot. Each one is a new, separate sandbox with its own ID, address and files, but it **starts exactly as the snapshot was**. This example creates three at once, one for each of three users: ```bash title="CLI" run theme={null} COPIES="" for user in alice bob carol; do COPIES="$COPIES $(fibre create --snapshot docs-node-app --lifetime 15m --label docs=snapshots --label user=$user --json | jq -r .id)" done for copy in $COPIES; do fibre exec "$copy" -- curl -s localhost:3000; echo # {"bootedAt":"…","items":100000,"zod":"function"} done ``` ```typescript title="TypeScript" run theme={null} const copies = await Promise.all( ["alice", "bob", "carol"].map((user) => Sandbox.create({ snapshot: "docs-node-app", lifetime: 900, labels: { docs: "snapshots", user } })), ); for (const copy of copies) { const answer = JSON.parse((await copy.run("curl -s localhost:3000")).stdout); console.log(copy.labels.user, answer); // alice { bootedAt: '…', items: 100000, zod: 'function' } } ``` ```python title="Python" run theme={null} import json from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor() as pool: copies = list(pool.map( lambda user: Sandbox.create(snapshot="docs-node-app", lifetime=900, labels={"docs": "snapshots", "user": user}), ["alice", "bob", "carol"], )) for copy in copies: answer = json.loads(copy.run("curl -s localhost:3000").stdout) print(copy.labels["user"], answer) # alice {'bootedAt': '…', 'items': 100000, 'zod': 'function'} ``` ```bash title="curl" run capture=COPY=.id theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"snapshot": "docs-node-app", "lifetime_sec": 900, "labels": {"docs": "snapshots", "user": "alice"}}' ``` ```bash title="curl: the server is already up" run theme={null} curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$COPY/exec" \ -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \ -d '{"command": ["curl", "-s", "localhost:3000"]}' ``` > [accordion] Response > > ```json title="response" expected theme={null} > { > "exit_code": 0, > "stdout": "…" > } > ``` > > `stdout` holds the server's answer, which looks like this: > > ```json title="stdout" theme={null} > { > "bootedAt": "2026-11-21T01:52:10.418Z", > "items": 100000, > "zod": "function" > } > ``` **Every new sandbox reports the same `bootedAt` time, which is the moment the snapshot's server started.** None of them ran `npm install`, started the server or built the catalog. They all began with that work already done. ## What a new sandbox gets A sandbox created from a snapshot shares some things with the snapshot and has others of its own: | | From the snapshot | Its own | | - | - | - | | Files, installed packages | ✓ (as its own copy: changes in one sandbox never affect another) | | | Running programs and their memory | ✓ | | | Image, size, runtime, environment, exposed port | ✓ | | | ID, `url`, labels, lifetime, idle timeout | | ✓ | > [!NOTE] > > **When you create a sandbox from a snapshot, you can only set `lifetime_sec`, `idle_timeout_sec` and `labels`.** > Everything else comes from the snapshot. If you send another setting, the request is refused with > `400 snapshot_fields_fixed`. ## Where snapshots fit Snapshots help wherever many sandboxes need the same starting point: * **A workspace per user.** Keep one snapshot with your stack. Each user's sandbox is created from it, and is ready the moment they sign in. * **Agents in parallel.** Keep one snapshot with the repository cloned and dependencies installed, and create one sandbox per task. * **Evals and reinforcement learning.** Every episode gets a fresh, identical environment, with nothing left over from the previous one. * **Code interpreters.** Keep a Python process with pandas and your libraries already imported, so the user's first piece of code runs at once. > [!TIP] > > **Put the slow, shared work in the snapshot, and the per-user work in each sandbox.** Install and load before you > take the snapshot, then add each user's own data after their sandbox starts. When your dependencies change, take a > new snapshot. ## List and delete You can list your snapshots, with what each one stores, and delete the ones you no longer need: ```bash title="CLI" run theme={null} fibre snapshot list fibre delete $COPIES fibre snapshot delete docs-node-app # after the sandboxes started from it fibre delete "$BASE" ``` ```typescript title="TypeScript" run theme={null} for (const s of await Snapshot.list()) console.log(s.name, s.sizeBytes, s.monthlyCostUsd); for (const copy of copies) await copy.delete(); await (await Snapshot.get("docs-node-app")).delete(); // after the sandboxes started from it await base.delete(); ``` ```python title="Python" run theme={null} for s in Snapshot.list(): print(s.name, s.size_bytes, s.monthly_cost_usd) for copy in copies: copy.delete() Snapshot.get("docs-node-app").delete() # after the sandboxes started from it base.delete() ``` ```bash title="curl" run theme={null} curl -sS "$FIBRE_API_URL/v1/snapshots" -H "Authorization: Bearer $FIBRE_API_KEY" echo curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$COPY" -H "Authorization: Bearer $FIBRE_API_KEY" curl -sS -X DELETE "$FIBRE_API_URL/v1/snapshots/docs-node-app" -H "Authorization: Bearer $FIBRE_API_KEY" curl -sS -X DELETE "$FIBRE_API_URL/v1/sandboxes/$BASE" -H "Authorization: Bearer $FIBRE_API_KEY" ``` * **Deleting the sandbox you took a snapshot of does not delete the snapshot.** The snapshot is kept separately. * **A snapshot cannot be deleted while sandboxes created from it still exist.** Delete those sandboxes first. * **A snapshot is kept until you delete it.** It does not expire. ## What it costs A snapshot is stored, so **it counts towards your account's storage** for as long as you keep it. Every account includes **20 GB** of storage, shared by your snapshots and your sleeping sandboxes, and storage beyond that costs **\$0.10 per GB per month**. See [pricing](/get-started/pricing#storage). Each snapshot tells you what it stores and what that size costs: * **`size_bytes`**: how much it stores, files, memory and running programs together. * **`monthly_cost_usd`**: what that size costs a month at the storage price. Your included 20 GB come first, so while your storage stays under it, you pay nothing for it. Delete the snapshots you no longer need to stop paying for them. ## Good to know A few more details: | | | | - | - | | Runtimes | Both. On `vm`, wait until the source's commands have ended before saving | | Runtime of a new sandbox | The snapshot's | | Storage | Counts towards your account's storage until deleted ([what it costs](#what-it-costs)) | | Names | Lowercase letters, digits and `-`, up to 100 characters, unique in your account | ## Errors These are the errors you may see when working with snapshots. A snapshot of a `vm` sandbox is also refused while a command is still running in it, so wait for its commands to finish first. | Status | Code | When | | - | - | - | | 400 | `snapshot_fields_fixed` | A new sandbox was given a field it takes from the snapshot | | 404 | `snapshot_not_found` | No snapshot with that name | | 409 | `snapshot_exists` | A snapshot with that name already exists | | 409 | `snapshot_in_use` | Deleting a snapshot while sandboxes created from it still exist | ## Related > [card] [Images and builds](/setup/images) > > Where a sandbox starts on day one: a registry image or one built from a Dockerfile. > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > The same memory-keeping that makes snapshots work. # Tests and CI Source: https://docs.fibre.dev/use-cases/ci Run a test suite in a fresh sandbox from any CI or script: send the code, stream the output live, fail the build on the exit code, and keep the sandbox around to debug a failure. Some tests are better kept off your CI runner and off your laptop. They might install software, start servers, reach the network, or run code that an agent has just written. **Running them in a sandbox** instead gives you several advantages: * **A clean machine for every run**, with nothing left over from the previous one. * **More power than the CI runner** when you need it (the `large` and `xlarge` sizes), and Docker on the `vm` runtime. * **The test output streamed live** into your CI log, as the tests run. * **A way to investigate failures**: when a run fails, you can keep its sandbox and look inside to see why. ## The script A single script does all of this. It packs up the project, sends it to a sandbox, runs the tests, streams their output into the log, and finally exits with the same code as the tests, so your CI marks the build as passed or failed. You can run it from GitHub Actions, GitLab, Jenkins, or your own terminal. **1. A project to test** To keep the example self-contained, we create a tiny project with one module and its tests. In your pipeline, this would be your own repository. ```bash title="CLI" run theme={null} mkdir -p project cat > project/slugify.py <<'PY' import re def slugify(text): return re.sub(r'[^a-z0-9]+', '-', text.lower()).strip('-') PY cat > project/test_slugify.py <<'PY' import unittest from slugify import slugify class T(unittest.TestCase): def test_spaces(self): self.assertEqual(slugify('Hello World'), 'hello-world') def test_symbols(self): self.assertEqual(slugify('fibre: sandboxes!'), 'fibre-sandboxes') def test_trim(self): self.assertEqual(slugify(' padded '), 'padded') PY ``` ```typescript title="TypeScript" run theme={null} import { mkdirSync, writeFileSync } from "node:fs"; mkdirSync("project", { recursive: true }); writeFileSync("project/slugify.py", [ "import re", "def slugify(text):", " return re.sub(r'[^a-z0-9]+', '-', text.lower()).strip('-')", ].join("\n") + "\n"); writeFileSync("project/test_slugify.py", [ "import unittest", "from slugify import slugify", "class T(unittest.TestCase):", " def test_spaces(self): self.assertEqual(slugify('Hello World'), 'hello-world')", " def test_symbols(self): self.assertEqual(slugify('fibre: sandboxes!'), 'fibre-sandboxes')", " def test_trim(self): self.assertEqual(slugify(' padded '), 'padded')", ].join("\n") + "\n"); ``` ```python title="Python" run theme={null} from pathlib import Path Path("project").mkdir(exist_ok=True) Path("project/slugify.py").write_text("\n".join([ "import re", "def slugify(text):", " return re.sub(r'[^a-z0-9]+', '-', text.lower()).strip('-')", ]) + "\n") Path("project/test_slugify.py").write_text("\n".join([ "import unittest", "from slugify import slugify", "class T(unittest.TestCase):", " def test_spaces(self): self.assertEqual(slugify('Hello World'), 'hello-world')", " def test_symbols(self): self.assertEqual(slugify('fibre: sandboxes!'), 'fibre-sandboxes')", " def test_trim(self): self.assertEqual(slugify(' padded '), 'padded')", ]) + "\n") ``` **2. Send it and run the tests** ```bash title="CLI" run theme={null} RUN_ID=${GITHUB_RUN_ID:-local} SBX=$(fibre create --size medium --lifetime 1h --label ci=tests --label run=$RUN_ID --json | jq -r .id) # send the project folder, then run the tests: their output streams into this job's log as it is written fibre cp project "$SBX:/work/app" if fibre exec "$SBX" --cwd /work/app -- python3 -m unittest -v; then EXIT_CODE=0; else EXIT_CODE=$?; fi echo "tests exited with $EXIT_CODE" # tests exited with 0 ``` ```typescript title="TypeScript" run theme={null} import { execFileSync } from "node:child_process"; import { Sandbox } from "@fibre-dev/sdk"; const runId = process.env.GITHUB_RUN_ID ?? "local"; const sbx = await Sandbox.create({ size: "medium", lifetime: 3600, labels: { ci: "tests", run: runId } }); // send the project as one archive, unpack it inside await sbx.files.write("/work/project.tgz", execFileSync("tar", ["-C", "project", "-czf", "-", "."])); await sbx.run("mkdir -p /work/app && tar -xzf /work/project.tgz -C /work/app"); // run the tests, streaming the output into this job's log as it is written const tests = await sbx.spawn(["python3", "-m", "unittest", "-v"], { cwd: "/work/app" }); for await (const chunk of tests.output()) process.stdout.write(chunk.data); const { exitCode } = await tests.wait(); console.log(`\ntests exited with ${exitCode}`); // tests exited with 0 ``` ```python title="Python" run theme={null} import os import subprocess import sys from fibre import Sandbox run_id = os.environ.get("GITHUB_RUN_ID", "local") sbx = Sandbox.create(size="medium", lifetime=3600, labels={"ci": "tests", "run": run_id}) # send the project as one archive, unpack it inside sbx.files.write("/work/project.tgz", subprocess.run(["tar", "-C", "project", "-czf", "-", "."], capture_output=True, check=True).stdout) sbx.run("mkdir -p /work/app && tar -xzf /work/project.tgz -C /work/app") # run the tests, streaming the output into this job's log as it is written tests = sbx.spawn(["python3", "-m", "unittest", "-v"], cwd="/work/app") for chunk in tests.output(): sys.stdout.write(chunk.data) exit_code = tests.wait().exit_code print(f"\ntests exited with {exit_code}") # tests exited with 0 ``` **3. Pass or fail the build** ```bash title="CLI" run theme={null} if [ "$EXIT_CODE" -eq 0 ]; then fibre delete "$SBX" else # keep the sandbox to debug: it sleeps (no compute cost) until its lifetime ends echo "Tests failed. Debug in sandbox $SBX (label run=$RUN_ID)." exit 1 fi ``` ```typescript title="TypeScript" run theme={null} if (exitCode === 0) { await sbx.delete(); } else { // keep the sandbox to debug: it sleeps (no compute cost) until its lifetime ends console.log(`Tests failed. Debug in sandbox ${sbx.id} (label run=${runId}).`); process.exitCode = 1; } ``` ```python title="Python" run theme={null} if exit_code == 0: sbx.delete() else: # keep the sandbox to debug: it sleeps (no compute cost) until its lifetime ends print(f"Tests failed. Debug in sandbox {sbx.id} (label run={run_id}).") sys.exit(1) ``` ## In GitHub Actions ```yaml title=".github/workflows/tests.yml" theme={null} name: tests on: [push, pull_request] jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: 22 } - run: npm install @fibre-dev/sdk - run: node scripts/test-in-sandbox.mjs env: FIBRE_API_KEY: ${{ secrets.FIBRE_API_KEY }} ``` Give your CI its own API key, limited to the `sandboxes.*` scope and set to expire. That way it can only manage sandboxes, and only for a limited time. See [API keys](/get-started/api-keys). ## Debug a failure When a run fails, the script keeps its sandbox instead of deleting it. That lets you look **inside the exact machine where the tests failed**: its files, its installed packages and its logs. You can find it by its labels and run commands in it from your terminal: ```bash title="Terminal" norun reason="debugs a sandbox from a failed run" theme={null} SBX=$(curl -sS "$FIBRE_API_URL/v1/sandboxes?label.ci=tests&label.run=$RUN_ID" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r '.sandboxes[0].id') 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", "cd /work/app && python3 -m unittest -v 2>&1 | tail -n 30"]}' ``` ## Faster runs Once the basic setup works, these changes make each run faster: | Do | Gain | | - | - | | A [snapshot](/setup/snapshots) with your dependencies installed | No install step in each run | | Copy the snapshot per shard, [in parallel](/use-cases/parallel) | Wall time divided by the number of shards | | A bigger `size` for compile-heavy suites | More cores, same per-second billing | | `needs: ["docker"]` | Tests that start databases in containers | ## Clean up ```bash title="CLI" run theme={null} rm -rf project ``` ```typescript title="TypeScript" run theme={null} import { rmSync } from "node:fs"; rmSync("project", { recursive: true, force: true }); ``` ```python title="Python" run theme={null} import shutil shutil.rmtree("project", ignore_errors=True) ``` ## Related > [card] [Run commands](/sandboxes/running-commands) > > How streaming output and exit codes work. > [card] [Docker Compose](/use-cases/docker) > > Run integration tests against real databases and services. # A coding agent on your repo Source: https://docs.fibre.dev/use-cases/coding-agent Hand a failing test to Claude Code in a sandbox: it gets the repo, the tools and a shell of its own, fixes the bug, proves it with the tests, and you review the diff before anything leaves the sandbox. Coding agents such as Claude Code can **fix bugs, add features and upgrade dependencies** on their own. They work best when they can actually run the code while they work: install packages, run the tests, and try again when something fails. On your laptop, that means letting a model run commands on your own machine. In a sandbox, **the agent gets a machine of its own**, and you decide what comes back out of it. The whole process is a simple loop: 1. **Start a sandbox** and put your repository in it. 2. **Give the agent its task**, together with an API key for its model, for that one command only. 3. **Check the agent's work yourself**: run the tests and read the changes. 4. **Ship the change** by pushing a branch, or **ask for more changes**. Between rounds, the sandbox sleeps with everything in place. ## The task To keep the example small, the repository is a single Python file with a real bug: `average([])` divides by zero, but a test says it should return `0`. Follow the steps to have Claude Code fix it. **1. A sandbox with the repo** ```bash title="CLI" run theme={null} SBX=$(fibre create --size medium --lifetime 2h --idle-timeout 10m --label agent=fix-average --json | jq -r .id) # in your project: fibre exec "$SBX" -- git clone https://github.com/you/your-repo /work/repo printf 'def average(xs):\n return sum(xs) / len(xs)\n' | fibre exec "$SBX" -i -- sh -c 'mkdir -p /work/repo && cat > /work/repo/stats.py' fibre exec "$SBX" -i -- sh -c 'cat > /work/repo/test_stats.py' <<'PY' import unittest from stats import average class TestAverage(unittest.TestCase): def test_numbers(self): self.assertEqual(average([2, 4, 6]), 4) def test_empty(self): self.assertEqual(average([]), 0) PY fibre exec "$SBX" --cwd /work/repo -- "git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm 'initial'" ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ size: "medium", lifetime: 7200, idleTimeout: 600, labels: { agent: "fix-average" } }); // in your project: git clone https://github.com/you/your-repo /work/repo await sbx.files.write("/work/repo/stats.py", "def average(xs):\n return sum(xs) / len(xs)\n"); await sbx.files.write("/work/repo/test_stats.py", [ "import unittest", "from stats import average", "", "class TestAverage(unittest.TestCase):", " def test_numbers(self):", " self.assertEqual(average([2, 4, 6]), 4)", " def test_empty(self):", " self.assertEqual(average([]), 0)", ].join("\n") + "\n"); await sbx.run("cd /work/repo && git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm 'initial'"); ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create(size="medium", lifetime=7200, idle_timeout=600, labels={"agent": "fix-average"}) # in your project: git clone https://github.com/you/your-repo /work/repo sbx.files.write("/work/repo/stats.py", "def average(xs):\n return sum(xs) / len(xs)\n") sbx.files.write("/work/repo/test_stats.py", "\n".join([ "import unittest", "from stats import average", "", "class TestAverage(unittest.TestCase):", " def test_numbers(self):", " self.assertEqual(average([2, 4, 6]), 4)", " def test_empty(self):", " self.assertEqual(average([]), 0)", ]) + "\n") sbx.run("cd /work/repo && git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm 'initial'") ``` **2. See the failure** ```bash title="CLI" run theme={null} fibre exec "$SBX" --cwd /work/repo -- 'python3 -m unittest -q 2>&1 | tail -n 3' # … ZeroDivisionError … FAILED (errors=1) ``` ```typescript title="TypeScript" run theme={null} const before = await sbx.run("cd /work/repo && python3 -m unittest -q 2>&1 | tail -n 3"); console.log(before.exitCode, before.stdout); // 0 … ZeroDivisionError … FAILED (errors=1) ``` ```python title="Python" run theme={null} before = sbx.run("cd /work/repo && python3 -m unittest -q 2>&1 | tail -n 3") print(before.exit_code, before.stdout) # 0 … ZeroDivisionError … FAILED (errors=1) ``` **3. Install the agent** Claude Code's installer takes about a minute. You can install it in each sandbox, or install it once in a [snapshot](/setup/snapshots) and start every task from that. ```bash title="CLI" run theme={null} fibre exec "$SBX" --timeout 10m -- 'curl -fsSL https://claude.ai/install.sh | bash > /dev/null && ~/.local/bin/claude --version' ``` ```typescript title="TypeScript" run theme={null} const install = await sbx.run("curl -fsSL https://claude.ai/install.sh | bash > /dev/null && ~/.local/bin/claude --version", { timeout: 600 }); console.log(install.stdout.trim()); // 2.1.… (Claude Code) ``` ```python title="Python" run theme={null} install = sbx.run("curl -fsSL https://claude.ai/install.sh | bash > /dev/null && ~/.local/bin/claude --version", timeout=600) print(install.stdout.strip()) # 2.1.… (Claude Code) ``` **4. Give it the task** Now give the agent its task. The model's API key goes in this command's `env` only, so other commands in the sandbox never see it. `--allowedTools` lists what the agent may do without asking for permission. Since nobody is there to answer its questions, anything not on that list is simply refused. Here it may read and edit files, and run the tests. The output is streamed, so you can watch the agent work as it happens: ```bash title="CLI" norun reason="needs your Anthropic API key" theme={null} # the agent's output streams here as it thinks and acts fibre exec "$SBX" --cwd /work/repo \ --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \ --env TASK="test_empty fails: average([]) should return 0. Fix stats.py and run the tests until they pass." \ -- '~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash(python3 -m unittest*)" --output-format stream-json --verbose' ``` ```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null} const agent = await sbx.spawn( ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash(python3 -m unittest*)" --output-format stream-json --verbose'], { env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY!, TASK: "test_empty fails: average([]) should return 0. Fix stats.py and run the tests until they pass.", }, }, ); for await (const chunk of agent.output()) process.stdout.write(chunk.data); // watch it think and act, live const finished = await agent.wait(); ``` ```python title="Python" norun reason="needs your Anthropic API key" theme={null} import os import sys agent = sbx.spawn( ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash(python3 -m unittest*)" --output-format stream-json --verbose'], env={ "ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"], "TASK": "test_empty fails: average([]) should return 0. Fix stats.py and run the tests until they pass.", }, ) for chunk in agent.output(): sys.stdout.write(chunk.data) # watch it think and act, live finished = agent.wait() ``` **5. Check its work yourself** An agent can be wrong, even when it says it has finished. So **run the tests and read the changes yourself** before anything leaves the sandbox: ```bash title="CLI" norun reason="runs after the agent's change" theme={null} fibre exec "$SBX" --cwd /work/repo -- python3 -m unittest -q && echo "tests pass" fibre exec "$SBX" --cwd /work/repo -- git diff # - return sum(xs) / len(xs) # + return sum(xs) / len(xs) if xs else 0 ``` ```typescript title="TypeScript" norun reason="runs after the agent's change" theme={null} const after = await sbx.run("cd /work/repo && python3 -m unittest -q"); console.log(after.exitCode === 0 ? "tests pass" : after.stdout); const diff = await sbx.run("cd /work/repo && git diff"); console.log(diff.stdout); // - return sum(xs) / len(xs) // + return sum(xs) / len(xs) if xs else 0 ``` ```python title="Python" norun reason="runs after the agent's change" theme={null} after = sbx.run("cd /work/repo && python3 -m unittest -q") print("tests pass" if after.exit_code == 0 else after.stdout) diff = sbx.run("cd /work/repo && git diff") print(diff.stdout) # - return sum(xs) / len(xs) # + return sum(xs) / len(xs) if xs else 0 ``` **6. Ship it, or ask for more** If you are happy with the change, push a branch from the sandbox, using a token that can only push to that repository. Or read the diff out of the sandbox and apply it on your side. If the change needs more work, **send your next instruction to the same sandbox**, even hours later. It wakes up with the repository, the installed agent and the agent's session exactly where they were, and `--continue` picks up the same conversation: ```bash title="CLI" norun reason="needs your Anthropic API key" theme={null} fibre exec "$SBX" --cwd /work/repo --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" --env TASK="Also add a docstring to average." \ -- '~/.local/bin/claude -p "$TASK" --continue --allowedTools "Read,Edit"' ``` ```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null} await sbx.run( ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --continue --allowedTools "Read,Edit"'], { env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY!, TASK: "Also add a docstring to average." } }, ); ``` ```python title="Python" norun reason="needs your Anthropic API key" theme={null} sbx.run( ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --continue --allowedTools "Read,Edit"'], env={"ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"], "TASK": "Also add a docstring to average."}, ) ``` ## 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() ``` ## Make it production-ready These changes turn the example into something you can run for real: | Concern | What to do | | - | - | | Setup time | A [snapshot](/setup/snapshots) with the agent installed and the repo cloned: each task starts in seconds | | Private repos | Clone with a short-lived token that reads one repo; push with one that writes one branch | | What the agent can reach | A [network allow list](/production/network): your Git host, the package registry, the model API | | The model key | In the command's `env` only; a key with a spending limit, revocable | | Watching | Stream `--output-format stream-json` to your UI; open the sandbox's [desktop](/connect/desktop) or browser for UI work | | Cost | The sandbox sleeps while you review: a task that works 10 minutes costs 10 minutes | ## Related > [card] [Claude Code in a sandbox](/build-with-ai/claude-code) > > Every Claude Code option, its sessions, and the API key, explained in detail. > [card] [Many agents in parallel](/use-cases/parallel) > > One task per sandbox, with many running at once. # Preview environments Source: https://docs.fibre.dev/use-cases/dev-server A live preview of every branch or pull request: the app's dev server running in a sandbox, at its own HTTPS link, updating as code changes, asleep when nobody looks, and gone when the branch is merged. A reviewer should not have to download a branch and set it up on their own machine just to see a change. And an agent that builds a user interface should **show** what it built, not only describe it. A **preview environment** solves both. You give each branch, pull request or agent session **a sandbox running the app's development server**. It has its own HTTPS link that you can share, it updates as the code changes, and it sleeps when nobody is looking at it. Here is how it fits into a pull request's life: | Event | Your automation | | - | - | | A pull request opens | Create a sandbox from the branch, start the dev server, comment the link on the PR | | New commits | Pull into the same sandbox: the dev server reloads | | Nobody looks for a while | Nothing: the sandbox sleeps, with no compute cost; the next visit wakes it | | The PR is merged or closed | Delete the sandbox | ## A live Vite app at a public link **1. A sandbox that serves port 3000** ```bash title="CLI" run theme={null} PR=128 SBX=$(fibre create --port 3000 --idle-timeout 10m --lifetime 1d --label preview=true --label pr=$PR --json | jq -r .id) ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const pr = 128; const sbx = await Sandbox.create({ exposedPort: 3000, idleTimeout: 600, lifetime: 86400, labels: { preview: "true", pr: String(pr) }, }); ``` ```python title="Python" run theme={null} from fibre import Sandbox pr = 128 sbx = Sandbox.create(exposed_port=3000, idle_timeout=600, lifetime=86400, labels={"preview": "true", "pr": str(pr)}) ``` **2. Get the code** In your pipeline, this step is a `git clone --branch` of the pull request's branch. To keep the example self-contained, we write a small Vite app instead. (Vite is a popular development server for web apps.) ```bash title="CLI" run theme={null} # in your pipeline: fibre exec "$SBX" -- git clone --depth 1 --branch "$BRANCH" "$REPO_URL" /work/app fibre exec "$SBX" -i -- sh -c 'mkdir -p /work/app && cat > /work/app/package.json' <<'JSON' { "name": "preview-demo", "private": true, "type": "module", "scripts": { "dev": "vite --host 0.0.0.0 --port 3000" }, "devDependencies": { "vite": "^6.0.0" } } JSON echo "PR #$PR

" \ | fibre exec "$SBX" -i -- sh -c 'cat > /work/app/index.html' echo "document.querySelector(\"#title\").textContent = \"Preview of PR #$PR: version 1\";" \ | fibre exec "$SBX" -i -- sh -c 'cat > /work/app/main.js' ``` ```typescript title="TypeScript" run theme={null} // in your pipeline: await sbx.run(`git clone --depth 1 --branch ${branch} ${repoUrl} /work/app`) await sbx.files.write("/work/app/package.json", JSON.stringify({ name: "preview-demo", private: true, type: "module", scripts: { dev: "vite --host 0.0.0.0 --port 3000" }, devDependencies: { vite: "^6.0.0" }, }, null, 2)); await sbx.files.write("/work/app/index.html", `PR #${pr}

`); await sbx.files.write("/work/app/main.js", `document.querySelector("#title").textContent = "Preview of PR #${pr}: version 1";`); ``` ```python title="Python" run theme={null} import json # in your pipeline: sbx.run(f"git clone --depth 1 --branch {branch} {repo_url} /work/app") sbx.files.write("/work/app/package.json", json.dumps({ "name": "preview-demo", "private": True, "type": "module", "scripts": {"dev": "vite --host 0.0.0.0 --port 3000"}, "devDependencies": {"vite": "^6.0.0"}, }, indent=2)) sbx.files.write("/work/app/index.html", f'PR #{pr}

') sbx.files.write("/work/app/main.js", f'document.querySelector("#title").textContent = "Preview of PR #{pr}: version 1";') ``` **3. Install and start the dev server** Install the app's dependencies, then start the development server with `keep: true`, so it keeps running across sleep and wake. Vite only answers requests for hostnames it knows about, so we tell it the sandbox's hostname through an environment variable: ```bash title="CLI" run theme={null} fibre exec "$SBX" --cwd /work/app -- npm install --silent HOST=$(fibre url "$SBX" --json | jq -r .hostname) fibre exec "$SBX" --cwd /work/app --env __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS=$HOST --detach --keep -- npm run dev fibre exec "$SBX" --timeout 2m -- 'until curl -sf -o /dev/null localhost:3000; do sleep 1; done' echo "Preview: $(fibre url "$SBX")" # comment this on the pull request ``` ```typescript title="TypeScript" run theme={null} await sbx.run("cd /work/app && npm install --silent", { timeout: 300 }); await sbx.spawn(["npm", "run", "dev"], { cwd: "/work/app", keep: true, env: { __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: sbx.hostname }, }); await sbx.run("until curl -sf -o /dev/null localhost:3000; do sleep 1; done", { timeout: 120 }); console.log(`Preview: ${sbx.url}`); // comment this on the pull request ``` ```python title="Python" run theme={null} sbx.run("cd /work/app && npm install --silent", timeout=300) sbx.spawn(["npm", "run", "dev"], cwd="/work/app", keep=True, env={"__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS": sbx.hostname}) sbx.run("until curl -sf -o /dev/null localhost:3000; do sleep 1; done", timeout=120) print(f"Preview: {sbx.url}") # comment this on the pull request ``` **4. Open the link** ```bash title="CLI" run theme={null} URL=$(fibre url "$SBX") curl -s "$URL" | grep -q main.js && echo "Vite is serving the app" curl -s "$URL/main.js" | grep -q "version 1" && echo "version 1" ``` ```typescript title="TypeScript" run theme={null} const page = await fetch(sbx.url).then((r) => r.text()); console.log(page.includes("main.js")); // true: Vite is serving the app const js = await fetch(`${sbx.url}/main.js`).then((r) => r.text()); console.log(js.includes("version 1")); // true ``` ```python title="Python" run theme={null} from urllib.request import urlopen page = urlopen(sbx.url).read().decode() print("main.js" in page) # True: Vite is serving the app js = urlopen(f"{sbx.url}/main.js").read().decode() print("version 1" in js) # True ``` **Anyone with the link now sees the running branch** in their own browser, with live reloading. They do not need to download the code or set anything up. **5. Push a change: the preview updates** When new commits arrive, run `git pull` in the same sandbox. Vite notices the changed files, and any open page reloads by itself. Here we change the file directly to show the effect: ```bash title="CLI" run theme={null} # in your pipeline: fibre exec "$SBX" --cwd /work/app -- git pull echo "document.querySelector(\"#title\").textContent = \"Preview of PR #$PR: version 2\";" \ | fibre exec "$SBX" -i -- sh -c 'cat > /work/app/main.js' sleep 1 curl -s "$URL/main.js" | grep -q "version 2" && echo "version 2: same sandbox, same link, new code" ``` ```typescript title="TypeScript" run theme={null} // in your pipeline: await sbx.run("cd /work/app && git pull") await sbx.files.write("/work/app/main.js", `document.querySelector("#title").textContent = "Preview of PR #${pr}: version 2";`); await new Promise((r) => setTimeout(r, 1000)); const updated = await fetch(`${sbx.url}/main.js`).then((r) => r.text()); console.log(updated.includes("version 2")); // true: same sandbox, same link, new code ``` ```python title="Python" run theme={null} import time # in your pipeline: sbx.run("cd /work/app && git pull") sbx.files.write("/work/app/main.js", f'document.querySelector("#title").textContent = "Preview of PR #{pr}: version 2";') time.sleep(1) updated = urlopen(f"{sbx.url}/main.js").read().decode() print("version 2" in updated) # True: same sandbox, same link, new code ``` ## When the PR closes When the pull request is merged or closed, find its sandbox by label and delete it: ```bash title="CLI" run theme={null} fibre delete $(fibre list --label preview=true --label pr=$PR --json | jq -r '.[].id') ``` ```typescript title="TypeScript" run theme={null} for await (const s of Sandbox.list({ labels: { preview: "true", pr: String(pr) } })) await s.delete(); ``` ```python title="Python" run theme={null} for s in Sandbox.list(labels={"preview": "true", "pr": str(pr)}): s.delete() ``` ## In GitHub Actions In practice, a CI workflow runs these steps for you. This GitHub Actions workflow runs a small script each time a pull request is opened, updated or closed, with your Fibre key stored as a secret: ```yaml title=".github/workflows/preview.yml" theme={null} name: preview on: pull_request: types: [opened, synchronize, closed] jobs: preview: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: 22 } - run: npm install @fibre-dev/sdk - run: node scripts/preview.mjs env: FIBRE_API_KEY: ${{ secrets.FIBRE_API_KEY }} PR: ${{ github.event.pull_request.number }} BRANCH: ${{ github.head_ref }} ACTION: ${{ github.event.action }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` `scripts/preview.mjs` finds the pull request's sandbox by its label and uses the calls from this page. When the pull request is opened, it creates the sandbox and posts the link as a comment. When new commits arrive, it pulls them. When the pull request is closed, it deletes the sandbox. ## Good to know A few things to keep in mind with previews: | | | | - | - | | Dev servers | Listen on `0.0.0.0`, and allow the sandbox's hostname if the framework checks the `Host` header | | Hot reload | Its WebSocket passes through the sandbox's URL | | Sleep | After `idleTimeout` with nobody looking; **an open preview tab keeps it awake** | | Who can open it | Anyone with the link. For private apps, put your own sign-in in front | | Cost | Awake time only: a preview looked at for 15 minutes a day costs 15 minutes a day | ## Related > [card] [Public URLs](/connect/public-urls) > > How a sandbox's public address works. > [card] [Snapshots](/setup/snapshots) > > Start previews with dependencies already installed. # Docker and Compose environments Source: https://docs.fibre.dev/use-cases/docker Run Docker and Docker Compose inside a VM sandbox: a whole stack with a database, a cache and your app, for an agent to work against, for integration tests, or as a dev environment that sleeps with every container up. Real applications depend on other services: a Postgres database, a Redis cache, a message queue. An agent or an integration test is only as useful as the environment it runs against, and **most projects already describe that environment in a Docker Compose file** (`compose.yaml`). A sandbox on the `vm` runtime can run Docker, so it can run that file exactly as it is. This opens up several uses: * **An agent can build a feature against a real database**, instead of a fake one. * **Integration tests can start the whole stack**, run, and throw everything away afterwards. * **A development environment can stay up for days.** It **sleeps with every container still running**, so the next morning the stack is exactly where it was, data included. ## A stack with Postgres, from a compose file **1. A VM sandbox with Docker running** This sandbox starts from Docker's official image and runs the Docker daemon (the background service that manages containers) as its main program. The last line waits until the daemon is ready: ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; const sbx = await Sandbox.create({ image: "docker:27-dind", needs: ["docker"], entrypoint: ["sh", "-c", "dind dockerd > /var/log/dockerd.log 2>&1"], size: "medium", lifetime: 1800, labels: { docs: "compose" }, }); await sbx.run("until docker info > /dev/null 2>&1; do sleep 1; done", { timeout: 120 }); console.log(sbx.runtime); // vm ``` ```python title="Python" run theme={null} from fibre import Sandbox sbx = Sandbox.create( image="docker:27-dind", needs=["docker"], entrypoint=["sh", "-c", "dind dockerd > /var/log/dockerd.log 2>&1"], size="medium", lifetime=1800, labels={"docs": "compose"}, ) sbx.run("until docker info > /dev/null 2>&1; do sleep 1; done", timeout=120) print(sbx.runtime) # vm ``` **2. The project's compose file** In your own project, this file is already in the repository. For this example we write a small one: a Postgres database, with a table and two rows created when it first starts. ```typescript title="TypeScript" run theme={null} await sbx.files.write("/work/compose.yaml", ` services: db: image: postgres:16-alpine environment: POSTGRES_PASSWORD: dev volumes: - ./init.sql:/docker-entrypoint-initdb.d/init.sql healthcheck: test: ["CMD", "pg_isready", "-U", "postgres"] interval: 2s retries: 30 `); await sbx.files.write("/work/init.sql", "CREATE TABLE orders (id serial PRIMARY KEY, item text, qty int);\n" + "INSERT INTO orders (item, qty) VALUES ('widget', 3), ('gadget', 5);\n"); ``` ```python title="Python" run theme={null} sbx.files.write("/work/compose.yaml", """ services: db: image: postgres:16-alpine environment: POSTGRES_PASSWORD: dev volumes: - ./init.sql:/docker-entrypoint-initdb.d/init.sql healthcheck: test: ["CMD", "pg_isready", "-U", "postgres"] interval: 2s retries: 30 """) sbx.files.write("/work/init.sql", "CREATE TABLE orders (id serial PRIMARY KEY, item text, qty int);\n" "INSERT INTO orders (item, qty) VALUES ('widget', 3), ('gadget', 5);\n") ``` **3. Bring it up** Downloading the container images takes longer than an exec allows, so `sbx.run()` runs the command in the background and waits for it. `--wait` makes Docker Compose wait until every service reports that it is healthy. ```typescript title="TypeScript" run theme={null} const up = await sbx.run("cd /work && docker compose up -d --wait", { timeout: 600 }); console.log(up.exitCode); // 0: every service healthy ``` ```python title="Python" run theme={null} up = sbx.run("cd /work && docker compose up -d --wait", timeout=600) print(up.exit_code) # 0: every service healthy ``` **4. Use it** Now the agent, your tests or you yourself can work with the real database: ```typescript title="TypeScript" run theme={null} const query = await sbx.run( `cd /work && docker compose exec -T db psql -U postgres -tAc "SELECT item, qty FROM orders ORDER BY id"`, ); console.log(query.stdout); // widget|3 \n gadget|5 await sbx.run(`cd /work && docker compose exec -T db psql -U postgres -c "INSERT INTO orders (item, qty) VALUES ('doohickey', 7)"`); ``` ```python title="Python" run theme={null} query = sbx.run('cd /work && docker compose exec -T db psql -U postgres -tAc "SELECT item, qty FROM orders ORDER BY id"') print(query.stdout) # widget|3 \n gadget|5 sbx.run("cd /work && docker compose exec -T db psql -U postgres -c \"INSERT INTO orders (item, qty) VALUES ('doohickey', 7)\"") ``` ## It sleeps with the stack running If you leave the sandbox alone, it goes to sleep after its idle timeout. **On the `vm` runtime, sleep keeps every process**: the Docker daemon, the Postgres container, and the database's data both in memory and on disk. The next call finds the stack still running, including the row added above. ```typescript title="TypeScript" norun reason="takes the idle timeout to fall asleep; the sleep page shows the same" theme={null} // … hours later const later = await Sandbox.get(sbx.id); const rows = await later.run(`cd /work && docker compose exec -T db psql -U postgres -tAc "SELECT count(*) FROM orders"`); console.log(rows.stdout); // 3 ``` ```python title="Python" norun reason="takes the idle timeout to fall asleep; the sleep page shows the same" theme={null} # … hours later later = Sandbox.get(sbx.id) rows = later.run('cd /work && docker compose exec -T db psql -U postgres -tAc "SELECT count(*) FROM orders"') print(rows.stdout) # 3 ``` There is no need to run `docker compose up` again after a wake, to reload data, or to wait for health checks. ## Clean up ```typescript title="TypeScript" run theme={null} await sbx.delete(); ``` ```python title="Python" run theme={null} sbx.delete() ``` ## Patterns These are the most common ways to use a Docker sandbox: | Use | How | | - | - | | **Agent with real services** | Install the agent in the same sandbox; it runs `docker compose` itself and tests against the stack | | **Integration tests in CI** | Up, test, delete, from your [CI script](/use-cases/ci); a `large` size for heavy stacks | | **Per-developer dev environment** | One sandbox per developer, `idleTimeout` of an hour, kept until you delete it: it sleeps overnight with everything up | | **Fast starts** | Bring the stack up once, then save the sandbox as a [snapshot](/setup/snapshots): copies start with every container already running | > [!NOTE] > > Docker needs the `vm` runtime, and `needs: ["docker"]` selects it for you. Images are downloaded from public > registries, or from your own private registry once you store a [registry login](/setup/registries). ## Related > [card] [Runtimes](/sandboxes/runtimes) > > What the `vm` runtime adds, and when you need it. > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > What sleep keeps on each runtime. # Evals and RL Source: https://docs.fibre.dev/use-cases/evals Score a model or an agent on many tasks: one identical, isolated environment per episode, all running in parallel, a checker that runs inside each, and the results collected into one table. To find out whether a new prompt, model or agent is actually better, you run it on **many tasks** and score each result. This is called an *eval*. For coding tasks, scoring means **running code**: the model's solution is run against tests it has not seen. Reinforcement learning (RL) is similar: each attempt, called an *episode*, needs a fresh environment in which the model can act. Both need the same thing: **a clean, identical machine for every episode**, many of them at once, with nothing shared between them, so that one episode can never affect another's score. Here is how Fibre provides each part: | Need | Fibre | | - | - | | Identical starting state | Every episode is a copy of one [snapshot](/setup/snapshots) | | No cross-talk | Each episode has its own sandbox | | Throughput | All episodes in parallel | | Untrusted solutions | Run the model's code with [no network](/production/network) | | Cost | Billed per second while each episode runs | ## A small eval This example evaluates three small programming tasks. For each task there is a candidate solution (standing in for what a model would return) and a set of hidden test cases. Every episode runs in its own sandbox, with no network access, and the scores are collected into one table. **1. The environment, once** ```bash title="CLI" run theme={null} ENV=$(fibre create --no-network --lifetime 30m --label eval=docs-demo --json | jq -r .id) fibre exec "$ENV" -i -- sh -c 'mkdir -p /eval && cat > /eval/run.py' <<'PY' import json, sys, importlib.util spec = importlib.util.spec_from_file_location("solution", "/eval/solution.py") solution = importlib.util.module_from_spec(spec); spec.loader.exec_module(solution) cases = json.load(open("/eval/cases.json")) passed = sum(1 for c in cases if solution.solve(*c["input"]) == c["expected"]) print(json.dumps({"passed": passed, "total": len(cases)})) PY fibre snapshot create docs-eval-env --from "$ENV" ``` ```typescript title="TypeScript" run theme={null} import { Sandbox, Snapshot } from "@fibre-dev/sdk"; const env = await Sandbox.create({ network: { block: true }, lifetime: 1800, labels: { eval: "docs-demo" } }); await env.files.write("/eval/run.py", ` import json, sys, importlib.util spec = importlib.util.spec_from_file_location("solution", "/eval/solution.py") solution = importlib.util.module_from_spec(spec); spec.loader.exec_module(solution) cases = json.load(open("/eval/cases.json")) passed = sum(1 for c in cases if solution.solve(*c["input"]) == c["expected"]) print(json.dumps({"passed": passed, "total": len(cases)})) `); await env.snapshot({ name: "docs-eval-env" }); ``` ```python title="Python" run theme={null} from fibre import Sandbox, Snapshot env = Sandbox.create(network={"block": True}, lifetime=1800, labels={"eval": "docs-demo"}) env.files.write("/eval/run.py", """ import json, sys, importlib.util spec = importlib.util.spec_from_file_location("solution", "/eval/solution.py") solution = importlib.util.module_from_spec(spec); spec.loader.exec_module(solution) cases = json.load(open("/eval/cases.json")) passed = sum(1 for c in cases if solution.solve(*c["input"]) == c["expected"]) print(json.dumps({"passed": passed, "total": len(cases)})) """) env.snapshot(name="docs-eval-env") ``` **2. The tasks and the model's answers** ```bash title="CLI" run theme={null} mkdir -p episodes/reverse episodes/fibonacci episodes/palindrome printf 'def solve(s):\n return s[::-1]\n' > episodes/reverse/solution.py echo '[{"input": ["abc"], "expected": "cba"}, {"input": [""], "expected": ""}]' > episodes/reverse/cases.json printf 'def solve(n):\n a, b = 0, 1\n for _ in range(n): a, b = b, a + b\n return a\n' > episodes/fibonacci/solution.py echo '[{"input": [0], "expected": 0}, {"input": [10], "expected": 55}, {"input": [20], "expected": 6765}]' > episodes/fibonacci/cases.json printf 'def solve(s):\n return s == s[::-1]\n' > episodes/palindrome/solution.py # misses case and spaces: should fail one case echo '[{"input": ["racecar"], "expected": true}, {"input": ["Never odd or even"], "expected": true}]' > episodes/palindrome/cases.json ``` ```typescript title="TypeScript" run theme={null} const episodes = [ { task: "reverse a string", solution: "def solve(s):\n return s[::-1]\n", cases: [{ input: ["abc"], expected: "cba" }, { input: [""], expected: "" }], }, { task: "nth fibonacci", solution: "def solve(n):\n a, b = 0, 1\n for _ in range(n): a, b = b, a + b\n return a\n", cases: [{ input: [0], expected: 0 }, { input: [10], expected: 55 }, { input: [20], expected: 6765 }], }, { task: "is a palindrome", solution: "def solve(s):\n return s == s[::-1]\n", // misses case and spaces: should fail one case cases: [{ input: ["racecar"], expected: true }, { input: ["Never odd or even"], expected: true }], }, ]; ``` ```python title="Python" run theme={null} episodes = [ { "task": "reverse a string", "solution": "def solve(s):\n return s[::-1]\n", "cases": [{"input": ["abc"], "expected": "cba"}, {"input": [""], "expected": ""}], }, { "task": "nth fibonacci", "solution": "def solve(n):\n a, b = 0, 1\n for _ in range(n): a, b = b, a + b\n return a\n", "cases": [{"input": [0], "expected": 0}, {"input": [10], "expected": 55}, {"input": [20], "expected": 6765}], }, { "task": "is a palindrome", "solution": "def solve(s):\n return s == s[::-1]\n", # misses case and spaces: should fail one case "cases": [{"input": ["racecar"], "expected": True}, {"input": ["Never odd or even"], "expected": True}], }, ] ``` **3. Run every episode in parallel** ```bash title="CLI" run theme={null} mkdir -p scores for ep in reverse fibonacci palindrome; do ( S=$(fibre create --snapshot docs-eval-env --lifetime 10m --label eval=docs-demo --label episode=$ep --json | jq -r .id) fibre cp episodes/$ep/solution.py "$S:/eval/solution.py" > /dev/null fibre cp episodes/$ep/cases.json "$S:/eval/cases.json" > /dev/null fibre exec "$S" --timeout 60 -- python3 /eval/run.py > scores/$ep.json fibre delete "$S" > /dev/null ) & done wait for ep in reverse fibonacci palindrome; do echo "$ep $(jq -r '"\(.passed) / \(.total)"' scores/$ep.json)"; done # reverse 2 / 2 · fibonacci 3 / 3 · palindrome 1 / 2 jq -s '"score: \((map(.passed) | add) * 100 / (map(.total) | add) | round)%"' -r scores/*.json # score: 86% ``` ```typescript title="TypeScript" run theme={null} const scores = await Promise.all(episodes.map(async (ep, i) => { const sbx = await Sandbox.create({ snapshot: "docs-eval-env", lifetime: 600, labels: { eval: "docs-demo", episode: String(i) } }); try { await sbx.files.write("/eval/solution.py", ep.solution); await sbx.files.write("/eval/cases.json", JSON.stringify(ep.cases)); const r = await sbx.run("python3 /eval/run.py", { timeout: 60 }); return { task: ep.task, ...JSON.parse(r.stdout) }; } finally { await sbx.delete(); } })); console.table(scores); // reverse a string 2 / 2 // nth fibonacci 3 / 3 // is a palindrome 1 / 2 const total = scores.reduce((t, s) => t + s.passed, 0) / scores.reduce((t, s) => t + s.total, 0); console.log(`score: ${(total * 100).toFixed(0)}%`); // score: 86% ``` ```python title="Python" run theme={null} import asyncio import json from fibre import AsyncSandbox async def score(i, ep): async with await AsyncSandbox.create(snapshot="docs-eval-env", lifetime=600, labels={"eval": "docs-demo", "episode": str(i)}) as sbx: await sbx.files.write("/eval/solution.py", ep["solution"]) await sbx.files.write("/eval/cases.json", json.dumps(ep["cases"])) r = await sbx.run("python3 /eval/run.py", timeout=60) return {"task": ep["task"], **json.loads(r.stdout)} async def main(): return await asyncio.gather(*(score(i, ep) for i, ep in enumerate(episodes))) scores = asyncio.run(main()) for s in scores: print(f"{s['task']:20} {s['passed']} / {s['total']}") # reverse a string 2 / 2 # nth fibonacci 3 / 3 # is a palindrome 1 / 2 total = sum(s["passed"] for s in scores) / sum(s["total"] for s in scores) print(f"score: {total:.0%}") # score: 86% ``` **4. Clean up** ```bash title="CLI" run theme={null} fibre snapshot delete docs-eval-env fibre delete "$ENV" rm -rf episodes scores ``` ```typescript title="TypeScript" run theme={null} await (await Snapshot.get("docs-eval-env")).delete(); await env.delete(); ``` ```python title="Python" run theme={null} Snapshot.get("docs-eval-env").delete() env.delete() ``` ## For agents and RL The same approach works for agent benchmarks and RL training runs. Each episode goes through four stages: 1. **It starts from the task's snapshot**: for example a repository at a given commit, a database with data in it, or a desktop with an application open. 2. **The agent acts**: it runs commands, edits files, or uses the browser or [desktop](/connect/desktop), for as many steps as it needs. 3. **A checker scores the result** inside the same sandbox, for example by running hidden tests, comparing the final state, or computing a reward. 4. **The sandbox is deleted**, so the next episode starts from a clean state. Because a sandbox keeps its memory while it sleeps, **a long episode can pause**, for example while it waits for a slow model or for a person to label something, without keeping a machine awake and paid for. ## At scale When you run hundreds or thousands of episodes, keep these points in mind: | | | | - | - | | Hundreds of episodes | Fan out in batches below your plan's sandboxes-at-once; [limits](/production/errors-and-limits#limits) | | Retries | An `Idempotency-Key` per episode, so a retried create never doubles an episode | | Reproducibility | Version the snapshot name (`swe-task-1432-v2`); the same snapshot gives the same start | | Cost | Per second: 500 episodes of 2 minutes on `small` is about 17 hours, **\$0.25** | ## Related > [card] [Snapshots](/setup/snapshots) > > How every episode gets the same starting point. > [card] [Agents in parallel](/use-cases/parallel) > > The same pattern, used for real work instead of scoring. # Use cases Source: https://docs.fibre.dev/use-cases/overview Complete, runnable programs for the jobs developers use Fibre for: code interpreters, coding agents, parallel agents, a sandbox per user, previews, CI, evals and Docker environments. Each page is **one real job, solved end to end**: what you are building, the program that does it, what it costs, and what to change for production. Copy the code, swap in your repo or your model, and run it. > [card] [A code interpreter for your AI app](/use-cases/run-code) > > A model writes Python, a sandbox per conversation runs it, variables and charts come back. **Run commands, files, network.** > [card] [A coding agent on your repo](/use-cases/coding-agent) > > Claude Code fixes a failing test in its own machine; you check the diff before anything leaves. **Commands, keys, sleep.** > [card] [Many agents in parallel](/use-cases/parallel) > > One snapshot, one copy per task, all at once, results collected. **Snapshots, labels.** > [card] [A sandbox per user](/use-cases/sandbox-per-user) > > A workspace for every user of your product, with the monthly cost worked out. **Sleep, labels, lifetime.** > [card] [Preview environments](/use-cases/dev-server) > > A live link for every pull request, updating as code changes. **Public URLs, keep.** > [card] [Tests and CI](/use-cases/ci) > > Run a suite in a clean sandbox from any CI, stream the output, keep failures to debug. **Files, streaming.** > [card] [Evals and RL](/use-cases/evals) > > One identical environment per episode, all in parallel, scored inside. **Snapshots, no network.** > [card] [Docker and Compose environments](/use-cases/docker) > > A whole stack with a database for agents, tests or development, asleep with every container up. **VM runtime.** # Many agents in parallel Source: https://docs.fibre.dev/use-cases/parallel Prepare one sandbox, save it as a snapshot, and fan out: one copy per task, all running at once, each isolated, results collected at the end. For agents on many issues, sharded test suites and batch jobs. Some work splits naturally into many independent pieces: ten issues in the backlog, a hundred files to migrate, a test suite that takes an hour on one machine. Doing them one after another is slow. **Run them side by side instead**, with one sandbox per task. Each sandbox has its own files and processes, so whatever one task does can never interfere with another. It always follows the same four steps: 1. **Prepare once.** Set up one sandbox with the repository, its dependencies and the agent. 2. **Save it as a [snapshot](/setup/snapshots).** Every sandbox created from it starts exactly where it was. 3. **Fan out.** Create one sandbox per task from the snapshot, all at the same time. 4. **Collect the results.** Read each sandbox's result, keep what is good, and delete the rest. ## Fan out This example runs three tasks in parallel. To keep it short and free to run, each task is a simple stand-in for what an agent would do: it makes a small change to a file and runs a check to prove it worked. The next section shows how to put a real agent in its place. **1. Prepare the base and save it** ```bash title="CLI" run theme={null} BASE=$(fibre create --lifetime 30m --label batch=docs-fanout --json | jq -r .id) printf "def greet(name):\n return 'Hello ' + name\n" | fibre exec "$BASE" -i -- sh -c 'mkdir -p /work/repo && cat > /work/repo/greet.py' fibre exec "$BASE" --cwd /work/repo -- 'git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm base' # in your project: clone, install dependencies, install the agent here: done once for every task fibre snapshot create docs-fanout-base --from "$BASE" ``` ```typescript title="TypeScript" run theme={null} import { Sandbox, Snapshot } from "@fibre-dev/sdk"; const base = await Sandbox.create({ lifetime: 1800, labels: { batch: "docs-fanout" } }); await base.files.write("/work/repo/greet.py", "def greet(name):\n return 'Hello ' + name\n"); await base.run("cd /work/repo && git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm base"); // in your project: clone, install dependencies, install the agent here: done once for every task await base.snapshot({ name: "docs-fanout-base" }); ``` ```python title="Python" run theme={null} from fibre import Sandbox, Snapshot base = Sandbox.create(lifetime=1800, labels={"batch": "docs-fanout"}) base.files.write("/work/repo/greet.py", "def greet(name):\n return 'Hello ' + name\n") base.run("cd /work/repo && git init -q && git add . && git -c user.name=dev -c user.email=dev@example.com commit -qm base") # in your project: clone, install dependencies, install the agent here: done once for every task base.snapshot(name="docs-fanout-base") ``` **2. One copy per task, all at once** ```bash title="CLI" run theme={null} for task in "task-1:s/Hello/Hi/" "task-2:s/Hello/Hey/" "task-3:s/Hello/Good morning,/"; do ( id=${task%%:*} change=${task#*:} S=$(fibre create --snapshot docs-fanout-base --lifetime 30m --label batch=docs-fanout --label task=$id --json | jq -r .id) # the agent's work goes here, e.g. claude -p "$TASK" (see the coding agent use case) fibre exec "$S" --cwd /work/repo -- sed -i "$change" greet.py echo "$id $S $(fibre exec "$S" --cwd /work/repo -- python3 -c "from greet import greet; print(greet('Ada'))")" ) & done wait # task-1 sbx-… Hi Ada · task-2 sbx-… Hey Ada · task-3 sbx-… Good morning, Ada ``` ```typescript title="TypeScript" run theme={null} const tasks = [ { id: "task-1", change: "s/Hello/Hi/" }, { id: "task-2", change: "s/Hello/Hey/" }, { id: "task-3", change: "s/Hello/Good morning,/" }, ]; const results = await Promise.all(tasks.map(async (task) => { const sbx = await Sandbox.create({ snapshot: "docs-fanout-base", lifetime: 1800, labels: { batch: "docs-fanout", task: task.id }, }); // the agent's work goes here, e.g. claude -p "$TASK" (see the coding agent use case) await sbx.run(`cd /work/repo && sed -i "${task.change}" greet.py`); const check = await sbx.run(`cd /work/repo && python3 -c "from greet import greet; print(greet('Ada'))"`); const diff = await sbx.run("cd /work/repo && git diff --stat"); return { task: task.id, sandbox: sbx.id, output: check.stdout.trim(), diff: diff.stdout.trim() }; })); console.table(results); // task-1 sbx-… Hi Ada 1 file changed, 1 insertion(+), 1 deletion(-) // task-2 sbx-… Hey Ada … // task-3 sbx-… Good morning, Ada … ``` ```python title="Python" run theme={null} import asyncio from fibre import AsyncSandbox tasks = [ {"id": "task-1", "change": "s/Hello/Hi/"}, {"id": "task-2", "change": "s/Hello/Hey/"}, {"id": "task-3", "change": "s/Hello/Good morning,/"}, ] async def work(task): sbx = await AsyncSandbox.create(snapshot="docs-fanout-base", lifetime=1800, labels={"batch": "docs-fanout", "task": task["id"]}) # the agent's work goes here, e.g. claude -p "$TASK" (see the coding agent use case) await sbx.run(f'cd /work/repo && sed -i "{task["change"]}" greet.py') check = await sbx.run("cd /work/repo && python3 -c \"from greet import greet; print(greet('Ada'))\"") diff = await sbx.run("cd /work/repo && git diff --stat") return {"task": task["id"], "sandbox": sbx.id, "output": check.stdout.strip(), "diff": diff.stdout.strip()} async def main(): return await asyncio.gather(*(work(t) for t in tasks)) for r in asyncio.run(main()): print(r["task"], r["sandbox"], r["output"], r["diff"], sep=" ") # task-1 sbx-… Hi Ada 1 file changed, 1 insertion(+), 1 deletion(-) # task-2 sbx-… Hey Ada … # task-3 sbx-… Good morning, Ada … ``` Each sandbox started with the repository already in place: **none of them had to clone or install anything.** **3. Collect, then clean up** Keep the sandboxes whose work you want to review. They sleep while you read, and cost nothing for compute. Delete the others. This example deletes all of them, then the snapshot, then the sandbox it was made from: ```bash title="CLI" run theme={null} for s in $(fibre list --label batch=docs-fanout --json | jq -r --arg base "$BASE" '.[] | select(.id != $base) | .id'); do fibre delete "$s" done fibre snapshot delete docs-fanout-base fibre delete "$BASE" ``` ```typescript title="TypeScript" run theme={null} for await (const s of Sandbox.list({ labels: { batch: "docs-fanout" } })) { if (s.id !== base.id) await s.delete(); } await (await Snapshot.get("docs-fanout-base")).delete(); await base.delete(); ``` ```python title="Python" run theme={null} for s in Sandbox.list(labels={"batch": "docs-fanout"}): if s.id != base.id: s.delete() Snapshot.get("docs-fanout-base").delete() base.delete() ``` ## With a real agent To use a real agent, replace the stand-in with the agent's command. The rest of the code stays the same. Here, Claude Code works on three issues at once, each in its own sandbox, and commits its fix to a branch: ```bash title="CLI" norun reason="needs your Anthropic API key" theme={null} for issue in "#101 login fails on Safari" "#102 export ignores filters" "#103 typo in onboarding email"; do ( S=$(fibre create --snapshot my-repo-with-agent --label batch=issues --label issue="${issue:1:3}" --json | jq -r .id) fibre exec "$S" --timeout 1h --env ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" --env TASK="Fix $issue. Run the tests." \ -- 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash"' fibre exec "$S" --cwd /work/repo -- "git checkout -b fix/${issue:1:3} && git commit -qam 'Fix $issue'" ) & done wait ``` ```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null} const issues = ["#101 login fails on Safari", "#102 export ignores filters", "#103 typo in onboarding email"]; await Promise.all(issues.map(async (issue) => { const sbx = await Sandbox.create({ snapshot: "my-repo-with-agent", labels: { batch: "issues", issue } }); await sbx.run( ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash"'], { env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY!, TASK: `Fix ${issue}. Run the tests.` }, timeout: 3600 }, ); await sbx.run(`cd /work/repo && git checkout -b fix/${issue.slice(1, 4)} && git commit -qam "Fix ${issue}"`); })); ``` ```python title="Python" norun reason="needs your Anthropic API key" theme={null} import asyncio import os from fibre import AsyncSandbox issues = ["#101 login fails on Safari", "#102 export ignores filters", "#103 typo in onboarding email"] async def fix(issue): sbx = await AsyncSandbox.create(snapshot="my-repo-with-agent", labels={"batch": "issues", "issue": issue}) await sbx.run( ["sh", "-c", 'cd /work/repo && ~/.local/bin/claude -p "$TASK" --allowedTools "Read,Edit,Bash"'], env={"ANTHROPIC_API_KEY": os.environ["ANTHROPIC_API_KEY"], "TASK": f"Fix {issue}. Run the tests."}, timeout=3600, ) await sbx.run(f'cd /work/repo && git checkout -b fix/{issue[1:4]} && git commit -qam "Fix {issue}"') async def main(): await asyncio.gather(*(fix(i) for i in issues)) asyncio.run(main()) ``` ## Sharding a test suite The same approach speeds up a slow test suite. Split the tests into parts (called *shards*), and run each part in its own sandbox at the same time. The suite then takes about as long as its slowest part: ```bash title="CLI" norun reason="needs your own repo and test runner" theme={null} SHARDS=8 for i in $(seq 1 $SHARDS); do fibre run --rm --snapshot my-repo-ready --label ci=run-4711 --cwd /work/repo -- npx vitest run --shard=$i/$SHARDS & done FAILED=0 for job in $(jobs -p); do wait "$job" || FAILED=1; done exit $FAILED ``` ```typescript title="TypeScript" norun reason="needs your own repo and test runner" theme={null} const shards = 8; const runs = await Promise.all(Array.from({ length: shards }, async (_, i) => { const sbx = await Sandbox.create({ snapshot: "my-repo-ready", labels: { ci: "run-4711" } }); const r = await sbx.run(`cd /work/repo && npx vitest run --shard=${i + 1}/${shards}`, { timeout: 1800 }); await sbx.delete(); return r.exitCode; })); process.exit(runs.every((code) => code === 0) ? 0 : 1); ``` ```python title="Python" norun reason="needs your own repo and test runner" theme={null} import sys from concurrent.futures import ThreadPoolExecutor from fibre import Sandbox shards = 8 def shard(i): with Sandbox.create(snapshot="my-repo-ready", labels={"ci": "run-4711"}) as sbx: return sbx.run(f"cd /work/repo && npx vitest run --shard={i + 1}/{shards}", timeout=1800).exit_code with ThreadPoolExecutor(shards) as pool: codes = list(pool.map(shard, range(shards))) sys.exit(0 if all(code == 0 for code in codes) else 1) ``` ## Limits to keep in mind When you start many sandboxes at once, keep your plan's limits in mind: | | | | - | - | | Sandboxes kept | By plan: 100 to 2,000, awake or asleep. Delete each copy when its task is done; above the number a create is refused | | Starts a day | By plan: 200 to 2,400, then \$0.03 each | | Retries | Give each create an `Idempotency-Key` per task, so a retry never starts a second copy | [Errors, retries and limits](/production/errors-and-limits) explains every limit in detail. ## Related > [card] [Snapshots](/setup/snapshots) > > What a new sandbox takes from its snapshot. > [card] [A coding agent on your repo](/use-cases/coding-agent) > > The single-task version of this page, step by step. # A code interpreter for your AI app Source: https://docs.fibre.dev/use-cases/run-code Let a model write Python and run it safely: one sandbox per conversation, packages installed once, variables kept between turns, charts and files returned to your app. Imagine your users asking questions about their own data, such as *"which region grew fastest last quarter?"*. A language model gives much better answers when it can **write code and run it**: it calculates the answer instead of guessing, and it can draw a chart to show it. This is often called a *code interpreter*. The code the model writes should never run on your own servers, because you cannot know in advance what it will do. Instead, **give each conversation its own sandbox.** The model's code runs there, next to the user's files, and nothing it does can reach your systems or any other user. This page builds a working code interpreter, step by step, and then connects it to a model. ```mermaid theme={null} sequenceDiagram participant U as User participant A as Your app participant M as Model participant S as Sandbox (one per conversation) U->>A: "Which region grew fastest?" A->>M: question + run_python tool M->>A: run_python(code) A->>S: run the code S->>A: output, chart.png A->>M: the output M->>A: "South grew 38%." + chart A->>U: answer and chart ``` ## What you build The interpreter is made of a few simple pieces: | Piece | How | | - | - | | One sandbox per conversation | Create on the first message, find it again by label on the next | | Packages ready | Install once per sandbox (or start from a [snapshot](/setup/snapshots) with them installed) | | **State between turns** | A Python process that stays alive, so `df` defined in turn 1 is still there in turn 3 | | Charts and files | The code saves to `/work/out`; your app reads them back | | Safety | Only PyPI reachable, a short idle timeout, a lifetime that ends forgotten conversations | ## The interpreter **1. A sandbox for the conversation** First, a function that returns the sandbox for a conversation, creating it the first time. The conversation's ID is stored as a label, so the next message finds the same sandbox again. **The sandbox goes to sleep two minutes after the last message**, and wakes up with everything still in memory when the user writes again. Its network only allows installing Python packages, so the code cannot send data anywhere else. ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; async function sandboxFor(conversationId: string): Promise { for await (const s of Sandbox.list({ labels: { conversation: conversationId } })) return s; return Sandbox.create({ labels: { app: "analyst", conversation: conversationId }, network: { allow: ["pypi.org", "files.pythonhosted.org"] }, // installs only: nowhere to send data idleTimeout: 120, lifetime: 86400, }); } const sbx = await sandboxFor("conv-1234"); ``` ```python title="Python" run theme={null} from fibre import Sandbox def sandbox_for(conversation_id: str) -> Sandbox: for s in Sandbox.list(labels={"conversation": conversation_id}): return s return Sandbox.create( labels={"app": "analyst", "conversation": conversation_id}, network={"allow": ["pypi.org", "files.pythonhosted.org"]}, # installs only: nowhere to send data idle_timeout=120, lifetime=86400, ) sbx = sandbox_for("conv-1234") ``` **2. A Python process that keeps its variables** Next, the part that remembers variables between turns. If every piece of code ran as a separate program, a variable created in one turn would be gone in the next. So instead we start **one long-running Python process** (a *kernel*) and send it each piece of code, called a *cell*, as the conversation goes on. This kernel is deliberately tiny. It reads a cell from its standard input, runs it in the same namespace as every earlier cell, and prints a marker when it has finished, so we know when to stop reading its output: ```typescript title="TypeScript" run theme={null} await sbx.run( "python3 -m venv /work/.venv && /work/.venv/bin/pip install -q pandas matplotlib", { timeout: 600 }, ); await sbx.files.write("/work/kernel.py", ` import sys, traceback, matplotlib matplotlib.use("Agg") namespace = {} buffer = [] for line in sys.stdin: if line.strip() != "#--END--": buffer.append(line); continue try: exec("".join(buffer), namespace) except Exception: traceback.print_exc(file=sys.stdout) buffer = [] print("#--DONE--", flush=True) `); const kernel = await sbx.spawn(["/work/.venv/bin/python", "-u", "/work/kernel.py"], { cwd: "/work", stdin: true }); ``` ```python title="Python" run theme={null} sbx.run("python3 -m venv /work/.venv && /work/.venv/bin/pip install -q pandas matplotlib", timeout=600) sbx.files.write("/work/kernel.py", """ import sys, traceback, matplotlib matplotlib.use("Agg") namespace = {} buffer = [] for line in sys.stdin: if line.strip() != "#--END--": buffer.append(line); continue try: exec("".join(buffer), namespace) except Exception: traceback.print_exc(file=sys.stdout) buffer = [] print("#--DONE--", flush=True) """) kernel = sbx.spawn(["/work/.venv/bin/python", "-u", "/work/kernel.py"], cwd="/work", stdin=True) ``` **3. Run a cell, collect output and charts** ```typescript title="TypeScript" run theme={null} let seen = 0; async function runCell(code: string): Promise<{ output: string; files: string[] }> { await sbx.run("mkdir -p /work/out && rm -f /work/out/*"); await kernel.write(code + "\n#--END--\n"); let output = ""; for await (const chunk of kernel.output()) { output += chunk.data; if (output.includes("#--DONE--", seen)) break; } const fresh = output.slice(seen).replace("#--DONE--\n", ""); seen = output.length; const { entries } = await sbx.files.list("/work/out"); return { output: fresh, files: entries.map((e) => `/work/out/${e.name}`) }; } ``` ```python title="Python" run theme={null} seen = 0 def run_cell(code: str) -> dict: global seen sbx.run("mkdir -p /work/out && rm -f /work/out/*") kernel.write(code + "\n#--END--\n") output = "" for chunk in kernel.output(): output += chunk.data if output.find("#--DONE--", seen) >= 0: break fresh = output[seen:].replace("#--DONE--\n", "") seen = len(output) entries = sbx.files.list("/work/out")["entries"] return {"output": fresh, "files": [f"/work/out/{e['name']}" for e in entries]} ``` **4. Try it with what a model would write** Here are two cells like the ones a model would write. The first loads the data into a table called `df`. **The second uses `df` without loading it again**, because the kernel remembers it, and saves a chart to `/work/out`. ```typescript title="TypeScript" run theme={null} await sbx.files.write("/work/sales.csv", "quarter,region,revenue\nQ1,north,120\nQ1,south,90\nQ1,west,70\nQ2,north,130\nQ2,south,124\nQ2,west,72\n"); const turn1 = await runCell(` import pandas as pd df = pd.read_csv("/work/sales.csv") print(df.groupby("region").revenue.sum().to_string()) `); console.log(turn1.output); // north 250 // south 214 // west 142 const turn2 = await runCell(` growth = df.pivot(index="region", columns="quarter", values="revenue") growth["pct"] = (growth.Q2 / growth.Q1 - 1) * 100 print(growth.pct.round(1).sort_values(ascending=False).to_string()) ax = growth[["Q1", "Q2"]].plot.bar(title="Revenue by region") ax.figure.savefig("/work/out/growth.png") `); console.log(turn2.output); // south 37.8 // north 8.3 // west 2.9 console.log(turn2.files); // [ '/work/out/growth.png' ] const png = await sbx.files.readBytes(turn2.files[0]); console.log(`chart: ${png.byteLength} bytes`); // send it to the user ``` ```python title="Python" run theme={null} sbx.files.write("/work/sales.csv", "quarter,region,revenue\nQ1,north,120\nQ1,south,90\nQ1,west,70\nQ2,north,130\nQ2,south,124\nQ2,west,72\n") turn1 = run_cell(""" import pandas as pd df = pd.read_csv("/work/sales.csv") print(df.groupby("region").revenue.sum().to_string()) """) print(turn1["output"]) # north 250 # south 214 # west 142 turn2 = run_cell(""" growth = df.pivot(index="region", columns="quarter", values="revenue") growth["pct"] = (growth.Q2 / growth.Q1 - 1) * 100 print(growth.pct.round(1).sort_values(ascending=False).to_string()) ax = growth[["Q1", "Q2"]].plot.bar(title="Revenue by region") ax.figure.savefig("/work/out/growth.png") """) print(turn2["output"]) # south 37.8 # north 8.3 # west 2.9 print(turn2["files"]) # ['/work/out/growth.png'] png = sbx.files.read_bytes(turn2["files"][0]) print(f"chart: {len(png)} bytes") # send it to the user ``` ## Connect a model To connect a model, give it one tool, `run_python`, and run whatever code it sends through `runCell`. The loop keeps going until the model answers without asking to run more code. Here it is with the Anthropic SDK: ```typescript title="TypeScript" norun reason="needs your Anthropic API key" theme={null} import Anthropic from "@anthropic-ai/sdk"; const anthropic = new Anthropic(); const tools = [{ name: "run_python", description: "Run Python in a persistent session. pandas and matplotlib are installed. /work/sales.csv holds the user's data. Save charts to /work/out.", input_schema: { type: "object", properties: { code: { type: "string" } }, required: ["code"] }, }]; const messages: any[] = [{ role: "user", content: "Which region grew fastest from Q1 to Q2? Show a chart." }]; for (;;) { const reply = await anthropic.messages.create({ model: "claude-opus-5-5", max_tokens: 2048, tools, messages }); messages.push({ role: "assistant", content: reply.content }); const calls = reply.content.filter((b) => b.type === "tool_use"); if (calls.length === 0) break; // the model has its answer const results = []; for (const call of calls) { const { output, files } = await runCell((call.input as any).code); results.push({ type: "tool_result", tool_use_id: call.id, content: output + (files.length ? `\nfiles: ${files}` : "") }); } messages.push({ role: "user", content: results }); } ``` ```python title="Python" norun reason="needs your Anthropic API key" theme={null} import anthropic client = anthropic.Anthropic() tools = [{ "name": "run_python", "description": "Run Python in a persistent session. pandas and matplotlib are installed. /work/sales.csv holds the user's data. Save charts to /work/out.", "input_schema": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]}, }] messages = [{"role": "user", "content": "Which region grew fastest from Q1 to Q2? Show a chart."}] while True: reply = client.messages.create(model="claude-opus-5-5", max_tokens=2048, tools=tools, messages=messages) messages.append({"role": "assistant", "content": reply.content}) calls = [b for b in reply.content if b.type == "tool_use"] if not calls: break # the model has its answer results = [] for call in calls: cell = run_cell(call.input["code"]) files = f"\nfiles: {cell['files']}" if cell["files"] else "" results.append({"type": "tool_result", "tool_use_id": call.id, "content": cell["output"] + files}) messages.append({"role": "user", "content": results}) ``` ## Clean up ```typescript title="TypeScript" run theme={null} await kernel.kill(); await sbx.delete(); ``` ```python title="Python" run theme={null} kernel.kill() sbx.delete() ``` In a real app, **there is no need to delete the sandbox after each answer.** It sleeps between turns and costs nothing for compute while it does. Let its lifetime end it, or delete it when the user deletes the conversation. ## What it costs Take a conversation with 6 turns, each running for 5 seconds on the `small` size. The sandbox is awake for about **30 seconds** in total, plus the time it takes to install packages once. At \$0.015 an hour, that is a fraction of a cent per conversation. If you start from a [snapshot](/setup/snapshots) with pandas already installed, the install time disappears too. ## Make it production-ready A few improvements take this from an example to a product: * **Make the kernel a snapshot.** Save a sandbox with the packages installed and the kernel already running. Each conversation then starts from it, ready in seconds. * **Upload the user's files** with the [files API](/sandboxes/files) before the first turn. * **Limit how long each cell can run.** If a cell takes too long, stop the kernel with `kill()` and start a fresh one. * **Send the charts back to the model** as well as to the user, so the model can describe its own chart. ## Related > [card] [Run commands](/sandboxes/running-commands) > > `spawn`, standard input and streaming output, all used above. > [card] [Network access](/production/network) > > How the sandbox is limited to installing packages, and nothing else. # A sandbox per user Source: https://docs.fibre.dev/use-cases/sandbox-per-user Give every user of your product their own sandbox: a workspace for their agent, their files and their running app. Three patterns with their monthly costs, the code to find or create a user's sandbox, and what to do when users come and go. Many products give **each user a machine of their own**: an AI app builder, a coding assistant, a notebook, or an agent that works on the user's files. Products like these have three needs in common: * **Each user's code must be kept apart** from everyone else's. * **A user's work must still be there** when they come back tomorrow. * **The bill must not grow because of users who are not active** right now. This page shows how to meet all three with Fibre, and what it costs. ## Three patterns There are three common ways to give users sandboxes. The first one suits almost every product: | Pattern | How it works | A user costs, per month | Use it when | | - | - | - | - | | **Sleep between turns** (Fibre's default) | One sandbox per user. It sleeps a few minutes after the last action and wakes on the next | **Only their active minutes**: 20 hours of use on `default` is **\$0.60** | Almost always | | Always on | `idle_timeout_sec: 0`. Never sleeps | 730 hours on `medium`: **\$21.90** | Bots, workers, apps that must answer in milliseconds | | One sandbox per task | A fresh copy of a snapshot per request, deleted after | Each task's seconds | Stateless jobs: code execution, file conversion | **With sleep, inactive users cost nothing for compute.** You do not need to write any code to stop and start sandboxes: a request to a sleeping sandbox wakes it, with the user's programs and memory exactly as they left them. ## Find or create a user's sandbox Each time a user does something, your app needs their sandbox. You do not need to store sandbox IDs in your own database for this: **label each sandbox with the user's ID**, and look it up by that label. If the user does not have a sandbox yet, create one. It is kept until you delete it, so it is there whenever the user comes back: ```bash title="CLI" run theme={null} sandbox_for_user() { local id id=$(fibre list --label app=builder --label user="$1" --json | jq -r '.[0].id // empty') if [ -n "$id" ]; then echo "$id" else fibre create --label app=builder --label user="$1" --idle-timeout 5m --port 3000 --json | jq -r .id fi } FIRST=$(sandbox_for_user user-42) AGAIN=$(sandbox_for_user user-42) [ "$FIRST" = "$AGAIN" ] && echo "the same sandbox on every visit" ``` ```typescript title="TypeScript" run theme={null} import { Sandbox } from "@fibre-dev/sdk"; async function sandboxForUser(userId: string): Promise { for await (const existing of Sandbox.list({ labels: { app: "builder", user: userId } })) { return existing; } return Sandbox.create({ labels: { app: "builder", user: userId }, idleTimeout: 300, // sleep 5 minutes after the last action exposedPort: 3000, // the user's app, at the sandbox's URL }); } const first = await sandboxForUser("user-42"); const again = await sandboxForUser("user-42"); console.log(first.id === again.id); // true: the same sandbox on every visit ``` ```python title="Python" run theme={null} from fibre import Sandbox def sandbox_for_user(user_id: str) -> Sandbox: for existing in Sandbox.list(labels={"app": "builder", "user": user_id}): return existing return Sandbox.create( labels={"app": "builder", "user": user_id}, idle_timeout=300, # sleep 5 minutes after the last action exposed_port=3000, # the user's app, at the sandbox's URL ) first = sandbox_for_user("user-42") again = sandbox_for_user("user-42") print(first.id == again.id) # True: the same sandbox on every visit ``` There is one subtle case. If two requests for a brand-new user arrive at the same moment, both might find no sandbox and both might create one. To prevent that, send an **idempotency key based on the user's ID**. Both requests then get the same sandbox: ```typescript title="TypeScript" norun reason="shows the header option on a raw call" theme={null} await fibre.json("POST", "/v1/sandboxes", { body: { labels: { app: "builder", user: userId }, idle_timeout_sec: 300 }, headers: { "Idempotency-Key": `builder-user-${userId}` }, }); ``` ```python title="Python" norun reason="shows the header option on a raw call" theme={null} fibre.json( "POST", "/v1/sandboxes", json={"labels": {"app": "builder", "user": user_id}, "idle_timeout_sec": 300}, headers={"Idempotency-Key": f"builder-user-{user_id}"}, ) ``` ## Start every user ready A new user should not have to wait for `npm install` to finish before they can start. Prepare one sandbox with your stack, save it as a [snapshot](/setup/snapshots), and create every user's sandbox from it. **Each one then starts with the dependencies installed and your development server already running:** ```bash title="CLI" norun reason="needs your own snapshot" theme={null} fibre create --snapshot builder-stack-v3 --label app=builder --label user="$1" --json | jq -r .id ``` ```typescript title="TypeScript" norun reason="needs your own snapshot" theme={null} return Sandbox.create({ snapshot: "builder-stack-v3", labels: { app: "builder", user: userId } }); ``` ```python title="Python" norun reason="needs your own snapshot" theme={null} return Sandbox.create(snapshot="builder-stack-v3", labels={"app": "builder", "user": user_id}) ``` ## Show the user their app If you create the sandbox with `exposedPort`, whatever the user's app serves on that port is available at the sandbox's `url`. You can show it in a frame next to your chat, or simply give the user the link. **A visit wakes a sleeping sandbox**, so the preview still works after the user has been away. See [public URLs](/connect/public-urls). ## When users come and go Here is what to do, or not do, as users come and go: | Event | Do | | - | - | | User returns after an hour | Nothing: the next call wakes their sandbox as they left it | | User returns after a week | Nothing: their sandbox is kept until you delete it | | User inactive for good | It sleeps, and only its storage is billed. Delete it when your product decides the user has gone, such as when they close their account | | User deletes their project | Delete the sandbox. **Only on an explicit action**, never on a timer | | You ship a new stack | New users start from the new snapshot; offer existing users a "rebuild" that creates a fresh sandbox | > [!TIP] > > **Keep a copy of the user's important work outside the sandbox as well.** Push their code to a repository, or copy > important files out with the [files API](/sandboxes/files) when a session ends. A sandbox is a workspace, not a > backup. ## Clean up ```bash title="CLI" run theme={null} fibre delete "$FIRST" ``` ```typescript title="TypeScript" run theme={null} await first.delete(); ``` ```python title="Python" run theme={null} first.delete() ``` ## What it costs, worked through Here is an example with real numbers: 1,000 users on the `medium` size, each active for 30 minutes a day, on 20 days a month. | | | | - | - | | Awake hours | 1,000 × 0.5 × 20 = 10,000 | | Compute | 10,000 × $0.030 = **$300 a month\*\* | | The same users, always on | 1,000 × 730 × $0.030 = $21,900 a month | The only difference between those two lines is sleep. See [pricing](/get-started/pricing) for all the prices. ## Related > [card] [Sleep and wake](/sandboxes/sleep-and-wake) > > What a sleeping sandbox keeps, and what wakes it. > [card] [A key for one sandbox](/get-started/api-keys#a-key-for-one-sandbox) > > Let the user's agent manage its own sandbox, and nothing else.