Skip to content

API Reference

Python Reference

from chainguard_sandbox import Sandbox. This page is generated from the package’s docstrings.

class Sandbox

A sandbox: one Chainguard Workspaces session with your packages.

with Sandbox.create(packages=["python-3.13"]) as sbx:
print(sbx.commands.run("python3 -c 'print(2+2)'").stdout)
# 4

Commands run one at a time per sandbox. Durations are in seconds.

@classmethod
def create(
*,
packages: Sequence[str] | None = None,
envs: dict[str, str] | None = None,
name: str = 'sandbox',
egress: Sequence[str] | None = None,
egress_policy: Literal['deny', 'destroy'] = 'deny',
document: bytes | None = None,
source: str | None = None,
source_revision: str = '',
start_timeout: float = 180,
client: Client | None = None,
instance: str | None = None,
) -> Sandbox

Create a sandbox and return when it can run commands (about 8-20 s).

  • packages: Chainguard package names (default DEFAULT_PACKAGES).
  • envs: environment variables for every command (kept client-side).
  • name: label; the display name becomes <name>/<word-word>.
  • egress, egress_policy: outbound allowlist (default ["*"]) and what happens outside it (“deny” refuses the connection, “destroy” stops the sandbox).
  • document: a full environment document instead of packages/egress.
  • source: a GitHub repository to start from instead of an empty /work.
  • instance: the organization ID. If None, $CHAINCTL_SANDBOX_INSTANCE is used; if that’s empty too, the organization is auto-detected when you belong to exactly one ($CHAINGUARD_SANDBOX_NO_DETECT_INSTANCE=1 turns that off). List IDs with list_organizations(), chainguard-sandbox orgs or chainctl iam organizations list.

A session the plane places on a host that never starts is deleted and recreated (up to 3 attempts). On failure nothing is left behind.

@classmethod
def connect(
sandbox_id: str,
*,
envs: dict[str, str] | None = None,
client: Client | None = None,
instance: str | None = None,
) -> Sandbox

A handle to an existing sandbox (short ID, display name or resource name). A paused sandbox resumes on its first command.

@staticmethod
def list(
*,
client: Client | None = None,
instance: str | None = None,
) -> list[SandboxInfo]

The sandboxes this package created in the instance.

def kill() -> bool
@classmethod
def kill(
sandbox_id: str,
*,
client: Client | None = None,
instance: str | None = None,
) -> bool

Delete the sandbox and everything in it, and return once it is gone, so the session slot is free. Returns False if it was already gone.

Raises TimeoutError if the sandbox still exists 30 s after the delete request (or that can’t be confirmed): deletion was requested, but the slot may not be free yet.

Works on the class too, Sandbox.kill("1a2b3c4d") (short ID, display name or resource name). That form deletes without attaching, so it also removes a sandbox that never started or can’t be attached to.

def close() -> None

Release the connection (if this handle opened it); the sandbox keeps running.

def pause() -> None

Snapshot (memory and disk) and stop the sandbox. Processes, including background commands, continue where they were on the next call.

def keep_alive(seconds: float) -> None

Hold the sandbox running (not parked when idle) for this long. There is no hard deadline: an idle sandbox parks after about 10 minutes.

def get_info() -> SandboxInfo
def is_running() -> bool
@property
client: chainguard_sandbox.workspaces.client.Client

The underlying Workspaces client, for anything this package doesn’t wrap.

class Commands

sbx.commands: run commands in the sandbox.

def run(
cmd: str | Sequence[str],
*,
background: Literal[False] = False,
cwd: str | None = None,
envs: dict[str, str] | None = None,
timeout: float | None = 60.0,
stdin: bytes | str | None = None,
on_stdout: Callable[[str], object] | None = None,
on_stderr: Callable[[str], object] | None = None,
) -> CommandResult
def run(
cmd: str | Sequence[str],
*,
background: Literal[True],
cwd: str | None = None,
envs: dict[str, str] | None = None,
timeout: float | None = 60.0,
stdin: bytes | str | None = None,
on_stdout: Callable[[str], object] | None = None,
on_stderr: Callable[[str], object] | None = None,
) -> CommandHandle

Run a command and wait for it.

  • cmd: a string (run with bash, so shell syntax works) or an argv list (no shell). background=True starts it detached and returns a CommandHandle at once (timeout, stdin and the callbacks don’t apply; pass callbacks to handle.wait()).

Raises CommandExitError (with .exit_code/.stdout/.stderr) on a non-zero exit, TimeoutError when timeout seconds pass (None or 0: no limit), and FileNotFoundError if cwd doesn’t exist.

