offload-to-sandbox

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Offloading 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
vercel sandbox
CLI. For the
@vercel/sandbox
SDK and running untrusted code, see the
vercel-sandbox
skill.
Vercel Sandbox 是一种 Linux microVM(x86_64),只需几秒即可创建,并可在使用完成后删除。因此,它非常适合作为远程 worker:将重型构建和长时间运行的测试套件留在笔记本电脑之外,并为每个 Agent 或任务提供一台干净的机器。本 skill 介绍如何通过
vercel sandbox
CLI 高效完成这些工作。有关
@vercel/sandbox
SDK 和运行不可信代码,请参阅
vercel-sandbox
skill。

When 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,
    git
    , small focused tests, type checks and lint, and orchestration.
  • 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)。
应保留在本地:
  • 编辑、
    git
    、小型定向测试、类型检查和 lint,以及编排工作。
  • 需要本地凭据或 sandbox 不具备的硬件的任何工作。
当多个 Agent 共享一台机器时,一个很好的默认做法是:Agent 在本地编辑并运行快速、定向的检查,而所有重型工作都转移到各自的 sandbox。

Plan limits

套餐限制

HobbyProEnterprise
Max vCPUs (2 GB memory each)4 (8 GB)8 (16 GB)32 (64 GB)
Max session duration45 minutes24 hours24 hours
Concurrent sandboxes1010,00010,000
--vcpus
takes 1 or an even number up to your plan's maximum; the default is 2. The examples below use Pro sizes (
--vcpus 8
,
--timeout 3h
). On Hobby, use
--vcpus 4
and a timeout of
45m
or less. Hobby also includes only 5 hours of Active CPU a month, so heavy offloading realistically needs Pro.
Running sandboxes are billed for Active CPU and provisioned memory. Snapshots are billed as Snapshot Storage per GB-month for as long as they exist.
HobbyProEnterprise
最大 vCPU 数(每个 2 GB 内存)4(8 GB)8(16 GB)32(64 GB)
最长会话时长45 分钟24 小时24 小时
并发 sandbox 数量1010,00010,000
--vcpus
可取 1 或不超过套餐上限的偶数,默认值为 2。下面的示例使用 Pro 规格(
--vcpus 8
、
--timeout 3h
)。在 Hobby 上,应使用
--vcpus 4
,并将超时设置为
45m
或更短。Hobby 每月仅包含 5 小时 Active CPU,因此要真正实现重型工作卸载,实际需要使用 Pro。
运行中的 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
undefined

1. 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
    ,
    exp-parser-2
    ) so parallel agents never collide. Names are unique per project and stay taken until the sandbox is removed. Never use another agent's sandbox.
  • 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
    、
    exp-parser-2
    ),以免并行 Agent 发生冲突。名称在项目内唯一,并且会持续占用,直到 sandbox 被移除。绝不要使用其他 Agent 的 sandbox。
  • **规格:**每个 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
create
here passes
--non-persistent
.
  • --timeout
    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.
    vercel sandbox config timeout <name> <duration>
    changes it later, and a higher value also extends the running session.
  • vercel sandbox remove <name>
    when a task is done.
    vercel sandbox stop
    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.
  • Removing a sandbox does not delete snapshots, so the base snapshot survives task cleanup.
    --delete-orphan-snapshots
    on
    remove
    also deletes the sandbox's own snapshots that no other sandbox uses. Don't pass it when removing the builder that made your base snapshot.
  • Sweep orphans from crashed agents with
    vercel sandbox list --all --tag owner=<agent>
    .
    --all
    includes stopped sandboxes (the default shows only running ones), and
    list
    filters by one tag at a time. Remove everything it shows with
    vercel sandbox remove <name>...
    . Sweep the whole project (
    --tag app=my-project
    ) only when no agent is still working.
