Skip to main content
Create and control a microVM sandbox: boot it from an image, run commands, stream logs and metrics, then shut it down. See Overview for configuration examples and Lifecycle for state management. For local runtime installation and verification, see Runtime setup.

Sandbox

Instance properties

sb.owns_lifecycle

Whether this handle owns the sandbox lifecycle. Local attached sandboxes returned by create() or start() own lifecycle. Local detached sandboxes, cloud sandboxes, and handles upgraded via SandboxHandle.connect() return False. This is an async property; use await sb.owns_lifecycle.

Returns

bool
True if this handle owns the lifecycle.

sb.fs

Get a filesystem handle for reading and writing files inside the running sandbox. This is a synchronous property; use sb.fs (no await). See Filesystem for API details.

Returns

Filesystem handle.

Static methods

Sandbox.create()

Create and boot a sandbox. Keyword arguments provide individual config fields; see 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 the local backend, async with guarantees cleanup: exit kills the sandbox and removes its persisted state. Cloud handles do not own the host process, so stop or remove them explicitly before leaving the context.

Parameters

namestr
Sandbox name, up to 128 UTF-8 bytes.
Configuration fields: image, cpus, memory, volumes, ports, network, secrets, detached, and more.

Returns

Running sandbox, usable as an async context manager.

Sandbox.create_with_progress()

Same parameters as create() but returns a PullSession that lets you track image pull progress before the sandbox is ready. This method is synchronous (not awaitable); the async work happens through the PullSession.

Parameters

namestr
Sandbox name, up to 128 UTF-8 bytes.
Same configuration fields as create().

Returns

Session for tracking pull progress and obtaining the final sandbox.

Sandbox.start()

Restart a previously stopped sandbox. The VM reboots using the persisted configuration.

Parameters

namestr
Name of a stopped sandbox, up to 128 UTF-8 bytes.
detachedbool
When True, the sandbox survives after your process exits. Default False.

Returns

Running sandbox.

Sandbox.get()

Get a handle to an existing sandbox (running or stopped). The handle provides status, configuration, and lifecycle control without requiring a full connection to the guest agent.

Parameters

namestr
Sandbox name, up to 128 UTF-8 bytes.

Returns

Handle with status and lifecycle control.

Sandbox.list()

Return the first page of sandboxes (running, stopped, and crashed), ordered newest first. The default page size is 20.

Returns

SandboxPage
Handles in this page and an optional cursor for the next page.

Sandbox.list_with()

Return a configured page of sandboxes. Label filters are applied before pagination and match every supplied key/value pair.

Parameters

cursorstr | None
Opaque next_cursor from the preceding page.
limitint | None
Page size from 1 through 100. Defaults to 20.
labelsMapping[str, str] | None
Label key/value pairs to match. None returns every sandbox, like list().

Returns

SandboxPage
Matching handles and an optional cursor for the next page.

Sandbox.remove()

Delete a stopped sandbox by name. See Remove for the exact local deletion scope and the external resources that are preserved. Fails if the sandbox is still running; stop it first.

Parameters

namestr
Sandbox name, up to 128 UTF-8 bytes.

Instance 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()

Return the sandbox name.

Returns

str
Sandbox name, up to 128 UTF-8 bytes.

sb.attach()

Bridge your terminal directly to a process inside the sandbox for a fully interactive PTY session. Returns the process exit code once the session ends.

Parameters

cmdstr
Command to run.
argslist[str] | None
Command arguments.
cwdstr | None
Working directory.
userstr | None
Guest user.
envMapping[str, str] | None
Environment variables.
detach_keysstr | None
Custom detach key sequence.

Returns

int
Exit code of the process.

sb.attach_shell()

Attach your terminal to the sandbox’s default shell for an interactive session.

Returns

int
Exit code.

sb.ping()

Check that the running sandbox’s guest agent is reachable without refreshing idle activity. This sends 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

Sandbox name and agent round-trip latency.

sb.touch()

Explicitly refresh the running sandbox’s idle activity. This sends 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

Sandbox name and updated activity sequence.

sb.modify()

Plan or apply a configuration change. The returned plan uses ModificationDisposition to classify when each change takes effect, and apply is all-or-nothing. cpus and memory resize live within the max_cpus / max_memory ceilings; raising a ceiling requires a restart. root_disk_size changes are offline: managed and flat OCI root disks grow only, tmpfs root disks can change in either direction on the next boot, and user-supplied disk images are rejected. Env and workdir changes affect future execs only. On a stopped sandbox, changes are saved for the next boot. Secret specs are keyed by stable secret name. Each SecretModifySpec selects at most one source (env, value, or store) and may also set placeholder and allowed_hosts; omitting a source updates only the other supplied fields. Plans expose only safe references and metadata; raw secret values never appear in a plan. Removal is explicit through secrets_rm. The returned SandboxModificationPlan is a typed dictionary: A live CPU or memory resize can take a moment to settle. The new limits are enforced immediately, and resize_status reports when the sandbox has finished adjusting.

Parameters

