BoxLite Python SDK
Python bindings for BoxLite - an embeddable virtual machine runtime for secure, isolated code execution.
Access the agent API through Box.agents
and SimpleBox.agents, including synchronous wrappers, grouped options and error handling.
On a local runtime, create an OpenCode agent and await events.opened() before
sending work when the first live event matters. Close the stream with aclose()
when finished; cancellation of a read preserves its pending event for the next read.
Upgrade notice: existing local boxes with secrets must be recreated with explicit
headers, including boxes managed by boxlite serve. See the
required-headers migration notes.
Managed checkpoints
When creating a box from a checkpoint, omit execution settings, including
explicit defaults such as detach=False, tty=False, or
advanced=AdvancedBoxOptions(privileged=False).
Explicit empty env, volumes, ports, or secrets lists also reject.
Omitted collection arguments default to None and normalize to empty lists;
ordinary image creation continues accepting empty lists.
Pass a checkpoint to the ordinary create call to use it as the source for a new
box. The checkpoint handle manages checkpoint archives. Archive import loads
local .boxlite files. The CLI form for creating a box from a checkpoint is
boxlite create --checkpoint ID [--name NAME].
CheckpointOptions(kind="disk") captures a stopped, idle source and is the
default. CheckpointOptions(kind="full") captures disk and memory from a
running source. Before requesting full capture, the SDK checks that the REST
server advertises memory_checkpoints_enabled.
On REST runtimes, runtime.checkpoints exposes async
create(source, name=None, options=None), list(), get(key), and
remove(key, force=False). SyncBoxlite.checkpoints exposes the same operations
synchronously. Checkpoints survive source deletion. CheckpointInfo.kind is
"disk", "full", or "unknown" for an unrecognized server kind.
CheckpointInfo.memory_size_bytes is None when omitted by the server and
preserves a reported zero.
checkpoint = await runtime.checkpoints.create("source", "dev-base")
worker = await runtime.create(BoxOptions(checkpoint=checkpoint.id), name="worker")
A box created from a checkpoint inherits all saved execution settings. Setting any
other BoxOptions field, including image or rootfs_path, raises an
invalid-argument error before a request is sent. A cloud capture can initially report
creating; query it until ready before use. Force removal only ignores absence.
Storage belongs to the server. Local runtime checkpoint operations, including
create with a checkpoint, raise an unsupported-operation error.
See CLI lifecycle details.
Overview
The BoxLite Python SDK provides a Pythonic API for creating and managing isolated execution environments. Built with PyO3, it wraps the Rust BoxLite runtime with async-first Python bindings.
Python: 3.10+
Platforms: macOS (Apple Silicon), Linux (x86_64, ARM64)
Key Features
- Async-first API - All I/O operations use async/await
- Context managers - Automatic cleanup with
async with
- Streaming I/O - Real-time stdout/stderr as execution happens
- Multiple box types - SimpleBox, CodeBox, BrowserBox, ComputerBox, InteractiveBox
- Resource control - Configure CPUs, memory, volumes, ports
- OCI compatible - Use any Docker/OCI image
Installation
pip install boxlite
Requires Python 3.10 or later.
Verify Installation
import boxlite
print(boxlite.__version__) # Prints installed package version
System Requirements
| Platform |
Architecture |
Requirements |
| macOS |
Apple Silicon |
macOS 12+ |
| Linux |
x86_64, ARM64 |
KVM enabled (/dev/kvm accessible) |
On Linux, verify KVM is available:
grep -E 'vmx|svm' /proc/cpuinfo # Should show CPU virtualization support
ls -l /dev/kvm # Should exist and be accessible
Quick Start
Basic Execution
import asyncio
import boxlite
async def main():
# Create a box and run a command
async with boxlite.SimpleBox(image="python:slim") as box:
result = await box.exec("python", "-c", "print('Hello from BoxLite!')")
print(result.stdout)
# Output: Hello from BoxLite!
asyncio.run(main())
Code Execution (AI Agents)
import asyncio
import boxlite
async def main():
# Execute untrusted Python code safely
code = """
import requests
response = requests.get('https://api.github.com/zen')
print(response.text)
"""
async with boxlite.CodeBox() as codebox:
# CodeBox automatically installs packages
result = await codebox.run(code)
print(result)
asyncio.run(main())
Core API Reference
Runtime Management
boxlite.Boxlite
The main runtime for creating and managing boxes.
Methods:
-
Boxlite.default() -> Boxlite
Create runtime with default settings (~/.boxlite)
-
Boxlite(options: Options) -> Boxlite
Create runtime with custom options
-
async create(box_options: BoxOptions) -> Box
Create a new box with specified configuration
-
async get(box_id: str) -> Optional[Box]
Reattach to an existing box by ID
-
async get_info(box_id: str) -> Optional[BoxInfo]
Get current metadata for a box by ID or name
-
async list_info() -> List[BoxInfo]
List all boxes (running and stopped)
-
async metrics() -> RuntimeMetrics
Get runtime-wide metrics
Example:
# Default runtime
runtime = boxlite.Boxlite.default()
# Custom runtime with different home directory
runtime = boxlite.Boxlite(boxlite.Options(home_dir="/custom/path"))
# Custom registry host with basic auth
runtime = boxlite.Boxlite(
boxlite.Options(
image_registries=[
boxlite.ImageRegistry(
host="registry.example.com",
username="user",
password="password",
)
]
)
)
# Create a box
box = await runtime.create(boxlite.BoxOptions(image="alpine:latest"))
# Reattach to existing box
box = await runtime.get("01JJNH8...")
# List all boxes
boxes = await runtime.list_info()
for info in boxes:
print(f"{info.id}: {info.state.status}")
Runtime Image Management
runtime.images holds the images a runtime can boot from: the local cache on
an embedded runtime, the server's catalog on Boxlite.rest(...). The same
code runs against either; pull is local only (a REST runtime pulls when a
box is created) and usage, create_alias and delete_alias are REST only.
runtime = boxlite.Boxlite.default()
for image in await runtime.images.list():
print(image.repository, image.tag, image.id)
detail = await runtime.images.get("docker.io/library/alpine")
print(detail.aliases, [version.digest for version in detail.versions])
await runtime.images.remove("docker.io/library/alpine")
pull fills a local cache ahead of time. A REST runtime refuses it with
UnsupportedError, because creating a box there pulls the image:
pull = await runtime.images.pull("alpine:latest")
print(pull.reference, pull.config_digest, pull.layer_count)
See the Python reference
for each method on each runtime.
Private Registry Logins
On Boxlite.rest(...), runtime.images.registries manages the logins the server
pulls private images with. The password goes up once and is never returned.
A local runtime raises UnsupportedError: pass image_registries to
boxlite.Options instead.
runtime = boxlite.Boxlite.rest(boxlite.BoxliteRestOptions.from_env())
login = await runtime.images.registries.create(
registry_host="ghcr.io",
repository_prefix="acme/", # leave out for the whole registry
username="acme-bot",
password=os.environ["GHCR_TOKEN"],
)
box = await runtime.create(boxlite.BoxOptions(image="ghcr.io/acme/private-app:1"))
...
await runtime.images.registries.remove(login.id) # refused while a box pulls through it
See the Python reference.
Runtime directory mounts (release candidate)
Directory mounts require a Linux x86_64 native Box and the native-vmm experimental feature.
Reopen an existing Box after its creator releases the runtime home, or connect through REST when boxlite serve owns that home; see creating a native Box.
from boxlite import Boxlite, MountOptions, Options
runtime = Boxlite(Options(), experimental_features="native-vmm,custom-kernel")
box = await runtime.get("dev")
if box is None:
raise LookupError("native Box 'dev' was not found")
mounted = await box.mount.add(
MountOptions(source="/srv/projects/demo", target="/workspace", read_only=True)
)
current = await box.mount.get("/workspace") # None when absent
mounts = await box.mount.list()
await box.mount.remove("/workspace")
No mount operation starts the Box: add saves a stopped Box's mount for its next start as
configured, and returns mounted on a running Box after guest confirmation. get and
list include saved mounts. remove drops a saved declaration or lazily detaches a live
mount, preserving open descriptors, and raises NotFoundError for an absent target.
The four states are described in the CLI reference.
SyncBox.mount provides the same calls without await; construct its runtime with
SyncBoxlite(Options(), experimental_features=...). SimpleBox.mount and SyncSimpleBox.mount
forward to their existing Box and raise RuntimeError before that Box exists.
For REST, enable the feature on the server; source paths refer to that server's filesystem.
Cancelling an await only stops waiting, so inspect with get or list before retrying.
Remote BoxLite server (REST)
Connect to a remote BoxLite server instead of the local runtime. Auth
uses a credential class: ApiKeyCredential is a concrete
implementation of the Credential ABC.
from boxlite import Boxlite, BoxliteRestOptions, ApiKeyCredential
rt = Boxlite.rest(
BoxliteRestOptions(
url="http://localhost:8100",
credential=ApiKeyCredential("your-api-key"),
)
)
boxes = await rt.list_info()
# Env discovery — returns None when BOXLITE_API_KEY is unset:
cred = ApiKeyCredential.from_env()
# Or read everything (BOXLITE_REST_URL + BOXLITE_API_KEY) from the env:
rt = Boxlite.rest(BoxliteRestOptions.from_env())
isinstance(ApiKeyCredential(k), Credential) is True (registered as
a virtual subclass), so code can type-check against the Credential
ABC and accept any future credential kind unchanged.
Routing prefix (vendor-agnostic)
Box-scoped requests resolve to {url}/v1/{prefix}/…. The
v1 segment is hardcoded; path_prefix is an opaque, deployment-
defined routing value that the server tells the client to use via
Principal.path_prefix from GET /v1/me. The slot's semantics
are vendor-specific: boxlite cloud uses it for the organization
id; another deployment may use a workspace name, a region+team
pair, or any other multi-segment value such as us-east/team-42.
rt = Boxlite.rest(
BoxliteRestOptions(
url="https://api.boxlite.ai",
credential=ApiKeyCredential("blk_live_…"),
path_prefix="acme", # → requests hit /v1/acme/boxes
)
)
When path_prefix is unset or empty, the client builds URLs
without the segment (/v1/boxes/…) — the canonical shape for
single-tenant deployments such as the local boxlite serve
reference server.
The CLI captures Principal.path_prefix at login and caches it
under the active profile, so subsequent boxlite commands route
correctly without an extra flag.
Box Configuration
boxlite.BoxOptions
Configuration options for creating a box.
Parameters:
image: str - OCI image URI (default: "python:slim")
cpus: float - CPU allocation (default: 1, range: 0.125–16, step: 0.001); fractions require a Linux execution host
memory_mib: int - Memory in MiB (default: 512, range: 128-65536)
disk_size_gb: int | None - Container disk size in GB, never smaller than the image (default: None, the image size)
working_dir: str - Working directory in container (default: "/root")
env: List[Tuple[str, str]] - Environment variables as (key, value) pairs
volumes: List[Tuple | Dict] - Volume mounts; a tuple is a host bind, a dict takes managed_volume (id or name) or host_path
read_only is a bool and defaults to False
network: NetworkSpec | None - Structured network configuration
ports: List[Tuple | Dict] - Local TCP forwarding; omit host_port in a dict for automatic allocation
- Protocol:
"tcp"; UDP is rejected
- Portable local/remote code uses
box.network.tunnel(("127.0.0.1", port), TunnelOptions(is_public=True));
pass False for a private cloud tunnel. Call forward() for a listener;
connections reuse the declaration and cannot undo revocation. See
private tunnel examples.
secrets - Pass inline Secret objects to overwrite configured headers on outbound HTTPS requests. With a hosted runtime, include {"secret": "openai"} to use an organization secret by name.
Secret(..., headers={"x-goog-api-key": "{value}"}) selects a raw API key header;
multiple entries share the same secret value. Each template must contain exactly one {value}.
headers is a required keyword argument; omission, None, empty maps and strings are rejected.
advanced: AdvancedBoxOptions | None - Expert-only container options
capabilities.add: List[str] - Capabilities added to BoxLite's baseline
capabilities.drop: List[str] - Capabilities removed from the resulting set
auto_delete: int | None - 0 keeps the box after stop; above 0, a REST runtime deletes it that many seconds after stop and a local runtime at stop. Default None keeps the runtime's default (auto_remove locally)
auto_remove: bool - Deprecated: use auto_delete. Auto cleanup after stop (default: True)
NetworkSpec uses:
outbound: OutboundNetworkSpec - Guest egress policy
inbound: InboundNetworkSpec - Service access policy (default: mode="disabled", unreachable from outside)
The pre-split form NetworkSpec(mode=..., allow_net=...) still works and
configures the outbound direction, positionally as well as by keyword.
Supplying it together with outbound raises ValueError. spec.mode and
spec.allow_net remain readable as views onto outbound.
allow_net restricts both TCP and UDP egress. Hostname entries are enforced by
inspecting TLS SNI / HTTP Host, which only TCP carries, so an allow_net
holding only hostnames denies all UDP egress — add the IP or CIDR to keep UDP
open. A host matched by a configured Secret is additionally reachable on port
443 without a rule of its own, so allow_net is not the only egress gate. The
connection is dialed by name, and under a non-empty allow_net an answer in a
private, loopback or CGNAT range is refused unless an IP or CIDR rule covers it.
mode="disabled" removes the guest network interface entirely.
Example:
options = boxlite.BoxOptions(
image="postgres:latest",
cpus=2,
memory_mib=1024,
disk_size_gb=10, # 10 GB disk
env=[
("POSTGRES_PASSWORD", "secret"),
("POSTGRES_DB", "mydb"),
],
volumes=[
("/host/data", "/mnt/data", True), # Read-only mount
],
ports=[
(5432, 5432, "tcp"), # PostgreSQL
],
network=boxlite.NetworkSpec(
outbound=boxlite.OutboundNetworkSpec(
mode="enabled",
allow_net=["api.openai.com"],
),
inbound=boxlite.InboundNetworkSpec(mode="disabled"),
),
advanced=boxlite.AdvancedBoxOptions(
capabilities=boxlite.ContainerCapabilities(
add=["NET_ADMIN"],
drop=["NET_RAW"],
),
),
secrets=[
boxlite.Secret(
name="openai",
value="sk-...",
hosts=["api.openai.com"],
headers={"Authorization": "Bearer {value}"},
),
],
)
box = await runtime.create(options)
Box Handle
boxlite.Box
Handle to a running or stopped box.
Properties: