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

# TypeScript SDK

> Programmatic access to boxd machines from Node, Bun, and Deno.

The `@boxd-sh/sdk` 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](/cli/commands.md), so everything you can do from the terminal you can do from TypeScript.

Promise-only, ESM-only. Runs on Node 20+, Bun, and Deno.

## Installation

```bash npm
npm install @boxd-sh/sdk
```

```bash bun
bun add @boxd-sh/sdk
```

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 exported as `VERSION`.

### Cloudflare Workers, browsers, and other non-Node runtimes

The default `@boxd-sh/sdk` entry point uses gRPC (`@grpc/grpc-js`), which needs Node's `http2`/`net` modules and can't load in a Cloudflare Worker or a browser. Import from `@boxd-sh/sdk/web` instead: same client, same namespaces, same options, same errors.

```typescript
import { Boxd } from "@boxd-sh/sdk/web";

const boxd = new Boxd({ apiKey: "bxd_..." });
const machine = await boxd.machines.create({ name: "myapp" });
```

Only the import path changes. This entry talks to the same `:9443` endpoint over [grpc-web](/reference/grpc-api.md#calling-from-a-browser-or-cloudflare-worker) (plain `fetch`). Every call, including `exec()` and file uploads, goes over one wire protocol `fetch` can carry. It works anywhere `fetch` is available: Cloudflare Workers, browsers, Bun, Deno, Node 20+. On a server, use the default `@boxd-sh/sdk` entry unless you have a specific reason not to. It has no such restriction.

> [!NOTE]
>
> The one thing that doesn't work on this entry is `streamExec()` (interactive PTY sessions). It needs a connection that's live in both directions at once, which grpc-web can't provide, so it throws immediately and says so. Ordinary `exec()` and file uploads are unaffected: both already send everything and then read the result, on either entry.

## Authentication

```typescript
new Boxd({ apiKey: "bxd_..." });   // recommended
new Boxd({ token: "..." });        // a token you already hold
new Boxd();                        // BOXD_TOKEN, then BOXD_API_KEY
```

Credentials are resolved in this order, first match wins:

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

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

Mint a key with `boxd auth keys create NAME` (see the [CLI](/cli/authentication.md#api-keys)), in the [console](https://app.boxd.sh), or with [`boxd.apiKeys.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 fails with `AuthenticationError` rather than retrying.

### Inside a machine

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

```typescript
const boxd = new Boxd();
const mine = await boxd.machines.list();
```

It also targets the cluster the surrounding machine belongs to, so the same code runs unchanged wherever it is deployed. An explicit `baseURL` 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

```typescript
new Boxd();                                        // production
new Boxd({ apiKey: "bxd_..." });
new Boxd({ region: "nyc" });                       // machines, snapshots and disks in New York
new Boxd({ baseURL: "https://boxd.example.com:9443" }); // any other cluster
```

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

| Option | Env var | Default |
| - | - | - |
| `apiKey` | `BOXD_API_KEY` | none |
| `token` | `BOXD_TOKEN` | none |
| `baseURL` | `BOXD_BASE_URL` (or the deprecated `BOXD_API_URL`) | `https://boxd.sh:9443` |
| `region` | `BOXD_REGION` | the region `baseURL` serves, Frankfurt for production |
| `timeout` | none | 60000 ms |
| `maxRetries` | none | 2 |

Timeouts are in milliseconds throughout this SDK: the client `timeout`, the `exec` `timeout`, and `waitUntilReady`. Idle timeouts such as `autoSuspendTimeout` are in seconds.

`baseURL` 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 `maxRetries` times with exponential backoff. Timeouts are never retried, because the request may already have been applied, and authentication failures are never retried either.

Call `close()` when you're done, or let the runtime do it:

```typescript
{
  await using boxd = new Boxd({ apiKey: "bxd_..." });
  await boxd.machines.list();
  // boxd.close() runs at scope exit
}
```

`await using` needs Node 20+, Bun, or Deno.

## 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.apiKeys` | 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:

```typescript
import { Boxd } from "@boxd-sh/sdk";

const boxd = new Boxd({ apiKey: "bxd_..." });

const machine = await boxd.machines.create({ name: "myapp" });
await boxd.machines.waitUntilReady(machine.id);

const result = await boxd.machines.exec(machine.id, { command: ["echo", "hello"] });
console.log(result.stdout);

await boxd.machines.delete(machine.id);
await 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.

### Machines

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

```typescript
const machine = await boxd.machines.create({ name: "myapp" });
const one     = await boxd.machines.get(machine.id);   // id or name
const all     = await boxd.machines.list();            // Machine[]
await boxd.machines.delete(machine.id);
await boxd.machines.deleteSelf({ confirm: "myapp" }); // inside a machine: delete the machine this code runs on
```

`deleteSelf()` only works inside a machine (on Node), 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(ownId)` from inside a machine. See [Self-delete](/guides/self-delete.md).

`list()` returns a plain array. Pass `{ org: "acme" }` for one organization's machines, or `{ allContexts: true }` for everything you can reach.

State:

```typescript
await boxd.machines.start(id);
await boxd.machines.stop(id);
await boxd.machines.reboot(id);
await boxd.machines.pause(id);        // standby, in RAM: { suspendUs }
await boxd.machines.resume(id);       // { resumeUs }
await boxd.machines.hibernate(id);    // hibernated, on disk
await boxd.machines.wake(id);
```

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

Everything else:

```typescript
const fork = await boxd.machines.fork(id, { name: "myapp2" });   // live copy of memory and disk
await boxd.machines.share(id);        // visible to your whole org
await boxd.machines.unshare(id);
await boxd.machines.rename(id, "new-name");            // returns the new name
await boxd.machines.setNetworks(id, ["backend"]);      // replaces the whole set
await boxd.machines.setAutoSuspendTimeout(id, 300);    // seconds, 0 disables (the default)
await boxd.machines.setAutoHibernateTimeout(id, 3600);
await boxd.machines.setBotProtection(id, "sleep_only"); // "on" | "sleep_only" | "off" (or true / false), see Bot protection
await boxd.machines.setIdleIgnoreOutbound(id, true);   // only inbound connections keep it awake, see Suspend, resume, and hibernate
await boxd.machines.setSsh(id, false);                 // nothing answers SSH; exec still works, see SSH below
await boxd.machines.setDeleteAfter(id, 7200);          // delete 2 h from now; resolves to the deadline, see Delete after
await boxd.machines.setDeleteAfterCron(id, "0 18 * * *"); // or at the next 18:00 UTC
await boxd.machines.setDeleteAfter(id, 0);             // clear the timer; resolves to null
for await (const chunk of boxd.machines.logs(id)) {}   // console output (Uint8Array); { follow: true } keeps it open
await boxd.machines.waitUntilReady(id);                // running and exec works
await boxd.machines.suggestName();                     // 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 `waitUntilReady` before doing anything that depends on it running, and especially before [forking](/guides/fork.md) it again. It polls for up to 90 seconds by default (`{ timeout, pollInterval }`, both in milliseconds).

#### Creating machines

```typescript
await boxd.machines.create({
  name: "myapp",
  image: "ubuntu:24.04",
  env: { API_URL: "https://example.com" },
  cmd: ["/usr/local/bin/start"],
  restartPolicy: "always",                 // "always" | "never"
  networks: ["backend", "cache"],          // machine-to-machine reachability, see Networks
  isolated: false,                         // sandbox, fixed at creation
  deleteAfter: 3600,                       // delete-after timer: seconds from now...
  // deleteAfterCron: "0 18 * * *",        // ...or the next match of a cron expression (UTC)
  config: {
    vcpu: 2,
    memory: "8G",
    autoSuspendTimeout: 300,               // seconds, 0 disables
    autoDestroyTimeout: 0,
    idleIgnoreOutbound: true,              // only inbound connections keep it awake; unset = the org's default
    ssh: true,                             // false: nothing answers SSH; leave out for on, or a fork's or snapshot's setting
    proxies: [{ name: "api", port: 3000 }],
    volumes: [{ diskId: "d_...", mountPath: "/data" }],
  },
});

// In an organization. `shared` makes it visible to every member.
await boxd.machines.create({ org: "acme", shared: true });

// Create a machine from a snapshot.
await boxd.machines.create({ fromSnapshot: "my-workspace", name: "myapp2" });

// Create a machine from a machine spec. See Machine specs below.
await boxd.machines.create({ name: "mike-dev", org: "acme", spec: Machine.spec().size("2x8").network("eng") });
```

Every field is optional, and `create({})` boots the [default image at the default size](/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. `config.memory` takes `"4G"`, `"8G"`, `"16G"`, or `"32G"`. Every machine gets a fixed 100 GB disk, so leave `config.disk` out. Any other value is refused.

`fork(id, { name, shared, networks, isolated, config })` inherits anything you leave out from the source machine, including its `networks`. A fork, and a machine created from a snapshot, starts its source's [automations](/guides/automations/jobs.md#forks-and-snapshots) paused so nothing runs twice: the returned `Machine` has `pausedAutomations` set to how many, and the call logs a `console.warn` when it isn't 0. A fork, and a machine created from a snapshot, keeps its source's size. `config.vcpu`, `config.memory`, `config.disk` and `config.volumes` are refused on both, and `config.autoSuspendTimeout` and `config.idleIgnoreOutbound` are accepted. Left unset, `config.idleIgnoreOutbound` keeps the source's value rather than taking the org default. Change the size afterwards with `resize`:

```typescript
await boxd.machines.resize(id, { memory: "16G" });   // or { vcpu: 4 }, returns { vcpu, memoryBytes, 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({ fromSnapshot })`. 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.

> [!NOTE]
>
> A machine created from a snapshot resumes as it was captured, so `create({ fromSnapshot })` takes only `name`, `org`, `isolated`, `config.autoSuspendTimeout`, and `config.idleIgnoreOutbound`. Passing `image`, `env`, `cmd`, `restartPolicy`, `shared`, or `networks` alongside it is a **type error**, and the two ways of creating a machine are separate shapes that the compiler keeps apart. Plain JavaScript, which has no compiler to catch it, gets the same refusal at runtime. `networks` are replayed from the snapshot. Set them afterwards with `setNetworks`. 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](/guides/machine-specs.md) for the whole picture.

```typescript
import { Machine, team, snapshot, github, slack, jira, claude, secrets } from "@boxd-sh/sdk";

const 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());

const mike = engineering
  .size("2x8")
  .with(slack(), jira({ shared: "jira" }), secrets("NPM_TOKEN"));
const m = await boxd.machines.create({ name: "mike-dev", org: "acme", spec: mike });
m.spec;          // the spec as it stands (updateSpec, and label, network, egress and size edits, change it)
m.createdSpec;   // the spec it was created with, never changed
mike.resolve();  // the same spec as plain data, 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"` |
| `.assignTo(userId)` | `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 `MachineSpec`, as plain data |

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 `MachineSpecPiece` object (`{ 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 throws a `BoxdError` 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`. `mergeSpecs(...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` or `config` sizing beside it (a type error). 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({ fromSnapshot, 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](/guides/machine-specs.md#secrets).

**For someone else.** An org owner or admin can create a machine for another member with `.assignTo(userId)`, the member's id as `orgs.getMembers()` 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 `deleteAfter`. The member sees `createdBy` and `createdByName` 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, `updateSpec` can't change that machine's own `egress` or `secrets`, and `assignTo` 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 `updateSpec` patch is at most 256 KiB.

#### Updating a machine's spec

`updateSpec` 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:

```typescript
// Patch: a field left out is untouched, a scalar replaces, maps merge key by
// key (null removes a key), a list replaces the whole list, null removes a field.
await boxd.machines.updateSpec("mike-dev", {
  labels: { owner: "mike", team: null },
  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.
await boxd.machines.updateSpec("mike-dev", (s) => s.network("ops").env("LOG_LEVEL", "debug"));

// Dry run: the diff, nothing changed.
const diff = await boxd.machines.updateSpec("mike-dev", { size: "4x16" }, { dryRun: true });
for (const c of diff.changes) console.log(c.field, c.apply, c.note, c.warnings);
if (diff.rebootRequired) {
  await boxd.machines.updateSpec("mike-dev", { size: "4x16" }, { reboot: true });
}

// Run the packages again from the one that failed.
await boxd.machines.updateSpec("mike-dev", {}, { retryPackages: true });

// A patch built from a spec you read: nothing applies if the spec changed since.
const { spec } = await boxd.machines.get("mike-dev");
if (spec) {
  await boxd.machines.updateSpec("mike-dev", { networks: [...(spec.networks ?? []), "ci"] }, { expectedSpec: spec });
}
```

| Option | |
| - | - |
| `dryRun` | Return the diff and change nothing. |
| `reboot` | 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. |
| `retryPackages` | 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 (`{}`). |
| `expectedSpec` | The spec you read (`machine.spec`). If the machine's spec is no longer that one, nothing is applied and the call throws `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 (`retryPackages`: 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 |

```typescript
interface MachineSpecUpdate {
  changes: MachineSpecChange[];  // every changed field, in the spec's order
  rebootRequired: boolean;       // a change applies only through a reboot
  rebootRecommended: boolean;    // a change reaches running processes only once they restart
  spec: MachineSpec;             // the spec after the patch (for a dry run, what it would be)
  applied: boolean;              // false for a dry run
  rebooted: boolean;             // the machine was rebooted to apply it
  resizeError: string | null;    // the resize failed after the rest applied (below)
}

interface MachineSpecChange {
  field: string;                 // "labels", "size", "packages", ...
  apply: "live" | "reboot_recommended" | "reboot" | "refused";
  added: string[];               // map keys, list entries or commands added
  removed: string[];
  changed: string[];             // map keys whose value changes (values are never shown)
  before: string | null;         // scalars (size, base, assignTo, isolated)
  after: string | null;
  note: string;                  // what happens on the machine, in one sentence
  warnings: string[];            // 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 throws `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: `resizeError` says why, and `spec` has the size the machine has.

The patched spec is checked like a create's. `machine.createdSpec` 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 throws, so use a patch to replace or remove. `specPatch(from, to)` computes the patch the builder form sends.

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

```typescript
await boxd.machines.setNetworks(id, ["backend", "cache"]);  // returns the set now in effect
await boxd.machines.setNetworks(id, []);                    // back to the default network
const { networks, isolated } = (await boxd.machines.get(id)).networking;
```

`setNetworks` **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 `setNetworks` 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](/use-cases/sandboxes.md).

#### Egress allowlist

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

```typescript
await boxd.machines.setEgressAllow(id, ["api.stripe.com", "*.github.com", "203.0.113.0/24"]);
(await boxd.machines.get(id)).egressAllow;    // string[]: empty = unrestricted
await boxd.machines.setEgressAllow(id, ["none"]); // nothing is reachable
await boxd.machines.setEgressAllow(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](/cli/commands.md#turn-ssh-off).

```typescript
await boxd.machines.create({ name: "task-1", config: { ssh: false } }); // born with SSH off
await boxd.machines.setSsh(id, true);         // back on, same port
(await boxd.machines.get(id)).ssh;            // boolean
```

`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 `config.ssh` says otherwise. From inside a machine, on its own credentials, `setSsh` 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

```typescript
interface Machine {
  id: string;
  name: string;
  status: MachineStatus;   // "pending" | "starting" | "running" | "suspended" |
                           // "hibernated" | "stopped" | "failed" | "destroyed" | "migrating"
  imageRef: string;        // the image the machine boots
  restartPolicy: string | null;
  createdAt: Date | null;

  resources: {             // the machine's CPU, memory and disk
    vcpu: number;
    memoryBytes: number;
    diskBytes: number;     // always the fixed 100 GB allocation, not usage
  };

  org: { id: string; name: string } | null;   // null = your default org
  shared: boolean;         // shared with that org, or private to you

  networking: {            // who it can reach inside the org: see Networks
    networks: string[];    // empty = the org's default network
    isolated: boolean;     // set at creation, a fork always inherits it
  };

  egressAllow: string[];   // the egress allowlist, empty = unrestricted

  access: {
    sshPort: number | null;  // the port to SSH to, null if it has none yet
    domain: string;          // the domain the machine is addressed under
    url: string;             // the machine's public HTTPS address
    desktopUrl: string;      // its live Desktop view in the console
    customDomains: CustomDomain[];   // custom domains bound to this machine
  };

  idle: {                  // seconds of inactivity before each action, 0 disables
    suspendAfter: number;
    hibernateAfter: number;
    destroyAfter: number;
  };

  botProtectionMode: "on" | "sleep_only" | "off" | null;  // see Bot protection
  botProtection: boolean;  // true for "on" and "sleep_only"
  idleIgnoreOutbound: boolean;  // only inbound connections keep it awake, see Suspend, resume, and hibernate
  ssh: boolean;            // SSH answers on access.sshPort, on by default

  source: MachineSource | null;    // null = booted from an image
  hibernatedAt: Date | null;       // when it went to disk, null = not hibernated
  deleteAt: Date | null;           // when the delete-after timer deletes it, null = no timer
  deleteAfterCron: string | null;  // the cron expression it was set with, if any
  lastConnectedAt: Date | null;    // null = never connected
  bootTimeMs: number | null;       // how long the last boot took

  spec: MachineSpec | null;        // the machine spec it runs under, null = none
  createdSpec: MachineSpec | null; // the spec it was created with
  createdBy: string | null;        // who created it for you (spec assignTo), null = you did
  createdByName: string | null;    // a name to show for createdBy
  requirements: MachineRequirement[]; // the spec's connections and agents, and whether each is met
  packages: MachinePackage[];      // the spec's packages and how each went
}

interface MachineRequirement {
  kind: "connection" | "agent";
  name: string;                    // integration ("slack", "github-app") or agent ("claude", "codex")
  scope: "personal" | "shared";
  tag: string | null;              // the shared connection's name
  met: boolean;                    // connected now
  canFix: boolean;                 // you could connect it
  reason: string | null;           // why this machine can't get it (isolated, shared, ...)
}

interface MachinePackage {
  command: string;
  state: "pending" | "running" | "done" | "failed" | "skipped";
  exitCode: number | null;         // null until it exits, and for a timeout or an interrupted run
  outputTail: string;              // the last 4 KiB of its output; empty from list(), get() has it
  reason: string | null;           // why there is no exit code, or that a restored snapshot ran it
  startedAt: Date | null;
  finishedAt: Date | null;
}

interface MachineSource {
  kind: "fork" | "snapshot";
  name: string;                    // the source machine, or the snapshot name
  version: number | null;          // the snapshot version, a fork has none
  id: string | null;               // the machine or snapshot this came from
}
```

`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](/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. `canFix` 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](/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 (`updateSpec(id, {}, { retryPackages: true })`), or until the failed command is removed from the spec, which marks it `"skipped"` and lets the rest run. In `outputTail` the value of every secret the machine gets shows as `[secret NAME]`. `list()` leaves `outputTail` empty to keep lists small, and `get()` has it. See [Packages](/guides/machine-specs.md#packages).

Every machine status the SDK knows is exported as `MACHINE_STATUSES`, with `isKnownMachineStatus(s)` to check one. An unrecognized status is passed through rather than thrown on, 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 `waitUntilReady` before the first `exec`.

One-shot exec collects the output:

```typescript
const r = await boxd.machines.exec(id, { command: ["python", "script.py"] });
r.stdout;    // string
r.stderr;    // string
r.exitCode;  // number
r.success;   // boolean: true when the command exited 0

await boxd.machines.exec(id, {
  command: ["sh", "-c", "echo $FOO"],
  env: { FOO: "bar" },
  timeout: 30_000,          // milliseconds
});
```

An array `command` is shell-quoted for you, while a string is passed through as a shell command line. `timeout` is in milliseconds and cancels the call, though the remote process may keep running. `exec` also takes `tty`, `cols` and `rows`. Under a PTY the terminal layer merges stderr into stdout, so `stderr` comes back empty and everything lands in `stdout`.

Interactive and PTY sessions use a stream handle, the one stateful object besides the client:

```typescript
const stream = boxd.machines.streamExec(id, { command: "bash", tty: true });

stream.write("echo hello\n");
for await (const chunk of stream) process.stdout.write(chunk);
const code = await stream.wait();
stream.close();
```

Without `tty`, stderr arrives separately on `stream.stderr`, which is useful when a tool's progress goes to stderr and its answer to stdout. With `tty`, the terminal layer merges the two onto stdout, as terminals do.

For TUI apps, pass the initial geometry and forward resizes:

```typescript
const stream = boxd.machines.streamExec(id, {
  command: "vim",
  tty: true,
  cols: process.stdout.columns,
  rows: process.stdout.rows,
});
process.stdout.on("resize", () =>
  stream.resize(process.stdout.columns, process.stdout.rows),
);
```

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 `closeStdin: true` to send EOF immediately, or call `stream.end()` yourself. It is rejected together with `tty`, where stdin must stay open.

#### Files

```typescript
await boxd.machines.files.upload(id, "/app/file.txt", "text content");
await boxd.machines.files.upload(id, "/app/file.bin", new Uint8Array([1, 2, 3]));
await boxd.machines.files.upload(id, "/app/app.py", { fromPath: "local.py" });
const bytes = await boxd.machines.files.download(id, "/app/output.json");
```

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

Directories are managed with the same namespace:

```typescript
const listing = await boxd.machines.files.listDir(id, "/home/boxd");   // DirListing
for (const e of listing.entries) e.name, e.isDir, e.sizeBytes, e.permissions, e.modifiedAt;
listing.truncated;                                                       // true past 5,000 entries

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

`listDir` 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](/guides/port-forwarding.md). Max 3 per machine.

```typescript
const fwd = await boxd.machines.ports.expose(id, 5432, { protocol: "tcp" });
fwd.dns;          // hostname to connect to
fwd.publicPort;   // port to connect on
fwd.machinePort;  // the port inside the machine
fwd.protocol;     // "tcp" | "udp" | "both"

await boxd.machines.ports.list(id);   // one machine's forwards
await boxd.machines.ports.list();     // every forward you own
await 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](/guides/proxies.md). The machine argument takes an id or a name, like everywhere else.

```typescript
await boxd.machines.proxies.create(machine.name, "api", 3000);
const routes = await boxd.machines.proxies.list(machine.name);
routes[0].port;        // number: where traffic actually goes
routes[0].portMode;    // "locked" (you pinned it) | "auto" (detected for you)
routes[0].domain;
routes[0].isDefault;

await boxd.machines.proxies.setPort(machine.name, 3001, { name: "api" });
await boxd.machines.proxies.setPort(machine.name, "auto");   // default route, auto-detected
await boxd.machines.proxies.delete(machine.name, "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 `setPort` addresses when you leave `name` off.

#### Checkpoints

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

```typescript
await boxd.machines.checkpoints.create(id, "before-upgrade");   // machine must be running
const points = await boxd.machines.checkpoints.list(id);
points[0].status;      // "pending" | "ready" | "failed"
points[0].available;   // restorable right now
points[0].sizeBytes;
points[0].createdAt;

await boxd.machines.checkpoints.restore(id, "before-upgrade");
await 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](/guides/disaster-recovery.md). Restoring one rewrites the disk only, not memory or running state.

```typescript
const backupId = await boxd.machines.backups.trigger(id);   // back up now, returns the new backup id

await boxd.machines.backups.setSchedule(id, { intervalSecs: 86400, retentionSecs: 30 * 86400 });
// or a wall-clock cron schedule instead of a fixed interval:
await boxd.machines.backups.setSchedule(id, { cron: "0 3 * * *", retentionSecs: 30 * 86400 });

const schedule = await boxd.machines.backups.schedule(id);   // null when there's no schedule

const list = await boxd.machines.backups.list(id);
list[0].status;      // "pending" | "ready" | "dedup" | "failed"
list[0].sizeBytes;
list[0].createdAt;

await boxd.machines.backups.restore(id, list[0].id);   // destructive, in-place
await boxd.machines.backups.delete(id, list[0].id);
await boxd.machines.backups.clearSchedule(id);
```

Pass exactly one of `intervalSecs` or `cron` to `setSchedule`. 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 answers with the screen's size, where the pointer is, and a screenshot taken after the action when you ask for one. See [Computer use](/guides/computer-use.md).

```typescript
const computer = boxd.machines.computer;

const { screenshot } = await computer.screenshot(id);  // PNG bytes in .data; mimeType, width, height
await computer.screenshot(id, { format: "jpeg", maxWidth: 1280, maxHeight: 800 });  // scaled to fit
await computer.screenshot(id, { region: { x: 0, y: 0, width: 400, height: 300 } }); // part of the screen

await computer.click(id, { x: 640, y: 360 });           // also button, count (2: double), modifiers
await computer.move(id, 100, 100);
await computer.drag(id, [{ x: 10, y: 10 }, { x: 200, y: 10 }]);
await computer.mouseDown(id, { x: 100, y: 100 });
await computer.mouseUp(id, { x: 300, y: 200 });
await computer.scroll(id, { x: 640, y: 360, dy: 3 });   // wheel clicks; positive scrolls down
await computer.type(id, "hello", { screenshot: true }); // result.screenshot shows the screen after
await computer.key(id, "ctrl+s");                       // X key names; "+" joins a combination; repeat, holdMs
await computer.wait(id, 1000);
const { screenWidth, screenHeight, cursor, screenHeld } = await computer.cursorPosition(id);

await computer.setScreenSize(id, 1280, 800);            // hold the screen at this size
await computer.releaseScreenSize(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. A mouse or keyboard action is sent again only when it can't have reached the machine. After any other failure, take a screenshot to see whether it ran.

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

`ClaudeComputer` and `OpenAIComputer` run a model's computer-use tool calls on a machine. They take and return plain objects, so they work with the official SDKs without depending on them.

```typescript
import { ClaudeComputer, OpenAIComputer } from "@boxd-sh/sdk";

const claude = new ClaudeComputer(boxd, "my-machine");  // maxWidth, maxHeight, screenSize, region
claude.tool;                                            // for tools: [...]: { type: "computer_toolset_20260801" }
const results = await claude.run(response.content);     // one tool_result per action, for the next user message
await claude.release();                                 // let go of the screen

const openai = new OpenAIComputer(boxd, "my-machine");
openai.tool;                                            // { type: "computer" }
const outputs = await openai.run(response.output);      // a computer_call_output per computer_call
```

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

### Snapshots

Named captures of a running machine's memory and disk. See [Snapshots](/guides/snapshots.md). Create a machine from one with `machines.create({ fromSnapshot })`.

```typescript
await boxd.snapshots.create(id, "my-workspace");
const snap = await boxd.snapshots.get("my-workspace");
await boxd.snapshots.list();
await boxd.snapshots.delete("my-workspace");
```

Saving under an existing name replaces the version, and older versions cannot be restored or pinned. A `Snapshot` carries `createdAt` (the first capture), `updatedAt` (the most recent one), `version`, `status`, `sizeBytes`, `vcpu`, `memoryBytes` and `useCount`. `get`, `list` and `delete` take an optional `{ org }`. `create` returns a `CreatedSnapshot` whose `pausedAutomations` is how many of the machine's automations it captured: every machine created from it starts them paused, and the call logs a `console.warn` when it isn't 0.

### Disks

```typescript
const disk = await boxd.disks.create("data", "10G");
await boxd.disks.attach(disk.id, id, "/mnt/data");
await boxd.disks.attach(disk.id, id, "/mnt/data", { readOnly: true });
await boxd.disks.detach(disk.id, id);
await boxd.disks.list();
await 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 `config.volumes`. 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](/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](/guides/env-secrets.md). The difference is what comes back: an env var has a readable `value`, a secret does not.

```typescript
await boxd.env.set("API_URL", "https://example.com", { scope: "all" });
await boxd.env.list();       // [{ name, scope, value }]
await boxd.env.delete("API_URL", { scope: "all" });

await boxd.secrets.set("STRIPE_KEY", "sk_live_...", { scope: "private" });
await boxd.secrets.list();   // [{ name, scope, domains, boundMachines }]: no values
await boxd.secrets.delete("STRIPE_KEY", { scope: "private" });
```

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

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

```typescript
await boxd.secrets.set("NPM_TOKEN", "npm_...", { scope: "unattached", org: "acme" });
const m = await boxd.machines.create({ name: "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 `boundMachines`, 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](/guides/env-secrets.md#unattached-secrets).

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

```typescript
await boxd.secrets.move("STRIPE_KEY", { from: "private", to: "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](/guides/env-secrets.md#host-bound-secrets).

```typescript
await boxd.secrets.set("STRIPE_KEY", "sk_live_...", { scope: "all", domains: ["api.stripe.com"] });
(await boxd.secrets.list())[0].domains;   // string[]: 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](/guides/egress).

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

```typescript
await boxd.machines.setEgressAllow(id, ["api.stripe.com", "*.npmjs.org", "203.0.113.0/24"]);
(await boxd.machines.get(id)).egressAllow;   // string[], empty = unrestricted
await boxd.machines.setEgressAllow(id, ["none"]); // an allowlist with nothing in it: nothing is reachable
await boxd.machines.setEgressAllow(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:

```typescript
await boxd.secrets.set("STRIPE_KEY", "sk_live_...", { scope: "all", domains: ["api.stripe.com"] });
await boxd.secrets.list();   // [{ name, scope, domains, boundMachines }]
```

A [machine spec](#machine-specs) can set the allowlist from birth with `.egress(...)`. From inside a machine, on its own credentials, `setEgressAllow` 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](/guides/custom-domains.md).

```typescript
const domain = await boxd.domains.create({ domain: "app.example.com", machine: machine.id });
domain.status;      // "pending" | "active"
domain.lastError;   // empty once active

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

### Organizations

```typescript
const orgs = await 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].isAdmin;
orgs[0].isDefault;   // your default org

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

#### Members and invites

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

```typescript
const roster = await boxd.orgs.getMembers("acme");
roster.members[0].userId, roster.members[0].role;         // "owner" | "admin" | "member"
roster.members[0].displayName, roster.members[0].githubUsername;
roster.invites[0].email, roster.invites[0].role, roster.invites[0].expiresAt;
roster.invites[0].acceptUrl;                              // interactive login only, empty otherwise

const invite = await boxd.orgs.invite("alice@example.com", { role: "member", org: "acme" });
await boxd.orgs.revokeInvite(invite.token);
await boxd.orgs.setMemberRole("usr_...", "admin", "acme");   // or "member" to demote
await boxd.orgs.removeMember("usr_...", "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.

```typescript
await boxd.orgs.setMachineDefaults("acme", { vcpu: 2 });   // or { memory: "8G" }
const d = await boxd.orgs.getMachineDefaults("acme");
d.isSet, d.vcpu, d.memoryBytes, d.ceilingVcpu, d.ceilingMemoryBytes;
await boxd.orgs.clearMachineDefaults("acme");
```

#### Idle clock default

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

```typescript
const r = await boxd.orgs.setIdleIgnoreOutboundDefault("acme", { enabled: true });
r.machinesChanged, r.snapshotsChanged, r.machinesSkipped;
await boxd.orgs.setIdleIgnoreOutboundDefault("acme", { enabled: true, newMachinesOnly: true });
const d = await boxd.orgs.getIdleIgnoreOutboundDefault("acme");
d.isSet, d.enabled, d.platformEnabled;   // platformEnabled: what new machines get without an org default
await boxd.orgs.clearIdleIgnoreOutboundDefault("acme");   // existing machines keep their value
```

#### Bot protection default

The [bot protection](/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 `{ newMachinesOnly: true }` to change only new machines. Setting or clearing requires org admin, and any member can read it.

```typescript
const r = await boxd.orgs.setBotProtectionDefault("acme", "on");   // "on" | "sleep_only" | "off"
r.machinesChanged, r.snapshotsChanged, r.machinesOff, r.machinesSkipped;
await boxd.orgs.setBotProtectionDefault("acme", "sleep_only", { newMachinesOnly: true });
const d = await boxd.orgs.getBotProtectionDefault("acme");
d.isSet, d.mode, d.platformMode;   // platformMode: what new machines get without an org default
await boxd.orgs.clearBotProtectionDefault("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: `maxVms` 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 throws `ConflictError` until the limit changes, and the owner gets an email when it does. Anyone else gets `PermissionDeniedError`.

```typescript
const l = await boxd.orgs.getMachineLimit("acme");
l.maxVms, l.vmCount, l.isOwner;
l.request;                    // MachineLimitRequest | null: .requestedAt, .maxVms
const r = await boxd.orgs.requestMachineLimit(100, { message: "CI runners", org: "acme" });
r.requestedAt, r.maxVms;
```

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

#### Wildcard domain

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

```typescript
const domain = await boxd.orgs.setDomain("acme", "preview.mysaas.com");   // call only once NS delegation is live
domain.status;    // "pending" | "active"

await boxd.orgs.getDomain("acme");     // null if unset
await boxd.orgs.clearDomain("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](/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.

```typescript
const nyc = new Boxd({ region: "nyc" });
await nyc.machines.create({ name: "web" });                     // created in New York
await boxd.machines.exec("web", { command: "uptime", region: "nyc" });
await boxd.snapshots.list({ region: "nyc" });

const one = await boxd.machines.list();                         // the client's region
one.elsewhere;                                                  // [{ region: "nyc", count: 3 }]
const all = await boxd.machines.list({ region: "all" });        // every region the org has
all.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`.

```typescript
const regions = await 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].orgState;                                 // "enabled" | "requested" | "available"

await boxd.orgs.requestRegion("nyc", "acme");        // org admins: "requested", or "enabled" if it is
await boxd.orgs.setDefaultRegion("nyc", "acme");     // org admins
await boxd.orgs.getDefaultRegion("acme");            // "nyc", or null
await boxd.orgs.clearDefaultRegion("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 `getDefaultRegion` 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](/guides/organizations.md#teams).

```typescript
const team = await boxd.teams.create("backend", "acme");   // org admin only
await boxd.teams.list("acme");                             // every team for an admin, your own otherwise
const t = await boxd.teams.get(team.id);
t.name, t.orgId, t.isAdmin;                                // isAdmin: you have team-admin authority
t.members[0].userId, t.members[0].role;                    // "admin" | "member"
t.defaultSnapshotId;                                       // null = none

await boxd.teams.addMember(team.id, "usr_...");            // must already be an org member
await boxd.teams.setMemberRole(team.id, "usr_...", "admin");
await boxd.teams.removeMember(team.id, "usr_...");
await boxd.teams.setDefaultSnapshot(team.id, snapshot.id); // a shared snapshot of the org
await boxd.teams.setDefaultSnapshot(team.id, null);        // clear
await boxd.teams.rename(team.id, "platform");
await 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](/cli/commands.md#usage-and-billing).

```typescript
// One machine over its whole life, or pass { since, until } (Date or unix seconds).
// A deleted machine is found by its id or name ({ org } says where to look).
const u = await boxd.machines.usage("myapp");
u.seconds.running; u.seconds.standby; u.seconds.hibernated; u.seconds.stopped;
u.costMicro / 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.vcpuHours; u.ramGibHours; u.diskGibHours;   // 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.
const r = await boxd.orgs.usage({ since: new Date("2026-09-01") });
r.totalCostMicro; r.currency;
for (const m of r.machines) console.log(m.name, m.status, m.costMicro / 1e6);

// Billing activity: what was actually charged, newest first.
for await (const e of boxd.orgs.billingActivity({ since: new Date("2026-09-01") })) {
  console.log(e.createdAt, e.kind, e.amountMicro / 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.

```typescript
await boxd.machines.delete(id);
// ...a little later, or from a periodic job:
const u = await boxd.machines.usage(id);
if (u.complete) save(id, u.costMicro, 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.billingActivityPage()` returns one page with its `nextPageToken` when you want to page by hand.

### API keys

```typescript
const key = await boxd.apiKeys.create({ name: "ci", org: "acme" });
key.apiKey;      // shown once: store it now
key.expiresAt;   // null = no expiry

await boxd.apiKeys.list();     // id, name, keyPrefix, createdAt, lastUsedAt, expiresAt, org, kind, createdBy, mine
await boxd.apiKeys.delete(key.id);
```

Pass `expiresIn` (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. `createdBy` 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 `apiKeys.*`, so an API key can never mint more keys.

### Account

```typescript
const me = await boxd.account.get();
me.userId;
me.displayName;           // null falls back to userId
me.sshKeyFingerprints;
me.billing.maxVms;              // your effective quota
me.billing.subscriptionStatus;  // null = never subscribed

await boxd.account.linkSshKey({ pubkey: "ssh-ed25519 AAAA..." });

const cfg = await boxd.account.config();
cfg.defaultImage;
cfg.zone;
```

`linkSshKey` takes the verbatim contents of a `.pub` file and lets you SSH to your machines with it. Pass `deviceId` 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, `linkSshKey` requires an interactive-login credential rather than an API key.

## Errors

```typescript
import { NotFoundError } from "@boxd-sh/sdk";

try {
  await boxd.machines.get("nope");
} catch (e) {
  if (e instanceof NotFoundError) { /* ... */ }
}
```

Everything thrown extends `BoxdError`:

| Class | Meaning |
| - | - |
| `AuthenticationError` | the credential was rejected, or none was found |
| `PermissionDeniedError` | authenticated, but not allowed |
| `NotFoundError` | no such resource |
| `ConflictError` | already exists, the resource is in the wrong state, or it changed while the call ran |
| `RateLimitError` | quota or rate limit reached |
| `RegionNotEnabledError` | a `PermissionDeniedError` for a region the org can't use, with `region` and `orgState` |
| `APIStatusError` | any other error returned by the server |
| `APIConnectionError` | the connection failed, or the server was unavailable |

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 `grpcCode`, 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 rejected parameter, have no `grpcCode`:

```typescript
import { BoxdError } from "@boxd-sh/sdk";

try {
  await boxd.machines.create({ name: "myapp" });
} catch (e) {
  if (e instanceof BoxdError && e.grpcCode === 8 /* RESOURCE_EXHAUSTED */) {
    // hit your quota: surface a 'wait or upgrade' path
  }
  throw e;
}
```
