Bespoke Sandbox
Run agents across providers. See their usage. Set the limits.
When agents start creating sandboxes, execution is only part of the problem. Your team also needs to know which environments are still running, where the money is going, and who can create the next GPU instance.
Bespoke Sandbox brings execution, observability, and control into one project. Use a common Python API to run code and agents across local and cloud providers. Add the self-hosted control plane to see resource usage and costs, enforce organization policies, and manage sandboxes from a shared dashboard.
Try the SDK · Run the control plane · Explore supported providers
Example Daytona + Modal workload report: runtime, idle time, and cost breakdowns.
Visibility and control, across providers
See what your agents are using
Open a sandbox to inspect its CPU and RAM history, GPU utilization and memory, execution history, and lifecycle timeline. Find the creator key, provider resource, age, and cleanup status in the inventory. Missing or stale measurements are labeled explicitly, so an unavailable metric never looks like an idle machine.
See the current per-sandbox dashboard
Actual dashboard with fixture data. Resource charts refresh every 15 seconds; available metrics depend on the provider and sandbox image.
Understand the cost of a run
Track sandbox compute spend by day, provider, or sandbox. For hosted agent runs, see input, output, and cached tokens alongside reported model costs and labeled Codex cost estimates. Compute spend and model spend remain separate, with the source and assumptions visible where they matter.
Set boundaries before resources are created
Keep provider credentials on your server and give teams organization-scoped product keys. Set concurrency limits, compute spend thresholds, allowed providers and GPU types, and maximum requested lifetimes. Creation requests are checked before provisioning; configured sandbox deadlines let the supervisor clean up attached resources even after the client disconnects.
Investigate and act from one place
Filter the inventory, inspect failed launches, review policy denials and audit events, and terminate a sandbox with the appropriate permissions. Export usage, costs, and ledger entries for analysis. Connect the direct SDK's lifecycle events to your own metrics tooling when you want execution telemetry in an existing stack.
| What you need | What you get |
|---|---|
| Visibility into resource consumption | Per-sandbox CPU/RAM charts and visible NVIDIA device metrics where supported |
| Cost attribution | Organization and sandbox compute metering, plus token/cost records from hosted agent runs |
| Control over provisioning | Scoped keys, concurrency and compute-spend checks, provider/GPU allowlists, and lifetime limits |
| An operational trail | Creation attempts, executions, errors, cleanup state, alerts, audit events, and CSV exports |
| Flexibility across providers | Common execution and file APIs, with explicit backend selection and provider-specific options |
The control plane is a service you operate. Live resource metrics require a
compatible image; model usage is captured through hosted run_agent calls.
Provider reconciliation and cleanup after a server restart require
deployment-supplied adapters. Compute budget checks apply at creation and do not
include model spend. See the setup and operating details.
Choose how to run
| Direct SDK | Self-hosted control plane | |
|---|---|---|
| Best fit | An application or agent that manages its own sandboxes | A team or platform that needs shared visibility and policies |
| Client | Sandbox / SandboxClient |
RemoteSandboxClient or HTTP |
| Provider credentials | In your application's environment | On the control-plane server |
| Operational visibility | Execution results, SDK usage, and lifecycle telemetry hooks | Dashboard, persisted usage, scoped access, policies, and audit history |
| Start here | Local quickstart | Server setup |
The direct SDK works independently of the server; its runs are not automatically uploaded to the dashboard. Both paths use explicit backend selection. You can change providers through the same interface, subject to their supported features; automatic failover and cheapest-provider routing are not implemented.
In this README: Install · Quickstart · Control plane · Providers · Agent usage and cost · API reference · Feature support · Examples · Development
Install
Use Python 3.10+ for the core SDK and 3.11+ for the control plane and its tests. The only required core dependency is Pydantic; provider SDKs are optional.
pip install bespokelabs-sandbox
For the server and a provider adapter, install the matching extras together:
pip install 'bespokelabs-sandbox[server,e2b]'
Using Sandbox alongside Curator or other Bespoke packages
Sandbox can share an environment with Curator:
python -m pip install bespokelabs-curator bespokelabs-sandbox
from bespokelabs import curator, sandbox
Each distribution owns its own subpackage. Sandbox installs only
bespokelabs/sandbox; it does not install bespokelabs/__init__.py.
The separate bespokelabs distribution is not needed for these imports.
The Nimble SDK uses the bespokelabs-nimble distribution.
For upgrades from older releases that shared the root file, use a fresh virtual
environment with namespace-compatible versions of all installed Bespoke packages.
Use python -m pip with the interpreter used by your app or notebook, and check
for old editable checkouts or a local bespokelabs.py if imports fail.
Provider installation options
pip install 'bespokelabs-sandbox[docker]'
pip install 'bespokelabs-sandbox[monty]' # local Python subset, no shell
pip install 'bespokelabs-sandbox[daytona]'
pip install 'bespokelabs-sandbox[tensorlake]'
pip install 'bespokelabs-sandbox[modal]'
pip install 'bespokelabs-sandbox[e2b]'
pip install 'bespokelabs-sandbox[ray]'
pip install 'bespokelabs-sandbox[boxd]'
pip install 'bespokelabs-sandbox[gcp-batch]' # detached jobs on Google Cloud Batch
pip install 'bespokelabs-sandbox[all]'
[all] installs all optional provider SDKs, but does not include [server]
or [dev]. Install 'bespokelabs-sandbox[server,e2b]', for example, to run
the API with E2B support. The remote HTTP client needs only the core package.
The RunPod backend has no Python extra; it uses the system OpenSSH client. The Safehouse backend also has no Python extra. Install its CLI separately on macOS:
brew install eugene1g/safehouse/agent-safehouse
Quickstart
Start with local execution. No provider account or Docker daemon is required.
from bespokelabs.sandbox import Sandbox
with Sandbox("local") as sb:
result = sb.execute_code('print("Ready to run")')
print(result.stdout)
The context manager cleans up when the block exits. Local execution runs on your host; choose Docker or a cloud provider when your workload needs that provider's isolation boundary.
Switch the backend when you are ready. With Docker running and the [docker]
extra installed:
from bespokelabs.sandbox import Sandbox
with Sandbox("docker") as sb:
result = sb.execute_code('print("hello from a container")')
print(result.stdout)
The same pattern works with configured cloud providers such as e2b, modal,
and daytona. See provider requirements and the
feature matrix for differences.
Ready for shared visibility and control? Run the control plane below and
connect through RemoteSandboxClient. For agent workloads, jump to
agent-ready sandboxes or token usage and cost.
Monty: local Python execution
Monty runs a Python subset in a local Rust interpreter worker. It needs no
provider account or Docker daemon. Install bespokelabs-sandbox[monty]
(Python 3.10+), then use the same code and file APIs:
from bespokelabs.sandbox import NetworkPolicy, Sandbox
with Sandbox(
"monty",
memory_mb=64,
timeout_secs=5,
network=NetworkPolicy(mode="none"),
files={"/data/numbers.json": "[1, 2, 3]"},
) as sb:
result = sb.execute_code(
"import json\n"
"numbers = json.loads(open('/data/numbers.json').read())\n"
"print(sum(numbers))"
)
print(result.stdout) # 6
Globals and files persist between calls in one sandbox. execute_code()
accepts python or python3 and returns captured stdout/stderr and an exit
code; trailing expression values are not printed automatically. return_type=
still parses printed JSON. SandboxClient and the async wrappers also work;
each sandbox owns a separate worker pool, closed by destroy() or context exit.
Calls on the same session are serialized.
Files live in memory through Monty's OSAccess, including writes from code
and single-file uploads/downloads. workdir is an absolute virtual POSIX
path (default /), created automatically and reset before each execution.
Relative SDK paths use that directory. env_vars exposes only supplied
values; host files, environment, network, callbacks and modules are not exposed.
Networking is always unavailable, including with the default legacy
allow_internet=True; explicit network= accepts only none.
memory_mb limits Monty's allocator usage, not worker RSS or total host memory.
timeout_secs sets the per-feed execution budget, per-turn worker deadline,
and sleep budget; it is not a single end-to-end wall-clock deadline.
Timeouts return exit code 124; guest errors return 1. A timeout, memory/output
limit, or worker crash closes the session: create a new sandbox afterward.
Ordinary syntax and runtime errors leave the session usable.
Supported backend_options are binary_path (explicit worker executable),
max_output_bytes (default 10 MiB per execution), max_file_bytes (default
50,000,000 total file-content bytes), max_recursion_depth (default 1000),
and max_suspensions (default 1000 host round trips per session). Numeric limits
must be positive; unknown options are rejected. File and output budgets are
separate from interpreter memory.
Shell commands, CLI agents, package installation, presets, git_repo, directory
transfers, executable permissions, images, CPU/GPU reservations, disk volumes,
ports, snapshots, and session reattachment are unsupported. Use files= (or
build_files_map) to seed directory contents. Monty is a language-level sandbox;
it does not provide container/VM isolation or full CPython/package compatibility.
See the upstream language limitations
and security model.
Hosted control plane
Give your users one product API key and your operators one place to manage their sandboxes. Clients send work to your control plane; it authenticates the organization, checks creation policies, calls the selected provider, and records usage against the organization and sandbox.
The dashboard brings together three views of the same workload:
- Resources: what is running, who created it, how much CPU/RAM/GPU it uses, and when it expires.
- Spend: sandbox compute costs and, for hosted agent runs, tokens and model costs with reported values and estimates clearly distinguished.
- Operations: creation failures, execution history, policy denials, alerts, audit events, and permission-controlled termination.
Use the five steps below to go from a server installation to a metered run you can inspect in the dashboard. For deployment details, keep the operations runbook and HTTP API contract alongside this guide.
This is a self-hosted service shipped in the repository. Run one API process per SQLite database: live sandbox handles are held in that process, and execution cannot resume automatically after a restart. Graceful shutdown attempts to destroy the process's attached sandboxes.
1. Install the server and provider
Install only the provider adapters enabled by this deployment. For a local and E2B development server:
pip install 'bespokelabs-sandbox[server,e2b]'
From a source checkout, use:
pip install -e '.[server,e2b]'
2. Configure and start the server
Provider credentials belong on the server. Customers never receive them.
export BESPOKE_API_KEY_PEPPER='replace-with-a-long-random-secret'
export BESPOKE_CONTROL_PLANE_ADMIN_TOKEN='replace-with-another-random-secret'
export BESPOKE_CONTROL_PLANE_DB='/absolute/path/to/bespoke-control-plane.db'
export BESPOKE_ALLOWED_BACKENDS='local,e2b'
export BESPOKE_CUSTOMER_MARKUP='1.20'
export BESPOKE_SUPERVISION_INTERVAL_SECS='30'
export BESPOKE_SESSION_COOKIE_SECURE='1'
export BESPOKE_DASHBOARD_SESSION_TTL_SECS='28800'
# Provider credential — server-side only.
export E2B_API_KEY='your-e2b-api-key'
bespokelabs-sandbox-api
Verify that it is running:
curl http://127.0.0.1:8000/healthz
# {"status":"ok"}
BESPOKE_API_KEY_PEPPER and BESPOKE_CONTROL_PLANE_DB are persistent server
identity. Keep both values unchanged across restarts. Changing the pepper or
pointing at another database makes previously issued product keys invalid.
The backend allowlist is also read at startup, so restart the server after
changing BESPOKE_ALLOWED_BACKENDS. If omitted, all registered backends are
allowed; set an explicit list for your deployment. HOST and PORT default to
127.0.0.1 and 8000. The CLI serves HTTP; terminate HTTPS at a reverse proxy
for the secure dashboard cookie.
Provider configuration, health checks, and restart recovery
Provider configuration is server-owned. The control plane reads the standard
Daytona, E2B, Modal, Runpod, Tensorlake, and boxd credential variables into memory;
it never returns their names or values through the product API. Scoped
provider-health responses expose only the backend, configured state, health
state, check time, and a fixed safe message. A configured provider remains
unchecked unless a deployment-supplied health checker actually runs; only a
successful check is reported as healthy.
The stock bespokelabs-sandbox-api CLI wires provider settings for safe
configuration visibility only. It does not construct provider health
checkers, reconcilers, or out-of-process terminators. Consequently, stock-CLI
provider health remains unchecked, reconciliation is unavailable, and a
restarted process cannot reclaim a real cloud resource whose in-memory runtime
was lost. A production deployment requiring those capabilities must instantiate
ControlPlane in deployment code and inject provider-specific health-check,
reconciler, and terminator adapters after testing them against that provider.
3. Issue the initial product API key
Issue an organization's initial product key through the protected bootstrap
endpoint. The returned secret is shown only in this response:
curl -X POST http://127.0.0.1:8000/v1/organizations \
-H "X-Control-Plane-Admin: $BESPOKE_CONTROL_PLANE_ADMIN_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"name":"Acme"}'
Copy the returned value beginning with bsk_live_. That is the customer-facing
product key. It is different from E2B_API_KEY and works across every backend
enabled by the server.
4. Run a client job
Set the product key in the client environment:
export BESPOKE_SANDBOX_KEY='bsk_live_...'
Then create and use a sandbox through the remote client:
import os
from bespokelabs.sandbox import RemoteSandboxClient
client = RemoteSandboxClient(
"http://127.0.0.1:8000",
os.environ["BESPOKE_SANDBOX_KEY"],
)
with client.create(
"e2b",
timeout_secs=60,
idempotency_key="example-launch-001",
) as sandbox:
result = sandbox.execute_code(
'print("hello from E2B")',
idempotency_key="example-job-001",
)
print(result.stdout)
print(result.usage)
# The same key can create a different provider's sandbox.
with client.create("local") as sandbox:
result = sandbox.execute_command("python", ["--version"])
print(result.stdout)
costs = client.costs(group_by="backend")
print(costs)
The run is now attributed to its organization and sandbox. Open the dashboard
in step 5 to inspect its lifecycle and compute cost. To capture model tokens and
costs as well, use the hosted run_agent workflow.
Request semantics, cost accounting, policies, and cleanup
The context manager requests sandbox destruction on exit. Creation keys are scoped to an organization: the same key and payload return the existing record, including its current status, while a different payload is rejected. Execution keys are scoped to an organization and sandbox. A completed code/command execution can return its cached response while the runtime remains attached and running; an in-progress or failed execution returns a conflict. Code/command payloads are not compared, so use a new key for each distinct command and reuse it only to retry that command. The client does not automatically retry HTTP requests. Hosted agent runs have their own persisted replay and payload checks, described in token usage and cost.
RemoteSandboxClient(..., timeout_secs=60) sets the HTTP request timeout;
client.create(..., timeout_secs=60) sets the sandbox timeout. Allow enough
HTTP time for provider creation. A client timeout does not cancel server work.
The remote surface currently supports creation, inventory (list / get),
code/command execution, run_agent, destruction, costs, and reconciliation.
Hosted run_agent records model usage for the dashboard. The remote client does
not expose the direct SDK's file transfers, Manifest, backend_options,
AgentSpec bindings, structured return_type, snapshot creation, or session resume. See the
API contract for the remaining HTTP endpoints.
Cost amounts and durations arrive as decimal strings; group_by accepts
"sandbox", "backend", or "day".
Provider failures expose a stable error contract in both HTTP responses and
RemoteSandboxError: code, backend, op, retryable, outcome, and a
small, redacted context. Sandbox responses include attempt_count,
latest_error, retry_status, cleanup_status, and provider_resource_id.
An ambiguous create has outcome="unknown" and
retry_status="blocked_cleanup_unknown"; do not issue a new provider create
until the possible orphan has been reconciled manually.
Sandbox records also expose requested, provisioning, running, stopping,
terminated, failed, and last-provider-observation timestamps. Lifecycle cost
uses the rate, currency, and pricing-source snapshot captured at creation and
accrues across the whole provider-billable window, including failed setup and
cleanup. GET /v1/reconciliation returns tenant-scoped health; an operator can
run a configured provider reconciler with
POST /v1/reconciliation/{backend} when the deployment injected that backend's
reconciler. Provider-reported cost replaces the
estimate through an idempotent delta ledger, so repeated observations do not
double-count spend. Billable-time deltas are split at UTC day boundaries, so
refreshes and later provider-cost adjustments do not move historical usage
between reporting days.
Sandbox responses also include the creating API-key ID/name and a numeric
version. GET /v1/sandboxes/{id}/detail returns the tenant-scoped creation
attempts, executions, lifecycle cost, and provider-observation history. A
termination request may send that version in If-Match; stale versions are
rejected with 409, while repeating a successful termination remains
idempotent. GET /v1/session reports the current key's scopes and whether the
dashboard may show termination controls.
Organization guardrails are managed with GET and PUT requests to
/v1/policies/current. They can cap concurrent sandboxes, rolling-hour and
UTC-day customer spend, allowed backends, allowed GPU types, and requested
sandbox lifetime. Each create request reserves its concurrency slot and checks
all limits in one database transaction before any provider call. A denial is a
stable, non-retryable policy_denied response and is attributed to the API key
that made the request. GET /v1/policy-summary returns current quota/spend and
recent denials. Redacted provider health is available from GET /v1/providers
and POST /v1/providers/{backend}/health-check.
An explicit creation timeout_secs also sets the control plane's expires_at
on every backend, independently of the provider's own timeout semantics. Omitted
values do not create a supervisor deadline, even when a preset supplies a
recommended timeout. The control-plane supervisor terminates expired sandboxes
even when the client disconnects. Its durable claim state is safe across process
restarts, and configured provider terminators can clean up resources whose
in-memory runtime was lost. Reconciliation watchdogs also remove provider resources that do not
belong to any recorded sandbox, with durable idempotency so a confirmed cleanup
is not repeated. Set BESPOKE_SUPERVISION_INTERVAL_SECS to tune the scan
interval. These restart-recovery and reconciliation behaviors require injected
terminator/reconciler adapters; the stock CLI does not supply them.
5. Inspect usage in the dashboard
Open http://127.0.0.1:8000/dashboard and
enter the bsk_live_... product key. For this plain-HTTP loopback example,
set BESPOKE_SESSION_COOKIE_SECURE=0 before starting the server so the browser
can send its session cookie. Keep the default 1 when serving over HTTPS.
Start with the sandbox you just created: inspect its lifecycle, execution result, and compute cost. For a still-running sandbox with a compatible image, its detail panel also shows live resource charts. Hosted agent runs add token and model-cost records. A local-only example records runtime with zero provider cost.
Live metrics: availability, sampling, and retention
The sandbox detail panel includes live CPU, RAM, and NVIDIA GPU charts for the
last hour. The control plane samples attached, running sandboxes every 15 seconds
independently of the lifecycle watchdog. Read the same history through
GET /v1/sandboxes/{id}/resources with both sandboxes:read and usage:read.
Dashboard refreshes read stored samples, without launching additional probes.
CPU is the average percentage of effective cgroup CPU capacity between samples;
the first sample has no CPU value. RAM is cgroup memory usage including filesystem
cache. The probe requires Python 3 and Linux cgroup v2 in the sandbox image.
Docker, Modal, Daytona, E2B, Runpod, Tensorlake, and Boxd use this probe on a
best-effort basis; missing counters or packages show unavailable. Local, Ray,
and Safehouse do not report shared host CPU/RAM as sandbox usage.
GPU charts require nvidia-smi and show visible device utilization and memory,
which can include other workloads on shared devices. Unsupported MIG counters
stay unavailable. These resource samples are separate from compute billing and
agent token costs; probes add a small amount of sandbox activity and provider
API traffic, but do not create execution-ledger entries.
The UI labels stale samples after 45 seconds, breaks chart lines across missing
data, and retains historical charts when a sandbox stops. Sampling resumes only
for attached runtimes; after a control-plane restart, historical samples remain
readable but detached sandboxes show unavailable. Storage migration 10 keeps at
most 240 samples per sandbox; an hourly sweep removes observations older than
24 hours while sampling is enabled. Set BESPOKE_RESOURCE_SAMPLING_INTERVAL_SECS
to 5–15 to adjust cadence, or 0 to disable sampling. Faster cadences shorten the
240-sample history. At most four probes run concurrently; a provider call that
exceeds ten seconds is marked unavailable and keeps its slot until it returns,
so repeated failures cannot accumulate unbounded workers.
The counter meanings follow the Linux cgroup v2 documentation and NVIDIA's monitoring documentation.
The initial organization key has every scope. A read-only dashboard key needs
both usage:read and sandboxes:read.
The dashboard provides:
- operational cards for active resources, failed launches, unreconciled spend, and resources nearing their TTL;
- budget/quota progress, backend/GPU/lifetime policy, provider health, and recent policy denials when the key has the corresponding read scopes;
- launches for keys with
sandboxes:create(choose an enabled backend and clear the form'sdashboard-cpupreset default unless your deployment has registered that custom preset); - status, provider, and creation-date filtering with client-side pagination;
- creator key, provider resource, compute/GPU, rate, age/TTL, cleanup, and reconciliation state for every sandbox;
- a detail view for lifecycle, attempts, executions, errors, cost, and provider observations;
- confirmed, revision-safe termination for keys with
sandboxes:terminate; legacysandboxes:writekeys remain compatible; and - automatic refresh every 15 seconds while the tab is visible, plus manual refresh.
The production dashboard exchanges the product key for an expiring, HTTP-only,
Secure, SameSite=Strict cookie and never stores that key in browser storage.
State-changing requests carry a session-bound CSRF token. For an explicitly
enabled local-only workflow, set BESPOKE_ENABLE_LOCAL_DASHBOARD_LOGIN=1, set
BESPOKE_SESSION_COOKIE_SECURE=0 only when serving plain HTTP on loopback, and
open /dashboard/local; that development route keeps the key in the current
tab's sessionStorage. Never expose that route on a shared network. Local
sandboxes record runtime but have a provider cost of $0; use a priced fake or
cloud backend to exercise spend counters.
The Activity view shows durable alerts and append-only audit history. Operators
with exports:read can download paginated CSV pages for usage, lifecycle costs,
and ledger entries. Dashboard export buttons download the first page of up to
500 rows; full exports require following the HTTP X-Next-Cursor header as
described in the API contract.
Alert thresholds and retention periods are tenant-owned and available through
the API. Retention defaults to 90 days for operational history and 365 days for
audit; an explicit retention request preserves usage and financial ledgers.
Security and deployment notes
API keys, browser session cookies, and CSRF tokens are HMAC-hashed at rest.
Runtime scopes are sandboxes:read,
sandboxes:create, sandboxes:execute, and sandboxes:terminate; governance
uses usage:read, policies:read, policies:write, providers:read, and
providers:write; reconciliation uses providers:reconcile; and key issuance
uses keys:write. Operational access uses alerts:read, alerts:write,
audit:read, exports:read, retention:read, and retention:write. The legacy
sandboxes:write scope grants create, execute, terminate, and provider
reconciliation for compatibility. Runtime events and provider/customer costs
are written to an idempotent ledger. All responses carry a restrictive content
security policy and browser security headers. See the
operations runbook and
hosted API contract before deployment.
Never commit the API-key pepper, admin token, provider credentials, or product keys. Revoke and replace a product key if it appears in source code, logs, or chat. Environment-variable ownership is:
| Value | Where it belongs |
|---|---|
E2B_API_KEY and other provider credentials |
Control-plane server only |
BESPOKE_API_KEY_PEPPER |
Control-plane server only; stable across restarts |
BESPOKE_CONTROL_PLANE_ADMIN_TOKEN |
Administrative bootstrap tooling only |
bsk_live_... / BESPOKE_SANDBOX_KEY |
Customer client or dashboard |
Common errors:
| Error | Resolution |
|---|---|
backend is not enabled: e2b |
Add e2b to BESPOKE_ALLOWED_BACKENDS and restart the server. |
invalid API key |
Confirm the full bsk_live_... value, database path, and original pepper. |
| Provider authentication failure | Install that provider's extra and configure its credential on the server. |
Supported Backends
Local
Local execution needs no provider account. Docker, Ray, and Safehouse have the runtime requirements listed below.
| Backend | Extra | Requires |
|---|---|---|
| Local subprocess | (none) | Python installed |
| Monty | [monty] |
Bundled Monty worker binary |
| Agent Safehouse | (none) | macOS + safehouse CLI |
| Docker | [docker] |
Docker daemon running |
| Ray | [ray] |
Ray installed (local or remote cluster) |
Cloud
| Backend | Extra | Auth |
|---|---|---|
| Daytona | [daytona] |
DAYTONA_API_KEY |
| Tensorlake | [tensorlake] |
TENSORLAKE_API_KEY or tl login |
| Modal | [modal] |
MODAL_TOKEN_ID + MODAL_TOKEN_SECRET |
| RunPod | (none) | RUNPOD_API_KEY + registered SSH key |
| E2B | [e2b] |
E2B_API_KEY |
| boxd | [boxd] |
BOXD_API_KEY |
| Google Cloud Batch (jobs only) | [gcp-batch] |
Application Default Credentials |
You only need to install the backend you use. The others are lazily imported.
Local and Ray execute subprocesses on the host or Ray worker and inherit its environment. Their workspace path rewriting is a convenience, not an OS security boundary. Safehouse wraps subprocesses with its macOS policy, while its file helpers still access the host directly. Use the isolation properties of your selected backend when deciding which workloads to run.
API Reference
Creating a Sandbox
from bespokelabs.sandbox import Sandbox
sb = Sandbox(
"local", # "local" | "safehouse" | "docker" | "ray" | "daytona" | "tensorlake" | "modal" | "runpod" | "e2b" | "boxd"
preset=None, # Preset name or SandboxPreset object
cpu=1.0, # vCPUs (Tensorlake, Modal, Docker, Daytona, RunPod, boxd)
memory_mb=1024, # RAM in MB (Tensorlake, Modal, Docker, Daytona, RunPod, boxd)
disk_mb=None, # Disk in MB (Daytona, RunPod)
gpu=None, # GPU type/count (Modal, RunPod)
timeout_secs=None, # Omitted: preset default, otherwise 600 seconds
image=None, # OCI image, or Tensorlake project image name
dockerfile=None, # Local Dockerfile to build instead of image (Docker, Daytona, Modal)
context_dir=None, # Build context for dockerfile (default: its directory)
template=None, # Template ID (E2B, RunPod)
env_vars=None, # dict of environment variables
allow_internet=True, # Legacy best-effort flag; prefer network= (see Network policy)
network=None, # NetworkPolicy: enforced egress policy, or an error
app_name=None, # App name (Modal)
snapshot_id=None, # Restore from snapshot (Tensorlake, Modal, Daytona, boxd)
workdir=None, # Sandbox root or command working directory
backend_options=None, # dict merged into the backend's native create call
files=None, # {path: bytes|str} written into the sandbox on create
git_repo=None, # repo URL cloned into the sandbox on create
git_ref=None, # branch/tag for git_repo
workspace=None, # Manifest of files/dirs/repos to materialize on create
)
Not every backend uses every parameter. Most unsupported parameters are ignored; a backend rejects values it cannot safely honor, such as network isolation on RunPod.
Modal GPU sandboxes accept Modal's GPU reservation strings, including a GPU
type such as gpu="L4" or a type and count such as gpu="H100:2":
with Sandbox("modal", gpu="A100") as sb:
result = sb.execute_command("nvidia-smi")
print(result.stdout)
GPU sandboxes can be preempted, so GPU workloads should tolerate interruption.
RunPod uses exact GPU type IDs and requires a GPU selection. Its official PyTorch image is used by default because it includes SSH support:
with Sandbox(
"runpod",
gpu="NVIDIA H100 80GB HBM3:2",
backend_options={"ssh_private_key_path": "~/.ssh/id_ed25519"},
) as sb:
result = sb.execute_command("nvidia-smi")
print(result.stdout)
For capacity fallback, pass RunPod's native creation fields through
backend_options, such as a gpuTypeIds list containing "NVIDIA L40S" and
"NVIDIA RTX A6000", with gpuTypePriority="availability". Custom images and
templates must run an SSH daemon on port 22. Add the matching public key to the
RunPod account before creating a sandbox. ssh_private_key_path is optional
when the key is already discoverable by OpenSSH.
boxd rounds cpu and memory_mb up to the smallest machine size that holds
both: 1 vCPU/4 GiB, 2/8, 4/16, or 8/32. Machines boot boxd's Ubuntu 24.04 image
with Python, Node, Docker, git, and the Claude Code, Codex, and OpenCode CLIs,
so image=, dockerfile=, and gpu= are rejected; restore a boxd snapshot
with snapshot_id, or run an image inside the machine with Docker. Every
machine is created isolated, without the in-VM boxd CLI, account integrations,
or agent logins:
with Sandbox("boxd", cpu=2, memory_mb=8192) as sb:
result = sb.execute_command("docker run --rm hello-world")
print(result.stdout)
Commands run as the boxd user, who has passwordless sudo, in /home/boxd.
/workspace is created for that user. The file helpers use boxd's file API as
that user, so a write creates missing parent directories, keeps an existing
file's mode and writes through a symlink; for root-owned paths they fall back
to sudo. env_vars are exported into each command rather than written to the
machine, so they stay out of its disk and its snapshots. boxd closes a command
that prints nothing for 30 minutes, so the adapter writes a NUL byte to stderr
every five minutes while one runs and strips it from the result.
timeout_secs is a command timeout on Local, Safehouse, Docker, Ray, and
RunPod. E2B and Modal pass it as the provider sandbox timeout; Tensorlake passes
it to create_and_connect. Daytona maps an explicit value to a wall-clock
ttl_minutes deadline, rounded up to at least one minute.
RunPod creation has a separate 10-minute default readiness timeout, adjustable
with backend_options={"create_timeout_secs": ...}. Daytona
destroys the sandbox when that deadline elapses in whatever state it is in,
running work included; no activity resets the clock, and the clock starts at
creation, so image pull and boot count against it. The mapping happens only
when you pass timeout_secs yourself. Omit it — including when a preset
supplies its own recommended value — and the Daytona sandbox gets no TTL at
all, leaving it bounded only by Daytona's default 15-minute idle auto-stop.
boxd treats an explicit value the same way, as a delete_after deadline that
the platform enforces even while the machine sleeps. Without one, a boxd
machine lives until destroy(), and hibernates after 4 hours without network
traffic.
Constructing a Sandbox creates the underlying sandbox immediately. To launch
many sandboxes on one backend, or to use async/await, see
Reusing a client across many sandboxes
and Async.
Building from a Dockerfile
Pass a local Dockerfile instead of an image name. The build context defaults to the Dockerfile's directory:
with Sandbox("daytona", dockerfile="env/Dockerfile") as sb:
sb.execute_command("cat /etc/os-release")
with Sandbox("docker", dockerfile="env/Dockerfile", context_dir=".") as sb:
...
Docker builds the image with the local daemon and leaves it untagged. Daytona
builds it declaratively (Image.from_dockerfile) as part of the create call,
so raise backend_options={"create_timeout": ...} for slow builds; it uses the
Dockerfile's directory as the context and rejects any other context_dir.
Modal uses Image.from_dockerfile. dockerfile cannot be combined with
image or snapshot_id, and with a preset it replaces the preset image, so
the preset's setup commands run. Other backends raise
FeatureNotSupportedError.
Executing Code
result = sb.execute_code('print(1 + 1)', language="python")
print(result.stdout) # "2"
print(result.stderr) # ""
print(result.exit_code) # 0
language defaults to "python". The Daytona and E2B adapters ignore this
argument and call their Python code endpoints. Other adapters invoke an
installed interpreter as <language> -c <code>; for runtimes with different
flags, use execute_command explicitly.
By default, inspect exit_code on the returned SandboxResult; a nonzero
exit is not uniformly converted into an exception. Local, Safehouse, Docker,
and Ray return exit code 124 on execution timeout. Provider/transport
failures can instead raise SandboxError subclasses.
Running Shell Commands
result = sb.execute_command("ls -la /tmp")
result = sb.execute_command("grep", args=["-r", "TODO", "/app"])
Structured output
Pass return_type to execute_code or execute_command to parse stdout into
a Pydantic model, dataclass, or class accepting keyword arguments:
from pydantic import BaseModel
from bespokelabs.sandbox import Sandbox
class Stats(BaseModel):
count: int
mean: float
with Sandbox("local") as sb:
stats = sb.execute_code(
'import json; print(json.dumps(dict(count=3, mean=2.0)))',
return_type=Stats,
)
print(stats.count, stats.mean)
# Parse existing text, including a downloaded file's decoded contents.
stats = Sandbox.parse_as('{"count": 3, "mean": 2.0}', Stats)
Parsing accepts JSON objects, including objects in Markdown fences or
surrounding text. It raises CommandFailedError if execution exited nonzero,
and SandboxExecutionError if no object can be parsed or constructed.
json_schema(Stats) generates a prompt instruction; for command calls,
inject_schema=True appends that instruction to the last item in args when
return_type is supplied. These helpers do not force the command to emit JSON.
File Operations
# List files
files = sb.list_files("/home")
for f in files:
print(f.path, f.is_dir, f.size)
# Read / write in-memory content
sb.write_file("/tmp/config.json", '{"key": "value"}')
data = sb.read_file("/tmp/config.json") # returns bytes
# Upload a local file into the sandbox
sb.upload_file("./local_data.csv", "/home/user/data.csv")
# Download a file from the sandbox to local disk
sb.download_file("/home/user/results.json", "./results.json")
# Move a whole directory tree in or out (preserves structure + executable bits).
# Defaults to a single tar.gz transfer, falling back to a per-file loop.
sb.upload_dir("~/.claude/skills/my-skill", ".claude/skills/my-skill")
sb.download_dir("/workspace/output", "./results")
Directory transfer is built on the single-file primitives above, so it works on every backend with the required shell tools. To seed a tree during creation, use
build_files_map(local, remote)withSandbox(files=...), or aManifestcontainingLocalDir. Seeexamples/move_files_into_sandbox.py.
Directory methods return the number of transferred files. Uploads skip symlinks
and empty directories. method="auto" uses tar when available, otherwise
"per_file"; the per-file download fallback does not preserve executable bits.
build_files_map and files= carry contents only. Some provider file APIs
require parent directories to exist, so create them before writing nested paths.
On macOS, COPYFILE_DISABLE=1 avoids AppleDouble metadata files in local tar
downloads.
Exposing ports
expose_port(port) returns an ExposedPort with a url that reaches a server
listening on that port inside the sandbox, plus any headers the request
needs:
import httpx
sb.execute_command("nohup python3 -m http.server 8080 >/dev/null 2>&1 &")
exposed = sb.expose_port(8080)
httpx.get(exposed.url, headers=exposed.headers)
The URLs are authenticated where the provider supports it. Daytona returns the
sandbox's preview link and keeps the sandbox private, so the link answers 401
without the X-Daytona-Preview-Token header in headers. E2B returns the
get_host address, and adds its traffic access token to headers when the
sandbox was created with restricted public traffic. Treat headers as a
secret; it is left out of repr.
Docker and Modal can only open ports at creation, and their URLs carry no
authentication. On Docker, publish the port with
backend_options={"ports": {"8080/tcp": ("127.0.0.1", None)}}; the URL points
at the host side of that mapping. On Modal, pass
backend_options={"encrypted_ports": [8080]}; the URL is the tunnel address.
Other backends raise FeatureNotSupportedError.
Declarative workspaces
files=, git_repo=, and upload_dir() cover the imperative cases. For
anything richer, pass a Manifest — a typed, ordered map of destination →
source materialized at creation (built on the primitives above, so it works on
every backend):
from bespokelabs.sandbox import Sandbox, Manifest, GitRepo, LocalDir, LocalFile, File
with Sandbox("daytona", workspace=Manifest(entries={
"repo": GitRepo("https://github.com/org/proj", ref="main"),
".claude/skills/pirate": LocalDir("~/.claude/skills/talk-like-a-pirate"),
"data/seed.csv": LocalFile("./seed.csv"),
"config.json": File('{"env": "prod"}'),
})) as sb:
...
Default creation order is git_repo clone → files → workspace entries →
preset setup (when needed). OpenCode opts into setup before workspace
materialization so npm and Git are ready before cloning. All of this happens after the provider resource exists;
setup/materialization failure triggers a cleanup attempt. Entries materialize
in insertion order, so a later one overlays an earlier one.
GitRepo clones, LocalDir / LocalFile upload (preserving the executable
bit), and File writes in-memory content. Subclass WorkspaceEntry for custom
sources, or call manifest.apply(sb) on a live sandbox.
Errors
SDK operation errors use SandboxError subclasses carrying a machine-readable
code, the backend and op when supplied, a retryable flag, outcome, and
a context dict. Branch on these fields instead of parsing message strings:
from bespokelabs.sandbox import Sandbox, SandboxError
try:
with Sandbox("daytona") as sb:
sb.execute_command("…")
except SandboxError as e:
print(e.code, e.backend, e.op, e.retryable, e.outcome, e.context)
# Decide whether retrying this operation is safe before repeating it.
Subtypes include SandboxConfigurationError, SandboxCreationError,
CommandFailedError (with exit_code / stdout / stderr),
SandboxTimeoutError and SandboxConnectionError (both retryable),
SandboxAuthenticationError, SandboxNotFoundError, WorkspaceError,
BackendNotInstalledError, and FeatureNotSupportedError. Invalid helper
arguments can still raise standard Python exceptions, such as KeyError for
an unknown preset. RemoteSandboxError is a separate HTTP-client exception
and does not inherit from SandboxError.
A retryable transport failure alone does not prove that repeating a create or
command is safe. Check outcome and cleanup state: "unknown" can mean the
provider performed the operation but its response was lost.
Agent-ready sandboxes
Sandboxes can also be bound to agents without replacing the low-level sandbox API. Agent placement is explicit:
inside: the agent process runs inside the sandbox, useful for CLI agents such as Codex CLI, Claude Code, or a custom inference runner.outside: the agent process runs outside the sandbox and drives it through capability-checked sandbox tools.
Inside-sandbox agent:
from bespokelabs.sandbox import AgentSpec, Sandbox
with Sandbox(
"docker",
preset="codex",
git_repo="https://github.com/bespokelabsai/sandbox",
) as sb:
agent = sb.agent(AgentSpec.inside(
name="codex",
command=["codex", "exec"],
cwd="sandbox",
))
result = agent.run("Run the eval suite and summarize failures")
print(result.stdout)
Outside-driver agent:
from bespokelabs.sandbox import AgentSpec, Sandbox
def run_eval(ctx, prompt: str) -> str:
ctx.write_file("/workspace/task.txt", prompt)
result = ctx.shell("python3", ["/workspace/eval.py"])
return result.stdout
with Sandbox(
"docker",
files={"/workspace/eval.py": "print('ok')"},
) as sb:
agent = sb.agent(AgentSpec.outside(
name="eval-runner",
capabilities=["shell", "files"],
runner=run_eval,
))
print(agent.run("Evaluate this input"))
For a complete Claude Code outside-sandbox example, see
examples/claude_code_outside.py. It starts
Claude Code on the host, clones a repository into a sandbox with git_repo=...,
and gives Claude a localhost bridge for running commands inside the sandbox. The
example asks Claude to count regular files directly in the cloned repository
root.
For outside agent frameworks, use agent_tools(...) directly:
with Sandbox("docker") as sb:
tools = sb.agent_tools(capabilities=["shell", "files", "patch"])
tools.write_file("/workspace/input.txt", "hello")
print(tools.shell("cat", ["/workspace/input.txt"]).stdout)
The generic context exposes shell, files, and patch operations. ports
and artifacts are accepted capability names but have no operations yet.
Capabilities gate context methods, not the sandbox OS: shell can access files,
and the runner can access the underlying sandbox through ctx.sandbox.
Inside agents accept input_mode="stdin" (default), "argv" (append the
prompt), "file" (write the prompt and append its path), or "none". They
return SandboxResult; outside agents return their runner's value. Install and
authenticate the agent CLI separately from provider authentication. Presets
install tools but do not supply agent credentials.
Token usage & cost
The hosted dashboard shows model usage separately from sandbox compute: input/output/cache token counts, reported model cost, and labeled Codex estimates. The overview follows the selected spend period; sandbox details show lifetime totals and individual runs, including unavailable/partial usage.
To collect this data, run agents through RemoteSandbox.run_agent (or
POST /v1/sandboxes/{id}/agent):
import os
from bespokelabs.sandbox import RemoteSandboxClient
client = RemoteSandboxClient(
"https://sandbox.example.com", os.environ["BESPOKE_API_KEY"],
timeout_secs=1800,
)
with client.create(
"docker", preset="codex",
env_vars={"CODEX_API_KEY": os.environ["CODEX_API_KEY"]},
) as sb:
result = sb.run_agent(
"Explain the current workspace.", harness="codex",
model="gpt-5.3-codex", extra_args=["--skip-git-repo-check"],
idempotency_key="workspace-review-1",
)
print(result.text)
print(result.agent_usage) # tokens, cost_usd, cost_state, pricing provenance
print(result.usage) # separate sandbox compute metering
Use harness="grok" with the grok preset and XAI_API_KEY to record
Grok's reported spend. JSON output is selected automatically. Hosted runs
are persisted once per idempotency key; repeating the same request returns
its saved response. A changed request with the same key is rejected.
An in-progress, failed, or interrupted request without a saved result returns
409 and is never automatically rerun, since it may already have produced side
effects or incurred costs. After a server crash, inspect the provider sandbox
and confirm the prior process has stopped before deliberately starting a new
request with a new key (and a new hosted sandbox after a control-plane restart).
The API requires sandboxes:execute; viewing model usage requires
usage:read, including fresh responses and idempotent replays. Without that
scope, RemoteAgentRunResult.agent_usage is empty. The database migration runs
automatically at server startup.
Codex estimates multiply uncached input, cache reads, and output by bundled
standard short-context API rates,
verified November 7, 2026. Supported explicit model IDs are gpt-5.3-codex,
gpt-6-astra, gpt-6.1-sol, gpt-6.1-terra, and gpt-6-luna.
Each run stores its rates and source date, so future price changes do not
rewrite history. These estimates exclude fast/long-context premiums, tool
charges, regional charges, and subscription billing. Unknown/default models,
model/provider overrides in extra_args, and missing/incomplete usage show
Unavailable, never a fabricated zero-dollar estimate.
Model costs are observational: they are not added to compute billing,
customer markup, compute budget guardrails, or existing compute CSV exports.
Direct Sandbox.run_agent calls and raw shell commands are not uploaded to
the control plane; earlier runs cannot be backfilled automatically.
run_agent supports harness="claude-code" (default), "opencode",
"grok", and "codex". Select the installation preset and runtime harness
separately. The sync and async clients expose the same options.
For Grok Build:
import os
from bespokelabs.sandbox import Sandbox
with Sandbox(
"local", preset="grok", workdir="/absolute/path/to/your/project",
env_vars={"XAI_API_KEY": os.environ["XAI_API_KEY"]},
) as sb:
result = sb.run_agent("Explain this project.", harness="grok")
print(result.text, result.usage.total_tokens, result.usage.total_cost_usd)
print(result.exit_code, result.stderr)
sb.run_agent("Which modules need tests?", harness="grok", resume=True)
The Grok preset installs @xai-official/grok via npm (Node.js 20+ required).
Docker setup installs Node.js, npm, and Git on the default Debian image before
cloning the workspace. Tensorlake uses its writable npm prefix. Other backends
need Node.js/npm and installation permissions. No prebuilt Grok image is
assumed. Local execution runs on the host; use Docker or a cloud backend for
an isolated environment.
For Codex, the existing
codex preset now works with the usage-aware helper:
with Sandbox(
"local", preset="codex", workdir="/absolute/path/to/your/project",
env_vars={"CODEX_API_KEY": os.environ["CODEX_API_KEY"]},
) as sb:
result = sb.run_agent("Explain this project.", harness="codex")
print(result.text, result.usage.total_tokens)
sb.run_agent("Which modules need tests?", harness="codex", resume=True)
Both harnesses accept model=..., command=... to override the binary, and
extra_args=[...] for CLI flags. Codex uses exec --json, and resume=True
uses exec resume --last; Grok uses --single and -c. Keep the same workspace
and the CLI's session files to resume. Authentication and tool permissions
come from the CLI configuration; the helper adds no approval-bypass flags.
Codex requires a Git working directory unless you explicitly pass
extra_args=["--skip-git-repo-check"].
Codex accepts output_format="json" or "text". Grok also accepts "plain"
("text" aliases it), "streaming-json", and "streaming-messages-json".
JSON is the default; plain output has no token/cost metadata. Streaming formats
are parsed after command completion, not delivered as live callbacks.
Usage normalization follows the CLI reports:
- Codex input includes cache reads; the SDK splits those into
input_tokens(uncached) andcache_read_tokens. Output already includes reasoning. The final completed agent message becomesresult.text. - Grok's headless input already excludes cache reads. Its output includes
reasoning, so
reasoning_tokensis not added again. Final spend overrides per-response events; interrupted streams retain completed response usage. - Grok's reported
total_cost_usdis parsed when available and complete. Standard Codex events do not report dollar cost. Missing/incomplete LLM cost stays0under the existingUsagecontract; this means unknown, not free. The direct SDK does not infer model pricing.total_cost_usdmay therefore include only estimated compute cost. - Raw events and session metadata remain in
result.raw; inspect Grok'susage_is_incomplete/cost_is_partialflags when present. stdout, stderr, exit status, and any parsed usage are retained on failure.
To run GLM through the OpenCode harness:
import os
from bespokelabs.sandbox import Sandbox
with Sandbox(
"local", preset="opencode",
env_vars={"ZHIPU_API_KEY": os.environ["ZHIPU_API_KEY"]},
) as sb:
result = sb.run_agent(
"Review this project.", harness="opencode", model="zai/glm-4.7",
)
print(result.text)
print(result.usage.total_tokens, result.usage.total_cost_usd)
For a Z.AI Coding Plan, use
model="zai-coding-plan/glm-4.7" with the same environment variable. Other
GLM models can be selected using their OpenCode provider/model identifier.
resume=True continues the latest conversation in the same workspace;
extra_args=["--session", session_id] selects a specific session.
The preset installs OpenCode at startup, requiring npm and install permissions
on the sandbox; its Docker setup installs npm and Git on the default Debian image
before cloning repositories. OpenCode opts into setup_before_workspace=True;
other presets retain setup after workspace materialization by default.
No prebuilt OpenCode image is assumed. The preset installs the CLI; select the
harness separately with harness="opencode" when calling run_agent.
OpenCode JSON step costs and token counts are summed across the run, including
cache usage and reasoning tokens (included in output_tokens). Original events
are available in result.raw["events"]; stdout, stderr and exit status are
preserved. See the runnable GLM example. Its local
workspace defaults to the Git-ignored examples/.sandbox_workdir/opencode_glm
directory and survives cleanup, so --resume works across invocations. Use
--workdir to override it. Recreating a cloud sandbox does not retain its files.
By default, run_agent(...) runs Claude Code on a prompt and reports what the run cost.
It drives the CLI with JSON output under the hood, so it can return both the
assistant's text answer and a Usage breakdown — LLM token counts and dollar
cost (from Claude Code's own total_cost_usd), plus an estimate of the sandbox
compute the call consumed (elapsed wall-clock × the backend's per-second price).
with Sandbox("local", preset="claude-code") as sb:
result = sb.run_agent("Review /code.py and suggest fixes.")
print(result.text) # the assistant's answer
u = result.usage # usage for this call
print(u.input_tokens, u.output_tokens) # token counts
print(u.llm_cost_usd) # tokens, in dollars
print(u.compute_cost_usd) # sandbox compute, in dollars
print(u.total_cost_usd) # llm + compute
# Continue the conversation; usage accumulates on the sandbox.
sb.run_agent("Now apply those fixes.", resume=True)
print(sb.usage.total_cost_usd) # running total across both calls
print(sb.usage.total_tokens)
sb.usage is the running total across every run_agent call in the sandbox's
lifetime (its compute component sums the agent-call durations, not idle time
between calls). Pass extra CLI flags with extra_args=[...]. Token counts
and llm_cost_usd reflect what the CLI's
JSON output reports, so llm_cost_usd can be 0 under subscription auth that
omits total_cost_usd (the token counts are still captured). The async
AsyncSandbox exposes the same run_agent(...) / usage. This is distinct
from bespokelabs.sandbox.pricing, which prices sandbox compute on its own.
For standalone sandbox compute estimates, use the bundled pricing helpers:
from bespokelabs.sandbox.pricing import cost_per_second, get_backend_pricing
print(get_backend_pricing("modal")) # raw bundled pricing metadata
print(cost_per_second("modal", vcpu=2.0)) # estimated $/sec for a sandbox
sb.estimate_compute_cost(elapsed_secs) estimates a measured interval using
the live session's hourly rate when available (RunPod), otherwise bundled
CPU/RAM rates. Bundled estimates omit GPU, disk, network, and other charges;
an unknown backend also returns zero, which does not establish that it is free.
Direct SDK sb.usage tracks only run_agent calls. Remote execution usage
tracks each command's runtime, while hosted cost summaries use lifecycle costs
when available, including idle time, without adding execution costs twice.
Pricing data is best-effort and local to the installed package. To compare
available backends for a real workload, see
examples/find_cheapest.py, which benchmarks
cold-start and execution time, then estimates cost with the same pricing data.
Presets
Presets are predefined sandbox configurations with setup commands that run after creation.
The built-in presets are focused on agent CLIs: codex, grok, claude-code, claude-code-codex, and opencode.
The npm-based setup commands require Node.js and npm in the execution environment when setup commands are used as a fallback.
Prebuilt Preset Images
The codex, claude-code, and claude-code-codex presets have prebuilt OCI
images published to GitHub Container Registry. grok and opencode install at
startup instead:
ghcr.io/bespokelabsai/sandbox/<preset>:v2
Docker, Daytona, and Modal use these images automatically when you pass a preset, then skip the preset's setup commands because the tools are already baked into the image.
The main advantage is that prebuilt images move setup work from sandbox startup time to image build time:
- Sandboxes start faster because they do not reinstall the same tools for every run.
- Startup is more reliable because it depends less on package registry availability during sandbox creation.
- Preset environments are more reproducible because images use pinned tags instead of a moving
latesttag.
For example, this Docker sandbox starts from ghcr.io/bespokelabsai/sandbox/codex:v2 and does not run npm install -g @openai/codex at startup:
with Sandbox("docker", preset="codex") as sb:
sb.execute_command("codex --version")
You can still override the image explicitly when you need a custom base image:
with Sandbox("docker", preset="codex", image="my-registry/codex-tools:v3") as sb:
sb.execute_command("codex --version")
An explicit image different from the preset image makes setup commands run
again, so that custom image must support the preset's installation commands.
On Local and Ray, those commands run on the host/worker and can install global
npm packages. Use Sandbox.list_presets() to inspect registered defaults.
The Dockerfiles live under images/<preset>/. Local, Safehouse, Ray, and other
backends that cannot use the prebuilt image still fall back to the preset setup
commands. RunPod deliberately does this on its SSH-ready default image.
Tensorlake image names are project-scoped, so you can build/register equivalent
images from the same Dockerfiles when you need Tensorlake-specific preset
images.
# Sandbox with Codex CLI installed
with Sandbox("docker", preset="codex") as sb:
sb.execute_command("codex --version")
# Sandbox with Claude Code installed
with Sandbox("docker", preset="claude-code") as sb:
sb.execute_command("claude --version")
# Sandbox with both Claude Code and Codex CLI installed
with Sandbox("docker", preset="claude-code-codex") as sb:
sb.execute_command("claude --version")
sb.execute_command("codex --version")
Built-in presets:
| Preset | What it installs | Defaults |
|---|---|---|
claude-code |
@anthropic-ai/claude-code via npm |
2GB RAM, 30min timeout |
claude-code-codex |
@anthropic-ai/claude-code and @openai/codex via npm |
2GB RAM, 30min timeout |
codex |
@openai/codex via npm |
2GB RAM, 30min timeout |
grok |
@xai-official/grok via npm (Node.js 20+) |
2GB RAM, 30min timeout |
opencode |
opencode-ai via npm |
2GB RAM, 30min timeout |
Non-interactive web access
The preset controls which CLI is installed in the sandbox. It does not grant the CLI permission to use its own web tools. When you run an agent inside a remote sandbox such as Daytona, preconfigure the CLI for non-interactive runs instead of waiting for an in-terminal approval prompt.
For Claude Code, WebFetch and WebSearch are permission-gated tools. Use
--permission-mode dontAsk with the narrowest --allowedTools entries that
fit the task:
agent = sb.agent(AgentSpec.inside(
name="claude",
command=[
"claude",
"-p",
"--permission-mode",
"dontAsk",
"--allowedTools",
"WebFetch(domain:github.com)",
"WebSearch",
],
input_mode="argv",
))
result = agent.run("Summarize https://github.com/bespokelabsai/sandbox")
For Codex CLI, use codex exec with explicit approval, sandbox, and search
settings. For read-only website summaries, keep the Codex sandbox read-only,
disable approval prompts, and enable live search:
agent = sb.agent(AgentSpec.inside(
name="codex",
command=[
"codex",
"exec",
"--ask-for-approval",
"never",
"--sandbox",
"read-only",
"--search",
],
input_mode="argv",
))
result = agent.run("Summarize https://github.com/bespokelabsai/sandbox")
Use broader modes only when the outer sandbox is the trust boundary. For
example, codex exec --sandbox workspace-write --ask-for-approval never lets
Codex edit files without pausing, and Claude Code's --permission-mode bypassPermissions skips most permission prompts. Those modes are best kept to
isolated sandboxes with scoped credentials.
Create your own:
from bespokelabs.sandbox import Sandbox, SandboxPreset
Sandbox.register_preset(SandboxPreset(
name="my-stack",
description="My custom environment",
setup_commands=["pip install my-library", "npm install -g my-tool"],
cpu=2.0,
memory_mb=4096,
))
with Sandbox("docker", preset="my-stack") as sb:
...
Explicit kwargs always override preset defaults.
Workspace convenience arguments
Populate the sandbox at creation instead of scripting uploads afterwards.
files are written after any git_repo clone. Preset setup normally follows
workspace materialization; OpenCode runs setup first to install its prerequisites.
files needs nothing special and works on every backend and image:
with Sandbox(
"docker",
image="python:3.12-slim",
files={"/work/run.py": "print('ready')"},
) as sb:
print(sb.execute_command("python", ["/work/run.py"]).stdout)
files values may be str or bytes.
git_repo runs git clone inside the sandbox, so git must be present in
the image. All prebuilt preset images include git, so git_repo works with
any preset on Docker/Daytona/Modal. For a custom image, make sure git is
installed; the host-based backends (local, safehouse) use the host's git.
with Sandbox(
"local",
git_repo="https://github.com/psf/requests",
git_ref="main", # optional branch/tag
) as sb:
entries = sb.list_files("/requests") # local workspace root / repo name
print(f"cloned {len(entries)} entries")
git_repo= clones into a relative <repo-name> under the command working
directory; the location is not always /<repo-name> on cloud backends. Use
Manifest(entries={"/explicit/path": GitRepo(...)}) to choose a destination.
For Local and Safehouse, workdir is a host directory: an explicit directory
survives destroy(), while an automatically created temporary directory is
removed. Daytona and Tensorlake use workdir for shell commands only; their
code and file APIs keep provider path semantics. RunPod defaults command
execution to /workspace, while its file helpers use SSH path semantics.
boxd runs commands in /home/boxd unless workdir is set, and resolves
relative file paths there.
Docker, Modal, E2B, and Ray do not map the top-level workdir option.
Network policy
network= sets an egress policy that the backend enforces or refuses:
from bespokelabs.sandbox import NetworkPolicy, Sandbox
hub_only = NetworkPolicy(mode="allowlist", domains=["8080-abc.daytonaproxy01.net"])
with Sandbox("daytona", network=hub_only) as sb:
...
sb.set_network(NetworkPolicy(mode="none")) # cut egress mid-run
sb.set_network(NetworkPolicy()) # back to public
mode is "public" (the default), "none", or "allowlist" with domains
and/or cidrs. A backend that cannot enforce the requested mode raises
FeatureNotSupportedError instead of creating an open sandbox. public is
accepted everywhere.
- Daytona: every mode, at creation and through
set_network(). Allow-lists take domains or IPv4 CIDRs, not both. Preview hosts share proxy IPs, so a CIDR that reaches one preview host reaches all of them; allow a preview host by domain, which Daytona filters by SNI. - Modal: every mode at creation (
block_network,outbound_cidr_allowlist,outbound_domain_allowlist).set_network()uses Modal's experimental outbound policy API and supportspublicandallowlist, notnone. - Docker and Tensorlake:
publicandnoneat creation. - boxd: every mode, at creation and through
set_network(), as an egress allow-list. HTTP and HTTPS are admitted by hostname and other traffic by address, so a CIDR does not open HTTPS to a bare IP in it.noneadmits nothing: DNS lookups fail and every connection is dropped. The policy is enforced beforeSandbox(...)orset_network()returns.
allow_internet keeps its old best-effort behavior (see the matrix) for
compatibility. Passing both network and allow_internet is an error; with
network, allow_internet is derived from it.
Backend-specific options
backend_options is an escape hatch: the dict is merged into the backend's
native creation call, so you can reach provider features the unified API
doesn't model — without waiting for a new keyword. It is forwarded to Docker
containers.run, Modal Sandbox.create, E2B Sandbox.create, Tensorlake
create_and_connect, Daytona's create params, the RunPod REST creation
payload, and boxd machines.create; ignored by local, safehouse, and ray.
# e.g. set the container hostname (a Docker-only knob)
with Sandbox("docker", backend_options={"hostname": "build-box"}) as sb:
sb.execute_command("hostname")
On Daytona, env_vars given here is merged over the env_vars= parameter
rather than replacing it, and create_timeout (seconds) is consumed by the SDK
adapter to bound the create call itself instead of being passed as a sandbox
parameter.
On RunPod, transport-only options are consumed by the adapter rather than sent
to the REST API: create_timeout_secs, api_timeout_secs,
poll_interval_secs, ssh_private_key_path, ssh_user,
ssh_connect_timeout_secs, ssh_strict_host_key_checking, and
ssh_known_hosts_file. Other keys use RunPod's native camelCase field names.
On boxd, name, name_prefix, ready_timeout_secs, snapshot_timeout_secs,
and auto_hibernate_timeout are consumed by the adapter. Other keys are
machines.create arguments such as org, labels, auto_destroy_timeout,
or idle_ignore_outbound; an unknown key is rejected before anything is
created. isolated cannot be turned off.
Session state (resume)
A snapshot saves state to restore later; session state is a lightweight, serializable handle that reattaches to a sandbox that is still running — including from another process or machine:
sb = Sandbox("e2b", timeout_secs=600)
sb.execute_command("echo hi > /tmp/work.txt")
state = sb.session_state()
blob = state.to_json() # JSON-safe; stash in a queue/DB/file
# ... do NOT destroy sb — the sandbox must stay alive to reattach ...
# Elsewhere — another worker, another process:
from bespokelabs.sandbox import Sandbox, SandboxSessionState
sb2 = Sandbox.resume(SandboxSessionState.from_json(blob))
print(sb2.read_file("/tmp/work.txt")) # b"hi\n"
SandboxClient("e2b").resume(state) is equivalent; an existing client can
reuse its provider connection.
Resume skips preset setup and workspace materialization. Provider credentials
must be available in the resuming process; host-directory sessions require the
same accessible directory. Session state is not a complete configuration or
usage checkpoint: wrapper configuration and cumulative agent usage reset on
resume. Local, Safehouse, and boxd state include the supplied environment
overlay, which may contain secrets. Resuming a boxd machine that is in standby,
hibernated, or stopped wakes it first. Both attached handles refer to the same resource, so
destroying either affects the other.
| Backend | Resume by | session_state payload |
|---|---|---|
| Docker | container id (containers.get) |
container_id |
| E2B | sandbox id (Sandbox.connect) |
sandbox_id |
| Modal | sandbox id (Sandbox.from_id) |
sandbox_id |
| Tensorlake | sandbox id (client.connect) |
sandbox_id |
| Daytona | sandbox id (client.get) |
sandbox_id, workdir (when set) |
| RunPod | Pod id (GET /pods/{id}) |
pod_id, workdir and SSH transport settings |
| boxd | machine id (machines.get) |
machine_id, workdir, env vars, org |
| Local, Safehouse | host workdir | workdir, env overlay |
| Ray | — (not supported) | raises FeatureNotSupportedError |
Listing sandboxes by label
SandboxClient.list_sandboxes(labels) returns the sandboxes that carry all
of the given labels, on Daytona (resource labels) and Modal (sandbox tags).
Each SandboxListing has the provider id, the sandbox's own labels, the raw
provider state, the creation time when the provider reports one (None on
Modal), and a session_state to pass to resume(), for example to destroy a
sandbox nobody owns any more:
client = SandboxClient("daytona")
for found in client.list_sandboxes({"team": "research", "run": "42"}):
client.resume(found.session_state).destroy()
At least one non-empty label is required, so an unfiltered listing is
refused. A provider failure raises; a partial list is never returned. Daytona
lists sandboxes in any state (a stopped one's session can be destroyed, not run
in, until it is started); Modal lists running ones only. On a Modal SDK that
cannot read tags back, labels is only the matched filter and
labels_complete is False. Other backends raise FeatureNotSupportedError.
Detached jobs (Google Cloud Batch)
A job runs one command to completion without the submitting process staying
attached, like an AWS Batch job. Jobs run on the gcp_batch backend, as
Google Cloud Batch jobs on GCP VMs; every other backend raises
FeatureNotSupportedError ("does not support jobs") from the job methods.
Submit returns a job id at once; the job keeps running if your process exits,
and any process holding the id can check on it, wait for it, read its logs,
or cancel it. This is the reattach path for a worker that restarts mid-job.
from bespokelabs.sandbox import JobSpec, SandboxClient
client = SandboxClient("gcp_batch")
job_id = client.submit_job(JobSpec(
command=["python", "train.py", "--epochs", "3"], # argv, or a shell string
image="us-docker.pkg.dev/my-project/repo/trainer@sha256:...",
env_vars={"WANDB_API_KEY": key}, # exported for the command
cpu=4, memory_mb=8192, timeout_secs=2 * 3600,
labels={"team": "evals"},
backend_options={"project": "my-project", "region": "us-central1"},
))
# ... store job_id (a plain string) anywhere ...
# Later, possibly in a new process:
client = SandboxClient("gcp_batch")
status = client.wait_job(job_id, timeout_secs=3 * 3600, poll_secs=30,
on_poll=lambda s: print(s.state.value))
print(status.state, status.exit_code, status.reason)
print(client.job_logs(job_id, tail=100)) # combined stdout + stderr
client.cancel_job(job_id) # stop it
| Method | Returns |
|---|---|
submit_job(spec: JobSpec) |
job id (str) |
job_status(job_id) |
JobStatus |
wait_job(job_id, timeout_secs=None, poll_secs=10.0, *, on_poll=None) |
terminal JobStatus; SandboxTimeoutError if timeout_secs passes first |
job_logs(job_id, tail=None) |
combined stdout/stderr (str), or its last tail lines |
cancel_job(job_id) |
JobStatus after the cancel request |
AsyncSandboxClient has the same methods as coroutines; its wait_job sleeps
on the event loop and accepts a coroutine on_poll.
JobStatus.state is a JobState: pending, running, succeeded,
failed, cancelled or unknown. succeeded and failed normally come from the
command's own exit code (reason="timeout" when timeout_secs stopped it);
Cloud Batch can also fail a job whose command never ran, with
exit_code=None and reason="batch_failed".
unknown is terminal and means the outcome can no longer be established: the
Batch job is gone (reason="job_not_found"). It is never reported as success.
JobStatus.done is true for every terminal state; started_at /
finished_at are UTC datetimes when known, and details carries provider
facts such as the raw Batch state (details["batch_state"]) and, on
gcp_batch, the job's labels as Batch stored them (details["labels"]), so a
caller can check a job is one it started before it cancels it.
wait_job rides out provider hiccups: before the job has been seen, four
consecutive failed reads are retried and the fifth raises; once it has been
seen, failed reads are retried with backoff (capped at 60s) until the deadline. Configuration,
authentication and not-installed errors raise at once.
How a Batch job runs. SandboxClient("gcp_batch") runs each job as a Batch
job with one container task; interactive Sandbox("gcp_batch") raises
FeatureNotSupportedError. The job id is the job's resource name,
projects/<project>/locations/<region>/jobs/<id>. image is any container
URI the VMs can pull (e.g. Artifact Registry); cpu / memory_mb become the
task's compute resource, disk_mb the boot disk, timeout_secs its
maxRunDuration, env_vars its environment, labels the job's and VMs'
labels (coerced to GCP label syntax; keys that collide once coerced
are rejected), workdir the container's --workdir,
and allow_internet=False blocks the container's external network. gpu
takes L4, T4, V100, P100, P4, A100, A100-80GB, H100,
H200, B200 or a Compute Engine type such as nvidia-l4, optionally with
:<count>; Batch installs the driver, and the smallest machine type with that
GPU count that fits cpu and memory_mb is chosen (H100 counts below 8 need
provisioning_model SPOT or FLEX_START). An accelerator-optimized machine
type (A2, A3, A4, G2) carries its GPUs, so the job names only the machine type;
T4, V100, P100 and P4 attach to an N1 VM as accelerators. GPUs reach the
container through Batch's own driver install; check that the image sees them
(nvidia-smi) before relying on it, and add --gpus all through
container_options if it does not. Pin an image by digest (.../repo/image@sha256:...) to run exactly what was
built. Status maps Batch's job state;
the exit code comes from the task, and Batch's reserved exit codes become
reasons (50005 is "timeout", 50001 "vm_preempted", ...). Logs are read
from Cloud Logging (batch_task_logs, by job uid) and may lag a few seconds.
cancel_job uses Batch's CancelJob on a pending or running job and keeps its
record. Batch cancels asynchronously, so cancel_job (and job_status)
return running with reason="cancelling" while it stops the VMs, then
job_status reads cancelled; wait_job after cancel_job to confirm. If
the installed SDK or the service lacks CancelJob, the job is deleted instead
(reason="deleting", again what job_status says while Batch deletes it)
and later reads as unknown /
"job_not_found". When Batch reports an event description, the status
carries the latest one in details["message"] (for a failure, why it failed:
the task's exit, or the job-level cause when no task exited); the key is
absent when Batch has given none, so read it with details.get("message"). Files reach the job through the
image or Cloud Storage. Credentials are Application Default Credentials.
backend_options key |
Meaning |
|---|---|
project, region |
Where to submit (else GOOGLE_CLOUD_PROJECT, and GOOGLE_CLOUD_REGION or CLOUDSDK_COMPUTE_REGION) |
service_account |
Service account email the VMs run as (it needs Artifact Registry read and whatever the job touches, e.g. GCS) |
service_account_scopes |
OAuth scopes for that service account (list) |
network, subnetwork |
VPC network and subnetwork for the VMs (projects/<p>/global/networks/<n>, projects/<p>/regions/<r>/subnetworks/<s>) |
no_external_ip |
True gives the VMs no external IP; the subnet then needs Private Google Access (Artifact Registry, GCS) or Cloud NAT |
machine_type |
Overrides the chosen machine type |
provisioning_model |
STANDARD, SPOT, PREEMPTIBLE or FLEX_START |
allowed_locations |
e.g. ["zones/us-central1-a"] |
max_retry_count |
Task retries (default 0) |
container_options |
Extra docker run options |
gpu_driver_version |
GPU driver version for Batch to install |
job_id, job_id_prefix |
Explicit Batch job id, or its prefix (default job) |
Snapshots
snap = sb.snapshot()
print(snap.snapshot_id)
# Restore later
sb2 = Sandbox("tensorlake", snapshot_id=snap.snapshot_id)
| Backend | Snapshot support |
|---|---|
| Docker | Yes (container.commit()) |
| Tensorlake | Yes (filesystem + memory) |
| Modal | Yes (filesystem) |
| boxd | Yes (memory and disk, running processes included) |
| Daytona, E2B, Local, Ray, RunPod, Safehouse | No |
Restore a Docker snapshot using image=snap.snapshot_id; Docker does not map
snapshot_id. Modal, Tensorlake, and boxd accept snapshot_id; boxd snapshots
outlive the sandbox, so remove them with boxd snapshot remove when you are
done. Daytona can create
from an existing provider snapshot via snapshot_id, although this adapter
cannot create snapshots with snapshot().
Lifecycle
# Context manager (recommended) — auto-destroys on exit
with Sandbox("local") as sb:
sb.execute_code("print('hi')")
# Manual cleanup
sb = Sandbox("docker")
sb.execute_code("print('hi')")
sb.destroy()
# Check state
sb.is_alive # True/False
sb.backend_name # "docker"
sb.provider_resource_id # provider ID, or None for local-style backends
is_alive tracks whether this wrapper has been destroyed; it does not poll the
provider or detect external termination. Cleanup behavior varies by adapter:
some suppress provider deletion errors. Use provider inventory or configured
control-plane reconciliation when you need confirmation of resource removal.
Reusing a client across many sandboxes
Sandbox(backend, ...) builds a fresh provider connection per sandbox. When
launching many sandboxes on one backend, create a SandboxClient once and
reuse it — provider-level state (the Docker daemon connection, Daytona auth,
the Ray runtime) is shared across create() calls:
from bespokelabs.sandbox import SandboxClient
client = SandboxClient("docker")
for task in tasks:
with client.create(image="python:3.12-slim") as sb:
sb.execute_code(task)
client.create(...) accepts the same keyword arguments as Sandbox(...)
and returns a regular Sandbox session. SandboxClient(backend) validates
the backend name and SDK availability up front — it raises
BackendNotInstalledError immediately if the backend's extra isn't
installed — but performs no network I/O until create().
Async
AsyncSandboxClient / AsyncSandbox mirror the sync API with coroutine
methods, so you can create and drive many sandboxes concurrently from one
event loop:
import asyncio
from bespokelabs.sandbox import AsyncSandbox, AsyncSandboxClient
async def run_snippet(client: AsyncSandboxClient, code: str) -> str:
async with await client.create() as sb:
result = await sb.execute_code(code)
return result.stdout
async def main():
client = AsyncSandboxClient("local")
snippets = ["print(1 + 1)", "print(2 + 2)"]
outputs = await asyncio.gather(*(run_snippet(client, c) for c in snippets))
print(outputs)
asyncio.run(main())
One-step creation works too: sb = await AsyncSandbox.create("local").
Use one AsyncSandboxClient per event loop. Execution, files, run_agent,
snapshots, resume, and destruction are awaitable; session_state() and
properties remain synchronous. The wrapper does not expose agent() or
agent_tools().
Backend SDKs are synchronous, so async calls are offloaded to worker
threads — the event loop is never blocked. Note that the missing-SDK check
(BackendNotInstalledError) surfaces at the first await client.create()
rather than at AsyncSandboxClient(...) construction, which does no I/O.
Feature Support Matrix
This table describes the adapters in this repository, not every feature offered
by each provider's native SDK. “Interpreter” means an installed binary that
accepts -c; use shell commands for other language runtimes.
Monty's Python-only capability set is described above; the table below covers the backends that support shell commands.
| Feature | Local | Safehouse | Docker | Ray | Daytona | Tensorlake | Modal | RunPod | E2B | boxd |
|---|---|---|---|---|---|---|---|---|---|---|
execute_code |
Interpreter | Interpreter | Interpreter | Interpreter | Python | Interpreter | Interpreter | Interpreter | Python | Interpreter |
execute_command |
Shell | Shell | Shell | Shell | Shell | Shell | Shell | SSH | Shell | Shell |
list_files |
Native | Native | find / ls |
Native | Native SDK | via ls |
Native SDK | via SSH | Native SDK | Native SDK |
read_file |
Native | Native | get_archive |
Native | Native SDK | via cat |
Native SDK | via SSH | Native SDK | Native SDK |
write_file |
Native | Native | put_archive |
Native | Native SDK | via base64 | Native SDK | via SSH | Native SDK | Native SDK |
upload_file |
shutil.copy |
shutil.copy |
put_archive |
Actor RPC | Native SDK | via base64 | Native SDK | via SSH | Native SDK | Native SDK |
download_file |
shutil.copy |
shutil.copy |
get_archive |
Actor RPC | Native SDK | via base64 | Native SDK | via SSH | Native SDK | Native SDK |
snapshot |
No | No | Yes | No | No | Yes | Yes | No | No | Yes |
dockerfile= |
Rejected | Rejected | Local build | Rejected | Declarative build | Rejected | Image.from_dockerfile |
Rejected | Rejected | Rejected |
expose_port |
No | No | Published port | No | Preview link + token | No | Tunnel | No | get_host |
Public HTTPS proxy |
| Resource limits | No | No | cpu, memory | cpu (Ray) | cpu, memory, disk | cpu, memory | cpu, memory, gpu | cpu, memory, disk, gpu | Tier-based | cpu, memory (size class) |
allow_internet=False (legacy, prefer network=) |
Ignored | Ignored | Yes | Ignored | Ignored | Yes | Ignored | Rejected | Ignored | Yes |
network= modes |
public | public | public, none | public | all | public, none | all | public | public | all |
set_network() |
No | No | No | No | Yes | No | public, allowlist | No | No | Yes |
| Isolation | Process-level | macOS sandbox-exec |
Container | Process | Full VM | Container | Container | Container | Full VM | Full VM |
gpu= reservation |
No | No | No | No | No | No | Yes | Yes | No | No |
| Needs install | Nothing | safehouse CLI |
Docker daemon | ray |
API key | tl login |
API key | API key + OpenSSH | API key | API key |
Daytona applies CPU/RAM/disk overrides when creating from image; the snapshot
creation path uses the snapshot's resources. RunPod CPU/RAM values are minimums
per GPU, not exact allocations. Ray reserves CPU scheduling resources without
requesting GPU or memory limits. Tensorlake currently does not forward the
top-level env_vars option; inside-agent AgentSpec.env can supply per-command
variables. Its read_file converts text stdout to bytes; use download_file
for binary data. boxd expose_port URLs are public and unauthenticated; the
first one on a machine waits for its TLS certificate, which takes about 20
seconds.
Exceptions
from bespokelabs.sandbox import (
SandboxError, # Base class for all errors
SandboxCreationError, # Sandbox failed to start
SandboxExecutionError, # Code or command execution failed
BackendNotInstalledError, # pip package missing for chosen backend
FeatureNotSupportedError, # Backend doesn't support this operation
)
All exceptions inherit from SandboxError, so you can catch broadly or narrowly:
try:
sb.snapshot()
except FeatureNotSupportedError:
print("This backend doesn't support snapshots")
except SandboxError as e:
print(f"Something else went wrong: {e}")
Environment Variables
# Docker — no auth needed, just a running Docker daemon
# Local — no auth needed
# Ray — optional remote cluster
export RAY_ADDRESS=ray://head-node:10001 # omit for local cluster
# Daytona
export DAYTONA_API_KEY=your_key
export DAYTONA_API_URL=https://app.daytona.io/api # optional
export DAYTONA_TARGET=us # optional
# Tensorlake
export TENSORLAKE_API_KEY=your_key
# Or authenticate via CLI:
tl login
# Modal
export MODAL_TOKEN_ID=your_id
export MODAL_TOKEN_SECRET=your_secret
# RunPod — add the matching public key to your RunPod account
export RUNPOD_API_KEY=your_key
# E2B
export E2B_API_KEY=your_key
# boxd
export BOXD_API_KEY=your_key
export BOXD_ORG=your_org # optional; picks the org for a BOXD_TOKEN session
# Google Cloud Batch (jobs) — Application Default Credentials
gcloud auth application-default login
export GOOGLE_CLOUD_PROJECT=your-project
export GOOGLE_CLOUD_REGION=us-central1
Envy notifications for agents
The optional Envy supervisor registers sandbox agents with a
shared human token and wakes their Codex or Claude Code conversations through
an authenticated event stream. It queues incoming messages, resumes the saved
conversation, posts replies, and retries interrupted deliveries. No inbox
polling or model calls happen while idle. Start with
examples/envy_listener.py.
Lifecycle telemetry
Every create, setup (preset, clone, files, workspace), exec, and
destroy emits one telemetry.SandboxEvent with backend, duration, outcome,
and the stable error code. Events are logged to
bespokelabs.sandbox.telemetry (WARNING on failure) and passed to listeners:
from bespokelabs.sandbox import telemetry
telemetry.add_listener(
lambda e: statsd.timing(
f"sandbox.{e.op}", e.duration_secs * 1000,
tags=[f"backend:{e.backend}", f"outcome:{e.outcome}"],
)
)
A command that exits non-zero is outcome="ok" with exit_code set. Events
never include commands, code, paths, env vars, or error messages.
Examples
Run examples from a source checkout after installing the package. Each script lists its own provider and agent prerequisites.
| Example | Demonstrates |
|---|---|
| move_files_into_sandbox.py | Generated local directory, file-map seeding, and live transfers |
| find_cheapest.py | Cold-start/execution benchmarks and bundled compute estimates |
| sandbox_repo.py | Claude Code or Codex inside Daytona/Tensorlake, with a clone or web input |
| claude_code_outside.py | Host-side agent driving sandbox commands through a local bridge |
| claude_code_persona.py | Declarative workspace and agent persona files |
| github_stats.py | Parsing agent output into a Pydantic model |
A local transfer demo needs no cloud credentials or agent CLI:
python examples/move_files_into_sandbox.py --backend local
Development
Use Python 3.11+ to include the server modules and tests:
python3.11 -m venv .venv
source .venv/bin/activate
python -m pip install -e '.[dev,server]'
# Unit/API tests using local execution and mocked providers.
python -m pytest -q --ignore=tests/test_regression.py
# Repository formatting and lint configuration.
python -m pyink --check src tests examples
python -m ruff check src tests examples
On macOS, prefix the test command with COPYFILE_DISABLE=1 to prevent the
system tar from adding AppleDouble ._* files to directory-transfer fixtures:
COPYFILE_DISABLE=1 python -m pytest -q --ignore=tests/test_regression.py
tests/test_regression.py probes installed providers at collection time and
can create real resources when SDKs/authentication are available. Run
python -m pytest -q when you intend to exercise those integrations. Mocked
Daytona adapter tests also need the [daytona] extra and skip without it.
The test suite exercises Python/API behavior and dashboard asset contracts;
tests/dashboard_browser_app.py is a separate deterministic browser fixture.
Codebase map
| Path | Responsibility |
|---|---|
src/bespokelabs/sandbox/sandbox.py |
Direct SDK, lifecycle, workspace setup, structured output, agent cost tracking |
src/bespokelabs/sandbox/aio.py |
Thread-backed async client and session wrapper |
src/bespokelabs/sandbox/backends/ |
Lazy-loaded provider clients and sessions, plus the job-only Google Cloud Batch client |
src/bespokelabs/sandbox/_jobs.py |
Job backend lookup and the shared wait_job loop |
src/bespokelabs/sandbox/protocols.py, types.py, exceptions.py |
Backend contracts and shared public types/errors |
src/bespokelabs/sandbox/workspace.py, _transfer.py |
Manifest entries and directory transfer strategies |
src/bespokelabs/sandbox/agents.py, _agent_runtime.py, _usage.py |
Agent placement, command preparation, Claude/OpenCode usage parsing |
src/bespokelabs/sandbox/presets.py, pricing.py, pricing.json |
Preset configuration and bundled compute rates |
src/bespokelabs/sandbox/remote.py |
Standard-library HTTP client for the control plane |
src/bespokelabs/sandbox/control_plane/ |
FastAPI routes, tenant service, SQLite migrations/ledgers, supervision, dashboard assets |
images/, .github/workflows/build-images.yml |
Preset Dockerfiles and image publishing workflow |
tests/, examples/, docs/ |
Regression coverage, usage examples, API contract and operations runbook |
See DEVELOPMENT.md for design direction and compatibility
rules. It includes proposed integrations as well as implemented concepts;
the current public API is exported by src/bespokelabs/sandbox/__init__.py.
For server deployments, read the operations runbook.
License
Metadata
Release files for bespokelabs-sandbox 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| bespokelabs_sandbox-0.4.0.tar.gz | 370.8 kB | Without provenance | Details for bespokelabs_sandbox-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| bespokelabs_sandbox-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for bespokelabs_sandbox-0.4.0-py3-none-any.whl |
Total release size: 604.7 kB
Release files / bespokelabs_sandbox-0.4.0.tar.gz
| Download URL | bespokelabs_sandbox-0.4.0.tar.gz |
|---|---|
| Size | 370.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
28c636c5c7fe3964ef1b850a0e35b37f23192b5b95c41445cdb65a57379c0a57
|
|
BLAKE2b-256 checksum How to use checksums |
a9d06861300dac790ff8e5fa6f592d98d03699d00eba73159ff60d50c5f5656d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.6
|
Release files / bespokelabs_sandbox-0.4.0-py3-none-any.whl
| Download URL | bespokelabs_sandbox-0.4.0-py3-none-any.whl |
|---|---|
| Size | 233.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7986ec9d1d53ef8f393bd9e16963feafd01f00791e76cc7279709abd8cca484e
|
|
BLAKE2b-256 checksum How to use checksums |
b22bdf18802861d1639d9091c33e4635f0a4c820b2ff0bca36701aa4f036e7db
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.6
|
Security for bespokelabs-sandbox 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.