Skip to content
Python OpenSandbox SDK

Python OpenSandbox SDK

Summarizes how to use the Python OpenSandbox SDK. Rather than enumerating the API reference, this article focuses on patterns that recur when using sandboxes in real services. Examples use the async API, which is the SDK’s primary surface. Based on v1.2.1.

1. Lifecycle and Connection Management

The SDK does not operate on its own — it acts as a client that forwards every request to the REST API of the OpenSandbox Server. Therefore, to use the SDK, the OpenSandbox Server address and the API Key must first be configured through ConnectionConfig. When domain and api_key are omitted, they are read from the OPEN_SANDBOX_DOMAIN and OPEN_SANDBOX_API_KEY environment variables respectively, so the API key can be injected without hardcoding it in the code.

In a single-tenant setup, the entire server shares one API key, so every caller creates sandboxes in the same space. In a multi-tenant setup, each tenant is issued its own API key, and the namespace and ownership of created sandboxes are separated by the key in use, allowing multiple teams or services to share one server in isolation.

import asyncio
from datetime import timedelta
from opensandbox import Sandbox
from opensandbox.config import ConnectionConfig

config = ConnectionConfig(
    domain="opensandbox.example.com",   # OpenSandbox Server address
    api_key="tenant-a-api-key",         # Per-tenant API key
)

async def main():
    sandbox = await Sandbox.create(
        "python:3.11",
        connection_config=config,
        timeout=timedelta(minutes=30),  # Default 10-minute TTL when omitted; None = no expiration
        env={"APP_ENV": "dev"},                    # Environment variables for the sandbox
        resource={"cpu": "1", "memory": "512Mi"},  # CPU/memory limits for the sandbox
    )
    try:
        execution = await sandbox.commands.run("python -V")
        print(execution.logs.stdout[0].text)  # e.g. Python 3.11.x
    finally:
        await sandbox.destroy()         # kill() + close()

asyncio.run(main())
[Code 1] Basic Lifecycle and Connection Management

[Code 1] shows the basic lifecycle of creating a sandbox, running a shell command, and terminating it. Every sandbox has a lifetime (timeout) at creation time; omitting it applies the default 10-minute TTL, and passing None disables expiration. Besides the lifetime, env sets environment variables and resource sets CPU/memory limits at creation time. There are two termination methods that must be distinguished: destroy(), which terminates the remote sandbox as well, and close(), which only cleans up the client-side session. Here, the session means the HTTP connection pool that the Sandbox object maintains inside the client process — separately from the remote sandbox running in the cluster — for communicating with the server and the sandbox.

  • destroy() : Terminates the remote sandbox (kill()) and then cleans up the client-side session as well. Suitable for workflows that create a sandbox, use it, and discard it right away.
  • close() : Only closes the client-side session without sending any termination request to the remote sandbox. The sandbox therefore keeps running in the cluster and holding resources until its TTL expires.
# Create a sandbox and store its ID externally (e.g. DB) —
# reattachment usually happens later or in another process
sandbox = await Sandbox.create("python:3.11", connection_config=config)
sandbox_id = sandbox.id

# Close only the client-side session — the remote sandbox keeps running
await sandbox.close()

# Reattach to the running sandbox by sandboxId (not resume)
sandbox = await Sandbox.connect(sandbox_id, connection_config=config)

# Extend lifetime: resets expiration to (now + duration)
await sandbox.renew(timedelta(minutes=30))

info = await sandbox.get_info()
print(info.status.state, info.expires_at)  # e.g. RUNNING 2026-11-29 12:30:00+00:00
[Code 2] Reattaching and Renewing

[Code 2] shows closing only the client-side session and then reattaching to the still-running sandbox to extend its lifetime. Since the remote sandbox keeps running after close(), keeping just the sandboxId allows reattaching with Sandbox.connect() — from the same process or from a separate one. Sandbox.connect() is not a resume — it attaches to a running sandbox — and renew() resets the expiration relative to the current time.

from opensandbox.models.sandboxes import SandboxLifecycle, RenewalPolicy

