> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> 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](https://docs.fibre.dev/sandboxes/overview.md).

## 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](https://docs.fibre.dev/sandboxes/running-commands.md).

## 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](https://docs.fibre.dev/sandboxes/files.md).

## 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](https://docs.fibre.dev/connect/public-urls.md).

## 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](https://docs.fibre.dev/setup/snapshots.md), including [what they cost](https://docs.fibre.dev/setup/snapshots.md#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](https://docs.fibre.dev/connect/browser.md) and [desktop](https://docs.fibre.dev/connect/desktop.md).

## 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](https://docs.fibre.dev/production/secrets.md).

## 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](https://docs.fibre.dev/production/errors-and-limits.md).

## 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<string, { per_hour: number }> }>("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` |


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