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

Guides / Go / API reference

Go API reference

The exports of github.com/kosa8ai/kosa8-go v0.6.1, package kosa8. Signatures were checked against the source at the v0.5.3 tag. Notes marked v0.1.x record older changes. Paths are the daemon's native API; … stands for /kosa8/v1/sandboxes/{sandbox}. Install it with go get github.com/kosa8ai/kosa8-go@v0.6.1. The RL helpers and a few smaller Cloud types are summarised rather than listed in full; go doc -all github.com/kosa8ai/kosa8-go has every one.

Conventions#

  • Every method that talks to the daemon takes a context.Context first. Its deadline or cancellation ends the HTTP request (not a process already running in the sandbox).
  • call ...Call is an optional trailing kosa8.Call{Approval: id}; only the first is used. Methods that take an options struct carry Approval in it instead. The approval is sent as the X-Kosa8-Approval header.
  • Info is map[string]any: the daemon's JSON object, unchanged, with JSON numbers as float64.
  • Every error returned by this package is a *kosa8.Error, except a cancelled (not timed-out) context, which comes back as context.Canceled, and failures from a custom CheckpointStore or the checkpoint file, which come back as they are.

Client#

type Client struct {
	// contains filtered or unexported fields
}

func New(o Options) (*Client, error)
func (c *Client) Endpoint() Endpoint

New resolves the endpoint (see ResolveEndpoint), checks Actor, builds the HTTP client and picks the checkpoint store. It sends nothing. It fails with a KindUsage error for a refused KOSA8_HOST or host, or an actor other than human, agent or tool. A *Client is safe for concurrent use by multiple goroutines. Endpoint reports where requests go.

Options#

type Options struct {
	SocketPath string // default ~/.kosa8/run/kosa8.sock
	Host       string // a remote worker; default $KOSA8_HOST
	Token      string // bearer token for Host; default $KOSA8_TOKEN when Host came from the env
	Insecure   bool   // allow plain http to a non-loopback worker
	// WorkerFile is the saved connection read when neither Host, KOSA8_HOST
	// nor SocketPath is set (default DefaultWorkerFile: ~/.kosa8/worker.json,
	// written by `kosa8 wsl setup` and `kosa8 worker join`).
	WorkerFile   string
	NoWorkerFile bool   // never read a worker file
	Actor      string // human | agent | tool (default tool)
	AgentToken string // default $KOSA8_AGENT_TOKEN
	Headers    map[string]string
	HTTPClient *http.Client // overrides the transport entirely
	// Checkpoints is where checkpoint stacks live. Default: the CLI's own
	// ~/.kosa8/checkpoints.json, so `kosa8 rewind` and this SDK share them.
	Checkpoints CheckpointStore
	Getenv      func(string) string // for tests; default os.Getenv
}
FieldDefaultEffect
SocketPathDefaultSocketPath()The daemon's unix socket. Used only when no host is set, either here or in KOSA8_HOST.
Host$KOSA8_HOSTA worker address. Forms and rules under ResolveEndpoint.
Token$KOSA8_TOKEN, only when the host came from KOSA8_HOSTSent as Authorization: Bearer …, to a URL endpoint only, never over a unix socket.
Insecurefalse (or KOSA8_INSECURE=1)Allows plain http:// to a host that is not loopback.
WorkerFileDefaultWorkerFile(), ~/.kosa8/worker.jsonThe connection the CLI saved (kosa8 wsl setup, kosa8 worker join). Read when no Host, KOSA8_HOST or SocketPath is set; its host, token and insecure flag are used.
NoWorkerFilefalseNever read a worker file.
Actor"tool"Sent as X-Kosa8-Actor on every request; recorded in the audit log.
AgentToken$KOSA8_AGENT_TOKENSent as X-Kosa8-Agent-Token when non-empty.
HeadersnoneSet on every request after Accept and X-Kosa8-Actor (so they can replace those) and before Content-Type, X-Kosa8-Approval, X-Kosa8-Agent-Token and Authorization (which win when the SDK sets them).
HTTPClientan http.Client with compression off, dialling the socket for a local endpointReplaces the SDK's client entirely. For a local endpoint, requests go to http://kosa8/… and your client must dial the socket itself.
CheckpointsNewFileCheckpointStore("")The checkpoint store. See Checkpoint stores.
Getenvos.GetenvWhere KOSA8_HOST, KOSA8_TOKEN, KOSA8_INSECURE and KOSA8_AGENT_TOKEN are read from.

Daemon#

MethodReturnsHTTP
func (c *Client) Health(ctx context.Context) (Info, error)Keys status, version, commit, go, uptime_seconds, phaseGET /kosa8/v1/health
func (c *Client) Version(ctx context.Context) (string, error)The daemon's version ("" if absent)GET /kosa8/v1/health
func (c *Client) Pull(ctx context.Context, ref string, call ...Call) (Info, error)The daemon's answerPOST /kosa8/v1/pull {"ref"}: into the host's shared engine, not a sandbox

Sandboxes#

