Kits¶
A sandbox is created from a kit: shell, the kit of a coding agent, or a
composition of a base kit and mixins. The daemon cannot resolve a kit by
itself: a kit package holds what the sbx CLI would send it for a kit,
and every sandbox of that kit is created from it through the socket alone.
fastsandbox forges packages without the CLI, the base kit rebuilt from its
published image; it compiles them with the CLI only when asked. This page
covers the cache that makes packages, compositions, mixins written in Python,
MCP servers given to the agent by a mixin, packages themselves, and kits added
to a running sandbox.
The kit cache¶
client.create(kit="shell") gets the package of the kit from the cache of the
client, client.kits, a
KitCache: by default the one of the process
(KitCache.default()), shared by its clients.
- A kit is forged on first use, without the
sbxCLI: the daemon pulls and exports the published image of the base kit,docker.io/sbx/shellforshell, and the forge rebuilds the kit from it. It takes a few seconds once the daemon holds the image. - The package is kept in memory for the process: nothing is written in the files of the host, while its images go to the image store of the daemon. A later process forges it again.
KitCache(directory), orFASTSANDBOX_KIT_CACHE, keeps the packages in a directory too, one directory per composition, for later processes.- A composition is its base kit, its arguments and its mixins, the text of the
spec.yamlof a mixin directory and the descriptor of a mixin written in Python included: a mixin changed is forged again. A package is used again while it suits the daemon (KitPackage.suits()): one forged by the version of thedocker-sandboxcrates this release binds, for the API the daemon speaks; one compiled bysbx, by the same version ofsbx. - A composition is made by one caller at a time, whatever their event loops.
docker-sandbox-kit keeps the packages: the cache only chooses where, and
whether they are forged or compiled
(compiles).
import fastsandbox
async def main() -> None:
client = await fastsandbox.connect()
# Forged without the `sbx` CLI on first use, then kept in memory.
package = await client.package("shell")
print(f"{', '.join(package.kit_refs)}, forged for the API {package.compiled_api}")
# The package creates sandboxes through the socket alone.
async with client.create(kit=package) as sandbox:
print(f"{sandbox.name}: agent {(await sandbox.inspect()).agent}")
if __name__ == "__main__":
fastsandbox.run(main())
client.package(kit) gives the package of a
kit, made now unless kept; given a package, it returns it as it is.
KitCache.package(client, kit) does the same
with a cache of one's choice, and
refresh(client, kit) makes the package again
in place of the one kept: for a base kit of a registry or a Git repository
that moved since, which the cache does not see by itself.
import sys
from pathlib import Path
import fastsandbox
from fastsandbox import KitCache, SandboxSpec
async def main(directory: Path) -> None:
client = await fastsandbox.connect()
# Kept in a directory, one per composition, for the processes that follow.
cache = KitCache(directory / "kits")
package = await cache.package(client, "shell")
print(f"kept: {package.dir is not None}, suits the daemon: {package.suits(client)}")
# Made again in place of the one kept, for a base kit that moved in its registry.
await cache.refresh(client, "shell")
# A package held in memory: a spec that names no base kit is launched on it, and saving it
# keeps it for the processes that follow.
forged = await KitCache().package(client, "shell")
async with SandboxSpec().launch_package(client, package=forged) as lease:
print(f"{lease.sandbox.name}: {', '.join(lease.report.kits)}")
forged.save(directory / "shell")
if __name__ == "__main__":
fastsandbox.run(main(Path(sys.argv[1])))
A package held in memory has no directory. A
sandbox spec that names no base kit,
SandboxSpec(), is launched on it with
launch_package, and a FastSandbox
task takes it as its kit; save(dir) writes it
into a directory, for a later process.
Compiling with the CLI¶
The forge rebuilds published kits and reads mixins from their directories. A
base kit only the CLI builds, a directory or a Git repository, raises
KitForgeError; a mixin only the CLI
resolves, an image, a ZIP file or a Git repository, raises
InvalidKitError. A cache given the
sbx program compiles kits with it instead:
from fastsandbox import KitCache
package = await KitCache(sbx="sbx").package(client, "./kits/my-local-kit")
sandbox = await client.create(kit=package)
A FastSandbox application takes such a cache as FastSandbox(kits=KitCache(sbx="sbx")).
The CLI runs sbx create once, on a throw-away sandbox, behind a proxy that
captures what it sends. It can take a few minutes for an agent kit; the kit
images it pulls stay on the daemon, as the cache of the next sandboxes. Such a
cache keeps its packages in ~/.cache/fastsandbox/kits, or under
$XDG_CACHE_HOME, unless given a directory, apart from the packages forged
there, and compiles a package again when the daemon runs another sbx
version, or when a mixin changed. To compile ahead of time, from a shell or a
deployment script:
fastsandbox kits compile claude
fastsandbox kits compile claude --mixin ./kits/my-mixin --arg model=claude-haiku-5-5
A package compiled once takes mixins forged without the CLI all the same:
KitForge.forge_over(package, mixins)
keeps every kit of the package, its base kit and its own mixins with their
images, and composes mixins after them, given as text or written in Python.
A sandbox spec of a compiled package composes its own mixins,
network rules and MCP servers that way, and so does a task whose kit only the
CLI resolves.
from fastsandbox import Kit, KitCache, KitForge
# A mixin given by image: only the CLI resolves it, once.
acme = Kit(base="shell", mixins=("docker.io/acme/tools:1",))
compiled = await KitCache(sbx="sbx").package(client, acme)
package = await KitForge(client).forge_over(compiled, ["./kits/my-mixin"])
forge_over_base(package, mixins)
takes the base kit of the package alone, its first kit, without pulling its
image again, and leaves its other kits out: a package saved or compiled once is
composed again with other mixins.
Compositions¶
A Kit composes a base kit with mixins, in order, and
kit args, as sbx create --kit-arg takes them. Its kits are named as
sbx create names them, and docker-sandbox-kit reads them as the CLI does,
by rules its audit measured on the CLI:
| Text | As the base kit | As a mixin |
|---|---|---|
a name without a slash: claude, tools |
an agent sbx knows, whatever the working directory holds; any other name is refused |
a directory of the working directory; refused when there is none |
a path written as one: ./kit, ../kit, /srv/kit, ~/kit |
a directory, which only the CLI builds | a directory, whose spec.yaml the forge reads; refused when it is not one |
a name with a slash: ghcr.io/acme/kit:1, or oci://… |
a published image, which the forge rebuilds | an image, which only the CLI resolves, unless a name without oci:// is a path that exists in the working directory, kits/tools for instance, which it then names |
git+https://…, git+ssh://… |
a Git repository, which only the CLI builds | a Git repository, which only the CLI resolves |
A mixin may also be written in Python. The forge
reads a spec.yaml written in the JSON subset of YAML.
KitRef.base(text) and
KitRef.mixin(text) read a text by those rules,
without forging anything: a KitRef holds its kind,
agent, image, local or git, and its value, the agent, the image, the
path (~ expanded) or the repository. A text the CLI would refuse raises
InvalidKitError. A KitRef is
taken where a kit is (Kit.of, KitForge.forge) and where a mixin is
(Mixin.from_ref).
from fastsandbox import KitRef
KitRef.base("claude") # KitRef(kind='agent', value='claude')
KitRef.base("./my-kit").kind # 'local', which only the CLI builds
KitRef.mixin("tools").kind # 'local' when ./tools exists
from fastsandbox import Kit
kit = Kit(base="claude", mixins=("./kits/my-mixin",), args={"model": "claude-haiku-5-5"})
sandbox = await client.create(kit=kit)
The forge gives the arguments to the base kit, and checks them as the CLI
does: an argument the kit does not declare, or a value it refuses, raises
InvalidKitError before anything
is created, as does a mixin it cannot take, or a kit not named as the CLI
names one. As the CLI, an argument may name its kit, claude.model=… for the
base kit claude; a mixin declares none. A mixin directory whose spec.yaml
cannot be read raises HostFileError.
KitForge forges without the cache, in memory or into
a directory of one's choice, over a compiled package with
forge_over, and check(kit)
checks a kit before anything is pulled: its base kit, the arguments that name
it, and the kit policy of the daemon;
KitCompiler compiles with the CLI, and raises
KitCompileError when the CLI
cannot.
Mixins written in Python¶
A mixin need not be a directory. A KitDescriptor
holds what it declares, the v3 descriptor of its spec.yaml, built in Python;
a Mixin lists it under a reference, and Kit.mixins
takes it as it takes a directory:
import fastsandbox
from fastsandbox import Kit, KitDescriptor, LifecycleStep, Mixin
configure = LifecycleStep(
command="mkdir -p ~/.acme && echo 'endpoint: https://api.acme.example' > ~/.acme/config.yaml"
).as_user("agent")
descriptor = (
KitDescriptor.mixin("Acme tools")
.with_description("The configuration of the Acme API, and its host")
.with_install(configure)
.with_network_allow("api.acme.example:443")
)
# Checked by the rules of the forge as it is made.
acme = Mixin(reference="/kits/acme-tools", descriptor=descriptor)
KIT = Kit(base="shell", mixins=(acme,))
async def main() -> None:
client = await fastsandbox.connect()
package = await client.package(KIT) # forged without the `sbx` CLI
print(f"{KIT.label}: {', '.join(package.kit_refs[1:])}")
async with client.create(kit=package) as sandbox, sandbox.running():
# The install command of the mixin ran when the sandbox was created.
config = await sandbox.exec("cat ~/.acme/config.yaml", user="agent", check=True)
print(f"{sandbox.name}: {config.stdout.strip()}")
if __name__ == "__main__":
fastsandbox.run(main())
- A
LifecycleStepis a command, a shell command or a program and its arguments: run once, when the sandbox is created (with_install), or at each of its starts (with_startup, in the background within_background()), as a user of the sandbox (as_user). An install command runs in an emptied environment, which keeps onlyPATH,HOME,USER,TERMand the proxy and certificate variables:with_env(*names)gives it variables of the sandbox,with_gateway_env()those that name its MCP gateway. with_network_allow(*hosts)andwith_network_deny(*hosts)add rules while the sandbox runs, each host in a form the CLI takes (host,*.domain,host:port, a CIDR prefix); a deny wins over any allow.- The models hold the format field for field, under the names it gives its
fields:
model_dump_json()is the descriptor as any program reads it, andto_spec()the text of itsspec.yaml, which the CLI reads too.KitDescriptor.parse(),read()andfrom_json()read a descriptor,Mixin.read(dir)the mixin of a directory, andMixin.from_ref(text)the mixin a text names, assbx create --kitreads it: a directory, refused otherwise.Mixin.to_json()is the form the crate reads, its reference and its descriptor, as a sandbox spec holds it. - A mixin is checked when it is made, by the rules of the forge, which
docker-sandbox-kitholds: a host the CLI refuses, a URL or a path in place of a host, a command without a word, an install command in the background, a field the format does not have, or a kit argument raiseInvalidKitErrorwhere the mixin is written, not when a sandbox is created from it. - The reference is a path, as the CLI lists a local kit, whose last part names
the mixin: the kit list of the sandbox shows it. The daemon finds the mixin
by its image, so the path need not exist. The compiler writes the mixin into
a directory of its own named after it, for the CLI, which lists the mixin
under that directory;
Mixin.save(dir)writes it into a directory of one's choice, as the CLI reads a local kit.
MCP servers for the agent¶
Mixin.mcp(agent, *servers) is a mixin the crate
builds, /kits/docker-sandbox-mcp-<agent>: its install commands register
McpServers in the configuration of the agent when
the sandbox is created, as the user agent (claude mcp add for Claude Code,
and the same for Copilot and OpenCode), and it allows the hosts of those
reached at a URL. Nothing is registered with the daemon or written on the
host. A server is one of three kinds:
| Server | Reached by the agent | Token |
|---|---|---|
McpServer.host(name, port) |
a process of the host, on port of its loopback, at http://host.docker.internal:<port>/mcp |
in DOCKER_SANDBOX_MCP_<NAME>_TOKEN, which the creation sets |
McpServer.remote(name, url) |
at url, over the network |
none, or the variable of with_bearer_env(env) |
McpServer.stdio(name, program) |
a program it starts in the sandbox, its arguments given by with_args(*args) |
none: it inherits the variables of the sandbox |
The tokens are not part of the mixin, so that one package serves sandboxes of
tokens of their own: server.env(token) gives the
variables of the creation request that hold one.
import secrets
import fastsandbox
from fastsandbox import Kit, McpServer, Mixin
# A server a process of the host serves on a port of its loopback.
tools = McpServer.host("project-tools", 47813)
# Registered in Claude Code when the sandbox is created, its host allowed.
KIT = Kit(base="claude", mixins=(Mixin.mcp("claude", tools),))
async def main() -> None:
client = await fastsandbox.connect()
# The token is the sandbox's own: the server checks it in each request.
token = secrets.token_urlsafe(32)
async with client.create(kit=KIT, env=tools.env(token)) as sandbox:
print(f"{sandbox.name}: {tools.name} at {tools.url}, its token in {tools.token_env}")
if __name__ == "__main__":
fastsandbox.run(main())
An agent other than claude, copilot or opencode, two servers of the same
name, a stdio server given a token or a server reached at a URL given
arguments raise InvalidKitError
where the mixin is made. to_json() and
McpServer.from_json() are the JSON form of
a server, as a sandbox spec holds it. See
Connect MCP tools for what the server
of the host is to accept.
Packages¶
A KitPackage is held in memory, or is a directory;
KitPackage.open(dir) opens one, and raises
KitPackageError when the directory
holds none. It records:
kit_refs, the kit references, base kit first, andkit_artifacts, what the daemon receives for them;dir, its directory,Nonefor a package held in memory;compiled_with, thesbxversion that compiled it,Nonefor a forged package, andcompiled_api, the daemon API it was written for, whichsuits(client)compares with the daemon;images, the image archives of the kits, whichload_images(client)loads into the daemon, each aPackageImagewith itsreference, itspath,Nonefor an archive held in memory, and itssize;image_archive(index)gives the bytes of one;agent, theKitAgentthe base kit describes, if any: its program, its run options, the command line that runs it (command(*args)) and the hosts it needs (hosts()).
request(name) gives the creation request
of a sandbox of the kit, which create_with(client, request)
creates once adjusted, loading the images first; client.create() does both.
save(dir) writes a package, one held in
memory included, into a directory.
A package is a creation request and the images it needs, and a forger of one's
own assembles it from them:
KitPackage.in_memory(template, images)
takes the request of every sandbox, whose name {{name}} stands for the name
of each one (CreateRequest.for_agent,
its kits and their artifacts), and images that hold their archives,
PackageImage.in_memory(reference, archive),
loaded under their reference when the daemon does not hold them yet.
from fastsandbox import KitPackage
from fastsandbox.models import PackageImage
images = [
PackageImage.in_memory(image.reference, package.image_archive(index))
for index, image in enumerate(package.images)
]
same = KitPackage.in_memory(package.request("{{name}}"), images)
Kits added to a running sandbox¶
A package of a composition adds its mixins to a sandbox created from the base kit alone, in one of two ways:
| Call | How | The kit list of the sandbox |
|---|---|---|
install_into(sandbox) |
runs the install of the kits in the running container: fast | stays as it was, so a container created again would lose the kits |
add_to(sandbox) |
commits the container to an image, then creates it again with the longer kit list: the work in progress is kept, the sandbox keeps its identity | holds the new kits |
After a swap, the new container needs a session of its own: open a new
async with sandbox.running(): block. A program that composes kits itself
uses the parts of the package with
Sandbox.add_kit_artifact() and
Sandbox.swap_container().
In tests¶
The fake daemon serves the published kits shell and claude, so that kits
are forged against it as against the daemon;
fastsandbox.testing.fake_package()
writes a package of one's own (see Testing).