Properties
sandbox_id
returncode
runner_id
profile_id
status
status_updated_at
started_at
runner_group_id
service_address
exposed_ports
applied_ingress_mode
applied_egress_mode
resource_limits
resource_requests
resource_gpu
exec_stats
Methods
run
*args(str): Optional command and arguments (e.g., “echo”, “hello”, “world”). If omitted, uses default command from SandboxDefaults.container_image(str | None): Container image to usedefaults(SandboxDefaults | None): Optional SandboxDefaults to applyrequest_timeout_seconds(float | None): Timeout for API requests (client-side)poll_retry_budget_seconds(float | None): Wall-clock budget for retrying transient errors on the sandbox-status poll loop (default: 30s). Set to 0 to disable retry.poll_rpc_timeout_seconds(float | None): Per-call timeout for poll Get RPCs (default: 15s). Separate from request_timeout_seconds.max_lifetime_seconds(float | None): Max sandbox lifetime (server-side)tags(list[str] | None): Optional tags for the sandboxprofile_ids(list[str] | None): Optional list of profile IDs for infrastructure selection. See SandboxDefaults.profile_ids for semantics. Preferprofile_nameswhen selecting by name.profile_names(list[str] | None): Optional list of profile names for infrastructure selection (preferred over profile_ids). See SandboxDefaults.profile_names for semantics.runner_ids(list[str] | None): Optional list of runner IDsresources(ResourceOptions | dict[str, Any] | None): Resource configuration. Accepts ResourceOptions for separate requests/limits, or a flat dict for backward-compatible Guaranteed QoS.mounted_files(list[dict[str, Any]] | None): Files to mount into the sandboxs3_mount(dict[str, Any] | None): S3 bucket mount configurationports(list[dict[str, Any]] | None): Port mappings for the sandboxnetwork(NetworkOptions | dict[str, Any] | None): Network configuration (NetworkOptions dataclass)max_timeout_seconds(int | None): Maximum timeout for sandbox operationsenvironment_variables(dict[str, str] | None): Environment variables to inject into the sandbox. Merges with and overrides matching keys from the session defaults. Use for non-sensitive config only.annotations(dict[str, str] | None): Kubernetes pod annotations for the sandbox. Merges with and overrides matching keys from the session defaults. Use for non-sensitive metadata only.secrets(Sequence[Secret | dict[str, Any]] | None): Secrets to inject as environment variables. Merged with defaults (defaults first, then this list).
session
- Shared configuration via defaults
- Automatic cleanup of orphaned sandboxes
- Function execution via @session.function() decorator Parameters
-
defaults(SandboxDefaults | Mapping[str, Any] | None): Optional defaults to apply to sandboxes created via session
Session: A Session instance
list
include_stopped=True to widen the search to include terminal
sandboxes (completed, failed, terminated).
A terminal status filter (e.g. status="completed") also widens
the search automatically.
Parameters
tags(list[str] | None): Filter by tags (sandboxes must have ALL specified tags)status(str | None): Filter by status (“running”, “completed”, “failed”, etc.)profile_ids(list[str] | None): Optional list of profile IDs for infrastructure selection. See SandboxDefaults.profile_ids for semantics. Preferprofile_nameswhen selecting by name.profile_names(list[str] | None): Optional list of profile names for infrastructure selection (preferred over profile_ids). See SandboxDefaults.profile_names for semantics.runner_ids(list[str] | None): Filter by runner IDsinclude_stopped(bool): If True, include terminal sandboxes (completed, failed, terminated). Defaults to False.base_url(str | None): Override API URL (default: CWSANDBOX_BASE_URL env or default)timeout_seconds(float | None): Request timeout (default: 300s)poll_retry_budget_seconds(float | None): Wall-clock budget for retrying transient errors on the sandbox-status poll loop (default: 30s). Set to 0 to disable retry. Applied to returned Sandbox instances.poll_rpc_timeout_seconds(float | None): Per-call timeout for poll Get RPCs (default: 15s). Separate fromtimeout_seconds. Applied to returned Sandbox instances.
OperationRef[list[Sandbox]]: OperationRef[list[Sandbox]]: Use .result() to block for results,OperationRef[list[Sandbox]]: or await directly in async contexts.
from_id
sandbox_id(str): The ID of the existing sandboxbase_url(str | None): Override API URL (default: CWSANDBOX_BASE_URL env or default)timeout_seconds(float | None): Request timeout (default: 300s)poll_retry_budget_seconds(float | None): Wall-clock budget for retrying transient errors on the sandbox-status poll loop (default: 30s). Set to 0 to disable retry. Applied to the returned Sandbox instance.poll_rpc_timeout_seconds(float | None): Per-call timeout for poll Get RPCs (default: 15s). Separate fromtimeout_seconds. Applied to the returned Sandbox instance.
OperationRef[Sandbox]: OperationRef[Sandbox]: Use .result() to block for the Sandbox instance,OperationRef[Sandbox]: or await directly in async contexts.
SandboxNotFoundError: If sandbox doesn’t exist
delete
sandbox_id(str): The sandbox ID to deletebase_url(str | None): Override API URL (default: CWSANDBOX_BASE_URL env or default)timeout_seconds(float | None): Request timeout (default: 300s)missing_ok(bool): If True, suppress SandboxNotFoundError when sandbox doesn’t exist.
OperationRef[None]: OperationRef[None]: Use .result() to block until complete.OperationRef[None]: Raises SandboxNotFoundError if not found (unless missing_ok=True),OperationRef[None]: SandboxError if deletion failed.
SandboxNotFoundError: If sandbox doesn’t exist and missing_ok=FalseSandboxError: If deletion failed for other reasons
get_status
SandboxStatus: SandboxStatus enum value
SandboxNotRunningError: If sandbox has not been started
start
OperationRef[None]: OperationRef[None]: Use .result() to block until backend accepts.
wait
timeout(float | None): Maximum seconds to wait. None means use default timeout.
Sandbox: Self for method chaining. Check .status to determine final state.
SandboxFailedError: If sandbox fails to startSandboxTerminatedError: If sandbox was terminated externallySandboxTimeoutError: If timeout expires
wait_until_complete
timeout(float | None): Maximum seconds to wait. None means use default timeout.raise_on_termination(bool): If True (default), raises SandboxTerminatedError when this client called stop() or the backend reports legacy TERMINATED status. External kills (infrastructure, lifetime limits, other clients) that result in COMPLETED are not detectable until the backend provides termination_reason metadata. Set to False to suppress SandboxTerminatedError entirely.
OperationRef[Sandbox]: OperationRef[Sandbox]: Use .result() to block or await in async contexts.
SandboxTimeoutError: If timeout expiresSandboxTerminatedError: If sandbox was stopped by this client or reported as TERMINATED by backend (and raise_on_termination=True)SandboxFailedError: If sandbox failed
poll_retry_budget_seconds is a hard sub-timeout inside the user’s timeout parameter. A 30s retry budget with a 300s user timeout can surface budget-exhaustion errors around 30s. Callers that want longer retry should configure poll_retry_budget_seconds accordingly.
Examples
stop
snapshot_on_stop(bool): If True, capture sandbox state before shutdown.graceful_shutdown_seconds(float): Time to wait for graceful shutdown.missing_ok(bool): If True, suppress SandboxNotFoundError when sandbox doesn’t exist.
OperationRef[None]: OperationRef[None]: Use .result() to block until terminal.OperationRef[None]: Raises SandboxError on failure, SandboxNotFoundError if not foundOperationRef[None]: (unless missing_ok=True).
exec
command(Sequence[str]): Command and arguments to executecwd(str | None): Working directory for command execution. Must be an absolute path. When specified, the command is wrapped with a shell cd.check(bool): If True, raise SandboxExecutionError on non-zero returncodetimeout_seconds(float | None): Timeout for command execution (after sandbox is RUNNING). Does not include time waiting for sandbox to reach RUNNING status.stdin(bool): If True, enable stdin streaming. Process.stdin will be a StreamWriter that can send input to the command. If False (default), stdin is closed immediately and Process.stdin is None.
Process: Process handle with streaming stdout/stderr. Call .result() to blockProcess: for the final ProcessResult, or iterate over .stdout/.stderr forProcess: real-time output. When stdin=True, Process.stdin is a StreamWriter.
ValueError: If command is empty or cwd is invalid (empty or relative path)
shell
command(Sequence[str] | None): Shell command to execute. Defaults to [“/bin/bash”]. Accepts a sequence like [“/bin/sh”] or [“/usr/bin/python3”].width(int | None): Initial terminal width in columns.height(int | None): Initial terminal height in rows.
TerminalSession: TerminalSession handle with .output (StreamReader[bytes]),TerminalSession: .stdin (StreamWriter), and .resize(w, h).
ValueError: If command is explicitly empty.
read_file
filepath(str): Path to file in sandboxtimeout_seconds(float | None): Timeout for the operation
OperationRef[bytes]: OperationRef[bytes]: Use .result() to block and retrieve contents.
write_file
filepath(str): Path to file in sandboxcontents(bytes): File contents as bytestimeout_seconds(float | None): Timeout for the operation
OperationRef[None]: OperationRef[None]: Use .result() to block until complete.
stream_logs
Sandbox.run() (or the default shell-trapped
keep-alive). Output from commands started via exec() is not
included; use Process.stdout/Process.stderr for those.
.. note::
Sandboxes created with the default keep-alive command do not
produce any log output. To see logs here, pass a command that
writes to stdout/stderr when calling Sandbox.run().
Returns a StreamReader that yields log lines as strings. The method
returns immediately — iteration on the StreamReader blocks until
data arrives.
Can also retrieve historical logs from stopped sandboxes when
follow=False.
Parameters
follow(bool): If True, continuously stream new logs (liketail -f). If False, stream existing logs and stop. Only running sandboxes supportfollow=True.tail_lines(int | None): Number of most recent lines to retrieve. If None, returns all available lines.since_time(datetime | None): Only return logs after this timestamp.timestamps(bool): If True, prefix each line with an ISO 8601 timestamp from the server.timeout_seconds(float | None): Client-side deadline for the gRPC call. Defaults torequest_timeout_secondswhenfollow=False, andNone(no timeout) whenfollow=True.
StreamReader[str]: StreamReader yielding log lines as strings. Iterate synchronouslyStreamReader[str]: withfor line in readeror asynchronously withStreamReader[str]:async for line in reader.
SandboxNotRunningError: Iffollow=Trueand the sandbox has been stopped.SandboxError: If the log stream encounters an error.