# TypeScript SDK (https://kumoba.dev/typescript)

```sh
npm install kumoba
```

The package needs Node 22 or later and depends only on `zod`. It also installs the [`kumoba` CLI](/cli).

## Connect [#connect]

```ts
import { Kumoba } from "kumoba";

const kumoba = new Kumoba();
```

With no options it finds the daemon through `~/.kumoba`. To reach another daemon, pass `url` and `token` or set `KUMOBA_URL` and `KUMOBA_TOKEN`:

```ts
const kumoba = new Kumoba({
  url: "unix:///path/to/kumobad.sock",          // or http://127.0.0.1:7788
  token: "...",
  publicUrl: "https://sandboxes.example.com",   // where browsers reach the preview listener
});
```

For a daemon on another machine, use its `https://` URL. `ca` trusts a private CA instead of the public ones, and `cert` and `key` present a client certificate when the daemon requires mutual TLS. Each defaults to the file `KUMOBA_CA_FILE`, `KUMOBA_CERT_FILE` or `KUMOBA_KEY_FILE` names when the URL is `https://`. With a socket or `http://` URL from `KUMOBA_URL` (or the default), a set variable, even an empty one, is an error, as in the CLI; with a socket or `http://` `url` passed in code, the variables are ignored. See [Run sandboxes on another machine](/guide/remote-daemon).

```ts
import { readFileSync } from "node:fs";

const remote = new Kumoba({
  url: "https://sandboxes.example.com:7788",
  token: "...",
  ca: readFileSync("ca.pem"),
  cert: readFileSync("client.pem"),
  key: readFileSync("client.key"),
});
```

## Run code once [#run-code-once]

```ts
const result = await kumoba.run("python3 --version", { image: "default" });
result.ok; result.exitCode; result.stdout; result.stderr; result.timedOut;
```

A string runs through `/bin/sh -c`; an array is the program and its arguments. `run` never throws on a non-zero exit.

## Work in a sandbox [#work-in-a-sandbox]

```ts
const sandbox = await kumoba.create({
  image: "default",
  cpu: 2,
  memoryMib: 4096,
  user: "kumoba",                          // default user for commands and files
  network: { allow: ["api.github.com"] },  // "open" | "blocked" | { allow: [...] }
  autoStopMinutes: 15,
  labels: { project: "demo" },
});

const r = await sandbox.run(["python3", "script.py"], {
  cwd: "/workspace",
  env: { PYTHONUNBUFFERED: "1" },
  timeoutMs: 60_000,
  onStdout: (text) => process.stdout.write(text),
});

await sandbox.files.write("/workspace/a.txt", "hi");
await sandbox.files.upload("./local.csv", "/workspace/data.csv");
const text = await sandbox.files.readText("/workspace/a.txt");

await sandbox.stop();
await sandbox.start();
await sandbox.delete();
```

