Metadata-Version: 2.4
Name: beadrun
Version: 0.1.0
Summary: Friendly typed bead sandbox SDK
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: urllib3<3,>=2.8.0
Description-Content-Type: text/markdown

```python
from beadrun import Sandbox
with Sandbox.create() as sb:
    print(sb.run("echo hi").stdout)
```

Install `pip install beadrun`. Set `BEAD_API_KEY`; Python 3.11+ is supported.
The PyPI distribution and Python module are both `beadrun`
(operator ruling, 2026-11-09), avoiding collisions with the unrelated `bead` module.
HTTP uses urllib3 (MIT), with no transitive runtime dependencies and the
operating system TLS trust store. Async socket operations run outside the event
loop; cancellation waits for the current socket operation to finish or time out. Results are dataclasses; the package ships `py.typed`.

Synchronous and asynchronous APIs have the same objects and verbs:

```python
from beadrun import AsyncSandbox
async with await AsyncSandbox.create() as sb:
    print((await sb.run("echo hi")).stdout)
    async for event in sb.run("echo stream", stream=True):
        print(event.type, event.data)
```

`Sandbox` uses sync generators; `AsyncSandbox` uses nonblocking HTTP calls and async
generators. Async calls do not wrap blocking HTTP in worker threads. Async file
transfer offloads local disk IO. Both context managers delete on exception.
Unclosed sandboxes emit a process-exit warning; remote work still lives until its
timeout. Default lifetime: 300 seconds. All timeouts are seconds. Breaking a
stream stops reading; kill the sandbox to stop remote processes.

```python
r = sb.run("pwd", cwd="/tmp", env={"GREETING": "hi"}, timeout=30)
print(r.exit_code, r.stdout, r.stderr)  # nonzero exit is a result
sb.run("echo hi", on_stdout=print)
for event in sb.run("echo stream", stream=True):
    print(event.type, event.data, event.exit_code)
sb.files.write("/tmp/hello.txt", "hi")
print(sb.files.read("/tmp/hello.txt"))
print(sb.files.list("/tmp"))
sb.files.upload("./data.bin", "/tmp/data.bin")
sb.files.download("/tmp/data.bin", "./download.bin")
print(sb.ports.url(3000))
```

Read/write accept text or bytes (`read_bytes` for binary). Transfer bounds are
server limits and raise typed errors. Port URLs may require `trafficAccessToken`
from `sb.info` in the `e2b-traffic-access-token` header; the URL grants no access.
Desktop, CDP and guest-control ports are reserved.

```python
sb.pause()
sb.resume()
children = sb.fork(2)
try:
    print(children[0].run("echo fork"))
finally:
    for child in children:
        child.kill()
golden = sb.snapshot(name="example")  # waits for publication
try:
    with Sandbox.from_golden(golden) as copy:
        print(copy.run("echo golden"))
finally:
    golden.delete()  # retained storage has a separate lifetime
```

Batch operations preserve partial failures as `BatchError.results`, with each
successful `sandbox` and typed `error`. Clean up those successes explicitly.

```python
from beadrun import Fleet, Swarm
with Fleet.create(2) as fleet:
    for member in fleet:
        print(member.run("echo fleet"))
swarm = Swarm.run(cmd="echo swarm", inputs=[1, 2])
try:
    for result in swarm:
        print(result)
finally:
    swarm.close()
```

`AsyncFleet` and `AsyncSwarm` provide native async equivalents. Swarms run on the
server, result iteration waits within `operation_timeout`, and closing a client
keeps a submitted job inspectable (`status` / `cancel`).

```python
import beadrun
print(sb.cost())
print(beadrun.pricing.estimate(vcpus=1, memory_mib=2048, disk_mib=1024, duration_seconds=60))
print(beadrun.limits())
account = beadrun.Bead()
try:
    print(account.profiles.list())
    # account.profiles.put(profile_id, "my agent", {"env": provider_environment})
    # account.profiles.revoke(profile_id)
finally:
    account.close()
```

```python
with Sandbox.create(template="computer", credential_profile=profile_id) as computer:
    for event in computer.agent.prompt("Describe this machine", profile_id=profile_id):
        print(event)
    screenshot = computer.desktop.screenshot()
    print(computer.browser.command(["snapshot"]))
```

Computer/agent recipes need an approved template and a funded credential profile.
Agent events use the server's cursor pages, yielded incrementally, not invented
SSE endpoints. Approval policy defaults to `untrusted`; `never` is an explicit
choice. Browser arguments are quoted individually. Helpers propagate unsupported
endpoint/tool errors on other templates. No agent harness is bundled.

`Sandbox.create` accepts `template`, `size={"vcpus":1,"memory_mib":2048}`,
`timeout`, `env`, `region`, `credential_profile` and client overrides `api_key`,
`api_url`, `sandbox_url`, `request_timeout`, `operation_timeout`, `retries`,
`retry_delay`, `poll_interval` (operation polling defaults to one second). `BEAD_API_URL` defaults to
`https://api.bead.run`. Size validates the selected approved template, and region
validates the deployment; use the correct regional `api_url` to change placement.
`idempotency_key` on create overrides the generated key for cross-process recovery. Creates/durable lifecycle operations generate idempotency keys. Only reads and
those durable mutations retry 429/502/503/504 and in-progress idempotency conflicts
with exponential jitter and Retry-After. Commands/prompts are never replayed.

```python
from beadrun import LimitError, PaymentRequiredError
try:
    sb.fork(21)
except LimitError as error:  # includes RateLimitError
    print(error.limit.id, error.limit.maximum, error.limit.usage,
          error.limit.retry_after, error.limit.next_action)
except PaymentRequiredError as error:
    print(error.purchase_url)
```

`NotFoundError`, `AuthenticationError`, `TimeoutError`, `ProtocolError` and
`BatchError` also extend `BeadError`. Exceptions retain status/code/request_id.
Billing links use server purchase/checkout URLs or the bead billing page.

One-line E2B wire migration (existing `from e2b import Sandbox` stays):

```sh
E2B_DOMAIN=bead.run E2B_API_URL=https://api.bead.run E2B_API_KEY="$BEAD_API_KEY" python your_existing_app.py
```

This covers bead's pinned E2B contract, not every E2B extension. Adopting bead's
friendly API changes the import to `from beadrun import Sandbox`; `commands.run`
remains available, alongside shorter `run`.

`sdk/tools/check.sh` runs contract tests, mypy, pyright, examples, builds and
`pdoc beadrun -o reference` for API reference. Generated low-level types live in
`beadrun.generated`; `sb.transport.call(operation, params, body)` uses its generated
operation map. The sync implementation owns behavior; a deterministic syntax
transform produces the native async client and CI rejects drift. Common recipes
live in `examples/common.py`. Publish instructions: ../PUBLISH.md.
