Add workspaces: `ctx.workspace` gives tools one API for files and commands, on your machine or in a sandbox, with durable execution support

Merged
AD
2mo ago
+10185-114

Agent runs get a workspace: an environment that tools, capabilities and your own code use through ctx.workspace to run commands and read or write files. A capability supplies it (core ships LocalWorkspace; the harness ships Modal, E2B and Sprites sandboxes), or the caller passes one to the run. Nothing is attached by default, so nothing touches the machine the agent runs on unless you attach LocalWorkspace.

from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import LocalWorkspace

agent = Agent('anthropic:claude-opus-5-5', capabilities=[LocalWorkspace('.')])


@agent.tool
async def run(ctx: RunContext[None], command: str) -> str:
    result = await ctx.workspace.run(command, shell=True, timeout=60)
    return result.stdout + result.stderr

What users get

  • ctx.workspace: run, read_bytes/write_bytes/read_text/write_text, stat, list_dir, make_dir, remove, exists, realpath, resolve, working_dir. Relative paths resolve against the working directory. A command that fails is a normal result, not an exception.
  • LocalWorkspace(working_dir, *, read_only=False, env=None): the host, with no isolation. Commands get the agent's PATH and HOME plus env, and nothing else from the process environment, so API keys don't reach the model's commands.
  • Continuing a conversation: the latest response's workspace_ref is continued automatically (a turn without a workspace carries it forward). Or pass workspace=result.workspace, or its ref as is. workspace='new' starts fresh. sanitize_messages strips refs from untrusted history by default.
  • Choosing the workspace: several capabilities may implement get_workspace. The first to answer wins, so one agent can continue old conversations on one provider while new runs go to another. A ref from history that none of the agent's workspace capabilities recognises raises a UserError naming it. An agent with no workspace capability (a summarizer, say) ignores it. A WorkspaceRef passed to the run that nothing resolves also raises.
  • Read-only: ReadOnlyWorkspace/read_only=True. Mutations raise WorkspaceReadOnlyError, and Workspace.read_only lets toolsets hide write tools.
  • Durable execution (Temporal, DBOS, Prefect): the workspace is created once before the run's hooks, and its ref is journaled. Tools run in their activities with the workspace rebuilt from that ref. Workspace calls made from workflow code (hooks, output functions) go through one durable operation, using the same config and retries as capability operations. Errors keep their types across the boundary.
  • Backend authors: implement WorkspaceBackend plus SupportsCommands and/or SupportsFilesystem. File operations and realpath fall back to the shell for command-only backends. Check your backend with pydantic_ai.workspaces.conformance.WorkspaceBackendSuite, which the harness runs over every provider, live. Its attach_backend rule checks what durable execution needs: a backend rebuilt from a ref reaches the same files and commands.

Decisions (from the 09-22, 09-24 and 09-25 reviews)

  • The workspace is selected before for_run, so for_run can read from it. A for_run that changes it raises.
  • Several workspace capabilities are allowed, with the first answer winning (parity with get_model). An agent with no workspace capability ignores a ref in history; one whose capabilities all decline it raises.
  • The framework never destroys an environment. Cleanup is the caller's job.
  • Durable: one bound operation, not one per method. No workspace-specific config role or retry policy. A command or write may repeat if a worker dies mid-call, as a tool call can.
  • FileEntry.is_symlink was dropped. Symlink containment in the harness FileSystem uses realpath only, which works on every backend.
  • The anyio<4.15 pipe workaround in LocalWorkspaceBackend.run stays until the anyio minimum can be raised.

Fixes from the live QA pass

QA ran this stack live against all four providers. The core fixes that came out of it:

  • A run's own capabilities are asked before the agent's. Within each list, the first to answer wins.
  • A turn that runs without a workspace keeps the conversation's ref, so the next turn continues in the same environment. After workspace='new', the old ref is not carried forward.
  • LocalWorkspaceBackend.run returns exit 127/126 for a program that is missing or not executable, as sh does. A missing working directory still raises.
  • UnavailableWorkspace(reason) raises WorkspaceUnavailableError, so tools catch it like any other workspace error.
  • Reads that fall back to the shell check the byte count, so truncated output raises instead of returning a short file.
  • A workspace capability with defer_loading=True raises UserError, because the workspace is chosen when the run starts.
  • Under durable execution, a workspace policy that only a run-level capability adds, such as read_only=True, raises. The durable units rebuild the workspace from the capabilities the agent was built with.
  • The docs recommend cleaning up a failed run's environment in on_run_error, because after_run doesn't run on failure.

Fixes from the final review (GPT-6 Sol and Fable)

  • ctx.workspace.backend returns the provider backend under any wrapper. Before this, LocalWorkspace(read_only=True), or a DBOS run, gave back the next Workspace layer, so provider methods such as get_client() weren't reachable.
  • Under durable execution, a call through another run's result.workspace (a child agent run from workflow code) now reaches that run's environment instead of the current run's.
  • The shell fallback for command-only backends behaves like native backends: writes go through a symlink instead of replacing it, writing onto a directory raises IsADirectoryError, and make_dir over a file raises FileExistsError. WorkspaceBackendSuite has a rule for each, so every provider is checked.
  • The agent and durable execution share one workspace-selection function, and the unused test-fake members and duplicate tests are gone.
  • The docs page leads with examples: moving an agent into a sandbox, continuing a conversation (the WorkspaceRef round trip through response.workspace_ref, saved JSON and workspace=ref), and a read-only reviewer subagent working in the parent's workspace. Every example except the harness one runs in the docs tests.

Changes from the 09-27 review

  • Temporal: only WorkspaceError is added to the workflow failure types. Builtin errors (a missing file, a bad argument) keep Temporal's default and fail the workflow task, so a fix can be deployed; nothing changes for users without workspaces.
  • DBOS numbers steps in start order, so parallel workspace calls could not be recovered reliably: inside a DBOS workflow, a run with a workspace attached runs tool calls one at a time and warns, unless parallel_execution_mode='sequential' is passed.
  • Prefect: two agents in one flow no longer share cached capability results (a second agent's ensure was served the first agent's environment).
  • A resolver asked for a ref must return a backend with that ref; one that would create a fresh environment raises.
  • The shell fallback rereads a file replaced mid-read (a job publishing its status) instead of reporting damage.
  • Oversized workspace writes from workflow code are left to Temporal's own payload limit check, which runs after the codec, so external payload storage works.

Verification

Workspace, local backend, conformance and durable (Temporal/DBOS/Prefect) test suites; doc examples; the harness stack runs the conformance suite and every provider docs example against the real services.

The harness side (every capability on ctx.workspace, then the Modal, E2B and Sprites providers) opens as monorepo PRs after this merges, replacing pydantic/pydantic-ai-harness#522, #734, #735 and #819. With #8837, this PR's CI already runs main's harness and clai2 suites against these core changes.

Checklist

  • Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.

šŸ¤– Generated with Claude Code