
Vercel Sandbox 现在会在沙箱会话就绪、即将超时或被停止时发送 webhook。你可以利用这些通知来更新应用状态、决定是否延长 agent 会话,或触发清理。
在团队的 webhook 设置中订阅 sandbox.session.started、sandbox.session.expiring 和 sandbox.session.stopped。每个事件都包含沙箱和会话详情,因此你的后端可以识别受影响的会话。stopped 事件包含停止原因(requested、snapshot、timeout、exited 或 error)以及会话时长、活跃 CPU 时间和网络传输量。
Vercel 会在会话超时前 1 分钟发送 sandbox.session.expiring,或在 expiryNotificationLeadTime 配置的时间发送。每次延长会话后,你都会在新的超时时间前 1 分钟收到新的警告。
在已验证的 webhook 处理程序中,检查已停止的会话:
if (event.type === 'sandbox.session.stopped') { const { id, stopReason, activeCpuDurationMs, networkTransfer } = event.payload.session; console.log({ id, stopReason, activeCpuDurationMs, networkTransfer });}
一个事件可能被投递多次,因此处理程序应以会话 ID 作为键,对于 expiring 事件则以 sandbox.expiresAt 作为键。
Agent 可以通过 Vercel MCP 订阅相同的事件。创建沙箱的 agent 可以监听 sandbox.session.expiring,并调用 extend_session_timeout 以保持会话运行。
Copy link to headingKeep agent sessions running with Sandbox lifecycle events and Workflow SDK
工作流可以等待生命周期事件,并在 agent 仍在工作时延长其沙箱会话,而无需轮询。
export const sandboxEvents = defineHook<SandboxSessionEvent>();
export async function agentTask(taskId: string, sandboxName: string) { 'use workflow'; const sandboxHook = sandboxEvents.create({ token: sandboxName }); for await (const { type } of sandboxHook) { if (type === 'sandbox.session.expiring' && (await isAgentWorking(taskId))) { await extendSession(sandboxName, ms('10m')); } if (type === 'sandbox.session.stopped') break; }}
将生命周期钩子与 Vercel Workflows 配合使用
在 Sandbox lifecycle webhooks 文档中了解更多。