zeroboot-vm-sandbox

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zeroboot VM Sandbox

Zeroboot VM沙箱

Skill by ara.so — Daily 2026 Skills collection.
Zeroboot provides sub-millisecond KVM virtual machine sandboxes for AI agents using copy-on-write forking. Each sandbox is a real hardware-isolated VM (via Firecracker + KVM), not a container. A template VM is snapshotted once, then forked in ~0.8ms per execution using
mmap(MAP_PRIVATE)
CoW semantics.
ara.so提供的Skill — 2026每日技能合集。
Zeroboot 借助写时复制分叉技术,为AI Agent提供亚毫秒级的KVM虚拟机沙箱。每个沙箱都是真正的硬件隔离VM(基于Firecracker + KVM),而非容器。模板VM只需创建一次快照,之后每次执行都可通过
mmap(MAP_PRIVATE)
写时复制(CoW)语义在约0.8毫秒内完成分叉。

How It Works

工作原理

Firecracker snapshot ──► mmap(MAP_PRIVATE) ──► KVM VM + restored CPU state
                           (copy-on-write)          (~0.8ms)
  1. Template: Firecracker boots once, pre-loads your runtime, snapshots memory + CPU state
  2. Fork (~0.8ms): New KVM VM maps snapshot memory as CoW, restores CPU state
  3. Isolation: Each fork is a separate KVM VM with hardware-enforced memory isolation
Firecracker 快照 ──► mmap(MAP_PRIVATE) ──► KVM VM + 恢复CPU状态
                           (写时复制)          (~0.8毫秒)
  1. 模板:Firecracker启动一次,预加载运行时环境,对内存和CPU状态创建快照
  2. 分叉(约0.8毫秒):新的KVM VM以写时复制方式映射快照内存,恢复CPU状态
  3. 隔离性:每个分叉都是独立的KVM VM,具备硬件强制的内存隔离

Installation

安装

Python SDK

Python SDK

bash
pip install zeroboot
bash
pip install zeroboot

Node/TypeScript SDK

Node/TypeScript SDK

bash
npm install @zeroboot/sdk
bash
npm install @zeroboot/sdk

or

or

pnpm add @zeroboot/sdk
undefined
pnpm add @zeroboot/sdk
undefined

Authentication

身份验证

Set your API key as an environment variable:
bash
export ZEROBOOT_API_KEY="zb_live_your_key_here"
Never hardcode keys in source files.
将你的API密钥设置为环境变量:
bash
export ZEROBOOT_API_KEY="zb_live_your_key_here"
切勿在源文件中硬编码密钥。

Quick Start

快速开始

REST API (cURL)

REST API (cURL)

bash
curl -X POST https://api.zeroboot.dev/v1/exec \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $ZEROBOOT_API_KEY" \
  -d '{"code":"import numpy as np; print(np.random.rand(3))"}'
bash
curl -X POST https://api.zeroboot.dev/v1/exec \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $ZEROBOOT_API_KEY" \
  -d '{"code":"import numpy as np; print(np.random.rand(3))"}'

Python

Python

python
import os
from zeroboot import Sandbox
python
import os
from zeroboot import Sandbox

Initialize with API key from environment

从环境变量初始化API密钥

sb = Sandbox(os.environ["ZEROBOOT_API_KEY"])
sb = Sandbox(os.environ["ZEROBOOT_API_KEY"])

Run Python code

运行Python代码

result = sb.run("print(1 + 1)") print(result) # "2"
result = sb.run("print(1 + 1)") print(result) # "2"

Run multi-line code

运行多行代码

result = sb.run(""" import numpy as np arr = np.arange(10) print(arr.mean()) """) print(result)
undefined
result = sb.run(""" import numpy as np arr = np.arange(10) print(arr.mean()) """) print(result)
undefined

TypeScript / Node.js

TypeScript / Node.js

typescript
import { Sandbox } from "@zeroboot/sdk";

const apiKey = process.env.ZEROBOOT_API_KEY!;
const sb = new Sandbox(apiKey);

// Run JavaScript/Node code
const result = await sb.run("console.log(1 + 1)");
console.log(result); // "2"

// Run async code
const output = await sb.run(`
const data = [1, 2, 3, 4, 5];
const sum = data.reduce((a, b) => a + b, 0);
console.log(sum / data.length);
`);
console.log(output);
typescript
import { Sandbox } from "@zeroboot/sdk";

const apiKey = process.env.ZEROBOOT_API_KEY!;
const sb = new Sandbox(apiKey);

// 运行JavaScript/Node代码
const result = await sb.run("console.log(1 + 1)");
console.log(result); // "2"

// 运行异步代码
const output = await sb.run(`
const data = [1, 2, 3, 4, 5];
const sum = data.reduce((a, b) => a + b, 0);
console.log(sum / data.length);
`);
console.log(output);

Common Patterns

常见模式

AI Agent Code Execution Loop (Python)