Sandbox 默认是持久化的:会话停止时,文件系统会被 snapshot,之后可以恢复该 sandbox,并且该 snapshot 按 Snapshot Storage 计费。任务 sandbox 不需要此功能,因此这里的每个
create
都传入了
--non-persistent
。
  • **
    --timeout
    设置的是会话长度,而不是 sandbox 的生命周期。**默认值为 5 分钟。超时后,会话停止,其中正在运行的所有内容都会被终止,包括分离作业。非持久化 sandbox 会在此时丢失整个文件系统。应根据整个任务设置超时。
    vercel sandbox config timeout <name> <duration>
    可以稍后修改它,更大的值也会延长正在运行的会话。
  • 任务完成后,使用
    vercel sandbox remove <name>
    。
    vercel sandbox stop
    仅结束当前会话:sandbox 会保留名称,持久化 sandbox 也会继续为其 snapshot 计费。Vercel 会移除闲置 14 天后无法恢复的 sandbox,因此已停止的非持久化 sandbox 在此之前仍会占用名称,除非将其移除。
  • 移除 sandbox 不会删除 snapshot,因此基础 snapshot 可以在任务清理后继续存在。在
    remove
    时使用
    --delete-orphan-snapshots
    ,还会删除没有被其他 sandbox 使用的该 sandbox 自身 snapshot。移除用于创建基础 snapshot 的 builder 时,不要传入此参数。
  • 使用
    vercel sandbox list --all --tag owner=<agent>
    清理崩溃 Agent 留下的孤立资源。
    --all
    包含已停止的 sandbox(默认仅显示正在运行的 sandbox),而
    list
    每次只能按一个 tag 过滤。使用
    vercel sandbox remove <name>...
    移除其显示的所有内容。只有在没有任何 Agent 仍在工作时,才按项目清理(
    --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 (
node_modules
) from the old tree into the new one so they don't need reinstalling, and swap the two.
sbx push
in the wrapper script does exactly this:
bash
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
    .git
    or dependency directories. If you need git history remotely, push a bundle or
    git clone
    inside the sandbox.
  • A tracked file you deleted but didn't stage makes
    tar
    fail. Stage the deletion (
    git rm
    ) first.
应传输源代码,而不是构建产物。将 Git 已知文件(已跟踪和未跟踪但未忽略的文件)打包成一个 tarball,复制后解压到旧目录树旁边。然后将大型目录(
node_modules
)从旧目录树移入新目录树,再交换两者。包装脚本中的
sbx push
正是这样做的:
bash
sbx push exp-parser . /vercel/sandbox/cand
  • 每次更改后都应推送,只需几秒。然后运行具备幂等性的准备步骤,仅安装或重新构建发生变化的依赖(例如,仅在 lockfile 发生变化时安装依赖)。
  • 在 sandbox 内构建特定平台的产物。不要将 macOS 二进制文件复制到 Linux VM 中。
  • 不要推送
    .git
    或依赖目录。如果需要在远端保留 Git 历史,请推送 bundle,或在 sandbox 内执行
    git clone
    。
  • 如果已删除某个已跟踪文件但尚未暂存,
    tar
    会失败。请先暂存该删除操作(
    git rm
    )。

Read, write, and copy files directly

直接读取、写入和复制文件

The standalone
sandbox
CLI supports file commands in releases containing vercel/sandbox#380. Install or update it with
npm i -g sandbox
, then check the installed commands before using the examples:
bash
sandbox --version
sandbox read --help
sandbox write --help
sandbox copy --help
Confirm that
read
and
write
exist and that
copy --help
lists
--recursive
. If they are unavailable, keep using
vercel sandbox copy
and the
sbx
wrapper below. The Vercel CLI bundles its own Sandbox CLI version, so support in
sandbox
does not establish support in
vercel sandbox
.
Use the same team and project as the existing task sandbox. Set
SBX_SCOPE
and
SBX_PROJECT
as described in Authentication and scope; the standalone CLI must also be authenticated.
bash
name=exp-parser
: "${SBX_SCOPE:?set SBX_SCOPE to your team slug}"
: "${SBX_PROJECT:?set SBX_PROJECT to your project name}"
独立
sandbox
CLI 在包含 vercel/sandbox#380 的版本中支持文件命令。使用
npm i -g sandbox
安装或更新它,然后在使用以下示例前检查已安装的命令:
bash
sandbox --version
sandbox read --help
sandbox write --help
sandbox copy --help
确认
read
和
write
命令存在,并且
copy --help
列出了
--recursive
。如果这些功能不可用,请继续使用
vercel sandbox copy
和下方的
sbx
包装脚本。Vercel CLI 捆绑了自己的 Sandbox CLI 版本,因此
sandbox
支持某项功能并不代表
vercel sandbox
也支持。
使用与现有任务 sandbox 相同的团队和项目。按照身份验证和范围中的说明设置
SBX_SCOPE
和
SBX_PROJECT
;独立 CLI 也必须完成身份验证。
bash
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
    sh -c
    . Your local shell otherwise expands
    $VARS
    and globs before the sandbox sees them. zsh in particular errors on unmatched globs and treats
    $var:r
    ,
    $var:h
    and similar as modifiers; use
    ${var}
    .
  • Check the bundled CLI's exit behavior. With
    vercel
    64.5.0 (Sandbox CLI 4.4.0),
    vercel sandbox exec
    exits 0 even when the remote command fails. On that version, end the remote command with
    echo "exit=$?"
    and read that, or use
    sbx exec
    , which returns the remote status. The standalone Sandbox CLI (
    npm i -g sandbox
    , then
    sandbox exec ...
    ) does pass the remote exit code through.
  • For anything longer than a line, write a script locally,
    vercel sandbox copy
    it in, and run it. That is easier to quote, review and rerun.
  • exec --timeout
    is optional and has no default. When it expires, the command is killed with SIGKILL and the CLI prints
    Command was killed (SIGKILL, exit code 137)
    . Without it, a command runs until it finishes or the session times out.
  • 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=$?"'
  • 将整个命令作为单个单引号字符串传给
    sh -c
    。否则,本地 shell 会在 sandbox 看到命令之前展开
    $VARS
    和 glob。尤其是 zsh 会因未匹配的 glob 而报错,并将
    $var:r
    、
    $var:h
    等视为修饰符;应使用
    ${var}
    。
  • **检查捆绑 CLI 的退出行为。**在
    vercel
    64.5.0(Sandbox CLI 4.4.0)中,即使远程命令失败,
    vercel sandbox exec
    也会退出 0。在该版本中,应让远程命令以
    echo "exit=$?"
    结尾并读取结果,或者使用
    sbx exec
    ,后者会返回远程状态。独立 Sandbox CLI(
    npm i -g sandbox
    ,然后执行
    sandbox exec ...
    )会正确透传远程退出码。
  • 对于超过一行的内容,应在本地编写脚本,通过
    vercel sandbox copy
    复制进去,然后运行。这样更便于处理引号、审查和重新执行。
  • exec --timeout
    是可选参数,并且没有默认值。超时时,命令会收到 SIGKILL,CLI 会打印
    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 --help
Confirm that
exec
lists
--detach
and
--stdin
, and that
commands
lists
get
,
logs
,
wait
, and
kill
. Check these independently of the file commands above: CLI releases may support command management before
read
,
write
, and recursive copy. The Vercel CLI bundles its own Sandbox CLI version.
Start 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"
get
checks status without waiting.
logs
streams stdout and stderr until the command exits; use it when you want to watch the task.
wait
returns the remote exit status, so use it to decide whether the task passed. Keep the sandbox name and command ID when returning to the job from another terminal.
To 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
确认
exec
列出了
--detach
和
--stdin
,并且
commands
列出了
get
、
logs
、
wait
和
kill
。请将这些检查与上述文件命令分开进行:CLI 版本可能在支持命令管理后,才支持
read
、
write
和递归复制。Vercel CLI 捆绑了自己的 Sandbox CLI 版本。
在现有 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"
get
无需等待即可检查状态。
logs
会持续流式传输 stdout 和 stderr,直到命令退出;需要实时观察任务时可以使用它。
wait
会返回远程退出状态,可据此判断任务是否通过。从其他终端返回任务时,请保留 sandbox 名称和 command ID。
要取消仍在运行的任务,请使用保存的 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
--stdin
:
bash
printf 'hello\n' | sandbox exec --scope "$SBX_SCOPE" --project "$SBX_PROJECT" --stdin "$name" -- cat
This prints
hello
. The CLI forwards input and closes the remote stdin when the local input ends. Use
--stdin
for pipes and scripts; it cannot be combined with
--interactive
. For detached input,
exec --detach --stdin
keeps stdin open for later
commands write
calls; finish with
commands close-stdin
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.
对于读取输入后结束的命令,请使用
--stdin
:
bash
printf 'hello\n' | sandbox exec --scope "$SBX_SCOPE" --project "$SBX_PROJECT" --stdin "$name" -- cat
这会打印
hello
。CLI 会转发输入,并在本地输入结束时关闭远程 stdin。将
--stdin
用于管道和脚本;它不能与
--interactive
结合使用。对于分离输入,
exec --detach --stdin
会保持 stdin 打开,以供后续调用
commands write
;在等待需要输入结束的程序之前,使用
commands close-stdin
结束输入。每次写入完成后,再开始下一次写入。将命令日志视为文本;二进制产物应使用文件传输。

Fall back on older CLI versions

回退到较旧的 CLI 版本

If native command management is unavailable, use the existing
sbx exec
wrapper for exit-status handling. For long jobs, keep the status-file approach below. The sandbox session timeout must cover the whole job:
bash
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 &'
如果原生命令管理功能不可用,请使用现有的
sbx exec
包装脚本处理退出状态。对于长任务,请保留下面的状态文件方案。Sandbox 会话超时必须覆盖整个作业:
bash
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'
undefined
vercel sandbox exec --timeout 30s exp-parser -- sh -c 'cat /tmp/test.status 2>/dev/null || tail -3 /tmp/test.log'
undefined

Get 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
    vercel sandbox copy exp-parser:/tmp/results.json ./results/results.json
    . With the bundled CLI described here,
    copy
    moves one file per call and needs a full destination file path. For a whole result directory, use standalone recursive copy when available.
  • On that older bundled CLI, a missing source file makes
    copy
    print an error without failing, so check that the local file exists afterwards (
    sbx get
    does).
  • Compress large logs remotely and only fetch them when needed. Streaming megabytes of output through
    exec
    is slow and wastes context when an agent reads it.
  • 让远程端写入紧凑的结果文件(失败测试名称摘要、退出码、JSON 报告),然后仅使用
    vercel sandbox copy exp-parser:/tmp/results.json ./results/results.json
    取回这些文件。对于这里介绍的捆绑 CLI,
    copy
    每次只移动一个文件,并且需要提供完整的目标文件路径。如需获取整个结果目录,请在支持时使用独立递归复制。
  • 在较旧的捆绑 CLI 中,源文件不存在时,
    copy
    会打印错误但不会失败,因此之后应检查本地文件是否存在(
    sbx get
    会执行此检查)。
  • 在远程压缩大型日志,仅在需要时获取。通过
    exec
    流式传输数 MB 输出速度较慢,而且 Agent 读取时会浪费大量上下文。

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:
    vercel sandbox
    uses
    --token
    , then
    VERCEL_AUTH_TOKEN
    , then
    VERCEL_TOKEN
    , then your
    vercel login
    session. It falls back to a
    VERCEL_OIDC_TOKEN
    environment variable only when none of those is available. For CI or long-running automation, set
    VERCEL_TOKEN
    .
  • The standalone
    sandbox
    CLI reads
    VERCEL_AUTH_TOKEN
    but not
    VERCEL_TOKEN
    , and it loads
    .env
    files from the current directory. A
    VERCEL_OIDC_TOKEN
    pulled into
    .env.local
    therefore takes precedence over your login there, and its project becomes the default scope.
  • Team and project: sandboxes and their names belong to one project.
    --scope
    (or
    --team
    ) and
    --project
    set it. Without them, the CLI uses the project in the token when it is an OIDC token, then the
    .vercel/project.json
    in the current directory (from
    vercel link
    ), then your default team and a project named
    vercel-sandbox-default-project
    , which it creates if needed.
  • Pass
    --scope
    and
    --project
    explicitly in scripts. Otherwise a script run from another directory works in a different project and can't see, reuse or clean up your sandboxes.
  • Token:
    vercel sandbox
    依次使用
    --token
    、
    VERCEL_AUTH_TOKEN
    、
    VERCEL_TOKEN
    ,然后是
    vercel login
    会话。只有上述选项都不可用时,才会回退到
    VERCEL_OIDC_TOKEN
    环境变量。对于 CI 或长时间运行的自动化,请设置
    VERCEL_TOKEN
    。
  • 独立
    sandbox
    CLI 读取
    VERCEL_AUTH_TOKEN
    ,但不读取
    VERCEL_TOKEN
    ;它会从当前目录加载
    .env
    文件。因此,从
    .env.local
    加载的
    VERCEL_OIDC_TOKEN
    在该目录中优先于登录会话,其项目也会成为默认范围。
  • **团队和项目:**sandbox 及其名称归属于一个项目。可使用
    --scope
    (或
    --team
    )和
    --project
    设置。未指定时,CLI 会依次使用 OIDC token 中的项目、当前目录中的
    .vercel/project.json
    (来自
    vercel link
    ),以及默认团队和名为
    vercel-sandbox-default-project
    的项目;如果后者不存在,则会按需创建。
  • 在脚本中显式传入
    --scope
    和
    --project
    。否则,从其他目录运行的脚本会作用于不同项目,并且无法查看、复用或清理自己的 sandbox。

Wrap it in one small script

封装成一个小脚本

A thin wrapper removes most mistakes and keeps agent instructions short. Save this as
sbx
, make it executable, and set
SBX_SCOPE
,
SBX_PROJECT
and
SBX_OWNER
(and
SBX_VCPUS=4 SBX_TIMEOUT=45m
on Hobby):
sh
#!/bin/sh
一个轻量包装器可以消除大多数错误,并让 Agent 指令保持简洁。将其保存为
sbx
,赋予执行权限,并设置
SBX_SCOPE
、
SBX_PROJECT
和
SBX_OWNER
(在 Hobby 上还需设置
SBX_VCPUS=4 SBX_TIMEOUT=45m
):
sh
#!/bin/sh

sbx: offload work to Vercel Sandboxes through
vercel sandbox
.

sbx: offload work to Vercel Sandboxes through
vercel sandbox
.

sbx 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 exec
exits 0 even when the remote command fails, so the

remote 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}" }
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) #
list
shows 50 sandboxes per page; run
sbx clean
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

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-parser
Document the workflow next to the wrapper (a short
SANDBOX.md
): 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.
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}" }
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) #
list
shows 50 sandboxes per page; run
sbx clean
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

