Sandbox
Live inspection
info() returns identity, status, optional failure message, and creation/update timestamps. Timestamps are UTC datetime values or None, with microsecond precision. id and name require no I/O; mutable state is fetched on each inspection call. See inspection and lifecycle.
sb.owns_lifecycle
create() or start() own lifecycle. Preparing a stopped local sandbox through ensure_running() or an operation acquires ownership on that object. Connecting to an already-running sandbox acquires no ownership. Local detached sandboxes and remote sandboxes return False. This is an async property; use await sb.owns_lifecycle.
Returns
True if this handle owns the lifecycle.sb.fs
Example
Example
sb.fs (no await). See Filesystem for API details.
Returns
Static methods
Sandbox.create()
Example
Example
SandboxConfig for the full set. Pulls the image if needed, boots the VM, starts the guest agent, and waits until it is ready to accept commands. Sandbox names must be non-empty and no longer than 128 UTF-8 bytes.
The returned Sandbox is an async context manager. On scope exit, async with awaits graceful shutdown only for the local run this object owns; persisted state is retained except for configured ephemeral cleanup. Detached, independently connected, and cloud resources are not stopped. Cleanup checks the captured run and cannot stop a replacement run. A cleanup failure is raised, with any body exception retained as its cause.
Creation also accepts cpu_placement, placement_profile, thp, deployment_profile and proxy through the default and context-bound factories.
Pass intercept_tls=True to enable TLS interception while preserving supplied network settings. False leaves them unchanged.
Parameters
namestr**kwargsSandboxConfigimage, cpus, memory, volumes, ports, network, proxy, secrets, detached, and more.Returns
Sandbox.create_with_progress()
Example
Example
create() but returns a PullSession that reports image preparation and local startup. This factory is synchronous; the async work happens through the session. Startup events have event_type == PullEventType.STARTUP, with phase, completed_bytes, and optional total_bytes. They distinguish backing preparation, cache waits/reuse, syncing, and activation. Preparation does not consume the activation timeout. Ignoring progress does not cancel creation; await session.result() for the outcome.
Parameters
namestr**kwargsSandboxConfigReturns
Sandbox.connect_or_create()
replace=True or replace_with_timeout raises an invalid-configuration error.
Parameters
name: reusable sandbox name, up to 128 UTF-8 bytes.**kwargs: the same creation fields accepted bySandbox.create(), used only if creation is necessary.
Returns
Sandbox
Sandbox.start()
Example
Example
Parameters
namestrdetachedboolTrue, the sandbox survives after your process exits. Default False.Returns
Sandbox.get_running()
Example
Example
Sandbox.get()
Example
Example
sb.ensure_running()
Example
Example
Sandbox.list()
Example
Example
Returns
Sandbox.list_with()
Example
Example
Parameters
cursorstr | Nonenext_cursor from the preceding page.limitint | NonelabelsMapping[str, str] | NoneNone returns every sandbox, like list().Returns
Sandbox.remove()
Example
Example
Parameters
namestrInstance methods
Command execution (exec, exec_stream, shell, shell_stream) is documented on the Execution page; SSH (ssh) on the SSH page. The lifecycle, attach, metrics, and logs methods follow.
sb.name
Example
Example
Returns
sb.id
Example
Example
sb.attach()
Example
Example
Parameters
cmdstrargslist[str] | Nonecwdstr | Noneuserstr | NoneenvMapping[str, str] | Nonedetach_keysstr | NoneReturns
sb.attach_shell()
Example
Example
Returns
sb.ping()
Example
Example
core.ping and waits for core.pong; it does not start stopped sandboxes and raises an error if the sandbox is not running or agentd cannot respond. After upgrading from a runtime that predates protocol generation 6, restart already-running sandboxes so the guest agent understands the message.
Returns
sb.touch()
Example
Example
core.touch, receives core.touched, and advances the guest activity sequence used by the runtime idle-timeout monitor. It does not start stopped sandboxes and it does not bypass max_duration.
Returns
sb.modify()
ports, preserving other mappings. Remove an
endpoint with ports_rm=[PortEndpoint(host_port=8080)]. PortEndpoint accepts optional
bind and protocol fields, defaulting to loopback TCP. Port changes require restart or
next-start policy on a running sandbox. See published port changes.
Example
Example
ModificationDisposition to classify when each change takes effect.
cpus and memory resize live within the max_cpus / max_memory ceilings; raising a ceiling requires a restart.
root_disk_size grows owned managed and flat ext4 roots live, including checkpoint-backed roots. Tmpfs root disks can change in either direction on the next boot. User-supplied disk images are rejected.
Env and workdir changes affect future execs only. Stopped roots grow before the new size is saved. Explicit restart and next-start policies remain available.
Secrets are keyed by name. Each SecretModifySpec can set one source (env, value, or store) and optional settings listed below. Omitted fields stay unchanged. Plans never include secret values. Use secrets_rm to remove secrets.
Changing a secret’s substitution rules, violation action, TLS identity requirement, or placeholder passthrough hosts requires a restart if the sandbox is running. Use policy=ModificationPolicy.RESTART to apply now, or policy=ModificationPolicy.NEXT_START to save for the next start. Omitted options keep their current settings.
The returned SandboxModificationPlan is a typed dictionary:
resize_status reports accepted after the runtime accepts each target; it does not confirm guest completion. The plan’s applied field describes applying the modification request, not usable guest capacity.
Parameters
cpusint | Nonemax_cpus.max_cpusint | Nonememoryint | Size | Nonemax_memory.max_memoryint | Size | Noneroot_disk_sizeint | NoneenvMapping[str, str] | Noneenv_rmlist[str] | NonelabelsMapping[str, str] | Nonelabels_rmlist[str] | Noneworkdirstr | NonesecretsMapping[str, SecretModifySpec] | Noneenv, value, or store, plus optional placeholder and allowed_hosts.secrets_rmlist[str] | NoneNO_RESTART (default) applies only changes that can complete without restarting; NEXT_START persists changes for the next start without mutating a running VM; RESTART restarts if needed so restart-required changes become active now.dry_runboolTrue, compute the plan without applying anything. Default False.Returns
dry_run=True.sb.modify_with_resize_tracking()
modify(). Returns plan and resize_operations, the exact requests dispatched by this call. resize_operations is None for dry runs, changes without tracked live resizes, and supported changes through older runtimes. Missing identities must not be replaced by a later current operation. The existing modify() return shape is unchanged.
Example
Example
sb.resize_operations()
id, runtime_boot_id, generation, requested_target, accepted_target, status, outcome and observation. Targets use ResourceKind.CPUS with online, or ResourceKind.MEMORY with total_mib. Status retains requested/actual/enforced quantities and convergence state. Outcome is ResizeOutcome.PENDING, APPLIED or SUPERSEDED; observation is ResizeObservation.AVAILABLE, UNSUPPORTED, PAUSED or UNAVAILABLE.
sb.wait_for_resize_operations()
timeout is seconds: None has no deadline and zero performs one bounded check. Expiry raises ResizeTimeoutError with the last completed per-resource reads; it does not undo the resize. Unsupported observation reports an error without claiming success.
The runtime retains at most 256 operation records, protecting the latest CPU and memory records from eviction. Older records can expire; restarting the runtime clears its history. Resident pause preserves the history. An expired identity cannot establish completion.
ResizeWaitError exposes reason, sandbox, operation_id and verified status. Its reasons are superseded, interrupted, history_unavailable, invalid_response and observation_unavailable; none proves rollback or final failure of the resize. Timeout and unsupported-feature errors remain separate. Unknown future peer errors retain their ordinary error mapping.
sb.resize_status()
resize_operations() when a later wait must stay bound to those records.
sb.wait_until_resized()
modify_with_resize_tracking() for a wait tied to your modification. Timeout semantics match wait_for_resize_operations().
sb.metrics()
Example
Example
Returns
sb.metrics_stream()
Example
Example
MetricsStream supports both recv() and async for.
Parameters
intervalfloat1.0.Returns
sb.logs()
Example
Example
exec.log. Backed by an on-disk JSON Lines file the runtime writes via the relay tap. Works on running and stopped sandboxes alike; there is no protocol traffic. Reading logs does not start the sandbox.
The default sources are STDOUT, STDERR, and OUTPUT (PTY-merged). Add LogReadSource.SYSTEM to include synthetic lifecycle markers and runtime/kernel diagnostic lines, or use LogReadSource.ALL as shorthand for all four. Timestamps are exposed as float ms since the Unix epoch (UTC) for parity with SandboxMetrics.timestamp_ms.
Parameters
tailint | Nonesince_msfloat | Noneuntil_msfloat | Nonesourceslist[LogReadSource] | NoneNone selects STDOUT, STDERR, and OUTPUT. Add SYSTEM to merge runtime/kernel diagnostics, or use ALL for all four.Returns
sb.log_stream()
Example
Example
LogStream. With follow=True the stream stays open and yields new entries as they are written, like tail -f. Resume an earlier stream by passing the cursor of the last entry you saw as from_cursor. Also available on Sandbox.
Parameters
sourceslist[LogReadSource] | Nonesince_msfloat | Nonefrom_cursorstr | Noneuntil_msfloat | NonefollowboolTrue, keep the stream open and yield new entries as they arrive. Default False.Returns
sb.stop()
Example
Example
timeout retains its call syntax and uses the same total budget as stop_with_timeout().
Parameters
timeoutfloat | timedelta | NoneNone waits indefinitely; expiry raises StopTimeoutError without killing.sb.stop_with_timeout()
await sb.stop_with_timeout(seconds) for an explicit total graceful-completion budget. Expiry raises StopTimeoutError; zero expires before dispatch. A delivered request may finish later, but the timeout never requests force termination.
sb.request_stop()
Example
Example
wait_until_stopped() when the caller needs to observe the terminal state.
sb.kill()
Example
Example
fsync’d may be lost, same durability semantics as a sudden power loss on a physical machine. Prefer stop() for graceful shutdown that gives the workload a chance to flush.
Parameters
timeoutfloat | timedelta | Nonesb.request_kill()
Example
Example
sb.request_drain()
Example
Example
exec calls are rejected; the sandbox transitions to stopped when all in-flight commands finish. Useful for zero-downtime rotation of worker sandboxes. Use wait_until_stopped() when you need to wait for the sandbox to stop.
sb.wait_until_stopped()
Example
Example
Returns
sb.wait_for_status()
info() for a fresh observation afterward. The observed status may change after this wait completes.
Wait without a built-in timeout until this exact sandbox reaches status. Raises SandboxReplacedError rather than following a reused name. Wrap the coroutine with asyncio.wait_for() when a deadline is required.
sb.restart()
force to kill, timeout in seconds to change how long shutdown can take, or detached for a local background start.
For a running Cloud sandbox, positive restart timeouts are rounded up to whole seconds and cannot exceed 60 seconds. Larger values fail before the restart request is sent.
sb.destroy()
SandboxReplacedError rather than deleting a same-name replacement.
sb.detach()
Example
Example
handle.snapshot()
Returns
Awaitable[Snapshot]
Patch
Factory for pre-boot root filesystem patches.Patch.text()
Example
Example
path.
Parameters
pathstrcontentstrmodeint | None0o644.replaceboolTrue, overwrite an existing path.Patch.file()
path. Use text() for UTF-8 text.
Parameters
pathstrcontentbytesmodeint | None0o644.replaceboolTrue, overwrite an existing path.Patch.append()
content to an existing file at path. If the file lives in a lower image layer, it’s copied up first.
Parameters
pathstrcontentstrPatch.mkdir()
path. Idempotent: a no-op if the directory already exists.
Parameters
pathstrmodeint | None0o755.Patch.remove()
path. Idempotent: a no-op if the path doesn’t exist.
Parameters
pathstrPatch.copy_file()
src into the guest rootfs at dst.
Parameters
srcstrdststrmodeint | None0o644. None keeps the source mode.replaceboolTrue, overwrite an existing path at dst.Patch.copy_dir()
src into the guest rootfs at dst.
Parameters
srcstrdststrreplaceboolTrue, overwrite an existing path at dst.Patch.symlink()
link pointing to target.
Parameters
targetstrlinkstrreplaceboolTrue, overwrite an existing path at link.MetricsStream
Returned by metrics_stream()
Async stream for receiving periodic metrics snapshots.metrics_stream.aiter()
async for
Returns
SandboxMetrics
metrics_stream.anext()
async for
Returns
SandboxMetrics
LogEntry
Returned by logs() · iterated from LogStream
A single captured log entry returned bylogs() or iterated from a LogStream.
entry.timestamp_ms
float
Wall-clock capture time (ms since Unix epoch, UTC)
entry.source
LogSource
Where the chunk came from
entry.session_id
int \| None
Relay-monotonic session id; None for "system" entries
entry.cursor
str
Opaque resume token; pass back via log_stream(from_cursor=...)
entry.data
bytes
The chunk’s raw bytes
entry.text()
data (lossy; invalid bytes are replaced)
Returns
str
LogStream
Returned by log_stream()
Async stream ofLogEntry values, returned by log_stream().
log_stream.aiter()
async for
Returns
LogEntry
log_stream.anext()
async for
Returns
LogEntry
PullSession
Returned by create_with_progress()
Returned bycreate_with_progress(). The factory itself is synchronous; use the returned session as an async context manager to track image pull progress.
session.progress
AsyncIterator[PullEvent]
Async iterator of pull progress events
session.result()
result() call raises RuntimeError.
Returns
Awaitable[Sandbox]
Types
SandboxConfig
Used by create() · create_with_progress()
The keyword arguments accepted bycreate() and create_with_progress(). There is no SandboxConfig object you construct directly; these are passed as **kwargs.
InitConfig
Used by create(init=…)
Custom init specification. Pass it (or one of the equivalent shorthand shapes) as theinit= kwarg to create() to hand PID 1 inside the guest off to your own init binary after agentd’s setup. Frozen dataclass. See Custom init system for image picks, shutdown semantics, and tradeoffs.
init= kwarg accepts a bare scalar for the simple case, an InitConfig dataclass, or an InitOptions typed dictionary for the rich case.
InitOptions
Used by create(init=…)
Typed-dictionary form ofInitConfig. cmd is required; args and env are optional.
SecurityProfile
Used by create(security=…)
Sandbox-wide in-guest security profile.SandboxPage
One stable, newest-first page returned bySandbox.list() or Sandbox.list_with().
SandboxPingResult
Returned by ping()
Agent reachability result.SandboxTouchResult
Returned by touch()
Explicit idle-refresh result.SandboxStopResult
Returned by wait_until_stopped()
Observed terminal sandbox state returned bywait_until_stopped().
SandboxStatus
Used by Sandbox.status · SandboxStopResult.status
Sandbox lifecycle status returned bystatus fields.
ModificationPolicy
Used by modify(policy=…)
Controls how sandbox modifications that cannot apply live are handled.SecretModifySpec
Used by modify(secrets=…)
Desired state for one secret.env, value, and store are mutually exclusive sources. Omit all three to update only the supplied policy or placeholder fields.
SandboxModificationPlan
Typed dictionary returned bySandbox.modify() and Sandbox.modify(). Config changes and secret changes use different typed shapes and are discriminated by their kind member.
ConfigPlannedChange has kind, field, change, and disposition, plus optional before, after, and reason. SecretPlannedChange has kind, field, name, change, and disposition, plus optional before_ref, after_ref, allow_hosts, and reason. Secret values never appear in a plan.
PlannedChangeKind
Discriminator for entries inSandboxModificationPlan.changes.
ChangeKind
Natural operation for a configuration change.SecretChangeKind
Natural operation for a secret change.ModificationDisposition
When or whether a planned change can take effect.ResourceKind
Resource reported by a live-resize result.ResourceConvergenceState
Observed convergence state for an accepted live resize.config()
kind, name, spec, unavailable and redacted. Read execution settings through observed["spec"]["runtime"]. Remote source identities and secret material are not reconstructed; unavailable/redacted paths are explicit. Failed lookups raise instead of returning stale data. Persisted settings may require restart to apply. See inspection result shapes.
SandboxMetrics
Returned by metrics() · metrics_stream()
Point-in-time resource usage snapshot.LogSource
Returned by LogEntry.source
Source attached to eachLogEntry.
LogReadSource
Used by logs(sources=…) · log_stream(sources=…)
Log source selector accepted bylogs() and log_stream().
LogLevel
Used by create(log_level=…)
Sandbox process log verbosity.PullPolicy
Used by create(pull_policy=…)
Controls when the SDK fetches an OCI image from the registry.RegistryAuth
Used by create(registry_auth=…)
Credentials for authenticating to a private container registry. Frozen dataclass; construct directly or viaRegistryAuth.basic(username, password).
PatchConfig
Returned by Patch.* factory methods · used by create(patches=…)
A single rootfs patch. Produced by thePatch factory; you’d normally not construct one directly. Frozen dataclass.
PatchKind
Used by PatchConfig.kind
Rootfs patch operation.PullEvent
Iterated from PullSession.progress
Native event object emitted byPullSession.progress. Inspect event_type and the fields relevant to that event; fields that do not apply to a particular event are None.
PullEventType
Discriminator returned byPullEvent.event_type.
Nested virtualization
nested_virt: bool | None controls nested virtualization for a local sandbox. Omit it to inherit configuration (off by default). See nested VM snapshots for requirements.
Storage recovery
Sandbox.recover_storage()
Parameters
selectionsMapping[str, str] | Noneaccept_selected_viewboolFalse. Required for explicit selections, which may omit writes from other disk branches.legacy_writers_stoppedboolFalse. On macOS, confirm that legacy VMs across all homes are stopped and new writers are prevented during recovery.Returns
StorageRecoveryname (string) identifies the sandbox. ready (boolean) confirms protected storage is ready, and originals_retained (boolean) confirms the original disks were retained.