Agent Sandbox

Python SDK Reference

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) -> 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 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 Kubernetes ApiClient forwarded to the underlying K8sHelper to target a specific cluster/context.

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 409, 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’s spec.lifecycle is populated with a shutdownTime of now + shutdown_after_seconds (UTC) and a shutdownPolicy of "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 via spec.additionalPodMetadata.labels. Unlike labels (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 via spec.additionalPodMetadata.annotations.
  • env - Optional environment variables to inject into the SandboxClaim. Setting this populates spec.env and 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

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.

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.

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.

Doesn’t work on Kata or gVisor; use SandboxdInClusterConnectionConfig for those.

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.

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.

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.

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.

Last modified July 17, 2026: add go and python docs (#780) (e255c39)