# Python SDK

Run and manage Hermitbox sandboxes from Python, synchronously or with asyncio. Create sandboxes, run
commands, stream output, transfer files, snapshot, and fork over the Hermitbox API.

## Install

On Python 3.12 or later:

```sh
pip install https://github.com/hermitbox/hermitbox/releases/download/v0.2.1/hermitbox-0.2.1-py3-none-any.whl
```

Set `HERMITBOX_API_URL` and `HERMITBOX_API_KEY` to the values the installer printed.

## Quickstart

```python
from hermitbox import Hermitbox

# Connect with HERMITBOX_API_URL and HERMITBOX_API_KEY from the environment.
with Hermitbox() as hb:
    # Create a container sandbox that sleeps after ten idle minutes.
    box = hb.sandbox(image='node:22', idle='10m')

    try:
        # Write a file and run it.
        box.write('hello.js', 'console.log("hello")')
        result = box.run('node /data/hello.js')

        # Stop if the command failed.
        if result.code != 0:
            raise RuntimeError(result.stderr)
        print(result.stdout)  # hello
    finally:
        # Delete it, even when something failed.
        box.delete()
```

On a host whose default tier is `process` or `wasm`, leave out `image`.

## Reference

Durations are positive seconds or `s`, `m`, `h`, `d` strings. String commands use `sh -c`, and
argv bypasses the shell. Commands run in persistent storage unless `cwd` overrides it.

Paths are relative to persistent storage (`/data`). Binary data streams through the agent while the
sandbox runs and through the node while it is stopped. File operations need no shell tools.

Each call carries one generated idempotency key, and no mutation retries automatically. Output
capture and observation queues are bounded: overflow is explicit, and the result stays available.

A missing exit is an unknown outcome, and a disconnect does not end the process. `HermitboxError`
keeps the status, code and details. Credentials never enter serialized views.

Use `async with Hermitbox(url=..., key=...) as hb:` for asynchronous handles with the same names.
Await I/O methods, `run` and `stream.result()`, and use `async for` on streams.

Sync `run` returns a `RunResult` once the command completes, with no `wait()` call. Result fields
use snake_case (`timed_out`, `stdout_truncated`, `duration_ms`). Create and process identity uses
`key=`, options are keyword arguments, and `timeout=` accepts durations.