AI Agent代码执行循环(Python)

python
import os
from zeroboot import Sandbox

def execute_agent_code(code: str) -> dict:
    """Execute LLM-generated code in an isolated VM sandbox."""
    sb = Sandbox(os.environ["ZEROBOOT_API_KEY"])
    try:
        result = sb.run(code)
        return {"success": True, "output": result}
    except Exception as e:
        return {"success": False, "error": str(e)}
python
import os
from zeroboot import Sandbox

def execute_agent_code(code: str) -> dict:
    """在隔离的VM沙箱中执行大语言模型生成的代码。"""
    sb = Sandbox(os.environ["ZEROBOOT_API_KEY"])
    try:
        result = sb.run(code)
        return {"success": True, "output": result}
    except Exception as e:
        return {"success": False, "error": str(e)}

Example: running agent-generated code safely

示例:安全运行Agent生成的代码

agent_code = """ import json data = {"agent": "result", "value": 42} print(json.dumps(data)) """ response = execute_agent_code(agent_code) print(response)
undefined
agent_code = """ import json data = {"agent": "result", "value": 42} print(json.dumps(data)) """ response = execute_agent_code(agent_code) print(response)
undefined

Concurrent Sandbox Execution (Python)

并发沙箱执行(Python)

python
import os
import asyncio
from zeroboot import Sandbox

async def run_sandbox(code: str, index: int) -> str:
    sb = Sandbox(os.environ["ZEROBOOT_API_KEY"])
    result = await asyncio.to_thread(sb.run, code)
    return f"[{index}] {result}"

async def run_concurrent(snippets: list[str]):
    tasks = [run_sandbox(code, i) for i, code in enumerate(snippets)]
    results = await asyncio.gather(*tasks)
    return results
python
import os
import asyncio
from zeroboot import Sandbox

async def run_sandbox(code: str, index: int) -> str:
    sb = Sandbox(os.environ["ZEROBOOT_API_KEY"])
    result = await asyncio.to_thread(sb.run, code)
    return f"[{index}] {result}"

async def run_concurrent(snippets: list[str]):
    tasks = [run_sandbox(code, i) for i, code in enumerate(snippets)]
    results = await asyncio.gather(*tasks)
    return results

Run 10 sandboxes concurrently

并发运行10个沙箱

codes = [f"print({i} ** 2)" for i in range(10)] outputs = asyncio.run(run_concurrent(codes)) for out in outputs: print(out)
undefined
codes = [f"print({i} ** 2)" for i in range(10)] outputs = asyncio.run(run_concurrent(codes)) for out in outputs: print(out)
undefined

TypeScript: Agent Tool Integration

TypeScript:Agent工具集成

typescript
import { Sandbox } from "@zeroboot/sdk";

interface ExecutionResult {
  success: boolean;
  output?: string;
  error?: string;
}

async function runInSandbox(code: string): Promise<ExecutionResult> {
  const sb = new Sandbox(process.env.ZEROBOOT_API_KEY!);
  try {
    const output = await sb.run(code);
    return { success: true, output };
  } catch (err) {
    return { success: false, error: String(err) };
  }
}

// Integrate as a tool for an LLM agent
const tool = {
  name: "execute_code",
  description: "Run code in an isolated VM sandbox",
  execute: async ({ code }: { code: string }) => runInSandbox(code),
};
typescript
import { Sandbox } from "@zeroboot/sdk";

interface ExecutionResult {
  success: boolean;
  output?: string;
  error?: string;
}

async function runInSandbox(code: string): Promise<ExecutionResult> {
  const sb = new Sandbox(process.env.ZEROBOOT_API_KEY!);
  try {
    const output = await sb.run(code);
    return { success: true, output };
  } catch (err) {
    return { success: false, error: String(err) };
  }
}

// 集成为大语言模型Agent的工具
const tool = {
  name: "execute_code",
  description: "在隔离的VM沙箱中运行代码",
  execute: async ({ code }: { code: string }) => runInSandbox(code),
};

REST API with fetch (TypeScript)

使用fetch的REST API(TypeScript)

typescript
const API_BASE = "https://api.zeroboot.dev/v1";

async function execCode(code: string): Promise<string> {
  const res = await fetch(`${API_BASE}/exec`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.ZEROBOOT_API_KEY}`,
    },
    body: JSON.stringify({ code }),
  });
  if (!res.ok) {
    const err = await res.text();
    throw new Error(`Zeroboot error ${res.status}: ${err}`);
  }
  const data = await res.json();
  return data.output;
}
typescript
const API_BASE = "https://api.zeroboot.dev/v1";

async function execCode(code: string): Promise<string> {
  const res = await fetch(`${API_BASE}/exec`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.ZEROBOOT_API_KEY}`,
    },
    body: JSON.stringify({ code }),
  });
  if (!res.ok) {
    const err = await res.text();
    throw new Error(`Zeroboot错误 ${res.status}: ${err}`);
  }
  const data = await res.json();
  return data.output;
}