MethodReturnsHTTP
func (c *Client) ListSandboxes(ctx context.Context) ([]Info, error)Every sandboxGET /kosa8/v1/sandboxes
func (c *Client) GetSandbox(ctx context.Context, idOrName string) (Info, error)The first sandbox whose id, then name, matches; nil, nil when none doesGET /kosa8/v1/sandboxes, filtered in the client
func (c *Client) CreateSandbox(ctx context.Context, o CreateOptions) (Info, error)Keys sandbox (an object), boot_ms, and broker when one was asked forPOST /kosa8/v1/sandboxes. KindUsage before sending if EgressAllow is set with an Egress other than "" or "deny", a Mounts entry is malformed, or Capture has no Path
func (c *Client) StartSandbox(ctx context.Context, sandbox string, call ...Call) (Info, error)Keys sandbox, boot_msPOST …/up
func (c *Client) StopSandbox(ctx context.Context, sandbox string, call ...Call) (Info, error)Key ok, and othersPOST …/down
func (c *Client) DeleteSandbox(ctx context.Context, sandbox string, o DeleteOptions) (Info, error)The daemon's answer (ok, …) plus checkpoints_dropped (an int)DELETE … (?wipe=1); then, unless KeepCheckpoints, removes the sandbox's records from the store and sends DELETE /kosa8/v1/snapshots/{id} for each, ignoring their errors
func (c *Client) PullIntoSandbox(ctx context.Context, sandbox, ref string, call ...Call) (Info, error)Keys ok, imagePOST …/pull {"ref"}
func (c *Client) SandboxImages(ctx context.Context, sandbox string) ([]string, error)Image referencesGET …/images
func (c *Client) SandboxContainers(ctx context.Context, sandbox string) ([]Info, error)Containers: id, image, status, …GET …/containers
func (c *Client) SandboxEgress(ctx context.Context, sandbox string) (Info, error)policy, stats, and moreGET …/egress

Running code#

MethodReturnsHTTP
func (c *Client) Run(ctx context.Context, sandbox, image string, args []string, opts *RunOptions) (ExecResult, error)The collected result. On error, the output so farPOST …/run {"image","args","env"?}, NDJSON frames. The image must already be in the sandbox
func (c *Client) StartContainer(ctx context.Context, sandbox, image string, args []string, call ...Call) (string, error)The container idPOST …/start {"image","args"}
func (c *Client) Exec(ctx context.Context, sandbox, container string, args []string, opts *RunOptions) (ExecResult, error)The collected result. A non-empty opts.Env is a KindUsage error before sending: the daemon's exec takes no environmentPOST …/exec {"container","args"}, NDJSON frames
func (c *Client) ExecFrames(ctx context.Context, sandbox, container string, args []string, fn func(Frame) error, call ...Call) errornil when the stream ends cleanly; fn's error if it returned one; a KindStream error when the final frame carries an error (after fn has seen that frame)POST …/exec; calls fn per frame, including the final Done frame
func (c *Client) StartInteractive(ctx context.Context, sandbox, image string, args []string, o InteractiveOptions) (string, error)The container idPOST …/start-interactive {"image","args","env","tty"}
func (c *Client) WriteStdin(ctx context.Context, sandbox, container string, r io.Reader, call ...Call) (Info, error){"ok": true}. A second call for the same sandbox and container on the same Client is a KindUsage error, sent nothingPOST …/containers/{cid}/stdin, body streamed from r as application/octet-stream; stdin closes when r returns EOF, so r is the whole of stdin (use an io.Pipe to feed it over time)
func (c *Client) Attach(ctx context.Context, sandbox, container string, opts *RunOptions) (ExecResult, error)The collected result when the container exitsPOST …/containers/{cid}/attach, NDJSON frames

Run, Exec and Attach fail with KindStream when the stream ends with an error frame, with a frame that cannot be decoded, or with no final frame; with KindTimeout when RunOptions.Timeout or the context's deadline passes. In both cases the error's Stdout/Stderr and the returned ExecResult hold the output so far. A non-zero exit code is not an error. opts may be nil.

Snapshots, fork, explore#

MethodReturnsHTTP
func (c *Client) Snapshot(ctx context.Context, sandbox string, o SnapshotOptions) (Info, error)Keys snapshot (an object), snapshot_ms, …POST …/snapshot {"id"?,"encrypt"?}
func (c *Client) ListSnapshots(ctx context.Context) ([]Info, error)Every snapshotGET /kosa8/v1/snapshots
func (c *Client) RestoreSnapshot(ctx context.Context, snapshotID string, o RestoreOptions) (Info, error)Keys sandbox, restore_msPOST /kosa8/v1/snapshots/{id}/restore {"name"?,"label"?,"allow_tampered"?}
func (c *Client) DeleteSnapshot(ctx context.Context, snapshotID string, o SnapshotDeleteOptions) (Info, error)The daemon's answerDELETE /kosa8/v1/snapshots/{id} (?wipe=1, &force=1)
func (c *Client) Fork(ctx context.Context, sandbox string, n int, o ForkOptions) (ForkResult, error)ForkResultPOST …/fork {"n","prefix"?,"label"?}; n below 1 is sent as 1
func (c *Client) Explore(ctx context.Context, sandbox string, variants []string, o ExploreOptions) (ExploreResult, error)ExploreResultPOST …/pull (unless NoPull), POST …/fork with n = len(variants), one POST /kosa8/v1/sandboxes/{branch}/run of sh -c VARIANT per branch, concurrently, then DELETE /kosa8/v1/sandboxes/{branch} for each branch not kept

Explore fails with KindUsage for fewer than two variants, when the fork returned fewer branches than variants, and when Keep names no branch (then it returns the result with every branch kept). A branch that fails to run is recorded in its Error field rather than failing the call; connection-level failures are retried up to four times, 0.5 s, 1 s and 1.5 s apart.

Checkpoints#

MethodReturnsHow
func (c *Client) Checkpoint(ctx context.Context, sandbox, label string, call ...Call) (CheckpointResult, error)CheckpointResultPicks <sandbox>-ckpt-<n>, POST …/snapshot with that id (on a 409 already exists, from a concurrent checkpoint, it moves to the next number, up to 10 tries; any other 409 is returned), DELETE /kosa8/v1/snapshots/{id} for each evicted checkpoint (past MaxCheckpointsPerSandbox), then records it in the store
func (c *Client) ListCheckpoints(sandbox string) ([]Checkpoint, error)Oldest first, by CreatedThe store only; no HTTP
func (c *Client) Rewind(ctx context.Context, sandbox, to string, call ...Call) (RewindResult, error)RewindResultResolves to (an id, or a label without regard to case, newest first; "" = the latest), DELETE …, POST /kosa8/v1/snapshots/{id}/restore {"name": sandbox}, removes later checkpoints from the store and sends DELETE /kosa8/v1/snapshots/{id} for each

Checkpoint errors: KindCheckpoint for an invalid sandbox name (empty, ., .., containing / or \, or starting with a dot), no checkpoints to rewind to, or a to that matches nothing. If the restore step of Rewind fails, the error is KindCheckpoint wrapping the daemon's error (Err), with the message restore failed and NAME no longer exists (it was deleted to free its name for the restore): … — the checkpoint is intact; recover with RestoreSnapshot("ID", RestoreOptions{Name: "NAME"}); by then the sandbox has been deleted and the snapshot is intact. If the delete step fails, its error is returned unchanged and nothing has changed.

Toolbox#

Higher-level calls on the daemon's toolbox routes (see Native HTTP API); they need kosa8 0.13.0 or later. Option structs may be nil.

MethodReturnsHTTP
func (c *Client) RunCode(ctx context.Context, sandbox, code string, opts *CodeOptions) (CodeResult, error)CodeResult. Python (default), JavaScript or TypeScript, run in /workspace; matplotlib charts come back as PNG Artifacts. A non-zero exit is not an error.POST …/code
func (c *Client) ListFiles(ctx context.Context, sandbox, p string) ([]FileInfo, error)A workspace folder (or one entry)GET …/files?path=
func (c *Client) StatFile(ctx context.Context, sandbox, p string) (FileInfo, error)One entry, not following a symlinkGET …/files/stat
func (c *Client) ReadFile(ctx context.Context, sandbox, p string) ([]byte, error)
func (c *Client) ReadFileTo(ctx context.Context, sandbox, p string, w io.Writer) (int64, error)
The file's bytes, or the count written to wGET …/files/content
func (c *Client) WriteFile(ctx context.Context, sandbox, p string, r io.Reader, opts *WriteOptions) (FileInfo, error)
func (c *Client) WriteFileBytes(ctx context.Context, sandbox, p string, data []byte, opts *WriteOptions) (FileInfo, error)
The new entry; folders are made, the file is replaced in one step. WriteOptions{Mode, Approval}.PUT …/files/content
func (c *Client) DeleteFile(ctx context.Context, sandbox, p string, opts *DeleteFileOptions) (Info, error)DeleteFileOptions{Recursive, Approval}DELETE …/files
func (c *Client) MakeDir(ctx context.Context, sandbox, p string, call ...Call) (FileInfo, error)
func (c *Client) MoveFile(ctx context.Context, sandbox, from, to string, call ...Call) (FileInfo, error)
The entryPOST …/files/mkdir, POST …/files/move
func (c *Client) Git(ctx context.Context, sandbox, op string, opts *GitOptions) (GitResult, error)GitResult. op: clone, status, add, commit, push, pull, checkout, branches, log, diff. A git failure is OK: false, not an error.POST …/git
GitClone(ctx, sandbox, repoURL, p string, opts *GitOptions), GitStatus(ctx, sandbox, p string, opts *GitOptions), GitCommit(ctx, sandbox, p, message string, opts *GitOptions)GitResult. GitCommit stages everything first unless NoStage.the same
CreateSession(ctx, sandbox, name string, opts *SessionOptions) (Session, error), ListSessions(ctx, sandbox) ([]Session, error), DeleteSession(ctx, sandbox, session string, call ...Call) (Info, error)A shell that keeps cd and export…/sessions
SessionExec(ctx, sandbox, session, command string, opts *ShellOptions) (ShellResult, error)
Shell(ctx, sandbox, command string, opts *ShellOptions) (ShellResult, error)
ShellResult. Shell uses opts.Session (default main), making it on first use.POST …/sessions/{name}/exec
StartPTY(ctx, sandbox string, opts *PTYOptions) (string, error), ResizePTY(ctx, sandbox, container string, cols, rows int, call ...Call) error, TTYPath(sandbox, container string) stringA container with a terminal; connect a WebSocket to TTYPathPOST …/pty, POST …/containers/{cid}/resize
CreatePreview(ctx, sandbox string, port int, opts *PreviewOptions) (Preview, error), RevokePreviews(ctx, call ...Call) (Info, error)A signed link to a port in the sandbox that expires; revoke ends every linkPOST …/previews, POST /kosa8/v1/previews/rotate
func (c *Client) SetLifecycle(ctx context.Context, sandbox string, o LifecycleOptions) (Info, error)The sandbox. A nil field keeps its value; 0 turns one off.POST …/lifecycle
ListTemplates(ctx) ([]Template, error), DeleteTemplate(ctx, name string, call ...Call) (Info, error)Template recordsGET / DELETE /kosa8/v1/templates
func (c *Client) BuildTemplate(ctx context.Context, name, contextDir string, opts *BuildOptions) (BuildResult, error)BuildResult{Image}. Builds the Dockerfile in a throwaway sandbox and keeps the image as a template for CreateOptions.Template. A failed build is KindStream.POST /kosa8/v1/templates, the context as a tar
type CodeOptions struct {
	Language string            // python (default), javascript or typescript
	Image    string            // default: the sandbox template's image, else the language's
	Env      map[string]string
	Timeout  time.Duration     // the daemon stops the snippet after this; 0 is its default
	Approval string
}
type CodeResult struct {
	ExitCode   int
	Stdout     string
	Stderr     string
	Language   string
	Image      string
	Artifacts  []Artifact // Artifact{Type, Name, Data []byte}
	DurationMS int64
	TimedOut   bool
	Truncated  bool
}
func (r CodeResult) OK() bool // ExitCode == 0 && !TimedOut

type FileInfo struct {
	Name, Path, Type string // Type: file | dir | symlink | other
	Size    int64
	Mode    uint32
	ModTime string
	Link    string
}
func (f FileInfo) IsDir() bool

type GitResult struct {
	Op, Path       string
	OK             bool
	ExitCode       int
	Stdout, Stderr string
	Status         *GitStatus
	Log            []GitCommit
	Branches       []GitBranch
}
type ShellResult struct {
	ExitCode       int
	Stdout, Stderr string
	Cwd            string
	DurationMS     int64
	TimedOut, Truncated bool
}
func (r ShellResult) OK() bool

type LifecycleOptions struct {
	AutoStopMin   *int  // stop after this many idle minutes
	AutoDeleteMin *int  // delete once stopped this long
	TTLMin        *int  // stop this long after creation
	Ephemeral     *bool // delete instead of stopping
	Approval      string
}
func Ptr[T any](v T) *T // kosa8.Ptr(30) for these fields

Also exported: GitOptions (Path, URL, Branch, Depth, Remote, Create, Files, Message, AuthorName, AuthorEmail, N, Staged, Username, Token, Image, NoStage, Approval), GitStatus, GitFileStatus, GitCommit, GitBranch, Session (Name, ID, Image, Status), SessionOptions (Image, Env, Approval), ShellOptions (Timeout, Session, Approval), PTYOptions (Image, Command, Cols, Rows, Env, Approval), Preview (URL, Token, ExpiresAt, Container, Port, Listen), PreviewOptions (Session, Container, ExpiresIn, Approval), Template, BuildOptions (Dockerfile, BuildArgs, Egress, Replace, OnOutput, Approval), BuildResult.

Handle#

func (c *Client) Sandbox(id string) *Sandbox

Returns a handle bound to one sandbox. It sends nothing and does not check that the sandbox exists.

Sandbox#

type Sandbox struct {
	ID string
	// contains filtered or unexported fields
}
MethodCalls
func (s *Sandbox) Info(ctx context.Context) (Info, error)GetSandbox
func (s *Sandbox) Start(ctx context.Context, call ...Call) (Info, error)StartSandbox
func (s *Sandbox) Stop(ctx context.Context, call ...Call) (Info, error)StopSandbox
func (s *Sandbox) Delete(ctx context.Context, o DeleteOptions) (Info, error)DeleteSandbox
func (s *Sandbox) Pull(ctx context.Context, ref string, call ...Call) (Info, error)PullIntoSandbox
func (s *Sandbox) Run(ctx context.Context, image string, args []string, o *RunOptions) (ExecResult, error)Run
func (s *Sandbox) StartContainer(ctx context.Context, image string, args []string, call ...Call) (string, error)StartContainer
func (s *Sandbox) Exec(ctx context.Context, container string, args []string, o *RunOptions) (ExecResult, error)Exec
func (s *Sandbox) Containers(ctx context.Context) ([]Info, error)SandboxContainers
func (s *Sandbox) Images(ctx context.Context) ([]string, error)SandboxImages
func (s *Sandbox) Egress(ctx context.Context) (Info, error)SandboxEgress
func (s *Sandbox) Snapshot(ctx context.Context, o SnapshotOptions) (Info, error)Snapshot
func (s *Sandbox) Fork(ctx context.Context, n int, o ForkOptions) (ForkResult, error)Fork
func (s *Sandbox) Explore(ctx context.Context, variants []string, o ExploreOptions) (ExploreResult, error)Explore
func (s *Sandbox) Checkpoint(ctx context.Context, label string, call ...Call) (CheckpointResult, error)Checkpoint
func (s *Sandbox) Checkpoints() ([]Checkpoint, error)ListCheckpoints
func (s *Sandbox) Rewind(ctx context.Context, to string, call ...Call) (RewindResult, error)Rewind
RunCode, ListFiles, StatFile, ReadFile, ReadFileTo, WriteFile, WriteFileBytes, DeleteFile, MakeDir, MoveFile, Git, GitClone, GitStatus, GitCommit, CreateSession, Sessions, SessionExec, Shell, DeleteSession, StartPTY, ResizePTY, CreatePreview, SetLifecycleThe toolbox method of the same name (Sessions is ListSessions), without the sandbox argument

There is no ExecFrames, StartInteractive, WriteStdin, Attach, RestoreSnapshot or DeleteSnapshot on the handle; call them on the client with s.ID.

Option types#

Call#

type Call struct{ Approval string }

Per-request options: a signed approval id, sent as X-Kosa8-Approval (trimmed; omitted when empty).

CreateOptions#

type CreateOptions struct {
	Name   string
	CPUs   int
	MemMB  int
	DiskGB int
	Mounts []string // host:guest[:ro]; host must be absolute
	Egress string   // deny | any | fakenet | allow:host,host
	// EgressAllow limits the network to these hosts (sets Egress to allow:…).
	EgressAllow []string
	// Capture records the sandbox's network traffic as pcap segments under
	// Capture.Path, a file on the host (pcapng). nil records nothing.
	Capture  *CaptureOptions
	Labels   map[string]string
	Broker   any // the credential-broker config, passed through
	// Lifecycle: AutoStopMin stops the sandbox after that many idle minutes,
	// TTLMin that long after creation, AutoDeleteMin deletes it once stopped
	// that long, and Ephemeral deletes it whenever it stops. 0 is off.
	AutoStopMin   int
	TTLMin        int
	AutoDeleteMin int
	Ephemeral     bool
	// Template starts the sandbox with a template's image (BuildTemplate).
	Template string
	Approval string
}

