# API reference

The exports of `@kosa8/sdk` and `@kosa8/ai-sdk-sandbox`. The current releases are `@kosa8/sdk` 0.7.0 and `@kosa8/ai-sdk-sandbox` 0.2.1 (`npm install @kosa8/sdk@0.7.0`). The sections below were written from the TypeScript source of 0.3.1 and 0.1.1; every name they list is still exported by 0.5.3 and 0.2.1 (checked against the published `index.d.ts`), and the names added since are in [Added since 0.3.1]. The package's `dist/index.d.ts` has the exact signatures of the release you install. Field names in results are the daemon's JSON names, unchanged.

[`Kosa8Client`Every method, with its endpoint.] [`Toolbox`Code, files, git, sessions, previews, lifecycle, templates.] [`Kosa8Cloud`The kosa8 Cloud client.] [`Options`The option types methods take.] [`Result types`What methods resolve with.] [`Transport and helpers`Lower-level pieces.] [`Errors`The error classes and refusal types.] [`@kosa8/ai-sdk-sandbox`Functions, classes and settings.] [`Added since 0.3.1`RL runs, jobs, retries, previews, secrets and more.]

## @kosa8/sdk: `Kosa8Client`

```
new Kosa8Client(options?: Kosa8ClientOptions)
readonly transport: Transport
readonly checkpoints: CheckpointBook
```

Every method returns a promise, except `execFrames` (an async generator) and `sandbox`. Every method's last argument accepts `CallOptions` (`{ approval?, signal? }`), alone or merged into its own options.

### Status and the shared engine

| Method | Resolves with | Endpoint |
|---|---|---|
| `health(opts?)` | `Health` | `GET /kosa8/v1/health` |
| `version(opts?)` | `string` | `GET /kosa8/v1/health` |
| `pull(ref, opts?)` | `{ ok, image }` | `POST /kosa8/v1/pull`, the shared engine |

### Sandboxes

| Method | Resolves with | Endpoint |
|---|---|---|
| `createSandbox(options?: CreateSandboxOptions)` | `CreateSandboxResult` | `POST /kosa8/v1/sandboxes` |
| `listSandboxes(opts?)` | `Sandbox[]` | `GET /kosa8/v1/sandboxes` |
| `getSandbox(idOrName, opts?)` | `Sandbox \| undefined` | the list, filtered |
| `startSandbox(id, opts?)` | `StartSandboxResult` | `POST …/sandboxes/{id}/up` |
| `stopSandbox(id, opts?)` | `StopSandboxResult` | `POST …/sandboxes/{id}/down` |
| `deleteSandbox(id, opts?: CallOptions & { wipe?, keepCheckpoints? })` | `DeleteSandboxResult & { checkpoints_dropped }` | `DELETE …/sandboxes/{id}` (`?wipe=1`), then its checkpoints' snapshots |
| `pullIntoSandbox(id, ref, opts?)` | `{ ok, image }` | `POST …/sandboxes/{id}/pull` |
| `sandboxImages(id, opts?)` | `string[]` | `GET …/sandboxes/{id}/images` |
| `sandboxContainers(id, opts?)` | `Container[]` | `GET …/sandboxes/{id}/containers` |
| `sandboxEgress(id, opts?)` | `EgressStatus` | `GET …/sandboxes/{id}/egress` |

### Running code

| Method | Resolves with | Endpoint |
|---|---|---|
| `run(id, image, args?, opts?: RunOptions)` | `ExecResult` | `POST …/sandboxes/{id}/run`, NDJSON stream |
| `startContainer(id, image, args?, opts?)` | container id | `POST …/sandboxes/{id}/start` |
| `exec(id, container, args, opts?: ExecOptions)` | `ExecResult` | `POST …/sandboxes/{id}/exec` |
| `execFrames(id, container, args, opts?)` | `AsyncGenerator<Frame>` | `POST …/sandboxes/{id}/exec` |
| `startInteractive(id, image, args?, opts?: CallOptions & { env?, tty? })` | container id | `POST …/sandboxes/{id}/start-interactive` |
| `writeStdin(id, container, data: Uint8Array \| string \| AsyncIterable<Uint8Array \| string>, opts?)` | `{ ok }` | `POST …/sandboxes/{id}/containers/{cid}/stdin` |
| `attach(id, container, opts?: ExecOptions)` | `ExecResult` | `POST …/sandboxes/{id}/containers/{cid}/attach` |

### Snapshots, fork, explore

| Method | Resolves with | Endpoint |
|---|---|---|
| `snapshot(id, opts?: CallOptions & { id?, encrypt? })` | `SnapshotSandboxResult` | `POST …/sandboxes/{id}/snapshot` |
| `listSnapshots(opts?)` | `Snapshot[]` | `GET /kosa8/v1/snapshots` |
| `restoreSnapshot(snapshotId, opts?: RestoreOptions)` | `RestoreResult` | `POST /kosa8/v1/snapshots/{id}/restore` |
| `deleteSnapshot(snapshotId, opts?: CallOptions & { wipe?, force? })` | `DeleteSnapshotResult` | `DELETE /kosa8/v1/snapshots/{id}` |
| `fork(id, opts?: ForkOptions)` | `ForkResult` | `POST …/sandboxes/{id}/fork` |
| `explore(id, opts: ExploreOptions)` | `ExploreResult` | pull, fork, one run per branch, deletes |

### Checkpoints

