kosa8 docs Dashboard
esc
↑ ↓ move↵ openRuns in your browser; nothing you type is sent anywhere.

Guides / JavaScript & TypeScript / API reference

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.

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

MethodResolves withEndpoint
health(opts?)HealthGET /kosa8/v1/health
version(opts?)stringGET /kosa8/v1/health
pull(ref, opts?){ ok, image }POST /kosa8/v1/pull, the shared engine

Sandboxes#

MethodResolves withEndpoint
createSandbox(options?: CreateSandboxOptions)CreateSandboxResultPOST /kosa8/v1/sandboxes
listSandboxes(opts?)Sandbox[]GET /kosa8/v1/sandboxes
getSandbox(idOrName, opts?)Sandbox | undefinedthe list, filtered
startSandbox(id, opts?)StartSandboxResultPOST …/sandboxes/{id}/up
stopSandbox(id, opts?)StopSandboxResultPOST …/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?)EgressStatusGET …/sandboxes/{id}/egress

Running code#

MethodResolves withEndpoint
run(id, image, args?, opts?: RunOptions)ExecResultPOST …/sandboxes/{id}/run, NDJSON stream
startContainer(id, image, args?, opts?)container idPOST …/sandboxes/{id}/start
exec(id, container, args, opts?: ExecOptions)ExecResultPOST …/sandboxes/{id}/exec
execFrames(id, container, args, opts?)AsyncGenerator<Frame>POST …/sandboxes/{id}/exec
startInteractive(id, image, args?, opts?: CallOptions & { env?, tty? })container idPOST …/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)ExecResultPOST …/sandboxes/{id}/containers/{cid}/attach

Snapshots, fork, explore#

MethodResolves withEndpoint
snapshot(id, opts?: CallOptions & { id?, encrypt? })SnapshotSandboxResultPOST …/sandboxes/{id}/snapshot
listSnapshots(opts?)Snapshot[]GET /kosa8/v1/snapshots
restoreSnapshot(snapshotId, opts?: RestoreOptions)RestoreResultPOST /kosa8/v1/snapshots/{id}/restore
deleteSnapshot(snapshotId, opts?: CallOptions & { wipe?, force? })DeleteSnapshotResultDELETE /kosa8/v1/snapshots/{id}
fork(id, opts?: ForkOptions)ForkResultPOST …/sandboxes/{id}/fork
explore(id, opts: ExploreOptions)ExploreResultpull, fork, one run per branch, deletes

Checkpoints#

MethodResolves withHow
checkpoint(sandbox, opts?: CheckpointOptions)CheckpointResulta snapshot <sandbox>-ckpt-<n>, recorded in the store; evicts past 10
listCheckpoints(sandbox)Checkpoint[]the store, oldest first
rewind(sandbox, opts?: RewindOptions)RewindResultdelete 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); they need kosa8 0.13.0 or later. Every one takes CallOptions as its last argument, merged into its own options.

MethodResolves withEndpoint
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, stringGET …/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 stepPUT …/files/content
deleteFile(id, path, opts?: CallOptions & { recursive? }){ removed }DELETE …/files
makeDir(id, path, opts?), moveFile(id, from, to, opts?)FileInfoPOST …/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)GitResultthe 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 commandsPOST …/sessions/{name}/exec
shell(id, command, opts?: ShellOptions)ShellResult; makes the session (default main) on first usethe 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 expiresPOST …/sandboxes/{id}/previews
revokePreviews(opts?){ ok, revoked }: ends every preview linkPOST /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.

FieldTypeDefault
socketPathstring$HOME/.kosa8/run/kosa8.sock; ignored when a host is set
hoststringKOSA8_HOST: https://…, http://…, tcp://h:p, h:p, unix:///path
tokenstringKOSA8_TOKEN, when the host came from KOSA8_HOST
insecurebooleanKOSA8_INSECURE=1; allows plain http to a non-loopback host
actorActor: 'human' | 'agent' | 'tool''tool'
agentTokenstringKOSA8_AGENT_TOKEN
headersRecord<string,string>extra headers on every request
envRecord<string, string | undefined>process.env
workerFilestring | 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.
checkpointStoreCheckpointStorenew 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)#

