Skip to content

Smol Sandbox

Run your agent’s commands and file edits in a smolvm microVM on your own machine, isolated from your files and processes, without a cloud account.

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.

flowchart TB
    accTitle: Smol Sandbox: your agent's commands run in a local smolvm microVM
    accDescr: On your machine, the model calls Coder, Shell or FileSystem tools such as run_command and gets results. Via ctx.workspace, the SmolSandbox capability hands the run a VM, a smolvm microVM on the same machine with its own kernel and filesystem, reached through smolmachines in your process. The VM has no network access by default, unless allow_internet_access=True.
    subgraph machine["Your machine"]
        model(["model"])
        tools["Coder, Shell or<br/>FileSystem tools,<br/>such as run_command"]
        sandbox["SmolSandbox()<br/>hands the run a VM"]:::capability
        vm["smolvm microVM<br/>own kernel and<br/>filesystem"]:::external
    end
    network["network access, unless<br/>allow_internet_access=True"]:::blocked
    model <-->|"tool call, result"| tools
    tools -->|"ctx.workspace"| sandbox
    sandbox <-->|"smolmachines,<br/>in your process"| vm
    vm -.-x|"none by default"| network
    classDef capability stroke:#E520E9,stroke-width:2px
    classDef external stroke:#0E9C86,stroke-width:2px
    classDef blocked stroke:#E5533D,stroke-width:2px,stroke-dasharray:4 3

Install

Terminal
pip install "pydantic-ai-harness[coder,smol,anthropic]"

The smol extra installs smolmachines, which runs VMs on this machine. It needs one of:

  • macOS on Apple silicon.
  • Linux on x86_64 or aarch64 with glibc 2.34 or newer. The user running the agent needs read and write access to /dev/kvm.

smolvm itself also runs on Windows x86_64, with the Windows Hypervisor Platform, but smolmachines has no Windows build, so SmolSandbox doesn’t run there.

The examples also use Coder and an Anthropic model, hence 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.smol_sandbox import SmolSandbox

agent = Agent('anthropic:claude-opus-5-5', capabilities=[SmolSandbox(image='python:3.12-alpine'), Coder()])
result = agent.run_sync('Write a script that prints the first 10 primes, and run it.')

Coder’s shell and file tools now run in a VM with its own kernel and filesystem. 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.
  • Its disk stays on this machine after the run. The VM shuts down when your process exits, but nothing deletes it. See Clean up.
  • It has no network access. Pass allow_internet_access=True to install packages or clone repositories. That access is unrestricted and comes from this machine, so the VM can reach anything this machine can, such as your local network or a cloud metadata endpoint.
  • Commands run as the image’s user, usually root, in /workspace, which is created if missing.
  • Without an image, the VM runs smolvm’s own Alpine Linux, which has BusyBox but no Python, git or ripgrep. An image is any OCI image with a POSIX /bin/sh; smolvm pulls it the first time.

Continue in the same VM

Pass the message history, and the next run works in the same VM:

from pydantic_ai import Agent
from pydantic_ai_harness.coder import Coder
from pydantic_ai_harness.smol_sandbox import SmolSandbox

agent = Agent('anthropic:claude-opus-5-5', capabilities=[SmolSandbox(image='python:3.12-alpine'), Coder()])
result = agent.run_sync('Write a script that prints the first 10 primes, and run it.')

followup = agent.run_sync('Now make it print the first 100.', message_history=result.all_messages())
ref = result.workspace.ref  # or store this, and pass `workspace=ref` to a later run

result.workspace.ref is a WorkspaceRef holding the VM’s name. Store it to continue later or to delete the VM.

If the VM has been deleted, the run raises WorkspaceUnavailableError. Pass workspace='new' to start over. Workspaces covers how runs find their workspace.

Another process can continue in the VM with the ref, and boots it again. smolmachines saves a VM’s disk when the VM stops or when sync runs inside it, so stop the VM before your process exits, or its recent file changes can be lost:

