Guides / JavaScript & TypeScript / API reference
API reference
Every export of @kosa8/sdk 0.1.0 and @kosa8/ai-sdk-sandbox
0.1.0. Signatures are taken from the packages' published .d.ts files, and the list of
names on this page was checked against them. Field names in results are the daemon's JSON names,
unchanged.
Kosa8ClientEvery method, with its endpoint.
OptionsThe option types methods take.
Result typesWhat methods resolve with.
Transport and helpersLower-level pieces.
ErrorsThe error classes and refusal types.
@kosa8/ai-sdk-sandboxFunctions, classes and settings.
@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 |
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. 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 |
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 |
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? |
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 |
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? |
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 |
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?. |
Kosa8ConnectionError | Kosa8Error | Daemon unreachable. |
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 |
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.
@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.