sandbox = await Sandbox.create(
    "python:3.11",
    connection_config=config,
    timeout=timedelta(hours=1),
    lifecycle=SandboxLifecycle(
        # Each observed access extends the expiration by 1 hour (now + 3600s)
        renewal_policy=RenewalPolicy(extend_seconds=3600),
    ),
)
[Code 3] Declaring Renew-on-Access

[Code 3] shows declaring Renew-on-Access. Instead of calling renew() explicitly on every request, declaring a renewal policy at creation time automatically extends the expiration on every access observed by the gateway/proxy. This works only if the platform operator has enabled [renew_intent] in the OpenSandbox Server configuration (config.toml).

2. Using Pools

Sandbox creation takes seconds due to pod scheduling and image pulls. A pool removes this creation latency from the request path by preparing sandboxes in advance, and it can be used in two ways: the SDK Pool, which the SDK implements itself at the client level, and the BatchSandbox Pool, where the OpenSandbox Controller maintains pre-warmed pods.

2.1. Using the SDK Pool

from opensandbox.pool import (
    AsyncSandboxPool,
    InMemoryAsyncPoolStateStore,
    PoolCreationSpec,
)

# Runs once per warmed-up sandbox before it enters the idle pool
async def prepare(sandbox):
    await sandbox.commands.run("pip install requests pandas")

pool = AsyncSandboxPool(
    pool_name="agent-pool",
    max_idle=5,                                 # Number of pre-created idle sandboxes
    state_store=InMemoryAsyncPoolStateStore(),  # Swap for the Redis store to share across clients
    connection_config=config,
    creation_spec=PoolCreationSpec(image="python:3.11"),
    warmup_sandbox_preparer=prepare,
)
await pool.start()   # Warm up idle sandboxes in the background

# Take a pre-created sandbox — no cold start on the request path
sandbox = await pool.acquire(sandbox_timeout=timedelta(minutes=30))
[Code 4] Using the SDK Pool

[Code 4] shows taking a pre-created sandbox from the SDK pool. The SDK pool pre-creates max_idle sandboxes and returns one immediately on acquire(). Since ownership of an acquired sandbox transfers to the caller, from then on it is used exactly like an ordinary sandbox, including destroy() and close().

Whatever is taken out is automatically replenished by a background reconcile process the SDK runs internally, keeping the idle count at the max_idle level, and idle sandboxes nearing their TTL are also reclaimed and replaced with new ones. When no idle sandbox is available, the default policy falls back to creating one on the spot. During the warmup stage, the warmup_sandbox_preparer hook can perform preparation work such as package installation in advance.

state_store is the store that holds the pool’s state: the list of idle sandboxes (sandboxId and expiration time), counters such as the idle count, and the primary lock that elects the replenishment owner. All state is keyed by pool_name. The bundled InMemoryAsyncPoolStateStore keeps the state in process memory, so it is for a single process only, and the idle list is lost when the process restarts. The existing idle sandboxes are not removed immediately in that case — they remain on the server holding resources, unused, until each one’s lifetime (idle_timeout, 24 hours by default) expires.

The Redis-backed AsyncRedisPoolStateStore, on the other hand, keeps the state outside the process. Processes looking at the same Redis share the same pool state just by specifying the same pool_name, so a restarted process takes over the idle list as-is, and multiple clients can share one pool. Even then, only the one client holding the primary lock performs warmup and replenishment, so no duplicate creation occurs.

The SDK pool is not a feature provided by OpenSandbox — it is implemented at the SDK level on top of the ordinary create/connect APIs. The server and the controller are therefore unaware of the pool’s existence, and the client itself is the pool’s managing entity.

2.2. Using the BatchSandbox Pool

# Allocate a pre-warmed pod from the controller-managed pool instead of creating a new pod.
# Sandbox specs (image, entrypoint, resource) are decided by the pool's pod template
sandbox = await Sandbox.create(
    connection_config=config,
    extensions={"poolRef": "prewarmed-python"},
)
[Code 5] Using the BatchSandbox Pool

[Code 5] shows allocating a sandbox from the controller-managed pool. Once the platform operator creates a Pool custom resource declaring the pre-warmed pods’ template and capacity, specifying the pool name in the creation request’s extensions.poolRef makes the controller allocate a pre-warmed pod from the pool instead of creating a new pod. Since the pod is already running, sandbox specs such as image, entrypoint, and resource are decided by the pool’s template and are omitted from the request. When the pool’s capacity is exhausted, allocation waits until capacity becomes available.

Compared to the SDK pool, this structure moves the warm-keeping and replenishment responsibility from the client to the controller. The client needs no extra infrastructure such as a state store and can use the pool with just a creation request, and multiple clients naturally share one pool. In exchange, sandbox specs cannot vary per request, and creating the pool and managing its capacity become the platform operator’s job. Also, pool allocation is exclusive to the batchsandbox workload provider path, so it is not available with the agent-sandbox provider configuration.

3. Command Execution and File Transfer

from opensandbox.models.filesystem import WriteEntry

# Upload files
await sandbox.files.write_files([
    WriteEntry(path="/workspace/main.py", data="print('hello')", mode=644),
])

# Run shell
execution = await sandbox.commands.run("cd /workspace && python main.py")

# Download a file
content = await sandbox.files.read_file("/workspace/result.json")
[Code 6] Command Execution and File Transfer

[Code 6] shows uploading a file, executing it through the shell, and downloading the resulting file. Command execution and file transfer are handled by execd injected into the sandbox pod as init, and are used in the SDK through the commands (shell) and files sub-objects of the Sandbox object.

from opensandbox.models.execd import RunCommandOpts, ExecutionHandlers

async def on_stdout(msg):
    print(msg.text, end="")

# Stream stdout of a long-running command in real time
execution = await sandbox.commands.run(
    "python train.py",
    opts=RunCommandOpts(
        working_directory="/workspace",
        timeout=timedelta(minutes=30),  # Per-command timeout, independent of the sandbox TTL
        envs={"EPOCHS": "10"},          # Environment variables for this command only
    ),
    handlers=ExecutionHandlers(on_stdout=on_stdout),
)

# Fire-and-forget: detach the command and return immediately with an execution handle.
# The command keeps running inside the sandbox (until the sandbox TTL expires),
# even if the client closes its session
background = await sandbox.commands.run(
    "python warmup.py",
    opts=RunCommandOpts(background=True),
)

# Later: fetch the detached command's output incrementally by cursor
logs = await sandbox.commands.get_background_command_logs(background.id)
print(logs.content, logs.cursor)  # e.g. warming up... 42
[Code 7] Streaming and Background Execution of Long-Running Commands

[Code 7] shows receiving the output of a long-running command in real time, and detaching a command into the background to return immediately. Since stdout/stderr can be streamed through async callbacks registered in handlers, this fits relaying an AI agent’s work logs to users in real time. Through opts, a per-command timeout can be set along with the working directory and per-command environment variables, and this timeout applies only to that command, independently of the sandbox’s lifetime (TTL).

With background=True, the call returns immediately with just an execution handle without waiting for the command to finish, and the command keeps running inside the sandbox. Output is not collected at return time; instead, it can be queried afterwards with cursor-based reads by calling commands.get_background_command_logs() with the handle’s id. Since the command runs inside the sandbox, it keeps running even if the client closes its session with close(), but it terminates together with the sandbox when the TTL expires.

4. Using Volumes

OpenSandbox provides a volume feature built on Kubernetes PVCs (PersistentVolumeClaims). It can be used in two modes: persistent PVCs, which preserve state beyond the sandbox’s lifetime, and ephemeral PVCs, per-run temporary space cleaned up along with the sandbox.

4.1. Using Persistent PVCs

from opensandbox.models.sandboxes import Volume, PVC