| Method | Resolves with | How |
|---|---|---|
| `checkpoint(sandbox, opts?: CheckpointOptions)` | `CheckpointResult` | a snapshot `<sandbox>-ckpt-<n>`, recorded in the store; evicts past 10 |
| `listCheckpoints(sandbox)` | `Checkpoint[]` | the store, oldest first |
| `rewind(sandbox, opts?: RewindOptions)` | `RewindResult` | delete the sandbox, restore the checkpoint under its name, drop later ones |

### Toolbox

Higher-level calls on the daemon's toolbox routes (see [Native HTTP API](https://docs.kosa8.com/guides/native-api/)); they need kosa8 0.13.0 or later. Every one takes `CallOptions` as its last argument, merged into its own options.

| Method | Resolves with | Endpoint |
|---|---|---|
| `runCode(id, code, opts?: RunCodeOptions)` | `CodeResult`. Python (default), JavaScript or TypeScript, run in `/workspace`; matplotlib charts come back as PNG `artifacts`. A non-zero exit is a result, not an error. | `POST …/sandboxes/{id}/code` |
| `listFiles(id, path = '/workspace', opts?)` | `FileInfo[]` | `GET …/sandboxes/{id}/files?path=` |
| `statFile(id, path, opts?)` | `FileInfo` (not following a symlink) | `GET …/files/stat` |
| `readFile(id, path, opts?)`, `readText(id, path, opts?: CallOptions & { encoding? })` | `Buffer`, `string` | `GET …/files/content` |
| `writeFile(id, path, data: Uint8Array \| string \| AsyncIterable<Uint8Array \| string>, opts?: WriteFileOptions)` | `FileInfo`, the new entry; folders are made and the file is replaced in one step | `PUT …/files/content` |
| `deleteFile(id, path, opts?: CallOptions & { recursive? })` | `{ removed }` | `DELETE …/files` |
| `makeDir(id, path, opts?)`, `moveFile(id, from, to, opts?)` | `FileInfo` | `POST …/files/mkdir`, `POST …/files/move` |
| `git(id, op: GitOp, opts?: GitOptions)` | `GitResult`. `GitOp` is `'clone' \| 'status' \| 'add' \| 'commit' \| 'push' \| 'pull' \| 'checkout' \| 'branches' \| 'log' \| 'diff'`. A git failure is `ok: false`, not a throw. | `POST …/sandboxes/{id}/git` |
| `gitClone(id, url, opts?)`, `gitStatus(id, path, opts?)`, `gitCommit(id, path, message, opts?: GitCommitOptions)` | `GitResult` | the same |
| `createSession(id, name?, opts?: CreateSessionOptions)`, `listSessions(id, opts?)`, `deleteSession(id, session, opts?)` | `SessionInfo`, `SessionInfo[]`, `{ deleted }` | `…/sandboxes/{id}/sessions` |
| `sessionExec(id, session, command, opts?: SessionExecOptions)` | `ShellResult`: a shell that keeps `cd` and `export` between commands | `POST …/sessions/{name}/exec` |
| `shell(id, command, opts?: ShellOptions)` | `ShellResult`; makes the session (default `main`) on first use | the same |
| `startPty(id, opts?: StartPtyOptions)`, `resizePty(id, container, cols, rows, opts?)` | A container id with a terminal (connect a WebSocket to `…/containers/{cid}/tty`); `{ ok }` | `POST …/pty`, `POST …/containers/{cid}/resize` |
| `createPreview(id, port, opts?: CreatePreviewOptions)` | `Preview`: a signed link to a web server in the sandbox that expires | `POST …/sandboxes/{id}/previews` |
| `revokePreviews(opts?)` | `{ ok, revoked }`: ends every preview link | `POST /kosa8/v1/previews/rotate` |
| `setLifecycle(id, opts?: SetLifecycleOptions)` | `Sandbox`. A field left out keeps its value; 0 turns one off. | `POST …/sandboxes/{id}/lifecycle` |
| `listTemplates(opts?)`, `deleteTemplate(name, opts?)` | `Template[]`, `{ deleted }` | `GET` / `DELETE /kosa8/v1/templates` |
| `buildTemplate(name, contextDir = '.', opts?: BuildTemplateOptions)` | The final `Frame`. Builds the Dockerfile in a throwaway sandbox and keeps the image as a template for `createSandbox({ template })`. | `POST /kosa8/v1/templates`, the context as a tar (`tarContext`) |

### Handle

`sandbox(id): SandboxHandle`. A `SandboxHandle` has `client`, `id`, and these methods with the sandbox filled in: `info` (`getSandbox`), `start`, `stop`, `delete`, `pull` (`pullIntoSandbox`), `run`, `startContainer`, `exec`, `containers`, `images`, `egress`, `snapshot`, `fork`, `explore`, `checkpoint`, `checkpoints` (`listCheckpoints`), `rewind`, and the toolbox: `runCode`, `listFiles`, `statFile`, `readFile`, `readText`, `writeFile`, `deleteFile`, `makeDir`, `moveFile`, `git`, `gitClone`, `gitStatus`, `gitCommit`, `createSession`, `sessions` (`listSessions`), `sessionExec`, `shell`, `deleteSession`, `startPty`, `resizePty`, `createPreview`, `setLifecycle`. There is no `execFrames`, `startInteractive`, `writeStdin` or `attach` on the handle; call them on the client.

## Options

### `Kosa8ClientOptions`

Extends `TransportOptions` with one field.

