pydantic_ai.workspaces
Workspace API, backend protocols, and implementations.
Bases: WorkspaceBackend
The workspace API tools and hooks use as ctx.workspace: the backend’s operations, relative paths, and text.
The provider backend underneath every wrapper, for access to provider-specific functionality.
Type: WorkspaceBackend
Whether this workspace refuses commands and file changes, so tools can leave those out.
Type: bool
The authority of this workspace’s files, so capabilities know how to send their text.
'operator' unless an AuthorityWorkspace wrapper lowers it;
with several, the lowest wins. Tools work the same either way. A wrapper’s path_authority can set
other levels for some paths: ask authority_of for a
given file’s.
Set authority with AuthorityWorkspace. Overriding this property on another wrapper changes neither
authority_of nor what the layers around that wrapper report, so its files would keep a higher level.
Type: Authority
Whether this workspace reaches an environment.
False for an UnavailableWorkspace and for a run
with no workspace attached.
Type: bool
The environment’s WorkspaceRef, None until it exists.
Type: WorkspaceRef | None
The backend’s shell and path syntax; 'posix' unless it says otherwise.
Type: WorkspacePlatform
The path functions for this workspace’s paths: ntpath on a 'windows' workspace, else posixpath.
Type: WorkspacePaths
@async
def authority_of(path: str) -> Authority
The authority of the file at path, so a capability knows how to send its text.
A file in the working directory has authority, unless a
wrapper’s path_authority sets another level for a directory or file containing it: the longest matching
path wins, and with several wrappers, the lowest of their levels. A path outside the working directory that no
wrapper’s path_authority contains is outside the workspace, so its level is 'none'.
The path is resolved like file methods resolve it, and the level is the lower of where it’s written and
where it leads: a symlink in the workspace takes the lower of its own level and its target’s, so a link
can’t raise its target’s level, nor launder a lower one. A link that only another link’s target leads
through, in a chain of links, isn’t seen: realpath resolves a chain at once. On a backend whose
realpath can’t follow symlinks, only the path as written
counts.
The answer reflects the filesystem now: call it when reading the file, and keep the level with the text, rather than asking again when the text is sent.
def durable_policy() -> tuple[object, ...]
Configuration a durable unit must rebuild with this wrapper.
Empty unless the wrapper’s own arguments change what the unit does. Two workspaces of the same class with different values are different policies: a run-level workspace that a unit would not rebuild is rejected, rather than replaced by the construction-time one.
@async
def run(
command: WorkspaceCommand,
*,
shell: bool = False,
env: Mapping[str, str] | None = None,
timeout: float | None = None,
cwd: str | None = None,
) -> CommandResult
Run a command and wait for it.
It starts in cwd, resolved like file paths, or the working directory by default. A missing cwd
raises FileNotFoundError, and a file NotADirectoryError.
There is no default timeout. Raises UserError if the backend can’t run commands.
CommandResult
@async
def working_dir() -> str
The default working directory, which relative paths resolve against.
@async
def resolve(path: str, *, base: str | None = None) -> str
Join path onto base (default: the working directory) and normalize it as text.
The only I/O is asking the backend for its working directory when base is omitted.
Symlinks are not followed and .. can escape base, so this confines nothing; use
realpath to learn where a path actually leads.
@async
def read_bytes(path: str) -> bytes
Read a file’s contents as bytes.
@async
def write_bytes(path: str, data: bytes) -> None
Write bytes to a file, creating missing parents and replacing existing contents.
@async
def stat(path: str) -> FileEntry
Return metadata for a file or directory.
FileEntry
@async
def list_dir(path: str) -> Sequence[FileEntry]
List the entries of a directory (non-recursive).
Sequence[FileEntry]
@async
def make_dir(path: str) -> None
Create a directory, including missing parents.
@async
def remove(path: str) -> None
Remove a file, or a directory and its contents.
@async
def exists(path: str) -> bool
Whether a file or directory exists at the path.
@async
def realpath(path: str) -> str
Follow every symlink in path in the environment, like os.path.realpath(path, strict=False).
Uses the backend’s SupportsRealpath, else readlink in
its shell, raising WorkspaceError on a link it cannot
read, including when the shell has no readlink. Without either, it only normalizes the path as
text: symlinks are not followed, so a path check built on it can be escaped through a link.
.. climbs from a symlink’s target, as it does for commands. File methods open
resolve(path), which collapses .. as text, so
realpath(await ws.resolve(path)) names the file they open.
@async
def read_text(path: str, *, encoding: str = 'utf-8') -> str
Read a file as text; undecodable bytes raise UnicodeDecodeError.
@async
def write_text(path: str, content: str, *, encoding: str = 'utf-8') -> None
Write text to a file.
Bases: Workspace
A workspace facade that composes another workspace.
Bases: WrapperWorkspace
A Workspace that allows reads and refuses commands and file changes.
Commands are refused too, since they could change files. This restricts the workspace API; it is not isolation.
Bases: WrapperWorkspace
A Workspace whose files carry at most the given authority.
Use authority='none' for files nobody on the application’s side wrote, such as a cloned third-party
repository or a sandbox another process filled, and authority='user' for the user’s own files, such as
their uploads. Every operation works as before. A capability that puts text read from the workspace in front
of the model sends it with no more authority than
authority_of gives its file, as a
capability part whose source is
WorkspaceSource.from_workspace. This changes how
file text reaches the model; it doesn’t restrict what the agent can do in the workspace.
path_authority gives directories and files their own level, such as 'none' for a vendored dependency in the
operator’s repository, or 'operator' for the operator’s own instruction files next to a cloned one. Paths
resolve against the working directory (~ is not expanded, so a path starting with it raises UserError), and
the longest matching path wins. A path outside the working directory
is part of the workspace only when some path_authority names it. Wrapping never raises a level: with several
wrappers, a file gets the lowest level any of them gives it.
Bases: HostWorkspaceBackend, WorkspaceBackend, SupportsCommands, SupportsFilesystem, SupportsRealpath
Run commands as subprocesses on this machine and use its filesystem (POSIX only).
This isolates nothing: commands and absolute paths reach anywhere this process can. Commands
inherit only PATH, HOME and locale (LANG, LC_ALL, LC_CTYPE), so they find the host’s
tools and use its text encoding without inheriting arbitrary secrets.
Background jobs outlive run(); redirect their output to avoid waiting up to two seconds
for inherited output pipes. The caller manages those jobs when the host exits.
The directory is the environment: its ref
exists from construction, and the first operation raises
WorkspaceUnavailableError if it is missing.
On Windows, use WindowsWorkspaceBackend.
working_dir : str | Path
Where commands start and relative paths resolve; ~ is expanded and a relative
path is taken from the current directory. The caller creates and removes it.
Environment variables for every command, on top of the inherited PATH, HOME, LANG,
LC_ALL and LC_CTYPE; the per-call env goes on top.
WorkspaceRef(provider='local', id=<absolute working_dir>), available from construction.
Type: WorkspaceRef
Bases: HostWorkspaceBackend, SupportsPlatform, SupportsRunInDirectory
Run commands as subprocesses on this Windows machine, in PowerShell, and use its filesystem.
The Windows counterpart of LocalWorkspaceBackend, and
like it, this isolates nothing: commands and absolute paths reach anywhere this process can. Paths are
Windows paths (C:\Users\me\project), and a shell=True command runs in PowerShell: pwsh when it
is on PATH, else Windows PowerShell. Its exit code is the last native command’s, as in sh.
Each command runs in a Windows Job Object, so a timeout or cancellation ends the processes it started
along with it. A background job started with Start-Process stays in that Job Object: it outlives a
command that returns, but not one that times out. Commands inherit only the variables Windows tools need
to start (PATH, PATHEXT, SYSTEMROOT, TEMP, USERPROFILE, APPDATA and the like), not arbitrary secrets.
working_dir : str | Path
Where commands start and relative paths resolve; ~ is expanded and a relative
path is taken from the current directory. The caller creates and removes it.
Environment variables for every command, on top of the inherited ones; the per-call env goes on top.
The PowerShell executable; by default pwsh when it is on PATH, else powershell.exe.
Always 'windows': commands run in PowerShell, and paths are Windows paths.
Type: WorkspacePlatform
@async
def run_in_directory(
command: WorkspaceCommand,
*,
cwd: str,
shell: bool = False,
env: Mapping[str, str] | None = None,
timeout: float | None = None,
) -> CommandResult
Run command, a PowerShell script with shell=True or an argv, starting in cwd.
CommandResult
Bases: WorkspaceBackend, SupportsCommands
A WorkspaceBackend whose operations raise WorkspaceUnavailableError with a configured reason.
Always None: there is no environment to name, so nothing can be reconnected to later.
Type: None
Serializable identity of a workspace environment, without credentials.
Pass it to a later run as workspace= to continue in that environment.
Provider that owns the environment.
Type: str
Provider-specific identifier for the environment.
Type: str
Bases: Protocol
The environment an agent run works in; any object with these members conforms.
Built without I/O from configuration and an optional WorkspaceRef;
the first operation creates the environment, or attaches to the one the ref names. The backend never
tears it down; whoever holds the ref does. See the module docstring for the full contract.
The environment’s identity: None until a fresh one is created, then set for good.
Type: WorkspaceRef | None
@async
def working_dir() -> str
The stable working directory for this environment: absolute, symlinks resolved, no ./.. segments.
Bases: Protocol
Optional command execution.
Without it, Workspace.run raises UserError.
@async
def run(
command: WorkspaceCommand,
*,
shell: bool = False,
env: Mapping[str, str] | None = None,
timeout: float | None = None,
) -> CommandResult
Execute a command with stdin at EOF, returning complete output or raising an error.
Undecodable stdout/stderr bytes are replaced with U+FFFD, never dropped.
The command starts in working_dir(). A missing argv program exits 127.
If the environment is destroyed while the command runs, raise WorkspaceUnavailableError;
a command killed by a signal in a live environment returns its exit code.
On timeout or cancellation, stop the foreground process tree on a best-effort basis;
background jobs may continue if they detach. Return when the direct command exits,
after at most a short output-drain grace even if a background child keeps stdout open.
Never stop a process the command detached into its own session, neither when the command returns
nor when a backend attaches by the same ref later; a provider’s own idle pause or stop is separate.
CommandResult
An argv sequence, or a shell string with shell=True; a mismatch raises TypeError.
Workspace.run rejects an empty argv with ValueError.
shell : bool Default: False
Whether to interpret command with the workspace’s shell.
Extra environment variables, layered over the backend’s own.
A positive finite number of seconds before
WorkspaceTimeoutError; no timeout by default.
Invalid values raise ValueError.
Bases: Protocol
Optional native file access; without it, Workspace uses the shell.
Paths are absolute POSIX paths. A missing path raises FileNotFoundError (except in exists),
and reading a directory raises IsADirectoryError.
@async
def read_bytes(path: str) -> bytes
Read a file’s contents as bytes.
@async
def write_bytes(path: str, data: bytes) -> None
Write bytes to a file, creating missing parents and writing through an existing symlink.
@async
def stat(path: str) -> FileEntry
Return metadata for a file or directory.
FileEntry
@async
def list_dir(path: str) -> Sequence[FileEntry]
List the entries of a directory (non-recursive).
Sequence[FileEntry]
@async
def make_dir(path: str) -> None
Create a directory, including missing parents (mkdir -p semantics).
@async
def remove(path: str) -> None
Remove a file, or a directory and its contents.
Refuses the working directory and its ancestors with ValueError; a symlink is removed itself.
@async
def exists(path: str) -> bool
Whether a file or directory exists at the path.
Bases: Protocol
Native symlink resolution for path boundaries such as harness FileSystem’s root_dir.
Without it, Workspace.realpath uses the backend’s shell, and on a backend without commands it
only normalizes the path as text, so path checks cannot see through symlinks. Implement it on a
filesystem-only backend whose storage can hold symlinks.
@async
def realpath(path: str) -> str
Resolve inside the environment, like os.path.realpath(path, strict=False).
Relative link targets start in the link’s directory; .. after a link climbs from its
target. Keep missing components as written. A loop must not hang; a returned path through a loop
must stay inside the directory holding it (or raise OSError). Return an absolute, normalized path.
Bases: Protocol
Optional: a backend that says which shell and path syntax it has; without it, a backend is 'posix'.
A 'windows' backend’s paths are absolute Windows paths wherever the rest of this module says POSIX.
It also implements SupportsRunInDirectory, since there
is no sh to change directory with.
The workspace’s shell and path syntax.
Type: WorkspacePlatform
Bases: Protocol
Optional: a backend that starts a command in a directory itself.
Without it, Workspace.run starts a command in a directory
through sh, which a 'windows' backend has no use for.
@async
def run_in_directory(
command: WorkspaceCommand,
*,
cwd: str,
shell: bool = False,
env: Mapping[str, str] | None = None,
timeout: float | None = None,
) -> CommandResult
SupportsCommands.run, started in cwd.
cwd is an absolute directory that Workspace.run has
resolved and checked.
CommandResult
Bases: Protocol
The path functions for a workspace’s paths: posixpath, or ntpath on a 'windows' workspace.
The result of a completed command.
The real exit code of the process. Non-zero is a normal result, not an error.
Type: int
Captured standard output.
Type: str
Captured standard error.
Type: str
Metadata about a file or directory.
Base name of the entry.
Type: str
Absolute POSIX path of the entry inside the workspace.
Type: str
Whether the entry is a directory, following a symlink to its target.
Type: bool
Size in bytes for a regular file when known; None is allowed (the shell fallback can measure it).
Bases: RuntimeError
The workspace layer deliberately failed an operation.
Bases: WorkspaceError
The environment is gone or unusable (terminated, expired, not found), so retrying can’t succeed.
Bases: WorkspaceError, TimeoutError
A command exceeded its timeout=; stdout/stderr hold partial output, like subprocess.TimeoutExpired.
Bases: WorkspaceError
A command exceeded its output cap; stdout and stderr hold their captured beginnings.
Bases: WorkspaceError, PermissionError
A mutation was refused because the workspace is read-only.
Raised by ReadOnlyWorkspace and wrappers like it.
@async
def lowest_authority_under(workspace: Workspace, directory: str) -> Authority
The lowest authority workspace gives any path at or under directory.
For a capability that hands a directory to something that reads it with one level, such as a delegate rooted
there or a check that decides whether to trust the files under it: every file it reads there gets no more than
workspace gives it. It’s authority_of(directory), lowered by
every wrapper’s path_authority entry at or under directory, both where the entry is written and where it
leads, at the level authority_of caps a link’s target at. Entries match ignoring case, as authority_of does,
keeping the lower level.
A directory outside the working directory that no path_authority entry contains is outside the workspace, at
'none', as authority_of puts it. Symlinks under directory that no entry names aren’t followed: the answer
comes from the workspace’s levels, not from listing the files.
The shell and path syntax of a workspace.
'posix': shell=True runs POSIX sh, and paths are POSIX paths (/home/me/project).
'windows': shell=True runs PowerShell, and paths are Windows paths (C:\Users\me\project).
Type: TypeAlias Default: Literal['posix', 'windows']
An argv sequence (['python', '-c', 'print(1)']), or a shell string with shell=True.
Type: TypeAlias Default: str | Sequence[str]
The conformance suite for Pydantic AI workspace backends.
Subclass WorkspaceBackendSuite in a pytest module and provide a backend fixture: each test checks
one rule of the WorkspaceBackend contract, the same rules the built-in and provider backends pass.
Requires pytest and the anyio pytest plugin.
Subclass in your test suite and provide the backend fixture.
Each test checks one rule of the backend contract. Command rules skip for a backend without
SupportsCommands; filesystem rules run through Workspace, so a
command-only backend is checked on the file operations derived through its shell. The reattach
rules need the optional fixtures below and skip without them.
def fresh_backend() -> Callable[[], WorkspaceBackend] | None
Build an uninitialized backend to check concurrent first use, if supported.
Callable[[], WorkspaceBackend] | None
def destructive_backend(
fresh_backend: Callable[[], WorkspaceBackend] | None,
) -> Callable[[], WorkspaceBackend] | None
Build an independent environment for destruction; defaults to fresh_backend.
Callable[[], WorkspaceBackend] | None
def attach_backend() -> Callable[[WorkspaceRef], WorkspaceBackend] | None
Build a second backend that attaches to ref. Enables the reattach rules.
Callable[[WorkspaceRef], WorkspaceBackend] | None
def destroy_environment() -> Callable[[WorkspaceBackend], Awaitable[None]] | None
Destroy the environment behind backend. Enables the reattach-after-destroy rule.
Callable[[WorkspaceBackend], Awaitable[None]] | None
@async
def test_command_form_must_match_shell(backend: WorkspaceBackend) -> None
A string needs shell=True and an argv sequence needs shell=False; a mismatch is a TypeError.
@async
def test_stdin_is_at_eof(backend: WorkspaceBackend) -> None
Noninteractive commands never wait for input from the caller.
@async
def test_command_output_is_complete(backend: WorkspaceBackend) -> None
If output cannot be collected in full, the backend must raise rather than return a truncated success.
def can_detect_exit_with_inherited_output_pipes() -> bool
Override only if the SDK cannot report exit independently of pipe EOF (E2B currently cannot).
@async
def test_result_reports_exit_code_stdout_and_stderr(backend: WorkspaceBackend) -> None
A non-zero exit is a normal result, not an error.
@async
def test_a_missing_program_exits_127(backend: WorkspaceBackend) -> None
Like sh, a program that doesn’t exist is a normal result with exit code 127, not an error.
@async
def test_working_dir_is_canonical(backend: WorkspaceBackend) -> None
Absolute, symlinks resolved, no ./..: the directory commands actually start in.
@async
def test_run_starts_in_cwd(backend: WorkspaceBackend) -> None
Workspace.run(cwd=...) starts the command there, relative paths resolving against the working directory.
@async
def test_large_file_round_trip(backend: WorkspaceBackend) -> None
A shell-derived filesystem must page reads rather than hit a command-output cap.
def has_real_posix_shell() -> bool
Only a test double with no POSIX process/filesystem can opt out.
def enforces_parent_file_errors() -> bool
Opt out only for an in-memory test double without real path traversal.
def filesystem_honors_shell_permissions() -> bool
Override only for provider file APIs that bypass the command user’s permissions (e.g. E2B envd).
@async
def test_native_realpath_keeps_the_working_dir_and_missing_names(
backend: WorkspaceBackend,
) -> None
Checked without commands, so a filesystem-only backend’s realpath is covered too.
@async
def test_a_backend_attached_by_ref_reaches_the_same_environment(
backend: WorkspaceBackend,
attach_backend: Callable[[WorkspaceRef], WorkspaceBackend] | None,
) -> None
Durable execution rebuilds the backend from its ref for every call, so this is what it relies on.
@async
def test_a_backend_attached_by_ref_reaches_a_detached_process(
backend: WorkspaceBackend,
attach_backend: Callable[[WorkspaceRef], WorkspaceBackend] | None,
has_real_posix_shell: bool,
) -> None
A process a command detached into its own session is still running for a backend attached by ref.
A Windows implementation of the workspace backend protocol.
WindowsWorkspaceBackend runs commands as plain host
subprocesses in PowerShell — it isolates nothing.
def powershell_script(script: str) -> str
script as WindowsWorkspaceBackend runs a shell=True command.
It writes its output as UTF-8 without progress bars, and exits with its last native command’s code, as sh
does, rather than PowerShell’s 1 for any failure. For a tool that runs PowerShell some other way, such as a
detached job, so that it behaves like a command run directly.