Sprites Sandbox
Run your agent’s commands and file edits in a persistent Fly.io Sprite instead of on your machine.
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: Sprites Sandbox: your agent's commands run in a persistent Fly.io Sprite
accDescr: On your machine, the model calls Coder, Shell or FileSystem tools such as run_command, using ctx.workspace. SpritesSandbox's get_workspace hands the run a Sprite via the Sprites API and SPRITE_TOKEN. The Fly.io Sprite sleeps when idle, destroy(ref) deletes it, and a later run reattaches with the WorkspaceRef in the message history and result.workspace.ref, waking it if asleep.
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"]
sprites["SpritesSandbox()<br/>get_workspace hands<br/>the run a Sprite"]:::capability
end
sandbox["Fly.io Sprite<br/>sleeps when idle,<br/>deleted by destroy(ref)"]:::external
model <-->|"tool call, result"| tools
tools -->|"ctx.workspace"| sprites
ref -.->|"a later run reattaches,<br/>waking it if asleep"| sprites
sprites <-->|"Sprites API,<br/>SPRITE_TOKEN"| sandbox
classDef capability stroke:#E520E9,stroke-width:2px
classDef external stroke:#0E9C86,stroke-width:2px
pip install "pydantic-ai-harness[coder,sprites,anthropic]"
uv add "pydantic-ai-harness[coder,sprites,anthropic]"
Set SPRITE_TOKEN to your Sprites API token. 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.
from pydantic_ai import Agent
from pydantic_ai_harness.coder import Coder
from pydantic_ai_harness.sprites_sandbox import SpritesSandbox
agent = Agent('anthropic:claude-opus-5-5', capabilities=[SpritesSandbox(), 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 Sprite. For a narrower agent, use Shell, FileSystem or your own tools on ctx.workspace.
Codercreates it when the run starts, to load the repository’s instructions, even if no tool is called. PassCoder(repo_context=False)to wait for the first tool call.- It has no lifetime limit. It sleeps when idle, keeps its files and installed packages, and costs money until you delete it. See Clean up.
- Processes pause between commands unless you run them as a Sprites service.
- Commands run as the non-root
spriteuser in/home/sprite. Passworking_dir='/home/sprite/project'to give the agent a project directory. It is created on a new Sprite. - A new Sprite has git, Python and Node.js, but not pytest or
rg. See its preinstalled tools. Install what your project needs once and reuse the Sprite by its ref. For fasterCodersearches, runsudo apt-get update && sudo apt-get install ripgrep.
Pass the message history, and the next run works in the same Sprite:
from pydantic_ai import Agent
from pydantic_ai_harness.coder import Coder
from pydantic_ai_harness.sprites_sandbox import SpritesSandbox
agent = Agent('anthropic:claude-opus-5-5', capabilities=[SpritesSandbox(), 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 Sprite as a WorkspaceRef, or “ref”: the provider’s name and the Sprite’s ID. result.workspace.ref is the same ref, for continuing without the history.
If the Sprite has been deleted, the run raises WorkspaceUnavailableError, as does a command running when it is deleted. Pass workspace='new' to start over. Workspaces covers how runs find their workspace.
The ref holds no credentials, so the process that reattaches needs SPRITE_TOKEN or a client= too.
Already have a sprites.AsyncSprite? Pass workspace=SpritesSandboxBackend(sandbox=sprite, working_dir=..., env=..., desktop=...) to a run. SpritesSandbox’s settings don’t apply to it. A backend’s get_sandbox() returns its sprites.AsyncSprite for Sprites features the workspace API doesn’t cover. On a backend with no Sprite yet, it creates one, which Sprites bills.
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.coder import Coder
from pydantic_ai_harness.sprites_sandbox import SpritesSandbox, SpritesSandboxBackend
agent = Agent('anthropic:claude-opus-5-5', capabilities=[SpritesSandbox(), Coder()])
async def run_in_prepared_sprite() -> str:
backend = SpritesSandboxBackend(working_dir='/home/sprite/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 Sprite exists
if ref is not None:
await SpritesSandbox().destroy(ref)
The run leaves a backend you built open, so close it with aclose(). That closes the client it opened from SPRITE_TOKEN, not the Sprite. A client= or sandbox= you passed is never closed. To keep the Sprite, store backend.ref instead of destroying it.
Pass desktop=True and add ComputerUse:
capabilities=[SpritesSandbox(desktop=True), ComputerUse()]. The screen is 1280x800; pass a size such as
desktop=(1440, 900) for another.
The first use installs the display’s programs with apt-get, which can take a minute. There’s no web browser.
- A cold wake stops the display and closes the agent’s windows; files on disk are kept. The display restarts on the agent’s next screenshot or action; until then, a program started from the shell can’t open a window.
- The agent can type only ASCII: an action that types or presses a character such as
éfails, and the model is told why.
Delete a Sprite with the ref you stored. This doesn’t wake it:
from pydantic_ai.workspaces import WorkspaceRef
from pydantic_ai_harness.sprites_sandbox import SpritesSandbox
async def delete_sprite(ref: WorkspaceRef) -> None:
await SpritesSandbox().destroy(ref)
A ref can name any Sprite your SPRITE_TOKEN reaches, and destroy deletes whatever it names, so keep refs on your server and only destroy Sprites you created.
A failed run returns no result, so delete its Sprite in an on_run_error hook. If Sprites’ reply to the create was lost, the ref still names the Sprite the backend tried to create, which may or may not exist. Delete it by that name anyway; deleting a Sprite that doesn’t exist returns quietly:
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.coder import Coder
from pydantic_ai_harness.sprites_sandbox import SpritesSandbox
hooks = Hooks()
@hooks.on.run_error
async def terminate_failed_run(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 kill short, bounded so a hung call can't hang it.
with anyio.move_on_after(30, shield=True):
await SpritesSandbox().destroy(ctx.workspace.ref)
raise error
agent = Agent('anthropic:claude-opus-5-5', capabilities=[SpritesSandbox(), Coder(), hooks])
You pay for compute while a Sprite is active, and for storage until you delete it. See Sprite lifecycle.
If your program stops before it stores the ref, for example after a crash or Ctrl-C, the Sprite stays until you delete it, since a Sprite never expires. To find it:
- List your Sprites. Sprites Pydantic AI creates are named
pydantic-ai-<hex>, and the name is the ref’s id. - Or search your logs for
Created Sprite <id>, logged at INFO by thepydantic_ai_harnesslogger. - If the run stopped before Sprites replied, there is no log line, but the Sprite may still exist. Look for it in the list.
Then delete it: await SpritesSandbox().destroy(WorkspaceRef(provider='sprites', id='<id>')).
| Option | What it does |
|---|---|
client | A sprites.AsyncSpritesClient to share across runs on one event loop, or to set its base URL or timeout. Default: None, a client each run opens from SPRITE_TOKEN and closes when it ends. You close a client you pass. |
runtime | Runtime for a new Sprite. Default: None, Sprites’ default. An unknown runtime fails on first use with WorkspaceUnavailableError. |
working_dir | Absolute directory commands start in and relative paths resolve against. Default: None, /home/sprite. Created on a new Sprite. On an attached one, it must already exist. |
env | Environment variables every command gets. Default: None. Nothing from your machine reaches the Sprite. The agent’s commands can read these, so leave out secrets it shouldn’t see. |
desktop | Give the Sprite a graphical display for ComputerUse: True for 1280x800, or its (width, height). The size applies when the display first starts. Default: False. |
authority | Who wrote the Sprite’s files. A capability that puts a file’s text in the prompt gives it no more authority than this. Default: 'operator', your own files. Use 'user' for the user’s files, and 'none' for files nobody on your side wrote, such as a cloned third-party repository. |
path_authority | Levels for some directories and files, overriding authority under them. The longest matching path wins. Paths are in the Sprite, relative to the working directory or absolute, and ~ isn’t expanded. Default: None. |
client, working_dir, env, desktop, authority and path_authority also apply when you reattach, and destroy uses client. runtime only shapes a new Sprite.
- Unix permissions don’t restrict the
spriteuser. A file with mode000is still readable. Don’t rely on them to keep tools out of a path. - Stopping a command on a timeout or cancellation is best effort, and its children may keep running. If unsure, inspect or delete the Sprite.
- A background process that keeps the command’s stdout or stderr open keeps
run()waiting. Redirect its output to a file.Shell.start_commanddoes this for you. timeout=Noneremoves the command deadline, not the Sprite’s idle pause.- The Sprites SDK needs asyncio. Under Trio, every operation raises
UserError.
Add a durability capability, such as TemporalDurability() from the temporal extra, next to SpritesSandbox(). Workspaces covers what changes.
If the connection drops after a command started but before it finished, the command may have run, so it raises a non-retryable error rather than running again.
In this example, one client is created when the module is imported, so the worker’s activities share it. Close it when the worker stops. Run a Temporal dev server on localhost:7233 first.
import asyncio
import os
import uuid
from pydantic_ai import Agent
from pydantic_ai.durable_exec.temporal import PydanticAIPlugin, PydanticAIWorkflow, TemporalDurability
from pydantic_ai_harness.coder import Coder
from pydantic_ai_harness.sprites_sandbox import SpritesSandbox
from temporalio import workflow
from temporalio.client import Client
from temporalio.worker import Worker
# The provider SDK must not be re-imported inside Temporal's restricted workflow sandbox.
with workflow.unsafe.imports_passed_through():
from sprites import AsyncSpritesClient
CLIENT = AsyncSpritesClient(token=os.environ['SPRITE_TOKEN'])
agent = Agent(
'anthropic:claude-opus-5-5',
name='sprites_coder',
capabilities=[SpritesSandbox(client=CLIENT), Coder(), TemporalDurability()],
)
@workflow.defn
class SandboxWorkflow(PydanticAIWorkflow):
__pydantic_ai_agents__ = [agent]
@workflow.run
async def run(self, prompt: str) -> str:
return (await agent.run(prompt)).output
async def main() -> None:
client = await Client.connect('localhost:7233', plugins=[PydanticAIPlugin()])
async with CLIENT:
async with Worker(client, task_queue='sandbox', workflows=[SandboxWorkflow]):
print(
await client.execute_workflow(
SandboxWorkflow.run,
'Use the shell tool to run pwd.',
id=f'sandbox-{uuid.uuid4()}', task_queue='sandbox',
)
)
if __name__ == '__main__':
asyncio.run(main())
SpritesSandbox emits no spans of its own. Core’s instrumentation records pydantic_ai.workspace.provider and pydantic_ai.workspace.id on the agent run span, and each command or file operation runs inside its tool call’s span.
Bases: AbstractCapability[AgentDepsT]
Run the agent’s workspace in a persistent Fly.io Sprite.
A run with no reference creates a fresh Sprite on first use; pass a WorkspaceRef to attach
to an existing one. Ending a run does not delete the Sprite: it sleeps when idle and persists
until you delete it. Commands run under sh -c in the Sprite’s own shell environment.
This capability supplies the workspace only. Compose it with capabilities that use it, such
as Coder, Shell, and FileSystem. See
Workspaces for more.
A caller-owned sprites.AsyncSpritesClient, which is never closed for you. When omitted,
each run’s backend creates one on first use from SPRITE_TOKEN and closes it when the run
ends; a backend this capability supplies outside a run (under Temporal, one per activity)
closes its client after each operation. A backend from backend(ref) needs aclose(). Supply one to share its connections across runs, on one event loop.
Type: AsyncSpritesClient | None Default: None
Runtime for a newly created Sprite; an unknown runtime fails on first use.
Type: str | None Default: None
Absolute directory commands start in and relative paths resolve against; None uses the Sprite’s default.
Created on a new Sprite; an attached Sprite must already have it.
Type: str | None Default: None
Environment variables every command gets, on top of the Sprite’s own; a command’s env is layered on top.
Type: Mapping[str, str] | None Default: field(default=None, repr=False)
Give the Sprite a graphical display, for ComputerUse: True
for 1280x800, or its (width, height).
Type: bool | tuple[int, int] Default: False
The authority of the sandbox’s files: 'none' for files nobody on the
application’s side wrote, such as a cloned third-party repository, and 'user' for the user’s own files.
Anything below 'operator' wraps the workspace in an AuthorityWorkspace.
Type: Authority Default: 'operator'
Levels for some directories and files, overriding authority for the paths under them; the longest matching
path wins. Paths are sandbox paths: relative ones resolve against the working directory, and ~ isn’t expanded.
See Workspace.authority_of.
Type: Mapping[str, Authority] | None Default: None
@classmethod
def from_spec(
cls,
*,
id: str | None = None,
description: str | None = None,
defer_loading: bool = False,
runtime: str | None = None,
working_dir: str | None = None,
env: Mapping[str, str] | None = None,
desktop: bool | tuple[int, int] = False,
authority: Authority = 'operator',
path_authority: Mapping[str, Authority] | None = None,
) -> SpritesSandbox[Any]
Build from an agent spec, naming the fields a spec can express.
Core reads this signature to generate the spec’s JSON schema. Inherited, core reads __init__, and
client’s AsyncSpritesClient hint has no JSON schema, so only the bare 'SpritesSandbox' is published.
SpritesSandbox[Any]
def backend(ref: WorkspaceRef) -> SpritesSandboxBackend
Construct a lazy backend for an existing Sprite.
SpritesSandboxBackend
@async
def destroy(ref: WorkspaceRef) -> None
Delete a Sprite by id without attaching or waking it.
A Sprite that no longer exists is already gone, so destroying it returns quietly.
def get_workspace(
ctx: RunContext[AgentDepsT],
*,
ref: WorkspaceRef | None,
) -> WorkspaceBackend | None
The backend for this run, in an AuthorityWorkspace when authority or path_authority asks for one.
WorkspaceBackend | None
Bases: WorkspaceBackend, SupportsCommands, SupportsFilesystem, SupportsDisplay
A Fly.io Sprite behind the Pydantic AI WorkspaceBackend protocol.
Pass sandbox= to wrap a sprites.AsyncSprite you already have, or ref= to reattach to one.
Construction does no I/O. The typed sprites.AsyncSprite is available through get_sandbox().
Without client=, the backend creates an AsyncSpritesClient from SPRITE_TOKEN on first use
and closes it in aclose().
The backend does not delete the Sprite; that is the application’s job, through the native
handle. Commands run under /bin/sh -c with shell=True, in the Sprite’s own environment
plus env. A working_dir is created on a Sprite the backend creates; an attached or
caller-supplied Sprite must already have it. File writes go through the Sprite’s filesystem
API; the other file operations run as shell commands.
With desktop, True or a (width, height) (1280x800 by default), the Sprite gets a desktop for
ComputerUse on first use, which installs the programs it needs.
A cold wake closes its windows. The display restarts on the next screenshot or action, and until then a program
started from the shell can’t open a window. A new backend starts the display on its first command.
The Sprite’s desktop, when created with desktop=True.
Type: Display | None
@async
def get_sandbox() -> AsyncSprite
Return the typed sprites.AsyncSprite, for Sprites features the workspace API does not cover.
On a backend with no Sprite yet, this creates one (which Sprites bills) or attaches to the one
ref names, just like the first operation. Attaching by ref to a Sprite that no longer
exists raises WorkspaceUnavailableError; it does not create a replacement. After that it
returns the cached handle without checking that the Sprite still exists: one deleted
elsewhere surfaces on the next operation. Calling this does not make you responsible for
deleting the Sprite; whoever holds the ref decides, as before.
The handle belongs to the backend’s AsyncSpritesClient, and this never returns a handle the
backend built without looking the Sprite up. Once aclose() closes the backend’s own client,
handles from it stop working, so call this again. A backend you build yourself outside a run
opens its own client, which you close with aclose().
AsyncSprite
UserError— The event loop is not asyncio.
@async
def aclose() -> None
Close the AsyncSpritesClient this backend created, if it created one.
The Sprite is untouched: the next operation opens a fresh client and reattaches by ref.
A caller-supplied client= or sandbox= handle is never closed. SpritesSandbox
calls this for the backend it supplied when each run ends. A close that fails or times out
is logged, not raised.