cpusint | None
Desired effective vCPU count. Live when within the booted max_cpus.
max_cpusint | None
Boot-time maximum possible vCPUs (restart-backed).
memoryint | None
Desired effective guest memory in MiB. Live when within the booted max_memory.
max_memoryint | None
Boot-time maximum hotpluggable memory in MiB (restart-backed).
root_disk_sizeint | None
Desired root disk size in MiB. Managed and flat OCI disks are grow-only; applies on restart or next start.
envMapping[str, str] | None
Environment variables to set for future execs.
env_rmlist[str] | None
Environment variable keys to remove.
labelsMapping[str, str] | None
Labels to set.
labels_rmlist[str] | None
Label keys to remove.
workdirstr | None
Working directory for future execs.
secretsMapping[str, SecretModifySpec] | None
Desired secret specs keyed by secret name. Each spec may contain at most one of env, value, or store, plus optional placeholder and allowed_hosts.
secrets_rmlist[str] | None
Secret names to remove explicitly.
NO_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_runbool
When True, compute the plan without applying anything. Default False.

Returns

The modification plan, applied unless dry_run=True.

sb.metrics()

Get a point-in-time snapshot of the sandbox’s resource usage: CPU, memory, disk I/O, network I/O, optional upper disk usage, and uptime.

Returns

Resource metrics.

sb.metrics_stream()

Stream resource metrics at a regular interval. The returned MetricsStream supports both recv() and async for.

Parameters

intervalfloat
Seconds between metric snapshots. Default 1.0.

Returns

Async stream yielding a snapshot each interval.

sb.logs()

Read captured output from the sandbox’s 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. The same method is available on SandboxHandle for callers that don’t want to start the sandbox first. 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 | None
Show only the last N entries after other filters apply.
since_msfloat | None
Inclusive lower bound on entry timestamp (ms since epoch).
until_msfloat | None
Exclusive upper bound on entry timestamp (ms since epoch).
Sources to include. None selects STDOUT, STDERR, and OUTPUT. Add SYSTEM to merge runtime/kernel diagnostics, or use ALL for all four.

Returns

Matching entries in chronological order.

sb.log_stream()

Stream captured log entries as a 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 SandboxHandle.

Parameters

Sources to include. Same semantics as logs().
since_msfloat | None
Inclusive lower bound on entry timestamp (ms since epoch).
from_cursorstr | None
Resume after this opaque cursor (from a prior LogEntry.cursor).
until_msfloat | None
Exclusive upper bound on entry timestamp (ms since epoch).
followbool
When True, keep the stream open and yield new entries as they arrive. Default False.

Returns

Async stream of log entries.

sb.stop()

Gracefully shut down the sandbox and wait until stopped state is observed. Lets the sandbox finish writing any pending data to disk before it exits, so files written inside the sandbox aren’t lost across a later restart. Waits up to ten seconds by default; pass timeout to override the graceful shutdown window before force-kill escalation.

Parameters

timeoutfloat | None
Seconds to wait for graceful exit before force-kill. None uses the ten-second default.

sb.request_stop()

Request graceful shutdown and return once the request is sent, without waiting for stopped state. Pair with wait_until_stopped() when the caller needs to observe the terminal state.

sb.kill()

Force-terminate the sandbox and wait until stopped state is observed. No graceful shutdown; use when the sandbox is unresponsive. Pending writes that the workload hasn’t 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 | None
Seconds to wait for the stopped state to be observed.

sb.request_kill()

Request force termination and return once the signal is sent, without waiting for stopped state.

sb.request_drain()

Request a graceful drain and return once the request is sent. Existing commands run to completion, but new 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 the caller needs stopped-state observation.

sb.wait_until_stopped()

Block until the sandbox is observed in a terminal non-running state, without triggering a stop or kill request.

Returns

Terminal status and optional observed exit code.

sb.detach()

Release the handle without stopping the sandbox. The sandbox continues running as a background process. Reconnect later with Sandbox.get().

Patch

Factory for pre-boot root filesystem patches.

Patch.text()

Write UTF-8 text content at path.

Parameters

pathstr
Absolute path inside the guest.
contentstr
Text content.
modeint | None
File mode, e.g. 0o644.
replacebool
When True, overwrite an existing path.

Patch.file()

Write arbitrary bytes at path. Use text() for UTF-8 text.

Parameters

pathstr
Absolute path inside the guest.
contentbytes
Binary file content.
modeint | None
File mode, e.g. 0o644.
replacebool
When True, overwrite an existing path.

Patch.append()

Append content to an existing file at path. If the file lives in a lower image layer, it’s copied up first.

Parameters

pathstr
Absolute path inside the guest.
contentstr
Text to append.

Patch.mkdir()

Create a directory at path. Idempotent: a no-op if the directory already exists.

Parameters

pathstr
Absolute path inside the guest.
modeint | None
Directory mode, e.g. 0o755.

Patch.remove()

Delete a file or directory at path. Idempotent: a no-op if the path doesn’t exist.

Parameters

pathstr
Absolute path inside the guest.

Patch.copy_file()