def workspace_volume(user_id: str) -> Volume:
    return Volume(
        pvc=PVC(
            claimName=f"ws-{user_id}",          # Fixed name derived from the session
            createIfNotExists=True,             # Server provisions the PVC on first use
            deleteOnSandboxTermination=False,   # PVC survives the sandbox
            storage="20Gi",
        ),
        mountPath="/workspace",
    )

# First session: the server provisions the PVC on first use
sandbox = await Sandbox.create(
    "python:3.11",
    connection_config=config,
    volumes=[workspace_volume(user_id)],
)

# Going idle: terminate only the sandbox — the PVC remains
await sandbox.destroy()

# Next session: recreate with the same claimName — prior state is restored at /workspace
sandbox = await Sandbox.create(
    "python:3.11",
    connection_config=config,
    volumes=[workspace_volume(user_id)],
)
[Code 8] Volume-Based State Preservation

[Code 8] shows declaring a PVC with a fixed claimName derived from the session, terminating only the sandbox when going idle, and recreating it in the next session. For workloads with long idle periods, such as AI agent sessions, keeping a sandbox alive for the entire session wastes compute for the idle time. With a persistent PVC, you can terminate the sandbox when it goes idle while leaving the state in the PVC, releasing compute, and restore the state by recreating the sandbox when it is needed again.

The server provisions the PVC automatically in the first session, and recreating a sandbox with the same claimName in later sessions mounts the existing PVC, so the prior state is restored at /workspace. In other words, releasing compute and restoring state are achieved with just termination and recreation, without any dedicated resume API.

Two things deserve attention when using volumes. First, state outside the mount path is not preserved. Packages installed into system paths by pip install disappear on recreation, so in-sandbox work should be designed to keep venvs and artifacts under the PVC path (/workspace). Second, the sandboxId changes on recreation. The mapping between sessions and sandboxes must be managed by the caller (platform backend) keyed by user_id ↔ claimName. If preservation with a stable sandboxId is required, snapshot-based pause/resume is needed, which presumes a container image registry setup.

4.2. Using Ephemeral PVCs

Volume(
    pvc=PVC(
        claimName=f"scratch-{run_id}",     # Unique per run (duplicate → 409)
        createIfNotExists=True,
        deleteOnSandboxTermination=True,   # Server deletes it on sandbox termination
        storage="5Gi",
    ),
    mountPath="/tmp/scratch",
)
[Code 9] Ephemeral Scratch Space

[Code 9] shows declaring one-off scratch space as an ephemeral PVC. A sandbox’s default writable space is the container layer, which has no capacity guarantee, and writing large amounts of data there pressures the node’s disk and can cause evictions. So for work that produces large intermediate artifacts that do not need preservation — processing large datasets, builds — it is safer to declare an ephemeral PVC and get an independent volume with a guaranteed size per run. Here, ephemeral refers to the PVC’s lifetime, not the storage medium — it does not use Kubernetes node-local ephemeral storage (emptyDir), but is a regular PVC that is deleted along with the sandbox’s termination.

When the sandbox terminates, the server cleans up the ephemeral PVC as well, so no separate cleanup is needed. An ephemeral PVC is exclusively owned by the sandbox that created it, so generate a unique claimName per run; another sandbox attempting to mount the same name is rejected with 409 CONFLICT.

5. Endpoint Access

import time

# Start an HTTP server listening on port 8000 inside the sandbox (background)
await sandbox.commands.run(
    "python -m http.server 8000",
    opts=RunCommandOpts(background=True),
)

# Resolve the externally reachable endpoint for port 8000
endpoint = await sandbox.get_endpoint(8000)
# e.g. gw.opensandbox.example.com {'OpenSandbox-Ingress-To': '<sandbox-id>-8000'}
print(endpoint.endpoint, endpoint.headers)

# Signed endpoint with a route token expiring at the given Unix time
signed = await sandbox.get_signed_endpoint(8000, expires=int(time.time()) + 600)
# e.g. gw.opensandbox.example.com
#      {'OpenSandbox-Ingress-To': '<sandbox-id>-8000-<expires>-<signature>',
#       'OpenSandbox-Secure-Access': '<per-sandbox-access-token>'}
print(signed.endpoint, signed.headers)
[Code 10] Accessing an In-Sandbox HTTP Server Endpoint