from pydantic_ai.workspaces import WorkspaceRef
from pydantic_ai_harness.smol_sandbox import SmolSandbox


async def stop_vm(ref: WorkspaceRef) -> None:
    machine = await SmolSandbox().backend(ref).get_sandbox()
    await machine.stop()

Prepare a VM before the run

To seed files or install packages before the agent starts, boot 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.smol_sandbox import SmolSandbox, SmolSandboxBackend

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


async def main() -> None:
    backend = SmolSandboxBackend(image='python:3.12-alpine', allow_internet_access=True)
    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 VM exists
        if ref is not None:
            await SmolSandbox().destroy(ref)


if __name__ == '__main__':
    asyncio.run(main())

The finally deletes the VM even when setup or the run fails, or is cancelled mid-boot. To keep it, store backend.ref instead.

SmolSandbox’s settings don’t apply to a backend you pass as workspace=. Give the backend its own.

For features the workspace API doesn’t cover, backend.get_sandbox() returns the SDK’s smol.AsyncMachine.

Give the agent a desktop

Pass desktop=True and add ComputerUse: capabilities=[SmolSandbox(desktop=True, allow_internet_access=True), ComputerUse()]. The screen is 1280x800; pass a size such as desktop=(1440, 900) for another.

Without an image, a new VM runs debian:bookworm-slim, and its first start installs the display’s programs, with no web browser. That needs allow_internet_access=True: creating a new VM without it raises UserError. For a VM without network access, pass an image that has the programs.

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

Delete a VM and its disk with the ref you stored. A VM that is already gone returns quietly. A stopped VM is booted briefly first, because smolmachines can’t delete a local VM without attaching to it:

from pydantic_ai.workspaces import WorkspaceRef
from pydantic_ai_harness.smol_sandbox import SmolSandbox


async def delete_vm(ref: WorkspaceRef) -> None:
    await SmolSandbox().destroy(ref)

A failed run returns no result, so delete its VM 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.smol_sandbox import SmolSandbox

hooks = Hooks()