`files.write()` and `files.upload()` create missing parent directories as the acting user, or as root when no user is set, so a write to `/workspace/src/app/main.py` needs no `files.mkdir()` first. File methods run as a user have the permissions `run()` has as that user, supplementary groups included. [Files](/http-api#files) has the owner, group and mode of created directories and the limits.

`create()` creates and boots the sandbox in one request. When every running slot is in use (`KUMOBAD_MAX_RUNNING`) it throws a `KumobaError` with code `capacity` and `retryable: true` at once, before kumobad copies any disk, and nothing is left to delete. `waitMs` makes kumobad wait up to that many milliseconds (at most 600000) for a free slot first, and `kumoba.run()` takes it too; keep `timeoutMs`, if you set one, above it. `kumoba.capacity()` returns `{ running, maxRunning, maxRunningSource, memoryMibInUse }`, plus `macosRunning` and `macosMaxRunning` on a Mac and `memoryMibBudget` when kumobad admits by memory (`KUMOBAD_ADMIT_BY_MEMORY=1`), to wait or queue instead of trying blindly. A sandbox larger than that whole budget throws code `exceeds_host_memory` (status 422), which is not retryable. Its `disk` (also on `info()`) has `freeBytes`, `totalBytes`, `stoppedSandboxBytes` and `minFreeBytes`; through a fleet it is `undefined`, since each host reports its own under `hosts`. When the host is short of disk, `create()` and `run()` throw code `disk_full` (status 507) with `retryable: false`, since waiting does not free space. `kumoba.pruneStopped({ olderThanMs, dryRun })` deletes stopped sandboxes that stopped at least `olderThanMs` ago, oldest first, and returns `{ dryRun, sandboxes: [{ id, createdAt, stoppedAt, bytes }], freedBytes }`; with `dryRun: true` it only lists them. On a filesystem with clones, `bytes` and `freedBytes` are an upper bound. Through a fleet, `host` prunes only that host, and leaving it out prunes every host. Through a fleet, the `disk_full` error's `diskFullHosts` names the hosts short of disk, so you can free one before you create again: `const host = error instanceof KumobaError ? error.diskFullHosts?.[0] : undefined; if (host !== undefined) await kumoba.pruneStopped({ olderThanMs, host });`. The result then also has `hosts`, `{ hostId, freedBytes }` per host that pruned, and `failedHosts`, `{ hostId, message, status?, mayHavePruned? }` per host that did not; `mayHavePruned: true` means the request reached that host but its answer was lost, so some of its sandboxes may be gone. When no host pruned, or the one host you named did not answer, `pruneStopped` throws a `KumobaError` with code `host_unavailable` that carries the same `failedHosts`, or `mayHavePruned: true` for a named host. Against kumobad 0.8 or earlier `create()` creates and then starts in two requests as before, deleting the sandbox when the start fails. The client remembers that for ten minutes, or until `capacity()` answers, which shows the daemon was upgraded; `waitMs` is refused there with `invalid_request`, and `capacity()` throws `not_found`.

A stopped sandbox moves to another host with `export()` and `import()`. The archive holds its disk, labels and settings, and the new sandbox arrives stopped with a new id:

```ts
import { createReadStream, createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";

await sandbox.stop();
await pipeline(await sandbox.export(), createWriteStream("sandbox.kumoba"));
const moved = await other.import(createReadStream("sandbox.kumoba"));
```

`import()` takes bytes or any stream of them, and `host` names the host under a fleet. `export()` of a running sandbox throws status 409, and of a macOS sandbox status 400. `import()` throws `invalid_request` for a damaged archive or one from another architecture, and `disk_full` or `exceeds_host_memory` like `create()`. Secrets stay behind, and the moved sandbox takes its whole disk on the new host.

`await using sandbox = await kumoba.create()` deletes the sandbox when the scope ends. It needs TypeScript 5.2 or later, or Node 24 for plain JavaScript.

## Ports, secrets and the desktop [#ports-secrets-and-the-desktop]

```ts
const link = await sandbox.expose(3000, { ttlSeconds: 600 });

await sandbox.setSecrets([
  { name: "gh", value: token, hosts: ["api.github.com"], envVars: ["GITHUB_TOKEN"] },
]);

await sandbox.desktop.start();
const png = await sandbox.desktop.screenshot({ settle: true });
await sandbox.desktop.click(200, 300);
await sandbox.desktop.type("hello");
await sandbox.desktop.hotkey("ctrl+s");

const view = await sandbox.desktop.liveView({ ttlSeconds: 600 });
console.log(view.url, view.viewer);
```

`expose()` and `liveView()` return the link kumobad sends, on its preview listener. When browsers reach that listener at another address, for example through a reverse proxy, pass `publicUrl` and the links start with it instead. Never point `publicUrl` at the API address: it serves previews only as downloads. `url` is `null` when kumobad has no preview listener and `publicUrl` is not set; `path` is always there.

`desktop.start()` asks kumobad to start the desktop, like `kumoba desktop`. On a Linux sandbox it returns once the desktop has drawn its first screen, so the next screenshot shows it, with the running processes and `painted: true`, such as `{ xvfb: true, xfce4: true, view: true, painted: true }`. When the screen is still one colour after 20 s it returns anyway, with `painted: false` and a `warning`. It throws a `KumobaError` with status 422 when the image has no desktop or its live view does not start listening. A macOS sandbox, or a kumobad from 0.16 or earlier, leaves `painted` out. `desktop.screenshot({ settle: true })` first waits up to 3 s for two captures in a row to match and not be one colour, like `kumoba screenshot --settle`, then takes the picture with the other options; it needs kumobad 0.17 or later. `hotkey()` and `press()` send the keys to kumobad, the same call `kumoba key` makes. It takes key names such as `Enter`, `ArrowLeft`, `PageUp` or `F5` in any case, and a letter after a modifier is the same key in either case, so `hotkey("ctrl+A")` is `ctrl+a`; a single letter on its own types that letter as written. The names are read by kumobad from the release after 0.17, with any image. Against kumobad 0.16 or earlier, which has no key route, `hotkey()`, `press()` and `screenshot({ settle: true })` throw `upgrade_required`.

`liveView()` returns a link to the [live view](/guide/desktop) and which viewer it opens: `stream`, kumoba's own, or `vnc`, the noVNC bridge that older images have, whose link is its ready-to-open `vnc.html` page. It asks kumobad, which starts the desktop when it isn't running. `liveView({ watchOnly: true })` returns a link that only watches: kumobad starts the desktop for it, and the engine ignores the page's keyboard, mouse and clipboard. When the sandbox has no such link, with the noVNC viewer, an image from 0.7.1 or earlier, or an older kumobad, it throws a `KumobaError` with code `upgrade_required` rather than return a link that controls the desktop. On a macOS sandbox `start()` and `liveView()` are the `desktop` methods that work: kumobad reads the screen on the host, and there is no desktop helper inside macOS for the others.

## Find sandboxes and read the access log [#find-sandboxes-and-read-the-access-log]

```ts
const sandboxes = await kumoba.list({ labels: { project: "demo" } });
const { sandboxes: newest, truncated } = await kumoba.listPage({ limit: 20 });
const one = await kumoba.get(id);
const unused = await kumoba.list({ idle: true, idleForMs: 10 * 60_000 });

for await (const entry of kumoba.accessLog({ since: new Date(Date.now() - 3_600_000) })) {
  console.log(entry.sandboxId, entry.host, entry.decision);
}
```

`list()` without `limit` returns every matching sandbox, newest first, so a cleanup loop over it reaches them all. If the daemon still cuts the list it throws a `KumobaError` with code `list_truncated` instead of returning part of it. `list({ limit })` returns at most `limit` sandboxes and does not say whether more matched. `listPage({ labels, limit })` returns `{ sandboxes, truncated }`, at most `limit` sandboxes (the daemon's default of 1000 when `limit` is left out) and whether more matched.

`kumoba.info()` returns what the host is, as `GET /v1/info` describes it: a stable `hostId`, the kumoba `version` and `guestProtocolVersion`, each image with its `sha256:` `digest` (`null` while kumobad is still hashing it), the `platform`, the `limits` and the host's `labels`. Against kumobad 0.9 or earlier it throws `not_found`.

`kumoba.drain()` takes the host out of service: from then on `create()` and `run()`, from any client, throw a `KumobaError` with code `draining`, which is not retryable, while running sandboxes carry on. `drain({ strict: true })` also makes `sandbox.start()` of a stopped sandbox throw `draining`. `kumoba.undrain()` puts the host back. `capacity()` and `info()` report `draining` and `drainStrict`. Each `drain()` call sets strictness anew, so `drain()` after `drain({ strict: true })` makes it a plain drain.

`list({ idle: true, idleForMs })` returns only started sandboxes with no open operation and no activity for `idleForMs` milliseconds, the test kumobad's auto-stop uses. Each sandbox's `info.activeOperations` counts its open commands, shells, file transfers and preview or live view connections, and `info.openPreviews` the preview and live view ones; a kumobad from 0.9 or earlier leaves both out and refuses `idle`.

`sandbox.stop({ ifIdleForMs })` stops the sandbox only if it is still idle when kumobad takes it, by the same test, so a command or preview that began after your `list()` is never cut off. Otherwise it throws a `KumobaError` with code `not_idle` and status 409, which is not retryable, and the sandbox keeps running. kumobad 0.10 and earlier refuse `ifIdleForMs` with `invalid_request`.

`list()` and `listPage()` throw a `KumobaError` with code `invalid_request`, before asking the daemon, when a `labels` key is empty or contains `:`, since a filter cannot express it, or when `limit` is not a whole number of 0 or more.

## Follow sandbox events [#follow-sandbox-events]

```ts
let cursor: string | undefined;
for (;;) {
  const page = await kumoba.events(cursor ? { cursor } : {});
  for (const event of page.events) console.log(event.type, event.sandboxId, event.at, event.reason);
  cursor = page.nextCursor ?? cursor;
  if (!page.truncated) await new Promise((resolve) => setTimeout(resolve, 5_000));
}
```

`events()` returns one page of the [event feed](/http-api#events): every sandbox being created, started, stopped (with `reason`) or deleted (with `reason: "disk_pressure"` when kumobad deleted it to make room for a create), and every network change (`network_changed`, with `previousMode`, `mode` and `revoked`, true when it closed open connections), in the order kumobad recorded them, for 72 hours, deleted sandboxes included. Save `nextCursor` to carry on where you left off, also after kumobad or your program restarts. `reset` is true when the cursor came from another kumobad's log and the page starts over from the oldest event; `gap` is true, once, when events after the cursor were deleted after 72 hours before you read them. A stopped sandbox's `info.stoppedAt` is when it stopped, and `info.startedAt` when it last finished booting. `info.networkChangedAt` is when its network policy last changed, the `at` of that `network_changed` event; it is absent until the first change.

## Cancel a call or give it a time limit [#cancel-a-call-or-give-it-a-time-limit]

Every call that asks kumobad for something takes `signal` and `timeoutMs` in its options object, the last argument; the desktop calls with positional arguments, such as `desktop.drag(from, to, button, options)`, take it last too.

```ts
const sandbox = await kumoba.create({ timeoutMs: 600_000 });
const data = await sandbox.files.read("/workspace/out.json", { signal: controller.signal });
await sandbox.desktop.click(200, 300, { timeoutMs: 10_000 });
```

- `signal` aborts the call: it throws a `KumobaError` with code `aborted` and `cause` set to `signal.reason`, and the request to kumobad is closed.
- `timeoutMs` throws a `KumobaError` with code `timeout` when that many milliseconds pass before the call's promise settles. The clock covers every request the call makes, so for `create()` it counts creating the sandbox and the whole boot. It must be above 0 and at most 2147483647; anything else is `invalid_request`.
- Neither is set by default and calls wait as long as kumobad takes. kumobad bounds a boot itself, at 2 minutes for Linux and 5 for macOS.
- `files.stream()` resolves once the download starts, so `timeoutMs` covers only opening it; `signal` still stops it partway, and the stream then emits the `aborted` error. `files.read()`, `files.download()` and `files.write()` count the whole transfer.
- `kumoba.accessLog()` counts its time limit across every page, from the first one to the last.
- When `create()` is aborted or times out, kumobad sees the request close and deletes the sandbox it was copying or booting. That relies on kumobad seeing the disconnect: a proxy between the SDK and kumobad that keeps its own connection open hides it, so set `autoDeleteMinutes` as a backstop there. Against kumobad 0.8 or earlier the SDK asks kumobad to delete the sandbox before it throws, and waits up to 10 seconds for that; there, a `create()` that stops before kumobad has replied to the create request itself may leave a sandbox whose id the SDK never received; find it with `list()` and delete it. With `start: false` nothing boots, and the same holds for the create request. `desktop.screenshot()` and `desktop.accessibilityTree()` remove their temporary file in the guest when they are aborted.
- `run()` already takes `signal`. Its `timeoutMs` is different: kumobad kills the command when it passes, and `run()` resolves with `timedOut: true` instead of throwing.

## Errors [#errors]

Failures throw `KumobaError` with a `code`, a `retryable` flag and an HTTP-style `status`: the daemon's own when it answered with an error, 502 or 503 for a failure the SDK detected in its reply or connection, and 0 when no request was made or the call was aborted or timed out. The exceptions are errors thrown by your own `onStdout` and `onStderr` callbacks, local file errors in `files.upload()` and `files.download()` such as a missing local path, and errors from a stream you pass to `files.write()`; those reach you unchanged.

| `code` | When | `retryable` |
| --- | --- | --- |
| `aborted` | The `signal` you passed was aborted. `cause` is `signal.reason`. | `false` |
| `timeout` | The `timeoutMs` you passed ran out before the call finished. | `true` |
| `unreachable` | kumobad could not be reached, or the connection broke before the reply was complete, for example because kumobad restarted. | `true` |
| `protocol` | kumobad sent something the SDK does not understand, a download ended early, or a command's output ended without an exit status. | `true` when a download or a command's output ended early, otherwise `false` |
| `daemon_error` | kumobad started the request but could not run the command and named no code, as a kumobad from 0.14 or earlier does. A newer one sends the code, such as `guest_error`. | `false` |
| `command_failed` | A shell helper such as `files.mkdir()`, `files.remove()` or a `desktop` method exited non-zero. For `mkdir` and `remove`, `result` holds the command's `RunResult`. | `false` |
| `invalid_request` | The SDK refused the arguments before asking kumobad, such as an empty command. | `false` |

Other codes, such as `not_found`, `capacity` or `guest_error`, are the daemon's own and come with its HTTP status (see the [HTTP API](/http-api)). An error reply without a code is `daemon_error`. Errors from the daemon are retryable when the status is 429 or 5xx.

When one daemon code covers several cases, `reason` tells them apart: `not_started`, `busy` or (from a fleet) `no_matching_host` with `conflict`, `unknown_image` or `invalid_cursor` with `invalid_request`, `sandbox_not_found` with `not_found`, `outcome_unknown` with `internal`, when kumobad lost track of the call and it may or may not have taken effect, and (from a fleet) `may_exist` with `host_unavailable`, when the host took a create, a `run()` or an import but its answer was lost, so the sandbox may exist there, or `outcome_unknown` with `host_unavailable` for any other call the host took but never answered. Both are `retryable: false`, although the status is 503. It is `undefined` against a kumobad from 0.14 or earlier. A missing token throws `config_invalid` with `reason` `no_token`. When `run()` fails before the command exits, the error carries the code and `reason` of the stream's `error` event, with `status` 502 since the stream itself was answered with 200, such as `guest_error`, or `conflict` with `not_started` for a sandbox stopped meanwhile; it is `daemon_error` against a kumobad from 0.14 or earlier, which sends no code there. `retryAfterSeconds` holds the daemon's `Retry-After`, as on a 429 `capacity`.

Once the SDK has connected to kumobad (after the TLS handshake), a call other than a `GET` may have reached it. If that connection then breaks, the reply breaks off, or a `run()` or `exec` stream ends before the command exits, the error keeps its code (`unreachable`, or `protocol` for a stream that ended) but has `reason: "outcome_unknown"` and `retryable: false`, since the call may have taken effect; a `GET` stays `retryable: true`. Refusals of the client certificate by the TLS layer stay plain `unreachable`, and so does a call that never connected. The SDK keeps idle connections open and reuses them, so a call sent on a reused connection that turns out to be closed or reset also counts as one that may have reached kumobad: it has `reason: "outcome_unknown"` and is not retried for you, even though kumobad may never have seen it. An error from the source you pass to `files.write()` or `files.upload()`, such as a missing local file, is thrown to you unchanged. Retry only calls that are safe to run twice. The same holds for `timeout`: kumobad may have done what the call asked, such as a desktop click, before the time ran out.

`files.read()`, `files.readText()`, `files.stream()` and `files.download()` compare the bytes received with the file size the daemon reports. A download that ends early, for example because the sandbox stopped mid-transfer, throws a `KumobaError` with code `protocol` and `retryable: true` instead of returning a short file. A stream emits it as an `error`.