def list() -> list[ProcessInfo]

Background commands started in this sandbox (running and finished).

def connect(pid: int) -> CommandHandle

A handle to a background command by pid.

def kill(pid: int) -> bool

SIGKILL a background command (and its process group). False if it had already exited.

class CommandHandle

A background command. Iterating yields (stdout, stderr) chunks until it exits.

@property
stdout: str

Standard output received so far.

@property
stderr: str
@property
exit_code: int | None

The exit code once known.

def poll() -> int | None

Fetch new output; return the exit code, or None while it runs.

def wait(
on_stdout: Callable[[str], object] | None = None,
on_stderr: Callable[[str], object] | None = None,
) -> CommandResult

Wait for the command to exit, passing output to the callbacks as it arrives (about every 2 s), starting with output fetched earlier. Output a concurrent poll() fetches is delivered too, once and in order. Raises CommandExitError on a non-zero exit.

def kill() -> bool

SIGKILL the command’s process group; the exit code becomes 137. False if it had already exited.

class Files

sbx.files: the sandbox filesystem. Relative paths resolve against /work.

def read(path: str, format: Literal['text'] = 'text') -> str
def read(path: str, format: Literal['bytes']) -> bytes

A file’s contents, as text (UTF-8) or bytes. Raises FileNotFoundError if missing.

def write(path: str, data: str | bytes | IO[bytes]) -> WriteInfo

Create or replace a file atomically (mode 0644), creating parent directories. Any size works (over 15 MiB is staged in pieces).

def write_files(files: Sequence[dict]) -> list[WriteInfo]

Write several files in one upload: [{"path": ..., "data": ..., "mode": 0o755}] (mode optional, default 0644). Parent directories are created.

def list(path: str = '.') -> list[EntryInfo]

Entries of a directory (one level), sorted by name.

def exists(path: str) -> bool

Whether a path exists (a dangling symlink counts).

def get_info(path: str) -> EntryInfo

Describe a path without following a final symlink.

def make_dir(path: str) -> bool

Create a directory and its parents. False if it already existed.

def remove(path: str) -> None

Delete a file or directory tree. Raises FileNotFoundError if missing.

def rename(old_path: str, new_path: str) -> EntryInfo

Move a file or directory (creating the destination’s parents); describes the result.

def upload(local_path: str | os.PathLike, remote_path: str) -> WriteInfo

Copy a local file into the sandbox (keeping its permission bits).

def download(remote_path: str, local_path: str | os.PathLike) -> None

Copy a file from the sandbox, creating local parent directories.

def upload_dir(local_dir: str | os.PathLike, remote_dir: str) -> None

Copy a local directory tree into remote_dir (created if missing) as one tar. Symlinks are copied as links; files are owned by root.

def download_dir(remote_dir: str, local_dir: str | os.PathLike) -> None

Copy a directory tree from the sandbox into local_dir. Nothing is written outside it: absolute names, “..”, and symbolic links that lead outside are refused.

class CommandResult

A finished command’s output and exit code.

Field Type Default
exit_code int required
stdout str required
stderr str required
class SandboxInfo

SandboxInfo(sandbox_id: ‘str’, name: ‘str’, display_name: ‘str’, state: ‘str’, region: ‘str’, created_at: ‘_dt.datetime | None’, expires_at: ‘_dt.datetime | None’, cpu_count: ‘int’, memory_mb: ‘int’)

Field Type Default
sandbox_id str required
name str required
display_name str required
state str required
region str required
created_at datetime.datetime | None required
expires_at datetime.datetime | None required
cpu_count int required
memory_mb int required
class ProcessInfo

ProcessInfo(pid: ‘int’, id: ‘str’, cmd: ‘str’, running: ‘bool’, exit_code: ‘int | None’)

Field Type Default
pid int required
id str required
cmd str required
running bool required
exit_code int | None required
class WriteInfo

WriteInfo(name: ‘str’, path: ‘str’, type: ‘str’ = ‘file’)

Field Type Default
name str required
path str required
type str 'file'
class EntryInfo

EntryInfo(name: ‘str’, path: ‘str’, type: ‘str’, size: ‘int’, mode: ‘int’, permissions: ‘str’, owner: ‘str’, group: ‘str’, modified_time: ‘_dt.datetime’, symlink_target: ‘str | None’ = None)

