Sandbox
Sandbox 是 Agent 工具执行的隔离环境,防止工具执行影响宿主系统。它用于执行代码、文件操作、Shell 命令等有风险的工具。
#type / concept
#status / evergreen
#tech / ai
#tech / security
[!info] related notes
- 所属 MOC: Agent Runtime MOC
- 相关: Tool Runtime, Permission Boundary
Sandbox
一句话定义
Sandbox 是 Agent 工具执行的隔离环境。当 Agent 需要执行代码、读写文件、运行 Shell 命令时,这些操作应该在沙箱中执行,防止影响宿主系统。
它解决什么问题
Agent 执行的工具可能是:
- 运行用户提供的代码
- 执行 Shell 命令
- 读写文件系统
- 调用外部 API
这些操作如果直接在宿主系统执行,可能导致:
- 代码注入攻击
- 文件系统被破坏
- 系统资源被耗尽
- 敏感数据泄露
核心原理
沙箱实现方式
| 方式 | 隔离级别 | 启动速度 | 适用场景 |
|---|---|---|---|
| Docker 容器 | 高 | 慢(秒级) | 生产环境 |
| gVisor | 高 | 中 | 生产环境 |
| Firecracker | 最高 | 中 | 多租户 |
| 进程隔离 | 中 | 快 | 开发环境 |
| 语言级沙箱 | 低 | 最快 | 简单脚本 |
Python 实现(Docker 沙箱)
class DockerSandbox:
def __init__(self, image: str = "python:3.11-slim"):
self.image = image
async def execute(self, code: str, timeout: int = 30) -> SandboxResult:
# 创建容器
container = await docker.containers.create(
image=self.image,
command=["python", "-c", code],
mem_limit="256m",
cpu_quota=50000, # 50% CPU
network_disabled=True, # 禁用网络
read_only=True, # 只读文件系统
tmpfs={"/tmp": "size=64m"}, # 临时目录
)
try:
# 启动并等待完成
await container.start()
result = await asyncio.wait_for(
container.wait(),
timeout=timeout,
)
# 获取输出
logs = await container.logs(stdout=True, stderr=True)
return SandboxResult(
exit_code=result["StatusCode"],
output=logs.decode(),
)
except asyncio.TimeoutError:
await container.kill()
return SandboxResult(error="Execution timeout")
finally:
await container.remove()
OpenAI Code Interpreter 的沙箱
OpenAI 的 Code Interpreter 在隔离容器中执行代码:
- 网络隔离
- 文件系统隔离
- 资源限制(CPU、内存、时间)
- 临时环境(执行后销毁)
常见坑1. 不做资源限制: 代码死循环吃满 CPU
- 不做网络隔离: 恶意代码访问外部服务
- 不做文件系统隔离: 代码读写宿主文件
- 沙箱启动太慢: 每次工具调用都创建新容器