Metadata-Version: 2.5
Name: stateset-sandbox
Version: 2.10.0
Summary: Python SDK for the StateSet Sandbox API
Project-URL: Homepage, https://sandbox.stateset.app
Project-URL: Documentation, https://sandbox.stateset.app/docs/python-sdk
Project-URL: Repository, https://github.com/stateset/stateset-sandbox
Project-URL: Support, https://sandbox.stateset.app/docs
Project-URL: Changelog, https://github.com/stateset/stateset-sandbox/blob/master/sdk-python/CHANGELOG.md
Project-URL: Source, https://github.com/stateset/stateset-sandbox/tree/master/sdk-python
Author-email: StateSet <support@stateset.io>
License-Expression: MIT
License-File: LICENSE
Keywords: ai,ai-agents,claude,claude-code,cloud-sandbox,code-execution,code-interpreter,llm,sandbox,sandbox-sdk,stateset
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Testing
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.7.0
Provides-Extra: dev
Requires-Dist: mypy>=1.13.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest-httpx>=0.34.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.8.0; extra == 'dev'
Description-Content-Type: text/markdown

# StateSet Sandbox Python SDK

Isolated cloud sandboxes for running code and AI agents such as Claude Code, from Python.

```bash
pip install stateset-sandbox
```

```python
from stateset_sandbox import Sandbox

with Sandbox.create() as sandbox:  # uses STATESET_API_KEY from the environment
    print(sandbox.exec(["python3", "-c", "print(1 + 1)"]).stdout)
```

