BoxRouter Python SDK
Alpha. The API can change in any release, and a release can be withdrawn. Pin an exact version.
Use one BoxRouter key to run sandbox commands and transfer files through Cloud. Requires Python 3.11 or later. Install the SDK from PyPI:
python -m pip install boxrouter
Sign in to your BoxRouter deployment, configure provider credentials under BYOK, and create an API key under API keys in that same deployment. Provider credentials stay in Cloud; the provider bills your compute usage directly.
Set BOXROUTER_API_KEY to the API key you created:
export BOXROUTER_API_KEY="<your BoxRouter API key>"
The client defaults to the hosted API. For another deployment, set BOXROUTER_BASE_URL
(or pass base_url=) to that deployment's API base URL.
Then:
from boxrouter import BoxRouter
with BoxRouter() as client:
with client.sandboxes.create() as box:
box.files.write("/tmp/hello.txt", "hello")
print(box.exec("cat /tmp/hello.txt").stdout)
A with block does not hold the sandbox's lifetime open: with no lifetime_seconds a
sandbox runs up to 300 seconds, or longer when its route can extend the timer, and it can
end while the block is still running. Set lifetime_seconds to cover the work:
with BoxRouter() as client:
with client.sandboxes.create(lifetime_seconds=1800) as box:
print(box.exec("slow-job").exit_code)
The next call through a handle for a sandbox that ended raises APIError with code
sandbox_ended (HTTP 410). Leaving the with still asks Cloud to destroy the sandbox,
which is a safe resend on one that already ended.
State what the sandbox needs instead of naming a provider: gates by name in
requirements, resources, a lifetime and ranking preferences. Routes that cannot
satisfy them are excluded before routing, and the sandbox's record keeps its contract and
why its route was chosen. match returns the same evaluation without creating anything:
needs = {
"lifetime_seconds": 1800,
"at_end": "paused",
"requirements": {"pause_resume": {}},
"resources": {"cpu_min": 2, "memory_min_mib": 4096},
"preferences": {"sort": "price"},
}
with BoxRouter() as client:
print([route.provider for route in client.sandboxes.match(**needs).routes])
with client.sandboxes.create(**needs) as box:
record = client.api.sandbox_records.get(box.id)
print(record.route.provider, record.contract.gates)
Name a gate in requirements with a list, and every handle has the matching calls:
requirements=["pause_resume"] sends {"pause_resume": {}}. A list names only requirements
that need no settings; one that has required settings, such as previews, takes the mapping
form. Any other name raises ValueError, listing the accepted ones. Gated calls on a sandbox
created without the gate raise APIError with code not_named; the SDK adds no check of
its own:
from boxrouter import BoxRouter
with BoxRouter() as client:
with client.sandboxes.create(requirements=["pause_resume"]) as box:
box.pause()
box.resume()
box.extend(1800) # the new total lifetime in seconds, not an addition
previews = {"previews": {"access": "public", "ports": [3000]}}
with client.sandboxes.create(requirements=previews) as box:
print(box.previews.open(3000).url)
pause() returns Paused, resume() returns Resumed (or None when the response has no
body) and extend() returns the new Lifetime; the handle's state and ends_at follow
each response. client.sandboxes.list(limit=..., state=[...], cursor=...) returns one page of
sandbox records (SandboxRow); pass its next_cursor back as cursor for the next. A row is
not a handle: call client.sandboxes.get(row.id) for one. get returns a handle that wraps a
Sandbox; handle.sandbox is that model, as of the last response. A row and a record
(SandboxRecord) are both a SandboxBase. Sandbox, SandboxBase, SandboxRecord and
SandboxRow import from boxrouter.
An image in a registry that needs a login is a PrivateImage. The SDK sends it as
image: {"private_oci": reference} with the login in the request-only
registry_credentials, which Cloud never stores, logs or returns. Private images run
on your own provider keys, so connect that provider account first:
from boxrouter import BoxRouter, PrivateImage
private = PrivateImage("ghcr.io/acme/app:1", username="reader", password=read_token)
with BoxRouter() as client:
with client.sandboxes.create(image=private, preferences={"only": ["e2b"]}) as box:
print(box.exec("cat /etc/os-release").stdout)
client.sandboxes.launch(image=private, provider="e2b") takes a PrivateImage too: the
manifest's image is {"private_oci": reference} and the login goes in the launch request's
registry_credentials.
Prepare an image ahead of its first sandbox so no create pays for the setup. Name the
providers, or pass match, the image with the resources and requirements you will
create with, and BoxRouter prepares the first top providers that would rank best for it. A
PrivateImage works in both
forms, on providers you connected with your own key; its login is used once for the setup and
never stored:
with BoxRouter() as client:
client.images.prepare("app:v12", providers=["e2b"], sizes=[4])
client.images.prepare(
image={"dockerfile": "FROM python:3.13\nRUN pip install flask", "context_artifact_id": "art_example"},
providers=["e2b"],
)
client.images.prepare(match={"image": "app:v12", "resources": {"cpu_min": 2}}, top=2)
client.images.prepare(match={"image": private, "resources": {"cpu_min": 2}}, top=2)
print(client.images.preparations("app:v12", providers=["e2b"]))
client.images.unprepare("app:v12", ["e2b"])
Status and unprepare name a private tag that this workspace prepared or created with its
login before; for any other private tag, name its digest (repo@sha256:...).
prepare takes exactly one of the two forms and raises TypeError otherwise.
prepare waits until no selected provider is queued or preparing, then returns the final status;
pass wait=False to return the started status at once. If preparation is still pending when the
wait's bound ends, it raises TimeoutError and setup continues in the background, so
preparations reads it later. The poll interval and bound come from the same declaration as the
launch wait (client-workflows.json in sdk-codegen).
client.operations.wait(operation_id) reads a recorded operation until its outcome is no longer
unknown and returns it; it raises TimeoutError if the outcome stays unknown for the bound and
never repeats the mutation. client.operations.get reads once.
When no route qualifies, creation raises APIError with code no_eligible_route;
error.error["details"] lists every excluded route with the checks it failed and the
nearest changes. The words of the retired 0.2.0 request (timeout_seconds, egress,
provider, a dotted requirements key) are refused with invalid_request.
Use AsyncBoxRouter for the corresponding async methods. The sandbox context
requests destruction on exit; closing the client alone closes HTTP connections.
Files read as bytes; box.files.list(path) returns entries with name and type.
Commands return stdout, stderr and exit_code; nonzero
exit status is a workload result. With output="bytes", stdout and stderr are
bytes, exact on a route that returns binary output; both command modes carry per-stream
truncation flags. Each stream is cut at 524288 bytes unless output_limit_bytes asks
for more.
A sandbox handle shows the sandbox's fields as read-only properties: box.id,
box.sandbox_class, box.state, box.size, box.region, box.image, box.labels,
box.created_at, box.ends_at, box.at_end and box.times. client.sandboxes.get(id)
returns a handle, box.refresh() reads the sandbox again, pause, resume and extend
update state and ends_at, and box.destroy() returns the state (destroyed, or
destroying while Cloud finishes the destroy) and sets it on the handle. box.cost() reads
what the sandbox cost. The provider, route, contract, usage and volume of a sandbox are on
its record: client.api.sandbox_records.get(box.id).
The first operation through a handle for an ended sandbox returns the usual sandbox_ended API error.
For output while a command runs, start a background process on a running sandbox:
from boxrouter import BoxRouter
with BoxRouter() as client:
box = client.sandboxes.get("SANDBOX_ID")
process = box.processes.start("echo hello")
print("Process ID:", process.id, flush=True)
done = process.wait(timeout=600, on_stdout=lambda text: print(text, end="", flush=True))
print("Exit code:", done.exit_code)
process.remove()
read() returns a page of output after cursor (the oldest output kept when you pass none)
as soon as there is some or the process has exited, and otherwise after wait_ms
milliseconds; wait_ms=0 returns at once. Pass the page's next_cursor to the next read.
state is exited, with exit_code, once the process ended. wait() reads pages until the
process exits and returns the result exec returns: stdout and stderr as text (invalid
bytes replaced), exit_code, timed_out and the truncation flags, which are true when older
output was discarded before it could be read. Process output is text only. wait() raises
TimeoutError when timeout passes; the command keeps running. on_stdout and on_stderr
receive each new piece of output while it runs. exec and run take the same two callbacks:
the command then runs as a background process that is followed to its end, its output is text,
it has no default deadline, and it starts a little later than a plain call. Use process.cancel() to stop it and
process.remove() to delete its retained output. With stdin=True, write_stdin() and
close_stdin() feed it.
To receive Cloud's bounded Server-Timing measurements, install the response hooks on
the client's HTTPX client before sending requests. This leaves HTTPX's configured
transport in place, including its environment proxy routing. The callback runs after
the response body is consumed or closed. On SDK calls it also reports TCP connect,
TLS, request send, first response headers, body read, SDK build and response decode
durations, plus whether the connection was reused. dns_ms remains None because
httpcore combines name lookup with TCP connect; connect_ms includes both. Values
that the transport cannot observe are None. Cloud service, database, code, provider
connect and provider wait durations are also included when the response reports them.
The callback receives only durations and a reuse flag, with no request or credential data.
from boxrouter import BoxRouter
from boxrouter.server_timing import RequestTiming, install_server_timing
def report(timing: RequestTiming) -> None:
print(timing)
with BoxRouter() as client:
install_server_timing(client.api_client.get_httpx_client(), report)
client.sandboxes.get("SANDBOX_ID")
For AsyncBoxRouter, install the async event hooks on its HTTPX client:
from boxrouter import AsyncBoxRouter
from boxrouter.server_timing import install_async_server_timing
async with AsyncBoxRouter() as client:
install_async_server_timing(client.api_client.get_async_httpx_client(), report)
await client.sandboxes.get("SANDBOX_ID")
The boxrouter command uses the same configuration. To install it, run the line for your system:
# macOS and Linux
curl -fsSL https://boxrouter.ai/install | sh
# Windows, in PowerShell
irm https://boxrouter.ai/install.ps1 | iex
The CLI guide explains how to upgrade, remove and use the boxrouter command.
Then run it:
boxrouter run 'echo hello'
boxrouter run --lifetime 10m --env MESSAGE=hello python3 --version
boxrouter exec SANDBOX_ID --env MESSAGE=hello 'echo "$MESSAGE"'
boxrouter --help
Put options before the command. Everything after the options (run) or the sandbox ID
(exec), or after --, is the command. One quoted argument is Bash source; several words
run as typed. run takes the options create takes: --lifetime sets how long the
sandbox lives, and --timeout-seconds is the command response deadline.
Common commands derive their arguments from SDK methods. Object options accept
JSON, @settings.json, or - for stdin.
The same temporary workflow is available to SDK users:
with BoxRouter() as client:
with client.sandboxes.run("echo hello") as result:
print(result.stdout)
Results are available inside the context before cleanup. Use
client.sandboxes.exec(sandbox_id, command) to execute against a known ID.
The generated api commands expose the SDK's resource namespaces:
boxrouter api sandboxes create --body '{}'
boxrouter api commands run SANDBOX_ID --body '{"command":"echo hello"}'
boxrouter api files write SANDBOX_ID --path /tmp/input.bin --body ./input.bin
boxrouter api files read SANDBOX_ID --path /tmp/input.bin > output.bin
boxrouter api sandboxes destroy SANDBOX_ID
boxrouter api sandboxes create --help
For an interactive shell, use boxrouter terminal SANDBOX_ID.
In Python, box.open_terminal() returns a handle owned by the sandbox.
terminal.output() yields exact bytes and records terminal.exit_code; an unconfirmed
exit remains None. terminal.exited is true once an exit event confirmed the shell ended,
so a shell that ended with no reported status has exited true and exit_code None. Error events raise TerminalError, retaining the raw event,
code, detail_code, and outcome.
A lost connection or a restarting API does not end terminal.output(): it reconnects after
the last consumed event for up to TERMINAL_RESUME_WINDOW_SECONDS and never sends input again.
on_connection(False) and on_connection(True) report the interruption. When the API no longer
replays the skipped stretch, the output continues from the current tip and output_gaps counts it.
Open with session="work" to run in a tmux session in the sandbox. The program then outlives the
shell: when the shell reaches its time limit or can no longer be read, output() opens a new one
on the same session (replacements counts them, and terminal.id changes), and a later
open_terminal(session="work") returns to it. A sandbox without tmux gets a plain shell and
terminal.session is None.
Call terminal.close() to detach early; it does not kill the shell. The next read
on that handle resumes after its last consumed event. For a different process,
save terminal.id and terminal.last_event_id, then open with terminal_id and
read with last_event_id. The namespace factory
client.sandboxes.open_terminal(sandbox_id) returns a separately owned handle;
use its context manager or close it explicitly. Async factories and close are awaited.
Rows and columns set the size of a new terminal. Attaching keeps its current size;
call terminal.resize() explicitly to change it. The sandbox image must provide python3.
JSON bodies also accept @request.json or - for stdin. Binary bodies accept a
local filename or -.
API commands print JSON responses, or JSON lines for events;
redirect binary output to a file or pipe. A successful API command exits zero even
when its JSON result contains a nonzero workload exit code. HTTP failures exit one,
and invalid arguments exit two. Use the top-level run/exec commands when you
want workload stdout, stderr and shell exit status directly. API commands do not
implicitly destroy sandboxes; a failed call is resent only when the error body names a
retry_after_seconds wait (see Errors). Help works without credentials.
Use --show-response-headers to print each HTTP response's status and headers to
stderr as they arrive. Binary stdout remains suitable for files and pipes. Headers
can arrive before a transfer fails: require exit zero before treating its output as
complete. This option also shows headers for HTTP errors.
HTTP failures raise boxrouter.api_error.APIError. Retain its request_id,
operation_id, outcome and idempotency_key. fix says what to do next and ends
the message as Fix: …; its error mapping keeps the complete envelope, including detail_code, retry_after_seconds and the x-boxrouter-provider-* fields. Streaming HTTP failures use its
StreamHTTPError subclass, with at most 64 KiB of diagnostics and body_truncated
indicating overflow. Unexpected responses include a Support link in report_url and
the error message, with support@boxrouter.ai as a direct alternative. Transport
failures against boxrouter.ai expose report_url on the original HTTPX exception,
including stream interruptions, and include the email alternative; the CLI renders
both. Custom API hosts do not get BoxRouter reporting details. Incomplete diagnostics may
not contain recovery fields.
Responses are read tolerantly: every property the client knows is checked, and a property
a newer API adds is kept on the returned model (to_dict() includes it); an unknown
property in your own input is still refused before sending. An invalid response to a
read (GET) says the read failed, nothing was changed and it can be retried; for any
other method it says the result is unconfirmed and to inspect the operation first. When no
kind of record matched, it adds that a newer SDK is needed if it keeps failing. When a
response a newer API extended fits several variants of a union, the SDK picks the one that
leaves the fewest properties unknown. A stream skips an event of a kind this client does not
know and still ends at its terminal event. A response enum the API grows (a sandbox's
state and state_reason, an API key's permissions) is typed str, so a value added later
reaches your code; request enums stay closed.
Transport failures remain HTTPX
exceptions and are not resent. Every API error carries outcome (failed, unknown or a newer
value) and retry_after_seconds; APIError exposes them as status, detail_code, outcome,
retry_after_seconds and details, and doc_url is the page that explains the code. The client resends only a failed error that names a retry_after_seconds wait, with the same idempotency key, up to max_retries times (BoxRouter(max_retries=2)
is the default; 0 turns it off), waiting retry_after_seconds; a wait longer than
the client sleeps is raised instead. Streams and uploads are not resent. A timeout or lost
response can leave work running: inspect the operation before submitting new work.
Failed cleanup does not prove the sandbox was destroyed.
BoxRouter, AsyncBoxRouter and the CLI default to short connection/pool waits
and a read/write inactivity limit long enough for image setup during a create
(HTTP_INACTIVITY_TIMEOUT_SECONDS in boxrouter.workflow_policy).
These HTTP limits are separate from
the command's response deadline and sandbox lifetime. For longer waits, pass an
HTTPX configuration such as timeout=httpx.Timeout(600.0, connect=10.0) to the
Python client; explicit timeout=None disables its HTTP timeouts. Active streams
can continue beyond the read timeout while chunks keep arriving.
For the CLI, put --http-timeout 600 before the command to allow longer HTTP waits.
If work and context cleanup both fail, an exception group preserves both errors;
use except* APIError to handle their separate recovery IDs. A lone failure keeps
its original exception type. Cancellation or interruption is retained in a
BaseExceptionGroup if cleanup also fails.
Every method in this package is provider-neutral. Generated methods expose a broader
contract than Cloud currently implements: a sandbox may use only the gates its creation
named, so read its record's contract.gates (client.api.sandbox_records.get(box.id)) for
what each was granted and the API repository's docs/coverage.md before relying on one. A
call outside them is refused with not_named. A record with no recorded contract has
contract set to None.
Tracing
The SDK depends on the OpenTelemetry API; the application owns provider setup,
sampling and export. Buffered requests and sync/async SSE contexts emit client spans
with operation names, HTTP status and validated request IDs. Buffered spans cover
response decoding, so malformed responses and unexpected statuses record failures.
Stream spans include delivered event counts and completion, error or cancellation
state, including errors caught during iteration. Keep iteration inside its with
or async with block.
The request span is active during SDK I/O and event decoding. Your code retains
its caller context while processing events or starting other operations.
Closing a stream does not establish cancellation of remote work.
Only W3C traceparent is automatically injected to link requests to Cloud;
vendor tracestate and baggage are not automatically forwarded. Request/response
bodies, credentials, URLs, resource IDs, exception messages and stacks are excluded
from spans. No exporter or background worker is installed by the SDK.
Application-installed automatic instrumentation has its own capture policy and
must be reviewed separately.
Client identification
All generated HTTP operations send boxrouter-python/<installed SDK version>,
including JSON, file streams and events. Set
user_agent_suffix="my-app/1.0" on BoxRouter or AsyncBoxRouter to append a
printable ASCII product token (at most 256 characters; complete header at most 512).
client.with_user_agent_suffix("integration/1.0") returns an independently
identified view sharing its owner's HTTP transport. It borrows the owner's lifetime:
closing a view does not close its owner; keep the owner open while using it.
Bound sandbox handles also support with_user_agent_suffix. Custom suffixes are
not retained by Cloud; Cloud keeps only an allowlisted name and major.minor version.
The upstream union template does not guard const branches, so an unmatched const can stop parsing before a valid later branch. The const property template adds a branch check while retaining the canonical response validator and request validation.
Work on a local repository in a box
client.sandboxes.up() gives a git working tree its own box, a second working tree of the
repository. Cloud clones the newest commit HEAD shares with the branch's GitHub remote (a
repository this workspace can read), and the commits and uncommitted files on top of it, tracked
and untracked but not ignored, travel as a git bundle. The box is on the same branch with the same
files; the branch, index and files here are not touched. Without a readable GitHub remote, the
bundle carries the whole history.
from boxrouter import BoxRouter
with BoxRouter() as client:
box = client.sandboxes.up("claude-code", directory="~/code/app")
print(box.id, box.sync.changed, box.sync.left)
... # the agent works in the box
print(client.sandboxes.pull(directory="~/code/app").changed)
client.sandboxes.down(directory="~/code/app")
The working tree remembers its box (in $(git rev-parse --git-path boxrouter)/box.json), so a
later up binds the same box, resumes it when paused and sends the changes made since the last
sync. pull merges the box's changes into the working tree: a three-way merge whose base is the
last snapshot both sides hold, computed here, writing only files the merge changes and only when
none of them changed here since the snapshot. When both sides changed the same lines, nothing
changes, the box's version is kept as refs/boxrouter/<sandbox>/box, and worktree.SyncConflict
names the files and how to take the box's version. down pulls, then destroys the box; when the
pull does not finish, nothing is destroyed. The box's own commits stay reachable from that ref.
At most 8 MiB moves each way, and the box's bundle is read in parts of at most 1 MiB, so every
route serves it; a larger change is refused before anything moves, with its size and largest
files. Uncommitted changes to files named like credentials (.env, *.pem, id_rsa and the
rest of WORKTREE_SYNC_CREDENTIAL_NAMES in boxrouter.workflow_policy) stay where they are, and
Sync.left lists them; pass secrets with secret_names. Git 2.38 or later is needed here; the box
needs plain git. Git LFS content and submodule contents do not travel.
Launch unattended agents
client.sandboxes.launch(...) waits for the launch operation (bounded by
LAUNCH_BOUND_SECONDS, raising TimeoutError if it is still pending), reads the
sandbox once, and returns the same SandboxHandle that create returns. A failed
launch raises the operation's API error. rows, cols and rm are gone: leaving the
handle's with block destroys the sandbox, and box.open_terminal(rows=, cols=) opens a
shell that starts the launch's command (it writes <command>\n to a new terminal with
a 3600 s timeout). For interactive: false, Cloud starts the command during
preparation, so the handle has no launch command and box.open_terminal() opens a plain
shell. If the sandbox read fails after a successful launch, the error carries the note
Sandbox ID: <id>. manifest also accepts a plain mapping; a source key marks a
source manifest.
launch_run(..., copies=N) requires its named secrets to be saved in the
workspace. The server refuses missing names before creating a run; the SDK raises
MissingWorkspaceSecrets with those names. It makes no extra metadata requests
and never saves local secrets.
Metadata
Release files for boxrouter 0.12.349
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 |
|---|---|---|---|---|
| boxrouter-0.12.349.tar.gz | 812.9 kB | With provenance | Details for boxrouter-0.12.349.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| boxrouter-0.12.349-py3-none-any.whl | Python 3 | none | any | Details for boxrouter-0.12.349-py3-none-any.whl |
Total release size: 2.4 MB
Release files / boxrouter-0.12.349.tar.gz
| Download URL | boxrouter-0.12.349.tar.gz |
|---|---|
| Size | 812.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4caabd71bd3527ef2fdc55254c3ef9ddcf052c363d88a9f933fe891385e3d040
|
|
BLAKE2b-256 checksum How to use checksums |
3574855e442c2fe0907de9a82876d28022a41a05491efa6ee42f3d0d0c73b1d2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logRelease files / boxrouter-0.12.349-py3-none-any.whl
| Download URL | boxrouter-0.12.349-py3-none-any.whl |
|---|---|
| Size | 1.6 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ad3ed78f064e70e19f4e341635806a864f4e01a521ae4b4ce2821a3fd88f3971
|
|
BLAKE2b-256 checksum How to use checksums |
229a91be409f3f7d77107e8ce15a5349adc2dba68aead19967a0f84562dab0e9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logSecurity for boxrouter 0.12.349
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for boxrouter-0.12.349.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.
Transparency logA 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.