Field Type Default
name str required
path str required
type str required
size int required
mode int required
permissions str required
owner str required
group str required
modified_time datetime.datetime required
symlink_target str | None None
def environment_document(
packages: Sequence[str] | None = None,
egress: Sequence[str] | None = None,
egress_policy: str = 'deny',
) -> bytes

The environment document Sandbox.create sends (packages + egress policy).

def list_organizations(token_source: TokenSource | None = None) -> list[Organization]

Organizations visible to the token’s identity, sorted by name. The token must be for the account API (default: platform_token_source()). Calls GET https://console-api.enforce.dev/iam/v1/groups?uidp.in_root=true.

class Organization

Organization(id: ‘str’, name: ‘str’)

Field Type Default
id str required
name str required
def workspaces_status(
*,
instance: str | None = None,
token_source: TokenSource | None = None,
) -> WorkspacesStatus

Whether Workspaces is turned on for the organization, and which required terms it still has to accept. Changes nothing.

  • instance: the organization ID. If None, $CHAINCTL_SANDBOX_INSTANCE is used, and failing that the only organization you belong to.
def enable_workspaces(
*,
accept_terms: bool = False,
instance: str | None = None,
github_account: str = '',
github_port: int = 0,
open_browser: bool = True,
open_url: Callable[[str], object] | None = None,
out=None,
token_source: TokenSource | None = None,
) -> WorkspacesStatus

Turn Workspaces on for the organization, so sandboxes can be created in it. It needs the owner role, and does nothing if everything is already in place.

  1. Accept the terms (only with accept_terms=True).
  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, GitHubAppNotInstalledError gives 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.
  • accept_terms: accept, on the organization’s behalf, the legal documents it has not accepted yet. Pass True only when the person running your program has read and agreed to them (workspaces_status() lists them, with URLs). Without it, an organization with unaccepted terms raises TermsNotAcceptedError.
  • github_account: the GitHub organization or user to link (default: the GitHub user who authorizes in the browser). github_port: the loopback port for GitHub’s redirect (default 8989). open_browser=False: don’t start the GitHub authorization; raise GitHubLinkRequiredError if a link is needed.
class WorkspacesStatus

An organization’s Workspaces setup.

Field Type Default
organization str required
enabled bool required
missing_terms list[chainguard_sandbox.workspaces.setup.TermsDocument] list()
github_accounts list[str] list()
plan str ''
max_sandboxes int 0
max_sandboxes_per_user int 0
@property
ready: bool

Whether sandboxes can be created.

class TermsDocument

A legal document an organization accepts.

Field Type Default
id str required
label str ''
url str ''

Exceptions raised by chainguard_sandbox. All derive from SandboxError.

class SandboxError(Exception)

Base class for sandbox errors.

class CommandResult

A finished command’s output and exit code.

Field Type Default
exit_code int required
stdout str required
stderr str required
class CommandExitError(SandboxError)

A command exited with a non-zero code. Carries the full result.

@property
exit_code: int
@property
stdout: str
@property
stderr: str
class NotFoundError(SandboxError)

A file, directory, background command or sandbox does not exist.

class FileNotFoundError(NotFoundError)

A path in the sandbox does not exist.

class SandboxNotFoundError(NotFoundError)

No sandbox with that ID.

class InvalidPathError(SandboxError)

The path exists but is the wrong kind (a directory where a file was expected, or the reverse).

class TimeoutError(SandboxError)

A deadline passed. For a command, result holds the output received before it was stopped.

class SandboxBusyError(SandboxError)

Another client (an interactive shell) is attached; commands run once it detaches.

class LimitReachedError(SandboxError)

The organization is at its session limit (one sandbox per user and three per organization during the Workspaces beta).

class OutcomeUnknownError(SandboxError)

The connection ended, or failed, before the command reported an exit status; it may or may not have run, in part or in full. cause is the transport error (a grpc.RpcError) that cut it short, if there was one.

class WorkspacesNotEnabledError(SandboxError)

Workspaces is not turned on for the organization. An owner can turn it on with enable_workspaces() or chainguard-sandbox enable.

class GitHubLinkRequiredError(SandboxError)

The organization has no GitHub account linked, which the service requires before it turns Workspaces on, and enable_workspaces() was told not to open a browser to link one.

class GitHubAppNotInstalledError(SandboxError)

The Chainguard GitHub App is not installed on the GitHub account being linked. Install it at install_url, then call enable_workspaces() again.

class TermsNotAcceptedError(SandboxError)

The organization has not accepted the legal documents Workspaces is offered under. missing lists them (.id, .label, .url); enable_workspaces(accept_terms=True) accepts them.