Model one Vercel Sandbox per workflow run — durable, idle-efficient, and not bound by the 5-hour sandbox hard cap.
Vercel Sandbox provides isolated code execution environments. The @vercel/sandbox package has first-class support for the Workflow SDK — the Sandbox class is serializable, and its methods (create, runCommand, stop, snapshot) implicitly run as steps. You can use Sandbox directly inside a workflow function without wrapping each call in a separate "use step" function.
A sandbox alone gets you an isolated VM. A workflow around it gets you a durable controller for that VM's entire lifetime:
- One workflow run = one sandbox session. The
runIdis the only state you need to persist on the client. Close the tab, come back a week later, POST the samerunIdand you're back in the same session. - Efficient resource use. Active sandboxes cost money; hibernated workflows cost nothing. The workflow races a command hook against a
sleep()timer — when idle, it callssandbox.snapshot()(which also stops the VM) and waits indefinitely. Next command → spin a new sandbox from the snapshot with filesystem, installed packages, and git history intact. - Beyond the 5-hour hard cap. Every Vercel Sandbox has a maximum lifetime. The workflow tracks that deadline and proactively snapshots + recreates before the cap, so the logical session outlives any one VM. Effectively unbounded session duration on top of time-bounded infrastructure.
- Automatic cleanup.
try/finallyin the workflow guarantees the VM is stopped on failure or destroy.
An effectively unbounded sandbox session is still one workflow run, so it stays on the deployment that started it. If the controller or agent code should upgrade over time, use an explicit version boundary and pass the serialized state or stream handles forward. See Versioning.
This is the pattern Open Agents uses to spawn coding agents that run "infinitely in the cloud." Each agent session gets its own sandbox — full filesystem, network, and runtime access — and the durable workflow keeps the agent loop resumable across restarts, auto-hibernates when the user walks away, and reconnects instantly when they return.
Most coding-agent workloads look like this:
- User sends a task → agent plans, reads files, runs shell commands, commits.
- User walks away mid-run → agent keeps going, eventually goes idle waiting for input.
- User comes back days later → same branch, same filesystem, same conversation history.
Without durable workflows you'd need a separate state store for the agent loop, a separate job queue for retries, a separate scheduler for idle cleanup, and bespoke reconnection logic. With the pattern below, all of it is one file.
Before the full session pattern, the simplest shape. Each sandbox method is an implicit step, so the event log records every command and the workflow replays from the last completed call on restart.
import { Sandbox } from "@vercel/sandbox";
export async function sandboxPipeline(input: { commands: string[] }) {
"use workflow";
const sandbox = await Sandbox.create({ runtime: "node22" });
try {
const results = [];
for (const command of input.commands) {
const result = await sandbox.runCommand({
cmd: "bash",
args: ["-c", command],
});
results.push({
command,
exitCode: result.exitCode,
stdout: await result.stdout(),
stderr: await result.stderr(),
});
}
return { status: "completed", results };
} finally {
await sandbox.stop();
}
}One workflow run owns a sandbox for its whole lifetime. The workflow's loop does two jobs simultaneously:
- Command pipeline — await a hook, run the next user command, stream output, loop.
- Sandbox lifecycle — race the hook against a
sleep()timer armed for whichever comes first: the idle deadline or the sandbox's refresh deadline (a safety margin before its hard cap).
When the timer wins:
- Idle →
sandbox.snapshot()and wait indefinitely for the next command. No compute while asleep. - Near sandbox hard cap →
sandbox.snapshot()and immediately create a new sandbox from the snapshot. The session appears continuous; the underlying VM just rotated.
The only way out is an explicit /destroy command.
- One workflow = one session. The workflow owns a sandbox for its entire lifetime. The
runIdis the only state the client has to remember. - Hook created once.
commandHook.create({ token: workflowRunId })outside the loop. Creating it twice with the same token throwsHookConflictError. - Two timer branches. The active-state race wakes on the earlier of
idleDeadlineandrefreshDeadline. The hibernated state awaits the hook alone — no timer, no compute. - Proactive refresh.
refreshDeadline = sandboxExpiresAt - REFRESH_SAFETY_MS. Hitting this triggers a snapshot + immediate new sandbox from that snapshot, rolling over the hard cap without user intervention. sandbox.snapshot()stops the VM. It's documented as part of the snapshot process — don't callstop()separately.- Resume = new sandbox.
Sandbox.create({ source: { type: "snapshot", snapshotId } })creates a fresh VM from the snapshot. The new sandbox has a differentsandboxId; filesystem, installed packages, and git history are preserved. - Reconnect by runId.
getRun(runId).getReadable({ startIndex: 0 })replays the durable event log to a returning client, who rebuilds UI state from the replay. - Exit only on
/destroy. The workflow loop has no hard deadline of its own. Individual sandboxes time out; the session doesn't.
sandbox.stop() is terminal
A stopped sandbox cannot be restarted — you have to create a new one. Hibernation is only possible via snapshot() + new-sandbox-from-snapshot. Don't try to "pause" an active sandbox with stop() and resume later.
snapshot() already stops the VM
Calling stop() after snapshot() either errors or is a no-op depending on timing. Snapshot takes care of it.
New sandboxId after resume and refresh
Both resuming (idle → command) and refreshing (near-hard-cap rotation) create a new sandbox with a new sandboxId. Emit it on the subsequent status: "active" event and have the UI read from there, not from the initial created event.
Keep the refresh margin generous
snapshot() + Sandbox.create({ source }) takes real time (typically tens of seconds). If REFRESH_SAFETY_MS is too small, the old sandbox hits its hard cap mid-snapshot. Leave at least 60–90 seconds; 5 minutes is comfortable.
Don't call writable.close() inside a workflow function
Stream closure must happen inside a "use step" function. Calling writable.close() directly in the workflow body throws Not supported in workflow functions. The runtime closes the underlying writable when the workflow returns.
Handle stale runId gracefully
Clients can hold runIds from long-gone workflow runs (localStorage, back button, server restart). Gate the reconnect path on run.exists and fall through to starting fresh. On hook.resume, catch not found / expired and return 410 so the client clears its state.
Keep the hook outside the loop
Each iteration's hook.then(...) attaches a listener to the same hook instance. Creating a new hook per iteration with the same token throws HookConflictError. One hook, one token (workflowRunId), reused every iteration.
Sandbox.create— provision a VM (runtime, source, timeout)sandbox.runCommand— execute a command; implicit stepsandbox.snapshot— save state and stop the VM; returnsSnapshotdefineHook()— suspension point for user commandssleep()— durable timer that powers both idle hibernation and proactive refreshgetRun()— look up a run and replay its event log for reconnectiongetWritable()— resumable NDJSON event stream