| Method | Behavior |
| --- | --- |
| `hb.sandbox(id \| **options)` | Create with `env`, `labels`, `name`, `workdir`, `user`, `autoDelete`, `egress`, `metadata` or `repo`; `name=` alone looks up; lookup wakes unless `wake=False`. |
| `hb.sandboxes(filters)` | Filter project handles by name, labels and state. |
| `hb.project()` | Project usage and limits. |
| `hb.run(image, command, options)` | Create, run and delete in a finally block. |
| `box.run(command, options)` | Start now; return the result (a native asyncio Task on the async handle). |
| `box.stream(command, options)` | Start now; iterate live chunks once, synchronously or asynchronously. |
| `stream.lines()` | Iterate complete stdout/stderr lines. |
| `stream.result()` | Await the same command result without starting it again. |
| `box.spawn(command, options)` | Start a process; stdin accepts one-shot string or bytes. |
| `box.start()` | Start sandbox compute. |
| `box.stop()` | Stop compute; retain data. |
| `box.sleep()` | Suspend or stop while retaining data. |
| `box.wake()` | Resume or recreate compute. |
| `box.rest()` | Archive data and release compute. |
| `box.refresh()` | Refresh the view and invalidate its cached capability. |
| `box.delete()` | Delete sandbox and owned data. |
| `box.read(path)` | Read UTF-8 persistent data. |
| `box.read_bytes(path)` | Read persistent bytes. |
| `box.read_stream(path)` | Read a byte stream without collecting the file. |
| `box.write(path, data)` | Write strings, bytes, streams or async iterables. |
| `box.snapshot()` | Create a snapshot handle. |
| `box.snapshots()` | List snapshot handles. |
| `snapshot.fork(options)` | Create a sandbox from the snapshot. |
| `snapshot.delete()` | Delete the snapshot. |
| `box.endpoints()` | List assigned application endpoints. |
| `box.events(options)` | Iterate lifecycle records with since and follow. |
| `box.logs(**options)` | Read or follow agent logs. |
| `box.terminal(options)` | Open a PTY with optional rows and cols. |
| `box.mcp_url()` | Scoped sandbox-local MCP URL. |
| `box.expose(port)` | Publish a spare port and return its URL. |
| `box.unexpose(port)` | Release an exposed spare. |
| `box.network(mode)` | Replace compute with internet or none policy. |
| `process.wait()` | Wait for its terminal status. |
| `process.events()` | Read agent output/exit frames. |
| `process.stream()` | Read decoded stdout/stderr chunks. |
| `process.lines()` | Read complete lines. |
| `process.stdin.write(data)` | Send string or bytes. |
| `process.stdin.close()` | Close input. |
| `process.signal(signal)` | Signal the process. |
| `process.kill()` | Kill the process. |
| `process.resize(cols, rows)` | Resize its PTY. |
| `terminal.stdin.write(data)` | Send terminal input. |
| `terminal.resize(cols, rows)` | Resize the terminal. |
| `terminal.signal(signal)` | Signal the terminal process. |
| `terminal.events()` | Read terminal frames. |
| `terminal.stream()` | Read terminal output. |
| `terminal.close()` | Close the terminal. |
| `files.read(path)` | Read UTF-8 text. |
| `files.read_bytes(path)` | Read bytes. |
| `files.read_stream(path)` | Stream bytes. |
| `files.write(path, data)` | Write persistent data. |
| `files.list(path)` | List directory entries. |
| `files.stat(path)` | Read file metadata. |
| `files.mkdir(path)` | Create directories. |
| `files.move(source, target)` | Move a persistent entry. |
| `files.delete(path)` | Delete a persistent entry. |
| `files.watch(path)` | Ready frame, then bounded changes. |
| `files.url(path, method)` | Grant one file operation for at most one minute. |
| `files.upload(local, remote, options)` | Stream caller disk to the sandbox with `on_progress`. |
| `files.download(remote, local, options)` | Stream to caller disk with `on_progress`. |
| `box.processes()` | List retained process handles. |
| `box.kill_all()` | Signal all running processes once. |
| `process.wait_for_port(port, options)` | Await owned TCP or HTTP readiness; timeout and early exit differ. |
| `process.wait_for_log(pattern, timeout)` | Await a bounded regular expression match in either stream. |
| `process.wait_for_exit(timeout)` | Await exit with a deadline. |
| `process.logs()` | Read retained process stdout/stderr chunks. |
| `box.shell(options)` | Open a persistent shell with cwd and env. |
| `shell.run(command, options)` | Run serially with exact separate streams and exit code. |
| `shell.close()` | Close and terminate that session. |
| `files.exists(path)` | Test existence without following links. |
| `files.find(glob)` | Find relative paths within the agent search budget. |
| `files.grep(pattern, options)` | Return path, line and matching text; paths scope the search. |
| `files.replace(pattern, text, options)` | Replace literal text at regex matches; preserve modes. |
| `files.chmod(path, mode)` | Set ordinary permission bits. |
| `files.upload_dir(local, remote, options)` | Stream a bounded tar; preserve files and empty directories. |
| `files.download_dir(remote, local, options)` | Extract a bounded tar; refuse links and traversal. |
| `box.sync(local, remote)` | Upsert changed content by SHA-256; never delete. |
| `box.git.clone(url, options)` | Clone public/HTTPS credentials with path, branch and depth. |
| `box.git.status()` | Parsed clean flag and entries, plus raw result. |
| `box.git.diff(options)` | Parsed patch, optionally staged, plus raw result. |
| `box.git.branch(name=None)` | List or create branches, plus raw result. |
| `box.git.checkout(ref, options)` | Checkout or create a branch, plus raw result. |
| `box.git.add(paths)` | Stage paths without shell interpolation. |
| `box.git.commit(message, options)` | Commit with optional author; return hash and raw result. |
| `box.git.push(options)` | Push with an optional one-call token helper. |
| `box.git.pull()` | Fast-forward pull, plus raw result. |
| `box.git.log(options)` | Parsed commit records with limit, plus raw result. |
| `box.keep_alive(duration)` | Extend access and touch activity within project ceilings. |
| `box.set_ttl(duration)` | Set TTL from now within the project ceiling. |
| `box.set_idle(duration)` | Set the idle timeout within the project ceiling. |
| `box.metrics(options)` | Latest node sample, or retained minute series with since. |
| `box.wait_until(state, timeout)` | Poll the public state until reached or timed out. |
| `hb.template(options)` | Build copy/run/ready on a node with from_, publish a snapshot version. |
| `template.rebuild()` | Build a new immutable version from the same local context. |
| `hb.templates()` | List project template versions. |
| `hb.webhook(options)` | Register lifecycle delivery and show its secret once. |
| `hb.webhooks()` | List registrations without secrets. |
| `webhook.delete()` | Delete this registration. |
| `webhook.deadletters()` | Inspect exhausted deliveries. |