典型的 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
在包装器旁记录该工作流(一份简短的
SANDBOX.md
):snapshot ID、基础 snapshot 包含的内容、准备步骤、运行测试套件的方式,以及已知仅由环境导致的故障。让每个 Agent 的说明都指向该文件。

Pitfalls

常见陷阱

  • False success:
    vercel sandbox exec
    exits 0 when the remote command fails. Read the printed exit status, or use
    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:
    stop
    doesn't free a sandbox's name or delete it. Use
    remove
    , and sweep with
    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.
  • **误报成功:**远程命令失败时,
    vercel sandbox exec
    仍会退出 0。应读取打印出的退出状态,或者使用
    sbx exec
    。
  • **OOM:**大型编译可能会被终止。远程退出状态为 137 表示进程收到了 SIGKILL,通常是 OOM killer 所致。应在套餐限制内提高规格,或在达到上限时降低并行度,而不是盲目重试。
  • **会话超时导致工作丢失:**非持久化 sandbox 会在会话停止时丢弃文件系统。应在超时前取回结果,并根据整个任务设置超时。
  • 遗留 sandbox:
    stop
    不会释放 sandbox 名称或删除它。应使用
    remove
    ,并通过
    list --all
    进行清理。
  • **过期 snapshot:**从旧基础 snapshot 启动的任务可能遇到工具链版本不匹配。版本发生变化时,应重建 snapshot,或在任务 sandbox 中刷新工具。
  • **共享 sandbox:**两个 Agent 使用同一个 sandbox 会互相破坏目录树。每个 sandbox 应只有一个所有者。
  • **运行中触发配额限制:**在 Hobby 上,月度配额用尽后,sandbox 创建会暂停;在 Pro 上,Spend Management 限制可能会暂停项目。应将工作拆成小步骤提交,随时将结果写入磁盘,并让脚本具备幂等性,使替代 Agent 能够继续工作,而不是从头开始。