API Reference
Python Reference
from chainguard_sandbox import Sandbox. This page is generated from the package’s docstrings.
Sandbox
Section titled “Sandbox”class SandboxA 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)# 4Commands run one at a time per sandbox. Durations are in seconds.
create
Section titled “create”@classmethoddef 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,) -> SandboxCreate 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 orgsorchainctl 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.
connect
Section titled “connect”@classmethoddef connect( sandbox_id: str, *, envs: dict[str, str] | None = None, client: Client | None = None, instance: str | None = None,) -> SandboxA handle to an existing sandbox (short ID, display name or resource name). A paused sandbox resumes on its first command.
@staticmethoddef list( *, client: Client | None = None, instance: str | None = None,) -> list[SandboxInfo]The sandboxes this package created in the instance.
def kill() -> bool@classmethoddef kill( sandbox_id: str, *, client: Client | None = None, instance: str | None = None,) -> boolDelete 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() -> NoneRelease the connection (if this handle opened it); the sandbox keeps running.
def pause() -> NoneSnapshot (memory and disk) and stop the sandbox. Processes, including background commands, continue where they were on the next call.
keep_alive
Section titled “keep_alive”def keep_alive(seconds: float) -> NoneHold the sandbox running (not parked when idle) for this long. There is no hard deadline: an idle sandbox parks after about 10 minutes.
get_info
Section titled “get_info”def get_info() -> SandboxInfois_running
Section titled “is_running”def is_running() -> boolclient
Section titled “client”@propertyclient: chainguard_sandbox.workspaces.client.ClientThe underlying Workspaces client, for anything this package doesn’t wrap.
Commands
Section titled “Commands”class Commandssbx.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,) -> CommandResultdef 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,) -> CommandHandleRun 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).
connect
Section titled “connect”def connect(pid: int) -> CommandHandleA handle to a background command by pid.
def kill(pid: int) -> boolSIGKILL a background command (and its process group). False if it had already exited.
CommandHandle
Section titled “CommandHandle”class CommandHandleA background command. Iterating yields (stdout, stderr) chunks until it exits.
stdout
Section titled “stdout”@propertystdout: strStandard output received so far.
stderr
Section titled “stderr”@propertystderr: strexit_code
Section titled “exit_code”@propertyexit_code: int | NoneThe exit code once known.
def poll() -> int | NoneFetch 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,) -> CommandResultWait 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() -> boolSIGKILL the command’s process group; the exit code becomes 137. False if it had already exited.
class Filessbx.files: the sandbox filesystem. Relative paths resolve against /work.
def read(path: str, format: Literal['text'] = 'text') -> strdef read(path: str, format: Literal['bytes']) -> bytesA file’s contents, as text (UTF-8) or bytes. Raises FileNotFoundError if missing.
def write(path: str, data: str | bytes | IO[bytes]) -> WriteInfoCreate or replace a file atomically (mode 0644), creating parent directories. Any size works (over 15 MiB is staged in pieces).
write_files
Section titled “write_files”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.
exists
Section titled “exists”def exists(path: str) -> boolWhether a path exists (a dangling symlink counts).
get_info
Section titled “get_info”def get_info(path: str) -> EntryInfoDescribe a path without following a final symlink.
make_dir
Section titled “make_dir”def make_dir(path: str) -> boolCreate a directory and its parents. False if it already existed.
remove
Section titled “remove”def remove(path: str) -> NoneDelete a file or directory tree. Raises FileNotFoundError if missing.
rename
Section titled “rename”def rename(old_path: str, new_path: str) -> EntryInfoMove a file or directory (creating the destination’s parents); describes the result.
upload
Section titled “upload”def upload(local_path: str | os.PathLike, remote_path: str) -> WriteInfoCopy a local file into the sandbox (keeping its permission bits).
download
Section titled “download”def download(remote_path: str, local_path: str | os.PathLike) -> NoneCopy a file from the sandbox, creating local parent directories.
upload_dir
Section titled “upload_dir”def upload_dir(local_dir: str | os.PathLike, remote_dir: str) -> NoneCopy a local directory tree into remote_dir (created if missing) as one tar. Symlinks are copied as links; files are owned by root.
download_dir
Section titled “download_dir”def download_dir(remote_dir: str, local_dir: str | os.PathLike) -> NoneCopy a directory tree from the sandbox into local_dir. Nothing is written outside it: absolute names, “..”, and symbolic links that lead outside are refused.
Data Types
Section titled “Data Types”CommandResult
Section titled “CommandResult”class CommandResultA finished command’s output and exit code.
| Field | Type | Default |
|---|---|---|
exit_code |
int |
required |
stdout |
str |
required |
stderr |
str |
required |
SandboxInfo
Section titled “SandboxInfo”class SandboxInfoSandboxInfo(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 |
ProcessInfo
Section titled “ProcessInfo”class ProcessInfoProcessInfo(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 |
WriteInfo
Section titled “WriteInfo”class WriteInfoWriteInfo(name: ‘str’, path: ‘str’, type: ‘str’ = ‘file’)
| Field | Type | Default |
|---|---|---|
name |
str |
required |
path |
str |
required |
type |
str |
'file' |
EntryInfo
Section titled “EntryInfo”class EntryInfoEntryInfo(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 |
environment_document
Section titled “environment_document”def environment_document( packages: Sequence[str] | None = None, egress: Sequence[str] | None = None, egress_policy: str = 'deny',) -> bytesThe environment document Sandbox.create sends (packages + egress policy).
list_organizations
Section titled “list_organizations”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.
Organization
Section titled “Organization”class OrganizationOrganization(id: ‘str’, name: ‘str’)
| Field | Type | Default |
|---|---|---|
id |
str |
required |
name |
str |
required |
Enabling Workspaces
Section titled “Enabling Workspaces”workspaces_status
Section titled “workspaces_status”def workspaces_status( *, instance: str | None = None, token_source: TokenSource | None = None,) -> WorkspacesStatusWhether 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.
enable_workspaces
Section titled “enable_workspaces”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,) -> WorkspacesStatusTurn 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.
- Accept the terms (only with accept_terms=True).
- 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.
- 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.
WorkspacesStatus
Section titled “WorkspacesStatus”class WorkspacesStatusAn 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 |
@propertyready: boolWhether sandboxes can be created.
TermsDocument
Section titled “TermsDocument”class TermsDocumentA legal document an organization accepts.
| Field | Type | Default |
|---|---|---|
id |
str |
required |
label |
str |
'' |
url |
str |
'' |
Errors
Section titled “Errors”Exceptions raised by chainguard_sandbox. All derive from SandboxError.
SandboxError
Section titled “SandboxError”class SandboxError(Exception)Base class for sandbox errors.
CommandResult
Section titled “CommandResult”class CommandResultA finished command’s output and exit code.
| Field | Type | Default |
|---|---|---|
exit_code |
int |
required |
stdout |
str |
required |
stderr |
str |
required |
CommandExitError
Section titled “CommandExitError”class CommandExitError(SandboxError)A command exited with a non-zero code. Carries the full result.
exit_code
Section titled “exit_code”@propertyexit_code: intstdout
Section titled “stdout”@propertystdout: strstderr
Section titled “stderr”@propertystderr: strNotFoundError
Section titled “NotFoundError”class NotFoundError(SandboxError)A file, directory, background command or sandbox does not exist.
FileNotFoundError
Section titled “FileNotFoundError”class FileNotFoundError(NotFoundError)A path in the sandbox does not exist.
SandboxNotFoundError
Section titled “SandboxNotFoundError”class SandboxNotFoundError(NotFoundError)No sandbox with that ID.
InvalidPathError
Section titled “InvalidPathError”class InvalidPathError(SandboxError)The path exists but is the wrong kind (a directory where a file was expected, or the reverse).
TimeoutError
Section titled “TimeoutError”class TimeoutError(SandboxError)A deadline passed. For a command, result holds the output received before it was stopped.
SandboxBusyError
Section titled “SandboxBusyError”class SandboxBusyError(SandboxError)Another client (an interactive shell) is attached; commands run once it detaches.
LimitReachedError
Section titled “LimitReachedError”class LimitReachedError(SandboxError)The organization is at its session limit (one sandbox per user and three per organization during the Workspaces beta).
OutcomeUnknownError
Section titled “OutcomeUnknownError”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.
WorkspacesNotEnabledError
Section titled “WorkspacesNotEnabledError”class WorkspacesNotEnabledError(SandboxError)Workspaces is not turned on for the organization. An owner can turn it on
with enable_workspaces() or chainguard-sandbox enable.
GitHubLinkRequiredError
Section titled “GitHubLinkRequiredError”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.
GitHubAppNotInstalledError
Section titled “GitHubAppNotInstalledError”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.
TermsNotAcceptedError
Section titled “TermsNotAcceptedError”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.
