页面简介
Run a Pydantic AI agent's commands and file edits in an isolated boxd cloud machine instead of on your machine.
正文摘录
boxd Sandbox Run your agent’s commands and file edits in an isolated boxd cloud machine instead of on your machine. Source While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy. flowchart TB accTitle: boxd Sandbox: your agent's commands run in a boxd cloud machine accDescr: On your machine, the model calls Coder, Shell or FileSystem tools like run_command. Via ctx.workspace, BoxdSandbox's get_workspace hands the run a boxd cloud machine over the boxd API with BOXD_API_KEY. Later runs reattach with the WorkspaceRef in the message history or result.workspace.ref, destroy(ref) deletes the machine and fork(ref) copies it with its files and processes. subgraph machine["Your machine"] model(["model"]) tools["Coder, Shell or<br/>FileSystem tools,<br/>such as run_command"] ref["WorkspaceRef<br/>in the message history,<br/>result.workspace.ref"] boxd["BoxdSandbox()<br/>get_workspace hands<br/>the run a boxd machine"]:::capability end sandbox["boxd cloud machine<br/>created on first use,<br/>deleted by destroy(ref)"]:::external copy["copy of the machine<br/>starts with the same<br/>files and processes"]:::external model <-->|"tool call, result"| tools tools -->|"ctx.workspace"| boxd ref -.->|"a later run reattaches"| boxd boxd <-->|"boxd API,<br/>BOXD_API_KEY"| sandbox sandbox -->|"fork(ref)"| copy classDef capability stroke:#E520E9,stroke-width:2px classDef external stroke:#0E9C86,stroke-width:2px Install pip uv Terminalpip install "pydantic-ai-harness[coder,boxd,anthropic]" Set BOXD_API_KEY to an API key from boxd auth keys create. Each key belongs to one boxd organization. The examples also use Coder and an Anthropic model, so they need the coder and anthropic extras and ANTHROPIC_API_KEY. Swap them for your own tools and model provider. Quick start from pydantic_ai import Agent from pydantic_ai_harness.boxd_sandbox import BoxdSandbox from pydantic_ai_harness.coder import Coder agent = Agent('anthropic:claude-opus-5-5', capabilities=[BoxdSandbox(), Coder()]) result = agent.run_sync('Clone https://github.com/pydantic/pydantic-ai and summarize how capabilities work.') Coder’s shell and file tools now run in a boxd machine. For a narrower agent, use Shell, FileSystem or your own tools on ctx.workspace. Coder creates it when the run starts, to load the repository’s instructions, even if no tool is called. Pass Coder(repo_context=False) to wait for the first tool call. It keeps its disk until you delete it. boxd suspends it when idle, but never deletes it unless your organization’s defaults say so. See Clean up. Commands run as the non-root boxd user in /home/boxd, with passwordless sudo. Pass working_dir='/home/boxd/project' to give the agent a project directory. It is created on a new machine. The default image is Ubuntu 24.04 with git, Python 3, uv, Node.js and rg, but not your project’s dependencies. Install them in a machine and save it as a snapshot, a copy new machines can start from, with boxd snapshots save. Then pass snapshot='my-snapshot'. An unknown snapshot, or one still saving, fails on first use with WorkspaceUnavailableError. It can reach the internet, and has a public HTTPS address that serves the port its code listens on. See Security model. Continue in the same machine Pass the message history, and the next run works in the same machine, waking or starting it if needed: from pydantic_ai import Agent from pydantic_ai_harness.boxd_sandbox import BoxdSandbox from pydantic_ai_harness.coder import Coder agent = Agent('anthropic:claude-opus-5-5', capabilities=[BoxdSandbox(), Coder()]) result = agent.run_sync('Clone https://github.com/pydantic/pydantic-ai and summarize how capabilities work.') followup = agent.run_sync( 'Which capability would you add next, and where would it live?', message_history=result.all_messages(), ) ref = result.workspace.ref # or store this, and pass `workspace=ref` to a later run The history records the machine as a WorkspaceRef, or “ref”: the provider’s name and the machine’s ID. result.workspace.ref is the same ref, for continuing without the history. If the machine has been deleted, the run raises WorkspaceUnavailableError. Pass workspace='new' to start over. Workspaces covers how runs find their workspace. The ref holds no credentials, so the process that reattaches needs BOXD_API_KEY or a client= too. Prepare a machine before the run To seed files before the agent starts, build the backend yourself, write through a Workspace, and pass the backend to the run: from pydantic_ai import Agent from pydantic_ai.workspaces import Workspace from pydantic_ai_harness.boxd_sandbox import BoxdSandbox, BoxdSandboxBackend from pydantic_ai_harness.coder import Coder agent = Agent('anthropic:claude-opus-5-5', capabilities=[BoxdSandbox(), Coder()]) async def run_in_prepared_machine() -> str: backend = BoxdSandboxBackend(working_dir='/home/boxd/project') try: await Workspace(backend).write_text('TASK.md', 'Add a `--version` flag to cli.py.\n') result = await agent.run('Do the task in TASK.md.', workspace=backend) return result.output finally: await backend.aclose() ref = backend.ref # set once the machine exists if ref is not None: await BoxdSandbox().destroy(ref) The run leaves a backend you built open, so close it with aclose(). That closes the client it opened from the environment, not the machine. A client= you passed is never closed. To keep the machine, store backend.ref instead of destroying it. For boxd features the workspace API doesn’t cover, such as snapshots and public URLs, await backend.get_sandbox() returns the machine’s boxd.Machine record. Use its id with your own boxd.AsyncBoxd. Give the agent a desktop Pass desktop=True and add ComputerUse: capabilities=[BoxdSandbox(desktop=True), ComputerUse()]. The screen is 1280x800; pass a size such as desktop=(1440, 900) for another. Machines on boxd’s current default image come with a desktop, with a panel that opens a terminal and boxd’s Chromium browser. A fork or snapshot of an older image has none, so use a fresh machine. On an attached machine, the first screen call installs the panel and terminal if they are missing, with apt-get and passwordless sudo. If the panel can’t start, the run only logs a warning, and the reason is in /tmp/pydantic-ai-desktop.log in the machine. With desktop set, every command gets DISPLAY=:100, so agent-browser open <url> from a shell opens the page on the desktop. Anyone in your boxd organization can watch the desktop live in the boxd console’s Desktop view. Clean up Delete a machine with the ref you stored, whatever state it is in: from pydantic_ai.workspaces import WorkspaceRef from pydantic_ai_harness.boxd_sandbox import BoxdSandbox async def delete_machine(ref: WorkspaceRef) -> None: await BoxdSandbox().destroy(ref) A failed run returns no result, so delete its machine in an on_run_error hook: from typing import Any import anyio from pydantic_ai import Agent, RunContext from pydantic_ai.capabilities import Hooks from pydantic_ai.run import AgentRunResult from pydantic_ai_harness.boxd_sandbox import BoxdSandbox from pydantic_ai_harness.coder import Coder hooks = Hooks() @hooks.on.run_error async def delete_failed_run_machine(ctx: RunContext[None], *, error: BaseException) -> AgentRunResult[Any]: if ctx.workspace.ref is not None: # Shielded so a deadline around the run can't cut the delete short, bounded so a hung call can't hang it. with anyio.move_on_after(30, shield=True): await BoxdSandbox().destroy(ctx.workspace.ref) raise error agent = Agent('anthropic:claude-opus-5-5', capabilities=[BoxdSandbox(), Coder(), hooks]) A machine you don’t delete is suspended when it sits idle, then hibernated: boxd uses your organization’s idle time. Set auto_suspend_timeout= in seconds to change it, or 0 to never suspend. boxd deletes a machine only if your organization gives new machines a delete timer. boxd machine get shows a machine’s timers. Find a lost machine If your program stops before it stores the ref, for example after a crash or Ctrl-C, the machine is left running. To find it: Run boxd list. Machines Pydantic AI creates are named pydantic-ai-<hex>. Or search your logs for Created boxd machine <id>, or Forked boxd machine for a copy, logged at INFO by the pydantic_ai_harness logger. Then delete it: await BoxdSandbox().destroy(WorkspaceRef(provider='boxd', id='<id>')). Keep a token out of the machine Pass secrets to give a new machine boxd secrets by name. If a secret is tied to domains, the machine gets only a placeholder starting with bxds_, and boxd swaps in the real value as requests leave for those domains. Create the secret first, since boxd won’t create a machine that names a missing one: import boxd from pydantic_ai_harness.boxd_sandbox import BoxdSandbox async def set_github_secret(token: str) -> None: # a fine-grained GitHub token, as below async with boxd.AsyncBoxd() as client: await client.secrets.set( 'GH_TOKEN', token, scope='private-unattached', # your own, reaching only machines whose spec names it domains=['github.com', 'api.github.com', 'uploads.github.com'], replace_in=['headers'], # not the URL or body, so a command can't post the real token ) sandbox = BoxdSandbox(secrets=['GH_TOKEN']) gh then works as the token’s owner, while echo $GH_TOKEN in the machine prints the placeholder. For git push, have git send the placeholder as its password: Terminalgit config --global credential.https://github.com.helper '!f() { echo username=x-access-token; echo "password=$GH_TOKEN"; }; f' Only HTTPS requests get the real value. Use https:// remotes, not git@github.com:owner/repo.git. replace_in=['headers'] swaps the value only into request headers, which covers gh and git’s Basic auth. Without it, boxd also swaps it into the URL and body, so a command could write the real token into something GitHub stores, such as an issue or