Daytona Sandbox
Run your agent’s commands and file edits in an isolated Daytona cloud 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.
flowchart TB
accTitle: Daytona Sandbox: your agent's commands run in a Daytona cloud sandbox
accDescr: On your machine, the model calls Coder, Shell or FileSystem tools such as run_command. DaytonaSandbox's get_workspace hands the run a Daytona cloud sandbox as ctx.workspace over the Daytona API with DAYTONA_API_KEY. It stops when idle, destroy(ref) deletes it, and later runs reattach with the WorkspaceRef in the message history or result.workspace.ref, starting it if stopped.
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"]
daytona["DaytonaSandbox()<br/>get_workspace hands<br/>the run the sandbox"]:::capability
end
sandbox["Daytona cloud sandbox<br/>stops when idle,<br/>deleted by destroy(ref)"]:::external
model <-->|"tool call, result"| tools
tools -->|"ctx.workspace"| daytona
ref -.->|"a later run reattaches,<br/>starting it if stopped"| daytona
daytona <-->|"Daytona API,<br/>DAYTONA_API_KEY"| sandbox
classDef capability stroke:#E520E9,stroke-width:2px
classDef external stroke:#0E9C86,stroke-width:2px
pip install "pydantic-ai-harness[coder,daytona,anthropic]"
uv add "pydantic-ai-harness[coder,daytona,anthropic]"
Set DAYTONA_API_KEY to an API key from your Daytona dashboard. 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.daytona_sandbox import DaytonaSandbox
agent = Agent('anthropic:claude-opus-5-5', capabilities=[DaytonaSandbox(), 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 its disk, and costs money, until you delete it. Daytona stops it when idle, but doesn’t delete it. See Clean up.
- Commands run as the non-root
daytonauser in/home/daytona. Passworking_dir='/home/daytona/project'to give the agent a project directory. It is created on a new sandbox. - The default snapshot has git, Python and
rg, but not your project’s dependencies. A snapshot is the image a new sandbox starts from. Build a Daytona snapshot with them and passsnapshot='my-snapshot', or install them before the run. An unknown snapshot fails on first use withWorkspaceUnavailableError.
Pass the message history, and the next run works in the same sandbox, starting it again if Daytona stopped it:
from pydantic_ai import Agent
from pydantic_ai_harness.coder import Coder
from pydantic_ai_harness.daytona_sandbox import DaytonaSandbox
agent = Agent('anthropic:claude-opus-5-5', capabilities=[DaytonaSandbox(), 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 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 deleted, 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 DAYTONA_API_KEY or a client= too.
Already have a daytona.AsyncSandbox? Pass workspace=DaytonaSandboxBackend(sandbox=sandbox, working_dir=..., env=...) to a run. DaytonaSandbox’s settings don’t apply to it. A backend’s get_sandbox() returns its daytona.AsyncSandbox for Daytona features the workspace API doesn’t cover. On a backend with no sandbox yet, it creates one, which Daytona 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.daytona_sandbox import DaytonaSandbox, DaytonaSandboxBackend
agent = Agent('anthropic:claude-opus-5-5', capabilities=[DaytonaSandbox(), Coder()])
async def run_in_prepared_sandbox() -> str:
backend = DaytonaSandboxBackend(working_dir='/home/daytona/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 sandbox exists
if ref is not None:
await DaytonaSandbox().destroy(ref)
The run leaves a backend you built open, so close it with aclose(). That closes the client it opened from DAYTONA_API_KEY, not the sandbox. A client= or sandbox= you passed is never closed. To keep the sandbox, store backend.ref instead of destroying it.
Pass desktop=True and add ComputerUse:
capabilities=[DaytonaSandbox(desktop=True), ComputerUse()]. The screen is 1280x800; pass a size such as
desktop=(1440, 900) for another. The size is set when the sandbox is created.
Daytona’s default snapshot has a desktop with a terminal and Chromium. A custom snapshot needs Daytona’s desktop packages.
- The desktop runs a VNC server with no password on one of the sandbox’s preview ports.
- On a private sandbox, anyone who holds a preview token for that port can see the screen and control the mouse and keyboard.
- On a public sandbox, Daytona’s preview links need no token, so anyone with the preview URL can see and control the desktop.
- Where the snapshot’s Chromium can’t run its own sandbox, as in Daytona’s default snapshot, the desktop start adds
--no-sandboxto Chromium’s flags through a file in/etc/chromium.d/. It writes the file as root or with passwordlesssudo, on sandboxes it creates and on ones you attach withref=orsandbox=. The file stays after the run, so a web page that breaks out of Chromium’s renderer can reach the rest of the sandbox. A custom snapshot whose Chromium sandbox works is left alone. - Keep the sandbox private if others shouldn’t see or control the desktop.
- On Daytona’s Tier 1 and Tier 2, a sandbox can reach only package registries, GitHub and AI APIs, even with
allow_internet_access=True, so its browser can’t open other sites. See Daytona’s network limits. - The desktop can’t press print screen, pause, scroll lock or the menu key, or type characters beyond U+FFFF, such as most emoji. The agent is told when it asks for one.
Delete a sandbox with the ref you stored. This doesn’t start a stopped sandbox:
from pydantic_ai.workspaces import WorkspaceRef
from pydantic_ai_harness.daytona_sandbox import DaytonaSandbox
async def delete_sandbox(ref: WorkspaceRef) -> None:
await DaytonaSandbox().destroy(ref)
A failed run returns no result, so delete its sandbox in an on_run_error hook:
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.daytona_sandbox import DaytonaSandbox
hooks = Hooks()
@hooks.on.run_error
async def delete_failed_run_sandbox(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 delete short, bounded so a hung call can't hang it.
with anyio.move_on_after(30, shield=True):
await DaytonaSandbox().destroy(ctx.workspace.ref)
raise error
agent = Agent('anthropic:claude-opus-5-5', capabilities=[DaytonaSandbox(), Coder(), hooks])
A sandbox you don’t delete keeps its disk, and a later run starts it again:
- A container sandbox is stopped after 15 idle minutes and archived after 7 days. Set
auto_stop_interval=in minutes to change the idle time, or0to keep it running. - A sandbox from a VM snapshot is paused after 60 idle minutes instead, and is never archived.
If your program stops before it stores the ref, for example after a crash or Ctrl-C, the sandbox is left behind. To find it:
- List your sandboxes in Daytona. Sandboxes Pydantic AI creates have the label
created-by=pydantic-ai. - Or search your logs for
Created Daytona sandbox <id>, logged at INFO by thepydantic_ai_harnesslogger.
Then delete it: await DaytonaSandbox().destroy(WorkspaceRef(provider='daytona', id='<id>')).
Pass secrets to give a new sandbox Daytona Secrets, as a map from environment variable name to Secret name. The variable holds a placeholder, and Daytona swaps in the real value as requests leave for the Secret’s hosts. Create the Secret once, then use it:
from daytona import AsyncDaytona, CreateSecretParams
from pydantic_ai_harness.daytona_sandbox import DaytonaSandbox
async def create_github_secret(token: str) -> None: # a GitHub token, such as the output of `gh auth token`
async with AsyncDaytona() as daytona:
await daytona.secret.create(
CreateSecretParams(
name='github-token',
value=token,
hosts=['github.com', 'api.github.com', 'uploads.github.com'],
)
)
sandbox = DaytonaSandbox(secrets={'GH_TOKEN': 'github-token'})
gh then works as the token’s owner, while echo $GH_TOKEN in the sandbox prints the placeholder. For git push, have git send the placeholder as its password:
git config --global credential.https://github.com.helper '!f() { echo username=x-access-token; echo "password=$GH_TOKEN"; }; f'
- Always set
hostson the Secret. Without them, Daytona sends the real value to any host. - Daytona swaps the value only in HTTPS request headers, including git’s password. Request bodies, query strings and plain HTTP keep the placeholder. Use
https://remotes, notgit@github.com:owner/repo.git. - The agent can’t see the token, but it can use it for anything the token allows.
- An attached sandbox keeps the Secrets it was created with. To swap the token, call
daytona.secret.updatewith the Secret’s ID. Running sandboxes pick it up within seconds. - To change which Secrets a running sandbox has, call
update_secretsonawait backend.get_sandbox(). It replaces the whole set. New variables reach only commands started after it. A sandbox created without Secrets must restart first.
| Option | What it does |
|---|---|
client | A daytona.AsyncDaytona to share across runs on one event loop, or to configure its API URL or target. Default: None, a client each run opens from DAYTONA_API_KEY and closes when it ends. You close a client you pass. |
snapshot | Daytona snapshot a new sandbox starts from. Default: None, Daytona’s default. An unknown snapshot fails on first use. |
auto_stop_interval | Idle minutes before Daytona stops a new sandbox. 0 disables it. Default: None, Daytona’s default of 15 minutes for a container. A VM pauses after 60 minutes instead. |
allow_internet_access | Whether a new sandbox can reach the internet. Default: True. False blocks everything only for Tier 3 and 4 organizations. Lower tiers can still reach package registries, GitHub and AI APIs, so False doesn’t stop data leaving the sandbox there. See Daytona’s network limits. |
working_dir | Absolute directory commands start in and relative paths resolve against. Default: None, /home/daytona. 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. |
secrets | Daytona Secrets for a new sandbox, as a map from environment variable name to the name of an existing organization Secret. Passed to AsyncDaytona.create unchanged. Default: None. An attached sandbox keeps the ones it was created with. See Keep a token out of the sandbox. |
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. |
desktop | Give the sandbox a graphical display for ComputerUse: True for 1280x800, or its (width, height). The size applies to a new sandbox. Default: False. |
client, working_dir, env, desktop (but not its size), authority and path_authority also apply when you reattach, and destroy uses client. The other options only shape a new sandbox.
- A timeout or cancellation stops the command, not the sandbox. If Daytona doesn’t confirm the stop, the command may still be running, so inspect or delete the sandbox.
WorkspaceTimeoutErrorcarries the last 4 KiB of each stream.- Output is collected when the command exits, so output a background child writes afterwards is lost. Redirect it to a file.
Shell.start_commanddoes this for you. - A command whose output passes 10 MiB raises
WorkspaceOutputLimitErroronce it exits. Redirect large output to a file. timeout=Noneremoves the command deadline, not Daytona’s idle stop.- The Daytona SDK needs asyncio. Under Trio, every operation raises
UserError.
Add TemporalDurability() next to DaytonaSandbox() and install the temporal extra. Workspaces covers what changes.
DaytonaSandbox 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 Daytona sandbox as the run’s workspace.
A run with no reference creates a fresh sandbox on first use; pass a WorkspaceRef to attach
to an existing one. Ending a run does not delete the sandbox: Daytona stops it when idle and
keeps it until you delete it. Commands run under sh -c as the sandbox’s default user.
This capability supplies the workspace only. Compose it with capabilities that use it, such
as Coder, Shell, and FileSystem. See
Workspaces for more.
A daytona.AsyncDaytona to share across runs on one event loop; you close it. When None,
each run opens one from DAYTONA_API_KEY and closes it when the run ends.
Type: AsyncDaytona | None Default: None
Daytona snapshot a newly created sandbox starts from; Daytona’s default when None.
An unknown snapshot raises WorkspaceUnavailableError on first use.
Type: str | None Default: None
Idle minutes before Daytona stops a newly created sandbox; 0 disables it, and None
keeps Daytona’s default (15 minutes for a container; a VM pauses after 60 instead). Attaching
starts a stopped or paused sandbox again.
Type: int | None Default: None
Whether a newly created sandbox may reach the internet. When False, Daytona’s Tier 3 and 4
block everything; lower tiers keep package registries, GitHub, and AI APIs reachable.
Type: bool Default: True
Absolute directory commands start in and relative paths resolve against; None uses the sandbox’s own.
Created on a new sandbox; an attached sandbox must already have it.
Type: str | None Default: None
Environment variables every command gets, also on an attached sandbox; a command’s env is
layered on top. 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
Daytona’s secrets for a new sandbox, passed to AsyncDaytona.create unchanged: environment
variable name to Secret name. The variable holds a placeholder, and Daytona swaps in the real value
in HTTPS request headers as requests leave for the Secret’s hosts (any host if it has none). An
attached sandbox keeps the ones it was created with.
Type: Mapping[str, str] | None Default: None
Give the sandbox a graphical display, for ComputerUse: True
for 1280x800, or its (width, height). The size applies to a new sandbox. A sandbox the run attaches to keeps its
own size.
Type: bool | tuple[int, int] Default: False
@classmethod
def from_spec(
cls,
*,
id: str | None = None,
description: str | None = None,
defer_loading: bool = False,
snapshot: str | None = None,
auto_stop_interval: int | None = None,
allow_internet_access: bool = True,
working_dir: str | None = None,
env: Mapping[str, str] | None = None,
authority: Authority = 'operator',
path_authority: Mapping[str, Authority] | None = None,
secrets: Mapping[str, str] | None = None,
desktop: bool | tuple[int, int] = False,
) -> DaytonaSandbox[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 falls back to the
variadic base from_spec, because client’s AsyncDaytona hint is a TYPE_CHECKING import, and
publishes only the bare 'DaytonaSandbox'.
DaytonaSandbox[Any]
def backend(ref: WorkspaceRef) -> DaytonaSandboxBackend
Construct a lazy backend for an existing sandbox.
DaytonaSandboxBackend
@async
def destroy(ref: WorkspaceRef) -> None
Delete a sandbox by ID without starting it, including one Daytona has stopped.
A sandbox 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, SupportsRealpath, SupportsDisplay
A Daytona sandbox as a Pydantic AI WorkspaceBackend.
Commands and file operations run inside a Daytona sandbox, so the host is never exposed.
Building one does no I/O. The first operation creates or attaches to a sandbox, and the typed
daytona.AsyncSandbox is available through get_sandbox(). The backend does not stop or
delete the sandbox; that is the application’s job.
A command’s complete output is returned once it exits. A shell string runs under /bin/sh -c;
a timeout or cancellation stops the command.
A deleted sandbox, one Daytona stopped while idle (attaching again starts it), rejected
credentials, and an unknown snapshot raise WorkspaceUnavailableError. Path failures raise the
built-in errors, such as FileNotFoundError.
sandbox : AsyncSandbox | None Default: None
A live daytona.AsyncSandbox you already have. Whoever created it owns deleting it.
client : AsyncDaytona | None Default: None
A daytona.AsyncDaytona API client to create or attach with. The caller owns closing
it. Without one, the backend opens its own from the environment on first use and closes
it in aclose().
ref : WorkspaceRef | None Default: None
Identity of an existing sandbox to attach to on first use.
Daytona snapshot a newly created sandbox starts from; Daytona’s default when None.
Idle minutes before Daytona stops a newly created sandbox; 0 disables
it, and None keeps Daytona’s default (15 minutes for a container; a VM pauses after 60
instead).
allow_internet_access : bool Default: True
Whether a newly created sandbox may reach the internet.
Absolute directory commands start in and relative paths resolve against; the
sandbox’s own default when None, discovered with pwd -P on first use.
Environment variables every command gets; a command’s own env is layered on top.
They are also set on a newly created sandbox.
Daytona’s secrets for a newly created sandbox, passed to AsyncDaytona.create
unchanged: environment variable name to Secret name. The variable holds a placeholder, and
Daytona swaps in the real value in HTTPS request headers as requests leave for the Secret’s
hosts (any host if it has none). An attached sandbox keeps the ones it was created with.
Whether the sandbox has a display for ComputerUse,
started on first use: True for 1280x800, or its (width, height). The size applies to a new sandbox,
since Daytona can’t resize a running one. The snapshot needs Daytona’s desktop packages, which the default
snapshot has.
Identity of the sandbox, or None before one has been created.
The id is always Daytona’s sandbox ID, also after attaching by a ref that names the sandbox.
Type: WorkspaceRef | None
The sandbox’s desktop, when created with desktop=True.
Type: Display | None
@async
def get_sandbox() -> AsyncSandbox
Return the typed daytona.AsyncSandbox, creating or attaching to it on first use.
Attaching by ref to a sandbox that no longer exists raises WorkspaceUnavailableError; it
does not create a replacement.
AsyncSandbox
@async
def aclose() -> None
Close the AsyncDaytona API client this backend opened for itself.
A client passed as client= is left alone, and the sandbox keeps running. A later
operation opens a new client and attaches by ref. DaytonaSandbox calls this when the
run that used the backend ends.
@async
def working_dir() -> str
Return the canonical directory commands start in, probed once per connection.