- Rust 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| agents | ||
| docs | ||
| src | ||
| tests | ||
| .gitignore | ||
| AGENTS.md | ||
| Cargo.lock | ||
| Cargo.toml | ||
| Changelog.md | ||
| README.md | ||
sandbox
Sandboxed process execution for AI-aided software development.
This crate builds an isolated sandbox around a git worktree. One of three back-ends provides the sandbox's SSH server: bubblewrap or rootless podman on the local machine, or an existing sshd on a remote host. Once that session is up, the same API drives everything, from program execution and PTY shells to port forwarding and filtered network egress.
A sandboxed agent cannot touch your real checkout, reach the network except through the proxy, or leave stray processes behind.
The crate ships as a library plus a standalone sandbox binary. Both read the
same TOML configuration, so you can reproduce a failing bondulance sandbox
with its exact config file.
Back-ends
| Back-end | Cargo feature | SSH server source | Workspace in the sandbox |
|---|---|---|---|
| bubblewrap | bubblewrap (default on Linux) |
socket-ssh inside fresh namespaces |
bind mount |
| podman | podman (opt-in) |
socket-ssh inside a --network=none rootless container |
volume bind |
| remote ssh | always compiled | connects an existing sshd | sshfs mount served by an in-process SFTP server |
The two local back-ends need a socket-ssh binary, staged and exec'd from
[ssh] server_binary (an explicit host path). The remote back-end ignores
that field (it connects to the remote host's own sshd) and needs sshfs
installed on the target host.
Quickstart
cargo build
cp src/config/example.toml my.toml # full annotated example config
./target/debug/sandbox --check my.toml
./target/debug/sandbox my.toml
The binary prints the port the sandbox's SSH server is reachable on:
ssh -p <port> $(whoami)@127.0.0.1
Proxy ask prompts appear on stdout and you answer them on stdin
(a/d/o/c; a/d are written back into the config file). Everything
else logs to stderr. Ctrl-C shuts the sandbox down cleanly, exit codes are
0 for a clean run, 1 for startup or teardown failure, and 2 for a usage
error.
Library interface
You load the same TOML config, hand it to SandboxBuilder, and get a
cloneable Sandbox handle plus an EventStream of lifecycle events.
build() validates the config as its first step, forks the worktree, starts
the back-end, opens the user-ssh bridge and the proxy, and emits Started.
use sandbox::{
ExecCallbacks, ExecSpec, OutputSink, SandboxBuilder, SandboxConfig, ShutdownMode,
};
let cfg = SandboxConfig::load("my.toml".as_ref())?;
let (sandbox, mut events) = SandboxBuilder::from_config(cfg).build().await?;
// Drain the event stream somewhere; lifecycle events block until consumed.
tokio::spawn(async move { while events.recv().await.is_some() {} });
let result = sandbox
.exec(
ExecSpec {
command_line: "make test".into(),
env: Default::default(),
cwd: None,
stdin: None,
},
ExecCallbacks {
stdout: Some(OutputSink::Lines(Box::new(|line| println!("{line}")))),
stderr: None,
},
)
.await?;
assert_eq!(result.exit_status, Some(0));
let report = sandbox.shutdown(ShutdownMode::Graceful).await?;
assert!(report.clean);
The handle
Sandbox offers these operations:
| Method | What it does |
|---|---|
exec(spec, callbacks) |
Run one command inside the sandbox and wait for it to finish. You hand over a command line, optional extra environment, working directory and stdin; you decide where stdout and stderr go, as log lines, raw chunks or discarded. Commands start in the workspace on local back-ends (the sshd default on the remote one); ExecSpec.cwd pins another directory. It returns how the program ended: an exit status or a fatal signal. |
shell(opts) |
Open an interactive PTY, the same kind of session you get from ssh. It arrives split by value into two owned halves: a PtyReader (the terminal output, AsyncRead) and a PtyWriter (keystrokes, resize, signal, close). They are independent — read in one task while another writes, no lock; closing the writer ends the reader with EOF. |
add_forward(spec) |
Open a port across the sandbox boundary at runtime. direct gives you a host port that reaches a service running inside the sandbox, reverse lets the sandbox connect back to a service on the host, and ssh_server exposes the sandbox's SSH server on an extra host port. Pass host_port = 0 for an ephemeral port; the address actually bound arrives as a ForwardActive event. |
remove_forward(id) |
Close a forward again and release its port before the call returns. |
ssh_port() |
The TCP port on 127.0.0.1 where the sandbox's SSH server answers, so you or your users can ssh -p <port> <user>@127.0.0.1 into it. |
proxy_port() |
The port the sandbox's egress proxy is reachable on. Inside the sandbox it is always 127.0.0.1:<port>; this tells you the number when you configured an ephemeral one, and returns None if the proxy is disabled or already torn down. |
forwards() |
List every currently open forward with its id and address, in the order they were opened. |
worktree() |
The host path of the git worktree the sandbox works in, or None when it runs against a plain fallback directory instead. |
worktree_report() |
Ask whether that directory has changes, for example to decide whether to merge the worktree back. The report carries a sample of up to 50 changed paths. |
persist_worktree() |
Mark the worktree to survive shutdown even if the run left it clean. Without this, a clean worktree is deleted at shutdown. |
asks() |
Get the handle for the network permission surface: allow_once and deny_once for one held connection (by the AskId from a PermissionRequested event), add_allow and add_deny to permanently add that ask's domain, and the entry-based list management — add_allow_entry / add_deny_entry, remove_allow_entry / remove_deny_entry, allow_list / deny_list — which changes the live lists by domain name, with no respawn. |
shutdown(mode) |
Tear the sandbox down and wait for it. Graceful lets the back-end shut its processes down in an orderly way, Force kills them. Returns the ShutdownReport: whether every teardown step succeeded, and the final state of the worktree. |
The handle is Clone and shareable across tasks. shutdown() is idempotent
and caches its report. Dropping the last clone without calling it runs a
best-effort teardown (detached async when a tokio runtime is current,
synchronous SIGKILL fallback otherwise); that path is logged and may report
less than shutdown(), so prefer the explicit call.
The builder
SandboxBuilder::from_config(cfg) and SandboxBuilder::load(path) start
from a SandboxConfig. Everything else is a chainable override applied on
top of the file: scratch_root, worktree_root, env_set, env_copy,
mount, authorized_key, tool, forward, workspace(host, sandbox), and
backend(impl Backend) for a custom back-end. Call config() to inspect the
effective config before build().
Events
EventStream::recv() yields SandboxEvent values:
| Event | Meaning |
|---|---|
Starting / Started { backend, ssh_port, worktree } |
bring-up progress; ssh_port is the usable bridge port |
ForwardActive { id, listen } / ForwardRemoved { id } |
a forward opened (with its effective address) or closed |
WorktreeLost { id } |
crash recovery: a registry entry whose owning process died; informational, nothing is deleted automatically |
Proxy(ProxyEvent) |
proxy asks (PermissionRequested { id, domain, waiting, peer }), connection reports, and list changes |
Stopped { report } |
teardown finished, with the ShutdownReport |
Answer an ask through the ProxyAsks handle you got from sandbox.asks().
add_allow/add_deny add the ask's domain to the live allow/deny lists and
release any ask waiting on that domain; the same handle manages the lists
independently of any ask by entry name (add_allow_entry,
remove_allow_entry, allow_list, …). The standalone binary wires these to
its stdout prompts and config write-back.
Worktree recovery
After a crash, list_lost reports registered worktrees whose owning process
is gone. cleanup_lost prunes the clean ones, reports (never deletes)
persisted ones, and cleanup_persisted deletes those on request. A clean,
non-persisted worktree is also pruned automatically at shutdown.
Documentation
User documentation is an mdbook in docs/src; build and open it:
mdbook build docs -d docs/book # then open docs/book/index.html
| Page | Covers |
|---|---|
| Architecture & index | component overview, the diagram, back-end comparison |
| Configuration | every config section, field tables, defaults, validation rules |
| Back-ends | per-back-end requirements and behavior, sshfs requirement for remote |
| Networking | proxy policies, proxy_env, forward kinds |
| Worktrees | fork lifecycle, registry, cleanup and recovery |
| Library | this overview in depth, with runnable-shaped examples |
| Binary | CLI usage, prompts, exit codes, scratch layout |
Development
cargo build
cargo test --workspace # integration tests skip without their tools
cargo clippy --workspace --all-targets
cargo fmt --check
mdbook build docs -d docs/book
See AGENTS.md for project conventions and agents/plan/ for the P001
implementation plans.