Skip to content

API Reference

Go Reference

Package github.com/sandboxing-dev/chainguard-sandbox-sdk/go/sandbox. Generated with go doc -all from the package source.

package sandbox // import "github.com/sandboxing-dev/chainguard-sandbox-sdk/go/sandbox"
Package sandbox is a simple sandbox API on Chainguard Workspaces, shaped like
the Vercel Sandbox, E2B and Modal Sandbox SDKs: create a sandbox, run commands
in it, move files in and out, and delete it.
sb, err := sandbox.Create(ctx, &sandbox.CreateOptions{Packages: []string{"python-3.13"}})
if err != nil { ... }
defer sb.Kill(context.Background())
res, err := sb.Commands.Run(ctx, "python3 -c 'print(2+2)'", nil)
fmt.Print(res.Stdout) // 4
_, err = sb.Files.Write(ctx, "data/input.txt", []byte("hello"))
A sandbox is a Workspaces session created from an empty workspace: the
package creates the session with an environment document (your package list),
waits for the guest, and completes the required first upload with an empty tree.
It is built on package workspaces; see the sandbox docs for how it maps to the
Sessions API and what differs from other sandbox services (no exposed ports,
one command at a time per sandbox, and more).
CONSTANTS
const DefaultCommandTimeout = 60 * time.Second
DefaultCommandTimeout bounds a foreground command when RunOptions.Timeout is
zero. A negative Timeout means no limit.
const DefaultWorkdir = "/work"
DefaultWorkdir is where commands run and relative paths resolve.
VARIABLES
var DefaultPackages = []string{"bash", "coreutils", "curl", "git", "jq", "python-3.13", "nodejs-22"}
DefaultPackages is the toolchain a sandbox gets when CreateOptions.Packages
is nil: a shell, the core tools, git, curl, jq, Python and Node.js.
Package names are Chainguard (Wolfi) package names, e.g. "python-3.12",
"go", "nodejs-22", "bun". busybox, git, curl, bash and a few more are always
installed.
var ErrBusy = errors.New("sandbox: busy: another client is attached to this sandbox (an interactive shell); commands run once it detaches")
ErrBusy: the sandbox is held by another controller, typically an interactive
shell attached with chainctl or the attach API. Commands can't run until it
detaches.
var ErrLimitReached = errors.New("sandbox: session limit reached (one sandbox per user during the Workspaces beta); kill an existing sandbox first")
ErrLimitReached: the organization is at its session limit (the beta allows
one sandbox per user and three per organization). Kill a sandbox first.
var ErrNotEnabled = errors.New("sandbox: Workspaces is not turned on for this organization; an owner can turn it on with sandbox.Enable or `chainguard-sandbox enable`")
ErrNotEnabled: Workspaces is not turned on for the organization. An owner
can turn it on with Enable (or `chainguard-sandbox enable`).
var ErrOutcomeUnknown = errors.New("sandbox: the command's outcome is unknown (the connection ended before it reported an exit status)")
ErrOutcomeUnknown: the connection ended, or failed, before the command
reported an exit status. It may or may not have run, in part or in full.
When a transport error cut it short, that error is wrapped too, so
status.Code(err) still reports its gRPC code.
FUNCTIONS
func Document(o *CreateOptions) []byte
Document returns the environment document Create would send for o.
func Kill(ctx context.Context, id string, o *ConnectOptions) (bool, error)
Kill deletes the sandbox with the given ID (short ID, display name or
resource name). It returns false if there was none. Unlike Connect it does
not attach to the sandbox first, so it also deletes one that never started
or cannot be attached to. Errors as for Sandbox.Kill.
TYPES
type CommandExitError struct {
CommandResult
}
CommandExitError is returned by Commands.Run and CommandHandle.Wait when the
command exits with a non-zero code. It carries the full result.
func (e *CommandExitError) Error() string
type CommandHandle struct {
// PID of the command's process group leader in the sandbox.
PID int
// ID names the command's state directory.
ID string
// Has unexported fields.
}
CommandHandle is a background command.
func (h *CommandHandle) ExitCode() *int
ExitCode returns the exit code once known (after Wait or a Poll that saw the
exit).
func (h *CommandHandle) Kill(ctx context.Context) (bool, error)
Kill sends SIGKILL to the command's process group. It returns false if the
command had already exited. The exit code becomes 137.
func (h *CommandHandle) Poll(ctx context.Context) (*int, error)
Poll fetches new output and returns the exit code, or nil while the command
runs.
func (h *CommandHandle) Stderr() string
Stderr returns the standard error received so far.
func (h *CommandHandle) Stdout() string
Stdout returns the standard output received so far.
func (h *CommandHandle) Wait(ctx context.Context, o *WaitOptions) (*CommandResult, error)
Wait waits for the command to exit, delivering output to the callbacks as it
arrives. A non-zero exit returns a *CommandExitError with the result.
type CommandResult struct {
ExitCode int
Stdout string
Stderr string
}
CommandResult is a finished command's output and exit code.
type Commands struct {
// Has unexported fields.
}
Commands runs commands in a sandbox: sb.Commands.
func (c *Commands) Connect(ctx context.Context, pid int) (*CommandHandle, error)
Connect returns a handle to a background command by pid.
func (c *Commands) Kill(ctx context.Context, pid int) (bool, error)
Kill sends SIGKILL to a background command (and its process group).
It returns false if the command had already exited.
func (c *Commands) List(ctx context.Context) ([]ProcessInfo, error)
List returns the background commands started in this sandbox (running and
finished).
func (c *Commands) Run(ctx context.Context, cmd string, o *RunOptions) (*CommandResult, error)
Run runs cmd with bash (a login shell, so shell syntax works) and waits
for it. A non-zero exit returns a *CommandExitError holding the result;
a timeout returns a *TimeoutError.
func (c *Commands) RunArgs(ctx context.Context, argv []string, o *RunOptions) (*CommandResult, error)
RunArgs runs argv directly, without a shell (like Vercel's runCommand and
Modal's exec). Errors as for Run.
func (c *Commands) Start(ctx context.Context, cmd string, o *StartOptions) (*CommandHandle, error)
Start runs cmd with bash in the background and returns at once. The command
keeps running after this call (and across a pause); its output goes to files
in the sandbox, read with the returned handle.
func (c *Commands) StartArgs(ctx context.Context, argv []string, o *StartOptions) (*CommandHandle, error)
StartArgs is Start without a shell.
type ConnectOptions struct {
// Envs for every command on the returned Sandbox (not stored remotely).
Envs map[string]string
Client *workspaces.Client
Instance string
}
ConnectOptions configures Connect, List and the package-level Kill.
type CreateOptions struct {
// Packages installed in the sandbox (Chainguard package names). Nil means
// DefaultPackages. They are resolved when the sandbox is created; an
// unknown package fails Create.
Packages []string
// Envs are environment variables for every command (per-command Envs
// override them). They are kept client-side, in this Sandbox value.
Envs map[string]string
// Name labels the sandbox. Its display name becomes "<name>/<word-word>".
// Defaults to "sandbox".
Name string
// Egress is the outbound allowlist (hostnames; "*" allows all). Nil means
// ["*"]. The platform always blocks cloud metadata, loopback and private
// ranges. Enforcement of narrower allowlists is the plane's (not verified
// by this package).
Egress []string
// EgressPolicy is what happens to a connection outside Egress: "deny"
// (refuse it; the default) or "destroy" (tear the sandbox down).
EgressPolicy string
// Document replaces the generated environment document entirely (a
// .chainguard/ci.yaml-style document). Packages, Egress and EgressPolicy
// are then ignored.
Document []byte
// Source starts from a GitHub repository instead of an empty tree.
Source *GitSource
// StartTimeout bounds waiting for the guest to start (default 3 minutes).
StartTimeout time.Duration
// Client is the Workspaces client to use. Nil creates one with the
// default login and the organization from Instance.
Client *workspaces.Client
// Instance is the organization ID (used when Client is nil). If empty,
// $CHAINCTL_SANDBOX_INSTANCE is used; if that's empty too, the
// organization is auto-detected when you belong to exactly one (turn off
// with $CHAINGUARD_SANDBOX_NO_DETECT_INSTANCE=1). List IDs with ListOrganizations,
// `chainguard-sandbox orgs` or `chainctl iam organizations list`.
Instance string
}
CreateOptions configures Create. The zero value (or nil) is a sandbox with
DefaultPackages and open egress.
type EntryInfo struct {
Name string
Path string
Type FileType
Size int64
Mode fs.FileMode // permission bits
Permissions string // e.g. "rwxr-xr-x"
Owner, Group string
ModifiedTime time.Time
SymlinkTarget string
}
EntryInfo describes a file, directory or symlink.
type FileType string
FileType is "file", "dir" or "symlink".
const (
FileTypeFile FileType = "file"
FileTypeDir FileType = "dir"
FileTypeSymlink FileType = "symlink"
)
type Files struct {
// Has unexported fields.
}
Files reads and writes a sandbox's filesystem: sb.Files. Relative paths
resolve against /work. Every call is a small shell program run in the
sandbox, so each costs one round trip (about 0.15 s once the sandbox is
warm); batch with WriteFiles and UploadDir where you can.
func (f *Files) Download(ctx context.Context, remotePath, localPath string) error
Download copies a file from the sandbox to localPath, creating local parent
directories.
func (f *Files) DownloadDir(ctx context.Context, remoteDir, localDir string) error
DownloadDir copies a directory tree from the sandbox into localDir (created
if missing). Nothing is written outside localDir: absolute names and ".."
are refused, an entry is never written through a symbolic link, and a link
that leads outside localDir (directly or through other links) is removed and
reported as an error.
func (f *Files) Exists(ctx context.Context, p string) (bool, error)
Exists reports whether a path exists (a dangling symlink counts).
func (f *Files) GetInfo(ctx context.Context, p string) (*EntryInfo, error)
GetInfo describes a path without following a final symlink.
func (f *Files) List(ctx context.Context, p string) ([]EntryInfo, error)
List returns the entries of a directory (one level), sorted by name.
func (f *Files) MakeDir(ctx context.Context, p string) (bool, error)
MakeDir creates a directory and its parents. It returns false if the
directory already existed.
func (f *Files) Read(ctx context.Context, p string) ([]byte, error)
Read returns a file's contents. A missing file returns a *NotFoundError.
func (f *Files) ReadText(ctx context.Context, p string) (string, error)
ReadText returns a file's contents as a string.
func (f *Files) Remove(ctx context.Context, p string) error
Remove deletes a file or a directory tree. A missing path returns a
*NotFoundError.
func (f *Files) Rename(ctx context.Context, oldPath, newPath string) (*EntryInfo, error)
Rename moves a file or directory, creating the destination's parents,
and describes it at its new path.
func (f *Files) Upload(ctx context.Context, localPath, remotePath string) error
Upload copies a local file into the sandbox.
func (f *Files) UploadDir(ctx context.Context, localDir, remoteDir string) error
UploadDir copies a local directory tree into remoteDir (created if missing),
as one tar. Symlinks are copied as links; sockets and devices are skipped.
Files are owned by root.
func (f *Files) Write(ctx context.Context, p string, data []byte) (*WriteInfo, error)
Write creates or replaces a file (atomically, mode 0644), creating parent
directories. Any size works: data over 15 MiB is staged in pieces.
func (f *Files) WriteFiles(ctx context.Context, files []WriteEntry) ([]WriteInfo, error)
WriteFiles writes several files in one upload (one tar), creating parent
directories. Files are owned by root.
type GitHubAppNotInstalledError struct {
InstallURL string
Err error
}
GitHubAppNotInstalledError: the Chainguard GitHub App is not installed on
the GitHub account being linked. Install it at InstallURL, then call Enable
again.
func (e *GitHubAppNotInstalledError) Error() string
func (e *GitHubAppNotInstalledError) Unwrap() error
type GitHubLinkRequiredError struct{ Organization string }
GitHubLinkRequiredError: the organization has no GitHub account linked,
which the service requires before it turns Workspaces on, and Enable was not
allowed to open a browser to link one (SetupOptions.NoBrowser).
func (e *GitHubLinkRequiredError) Error() string
type GitSource struct {
// URL of a github.com repository ("github.com/o/r", "https://github.com/o/r", "git@github.com:o/r.git").
URL string
// Revision to check out; empty means the default branch.
Revision string
}
GitSource starts the sandbox from a GitHub repository instead of an empty
tree: the plane clones it into /work (no upload).
type Info struct {
ID string
Name string
DisplayName string
// State is "creating", "running", "paused" or "stopped".
State string
Region string
CreatedAt time.Time
// ExpiresAt is when a paused sandbox is discarded (zero if not set).
ExpiresAt time.Time
CPUs int
MemoryMiB int64
}
Info describes a sandbox.
func List(ctx context.Context, o *ConnectOptions) ([]Info, error)
List returns the sandboxes this package created (sessions with a sandbox
label) in the instance.
type InvalidPathError struct {
Path string
Reason string // "is a directory" or "not a directory"
}
InvalidPathError: the path exists but is the wrong kind (a directory where a
file was expected, or the reverse).
func (e *InvalidPathError) Error() string
type NotFoundError struct {
// What is "file", "directory", "path", "command" or "sandbox".
What string
Name string
}
NotFoundError: a file, directory, background command or sandbox does not
exist.
func (e *NotFoundError) Error() string
type Organization = workspaces.Organization
Organization is a Chainguard organization a sandbox can live in.
func ListOrganizations(ctx context.Context) ([]Organization, error)
ListOrganizations returns the organizations you belong to (their IDs
are what CreateOptions.Instance and $CHAINCTL_SANDBOX_INSTANCE take).
With exactly one, Create uses it automatically when no organization is set.
It uses the saved login's account-API token (see the authentication docs).
type ProcessInfo struct {
PID int
ID string
Cmd string
Running bool
// ExitCode is set once the command has exited.
ExitCode *int
}
ProcessInfo describes a background command.
type RunOptions struct {
// Cwd is the working directory (default /work; relative paths resolve
// against /work).
Cwd string
// Envs are added to the sandbox-level Envs (and override them).
Envs map[string]string
// Timeout kills the command after this long (default 60s; negative means
// no limit). The plane enforces it.
Timeout time.Duration
// Stdin is sent to the command (at most 16 MiB), then closed.
Stdin []byte
// OnStdout and OnStderr receive output as it arrives. A character whose
// bytes arrive in two pieces is delivered whole, with the later piece.
OnStdout, OnStderr func(data string)
}
RunOptions configures Run and RunArgs.
type Sandbox struct {
// ID is the sandbox's short ID (8 hex characters), usable with Connect.
ID string
// Name is the full resource name (instances/<org>/sessions/<id>).
Name string
// Commands runs commands in the sandbox.
Commands *Commands
// Files reads and writes the sandbox's filesystem.
Files *Files
// Has unexported fields.
}
Sandbox is a handle to one sandbox. Its methods are safe for concurrent use,
but the sandbox runs one command at a time: concurrent calls queue in the
plane.
func Connect(ctx context.Context, id string, o *ConnectOptions) (*Sandbox, error)
Connect returns a handle to an existing sandbox by short ID, display name or
resource name. A paused sandbox resumes on its first command.
func Create(ctx context.Context, o *CreateOptions) (*Sandbox, error)
Create starts a new sandbox and returns when it can run commands (about 8–20
seconds). On failure it deletes anything it created. A session the plane
places on a host that never starts is deleted and recreated (up to three
attempts).
func (sb *Sandbox) Client() *workspaces.Client
Client returns the underlying Workspaces client, for anything this package
doesn't wrap.
func (sb *Sandbox) Close() error
Close releases the handle's connection (if Create or Connect opened it)
without touching the sandbox.
func (sb *Sandbox) GetInfo(ctx context.Context) (Info, error)
GetInfo fetches the sandbox's current state.
func (sb *Sandbox) IsRunning(ctx context.Context) (bool, error)
IsRunning reports whether the sandbox is running (not paused, stopped or
still starting).
func (sb *Sandbox) KeepAlive(ctx context.Context, d time.Duration) error
KeepAlive asks the plane to hold the sandbox running (not park it when idle)
for d. There is no hard deadline to set: an idle sandbox parks after about
10 minutes, and a parked one is discarded after 5 days.
func (sb *Sandbox) Kill(ctx context.Context) (bool, error)
Kill deletes the sandbox and everything in it, and returns once it is gone,
so the session slot is free for a new sandbox. It returns false if the
sandbox was already gone. If the sandbox still exists 30 seconds after the
delete request (or its disappearance can't be confirmed), Kill returns true
with a *TimeoutError (Op "kill"): the deletion was requested but the slot
may not be free yet. The handle's client is closed if Create or Connect
created it.
func (sb *Sandbox) Pause(ctx context.Context) error
Pause snapshots the sandbox (memory and disk) and stops it. Running
processes, including background commands, resume where they were on the next
command or file operation (about 80 seconds after an explicit pause).
type SetupOptions struct {
// Instance is the organization ID. If empty, $CHAINCTL_SANDBOX_INSTANCE is
// used, and failing that the only organization you belong to.
Instance string
// TokenSource mints tokens for the platform API (default: the saved login).
TokenSource workspaces.TokenSource
// AcceptTerms lets Enable accept, on the organization's behalf, the legal
// documents it has not accepted yet. Set it only when the person running
// your program has read and agreed to them (Status lists them, with URLs).
// Status ignores it.
AcceptTerms bool
// GitHubAccount is the GitHub organization or user to link when the
// organization has none linked (Enable only). Empty means the GitHub user
// who authorizes in the browser.
GitHubAccount string
// GitHubPort is the loopback port for GitHub's redirect (default 8989).
GitHubPort int
// NoBrowser stops Enable from opening a browser for the GitHub
// authorization; it then fails with *GitHubLinkRequiredError if a link is needed.
NoBrowser bool
// Out receives instructions during the GitHub authorization (default os.Stderr).
Out io.Writer
}
SetupOptions selects the organization for Status and Enable.
type StartOptions struct {
Cwd string
Envs map[string]string
}
StartOptions configures a background command (Start / StartArgs).
type TermsDocument = workspaces.TermsDocument
TermsDocument is a legal document an organization accepts.
type TermsNotAcceptedError struct{ Missing []TermsDocument }
TermsNotAcceptedError: the organization has not accepted the legal
documents Workspaces is offered under. Enable accepts them when
EnableOptions.AcceptTerms is set.
func (e *TermsNotAcceptedError) Error() string
type TimeoutError struct {
Op string // "command", "start" or "kill"
Detail string
Result *CommandResult
}
TimeoutError: a deadline passed. For a command, Result holds the output
received before it was stopped.
func (e *TimeoutError) Error() string
type WaitOptions struct {
// OnStdout and OnStderr receive the output as Wait polls for it (about
// every 2 seconds while the command runs), starting with any output an
// earlier Poll already fetched. Output a concurrent Poll fetches is
// delivered too, once and in order.
OnStdout, OnStderr func(data string)
}
WaitOptions configures CommandHandle.Wait.
type WorkspacesStatus struct {
// Organization is the organization ID the status is for.
Organization string
// Enabled reports whether Workspaces is turned on. Sandboxes can be
// created when it is and MissingTerms is empty.
Enabled bool
// MissingTerms are the required legal documents not accepted yet. While
// Workspaces is off these are all the documents turning it on needs.
MissingTerms []TermsDocument
// GitHubAccounts are the GitHub organizations or users linked to the
// organization. Turning Workspaces on needs at least one.
GitHubAccounts []string
// Plan is the organization's plan ("Starter", ...).
Plan string
// MaxSandboxes and MaxSandboxesPerUser are the plan's limits on sandboxes
// existing at once (0: not reported).
MaxSandboxes, MaxSandboxesPerUser int
}
WorkspacesStatus is an organization's Workspaces setup.
func Enable(ctx context.Context, o *SetupOptions) (*WorkspacesStatus, error)
Enable turns Workspaces on for the organization, so sandboxes can be created
in it. It is what `chainctl develop init --parent ORG` does for an existing
organization, without chainctl. It needs the owner role, and does nothing if
everything is already in place. The steps:
1. Accept the terms. Only with o.AcceptTerms; without it, an organization
with unaccepted terms gets a *TermsNotAcceptedError listing them.
2. Link a GitHub account, if the organization has none: the service
requires one. This opens a browser on GitHub, where you choose the
account, and waits for you to finish (up to 10 minutes). The Chainguard
GitHub App must be installed on the account; if it is not, the error is
a *GitHubAppNotInstalledError with the page to install it from.
3. Turn the feature on with the plan's allowance. This also turns on
Chainguard Checks, which the same switch controls.
func Status(ctx context.Context, o *SetupOptions) (*WorkspacesStatus, error)
Status reports whether Workspaces is turned on for the organization and
which required terms it still has to accept. It changes nothing.
func (s *WorkspacesStatus) Ready() bool
Ready reports whether sandboxes can be created.
type WriteEntry struct {
Path string
Data []byte
// Mode defaults to 0644.
Mode fs.FileMode
}
WriteEntry is one file for WriteFiles.
type WriteInfo struct {
Name string
Path string
Type FileType
}
WriteInfo describes a written file.