// CaptureOptions turn on packet capture for a sandbox (the daemon writes one pcapng file at Path).
type CaptureOptions struct {
	Path     string // host file the capture is written to (required)
	MaxBytes int64  // per segment; 0 is the daemon's default
	MaxFiles int    // segments kept; 0 is the daemon's default
}
FieldSent asNotes
NamenameOmitted when empty: the daemon picks one.
CPUs, MemMB, DiskGBcpus, mem_mb, disk_gbOmitted when 0 or less: the daemon's defaults.
Mountsmounts, each "host:guest[:ro|:rw]" as {"host_path","guest_path","read_only"}Anything that is not two non-empty parts (plus an optional ro/rw) is a KindUsage error, and so (from v0.1.2) is a host path that is not absolute (filepath.IsAbs) or a guest path not starting with /. Shared with virtiofs. v0.1.0 sent strings and every mount failed. See the guide.
Egressegressdeny, any, fakenet or allow:h1,h2. Empty: the daemon's default (the org policy's, if it sets one).
EgressAllowegress: "allow:h1,h2"Each host trimmed. Combined with an Egress other than ""/"deny" it is a KindUsage error.
Capturecapture: {"path", "max_bytes"?, "max_files"?}nil: no capture. Empty Path is a KindUsage error. Path is a pcapng file path (like kosa8 sandbox create --pcap FILE); a directory is refused with a 500 capture: open …: is a directory. MaxBytes, MaxFiles are sent only when positive. v0.1.0 had a bool here that never worked.
LabelslabelsOmitted when empty.
BrokerbrokerMarshalled with encoding/json as given.
AutoStopMin, TTLMin, AutoDeleteMinauto_stop_min, ttl_min, auto_delete_minMinutes; sent when positive. A negative value is a KindUsage error.
Ephemeralephemeral: trueDelete the sandbox whenever it stops.
TemplatetemplateStart with a template's image (BuildTemplate). Omitted when empty.
ApprovalheaderX-Kosa8-Approval.

Other option types#

type DeleteOptions struct {
	Wipe            bool // overwrite the disks, not just unlink them
	KeepCheckpoints bool // keep this sandbox's checkpoint snapshots
	Approval        string
}

type RunOptions struct {
	Env      []string // KEY=VALUE
	OnStdout func([]byte)
	OnStderr func([]byte)
	OnStatus func([]byte) // pull/progress lines
	Timeout  time.Duration
	Approval string
}

type InteractiveOptions struct {
	Env      []string
	TTY      bool
	Approval string
}

type SnapshotOptions struct {
	ID       string // default: the daemon picks one
	Encrypt  bool
	Approval string
}

type RestoreOptions struct {
	Name          string
	Label         string
	AllowTampered bool
	Approval      string
}

type SnapshotDeleteOptions struct {
	Wipe, Force bool
	Approval    string
}

type ForkOptions struct {
	Prefix   string
	Label    string
	Approval string
}

type ExploreOptions struct {
	Image    string        // default alpine:latest
	KeepAll  bool          // keep every branch
	Keep     string        // keep this branch instead of the fastest success
	Timeout  time.Duration // per branch; default 120s
	Prefix   string
	NoPull   bool // the image is already in the sandbox
	Approval string
}
FieldBehaviour
DeleteOptions.Wipe?wipe=1 on the sandbox delete and on each checkpoint snapshot delete.
DeleteOptions.KeepCheckpointsLeaves the store and the snapshots alone; checkpoints_dropped is 0.
RunOptions.EnvSent by Run (when non-nil). Exec refuses a non-empty one with KindUsage; Attach ignores it.
RunOptions.OnStdout, OnStderrCalled with each chunk as it arrives, on the calling goroutine. The chunk is also collected in the result.
RunOptions.OnStatusCalled with status frames (progress lines); these are not collected.
RunOptions.TimeoutWhen positive, wraps the context with context.WithTimeout for this call.
InteractiveOptions.Env, TTYSent as env (null when nil) and tty.
SnapshotOptions.ID, EncryptSent as id and encrypt: true when set.
RestoreOptions.Name, Label, AllowTamperedSent as name, label, allow_tampered: true when set. Name empty: the daemon picks one.
SnapshotDeleteOptions.Wipe, Force?wipe=1, ?force=1.
ForkOptions.Prefix, LabelSent when set. The daemon names forks <prefix>1, <prefix>2, …; its default prefix is <sandbox>-fork.
ExploreOptions.PrefixDefault <sandbox>-explore-<unix seconds mod 100000>.

Result types#

type Info = map[string]any

type ExecResult struct {
	ExitCode    int
	StdoutBytes []byte
	StderrBytes []byte
}
func (r ExecResult) Stdout() string
func (r ExecResult) Stderr() string
func (r ExecResult) OK() bool // ExitCode == 0

type ForkResult struct {
	Forks    []Info `json:"forks"`
	Snapshot any    `json:"snapshot"`
	ForkMS   int64  `json:"fork_ms"`
	Count    int    `json:"count"`
}

type ExploreBranch struct {
	Name       string
	Variant    string
	Exit       int
	Output     string
	Error      string // set when the branch could not run
	DurationMS int64
}

type ExploreResult struct {
	Parent   string
	Branches []ExploreBranch
	Winner   string // "" when no branch succeeded
	Removed  int
}

type Checkpoint struct {
	ID      string    `json:"id"`
	Sandbox string    `json:"sandbox"`
	Label   string    `json:"label"`
	Auto    bool      `json:"auto,omitempty"`
	Created time.Time `json:"created"`
}

type CheckpointResult struct {
	Checkpoint Checkpoint
	Evicted    []string
	Snapshot   Info
}

