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 records its contract and why
its route was chosen. match returns the same evaluation without creating anything:
needs = {
"lifetime_seconds": 1800,
"at_end": "pause",
"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).eligible])
with client.sandboxes.create(**needs) as box:
print(box.route.provider, box.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 lifetime follow
each response. client.sandboxes.list(limit=..., state=[...], cursor=...) returns one page of
sandboxes; pass its next_cursor back as cursor for the next.
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 the body you would send to create as match and BoxRouter prepares
the first top providers that create would rank best. 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. native_error keeps the provider's error for the
command when it reports one. With output="bytes", stdout and stderr are exact
bytes; both command modes carry per-stream truncation flags.
A sandbox handle shows the sandbox's fields as read-only properties: box.id, box.state,
box.lifetime, box.cost, box.route and the rest of the Sandbox object. Properties
change on every response that carries the sandbox: client.sandboxes.get(id) returns a handle,
box.refresh() reads the sandbox again, and box.destroy() updates the handle from the
sandbox Cloud returns (destroyed, or destroying while Cloud finishes the destroy).
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)
print(done.stdout, end="")
print("Exit code:", done.exit_code)
process.remove()
read() returns up to 256 KiB per stream from the byte offsets you pass and never blocks;
exit_code is set once the process ended and both streams were read to their ends.
wait() polls read() 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. wait(output="bytes") returns the exact bytes instead. It raises TimeoutError
when timeout passes; the command keeps running. For output while the command runs, loop on
read() from next_stdout and next_stderr; its streams are base64. 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, from the separate boxrouter-cli package, uses the same
configuration:
boxrouter run 'echo hello'
boxrouter run --lifetime-seconds 600 'echo hello'
boxrouter exec SANDBOX_ID 'echo "$MESSAGE"' --env '{"MESSAGE":"hello"}'
boxrouter --help
Common commands derive their arguments from SDK methods. Object options accept
JSON, @settings.json, or - for stdin. For run, --lifetime-seconds controls
sandbox lifetime and --timeout-seconds controls the command response deadline.
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. Error events raise TerminalError, retaining the raw event,
code, outcome, and retry.
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 as the API's retry value allows (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 provider, native_status and native_code. 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 retry (safe, after_fix, check_outcome or
never) and retry_after_seconds; APIError exposes them as status, retry,
retry_after_seconds and details, and doc_url is the page that explains the code. The client resends only retry == "safe" (nothing ran and
waiting helps), 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 or a doubling backoff; 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 10-second connection/pool waits
and 360-second read/write inactivity limits, long enough for image setup during a create.
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 box.contract.gates 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 box.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.
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.182
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.182.tar.gz | 663.0 kB | With provenance | Details for boxrouter-0.12.182.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| boxrouter-0.12.182-py3-none-any.whl | Python 3 | none | any | Details for boxrouter-0.12.182-py3-none-any.whl |
Total release size: 2.1 MB
Release files / boxrouter-0.12.182.tar.gz
| Download URL | boxrouter-0.12.182.tar.gz |
|---|---|
| Size | 663.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5dd7ad77accbb7b5eb9184c2c81a1c2daad3fd3fc3cbda8d2cf99508a7070672
|
|
BLAKE2b-256 checksum How to use checksums |
9718c480a42e79a0ba86ccb1128c0974614fe2b91a000f73c444dbf05bd7256f
|
| 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 14, 2026.
Transparency logRelease files / boxrouter-0.12.182-py3-none-any.whl
| Download URL | boxrouter-0.12.182-py3-none-any.whl |
|---|---|
| Size | 1.4 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6a5fb54ca0a4a8dd2acf1ed55b2a4d6379c342150e5fe1bb8cf44406cc4b4ffe
|
|
BLAKE2b-256 checksum How to use checksums |
8a4b295692f5b6da3ef8414e0de050cf0b911bdd51559f814c50ae6ccfa8467a
|
| 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 14, 2026.
Transparency logSecurity for boxrouter 0.12.182
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.182.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 14, 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.