Agent Sandbox
Python SDK Reference
This module provides the SandboxClient for interacting with the Agentic Sandbox. It handles lifecycle management (claiming, waiting) and interaction (execution, file I/O) via the Sandbox resource handle.
SandboxClient Objects
class SandboxClient(Generic[T])
A registry-based client for managing Sandbox lifecycles. Tracks all active handles to ensure flat code structure and safe cleanup.
sandbox_class
type: ignore
__init__
def __init__(connection_config: SandboxConnectionConfig | None = None,
tracer_config: SandboxTracerConfig | None = None,
cleanup: bool = False,
api_client: client.ApiClient | None = None,
*,
file_config: SandboxFileConfig | None = None) -> None
Initializes the SandboxClient.
Arguments:
connection_config- Configuration for connecting to the sandboxes. Defaults to SandboxLocalTunnelConnectionConfig() which uses kubectl port-forwarding. Sandboxd supports a Pod or router tunnel, or the explicit Service DNS / Pod IP in-cluster connection config.tracer_config- Configuration for OpenTelemetry tracing. Defaults to an empty SandboxTracerConfig (tracing disabled).cleanup- If True, registers an atexit hook to automatically delete tracked sandboxes when the program terminates, excluding claims explicitly named through create_sandbox(). Defaults to False.api_client- Optional pre-configured KubernetesApiClientforwarded to the underlyingK8sHelperto target a specific cluster/context.file_config- File download limits for created and attached sandboxes. Defaults to unlimited downloads.
create_sandbox
def create_sandbox(warmpool: str,
namespace: str = "default",
sandbox_ready_timeout: int = 180,
labels: dict[str, str] | None = None,
*,
claim_name: str | None = None,
adopt_existing: bool = False,
shutdown_after_seconds: int | None = None,
volume_claim_templates: list[dict[str, Any]] | None = None,
pod_labels: dict[str, str] | None = None,
pod_annotations: dict[str, str] | None = None,
env: dict[str, str] | None = None) -> T
Provisions new Sandbox claim and returns a Sandbox handle which tracks the underlying infrastructure.
Arguments:
warmpool- Name of the SandboxWarmPool to use.namespace- Kubernetes namespace for the claim.sandbox_ready_timeout- Seconds to wait for the sandbox to be ready.labels- Optional Kubernetes labels to attach to the claim object (SandboxClaim.metadata.labels).claim_name- Optional DNS-1123 Claim name. Explicit names remain caller-owned and are excluded from automatic cleanup.adopt_existing- On AlreadyExists, attach to the existing named Claim after checking its warm pool and that it is not terminating. Requires claim_name. Creation options are not reapplied on adoption; an existing shutdownTime is preserved.shutdown_after_seconds- Optional TTL in seconds. When set, the claim’sspec.lifecycleis populated with ashutdownTimeof now + shutdown_after_seconds (UTC) and ashutdownPolicyof"Delete", so the controller auto-deletes the claim on expiry. Must be a positive integer.volume_claim_templates- Optional list of volume claim templates to override/merge with the sandbox template.pod_labels- Optional labels stamped onto the running Sandbox Pod viaspec.additionalPodMetadata.labels. Unlikelabels(which land on the claim object), these are readable from inside the sandbox through the Downward API.pod_annotations- Optional annotations stamped onto the running Sandbox Pod viaspec.additionalPodMetadata.annotations.env- Optional environment variables to inject into the SandboxClaim. Setting this populatesspec.envand forces a cold start from the warm pool template instead of adopting a pre-warmed pod, which may increase startup latency.
Example:
client = SandboxClient() sandbox = client.create_sandbox(warmpool=“python-sandbox-pool”) sandbox.commands.run(“echo ‘Hello World’”)
get_sandbox
def get_sandbox(claim_name: str,
namespace: str = "default",
resolve_timeout: int = 30) -> T
Retrieves an existing sandbox handle given a sandbox claim name. If the handle is closed or missing, it re-attaches to the infrastructure.
Arguments:
claim_name- Name of the SandboxClaim to attach to.namespace- Kubernetes namespace the claim lives in.resolve_timeout- Seconds to wait while resolving the sandbox name from the claim status.
Example:
client = SandboxClient() sandbox = client.get_sandbox( … “sandbox-claim-1234abcd”, … ) sandbox.commands.run(“ls -la”)
list_active_sandboxes
def list_active_sandboxes() -> List[Tuple[str, str]]
Returns a list of tuples containing (namespace, claim_name) currently managed by this client.
Example:
client = SandboxClient() client.create_sandbox(“python-sandbox-pool”) print(client.list_active_sandboxes()) [(‘default’, ‘sandbox-claim-1234abcd’)]
list_all_sandboxes
def list_all_sandboxes(namespace: str = "default",
label_selector: str | None = None) -> List[str]
Lists all SandboxClaim names currently existing in the Kubernetes cluster for the given namespace.
Arguments:
namespace- Kubernetes namespace to list claims in.label_selector- Optional Kubernetes label selector string (e.g."app=myapp"). When set, only claims matching the selector are returned.
Example:
client = SandboxClient() print(client.list_all_sandboxes(namespace=“default”)) [‘sandbox-claim-1234abcd’, ‘sandbox-claim-5678efgh’]
delete_sandbox
def delete_sandbox(claim_name: str, namespace: str = "default") -> None
Stops the client side connection and deletes the Kubernetes resources.
Example:
client = SandboxClient() sandbox = client.create_sandbox(“python-sandbox-pool”) client.delete_sandbox(sandbox.claim_name)
delete_all
def delete_all() -> None
Cleanup all tracked sandboxes managed by this client.
Example:
client = SandboxClient() client.create_sandbox(“python-sandbox-pool”) client.create_sandbox(“python-sandbox-pool”) client.delete_all()
get_sandbox_claim_warmpool_name
def get_sandbox_claim_warmpool_name(claim_name: str, namespace: str) -> str
Get warmpool name of a sandbox claim.
k8s_agent_sandbox.models
Configuration and wire-format models for the Python SDK.
ExecutionResult Objects
class ExecutionResult(BaseModel)
A structured object for holding the result of a command execution.
stdout
Standard output from the command.
stderr
Standard error from the command.
exit_code
Exit code of the command.
timed_out
True if the runtime killed the command for exceeding its time limit.
LegacyExecuteRequest Objects
class LegacyExecuteRequest(BaseModel)
Request body for the legacy python-runtime /execute endpoint.
command
Shell command to run.
timeout_seconds
Limit on how long the command may run; omitted when unset.
ProcessOutputEvent Objects
class ProcessOutputEvent(BaseModel)
A chunk of stdout or stderr from a process started with commands.start().
data is raw bytes, not text: a multi-byte character can be split
across two chunks, so callers decode the stream rather than each chunk.
A PTY process never produces stderr events, because the terminal
merges stderr into stdout.
ProcessExitEvent Objects
class ProcessExitEvent(BaseModel)
Terminal event of a process started with commands.start().
exit_code is -1 when the process was killed by a signal: sandboxd
reports Go’s ExitCode(), not the shell’s 128+N convention.
PtySize Objects
class PtySize(BaseModel)
Pseudo-terminal geometry for commands.start().
Mirrors the TypeScript SDK’s PtySize.
FileEntry Objects
class FileEntry(BaseModel)
Represents a file or directory entry in the sandbox.
Runtime-neutral: the SDK decodes both the legacy python-runtime wire
format (mod_time as a float POSIX timestamp) and the sandboxd wire
format (modified_at as an RFC 3339 string, plus mode) into this
one shape. modified is always a timezone-aware datetime.
name
Name of the file.
size
Size of the file in bytes.
type
Type of the entry (file or directory).
modified
Last modification time (timezone-aware).
mode
Octal permission bits (sandboxd only), e.g. “0644”.
from_legacy
@classmethod
def from_legacy(cls, entry: dict[str, Any]) -> "FileEntry"
Build from the legacy python-runtime listing entry.
from_sandboxd
@classmethod
def from_sandboxd(cls, entry: dict[str, Any]) -> "FileEntry"
Build from a sandboxd DirectoryListing entry.
FileEvent Objects
class FileEvent(BaseModel)
A filesystem change observed by :meth:FileWatcher.watch.
Mirrors the watcher.v1.FileEvent protobuf message with SDK-idiomatic
field names. type is a string matching the proto names (create,
write, remove, rename, chmod, error); future proto
versions may introduce additional values, so consumers should tolerate
unknown types rather than treating the set as closed.
For rename events, path carries the OLD (source) path; when the
new name lands inside the watched tree it arrives as a separate
create event. Pair the two to reconstruct renames.
type
Kind of change observed (e.g. “create”, “write”, “rename”).
path
Sandbox-relative path; for rename events the OLD path.
error
For error events, a human-readable message; empty otherwise.
SandboxHealth Objects
class SandboxHealth(BaseModel)
Sandbox liveness/readiness reported by sandboxd’s /v1/health endpoint.
Mirrors the Go SDK’s sandbox.Health and the TypeScript SDK’s
SandboxHealth.
status
HealthResponse.status enum in the sandboxd spec.
uptime_seconds
Seconds sandboxd has been running.
from_sandboxd
@classmethod
def from_sandboxd(cls, payload: dict[str, Any]) -> "SandboxHealth"
Build from a sandboxd /v1/health response body.
SandboxMetadata Objects
class SandboxMetadata(BaseModel)
Runtime environment metadata reported by sandboxd’s /v1/metadata endpoint.
Only non-sensitive orchestrator-injected configuration is exposed here;
the sandboxd spec forbids serving credentials from /v1/metadata. Mirrors
the Go SDK’s sandbox.Metadata and the TypeScript SDK’s
SandboxMetadata.
env
Orchestrator-injected environment variables; empty when none apply.
from_sandboxd
@classmethod
def from_sandboxd(cls, payload: dict[str, Any]) -> "SandboxMetadata"
Build from a sandboxd /v1/metadata response body.
SandboxClaimEnvVar Objects
class SandboxClaimEnvVar(BaseModel)
Represents an environment variable entry in a SandboxClaim spec.
name
Name of the environment variable.
value
Value of the environment variable.
SandboxDirectConnectionConfig Objects
class SandboxDirectConnectionConfig(BaseModel)
Configuration for connecting directly to a Sandbox URL.
extra_headers and client_cert/ca_cert (mTLS) support a router
behind an authenticating gateway.
api_url
Direct URL to the router.
server_port
Port the sandbox container listens on.
extra_headers
Sent on every request.
client_cert
(certificate path, private key path) for mTLS.
ca_cert
CA bundle path used to verify the router; default trust store if unset.
SandboxGatewayConnectionConfig Objects
class SandboxGatewayConnectionConfig(BaseModel)
Configuration for connecting via Kubernetes Gateway API.
gateway_name
Name of the Gateway resource.
gateway_namespace
Namespace where the Gateway resource resides.
gateway_ready_timeout
Timeout in seconds to wait for Gateway IP.
server_port
Port the sandbox container listens on.
SandboxLocalTunnelConnectionConfig Objects
class SandboxLocalTunnelConnectionConfig(BaseModel)
Configuration for connecting via kubectl port-forward.
port_forward_ready_timeout
Timeout in seconds to wait for port-forward to be ready.
server_port
Port the sandbox container listens on.
router_namespace
Namespace where the Router service resides.
SandboxdPodTunnelConnectionConfig Objects
class SandboxdPodTunnelConnectionConfig(BaseModel)
Configuration for the sandboxd runtime via a direct pod port-forward.
sandboxd (KEP-539.2) exposes two listeners: the Filesystem & Runtime REST API and the gRPC ProcessService. This config port-forwards directly to the sandbox pod, reaching both.
For Kata or gVisor, use SandboxdRouterTunnelConnectionConfig or SandboxdInClusterConnectionConfig.
auth_token
Optional bearer token for sandboxd REST and gRPC.
rest_port
sandboxd REST filesystem port on the pod.
grpc_port
sandboxd gRPC ProcessService port on the pod.
port_forward_ready_timeout
Seconds to wait for port-forward readiness.
SandboxdRouterTunnelConnectionConfig Objects
class SandboxdRouterTunnelConnectionConfig(BaseModel)
Connect to sandboxd through a port-forward to sandbox-router-svc.
REST and gRPC share the router’s port 8080. Routing headers and metadata
select the Sandbox and its REST or gRPC port. gRPC requires sandbox-router
v1.0.9 or later. Set router_auth_token when the router requires
authentication. The SDK sends that token as Authorization, which the
router strips. It sends auth_token as X-Sandboxd-Token, which the
router forwards to sandboxd.
pod_ip_routing stays false so the router selects the Pod from its cache
or DNS. Scoped tokens reject X-Sandbox-Pod-IP.
auth_token
sandboxd token. Sent as X-Sandboxd-Token because the router strips Authorization.
router_auth_token
Bearer token for the router. Sent as Authorization on REST and gRPC. The router strips it.
rest_port
sandboxd REST port, not the router port.
grpc_port
sandboxd gRPC port, not the router port.
router_namespace
Namespace of sandbox-router-svc. Defaults to agent-sandbox-system.
port_forward_ready_timeout
Seconds to wait for the router tunnel. Must be positive.
pod_ip_routing
Send X-Sandbox-Pod-IP on REST and gRPC. Set true only when the router cache is disabled and the Sandbox has no Service.
SandboxdInClusterConnectionConfig Objects
class SandboxdInClusterConnectionConfig(BaseModel)
Connect to sandboxd directly over the selected in-cluster address.
in-cluster-service requires Sandbox.status.serviceFQDN and a Service
enabled on the Sandbox template. in-cluster-pod-ip uses
Sandbox.status.podIPs. Neither mode falls back to the other. sandboxd’s
REST filesystem listener defaults to port 8080 and its gRPC ProcessService
listener to port 9090.
auth_token
Optional bearer token for sandboxd REST and gRPC.
SandboxInClusterConnectionConfig Objects
class SandboxInClusterConnectionConfig(BaseModel)
Configuration for direct in-cluster connection to the sandbox pod, bypassing the router.
The client first uses the pod IP reported in the Sandbox status. If the pod IP is unavailable, it falls back to the stable Kubernetes DNS endpoint: http://{sandbox_id}.{namespace}.svc.cluster.local:{server_port}
server_port
Port the sandbox container listens on.
AdditionalPodMetadata Objects
class AdditionalPodMetadata(BaseModel)
Wire-format for SandboxClaim spec.additionalPodMetadata.
Labels and annotations stamped onto the running Sandbox Pod (not the
SandboxClaim object). Omit empty sections so the manifest never carries
an empty additionalPodMetadata.
SandboxFileConfig Objects
class SandboxFileConfig(BaseModel)
Client-side file download limits, shared by read() and read_to().
max_download_size
Maximum file bytes downloaded; None preserves unlimited reads.
SandboxTracerConfig Objects
class SandboxTracerConfig(BaseModel)
Configuration for tracer level information
enable_tracing
Whether to enable OpenTelemetry tracing.
trace_service_name
Service name used for traces.