Metadata-Version: 2.4
Name: boxrouter
Version: 0.12.241
Summary: BoxRouter Python SDK (alpha)
Author: BoxRouter, Inc.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Classifier: Development Status :: 3 - Alpha
Classifier: Typing :: Typed
Requires-Dist: httpx>=0.23.1,<0.29.0
Requires-Dist: attrs>=22.2.0
Requires-Dist: opentelemetry-api==1.44.0
Requires-Dist: httpx-sse==0.4.3
Requires-Dist: jsonschema==4.26.0
Requires-Dist: rfc3339-validator==0.1.4
Requires-Dist: rfc3986-validator==0.1.1
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# 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:

```sh
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:

```sh
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:

```python
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:

```python
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:

```python
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:

```python
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
sandbox rows (`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, and it is a `SandboxBase`. The handle itself is not.
Check a row's type with `SandboxBase` or `SandboxRow`, not `Sandbox`. All three 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:

```python
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:

```python
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:

```python
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.

```python
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:

```python
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:

```sh
# macOS and Linux
curl -fsSL https://boxrouter.ai/install | sh
# Windows, in PowerShell
irm https://boxrouter.ai/install.ps1 | iex
```

The [CLI guide](https://boxrouter.ai/docs/cli) explains how to upgrade, remove and use the `boxrouter` command.

Then run it:

```sh
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:

```python
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:

```sh
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`, `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 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 `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.