[Code 10] shows starting an HTTP server inside the sandbox and obtaining an externally reachable endpoint. When serving an HTTP server inside the sandbox, such as Jupyter or a preview server, get_endpoint() returns the access address for the port. Depending on the server’s ingress configuration, the returned address either connects directly to the sandbox or goes through the ingress gateway, and headers carries the headers required to access the endpoint. Typically it contains the OpenSandbox-Ingress-To header — route information for the ingress gateway to find the target sandbox and port to forward the request to — and it must be sent with every request. It is empty in configurations that do not need it.

When Secure Access is enabled on the server, get_signed_endpoint() returns a signed endpoint valid only until the given time, which fits temporary URLs for sharing results externally. In this case, headers additionally carries the OpenSandbox-Secure-Access header, a per-sandbox access token, and the gateway rejects requests with a missing or mismatched token.

6. Egress Restriction

from opensandbox.models.sandboxes import NetworkPolicy, NetworkRule

sandbox = await Sandbox.create(
    "python:3.11",
    connection_config=config,
    network_policy=NetworkPolicy(
        default_action="deny",
        egress=[
            # Allow only package installation paths
            NetworkRule(action="allow", target="pypi.org"),
            NetworkRule(action="allow", target="*.pythonhosted.org"),
            # Internal DB by IP/CIDR + port (requires dns+nft mode)
            NetworkRule(action="allow", target="10.0.20.0/24", ports=[5432]),
        ],
    ),
)
[Code 11] Egress Allowlist

[Code 11] shows an allowlist declaration permitting only package installation paths and an internal database. Since code running in a sandbox cannot be trusted — such as exfiltration code produced by prompt injection — declare the baseline pattern at creation time: deny all egress by default (default-deny) and allow only the required destinations through an allowlist.

Rules are divided by the target value into domain-based (FQDNs, wildcard domains) and IP-based (IPs, CIDRs) rules. A domain rule is judged by the egress sidecar’s DNS proxy at the moment the domain is looked up. At that moment, which port the connection will use is not yet decided, so domain rules cannot be combined with ports — the combination is rejected with a validation error. IP/CIDR rules, in contrast, are judged by nftables looking at actual packets, so ports can restrict TCP destination ports.

For IP/CIDR rules to actually work, however, the server needs the [egress] mode = "dns+nft" setting, which turns on nftables as well. With the default [egress] mode = "dns" setting, only the DNS proxy runs, so IP/CIDR rules are accepted without an error but are never applied. The third mode, [egress] mode = "forward", is different in nature. It evaluates no per-sandbox rules and tunnels every TCP connection of every sandbox to the designated upstream proxy. Where traffic may go is also decided by the upstream proxy, so this mode fits environments that manage destination control centrally at one shared proxy.

The upstream proxy is configured with [egress].upstream_proxy. In forward mode it is mandatory, since it is the destination every connection is tunneled to; in dns+nft mode it is optional. When set in the latter, requests that pass the sidecar’s inspection exit via the upstream proxy instead of going straight out.

# Inspect the currently applied policy
policy = await sandbox.get_egress_policy()

# Add rules while the sandbox is running
await sandbox.patch_egress_rules([
    NetworkRule(action="allow", target="api.github.com"),
])

# Remove rules by target
await sandbox.delete_egress_rules(["api.github.com"])
[Code 12] Changing Egress Rules at Runtime

[Code 12] shows inspecting and changing the egress rules of a running sandbox. The egress policy is not fixed at creation time — patch_egress_rules() adds rules and delete_egress_rules() removes them by target. This fits an interactive approval pattern that starts from a minimal allowlist and gradually opens destinations the user approves.

7. Pause/Resume

# Asynchronous request — does not become Paused immediately
await sandbox.pause()

while True:
    info = await sandbox.get_info()
    if info.status.state == "PAUSED":
        break
    await asyncio.sleep(2)