Copy a single host file at src into the guest rootfs at dst.

Parameters

srcstr
Host source file.
dststr
Absolute destination path inside the guest.
modeint | None
File mode, e.g. 0o644. None keeps the source mode.
replacebool
When True, overwrite an existing path at dst.

Patch.copy_dir()

Recursively copy a host directory at src into the guest rootfs at dst.

Parameters

srcstr
Host source directory.
dststr
Absolute destination path inside the guest.
replacebool
When True, overwrite an existing path at dst.
Create a symlink at link pointing to target.

Parameters

targetstr
What the symlink points to (literal symlink target text).
linkstr
Absolute path of the symlink itself.
replacebool
When True, overwrite an existing path at link.

SandboxHandle

Returned by Sandbox.get() · Sandbox.list() · Sandbox.list_with()

A metadata and lifecycle handle for an existing sandbox.

handle.name

str Sandbox name, up to 128 UTF-8 bytes

handle.status

SandboxStatus Current status

handle.config_json

str Raw JSON configuration

handle.created_at

float \| None Creation timestamp (ms since epoch)

handle.updated_at

float \| None Last update timestamp (ms since epoch)

handle.config()

Parsed configuration

Returns

dict[str, Any]

handle.refresh()

Re-fetch status and metadata, returning a fresh handle

Returns

Awaitable[SandboxHandle]

handle.ping()

Check agent reachability without refreshing idle activity; does not start stopped sandboxes

Returns

Awaitable[SandboxPingResult]

handle.touch()

Explicitly refresh idle activity; does not start stopped sandboxes

Returns

Awaitable[SandboxTouchResult]

handle.modify()

Plan or apply a configuration change; same kwargs as modify(). Does not start stopped sandboxes; changes persist for the next boot

Returns

Awaitable[SandboxModificationPlan]

handle.connect()

Connect to a running sandbox, optionally with an explicit timeout in seconds

Returns

Awaitable[Sandbox]

handle.start()

Start in attached or detached mode

Returns

Awaitable[Sandbox]

handle.stop()

Gracefully shut down and wait until stopped state is observed

Returns

Awaitable[None]

handle.request_stop()

Request graceful shutdown without waiting

Returns

Awaitable[None]

handle.kill()

Force terminate and wait until stopped state is observed

Returns

Awaitable[None]

handle.request_kill()

Request force termination without waiting

Returns

Awaitable[None]

handle.request_drain()

Request graceful drain without waiting

Returns

Awaitable[None]

handle.wait_until_stopped()

Block until the sandbox reaches terminal state

Returns

Awaitable[SandboxStopResult]

handle.remove()

Delete sandbox and state

Returns

Awaitable[None]

handle.metrics()

Point-in-time resource metrics

Returns

Awaitable[SandboxMetrics]

handle.logs()

Read captured exec.log (works without starting)

Returns

Awaitable[list[LogEntry]]

handle.log_stream()

Stream captured log entries (works without starting)

Returns

Awaitable[LogStream]

handle.snapshot()

Create a named snapshot of the sandbox

Returns

Awaitable[Snapshot]

MetricsStream

Returned by metrics_stream()

Async stream for receiving periodic metrics snapshots.

metrics_stream.aiter()

Use with async for

Returns

SandboxMetrics

metrics_stream.anext()

Use with async for

Returns

SandboxMetrics

LogEntry

Returned by logs() · iterated from LogStream

A single captured log entry returned by logs() 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()

Convenience: UTF-8 decode of data (lossy; invalid bytes are replaced)

Returns

str

LogStream

Returned by log_stream()

Async stream of LogEntry values, returned by log_stream().

log_stream.aiter()

Use with async for

Returns

LogEntry

log_stream.anext()

Use with async for

Returns

LogEntry

PullSession

Returned by create_with_progress()

Returned by create_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()

Await once to get the final running sandbox. A second call raises RuntimeError

Returns

Awaitable[Sandbox]

Types

SandboxConfig

Used by create() · create_with_progress()

The keyword arguments accepted by create() 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 the init= 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. The 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 of InitConfig. 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 by Sandbox.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 by wait_until_stopped().

SandboxStatus

Used by SandboxHandle.status · SandboxStopResult.status

Sandbox lifecycle status returned by status fields.

BackendKind

Used by set_default_backend() · backend_scope() · returned by default_backend_kind()

Selected sandbox backend.

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 placeholder or allowed hosts.

SandboxModificationPlan

Typed dictionary returned by Sandbox.modify() and SandboxHandle.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 in SandboxModificationPlan.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.

SandboxMetrics

Returned by metrics() · metrics_stream()

Point-in-time resource usage snapshot.

LogSource

Returned by LogEntry.source

Source attached to each LogEntry.

LogReadSource

Used by logs(sources=…) · log_stream(sources=…)

Log source selector accepted by logs() 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 via RegistryAuth.basic(username, password).

PatchConfig

Returned by Patch.* factory methods · used by create(patches=…)

A single rootfs patch. Produced by the Patch 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 by PullSession.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 by PullEvent.event_type.