Sandboxes¶
A sandbox is a virtual machine the daemon creates from a kit: the shell kit,
or the kit of a coding agent. This page covers its life: the creation, the
sessions that keep it running, looking it up, stopping and deleting it, and
saving it as a template.
Creating a sandbox¶
client.create() creates a sandbox from a kit,
shell by default, forged without the sbx CLI on first use (see
Kits). It returns a
Creation, used in one of two ways:
- awaited, it gives the
Sandbox, which stays until it is deleted; - as an async context manager, it gives the sandbox and deletes it on the way out, also on an error or a cancellation: stopped if it runs, then deleted.
The error of the block is never masked by its cleanup. When the block raised,
an error, a timeout or Ctrl-C, and the deletion fails too, the error of the
block goes on as it is, its type kept for the handlers around the block: the
failed deletion is noted on it (__notes__, shown in its traceback) and logged
as a warning on the fastsandbox logger, with the name and the identifier of
the sandbox that may stay. When the block ended well, a failed deletion
raises. A sandbox already gone is no failure. The block deletes its sandbox by
its identifier: a sandbox that another program created since under the same
name stays, which is logged as a warning and noted on the error of the block,
if any.
Either way, a creation cancelled while the daemon creates the sandbox, by a
timeout or Ctrl-C, leaves none behind that the program never got:
docker-sandbox reads the creation to its end, in a task of its own, then
deletes the sandbox it made, by its identifier; the interpreter waits for it as it exits, for 10 s at most or until a second Ctrl-C.
A killed process, or a task the exit cuts short, which the fastsandbox
logger warns of, can leave the sandbox, or the network rules of its kit. A
sandbox of that name that the daemon refused to
replace belongs to another, and stays as it is. The same holds for
client.sandboxes.create_stream() left
before its result.
import fastsandbox
async def main() -> None:
client = await fastsandbox.connect()
# Awaited, the creation gives a sandbox that stays until it is deleted.
creation = client.create("docs-kept", kit="shell", env={"MODE": "docs"}, cpus=2)
kept = await creation
assert creation.created is not None
print(f"{kept.name} created: {creation.created.status}")
# As a context manager, it deletes the sandbox on the way out.
async with client.create("docs-scratch", kit="shell") as scratch:
names = [info.name for info in await client.sandboxes.list()]
print(f"sandboxes: {', '.join(names)}")
print(f"{scratch.name} after the block: {await client.sandboxes.find(scratch.name)}")
# The identifier returned at creation guards the deletion.
await kept.delete(force=True, expected_id=creation.created.id)
if __name__ == "__main__":
fastsandbox.run(main())
Once created, Creation.created holds what the daemon
answered, a Created: the identifier of the
sandbox, its agent, its state, its MCP gateway, and withheld, the
credentials its kits declare that the daemon does not authorize (see
Withheld credentials). A sandbox runs
right after its creation. A sandbox spec goes further in one
call: the creation, the session, the network rules from the creation, the
API keys and the MCP servers of the agent, and the removal.
The arguments adjust the creation request of the kit:
| Argument | What it sets |
|---|---|
name |
The sandbox name; a unique one by default (unique_name(), fastsandbox- and a random suffix). |
kit |
The kit: a name ("shell", "claude"…), a Kit or a KitPackage; None to create from request alone. |
request |
A full CreateRequest; the other arguments adjust it. |
workspace |
A host directory mounted as workspace, at its own path in the sandbox. |
clone |
The sandbox works on a private Git clone of workspace, the repository of the host mounted read-only. |
workspaces |
Further host directories or files to mount, as Workspace (dir, read_only, target). |
env |
Environment variables of the sandbox. |
ports |
Ports published from the start (see Ports). |
cpus, memory |
Virtual CPUs and a memory limit in sbx notation, e.g. "4g". |
template |
An image to start from, such as one saved with Sandbox.save(). |
pull_policy |
When kit images are pulled: PullPolicy ALWAYS, MISSING or NEVER. |
A name already in use raises
ConflictError; a request the daemon
refuses, an unknown governance profile for instance,
InvalidInputError, before
anything is created. A failure the daemon reports while it creates the
sandbox, an error line of its answer such as image is not cached locally
for an image missing under PullPolicy.NEVER, raises
OperationFailedError.
Sessions¶
The daemon stops a sandbox about 30 seconds after its last session closes. A
session is an open request on the sandbox, which the sbx CLI holds for the
duration of each of its commands: a program that works in a sandbox holds one
too.
import fastsandbox
async def main() -> None:
client = await fastsandbox.connect()
async with client.create("docs-sessions", kit="shell") as sandbox:
info = await sandbox.stop()
print(f"stopped: {info.status}")
# Starts the sandbox if needed and keeps it running in the block.
async with sandbox.running():
info = await sandbox.inspect()
print(f"in the block: {info.status}")
# The same by hand: a session held, then released.
session = await sandbox.ensure_running()
try:
print(f"session held on {session.sandbox}: {session.is_connected}")
finally:
session.release()
if __name__ == "__main__":
fastsandbox.run(main())
sandbox.running()starts the sandbox if needed and keeps it running for the duration of the block. It is the way to work in a sandbox:async with client.create(...) as sandbox, sandbox.running():.ensure_running()does the same outside a block: it opens a session, pushes an empty credentials update and starts the sandbox, as the CLI does, and returns theSession. Release it withrelease(), or use it as an async context manager.hold_session()opens a session without starting the sandbox: it keeps a running sandbox running.
A session closed by the daemon is opened again on its own, until it is
released or the sandbox no longer exists;
Session.is_connected says whether it is
open right now. A command sent to a stopped sandbox raises
ConflictError.
Note
A sandbox created and left without a session keeps running for about 30 seconds, then stops. It stays on the daemon, stopped, until it is deleted: a creation that is awaited is the program's to delete.
Looking sandboxes up¶
| Call | Gives |
|---|---|
client.sandboxes.list() |
every sandbox, as SandboxInfo |
client.sandboxes.get(name) |
one sandbox, or NotFoundError |
client.sandboxes.find(name) |
one sandbox, or None |
client.sandbox(name) |
the handle of a sandbox, by name; nothing is checked until it is used |
sandbox.inspect() |
the current state of the sandbox |
sandbox.exists() |
whether it exists |
SandboxInfo carries the identifier, the
agent of the kit, the status (running, stopped, or another state the
daemon reports) and is_running,
the workspace and mounts, the CPUs and memory set at creation, the published
ports (in single-sandbox answers only) and the service credentials configured.
Starting, stopping, deleting¶
start()starts the sandbox; starting a running sandbox does nothing. Without a session, it stops again about 30 seconds later.stop()stops it at once, sessions or not.wait_running()polls until the sandbox runs, everyintervalseconds for at mosttimeout(0.5 s and 60 s by default), then raisesSandboxTimeoutError.delete()deletes it;force=Truestops it first when it runs.force_delete()isdelete(force=True).
A name is free again once its sandbox is deleted. expected_id, the
identifier returned at creation, guards a deletion against a sandbox that
someone else recreated under the same name: the daemon refuses it with a
ConflictError.
Following a creation¶
client.sandboxes.create_stream()
creates a sandbox from a CreateRequest
and streams what the daemon does. Each item is a
CreateEvent: progress lines
(CreateProgress), then the result
(CreateResult) or the failure
(CreateFailure); a line the library does
not know is a CreateUnknown, which keeps
it as raw. A failure is an item of the stream, not an exception: the daemon
answers it with HTTP 200. A program
that relays the stream of the daemon itself reads its lines with
parse_create_event(line), as the
collection does: None for a blank line,
ProtocolError for a line that is not
JSON.
import fastsandbox
from fastsandbox.models import CreateFailure, CreateProgress, CreateResult
async def main() -> None:
client = await fastsandbox.connect()
package = await client.package("shell")
# A request from the kit package, adjusted; its images loaded first.
request = package.request("docs-stream").with_env(MODE="docs")
await package.load_images(client)
async with await client.sandboxes.create_stream(request) as events:
async for event in events:
match event:
case CreateProgress(message=message):
print(f"progress: {message.strip()}")
case CreateResult(created=created):
print(f"created {created.name}: {created.status}")
case CreateFailure(message=message):
raise RuntimeError(f"creation failed: {message}")
await client.sandbox("docs-stream").force_delete()
if __name__ == "__main__":
fastsandbox.run(main())
The request comes from the kit package,
KitPackage.request(name), adjusted with the
with_* methods of the request or model_copy(update=...); a request
assembled from its parts starts from
CreateRequest.for_agent(name, agent),
which names no kit yet. Unlike
client.create(), the collection creates from images already on the daemon:
load those of the package first, with
load_images().
client.sandboxes.create() takes the same
request and waits for the result instead.
A creation request is plain data: an application can store it as JSON, with
model_dump_json(), and replay it under another name with
CreateRequest.model_validate_json() and client.create(request=...).
Templates¶
sandbox.save(tag) saves a sandbox as an image,
the template of new sandboxes; stop it first, so that its file system is at
rest. A new sandbox starts from it with template; the image is on this
daemon only, so it is not pulled:
from fastsandbox.models import PullPolicy
await sandbox.stop()
saved = await sandbox.save("my-snapshot:v1")
copy = await client.create(kit="shell", template="my-snapshot:v1", pull_policy=PullPolicy.NEVER)
SavedImage holds the identifier of the image
and its fully qualified tag. An image moves to another daemon as a file:
client.images.export() then
load_file() there (see Images).
Working directory, host paths, metrics¶
set_working_dir(dir)sets the working directory of new sessions;SandboxInfo.working_dirrecords it.allow_host_path(path)grants a running sandbox access to an existing path of the host, by its real path, andrevoke_host_path(path)takes it back. A grant is listed with theruntime_mountsof the sandbox; it is not a mount. To mount directories, useworkspaceandworkspacesat creation.vm_metrics()gives the metrics of the virtual machine, in the Prometheus text format.