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

# 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](https://docs.fibre.dev/get-started/pricing.md#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](https://docs.fibre.dev/sandboxes/running-commands.md)
>
> Run the code you just put in, and watch its output live.

> [card] [Create and configure](https://docs.fibre.dev/sandboxes/overview.md)
>
> A sandbox's size decides how much disk space it has.


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