Skip to content

Render Sandbox

Run your agent’s commands and file edits in an isolated Render sandbox 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.

Install

Terminal
pip install "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.

Quick start

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.

  • 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 running, and billing, after the run, even when idle, until sandbox_timeout runs out. RenderSandbox turns off Render’s idle suspension. See Clean up.
  • It lives for 1 hour. Pass up to sandbox_timeout=86400 for 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=False to block it.
  • The image needs python3. Render’s default image has it.

Continue in the same sandbox

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.

Prepare a sandbox before the run

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.

Give the agent a desktop

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.

Clean up

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.

Find a lost sandbox

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 the pydantic_ai_harness logger.
  • 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>')).

Configuration

OptionWhat it does
clientA render.RenderAsync you own. It is never closed for you. Default: None, which reads RENDER_API_KEY and RENDER_WORKSPACE_ID.
allow_internet_accessWhether a new sandbox can reach the internet. Default: True.
sandbox_timeoutSeconds a new sandbox lives before Render terminates it, at most 86_400. Default: 3_600.
working_dirAbsolute 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.
envEnvironment 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.
desktopGive 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.
authorityWho 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_authorityLevels 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.

Limits

  • 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 RateLimitError and 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.
  • RenderSandbox needs asyncio. Under Trio, it raises UserError.

Durable execution

RenderSandbox works with RenderWorkflows, and its model and tool tasks share one sandbox.

  • The render extra 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.

Telemetry

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.

API reference

RenderSandbox

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.

Attributes

client

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

allow_internet_access

Whether a newly created sandbox may reach the internet; without it, commands such as pip install fail.

Type: bool Default: True

sandbox_timeout

Seconds a newly created sandbox lives before Render terminates it, up to 86400.

Type: int Default: DEFAULT_SANDBOX_TIMEOUT

working_dir

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

env

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)

authority

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'

path_authority

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

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 creating a new sandbox without allow_internet_access raises UserError; attaching to one doesn’t.

Type: bool | tuple[int, int] Default: False

Methods

from_spec

@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.

Returns

RenderSandbox[Any]

backend
def backend(ref: WorkspaceRef) -> RenderSandboxBackend

Attach lazily to an existing Render sandbox.

Returns

RenderSandboxBackend

destroy

@async

def destroy(ref: WorkspaceRef) -> None

Terminate the sandbox identified by ref; an already terminated or unknown one returns quietly.

Rejected credentials raise WorkspaceUnavailableError.

Returns

None

get_workspace
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.

Returns

WorkspaceBackend | None

RenderSandboxBackend

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.

Constructor Parameters

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.

working_dir : str | None Default: None

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.

env : Mapping[str, str] | None Default: None

Environment variables every command gets; per-command env is layered on top. Nothing is read from the host environment.

desktop : bool | tuple[int, int] Default: False

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.

Attributes

display

The sandbox’s desktop, when created with desktop=True.

Type: Display | None

ref

The sandbox’s identity: None until a fresh one is created, then set for good.

Type: WorkspaceRef | None

Methods

run

@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.

Returns

CommandResult