FieldTypeSent as
namestringname
cpusnumbercpus
memMbnumbermem_mb
diskGbnumberdisk_gb
mountsMount[]mounts
egressEgressPolicyegress (a { allow } becomes allow:a,b)
egressAllowreadonly string[]egress: "allow:…"
captureCaptureSpeccapture
labelsRecord<string,string>labels
brokerBrokerSpecbroker
autoStopMinnumberauto_stop_min: stop after this many idle minutes
ttlMinnumberttl_min: stop this many minutes after creation
autoDeleteMinnumberauto_delete_min: delete once stopped this long
ephemeralbooleanephemeral: delete whenever it stops
templatestringtemplate: start with a template's image (buildTemplate)

Other option types#

TypeFields
RunOptionsCallOptions + env?: Record<string,string> | string[], onStdout?, onStderr?, onStatus? (each (chunk: Buffer) => void)
ExecOptionsCallOptions + onStdout?, onStderr?
ForkOptionsCallOptions + n? (default 1), prefix? (default <sandbox>-fork), label?
ExploreOptionsCallOptions + variants: string[] (2 or more), image? (alpine:latest), keepAll?, keep?, timeoutMs? (120000), prefix?, pull? (true)
CheckpointOptionsCallOptions + label?
RewindOptionsCallOptions + to?: a checkpoint id or label (default: the latest)
RestoreOptionsCallOptions + name?, label?, allowTampered?
RunCodeOptionsCallOptions + language? (default 'python'), image?, env?: Record<string,string>, timeoutS?
WriteFileOptionsCallOptions + mode? (such as '644')
GitOptionsCallOptions + path?, url?, branch?, depth?, remote?, create?, files?, message?, authorName?, authorEmail?, n?, staged?, username?, token?, image?
GitCommitOptionsGitOptions without path and message, + addAll? (default true)
CreateSessionOptionsCallOptions + image?, env?
SessionExecOptions, ShellOptionsCallOptions + timeoutS?; ShellOptions also session? (default 'main')
StartPtyOptionsCallOptions + image?, command?, cols?, rows?, env?
CreatePreviewOptionsCallOptions + session?, container?, expiresInS?
SetLifecycleOptionsCallOptions + autoStopMin?, autoDeleteMin?, ttlMin?, ephemeral?
BuildTemplateOptionsCallOptions + 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}`
EgressPolicyEgressPolicyString | { 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#

TypeFields
Healthstatus, version, commit, go, uptime_seconds, phase
Sandboxid, name, created, state (running, paused, stopped), cpus, mem_mb, disk_gb?, parent?, mounts?, egress?, capture?, ip?, labels?, broker?: BrokerInfo
BrokerInfourl, hosts?, routes?
CreateSandboxResultsandbox, boot_ms, broker?: { url, placeholders }
StartSandboxResultsandbox, boot_ms, warning?
StopSandboxResultok, sandbox?, warning?, already_stopped?
DeleteSandboxResultok, wipe?, files?
Containerid, image, status, exit?, ip?
EgressStatuspolicy, stats: { passed, denied, dropped, dns_answered, dns_refused, fakenet? }, capture?, wildcards?, fakenet?
Framestream? (stdout, stderr, status), data?: Buffer, done?, ok?, error?, exit?, id?, image?
ExecResultexitCode, stdout, stderr, stdoutBytes: Buffer, stderrBytes: Buffer
Snapshotid, 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
SnapshotSandboxResultsnapshot, snapshot_ms, encrypted_by_policy?, encrypt_ms?, encryption?
RestoreResultsandbox, restore_ms, seal?
DeleteSnapshotResultok, removed, encrypted, shred?, wipe?, files?
ForkResultforks: Sandbox[], snapshot, fork_ms, count, encrypted_by_policy?, encrypt_ms?
ExploreBranchname, variant, exit, output, duration_ms, error?
ExploreResultparent, branches, winner ("" if none succeeded), removed
Checkpointid, sandbox, label, created, auto?
CheckpointResultcheckpoint, evicted: string[], snapshot: SnapshotSandboxResult
RewindResultsandbox, checkpoint, dropped: string[], restore_ms
CodeResultok, exitCode, stdout, stderr, language, image, artifacts: CodeArtifact[], durationMs, timedOut, truncated
CodeArtifacttype (such as image/png), name, data: Buffer
ShellResultok, exitCode, stdout, stderr, cwd, durationMs, timedOut, truncated
GitResultop, ok, exitCode, stdout, stderr, path, status?, log?, branches?
FileInfoname, path, type (file, dir, symlink, other), size, mode, mod_time, link?
SessionInfoname, id, image, status
Previewurl, token, expires_at, container, port, listen
Templatename, image, size_bytes, created, dockerfile?

Transport, checkpoint stores and helpers#

ExportWhat it is
Transportnew 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.
TransportOptionssocketPath?, host?, token?, insecure?, actor?, agentToken?, headers?, env?, workerFile?
RequestOptionsquery?, 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'
CheckpointStoreInterface: load(): Promise<Record<string, Checkpoint[]>>, update<T>(fn): Promise<T> (serialised).
FileCheckpointStorenew FileCheckpointStore(filePath?), default ~/.kosa8/checkpoints.json (mode 0600, atomic rewrite, lock file for Node writers). path.
MemoryCheckpointStoreIn memory only; nothing shared with the CLI.
CheckpointBookThe stack logic over a store, as client.checkpoints: store, nextId, record, list, latest, resolve, pop, forget.
MAX_CHECKPOINTS_PER_SANDBOX10
validateSandboxName(name)Throws Kosa8CheckpointError for a name that could escape the store (empty, ., .., a slash, a leading dot).

Errors#

ExportExtendsThrown for
Kosa8ErrorErrorBase class; client-side checks. Fields status?, daemonMessage?, remediation?, method?, path?, body?, code? (code is kosa8 Cloud's stable error code).
Kosa8ConnectionErrorKosa8ErrorDaemon (or kosa8 Cloud) unreachable.
Kosa8TimeoutErrorKosa8ConnectionErrorA 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.
Kosa8ApiErrorKosa8ErrorAny HTTP error without a more specific class.
Kosa8BadRequestErrorKosa8ApiError400
Kosa8AuthErrorKosa8ApiError401
Kosa8PolicyErrorKosa8ApiError403
Kosa8ApprovalRequiredErrorKosa8PolicyError403 with a refusal; approval: ApprovalRefusal
Kosa8NotFoundErrorKosa8ApiError404
Kosa8ConflictErrorKosa8ApiError409
Kosa8PaymentRequiredErrorKosa8ApiError402, 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.
Kosa8RateLimitErrorKosa8ApiError429: 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).
Kosa8UnsupportedErrorKosa8ApiError501
Kosa8StreamErrorKosa8ErrorError frame in a stream; stdout, stderr
Kosa8CheckpointErrorKosa8ErrorCheckpoint bookkeeping
errorFromResponse(status, body, ctx?)Builds the typed error for an HTTP error answer, as the client does.
ApprovalRefusaltyperoute, action: ApprovalAction, description, class, policy, policy_digest, requirement: ApprovalRequirement, request_id?, why, signers?, request_command
ApprovalActiontypekind, target?, command?, sandbox?, and more
ApprovalRequirementtypepolicy, rules: ApprovalRule[]
ApprovalRuletypeAn approval rule as the daemon reports it (an open record).

Details and real messages: Errors reference.

@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 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 fieldDefault
apiKeyKOSA8_API_KEY. Missing, or not starting with k8c_live_ (CLOUD_KEY_PREFIX) or k8c_tok_ (CLOUD_TOKEN_PREFIX, a capability token): Kosa8Error.
baseUrlKOSA8_CLOUD_URL, then https://api.kosa8.com (DEFAULT_CLOUD_URL). Must be https (plain http only to localhost).
envprocess.env
fetchglobalThis.fetch
timeoutMs120000, per request; past it, Kosa8TimeoutError
retryA RetryPolicy, its options, or false for none. Default: 3 tries with full jitter.

The client#

MemberResolves withEndpoint
cloud.me()The org, the key in use and, for a member's key, the memberGET /v1/me
cloud.usage()This month's usage, the bill estimate and whether work is paused for paymentGET /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, createdPOST /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)CloudSandboxGET /v1/sandboxes/{id}
cloud.snapshotscreate(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 recordsGET / 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 orderPOST /v1/functions/{name}/map
cloud.secrets, tokens, pipelines, orgTemplates, jobs, burst, recordingsSee 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 retriesany

A sandbox: CloudSandbox#

MemberResolves withEndpoint
box.id, box.state, box.infoCloudSandboxInfo: 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 endsPOST …/exec in the background
box.filesread, 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 setPOST …/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.codeContextsA 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#

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

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

TypeFields
Kosa8SandboxSettingsclient?, image?, workingDirectory?, env?, networkPolicy?, egress?, cpus?, memMb?, diskGb?, mounts?, labels?, broker?, setupCommands?, approval?
Kosa8NetworkSandboxSessionCreateOptionsHarnessV1SandboxSessionCreateOptions<Kosa8SandboxSettings>
Kosa8NetworkSandboxSessionResumeOptionsHarnessV1SandboxSessionResumeOptions<Kosa8SandboxSettings>

Usage and behaviour: Vercel AI SDK adapter.

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.

ExportMeaning
RlRun, withRunAn 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.
mapRollouts, RolloutsmapRollouts(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, leaseHeartbeats a set of leased sandboxes while the trainer runs and drains them when it stops: await using _ = rl.lease(cloud, { labels: { job: 'exp-7' } }).
rlThe 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, failureOfThe 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_TASKSHosted jobs (cloud.jobs): kosa8 runs every task's rollout itself. See hosted jobs. A job takes up to 10,000 tasks.
RetryPolicy, callWithRetry, NO_RETRY, newIdempotencyKeyHow often and how long to retry (full jitter), a helper that retries a call under a policy, no retries, and a random Idempotency-Key.
CloudSandboxFilessandbox.files: read, write, list and delete files in a cloud sandbox.
CloudBackgroundExecA command that keeps running after execBackground returns; status() and wait().
CloudSnapshots, CloudOrgTemplatesThe org's snapshots (start a sandbox with create({ snapshot })) and its own templates (built once from an image or Dockerfile, then restored).
CloudPreviews, CloudPreviewDomainssandbox.previews.create(3000) gives an https URL for a port; custom domains for a preview.
CloudSecrets, CloudTokens, CLOUD_TOKEN_PREFIXEncrypted 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, pipelineRunDoneCron commands in a sandbox; CI runs with logs, artifacts and webhook or cron triggers.
CloudCodeContexts, CloudEmbeds, CloudRecordings, CloudBurstCode-interpreter contexts, embeddable sandbox pages, desktop recordings, and Burst Passes.
Kosa8ExecTimeoutError, Kosa8ItemTimeoutError, Kosa8CancelledError, Kosa8OrgFrozenErrorA 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_SIZES2x4 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_S1,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.

ExportMeaning
createKosa8CloudSandbox, Kosa8CloudSandboxProvider, KOSA8_CLOUD_PROVIDER_IDA kosa8 Cloud sandbox provider in the AI SDK 7 provider shape ("kosa8-cloud-sandbox").
createKosa8CloudSandboxSession, resumeKosa8CloudSandboxSession, createKosa8CloudSandboxSessionFromSandboxCreate, reattach to (by sbx_… id or name, waking it) or wrap a kosa8 Cloud sandbox as a network sandbox session.
Kosa8CloudSandboxSession, Kosa8CloudNetworkSandboxSessionThe 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_BYTESThe 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, Kosa8CloudSandboxSessionResumeOptionsTheir settings and options types.

Something wrong or missing? Write to contact@kosa8.com.

The kosa8 weekly

Agent security news, one industry deep-dive and a hands-on challenge, every Monday. Unsubscribe in one click.

© 2026 kosa8 · kosa8.com · Zero Trust cybersecurity infrastructure for AI agents · Local models served by llamay · Agent gateway: MAQPNA