Retrieved article excerpt
Open article · Retrieved 2026-11-17T21:22:25.232098+00:00
# exec-sandbox
[CI](https://github.com/dualeai/exec-sandbox/actions/workflows/test.yml)
[CodSpeed Badge](https://codspeed.io/dualeai/exec-sandbox?utm_source=badge)
[Coverage](https://codecov.io/gh/dualeai/exec-sandbox)
[PyPI](https://pypi.org/project/exec-sandbox/)
[Python](https://pypi.org/project/exec-sandbox/)
[License](https://opensource.org/licenses/Apache-2.0)
exec-sandbox runs untrusted Python, JavaScript or shell code in QEMU microVMs on your own Linux or macOS hosts, for example code that an AI agent wrote. It is a Python asyncio library with a command line (`sbx`). It needs no cloud account and no API key.
```
import asyncio
from exec_sandbox import Language, Scheduler, VmSpec
async def main() -> None:
async with Scheduler() as scheduler:
# Language.PYTHON, Language.JAVASCRIPT or Language.RAW
async with await scheduler.new(VmSpec(language=Language.PYTHON)) as session:
result = await session.exec("print('Hello from a secure VM!')")
print(result.stdout) # Hello from a secure VM!
print(result.exit_code) # 0
asyncio.run(main())
```
The other Python examples use `async with` and `await` at the top level: run them in an `async def` function, as `main()` above.
## Contents
- **Start:** [Features](https://github.com/dualeai/exec-sandbox#features) · [Install](https://github.com/dualeai/exec-sandbox#install) · [Quick start](https://github.com/dualeai/exec-sandbox#quick-start) · [Key terms](https://github.com/dualeai/exec-sandbox#key-terms)
- **Use:** [Sessions](https://github.com/dualeai/exec-sandbox#sessions) · [Files](https://github.com/dualeai/exec-sandbox#files) · [Packages](https://github.com/dualeai/exec-sandbox#packages) · [Network](https://github.com/dualeai/exec-sandbox#network) · [Saved instances](https://github.com/dualeai/exec-sandbox#saved-instances) · [Configuration](https://github.com/dualeai/exec-sandbox#configuration) · [Errors and recovery](https://github.com/dualeai/exec-sandbox#errors-and-recovery)
- **Operate:** [Performance](https://github.com/dualeai/exec-sandbox#performance) · [Caches and disk use](https://github.com/dualeai/exec-sandbox#caches-and-disk-use) · [VM images and offline use](https://github.com/dualeai/exec-sandbox#vm-images-and-offline-use) · [Linux host setup](https://github.com/dualeai/exec-sandbox#linux-host-setup) · [Instance store operations](https://github.com/dualeai/exec-sandbox#instance-store-operations)
- **Reference:** [CLI reference](https://github.com/dualeai/exec-sandbox#cli-reference) · [API reference](https://github.com/dualeai/exec-sandbox#api-reference) · [Limits](https://github.com/dualeai/exec-sandbox#limits) · [Guest environment](https://github.com/dualeai/exec-sandbox#guest-environment)
- **Internals:** [How it works](https://github.com/dualeai/exec-sandbox#how-it-works) · [Security](https://github.com/dualeai/exec-sandbox#security) · [Contributing](https://github.com/dualeai/exec-sandbox#contributing) · [License](https://github.com/dualeai/exec-sandbox#license)
## Features
- **Hardware isolation.** Each session runs in its own QEMU VM, not in a container, with KVM or HVF acceleration. Up to 8 layers of isolation ([Security](https://github.com/dualeai/exec-sandbox#security)).
- **Fast start.** Under 1 ms from the warm pool, about 50-60 ms from an L1 memory snapshot. L2 disk snapshots keep the installed packages, and L3 shares them in S3 with all hosts ([Performance](https://github.com/dualeai/exec-sandbox#performance)).
- **Self-hosted.** The first use downloads the VM images from GitHub Releases. For hosts with no internet access, use `sbx prefetch`.
- **Python API and CLI.** Run code once or in several steps, stream stdout and stderr, and read and write files.
- **Saved instances.** `save()` writes the RAM, the processes and `/home/user` of a VM, encrypted, to S3 or a local folder. `reuse()` continues it later on any worker of the same host kind.
- **Network control.** No network access by default. Per spec, an allow-list of domains, checked by DNS filtering and TLS SNI inspection.
- **Memory density.** zram in the guest. On Linux, KSM page merging and memory reclaim of idle warm-pool VMs.
## Install
- **Python:** 3.12, 3.13, 3.14 (including free-threaded).
- **OS:** Linux or macOS, x64 or arm64. On Windows, use WSL2 (on native Windows, `import exec_sandbox` raises `ConfigError` `PLATFORM_UNSUPPORTED`).
- **QEMU:** 11.0+ for L1 memory snapshots and saved instances; 8.0+ for the rest. ARM64 without KVM or HVF needs 9.0.4+.
- **Hardware acceleration:** KVM (Linux) or HVF (macOS), recommended (~5-8x faster).
- **x86 CPU with KVM or HVF:** x86-64-v3 (Intel Haswell, AMD Zen 1 or newer). On a CPU without it, the `Scheduler` start raises `ConfigError` `HOST_DEPENDENCY` with the missing features. TCG runs on any x86 CPU.
### Install the package
```
uv add exec-sandbox # Core library
uv add "exec-sandbox[cli]" # + the sbx command line and the local instance store
uv add "exec-sandbox[s3]" # + the L3 snapshot cache and the s3 instance store (and the local store)
```
With pip, use `pip install` with the same names. For `sbx` with the `s3` store, install `exec-sandbox[cli,s3]`.
### Install QEMU
```
brew install qemu # macOS
apt install qemu-system qemu-utils # Ubuntu/Debian
test -r /dev/kvm -a -w /dev/kvm && echo ok # Linux: ok means your user can use KVM
sysctl kern.hv_support # macOS: kern.hv_support: 1 means HVF is available
```
exec-sandbox uses `qemu-system-x86_64` or `qemu-system-aarch64` from `/usr/bin/`, else from `PATH` (`EXEC_SANDBOX_QEMU_BIN_X86` and `EXEC_SANDBOX_QEMU_BIN_ARM` set another file), and `qemu-img` and `qemu-storage-daemon` from `PATH`. A missing QEMU binary, or one whose version or machine types this user cannot read, raises `ConfigError` (`HOST_DEPENDENCY`) when the `Scheduler` starts; a missing `qemu-img` raises it at its first use. Check the version with `/usr/bin/qemu-system-x86_64 --version` (or `qemu-system-aarch64`): Ubuntu 24.04 ships 8.2.2. Saved instances and L1 snapshots need QEMU 11.0 or later: where the distribution ships an older one, build QEMU from its source release ([qemu.org/download](https://www.qemu.org/download/#source)) and set `EXEC_SANDBOX_QEMU_BIN_X86` or `EXEC_SANDBOX_QEMU_BIN_ARM` to the binary.
On Linux, give your user access to KVM with `sudo usermod -aG kvm $USER`, then log in again. Without this access, exec-sandbox logs a warning and uses TCG. To run QEMU as its own user, with cgroup limits and namespaces, see [Linux host setup](https://github.com/dualeai/exec-sandbox#linux-host-setup).
## Quick start
The first run downloads the VM images ([How images download](https://github.com/dualeai/exec-sandbox#how-images-download)). For Python, see the example at the top and [Sessions](https://github.com/dualeai/exec-sandbox#sessions). `sbx` comes with the `cli` extra; all its options are in the [CLI reference](https://github.com/dualeai/exec-sandbox#cli-reference).
```
sbx run 'print("Hello from sandbox")' # Python
sbx run -l javascript 'console.log("Hello from sandbox")' # JavaScript
sbx run script.py # A file: the extension gives the language
sbx run -p pandas==3.0.1 'import pandas; print(pandas.__version__)' # With packages
sbx run --network --allow-domain api.example.com fetch_data.py # Network, with an allow-list
sbx run --instance my-vm -c 'x = 41' # Keep the VM state (Saved instances)
sbx run --instance my-vm -c 'print(x + 1)' # 42
```
## Key terms
| Term | Meaning |
| --- | --- |
| Spec | A `VmSpec`: what a VM is made of ([VmSpec](https://github.com/dualeai/exec-sandbox#vmspec)) |
| REPL | The interpreter in the VM that runs your code |
| Session | One VM that runs your code: `new()` or `reuse()` gives it, `close()` ends the VM ([Sessions](https://github.com/dualeai/exec-sandbox#sessions)) |
| Saved instance | The state of a session that `save()` stored (RAM, processes, files in `/home/user`): `reuse()` continues it on any worker of its host kind ([Saved instances](https://github.com/dualeai/exec-sandbox#saved-instances)) |
| Warm pool | VMs started before the request ([Warm pool](https://github.com/dualeai/exec-sandbox#warm-pool)) |
| L1, L2, L3 | The snapshot cache: memory snapshots, disk snapshots with the packages installed, and a copy of L2 in S3 ([Snapshot cache](https://github.com/dualeai/exec-sandbox#snapshot-cache)). It makes new VMs start faster; it holds no saved instance |
| Instance store | Where saved instances live: your S3 bucket (`s3`) or a folder on this host (`local`) ([Choose a store](https://github.com/dualeai/exec-sandbox#choose-a-store)) |
| Generation | The save number of an instance: 1, then +1 for each save |
| Head | The object in the store that names the current state of an instance |
| VM images | The kernel, the initramfs and the base disk image of each language ([VM images and offline use](https://github.com/dualeai/exec-sandbox#vm-images-and-offline-use)) |
| Assets | The VM images and the gvproxy-wrapper binary: what `sbx prefetch` downloads |
| Guest images | The disk images of one VM: the base image and, with packages, the L2 package image |
| Worker | A process that runs a `Scheduler`, on its host (a machine or a container) |
| Host kind | What a saved instance must match to load ([Rules for save and reuse](https://github.com/dualeai/exec-sandbox#rules-for-save-and-reuse)) |
| Admission | The wait until the host has the memory, CPU and disk for a VM ([Limits](https://github.com/dualeai/exec-sandbox#limits)) |
| KVM, HVF, TCG | Hardware acceleration on Linux (KVM) and macOS (HVF). TCG is QEMU's software emulation |
## Sessions
`scheduler.new(spec)` starts a new VM and returns its session. The session keeps variables, imports, files and background processes between `exec()` calls ([Limits](https://github.com/dualeai/exec-sandbox#limits)), until `close()` destroys the VM. Some errors close a session ([What closes a session](https://github.com/dualeai/exec-sandbox#what-closes-a-session)).
```
async with Scheduler() as scheduler:
async with await scheduler.new(VmSpec(language=Language.PYTHON)) as session:
await session.exec("import math")
await session.exec("x = math.pi * 2")
result = await session.exec("print(f'{x:.4f}')")
print(result.stdout) # 6.2832
print(session.exec_count) # 3
```
JavaScript sessions (also TypeScript) keep variables and functions. Shell sessions (`raw`, Bash) keep environment variables, the working folder and functions.
A session closes after `session_idle_timeout_seconds` (default 300) with no call. For one session, pass `idle_timeout_seconds` (10-3600) to `new()` or `reuse()`; a value out of range raises `InvalidInputError` (`ARGUMENT_INVALID`).
To get the output while the code runs, pass `on_stdout` and `on_stderr` to `exec()`: `await session.exec(code, on_stdout=lambda chunk: print(chunk, end=""))`. To get the boot output of the kernel, tiny-init and the guest agent, pass `on_boot_log` to `new()`; the VM then always cold boots (no warm pool, no L1). Keep each callback short: a slow callback blocks the event loop.
## Files
Paths are relative to `/home/user`, the folder where your code runs.
```
await session.write_file("input.csv", b"name,score\nAlice,95") # From bytes, a local Path or an IO[bytes] stream
await session.write_file("run.sh", Path("./run.sh"), make_executable=True) # Mode 0755 (default 0644)
await session.exec("open('output.csv', 'w').write(open('input.csv').read().upper())")
await session.read_file("output.csv", destination=Path("./output.csv")) # To a local Path or an IO[bytes] stream
for f in await session.list_files(""): # "" is /home/user
print(f.name, f.is_dir, f.size)
```
```
sbx run -