zipbox

package module
v0.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 28 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

zipbox-go

The Go SDK and the zipbox CLI for Zipbox: create boxes, run commands, move files, open a terminal and publish ports from code. Nothing on a box stops on a clock.

Docs: zipbox.ai/docs/sdk-go · CLI: zipbox.ai/docs/cli · Index for agents: zipbox.ai/llms.txt

Install

go get github.com/tribes-protocol/zipbox-go
export ZIPBOX_API_KEY=zb_…   # zipbox.ai → Settings → API keys

Quickstart

c := zipbox.New("") // reads ZIPBOX_API_KEY
// the options apply only when the box is created; an existing box comes back as it is
box, err := c.Sandboxes.GetOrCreate(ctx, "demo", zipbox.CreateOptions{Tier: "s"})
if err != nil {
	log.Fatal(err)
}
res, err := box.Exec(ctx, "uname -a")
if err != nil {
	log.Fatal(err)
}
fmt.Print(res.Stdout)

A runnable version is in ../examples/go/quickstart.

The surface

  • c.Sandboxes: Create(ctx, CreateOptions), GetOrCreate(ctx, name, CreateOptions), List, Get, Start, Stop, Restart, Delete(ctx, id, DeleteOptions), SetTier, WaitReady. c.Sandbox(id) returns a handle without a call.
  • Box handle: Refresh, WaitReady, Start, Stop, Restart, SetTier, Delete, Exec, ExecArgv, ExecStream, ExecStreamArgv, ExecBackground, ExecBackgroundArgv, RunCode, Logs(LogOptions{Since, Lines, Unit}), SSHInfo, Screenshot, Command(id).
  • box.Commands: Get, List, Events, Stdin, CloseStdin, Signal; a *Command adds Wait. Every stream re-attaches from its cursor after a drop.
  • box.Files: Read, ReadTo, Write, List, Stat, Mkdir, Move, Copy, Delete, Upload, Download. Relative paths resolve against /root/workspace.
  • box.Pty: Create, Attach (PtyOptions{Cols, Rows, ClientLabel}) → an io.ReadWriter with Resize, Takeover, Detach, Close and ExitCode. A dropped socket reconnects by itself (exponential backoff, no attempt limit) and re-attaches the same session.
  • box.Preview: Create(port, label) → https://<label>.<box host>, Remove(label) (a label or the full host). Previews are public unless the box is private.
  • box.Tailscale: Status (nil when the box never joined a tailnet), Connect(authKey), Disconnect. Connect seals the auth key on this machine to the box's own key (AgentPublicKey), so Zipbox relays it once and never sees it; it re-reads the key and re-seals once on box_key_changed. Use a one-off, pre-approved key.
  • box.SetPrivate(enabled): private mode ("tailnet only"). Needs the box connected (tailnet_not_connected otherwise). CreateOptions{Private: true} starts a box private; Create then returns once it is running with its key, since it is not ready until it joins. Box calls (exec, files, PTY, previews) on a private box work only from a device on your tailnet; elsewhere they fail fast with box_private_unreachable. Lifecycle calls always work.
  • c.Account: WhoAmI, Balance, Usage.

Every failure is a *zipbox.Error (errors.As) carrying Code, Status, Message, RequestID, Retryable, RetryAfter and DocsURL. A command that exits non-zero is a result (ExecResult.ExitCode), never an error. No call has a default deadline: bound one with a context. An account holds 250 machine names, and a deleted box keeps its name: reuse a fixed pool of names with GetOrCreate instead of a fresh name per job. A new name past the limit returns CodeMachineLimitReached (zipbox.ai/docs/machine-limit).

CLI

curl -fsSL https://zipbox.ai/install.sh | sh        # macOS, Linux
irm https://zipbox.ai/install.ps1 | iex             # Windows
brew install tribes-protocol/tap/zipbox             # Homebrew

zipbox login
zipbox sandbox create --name demo
zipbox exec demo -- make test                       # exits with the remote status
zipbox shell demo
zipbox tailscale connect demo < tskey.txt           # the auth key never goes on argv
zipbox private on demo

Commands: login [--with-key], logout, whoami, sandbox {create,list,get,start,stop,restart,delete,tier}, exec, run, files {ls,cat,put,get,rm,mkdir,mv}, shell, ssh, preview (preview rm), tailscale {connect,status,disconnect}, private {on,off}, logs, docs [slug], mcp {start,init <claude|codex|cursor|windsurf>,config}. --json works on every command. ZIPBOX_API_KEY overrides the saved login, for CI.

