# Deno Sandbox

Deno Sandbox 通过 `@deno/sandbox` 创建按需 Linux microVM，适合让 AI Agent 执行代码、运行插件或构建用户项目。它与 Deno 运行时权限不是同一层：Sandbox 提供独立虚拟机和资源边界。

## 创建并自动清理

```ts
import { Sandbox } from "@deno/sandbox";

await using sandbox = await Sandbox.create({
  memoryMb: 2048,
  timeout: "10m",
  allowNet: ["jsr.io", "registry.npmjs.org"],
  labels: { workload: "agent-build" },
});

const result = await sandbox.sh`deno --version`;
console.log(result.stdout);
```

使用 `await using` 或 `finally` 保证连接清理。`close()` 是断开连接；需要提前终止 VM 时用 `kill()`，不要混淆生命周期语义。

## 安全默认值

官方页面截至 2026-08-03 对省略 `allowNet` 的默认值存在不一致描述：创建页写“无出站网络”，安全页写“允许全部出站”。因此不要依赖默认值，始终显式传入最小 `allowNet`。默认内存约 1280 MB；内存、区域、生命周期和预发布配额都需按当前页面核对。

- 网络使用 allowlist，密钥绑定到需要访问的 host。
- 上传前检查路径，下载产物前限制大小和类型。
- 命令使用参数化 API/tagged template，不拼接用户文本进 shell。
- 设置 wall-clock timeout、输出上限、并发和磁盘预算。
- 把 sandbox ID、agent ID、用户/租户和 request ID 写入 labels 与审计日志。
- 稳定的长服务迁移为 Deploy app，不把临时 sandbox 当永久主机。

<Callout type="warn" title="Sandbox 不是授权">
模型建议运行某段代码不等于用户授权执行。删除、发布、联网、读取客户数据和产生费用的动作仍需业务授权与审批。
</Callout>

官方依据：[Deno Sandbox](https://docs.deno.com/sandbox/)、[Create a sandbox](https://docs.deno.com/sandbox/create/)、[Security](https://docs.deno.com/sandbox/security/)。