| Field | Type | Default |
|---|---|---|
| `socketPath` | string | `$HOME/.kosa8/run/kosa8.sock`; ignored when a host is set |
| `host` | string | `KOSA8_HOST`: `https://…`, `http://…`, `tcp://h:p`, `h:p`, `unix:///path` |
| `token` | string | `KOSA8_TOKEN`, when the host came from `KOSA8_HOST` |
| `insecure` | boolean | `KOSA8_INSECURE=1`; allows plain http to a non-loopback host |
| `actor` | `Actor`: `'human' \| 'agent' \| 'tool'` | `'tool'` |
| `agentToken` | string | `KOSA8_AGENT_TOKEN` |
| `headers` | `Record<string,string>` | extra headers on every request |
| `env` | `Record<string, string \| undefined>` | `process.env` |
| `workerFile` | `string \| null` | `$HOME/.kosa8/worker.json` (`defaultWorkerFile()`): the connection `kosa8 wsl setup` and `kosa8 worker join` save, read when no host, `KOSA8_HOST` or `socketPath` is set. `null` reads none. |
| `checkpointStore` | `CheckpointStore` | `new FileCheckpointStore()`, `~/.kosa8/checkpoints.json` |

### `CallOptions`

`{ approval?: string; signal?: AbortSignal }`. `approval` is sent as `X-Kosa8-Approval`; `signal` aborts the HTTP request (not the process in the sandbox).

### `CreateSandboxOptions` (extends `CallOptions`)

| Field | Type | Sent as |
|---|---|---|
| `name` | string | `name` |
| `cpus` | number | `cpus` |
| `memMb` | number | `mem_mb` |
| `diskGb` | number | `disk_gb` |
| `mounts` | `Mount[]` | `mounts` |
| `egress` | `EgressPolicy` | `egress` (a `{ allow }` becomes `allow:a,b`) |
| `egressAllow` | `readonly string[]` | `egress: "allow:…"` |
| `capture` | `CaptureSpec` | `capture` |
| `labels` | `Record<string,string>` | `labels` |
| `broker` | `BrokerSpec` | `broker` |
| `autoStopMin` | number | `auto_stop_min`: stop after this many idle minutes |
| `ttlMin` | number | `ttl_min`: stop this many minutes after creation |
| `autoDeleteMin` | number | `auto_delete_min`: delete once stopped this long |
| `ephemeral` | boolean | `ephemeral`: delete whenever it stops |
| `template` | string | `template`: start with a template's image (`buildTemplate`) |

### Other option types

| Type | Fields |
|---|---|
| `RunOptions` | `CallOptions` + `env?: Record<string,string> \| string[]`, `onStdout?`, `onStderr?`, `onStatus?` (each `(chunk: Buffer) => void`) |
| `ExecOptions` | `CallOptions` + `onStdout?`, `onStderr?` |
| `ForkOptions` | `CallOptions` + `n?` (default 1), `prefix?` (default `<sandbox>-fork`), `label?` |
| `ExploreOptions` | `CallOptions` + `variants: string[]` (2 or more), `image?` (`alpine:latest`), `keepAll?`, `keep?`, `timeoutMs?` (120000), `prefix?`, `pull?` (true) |
| `CheckpointOptions` | `CallOptions` + `label?` |
| `RewindOptions` | `CallOptions` + `to?`: a checkpoint id or label (default: the latest) |
| `RestoreOptions` | `CallOptions` + `name?`, `label?`, `allowTampered?` |
| `RunCodeOptions` | `CallOptions` + `language?` (default `'python'`), `image?`, `env?: Record<string,string>`, `timeoutS?` |
| `WriteFileOptions` | `CallOptions` + `mode?` (such as `'644'`) |
| `GitOptions` | `CallOptions` + `path?, url?, branch?, depth?, remote?, create?, files?, message?, authorName?, authorEmail?, n?, staged?, username?, token?, image?` |
| `GitCommitOptions` | `GitOptions` without `path` and `message`, + `addAll?` (default true) |
| `CreateSessionOptions` | `CallOptions` + `image?`, `env?` |
| `SessionExecOptions`, `ShellOptions` | `CallOptions` + `timeoutS?`; `ShellOptions` also `session?` (default `'main'`) |
| `StartPtyOptions` | `CallOptions` + `image?, command?, cols?, rows?, env?` |
| `CreatePreviewOptions` | `CallOptions` + `session?, container?, expiresInS?` |
| `SetLifecycleOptions` | `CallOptions` + `autoStopMin?, autoDeleteMin?, ttlMin?, ephemeral?` |
| `BuildTemplateOptions` | `CallOptions` + `dockerfile?, buildArgs?, egress?, replace?, onOutput?: (chunk: Buffer, stream: string) => void` |
| `Mount` | `{ host_path: string; guest_path: string; read_only: boolean }` |
| `EgressPolicyString` | `'any' \| 'deny' \| 'fakenet' \| `allow:${string} |
| `EgressPolicy` | `EgressPolicyString \| { allow: readonly string[] }` |
| `CaptureSpec` | `{ path: string; max_bytes?: number; max_files?: number }` |
| `BrokerSpec` | `{ allow?: BrokerHostRule[]; routes?: BrokerRoute[] }` |
| `BrokerHostRule` | `{ host: string; ports?: number[]; methods?: string[] }` |
| `BrokerRoute` | `{ name; upstream; header; secret; methods?; paths?; scheme? }`, all strings or string arrays |

## Result types