zipbox mcp start serves the Zipbox MCP tools over stdio by bridging to the hosted server (https://mcp.zipbox.ai/mcp, override with ZIPBOX_MCP_URL), so stdio clients get exactly the hosted tool set. Like the hosted server, it cannot reach a private box.

zipbox tailscale connect <box> reads a one-off Tailscale auth key from stdin (hidden on a terminal) or --auth-key-file F, never from an argument. zipbox sandbox create --private --tailscale-auth-key-file F creates a private box and joins it to your tailnet.

--json shapes
Command Output
sandbox list array of boxes (id, name, status, tier, …)
sandbox create/get one box plus ready, baseUrl
sandbox start/stop/… {"id", "action"}
exec, run {"id", "exitCode", "stdout", "stderr", "timedOut"}
exec --background the command record (id, state, argv, …)
files ls array of {"name", "kind", "sizeBytes", "modifiedAtMs"}
ssh {"host", "user", "command"}
preview {"url", "label", "host"}
tailscale status {"id", "tailscale": {"state", "tailnet", "ipv4", …}}
tailscale connect {"id", "pending": true}
private on/off {"id", "private"}
whoami, login {"userId", "apiKey": {…}}
errors (stderr) {"error": {"code", "message", "docsUrl", …}}

Development

go vet ./... && go test -race ./...

The tests run the shared conformance suite in ../conformance/fixtures and reproduce the box envelope vector in ../conformance/vectors byte for byte.

Documentation

Overview

Package zipbox is the Go SDK for Zipbox: create boxes, run commands, move files, open terminals and publish ports from code.

c := zipbox.New("") // reads ZIPBOX_API_KEY
box, err := c.Sandboxes.GetOrCreate(ctx, "demo", zipbox.CreateOptions{Tier: "s"})
res, err := box.Exec(ctx, "echo hello")
fmt.Print(res.Stdout)

Nothing on a box stops on a clock, and no call has a default deadline: pass a context with a deadline when you want one.

Index

Constants

View Source
const DefaultBaseURL = "https://api.tribes.xyz"

DefaultBaseURL is the Zipbox control plane.

View Source
const MaxFileBytes = 250 * 1024 * 1024

MaxFileBytes is the largest file one read or write moves (250 MiB).

View Source
const Version = "0.1.6"

Version is the SDK version, sent in the User-Agent header.

View Source
const WorkspaceDir = "/root/workspace"

WorkspaceDir is where relative paths resolve and commands start by default.

Variables

View Source
var ErrPtyClosed = errors.New("zipbox: the terminal is closed")

ErrPtyClosed is returned by Pty methods after Close or Detach.

View Source
var ErrPtyTaken = errors.New("zipbox: the terminal session was taken over by another client")

ErrPtyTaken is returned by Pty.Read when another client took the session over.

Functions

func IsCode

func IsCode(err error, code ErrorCode) bool

IsCode reports whether err is a *Error with the given code.

func ResolvePath

func ResolvePath(p string) string

ResolvePath joins a relative path to WorkspaceDir; an absolute path is cleaned.

Types

type APIKey

type APIKey struct {
	ID         string     `json:"id"`
	Name       string     `json:"name"`
	Kind       string     `json:"kind"`
	Last4      string     `json:"last4"`
	CreatedAt  time.Time  `json:"createdAt"`
	LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
}

APIKey is an account API key as listed in Settings (never the secret).

type AccountService

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

AccountService reads account state. Reach it as Client.Account.

func (*AccountService) Balance

func (a *AccountService) Balance(ctx context.Context) (map[string]any, error)

Balance returns the credit balance and auto top-up state, as the dashboard reads them. The shape is not part of the stable contract.

func (*AccountService) Usage

func (a *AccountService) Usage(ctx context.Context) (map[string]any, error)

Usage returns recent metered usage, as the dashboard reads it.

func (*AccountService) WhoAmI

func (a *AccountService) WhoAmI(ctx context.Context) (*WhoAmI, error)

WhoAmI returns the account and key the client authenticates as.

type Box

type Box struct {
	// ID is the box id.
	ID string
	// Detail is the last box row this handle read, when it read one.
	Detail *SandboxDetail

	// Files reads and writes the box's filesystem.
	Files *FilesService
	// Commands manages commands started with ExecBackground.
	Commands *CommandsService
	// Pty opens interactive terminals on the box.
	Pty *PtyService
	// Preview publishes a local port at a public HTTPS URL.
	Preview *PreviewService
	// Tailscale joins the box to your own tailnet.
	Tailscale *TailscaleService
	// contains filtered or unexported fields
}

Box is a handle to one box. It is cheap to create (Client.Sandbox makes no call) and safe for concurrent use. The box token it needs is fetched on first use and cached by the client.

func (*Box) Command

func (b *Box) Command(id string) *Command

Command returns a handle to an existing command by id.

func (*Box) Delete added in v0.1.5

func (b *Box) Delete(ctx context.Context, opts DeleteOptions) error

Delete deletes the box (see SandboxesService.Delete).

func (*Box) Exec

func (b *Box) Exec(ctx context.Context, cmd string, opts ...ExecOption) (*ExecResult, error)

Exec runs cmd through `bash -lc` (so PATH, nvm, pyenv and the harness env are present) and waits for it to exit.

func (*Box) ExecArgv

func (b *Box) ExecArgv(ctx context.Context, argv []string, opts ...ExecOption) (*ExecResult, error)

ExecArgv spawns argv directly, without a shell, and waits for it to exit.

func (*Box) ExecBackground

func (b *Box) ExecBackground(ctx context.Context, cmd string, opts ...ExecOption) (*Command, error)

ExecBackground starts cmd through `bash -lc` and returns as soon as it is running. The command keeps running whether or not anyone is attached, and survives a restart of the box's agent. Follow it with Command.Wait or Command.Events.

func (*Box) ExecBackgroundArgv added in v0.1.5

func (b *Box) ExecBackgroundArgv(ctx context.Context, argv []string, opts ...ExecOption) (*Command, error)

ExecBackgroundArgv is ExecBackground for argv spawned directly, without a shell.

func (*Box) ExecStream

func (b *Box) ExecStream(ctx context.Context, cmd string, opts ...ExecOption) (*ExecStream, error)

ExecStream runs cmd through `bash -lc` and streams its events. The command is killed if the stream is closed before it exits; use ExecBackground for a command that must outlive the caller.

func (*Box) ExecStreamArgv added in v0.1.5

func (b *Box) ExecStreamArgv(ctx context.Context, argv []string, opts ...ExecOption) (*ExecStream, error)

ExecStreamArgv is ExecStream for argv spawned directly, without a shell.

func (*Box) Logs

func (b *Box) Logs(ctx context.Context, opts LogOptions) (string, error)

Logs returns the box's system journal (journalctl). Command output is its own log: see Commands.Events.

func (*Box) Refresh

func (b *Box) Refresh(ctx context.Context) (*SandboxDetail, error)

Refresh re-reads the box row.

func (*Box) Restart added in v0.1.5

func (b *Box) Restart(ctx context.Context) error

Restart hard-restarts the box. Files survive; running processes do not.

func (*Box) RunCode

func (b *Box) RunCode(ctx context.Context, lang Language, code string, opts ...ExecOption) (*ExecResult, error)

RunCode writes code to a temporary file on the box, runs it with python3, node (as an ES module) or bash through the login shell, then removes it. It is sugar over Files.Write and Exec.

func (*Box) SSHInfo

func (b *Box) SSHInfo(ctx context.Context) (*SSHInfo, error)

SSHInfo returns the box's SSH address and the command line that reaches it. Your public key must be on the box (Settings → SSH keys, or SSHPublicKey at create).

func (*Box) Screenshot

func (b *Box) Screenshot(ctx context.Context) ([]byte, error)

Screenshot returns a PNG of the box's desktop. The desktop must be running (open it from the dashboard or start the browser).

func (*Box) SetPrivate added in v0.1.5

func (b *Box) SetPrivate(ctx context.Context, enabled bool) error

SetPrivate turns private mode ("tailnet only") on or off. A private box closes every public way in: its URLs, previews, terminal, IDE, desktop and SSH answer only devices on your tailnet. Turning it on needs the box connected to a tailnet (tailnet_not_connected otherwise).

func (*Box) SetTier added in v0.1.5

func (b *Box) SetTier(ctx context.Context, tier string) error

SetTier moves the box to another tier. A running box restarts into it.

func (*Box) Start added in v0.1.5

func (b *Box) Start(ctx context.Context) error

Start starts the box if it is stopped (see SandboxesService.Start).

func (*Box) Stop added in v0.1.5

func (b *Box) Stop(ctx context.Context) error

Stop stops the box: its disk is archived and nothing is billed while stopped.

func (*Box) WaitReady added in v0.1.5

func (b *Box) WaitReady(ctx context.Context) (*SandboxDetail, error)

WaitReady re-reads the box with backoff until it is ready (see SandboxesService.WaitReady).

type Client

type Client struct {
	// Sandboxes creates, lists and manages boxes.
	Sandboxes *SandboxesService
	// Account reads the account's balance and usage.
	Account *AccountService
	// contains filtered or unexported fields
}

Client is a Zipbox API client. It is safe for concurrent use. Box tokens are fetched lazily per box and cached for the client's lifetime.

func New

func New(apiKey string, opts ...Option) *Client

New returns a client. An empty apiKey reads ZIPBOX_API_KEY.

func (*Client) Sandbox

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

Sandbox returns a handle to the box with this id. It makes no network call.

type Command

type Command struct {
	CommandRecord
	// contains filtered or unexported fields
}

Command is a handle to a command on a box.

func (*Command) CloseStdin

func (c *Command) CloseStdin(ctx context.Context) error

CloseStdin closes the command's stdin.

func (*Command) Events

func (c *Command) Events(ctx context.Context, since string) (*ExecStream, error)

Events streams the command's events after since ("" = from the start).

func (*Command) Get

func (c *Command) Get(ctx context.Context) (*CommandRecord, error)

Get re-reads the command's record.

func (*Command) Signal

func (c *Command) Signal(ctx context.Context, sig Signal) error

Signal sends sig to the command's process group.

func (*Command) Stdin

func (c *Command) Stdin(ctx context.Context, r io.Reader) error

Stdin appends r's bytes to the command's stdin (start it WithStdin).

func (*Command) Wait

func (c *Command) Wait(ctx context.Context) (*ExecResult, error)

Wait follows the command until it exits and returns everything it printed. A dropped stream is resumed from its cursor with backoff, without limit; only an answered error (not_found, unauthorized, …) or ctx ends the wait.

type CommandRecord

type CommandRecord struct {
	ID         string   `json:"id"`
	State      string   `json:"state"`
	Argv       []string `json:"argv"`
	Cwd        string   `json:"cwd"`
	Background bool     `json:"background"`
	// ExitCode is nil while the command runs.
	ExitCode    *int       `json:"exitCode,omitempty"`
	Signal      *string    `json:"signal,omitempty"`
	TimedOut    bool       `json:"timedOut"`
	StartedAt   time.Time  `json:"startedAt"`
	EndedAt     *time.Time `json:"endedAt,omitempty"`
	StdoutBytes int64      `json:"stdoutBytes"`
	StderrBytes int64      `json:"stderrBytes"`
}

CommandRecord is a command as the box reports it.

type CommandsService

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

CommandsService manages a box's commands. Reach it as Box.Commands.

func (*CommandsService) CloseStdin

func (s *CommandsService) CloseStdin(ctx context.Context, id string) error

CloseStdin closes a command's stdin.

func (*CommandsService) Events

func (s *CommandsService) Events(ctx context.Context, id, since string) (*ExecStream, error)

Events replays a command's events after since ("" = from the start) and follows it until it exits, re-attaching from the last cursor whenever the stream drops (see ExecStream). An answered error on the first attach is returned here.

func (*CommandsService) Get

Get returns one command's record.

func (*CommandsService) List

List returns running and recently finished commands.

func (*CommandsService) Signal

func (s *CommandsService) Signal(ctx context.Context, id string, sig Signal) error

Signal sends sig to a command's process group.

func (*CommandsService) Stdin

func (s *CommandsService) Stdin(ctx context.Context, id string, r io.Reader) error

Stdin appends r's bytes to a command's stdin.

type CreateOptions

type CreateOptions struct {
	// Name is the box's permanent subdomain. Empty = the account's default box.
	Name string
	// Tier is the machine size (xs, s, m, l, xl, xxl). Empty = the default tier.
	Tier string
	// SSHPublicKey is an OpenSSH public key line authorized on the box.
	SSHPublicKey string
	// Mailbox creates the box's mailbox now. False = created the first time the box uses mail.
	Mailbox bool
	// Private starts the box in private mode ("tailnet only"): it is never public.
	// A private box is not ready until it joins your tailnet, so Create returns
	// once it is running with its key; then call Box.Tailscale.Connect.
	Private bool
}

CreateOptions configures a new box. GetOrCreate takes the same options and applies them only when it creates the box.

type DeleteOptions added in v0.1.5

type DeleteOptions struct {
	// Archive keeps a recoverable copy for 30 days. Nil = the server default (true).
	Archive *bool
}

DeleteOptions configures Delete.

type Error

type Error struct {
	// Code is the public error code.
	Code ErrorCode `json:"code"`
	// Status is the HTTP status, or 0 when the error did not come from a response.
	Status int `json:"status,omitempty"`
	// Message is a human-readable description.
	Message string `json:"message"`
	// RequestID identifies the request in Zipbox's logs, when the server sent one.
	RequestID string `json:"requestId,omitempty"`
	// Retryable reports whether the same request may succeed if sent again later.
	Retryable bool `json:"retryable"`
	// RetryAfter is how long the server asked the caller to wait, when it said.
	RetryAfter time.Duration `json:"-"`
	// DocsURL points at the docs entry for Code.
	DocsURL string `json:"docsUrl"`
	// contains filtered or unexported fields
}

Error is the single error type every SDK call returns for a failure the control plane or a box reported (and for a box that is not ready). Use errors.As to inspect it:

var zerr *zipbox.Error
if errors.As(err, &zerr) && zerr.Code == zipbox.CodeNotFound { … }

A command that exits non-zero is a result, never an Error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type ErrorCode

type ErrorCode string

ErrorCode is the public error code carried by every Zipbox error. The code is the contract; the message is for humans and may change.

const (
	CodeInvalidRequest      ErrorCode = "invalid_request"
	CodeUnauthorized        ErrorCode = "unauthorized"
	CodeForbidden           ErrorCode = "forbidden"
	CodeNotFound            ErrorCode = "not_found"
	CodeInsufficientCredits ErrorCode = "insufficient_credits"
	CodeConflict            ErrorCode = "conflict"
	CodeRateLimited         ErrorCode = "rate_limited"
	CodeBoxNotRunning       ErrorCode = "box_not_running"
	CodeUnavailable         ErrorCode = "unavailable"
	// CodeMachineLimitReached: the account holds 250 machine names (a deleted box
	// keeps its name); reuse one instead of creating a new one. Never retried. See
	// https://zipbox.ai/docs/machine-limit.
	CodeMachineLimitReached ErrorCode = "machine_limit_reached"
	// CodeBoxKeyChanged: the box's key changed between reading it and sending a
	// sealed credential (a claim re-mints it). Tailscale.Connect re-seals once.
	CodeBoxKeyChanged ErrorCode = "box_key_changed"
	// CodeTailnetNotConnected: private mode needs the box on a tailnet first.
	CodeTailnetNotConnected ErrorCode = "tailnet_not_connected"
	// CodeTailscaleUnavailableEgressLockdown: company egress lockdown blocks Tailscale on this box.
	CodeTailscaleUnavailableEgressLockdown ErrorCode = "tailscale_unavailable_egress_lockdown"
	// CodeTailscaleRequiresUpdate: the box's ZipOS predates Tailscale; accept the ZipOS update first.
	CodeTailscaleRequiresUpdate ErrorCode = "tailscale_requires_update"
	// CodeBoxPrivateUnreachable: the box is private and this device is not on its tailnet.
	CodeBoxPrivateUnreachable ErrorCode = "box_private_unreachable"
)

The public error codes. See https://zipbox.ai/docs/errors for causes and fixes.

type ExecEvent

type ExecEvent struct {
	Type ExecEventType `json:"type"`
	// Cursor resumes the stream after this event (Commands.Events since).
	Cursor string `json:"cursor"`
	// ID is set on start.
	ID string `json:"id,omitempty"`
	// Data is set on stdout and stderr.
	Data string `json:"data,omitempty"`
	// Stream and Message are set on gap: output past the 64 MiB per-stream cap
	// was discarded (the process keeps running).
	Stream  string `json:"stream,omitempty"`
	Message string `json:"message,omitempty"`
	// State, ExitCode, Signal and TimedOut are set on exit.
	State    string  `json:"state,omitempty"`
	ExitCode *int    `json:"exitCode,omitempty"`
	Signal   *string `json:"signal,omitempty"`
	TimedOut bool    `json:"timedOut,omitempty"`
}

ExecEvent is one event on a command's stream. Which fields are set depends on Type.

type ExecEventType

type ExecEventType string

ExecEventType is the kind of an ExecEvent.

const (
	EventStart  ExecEventType = "start"
	EventStdout ExecEventType = "stdout"
	EventStderr ExecEventType = "stderr"
	EventGap    ExecEventType = "gap"
	EventExit   ExecEventType = "exit"
)

Event types on a command's stream.

type ExecOption

type ExecOption func(*execRequest)

ExecOption configures a command.

func WithCwd

func WithCwd(dir string) ExecOption

WithCwd sets the working directory: absolute, or relative to /root/workspace (the default).

func WithEnv

func WithEnv(env map[string]string) ExecOption

WithEnv adds environment variables on top of the box's own.

func WithStdin

func WithStdin() ExecOption

WithStdin opens a stdin pipe fed by Command.Stdin. Default: /dev/null.

func WithTimeout

func WithTimeout(d time.Duration) ExecOption

WithTimeout asks the box to kill the command after d. Without it a command runs until it exits or is signalled.

func WithUser

func WithUser(user string) ExecOption

WithUser runs the command as another local user. Default: the box user (root).

type ExecResult

type ExecResult struct {
	// ID is the command id on the box.
	ID string `json:"id"`
	// ExitCode is shell-style: 0..255, 128+N when killed by signal N, -1 when
	// the box lost track of the process (state "unknown").
	ExitCode int `json:"exitCode"`
	// Stdout and Stderr are the command's output, decoded as UTF-8.
	Stdout string `json:"stdout"`
	Stderr string `json:"stderr"`
	// Signal is the signal the box delivered (a Signal call or a timeout), if any.
	Signal *string `json:"signal,omitempty"`
	// TimedOut is true when WithTimeout ended the command.
	TimedOut bool `json:"timedOut"`
}

ExecResult is a finished command. A non-zero ExitCode is a result, not an error.

type ExecStream

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

ExecStream reads a command's events. Use it like bufio.Scanner and always Close it:

for stream.Next() { ev := stream.Event() … }
if err := stream.Err(); err != nil { … }

A stream that drops once its command has started re-attaches from the last cursor by itself: a followed command is a live surface, so there is no attempt ceiling, the backoff is capped and jittered (WithBackoff), and the ladder resets only when an event arrives. Only an answered error, ctx or Close ends it.

func (*ExecStream) Close

func (s *ExecStream) Close() error

Close releases the stream and stops it re-attaching; a Next in flight returns false. Closing the stream of a foreground Exec before it exits makes the box kill the command.

func (*ExecStream) Cursor

func (s *ExecStream) Cursor() string

Cursor is the resume cursor after the last event read.

func (*ExecStream) Err

func (s *ExecStream) Err() error

Err returns the error that stopped the stream, or nil after a clean exit event.

func (*ExecStream) Event

func (s *ExecStream) Event() ExecEvent

Event returns the current event.

func (*ExecStream) Next

func (s *ExecStream) Next() bool

Next advances to the next event. It returns false after the exit event, or on an error that ends the stream (see Err).

type FileEntry

type FileEntry struct {
	Name         string   `json:"name"`
	Kind         FileKind `json:"kind"`
	SizeBytes    int64    `json:"sizeBytes"`
	ModifiedAtMs int64    `json:"modifiedAtMs"`
}

FileEntry is one directory entry.

func (FileEntry) ModifiedAt

func (e FileEntry) ModifiedAt() time.Time

ModifiedAt is the entry's modification time.

type FileKind

type FileKind string

FileKind is the type of a directory entry.

const (
	KindDirectory FileKind = "directory"
	KindFile      FileKind = "file"
	KindSymlink   FileKind = "symlink"
	KindOther     FileKind = "other"
)

Directory entry kinds.

type FilesService

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

FilesService reads and writes a box's filesystem. Reach it as Box.Files. Paths are absolute, or relative to /root/workspace.

func (*FilesService) Copy

func (s *FilesService) Copy(ctx context.Context, src, dst string) error

Copy copies src to dst.

func (*FilesService) Delete

func (s *FilesService) Delete(ctx context.Context, p string) error

Delete deletes a file or directory.

func (*FilesService) Download

func (s *FilesService) Download(ctx context.Context, remotePath, localPath string) error

Download copies a file from the box to localPath, replacing it.

func (*FilesService) List

func (s *FilesService) List(ctx context.Context, p string) ([]FileEntry, error)

List returns a directory's entries.

func (*FilesService) Mkdir

func (s *FilesService) Mkdir(ctx context.Context, p string) error

Mkdir creates a directory.

func (*FilesService) Move

func (s *FilesService) Move(ctx context.Context, src, dst string) error

Move moves or renames src to dst.

func (*FilesService) Read

func (s *FilesService) Read(ctx context.Context, p string) ([]byte, error)

Read returns a file's bytes.

func (*FilesService) ReadTo

func (s *FilesService) ReadTo(ctx context.Context, p string, w io.Writer) (int64, error)

ReadTo streams a file into w and returns the bytes copied.

func (*FilesService) Stat

func (s *FilesService) Stat(ctx context.Context, p string) (*FileEntry, error)

Stat returns one entry, read from its parent directory's listing.

func (*FilesService) Upload

func (s *FilesService) Upload(ctx context.Context, localPath, remotePath string) error

Upload copies a local file to the box.

func (*FilesService) Write

func (s *FilesService) Write(ctx context.Context, p string, content io.Reader) error

Write writes content to a file atomically, replacing it. The parent directory must exist (see Mkdir).

type Language

type Language string

Language is a RunCode language.

const (
	Python Language = "python"
	Node   Language = "node"
	Bash   Language = "bash"
)

RunCode languages.

type LogOptions

type LogOptions struct {
	// Since is a journalctl time ("1 hour ago", "2026-10-19 10:00"). Empty = all.
	Since string
	// Lines limits output to the last N lines. 0 = no limit.
	Lines int
	// Unit restricts to one systemd unit.
	Unit string
}

LogOptions filters Logs.

type MachineSize

type MachineSize struct {
	VCPUs  int `json:"vcpus"`
	MemMiB int `json:"memMib"`
	DiskGB int `json:"diskGb"`
}

MachineSize is the resolved size a box runs at.

type Option

type Option func(*Client)

Option configures a Client.

func WithBackoff

func WithBackoff(base, max time.Duration) Option

WithBackoff sets the exponential backoff used between retries and command stream reconnects: the first delay and the cap. Default 500ms and 30s.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the control plane URL (default ZIPBOX_API_URL or DefaultBaseURL).

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets the HTTP client. The default has no timeout.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how many times a retryable failure (rate_limited, unavailable) of a GET or a create is retried. Default 3.

func WithPollInterval

func WithPollInterval(min, max time.Duration) Option

WithPollInterval sets how often Create re-reads a box while it boots: the first delay and the cap. Default 1s and 10s.

func WithPtyBackoff added in v0.1.5

func WithPtyBackoff(base, max time.Duration) Option

WithPtyBackoff sets the backoff between PTY reconnects: the first delay and the cap. Default 500ms and 30s. There is no attempt ceiling.

type Preview

type Preview struct {
	// URL is the HTTPS address, e.g. https://web.demo.zbox.sh.
	URL string `json:"url"`
	// Label is the subdomain label.
	Label string `json:"label"`
	// Host is the full hostname.
	Host string `json:"host"`
}

Preview is a published port.

type PreviewService

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

PreviewService publishes ports on a box. Reach it as Box.Preview.

func (*PreviewService) Create

func (s *PreviewService) Create(ctx context.Context, port int, label string) (*Preview, error)

Create publishes 127.0.0.1:port on the box at https://<label>.<box host>. An empty label is "p<port>". On a public box anyone with the URL can reach the port; on a private box, only devices on the owner's tailnet.

func (*PreviewService) Remove

func (s *PreviewService) Remove(ctx context.Context, label string) error

Remove unpublishes a preview by its label (or full host).

type Pty

type Pty struct {
	// SessionID names the session on the box (bash-<uuid>).
	SessionID string
	// ClientID identifies this client to the box; it is reused on reconnect.
	ClientID string
	// contains filtered or unexported fields
}

Pty is an attached terminal. Read returns the session's output (io.EOF once the shell exits); Write sends keystrokes. A dropped connection reconnects by itself with exponential backoff and no attempt limit; Write waits for it.

func (*Pty) Close

func (p *Pty) Close() error

Close kills the session on the box and closes the connection.

func (*Pty) Detach

func (p *Pty) Detach() error

Detach closes this connection and leaves the session running on the box.

func (*Pty) ExitCode

func (p *Pty) ExitCode() *int

ExitCode is the shell's exit status once it has exited, else nil.

func (*Pty) Read

func (p *Pty) Read(b []byte) (int, error)

Read reads terminal output. It returns io.EOF after the shell exits.

func (*Pty) Resize

func (p *Pty) Resize(cols, rows int) error

Resize sets the terminal size; it is re-applied after every reconnect.

func (*Pty) Takeover added in v0.1.5

func (p *Pty) Takeover() error

Takeover takes the session over from another client attached to it.

func (*Pty) Write

func (p *Pty) Write(b []byte) (int, error)

Write sends input. While the socket is reconnecting it waits.

type PtyOptions

type PtyOptions struct {
	// Cols and Rows are the initial size. Zero leaves the box's default.
	Cols, Rows int
	// ClientLabel names this client in the box's session list. Default "zipbox-sdk".
	ClientLabel string
}

PtyOptions configures a terminal.

type PtyService

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

PtyService opens terminals on a box. Reach it as Box.Pty.

func (*PtyService) Attach

func (s *PtyService) Attach(ctx context.Context, sessionID string, opts PtyOptions) (*Pty, error)

Attach re-joins an existing session by id; the box replays its screen.

func (*PtyService) Create

func (s *PtyService) Create(ctx context.Context, opts PtyOptions) (*Pty, error)

Create opens a new shell session (bash) and attaches to it. The session outlives the connection: Detach leaves it running and Attach re-joins it.

type SSHInfo

type SSHInfo struct {
	Host    string `json:"host"`
	User    string `json:"user"`
	Command string `json:"command"`
}

SSHInfo is how to reach a box over SSH (IPv6).

type Sandbox

type Sandbox struct {
	ID          string       `json:"id"`
	Name        *string      `json:"name,omitempty"`
	Domain      *string      `json:"domain,omitempty"`
	IPv6        *string      `json:"ipv6,omitempty"`
	Status      Status       `json:"status"`
	Tier        *string      `json:"tier,omitempty"`
	PendingTier *string      `json:"pendingTier,omitempty"`
	MachineSize *MachineSize `json:"machineSize,omitempty"`
	// IsArchived is true when the disk is archived (a stopped box) or an archive is in flight.
	IsArchived     *bool      `json:"isArchived,omitempty"`
	CPUPct         *float64   `json:"cpuPct,omitempty"`
	MemPct         *float64   `json:"memPct,omitempty"`
	DiskPct        *float64   `json:"diskPct,omitempty"`
	NetRxBps       *float64   `json:"netRxBps,omitempty"`
	NetTxBps       *float64   `json:"netTxBps,omitempty"`
	StatsUpdatedAt *time.Time `json:"statsUpdatedAt,omitempty"`
	StartFailedAt  *time.Time `json:"startFailedAt,omitempty"`
	ClaimedAt      *time.Time `json:"claimedAt,omitempty"`
	// PrivateMode is true when the box answers only devices on your tailnet.
	PrivateMode bool `json:"privateMode"`
	// Tailscale is the box's tailnet status; nil when it never joined one.
	Tailscale *TailscaleStatus `json:"tailscale,omitempty"`
	// TailscaleSupported is false when the box's ZipOS predates Tailscale
	// (Tailscale.Connect fails with CodeTailscaleRequiresUpdate until the ZipOS
	// update is accepted); nil until the box has reported since it booted.
	TailscaleSupported *bool `json:"tailscaleSupported,omitempty"`
	// AgentPublicKey is the box's own P-256 key (base64 SPKI DER) that box
	// credentials are sealed to. Nil until the box has started; a claim re-mints it.
	AgentPublicKey *string   `json:"agentPublicKey,omitempty"`
	CreatedAt      time.Time `json:"createdAt"`
	UpdatedAt      time.Time `json:"updatedAt"`
}

Sandbox is the documented subset of a box row.

type SandboxDetail

type SandboxDetail struct {
	Sandbox
	// Ready is true once the box is running and serving its owner.
	Ready bool `json:"ready"`
	// HTTPSReady is true once BaseURL completes a TLS handshake with a trusted
	// certificate. A fresh name's certificate can trail Ready; the SDK's box calls
	// retry the handshake meanwhile.
	HTTPSReady bool `json:"httpsReady"`
	// BaseURL is the box's HTTPS origin once Ready.
	BaseURL *string `json:"baseUrl,omitempty"`
	// BoxToken is the per-key, per-box bearer the box accepts. The SDK manages
	// it; it is exposed for curl and debugging.
	BoxToken *string `json:"boxToken,omitempty"`
}

SandboxDetail is one box as GET /sandbox/{id} returns it.

func (SandboxDetail) MarshalJSON

func (d SandboxDetail) MarshalJSON() ([]byte, error)

MarshalJSON leaves BoxToken out: it is a credential, and a detail printed or logged as JSON (the CLI's --json) must never carry it.

type SandboxesService

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

SandboxesService manages boxes. Reach it as Client.Sandboxes.

func (*SandboxesService) Create

func (s *SandboxesService) Create(ctx context.Context, opts CreateOptions) (*Box, error)

Create creates a box and waits until it is ready, re-reading it with backoff. The wait has no deadline of its own; bound it with ctx. The request carries an Idempotency-Key, so a retried create never makes two boxes. With Private set it waits until the box is running with its key instead.

func (*SandboxesService) Delete

func (s *SandboxesService) Delete(ctx context.Context, id string, opts DeleteOptions) error

Delete deletes a box. A recoverable copy is kept for 30 days unless opts.Archive is false.

func (*SandboxesService) Get

Get returns one box with its readiness and HTTPS origin.

func (*SandboxesService) GetOrCreate

func (s *SandboxesService) GetOrCreate(ctx context.Context, name string, opts CreateOptions) (*Box, error)

GetOrCreate returns the live box with this name, starting it if it is stopped, or creates it with opts. It waits until the box is ready; a private box that has not joined a tailnet yet is returned once it is running with its key. opts.Name must be empty or name (CodeInvalidRequest otherwise).

The options apply only when a box is created. A box that already has this name is returned as it is, even when it differs (another tier, not private): that is not an error and nothing is resized. Check Box.Detail.Tier and call SetTier if it matters.

func (*SandboxesService) List

func (s *SandboxesService) List(ctx context.Context) ([]Sandbox, error)

List returns the account's boxes.

func (*SandboxesService) Restart

func (s *SandboxesService) Restart(ctx context.Context, id string) error

Restart hard-restarts a running box. Files survive; running processes do not.

func (*SandboxesService) SetTier

func (s *SandboxesService) SetTier(ctx context.Context, id, tier string) error

SetTier moves a box to another tier. A running box restarts into it.

func (*SandboxesService) Start

func (s *SandboxesService) Start(ctx context.Context, id string) error

Start starts a stopped box. Credit-gated: insufficient_credits when dry.

A stop is accepted at once but its disk takes seconds to minutes to land; meanwhile the box reads StatusStopping and the restore answers conflict. Start waits that out with backoff and starts the box once it reads StatusArchived. A box that comes out of the wait already starting or running (a resize restores itself, a failed archive leaves it running) is started. Any other conflict is returned as it came.

func (*SandboxesService) Stop

func (s *SandboxesService) Stop(ctx context.Context, id string) error

Stop stops a box: its disk is archived and nothing is billed while stopped.

func (*SandboxesService) WaitReady

func (s *SandboxesService) WaitReady(ctx context.Context, id string) (*Box, error)

WaitReady re-reads a box with backoff until it is ready, and returns its handle. The wait has no deadline of its own; bound it with ctx. A private box that has not joined a tailnet yet is returned once it is running with its key.

type Signal

type Signal string

Signal names a command can be sent.

const (
	SIGTERM Signal = "TERM"
	SIGKILL Signal = "KILL"
	SIGINT  Signal = "INT"
	SIGHUP  Signal = "HUP"
	SIGQUIT Signal = "QUIT"
)

Signals.

type Status

type Status string

Status is a box's lifecycle state.

const (
	StatusProvisioning Status = "provisioning"
	StatusRunning      Status = "running"
	StatusStopping     Status = "stopping"
	StatusStopped      Status = "stopped"
	StatusArchived     Status = "archived"
	StatusDeleting     Status = "deleting" // signing out of its tailnet before it is destroyed
	StatusDestroyed    Status = "destroyed"
)

Box lifecycle states.

type TailscalePeer added in v0.1.5

type TailscalePeer struct {
	// Name is the device's own name, e.g. "lucys-macbook".
	Name string `json:"name"`
	// DNSName is its MagicDNS name.
	DNSName *string `json:"dnsName,omitempty"`
	// OS is "macOS", "linux", "iOS", "windows", "android", …
	OS *string `json:"os,omitempty"`
	// Online is true while the device is connected to Tailscale.
	Online bool `json:"online"`
	// IPv4 is its tailnet IPv4 (100.x).
	IPv4 *string `json:"ipv4,omitempty"`
	// Connection is "direct" (peer to peer), "relay" (through a Tailscale DERP
	// relay), or nil (no recent traffic). Kept as a string so a later value never
	// breaks decoding.
	Connection *string `json:"connection,omitempty"`
}

TailscalePeer is one of your other devices on the tailnet, as the box sees it.

type TailscaleService added in v0.1.5

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

TailscaleService joins a box to your own tailnet. Reach it as Box.Tailscale.

The auth key is sealed on this machine to the box's own key and only the box can open it: Zipbox relays it once and never stores or logs it.

func (*TailscaleService) Connect added in v0.1.5

func (t *TailscaleService) Connect(ctx context.Context, authKey string) error

Connect joins the box to the tailnet the auth key belongs to. Use a one-off, pre-approved key. The box must be running. Connect returns once the key is on its way; read Status for the join itself.

The box key is read right before sealing, because claiming a box re-mints it. If the key changed between the read and the send (box_key_changed), Connect reads it again and re-seals once.

func (*TailscaleService) Disconnect added in v0.1.5

func (t *TailscaleService) Disconnect(ctx context.Context) error

Disconnect leaves the tailnet: the box signs out and its Tailscale state is wiped. A private box is made public first, in the same call, so it is never left private with no way in.

func (*TailscaleService) Status added in v0.1.5

Status returns the box's tailnet status, or nil when it never joined one and no key is pending.

type TailscaleState added in v0.1.5

type TailscaleState string

TailscaleState is a box's tailnet state as the box reports it.

const (
	// TailscaleJoining: the auth key was accepted and the node is coming up.
	TailscaleJoining TailscaleState = "joining"
	// TailscaleConnected: the box is on the tailnet.
	TailscaleConnected TailscaleState = "connected"
	// TailscaleNeedsApproval: a tailnet admin must approve the device.
	TailscaleNeedsApproval TailscaleState = "needsApproval"
	// TailscaleNeedsLogin: the node key expired or the auth key was refused. Connect again with a new key.
	TailscaleNeedsLogin TailscaleState = "needsLogin"
	// TailscaleStopped: logged in but turned off.
	TailscaleStopped TailscaleState = "stopped"
	// TailscaleFailed: the box's Tailscale daemon does not answer.
	TailscaleFailed TailscaleState = "failed"
)

Tailnet states.

type TailscaleStatus added in v0.1.5

type TailscaleStatus struct {
	// State is nil when only the last known identity is known (the box is stopped).
	State *TailscaleState `json:"state,omitempty"`
	// Tailnet is the tailnet's name, e.g. "example.com".
	Tailnet *string `json:"tailnet,omitempty"`
	// IPv4 and IPv6 are the box's tailnet addresses.
	IPv4 *string `json:"ipv4,omitempty"`
	IPv6 *string `json:"ipv6,omitempty"`
	// DNSName is the box's MagicDNS name.
	DNSName *string `json:"dnsName,omitempty"`
	// KeyExpiry is when the node key expires; nil when key expiry is off.
	KeyExpiry *time.Time `json:"keyExpiry,omitempty"`
	// Pending is true while an auth key is on its way to the box. Pending going
	// false with no state change means the key never arrived: connect again.
	Pending bool `json:"pending"`
	// Peers are your other devices on the tailnet (online first, at most 50); nil
	// while the box is not reporting.
	Peers []TailscalePeer `json:"peers,omitempty"`
}

TailscaleStatus is a box's tailnet status: the live state merged with the last known identity.

type WhoAmI

type WhoAmI struct {
	UserID string  `json:"userId"`
	APIKey *APIKey `json:"apiKey,omitempty"`
}

WhoAmI is the identity behind the client's credential.

Directories

Path Synopsis
cmd
zipbox command
Command zipbox drives Zipbox boxes from a terminal or CI: create and manage boxes, run commands, move files, open a shell, publish ports, read docs, and serve the Zipbox MCP tools over stdio.
Command zipbox drives Zipbox boxes from a terminal or CI: create and manage boxes, run commands, move files, open a shell, publish ports, read docs, and serve the Zipbox MCP tools over stdio.
internal
cli
Package cli implements the zipbox command.
Package cli implements the zipbox command.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL