sandboxd API¶
The sandbox service and the read-only archive of what its sessions left behind.
See sandboxd for the concepts and the security model; the
client is SandboxdWorkspace.
WorkspaceArchive¶
Read-only view of the files sessions left behind, with no sandbox running. Needs
the remote extra.
pydantic_ai_backends.remote.archive.WorkspaceArchive
¶
Read-only view of the files sessions left behind.
Reads the service's host volume directly, so a session reaped long ago is still browsable and listing a conversation's files costs no container start.
This raises rather than degrading. Nothing here is in an agent's tool path — the caller is an application answering a user who asked to see some files, and it needs to tell "there are none" apart from "the service is misconfigured".
Requires the service to be running with SandboxdConfig.workspace_root set,
and the service token: a reaped session has no token of its own left, and the
intended caller is a backend applying its own authorization first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service_url
|
str
|
Base URL of the service. Ignored when |
'http://localhost:8080'
|
token
|
str
|
Service token. |
''
|
timeout
|
float
|
Request timeout in seconds. |
DEFAULT_TIMEOUT_SECONDS
|
client
|
Client | None
|
Pre-built |
None
|
Example
from pydantic_ai_backends.remote import WorkspaceArchive
archive = WorkspaceArchive("http://sandboxd:8080", token="...")
for entry in archive.ls(session_id):
print(entry["path"], entry["size"])
print(archive.read(session_id, "report.md"))
Path("chart.png").write_bytes(archive.read_bytes(session_id, "chart.png"))
Source code in src/pydantic_ai_backends/remote/archive.py
| Python | |
|---|---|
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
__init__(service_url='http://localhost:8080', *, token='', timeout=DEFAULT_TIMEOUT_SECONDS, client=None)
¶
Source code in src/pydantic_ai_backends/remote/archive.py
ls(session_id, path='.')
¶
List one directory of a stored workspace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Session whose files are wanted. |
required |
path
|
str
|
Directory to list. An absolute in-container path works, so a path taken from a live session's listing can be handed straight back. |
'.'
|
Raises:
| Type | Description |
|---|---|
WorkspaceArchiveError
|
If the workspace or directory is absent, the path escapes the workspace, or the service cannot be reached. |
Source code in src/pydantic_ai_backends/remote/archive.py
tree(session_id, path='.', *, max_depth=6, max_entries=2000)
¶
List a directory of a stored workspace and the directories under it.
One request where walking with :meth:ls takes one per directory. Needs
a service from 0.2.35; an older one answers 404.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Session whose files are wanted. |
required |
path
|
str
|
Directory to start from, as for :meth: |
'.'
|
max_depth
|
int
|
Levels to list; 1 is |
6
|
max_entries
|
int
|
Most entries to return. |
2000
|
Raises:
| Type | Description |
|---|---|
WorkspaceArchiveError
|
If the workspace or directory is absent, the path escapes the workspace, or the service cannot be reached. |
Source code in src/pydantic_ai_backends/remote/archive.py
read(session_id, path, offset=0, limit=2000)
¶
Read a slice of a stored workspace file.
Decoded exactly as a live session would decode it, so the archive and the sandbox never disagree about what a file says.
Raises:
| Type | Description |
|---|---|
WorkspaceArchiveError
|
If the file is absent, too large, not readable as text, outside the workspace, or the service is unreachable. |
Source code in src/pydantic_ai_backends/remote/archive.py
read_bytes(session_id, path)
¶
Read a whole stored workspace file as bytes.
The sibling of :meth:read, and the one to use for anything an agent
produced that is not text - a chart, a rendered PDF, an image it fetched.
Those are the commonest contents of a real workspace, and read decodes
them: the result re-encodes to a corrupt file that nonetheless downloads
successfully, which is worse than an error, so a caller serving downloads
had to refuse them instead.
Whole rather than sliced, because a byte range means nothing for the
formats this exists for. ls carries size, so a caller that wants to
bound a read can look first.
Raises:
| Type | Description |
|---|---|
WorkspaceArchiveError
|
If the file is absent, over the service's read ceiling, outside the workspace, or the service is unreachable. |
Source code in src/pydantic_ai_backends/remote/archive.py
close()
¶
pydantic_ai_backends.remote.archive.WorkspaceTree
dataclass
¶
A directory and what is under it, from :meth:WorkspaceArchive.tree.
Source code in src/pydantic_ai_backends/remote/archive.py
pydantic_ai_backends.remote.archive.WorkspaceArchiveError
¶
Bases: Exception
Raised when a stored workspace cannot be listed or read.
Attributes:
| Name | Type | Description |
|---|---|---|
status_code |
What the service answered, or |
Source code in src/pydantic_ai_backends/remote/archive.py
SandboxdConfig¶
Everything the service decides on a client's behalf. Needs the server extra.
pydantic_ai_backends.remote.server.SandboxdConfig
dataclass
¶
Everything the service decides on a client's behalf.
Attributes:
| Name | Type | Description |
|---|---|---|
token |
str
|
Service token. Required to open, list or inspect any session. |
runtimes |
Mapping[str, str | SandboxRuntime]
|
Allowlist mapping a client-visible alias to what may run
under it — a bare image string, or a :class: |
default_runtime |
str
|
Alias used when a request names none. Empty — the
default — takes the first entry in |
max_sessions |
int | None
|
Ceiling on resident sandboxes across the service, or
|
max_open_sessions |
int | None
|
Ceiling on sessions that exist, resident or
hibernated, or |
evict_idle_after |
int | None
|
Seconds of inactivity after which a session at the
ceiling may be hibernated to make room for a new one, instead of the
new one being refused with |
max_sessions_per_tenant |
int | None
|
Ceiling on simultaneous sessions carrying one
|
mem_limit |
str | None
|
Default memory ceiling per sandbox, in Docker syntax. A runtime naming its own overrides this, upwards or downwards. |
memswap_limit |
str | None
|
Default ceiling on memory and swap combined. Raise it only where swap is |
cpus |
float | None
|
Default hard CPU ceiling per sandbox, in cores. |
cpu_shares |
int | None
|
Default relative CPU weight, applied only under contention.
Preferable to a hard |
tmpfs_size |
str | None
|
Size of an in-memory Sized against |
pids_limit |
int | None
|
Default process ceiling per sandbox. |
network_mode |
str | None
|
Default Docker network mode. |
oci_runtime |
str | None
|
Default low-level runtime for every sandbox, overridable per
runtime. |
work_dir |
str
|
Working directory inside every sandbox. Applied to built
runtimes as well, overriding whatever their |
workspace_root |
str | None
|
Host directory backing each sandbox's work directory, as
|
prewarm |
bool
|
Pull and build the whole allowlist in the background at startup. Without it the first session on a built runtime pays for the image build — a measured ten seconds and upwards — and pays it in the middle of somebody's request. Only applies to the default Docker builder, since nothing else knows how to warm a custom one. |
persist_containers |
bool
|
Give each sandbox a stable container name, so a
reaped session keeps its filesystem and the next attach restarts the
same container. |
idle_timeout |
int
|
Seconds of inactivity before a session is reaped. |
cleanup_interval |
int
|
Seconds between reaping passes. |
workspace_ttl |
int | None
|
Seconds an unused workspace directory is kept before it is
swept, timed from when its session was last opened. |
container_ttl |
int | None
|
Seconds a stopped persisted container is kept before it
is removed, timed from when it stopped. This reclaims what a session
installed inside its container — the build, the wheels, the
|
sandbox_uid |
int | None
|
Run every built runtime's sandbox as this unprivileged
user instead of root, and give each session's workspace to it.
Worth turning on. A container escape starts from whoever the
container runs as, and every file an agent writes into its
bind-mounted workspace is owned by that user on the host — as root,
a Two things it asks of the deployment. The service must be able to
|
max_read_bytes |
int
|
Largest single file a client may read out of a sandbox. |
execute_timeout |
int
|
Hard ceiling applied to every command, so one client cannot occupy a worker indefinitely. |
max_workers |
int
|
Threads dedicated to blocking sandbox calls. Sandbox commands are long, so this pool is kept separate from asyncio's shared default one. |
max_running_commands |
int
|
Commands that may run at once across every
session. Each running command holds a thread for as long as it runs,
reading its output, and the thread pool behind them defaulted to 40:
the forty-first command - an |
native_files |
bool
|
Serve a session's file operations from its directory on
the host instead of a command in its container, where the service
keeps workspaces on disk. A read or a write is then a millisecond
rather than one or more |
ui_enabled |
bool
|
Serve the bundled dashboard at |
Source code in src/pydantic_ai_backends/remote/server.py
| Python | |
|---|---|
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 | |
resolve_runtime(alias)
¶
Resolve a client-supplied alias to an allowed runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alias
|
str | None
|
Runtime alias from the request, or |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, SandboxRuntime]
|
The |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the alias is not on the allowlist. |
Source code in src/pydantic_ai_backends/remote/server.py
limits_for(runtime)
¶
The ceilings one runtime actually runs under.
Its own values where it names them, the service defaults otherwise.
Source code in src/pydantic_ai_backends/remote/server.py
SandboxRuntime¶
One entry in the service's allowlist: what an alias runs, and under which ceilings.
pydantic_ai_backends.remote.server.SandboxRuntime
dataclass
¶
One entry in the service's runtime allowlist.
A client names the alias this is registered under and nothing else, so
everything here is the operator's decision. Give it either a ready-made
image, or a runtime whose packages are built into an image on first use.
The ceilings are per runtime, because they are not one number for a whole
service: a notebook-style data runtime needs several gigabytes where a plain
shell needs a few hundred megabytes, and forcing one value on both either
starves the first or over-commits the host for the second. A ceiling left
None takes the service-wide default from :class:SandboxdConfig, which is
a default rather than a maximum — a runtime may name more.
Attributes:
| Name | Type | Description |
|---|---|---|
image |
str | None
|
Ready-made image, started as-is. |
runtime |
RuntimeConfig | str | None
|
|
description |
str
|
What this environment is for, shown in the dashboard. |
mem_limit |
str | None
|
Memory ceiling in Docker syntax, e.g. |
memswap_limit |
str | None
|
Ceiling on memory and swap combined. |
cpus |
float | None
|
Hard CPU ceiling in cores. A sandbox never exceeds it — and so cannot use cores that are idle. |
cpu_shares |
int | None
|
Relative CPU weight, which applies only under contention. On a small host this is usually the better knob: one active sandbox may take the whole machine, and several are still divided fairly. |
pids_limit |
int | None
|
Process ceiling. |
network_mode |
str | None
|
Docker network mode. Naming anything but |
oci_runtime |
str | None
|
Low-level runtime the daemon starts this runtime's
containers with — |
Source code in src/pydantic_ai_backends/remote/server.py
| Python | |
|---|---|
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
builds
property
¶
Whether first use builds an image rather than pulling a ready one.
resolved_runtime()
¶
The RuntimeConfig this entry builds, looked up when named.
Source code in src/pydantic_ai_backends/remote/server.py
describes()
¶
Human-readable summary of what will run, for the policy view.
Source code in src/pydantic_ai_backends/remote/server.py
| Python | |
|---|---|
image_label()
¶
The image, or what it is built from when there is not one yet.
Source code in src/pydantic_ai_backends/remote/server.py
| Python | |
|---|---|
create_app¶
pydantic_ai_backends.remote.server.create_app(config, *, sandbox_builder=None)
¶
Build the sandbox service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SandboxdConfig
|
Service policy. See :class: |
required |
sandbox_builder
|
SandboxBuilder | None
|
Override for how a sandbox is constructed, receiving
|
None
|
Returns:
| Type | Description |
|---|---|
FastAPI
|
A configured |
Source code in src/pydantic_ai_backends/remote/server.py
Configuration from the environment¶
Every field of SandboxdConfig is SANDBOXD_ plus its name in upper case. The
shipped entrypoint — python -m pydantic_ai_backends.remote.server — is this
plus uvicorn, and it is importable so a service embedded in something larger can
parse the environment and then adjust what it produced.
pydantic_ai_backends.remote.env.config_from_env(env)
¶
The service configuration these variables describe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Mapping[str, str]
|
Usually |
required |
Returns:
| Type | Description |
|---|---|
SandboxdConfig
|
A validated |
SandboxdConfig
|
default, so an empty environment (bar the token) is the shipped policy. |
Raises:
| Type | Description |
|---|---|
SandboxdConfigError
|
If a variable is missing, unparseable, or describes a combination the service refuses. |
Source code in src/pydantic_ai_backends/remote/env.py
pydantic_ai_backends.remote.env.bind_from_env(env)
¶
The address to serve on: SANDBOXD_HOST and SANDBOXD_PORT.
Separate from the service policy because it is not part of it — the same configuration served on a different port is the same service.
Source code in src/pydantic_ai_backends/remote/env.py
pydantic_ai_backends.remote.env.SandboxdConfigError
¶
Bases: ValueError
The environment does not describe a service that could start.
A ValueError rather than SystemExit: turning a bad configuration into an
exit code is the entrypoint's decision, and a caller embedding the service
in its own application wants to catch this, not be terminated by it.
Source code in src/pydantic_ai_backends/remote/env.py
Wire protocol¶
The HTTP contract as Pydantic models — one source of truth for both sides.
Wire protocol between sandboxd and its clients.
These models are the single source of truth for the HTTP contract: sessions,
/run for a Pydantic AI workspace, the archive reads, the policy.
Binary payloads travel base64-encoded (content_b64) because JSON cannot carry
arbitrary bytes, and a workspace holds real files.
CreateSessionRequest
¶
Bases: BaseModel
Open a sandbox session.
Deliberately carries no container settings. Image, mounts, network mode and every resource ceiling come from the server's configuration, because a process holding the Docker socket can start a privileged container that mounts the host — a client that could name its own image or volumes would own the machine.
Source code in src/pydantic_ai_backends/remote/wire.py
runtime = None
class-attribute
instance-attribute
¶
Alias of a server-allowed runtime. None selects the server default.
tenant = Field(default=None, pattern=TENANT_PATTERN)
class-attribute
instance-attribute
¶
Who this session is opened on behalf of, for the per-tenant ceiling.
Declared by the client rather than derived from session_id, so the service
imposes no naming convention on ids. Only a caller holding the service token
can open a session at all, so this is a capacity label from a trusted
application — not an authorization claim, and it grants nothing.
reuse = False
class-attribute
instance-attribute
¶
Attach to the session under session_id when one is already open.
Off by default, so an id collision is reported rather than silently sharing
somebody else's sandbox. Turn it on for a session that spans several runs —
one conversation, say — where the second run has to reach the files the
first one wrote. The runtime of an attached session is whatever it was
opened with; a runtime that disagrees is rejected rather than ignored.
attach = False
class-attribute
instance-attribute
¶
Only attach, never create: refuse with 404 when session_id names neither
an open session nor a workspace this service still holds.
What a client continuing earlier work needs. reuse alone opens a fresh,
empty session when the old one is gone, so the caller would carry on in an
empty directory believing its files were there. Implies reuse.
RunRequest
¶
Bases: BaseModel
Run one program, under the contract a Pydantic AI workspace needs.
The streams come back apart, a dead sandbox is reported as one rather than as a command that failed, and a command whose caller gave up can be stopped.
Source code in src/pydantic_ai_backends/remote/wire.py
argv = Field(min_length=1)
class-attribute
instance-attribute
¶
The program and its arguments, passed through literally. A shell command
is ["/bin/sh", "-c", "..."], spelled out by the client.
env = Field(default_factory=dict)
class-attribute
instance-attribute
¶
Variables layered over the sandbox's own environment.
timeout_seconds = Field(default=None, gt=0)
class-attribute
instance-attribute
¶
Deadline for the command. Clamped to the service's execute_timeout, and
that ceiling applies when this is None.
run_id = Field(pattern=RUN_ID_PATTERN)
class-attribute
instance-attribute
¶
Chosen by the client, so it can stop the run from another request when it stops waiting for this one.
RunResponse
¶
Bases: BaseModel
How a /run command ended: finished, timed out, or over its output limit.
A non-zero exit_code is a result. timed_out and output_limited carry no
exit code and only the beginning of each stream, because the command was
stopped rather than allowed to finish.
Source code in src/pydantic_ai_backends/remote/wire.py
output_limit = None
class-attribute
instance-attribute
¶
The ceiling an output_limited command crossed, in bytes.
SessionCreated
¶
Bases: BaseModel
A freshly opened session and the token scoped to it.
Source code in src/pydantic_ai_backends/remote/wire.py
token
instance-attribute
¶
Grants access to this session only. The service token also works.
SessionInfo
¶
Bases: BaseModel
Observable state of one session.
Source code in src/pydantic_ai_backends/remote/wire.py
tenant = None
class-attribute
instance-attribute
¶
Whoever the session was opened for, when the client said.
state = 'running'
class-attribute
instance-attribute
¶
Whether the session holds a sandbox, or was stopped to free a slot and is
waiting for its next request to wake it. A hibernated session is never
alive; it still has its token, its event log and its files.
SessionList
¶
Bases: BaseModel
Every open session, for monitoring.
Source code in src/pydantic_ai_backends/remote/wire.py
limit = None
class-attribute
instance-attribute
¶
Configured max_sessions — the ceiling on resident sandboxes.
open_limit = None
class-attribute
instance-attribute
¶
Configured max_open_sessions, or None when uncapped.
tenant_limit = None
class-attribute
instance-attribute
¶
Configured max_sessions_per_tenant, or None when uncapped.
SessionUsage
¶
Bases: BaseModel
Point-in-time resource usage for one sandbox.
Source code in src/pydantic_ai_backends/remote/wire.py
SessionEvent
¶
Bases: BaseModel
One operation performed against a session.
Records what was asked for and how it went — never file contents or command output, which would turn an audit trail into a data leak and grow without bound.
Source code in src/pydantic_ai_backends/remote/wire.py
seq
instance-attribute
¶
Monotonic per-session sequence number, for incremental polling.
op
instance-attribute
¶
Operation name: run for a command, which is the one operation a session takes.
target
instance-attribute
¶
Command or path the operation addressed, truncated.
detail = ''
class-attribute
instance-attribute
¶
Short outcome summary, e.g. exit 0 or 14 entries.
SessionEvents
¶
Bases: BaseModel
A slice of a session's activity log.
Source code in src/pydantic_ai_backends/remote/wire.py
latest_seq = 0
class-attribute
instance-attribute
¶
Highest sequence number the service holds; pass it back as after.
ServiceHealth
¶
Bases: BaseModel
Liveness and capacity summary. Unauthenticated.
Source code in src/pydantic_ai_backends/remote/wire.py
ServicePolicy
¶
Bases: BaseModel
The ceilings and allowlist the service imposes on every sandbox.
Authenticated, because it describes the host's configuration — though it holds nothing a caller with the service token is not already subject to. Exists so an operator can see the limits actually in force rather than inferring them from a config file.
Source code in src/pydantic_ai_backends/remote/wire.py
runtimes = Field(default_factory=list)
class-attribute
instance-attribute
¶
Every allowed runtime, with the ceilings it actually runs under.
max_sessions = None
class-attribute
instance-attribute
¶
Ceiling on resident sandboxes.
max_open_sessions = None
class-attribute
instance-attribute
¶
Ceiling on sessions that exist, resident or hibernated.
evict_idle_after = None
class-attribute
instance-attribute
¶
Seconds after which an idle session may be hibernated to free a slot.
memswap_limit = None
class-attribute
instance-attribute
¶
Default memory-plus-swap ceiling, or None when swap is pinned to memory.
oci_runtime = None
class-attribute
instance-attribute
¶
Default low-level runtime, or None for whatever the daemon defaults to.
persist_containers = False
class-attribute
instance-attribute
¶
Whether a stopped sandbox keeps its filesystem for the next attach.
sandbox_uid = None
class-attribute
instance-attribute
¶
Uid built runtimes run as, or None when sandboxes run as root.
workspace_ttl = None
class-attribute
instance-attribute
¶
Seconds an unused workspace is kept before it is swept, or None.
container_ttl = None
class-attribute
instance-attribute
¶
Seconds a stopped container is kept before its build is reclaimed.
tmpfs_size = None
class-attribute
instance-attribute
¶
Size of the in-memory /tmp each sandbox gets, or None when it has none.
prewarm = False
class-attribute
instance-attribute
¶
Whether the allowlist is pulled and built at startup rather than on demand.
buildkit = False
class-attribute
instance-attribute
¶
Whether image builds use BuildKit, and so keep package caches between them.
native_files = False
class-attribute
instance-attribute
¶
Whether a session's file operations are served off the host, not by its sandbox.
Defaults off, so a client talking to a service older than this falls back to the shell path rather than calling routes that are not there.
native_writes = False
class-attribute
instance-attribute
¶
Whether writes are served that way too, and not only reads.
native_realpath = False
class-attribute
instance-attribute
¶
Whether realpath is answered off the host for a path with no link in it.
The console's path checks ask it before every read and write, so without it
each of those cost a docker exec of its own.
ServiceIndex
¶
Bases: BaseModel
What this service is and where to find its endpoints.
Served at / so that opening the base URL says something useful instead of
a bare 404. Unauthenticated, and deliberately free of any session detail.