Health Check

健康检查

bash
curl https://api.zeroboot.dev/v1/health
bash
curl https://api.zeroboot.dev/v1/health

API Reference

API参考

POST /v1/exec

POST /v1/exec

Execute code in a fresh sandbox fork.
Request:
json
{
  "code": "print('hello')"
}
Headers:
Authorization: Bearer <ZEROBOOT_API_KEY>
Content-Type: application/json
Response:
json
{
  "output": "hello\n",
  "duration_ms": 0.79
}
在新的沙箱分叉中执行代码。
请求:
json
{
  "code": "print('hello')"
}
请求头:
Authorization: Bearer <ZEROBOOT_API_KEY>
Content-Type: application/json
响应:
json
{
  "output": "hello\n",
  "duration_ms": 0.79
}

Performance Characteristics

性能指标

MetricValue
Spawn latency p50~0.79ms
Spawn latency p99~1.74ms
Memory per sandbox~265KB
Fork + exec Python~8ms
1000 concurrent forks~815ms
  • Each sandbox is a real KVM VM — not a container or process jail
  • Memory isolation is hardware-enforced (not software)
  • CoW means only pages written by your code consume extra RAM
指标数值
启动延迟p50~0.79毫秒
启动延迟p99~1.74毫秒
每个沙箱内存占用~265KB
分叉+执行Python代码~8毫秒
1000个并发分叉~815毫秒
  • 每个沙箱都是真实的KVM VM — 而非容器或进程限制环境
  • 内存隔离由硬件强制实现(而非软件层面)
  • 写时复制意味着只有被代码修改的页面才会占用额外内存

Self-Hosting / Deployment

自托管/部署

See docs/DEPLOYMENT.md in the repo. Requirements:
  • Linux host with KVM support (
    /dev/kvm
    accessible)
  • Firecracker binary
  • Rust 2021 edition toolchain
bash
undefined
请查看仓库中的docs/DEPLOYMENT.md。部署要求:
  • 支持KVM的Linux主机(可访问
    /dev/kvm
  • Firecracker二进制文件
  • Rust 2021版本工具链
bash
undefined

Check KVM availability

检查KVM可用性

ls /dev/kvm
ls /dev/kvm

Clone and build

克隆并构建项目

git clone https://github.com/adammiribyan/zeroboot cd zeroboot cargo build --release
undefined
git clone https://github.com/adammiribyan/zeroboot cd zeroboot cargo build --release
undefined

Architecture Notes

架构说明

  • Snapshot layer: Firecracker VM boots once per runtime template, memory + vCPU state saved to disk
  • Fork layer (Rust):
    mmap(MAP_PRIVATE)
    on snapshot file → kernel handles CoW page faults per VM
  • Isolation: Each fork has its own KVM VM file descriptors, vCPU, and page table — fully hardware-separated
  • No shared kernel: Unlike containers, each sandbox runs its own kernel instance
  • 快照层:Firecracker针对每个运行时模板启动一次,将内存和vCPU状态保存到磁盘
  • 分叉层(Rust实现):对快照文件执行
    mmap(MAP_PRIVATE)
    → 内核为每个VM处理写时复制页面错误
  • 隔离性:每个分叉都有独立的KVM VM文件描述符、vCPU和页表 — 完全硬件隔离
  • 无共享内核:与容器不同,每个沙箱都运行独立的内核实例

Troubleshooting

故障排查

/dev/kvm not found
(self-hosted)
bash
undefined
/dev/kvm not found
(自托管场景)
bash
undefined

Enable KVM kernel module

启用KVM内核模块

sudo modprobe kvm sudo modprobe kvm_intel # or kvm_amd

**API returns 401 Unauthorized**
- Verify `ZEROBOOT_API_KEY` is set and starts with `zb_live_`
- Check the key is not expired in your dashboard

**Timeout on execution**
- Default execution timeout is enforced server-side
- Break large computations into smaller chunks
- Avoid infinite loops or blocking I/O in sandbox code

**High memory usage (self-hosted)**
- Each VM fork starts at ~265KB CoW overhead
- Pages are allocated on write — memory grows with sandbox activity
- Tune concurrent fork limits based on available RAM
sudo modprobe kvm sudo modprobe kvm_intel # 或kvm_amd

**API返回401 Unauthorized**
- 确认`ZEROBOOT_API_KEY`已正确设置,且以`zb_live_`开头
- 检查密钥在你的控制台中是否未过期

**执行超时**
- 服务器端会强制执行默认超时时间
- 将大型计算拆分为更小的任务块
- 避免在沙箱代码中出现无限循环或阻塞I/O

**内存占用过高(自托管场景)**
- 每个VM分叉初始写时复制开销约为265KB
- 页面仅在写入时分配 — 内存占用随沙箱活动增长
- 根据可用内存调整并发分叉限制

Resources

资源