Handles expose `id`, `state`, `isolation`, `units` and `files`. Option and result models are
exported alongside the seven handle and error classes. Models come from the committed OpenAPI.
See [agent security](https://docs.hermitbox.dev/v0.2.1/reference/sandbox-agent.md) and [tiers](https://docs.hermitbox.dev/v0.2.1/reference/tiers.md).

Git works in `repo` by default, and a clone changes that handle's path. Tokens go through a
one-call credential helper, never a credential file. A public clone needs permitted internet access
and Git in the image or userland; the wasm tier stages its Git package on demand.

Git clone, push and pull default to five minutes, and other Git operations use the normal command
budget. Every method accepts a timeout override. Background maintenance and every Git trace
destination stay off during helper calls.

Wasm clones keep metadata in persistent guest storage and checkout files in data, and both survive
stop and snapshots.

Shells use serialized pipes with independent stdout and stderr markers. Search and tar budgets and
link refusals are in [agent security](https://docs.hermitbox.dev/v0.2.1/reference/sandbox-agent.md).

Container hostname egress needs the host firewall feature its node advertises. Process sandboxes
take it where their node announces kernel network policy ([bpf](https://docs.hermitbox.dev/v0.2.1/reference/bpf.md)), and wasm refuses
it, naming the tier. Webhook signatures and retry limits are in [the API reference](https://docs.hermitbox.dev/v0.2.1/reference/api.md).

## AI integrations

Each adapter's `hermitbox_tools(box)` takes an existing asynchronous sandbox handle. Its tools read,
write, list and search sandbox files. Set `read_only=True` or pass an `allow` list of tool names to
limit access, and `cwd="src"` to scope the paths.

With the sandbox root in scope, the AI tools can also snapshot, fork an owned snapshot, sleep and
wake the bound sandbox. Read-only access and subdirectory scopes omit these whole-sandbox actions.

### OpenAI Agents SDK

Install `hermitbox[ai-openai]` and pass the tools from
`hermitbox.ai.openai.hermitbox_tools(box)` to an Agent.
[Agents runner example](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/examples/ai-openai/read_project.py)

### Anthropic Messages SDK

Install `hermitbox[ai-anthropic]` and pass the tools from
`hermitbox.ai.anthropic.hermitbox_tools(box)` to the Messages tool runner.
[Messages runner example](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/examples/ai-anthropic/read_project.py)

### Pydantic AI

Install `hermitbox[ai-pydantic]` and pass
`hermitbox.ai.pydantic.hermitbox_tools(box)` as an Agent's `tools`.
[Pydantic AI example](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/examples/ai-pydantic/read_project.py)

### LangChain and LangGraph

Install `hermitbox[ai-langchain]`. The LangChain structured tools returned by
`hermitbox.ai.langchain.hermitbox_tools(box)` run in LangGraph tool nodes and
LangChain agents. With `stream_mode="custom"`, project tasks emit bounded stdout
and stderr chunks as they arrive. The tool result includes the exit status.
[LangGraph-backed agent example](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/examples/ai-langchain/read_project.py)

### LlamaIndex

Install `hermitbox[ai-llamaindex]` to pass the tools returned by
`hermitbox.ai.llamaindex.hermitbox_tools` to a LlamaIndex function agent.
[LlamaIndex example](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/examples/ai-llamaindex/read_project.py)

### CrewAI

Install `hermitbox[ai-crewai]` for CrewAI tools. Use the asynchronous agent
entry point with your AsyncSandbox.
[CrewAI example](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/examples/ai-crewai/read_project.py)

### Google ADK

Install `hermitbox[ai-adk]` for Google ADK tools. The ADK selects
websockets 15.0.1. The regular SDK also supports 17.4.
[ADK example](https://github.com/hermitbox/hermitbox/blob/75b22d18abc93b8be54b6ae2324b97ed713be910/examples/ai-adk/read_project.py)

### Commands and ports

For project tasks, `hermitbox_tools(box, commands=[['npm', 'test']], ports=[3000])` lets the model run
that exact argument vector and open the selected preview port. The run tool waits for the exit
status, and a background start returns a process ID for the output tool.

Results include a truncation flag and a pointer to the SDK stream when output exceeds the model's
budget. Read-only and subdirectory catalogs omit task and preview tools.