| Type | Fields |
|---|---|
| `Health` | `status, version, commit, go, uptime_seconds, phase` |
| `Sandbox` | `id, name, created, state` (running, paused, stopped), `cpus, mem_mb, disk_gb?, parent?, mounts?, egress?, capture?, ip?, labels?, broker?: BrokerInfo` |
| `BrokerInfo` | `url, hosts?, routes?` |
| `CreateSandboxResult` | `sandbox, boot_ms, broker?: { url, placeholders }` |
| `StartSandboxResult` | `sandbox, boot_ms, warning?` |
| `StopSandboxResult` | `ok, sandbox?, warning?, already_stopped?` |
| `DeleteSandboxResult` | `ok, wipe?, files?` |
| `Container` | `id, image, status, exit?, ip?` |
| `EgressStatus` | `policy, stats: { passed, denied, dropped, dns_answered, dns_refused, fakenet? }, capture?, wildcards?, fakenet?` |
| `Frame` | `stream?` (stdout, stderr, status), `data?: Buffer`, `done?, ok?, error?, exit?, id?, image?` |
| `ExecResult` | `exitCode, stdout, stderr, stdoutBytes: Buffer, stderrBytes: Buffer` |
| `Snapshot` | `id, sandbox, created, cpus, mem_mb, cmdline, size_bytes, state_path`, and optional `machine_id, mac, disk_path, data_path, disk_gb, ephemeral, mounts, egress, received, received_mounts, sealed, labels, encryption` |
| `SnapshotSandboxResult` | `snapshot, snapshot_ms, encrypted_by_policy?, encrypt_ms?, encryption?` |
| `RestoreResult` | `sandbox, restore_ms, seal?` |
| `DeleteSnapshotResult` | `ok, removed, encrypted, shred?, wipe?, files?` |
| `ForkResult` | `forks: Sandbox[], snapshot, fork_ms, count, encrypted_by_policy?, encrypt_ms?` |
| `ExploreBranch` | `name, variant, exit, output, duration_ms, error?` |
| `ExploreResult` | `parent, branches, winner` (`""` if none succeeded), `removed` |
| `Checkpoint` | `id, sandbox, label, created, auto?` |
| `CheckpointResult` | `checkpoint, evicted: string[], snapshot: SnapshotSandboxResult` |
| `RewindResult` | `sandbox, checkpoint, dropped: string[], restore_ms` |
| `CodeResult` | `ok, exitCode, stdout, stderr, language, image, artifacts: CodeArtifact[], durationMs, timedOut, truncated` |
| `CodeArtifact` | `type` (such as `image/png`), `name`, `data: Buffer` |
| `ShellResult` | `ok, exitCode, stdout, stderr, cwd, durationMs, timedOut, truncated` |
| `GitResult` | `op, ok, exitCode, stdout, stderr, path, status?, log?, branches?` |
| `FileInfo` | `name, path, type` (file, dir, symlink, other), `size, mode, mod_time, link?` |
| `SessionInfo` | `name, id, image, status` |
| `Preview` | `url, token, expires_at, container, port, listen` |
| `Template` | `name, image, size_bytes, created, dockerfile?` |

## Transport, checkpoint stores and helpers

| Export | What it is |
|---|---|
| `Transport` | `new Transport(opts?: TransportOptions)`. `target` (where requests go), `raw(method, path, opts?: RequestOptions)` (headers arrived), `json<T>(method, path, opts?)` (decoded; HTTP errors become typed errors), `frames(method, path, opts?)` (NDJSON frames, `data` decoded). For endpoints the client does not wrap. |
| `TransportOptions` | `socketPath?, host?, token?, insecure?, actor?, agentToken?, headers?, env?, workerFile?` |
| `RequestOptions` | `query?, body?` (JSON), `rawBody?` (bytes, string or async iterable, streamed), `approval?, signal?, headers?` |
| `Actor` | `'human' \| 'agent' \| 'tool'` |
| `resolveEndpoint(opts: TransportOptions)` | `{ kind: 'unix', socketPath } \| { kind: 'tcp', url, token? }`, following the CLI's `KOSA8_HOST` rules. Throws `Kosa8Error` for a refused address. |
| `defaultSocketPath()` | `$HOME/.kosa8/run/kosa8.sock` |
| `defaultWorkerFile()` | `$HOME/.kosa8/worker.json` |
| `tarContext(dir, dockerfile?)` | Packs a build context as `buildTemplate` sends it. |
| `APPROVAL_HEADER`, `ACTOR_HEADER`, `AGENT_TOKEN_HEADER` | `'X-Kosa8-Approval'`, `'X-Kosa8-Actor'`, `'X-Kosa8-Agent-Token'` |
| `CheckpointStore` | Interface: `load(): Promise<Record<string, Checkpoint[]>>`, `update<T>(fn): Promise<T>` (serialised). |
| `FileCheckpointStore` | `new FileCheckpointStore(filePath?)`, default `~/.kosa8/checkpoints.json` (mode 0600, atomic rewrite, lock file for Node writers). `path`. |
| `MemoryCheckpointStore` | In memory only; nothing shared with the CLI. |
| `CheckpointBook` | The stack logic over a store, as `client.checkpoints`: `store`, `nextId`, `record`, `list`, `latest`, `resolve`, `pop`, `forget`. |
| `MAX_CHECKPOINTS_PER_SANDBOX` | `10` |
| `validateSandboxName(name)` | Throws `Kosa8CheckpointError` for a name that could escape the store (empty, `.`, `..`, a slash, a leading dot). |

## Errors