# Resume the paused sandbox (classmethod) — returns a new instance with the same sandboxId
sandbox = await Sandbox.resume(sandbox.id, connection_config=config)
[Code 13] Requesting Pause/Resume and Checking State

[Code 13] shows requesting a pause, checking the state transition, and then resuming. Pause transitions a sandbox into an idle state to release its compute resources, and resume brings the paused sandbox back with the same sandboxId. Since pause() is an asynchronous request, the sandbox does not become Paused immediately, and the transition must be checked through get_info().

The SDK’s pause() / resume() are provided as the same API, but the actual behavior and availability depend on how the server is configured to run sandboxes. How a sandbox runs is determined by server configuration — the workload provider (batchsandbox, agent-sandbox), the container runtime (runc, gVisor), and whether Fast Sandbox is used — and the client cannot tell the difference from the API call alone. Client code using pause() must therefore be aware of the semantic differences per server configuration. The behavior per server configuration is as follows.

Workload ProviderContainer RuntimePause/Resume BehaviorNotes
batchsandboxruncCommits the rootfs to a registry, then removes the podFails if no snapshot registry is configured on the controller
batchsandboxgVisorRejected with HTTP 409gVisor isolation and snapshots are incompatible
agent-sandboxruncRemoves only the pod, preserving only PVC dataNo registry required
Fast SandboxFirecracker MicroVMPreserves memory as wellAutomatic pause/wake without explicit calls via IdlePolicy (Fast Sandbox only)
# Persist a snapshot while the sandbox keeps running
snapshot = await sandbox.create_snapshot(name="before-upgrade", mode="full")

# Later: create a new sandbox restored from the snapshot
restored = await Sandbox.create(
    snapshot_id=snapshot.id,
    connection_config=config,
)
[Code 14] Creating and Restoring an Explicit Snapshot

[Code 14] shows explicitly creating a snapshot of a running sandbox and restoring a new sandbox from it. While pause is “preserve then stop”, create_snapshot() leaves a preservation point without stopping the sandbox, and restoration creates a new sandbox with Sandbox.create(snapshot_id=...) — so one preservation point can also fork multiple sandboxes as a cloning pattern. mode selects between full, which also captures memory and process state, and rootfsOnly, which keeps only the writable filesystem; availability prerequisites such as the registry setup for snapshot storage are the same as for pause.

8. Credential Vault

from opensandbox.models.sandboxes import (
    CredentialProxyConfig, Credential, InlineCredentialSource,
    CredentialBinding, CredentialMatch, CredentialAuth,
)

sandbox = await Sandbox.create(
    "python:3.11",
    connection_config=config,
    network_policy=NetworkPolicy(
        default_action="deny",  # deny every other destination
        egress=[NetworkRule(action="allow", target="api.github.com")],  # allow only the binding's host
    ),
    credential_proxy=CredentialProxyConfig(enabled=True),  # Transparent MITM injection
)

# Write the real token to the sidecar vault — the sandbox never sees it
await sandbox.credential_vault.create(
    credentials=[Credential(
        name="github-token",
        source=InlineCredentialSource(type="inline", value="ghp_realtoken..."),  # source.type
    )],
    bindings=[CredentialBinding(
        name="github-api",
        match=CredentialMatch(hosts=["api.github.com"]),
        auth=CredentialAuth(type="bearer", credential="github-token"),  # auth.type
    )],
)
[Code 15] Configuring the Credential Vault

[Code 15] shows configuring the Credential Vault, which handles external API authentication without putting real credentials into the sandbox. The real secret is written only to the egress sidecar’s vault while the sandbox runs with fake or empty values, and when an allowed HTTPS request matches a binding’s match (host, method, path), the sidecar injects the authentication header into the outgoing request via transparent MITM (man-in-the-middle). Even if code produced by prompt injection scans environment variables or the filesystem, there is no secret inside the sandbox to exfiltrate.