@hooks.on.run_error
async def delete_failed_run_vm(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 SmolSandbox().destroy(ctx.workspace.ref)
    raise error


agent = Agent('anthropic:claude-opus-5-5', capabilities=[SmolSandbox(image='python:3.12-alpine'), Coder(), hooks])

Find a lost VM

If your program stops before it stores the ref, for example after a crash or Ctrl-C, the VM is left behind. To find it, search your logs for Creating smol VM <id>, logged at INFO by the pydantic_ai_harness logger.

Then delete it: await SmolSandbox().destroy(WorkspaceRef(provider='smol', id='<id>')).

Use a VM you already have

Pass one of these as workspace=:

  • SmolSandboxBackend(sandbox=machine), with a smol.Machine or smol.AsyncMachine.
  • SmolSandboxBackend(ref=WorkspaceRef(provider='smol', id=...)), with a VM’s name.

Give the backend its own working_dir= and env=. The backend never deletes the VM.

Security model

The VM is the boundary. It has its own kernel and filesystem. Nothing from this machine is mounted into it, no ports are published, and none of your environment variables reach it. Commands run as the image’s user, root on smolvm’s Alpine and most images, so anything the agent runs can change anything in the VM.

  • smolvm runs in your process with your OS user’s permissions. SMOLVM_* environment variables configure it, and some, like SMOLVM_SECCOMP=off, turn off its own confinement on Linux. Don’t let untrusted input set them.
  • image is pulled by tag; pin a digest, such as python:3.12-alpine@sha256:..., to get the same image every time.
  • cpus and memory_mb cap one VM. Nothing limits how many VMs a process boots.

Which VMs a run can use

Whoever passes a ref runs commands in the VM it names. smolmachines can open any VM of your OS user by name, including ones other tools made with your folders mounted. So:

  • Refs reaching SmolSandbox (message history, workspace=ref, backend(ref), destroy(ref)) only open VMs SmolSandbox booted, named pydantic-ai- and 32 hex digits. Any other name raises ValueError. Durable execution rebuilds the workspace from its ref, so it only works with VMs SmolSandbox booted.
  • SmolSandboxBackend(...) built by your code opens any VM on this machine, because your code chose it. A later run given only its message history raises ValueError; pass the backend again, or workspace='new'.
  • The name doesn’t prove origin: any program running as your OS user can boot a VM with such a name. Only pass refs your application stored itself, and don’t build SmolSandboxBackend(ref=...) from user input.

Configuration

OptionWhat it does
imageOCI image for a new VM. Default: None, smolvm’s own Alpine Linux, or debian:bookworm-slim with desktop.
cpusvCPUs for a new VM. Default: None, smolvm’s default.
memory_mbMemory for a new VM in MiB. Default: None, smolvm’s default.
allow_internet_accessWhether a new VM has unrestricted outbound network access, from this machine’s network. Default: False.
working_dirAbsolute directory commands start in and relative paths resolve against, created if missing. Default: /workspace. None uses the VM’s own, / without an image.
envEnvironment variables every command gets, on top of the image’s. Default: None. Nothing from your machine’s environment reaches the VM. The agent’s commands can read these, so leave out secrets it shouldn’t see.
desktopGive the VM a graphical display for ComputerUse: True for 1280x800, or its (width, height). The size applies when the display first starts. Default: False.
authorityWho wrote the VM’s files: 'none' for files nobody on your side wrote, such as a cloned third-party repository, or 'user' for the user’s own. Capabilities that put a file into the prompt give it no more authority than this. Default: 'operator', files you wrote.
path_authorityAn authority level for specific directories and files, overriding authority under them. The longest matching path wins. Paths are VM paths, relative to the working directory or absolute, and ~ isn’t expanded. Default: None.

image, cpus, memory_mb and allow_internet_access only shape a new VM. working_dir and env apply to every command. They and desktop also apply after you reattach.

Limits

  • On an unsupported platform, importing pydantic_ai_harness.smol_sandbox raises ImportError.
  • A host that can’t run VMs, such as Linux without /dev/kvm access, raises WorkspaceUnavailableError on first use. Check with smol.local_availability().
  • Files move 64 KiB per command, so a file of several MiB takes seconds to read or write.
  • Images need the usual file utilities, which BusyBox has.
  • A command whose output passes 10 MiB is stopped with WorkspaceOutputLimitError. Redirect large output to a file.
  • On a timeout, the command and the processes it started are killed. Jobs that outlive their command, like a Shell background job, keep running.
  • The smol SDK needs asyncio. Under Trio, operations raise UserError.

Telemetry

SmolSandbox emits no spans of its own. Core’s instrumentation records pydantic_ai.workspace.provider (smol) and pydantic_ai.workspace.id on the agent run span, and each command or file operation runs inside its tool call’s span.

Treat the recorded id like a ref: any process of your OS user on this machine can attach to the VM with it.

API reference

SmolSandbox

Bases: AbstractCapability[AgentDepsT]

Supply a smolvm microVM on this machine as the run’s workspace.

A run with no reference boots a fresh VM on first use. Pass a WorkspaceRef supplied by the application to attach to a VM from an earlier run; only ids in the form SmolSandbox names its VMs are accepted.

This capability supplies execution only. Compose it with tools or capabilities that use the workspace, such as Coder, Shell, or FileSystem.

Attributes

image

OCI image a new VM runs, such as 'python:3.12-alpine'; None boots smolvm’s own Alpine Linux without pulling anything, unless desktop is set.

Type: str | None Default: None

cpus

vCPUs for a new VM; smolvm’s default when None.

Type: int | None Default: None

memory_mb

Memory for a new VM in MiB; smolvm’s default when None.

Type: int | None Default: None

allow_internet_access

Whether a new VM gets unrestricted outbound network access, made from this machine’s network: the internet, but also its local network and services.

Type: bool Default: False

working_dir

Absolute directory commands start in and relative paths resolve against, created if missing; None uses the VM’s own.

Type: str | None Default: '/workspace'

env

Environment variables every command gets, also on an attached VM; nothing is read from the host.

Type: Mapping[str, str] | None Default: field(default=None, repr=False)

desktop

Give the VM a graphical display, for ComputerUse: True for 1280x800, or its (width, height). Without an image, a new VM runs debian:bookworm-slim, and the first start installs the display programs, which needs allow_internet_access.

Type: bool | tuple[int, int] Default: 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

Methods

backend
def backend(ref: WorkspaceRef) -> SmolSandboxBackend

Attach lazily to an existing VM, one SmolSandbox created.

Returns

SmolSandboxBackend

destroy

@async

def destroy(ref: WorkspaceRef) -> None

Delete a VM by ref; one that is already gone returns quietly.

A boot of it still in progress in this process finishes first, and the deletion isn’t abandoned when the caller is cancelled. The SDK has no delete by ID for a local VM, so this attaches first, which boots a stopped VM briefly.

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

SmolSandboxBackend

Bases: WorkspaceBackend, SupportsCommands, SupportsDisplay

A local smolvm microVM as a Pydantic AI WorkspaceBackend.

Commands run inside a VM on this machine, with its own kernel and filesystem, so they can’t touch the host’s files or processes. File operations run as shell commands in the VM (see Writing a backend), so a custom image needs /bin/sh and the usual file utilities.

Building one does no I/O. The first operation boots a new persistent VM, or attaches to the one sandbox is or ref names, and get_sandbox() returns the SDK’s smol.AsyncMachine. ref is set as soon as a boot starts; a VM the backend boots is named pydantic-ai- and 32 hex digits. The backend never deletes the VM; whoever holds the ref does. A ref also works from another process, which boots the VM again, but only the VM’s stop() flushes its disk: stop it before this process exits to keep recent file changes.

Constructor Parameters

sandbox : smol.Machine | smol.AsyncMachine | None Default: None

A smol.Machine or smol.AsyncMachine on this machine that you already have. The backend opens its own handle to it by id. Whoever created it owns deleting it.

ref : WorkspaceRef | None Default: None

Identity of an existing VM on this machine to attach to on first use: its name.

image : str | None Default: None

OCI image a new VM runs, such as 'python:3.12-alpine'; None boots smolvm’s own Alpine Linux root filesystem without pulling anything, unless desktop is set.

cpus : int | None Default: None

vCPUs for a new VM; smolvm’s default when None.

memory_mb : int | None Default: None

Memory for a new VM in MiB; smolvm’s default when None.

allow_internet_access : bool Default: False

Whether a new VM gets unrestricted outbound network access, made from this machine’s network: the internet, but also its local network and services.

working_dir : str | None Default: '/workspace'

Absolute directory commands start in and relative paths resolve against, created if missing when the backend first reaches the VM; None uses the VM’s own, / on the default image.

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 VM has a display for ComputerUse: True for 1280x800, or its (width, height). The first start installs the programs it needs, which needs allow_internet_access. Without an image, a new VM runs debian:bookworm-slim.

Attributes

ref

Identity of the VM, or None before one starts booting.

Set before the boot finishes, so cleanup that runs while it is still booting can pass it to SmolSandbox.destroy, which waits for the boot.

Type: WorkspaceRef | None

display

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

Type: Display | None

Methods

get_sandbox

@async

def get_sandbox() -> smol.AsyncMachine

Return the SDK’s smol.AsyncMachine, for smol features the workspace API does not cover.

On a backend with no VM yet, this boots one or attaches to the one ref names, just like the first operation. Attaching to a deleted VM raises WorkspaceUnavailableError; it does not create a replacement.

Returns

smol.AsyncMachine

working_dir

@async

def working_dir() -> str

The canonical absolute directory commands start in.

Returns

str

run

@async

def run(
    command: WorkspaceCommand,
    *,
    shell: bool = False,
    env: Mapping[str, str] | None = None,
    timeout: float | None = None,
) -> CommandResult

Run a command in the VM, killing it and the processes it started on timeout or cancellation.

Returns

CommandResult