| Export | Extends | Thrown for |
|---|---|---|
| `Kosa8Error` | `Error` | Base class; client-side checks. Fields `status?, daemonMessage?, remediation?, method?, path?, body?, code?` (`code` is kosa8 Cloud's stable error code). |
| `Kosa8ConnectionError` | `Kosa8Error` | Daemon (or kosa8 Cloud) unreachable. |
| `Kosa8TimeoutError` | `Kosa8ConnectionError` | A `Kosa8Cloud` request took longer than `timeoutMs` (the local client uses `signal` instead). A subclass of the connection error, so a handler for that catches it too. |
| `Kosa8ApiError` | `Kosa8Error` | Any HTTP error without a more specific class. |
| `Kosa8BadRequestError` | `Kosa8ApiError` | 400 |
| `Kosa8AuthError` | `Kosa8ApiError` | 401 |
| `Kosa8PolicyError` | `Kosa8ApiError` | 403 |
| `Kosa8ApprovalRequiredError` | `Kosa8PolicyError` | 403 with a refusal; `approval: ApprovalRefusal` |
| `Kosa8NotFoundError` | `Kosa8ApiError` | 404 |
| `Kosa8ConflictError` | `Kosa8ApiError` | 409 |
| `Kosa8PaymentRequiredError` | `Kosa8ApiError` | 402, from kosa8 Cloud: no new work until the account is in order (no payment method on file, the last charge declined, or the spending cap reached). `code` is `payment_required` or `spending_cap_reached`; `body` carries `upgrade_url` and `agent_message`. Do not retry until a person acts. |
| `Kosa8RateLimitError` | `Kosa8ApiError` | 429: `code` `quota_exceeded` is the organization's running-sandbox limit (delete or sleep one first); `rate_limited` is a request rate limit (wait and retry). |
| `Kosa8UnsupportedError` | `Kosa8ApiError` | 501 |
| `Kosa8StreamError` | `Kosa8Error` | Error frame in a stream; `stdout`, `stderr` |
| `Kosa8CheckpointError` | `Kosa8Error` | Checkpoint bookkeeping |
| `errorFromResponse(status, body, ctx?)` |  | Builds the typed error for an HTTP error answer, as the client does. |
| `ApprovalRefusal` | type | `route, action: ApprovalAction, description, class, policy, policy_digest, requirement: ApprovalRequirement, request_id?, why, signers?, request_command` |
| `ApprovalAction` | type | `kind, target?, command?, sandbox?`, and more |
| `ApprovalRequirement` | type | `policy, rules: ApprovalRule[]` |
| `ApprovalRule` | type | An approval rule as the daemon reports it (an open record). |

Details and real messages: [Errors reference](https://docs.kosa8.com/guides/js-errors/).

## @kosa8/sdk: `Kosa8Cloud`

A separate client for kosa8 Cloud, which runs sandboxes on kosa8's hosts instead of the local daemon. It calls `https://api.kosa8.com` with an API key from an [app.kosa8.com](https://app.kosa8.com) account, and sends nothing until you construct it and call it.

```
import { Kosa8Cloud } from '@kosa8/sdk';

const cloud = new Kosa8Cloud();           // KOSA8_API_KEY from the environment
const box = await cloud.sandboxes.create({ template: 'python' });
console.log((await box.exec(['python3', '-c', 'print(6 * 7)'])).stdout);
await box.delete();
```

```
$ KOSA8_API_KEY=k8c_live_… node cloud.mjs
42
```

| `Kosa8CloudOptions` field | Default |
|---|---|
| `apiKey` | `KOSA8_API_KEY`. Missing, or not starting with `k8c_live_` (`CLOUD_KEY_PREFIX`) or `k8c_tok_` (`CLOUD_TOKEN_PREFIX`, a capability token): `Kosa8Error`. |
| `baseUrl` | `KOSA8_CLOUD_URL`, then `https://api.kosa8.com` (`DEFAULT_CLOUD_URL`). Must be https (plain http only to localhost). |
| `env` | `process.env` |
| `fetch` | `globalThis.fetch` |
| `timeoutMs` | `120000`, per request; past it, `Kosa8TimeoutError` |
| `retry` | A `RetryPolicy`, its options, or `false` for none. Default: 3 tries with full jitter. |

### The client

| Member | Resolves with | Endpoint |
|---|---|---|
| `cloud.me()` | The org, the key in use and, for a member's key, the member | `GET /v1/me` |
| `cloud.usage()` | This month's usage, the bill estimate and whether work is paused for payment | `GET /v1/usage` |
| `cloud.templates()` | `CloudTemplate[]`: `{ key, cpus?, mem_mb?, image?, … }` (`base`, `python`, `node`, …) | `GET /v1/templates` |
| `cloud.sandboxes.create(opts?: CloudCreateOptions)` | `CloudSandbox`, once running (`wait: false` returns at once). Options include `template?`, `size?`, `cpus?`, `memMb?`, `image?`, `diskGb?`, `name?`, `env?`, `labels?`, `egress?`, `secrets?`, `snapshot?`, `sleepAfterS?`, `ttlS?`, `persistent?`, `region?`, `idempotencyKey?`. | `POST /v1/sandboxes` |
| `cloud.sandboxes.createMany(n, opts?)` | `CloudSandboxBatch`: the sandboxes, plus `failed`, `requested`, `created` | `POST /v1/sandboxes/batch` |
| `cloud.sandboxes.list({ all?, limit?, cursor?, name?, labels? })`, `listPage(…)`, `iterate(…)` | `CloudSandbox[]`; `{ sandboxes, nextCursor }`; an async generator over every page. With `all`, deleted ones too. | `GET /v1/sandboxes` |
| `cloud.sandboxes.get(id)` | `CloudSandbox` | `GET /v1/sandboxes/{id}` |
| `cloud.snapshots` | `create(sandboxId, { name? })`, `list({ sandboxId? })`, `get(id)`, `delete(id)` | `/v1/snapshots` |
| `cloud.functions.deploy(name, spec: CloudFunctionSpec)` | The function. `spec`: `runtime` (`'python3.12' \| 'node22'`), `code`, `env?`, `timeout_s?`, `web?` (`'off' \| 'public' \| 'key'`), `schedule?`, …; each deploy bumps the version. | `PUT /v1/functions/{name}` |
| `cloud.functions.list()`, `get(name)`, `delete(name)` | Function records | `GET` / `DELETE /v1/functions…` |
| `cloud.functions.invoke(name, event?)` | `CloudInvokeResult`: `{ invocation, ok, result?, error?, logs?, source?, timings_ms? }`. A handler that throws resolves with `ok: false`. | `POST /v1/functions/{name}/invoke` |
| `cloud.functions.map(name, events, { concurrency? })` | `{ function, version, count, succeeded, failed, total_ms, results }`, results in input order | `POST /v1/functions/{name}/map` |
| `cloud.secrets`, `tokens`, `pipelines`, `orgTemplates`, `jobs`, `burst`, `recordings` | See [Added since 0.3.1] |  |
| `cloud.request(method, path, body?)` | The decoded JSON of any `/v1` route the client does not wrap, with the same errors and retries | any |

### A sandbox: `CloudSandbox`

| Member | Resolves with | Endpoint |
|---|---|---|
| `box.id`, `box.state`, `box.info` | `CloudSandboxInfo`: `id, state` (creating, running, paused, sleeping, stopped, error, deleted, …), `template, cpus, mem_mb, source, region, name, labels, created_at, cost_usd`, … |  |
| `box.exec(cmd: string \| string[], opts?: CloudExecOptions)` | `CloudExecResult`: `{ exitCode, stdout, stderr, failureClass, retryable, wokeMs? }`. A string runs through `sh -c`. Options `image?`, `env?`, `timeoutS?`, `signal?`. A non-zero exit is a result, not an error. A sleeping sandbox wakes for it. | `POST /v1/sandboxes/{id}/exec` |
| `box.execBackground(cmd, opts?)`, `box.getExec(id)` | `CloudBackgroundExec`: `status()`, `wait()`, `stop()`; `info.exit` and `info.output` when it ends | `POST …/exec` in the background |
| `box.files` | `read`, `readText`, `write`, `list`, `mkdir`, `delete(path, { recursive? })`, `link(path, { method?, ttlS? })` (a signed URL), `readRaw`, `writeRaw` | `…/files` |
| `box.checkpoint(label?)`, `box.checkpoints()`, `box.rewind(checkpoint)` | `CloudCheckpoint` (`{ id, label?, created_at?, bytes? }`); the list; `{ checkpoint, backup, ms }` | `…/checkpoints`, `…/rewind` |
| `box.fork(n?)` | `CloudSandboxBatch` of copies, each with `source: 'fork'` and `parent_id` set | `POST …/fork` |
| `box.snapshot(name?)` | `CloudSnapshot`; start new sandboxes from it with `create({ snapshot })` | `POST …/snapshots` |
| `box.sleep()`, `box.wake()`, `box.refresh()`, `box.waitUntilRunning()` | The box, with `info` updated. Sleep snapshots it and frees its VM; wake restores it with its files. | `POST …/sleep`, `POST …/wake`, `GET …` |
| `box.update({ ttlS?, deleteAfter?, sleepAfterS? })` | `{ sandbox, notes }` | `PATCH /v1/sandboxes/{id}` |
| `box.egress()`, `box.setEgress(policy)`, `box.resetEgress()` | `CloudEgress`: `{ internet, allow, deny, presets, source, enforced }`. Changes apply to the running sandbox. | `…/egress` |
| `box.previews`, `box.ports()` | `previews.create(port, opts?)` gives an https URL for a port; the ports listening inside | `…/previews`, `…/ports` |
| `box.runCode(code, opts?)`, `box.codeContexts` | A code-interpreter run, and contexts that keep state between runs | `…/code` |
| `box.metrics()`, `box.logs({ limit? })`, `box.setLabels(labels)`, `box.secrets()` | CPU, memory, disk and network now; recent commands; labels; the secret names it holds | `…/metrics`, `…/logs`, … |
| `box.delete()` | `void`. Also `await using box = …` (`Symbol.asyncDispose`). | `DELETE /v1/sandboxes/{id}` |

Errors are the same classes as the local client, with `code` set from the cloud's `{ error, message }` answer, plus `failureClass` and `retryable`. Things to know:

- `exec` waits and returns the whole output. The API stops a buffered exec after 90 seconds and the call rejects with `Kosa8ExecTimeoutError` (HTTP 504, `code` `exec_timeout`). Keep each command short, or use `execBackground` for long work.

- The default template, `base`, is Alpine Linux: busybox `sh`, no `bash` or `python`. Pass `template` (such as `'python'`) when you need them. `cloud.templates()` lists the keys.

- Sandboxes run in `us-ash1` (Ashburn, Virginia, US).

- There is no `explore`, no host-folder mounts and no broker; org secrets (`cloud.secrets`, `create({ secrets })`) keep credentials out instead.

Exported with it: `CloudSandbox`, `CloudSandboxes`, `CloudSandboxFiles`, `CloudFunctions`, `CloudSnapshots`, `CloudBackgroundExec`, `DEFAULT_CLOUD_URL`, `CLOUD_KEY_PREFIX`, and the types `Kosa8CloudOptions`, `CloudSandboxInfo`, `CloudCreateOptions`, `CloudExecOptions`, `CloudExecResult`, `CloudInvokeResult`, `CloudInvocation`, `CloudFunctionSpec` and more (see `dist/index.d.ts`).

## @kosa8/ai-sdk-sandbox

### Functions

| Export | Signature and meaning |
|---|---|
| `createKosa8NetworkSandboxSession` | `(options?: Kosa8NetworkSandboxSessionCreateOptions) => Promise<HarnessV1NetworkSandboxSession & Kosa8NetworkSandboxSession>`. Boots a sandbox and its work container. Options are the settings plus `sandboxId?`, `template?: { identity, prepare }`, `abortSignal?`. |
| `resumeKosa8NetworkSandboxSession` | `(options: Kosa8NetworkSandboxSessionResumeOptions) => Promise<…>`. Settings plus `sandboxId` (required), `abortSignal?`. Reattaches; never creates. |
| `createKosa8NetworkSandboxSessionFromSandbox` | `(options: Kosa8SandboxSettings & { sandbox; container?; abortSignal? }) => Promise<…>`. Wraps a sandbox you own; `stop` and `destroy` do nothing. |
| `createKosa8SandboxSessionFromContainer` | `(options: { sandbox; container; client?; image?; workingDirectory?; env?; approval? }) => Experimental_SandboxSession`. The restricted view only. |
| `createKosa8Sandbox` | `(settings?: Kosa8SandboxSettings) => HarnessV1SandboxProvider`. The provider shape. |
| `toKosa8Egress` | `(policy: HarnessV1NetworkPolicy) => string`. The AI SDK policy as kosa8 egress; throws `HarnessCapabilityUnsupportedError` for `deniedCIDRs` or an empty custom list. |
| `restrictedView` | `(session: Experimental_SandboxSession) => Experimental_SandboxSession`. A frozen object of the eight tool-safe members. |
| `sandboxNameForSession` | `(sessionId: string) => string`. `aisdk-<slug>-<hash>`. |
| `templateSnapshotId` | `(identity, image, egress, workdir) => string`. `aisdk-tpl-<hash>`. |
| `resumeSnapshotId` | `(sandbox: string) => string`. `<sandbox>-aisdk-resume`. |

### Constants

`DEFAULT_IMAGE` = `'alpine:latest'`, `DEFAULT_WORKING_DIRECTORY` = `'/workspace'`, `KOSA8_PROVIDER_ID` = `'kosa8-sandbox'`.

### Classes

| Class | Members |
|---|---|
| `Kosa8SandboxSession` (implements `Experimental_SandboxSession`) | `description`, `run({ command, workingDirectory?, env?, abortSignal? })`, `spawn(…)` returning `{ stdout, stderr, wait(), kill() }`, `readFile`, `readBinaryFile`, `readTextFile`, `writeFile`, `writeBinaryFile`, `writeTextFile`. |
| `Kosa8NetworkSandboxSession` (extends the above, implements `HarnessV1NetworkSandboxSession`) | `id`, `sandboxName`, `containerId`, `defaultWorkingDirectory`, `ports` (`[]`), `restricted()`, `stop()`, `destroy()`, `setNetworkPolicy(policy)`, `getPortEndpoint()` and `getPortUrl()` (throw), `setPorts(ports)` (throws unless empty). |
| `Kosa8SandboxProvider` (implements `HarnessV1SandboxProvider`) | `new Kosa8SandboxProvider(settings?)`. `specificationVersion` (`'harness-sandbox-v1'`), `providerId`, `createSession({ sessionId?, abortSignal?, identity?, onFirstCreate? })`, `resumeSession({ sessionId, abortSignal? })`. |

### Types

| Type | Fields |
|---|---|
| `Kosa8SandboxSettings` | `client?, image?, workingDirectory?, env?, networkPolicy?, egress?, cpus?, memMb?, diskGb?, mounts?, labels?, broker?, setupCommands?, approval?` |
| `Kosa8NetworkSandboxSessionCreateOptions` | `HarnessV1SandboxSessionCreateOptions<Kosa8SandboxSettings>` |
| `Kosa8NetworkSandboxSessionResumeOptions` | `HarnessV1SandboxSessionResumeOptions<Kosa8SandboxSettings>` |

Usage and behaviour: [Vercel AI SDK adapter](https://docs.kosa8.com/guides/js-ai-sdk/).

## Added since 0.3.1

Names exported by `@kosa8/sdk` 0.5.3 that the sections above do not cover, from the package's own doc comments. 0.5.3 also exports about 80 option and result types for them (`CloudGradeOptions`, `CloudJobOptions`, `RlRunOptions` and so on); see `dist/index.d.ts`.

| Export | Meaning |
|---|---|
| `RlRun`, `withRun` | An RL training run on kosa8 Cloud: `withRun(cloud, { name }, async (run) => run.map(base, tasks, solve, { gradeCmd }))` starts it, finishes it (`finished`, or `failed` if `fn` throws) and drains its sandboxes. See [RL training](https://docs.kosa8.com/guides/rl-training/). |
| `mapRollouts`, `Rollouts` | `mapRollouts(solve, tasks, opts)`: run `solve(sandbox, task)` for every task (`groupSize` times each), `concurrency` at a time, each in its own fork of `base`, graded in a sealed copy with `gradeCmd`. Resolves with `Rollouts`, the results in input order. |
| `Lease`, `lease` | Heartbeats a set of leased sandboxes while the trainer runs and drains them when it stops: `await using _ = rl.lease(cloud, { labels: { job: 'exp-7' } })`. |
| `rl` | The RL names above as one namespace (`import { rl } from '@kosa8/sdk'`). |
| `RUN_LABEL`, `DEFAULT_LEASE_S`, `MIN_LEASE_S`, `MAX_LEASE_S` | `"kosa8.run"`, the label a run's sandboxes carry; the default lease (600 s) and the range a lease takes (60 s to 1 day). |
| `FAILURE_CLASSES`, `DEFAULT_MASK`, `classifyFailure`, `failureOf` | The failure classes (`ok`, `exit_nonzero`, `timeout`, `oom`, `infra`, `quota`, `client`, `error`), the ones masked by default, and `{ failureClass, retryable }` for a thrown error or an HTTP status and code. |
| `CloudJobs`, `jobBody`, `jobDone`, `JOB_DONE_STATES`, `loadJobTasks`, `encodeJobFiles`, `MAX_JOB_TASKS` | Hosted jobs (`cloud.jobs`): kosa8 runs every task's rollout itself. See [hosted jobs](https://docs.kosa8.com/guides/cloud-jobs/). A job takes up to 10,000 tasks. |
| `RetryPolicy`, `callWithRetry`, `NO_RETRY`, `newIdempotencyKey` | How often and how long to retry (full jitter), a helper that retries a call under a policy, no retries, and a random Idempotency-Key. |
| `CloudSandboxFiles` | `sandbox.files`: read, write, list and delete files in a cloud sandbox. |
| `CloudBackgroundExec` | A command that keeps running after `execBackground` returns; `status()` and `wait()`. |
| `CloudSnapshots`, `CloudOrgTemplates` | The org's snapshots (start a sandbox with `create({ snapshot })`) and its own templates (built once from an image or Dockerfile, then restored). |
| `CloudPreviews`, `CloudPreviewDomains` | `sandbox.previews.create(3000)` gives an https URL for a port; custom domains for a preview. |
| `CloudSecrets`, `CloudTokens`, `CLOUD_TOKEN_PREFIX` | Encrypted org secrets a sandbox reaches only as a placeholder; capability tokens (`k8c_tok_…`) that reach only some sandboxes, for at most a day. |
| `CloudSchedules`, `CloudPipelines`, `CloudPipelineHooks`, `pipelineRunDone` | Cron commands in a sandbox; CI runs with logs, artifacts and webhook or cron triggers. |
| `CloudCodeContexts`, `CloudEmbeds`, `CloudRecordings`, `CloudBurst` | Code-interpreter contexts, embeddable sandbox pages, desktop recordings, and Burst Passes. |
| `Kosa8ExecTimeoutError`, `Kosa8ItemTimeoutError`, `Kosa8CancelledError`, `Kosa8OrgFrozenError` | A buffered exec past the API's 90 s limit; a map item past its `timeoutMs`; a map aborted before an item ran; **423** `org_frozen`. |
| `CLOUD_SIZES`, `SMALL_CLOUD_SIZES` | `2x4` to `16x32`; `0.25x0.5`, `0.5x1` and `1x2`, taken only on hosts that run small sizes (else **501**). |
| `MAX_BATCH`, `MAX_FORK`, `MAX_FORK_N`, `MIN_TTL_S`, `MAX_TTL_S`, `MAX_SLEEP_AFTER_S` | 1,000 sandboxes a `createMany`; 1,000 copies a partial fork, 100 an all-or-nothing `fork(n)`; a TTL of 60 s to 90 days; sleep after at most 7 days idle. |

### `@kosa8/ai-sdk-sandbox` 0.2.1

Added since 0.1.1: the kosa8 Cloud provider, beside the local one above.

| Export | Meaning |
|---|---|
| `createKosa8CloudSandbox`, `Kosa8CloudSandboxProvider`, `KOSA8_CLOUD_PROVIDER_ID` | A kosa8 Cloud sandbox provider in the AI SDK 7 provider shape (`"kosa8-cloud-sandbox"`). |
| `createKosa8CloudSandboxSession`, `resumeKosa8CloudSandboxSession`, `createKosa8CloudSandboxSessionFromSandbox` | Create, reattach to (by `sbx_…` id or name, waking it) or wrap a kosa8 Cloud sandbox as a network sandbox session. |
| `Kosa8CloudSandboxSession`, `Kosa8CloudNetworkSandboxSession` | The sessions over a kosa8 Cloud sandbox; commands run as background execs, so they are not held to the 90 s limit. |
| `toCloudEgress`, `cloudTemplateSnapshotName`, `CLOUD_FILES_ROOT`, `MAX_FILES_API_BYTES` | The AI SDK network policy as a kosa8 Cloud egress policy; the snapshot name a template is kept under; `/workspace`; the most the files API carries a request. |
| `Kosa8CloudCreateSettings`, `Kosa8CloudSandboxSettings`, `Kosa8CloudSandboxSessionCreateOptions`, `Kosa8CloudSandboxSessionResumeOptions` | Their settings and options types. |

---
Source: https://docs.kosa8.com/guides/js-api/
