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

# Python SDK

> Programmatic access to boxd machines from Python, sync and async.

The `boxd` package gives you programmatic access to the full boxd API. Create and manage machines, run commands in them, stream output, move files, and manage proxies, snapshots, disks, domains, env vars, and secrets. It talks to the same API as the [CLI](https://docs.boxd.sh/cli/commands.md), so everything you can do from the terminal you can do from Python.

Requires Python 3.10+.

## Installation

```bash pip theme={"theme":"github-dark"}
pip install boxd
```

```bash uv theme={"theme":"github-dark"}
uv add boxd
```

The SDK prints a one-time note on stderr when a newer release is available. It never causes a request to fail. The installed version is available as `boxd.__version__`.

## Authentication

```python theme={"theme":"github-dark"}
Boxd(api_key="bxd_...")   # recommended
Boxd(token="...")         # a token you already hold
Boxd()                    # BOXD_TOKEN, then BOXD_API_KEY
```

Credentials are resolved in this order, first match wins:

1. An explicit `token`.
2. An explicit `api_key`.
3. `BOXD_TOKEN`.
4. `BOXD_API_KEY`.
5. Automatic, inside a boxd machine (below).

If none of those produce a credential, the first request raises `AuthenticationError`.

Mint a key with `boxd auth keys create NAME` (see the [CLI](https://docs.boxd.sh/cli/authentication.md#api-keys)), in the [console](https://app.boxd.sh), or with [`boxd.api_keys.create()`](#api-keys). An API key is exchanged for a short-lived session and kept fresh for you. Revoking a key takes effect immediately, so if a key is revoked mid-run the next call raises `AuthenticationError` rather than retrying.

### Inside a machine

Inside a boxd machine, `Boxd()` authenticates automatically, with neither an API key nor configuration:

```python theme={"theme":"github-dark"}
boxd = Boxd()
for machine in boxd.machines.list():
    print(machine.name, machine.status)
```

It also targets the cluster the surrounding machine belongs to, so the same code runs unchanged wherever it is deployed. An explicit `base_url` or credential still wins.

> [!WARNING]
>
> Inside a **shared** machine the SDK can manage the organization's shared machines, but it cannot read env vars or secrets, and cannot reach machines that are private to another member. Pass an API key for those.

### The client

```python theme={"theme":"github-dark"}
Boxd()                                            # production
Boxd(api_key="bxd_...")
Boxd(region="nyc")                                # machines, snapshots and disks in New York
Boxd(base_url="https://boxd.example.com:9443")    # any other cluster
```

> [!NOTE]
>
> `base_url` selects the cluster. `region` selects where machines, snapshots and disks go within it. See [Regions](#regions).

| Argument | Environment variable | Default |
| - | - | - |
| `api_key` | `BOXD_API_KEY` | none |
| `token` | `BOXD_TOKEN` | none |
| `base_url` | `BOXD_BASE_URL` (or the deprecated `BOXD_API_URL`) | `https://boxd.sh:9443` |
| `region` | `BOXD_REGION` | the region `base_url` serves, Frankfurt for production |
| `timeout` | none | 60 seconds |
| `max_retries` | none | 2 |

Timeouts are in seconds throughout this SDK: the client `timeout`, the `exec` `timeout`, and `wait_until_ready`. Idle timeouts such as `auto_suspend_timeout` are in seconds too.

All arguments are keyword-only. `base_url` accepts an optional scheme that controls TLS:

| Value | Transport |
| - | - |
| `http://host:port` | plaintext |
| `https://host:port` | TLS |
| bare `host:port` | TLS, except `localhost` / `127.*` |

Failed connections are retried up to `max_retries` times with exponential backoff. Timeouts are never retried, because the request may already have been applied, and authentication failures are never retried either.

The client holds a connection, so keep one around rather than making a new one per call. Close it when you're done, or use it as a context manager:

```python theme={"theme":"github-dark"}
with Boxd(api_key="bxd_...") as boxd:
    ...
```

### Sync and async

`Boxd` and `AsyncBoxd` are two top-level classes with the same surface: same namespaces, same method names, same arguments. Switching is `await` and an import rather than a rewrite. The streaming surfaces differ in shape, since `stream_exec` returns an `AsyncExecStream` you drive with `async for` and awaited `write`/`resize` calls, and `logs` is an async generator.

```python theme={"theme":"github-dark"}
from boxd import AsyncBoxd

async with AsyncBoxd(api_key="bxd_...") as boxd:
    machine = await boxd.machines.create("myapp")
    result = await boxd.machines.exec(machine.id, "echo hello")
```

Use `AsyncBoxd` when you already have an event loop (FastAPI, asyncio scripts, anyio). Use `Boxd` everywhere else: scripts, notebooks, Django views.

| | `Boxd` | `AsyncBoxd` |
| - | - | - |
| Call style | `boxd.machines.create(...)` | `await boxd.machines.create(...)` |
| Context manager | `with` | `async with` |
| Best for | scripts, CLIs, notebooks | FastAPI, async workers, concurrent fan-out |

## Commands

Every call is **`boxd.<namespace>.<verb>(...)`**, and eleven namespaces hold the whole surface:

| Namespace | For |
| - | - |
| `boxd.machines` | machines, plus `.files`, `.ports`, `.proxies`, `.checkpoints`, `.backups`, `.computer` |
| `boxd.snapshots` | reusable point-in-time captures |
| `boxd.disks` | persistent disks |
| `boxd.env` | environment variables |
| `boxd.secrets` | secrets (write-only values) |
| `boxd.domains` | custom domains bound to machines |
| `boxd.orgs` | the organizations you belong to, their members and invites, usage and billing activity |
| `boxd.teams` | teams inside an organization |
| `boxd.api_keys` | API keys |
| `boxd.account` | your identity and cluster defaults |
| `boxd.regions` | the regions boxd runs in, and which ones your org can use |

### Quickstart

The whole loop in one example, create through delete:

```python theme={"theme":"github-dark"}
from boxd import Boxd

boxd = Boxd(api_key="bxd_...")

machine = boxd.machines.create("myapp")
boxd.machines.wait_until_ready(machine.id)

result = boxd.machines.exec(machine.id, "uname -a")
print(result.stdout)

boxd.machines.delete(machine.id)
boxd.close()
```

The client is the only stateful object. Everything else is a namespace of flat methods that return plain data. A `Machine` is a record of fields rather than a handle, and every operation takes the machine id (or name) as its first argument: **`boxd.<resource>.<verb>(id, ...)`**.

### Machines

Create, inspect, and control machines. The sub-namespaces `boxd.machines.files`, `.ports`, `.proxies`, `.checkpoints`, and `.backups` are covered further down in this section.

```python theme={"theme":"github-dark"}
machine = boxd.machines.create("myapp")
one     = boxd.machines.get("myapp")   # id or name
all     = boxd.machines.list()              # list[Machine]
boxd.machines.delete("myapp")
boxd.machines.delete_self(confirm="myapp")  # inside a machine: delete the machine this code runs on
```

`delete_self()` only works inside a machine, and deletes that machine: it is the SDK form of `boxd machine remove --self`, with `confirm` set to the machine's name. Use it rather than `delete(own_id)` from inside a machine. See [Self-delete](https://docs.boxd.sh/guides/self-delete.md).

`list()` returns a plain list. Pass `org="acme"` for one organization's machines, or `all_contexts=True` for everything you can reach.

State:

```python theme={"theme":"github-dark"}
boxd.machines.start(id)
boxd.machines.stop(id)
boxd.machines.reboot(id)
boxd.machines.pause(id)        # standby, in RAM: PauseResult(suspend_us=...)
boxd.machines.resume(id)       # ResumeResult(resume_us=...)
boxd.machines.hibernate(id)    # hibernated, on disk
boxd.machines.wake(id)
```

See [Suspend, resume, and hibernate](https://docs.boxd.sh/guides/suspend-resume.md) for the difference between `stop`/`start` (cold) and `pause`/`resume` (warm).

Everything else:

```python theme={"theme":"github-dark"}
fork = boxd.machines.fork("myapp", "myapp2")    # live copy of memory and disk
boxd.machines.share(id)                              # visible to your whole org
boxd.machines.unshare(id)
boxd.machines.rename(id, "new-name")                 # returns the new name
boxd.machines.set_networks(id, ["backend"])          # replaces the whole set
boxd.machines.set_auto_suspend_timeout(id, 300)      # seconds, 0 disables (the default)
boxd.machines.set_auto_hibernate_timeout(id, 3600)
boxd.machines.set_bot_protection(id, mode="sleep_only")  # "on" | "sleep_only" | "off" (or True / False), see Bot protection
boxd.machines.set_idle_ignore_outbound(id, True)     # only inbound connections keep it awake, see Suspend, resume, and hibernate
boxd.machines.set_ssh(id, False)                     # nothing answers SSH; exec still works, see SSH below
boxd.machines.set_delete_after(id, 7200)             # delete 2 h from now; returns the deadline, see Delete after
boxd.machines.set_delete_after(id, cron="0 18 * * *")  # or at the next 18:00 UTC
boxd.machines.set_delete_after(id, 0)                # clear the timer; returns None
for chunk in boxd.machines.logs(id):                 # console output, as bytes
    ...                                              # follow=True keeps the stream open
boxd.machines.wait_until_ready(id)                   # running and exec works
boxd.machines.suggest_name()                         # a free, generated name
```

> [!WARNING]
>
> `rename` reboots the machine. It is its own call rather than part of an `update()` for exactly that reason.

`create` and `fork` return once the machine is scheduled rather than once it is usable. Call `wait_until_ready` before doing anything that depends on it running, and especially before [forking](https://docs.boxd.sh/guides/fork.md) it again. It polls for up to 90 seconds by default (`timeout=`, `poll_interval=`, both in seconds) and raises the builtin `TimeoutError` when the deadline passes.

#### Creating machines

```python theme={"theme":"github-dark"}
boxd.machines.create(
    "myapp",
    image="ubuntu:24.04",
    env={"API_URL": "https://example.com"},
    cmd=["/usr/local/bin/start"],
    restart_policy="always",          # "always" | "never"
    networks=["backend", "cache"],    # machine-to-machine reachability, see Networks
    isolated=False,                   # sandbox, fixed at creation
    vcpu=2,
    memory="8G",
    auto_suspend_timeout=300,         # seconds, 0 disables
    auto_destroy_timeout=0,
    idle_ignore_outbound=True,        # only inbound connections keep it awake; None = the org's default
    delete_after=3600,                # delete-after timer: seconds from now...
    # delete_after_cron="0 18 * * *", # ...or the next match of a cron expression (UTC)
    ssh=True,                         # False: nothing answers SSH; leave out for on, or a fork's or snapshot's setting
)

# In an organization. `shared` makes it visible to every member.
boxd.machines.create(org="acme", shared=True)

# Create a machine from a snapshot.
boxd.machines.create("myapp2", from_snapshot="my-workspace")

# Create a machine from a machine spec. See Machine specs below.
boxd.machines.create("mike-dev", org="acme", spec=Machine.spec().size("2x8").network("eng"))
```

Sizing and lifecycle are flat keyword arguments, with no config object. Every one is optional, and `create()` boots the [default image at the default size](https://docs.boxd.sh/guides/resources.md). There are four sizes: 1 vCPU / 4 GiB, 2 vCPU / 8 GiB (the default), 4 vCPU / 16 GiB, and 8 vCPU / 32 GiB. `memory` takes `"4G"`, `"8G"`, `"16G"`, or `"32G"`. Every machine gets a fixed 100 GB disk, so leave `disk` out. Any other value is refused.

`fork(source, name)` also takes `shared`, `networks`, `isolated`, `auto_suspend_timeout` and `idle_ignore_outbound`, and inherits anything you leave out from the source machine, including its networks and its `idle_ignore_outbound` (the org default doesn't apply to a fork). A fork, and a machine created from a snapshot, starts its source's [automations](https://docs.boxd.sh/guides/automations/jobs.md#forks-and-snapshots) paused so nothing runs twice: the returned `Machine` has `paused_automations` set to how many, and the call warns once when it isn't 0. A fork, and a machine created from a snapshot, keeps its source's size. `vcpu`, `memory`, `disk` and `volumes` are refused on both, and `auto_suspend_timeout` and `idle_ignore_outbound` are accepted. Change the size afterwards with `resize`:

```python theme={"theme":"github-dark"}
boxd.machines.resize(id, memory="16G")   # or vcpu=4, returns ResizeResult(vcpu, memory_bytes, rebooted)
```

Either `vcpu` or `memory` names the whole size. A running machine is rebooted to apply it, a stopped one takes it at its next start, and a machine on standby or hibernated is refused until you resume or wake it.

`isolated` is a **one-way** flag on `fork` and on `create(from_snapshot=...)`. A fork of an isolated machine, or a machine created from an isolated snapshot, is always isolated, and passing `isolated=True` isolates a copy of a machine that wasn't. There is no way to remove isolation from a copy, and no setter afterwards.

Proxies and disk mounts are set up at create time with two small models:

```python theme={"theme":"github-dark"}
from boxd import ProxyEntry, VolumeMount

boxd.machines.create(
    "myapp",
    proxies=[ProxyEntry(name="api", port=3000)],
    volumes=[VolumeMount(disk_id="d_...", mount_path="/data")],
)
```

> [!NOTE]
>
> A machine created from a snapshot resumes as it was captured, so `create(from_snapshot=...)` takes only `name`, `org`, `isolated`, `auto_suspend_timeout`, and `idle_ignore_outbound`. Passing `image`, `env`, `cmd`, `restart_policy`, `shared` or `networks` alongside it raises `ValueError` rather than silently ignoring them. `networks` are replayed from the snapshot. Set them afterwards with `set_networks`. A `spec=` is also accepted, merged over the snapshot's own: see [Machine specs](#machine-specs).

Renaming reboots the machine, so it is its own call. Everything else is readable straight off `Machine`.

#### Machine specs

A machine spec describes a machine in one value: what it boots from, its size, labels, networks, isolation, egress, env, the secrets it gets, the integrations and agent logins it needs, and the packages it installs on first boot. Build one from reusable pieces and create from it. See [Machine specs](https://docs.boxd.sh/guides/machine-specs.md) for the whole picture.

```python theme={"theme":"github-dark"}
from boxd import Machine, team, snapshot, github, slack, jira, claude, secrets

engineering = (
    Machine.spec()
    .from_(team("eng"))                  # a team's default snapshot; or snapshot("eng-base")
    .network("eng")
    .label("team", "eng")
    .env("NODE_ENV", "development")
    .packages("apt-get update", "apt-get install -y nginx")
    .with_(github(shared="eng-bot"), claude())
)

mike = engineering.size("2x8").with_(slack(), jira(shared="jira"), secrets("NPM_TOKEN"))
m = boxd.machines.create("mike-dev", org="acme", spec=mike)
m.spec           # the spec as it stands (update_spec, and label, network, egress and size edits, change it)
m.created_spec   # the spec it was created with, never changed
mike.resolve()   # the same spec as a dict, without creating anything
```

| Builder | Sets |
| - | - |
| `.from_(team(name))`, `.from_(snapshot(name))` | `base`. Omit for the default image. |
| `.size("2x8")` | `size`, as `<vcpu>x<memory GiB>`: `"1x4"`, `"2x8"`, `"4x16"`, `"8x32"` |
| `.assign_to(user_id)` | `assignTo`: create the machine for another member of the org (below) |
| `.label(key, value)`, `.label({...})` | `labels` |
| `.network(*names)` | `networks` |
| `.isolated()` | `isolated` |
| `.egress(*hosts)` | `egress`: the machine's egress allowlist from birth |
| `.env(key, value)`, `.env({...})` | `env`: wins over org and personal vars of the same name |
| `.packages(*commands)` | `packages`: shell commands run once after the first boot |
| `.with_(*pieces)` | merges pieces or other builders |
| `.resolve()` | the resolved spec, as a dict |

A builder is immutable: every method returns a new one, so one base can be extended in several directions.

Pieces: `slack()`, `jira()`, `github()`, `asana()` (pass `shared="tag"` to use the org connection shared under that tag instead of the owner's own), `claude()`, `codex()`, and `secrets(*names)`. Integrations and agent logins are recorded on the machine, and a missing one never blocks the create. A piece is a plain dict (`{"labels": {...}}`, or `{"connections": {"notion": "personal"}}` for any integration), so you can write your own.

Pieces merge in order: maps (`labels`, `env`, `connections`) merge with the later piece winning, lists (`networks`, `egress`, `secrets`, `agents`, `packages`) combine in order without duplicates, `isolated` only turns on, and `base`, `size` or `assignTo` set twice to different values raises `MachineSpecError` (a `ValueError`) naming the field (`"2X8"` is the same size as `"2x8"`). So does a key a spec doesn't have, and a name in both `env` and `secrets`. `merge_specs(*pieces)` applies the same rules to plain pieces and returns the resolved spec. The server checks every field again and names it in its error (`spec.size: ...`).

A spec carries its machine's base, size, labels, networks, isolation and env, so `create(spec=...)` takes none of `image`, `env`, `labels`, `networks`, `isolated`, `vcpu` or `memory` beside it, and raises `MachineSpecError` if you pass one. A spec whose base is a snapshot, or a team with a default snapshot, restores it. A snapshot keeps its machine's spec: restoring it gives the new machine that spec, and `create(from_snapshot=..., spec=...)` merges a spec on top by the same rules. Its `size`, if set, must be the snapshot's. A fork keeps its source's spec.

**Secrets.** `secrets(*names)` names the secrets the machine gets. Their values stay in `boxd.secrets`, usually with the `unattached` scope, which reaches no machine until a spec lists it (see [Env vars and secrets](#env-vars-and-secrets)). On your own machine a name resolves to your own secret first (`private-unattached`, then `private`), else the org's (`unattached`, `all`, `shared`). On a machine created for someone else, or a shared machine, only the org's count. Only org owners and admins may list an org `unattached` secret, and an org `shared` secret only reaches shared machines, so a private machine can't list one. A name that resolves to nothing, or that the create may not list, fails the create, naming it. On the machine, the spec's `env` and `secrets` win over your `private` vars, which win over the org's `shared` vars (shared machines only), which win over its `all` vars. The machine keeps a reference, so rotating a secret reaches it. See [Secrets](https://docs.boxd.sh/guides/machine-specs.md#secrets).

**For someone else.** An org owner or admin can create a machine for another member with `.assign_to(user_id)`, the member's id as `orgs.get_members()` lists it, and `org=` set on the create. The machine is the member's from the start: private to them, billed to the org, set up with their own integrations and agent logins. You can't reach it afterwards, so `create()` answers with its id and name only, and can't also set `delete_after`. The member sees `created_by` and `created_by_name` on it. Refused, naming `spec.assignTo`: without `org`, with `shared=True`, for a caller who isn't an owner or admin of the org, with an org API key or from inside a machine, for someone who isn't a member, and with a snapshot or disk the member couldn't use. Your own id is a plain create, and forks, snapshots and restores drop `assignTo`.

> [!WARNING]
>
> The machine runs the spec you wrote as the member's own machine: its packages as root, its env and its base, alongside the member's GitHub token, agent logins and personal connections. Assign a spec only if the member would run it themselves.

**From inside a machine**, with its own credentials, a spec can't list an unattached secret (yours or the org's) on any machine, `update_spec` can't change that machine's own `egress` or `secrets`, and `assign_to` is refused. Make those changes with an API key or in the console. Names a fork or a restore takes over from its source's spec are not affected.

**Limits**, checked first and named with what was given (`spec.env: at most 128 variables (got 129)`): at most 256 KiB as JSON in all; `env` at most 128 variables, each value at most 32 KiB and all values together at most 64 KiB; `secrets` at most 64 names; `networks` at most 16, each name at most 63 bytes; `egress` at most 256 entries, none empty (leave `egress` out for no allowlist); `connections` at most 64; `packages` at most 200 listed and 50 once duplicates are dropped, each at most 4 KiB (a restore counts the snapshot's too). An `update_spec` patch is at most 256 KiB.

#### Updating a machine's spec

`update_spec` changes the spec of a machine created from one and applies what changes. Pass a JSON Merge Patch, or a function that adds to the current spec:

```python theme={"theme":"github-dark"}
# Patch: a field left out is untouched, a scalar replaces, maps merge key by
# key (None removes a key), a list replaces the whole list, None removes a field.
boxd.machines.update_spec("mike-dev", {
    "labels": {"owner": "mike", "team": None},
    "networks": ["eng", "ops"],
    "packages": ["apt-get install -y nginx", "npm i -g pnpm"],
})

# Builder: reads the spec, adds with the composition rules, sends the difference.
boxd.machines.update_spec("mike-dev", lambda s: s.network("ops").env("LOG_LEVEL", "debug"))

# Dry run: the diff, nothing changed.
diff = boxd.machines.update_spec("mike-dev", {"size": "4x16"}, dry_run=True)
for c in diff.changes:
    print(c.field, c.apply, c.note, c.warnings)
if diff.reboot_required:
    boxd.machines.update_spec("mike-dev", {"size": "4x16"}, reboot=True)

# Run the packages again from the one that failed.
boxd.machines.update_spec("mike-dev", {}, retry_packages=True)

# A patch built from a spec you read: nothing applies if the spec changed since.
spec = boxd.machines.get("mike-dev").spec
if spec:
    boxd.machines.update_spec("mike-dev", {"networks": [*spec.get("networks", []), "ci"]}, expected_spec=spec)
```

| Argument | |
| - | - |
| `dry_run=True` | Return the diff and change nothing. |
| `reboot=True` | Allow a change that reboots the machine (a new size for a running machine). It doesn't reboot for env or secrets: `machines.reboot()` does that. |
| `retry_packages=True` | Run the machine's packages again from the first failed one: it and every command after it that didn't finish (skipped ones excepted) go back to pending and run now (or the next time the machine runs), before any the patch adds. Works with an empty patch (`{}`). |
| `expected_spec=` | The spec you read (`machine.spec`). If the machine's spec is no longer that one, nothing is applied and it raises `ConflictError`. |

Each change in `changes` says how it applies (`apply`):

| Field | `apply` |
| - | - |
| `labels`, `networks`, `egress` | `"live"` (new egress rules are in force within about a second of the call returning) |
| `connections`, `agents` | `"live"`: what the machine needs (`requirements`) changes |
| `packages` | `"live"`: added commands run now, after the ones before them. Removing a done command undoes nothing (a warning says so), and a command that already ran isn't run again. A pending or failed command the update removes is skipped (`skipped` in the change), so the ones after it run; a skipped one listed again goes back to pending (`unskipped`). Commands after a failed one don't run (a warning says so) unless the update also retries (`retry_packages=True`: the failed command and the rest run again first, skipped ones excepted; a failed command the same update removes is skipped, not retried). Removing a running command is `"refused"` until it ends. |
| `env`, `secrets` | `"reboot_recommended"`: new shells and exec sessions get them now. Processes already running keep the old values until they restart. |
| `size` | `"reboot"` on a running machine, which reboots to apply it (as `resize`), so it needs `reboot=True`. `"live"` on a stopped one. |
| `base`, `isolated`, `assignTo` | `"refused"`: fixed when the machine is created |

It returns a `MachineSpecUpdate`: `changes` (a list of `MachineSpecChange`), `reboot_required`, `reboot_recommended`, `spec` (after the patch, or what it would be for a dry run), `applied` (`False` for a dry run), `rebooted` and `resize_error`. A `MachineSpecChange` has `field`, `apply` (`"live"`, `"reboot_recommended"`, `"reboot"` or `"refused"`), `added`, `removed`, `changed` (map keys whose value changes; values are never shown), `before` and `after` for scalars, a one-sentence `note`, and `warnings` for what the change won't do.

A refused change (also: new packages or a retry on a fork, a size change in standby or hibernated) refuses the whole patch, and so does a reboot without `reboot=True`. Nothing is applied. So is an update during which the spec changed (another update, a label edit): it raises `ConflictError`, and reading the machine again and retrying is safe. The builder form does that itself: it sends the spec it read, so a change made in between can't be undone by its lists, and on a conflict reads the spec again and reapplies the function, up to 3 times. Otherwise the spec and the labels, networks, egress and secrets it drives change together, then the size, then the new packages run. If the size then fails (the org's quota changed, the machine went to standby), the rest stays applied and the call still returns: `resize_error` says why, and `spec` has the size the machine has.

The patched spec is checked like a create's. `machine.created_spec` never changes, so the console shows the spec badge as updated. Allowed to whoever may edit the machine's labels: its owner, or an org owner or admin on a shared machine. The builder form only adds: a `size` that differs from the spec's raises, so use a patch to replace or remove. `spec_patch(from_spec, to_spec)` computes the patch the builder form sends. `AsyncBoxd` has the same `await boxd.machines.update_spec(...)`.

#### Networks

Two machines reach each other when they **share at least one network**, or when **neither has any**. Machines with no networks form the org's default network, so naming a network opts a machine out of that pool. The same rule governs the `<name>.boxd` DNS name and `exec` / `cp` between machines, so what resolves is exactly what is reachable.

```python theme={"theme":"github-dark"}
boxd.machines.set_networks(id, ["backend", "cache"])   # returns the set now in effect
boxd.machines.set_networks(id, [])                     # back to the default network
machine.networking.networks, machine.networking.isolated
```

`set_networks` **replaces** the whole set rather than merging, and `[]` is a real destination, the default network, rather than a no-op. Networks are labels you pick, with nothing to create first, and they never cross an organization. Changes take effect immediately.

`isolated` sandboxes a machine. It never joins the default network and is never a peer of another isolated machine, and boxd removes the in-machine `boxd` CLI, the metadata endpoint, integrations and the `run` CLI, agent logins, and the laptop bridge from it. An isolated machine with no networks therefore has no peers at all, and `set_networks` is the only lever it has. It is fixed at creation, with no setter. It keeps outbound internet, unless an egress allowlist is set, and inbound SSH and HTTPS. See [Sandboxes](https://docs.boxd.sh/use-cases/sandboxes.md).

#### Egress allowlist

Limit what a machine can reach on the internet. See [Egress allowlist](https://docs.boxd.sh/guides/egress-allowlist.md).

```python theme={"theme":"github-dark"}
boxd.machines.set_egress_allow(id, ["api.stripe.com", "*.github.com", "203.0.113.0/24"])
machine.egress_allow                    # list[str]: empty = unrestricted
boxd.machines.set_egress_allow(id, ["none"])  # nothing is reachable
boxd.machines.set_egress_allow(id, [])  # unrestricted again
```

The list replaces the whole allowlist, at most 256 entries. Hostnames and wildcards admit HTTP and HTTPS, addresses and CIDRs admit everything else, and the hosts of any host-bound secret the machine holds are always admitted on top. An internationalized name is kept in its ASCII form (`bücher.de` becomes `xn--bcher-kva.de`), which is what the machine looks up. A machine restored from a snapshot starts unrestricted, unless its [machine spec](#machine-specs) lists `egress`.

#### SSH

A machine has SSH on unless you turn it off. With SSH off, nothing answers SSH for it, on its public address or your org's network: the connection closes before a byte of SSH is sent, and the SSH sessions open to it are closed. See [Turn SSH off](https://docs.boxd.sh/cli/commands.md#turn-ssh-off).

```python theme={"theme":"github-dark"}
boxd.machines.create("task-1", ssh=False)   # born with SSH off
boxd.machines.set_ssh(id, True)             # back on, same port
boxd.machines.get(id).ssh                   # bool
```

`exec`, file transfers, `boxd connect` and the console's terminal don't use SSH and keep working. A fork and a machine created from a snapshot keep their source's setting unless `ssh` says otherwise. From inside a machine, on its own credentials, `set_ssh` can't change that machine's setting. SDK releases from before this setting never sent `ssh=False` to the server, so update the SDK before relying on it.

#### The `Machine` object

```python theme={"theme":"github-dark"}
machine.id
machine.name
machine.status            # "pending" | "starting" | "running" | "suspended" |
                          # "hibernated" | "stopped" | "failed" | "destroyed" | "migrating"
machine.image_ref         # the image the machine boots
machine.restart_policy    # str | None
machine.created_at        # datetime | None

machine.resources.vcpu           # the machine's CPU, memory and disk
machine.resources.memory_bytes
machine.resources.disk_bytes     # always the fixed 100 GB allocation, not usage

machine.org               # OrgRef(id, name) | None: None = your default org
machine.shared            # shared with that org, or private to you

machine.networking.networks   # list[str]: empty = the org's default network
machine.networking.isolated   # set at creation, a fork always inherits it

machine.egress_allow      # list[str]: the egress allowlist, empty = unrestricted
machine.ssh               # SSH answers on access.ssh_port, on by default

machine.access.ssh_port         # the port to SSH to, None if it has none yet
machine.access.domain           # the domain the machine is addressed under
machine.access.url              # the machine's public HTTPS address
machine.access.desktop_url      # its live Desktop view in the console
machine.access.custom_domains   # list[CustomDomain] bound to this machine

machine.idle.suspend_after     # seconds of inactivity before each action,
machine.idle.hibernate_after   # 0 disables it
machine.idle.destroy_after

machine.bot_protection_mode  # "on" | "sleep_only" | "off", see Bot protection
machine.bot_protection       # bool: True for "on" and "sleep_only"
machine.idle_ignore_outbound # bool: only inbound connections keep it awake, see Suspend, resume, and hibernate

machine.source            # MachineSource | None: None = booted from an image
machine.source.kind       # "fork" | "snapshot"
machine.source.name       # the source machine, or the snapshot name
machine.source.version    # the snapshot version, a fork has none
machine.source.id         # the machine or snapshot this came from

machine.hibernated_at     # when it went to disk, None = not hibernated
machine.delete_at         # when the delete-after timer deletes it, None = no timer
machine.delete_after_cron # the cron expression it was set with, if any
machine.last_connected_at # datetime | None: None = never connected
machine.boot_time_ms      # how long the last boot took

machine.spec              # dict | None: the machine spec it runs under, None = none
machine.created_spec      # dict | None: the spec it was created with
machine.created_by        # str | None: who created it for you (spec assignTo), None = you did
machine.created_by_name   # str | None: a name to show for created_by
machine.requirements      # list[MachineRequirement]: the spec's connections and agents:
                          #   kind, name, scope ("personal"/"shared"), tag, met, can_fix, reason
machine.packages          # list[MachinePackage]: the spec's packages and how each went:
                          #   command, state, exit_code, output_tail, reason, started_at, finished_at
                          #   (output_tail is empty from list(): get() has it)
```

`org` is the organization the machine belongs to and is billed to, and `shared` says whether the rest of the org can see it. A private machine can still be org-billed, so `org` set with `shared=False` is normal rather than a contradiction. See [Machine sharing](https://docs.boxd.sh/guides/share-a-vm.md).

`source.id` **may not resolve** if the machine or snapshot it points at was since deleted. A lookup that finds nothing is normal.

`requirements` says, for each connection and agent login the spec needs, whether it is connected now. `can_fix` is true when you could connect it: the owner for personal connections and agents, an org owner or admin for shared ones. `reason` says why this machine can't get one as it is: an isolated machine gets no integrations or agent logins, and a shared machine never gets anyone's personal connection or agent login. An unmet requirement is only unavailable on the machine. Nothing blocks creating, booting or using it. Connect from the console's **Integrations needed** section on the machine. See [Integrations the machine needs](https://docs.boxd.sh/guides/machine-specs.md#integrations-the-machine-needs).

`packages` reports the spec's first-boot commands, run once, in order, as root. `state` is `"pending"`, `"running"`, `"done"`, `"failed"` or `"skipped"`. The first failure stops the rest until a retry (`update_spec(id, {}, retry_packages=True)`), or until the failed command is removed from the spec, which marks it `"skipped"` and lets the rest run. In `output_tail` the value of every secret the machine gets shows as `[secret NAME]`. `list()` leaves `output_tail` empty to keep lists small, and `get()` has it. See [Packages](https://docs.boxd.sh/guides/machine-specs.md#packages).

Models are pydantic, so `machine.model_dump()` gives you a plain dict. An unrecognized `status` is passed through rather than rejected, so a machine in a newly added state still prints. The CLI shows `standby` for the state the SDK calls `suspended`.

#### Exec

`machines.get`, `exec`, `fork` and `delete` accept a machine name or an id. `create` returns before the machine is running, so call `wait_until_ready` before the first `exec`.

One-shot exec collects the output:

```python theme={"theme":"github-dark"}
result = boxd.machines.exec(id, "cargo build")
result.stdout      # str
result.stderr      # str
result.exit_code   # int
result.success     # bool: exit_code == 0

boxd.machines.exec(id, ["echo", "a b"])              # a list is quoted for you
boxd.machines.exec(id, "env", env={"FOO": "bar"})
boxd.machines.exec(id, "pytest", timeout=30)         # seconds
```

A list `command` is shell-quoted for you, while a string is passed through as written. `timeout` is in seconds and gives up on the call, though the remote process may keep running. `exec` also takes `tty`, `cols` and `rows`. Under a PTY the terminal merges stderr into stdout, so `stderr` comes back empty and everything lands in `stdout`.

For anything interactive, `stream_exec` gives you a live session, the one handle in the SDK, because a bidirectional stream really is stateful:

```python theme={"theme":"github-dark"}
with boxd.machines.stream_exec(id, command="bash", tty=True) as stream:
    stream.write(b"ls\n")
    stream.write_eof()
    for chunk in stream:
        print(chunk.decode(errors="replace"), end="")
    print("exited", stream.exit_code)
```

Iterating the stream yields merged output, what a terminal would show. `iter_chunks()` yields `OutputChunk(data, is_stderr)` when you need the two streams apart. Under `tty=True` the terminal merges them, so everything arrives as stdout. Set `tty=False` if you need the split. `exit_code` is `None` until the stream is exhausted.

Set the terminal size with `cols`/`rows`, and call `stream.resize(cols, rows)` when the local terminal changes size:

```python theme={"theme":"github-dark"}
import shutil, signal

cols, rows = shutil.get_terminal_size()
stream = boxd.machines.stream_exec(id, command="htop", tty=True, cols=cols, rows=rows)
signal.signal(signal.SIGWINCH, lambda *_: stream.resize(*shutil.get_terminal_size()))
```

Set `cols`/`rows` for anything that draws to the terminal, since an unset size gives the PTY zero geometry and leaves the fallback to the program. `resize()` on a non-PTY exec is a harmless no-op.

Headless one-shots that read stdin (`jq`, `cat`, `claude -p`) hang waiting for input. Pass `close_stdin=True` to send end-of-input immediately, or call `write_eof()` yourself. Combining it with `tty=True` raises `ValueError`, since a shell needs stdin open.

#### Files

```python theme={"theme":"github-dark"}
boxd.machines.files.upload(id, "/app/config.json", '{"debug": true}')
boxd.machines.files.upload(id, "/app/data.bin", open("local.bin", "rb").read())
data = boxd.machines.files.download(id, "/app/output.json")   # bytes
```

`upload` takes `str` or `bytes` and returns the number of bytes written, and large uploads are chunked for you. Paths inside the machine are absolute, or relative to `/home/boxd`.

Directories are managed with the same namespace:

```python theme={"theme":"github-dark"}
listing = boxd.machines.files.list_dir(id, "/home/boxd")   # DirListing
for e in listing.entries:
    e.name, e.is_dir, e.size_bytes, e.permissions, e.modified_at
listing.truncated                                          # True past 5,000 entries

boxd.machines.files.mkdir(id, "/home/boxd/assets")         # the parent must exist
boxd.machines.files.rename(id, "/home/boxd/a", "/home/boxd/b")
boxd.machines.files.copy(id, "/home/boxd/src", "/home/boxd/src-copy")   # recursive
boxd.machines.files.delete(id, "/home/boxd/src-copy")                    # recursive
```

`list_dir` returns the direct children only, in no particular order, and caps at 5,000 entries. A listing with `truncated` set holds the first 5,000. Use `exec` for the rest.

#### Ports

Raw port forwards: TCP and UDP on a public address. See [Port forwarding](https://docs.boxd.sh/guides/port-forwarding.md). Max 3 per machine.

```python theme={"theme":"github-dark"}
fwd = boxd.machines.ports.expose(id, 5432, protocol="tcp")
fwd.dns             # hostname to connect to
fwd.public_port     # port to connect on
fwd.machine_port    # the port inside the machine
fwd.protocol        # "tcp" | "udp" | "both"

boxd.machines.ports.list(id)    # one machine's forwards
boxd.machines.ports.list()      # every forward you own
boxd.machines.ports.unexpose(id, 5432)
```

Re-exposing the same machine port keeps its public port and just updates the protocol, and `"both"` shares one public port across TCP and UDP.

#### Proxies

Subdomain proxies: HTTPS routes into a machine. See [Proxies](https://docs.boxd.sh/guides/proxies.md). The machine argument takes an id or a name, like everywhere else.

```python theme={"theme":"github-dark"}
boxd.machines.proxies.create("myapp", "api", 3000)
routes = boxd.machines.proxies.list("myapp")
routes[0].port          # int: where traffic actually goes
routes[0].port_mode     # "locked" (you pinned it) | "auto" (detected for you)
routes[0].domain
routes[0].is_default

boxd.machines.proxies.set_port("myapp", 3001, name="api")
boxd.machines.proxies.set_port("myapp", "auto")   # default route, auto-detected
boxd.machines.proxies.delete("myapp", "api")
```

`name` and `port` are both required on `create`, because a subdomain proxy is always pinned to a port. `"auto"` is only accepted for a machine's default route, which is what `set_port` addresses when you leave `name` off.

#### Checkpoints

Per-machine save points, restored in place. See [Checkpoints](https://docs.boxd.sh/guides/checkpoints.md). They are deleted with the machine.

```python theme={"theme":"github-dark"}
boxd.machines.checkpoints.create(id, "before-upgrade")   # machine must be running
points = boxd.machines.checkpoints.list(id)
points[0].status        # "pending" | "ready" | "failed"
points[0].available     # restorable right now
points[0].size_bytes
points[0].created_at

boxd.machines.checkpoints.restore(id, "before-upgrade")
boxd.machines.checkpoints.delete(id, "before-upgrade")
```

`create` returns while the capture is still `"pending"`.

#### Backups

Off-machine disk backups for disaster recovery, on demand or on a schedule. See [Disaster recovery](https://docs.boxd.sh/guides/disaster-recovery.md). Restoring one rewrites the disk only, not memory or running state.

```python theme={"theme":"github-dark"}
backup_id = boxd.machines.backups.trigger(id)   # back up now, returns the new backup id

boxd.machines.backups.schedule_set(id, interval_secs=86400, retention_secs=30 * 86400)
# or a wall-clock cron schedule instead of a fixed interval:
boxd.machines.backups.schedule_set(id, cron="0 3 * * *", retention_secs=30 * 86400)

schedule = boxd.machines.backups.schedule_get(id)   # None when there's no schedule

backups = boxd.machines.backups.list(id)
backups[0].status        # "pending" | "ready" | "dedup" | "failed"
backups[0].size_bytes
backups[0].created_at

boxd.machines.backups.restore(id, backups[0].id)   # destructive, in-place
boxd.machines.backups.delete(id, backups[0].id)
boxd.machines.backups.schedule_clear(id)
```

Pass exactly one of `interval_secs` or `cron` to `schedule_set`. A schedule can't fire more often than every 15 minutes either way. `trigger` is independent of the schedule and runs one capture at a time per machine. `delete` is refused for a backup still being captured or one a newer `"dedup"` entry still points at. A `"dedup"` backup restores the same as a `"ready"` one.

#### Computer use

`machines.computer` works a machine's desktop, the one the console's Desktop view shows, for computer-use agents: screenshots, the mouse and the keyboard. The desktop starts on demand. Each call does one action and returns a `ComputerActionResult` with the screen's size, where the pointer is, and a screenshot taken after the action when you ask for one. See [Computer use](https://docs.boxd.sh/guides/computer-use.md).

```python theme={"theme":"github-dark"}
c = boxd.machines.computer

r = c.screenshot(id)
r.screen_width, r.screen_height, r.cursor          # cursor.x, cursor.y
r.screen_held                                      # set_screen_size is holding it
r.screenshot.data                                  # PNG bytes; .mime_type, .width, .height
c.screenshot(id, max_width=1280, max_height=800)   # scaled down to fit
c.screenshot(id, format="jpeg", quality=80)        # "png" | "jpeg" | "webp"
c.screenshot(id, region=(0, 0, 640, 400))          # part of the screen: x, y, width, height

c.click(id, 640, 400)                              # button="right" | "middle" | "back" | "forward"
c.click(id, 640, 400, count=2, modifiers="ctrl")   # a double click, ctrl held
c.move(id, 100, 100)
c.drag(id, [(100, 100), (300, 200)])
c.mouse_down(id, 100, 100)
c.mouse_up(id, 300, 200)
c.scroll(id, 640, 400, dy=3)                       # wheel clicks: dy down, dx right
c.type(id, "hello")
c.key(id, "ctrl+s")                                # "Return", "alt+Tab"; repeat=, hold_ms=
c.wait(id, 1000)                                   # milliseconds
c.cursor_position(id)

c.click(id, 640, 400, screenshot=True)             # and a screenshot after it, same call
c.key(id, "Return", screenshot={"max_width": 1280, "delay_ms": 300})

c.set_screen_size(id, 1280, 800)                   # hold the screen at this size
c.release_screen_size(id)                          # it follows the viewer again
```

Coordinates are screen pixels from the top left. Leave out `x` and `y` to act where the pointer is. `screenshot=` takes `True`, a `ScreenshotOptions` or a dict of its fields (`format`, `quality`, `max_width`, `max_height`, `region`, `delay_ms`). An action that doesn't fit the screen, or a key name boxd doesn't know, raises `APIStatusError` with `code == "invalid_argument"`.

A machine in another region takes `region=` on these calls, as elsewhere in the SDK. On `screenshot`, `region` is the part of the screen to capture, so use `c.in_region("nyc").screenshot(id)` there.

`boxd.computer_use` runs a model's computer-use tool calls on a machine. `ClaudeComputer` and `OpenAIComputer` take `(boxd, machine)`, and `AsyncClaudeComputer` and `AsyncOpenAIComputer` take an `AsyncBoxd`. They need neither the `anthropic` nor the `openai` package.

```python theme={"theme":"github-dark"}
from boxd.computer_use import ClaudeComputer, OpenAIComputer

computer = ClaudeComputer(boxd, "my-machine")      # max_width=, max_height=, screen_size=, region=
computer.tool                                      # for tools=[...]: {"type": "computer_toolset_20260801"}
results = computer.run(response.content)           # one tool_result per action, for the next user message
computer.release()                                 # let go of the screen

computer = OpenAIComputer(boxd, "my-machine")
computer.tool                                      # {"type": "computer"}
outputs = computer.run(response.output)            # a computer_call_output per computer_call
```

The first action holds the screen at 1280x800 until `release()`. `screen_size=` picks another size, and `screen_size=None` leaves the screen alone. The full loop is in [Claude and OpenAI agents](https://docs.boxd.sh/guides/computer-use.md#claude-and-openai-agents).

### Snapshots

Named captures of a running machine's memory and disk. See [Snapshots](https://docs.boxd.sh/guides/snapshots.md). Create a machine from one with `machines.create(from_snapshot=...)`.

```python theme={"theme":"github-dark"}
boxd.snapshots.create(machine_id, "my-workspace")
snap = boxd.snapshots.get("my-workspace")
boxd.snapshots.list()
boxd.snapshots.delete("my-workspace")
```

Saving under an existing name replaces the version, and older versions cannot be restored or pinned. A `Snapshot` carries `created_at` (the first capture), `updated_at` (the most recent one), `version`, `status`, `size_bytes`, `vcpu`, `memory_bytes` and `use_count`. `get`, `list` and `delete` take an optional `org=`. `create` returns a `CreatedSnapshot` whose `paused_automations` is how many of the machine's automations it captured: every machine created from it starts them paused, and the call warns once when it isn't 0.

### Disks

```python theme={"theme":"github-dark"}
disk = boxd.disks.create("data", "10G")
boxd.disks.attach(disk.id, machine_id, "/mnt/data")
boxd.disks.attach(disk.id, machine_id, "/mnt/data", read_only=True)
boxd.disks.detach(disk.id, machine_id)
boxd.disks.list()
boxd.disks.delete(disk.id)
```

`size` takes a human string (`"10G"`) or a byte count. A disk is always created writable, and read-only is chosen per attachment. A disk can be attached to one machine at a time. `status` is `"creating"`, `"ready"` or `"destroyed"`, and it can only be attached once it is `"ready"`. `list()` also returns each disk's current `attachments`.

You can mount a disk at create time instead, with `volumes=[VolumeMount(...)]`. A machine can only mount a disk that lives on its own host, so that is the way to pair a disk with a new machine: the machine is placed on the disk's host. See [Disks](https://docs.boxd.sh/guides/disks.md).

A disk lives in one [region](#regions) and attaches to machines there. `create`, `attach`, `detach`, `list` and `delete` take `region=`.

### Env vars and secrets

Two namespaces with identical methods. See [Env vars and secrets](https://docs.boxd.sh/guides/env-secrets.md). The difference is what comes back: an `EnvVar` has a readable `value`, a `Secret` has no `value` field at all.

```python theme={"theme":"github-dark"}
boxd.env.set("MODE", "production", scope="all")
boxd.env.list()                    # [EnvVar(name, scope, value)]
boxd.env.delete("MODE", scope="all")

boxd.secrets.set("API_TOKEN", "s3cr3t", scope="shared")
boxd.secrets.list()                # [Secret(name, scope, domains, bound_machines)]: no values
boxd.secrets.delete("API_TOKEN", scope="shared")
```

`set`, `delete` and `move` each hand back the server's confirmation message as a `str`.

Scope decides which machines a value reaches:

| Scope | Applies to |
| - | - |
| `private` | your own private machines in that organization |
| `shared` | the organization's shared machines (the default) |
| `all` | both |
| `unattached` | secrets only: just the machines whose [spec](#machine-specs) lists it. The organization's with `org` (set, moved and deleted by its owners and admins only), else your own. |
| `private-unattached` | secrets only: your own unattached secret in the organization named by `org` |

```python theme={"theme":"github-dark"}
boxd.secrets.set("NPM_TOKEN", "npm_...", scope="unattached", org="acme")
m = boxd.machines.create("mike-dev", org="acme", spec=Machine.spec().with_(secrets("NPM_TOKEN")))
```

`list` reports the organization's unattached secrets as `unattached` and your own as `private-unattached`, each with `bound_machines`, the number of machines whose spec lists it (0 for every other scope). `unattached` is for secrets only: a plain value a machine needs belongs in its spec's `env`. See [Unattached secrets](https://docs.boxd.sh/guides/env-secrets.md#unattached-secrets).

`move` changes the scope. It needs `from_scope` as well as `to_scope`, because the same name can exist in several scopes at once:

```python theme={"theme":"github-dark"}
boxd.secrets.move("API_TOKEN", from_scope="private", to_scope="all")
```

It is a move between two places rather than a field update, so calling it twice fails the second time. Env vars and secrets share one name space per scope, so an existing env var can block a secret moving into that scope, and vice versa.

A secret can be bound to the hosts it may be sent to, so the machine only ever holds a placeholder. See [Host-bound secrets](https://docs.boxd.sh/guides/env-secrets.md#host-bound-secrets).

```python theme={"theme":"github-dark"}
boxd.secrets.set("STRIPE_KEY", "sk_live_...", scope="all", domains=["api.stripe.com"])
boxd.secrets.list()[0].domains    # list[str]: empty = a plain secret
```

`domains` is the complete set. Setting the secret again without it makes it a plain secret, so pass it again when rotating a value.

Pass `org="acme"` to any of these to work in an organization instead of your default org.

### Egress

Two controls, both enforced outside the machine. See [Egress control](https://docs.boxd.sh/guides/egress).

A per-machine allowlist of what it may reach. Each call replaces the whole set, and `[]` clears it:

```python theme={"theme":"github-dark"}
boxd.machines.set_egress_allow(id, ["api.stripe.com", "*.npmjs.org", "203.0.113.0/24"])
boxd.machines.get(id).egress_allow   # list[str], empty = unrestricted
boxd.machines.set_egress_allow(id, ["none"])  # an allowlist with nothing in it: nothing is reachable
boxd.machines.set_egress_allow(id, [])
```

A secret bound to the hosts it may be sent to. The machine holds a `bxds_…` placeholder, and the real value is substituted into HTTPS requests to those hosts on the way out, anywhere in the request (the URL, a header, the body). Over plain HTTP it stays the placeholder, and where a bound host's response repeats the value, the machine gets the placeholder instead. `domains` is the full desired set, and setting the secret again without it makes it a plain secret:

```python theme={"theme":"github-dark"}
boxd.secrets.set("STRIPE_KEY", "sk_live_...", scope="all", domains=["api.stripe.com"])
boxd.secrets.list()   # [Secret(name, scope, domains, bound_machines)]
```

A [machine spec](#machine-specs) can set the allowlist from birth with `.egress(...)`. From inside a machine, on its own credentials, `set_egress_allow` can't change that machine's own allowlist.

### Domains

Bring your own domain instead of `name.boxd.sh`. `create` binds the domain and starts verification immediately, so call it only once the DNS records are actually in place. The records to set (an A record plus a wildcard CNAME) and the verification flow are covered in [Custom domains](https://docs.boxd.sh/guides/custom-domains.md).

```python theme={"theme":"github-dark"}
d = boxd.domains.create("app.example.com", machine.id)
d.status         # "pending" | "active"
d.last_error     # empty when healthy

boxd.domains.list()
boxd.domains.delete("app.example.com")
```

### Organizations

```python theme={"theme":"github-dark"}
orgs = boxd.orgs.list()
orgs[0].slug         # the org's unique key: pass this wherever a method takes `org`
orgs[0].name         # display label
orgs[0].is_admin
orgs[0].is_default   # your default org

org = boxd.orgs.create("Acme")       # you become its owner, interactive login only
boxd.orgs.rename("Acme Labs", org="acme")
```

#### Members and invites

See [Organizations and teams](https://docs.boxd.sh/guides/organizations.md) for the roles. Anywhere `org` is omitted, your default org is used.

```python theme={"theme":"github-dark"}
roster = boxd.orgs.get_members("acme")
roster.members[0].user_id, roster.members[0].role         # "owner" | "admin" | "member"
roster.members[0].display_name, roster.members[0].github_username
roster.invites[0].email, roster.invites[0].role, roster.invites[0].expires_at
roster.invites[0].accept_url                              # interactive login only, empty otherwise

invite = boxd.orgs.invite("alice@example.com", role="member", org="acme")
boxd.orgs.revoke_invite(invite.token)
boxd.orgs.set_member_role("usr_...", "admin", org="acme")   # or "member" to demote
boxd.orgs.remove_member("usr_...", org="acme")
```

Invites and role changes need org admin. An invite that makes someone an admin, and a promotion to admin, need an interactive login as well, so an API key or an in-machine client gets `PermissionDeniedError` there. Demoting another admin is owner-only, and the owner cannot be demoted or removed.

#### Machine defaults

What a `create` that names no size gets. It is a preference below the quota, not the quota itself. Setting or clearing requires org admin.

```python theme={"theme":"github-dark"}
boxd.orgs.set_machine_defaults("acme", vcpu=2)   # or memory="8G"
d = boxd.orgs.get_machine_defaults("acme")
d.is_set, d.vcpu, d.memory_bytes, d.ceiling_vcpu, d.ceiling_memory_bytes
boxd.orgs.clear_machine_defaults("acme")
```

#### Idle clock default

Whether new machines in the org start with their idle timers [ignoring outbound traffic](https://docs.boxd.sh/guides/suspend-resume.md#org-default). Setting it also changes the existing machines and snapshots you can manage; pass `new_machines_only=True` to change only new machines. Setting or clearing requires org admin, and any member can read it.

```python theme={"theme":"github-dark"}
r = boxd.orgs.set_idle_ignore_outbound_default("acme", enabled=True)
r.machines_changed, r.snapshots_changed, r.machines_skipped
boxd.orgs.set_idle_ignore_outbound_default("acme", enabled=True, new_machines_only=True)
d = boxd.orgs.get_idle_ignore_outbound_default("acme")
d.is_set, d.enabled, d.platform_enabled   # platform_enabled: what new machines get without an org default
boxd.orgs.clear_idle_ignore_outbound_default("acme")   # existing machines keep their value
```

#### Bot protection default

The [bot protection](https://docs.boxd.sh/guides/bot-protection.md#org-default) new machines in the org start with. Setting it also changes the existing machines you can manage, except machines with bot protection off; pass `new_machines_only=True` to change only new machines. Setting or clearing requires org admin, and any member can read it.

```python theme={"theme":"github-dark"}
r = boxd.orgs.set_bot_protection_default("acme", mode="on")   # "on" | "sleep_only" | "off"
r.machines_changed, r.snapshots_changed, r.machines_off, r.machines_skipped
boxd.orgs.set_bot_protection_default("acme", mode="sleep_only", new_machines_only=True)
d = boxd.orgs.get_bot_protection_default("acme")
d.is_set, d.mode, d.platform_mode   # platform_mode: what new machines get without an org default
boxd.orgs.clear_bot_protection_default("acme")             # existing machines keep their mode
```

#### Machine limit

How many machines the org may have at once, and asking for more. Any member can read it, with a login or an API key issued for the org. Only the org's owner can send a request, with their login or an API key of theirs: `max_vms` is the new total, above the current limit and at most 1000, and `message` (at most 1000 characters) is optional. One request is open at a time; another raises `ConflictError` until the limit changes, and the owner gets an email when it does. Anyone else gets `PermissionDeniedError`.

```python theme={"theme":"github-dark"}
l = boxd.orgs.get_machine_limit("acme")
l.max_vms, l.vm_count, l.is_owner
l.request                     # MachineLimitRequest | None: .requested_at, .max_vms
r = boxd.orgs.request_machine_limit(100, message="CI runners", org="acme")
r.requested_at, r.max_vms
```

With several [regions](#regions), the limit applies in each region on its own, and `vm_count` counts the machines in Frankfurt.

#### Wildcard domain

A wildcard domain for the whole org. See [Custom domains](https://docs.boxd.sh/guides/custom-domains.md#org-wide-wildcard-domain). Setting or clearing requires org admin, and any member can read it.

```python theme={"theme":"github-dark"}
domain = boxd.orgs.set_domain("acme", "preview.mysaas.com")   # call only once NS delegation is live
domain.status       # "pending" | "active"

boxd.orgs.get_domain("acme")     # None if unset
boxd.orgs.clear_domain("acme")
```

An org has one wildcard domain in each [region](#regions), delegated to that region's nameservers. All three take `region=` to pick which, and the domain carries its `region`.

### Regions

boxd runs in Frankfurt (`fra`) and New York (`nyc`). A machine, snapshot or disk lives in one region. See [Regions](https://docs.boxd.sh/guides/regions.md).

Calls on machines, snapshots and disks take `region=`, and so does everything under a machine: `exec`, `files`, `ports`, `proxies`, `checkpoints`, `backups` and `computer`. Without it, a call goes to the client's `region`, else to Frankfurt. Calls on the account, orgs, API keys, env vars, secrets, teams and billing work the same whatever `region` says.

```python theme={"theme":"github-dark"}
nyc = Boxd(region="nyc")
nyc.machines.create("web")                              # created in New York
boxd.machines.exec("web", "uptime", region="nyc")
boxd.snapshots.list(region="nyc")

one = boxd.machines.list()                              # the client's region
one.elsewhere                                           # [RegionCount(region="nyc", count=3)]
everywhere = boxd.machines.list(region="all")           # every region the org has
everywhere.unavailable                                  # regions that didn't answer
```

Machines, snapshots, disks and org domains carry their `region`. `region="all"` works on `machines.list`, `snapshots.list` and `disks.list`. A list is a plain `list` with `elsewhere` and `unavailable` added.

```python theme={"theme":"github-dark"}
regions = boxd.regions.list()                     # or boxd.orgs.regions("acme")
regions[0].id, regions[0].name, regions[0].zone
regions[0].home                                   # True for Frankfurt, where account and org calls go
regions[0].org_state                              # "enabled" | "requested" | "available"

boxd.orgs.request_region("nyc", org="acme")       # org admins: "requested", or "enabled" if it is
boxd.orgs.set_default_region("nyc", org="acme")   # org admins
boxd.orgs.get_default_region(org="acme")          # "nyc", or None
boxd.orgs.clear_default_region(org="acme")
```

The org's default region is where the CLI and the console create machines when nobody names a region. The SDK goes where `region` says, so read the default with `get_default_region` and pass it on when you want the same behavior.

### Teams

A team is a group of members inside an org, with an optional default snapshot that new team machines are created from. See [Organizations and teams](https://docs.boxd.sh/guides/organizations.md#teams).

```python theme={"theme":"github-dark"}
team = boxd.teams.create("backend", org="acme")   # org admin only
boxd.teams.list(org="acme")                       # every team for an admin, your own otherwise
team = boxd.teams.get(team.id)
team.name, team.org_id, team.is_admin             # is_admin: you have team-admin authority
team.members[0].user_id, team.members[0].role     # "admin" | "member"
team.default_snapshot_id                          # None = none

boxd.teams.add_member(team.id, "usr_...")         # must already be an org member
boxd.teams.set_member_role(team.id, "usr_...", "admin")
boxd.teams.remove_member(team.id, "usr_...")
boxd.teams.set_default_snapshot(team.id, snapshot.id)   # a shared snapshot of the org
boxd.teams.set_default_snapshot(team.id, None)          # clear
boxd.teams.rename(team.id, "platform")
boxd.teams.delete(team.id)
```

### Usage and cost

What each machine used and cost, and what was actually charged. Org owners and admins only. An API key issued for the org works too. The CLI equivalents are `boxd manage usage`, `boxd machine usage` and `boxd manage billing activity`. See [Commands](https://docs.boxd.sh/cli/commands.md#usage-and-billing).

```python theme={"theme":"github-dark"}
from datetime import datetime, timezone

# One machine over its whole life, or pass since=/until= (datetime or unix
# seconds). A deleted machine is found by its id or name (org= says where to look).
u = boxd.machines.usage("myapp")
u.seconds.running, u.seconds.standby, u.seconds.hibernated, u.seconds.stopped
u.cost_micro / 1e6                   # estimated cost, in u.currency ("eur" | "usd")
u.complete                           # True once all its usage is metered (see below)
u.period.start, u.period.end
u.vcpu_hours, u.ram_gib_hours, u.disk_gib_hours   # what the cost is priced on
u.rates                              # ...at these rates, per unit-hour

# Every machine in an org, most expensive first. Default: the last 28 days.
r = boxd.orgs.usage(since=datetime(2026, 9, 1, tzinfo=timezone.utc))
r.total_cost_micro, r.currency
for m in r.machines:
    print(m.name, m.status, m.cost_micro / 1e6)

# Billing activity: what was actually charged, newest first.
for e in boxd.orgs.billing_activity(since=datetime(2026, 9, 1, tzinfo=timezone.utc)):
    print(e.created_at, e.kind, e.amount_micro / 1e6)   # charges are negative
```

To record what a machine cost after deleting it, wait for `complete`. Metering lags by up to about 25 minutes, so the figure read right after `delete()` is still growing.

```python theme={"theme":"github-dark"}
boxd.machines.delete(machine_id)
# ...a little later, or from a periodic job:
u = boxd.machines.usage(machine_id)
if u.complete:
    save(machine_id, u.cost_micro, u.currency)   # otherwise try again later
```

`orgs.usage()` carries the same flag on every machine, so one periodic call can settle all of them. A machine that still exists is never complete in a window that runs to now.

Money is in micro-units (1e-6) of the org's currency. Usage is metered every second and settled every 15 minutes. The usage figures are priced at the org's current rates, so they are an estimate that tracks billing activity closely. Billing activity is what was charged: one `usage_charge` per 15 minutes for the whole org, plus top-ups and grants. Machines deleted since still show up, with status `"deleted"`. A window spans at most 366 days. `orgs.billing_activity_page()` returns one page with its `next_page_token` when you want to page by hand. The async client has the same methods (`async for e in boxd.orgs.billing_activity(): ...`).

### API keys

```python theme={"theme":"github-dark"}
key = boxd.api_keys.create("ci", org="acme")
key.api_key      # shown once: store it now
key.expires_at   # None = no expiry

boxd.api_keys.list()   # id, name, key_prefix, created_at, last_used_at, expires_at, org, kind, created_by, mine
boxd.api_keys.delete(key.id)
```

Pass `expires_in` (seconds) for a key that expires. Every key belongs to exactly one organization: `org` names it, and omitting `org` uses your default org. `kind="member"` (the default) acts as you within that organization, while `kind="org"` is limited to the organization's shared machines and requires an org admin to create.

`list()` returns the keys you made and, in every organization you administer, that organization's `kind="org"` keys, whoever made them. An org key keeps working after its maker leaves the organization, so its admins can see it and `delete()` it. `created_by` names the maker, and `mine` is `True` for your own keys.

> [!WARNING]
>
> `create` is the only time the raw key is returned. `list` shows the prefix only, and deleting a key takes effect immediately.
>
> Key management itself needs a credential from an **interactive login** (the token `boxd auth login` stores, or `BOXD_TOKEN`). A client authenticated with an API key, or running on in-machine auth, gets `PermissionDeniedError` from `api_keys.*`, so an API key can never mint more keys.

### Account

```python theme={"theme":"github-dark"}
from pathlib import Path

me = boxd.account.get()
me.user_id
me.display_name           # None falls back to user_id
me.pubkey_fingerprints
me.billing.max_vms              # your effective quota
me.billing.subscription_status  # None = never subscribed

boxd.account.link_ssh_key(Path.home().joinpath(".ssh/id_ed25519.pub").read_text())

cfg = boxd.account.config()
cfg.default_image
cfg.zone
```

`link_ssh_key` takes the verbatim contents of a `.pub` file and lets you SSH to your machines with it. Pass `device_id=` to keep one key per device, so re-linking from the same device replaces that device's key instead of accumulating stale ones. Like key management, `link_ssh_key` requires an interactive-login credential rather than an API key.

## Errors

```python theme={"theme":"github-dark"}
from boxd import (
    BoxdError,               # base class: catch this to catch everything
    AuthenticationError,     # no usable credential, or it was rejected
    PermissionDeniedError,   # authenticated, but not allowed
    NotFoundError,           # no such resource
    ConflictError,           # already exists, the resource is in the wrong state, or it changed meanwhile
    RateLimitError,          # quota or rate limit reached
    RegionNotEnabledError,   # a PermissionDeniedError for a region the org can't use
    APIStatusError,          # any other error returned by the server
    APIConnectionError,      # the request never reached the server
)

try:
    boxd.machines.get("nope")
except NotFoundError:
    ...
```

`RegionNotEnabledError` carries `region` and `org_state`. When a machine, snapshot or disk isn't in the region a call went to, the `NotFoundError` says where else your orgs have it. `elsewhere` lists the same name in other regions, `close` lists names one or two letters off, and the message says which `region=` to pass.

Errors returned by the server carry `.message`, `.code` (the canonical status name, for example `"not_found"`) and `.grpc_code` (the numeric [status code](https://grpc.github.io/grpc/core/md_doc_statuscodes.html)) for finer-grained handling. Errors raised client-side, like an exec timeout or a [machine spec](#machine-specs) that doesn't merge (`MachineSpecError`, also a `ValueError`), leave `.code` and `.grpc_code` as `None`:

```python theme={"theme":"github-dark"}
import grpc

try:
    boxd.machines.create("myapp")
except BoxdError as e:
    if e.grpc_code == grpc.StatusCode.RESOURCE_EXHAUSTED.value[0]:
        ...   # hit your quota: surface a 'wait or upgrade' path
    raise
```


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