offload-to-sandbox
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOffloading work to a Vercel Sandbox
将工作卸载到 Vercel Sandbox
A Vercel Sandbox is a Linux microVM (x86_64) you can create in seconds and remove when you're done. That makes it a good remote worker: it keeps heavy builds and long test suites off your laptop and gives every agent or task its own clean machine. This skill covers how to do that efficiently with the CLI. For the SDK and running untrusted code, see the skill.
vercel sandbox@vercel/sandboxvercel-sandboxVercel Sandbox 是一种 Linux microVM(x86_64),只需几秒即可创建,并可在使用完成后删除。因此,它非常适合作为远程 worker:将重型构建和长时间运行的测试套件留在笔记本电脑之外,并为每个 Agent 或任务提供一台干净的机器。本 skill 介绍如何通过 CLI 高效完成这些工作。有关 SDK 和运行不可信代码,请参阅 skill。
vercel sandbox@vercel/sandboxvercel-sandboxWhen to offload, and what to keep local
何时卸载,以及哪些内容应保留在本地
Offload:
- Full test suites, especially when they can be sharded.
- Builds that take minutes or need Linux.
- Many tasks at once: one sandbox per task or per agent.
- Anything that fills the local disk (large build trees, many worktrees).
Keep local:
- Editing, , small focused tests, type checks and lint, and orchestration.
git - Anything needing local credentials or hardware the sandbox doesn't have.
A good default when several agents share one machine: agents edit locally and run quick focused checks, and everything heavy goes to their own sandboxes.
应卸载:
- 完整测试套件,尤其是可以进行分片时。
- 耗时数分钟或需要 Linux 的构建。
- 同时运行许多任务:每个任务或 Agent 使用一个 sandbox。
- 会占满本地磁盘的任何内容(大型构建目录树、大量 worktree)。
应保留在本地:
- 编辑、、小型定向测试、类型检查和 lint,以及编排工作。
git - 需要本地凭据或 sandbox 不具备的硬件的任何工作。
当多个 Agent 共享一台机器时,一个很好的默认做法是:Agent 在本地编辑并运行快速、定向的检查,而所有重型工作都转移到各自的 sandbox。
Plan limits
套餐限制
| Hobby | Pro | Enterprise | |
|---|---|---|---|
| Max vCPUs (2 GB memory each) | 4 (8 GB) | 8 (16 GB) | 32 (64 GB) |
| Max session duration | 45 minutes | 24 hours | 24 hours |
| Concurrent sandboxes | 10 | 10,000 | 10,000 |
--vcpus--vcpus 8--timeout 3h--vcpus 445mRunning sandboxes are billed for Active CPU and provisioned memory. Snapshots are billed as Snapshot Storage per GB-month for as long as they exist.
| Hobby | Pro | Enterprise | |
|---|---|---|---|
| 最大 vCPU 数(每个 2 GB 内存) | 4(8 GB) | 8(16 GB) | 32(64 GB) |
| 最长会话时长 | 45 分钟 | 24 小时 | 24 小时 |
| 并发 sandbox 数量 | 10 | 10,000 | 10,000 |
--vcpus--vcpus 8--timeout 3h--vcpus 445m运行中的 sandbox 按 Active CPU 和已配置内存计费。Snapshot 在存续期间按每 GB-月的 Snapshot Storage 计费。
Prepare a base snapshot once
一次性准备基础 snapshot
Installing toolchains and dependencies in every new sandbox wastes minutes and money. Do it once, snapshot, and start everything else from the snapshot:
bash
undefined在每个新 sandbox 中安装工具链和依赖会浪费时间和费用。只执行一次,创建 snapshot,并让其他所有内容都从该 snapshot 启动:
bash
undefined1. Create a builder sandbox from the default image (Ubuntu, Node.js, Python, common tools).
1. Create a builder sandbox from the default image (Ubuntu, Node.js, Python, common tools).
vercel sandbox create --name base-builder --non-persistent --vcpus 8 --timeout 2h --image vercel/sandbox/universal
vercel sandbox create --name base-builder --non-persistent --vcpus 8 --timeout 2h --image vercel/sandbox/universal
2. Install the pinned toolchain and build the baseline tree once.
2. Install the pinned toolchain and build the baseline tree once.
vercel sandbox copy ./setup-base.sh base-builder:/vercel/sandbox/setup-base.sh
vercel sandbox exec base-builder -- sh -c 'cd /vercel/sandbox && sh setup-base.sh; echo "exit=$?"'
vercel sandbox copy ./setup-base.sh base-builder:/vercel/sandbox/setup-base.sh
vercel sandbox exec base-builder -- sh -c 'cd /vercel/sandbox && sh setup-base.sh; echo "exit=$?"'
3. Snapshot it (this stops the sandbox). The ID is printed on stderr, not stdout.
3. Snapshot it (this stops the sandbox). The ID is printed on stderr, not stdout.
vercel sandbox snapshot base-builder --stop --expiration 0 2>&1 | grep -o 'snap_[A-Za-z0-9_-]*' | head -n 1 > BASE_SNAPSHOT
test -s BASE_SNAPSHOT
vercel sandbox snapshot base-builder --stop --expiration 0 2>&1 | grep -o 'snap_[A-Za-z0-9_-]*' | head -n 1 > BASE_SNAPSHOT
test -s BASE_SNAPSHOT
4. The builder is no longer needed. Removing it keeps the snapshot.
4. The builder is no longer needed. Removing it keeps the snapshot.
vercel sandbox remove base-builder
Check that step 2 printed `exit=0` before you snapshot (see [Run commands](#run-commands) for why).
What to put in the base:
- The exact toolchain versions your project pins (compilers, runtimes, package manager).
- An installed and built copy of the main branch at a known commit, as a read-only baseline (for example `/vercel/sandbox/base`).
- Small helper scripts the tasks will reuse (for example a `prepare.sh` that turns a freshly pushed tree into a runnable checkout).
Keep the snapshot ID in a file next to your tooling. `--expiration 0` means the snapshot never expires, so it is billed until you delete it. When the toolchain changes, build a new snapshot and delete the old one with `vercel sandbox snapshots delete <old-id>`. Before a big run, check that `vercel sandbox snapshots get "$(cat BASE_SNAPSHOT)"` still shows the status `created`; a deleted or expired snapshot shows `deleted`.vercel sandbox remove base-builder
在创建 snapshot 前,确认步骤 2 输出了 `exit=0`(原因请参阅[运行命令](#run-commands))。
基础 snapshot 中应包含:
- 项目锁定的精确工具链版本(编译器、运行时、包管理器)。
- 主分支在已知 commit 下的已安装、已构建副本,作为只读基线(例如 `/vercel/sandbox/base`)。
- 任务会复用的小型辅助脚本(例如将新推送的目录树转换为可运行 checkout 的 `prepare.sh`)。
将 snapshot ID 保存在工具旁边的文件中。`--expiration 0` 表示 snapshot 永不过期,但仍会持续计费,直到将其删除。工具链发生变化时,应创建新的 snapshot,并使用 `vercel sandbox snapshots delete <old-id>` 删除旧 snapshot。在大规模运行前,检查 `vercel sandbox snapshots get "$(cat BASE_SNAPSHOT)"` 是否仍显示状态 `created`;已删除或过期的 snapshot 会显示 `deleted`。Create one sandbox per task
为每个任务创建一个 sandbox
bash
vercel sandbox create --name exp-parser --non-persistent --snapshot "$(cat BASE_SNAPSHOT)" \
--vcpus 8 --timeout 3h --tag app=my-project --tag owner=agent-parser --silent- Name by owner and purpose (,
exp-parser) so parallel agents never collide. Names are unique per project and stay taken until the sandbox is removed. Never use another agent's sandbox.exp-parser-2 - Size: each vCPU comes with 2 GB of memory, and that is the only way to get more memory. Memory-heavy steps (large compiles, big linker jobs) can be killed by the Linux OOM killer. Below your plan's vCPU maximum, size up. At the maximum, lower the step's parallelism (for example fewer build jobs) or run it alone.
- Tags (up to 5 per sandbox) make cleanup easy: list and remove everything with your owner tag at the end.
bash
vercel sandbox create --name exp-parser --non-persistent --snapshot "$(cat BASE_SNAPSHOT)" \
--vcpus 8 --timeout 3h --tag app=my-project --tag owner=agent-parser --silent- 按所有者和用途命名(、
exp-parser),以免并行 Agent 发生冲突。名称在项目内唯一,并且会持续占用,直到 sandbox 被移除。绝不要使用其他 Agent 的 sandbox。exp-parser-2 - **规格:**每个 vCPU 配备 2 GB 内存,并且这是增加内存的唯一方式。内存密集型步骤(大型编译、大规模链接任务)可能会被 Linux OOM killer 终止。如果尚未达到套餐的 vCPU 上限,应提高规格;达到上限时,应降低步骤的并行度(例如减少构建作业数),或单独运行该步骤。
- Tags(每个 sandbox 最多 5 个)便于清理:最后可以按 owner tag 列出并移除所有相关 sandbox。
Lifetime and cleanup
生命周期与清理
Sandboxes are persistent by default: when a session stops, the filesystem is snapshotted so the sandbox can resume later, and that snapshot is billed as Snapshot Storage. Task sandboxes don't need that, which is why every here passes .
create--non-persistent- sets the session length, not the sandbox's lifetime. The default is 5 minutes. When it runs out, the session stops and everything running in it is killed, detached jobs included. A non-persistent sandbox loses its whole filesystem at that point. Set the timeout for the whole task.
--timeoutchanges it later, and a higher value also extends the running session.vercel sandbox config timeout <name> <duration> - when a task is done.
vercel sandbox remove <name>only ends the current session: the sandbox keeps its name, and a persistent sandbox keeps billing for its snapshot. Vercel removes sandboxes that can't resume after 14 days of inactivity, so a stopped non-persistent sandbox blocks its name until then unless you remove it.vercel sandbox stop - Removing a sandbox does not delete snapshots, so the base snapshot survives task cleanup. on
--delete-orphan-snapshotsalso deletes the sandbox's own snapshots that no other sandbox uses. Don't pass it when removing the builder that made your base snapshot.remove - Sweep orphans from crashed agents with .
vercel sandbox list --all --tag owner=<agent>includes stopped sandboxes (the default shows only running ones), and--allfilters by one tag at a time. Remove everything it shows withlist. Sweep the whole project (vercel sandbox remove <name>...) only when no agent is still working.--tag app=my-project
Sandbox 默认是持久化的:会话停止时,文件系统会被 snapshot,之后可以恢复该 sandbox,并且该 snapshot 按 Snapshot Storage 计费。任务 sandbox 不需要此功能,因此这里的每个 都传入了 。
create--non-persistent- **设置的是会话长度,而不是 sandbox 的生命周期。**默认值为 5 分钟。超时后,会话停止,其中正在运行的所有内容都会被终止,包括分离作业。非持久化 sandbox 会在此时丢失整个文件系统。应根据整个任务设置超时。
--timeout可以稍后修改它,更大的值也会延长正在运行的会话。vercel sandbox config timeout <name> <duration> - 任务完成后,使用 。
vercel sandbox remove <name>仅结束当前会话:sandbox 会保留名称,持久化 sandbox 也会继续为其 snapshot 计费。Vercel 会移除闲置 14 天后无法恢复的 sandbox,因此已停止的非持久化 sandbox 在此之前仍会占用名称,除非将其移除。vercel sandbox stop - 移除 sandbox 不会删除 snapshot,因此基础 snapshot 可以在任务清理后继续存在。在 时使用
remove,还会删除没有被其他 sandbox 使用的该 sandbox 自身 snapshot。移除用于创建基础 snapshot 的 builder 时,不要传入此参数。--delete-orphan-snapshots - 使用 清理崩溃 Agent 留下的孤立资源。
vercel sandbox list --all --tag owner=<agent>包含已停止的 sandbox(默认仅显示正在运行的 sandbox),而--all每次只能按一个 tag 过滤。使用list移除其显示的所有内容。只有在没有任何 Agent 仍在工作时,才按项目清理(vercel sandbox remove <name>...)。--tag app=my-project
Move code in without reinstalling dependencies
无需重新安装依赖即可传入代码
Send source, not build output. Package the files git knows about (tracked plus untracked but not ignored) as one tarball, copy it, and extract it next to the old tree. Then move heavy directories () from the old tree into the new one so they don't need reinstalling, and swap the two. in the wrapper script does exactly this:
node_modulessbx pushbash
sbx push exp-parser . /vercel/sandbox/cand- Push after every change; it takes seconds. Then run an idempotent prepare step that installs or rebuilds only what changed (for example, install dependencies only when the lockfile changed).
- Build platform-specific artifacts inside the sandbox. Don't copy macOS binaries into a Linux VM.
- Don't push or dependency directories. If you need git history remotely, push a bundle or
.gitinside the sandbox.git clone - A tracked file you deleted but didn't stage makes fail. Stage the deletion (
tar) first.git rm
应传输源代码,而不是构建产物。将 Git 已知文件(已跟踪和未跟踪但未忽略的文件)打包成一个 tarball,复制后解压到旧目录树旁边。然后将大型目录()从旧目录树移入新目录树,再交换两者。包装脚本中的 正是这样做的:
node_modulessbx pushbash
sbx push exp-parser . /vercel/sandbox/cand- 每次更改后都应推送,只需几秒。然后运行具备幂等性的准备步骤,仅安装或重新构建发生变化的依赖(例如,仅在 lockfile 发生变化时安装依赖)。
- 在 sandbox 内构建特定平台的产物。不要将 macOS 二进制文件复制到 Linux VM 中。
- 不要推送 或依赖目录。如果需要在远端保留 Git 历史,请推送 bundle,或在 sandbox 内执行
.git。git clone - 如果已删除某个已跟踪文件但尚未暂存,会失败。请先暂存该删除操作(
tar)。git rm
Read, write, and copy files directly
直接读取、写入和复制文件
The standalone CLI supports file commands in releases containing vercel/sandbox#380. Install or update it with , then check the installed commands before using the examples:
sandboxnpm i -g sandboxbash
sandbox --version
sandbox read --help
sandbox write --help
sandbox copy --helpConfirm that and exist and that lists . If they are unavailable, keep using and the wrapper below. The Vercel CLI bundles its own Sandbox CLI version, so support in does not establish support in .
readwritecopy --help--recursivevercel sandbox copysbxsandboxvercel sandboxUse the same team and project as the existing task sandbox. Set and as described in Authentication and scope; the standalone CLI must also be authenticated.
SBX_SCOPESBX_PROJECTbash
name=exp-parser
: "${SBX_SCOPE:?set SBX_SCOPE to your team slug}"
: "${SBX_PROJECT:?set SBX_PROJECT to your project name}"bash
sandbox --version
sandbox read --help
sandbox write --help
sandbox copy --help确认 和 命令存在,并且 列出了 。如果这些功能不可用,请继续使用 和下方的 包装脚本。Vercel CLI 捆绑了自己的 Sandbox CLI 版本,因此 支持某项功能并不代表 也支持。
readwritecopy --help--recursivevercel sandbox copysbxsandboxvercel sandboxbash
name=exp-parser
: "${SBX_SCOPE:?set SBX_SCOPE to your team slug}"
: "${SBX_PROJECT:?set SBX_PROJECT to your project name}"Read a sandbox file to stdout without changing its bytes.
Read a sandbox file to stdout without changing its bytes.
sandbox read --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "${name}:/vercel/sandbox/cand/package.json"
sandbox read --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "${name}:/vercel/sandbox/cand/package.json"
Write a script from stdin and make it executable.
Write a script from stdin and make it executable.
sandbox write --scope "$SBX_SCOPE" --project "$SBX_PROJECT" --mode 755 "${name}:/vercel/sandbox/check.sh" <<'SCRIPT'
#!/bin/sh
cd /vercel/sandbox/cand
npm test
SCRIPT
sandbox write --scope "$SBX_SCOPE" --project "$SBX_PROJECT" --mode 755 "${name}:/vercel/sandbox/check.sh" <<'SCRIPT'
#!/bin/sh
cd /vercel/sandbox/cand
npm test
SCRIPT
Copy a prepared local directory into the sandbox.
Copy a prepared local directory into the sandbox.
sandbox copy -r --scope "$SBX_SCOPE" --project "$SBX_PROJECT" ./task-input "${name}:/vercel/sandbox/task-input"
sandbox copy -r --scope "$SBX_SCOPE" --project "$SBX_PROJECT" ./task-input "${name}:/vercel/sandbox/task-input"
Download the result directory after the task has produced it.
Download the result directory after the task has produced it.
sandbox copy -r --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "${name}:/vercel/sandbox/results" ./results
`read` (also `cat`) prints file contents to stdout. `write` replaces the destination with stdin; redirect a local file with `< ./script.sh` when you already have one. Both return a non-zero status on failure.
Recursive copy puts the source directory's **contents** inside the destination and preserves empty directories, symlinks, and permissions. Windows downloads reject filenames containing backslashes or colons. It copies every entry, including ignored files, and leaves unrelated destination files in place. Use it for prepared input directories and results. Keep `sbx push` for project updates that need Git-based selection, removal of stale files, and reuse of remote `node_modules`.sandbox copy -r --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "${name}:/vercel/sandbox/results" ./results
`read`(也可用 `cat`)会将文件内容打印到 stdout。`write` 会使用 stdin 替换目标内容;已有本地文件时,可使用 `< ./script.sh` 进行重定向。两者在失败时都会返回非零状态。
递归复制会将源目录的**内容**放入目标目录,并保留空目录、符号链接和权限。Windows 下载会拒绝包含反斜杠或冒号的文件名。它会复制所有条目,包括被忽略的文件,并保留目标目录中无关的文件。适用于 prepared 输入目录和结果。对于需要基于 Git 选择文件、删除过期文件以及复用远程 `node_modules` 的项目更新,应继续使用 `sbx push`。Run commands
运行命令
bash
vercel sandbox exec --timeout 2h exp-parser -- sh -c 'cd /vercel/sandbox/cand && npm test -- --shard 1/4; echo "exit=$?"'- Pass the whole command as one single-quoted string to . Your local shell otherwise expands
sh -cand globs before the sandbox sees them. zsh in particular errors on unmatched globs and treats$VARS,$var:rand similar as modifiers; use$var:h.${var} - Check the bundled CLI's exit behavior. With 64.5.0 (Sandbox CLI 4.4.0),
vercelexits 0 even when the remote command fails. On that version, end the remote command withvercel sandbox execand read that, or useecho "exit=$?", which returns the remote status. The standalone Sandbox CLI (sbx exec, thennpm i -g sandbox) does pass the remote exit code through.sandbox exec ... - For anything longer than a line, write a script locally, it in, and run it. That is easier to quote, review and rerun.
vercel sandbox copy - is optional and has no default. When it expires, the command is killed with SIGKILL and the CLI prints
exec --timeout. Without it, a command runs until it finishes or the session times out.Command was killed (SIGKILL, exit code 137) - If you compare timings, run both versions in the same sandbox, because hosts of the same size can differ in speed.
bash
vercel sandbox exec --timeout 2h exp-parser -- sh -c 'cd /vercel/sandbox/cand && npm test -- --shard 1/4; echo "exit=$?"'- 将整个命令作为单个单引号字符串传给 。否则,本地 shell 会在 sandbox 看到命令之前展开
sh -c和 glob。尤其是 zsh 会因未匹配的 glob 而报错,并将$VARS、$var:r等视为修饰符;应使用$var:h。${var} - **检查捆绑 CLI 的退出行为。**在 64.5.0(Sandbox CLI 4.4.0)中,即使远程命令失败,
vercel也会退出 0。在该版本中,应让远程命令以vercel sandbox exec结尾并读取结果,或者使用echo "exit=$?",后者会返回远程状态。独立 Sandbox CLI(sbx exec,然后执行npm i -g sandbox)会正确透传远程退出码。sandbox exec ... - 对于超过一行的内容,应在本地编写脚本,通过 复制进去,然后运行。这样更便于处理引号、审查和重新执行。
vercel sandbox copy - 是可选参数,并且没有默认值。超时时,命令会收到 SIGKILL,CLI 会打印
exec --timeout。未设置时,命令会一直运行,直到完成或会话超时。Command was killed (SIGKILL, exit code 137) - 如果需要比较耗时,请在同一个 sandbox 中运行两个版本,因为相同规格的宿主机在速度上可能存在差异。
Run long jobs with the standalone CLI
使用独立 CLI 运行长任务
Use native command management when your installed CLI supports it. With the standalone CLI installed and authenticated as described above, check:
bash
sandbox --version
sandbox exec --help
sandbox commands --helpConfirm that lists and , and that lists , , , and . Check these independently of the file commands above: CLI releases may support command management before , , and recursive copy. The Vercel CLI bundles its own Sandbox CLI version.
exec--detach--stdincommandsgetlogswaitkillreadwriteStart the task in the existing sandbox and save its command ID:
bash
name=exp-parser
: "${SBX_SCOPE:?set SBX_SCOPE to your team slug}"
: "${SBX_PROJECT:?set SBX_PROJECT to your project name}"
command_id=$(sandbox exec --scope "$SBX_SCOPE" --project "$SBX_PROJECT" --detach "$name" -- sh -c 'cd /vercel/sandbox/cand && npm run test:all')
printf '%s\n' "$command_id"
sandbox commands get --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id"
sandbox commands logs --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id"
sandbox commands wait --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id"getlogswaitTo cancel a still-running task, use its saved command ID:
bash
sandbox commands kill --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id" --signal SIGTERM
sandbox commands wait --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id"Cancellation normally produces a non-zero exit status. Killing a command leaves the sandbox running. Command IDs belong to the current session; collect results before it stops. Detached commands still end when their command timeout or sandbox session timeout expires.
当已安装的 CLI 支持时,使用原生命令管理功能。安装独立 CLI 并按照上文完成身份验证后,检查:
bash
sandbox --version
sandbox exec --help
sandbox commands --help确认 列出了 和 ,并且 列出了 、、 和 。请将这些检查与上述文件命令分开进行:CLI 版本可能在支持命令管理后,才支持 、 和递归复制。Vercel CLI 捆绑了自己的 Sandbox CLI 版本。
exec--detach--stdincommandsgetlogswaitkillreadwrite在现有 sandbox 中启动任务并保存其 command ID:
bash
name=exp-parser
: "${SBX_SCOPE:?set SBX_SCOPE to your team slug}"
: "${SBX_PROJECT:?set SBX_PROJECT to your project name}"
command_id=$(sandbox exec --scope "$SBX_SCOPE" --project "$SBX_PROJECT" --detach "$name" -- sh -c 'cd /vercel/sandbox/cand && npm run test:all')
printf '%s\n' "$command_id"
sandbox commands get --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id"
sandbox commands logs --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id"
sandbox commands wait --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id"getlogswait要取消仍在运行的任务,请使用保存的 command ID:
bash
sandbox commands kill --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id" --signal SIGTERM
sandbox commands wait --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$name" "$command_id"取消通常会产生非零退出状态。终止命令不会停止 sandbox。Command ID 属于当前会话;应在会话停止前收集结果。分离命令仍会在命令超时或 sandbox 会话超时后结束。
Pipe input without an interactive terminal
在没有交互式终端时管道输入
For a command that reads input and then finishes, use :
--stdinbash
printf 'hello\n' | sandbox exec --scope "$SBX_SCOPE" --project "$SBX_PROJECT" --stdin "$name" -- catThis prints . The CLI forwards input and closes the remote stdin when the local input ends. Use for pipes and scripts; it cannot be combined with . For detached input, keeps stdin open for later calls; finish with before waiting for a program that needs end-of-input. Wait for each write to finish before starting another. Treat command logs as text; use file transfers for binary artifacts.
hello--stdin--interactiveexec --detach --stdincommands writecommands close-stdin对于读取输入后结束的命令,请使用 :
--stdinbash
printf 'hello\n' | sandbox exec --scope "$SBX_SCOPE" --project "$SBX_PROJECT" --stdin "$name" -- cat这会打印 。CLI 会转发输入,并在本地输入结束时关闭远程 stdin。将 用于管道和脚本;它不能与 结合使用。对于分离输入, 会保持 stdin 打开,以供后续调用 ;在等待需要输入结束的程序之前,使用 结束输入。每次写入完成后,再开始下一次写入。将命令日志视为文本;二进制产物应使用文件传输。
hello--stdin--interactiveexec --detach --stdincommands writecommands close-stdinFall back on older CLI versions
回退到较旧的 CLI 版本
If native command management is unavailable, use the existing wrapper for exit-status handling. For long jobs, keep the status-file approach below. The sandbox session timeout must cover the whole job:
sbx execbash
vercel sandbox exec exp-parser -- sh -c 'cd /vercel/sandbox/cand && rm -f /tmp/test.status && nohup sh -c "npm run test:all > /tmp/test.log 2>&1; echo \$? > /tmp/test.status" > /dev/null 2>&1 &'如果原生命令管理功能不可用,请使用现有的 包装脚本处理退出状态。对于长任务,请保留下面的状态文件方案。Sandbox 会话超时必须覆盖整个作业:
sbx execbash
vercel sandbox exec exp-parser -- sh -c 'cd /vercel/sandbox/cand && rm -f /tmp/test.status && nohup sh -c "npm run test:all > /tmp/test.log 2>&1; echo \$? > /tmp/test.status" > /dev/null 2>&1 &'later, cheap polls:
later, cheap polls:
vercel sandbox exec --timeout 30s exp-parser -- sh -c 'cat /tmp/test.status 2>/dev/null || tail -3 /tmp/test.log'
undefinedvercel sandbox exec --timeout 30s exp-parser -- sh -c 'cat /tmp/test.status 2>/dev/null || tail -3 /tmp/test.log'
undefinedGet results back
取回结果
- Have the remote side write compact result files (a summary of failing test names, exit codes, a JSON report) and copy just those back with . With the bundled CLI described here,
vercel sandbox copy exp-parser:/tmp/results.json ./results/results.jsonmoves one file per call and needs a full destination file path. For a whole result directory, use standalone recursive copy when available.copy - On that older bundled CLI, a missing source file makes print an error without failing, so check that the local file exists afterwards (
copydoes).sbx get - Compress large logs remotely and only fetch them when needed. Streaming megabytes of output through is slow and wastes context when an agent reads it.
exec
- 让远程端写入紧凑的结果文件(失败测试名称摘要、退出码、JSON 报告),然后仅使用 取回这些文件。对于这里介绍的捆绑 CLI,
vercel sandbox copy exp-parser:/tmp/results.json ./results/results.json每次只移动一个文件,并且需要提供完整的目标文件路径。如需获取整个结果目录,请在支持时使用独立递归复制。copy - 在较旧的捆绑 CLI 中,源文件不存在时,会打印错误但不会失败,因此之后应检查本地文件是否存在(
copy会执行此检查)。sbx get - 在远程压缩大型日志,仅在需要时获取。通过 流式传输数 MB 输出速度较慢,而且 Agent 读取时会浪费大量上下文。
exec
Shard and parallelize
分片与并行化
- Split a slow suite across N sandboxes by shard index, with your test runner's sharding or one orchestration script, and run the shards at the same time.
- Give each task its own sandbox. Ten agents each working in their own sandbox beat ten tasks queued on one machine.
- Bound concurrency by budget, not by what the API allows. Every running sandbox costs money.
- Large fan-outs are throttled by how fast you can allocate vCPUs. An idle Pro team starts at 150 vCPUs per minute (18 sandboxes with 8 vCPUs) and ramps up with sustained use; Hobby allows 20 to 40 per minute.
- 使用测试运行器的分片功能或一个编排脚本,按分片索引将缓慢的测试套件拆分到 N 个 sandbox 中,并同时运行这些分片。
- 为每个任务提供独立的 sandbox。让 10 个 Agent 分别在自己的 sandbox 中工作,效果优于让 10 个任务在一台机器上排队。
- 根据预算限制并发量,而不是根据 API 允许的最大值。每个正在运行的 sandbox 都会产生费用。
- 大规模任务分发会受到 vCPU 分配速度的限制。空闲的 Pro 团队初始速度为每分钟 150 个 vCPU(相当于 18 个配备 8 个 vCPU 的 sandbox),并会随着持续使用而提升;Hobby 每分钟可分配 20 到 40 个。
Separate pre-existing failures from new ones
区分既有故障与新故障
A remote suite usually has some failures that have nothing to do with your change: environment differences, flaky tests, failures already on main.
- Run the failing tests again on the untouched baseline tree in the same sandbox. Only failures that the baseline doesn't have are yours.
- Keep a short list of known environment-only failures next to your tooling, so nobody chases them again.
- While iterating, run focused checks. Run the full suite on the final candidate, not on every intermediate step.
远程测试套件通常存在一些与改动无关的故障:环境差异、不稳定测试,以及 main 分支上已经存在的故障。
- 在同一个 sandbox 中,对未改动的基线目录树重新运行失败的测试。只有基线中不存在的故障才属于本次改动。
- 在工具旁保留一份简短的环境专属已知故障列表,避免其他人重复排查。
- 迭代期间运行定向检查。只在最终候选版本上运行完整测试套件,不要在每个中间步骤都运行。
Authentication and scope
身份验证和范围
- Token: uses
vercel sandbox, then--token, thenVERCEL_AUTH_TOKEN, then yourVERCEL_TOKENsession. It falls back to avercel loginenvironment variable only when none of those is available. For CI or long-running automation, setVERCEL_OIDC_TOKEN.VERCEL_TOKEN - The standalone CLI reads
sandboxbut notVERCEL_AUTH_TOKEN, and it loadsVERCEL_TOKENfiles from the current directory. A.envpulled intoVERCEL_OIDC_TOKENtherefore takes precedence over your login there, and its project becomes the default scope..env.local - Team and project: sandboxes and their names belong to one project. (or
--scope) and--teamset it. Without them, the CLI uses the project in the token when it is an OIDC token, then the--projectin the current directory (from.vercel/project.json), then your default team and a project namedvercel link, which it creates if needed.vercel-sandbox-default-project - Pass and
--scopeexplicitly in scripts. Otherwise a script run from another directory works in a different project and can't see, reuse or clean up your sandboxes.--project
- Token:依次使用
vercel sandbox、--token、VERCEL_AUTH_TOKEN,然后是VERCEL_TOKEN会话。只有上述选项都不可用时,才会回退到vercel login环境变量。对于 CI 或长时间运行的自动化,请设置VERCEL_OIDC_TOKEN。VERCEL_TOKEN - 独立 CLI 读取
sandbox,但不读取VERCEL_AUTH_TOKEN;它会从当前目录加载VERCEL_TOKEN文件。因此,从.env加载的.env.local在该目录中优先于登录会话,其项目也会成为默认范围。VERCEL_OIDC_TOKEN - **团队和项目:**sandbox 及其名称归属于一个项目。可使用 (或
--scope)和--team设置。未指定时,CLI 会依次使用 OIDC token 中的项目、当前目录中的--project(来自.vercel/project.json),以及默认团队和名为vercel link的项目;如果后者不存在,则会按需创建。vercel-sandbox-default-project - 在脚本中显式传入 和
--scope。否则,从其他目录运行的脚本会作用于不同项目,并且无法查看、复用或清理自己的 sandbox。--project
Wrap it in one small script
封装成一个小脚本
A thin wrapper removes most mistakes and keeps agent instructions short. Save this as , make it executable, and set , and (and on Hobby):
sbxSBX_SCOPESBX_PROJECTSBX_OWNERSBX_VCPUS=4 SBX_TIMEOUT=45msh
#!/bin/sh一个轻量包装器可以消除大多数错误,并让 Agent 指令保持简洁。将其保存为 ,赋予执行权限,并设置 、 和 (在 Hobby 上还需设置 ):
sbxSBX_SCOPESBX_PROJECTSBX_OWNERSBX_VCPUS=4 SBX_TIMEOUT=45msh
#!/bin/shsbx: offload work to Vercel Sandboxes through vercel sandbox
.
vercel sandboxsbx: offload work to Vercel Sandboxes through vercel sandbox
.
vercel sandboxsbx create <name> new task sandbox from the base snapshot
sbx create <name> new task sandbox from the base snapshot
sbx push <name> <local-dir> <remote-dir> sync git-tracked and untracked files, keep node_modules
sbx push <name> <local-dir> <remote-dir> sync git-tracked and untracked files, keep node_modules
sbx exec <name> <script> run a shell script remotely, exit with its status
sbx exec <name> <script> run a shell script remotely, exit with its status
sbx get <name> <remote-file> <local-file>
sbx get <name> <remote-file> <local-file>
sbx put <name> <local-file> <remote-file>
sbx put <name> <local-file> <remote-file>
sbx rm <name>... permanently remove sandboxes
sbx rm <name>... permanently remove sandboxes
sbx clean remove every sandbox tagged with your owner tag
sbx clean remove every sandbox tagged with your owner tag
shellcheck disable=SC2016 # single-quoted scripts are expanded by the remote shell
shellcheck disable=SC2016 # single-quoted scripts are expanded by the remote shell
set -eu
: "${SBX_SCOPE:?set SBX_SCOPE to your team slug}"
: "${SBX_PROJECT:?set SBX_PROJECT to your project name}"
owner=${SBX_OWNER:-${USER:-agent}}
vcpus=${SBX_VCPUS:-8} # Pro maximum; Hobby allows 4
timeout=${SBX_TIMEOUT:-3h} # session length; Hobby allows 45m
exec_timeout=${SBX_EXEC_TIMEOUT:-2h}
sb() { # sb <subcommand> [args...]
sub=$1
shift
vercel sandbox "$sub" --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$@"
}
set -eu
: "${SBX_SCOPE:?set SBX_SCOPE to your team slug}"
: "${SBX_PROJECT:?set SBX_PROJECT to your project name}"
owner=${SBX_OWNER:-${USER:-agent}}
vcpus=${SBX_VCPUS:-8} # Pro maximum; Hobby allows 4
timeout=${SBX_TIMEOUT:-3h} # session length; Hobby allows 45m
exec_timeout=${SBX_EXEC_TIMEOUT:-2h}
sb() { # sb <subcommand> [args...]
sub=$1
shift
vercel sandbox "$sub" --scope "$SBX_SCOPE" --project "$SBX_PROJECT" "$@"
}
vercel sandbox exec
exits 0 even when the remote command fails, so the
vercel sandbox execvercel sandbox exec
exits 0 even when the remote command fails, so the
vercel sandbox execremote shell prints the script's exit status and remote() returns it.
remote shell prints the script's exit status and remote() returns it.
remote() { # remote <name> <script> [args...]
name=$1
script=$2
shift 2
log=$(mktemp)
sb exec --timeout "$exec_timeout" "$name" --
sh -c 'sh -c "$0" sh "$@"; echo "__sbx_exit=$?"' "$script" "$@" | tee "$log" code=$(sed -n 's/^__sbx_exit=//p' "$log" | tail -n 1) rm -f "$log" return "${code:-1}" }
sh -c 'sh -c "$0" sh "$@"; echo "__sbx_exit=$?"' "$script" "$@" | tee "$log" code=$(sed -n 's/^__sbx_exit=//p' "$log" | tail -n 1) rm -f "$log" return "${code:-1}" }
push() { # push <name> <local-dir> <remote-dir>
git -C "$2" rev-parse --is-inside-work-tree > /dev/null
tgz=$(mktemp)
(cd "$2" && git ls-files -z --cached --others --exclude-standard |
COPYFILE_DISABLE=1 tar -czf "$tgz" --null -T -)
sb copy "$tgz" "$1:$3.tgz"
rm -f "$tgz"
remote "$1" '
set -e
dest=$1
rm -rf "$dest.new"
mkdir -p "$dest.new"
tar -xzf "$dest.tgz" -C "$dest.new"
rm -f "$dest.tgz"
if [ -d "$dest" ]; then
(cd "$dest" && find . -maxdepth 4 -type d -name node_modules -prune -print) > "$dest.keep"
while IFS= read -r keep; do
[ -e "$dest.new/$keep" ] && continue
mkdir -p "$(dirname "$dest.new/$keep")"
mv "$dest/$keep" "$dest.new/$keep"
done < "$dest.keep"
rm -rf "$dest" "$dest.keep"
fi
mv "$dest.new" "$dest"' "$3" > /dev/null
}
cmd=${1:?usage: sbx create|push|exec|get|put|rm|clean ...}
shift
case "$cmd" in
create)
name=${1:?usage: sbx create <name>}
snapshot=${SBX_SNAPSHOT:-$(cat BASE_SNAPSHOT)}
sb create --name "$name" --non-persistent --snapshot "$snapshot"
--vcpus "$vcpus" --timeout "$timeout"
--tag "app=$SBX_PROJECT" --tag "owner=$owner" --silent echo "$name" ;; push) push "${1:?name}" "${2:?local dir}" "${3:?remote dir}" ;; exec) name=${1:?usage: sbx exec <name> <script>} shift remote "$name" "$*" ;; get) rm -f "${3:?local file}" sb copy "${1:?name}:${2:?remote file}" "$3" [ -f "$3" ] || { echo "sbx: could not copy $1:$2" >&2; exit 1; } ;; put) [ -f "${2:?local file}" ] || { echo "sbx: no such file: $2" >&2; exit 1; } sb copy "$2" "${1:?name}:${3:?remote file}" ;; rm) : "${1:?usage: sbx rm <name>...}" sb remove "$@" ;; clean) # shows 50 sandboxes per page; run again if more remain.
names=$(sb list --all --tag "owner=$owner" | awk 'NR > 1 && NF && $1 != "More" { print $1 }')
# shellcheck disable=SC2086 # one word per sandbox name
if [ -n "$names" ]; then sb remove $names; fi
;;
*)
echo "usage: sbx create|push|exec|get|put|rm|clean ..." >&2
exit 2
;;
esac
--vcpus "$vcpus" --timeout "$timeout"
--tag "app=$SBX_PROJECT" --tag "owner=$owner" --silent echo "$name" ;; push) push "${1:?name}" "${2:?local dir}" "${3:?remote dir}" ;; exec) name=${1:?usage: sbx exec <name> <script>} shift remote "$name" "$*" ;; get) rm -f "${3:?local file}" sb copy "${1:?name}:${2:?remote file}" "$3" [ -f "$3" ] || { echo "sbx: could not copy $1:$2" >&2; exit 1; } ;; put) [ -f "${2:?local file}" ] || { echo "sbx: no such file: $2" >&2; exit 1; } sb copy "$2" "${1:?name}:${3:?remote file}" ;; rm) : "${1:?usage: sbx rm <name>...}" sb remove "$@" ;; clean) #
listsbx clean
Typical agent session:
```sh
sbx create exp-parser
sbx push exp-parser . /vercel/sandbox/cand
sbx exec exp-parser 'cd /vercel/sandbox/cand && sh /vercel/sandbox/prepare.sh && npm test'
sbx get exp-parser /tmp/results.json ./results.json
sbx rm exp-parserDocument the workflow next to the wrapper (a short ): the snapshot ID, what the base contains, the prepare step, how to run the suite, and the known environment-only failures. Point every agent's instructions at that file.
SANDBOX.mdremote() { # remote <name> <script> [args...]
name=$1
script=$2
shift 2
log=$(mktemp)
sb exec --timeout "$exec_timeout" "$name" --
sh -c 'sh -c "$0" sh "$@"; echo "__sbx_exit=$?"' "$script" "$@" | tee "$log" code=$(sed -n 's/^__sbx_exit=//p' "$log" | tail -n 1) rm -f "$log" return "${code:-1}" }
sh -c 'sh -c "$0" sh "$@"; echo "__sbx_exit=$?"' "$script" "$@" | tee "$log" code=$(sed -n 's/^__sbx_exit=//p' "$log" | tail -n 1) rm -f "$log" return "${code:-1}" }
push() { # push <name> <local-dir> <remote-dir>
git -C "$2" rev-parse --is-inside-work-tree > /dev/null
tgz=$(mktemp)
(cd "$2" && git ls-files -z --cached --others --exclude-standard |
COPYFILE_DISABLE=1 tar -czf "$tgz" --null -T -)
sb copy "$tgz" "$1:$3.tgz"
rm -f "$tgz"
remote "$1" '
set -e
dest=$1
rm -rf "$dest.new"
mkdir -p "$dest.new"
tar -xzf "$dest.tgz" -C "$dest.new"
rm -f "$dest.tgz"
if [ -d "$dest" ]; then
(cd "$dest" && find . -maxdepth 4 -type d -name node_modules -prune -print) > "$dest.keep"
while IFS= read -r keep; do
[ -e "$dest.new/$keep" ] && continue
mkdir -p "$(dirname "$dest.new/$keep")"
mv "$dest/$keep" "$dest.new/$keep"
done < "$dest.keep"
rm -rf "$dest" "$dest.keep"
fi
mv "$dest.new" "$dest"' "$3" > /dev/null
}
cmd=${1:?usage: sbx create|push|exec|get|put|rm|clean ...}
shift
case "$cmd" in
create)
name=${1:?usage: sbx create <name>}
snapshot=${SBX_SNAPSHOT:-$(cat BASE_SNAPSHOT)}
sb create --name "$name" --non-persistent --snapshot "$snapshot"
--vcpus "$vcpus" --timeout "$timeout"
--tag "app=$SBX_PROJECT" --tag "owner=$owner" --silent echo "$name" ;; push) push "${1:?name}" "${2:?local dir}" "${3:?remote dir}" ;; exec) name=${1:?usage: sbx exec <name> <script>} shift remote "$name" "$*" ;; get) rm -f "${3:?local file}" sb copy "${1:?name}:${2:?remote file}" "$3" [ -f "$3" ] || { echo "sbx: could not copy $1:$2" >&2; exit 1; } ;; put) [ -f "${2:?local file}" ] || { echo "sbx: no such file: $2" >&2; exit 1; } sb copy "$2" "${1:?name}:${3:?remote file}" ;; rm) : "${1:?usage: sbx rm <name>...}" sb remove "$@" ;; clean) # shows 50 sandboxes per page; run again if more remain.
names=$(sb list --all --tag "owner=$owner" | awk 'NR > 1 && NF && $1 != "More" { print $1 }')
# shellcheck disable=SC2086 # one word per sandbox name
if [ -n "$names" ]; then sb remove $names; fi
;;
*)
echo "usage: sbx create|push|exec|get|put|rm|clean ..." >&2
exit 2
;;
esac
--vcpus "$vcpus" --timeout "$timeout"
--tag "app=$SBX_PROJECT" --tag "owner=$owner" --silent echo "$name" ;; push) push "${1:?name}" "${2:?local dir}" "${3:?remote dir}" ;; exec) name=${1:?usage: sbx exec <name> <script>} shift remote "$name" "$*" ;; get) rm -f "${3:?local file}" sb copy "${1:?name}:${2:?remote file}" "$3" [ -f "$3" ] || { echo "sbx: could not copy $1:$2" >&2; exit 1; } ;; put) [ -f "${2:?local file}" ] || { echo "sbx: no such file: $2" >&2; exit 1; } sb copy "$2" "${1:?name}:${3:?remote file}" ;; rm) : "${1:?usage: sbx rm <name>...}" sb remove "$@" ;; clean) #
listsbx clean
典型的 Agent 会话:
```sh
sbx create exp-parser
sbx push exp-parser . /vercel/sandbox/cand
sbx exec exp-parser 'cd /vercel/sandbox/cand && sh /vercel/sandbox/prepare.sh && npm test'
sbx get exp-parser /tmp/results.json ./results.json
sbx rm exp-parser在包装器旁记录该工作流(一份简短的 ):snapshot ID、基础 snapshot 包含的内容、准备步骤、运行测试套件的方式,以及已知仅由环境导致的故障。让每个 Agent 的说明都指向该文件。
SANDBOX.mdPitfalls
常见陷阱
- False success: exits 0 when the remote command fails. Read the printed exit status, or use
vercel sandbox exec.sbx exec - OOM: big compiles can be killed. A remote exit status of 137 means the process got SIGKILL, usually from the OOM killer. Size up within your plan, or lower parallelism at the maximum, rather than retrying blindly.
- Lost work at the session timeout: a non-persistent sandbox discards its filesystem when the session stops. Copy results out before the timeout, and set the timeout for the whole task.
- Leftover sandboxes: doesn't free a sandbox's name or delete it. Use
stop, and sweep withremove.list --all - Stale snapshot: tasks that start from an old base can hit toolchain-version mismatches. Rebuild the snapshot, or refresh the tools in the task sandbox, when versions change.
- Shared sandboxes: two agents in one sandbox corrupt each other's trees. One owner per sandbox.
- Quotas mid-run: on Hobby, sandbox creation pauses once the monthly allotment is used up, and on Pro a Spend Management limit can pause projects. Commit work in small steps, write results to disk as you go, and keep scripts idempotent, so a replacement agent can resume instead of starting over.
- **误报成功:**远程命令失败时,仍会退出 0。应读取打印出的退出状态,或者使用
vercel sandbox exec。sbx exec - **OOM:**大型编译可能会被终止。远程退出状态为 137 表示进程收到了 SIGKILL,通常是 OOM killer 所致。应在套餐限制内提高规格,或在达到上限时降低并行度,而不是盲目重试。
- **会话超时导致工作丢失:**非持久化 sandbox 会在会话停止时丢弃文件系统。应在超时前取回结果,并根据整个任务设置超时。
- 遗留 sandbox:不会释放 sandbox 名称或删除它。应使用
stop,并通过remove进行清理。list --all - **过期 snapshot:**从旧基础 snapshot 启动的任务可能遇到工具链版本不匹配。版本发生变化时,应重建 snapshot,或在任务 sandbox 中刷新工具。
- **共享 sandbox:**两个 Agent 使用同一个 sandbox 会互相破坏目录树。每个 sandbox 应只有一个所有者。
- **运行中触发配额限制:**在 Hobby 上,月度配额用尽后,sandbox 创建会暂停;在 Pro 上,Spend Management 限制可能会暂停项目。应将工作拆成小步骤提交,随时将结果写入磁盘,并让脚本具备幂等性,使替代 Agent 能够继续工作,而不是从头开始。