Render Sandbox
Run your agent’s commands and file edits in an isolated Render sandbox 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.
pip install "pydantic-ai-harness[coder,render,anthropic]"
uv add "pydantic-ai-harness[coder,render,anthropic]"
Set RENDER_API_KEY to a Render API key, and RENDER_WORKSPACE_ID to the tea-... ID of your Render workspace, Render’s name for a team. The workspace needs Sandboxes access and billing set up. 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.render_sandbox import RenderSandbox
agent = Agent('anthropic:claude-opus-5-5', capabilities=[RenderSandbox(), 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 the sandbox. 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 keeps running, and billing, after the run, even when idle, until
sandbox_timeoutruns out.RenderSandboxturns off Render’s idle suspension. See Clean up. - It lives for 1 hour. Pass up to
sandbox_timeout=86400for longer. - Commands start in the sandbox’s home directory. Pass
working_dir=for another absolute directory. It is created on a new sandbox. - It can reach the internet. Pass
allow_internet_access=Falseto block it. - The image needs
python3. Render’s default image has it.
Pass the message history, and the next run works in the same sandbox:
from pydantic_ai import Agent
from pydantic_ai_harness.coder import Coder
from pydantic_ai_harness.render_sandbox import RenderSandbox
agent = Agent('anthropic:claude-opus-5-5', capabilities=[RenderSandbox(), Coder()])
result = agent.run_sync('Write a fizzbuzz.py and run it.')
followup = agent.run_sync('Add tests for fizzbuzz.py.', message_history=result.all_messages())
ref = result.workspace.ref # or store this, and pass `workspace=ref` to a later run
The history records the sandbox as a WorkspaceRef, or “ref”: the provider’s name and the sandbox’s ID. result.workspace.ref is the same ref, for continuing without the history.
If the sandbox has been terminated, 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 RENDER_API_KEY and RENDER_WORKSPACE_ID, or a client=, too.
To seed files or install packages before the agent starts, create the backend yourself, work in it through Workspace, and pass it to the run:
import asyncio
from pydantic_ai import Agent
from pydantic_ai.workspaces import Workspace
from pydantic_ai_harness.coder import Coder
from pydantic_ai_harness.render_sandbox import RenderSandbox, RenderSandboxBackend
agent = Agent('anthropic:claude-opus-5-5', capabilities=[RenderSandbox(), Coder()])
async def main() -> None:
backend = RenderSandboxBackend()
try:
workspace = Workspace(backend)
await workspace.write_text('calc.py', 'def add(a, b):\n return a - b\n')
install = await workspace.run(['pip', 'install', 'pytest'], timeout=300)
if install.exit_code != 0:
raise RuntimeError(f'pip install failed: {install.stderr}')
result = await agent.run('Fix the bug in calc.py.', workspace=backend)
print(result.output)
finally:
ref = backend.ref # set once the sandbox exists
if ref is not None:
await RenderSandbox().destroy(ref)
if __name__ == '__main__':
asyncio.run(main())
The finally terminates the sandbox even when setup or the run fails, so read any files you want to keep before it. To keep the sandbox, store backend.ref instead.
Pass desktop=True and add ComputerUse:
capabilities=[RenderSandbox(desktop=True), ComputerUse()]. The screen is 1280x800; pass a size such as
desktop=(1440, 900) for another.
Render’s default image has none of the display’s programs, so the first use of the screen installs them with apt-get, with no web browser. That needs allow_internet_access: creating a new sandbox without it raises UserError. An attached sandbox without internet access must already have the programs, or the first use of the screen raises WorkspaceUnavailableError naming what’s missing.
To give the agent a browser or other programs, install them before the run, as in Prepare a sandbox before the run with RenderSandboxBackend(desktop=True), or let the agent install them with Shell.
The agent can type only ASCII: an action that types or presses a character such as é fails, and the model is told why.
Terminate a sandbox with the ref you stored:
from pydantic_ai.workspaces import WorkspaceRef
from pydantic_ai_harness.render_sandbox import RenderSandbox
async def terminate_sandbox(ref: WorkspaceRef) -> None:
await RenderSandbox().destroy(ref)
destroy(ref) raises WorkspaceUnavailableError if Render rejects the credentials.
To terminate the sandbox after every run, including failed ones, use after_run and run_error hooks:
from typing import Any
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.render_sandbox import RenderSandbox
sandbox = RenderSandbox()
hooks = Hooks()
@hooks.on.after_run
async def terminate_sandbox(ctx: RunContext[None], *, result: AgentRunResult[Any]) -> AgentRunResult[Any]:
if ctx.workspace.ref is not None:
await sandbox.destroy(ctx.workspace.ref)
return result
@hooks.on.run_error
async def terminate_failed_run(ctx: RunContext[None], *, error: BaseException) -> AgentRunResult[Any]:
if ctx.workspace.ref is not None:
await sandbox.destroy(ctx.workspace.ref)
raise error
agent = Agent('anthropic:claude-opus-5-5', capabilities=[sandbox, Coder(), hooks])
To keep results, read them through ctx.workspace in after_run before calling destroy.
If your program stops before it stores the ref, for example after a crash or Ctrl-C, the sandbox runs until its sandbox_timeout. To find it:
- Search your logs for
Created Render sandbox <id>, logged at INFO by thepydantic_ai_harnesslogger. - A connection failure while Render creates the sandbox can leave it running with no ref and no log line. Check your Render workspace for unused sandboxes.
Then terminate it: await RenderSandbox().destroy(WorkspaceRef(provider='render', id='<id>')).
| Option | What it does |
|---|---|
client | A render.RenderAsync you own. It is never closed for you. Default: None, which reads RENDER_API_KEY and RENDER_WORKSPACE_ID. |
allow_internet_access | Whether a new sandbox can reach the internet. Default: True. |
sandbox_timeout | Seconds a new sandbox lives before Render terminates it, at most 86_400. Default: 3_600. |
working_dir | Absolute directory commands start in and relative paths resolve from. Default: None, the sandbox’s home directory. Created on a new sandbox. On an attached one, it must already exist. |
env | Environment variables every command gets. Default: None. Nothing from your machine reaches the sandbox. The agent’s commands can read these, so leave out secrets it shouldn’t see. |
desktop | Give the sandbox a graphical display for ComputerUse: True for 1280x800, or its (width, height). The first use installs the desktop’s programs with apt-get, so a new sandbox needs allow_internet_access. The size applies when the display first starts. Default: False. |
authority | Who wrote the sandbox’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 sandbox, 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. The other options only shape a new sandbox.
- A sandbox that doesn’t finish setting up in time raises
TimeoutError. - A missing sandbox or rejected access raises
WorkspaceUnavailableError. - Render allows 100 API requests a minute. A rate-limited request raises the SDK’s
RateLimitErrorand is not retried. - A command and its environment must fit in about 110 KB. Write larger content with the file tools.
- A command whose output passes 10 MiB raises
WorkspaceOutputLimitError. Redirect large output to a file. - Stopping a command on a timeout or cancellation is best effort. If the stop can’t be confirmed, a warning names the sandbox.
- Background processes that detach can keep running.
RenderSandboxneeds asyncio. Under Trio, it raisesUserError.
RenderSandbox works with RenderWorkflows, and its model and tool tasks share one sandbox.
- The
renderextra covers both. Set the Render variables on every worker. - A retried root task runs the agent again, so terminate the sandbox from the task that runs the agent, as in Clean up.
RenderSandbox 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]
Supply an isolated Render sandbox as the run’s workspace.
A run with no reference creates a fresh sandbox on first use. Pass a WorkspaceRef supplied by the
application to attach to an environment managed elsewhere. Ending a run does not terminate the
sandbox: store result.workspace.ref and call destroy(ref), or let sandbox_timeout end it.
This capability supplies execution only. Compose it with tools or capabilities that use the
workspace, such as Coder, Shell, or FileSystem.
A caller-owned render.RenderAsync, never closed for you.
When omitted, credentials come from RENDER_API_KEY and RENDER_WORKSPACE_ID.
Type: RenderAsync | None Default: None
Whether a newly created sandbox may reach the internet; without it, commands such as pip install fail.
Type: bool Default: True
Seconds a newly created sandbox lives before Render terminates it, up to 86400.
Type: int Default: DEFAULT_SANDBOX_TIMEOUT
Absolute directory commands start in and relative paths resolve against.
Created on a new sandbox; an attached sandbox must already have it. None uses the sandbox’s home directory.
Type: str | None Default: None
Environment variables every command gets, also on an attached sandbox; nothing is read from the host.
Type: Mapping[str, str] | None Default: field(default=None, repr=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
Give the sandbox a graphical display, for ComputerUse: True
for 1280x800, or its (width, height). The first use installs the desktop’s programs with apt-get, so creating
a new sandbox without allow_internet_access raises UserError; attaching to one doesn’t.
Type: bool | tuple[int, int] Default: False
@classmethod
def from_spec(
cls,
*,
id: str | None = None,
description: str | None = None,
defer_loading: bool = False,
allow_internet_access: bool = True,
sandbox_timeout: int = DEFAULT_SANDBOX_TIMEOUT,
working_dir: str | None = None,
env: Mapping[str, str] | None = None,
authority: Authority = 'operator',
path_authority: Mapping[str, Authority] | None = None,
desktop: bool | tuple[int, int] = False,
) -> RenderSandbox[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 RenderAsync hint has no JSON schema, so only the bare 'RenderSandbox' is published.
RenderSandbox[Any]
def backend(ref: WorkspaceRef) -> RenderSandboxBackend
Attach lazily to an existing Render sandbox.
RenderSandboxBackend
@async
def destroy(ref: WorkspaceRef) -> None
Terminate the sandbox identified by ref; an already terminated or unknown one returns quietly.
Rejected credentials raise WorkspaceUnavailableError.
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 Render sandbox as a Pydantic AI WorkspaceBackend.
Building one does no I/O. Built without a ref, the first operation creates a sandbox; built with one,
it attaches and never creates a replacement. The backend never terminates the sandbox: whoever holds
the ref does, with RenderSandbox.destroy(ref).
Commands and file operations use the same sandbox. On timeout or cancellation, stopping a command and its children is best effort. An unconfirmed stop is logged, and the sandbox remains usable.
client : RenderAsync | None Default: None
An optional caller-owned render.RenderAsync, never closed here. When None, credentials
come from RENDER_API_KEY and RENDER_WORKSPACE_ID.
ref : WorkspaceRef | None Default: None
Identity of an existing sandbox to attach to on first use.
allow_internet_access : bool Default: True
Whether a newly created sandbox may reach the internet.
sandbox_timeout : int Default: DEFAULT_SANDBOX_TIMEOUT
Seconds a newly created sandbox lives before Render terminates it, 1 to 86400.
Absolute directory commands start in and relative paths resolve against. Created on a
new sandbox; an attached sandbox must already have it. None uses the sandbox’s home directory.
Environment variables every command gets; per-command env is layered on top. Nothing is
read from the host environment.
Whether the sandbox has a display for
ComputerUse: True for 1280x800, or its
(width, height). The first use installs the programs it needs with apt-get, so a new sandbox needs
allow_internet_access.
The sandbox’s desktop, when created with desktop=True.
Type: Display | None
The sandbox’s identity: None until a fresh one is created, then set for good.
Type: WorkspaceRef | None
@async
def run(
command: WorkspaceCommand,
*,
shell: bool = False,
env: Mapping[str, str] | None = None,
timeout: float | None = None,
) -> CommandResult
Run once with stdin at EOF, attempting to stop the command on timeout or cancellation.
CommandResult