A credential’s source.type decides where the secret value comes from. inline in [Code 15] stores the value carried in the request directly in the vault, while exchange specifies an external endpoint instead of a value so the sidecar resolves the secret dynamically at request time. Either way, the vault query APIs return only metadata with secret values redacted.

A binding’s auth.type is a separate field from source.type, and it decides in what form the credential is injected into a request that matches the binding.

  • bearer : Injects an Authorization: Bearer <value> header.
  • basic : Injects an Authorization: Basic <value> header. The credential value must already be base64-encoded username:password.
  • apiKey : Injects the credential value into a header with the configured name.
  • customHeaders : Injects multiple headers, each backed by its own credential.
  • passthrough : Injects no auth header. Use it together with substitutions for APIs that need the credential in a path, query string, or body placeholder rather than a header.

Using the Credential Vault has three prerequisites. First, the server must run with [egress] mode = "dns+nft". DNS-only mode can be bypassed by connecting directly to an IP, so the Credential Vault activates only in the mode that also turns on nftables. Second, as in the network_policy of [Code 15], only the hosts the bindings use should be allowed and everything else must stay default-denied. Injection happens only for requests that pass the egress policy, and blocking the rest keeps requests carrying credentials from going anywhere else. Finally, credential_proxy must be enabled in the creation request, because header injection runs on top of the sidecar’s transparent MITM.

9. Monitoring

# Current resource usage (CPU, memory, I/O)
metrics = await sandbox.get_metrics()

# Diagnostic logs and events by scope
logs = await sandbox.get_diagnostic_logs(scope="all")        # container, all
events = await sandbox.get_diagnostic_events(scope="runtime")  # runtime, all

# Attach operational metadata — set a key to None to remove it
info = await sandbox.patch_metadata({"team": "sre", "ticket": None})
[Code 16] Querying Metrics and Diagnostics

[Code 16] shows querying the state of a running sandbox and managing operational metadata. get_metrics() returns CPU, memory, and I/O usage. get_diagnostic_logs() and get_diagnostic_events() return diagnostic logs and events, and the scope argument selects which area’s records to look at. The values accepted for scope are defined by the runtime (Docker, Kubernetes), and unsupported values are rejected with a 400 error. The currently supported values are:

  • container for logs : Returns the output the sandbox container wrote to stdout/stderr.
  • runtime for events : Returns the runtime’s state-change events such as container start, stop, and pause.
  • all for both : Returns every record the runtime can provide. The current backends contribute only container output to logs and only runtime events to events.

patch_metadata() attaches operational labels to the sandbox, and setting a value to None removes that key. Listing and filtering sandboxes is provided through SandboxManager.

10. Sync API

from opensandbox import SandboxSync
from opensandbox.config import ConnectionConfigSync

config = ConnectionConfigSync(
    domain="opensandbox.example.com",
    api_key="tenant-a-api-key",
)

sandbox = SandboxSync.create("python:3.11", connection_config=config)
try:
    execution = sandbox.commands.run("python -V")
    print(execution.logs.stdout[0].text)  # e.g. Python 3.11.x
finally:
    sandbox.destroy()
[Code 17] Sync API Basic Lifecycle
sandbox = SandboxSync.create(
    "python:3.11",
    connection_config=config,
    volumes=[workspace_volume(user_id)],   # Same volume declaration as [Code 8]
)
try:
    sandbox.files.write_files([
        WriteEntry(path="/workspace/note.md", data="session state", mode=644),
    ])
finally:
    sandbox.destroy()                       # The PVC remains for the next session

# Reattaching to an existing sandbox works the same
sandbox = SandboxSync.connect(sandbox_id, connection_config=config)
[Code 18] Volume-Based State Preservation with the Sync API

[Code 17] shows the same basic lifecycle as [Code 1], and [Code 18] shows volume-based state preservation, both using the sync API. In scripts, Jupyter notebooks, or environments without an async runtime, use the sync API. The method surface is identical to the async API — use SandboxSync instead of Sandbox and ConnectionConfigSync instead of ConnectionConfig, and remove the await/async keywords. The volume declaration can be reused as-is from [Code 8].

11. References