type RewindResult struct {
	Sandbox    any
	Checkpoint Checkpoint
	Dropped    []string
	RestoreMS  any
}
FieldMeaning
ExploreBranch.Outputstdout followed by stderr, trailing newlines trimmed.
ExploreBranch.DurationMSWall time for the branch, retries included.
ExploreResult.WinnerThe successful branch (no Error, exit 0) with the smallest DurationMS, or Keep when set.
ExploreResult.RemovedBranches deleted successfully. With KeepAll, 0. With no winner and no KeepAll, every branch is deleted.
CheckpointResult.EvictedIds of checkpoints removed to stay within 10.
CheckpointResult.SnapshotThe daemon's snapshot answer (snapshot, snapshot_ms, …).
RewindResult.Sandbox, RestoreMSThe restore answer's sandbox (a map[string]any) and restore_ms (a float64), untyped.
RewindResult.DroppedIds of checkpoints taken after the target, now removed.

Checkpoint stores#

const MaxCheckpointsPerSandbox = 10

type CheckpointStore interface {
	Load() (map[string][]Checkpoint, error)
	// Update runs fn on the stacks and saves what it leaves, serialised against other updates.
	Update(fn func(map[string][]Checkpoint) error) error
}

type FileCheckpointStore struct {
	Path string
	// contains filtered or unexported fields
}
func NewFileCheckpointStore(path string) *FileCheckpointStore
func (f *FileCheckpointStore) Load() (map[string][]Checkpoint, error)
func (f *FileCheckpointStore) Update(fn func(map[string][]Checkpoint) error) error

type MemoryCheckpointStore struct {
	// contains filtered or unexported fields
}
func (m *MemoryCheckpointStore) Load() (map[string][]Checkpoint, error)
func (m *MemoryCheckpointStore) Update(fn func(map[string][]Checkpoint) error) error
NameBehaviour
NewFileCheckpointStore"" means ~/.kosa8/checkpoints.json, the CLI's file.
FileCheckpointStore.LoadA missing file is an empty store; so is a file that is not valid JSON (a corrupt store must not make the sandbox unusable).
FileCheckpointStore.UpdateCreates the directory (0700), takes an exclusive flock on <Path>.lock (the CLI's lock; no lock on systems without flock, only an in-process mutex), loads, runs fn, writes <Path>.tmp (0600) and renames it over the file. If fn fails nothing is written.
MemoryCheckpointStoreThe zero value is ready to use; use it by pointer. Load returns a copy; Update works on a copy and keeps it only if fn succeeds.

Endpoint, frames and constants#

const Version = "0.5.3"

const (
	ApprovalHeader   = "X-Kosa8-Approval"
	ActorHeader      = "X-Kosa8-Actor"
	AgentTokenHeader = "X-Kosa8-Agent-Token"
)

func DefaultSocketPath() string // $HOME/.kosa8/run/kosa8.sock
func DefaultWorkerFile() string // $HOME/.kosa8/worker.json

type Endpoint struct {
	Unix  string   // socket path, when local
	URL   *url.URL // remote worker, when not
	Token string
}
func (e Endpoint) Target() string // "unix://PATH" or "SCHEME://HOST"

func ResolveEndpoint(host, socketPath, token string, insecure bool, getenv func(string) string) (Endpoint, error)
func Resolve(o Options) (Endpoint, error) // as New does: ResolveEndpoint's rules plus the saved worker file

type Frame struct {
	Stream string `json:"stream,omitempty"` // stdout | stderr | status
	Data   []byte `json:"data,omitempty"`
	Done   bool   `json:"done,omitempty"`
	OK     bool   `json:"ok,omitempty"`
	Error  string `json:"error,omitempty"`
	Exit   *int   `json:"exit,omitempty"`
	ID     string `json:"id,omitempty"`
}

ResolveEndpoint follows the CLI's KOSA8_HOST rules. It sends nothing.

  • The address is host if non-empty, else KOSA8_HOST from getenv (nil means os.Getenv), trimmed of spaces and trailing slashes.
  • Empty: the unix socket socketPath, or DefaultSocketPath().
  • unix:///path: that socket. tcp://h:p and a bare h:p: http://h:p. http:// and https://: as given (the scheme's case is ignored, and a path is kept as a prefix). Any other scheme, or no host name, is a KindUsage error.
  • Plain http to a host other than localhost, ::1 or 127.* is a KindUsage error unless insecure or KOSA8_INSECURE=1.
  • token is kept for a URL endpoint; when empty and the address came from KOSA8_HOST, KOSA8_TOKEN is used. A unix endpoint carries no token.

Frame is one NDJSON frame of a run, exec or attach stream, with Data decoded from base64. Output frames have Stream and Data; the last frame has Done, and either OK and Exit, or Error.

Cloud: kosa8 Cloud#

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. New never creates one.

const DefaultCloudURL = "https://api.kosa8.com"
const CloudKeyPrefix = "k8c_live_"
const CloudExecMaxTimeoutS = 90

type CloudOptions struct {
	APIKey     string              // default $KOSA8_API_KEY
	BaseURL    string              // default $KOSA8_CLOUD_URL, then DefaultCloudURL
	HTTPClient *http.Client        // default a plain http.Client
	Timeout    time.Duration       // per request; default 120 s
	Getenv     func(string) string // for tests; default os.Getenv
	Retry      *RetryPolicy        // retries of retryable answers
}

func NewCloud(o CloudOptions) (*Cloud, error)

type Cloud struct {
	Sandboxes    *CloudSandboxes
	Functions    *CloudFunctions
	Snapshots    *CloudSnapshots    // durable snapshots
	Secrets      *CloudSecrets      // the org's secrets
	Pipelines    *CloudPipelines    // CI runs and hooks
	OrgTemplates *CloudOrgTemplates // the org's own templates, built once and restored
	Tokens       *CloudTokens       // short-lived capability tokens
}
func (c *Cloud) BaseURL() string
func (c *Cloud) Me(ctx context.Context) (Info, error)    // GET /v1/me: the org, the key, the member
func (c *Cloud) Usage(ctx context.Context) (Info, error) // GET /v1/usage: usage, bill estimate, payment pause
func (c *Cloud) Templates(ctx context.Context) ([]CloudTemplate, error)

cloud, err := kosa8.NewCloud(kosa8.CloudOptions{})
box, err := cloud.Sandboxes.Create(ctx, kosa8.CloudCreateOptions{Template: "python"})
res, err := box.Exec(ctx, []string{"python3", "-c", "print(6 * 7)"}, nil)
fmt.Print(res.Stdout) // 42
err = box.Delete(ctx)

NewCloud returns a KindUsage error for a missing key, a key without the k8c_live_ prefix, or a base URL that is not https (plain http only to localhost). HTTP errors are the usual *Error kinds, with the cloud's stable code in Code and the request id in RequestID.

MethodReturns
func (s *CloudSandboxes) Create(ctx context.Context, o CloudCreateOptions) (*CloudSandbox, error)The sandbox, once running (unless NoWait). CloudCreateOptions has Template, Region string; SleepAfterS *int; TTLSeconds int; DeleteAfter int64; AcceptPrice *float64; Size string; CPUs, MemMB int; Image string; DiskGB int; Persistent, Docker bool; CPU, Name string; Labels, Env map[string]string; Snapshot string; Secrets []string; Egress *CloudEgress; NoWait bool; LeaseS int; IdempotencyKey string. POST /v1/sandboxes.
func (s *CloudSandboxes) CreateMany(ctx context.Context, o CloudBatchOptions) (*CloudSandboxBatch, error)Several sandboxes in one call
func (s *CloudSandboxes) List(ctx context.Context, all bool) ([]*CloudSandbox, error), ListPage(ctx, o CloudListOptions), ListAll(ctx, o CloudListOptions)The org's sandboxes; with all, deleted ones too. ListPage returns one page with a cursor.
func (s *CloudSandboxes) Get(ctx context.Context, id string) (*CloudSandbox, error)One sandbox; KindNotFound if there is none
Heartbeat(ctx, sel CloudSelector, extendS int), Drain(ctx, sel CloudSelector), Grade(ctx, id, cmd, o)For RL runs: extend leases, delete a run's sandboxes, grade in a sealed fork
func (b *CloudSandbox) Exec(ctx context.Context, argv []string, o *CloudExecOptions) (CloudExecResult, error)
func (b *CloudSandbox) ExecShell(ctx context.Context, cmd string, o *CloudExecOptions) (CloudExecResult, error)
CloudExecResult{ExitCode *int; Stdout, Stderr string; WokeMs *int; FailureClass FailureClass; Retryable bool} and OK(). ExecShell runs sh -c cmd. CloudExecOptions{Image string; Env map[string]string; TimeoutS int}; TimeoutS is at most 90. A sleeping sandbox wakes for it. POST /v1/sandboxes/{id}/exec.
ExecBackground(ctx, argv, o) (CloudBackgroundExec, error), BackgroundExec(ctx, execID), WaitBackground(ctx, execID, interval)A command not held to the 90-second limit; its output goes to a workspace file
RunCode(ctx, code, o *CloudCodeOptions) (CloudCodeResult, error), CodeContexts, CreateCodeContext, ResetCodeContext, DeleteCodeContextA stateful code interpreter; needs a Persistent sandbox
b.Files()*CloudFiles: Read, ReadText, Write, WriteString, List, Mkdir, Delete(ctx, path, recursive), Download, Upload, Link
Checkpoint(ctx, label string) (CloudCheckpoint, error), Checkpoints(ctx), Rewind(ctx, checkpointID string) (CloudRewindResult, error)Checkpoints of the cloud sandbox and a rewind to one
Fork(ctx, n int) ([]*CloudSandbox, error), ForkWith(ctx, o CloudForkOptions) (*CloudSandboxBatch, error)Live copies
Snapshot(ctx, name string) (CloudSnapshot, error); cloud.Snapshots.List(ctx, sandboxID), Get, DeleteDurable snapshots; start from one with CloudCreateOptions.Snapshot
Sleep(ctx) error, Wake(ctx) error, Refresh(ctx) error, WaitRunning(ctx, interval), Update(ctx, o CloudUpdateOptions), SetLabels, HeartbeatUpdate b.Info. Sleep snapshots it and frees its VM; wake restores it with its files.
Egress, SetEgress, ResetEgress, Previews(), Ports, Terminal, Schedules(), Secrets, Metrics, LogsNetwork rules, preview links, listening ports, a terminal, cron schedules, the secret names it gets, metrics, its log
Delete(ctx) errorDELETE /v1/sandboxes/{id}
b.Info, b.ID(), b.State()CloudSandboxInfo: ID, State (creating, running, sleeping, stopped, deleted, error), Template, CPUs, MemMB, Source, ParentID, Region (us-ash1, or cf-auto for overflow capacity), CreatedAt, Persistent, Name, Labels, CostUSD, …
func (f *CloudFunctions) Deploy(ctx context.Context, name string, spec CloudFunctionSpec) (Info, error)CloudFunctionSpec{Runtime, Code string; Env map[string]string; TimeoutS int; Web, Schedule string; Extra map[string]any}; each deploy bumps the version. PUT /v1/functions/{name}.
List(ctx) ([]Info, error), Get(ctx, name) (Info, error), Delete(ctx, name) errorFunction records
func (f *CloudFunctions) Invoke(ctx context.Context, name string, event any) (CloudInvokeResult, error)CloudInvokeResult (OK, Result, Error, Logs, …; DecodeResult(v)). A handler that fails is OK: false, not an error.
func (f *CloudFunctions) Map(ctx context.Context, name string, events []any, o *CloudMapOptions) (CloudMapResult, error)One call per event, results in input order. CloudMapOptions{Concurrency int}.
cloud.Secrets, cloud.OrgTemplates, cloud.Pipelines, cloud.Tokens, cloud.StartRunOrg secrets (Set, List, Delete), org templates (Build, Import, List, Get, WaitReady, Delete), CI pipelines, capability tokens, RL runs

Also:

  • Exec waits and returns the whole output. The API cuts a buffered exec off after 90 seconds (or TimeoutS) and the call fails with KindExecTimeout (504, Code exec_timeout), which errors.Is(err, kosa8.ErrTimeout) also matches. For long work use ExecBackground.
  • The default template, base, is Alpine Linux: busybox sh, no bash or python. Set Template (such as "python") when you need them.
  • Execs share the sandbox's exec container while it lasts, but only /workspace is kept for certain. Write files you need later there, or set Persistent.

Errors#

type Error struct {
	Kind          Kind
	Message       string
	Status        int    // HTTP status, when the daemon answered
	DaemonMessage string // the daemon's "error" text, verbatim
	Remediation   string // the daemon's "remediation": what to do about it
	Method, Path  string
	Body          any            // the decoded response body
	Approval      map[string]any // set when Kind == KindApprovalRequired: the daemon's refusal
	Stdout        string         // KindStream: output produced before the error
	Stderr        string
	Err           error // the underlying cause, if any
	// The rest are set on kosa8 Cloud errors; empty for daemon errors.
	Code         string        // the stable error code (payment_required, quota_exceeded, ...)
	UpgradeURL   string        // 402: where a person fixes it
	AgentMessage string        // 402: a sentence an agent should relay word for word
	RetryAfter   time.Duration // the server's Retry-After
	FailureClass FailureClass
	Retryable    bool
	RequestID    string
}
func (e *Error) Error() string        // Message
func (e *Error) Unwrap() error        // Err
func (e *Error) Is(target error) bool

func AsError(err error) (*Error, bool)

type Kind string

const (
	KindConnection       Kind = "connection"        // daemon unreachable
	KindAPI              Kind = "api"               // any other HTTP error
	KindBadRequest       Kind = "bad_request"       // 400
	KindAuth             Kind = "auth"              // 401
	KindPolicy           Kind = "policy"            // 403
	KindApprovalRequired Kind = "approval_required" // 403 needing a signed approval
	KindNotFound         Kind = "not_found"         // 404
	KindConflict         Kind = "conflict"          // 409
	KindPaymentRequired  Kind = "payment_required"  // 402: kosa8 Cloud wants a payment method first
	KindRateLimit        Kind = "rate_limit"        // 429: too many requests, or a quota reached
	KindUnsupported      Kind = "unsupported"       // 501: not_available / not_supported
	KindOrgFrozen        Kind = "org_frozen"        // 423: the org is frozen in the Security Center
	KindExecTimeout      Kind = "exec_timeout"      // a kosa8 Cloud exec ran past the 90 s limit
	KindStream           Kind = "stream"            // a stream ended with an error frame
	KindCheckpoint       Kind = "checkpoint"        // client-side checkpoint bookkeeping
	KindTimeout          Kind = "timeout"
	KindUsage            Kind = "usage" // bad arguments
)

var (
	ErrConnection       = &Error{Kind: KindConnection}
	ErrAPI              = &Error{Kind: KindAPI}
	ErrBadRequest       = &Error{Kind: KindBadRequest}
	ErrAuth             = &Error{Kind: KindAuth}
	ErrPolicy           = &Error{Kind: KindPolicy}
	ErrApprovalRequired = &Error{Kind: KindApprovalRequired}
	ErrNotFound         = &Error{Kind: KindNotFound}
	ErrConflict         = &Error{Kind: KindConflict}
	ErrPaymentRequired  = &Error{Kind: KindPaymentRequired}
	ErrRateLimit        = &Error{Kind: KindRateLimit}
	ErrUnsupported      = &Error{Kind: KindUnsupported}
	ErrOrgFrozen        = &Error{Kind: KindOrgFrozen}
	ErrExecTimeout      = &Error{Kind: KindExecTimeout}
	ErrStream           = &Error{Kind: KindStream}
	ErrCheckpoint       = &Error{Kind: KindCheckpoint}
	ErrTimeout          = &Error{Kind: KindTimeout}
	ErrUsage            = &Error{Kind: KindUsage}
)

Is matches a target *Error with an empty Message (a sentinel, or &kosa8.Error{Kind: k}) by Kind. Three extra rules: ErrPolicy also matches KindApprovalRequired, ErrTimeout also matches KindExecTimeout, and ErrAPI matches every HTTP kind (api, bad_request, auth, policy, approval_required, not_found, conflict, payment_required, rate_limit, unsupported, org_frozen, exec_timeout). ErrUsage (new in v0.1.1) matches KindUsage.

ErrPaymentRequired (402) comes from kosa8 Cloud: it will not start new work until the account is in order (no payment method on file, the last charge declined, the spending cap reached, or no plan that covers the request). Code is payment_required, spending_cap_reached, plan_required, plan_limit or plan_feature, and UpgradeURL and AgentMessage carry the body's upgrade_url and agent_message; ErrOrgFrozen (423) means an owner froze the organization, so stop and tell a person; do not retry until a person acts. ErrRateLimit (429): Code quota_exceeded is the organization's running-sandbox limit (delete or sleep one first), rate_limited a request rate limit (wait and retry). AsError is errors.As into a *Error. When each kind occurs, with real messages: Go errors and troubleshooting.

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