[Docs](https://sandbox.stateset.app/docs) ·
[Pricing](https://sandbox.stateset.app/pricing) ·
[Integrations](https://github.com/stateset/stateset-sandbox/tree/master/integrations)
(LangChain, CrewAI, OpenAI, AI SDK, ... adapters)

## Get an API key

Sign up in the dashboard at https://sandbox.stateset.app/signup, verify your
email, and create a key under **API Keys**
(https://sandbox.stateset.app/dashboard/api-keys). Then add a card on the
billing page (https://sandbox.stateset.app/dashboard/billing): a card is needed
before your first sandbox. It is not charged while your trial credits last;
after they are used up, usage is billed to the card at pay-as-you-go rates.
Until a card is on file, creating a sandbox raises `PaymentMethodRequiredError`
(see [Error Handling](#error-handling)).

The key identifies your workspace:

```bash
export STATESET_API_KEY="sk-sandbox-..."
```

## Quick Start

Give the sandbox a lifetime, a compute class and a spending budget, and move
files in and out as bytes:

```python
from pathlib import Path
from stateset_sandbox import Sandbox

with Sandbox.create(
    timeout_seconds=300,
    resource_class="dedicated",
    budget={"max_cost_cents": 100, "max_runtime_seconds": 300, "on_exhausted": "stop"},
) as sandbox:
    sandbox.write_file("/workspace/hello.py", 'print("Hello from StateSet")')
    result = sandbox.exec(["python3", "/workspace/hello.py"])
    if result.exit_code != 0:
        raise RuntimeError(result.stderr)
    print(result.stdout)
    Path("hello.py").write_bytes(sandbox.read_file_bytes("/workspace/hello.py"))
```

The context manager stops compute even if the command fails. If stopping raises,
`sandbox.close()` can be retried; the configured lifetime remains in effect.
`AsyncSandbox` supports the same controls and binary helpers with `async` / `await`.
Budgets are checked periodically, so in-flight work may exceed the requested limit.

## Features

- **Sandbox Management**: Create, list, and manage isolated execution environments
- **Command Execution**: Run commands with streaming output support
- **File Operations**: Read and write files within sandboxes
- **Checkpoints**: Save and restore sandbox state
- **Artifacts**: Upload files to cloud storage (S3/GCS)
- **Webhooks**: Receive notifications for sandbox events
- **Audit Logs**: Track all operations for compliance
- **Secrets**: Securely inject environment variables
- **Terminals**: Interactive pseudo-terminal sessions that outlive the connection
- **Code Interpreter**: A persistent Jupyter kernel with rich results
- **Durable Agents**: Start, steer, pause, resume, and reconnect to Temporal workflows
- **Multi-Agent Orchestration**: Bound concurrency, retry workers, cancel tasks, and synthesize results
- **Swarms**: Store a goal split into tasks with dependencies, report each task, and read or cancel the record
- **Regional Placement**: Request a region on deployments that enforce placement
- **Lifecycle Events**: Resumable SSE plus bounded sync and async status waits
- **Execution Recovery**: Typed receipts, cancellation, terminal waits, and cursor-based replay

The bound sandbox API exposes region selection and lifecycle waits:

```python
from stateset_sandbox import Sandbox

with Sandbox.create(region="us-central1") as sandbox:
    sandbox.wait_for_status("running", timeout_seconds=30)
```

## Recover command executions

Save the execution ID returned by `execute`, or use `on_execution_id` on
`execute_stream` to save it before streaming output arrives. Reattach using
the receipt rather than submitting the command again:

```python
execution = client.executions.get(sandbox_id, saved_execution_id)
for event in client.executions.events(
    sandbox_id, saved_execution_id, after=saved_event_id,
):
    if event.type == "reset":
        clear_displayed_output()  # The journal was replaced by a result snapshot.
    consume(event)
    if event.id:
        save_cursor(event.id)  # Save after successfully processing the event.

final = client.executions.wait(sandbox_id, saved_execution_id, timeout=60)
if final.status == "outcome_unknown":
    reconcile_external_effects()  # Never treat this as permission to rerun.
```

`execute_stream` accepts a persisted `idempotency_key`; a replayed key follows
the original command's receipt. Its `on_event` callback runs after the output
callbacks, allowing you to save each processed cursor. Supply `on_replay_reset`
to clear accumulated output when replay falls back to a stored result.

These operations are also available as `sandbox.executions` on `Sandbox` and
`AsyncSandbox`, with the sandbox ID already bound. The async methods use
`await`; replay uses `async for`. `list()` returns the latest 50 receipts.
`cancel()` returns whether cancellation was requested; use `wait()` to inspect
the eventual outcome. Failed, timed out, cancelled, and unknown outcomes are
returned as terminal receipts, so inspect `status` and `exit_code`.

Wait options use seconds. Expiry or asyncio task cancellation stops local
waiting and leaves the remote command running. Async waits enforce a total
deadline, including stalled reads; synchronous waits apply their remaining
budget to each HTTPX I/O phase. Streams retry only GET requests, resume after
complete events, and have a bounded consecutive reconnect budget. Store event
IDs as opaque strings. Close a sync generator (`close()`) or async generator
(`await aclose()`) when stopping early to release its connection. Consumers
must coordinate their effects and cursor storage to handle replay safely.

## Follow supervised process logs

Use supervised processes for agents and servers that must outlive their starting
request. Close a follower when stopping early; this leaves the remote process
running. Sync followers support `with`, and async followers support `async with`:

```python
with client.follow_process_logs(
    sandbox_id, process_id, offset=saved_byte_offset,
    max_reconnects=5, read_timeout_s=30,
) as logs:
    for chunk in logs:
        if chunk.truncated:
            report_rotated_output(chunk.offset)
        display(chunk.text)
        save_byte_offset(chunk.next_offset)
```

For `AsyncSandbox`, use `sandbox.processes.follow_logs(process_id, ...)` and
`async for`. Explicit cleanup is `logs.close()` or `await logs.aclose()`;
closing an async follower also cancels a pending local read or reconnect delay.
Ordinary asyncio cancellation releases the active response. Sync cleanup
interrupts reconnect delays, and idle network reads use the configured timeout.
Only GET reads reconnect; authorization and unsupported-agent errors stop the
follow. Duplicate-only connections cannot reset its reconnect budget.

The follower preserves UTF-8 characters split across reads and reconnects.
Concatenate `chunk.text` for text, or `chunk.data` for exact binary bytes. Rotation
can yield an empty byte chunk with `truncated=True`; an incomplete final UTF-8
sequence can yield an empty byte chunk containing replacement text at completion.
Malformed byte ranges, JSON and terminal receipts fail without advancing the
saved cursor. SSE parsing accepts LF, CRLF and CR, bounds accumulated frames and
discards incomplete frames on disconnect. Lifecycle `StreamingIterator` now
also discards partial EOF frames and supports `with` for early cleanup.

## Terminal sessions

A terminal is a shell, or any command, on a real pseudo-terminal in the sandbox:
job control, full-screen programs and password prompts work as they do locally.
It lives in the sandbox, not in the connection, so it keeps running when a
client goes away and is reached again by its id.

```python
import sys
from stateset_sandbox import Sandbox

with Sandbox.create() as sandbox:
    term = sandbox.terminals.create(cols=120, rows=40)  # a login shell
    sandbox.terminals.write(term.terminal_id, "ls -la\n")
    print(sandbox.terminals.screen(term.terminal_id).text)  # what it displays now

    sandbox.terminals.write(term.terminal_id, "exit\n")
    with sandbox.terminals.stream(term.terminal_id) as stream:
        for chunk in stream:  # every byte once, in order
            sys.stdout.buffer.write(chunk.data)
    print(stream.terminal.exit_code)
```

With `AsyncSandbox` the calls are awaited, and `stream()` is an async iterator:

```python
import asyncio
import sys
from stateset_sandbox import AsyncSandbox

async def main() -> None:
    async with await AsyncSandbox.create() as sandbox:
        term = await sandbox.terminals.create(["python3", "-i"], name="repl")
        await sandbox.terminals.write(term.terminal_id, "print(6 * 7)\n")
        screen = await sandbox.terminals.screen(term.terminal_id, scrollback=100)
        print(screen.text, screen.cursor.row, screen.cursor.col)

        await sandbox.terminals.write(term.terminal_id, b"\x04")  # Ctrl-D
        async with sandbox.terminals.stream(term.terminal_id, offset=screen.offset) as stream:
            async for chunk in stream:
                sys.stdout.buffer.write(chunk.data)
        print(stream.terminal.status)

asyncio.run(main())
```

`client.terminals` has the same methods with the sandbox ID first:
`create`, `list`, `get`, `write`, `resize`, `read`, `screen`, `stream` and
`close`. To look at a terminal, read `screen()` rather than parsing escape
sequences out of the output; a program may still be drawing, so read again
until the screen shows what you are waiting for. `read(terminal_id, offset=...,
wait_ms=...)` is one read of the raw output without holding a stream open.

`search(terminal_id, "FAILED")` finds a plain substring in the screen and the
history above it, newest match first (`case_sensitive=True`, `limit=N`).
`recording(terminal_id)` returns the session as the text of an asciicast v2
file, for `asciinema play` (`idle_time_limit=2` shortens long pauses on replay).

`write()` takes `str` or `bytes`, at most 64 KiB a call. Finish each write
before the next: two in flight together can arrive in either order. It is not
re-sent after a failure that may have reached the server.

`stream()` ends when the terminal does, and `stream.terminal` is then the ended
terminal. A dropped connection is reopened at `stream.offset` (the last
`next_offset`), so no byte is yielded twice; a chunk with `truncated=True`
means the output before its `offset` was rotated away. After `max_reconnects`
(default 10) consecutive failed reconnects it raises `SandboxApiError` with code
`STREAM_DISCONNECTED`. Leaving the `with` block, or `close()` / `await
aclose()`, stops the stream and leaves the terminal running;
`terminals.close(terminal_id)` ends the terminal itself.

A sandbox that cannot run terminals (an older image) raises
`SandboxTerminalUnsupportedError`, and an unknown terminal ID raises
`SandboxTerminalNotFoundError`. Neither is retried.

## Durable long-running agents

Use `DurableRunClient` with the `next-temporal-rs` control plane. Workflow IDs are
safe to persist: status calls and event streams can reconnect after the caller restarts.

```python
from stateset_sandbox import (
    DurableRunClient,
    SandboxAgentLoopInput,
    SandboxSessionBudget,
    SandboxSessionSpec,
    StartSandboxAgentLoopInput,
)

durable = DurableRunClient(
    base_url="https://workflows.example.com",
    api_key="engine-key",
)
run = durable.start_sandbox_agent_loop(StartSandboxAgentLoopInput(
    brand_id="brand_123",
    request_id="request_123",
    loop=SandboxAgentLoopInput(
        session=SandboxSessionSpec(
            isolation="gvisor",
            budget=SandboxSessionBudget(iteration_limit=20),
        ),
        commands=[["python", "/workspace/agent.py"]],
    ),
))

for event in durable.iter_events(run.workflow_id, last_event_id=0):
    print(event.event, event.data)
```

`AsyncDurableRunClient` exposes the same lifecycle controls for asyncio applications.

## Parallel agent orchestration

`MultiAgentOrchestrator` accepts any async runner implementing `run_and_cleanup`.
Ready workers start in submitted order with bounded concurrency and optional
retries, fail-fast scheduling, lifecycle events, and synthesis. `depends_on`
waits for successful prerequisites and includes their outputs in the assignment.
Results retain submitted order even when the dependency graph executes out of order.

```python
from stateset_sandbox import MultiAgentOrchestrator, MultiAgentWorker

orchestrator = MultiAgentOrchestrator(
    runner=my_agent_runner,
    max_concurrency=4,
    max_attempts=2,
)
result = await orchestrator.run(
    task="Review the service before release",
    workers=[
        MultiAgentWorker(id="security", role="security reviewer", prompt="Audit auth boundaries"),
        MultiAgentWorker(id="tests", role="test reviewer", prompt="Find coverage gaps"),
        MultiAgentWorker(id="plan", role="planner", prompt="Combine the findings",
                         depends_on=("security", "tests")),
    ],
    synthesis=True,
)
```

The graph is validated before launching any agent: unknown, duplicate, self, and
cyclic dependencies fail admission. There can be at most 500 workers and 32
dependencies per worker. A failed prerequisite makes downstream workers `blocked`
with zero attempts; independent work can continue. Configure retries only for
tasks whose effects are safe to repeat.

Setting `cancel_event` prevents queued work and retries; active attempts settle
before returning. Cancelling the orchestration task cancels and awaits active
runner tasks, whose implementations must perform cleanup on cancellation.
The local scheduler keeps its queue in memory. Use `AsyncDurableRunClient` with
Temporal Active Horizon when the work must recover after process restarts.

## Code Interpreter

`CodeInterpreter` runs Python in a persistent Jupyter kernel inside the sandbox (one REPL
session per interpreter, opened on the first `run()`): variables and imports persist between
calls, and plots, HTML and JSON come back as rich results.

```python
from stateset_sandbox import CodeInterpreter

with CodeInterpreter(client) as ci:          # creates a sandbox; or pass sandbox_id=...
    ci.run("import math; r = 2")
    area = ci.run("math.pi * r ** 2")
    area.text                                 # '12.566370614359172' (the cell's value)

    plot = ci.run("import matplotlib.pyplot as plt; plt.plot([1, 3, 2]); plt.show()")
    plot.png                                  # base64 PNG; plot.results[0].png_bytes() decodes it

    failed = ci.run("1 / 0")
    failed.error.name, failed.error.value     # ('ZeroDivisionError', 'division by zero')
# leaving the block deletes the REPL session and stops the sandbox it created
```

- `run()` calls are serialized with a lock (a kernel runs one cell at a time).
- `timeout` (seconds, default 30) interrupts a long cell: `result.timed_out` is `True`,
  `result.error.name == "TimeoutError"`, and the kernel keeps its state.
- Other languages (`node`, `bash`, `sh`, `ruby`) and `CodeInterpreter(..., stateful=False)` run
  each snippet as a one-off script (stdout/stderr/exit code; no state).
- When the deployment has REPL disabled or the image has no Jupyter server, the interpreter
  falls back to script mode and emits a `RuntimeWarning`.

## API Reference

### Client

`StateSetSandbox` is the full client; it is also a context manager that closes
its connections on exit:

```python
from stateset_sandbox import StateSetSandbox

with StateSetSandbox(
    base_url="https://api.sandbox.stateset.app",
    auth_token="sk_test_xxx",  # API key or JWT token
    org_id="org_xxx",          # Optional: pins requests to this org (sent as X-Org-Id)
    timeout=30000,             # Request timeout in ms (default: 30000)
    api_version="v1",          # API version (default: v1)
) as client:
    sandbox = client.create()
    result = client.execute(sandbox.sandbox_id, command=["python", "--version"])
    print(result.stdout)
    client.stop(sandbox.sandbox_id)
```

The examples below use this `client` and the `sandbox` it created.

### Sandbox Operations

#### Create a Sandbox

```python
from stateset_sandbox import CreateSandboxOptions

# Basic creation
sandbox = client.create()

# With options
sandbox = client.create(CreateSandboxOptions(
    cpus="500m",           # CPU limit
    memory="512Mi",        # Memory limit
    timeout_seconds=3600,  # Sandbox lifetime
    env={"DEBUG": "true"}, # Environment variables
))

# From a template (create_from_template; `template` is not a create option)
sandbox = client.create_from_template("python-basic")
```

#### Execute Commands

```python
# Simple command
result = client.execute(sandbox.sandbox_id, command="echo hello")

# Command with options
result = client.execute(
    sandbox.sandbox_id,
    command=["python", "-c", "print('Hello')"],
    timeout=60000,  # Command timeout in ms
    env={"PYTHONPATH": "/app"},
    cwd="/workspace"
)

print(result.exit_code)  # 0
print(result.stdout)     # Hello
print(result.stderr)     #
```

#### Streaming Execution

```python
client.execute_stream(
    sandbox.sandbox_id,
    command=["python", "long_running_script.py"],
    on_stdout=lambda data: print(f"OUT: {data}"),
    on_stderr=lambda data: print(f"ERR: {data}"),
    on_exit=lambda code: print(f"Exit code: {code}"),
    on_error=lambda err: print(f"Error: {err}")
)
```

#### File Operations

```python
# Write a single file
client.write_file(sandbox.sandbox_id, "/workspace/main.py", "print('Hello')")

# Write multiple files
client.write_files(sandbox.sandbox_id, [
    {"path": "/workspace/main.py", "content": "print('Hello')"},
    {"path": "/workspace/utils.py", "content": "def helper(): pass"}
])

# Read a file
content = client.read_file(sandbox.sandbox_id, "/workspace/main.py")
print(content)  # print('Hello')
```

```python
sid = sandbox.sandbox_id

# Find files; path is the directory to search (the server searches /workspace without it)
files = client.glob(sid, "**/*.py", path="/workspace/src")
for entry in files:
    print(entry["path"], entry["size"])

# Create a directory (parents too, unless recursive=False)
client.mkdir(sid, "/workspace/backup")

# Copy a directory: recursive=True is required for one (default False copies a file)
client.copy_file(sid, "/workspace/src", "/workspace/backup/src", recursive=True)

# Move or rename
client.move_file(sid, "/workspace/main.py", "/workspace/app.py")

# Delete a file, or a directory with recursive=True
client.delete_file(sid, "/workspace/backup", recursive=True)
```

### Checkpoints

Save and restore sandbox state:

```python
from stateset_sandbox import CreateCheckpointOptions

# Create a checkpoint
checkpoint = client.create_checkpoint(
    sandbox.sandbox_id,
    CreateCheckpointOptions(
        name="after-setup",
        description="Initial environment setup complete",
        include_paths=["/app", "/data"],
        exclude_paths=["/workspace/node_modules"],
        include_env=True
    )
)

# List checkpoints
checkpoints = client.list_checkpoints(sandbox_id=sandbox.sandbox_id)

# Restore a checkpoint to a new sandbox
new_sandbox = client.create()
client.restore_checkpoint(
    new_sandbox.sandbox_id,
    checkpoint.id,
    restore_files=True,
    restore_env=True
)

# Clone a checkpoint
cloned = client.clone_checkpoint(checkpoint.id, name="checkpoint-copy")

# Delete a checkpoint
client.delete_checkpoint(checkpoint.id)
```

### Artifacts

Upload and manage files in cloud storage:

```python
from stateset_sandbox import UploadArtifactOptions

# Upload an artifact
artifact = client.upload_artifact(
    sandbox.sandbox_id,
    UploadArtifactOptions(
        path="/workspace/output/report.pdf",
        content_type="application/pdf",
        expires_in=86400,  # 24 hours
        metadata={"version": "1.0"}
    )
)

# Get download URL
url = client.get_artifact_url(artifact.id, expires_in=3600)

# List artifacts
artifacts = client.list_artifacts(sandbox_id=sandbox.sandbox_id)

# Delete artifact
client.delete_artifact(artifact.id)
```

### Webhooks

Receive notifications for sandbox events:

```python
from stateset_sandbox import CreateWebhookOptions, WebhookEvent

# Create a webhook
webhook = client.create_webhook(CreateWebhookOptions(
    url="https://your-server.com/webhook",
    events=[WebhookEvent.SANDBOX_CREATED, WebhookEvent.SANDBOX_STOPPED],
    secret="your-signing-secret",
    headers={"X-Custom-Header": "value"}
))

# List webhooks
webhooks = client.list_webhooks()

# Test a webhook
result = client.test_webhook(webhook.id)

# View delivery history
deliveries = client.get_webhook_deliveries(webhook.id, limit=50)

# Delete webhook
client.delete_webhook(webhook.id)
```

### Audit Logs

Track all operations for compliance:

```python
# List audit events
result = client.list_audit_events(
    sandbox_id=sandbox.sandbox_id,
    action="command.execute",
    outcome="success",
    limit=100
)

for event in result["events"]:
    print(f"{event.timestamp}: {event.action} - {event.outcome}")

# Get sandbox audit summary
summary = client.get_sandbox_audit_summary(sandbox.sandbox_id)
print(f"Commands executed: {summary.commands_executed}")
print(f"Files written: {summary.files_written}")
```

### Secrets

Securely manage and inject secrets:

```python
from stateset_sandbox import CreateSecretOptions

# Create a secret
secret = client.create_secret(CreateSecretOptions(
    name="DATABASE_URL",
    value="postgres://user:pass@host/db",
    scope="sandbox"
))

# List secrets (values not included)
secrets = client.list_secrets()

# Inject secrets into a sandbox
injected = client.inject_secrets(
    sandbox.sandbox_id,
    secrets=["DATABASE_URL", "API_KEY"]
)
# Or inject all secrets
injected = client.inject_secrets(sandbox.sandbox_id, all_secrets=True)

# Update a secret
client.update_secret("DATABASE_URL", "postgres://new-url")

# Delete a secret
client.delete_secret("DATABASE_URL")
```

### API Keys

Manage API keys programmatically:

```python
from stateset_sandbox import CreateApiKeyOptions

# Create an API key
response = client.create_api_key(CreateApiKeyOptions(
    name="production-key",
    expires_in_days=365,
    scopes=["sandbox:create", "sandbox:write"]
))
print(f"New API key: {response.key}")  # Only shown once!

# List API keys
keys = client.list_api_keys()

# Revoke an API key
client.revoke_api_key(key_id)
```

### Swarms

A swarm is one goal split into tasks with dependencies, each task done by a
coding agent in a sandbox of its own. The service keeps the plan and its
progress; these calls store and report only, and none of them starts, stops or
touches a sandbox. Creating, cancelling and reporting need `sandbox:write`;
reading needs `sandbox:read`.

```python
from stateset_sandbox import (
    CreateSwarmOptions,
    SandboxApiError,
    SandboxConflictError,
    SwarmStatus,
    SwarmTaskInput,
    SwarmTaskReport,
)

# Store a swarm (201). Tasks that depend on nothing start `ready`, the others `waiting`.
swarm = client.create_swarm(
    CreateSwarmOptions(
        name="checkout-rework",
        goal="Move checkout to the new tax service.",
        repository={"url": "https://github.com/acme/app.git", "base": "4f2c1d9"},
        tasks=[
            SwarmTaskInput(key="schema", name="Schema", objective="Write the schema."),
            SwarmTaskInput(
                key="api", name="API", objective="Write the routes.", depends_on=["schema"]
            ),
        ],
    )
)
print(swarm.id, swarm.status, [(t.key, t.phase) for t in swarm.tasks])

# List swarms, newest first. Summaries carry no tasks.
page = client.list_swarms(status=SwarmStatus.RUNNING, limit=20)
while True:
    for summary in page.swarms:
        print(summary.id, summary.name, summary.status)
    if page.next_cursor is None:
        break
    page = client.list_swarms(status=SwarmStatus.RUNNING, limit=20, cursor=page.next_cursor)

# One swarm with its tasks
swarm = client.get_swarm(swarm.id)

# Report a task: phase is "running", "accepted" or "failed". The answer is the
# swarm after the report, with the tasks it unblocked or blocked.
client.report_swarm_task(
    swarm.id, "schema", SwarmTaskReport(phase="running", sandbox_id="sb_41c0")
)
swarm = client.report_swarm_task(
    swarm.id,
    "schema",
    SwarmTaskReport(phase="accepted", branch="agent/schema", cost_cents=125),
)
# A coordinator that reviews the work can say what the review cost (part of
# cost_cents) and its verdict; both are left out when not given.
swarm = client.report_swarm_task(
    swarm.id,
    "api",
    SwarmTaskReport(
        phase="failed",
        error="review rejected the routes",
        cost_cents=90,
        review_cost_cents=15,
        review_verdict="rejected",
    ),
)

# The report: per task its outcome, attempts and cost (work and review), in
# plan order, and the swarm's totals. `not_stored` names the figures the
# service cannot give (planning cost, time per phase).
report = client.get_swarm_report(swarm.id)
for task in report.tasks:
    print(task.key, task.outcome, task.attempts, task.work_cost_cents, task.review_cost_cents)
print(report.totals.outcomes.accepted, report.totals.cost_cents.total, report.wall_time_seconds)

# Cancel the swarm and its unfinished tasks in the record (stops no sandbox)
try:
    swarm = client.cancel_swarm(swarm.id)
except SandboxConflictError as e:
    print(e.message)  # already completed or failed: nothing to cancel
except SandboxApiError as e:
    if e.code != "SWARM_NOT_FOUND":
        raise
    print(e.details)  # {"swarm_id": "..."}
```

| Call | Request | Returns |
|---|---|---|
| `create_swarm(options)` | `POST /swarms` | `Swarm` |
| `list_swarms(status=None, limit=None, cursor=None)` | `GET /swarms` | `SwarmPage` (`swarms`, `next_cursor`) |
| `get_swarm(swarm_id)` | `GET /swarms/:id` | `Swarm` |
| `get_swarm_report(swarm_id)` | `GET /swarms/:id/report` | `SwarmReport` (`tasks`, `totals`, `not_stored`) |
| `cancel_swarm(swarm_id)` | `POST /swarms/:id/cancel` | `Swarm` |
| `report_swarm_task(swarm_id, key, report)` | `PATCH /swarms/:id/tasks/:key` | `Swarm` |

- `repository` and `defaults` are stored and returned as given; the service
  does not read them. Fields left unset are not sent.
- `create_swarm` sends a random `Idempotency-Key` of its own with each call,
  which the caller cannot set, so calling it again stores a second swarm; the
  service gives the first answer only to a request with the same key, within
  24 hours. Within one call the request is sent again, with the same key,
  only when the server certainly did not act (429 `RATE_LIMIT_EXCEEDED`, 503,
  or a failure to connect), never after a timeout or another 5xx.
- The swarm id and the task key are each sent as one escaped path component;
  an empty one, `.` or `..` raises `ValueError` before any request.
- Errors: a 404 is a plain `SandboxApiError` with `code` `SWARM_NOT_FOUND`
  (`details["swarm_id"]`) or `SWARM_TASK_NOT_FOUND` (also `details["key"]`),
  not a `SandboxNotFoundError`, which is for sandboxes. A 409 is a
  `SandboxConflictError`: cancelling a swarm that has completed or failed, or
  a report the task's phase does not allow (the message says which). A plan
  the service refuses is a 400 `VALIDATION_ERROR`. An organization with too
  many unfinished swarms gets 429 `CONCURRENT_LIMIT_EXCEEDED`
  (`details["limit"]`, `details["current"]`), which is not retried.
- These are methods of the sync client `StateSetSandbox`. `AsyncSandbox` is a
  handle on one sandbox and has none of them.

### Usage & Billing

```python
# Get current usage
usage = client.get_current_usage()
print(f"CPU hours: {usage.cpu_hours}")
print(f"Estimated cost: ${usage.estimated_cost_cents / 100:.2f}")

# Get usage history
history = client.get_usage_history(
    granularity="daily",
    start_date="2025-01-01",
    end_date="2025-01-15"
)

# Get subscription info
subscription = client.get_subscription()
print(f"Plan: {subscription.plan}")

# Get Stripe billing portal URL
portal_url = client.get_billing_portal(return_url="https://your-app.com/billing")

# List invoices
invoices = client.list_invoices(limit=10)
```

### Registration (deprecated)

Accounts are created in the dashboard: sign up at
https://sandbox.stateset.app/signup, then create an API key there (see
[Get an API key](#get-an-api-key)).

`register()` is deprecated: it emits a `DeprecationWarning` and will be removed
in a future release. It still calls `POST /api/v1/register` as before, but it
cannot create an account: the server requires a password, which the helper
does not send, and, on the hosted service, a signup CAPTCHA token. Without a
valid token it raises `CaptchaRequiredError`, whose `signup_url` points to the
dashboard.

## Error Handling

```python
from stateset_sandbox import (
    SandboxError,
    SandboxApiError,
    SandboxTimeoutError,
    SandboxNetworkError,
    SandboxNotFoundError,
    SandboxAuthenticationError,
    SandboxRateLimitError,
    PaymentMethodRequiredError,
)

try:
    sandbox = client.create()
    result = client.execute(sandbox.sandbox_id, command=["python", "script.py"])
except PaymentMethodRequiredError as e:
    print(f"Add a card before your first sandbox: {e.billing_url}")
except SandboxNotFoundError as e:
    print(f"Sandbox not found: {e.sandbox_id}")
except SandboxAuthenticationError:
    print("Invalid API key or token")
except SandboxRateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except SandboxTimeoutError as e:
    print(f"Request timed out after {e.timeout_ms}ms")
except SandboxNetworkError as e:
    print(f"Network error: {e.original_error}")
except SandboxApiError as e:
    print(f"API error [{e.code}]: {e.message}")
    print(f"Request ID: {e.request_id}")
```

Errors for new accounts:

| Exception | HTTP / code | Meaning |
|---|---|---|
| `PaymentMethodRequiredError` | 402 `PAYMENT_METHOD_REQUIRED` | The organization has no card on file. Every way of starting a sandbox (create, templates, snapshot restore, resume, agent sessions) raises it. Add a card at `e.billing_url` (the dashboard billing page); it is not charged while trial credits last. Not retryable until then. Different from 402 `PAYMENT_REQUIRED` (no subscription and the trial is used up), which stays a plain `SandboxApiError`. |
| `CaptchaRequiredError` | 400 `CAPTCHA_REQUIRED` | The deprecated `register()` without a valid signup CAPTCHA token (`e.reason`: `missing` or `rejected`). Sign up at `e.signup_url` instead. |

Both are subclasses of `SandboxApiError`, and are also exported as
`SandboxPaymentMethodRequiredError` and `SandboxCaptchaRequiredError`.

## Requirements

- Python 3.10–3.13
- httpx >= 0.27.0
- pydantic >= 2.7.0

## License

MIT
