Update to Vercel
Snapshot Oct 6, 2026 · 18:03 UTC · version 0.54.1
Collection source: downloaded plugin package. These snapshots do not have a confirmed matching collection source. Differences in file lists alone do not establish changes to the package.
Payment or plan references changed
Instruction wording changed from “DevKit (WDK) ” to “SDK ”. 324 additional added or edited lines are in the evidence.
Observed in published text. Live prices and checkout terms have not been verified by this change.
Product description
DevKit (WDK)
SDK
Skill instructions
DevKit (WDK) expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow. - "https://vercel.co...
SDK expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow. - "https://vercel.com/docs/wo...
Supporting files
[{"relative_path":"agents/openai.yaml","size_in_bytes":106},{"relative_path":"references/durable-agent-patterns.md","size_in_bytes":2522}]
[{"relative_path":"agents/openai.yaml","size_in_bytes":106}]
Compare saved observations
Download comparison JSONFull technical diff · 3 changed fields
changed /description
"Vercel Workflow DevKit (WDK) expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow."
"Vercel Workflow SDK expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow."
changed /included_files
[
{
"relative_path": "agents/openai.yaml",
"size_in_bytes": 106
},
{
"relative_path": "references/durable-agent-patterns.md",
"size_in_bytes": 2522
}
][
{
"relative_path": "agents/openai.yaml",
"size_in_bytes": 106
}
]changed /skill_md_contents
"---\nname: workflow\ndescription: Vercel Workflow DevKit (WDK) expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow.\nmetadata:\n priority: 9\n docs:\n - \"https://vercel.com/docs/workflow\"\n - \"https://useworkflow.dev\"\n sitemap: \"https://vercel.com/sitemap/docs.xml\"\n pathPatterns:\n - 'lib/workflow/**'\n - 'src/lib/workflow/**'\n - 'lib/workflow.*'\n - 'src/lib/workflow.*'\n - 'workflow.*'\n - '*workflow*'\n importPatterns:\n - '@vercel/workflow'\n - 'workflow'\n - '@workflow/*'\n - '*workflow*'\n bashPatterns:\n - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*@vercel/workflow\\b'\n - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*@vercel/workflow\\b'\n - '\\bbun\\s+(install|i|add)\\s+[^\\n]*@vercel/workflow\\b'\n - '\\byarn\\s+add\\s+[^\\n]*@vercel/workflow\\b'\n - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\bbun\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\byarn\\s+add\\s+[^\\n]*\\bworkflow\\b'\n - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\bbun\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\byarn\\s+add\\s+[^\\n]*@workflow/'\n - '\\bnpx\\s+workflow(?:@latest)?\\b'\n - '\\bbunx\\s+workflow(?:@latest)?\\b'\n promptSignals:\n phrases:\n # Direct workflow mentions\n - \"vercel workflow\"\n - \"workflow devkit\"\n - \"durable workflow\"\n - \"durable execution\"\n - \"durable function\"\n - \"durable pipeline\"\n - \"durable process\"\n - \"durable agent\"\n - \"durable chat\"\n - \"step function\"\n - \"step functions\"\n - \"use workflow\"\n - \"use step\"\n # Pipeline / multi-step language (the BIG gap — natural product prompts)\n - \"multi-step pipeline\"\n - \"multi step pipeline\"\n - \"multi-step process\"\n - \"multi step process\"\n - \"multi-step creation\"\n - \"multi-step generation\"\n - \"processing pipeline\"\n - \"creation pipeline\"\n - \"generation pipeline\"\n - \"content pipeline\"\n - \"production pipeline\"\n - \"approval pipeline\"\n - \"ingestion pipeline\"\n - \"streams progress\"\n - \"stream progress\"\n - \"streams each phase\"\n - \"streams each step\"\n - \"streams each\"\n - \"stream each\"\n # Reliability / durability language (missed in customer-support eval)\n - \"survive page reload\"\n - \"survive page reloads\"\n - \"survive a crash\"\n - \"survive crashes\"\n - \"survive network\"\n - \"fault-tolerant\"\n - \"fault tolerant\"\n - \"crash-safe\"\n - \"crash safe\"\n - \"automatically retry\"\n - \"auto retry\"\n - \"retry on failure\"\n - \"retry on error\"\n - \"reliable and retry\"\n - \"reliable processing\"\n - \"individually reliable\"\n - \"each step reliable\"\n - \"each step should be reliable\"\n - \"steps should be reliable\"\n - \"reliable with automatic retry\"\n - \"reliable with retry\"\n - \"retry on transient\"\n - \"transient failures\"\n - \"session persistence\"\n - \"session should persist\"\n - \"session survives\"\n - \"reconnect automatically\"\n - \"auto reconnect\"\n - \"reconnect if the network\"\n - \"reconnect on disconnect\"\n - \"resume after failure\"\n - \"resume after crash\"\n - \"resume on reconnect\"\n # Human-in-the-loop / approval patterns\n - \"human-in-the-loop\"\n - \"human in the loop\"\n - \"wait for approval\"\n - \"approval step\"\n - \"approval before\"\n - \"editorial approval\"\n - \"manual approval\"\n - \"wait for user\"\n - \"pause until\"\n - \"wait for response\"\n - \"callback url\"\n - \"webhook callback\"\n # Conversational AI with durability\n - \"chat should survive\"\n - \"chat survives\"\n - \"conversation should persist\"\n - \"conversation persists\"\n - \"conversation should survive\"\n # Sequential / chain / trigger orchestration language\n - \"sequential chain\"\n - \"email chain\"\n - \"chain of emails\"\n - \"chain of steps\"\n - \"chain engine\"\n - \"chain with triggers\"\n - \"trigger chain\"\n - \"triggered chain\"\n - \"webhook chain\"\n - \"webhook pipeline\"\n - \"webhook orchestration\"\n - \"multi-service trigger\"\n - \"cross-service trigger\"\n - \"various triggers\"\n - \"different triggers\"\n - \"triggers from different\"\n - \"triggers from various\"\n - \"sequential steps\"\n - \"sequential pipeline\"\n - \"sequential process\"\n - \"sequential emails\"\n - \"escalation chain\"\n - \"escalation pipeline\"\n - \"state machine\"\n - \"step-based\"\n - \"step based\"\n - \"delay between steps\"\n - \"delay between emails\"\n - \"delayed steps\"\n - \"conditional steps\"\n - \"skip steps\"\n - \"branch based on\"\n - \"wait for webhook\"\n - \"wait for trigger\"\n - \"wait for event\"\n - \"orchestrate emails\"\n - \"orchestrate webhooks\"\n - \"orchestrate services\"\n - \"chain across services\"\n # Debugging\n - \"workflow stuck\"\n - \"workflow hung\"\n - \"workflow hanging\"\n - \"workflow waiting\"\n - \"workflow failing\"\n - \"workflow timeout\"\n - \"workflow not running\"\n - \"workflow error\"\n - \"check workflow\"\n - \"workflow logs\"\n - \"workflow run status\"\n - \"debug workflow\"\n - \"workflow not finishing\"\n - \"workflow not responding\"\n - \"workflow stalled\"\n - \"workflow pending\"\n - \"step is stuck\"\n - \"step is hanging\"\n - \"why is my workflow\"\n - \"workflow run\"\n - \"step failed\"\n - \"run status\"\n - \"run failed\"\n - \"run logs\"\n - \"workflow run failed\"\n - \"workflow step failed\"\n allOf:\n - [workflow, durable]\n - [workflow, retry]\n - [workflow, resume]\n - [pause, resume]\n - [survive, crash]\n - [survive, reload]\n - [survive, disconnect]\n - [pipeline, stream]\n - [pipeline, step]\n - [pipeline, durable]\n - [pipeline, reliable]\n - [pipeline, retry]\n - [multi-step, stream]\n - [multi-step, reliable]\n - [generation, pipeline]\n - [creation, pipeline]\n - [process, stream]\n - [process, reliable]\n - [process, retry]\n - [retry, failure]\n - [retry, error]\n - [retry, automatically]\n - [retry, transient]\n - [reliable, retry]\n - [individually, reliable]\n - [steps, reliable]\n - [sandbox, reliable]\n - [sandbox, retry]\n - [reconnect, network]\n - [reconnect, drop]\n - [reconnect, disconnect]\n - [session, persist]\n - [session, survive]\n - [session, reload]\n - [session, reconnect]\n - [chat, survive]\n - [chat, persist]\n - [chat, reconnect]\n - [chat, durable]\n - [chat, fault]\n - [conversation, persist]\n - [conversation, survive]\n - [approval, wait]\n - [approval, human]\n - [each, step]\n - [each, phase]\n - [each, stage]\n - [step, reliable]\n - [step, retry]\n # Chain / trigger / sequential orchestration\n - [chain, trigger]\n - [chain, sequential]\n - [chain, email]\n - [chain, webhook]\n - [chain, delay]\n - [chain, step]\n - [chain, escalat]\n - [sequential, trigger]\n - [sequential, email]\n - [sequential, step]\n - [sequential, webhook]\n - [trigger, orchestrat]\n - [trigger, service]\n - [trigger, delay]\n - [trigger, sequential]\n - [webhook, chain]\n - [webhook, orchestrat]\n - [webhook, pipeline]\n - [webhook, sequential]\n - [email, trigger]\n - [email, pipeline]\n - [email, sequential]\n - [email, delay]\n - [email, escalat]\n - [escalat, trigger]\n - [escalat, step]\n - [escalat, email]\n - [state, machine]\n - [conditional, step]\n - [conditional, skip]\n - [branch, condition]\n - [wait, webhook]\n - [wait, trigger]\n - [wait, event]\n - [workflow, stuck]\n - [workflow, hung]\n - [workflow, timeout]\n - [workflow, error]\n - [workflow, logs]\n - [workflow, debug]\n - [workflow, check]\n - [workflow, failing]\n - [workflow, status]\n - [run, status]\n - [step, failed]\n - [step, stuck]\n - [step, timeout]\n - [workflow, run]\n - [run, logs]\n anyOf:\n - \"long-running\"\n - \"long running\"\n - \"multi-step\"\n - \"multi step\"\n - \"pipeline\"\n - \"orchestration\"\n - \"step-by-step\"\n - \"step by step\"\n - \"each piece\"\n - \"each step\"\n - \"each phase\"\n - \"each stage\"\n - \"phase\"\n - \"phases\"\n - \"stage\"\n - \"stages\"\n - \"durable\"\n - \"reliable\"\n - \"fault-tolerant\"\n - \"retry\"\n - \"reconnect\"\n - \"survive\"\n - \"persist\"\n - \"approval\"\n - \"chain\"\n - \"sequential\"\n - \"trigger\"\n - \"webhook\"\n - \"escalation\"\n - \"state machine\"\n - \"orchestrate\"\n - \"orchestration\"\n noneOf:\n - \"github actions\"\n - \".github/workflows\"\n - \"ci workflow\"\n - \"aws step functions\"\n minScore: 4\n---\n\n## *CRITICAL*: Always Use Correct `workflow` Documentation\n\nYour knowledge of `workflow` is outdated.\n\nThe `workflow` documentation outlined below matches the installed version of the Workflow DevKit.\nFollow these instructions before starting on any `workflow`-related tasks:\n\nSearch the bundled documentation in `node_modules/workflow/docs/`:\n\n1. **Find docs**: `glob \"node_modules/workflow/docs/**/*.mdx\"`\n2. **Search content**: `grep \"your query\" node_modules/workflow/docs/`\n\nDocumentation structure in `node_modules/workflow/docs/`:\n\n- `getting-started/` - Framework setup (next.mdx, express.mdx, hono.mdx, etc.)\n- `foundations/` - Core concepts (workflows-and-steps.mdx, hooks.mdx, streaming.mdx, etc.)\n- `api-reference/workflow/` - API docs (sleep.mdx, create-hook.mdx, fatal-error.mdx, etc.)\n- `api-reference/workflow-api/` - Client API (start.mdx, get-run.mdx, resume-hook.mdx, etc.)\n- `ai/` - AI SDK integration docs\n- `errors/` - Error code documentation\n\nRelated packages also include bundled docs:\n\n- `@workflow/ai`: `node_modules/@workflow/ai/docs/` - DurableAgent and AI integration\n- `@workflow/core`: `node_modules/@workflow/core/docs/` - Core runtime (foundations, how-it-works)\n- `@workflow/next`: `node_modules/@workflow/next/docs/` - Next.js integration\n\n**When in doubt, update to the latest version of the Workflow DevKit.**\n\n### Official Resources\n\n- **Website**: https://useworkflow.dev\n- **GitHub**: https://github.com/vercel/workflow\n\n### Quick Reference\n\n**Directives:**\n\n```typescript\n\"use workflow\"; // First line - makes async function durable\n\"use step\"; // First line - makes function a cached, retryable unit\n```\n\n**Essential imports:**\n\n```typescript\n// Workflow primitives\nimport { sleep, fetch, createHook, createWebhook, getWritable } from \"workflow\";\nimport { FatalError, RetryableError } from \"workflow\";\nimport { getWorkflowMetadata, getStepMetadata } from \"workflow\";\n\n// API operations\nimport { start, getRun, resumeHook, resumeWebhook } from \"workflow/api\";\n\n// Framework integrations\nimport { withWorkflow } from \"workflow/next\";\nimport { workflow } from \"workflow/vite\";\nimport { workflow } from \"workflow/astro\";\n// Or use modules: [\"workflow/nitro\"] for Nitro/Nuxt\n\n// AI agent\nimport { DurableAgent } from \"@workflow/ai/agent\";\n```\n\n## Prefer Step Functions to Avoid Sandbox Errors\n\n`\"use workflow\"` functions run in a sandboxed VM. `\"use step\"` functions have **full Node.js access**. Put your logic in steps and use the workflow function purely for orchestration.\n\n```typescript\n// Steps have full Node.js and npm access\nasync function fetchUserData(userId: string) {\n \"use step\";\n const response = await fetch(`https://api.example.com/users/${userId}`);\n return response.json();\n}\n\nasync function processWithAI(data: any) {\n \"use step\";\n // AI SDK works in steps without workarounds\n return await generateText({\n model: openai(\"gpt-4\"),\n prompt: `Process: ${JSON.stringify(data)}`,\n });\n}\n\n// Workflow orchestrates steps - no sandbox issues\nexport async function dataProcessingWorkflow(userId: string) {\n \"use workflow\";\n const data = await fetchUserData(userId);\n const processed = await processWithAI(data);\n return { success: true, processed };\n}\n```\n\n**Benefits:** Steps have automatic retry, results are persisted for replay, and no sandbox restrictions.\n\n## Workflow Sandbox Limitations\n\nWhen you need logic directly in a workflow function (not in a step), these restrictions apply:\n\n| Limitation | Workaround |\n|------------|------------|\n| No `fetch()` | `import { fetch } from \"workflow\"` then `globalThis.fetch = fetch` |\n| No `setTimeout`/`setInterval` | Use `sleep(\"5s\")` from `\"workflow\"` |\n| No Node.js modules (fs, crypto, etc.) | Move to a step function |\n\n**Example - Using fetch in workflow context:**\n\n```typescript\nimport { fetch } from \"workflow\";\n\nexport async function myWorkflow() {\n \"use workflow\";\n globalThis.fetch = fetch; // Required for AI SDK and HTTP libraries\n // Now generateText() and other libraries work\n}\n```\n\n**Note:** `DurableAgent` from `@workflow/ai` handles the fetch assignment automatically.\n\n## DurableAgent — AI Agents in Workflows\n\nUse `DurableAgent` to build AI agents that maintain state and survive interruptions. It handles the workflow sandbox automatically (no manual `globalThis.fetch` needed).\n\n```typescript\nimport { DurableAgent } from \"@workflow/ai/agent\";\nimport { getWritable } from \"workflow\";\nimport { z } from \"zod\";\nimport type { UIMessageChunk } from \"ai\";\n\nasync function lookupData({ query }: { query: string }) {\n \"use step\";\n // Step functions have full Node.js access\n return `Results for \"${query}\"`;\n}\n\nexport async function myAgentWorkflow(userMessage: string) {\n \"use workflow\";\n\n const agent = new DurableAgent({\n model: \"anthropic/claude-sonnet-4-5\",\n system: \"You are a helpful assistant.\",\n tools: {\n lookupData: {\n description: \"Search for information\",\n inputSchema: z.object({ query: z.string() }),\n execute: lookupData,\n },\n },\n });\n\n const result = await agent.stream({\n messages: [{ role: \"user\", content: userMessage }],\n writable: getWritable<UIMessageChunk>(),\n maxSteps: 10,\n });\n\n return result.messages;\n}\n```\n\n**Key points:**\n- `getWritable<UIMessageChunk>()` streams output to the workflow run's default stream\n- Tool `execute` functions that need Node.js/npm access should use `\"use step\"`\n- Tool `execute` functions that use workflow primitives (`sleep()`, `createHook()`) should **NOT** use `\"use step\"` — they run at the workflow level\n- `maxSteps` limits the number of LLM calls (default is unlimited)\n- Multi-turn: pass `result.messages` plus new user messages to subsequent `agent.stream()` calls\n\n**For more details on `DurableAgent`, check the AI docs in `node_modules/@workflow/ai/docs/`.**\n\n## Starting Workflows & Child Workflows\n\nUse `start()` to launch workflows from API routes. **`start()` cannot be called directly in workflow context** — wrap it in a step function.\n\n```typescript\nimport { start } from \"workflow/api\";\n\n// From an API route — works directly\nexport async function POST() {\n const run = await start(myWorkflow, [arg1, arg2]);\n return Response.json({ runId: run.runId });\n}\n\n// No-args workflow\nconst run = await start(noArgWorkflow);\n```\n\n**Starting child workflows from inside a workflow — must use a step:**\n\n```typescript\nimport { start } from \"workflow/api\";\n\n// Wrap start() in a step function\nasync function triggerChild(data: string) {\n \"use step\";\n const run = await start(childWorkflow, [data]);\n return run.runId;\n}\n\nexport async function parentWorkflow() {\n \"use workflow\";\n const childRunId = await triggerChild(\"some data\"); // Fire-and-forget via step\n await sleep(\"1h\");\n}\n```\n\n`start()` returns immediately — it doesn't wait for the workflow to complete. Use `run.returnValue` to await completion.\n\n## Hooks — Pause & Resume with External Events\n\nHooks let workflows wait for external data. Use `createHook()` inside a workflow and `resumeHook()` from API routes. Deterministic tokens are for `createHook()` + `resumeHook()` (server-side) only. `createWebhook()` always generates random tokens — do not pass a `token` option to `createWebhook()`.\n\n### Single event\n\n```typescript\nimport { createHook } from \"workflow\";\n\nexport async function approvalWorkflow() {\n \"use workflow\";\n\n const hook = createHook<{ approved: boolean }>({\n token: \"approval-123\", // deterministic token for external systems\n });\n\n const result = await hook; // Workflow suspends here\n return result.approved;\n}\n```\n\n### Multiple events (iterable hooks)\n\nHooks implement `AsyncIterable` — use `for await...of` to receive multiple events:\n\n```typescript\nimport { createHook } from \"workflow\";\n\nexport async function chatWorkflow(channelId: string) {\n \"use workflow\";\n\n const hook = createHook<{ text: string; done?: boolean }>({\n token: `chat-${channelId}`,\n });\n\n for await (const event of hook) {\n await processMessage(event.text);\n if (event.done) break;\n }\n}\n```\n\nEach `resumeHook(token, payload)` call delivers the next value to the loop.\n\n### Resuming from API routes\n\n```typescript\nimport { resumeHook } from \"workflow/api\";\n\nexport async function POST(req: Request) {\n const { token, data } = await req.json();\n await resumeHook(token, data);\n return new Response(\"ok\");\n}\n```\n\n## Error Handling\n\nUse `FatalError` for permanent failures (no retry), `RetryableError` for transient failures:\n\n```typescript\nimport { FatalError, RetryableError } from \"workflow\";\n\nif (res.status >= 400 && res.status < 500) {\n throw new FatalError(`Client error: ${res.status}`);\n}\nif (res.status === 429) {\n throw new RetryableError(\"Rate limited\", { retryAfter: \"5m\" });\n}\n```\n\n## Serialization\n\nAll data passed to/from workflows and steps must be serializable.\n\n**Supported types:** string, number, boolean, null, undefined, bigint, plain objects, arrays, Date, RegExp, URL, URLSearchParams, Map, Set, Headers, ArrayBuffer, typed arrays, Request, Response, ReadableStream, WritableStream.\n\n**Not supported:** Functions, class instances, Symbols, WeakMap/WeakSet. Pass data, not callbacks.\n\n## Streaming\n\nUse `getWritable()` to stream data from workflows. `getWritable()` can be called in **both** workflow and step contexts, but you **cannot interact with the stream** (call `getWriter()`, `write()`, `close()`) directly in a workflow function. The stream must be passed to step functions for actual I/O, or steps can call `getWritable()` themselves.\n\n**Get the stream in a workflow, pass it to a step:**\n```typescript\nimport { getWritable } from \"workflow\";\n\nexport async function myWorkflow() {\n \"use workflow\";\n const writable = getWritable();\n await writeData(writable, \"hello world\");\n}\n\nasync function writeData(writable: WritableStream, chunk: string) {\n \"use step\";\n const writer = writable.getWriter();\n try {\n await writer.write(chunk);\n } finally {\n writer.releaseLock();\n }\n}\n```\n\n**Call `getWritable()` directly inside a step (no need to pass it):**\n```typescript\nimport { getWritable } from \"workflow\";\n\nasync function streamData(chunk: string) {\n \"use step\";\n const writer = getWritable().getWriter();\n try {\n await writer.write(chunk);\n } finally {\n writer.releaseLock();\n }\n}\n```\n\n### Namespaced Streams\n\nUse `getWritable({ namespace: 'name' })` to create multiple independent streams for different types of data. This is useful for separating logs from primary output, different log levels, agent outputs, metrics, or any distinct data channels. Long-running workflows benefit from namespaced streams because you can replay only the important events (e.g., final results) while keeping verbose logs in a separate stream.\n\n**Example: Log levels and agent output separation:**\n```typescript\nimport { getWritable } from \"workflow\";\n\ntype LogEntry = { level: \"debug\" | \"info\" | \"warn\" | \"error\"; message: string; timestamp: number };\ntype AgentOutput = { type: \"thought\" | \"action\" | \"result\"; content: string };\n\nasync function logDebug(message: string) {\n \"use step\";\n const writer = getWritable<LogEntry>({ namespace: \"logs:debug\" }).getWriter();\n try {\n await writer.write({ level: \"debug\", message, timestamp: Date.now() });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function logInfo(message: string) {\n \"use step\";\n const writer = getWritable<LogEntry>({ namespace: \"logs:info\" }).getWriter();\n try {\n await writer.write({ level: \"info\", message, timestamp: Date.now() });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function emitAgentThought(thought: string) {\n \"use step\";\n const writer = getWritable<AgentOutput>({ namespace: \"agent:thoughts\" }).getWriter();\n try {\n await writer.write({ type: \"thought\", content: thought });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function emitAgentResult(result: string) {\n \"use step\";\n // Important results go to the default stream for easy replay\n const writer = getWritable<AgentOutput>().getWriter();\n try {\n await writer.write({ type: \"result\", content: result });\n } finally {\n writer.releaseLock();\n }\n}\n\nexport async function agentWorkflow(task: string) {\n \"use workflow\";\n \n await logInfo(`Starting task: ${task}`);\n await logDebug(\"Initializing agent context\");\n await emitAgentThought(\"Analyzing the task requirements...\");\n \n // ... agent processing ...\n \n await emitAgentResult(\"Task completed successfully\");\n await logInfo(\"Workflow finished\");\n}\n```\n\n**Consuming namespaced streams:**\n```typescript\nimport { start, getRun } from \"workflow/api\";\nimport { agentWorkflow } from \"./workflows/agent\";\n\nexport async function POST(request: Request) {\n const run = await start(agentWorkflow, [\"process data\"]);\n\n // Access specific streams by namespace\n const results = run.getReadable({ namespace: undefined }); // Default stream (important results)\n const infoLogs = run.getReadable({ namespace: \"logs:info\" });\n const debugLogs = run.getReadable({ namespace: \"logs:debug\" });\n const thoughts = run.getReadable({ namespace: \"agent:thoughts\" });\n\n // Return only important results for most clients\n return new Response(results, { headers: { \"Content-Type\": \"application/json\" } });\n}\n\n// Resume from a specific point (useful for long sessions)\nexport async function GET(request: Request) {\n const { searchParams } = new URL(request.url);\n const runId = searchParams.get(\"runId\")!;\n const startIndex = parseInt(searchParams.get(\"startIndex\") || \"0\", 10);\n \n const run = getRun(runId);\n // Resume only the important stream, skip verbose debug logs\n const stream = run.getReadable({ startIndex });\n \n return new Response(stream);\n}\n```\n\n**Pro tip:** For very long-running sessions (50+ minutes), namespaced streams help manage replay performance. Put verbose/debug output in separate namespaces so you can replay just the important events quickly.\n\n## Debugging\n\n```bash\n# Check workflow endpoints are reachable\nnpx workflow health\nnpx workflow health --port 3001 # Non-default port\n\n# Visual dashboard for runs\nnpx workflow web\nnpx workflow web <run_id>\n\n# CLI inspection (use --json for machine-readable output, --help for full usage)\nnpx workflow inspect runs\nnpx workflow inspect run <run_id>\n\n# For Vercel-deployed projects, specify backend and project\nnpx workflow inspect runs --backend vercel --project <project-name> --team <team-slug>\nnpx workflow inspect run <run_id> --backend vercel --project <project-name> --team <team-slug>\n\n# Open Vercel dashboard in browser for a specific run\nnpx workflow inspect run <run_id> --web\nnpx workflow web <run_id> --backend vercel --project <project-name> --team <team-slug>\n\n# Cancel a running workflow\nnpx workflow cancel <run_id>\nnpx workflow cancel <run_id> --backend vercel --project <project-name> --team <team-slug>\n# --env defaults to \"production\"; use --env preview for preview deployments\n```\n\n**Debugging tips:**\n- Use `--json` (`-j`) on any command for machine-readable output\n- Use `--web` to open the Vercel Observability dashboard in your browser\n- Use `--help` on any command for full usage details\n- Only import workflow APIs you actually use. Unused imports can cause 500 errors.\n\n## Testing Workflows\n\nWorkflow DevKit provides a Vitest plugin for testing workflows in-process — no running server required.\n\n**Unit testing steps:** Steps are just functions; without the compiler, `\"use step\"` is a no-op. Test them directly:\n\n```typescript\nimport { describe, it, expect } from \"vitest\";\nimport { createUser } from \"./user-signup\";\n\ndescribe(\"createUser step\", () => {\n it(\"should create a user\", async () => {\n const user = await createUser(\"test@example.com\");\n expect(user.email).toBe(\"test@example.com\");\n });\n});\n```\n\n**Integration testing:** Use `@workflow/vitest` for workflows using `sleep()`, hooks, webhooks, or retries:\n\n```typescript\n// vitest.integration.config.ts\nimport { defineConfig } from \"vitest/config\";\nimport { workflow } from \"@workflow/vitest\";\n\nexport default defineConfig({\n plugins: [workflow()],\n test: {\n include: [\"**/*.integration.test.ts\"],\n testTimeout: 60_000,\n },\n});\n```\n\n```typescript\n// approval.integration.test.ts\nimport { describe, it, expect } from \"vitest\";\nimport { start, getRun, resumeHook } from \"workflow/api\";\nimport { waitForHook, waitForSleep } from \"@workflow/vitest\";\nimport { approvalWorkflow } from \"./approval\";\n\ndescribe(\"approvalWorkflow\", () => {\n it(\"should publish when approved\", async () => {\n const run = await start(approvalWorkflow, [\"doc-123\"]);\n\n // Wait for the hook, then resume it\n await waitForHook(run, { token: \"approval:doc-123\" });\n await resumeHook(\"approval:doc-123\", { approved: true, reviewer: \"alice\" });\n\n // Wait for sleep, then wake it up\n const sleepId = await waitForSleep(run);\n await getRun(run.runId).wakeUp({ correlationIds: [sleepId] });\n\n const result = await run.returnValue;\n expect(result).toEqual({ status: \"published\", reviewer: \"alice\" });\n });\n});\n```\n\n**Testing webhooks:** Use `resumeWebhook()` with a `Request` object — no HTTP server needed:\n\n```typescript\nimport { start, resumeWebhook } from \"workflow/api\";\nimport { waitForHook } from \"@workflow/vitest\";\n\nconst run = await start(ingestWorkflow, [\"ep-1\"]);\nconst hook = await waitForHook(run); // Discovers the random webhook token\nawait resumeWebhook(hook.token, new Request(\"https://example.com/webhook\", {\n method: \"POST\",\n body: JSON.stringify({ event: \"order.created\" }),\n}));\n```\n\n**Key APIs:**\n- `start()` — trigger a workflow\n- `run.returnValue` — await workflow completion\n- `waitForHook(run, { token? })` / `waitForSleep(run)` — wait for workflow to reach a pause point\n- `resumeHook(token, data)` / `resumeWebhook(token, request)` — resume paused workflows\n- `getRun(runId).wakeUp({ correlationIds })` — skip `sleep()` calls\n\n**Best practices:**\n- Keep unit tests (no plugin) and integration tests (`workflow()` plugin) in separate configs\n- Use deterministic hook tokens based on test data for easier resumption\n- Set generous `testTimeout` — workflows may run longer than typical unit tests\n- `vi.mock()` does **not** work in integration tests — step dependencies are bundled by esbuild\n""---\nname: workflow\ndescription: Vercel Workflow SDK expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow.\nmetadata:\n priority: 9\n docs:\n - \"https://vercel.com/docs/workflows\"\n - \"https://workflow-sdk.dev\"\n sitemap: \"https://vercel.com/sitemap.xml\"\n pathPatterns:\n - 'lib/workflow/**'\n - 'src/lib/workflow/**'\n - 'lib/workflow.*'\n - 'src/lib/workflow.*'\n - 'workflow.*'\n - '*workflow*'\n importPatterns:\n - 'workflow'\n - '@workflow/*'\n - '*workflow*'\n bashPatterns:\n - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\bbun\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\byarn\\s+add\\s+[^\\n]*\\bworkflow\\b'\n - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\bbun\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\byarn\\s+add\\s+[^\\n]*@workflow/'\n - '\\bnpx\\s+workflow(?:@latest)?\\b'\n - '\\bbunx\\s+workflow(?:@latest)?\\b'\n promptSignals:\n phrases:\n # Direct workflow mentions\n - \"vercel workflow\"\n - \"workflow sdk\"\n # Legacy product name retained only as an input matcher.\n - \"workflow devkit\"\n - \"durable workflow\"\n - \"durable execution\"\n - \"durable function\"\n - \"durable pipeline\"\n - \"durable process\"\n - \"durable agent\"\n - \"durable chat\"\n - \"step function\"\n - \"step functions\"\n - \"use workflow\"\n - \"use step\"\n # Pipeline / multi-step language (the BIG gap — natural product prompts)\n - \"multi-step pipeline\"\n - \"multi step pipeline\"\n - \"multi-step process\"\n - \"multi step process\"\n - \"multi-step creation\"\n - \"multi-step generation\"\n - \"processing pipeline\"\n - \"creation pipeline\"\n - \"generation pipeline\"\n - \"content pipeline\"\n - \"production pipeline\"\n - \"approval pipeline\"\n - \"ingestion pipeline\"\n - \"streams progress\"\n - \"stream progress\"\n - \"streams each phase\"\n - \"streams each step\"\n - \"streams each\"\n - \"stream each\"\n # Reliability / durability language (missed in customer-support eval)\n - \"survive page reload\"\n - \"survive page reloads\"\n - \"survive a crash\"\n - \"survive crashes\"\n - \"survive network\"\n - \"fault-tolerant\"\n - \"fault tolerant\"\n - \"crash-safe\"\n - \"crash safe\"\n - \"automatically retry\"\n - \"auto retry\"\n - \"retry on failure\"\n - \"retry on error\"\n - \"reliable and retry\"\n - \"reliable processing\"\n - \"individually reliable\"\n - \"each step reliable\"\n - \"each step should be reliable\"\n - \"steps should be reliable\"\n - \"reliable with automatic retry\"\n - \"reliable with retry\"\n - \"retry on transient\"\n - \"transient failures\"\n - \"session persistence\"\n - \"session should persist\"\n - \"session survives\"\n - \"reconnect automatically\"\n - \"auto reconnect\"\n - \"reconnect if the network\"\n - \"reconnect on disconnect\"\n - \"resume after failure\"\n - \"resume after crash\"\n - \"resume on reconnect\"\n # Human-in-the-loop / approval patterns\n - \"human-in-the-loop\"\n - \"human in the loop\"\n - \"wait for approval\"\n - \"approval step\"\n - \"approval before\"\n - \"editorial approval\"\n - \"manual approval\"\n - \"wait for user\"\n - \"pause until\"\n - \"wait for response\"\n - \"callback url\"\n - \"webhook callback\"\n # Conversational AI with durability\n - \"chat should survive\"\n - \"chat survives\"\n - \"conversation should persist\"\n - \"conversation persists\"\n - \"conversation should survive\"\n # Sequential / chain / trigger orchestration language\n - \"sequential chain\"\n - \"email chain\"\n - \"chain of emails\"\n - \"chain of steps\"\n - \"chain engine\"\n - \"chain with triggers\"\n - \"trigger chain\"\n - \"triggered chain\"\n - \"webhook chain\"\n - \"webhook pipeline\"\n - \"webhook orchestration\"\n - \"multi-service trigger\"\n - \"cross-service trigger\"\n - \"various triggers\"\n - \"different triggers\"\n - \"triggers from different\"\n - \"triggers from various\"\n - \"sequential steps\"\n - \"sequential pipeline\"\n - \"sequential process\"\n - \"sequential emails\"\n - \"escalation chain\"\n - \"escalation pipeline\"\n - \"state machine\"\n - \"step-based\"\n - \"step based\"\n - \"delay between steps\"\n - \"delay between emails\"\n - \"delayed steps\"\n - \"conditional steps\"\n - \"skip steps\"\n - \"branch based on\"\n - \"wait for webhook\"\n - \"wait for trigger\"\n - \"wait for event\"\n - \"orchestrate emails\"\n - \"orchestrate webhooks\"\n - \"orchestrate services\"\n - \"chain across services\"\n # Debugging\n - \"workflow stuck\"\n - \"workflow hung\"\n - \"workflow hanging\"\n - \"workflow waiting\"\n - \"workflow failing\"\n - \"workflow timeout\"\n - \"workflow not running\"\n - \"workflow error\"\n - \"check workflow\"\n - \"workflow logs\"\n - \"workflow run status\"\n - \"debug workflow\"\n - \"workflow not finishing\"\n - \"workflow not responding\"\n - \"workflow stalled\"\n - \"workflow pending\"\n - \"step is stuck\"\n - \"step is hanging\"\n - \"why is my workflow\"\n - \"workflow run\"\n - \"step failed\"\n - \"run status\"\n - \"run failed\"\n - \"run logs\"\n - \"workflow run failed\"\n - \"workflow step failed\"\n allOf:\n - [workflow, durable]\n - [workflow, retry]\n - [workflow, resume]\n - [pause, resume]\n - [survive, crash]\n - [survive, reload]\n - [survive, disconnect]\n - [pipeline, stream]\n - [pipeline, step]\n - [pipeline, durable]\n - [pipeline, reliable]\n - [pipeline, retry]\n - [multi-step, stream]\n - [multi-step, reliable]\n - [generation, pipeline]\n - [creation, pipeline]\n - [process, stream]\n - [process, reliable]\n - [process, retry]\n - [retry, failure]\n - [retry, error]\n - [retry, automatically]\n - [retry, transient]\n - [reliable, retry]\n - [individually, reliable]\n - [steps, reliable]\n - [sandbox, reliable]\n - [sandbox, retry]\n - [reconnect, network]\n - [reconnect, drop]\n - [reconnect, disconnect]\n - [session, persist]\n - [session, survive]\n - [session, reload]\n - [session, reconnect]\n - [chat, survive]\n - [chat, persist]\n - [chat, reconnect]\n - [chat, durable]\n - [chat, fault]\n - [conversation, persist]\n - [conversation, survive]\n - [approval, wait]\n - [approval, human]\n - [each, step]\n - [each, phase]\n - [each, stage]\n - [step, reliable]\n - [step, retry]\n # Chain / trigger / sequential orchestration\n - [chain, trigger]\n - [chain, sequential]\n - [chain, email]\n - [chain, webhook]\n - [chain, delay]\n - [chain, step]\n - [chain, escalat]\n - [sequential, trigger]\n - [sequential, email]\n - [sequential, step]\n - [sequential, webhook]\n - [trigger, orchestrat]\n - [trigger, service]\n - [trigger, delay]\n - [trigger, sequential]\n - [webhook, chain]\n - [webhook, orchestrat]\n - [webhook, pipeline]\n - [webhook, sequential]\n - [email, trigger]\n - [email, pipeline]\n - [email, sequential]\n - [email, delay]\n - [email, escalat]\n - [escalat, trigger]\n - [escalat, step]\n - [escalat, email]\n - [state, machine]\n - [conditional, step]\n - [conditional, skip]\n - [branch, condition]\n - [wait, webhook]\n - [wait, trigger]\n - [wait, event]\n - [workflow, stuck]\n - [workflow, hung]\n - [workflow, timeout]\n - [workflow, error]\n - [workflow, logs]\n - [workflow, debug]\n - [workflow, check]\n - [workflow, failing]\n - [workflow, status]\n - [run, status]\n - [step, failed]\n - [step, stuck]\n - [step, timeout]\n - [workflow, run]\n - [run, logs]\n anyOf:\n - \"long-running\"\n - \"long running\"\n - \"multi-step\"\n - \"multi step\"\n - \"pipeline\"\n - \"orchestration\"\n - \"step-by-step\"\n - \"step by step\"\n - \"each piece\"\n - \"each step\"\n - \"each phase\"\n - \"each stage\"\n - \"phase\"\n - \"phases\"\n - \"stage\"\n - \"stages\"\n - \"durable\"\n - \"reliable\"\n - \"fault-tolerant\"\n - \"retry\"\n - \"reconnect\"\n - \"survive\"\n - \"persist\"\n - \"approval\"\n - \"chain\"\n - \"sequential\"\n - \"trigger\"\n - \"webhook\"\n - \"escalation\"\n - \"state machine\"\n - \"orchestrate\"\n - \"orchestration\"\n noneOf:\n - \"github actions\"\n - \".github/workflows\"\n - \"ci workflow\"\n - \"aws step functions\"\n minScore: 4\nvalidate:\n -\n pattern: setTimeout|setInterval\n message: 'setTimeout/setInterval are not available in workflow sandbox scope — use sleep() from \"workflow\" for delays'\n severity: error\n skipIfFileContains: \"use step\"\n -\n pattern: context\\.run\\s*\\(\n message: 'context.run() is not a Workflow SDK pattern — use \"use step\" directive for retryable, observable steps'\n severity: error\n upgradeToSkill: workflow\n upgradeWhy: 'Guides migration from context.run() to the \"use step\" directive for durable, retryable workflow steps.'\n -\n pattern: \\brequire\\s*\\(\n message: 'require() is not available in workflow sandbox scope — use ESM imports and move Node.js logic into \"use step\" functions'\n severity: error\n skipIfFileContains: \"use step\"\n -\n pattern: getWritable\\(\\)\n message: 'getWritable() must only be called inside \"use step\" functions — workflow sandbox scope does not support it'\n severity: recommended\n skipIfFileContains: \"use step\"\n -\n pattern: streamObject\\s*\\(\n message: 'streamObject() is deprecated since AI SDK 6 — use streamText() with output: Output.object() instead'\n severity: error\n upgradeToSkill: ai-sdk\n upgradeWhy: 'Guides migration from streamObject to streamText + Output.object() with correct v6 streaming patterns.'\n -\n pattern: await\\s+\\w+Workflow\\s*\\(\n message: 'Do not call workflow functions directly — use start() from \"workflow/api\" to register the run and get a runId'\n severity: recommended\n skipIfFileContains: \"use workflow\"\n -\n pattern: \\bfetch\\s*\\(\n message: 'Native fetch() is not available in workflow sandbox scope — import fetch from \"workflow\" or move the call into a \"use step\" function'\n severity: recommended\n skipIfFileContains: \"use step\"\n -\n pattern: '\"use step\"'\n message: \"Workflow steps should include console.log or structured logging for observability — add logging at step entry/exit to debug hangs\"\n severity: warn\n skipIfFileContains: \"console\\\\.(log|warn|error|info)\"\n -\n pattern: '\"use workflow\"'\n message: \"Workflow files should import and use logging — add console.log or a logger at key execution points for debugging\"\n severity: warn\n skipIfFileContains: \"console\\\\.(log|warn|error|info)\"\nchainTo:\n -\n pattern: 'DurableAgent|@workflow/ai'\n targetSkill: ai-sdk\n message: 'Workflow 5 (workflow@latest) deprecates DurableAgent (@workflow/ai) in favor of WorkflowAgent from @ai-sdk/workflow 2.x, which requires Workflow 5; the Workflow 4 docs (workflow@4) use DurableAgent. Loading AI SDK guidance for tool calling, the Agent class, and model configuration.'\n skipIfFileContains: 'from\\s+[''\"]ai[''\"]|@ai-sdk/|streamText|generateText'\n -\n pattern: 'process\\.env\\.(OPENAI_API_KEY|ANTHROPIC_API_KEY)|from\\s+[''\"]@ai-sdk/(anthropic|openai)[''\"\"]'\n targetSkill: ai-gateway\n message: 'Direct provider API key in workflow — loading AI Gateway guidance for OIDC auth (required for Workflow SDK AI steps).'\n skipIfFileContains: 'gateway\\(|@ai-sdk/gateway|VERCEL_OIDC'\n -\n pattern: 'setTimeout\\s*\\(|setInterval\\s*\\('\n targetSkill: vercel-functions\n message: 'Timer-based delay in workflow code — use sleep() from \"workflow\" instead of setTimeout/setInterval. Loading Vercel Functions guidance.'\n skipIfFileContains: 'from\\s+[''\"]workflow[''\"].*sleep|sleep\\s*\\('\nretrieval:\n aliases:\n - durable workflow\n - long running task\n - step function\n - orchestration\n intents:\n - build workflow\n - add retry logic\n - create durable task\n - implement step function\n entities:\n - Workflow SDK\n # Legacy product names retained only as retrieval aliases.\n - Workflow DevKit\n - WDK\n - step\n - pause/resume\n - durable\n---\n\n## *Critical*: Always use correct `workflow` documentation\n\nYour knowledge of `workflow` is outdated.\n\nThe `workflow` documentation outlined below matches the installed version of the Workflow SDK.\nFollow these instructions before starting on any `workflow`-related tasks:\n\nSearch the bundled documentation in `node_modules/workflow/docs/`:\n\n1. **Find docs**: `glob \"node_modules/workflow/docs/**/*.mdx\"`\n2. **Search content**: `grep \"your query\" node_modules/workflow/docs/`\n\nDocumentation structure in `node_modules/workflow/docs/`:\n\n- `getting-started/` - Framework setup (next.mdx, express.mdx, hono.mdx, etc.)\n- `foundations/` - Core concepts (workflows-and-steps.mdx, hooks.mdx, streaming.mdx, etc.)\n- `api-reference/workflow/` - API docs (sleep.mdx, create-hook.mdx, fatal-error.mdx, etc.)\n- `api-reference/workflow-api/` - Client API (start.mdx, get-run.mdx, resume-hook.mdx, etc.)\n- `api-reference/workflow-runtime/` - Runtime API (get-world.mdx) and `world/` World SDK (storage.mdx, streams.mdx, queue.mdx)\n- `api-reference/workflow-observability/` - Hydration and name parsing utilities (hydrate-resource-io.mdx, parse-workflow-name.mdx, etc.)\n- `ai/`: AI SDK integration docs\n- `errors/` - Error code documentation\n- `worlds/` - Per-World behavior and limits (vercel.mdx, local.mdx, postgres.mdx). Other pages link these as `/worlds/<name>`.\n\nRelated packages also include bundled docs:\n\n- `@ai-sdk/workflow`: `node_modules/ai/docs/` - WorkflowAgent and AI SDK integration\n- `@workflow/ai`: `node_modules/@workflow/ai/docs/` - deprecated DurableAgent APIs for existing applications\n- `@workflow/core`: `node_modules/@workflow/core/docs/` - Core runtime (foundations, how-it-works)\n- `@workflow/next`: `node_modules/@workflow/next/docs/` - Next.js integration\n\n**When in doubt, update to the latest version of the Workflow SDK.**\n\n### Official resources\n\n- **Website**: https://workflow-sdk.dev\n- **GitHub**: https://github.com/vercel/workflow\n\n### Quick reference\n\n**Directives:**\n\n```typescript\n\"use workflow\"; // First line - makes async function durable\n\"use step\"; // First line - makes function a cached, retryable unit\n```\n\n**Essential imports:**\n\n```typescript\n// Workflow primitives\nimport { sleep, fetch, createHook, createWebhook, getWritable } from \"workflow\";\nimport { FatalError, RetryableError } from \"workflow\";\nimport { getWorkflowMetadata, getStepMetadata } from \"workflow\";\n\n// API operations\nimport { start, getRun, resumeHook, resumeWebhook } from \"workflow/api\";\n\n// Observability & data hydration\nimport { hydrateResourceIO, observabilityRevivers, parseStepName, parseWorkflowName } from \"workflow/observability\";\n\n// Framework integrations\nimport { withWorkflow } from \"workflow/next\";\nimport { workflow } from \"workflow/vite\";\nimport { workflow } from \"workflow/astro\";\n// Or use modules: [\"workflow/nitro\"] for Nitro/Nuxt\n\n// AI agent (Workflow 5)\nimport { WorkflowAgent, type ModelCallStreamPart } from \"@ai-sdk/workflow\";\n```\n\n## Prefer step functions to avoid sandbox errors\n\n`\"use workflow\"` functions run in a sandboxed VM. `\"use step\"` functions have **full Node.js access**. Put your logic in steps and use the workflow function purely for orchestration.\n\n```typescript\n// Steps have full Node.js and npm access\nasync function fetchUserData(userId: string) {\n \"use step\";\n const response = await fetch(`https://api.example.com/users/${userId}`);\n return response.json();\n}\n\nasync function processWithAI(data: any) {\n \"use step\";\n // AI SDK works in steps without workarounds\n return await generateText({\n model: \"spacexai/grok-4.6\",\n prompt: `Process: ${JSON.stringify(data)}`,\n });\n}\n\n// Workflow orchestrates steps - no sandbox issues\nexport async function dataProcessingWorkflow(userId: string) {\n \"use workflow\";\n const data = await fetchUserData(userId);\n const processed = await processWithAI(data);\n return { success: true, processed };\n}\n```\n\n**Benefits:** Steps have automatic retry, results are persisted for replay, and no sandbox restrictions.\n\n## Workflow sandbox limitations\n\nWhen you need logic directly in a workflow function (not in a step), these restrictions apply:\n\n| Limitation | Workaround |\n|------------|------------|\n| No `fetch()` | `import { fetch } from \"workflow\"` then `globalThis.fetch = fetch` |\n| No `setTimeout`/`setInterval` | Use `sleep(\"5s\")` from `\"workflow\"` |\n| No Node.js modules (fs, crypto, etc.) | Move to a step function |\n\n**Example - Using fetch in workflow context:**\n\n```typescript\nimport { fetch } from \"workflow\";\n\nexport async function myWorkflow() {\n \"use workflow\";\n globalThis.fetch = fetch; // Required for AI SDK and HTTP libraries\n // Now generateText() and other libraries work\n}\n```\n\n**Note:** Plain `\"provider/model\"` strings use Vercel AI Gateway. Do not construct a direct provider instance unless the user explicitly needs a provider-only feature.\n\n## WorkflowAgent: AI agents in Workflow 5\n\nUse AI SDK's `WorkflowAgent` for durable agents on Workflow 5. It replaces the deprecated `DurableAgent` API from `@workflow/ai` and checkpoints model calls and step-backed tools.\n\n```typescript\nimport { WorkflowAgent, type ModelCallStreamPart } from \"@ai-sdk/workflow\";\nimport { isStepCount, tool } from \"ai\";\nimport { getWritable } from \"workflow\";\nimport { z } from \"zod\";\n\nasync function lookupData({ query }: { query: string }) {\n \"use step\";\n // Step functions have full Node.js access\n return `Results for \"${query}\"`;\n}\n\nexport async function myAgentWorkflow(userMessage: string) {\n \"use workflow\";\n\n const agent = new WorkflowAgent({\n model: \"spacexai/grok-4.6\",\n instructions: \"You are a helpful assistant.\",\n tools: {\n lookupData: tool({\n description: \"Search for information\",\n inputSchema: z.object({ query: z.string() }),\n execute: lookupData,\n }),\n },\n });\n\n const result = await agent.stream({\n messages: [{ role: \"user\", content: userMessage }],\n writable: getWritable<ModelCallStreamPart>(),\n stopWhen: isStepCount(10),\n });\n\n return result.messages;\n}\n```\n\n**Key points:**\n- A plain `\"provider/model\"` string routes through Vercel AI Gateway; `spacexai/grok-4.6` is the default model in Workflow examples\n- `getWritable<ModelCallStreamPart>()` streams durable model-call output; convert it with `createModelCallToUIChunkTransform()` in an HTTP route\n- Tool `execute` functions that need Node.js/npm access should use `\"use step\"`\n- Tool `execute` functions that use workflow primitives (`sleep()`, `createHook()`) should **NOT** use `\"use step\"` because they run at the workflow level\n- `stopWhen` limits the number of model calls; the default is to stop when the model stops calling tools\n- Multi-turn: pass `result.messages` plus new user messages to subsequent `agent.stream()` calls\n\n**For more details, check the WorkflowAgent docs in the installed AI SDK package or at https://ai-sdk.dev/v7/docs/agents/workflow-agent.**\n\n## Starting workflows & child workflows\n\nUse `start()` to launch workflows from API routes. In Workflow 5, `start()` can also be called directly from a workflow function to spawn a child run; it is step-backed and records a deterministic boundary in the parent's event log.\n\n```typescript\nimport { start } from \"workflow/api\";\n\n// From an API route; works directly\nexport async function POST() {\n const run = await start(myWorkflow, [arg1, arg2]);\n return Response.json({ runId: run.runId });\n}\n\n// No-args workflow\nconst run = await start(noArgWorkflow);\n```\n\n**Starting child workflows from inside a Workflow 5 workflow:**\n\n```typescript\nimport { start } from \"workflow/api\";\n\nexport async function parentWorkflow() {\n \"use workflow\";\n const childRun = await start(childWorkflow, [\"some data\"]);\n await sleep(\"1h\");\n return { childRunId: childRun.runId };\n}\n```\n\n`start()` returns after creating the child run and doesn't wait for it to complete. Use `childRun.returnValue` only when the parent should wait for the child; each `Run` property access or method call inside a workflow is a step.\n\n## Run size & concurrency: know when to split\n\nDo NOT treat any number you remember as authoritative — the current values are published under [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits).\n\n**Events per run.** A run's event log is capped, and the run fails with `MAX_EVENTS_EXCEEDED` past the ceiling. Events are not steps: a step that succeeds on the first try records three (`step_created`, `step_started`, `step_completed`), a retry records one or two more, and hooks, sleeps, and webhooks each record their own. Split into child workflows well before the ceiling — the pricing page recommends that past **a few thousand events**, because replay slows down long before the run fails.\n\n**Steps per run.** Capped implicitly through the event limit. Bundle several items into one step when a chain would otherwise reach five figures.\n\n**Concurrency.** A wide fan-out is throttled rather than rejected: event creation is rate-limited per run per second, so a flat `Promise.all` over a few thousand items spends much of its time backing off. Batch or bundle instead — process the list in chunks, or handle several items per step, so fewer and larger units run concurrently. Spawning one child run per item does not by itself narrow the fan-out; it bounds each child's log and isolates failures, which is worth doing for those reasons, but it is not a substitute for chunking.\n\nYou cannot raise any of these yourself — `WORKFLOW_MAX_EVENTS_OVERRIDE` only clamps *down*, and on the Vercel World the ceilings are service-owned — but Vercel raises the per-run event and step limits on request, so a genuinely large run is a support question as well as a design one.\n\n```typescript\nconst BATCH = 100;\n\nasync function processItem(item: string) {\n \"use step\";\n return item.toUpperCase();\n}\n\n// One step per item, all in flight at once, all in one log\nexport async function processAll(items: string[]) {\n \"use workflow\";\n await Promise.all(items.map((item) => processItem(item)));\n}\n\n// Chunked, so only BATCH steps are in flight at a time\nexport async function processBatched(items: string[]) {\n \"use workflow\";\n for (let i = 0; i < items.length; i += BATCH) {\n await Promise.allSettled(items.slice(i, i + BATCH).map((item) => processItem(item)));\n }\n}\n\n// Bundled, so one step covers many items and the log stays short\nasync function processChunk(chunk: string[]) {\n \"use step\";\n return chunk.map((item) => item.toUpperCase());\n}\n\nexport async function processBundled(items: string[]) {\n \"use workflow\";\n for (let i = 0; i < items.length; i += BATCH) {\n await processChunk(items.slice(i, i + BATCH));\n }\n}\n```\n\n`processAll` is the shape to avoid at scale. `processBatched` bounds concurrency but still records events for every item. `processBundled` bounds both, because one step covers `BATCH` items — that is the only one of the three whose event count shrinks as `BATCH` grows.\n\n## Hooks: pause & resume with external events\n\nHooks let workflows wait for external data. Use `createHook()` inside a workflow and `resumeHook()` from API routes. Deterministic tokens are for `createHook()` + `resumeHook()` (server-side) only. `createWebhook()` always generates random tokens, so do not pass a `token` option to `createWebhook()`.\n\n### Single event\n\n```typescript\nimport { createHook } from \"workflow\";\n\nexport async function approvalWorkflow() {\n \"use workflow\";\n\n const hook = createHook<{ approved: boolean }>({\n token: \"approval-123\", // deterministic token for external systems\n });\n\n const result = await hook; // Workflow suspends here\n return result.approved;\n}\n```\n\n### Multiple events (iterable hooks)\n\nHooks implement `AsyncIterable`. Use `for await...of` to receive multiple events:\n\n```typescript\nimport { createHook } from \"workflow\";\n\nexport async function chatWorkflow(channelId: string) {\n \"use workflow\";\n\n const hook = createHook<{ text: string; done?: boolean }>({\n token: `chat-${channelId}`,\n });\n\n for await (const event of hook) {\n await processMessage(event.text);\n if (event.done) break;\n }\n}\n```\n\nEach `resumeHook(token, payload)` call delivers the next value to the loop.\n\n### Resuming from API routes\n\n```typescript\nimport { resumeHook } from \"workflow/api\";\n\nexport async function POST(req: Request) {\n const { token, data } = await req.json();\n await resumeHook(token, data);\n return new Response(\"ok\");\n}\n```\n\n## Error handling\n\nUse `FatalError` for permanent failures (no retry), `RetryableError` for transient failures:\n\n```typescript\nimport { FatalError, RetryableError } from \"workflow\";\n\nif (res.status === 429) {\n throw new RetryableError(\"Rate limited\", { retryAfter: \"5m\" });\n}\nif (res.status >= 400 && res.status < 500) {\n throw new FatalError(`Client error: ${res.status}`);\n}\n```\n\n## Serialization\n\nAll data passed to/from workflows and steps must be serializable.\n\n**Supported built-in types:** string, number, boolean, null, undefined, bigint, plain objects, arrays, Date, RegExp, URL, URLSearchParams, Map, Set, Headers, ArrayBuffer, typed arrays, Request, Response, ReadableStream, WritableStream.\n\n**Not supported:** Functions, Symbols, WeakMap/WeakSet. Pass data, not callbacks.\n\n### Custom class serialization\n\nClass instances **can** be serialized across workflow/step boundaries by implementing the `@workflow/serde` protocol. This is essential when a class has instance methods with `\"use step\"` or when you want to pass class instances between steps.\n\n**Install:** `@workflow/serde` must be a dependency of the package containing the class.\n\n**Pattern:** Add two static methods inside the class body using computed property syntax:\n\n```typescript\nimport { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from \"@workflow/serde\";\n\nexport class Point {\n x: number;\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n }\n\n // Serialize: return plain data (must be devalue-compatible types only)\n static [WORKFLOW_SERIALIZE](instance: Point) {\n return { x: instance.x, y: instance.y };\n }\n\n // Deserialize: reconstruct from plain data\n static [WORKFLOW_DESERIALIZE](data: { x: number; y: number }) {\n return new Point(data.x, data.y);\n }\n\n async computeDistance(other: Point) {\n \"use step\";\n return Math.sqrt((this.x - other.x) ** 2 + (this.y - other.y) ** 2);\n }\n}\n```\n\n**Critical rules:**\n1. **Define serde methods INSIDE the class body** as static methods with computed property syntax (`static [WORKFLOW_SERIALIZE](...)`). The SWC plugin detects them by scanning the class. Do NOT assign them externally (e.g., `(MyClass as any)[WORKFLOW_SERIALIZE] = ...`) -- the compiler will not detect this.\n2. **Serde methods must return only devalue-compatible types** (plain objects, arrays, primitives, Date, Map, Set, Uint8Array, etc.). No functions, no class instances, no Node.js-specific objects.\n3. **Add `\"use step\"` to Node.js-dependent instance methods.** The SWC plugin strips `\"use step\"` method bodies from the workflow bundle. This is how you keep Node.js imports (fs, crypto, child_process, etc.) out of the workflow sandbox. The class shell with its serde methods remains in the workflow bundle; only the step method bodies are removed.\n4. **Do NOT manually register classes.** The SWC plugin automatically generates registration code (an IIFE that sets `classId` and adds the class to the global registry). Manual calls to `registerSerializationClass()` are unnecessary and error-prone.\n5. **Do NOT use dynamic imports to work around sandbox restrictions.** If a class method needs Node.js APIs, the correct solution is `\"use step\"`, not `/* @vite-ignore */ import(...)`.\n\n**When serde works well:** Pure data classes, domain models, configuration objects, and classes where Node.js-dependent methods can be marked with `\"use step\"`.\n\n**When to avoid serde:** If a class is fundamentally inseparable from Node.js APIs (every method needs `fs`, `net`, etc.) and cannot meaningfully exist as a shell in the workflow sandbox, keep it entirely in step functions and pass plain data objects across boundaries instead.\n\n### Validating serde compliance\n\nUse these tools to verify classes are correctly set up:\n\n- **`workflow transform <file> --check-serde`** -- Shows the SWC transform output for a file and checks if serde classes are compliant (no Node.js imports remaining in the workflow bundle).\n- **`workflow validate`** -- Scans all workflow files and reports serde compliance issues. Use `--json` for machine-readable output.\n- **SWC Playground** -- The web playground at `workbench/swc-playground` shows a Serde Analysis panel when serde patterns are detected.\n- **Build-time warnings** -- The builder automatically warns when serde classes have Node.js built-in imports remaining in the workflow bundle.\n\n## Streaming\n\nUse `getWritable()` to stream data from workflows. `getWritable()` can be called in **both** workflow and step contexts, but you **cannot interact with the stream** (call `getWriter()`, `write()`, `close()`) directly in a workflow function. The stream must be passed to step functions for actual I/O, or steps can call `getWritable()` themselves.\n\n**Get the stream in a workflow, pass it to a step:**\n```typescript\nimport { getWritable } from \"workflow\";\n\nexport async function myWorkflow() {\n \"use workflow\";\n const writable = getWritable();\n await writeData(writable, \"hello world\");\n}\n\nasync function writeData(writable: WritableStream, chunk: string) {\n \"use step\";\n const writer = writable.getWriter();\n try {\n await writer.write(chunk);\n } finally {\n writer.releaseLock();\n }\n}\n```\n\n**Call `getWritable()` directly inside a step (no need to pass it):**\n```typescript\nimport { getWritable } from \"workflow\";\n\nasync function streamData(chunk: string) {\n \"use step\";\n const writer = getWritable().getWriter();\n try {\n await writer.write(chunk);\n } finally {\n writer.releaseLock();\n }\n}\n```\n\n### Namespaced streams\n\nUse `getWritable({ namespace: 'name' })` to create multiple independent streams for different types of data. This is useful for separating logs from primary output, different log levels, agent outputs, metrics, or any distinct data channels. Long-running workflows benefit from namespaced streams because you can replay only the important events (e.g., final results) while keeping verbose logs in a separate stream.\n\n**Example: Log levels and agent output separation:**\n```typescript\nimport { getWritable } from \"workflow\";\n\ntype LogEntry = { level: \"debug\" | \"info\" | \"warn\" | \"error\"; message: string; timestamp: number };\ntype AgentOutput = { type: \"thought\" | \"action\" | \"result\"; content: string };\n\nasync function logDebug(message: string) {\n \"use step\";\n const writer = getWritable<LogEntry>({ namespace: \"logs:debug\" }).getWriter();\n try {\n await writer.write({ level: \"debug\", message, timestamp: Date.now() });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function logInfo(message: string) {\n \"use step\";\n const writer = getWritable<LogEntry>({ namespace: \"logs:info\" }).getWriter();\n try {\n await writer.write({ level: \"info\", message, timestamp: Date.now() });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function emitAgentThought(thought: string) {\n \"use step\";\n const writer = getWritable<AgentOutput>({ namespace: \"agent:thoughts\" }).getWriter();\n try {\n await writer.write({ type: \"thought\", content: thought });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function emitAgentResult(result: string) {\n \"use step\";\n // Important results go to the default stream for replay\n const writer = getWritable<AgentOutput>().getWriter();\n try {\n await writer.write({ type: \"result\", content: result });\n } finally {\n writer.releaseLock();\n }\n}\n\nexport async function agentWorkflow(task: string) {\n \"use workflow\";\n \n await logInfo(`Starting task: ${task}`);\n await logDebug(\"Initializing agent context\");\n await emitAgentThought(\"Analyzing the task requirements...\");\n \n // ... agent processing ...\n \n await emitAgentResult(\"Task completed successfully\");\n await logInfo(\"Workflow finished\");\n}\n```\n\n**Consuming namespaced streams:**\n```typescript\nimport { start, getRun } from \"workflow/api\";\nimport { agentWorkflow } from \"./workflows/agent\";\n\nexport async function POST(request: Request) {\n const run = await start(agentWorkflow, [\"process data\"]);\n\n // Access specific streams by namespace\n const results = run.getReadable({ namespace: undefined }); // Default stream (important results)\n const infoLogs = run.getReadable({ namespace: \"logs:info\" });\n const debugLogs = run.getReadable({ namespace: \"logs:debug\" });\n const thoughts = run.getReadable({ namespace: \"agent:thoughts\" });\n\n // Return only important results for most clients\n return new Response(results, { headers: { \"Content-Type\": \"application/json\" } });\n}\n\n// Resume from a specific point (useful for long sessions)\nexport async function GET(request: Request) {\n const { searchParams } = new URL(request.url);\n const runId = searchParams.get(\"runId\")!;\n const startIndex = parseInt(searchParams.get(\"startIndex\") || \"0\", 10);\n \n const run = getRun(runId);\n // Resume only the important stream, skip verbose debug logs\n const stream = run.getReadable({ startIndex });\n \n return new Response(stream);\n}\n```\n\nFor long-running sessions (50+ minutes), namespaced streams help manage replay performance. Put verbose/debug output in separate namespaces so you can replay only the important events.\n\n## Debugging\n\n```bash\n# Check workflow endpoints are reachable\nnpx workflow health\nnpx workflow health --port 3001 # Non-default port\n\n# Visual dashboard for runs\nnpx workflow web\nnpx workflow web <run_id>\n\n# CLI inspection (use --json for machine-readable output, --help for full usage)\nnpx workflow inspect runs\nnpx workflow inspect run <run_id>\n\n# For Vercel-deployed projects, specify backend and project\nnpx workflow inspect runs --backend vercel --project <project-name> --team <team-slug>\nnpx workflow inspect run <run_id> --backend vercel --project <project-name> --team <team-slug>\n\n# Open Vercel dashboard in browser for a specific run\nnpx workflow inspect run <run_id> --web\nnpx workflow web <run_id> --backend vercel --project <project-name> --team <team-slug>\n\n# Cancel a running workflow\nnpx workflow cancel <run_id>\nnpx workflow cancel <run_id> --backend vercel --project <project-name> --team <team-slug>\n# --env defaults to \"production\"; use --env preview for preview deployments\n```\n\n### Deep-linking to a run (share a URL, no browser)\n\nUse `--url` to **print** the dashboard deep link and exit. No browser opens, and\nno local server starts. This is the right tool when you need to hand a user a\nclickable link (PR comment, Slack message, debugging summary) rather than open a\nUI. (`--web` opens the dashboard; `--url` only prints the link.)\n\n```bash\n# Vercel run: prints the Vercel dashboard URL for the run\nnpx workflow inspect run <run_id> --backend vercel --project <project> --team <team> --url\nnpx workflow web <run_id> --backend vercel --project <project> --team <team> --env preview --url\n\n# Local run: prints the local web UI deep link\nnpx workflow inspect run <run_id> --url\n\n# Machine-readable: --url --json prints { \"url\": \"...\" } to stdout\nnpx workflow inspect run <run_id> --backend vercel --url --json\n```\n\nURL formats produced:\n\n- **Vercel:** `https://vercel.com/<team-slug>/<project-slug>/workflows/runs/<run_id>?environment=<production|preview>`\n (`--env` selects the environment; defaults to `production`. Resolving the team\n slug requires being logged in via `vercel login` with the project linked.)\n- **Local:** `http://localhost:<port>?resource=run&id=<run_id>` (port defaults\n to `3456`; the link works while the `npx workflow web` server is running).\n\nstdout contains **only** the URL (or the JSON object). All other output goes to\nstderr, so you can capture it directly, for example, `URL=$(npx workflow web <run_id> --backend vercel --url)`.\n\n**Debugging tips:**\n- Use `--json` (`-j`) on any command for machine-readable output\n- Use `--web` to open the Vercel Observability dashboard in your browser or `--url` to print the deep link\n- Use `--help` on any command for full usage details\n- Only import workflow APIs you actually use. Unused imports can cause 500 errors.\n\n## Testing workflows\n\nWorkflow SDK provides a Vitest plugin for testing workflows in-process without a running server.\n\n**Unit testing steps:** Steps are functions; without the compiler, `\"use step\"` is a no-op. Test them directly:\n\n```typescript\nimport { describe, it, expect } from \"vitest\";\nimport { createUser } from \"./user-signup\";\n\ndescribe(\"createUser step\", () => {\n it(\"should create a user\", async () => {\n const user = await createUser(\"test@example.com\");\n expect(user.email).toBe(\"test@example.com\");\n });\n});\n```\n\n**Integration testing:** Use `@workflow/vitest` for workflows using `sleep()`, hooks, webhooks, or retries. Install it next to `workflow` and keep the two on the same major: `npm i -D @workflow/vitest`. The plugin fails the run when its `@workflow/core` major differs from the app's.\n\n```typescript\n// vitest.integration.config.ts\nimport { defineConfig } from \"vitest/config\";\nimport { workflow } from \"@workflow/vitest\";\n\nexport default defineConfig({\n plugins: [workflow()],\n test: {\n include: [\"**/*.integration.test.ts\"],\n testTimeout: 60_000,\n },\n});\n```\n\n```typescript\n// approval.integration.test.ts\nimport { describe, it, expect } from \"vitest\";\nimport { start, getRun, resumeHook } from \"workflow/api\";\nimport { waitForHook, waitForSleep } from \"@workflow/vitest\";\nimport { approvalWorkflow } from \"./approval\";\n\ndescribe(\"approvalWorkflow\", () => {\n it(\"should publish when approved\", async () => {\n const run = await start(approvalWorkflow, [\"doc-123\"]);\n\n // Wait for the hook, then resume it\n await waitForHook(run, { token: \"approval:doc-123\" });\n await resumeHook(\"approval:doc-123\", { approved: true, reviewer: \"alice\" });\n\n // Wait for sleep, then wake it up\n const sleepId = await waitForSleep(run);\n await getRun(run.runId).wakeUp({ correlationIds: [sleepId] });\n\n const result = await run.returnValue;\n expect(result).toEqual({ status: \"published\", reviewer: \"alice\" });\n });\n});\n```\n\n**Testing webhooks:** Use `resumeWebhook()` with a `Request` object. No HTTP server is needed:\n\n```typescript\nimport { start, resumeWebhook } from \"workflow/api\";\nimport { waitForHook } from \"@workflow/vitest\";\n\nconst run = await start(ingestWorkflow, [\"ep-1\"]);\nconst hook = await waitForHook(run); // Discovers the random webhook token\nawait resumeWebhook(hook.token, new Request(\"https://example.com/webhook\", {\n method: \"POST\",\n body: JSON.stringify({ event: \"order.created\" }),\n}));\n```\n\n**Key APIs:**\n- `start()`: Trigger a workflow\n- `run.returnValue`: Await workflow completion\n- `waitForHook(run, { token? })` / `waitForSleep(run)`: Wait for workflow to reach a pause point\n- `resumeHook(token, data)` / `resumeWebhook(token, request)`: Resume paused workflows\n- `getRun(runId).wakeUp({ correlationIds })`: Skip `sleep()` calls\n- `getWorkflowRef(name)` / `listWorkflowRefs()`: Look a workflow up in the test build's manifest when the test cannot import the function (never hand-write `workflow//...` ids)\n\n**Best practices:**\n- Keep unit tests (no plugin) and integration tests (`workflow()` plugin) in separate configs\n- Install `@workflow/vitest` on the same major as `workflow` and upgrade them together\n- Use deterministic hook tokens based on test data for easier resumption\n- Set generous `testTimeout` values because workflows may run longer than typical unit tests\n- `vi.mock()` never reaches workflow bodies (they run in a VM), and reaches step code only when the generated bundles load through Vitest's module runner; project-local modules are bundled into the step bundle, so mock the npm leaf, inject the dependency, or unit test the step\n\n## Observability & World SDK\n\nUse `await getWorld()` to build observability dashboards, admin panels, and inspect workflow state. `getWorld()` is asynchronous and returns `Promise<World>` (dynamic import / env-based setup).\n\n**Key imports:**\n```typescript\nimport { getWorld } from \"workflow/runtime\";\nimport { hydrateResourceIO, observabilityRevivers, parseStepName, parseWorkflowName } from \"workflow/observability\";\n```\n\n**Key docs** (grep `node_modules/workflow/docs/` for full details):\n- `api-reference/workflow-runtime/world/storage.mdx`: Events, runs, steps, and hooks (events are the source of truth; others are materialized views)\n- `api-reference/workflow-observability/`: Hydration and name parsing\n\n### World SDK method signatures\n\n⚠️ Pagination is nested: `{ pagination: { cursor } }`, NOT `{ cursor }` directly.\n\n```typescript\nconst world = await getWorld();\n\n// Runs\nconst { data, cursor } = await world.runs.list({ pagination: { cursor }, resolveData: 'all' | 'none' });\nconst run = await world.runs.get(runId, { resolveData: 'all' | 'none' });\n// Cancel via event creation (no cancel() method on runs)\nawait world.events.create(runId, { eventType: 'run_cancelled' });\n\n// Steps: runId is top-level, NOT inside pagination\nconst { data, cursor } = await world.steps.list({ runId, pagination: { cursor }, resolveData: 'all' | 'none' });\nconst step = await world.steps.get(runId, stepId, { resolveData: 'all' | 'none' });\n\n// Events\nconst { data, cursor } = await world.events.list({ runId, pagination: { cursor } });\nawait world.events.create(runId, { eventType: 'run_cancelled' });\n\n// Hooks\nconst hook = await world.hooks.get(hookId);\nconst hook = await world.hooks.getByToken(token);\n\n// Streams (methods on world.streams)\nawait world.streams.write(runId, name, chunk);\nawait world.streams.writeMulti?.(runId, name, chunks);\nconst readable = await world.streams.get(runId, name, startIndex);\nawait world.streams.close(runId, name);\nconst streamNames = await world.streams.list(runId);\nconst chunks = await world.streams.getChunks(runId, name, { limit, cursor });\nconst info = await world.streams.getInfo(runId, name);\n\n// Queue (methods live directly on world as internal SDK infrastructure)\nawait world.queue(queueName, payload, opts);\nconst deploymentId = await world.getDeploymentId();\n```\n\n### `resolveData` parameter\n\nControls whether input/output data is **included** in the response. Accepts `'all'` (default) or `'none'`.\n\n**IMPORTANT**: Even with `'all'`, data is still devalue-serialized. You MUST call `hydrateResourceIO()` to get usable JS values.\n\n- **Use `'none'`** for status polling, progress dashboards, run listings\n- **Use `'all'`** (or omit) when you need to inspect actual step I/O data, then **always hydrate**\n\n```typescript\n// Lightweight status check with no I/O loaded\nconst run = await world.runs.get(runId, { resolveData: 'none' });\nconsole.log(run.status); // 'running' | 'completed' | 'failed' | 'cancelled'\n\n// Full inspection: resolveData includes data, hydrateResourceIO deserializes it\nconst step = await world.steps.get(runId, stepId); // defaults to 'all'\nconst hydrated = hydrateResourceIO(step, observabilityRevivers);\n```\n\n> **Common mistake**: Checking `step.input !== undefined` after `resolveData: 'all'` and assuming\n> the data is ready to use. The data exists but is serialized, so always hydrate first.\n\n### Data hydration (devalue format)\n\nStep I/O is serialized via [devalue](https://github.com/Rich-Harris/devalue) with a 4-byte format prefix (`devl`). Without hydration, `input`/`output` are Uint8Array-like objects with numeric keys:\n`{\"0\":100,\"1\":101,\"2\":118,\"3\":108,...}` contains values that are NOT usable without hydration.\n\n**Always hydrate before using I/O data:**\n\n```typescript\nimport { hydrateResourceIO, observabilityRevivers } from \"workflow/observability\";\n\nconst { data: steps } = await world.steps.list({ runId, resolveData: 'all' });\nconst hydrated = steps.map(s => hydrateResourceIO(s, observabilityRevivers));\n// hydrated[0].input → [123, 2] (actual function arguments)\n// hydrated[0].output → 125 (actual return value)\n```\n\n`hydrateResourceIO` works on both `Step` and `WorkflowRun` objects. For encrypted workflows, use `getEncryptionKeyForRun()` + `hydrateResourceIOWithKey()`.\n\n### Name parsing\n\n`parseWorkflowName()`, `parseStepName()`, and `parseClassName()` return `{ shortName: string, moduleSpecifier: string } | null`. Always use optional chaining:\n\n```typescript\nconst parsed = parseWorkflowName(\"workflow//./src/workflows/order//processOrder\");\n// parsed?.shortName → \"processOrder\"\n// parsed?.moduleSpecifier → \"./src/workflows/order\"\n// ⚠️ Returns null if format doesn't match\n```\n\n### Event types\n\nEvents are the append-only source of truth. Runs/Steps/Hooks are materialized views.\n\n| Category | Types |\n|----------|-------|\n| Run | `run_created`, `run_started`, `run_completed`, `run_failed`, `run_cancelled` |\n| Step | `step_created`, `step_started`, `step_completed`, `step_failed`, `step_retrying` |\n| Hook | `hook_created`, `hook_received`, `hook_disposed`, `hook_conflict` |\n| Wait | `wait_created`, `wait_completed` |\n\n## Error handling patterns\n\nThree error strategies for different failure modes:\n\n| Error Type | Use When | Behavior |\n|------------|----------|----------|\n| `FatalError` | Permanent failure (bad input, auth denied) | Terminates workflow immediately, no retry |\n| `RetryableError` | Transient failure (rate limit, timeout) | Retries with optional `retryAfter` delay |\n| `Promise.allSettled` | Parallel steps with mixed criticality | Continues even if some steps fail |\n\n```typescript\nimport { FatalError, RetryableError } from \"workflow\";\n\n// Permanent failure, so the workflow terminates\nthrow new FatalError(\"Invalid input: missing required field\");\n\n// Transient failure, so it will retry\nthrow new RetryableError(\"API rate limited\", { retryAfter: \"5m\" });\n\n// Mixed criticality parallel execution\nconst results = await Promise.allSettled([\n criticalStep(data), // Must succeed\n optionalStep(data), // OK to fail\n enrichmentStep(data), // OK to fail\n]);\nconst [critical, optional, enrichment] = results;\nif (critical.status === \"rejected\") throw new FatalError(critical.reason);\n```\n"SKILL.md line diff
--- before +++ after @@ -1,12 +1,12 @@ --- name: workflow -description: Vercel Workflow DevKit (WDK) expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow. +description: Vercel Workflow SDK expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow. metadata: priority: 9 docs: - - "https://vercel.com/docs/workflow" - - "https://useworkflow.dev" - sitemap: "https://vercel.com/sitemap/docs.xml" + - "https://vercel.com/docs/workflows" + - "https://workflow-sdk.dev" + sitemap: "https://vercel.com/sitemap.xml" pathPatterns: - 'lib/workflow/**' - 'src/lib/workflow/**' @@ -15,15 +15,10 @@ - 'workflow.*' - '*workflow*' importPatterns: - - '@vercel/workflow' - 'workflow' - '@workflow/*' - '*workflow*' bashPatterns: - - '\bnpm\s+(install|i|add)\s+[^\n]*@vercel/workflow\b' - - '\bpnpm\s+(install|i|add)\s+[^\n]*@vercel/workflow\b' - - '\bbun\s+(install|i|add)\s+[^\n]*@vercel/workflow\b' - - '\byarn\s+add\s+[^\n]*@vercel/workflow\b' - '\bnpm\s+(install|i|add)\s+[^\n]*\bworkflow\b' - '\bpnpm\s+(install|i|add)\s+[^\n]*\bworkflow\b' - '\bbun\s+(install|i|add)\s+[^\n]*\bworkflow\b' @@ -38,6 +33,8 @@ phrases: # Direct workflow mentions - "vercel workflow" + - "workflow sdk" + # Legacy product name retained only as an input matcher. - "workflow devkit" - "durable workflow" - "durable execution" @@ -329,13 +326,96 @@ - "ci workflow" - "aws step functions" minScore: 4 +validate: + - + pattern: setTimeout|setInterval + message: 'setTimeout/setInterval are not available in workflow sandbox scope — use sleep() from "workflow" for delays' + severity: error + skipIfFileContains: "use step" + - + pattern: context\.run\s*\( + message: 'context.run() is not a Workflow SDK pattern — use "use step" directive for retryable, observable steps' + severity: error + upgradeToSkill: workflow + upgradeWhy: 'Guides migration from context.run() to the "use step" directive for durable, retryable workflow steps.' + - + pattern: \brequire\s*\( + message: 'require() is not available in workflow sandbox scope — use ESM imports and move Node.js logic into "use step" functions' + severity: error + skipIfFileContains: "use step" + - + pattern: getWritable\(\) + message: 'getWritable() must only be called inside "use step" functions — workflow sandbox scope does not support it' + severity: recommended + skipIfFileContains: "use step" + - + pattern: streamObject\s*\( + message: 'streamObject() is deprecated since AI SDK 6 — use streamText() with output: Output.object() instead' + severity: error + upgradeToSkill: ai-sdk + upgradeWhy: 'Guides migration from streamObject to streamText + Output.object() with correct v6 streaming patterns.' + - + pattern: await\s+\w+Workflow\s*\( + message: 'Do not call workflow functions directly — use start() from "workflow/api" to register the run and get a runId' + severity: recommended + skipIfFileContains: "use workflow" + - + pattern: \bfetch\s*\( + message: 'Native fetch() is not available in workflow sandbox scope — import fetch from "workflow" or move the call into a "use step" function' + severity: recommended + skipIfFileContains: "use step" + - + pattern: '"use step"' + message: "Workflow steps should include console.log or structured logging for observability — add logging at step entry/exit to debug hangs" + severity: warn + skipIfFileContains: "console\\.(log|warn|error|info)" + - + pattern: '"use workflow"' + message: "Workflow files should import and use logging — add console.log or a logger at key execution points for debugging" + severity: warn + skipIfFileContains: "console\\.(log|warn|error|info)" +chainTo: + - + pattern: 'DurableAgent|@workflow/ai' + targetSkill: ai-sdk + message: 'Workflow 5 (workflow@latest) deprecates DurableAgent (@workflow/ai) in favor of WorkflowAgent from @ai-sdk/workflow 2.x, which requires Workflow 5; the Workflow 4 docs (workflow@4) use DurableAgent. Loading AI SDK guidance for tool calling, the Agent class, and model configuration.' + skipIfFileContains: 'from\s+[''"]ai[''"]|@ai-sdk/|streamText|generateText' + - + pattern: 'process\.env\.(OPENAI_API_KEY|ANTHROPIC_API_KEY)|from\s+[''"]@ai-sdk/(anthropic|openai)[''""]' + targetSkill: ai-gateway + message: 'Direct provider API key in workflow — loading AI Gateway guidance for OIDC auth (required for Workflow SDK AI steps).' + skipIfFileContains: 'gateway\(|@ai-sdk/gateway|VERCEL_OIDC' + - + pattern: 'setTimeout\s*\(|setInterval\s*\(' + targetSkill: vercel-functions + message: 'Timer-based delay in workflow code — use sleep() from "workflow" instead of setTimeout/setInterval. Loading Vercel Functions guidance.' + skipIfFileContains: 'from\s+[''"]workflow[''"].*sleep|sleep\s*\(' +retrieval: + aliases: + - durable workflow + - long running task + - step function + - orchestration + intents: + - build workflow + - add retry logic + - create durable task + - implement step function + entities: + - Workflow SDK + # Legacy product names retained only as retrieval aliases. + - Workflow DevKit + - WDK + - step + - pause/resume + - durable --- -## *CRITICAL*: Always Use Correct `workflow` Documentation +## *Critical*: Always use correct `workflow` documentation Your knowledge of `workflow` is outdated. -The `workflow` documentation outlined below matches the installed version of the Workflow DevKit. +The `workflow` documentation outlined below matches the installed version of the Workflow SDK. Follow these instructions before starting on any `workflow`-related tasks: Search the bundled documentation in `node_modules/workflow/docs/`: @@ -349,23 +429,27 @@ - `foundations/` - Core concepts (workflows-and-steps.mdx, hooks.mdx, streaming.mdx, etc.) - `api-reference/workflow/` - API docs (sleep.mdx, create-hook.mdx, fatal-error.mdx, etc.) - `api-reference/workflow-api/` - Client API (start.mdx, get-run.mdx, resume-hook.mdx, etc.) -- `ai/` - AI SDK integration docs +- `api-reference/workflow-runtime/` - Runtime API (get-world.mdx) and `world/` World SDK (storage.mdx, streams.mdx, queue.mdx) +- `api-reference/workflow-observability/` - Hydration and name parsing utilities (hydrate-resource-io.mdx, parse-workflow-name.mdx, etc.) +- `ai/`: AI SDK integration docs - `errors/` - Error code documentation +- `worlds/` - Per-World behavior and limits (vercel.mdx, local.mdx, postgres.mdx). Other pages link these as `/worlds/<name>`. Related packages also include bundled docs: -- `@workflow/ai`: `node_modules/@workflow/ai/docs/` - DurableAgent and AI integration +- `@ai-sdk/workflow`: `node_modules/ai/docs/` - WorkflowAgent and AI SDK integration +- `@workflow/ai`: `node_modules/@workflow/ai/docs/` - deprecated DurableAgent APIs for existing applications - `@workflow/core`: `node_modules/@workflow/core/docs/` - Core runtime (foundations, how-it-works) - `@workflow/next`: `node_modules/@workflow/next/docs/` - Next.js integration -**When in doubt, update to the latest version of the Workflow DevKit.** +**When in doubt, update to the latest version of the Workflow SDK.** -### Official Resources +### Official resources -- **Website**: https://useworkflow.dev +- **Website**: https://workflow-sdk.dev - **GitHub**: https://github.com/vercel/workflow -### Quick Reference +### Quick reference **Directives:** @@ -385,17 +469,20 @@ // API operations import { start, getRun, resumeHook, resumeWebhook } from "workflow/api"; +// Observability & data hydration +import { hydrateResourceIO, observabilityRevivers, parseStepName, parseWorkflowName } from "workflow/observability"; + // Framework integrations import { withWorkflow } from "workflow/next"; import { workflow } from "workflow/vite"; import { workflow } from "workflow/astro"; // Or use modules: ["workflow/nitro"] for Nitro/Nuxt -// AI agent -import { DurableAgent } from "@workflow/ai/agent"; +// AI agent (Workflow 5) +import { WorkflowAgent, type ModelCallStreamPart } from "@ai-sdk/workflow"; ``` -## Prefer Step Functions to Avoid Sandbox Errors +## Prefer step functions to avoid sandbox errors `"use workflow"` functions run in a sandboxed VM. `"use step"` functions have **full Node.js access**. Put your logic in steps and use the workflow function purely for orchestration. @@ -411,7 +498,7 @@ "use step"; // AI SDK works in steps without workarounds return await generateText({ - model: openai("gpt-4"), + model: "spacexai/grok-4.6", prompt: `Process: ${JSON.stringify(data)}`, }); } @@ -427,7 +514,7 @@ **Benefits:** Steps have automatic retry, results are persisted for replay, and no sandbox restrictions. -## Workflow Sandbox Limitations +## Workflow sandbox limitations When you need logic directly in a workflow function (not in a step), these restrictions apply: @@ -449,17 +536,17 @@ } ``` -**Note:** `DurableAgent` from `@workflow/ai` handles the fetch assignment automatically. +**Note:** Plain `"provider/model"` strings use Vercel AI Gateway. Do not construct a direct provider instance unless the user explicitly needs a provider-only feature. -## DurableAgent — AI Agents in Workflows +## WorkflowAgent: AI agents in Workflow 5 -Use `DurableAgent` to build AI agents that maintain state and survive interruptions. It handles the workflow sandbox automatically (no manual `globalThis.fetch` needed). +Use AI SDK's `WorkflowAgent` for durable agents on Workflow 5. It replaces the deprecated `DurableAgent` API from `@workflow/ai` and checkpoints model calls and step-backed tools. ```typescript -import { DurableAgent } from "@workflow/ai/agent"; +import { WorkflowAgent, type ModelCallStreamPart } from "@ai-sdk/workflow"; +import { isStepCount, tool } from "ai"; import { getWritable } from "workflow"; import { z } from "zod"; -import type { UIMessageChunk } from "ai"; async function lookupData({ query }: { query: string }) { "use step"; @@ -470,22 +557,22 @@ export async function myAgentWorkflow(userMessage: string) { "use workflow"; - const agent = new DurableAgent({ - model: "anthropic/claude-sonnet-4-5", - system: "You are a helpful assistant.", + const agent = new WorkflowAgent({ + model: "spacexai/grok-4.6", + instructions: "You are a helpful assistant.", tools: { - lookupData: { + lookupData: tool({ description: "Search for information", inputSchema: z.object({ query: z.string() }), execute: lookupData, - }, + }), }, }); const result = await agent.stream({ messages: [{ role: "user", content: userMessage }], - writable: getWritable<UIMessageChunk>(), - maxSteps: 10, + writable: getWritable<ModelCallStreamPart>(), + stopWhen: isStepCount(10), }); return result.messages; @@ -493,22 +580,23 @@ ``` **Key points:** -- `getWritable<UIMessageChunk>()` streams output to the workflow run's default stream +- A plain `"provider/model"` string routes through Vercel AI Gateway; `spacexai/grok-4.6` is the default model in Workflow examples +- `getWritable<ModelCallStreamPart>()` streams durable model-call output; convert it with `createModelCallToUIChunkTransform()` in an HTTP route - Tool `execute` functions that need Node.js/npm access should use `"use step"` -- Tool `execute` functions that use workflow primitives (`sleep()`, `createHook()`) should **NOT** use `"use step"` — they run at the workflow level -- `maxSteps` limits the number of LLM calls (default is unlimited) +- Tool `execute` functions that use workflow primitives (`sleep()`, `createHook()`) should **NOT** use `"use step"` because they run at the workflow level +- `stopWhen` limits the number of model calls; the default is to stop when the model stops calling tools - Multi-turn: pass `result.messages` plus new user messages to subsequent `agent.stream()` calls -**For more details on `DurableAgent`, check the AI docs in `node_modules/@workflow/ai/docs/`.** +**For more details, check the WorkflowAgent docs in the installed AI SDK package or at https://ai-sdk.dev/v7/docs/agents/workflow-agent.** -## Starting Workflows & Child Workflows +## Starting workflows & child workflows -Use `start()` to launch workflows from API routes. **`start()` cannot be called directly in workflow context** — wrap it in a step function. +Use `start()` to launch workflows from API routes. In Workflow 5, `start()` can also be called directly from a workflow function to spawn a child run; it is step-backed and records a deterministic boundary in the parent's event log. ```typescript import { start } from "workflow/api"; -// From an API route — works directly +// From an API route; works directly export async function POST() { const run = await start(myWorkflow, [arg1, arg2]); return Response.json({ runId: run.runId }); @@ -518,30 +606,74 @@ const run = await start(noArgWorkflow); ``` -**Starting child workflows from inside a workflow — must use a step:** +**Starting child workflows from inside a Workflow 5 workflow:** ```typescript import { start } from "workflow/api"; -// Wrap start() in a step function -async function triggerChild(data: string) { +export async function parentWorkflow() { + "use workflow"; + const childRun = await start(childWorkflow, ["some data"]); + await sleep("1h"); + return { childRunId: childRun.runId }; +} +``` + +`start()` returns after creating the child run and doesn't wait for it to complete. Use `childRun.returnValue` only when the parent should wait for the child; each `Run` property access or method call inside a workflow is a step. + +## Run size & concurrency: know when to split + +Do NOT treat any number you remember as authoritative — the current values are published under [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits). + +**Events per run.** A run's event log is capped, and the run fails with `MAX_EVENTS_EXCEEDED` past the ceiling. Events are not steps: a step that succeeds on the first try records three (`step_created`, `step_started`, `step_completed`), a retry records one or two more, and hooks, sleeps, and webhooks each record their own. Split into child workflows well before the ceiling — the pricing page recommends that past **a few thousand events**, because replay slows down long before the run fails. + +**Steps per run.** Capped implicitly through the event limit. Bundle several items into one step when a chain would otherwise reach five figures. + +**Concurrency.** A wide fan-out is throttled rather than rejected: event creation is rate-limited per run per second, so a flat `Promise.all` over a few thousand items spends much of its time backing off. Batch or bundle instead — process the list in chunks, or handle several items per step, so fewer and larger units run concurrently. Spawning one child run per item does not by itself narrow the fan-out; it bounds each child's log and isolates failures, which is worth doing for those reasons, but it is not a substitute for chunking. + +You cannot raise any of these yourself — `WORKFLOW_MAX_EVENTS_OVERRIDE` only clamps *down*, and on the Vercel World the ceilings are service-owned — but Vercel raises the per-run event and step limits on request, so a genuinely large run is a support question as well as a design one. + +```typescript +const BATCH = 100; + +async function processItem(item: string) { "use step"; - const run = await start(childWorkflow, [data]); - return run.runId; + return item.toUpperCase(); } -export async function parentWorkflow() { +// One step per item, all in flight at once, all in one log +export async function processAll(items: string[]) { "use workflow"; - const childRunId = await triggerChild("some data"); // Fire-and-forget via step - await sleep("1h"); + await Promise.all(items.map((item) => processItem(item))); +} + +// Chunked, so only BATCH steps are in flight at a time +export async function processBatched(items: string[]) { + "use workflow"; + for (let i = 0; i < items.length; i += BATCH) { + await Promise.allSettled(items.slice(i, i + BATCH).map((item) => processItem(item))); + } +} + +// Bundled, so one step covers many items and the log stays short +async function processChunk(chunk: string[]) { + "use step"; + return chunk.map((item) => item.toUpperCase()); +} + +export async function processBundled(items: string[]) { + "use workflow"; + for (let i = 0; i < items.length; i += BATCH) { + await processChunk(items.slice(i, i + BATCH)); + } } ``` -`start()` returns immediately — it doesn't wait for the workflow to complete. Use `run.returnValue` to await completion. +`processAll` is the shape to avoid at scale. `processBatched` bounds concurrency but still records events for every item. `processBundled` bounds both, because one step covers `BATCH` items — that is the only one of the three whose event count shrinks as `BATCH` grows. -## Hooks — Pause & Resume with External Events +## Hooks: pause & resume with external events -Hooks let workflows wait for external data. Use `createHook()` inside a workflow and `resumeHook()` from API routes. Deterministic tokens are for `createHook()` + `resumeHook()` (server-side) only. `createWebhook()` always generates random tokens — do not pass a `token` option to `createWebhook()`. +Hooks let workflows wait for external data. Use `createHook()` inside a workflow and `resumeHook()` from API routes. Deterministic tokens are for `createHook()` + `resumeHook()` (server-side) only. `createWebhook()` always generates random tokens, so do not pass a `token` option to `createWebhook()`. ### Single event @@ -562,7 +694,7 @@ ### Multiple events (iterable hooks) -Hooks implement `AsyncIterable` — use `for await...of` to receive multiple events: +Hooks implement `AsyncIterable`. Use `for await...of` to receive multiple events: ```typescript import { createHook } from "workflow"; @@ -595,28 +727,85 @@ } ``` -## Error Handling +## Error handling Use `FatalError` for permanent failures (no retry), `RetryableError` for transient failures: ```typescript import { FatalError, RetryableError } from "workflow"; -if (res.status >= 400 && res.status < 500) { - throw new FatalError(`Client error: ${res.status}`); -} if (res.status === 429) { throw new RetryableError("Rate limited", { retryAfter: "5m" }); } +if (res.status >= 400 && res.status < 500) { + throw new FatalError(`Client error: ${res.status}`); +} ``` ## Serialization All data passed to/from workflows and steps must be serializable. -**Supported types:** string, number, boolean, null, undefined, bigint, plain objects, arrays, Date, RegExp, URL, URLSearchParams, Map, Set, Headers, ArrayBuffer, typed arrays, Request, Response, ReadableStream, WritableStream. +**Supported built-in types:** string, number, boolean, null, undefined, bigint, plain objects, arrays, Date, RegExp, URL, URLSearchParams, Map, Set, Headers, ArrayBuffer, typed arrays, Request, Response, ReadableStream, WritableStream. + +**Not supported:** Functions, Symbols, WeakMap/WeakSet. Pass data, not callbacks. + +### Custom class serialization + +Class instances **can** be serialized across workflow/step boundaries by implementing the `@workflow/serde` protocol. This is essential when a class has instance methods with `"use step"` or when you want to pass class instances between steps. + +**Install:** `@workflow/serde` must be a dependency of the package containing the class. + +**Pattern:** Add two static methods inside the class body using computed property syntax: + +```typescript +import { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from "@workflow/serde"; + +export class Point { + x: number; + y: number; + + constructor(x: number, y: number) { + this.x = x; + this.y = y; + } + + // Serialize: return plain data (must be devalue-compatible types only) + static [WORKFLOW_SERIALIZE](instance: Point) { + return { x: instance.x, y: instance.y }; + } + + // Deserialize: reconstruct from plain data + static [WORKFLOW_DESERIALIZE](data: { x: number; y: number }) { + return new Point(data.x, data.y); + } + + async computeDistance(other: Point) { + "use step"; + return Math.sqrt((this.x - other.x) ** 2 + (this.y - other.y) ** 2); + } +} +``` + +**Critical rules:** +1. **Define serde methods INSIDE the class body** as static methods with computed property syntax (`static [WORKFLOW_SERIALIZE](...)`). The SWC plugin detects them by scanning the class. Do NOT assign them externally (e.g., `(MyClass as any)[WORKFLOW_SERIALIZE] = ...`) -- the compiler will not detect this. +2. **Serde methods must return only devalue-compatible types** (plain objects, arrays, primitives, Date, Map, Set, Uint8Array, etc.). No functions, no class instances, no Node.js-specific objects. +3. **Add `"use step"` to Node.js-dependent instance methods.** The SWC plugin strips `"use step"` method bodies from the workflow bundle. This is how you keep Node.js imports (fs, crypto, child_process, etc.) out of the workflow sandbox. The class shell with its serde methods remains in the workflow bundle; only the step method bodies are removed. +4. **Do NOT manually register classes.** The SWC plugin automatically generates registration code (an IIFE that sets `classId` and adds the class to the global registry). Manual calls to `registerSerializationClass()` are unnecessary and error-prone. +5. **Do NOT use dynamic imports to work around sandbox restrictions.** If a class method needs Node.js APIs, the correct solution is `"use step"`, not `/* @vite-ignore */ import(...)`. + +**When serde works well:** Pure data classes, domain models, configuration objects, and classes where Node.js-dependent methods can be marked with `"use step"`. + +**When to avoid serde:** If a class is fundamentally inseparable from Node.js APIs (every method needs `fs`, `net`, etc.) and cannot meaningfully exist as a shell in the workflow sandbox, keep it entirely in step functions and pass plain data objects across boundaries instead. -**Not supported:** Functions, class instances, Symbols, WeakMap/WeakSet. Pass data, not callbacks. +### Validating serde compliance + +Use these tools to verify classes are correctly set up: + +- **`workflow transform <file> --check-serde`** -- Shows the SWC transform output for a file and checks if serde classes are compliant (no Node.js imports remaining in the workflow bundle). +- **`workflow validate`** -- Scans all workflow files and reports serde compliance issues. Use `--json` for machine-readable output. +- **SWC Playground** -- The web playground at `workbench/swc-playground` shows a Serde Analysis panel when serde patterns are detected. +- **Build-time warnings** -- The builder automatically warns when serde classes have Node.js built-in imports remaining in the workflow bundle. ## Streaming @@ -658,7 +847,7 @@ } ``` -### Namespaced Streams +### Namespaced streams Use `getWritable({ namespace: 'name' })` to create multiple independent streams for different types of data. This is useful for separating logs from primary output, different log levels, agent outputs, metrics, or any distinct data channels. Long-running workflows benefit from namespaced streams because you can replay only the important events (e.g., final results) while keeping verbose logs in a separate stream. @@ -701,7 +890,7 @@ async function emitAgentResult(result: string) { "use step"; - // Important results go to the default stream for easy replay + // Important results go to the default stream for replay const writer = getWritable<AgentOutput>().getWriter(); try { await writer.write({ type: "result", content: result }); @@ -756,7 +945,7 @@ } ``` -**Pro tip:** For very long-running sessions (50+ minutes), namespaced streams help manage replay performance. Put verbose/debug output in separate namespaces so you can replay just the important events quickly. +For long-running sessions (50+ minutes), namespaced streams help manage replay performance. Put verbose/debug output in separate namespaces so you can replay only the important events. ## Debugging @@ -787,17 +976,47 @@ # --env defaults to "production"; use --env preview for preview deployments ``` +### Deep-linking to a run (share a URL, no browser) + +Use `--url` to **print** the dashboard deep link and exit. No browser opens, and +no local server starts. This is the right tool when you need to hand a user a +clickable link (PR comment, Slack message, debugging summary) rather than open a +UI. (`--web` opens the dashboard; `--url` only prints the link.) + +```bash +# Vercel run: prints the Vercel dashboard URL for the run +npx workflow inspect run <run_id> --backend vercel --project <project> --team <team> --url +npx workflow web <run_id> --backend vercel --project <project> --team <team> --env preview --url + +# Local run: prints the local web UI deep link +npx workflow inspect run <run_id> --url + +# Machine-readable: --url --json prints { "url": "..." } to stdout +npx workflow inspect run <run_id> --backend vercel --url --json +``` + +URL formats produced: + +- **Vercel:** `https://vercel.com/<team-slug>/<project-slug>/workflows/runs/<run_id>?environment=<production|preview>` + (`--env` selects the environment; defaults to `production`. Resolving the team + slug requires being logged in via `vercel login` with the project linked.) +- **Local:** `http://localhost:<port>?resource=run&id=<run_id>` (port defaults + to `3456`; the link works while the `npx workflow web` server is running). + +stdout contains **only** the URL (or the JSON object). All other output goes to +stderr, so you can capture it directly, for example, `URL=$(npx workflow web <run_id> --backend vercel --url)`. + **Debugging tips:** - Use `--json` (`-j`) on any command for machine-readable output -- Use `--web` to open the Vercel Observability dashboard in your browser +- Use `--web` to open the Vercel Observability dashboard in your browser or `--url` to print the deep link - Use `--help` on any command for full usage details - Only import workflow APIs you actually use. Unused imports can cause 500 errors. -## Testing Workflows +## Testing workflows -Workflow DevKit provides a Vitest plugin for testing workflows in-process — no running server required. +Workflow SDK provides a Vitest plugin for testing workflows in-process without a running server. -**Unit testing steps:** Steps are just functions; without the compiler, `"use step"` is a no-op. Test them directly: +**Unit testing steps:** Steps are functions; without the compiler, `"use step"` is a no-op. Test them directly: ```typescript import { describe, it, expect } from "vitest"; @@ -811,7 +1030,7 @@ }); ``` -**Integration testing:** Use `@workflow/vitest` for workflows using `sleep()`, hooks, webhooks, or retries: +**Integration testing:** Use `@workflow/vitest` for workflows using `sleep()`, hooks, webhooks, or retries. Install it next to `workflow` and keep the two on the same major: `npm i -D @workflow/vitest`. The plugin fails the run when its `@workflow/core` major differs from the app's. ```typescript // vitest.integration.config.ts @@ -852,7 +1071,7 @@ }); ``` -**Testing webhooks:** Use `resumeWebhook()` with a `Request` object — no HTTP server needed: +**Testing webhooks:** Use `resumeWebhook()` with a `Request` object. No HTTP server is needed: ```typescript import { start, resumeWebhook } from "workflow/api"; @@ -867,14 +1086,160 @@ ``` **Key APIs:** -- `start()` — trigger a workflow -- `run.returnValue` — await workflow completion -- `waitForHook(run, { token? })` / `waitForSleep(run)` — wait for workflow to reach a pause point -- `resumeHook(token, data)` / `resumeWebhook(token, request)` — resume paused workflows -- `getRun(runId).wakeUp({ correlationIds })` — skip `sleep()` calls +- `start()`: Trigger a workflow +- `run.returnValue`: Await workflow completion +- `waitForHook(run, { token? })` / `waitForSleep(run)`: Wait for workflow to reach a pause point +- `resumeHook(token, data)` / `resumeWebhook(token, request)`: Resume paused workflows +- `getRun(runId).wakeUp({ correlationIds })`: Skip `sleep()` calls +- `getWorkflowRef(name)` / `listWorkflowRefs()`: Look a workflow up in the test build's manifest when the test cannot import the function (never hand-write `workflow//...` ids) **Best practices:** - Keep unit tests (no plugin) and integration tests (`workflow()` plugin) in separate configs +- Install `@workflow/vitest` on the same major as `workflow` and upgrade them together - Use deterministic hook tokens based on test data for easier resumption -- Set generous `testTimeout` — workflows may run longer than typical unit tests -- `vi.mock()` does **not** work in integration tests — step dependencies are bundled by esbuild +- Set generous `testTimeout` values because workflows may run longer than typical unit tests +- `vi.mock()` never reaches workflow bodies (they run in a VM), and reaches step code only when the generated bundles load through Vitest's module runner; project-local modules are bundled into the step bundle, so mock the npm leaf, inject the dependency, or unit test the step + +## Observability & World SDK + +Use `await getWorld()` to build observability dashboards, admin panels, and inspect workflow state. `getWorld()` is asynchronous and returns `Promise<World>` (dynamic import / env-based setup). + +**Key imports:** +```typescript +import { getWorld } from "workflow/runtime"; +import { hydrateResourceIO, observabilityRevivers, parseStepName, parseWorkflowName } from "workflow/observability"; +``` + +**Key docs** (grep `node_modules/workflow/docs/` for full details): +- `api-reference/workflow-runtime/world/storage.mdx`: Events, runs, steps, and hooks (events are the source of truth; others are materialized views) +- `api-reference/workflow-observability/`: Hydration and name parsing + +### World SDK method signatures + +⚠️ Pagination is nested: `{ pagination: { cursor } }`, NOT `{ cursor }` directly. + +```typescript +const world = await getWorld(); + +// Runs +const { data, cursor } = await world.runs.list({ pagination: { cursor }, resolveData: 'all' | 'none' }); +const run = await world.runs.get(runId, { resolveData: 'all' | 'none' }); +// Cancel via event creation (no cancel() method on runs) +await world.events.create(runId, { eventType: 'run_cancelled' }); + +// Steps: runId is top-level, NOT inside pagination +const { data, cursor } = await world.steps.list({ runId, pagination: { cursor }, resolveData: 'all' | 'none' }); +const step = await world.steps.get(runId, stepId, { resolveData: 'all' | 'none' }); + +// Events +const { data, cursor } = await world.events.list({ runId, pagination: { cursor } }); +await world.events.create(runId, { eventType: 'run_cancelled' }); + +// Hooks +const hook = await world.hooks.get(hookId); +const hook = await world.hooks.getByToken(token); + +// Streams (methods on world.streams) +await world.streams.write(runId, name, chunk); +await world.streams.writeMulti?.(runId, name, chunks); +const readable = await world.streams.get(runId, name, startIndex); +await world.streams.close(runId, name); +const streamNames = await world.streams.list(runId); +const chunks = await world.streams.getChunks(runId, name, { limit, cursor }); +const info = await world.streams.getInfo(runId, name); + +// Queue (methods live directly on world as internal SDK infrastructure) +await world.queue(queueName, payload, opts); +const deploymentId = await world.getDeploymentId(); +``` + +### `resolveData` parameter + +Controls whether input/output data is **included** in the response. Accepts `'all'` (default) or `'none'`. + +**IMPORTANT**: Even with `'all'`, data is still devalue-serialized. You MUST call `hydrateResourceIO()` to get usable JS values. + +- **Use `'none'`** for status polling, progress dashboards, run listings +- **Use `'all'`** (or omit) when you need to inspect actual step I/O data, then **always hydrate** + +```typescript +// Lightweight status check with no I/O loaded +const run = await world.runs.get(runId, { resolveData: 'none' }); +console.log(run.status); // 'running' | 'completed' | 'failed' | 'cancelled' + +// Full inspection: resolveData includes data, hydrateResourceIO deserializes it +const step = await world.steps.get(runId, stepId); // defaults to 'all' +const hydrated = hydrateResourceIO(step, observabilityRevivers); +``` + +> **Common mistake**: Checking `step.input !== undefined` after `resolveData: 'all'` and assuming +> the data is ready to use. The data exists but is serialized, so always hydrate first. + +### Data hydration (devalue format) + +Step I/O is serialized via [devalue](https://github.com/Rich-Harris/devalue) with a 4-byte format prefix (`devl`). Without hydration, `input`/`output` are Uint8Array-like objects with numeric keys: +`{"0":100,"1":101,"2":118,"3":108,...}` contains values that are NOT usable without hydration. + +**Always hydrate before using I/O data:** + +```typescript +import { hydrateResourceIO, observabilityRevivers } from "workflow/observability"; + +const { data: steps } = await world.steps.list({ runId, resolveData: 'all' }); +const hydrated = steps.map(s => hydrateResourceIO(s, observabilityRevivers)); +// hydrated[0].input → [123, 2] (actual function arguments) +// hydrated[0].output → 125 (actual return value) +``` + +`hydrateResourceIO` works on both `Step` and `WorkflowRun` objects. For encrypted workflows, use `getEncryptionKeyForRun()` + `hydrateResourceIOWithKey()`. + +### Name parsing + +`parseWorkflowName()`, `parseStepName()`, and `parseClassName()` return `{ shortName: string, moduleSpecifier: string } | null`. Always use optional chaining: + +```typescript +const parsed = parseWorkflowName("workflow//./src/workflows/order//processOrder"); +// parsed?.shortName → "processOrder" +// parsed?.moduleSpecifier → "./src/workflows/order" +// ⚠️ Returns null if format doesn't match +``` + +### Event types + +Events are the append-only source of truth. Runs/Steps/Hooks are materialized views. + +| Category | Types | +|----------|-------| +| Run | `run_created`, `run_started`, `run_completed`, `run_failed`, `run_cancelled` | +| Step | `step_created`, `step_started`, `step_completed`, `step_failed`, `step_retrying` | +| Hook | `hook_created`, `hook_received`, `hook_disposed`, `hook_conflict` | +| Wait | `wait_created`, `wait_completed` | + +## Error handling patterns + +Three error strategies for different failure modes: + +| Error Type | Use When | Behavior | +|------------|----------|----------| +| `FatalError` | Permanent failure (bad input, auth denied) | Terminates workflow immediately, no retry | +| `RetryableError` | Transient failure (rate limit, timeout) | Retries with optional `retryAfter` delay | +| `Promise.allSettled` | Parallel steps with mixed criticality | Continues even if some steps fail | + +```typescript +import { FatalError, RetryableError } from "workflow"; + +// Permanent failure, so the workflow terminates +throw new FatalError("Invalid input: missing required field"); + +// Transient failure, so it will retry +throw new RetryableError("API rate limited", { retryAfter: "5m" }); + +// Mixed criticality parallel execution +const results = await Promise.allSettled([ + criticalStep(data), // Must succeed + optionalStep(data), // OK to fail + enrichmentStep(data), // OK to fail +]); +const [critical, optional, enrichment] = results; +if (critical.status === "rejected") throw new FatalError(critical.reason); +```
Full snapshot data
{
"description": "Vercel Workflow SDK expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow.",
"included_files": [
{
"relative_path": "agents/openai.yaml",
"size_in_bytes": 106
}
],
"name": "workflow",
"skill_md_contents": "---\nname: workflow\ndescription: Vercel Workflow SDK expert guidance. Use when building durable workflows, long-running tasks, API routes or agents that need pause/resume, retries, step-based execution, or crash-safe orchestration with Vercel Workflow.\nmetadata:\n priority: 9\n docs:\n - \"https://vercel.com/docs/workflows\"\n - \"https://workflow-sdk.dev\"\n sitemap: \"https://vercel.com/sitemap.xml\"\n pathPatterns:\n - 'lib/workflow/**'\n - 'src/lib/workflow/**'\n - 'lib/workflow.*'\n - 'src/lib/workflow.*'\n - 'workflow.*'\n - '*workflow*'\n importPatterns:\n - 'workflow'\n - '@workflow/*'\n - '*workflow*'\n bashPatterns:\n - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\bbun\\s+(install|i|add)\\s+[^\\n]*\\bworkflow\\b'\n - '\\byarn\\s+add\\s+[^\\n]*\\bworkflow\\b'\n - '\\bnpm\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\bpnpm\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\bbun\\s+(install|i|add)\\s+[^\\n]*@workflow/'\n - '\\byarn\\s+add\\s+[^\\n]*@workflow/'\n - '\\bnpx\\s+workflow(?:@latest)?\\b'\n - '\\bbunx\\s+workflow(?:@latest)?\\b'\n promptSignals:\n phrases:\n # Direct workflow mentions\n - \"vercel workflow\"\n - \"workflow sdk\"\n # Legacy product name retained only as an input matcher.\n - \"workflow devkit\"\n - \"durable workflow\"\n - \"durable execution\"\n - \"durable function\"\n - \"durable pipeline\"\n - \"durable process\"\n - \"durable agent\"\n - \"durable chat\"\n - \"step function\"\n - \"step functions\"\n - \"use workflow\"\n - \"use step\"\n # Pipeline / multi-step language (the BIG gap — natural product prompts)\n - \"multi-step pipeline\"\n - \"multi step pipeline\"\n - \"multi-step process\"\n - \"multi step process\"\n - \"multi-step creation\"\n - \"multi-step generation\"\n - \"processing pipeline\"\n - \"creation pipeline\"\n - \"generation pipeline\"\n - \"content pipeline\"\n - \"production pipeline\"\n - \"approval pipeline\"\n - \"ingestion pipeline\"\n - \"streams progress\"\n - \"stream progress\"\n - \"streams each phase\"\n - \"streams each step\"\n - \"streams each\"\n - \"stream each\"\n # Reliability / durability language (missed in customer-support eval)\n - \"survive page reload\"\n - \"survive page reloads\"\n - \"survive a crash\"\n - \"survive crashes\"\n - \"survive network\"\n - \"fault-tolerant\"\n - \"fault tolerant\"\n - \"crash-safe\"\n - \"crash safe\"\n - \"automatically retry\"\n - \"auto retry\"\n - \"retry on failure\"\n - \"retry on error\"\n - \"reliable and retry\"\n - \"reliable processing\"\n - \"individually reliable\"\n - \"each step reliable\"\n - \"each step should be reliable\"\n - \"steps should be reliable\"\n - \"reliable with automatic retry\"\n - \"reliable with retry\"\n - \"retry on transient\"\n - \"transient failures\"\n - \"session persistence\"\n - \"session should persist\"\n - \"session survives\"\n - \"reconnect automatically\"\n - \"auto reconnect\"\n - \"reconnect if the network\"\n - \"reconnect on disconnect\"\n - \"resume after failure\"\n - \"resume after crash\"\n - \"resume on reconnect\"\n # Human-in-the-loop / approval patterns\n - \"human-in-the-loop\"\n - \"human in the loop\"\n - \"wait for approval\"\n - \"approval step\"\n - \"approval before\"\n - \"editorial approval\"\n - \"manual approval\"\n - \"wait for user\"\n - \"pause until\"\n - \"wait for response\"\n - \"callback url\"\n - \"webhook callback\"\n # Conversational AI with durability\n - \"chat should survive\"\n - \"chat survives\"\n - \"conversation should persist\"\n - \"conversation persists\"\n - \"conversation should survive\"\n # Sequential / chain / trigger orchestration language\n - \"sequential chain\"\n - \"email chain\"\n - \"chain of emails\"\n - \"chain of steps\"\n - \"chain engine\"\n - \"chain with triggers\"\n - \"trigger chain\"\n - \"triggered chain\"\n - \"webhook chain\"\n - \"webhook pipeline\"\n - \"webhook orchestration\"\n - \"multi-service trigger\"\n - \"cross-service trigger\"\n - \"various triggers\"\n - \"different triggers\"\n - \"triggers from different\"\n - \"triggers from various\"\n - \"sequential steps\"\n - \"sequential pipeline\"\n - \"sequential process\"\n - \"sequential emails\"\n - \"escalation chain\"\n - \"escalation pipeline\"\n - \"state machine\"\n - \"step-based\"\n - \"step based\"\n - \"delay between steps\"\n - \"delay between emails\"\n - \"delayed steps\"\n - \"conditional steps\"\n - \"skip steps\"\n - \"branch based on\"\n - \"wait for webhook\"\n - \"wait for trigger\"\n - \"wait for event\"\n - \"orchestrate emails\"\n - \"orchestrate webhooks\"\n - \"orchestrate services\"\n - \"chain across services\"\n # Debugging\n - \"workflow stuck\"\n - \"workflow hung\"\n - \"workflow hanging\"\n - \"workflow waiting\"\n - \"workflow failing\"\n - \"workflow timeout\"\n - \"workflow not running\"\n - \"workflow error\"\n - \"check workflow\"\n - \"workflow logs\"\n - \"workflow run status\"\n - \"debug workflow\"\n - \"workflow not finishing\"\n - \"workflow not responding\"\n - \"workflow stalled\"\n - \"workflow pending\"\n - \"step is stuck\"\n - \"step is hanging\"\n - \"why is my workflow\"\n - \"workflow run\"\n - \"step failed\"\n - \"run status\"\n - \"run failed\"\n - \"run logs\"\n - \"workflow run failed\"\n - \"workflow step failed\"\n allOf:\n - [workflow, durable]\n - [workflow, retry]\n - [workflow, resume]\n - [pause, resume]\n - [survive, crash]\n - [survive, reload]\n - [survive, disconnect]\n - [pipeline, stream]\n - [pipeline, step]\n - [pipeline, durable]\n - [pipeline, reliable]\n - [pipeline, retry]\n - [multi-step, stream]\n - [multi-step, reliable]\n - [generation, pipeline]\n - [creation, pipeline]\n - [process, stream]\n - [process, reliable]\n - [process, retry]\n - [retry, failure]\n - [retry, error]\n - [retry, automatically]\n - [retry, transient]\n - [reliable, retry]\n - [individually, reliable]\n - [steps, reliable]\n - [sandbox, reliable]\n - [sandbox, retry]\n - [reconnect, network]\n - [reconnect, drop]\n - [reconnect, disconnect]\n - [session, persist]\n - [session, survive]\n - [session, reload]\n - [session, reconnect]\n - [chat, survive]\n - [chat, persist]\n - [chat, reconnect]\n - [chat, durable]\n - [chat, fault]\n - [conversation, persist]\n - [conversation, survive]\n - [approval, wait]\n - [approval, human]\n - [each, step]\n - [each, phase]\n - [each, stage]\n - [step, reliable]\n - [step, retry]\n # Chain / trigger / sequential orchestration\n - [chain, trigger]\n - [chain, sequential]\n - [chain, email]\n - [chain, webhook]\n - [chain, delay]\n - [chain, step]\n - [chain, escalat]\n - [sequential, trigger]\n - [sequential, email]\n - [sequential, step]\n - [sequential, webhook]\n - [trigger, orchestrat]\n - [trigger, service]\n - [trigger, delay]\n - [trigger, sequential]\n - [webhook, chain]\n - [webhook, orchestrat]\n - [webhook, pipeline]\n - [webhook, sequential]\n - [email, trigger]\n - [email, pipeline]\n - [email, sequential]\n - [email, delay]\n - [email, escalat]\n - [escalat, trigger]\n - [escalat, step]\n - [escalat, email]\n - [state, machine]\n - [conditional, step]\n - [conditional, skip]\n - [branch, condition]\n - [wait, webhook]\n - [wait, trigger]\n - [wait, event]\n - [workflow, stuck]\n - [workflow, hung]\n - [workflow, timeout]\n - [workflow, error]\n - [workflow, logs]\n - [workflow, debug]\n - [workflow, check]\n - [workflow, failing]\n - [workflow, status]\n - [run, status]\n - [step, failed]\n - [step, stuck]\n - [step, timeout]\n - [workflow, run]\n - [run, logs]\n anyOf:\n - \"long-running\"\n - \"long running\"\n - \"multi-step\"\n - \"multi step\"\n - \"pipeline\"\n - \"orchestration\"\n - \"step-by-step\"\n - \"step by step\"\n - \"each piece\"\n - \"each step\"\n - \"each phase\"\n - \"each stage\"\n - \"phase\"\n - \"phases\"\n - \"stage\"\n - \"stages\"\n - \"durable\"\n - \"reliable\"\n - \"fault-tolerant\"\n - \"retry\"\n - \"reconnect\"\n - \"survive\"\n - \"persist\"\n - \"approval\"\n - \"chain\"\n - \"sequential\"\n - \"trigger\"\n - \"webhook\"\n - \"escalation\"\n - \"state machine\"\n - \"orchestrate\"\n - \"orchestration\"\n noneOf:\n - \"github actions\"\n - \".github/workflows\"\n - \"ci workflow\"\n - \"aws step functions\"\n minScore: 4\nvalidate:\n -\n pattern: setTimeout|setInterval\n message: 'setTimeout/setInterval are not available in workflow sandbox scope — use sleep() from \"workflow\" for delays'\n severity: error\n skipIfFileContains: \"use step\"\n -\n pattern: context\\.run\\s*\\(\n message: 'context.run() is not a Workflow SDK pattern — use \"use step\" directive for retryable, observable steps'\n severity: error\n upgradeToSkill: workflow\n upgradeWhy: 'Guides migration from context.run() to the \"use step\" directive for durable, retryable workflow steps.'\n -\n pattern: \\brequire\\s*\\(\n message: 'require() is not available in workflow sandbox scope — use ESM imports and move Node.js logic into \"use step\" functions'\n severity: error\n skipIfFileContains: \"use step\"\n -\n pattern: getWritable\\(\\)\n message: 'getWritable() must only be called inside \"use step\" functions — workflow sandbox scope does not support it'\n severity: recommended\n skipIfFileContains: \"use step\"\n -\n pattern: streamObject\\s*\\(\n message: 'streamObject() is deprecated since AI SDK 6 — use streamText() with output: Output.object() instead'\n severity: error\n upgradeToSkill: ai-sdk\n upgradeWhy: 'Guides migration from streamObject to streamText + Output.object() with correct v6 streaming patterns.'\n -\n pattern: await\\s+\\w+Workflow\\s*\\(\n message: 'Do not call workflow functions directly — use start() from \"workflow/api\" to register the run and get a runId'\n severity: recommended\n skipIfFileContains: \"use workflow\"\n -\n pattern: \\bfetch\\s*\\(\n message: 'Native fetch() is not available in workflow sandbox scope — import fetch from \"workflow\" or move the call into a \"use step\" function'\n severity: recommended\n skipIfFileContains: \"use step\"\n -\n pattern: '\"use step\"'\n message: \"Workflow steps should include console.log or structured logging for observability — add logging at step entry/exit to debug hangs\"\n severity: warn\n skipIfFileContains: \"console\\\\.(log|warn|error|info)\"\n -\n pattern: '\"use workflow\"'\n message: \"Workflow files should import and use logging — add console.log or a logger at key execution points for debugging\"\n severity: warn\n skipIfFileContains: \"console\\\\.(log|warn|error|info)\"\nchainTo:\n -\n pattern: 'DurableAgent|@workflow/ai'\n targetSkill: ai-sdk\n message: 'Workflow 5 (workflow@latest) deprecates DurableAgent (@workflow/ai) in favor of WorkflowAgent from @ai-sdk/workflow 2.x, which requires Workflow 5; the Workflow 4 docs (workflow@4) use DurableAgent. Loading AI SDK guidance for tool calling, the Agent class, and model configuration.'\n skipIfFileContains: 'from\\s+[''\"]ai[''\"]|@ai-sdk/|streamText|generateText'\n -\n pattern: 'process\\.env\\.(OPENAI_API_KEY|ANTHROPIC_API_KEY)|from\\s+[''\"]@ai-sdk/(anthropic|openai)[''\"\"]'\n targetSkill: ai-gateway\n message: 'Direct provider API key in workflow — loading AI Gateway guidance for OIDC auth (required for Workflow SDK AI steps).'\n skipIfFileContains: 'gateway\\(|@ai-sdk/gateway|VERCEL_OIDC'\n -\n pattern: 'setTimeout\\s*\\(|setInterval\\s*\\('\n targetSkill: vercel-functions\n message: 'Timer-based delay in workflow code — use sleep() from \"workflow\" instead of setTimeout/setInterval. Loading Vercel Functions guidance.'\n skipIfFileContains: 'from\\s+[''\"]workflow[''\"].*sleep|sleep\\s*\\('\nretrieval:\n aliases:\n - durable workflow\n - long running task\n - step function\n - orchestration\n intents:\n - build workflow\n - add retry logic\n - create durable task\n - implement step function\n entities:\n - Workflow SDK\n # Legacy product names retained only as retrieval aliases.\n - Workflow DevKit\n - WDK\n - step\n - pause/resume\n - durable\n---\n\n## *Critical*: Always use correct `workflow` documentation\n\nYour knowledge of `workflow` is outdated.\n\nThe `workflow` documentation outlined below matches the installed version of the Workflow SDK.\nFollow these instructions before starting on any `workflow`-related tasks:\n\nSearch the bundled documentation in `node_modules/workflow/docs/`:\n\n1. **Find docs**: `glob \"node_modules/workflow/docs/**/*.mdx\"`\n2. **Search content**: `grep \"your query\" node_modules/workflow/docs/`\n\nDocumentation structure in `node_modules/workflow/docs/`:\n\n- `getting-started/` - Framework setup (next.mdx, express.mdx, hono.mdx, etc.)\n- `foundations/` - Core concepts (workflows-and-steps.mdx, hooks.mdx, streaming.mdx, etc.)\n- `api-reference/workflow/` - API docs (sleep.mdx, create-hook.mdx, fatal-error.mdx, etc.)\n- `api-reference/workflow-api/` - Client API (start.mdx, get-run.mdx, resume-hook.mdx, etc.)\n- `api-reference/workflow-runtime/` - Runtime API (get-world.mdx) and `world/` World SDK (storage.mdx, streams.mdx, queue.mdx)\n- `api-reference/workflow-observability/` - Hydration and name parsing utilities (hydrate-resource-io.mdx, parse-workflow-name.mdx, etc.)\n- `ai/`: AI SDK integration docs\n- `errors/` - Error code documentation\n- `worlds/` - Per-World behavior and limits (vercel.mdx, local.mdx, postgres.mdx). Other pages link these as `/worlds/<name>`.\n\nRelated packages also include bundled docs:\n\n- `@ai-sdk/workflow`: `node_modules/ai/docs/` - WorkflowAgent and AI SDK integration\n- `@workflow/ai`: `node_modules/@workflow/ai/docs/` - deprecated DurableAgent APIs for existing applications\n- `@workflow/core`: `node_modules/@workflow/core/docs/` - Core runtime (foundations, how-it-works)\n- `@workflow/next`: `node_modules/@workflow/next/docs/` - Next.js integration\n\n**When in doubt, update to the latest version of the Workflow SDK.**\n\n### Official resources\n\n- **Website**: https://workflow-sdk.dev\n- **GitHub**: https://github.com/vercel/workflow\n\n### Quick reference\n\n**Directives:**\n\n```typescript\n\"use workflow\"; // First line - makes async function durable\n\"use step\"; // First line - makes function a cached, retryable unit\n```\n\n**Essential imports:**\n\n```typescript\n// Workflow primitives\nimport { sleep, fetch, createHook, createWebhook, getWritable } from \"workflow\";\nimport { FatalError, RetryableError } from \"workflow\";\nimport { getWorkflowMetadata, getStepMetadata } from \"workflow\";\n\n// API operations\nimport { start, getRun, resumeHook, resumeWebhook } from \"workflow/api\";\n\n// Observability & data hydration\nimport { hydrateResourceIO, observabilityRevivers, parseStepName, parseWorkflowName } from \"workflow/observability\";\n\n// Framework integrations\nimport { withWorkflow } from \"workflow/next\";\nimport { workflow } from \"workflow/vite\";\nimport { workflow } from \"workflow/astro\";\n// Or use modules: [\"workflow/nitro\"] for Nitro/Nuxt\n\n// AI agent (Workflow 5)\nimport { WorkflowAgent, type ModelCallStreamPart } from \"@ai-sdk/workflow\";\n```\n\n## Prefer step functions to avoid sandbox errors\n\n`\"use workflow\"` functions run in a sandboxed VM. `\"use step\"` functions have **full Node.js access**. Put your logic in steps and use the workflow function purely for orchestration.\n\n```typescript\n// Steps have full Node.js and npm access\nasync function fetchUserData(userId: string) {\n \"use step\";\n const response = await fetch(`https://api.example.com/users/${userId}`);\n return response.json();\n}\n\nasync function processWithAI(data: any) {\n \"use step\";\n // AI SDK works in steps without workarounds\n return await generateText({\n model: \"spacexai/grok-4.6\",\n prompt: `Process: ${JSON.stringify(data)}`,\n });\n}\n\n// Workflow orchestrates steps - no sandbox issues\nexport async function dataProcessingWorkflow(userId: string) {\n \"use workflow\";\n const data = await fetchUserData(userId);\n const processed = await processWithAI(data);\n return { success: true, processed };\n}\n```\n\n**Benefits:** Steps have automatic retry, results are persisted for replay, and no sandbox restrictions.\n\n## Workflow sandbox limitations\n\nWhen you need logic directly in a workflow function (not in a step), these restrictions apply:\n\n| Limitation | Workaround |\n|------------|------------|\n| No `fetch()` | `import { fetch } from \"workflow\"` then `globalThis.fetch = fetch` |\n| No `setTimeout`/`setInterval` | Use `sleep(\"5s\")` from `\"workflow\"` |\n| No Node.js modules (fs, crypto, etc.) | Move to a step function |\n\n**Example - Using fetch in workflow context:**\n\n```typescript\nimport { fetch } from \"workflow\";\n\nexport async function myWorkflow() {\n \"use workflow\";\n globalThis.fetch = fetch; // Required for AI SDK and HTTP libraries\n // Now generateText() and other libraries work\n}\n```\n\n**Note:** Plain `\"provider/model\"` strings use Vercel AI Gateway. Do not construct a direct provider instance unless the user explicitly needs a provider-only feature.\n\n## WorkflowAgent: AI agents in Workflow 5\n\nUse AI SDK's `WorkflowAgent` for durable agents on Workflow 5. It replaces the deprecated `DurableAgent` API from `@workflow/ai` and checkpoints model calls and step-backed tools.\n\n```typescript\nimport { WorkflowAgent, type ModelCallStreamPart } from \"@ai-sdk/workflow\";\nimport { isStepCount, tool } from \"ai\";\nimport { getWritable } from \"workflow\";\nimport { z } from \"zod\";\n\nasync function lookupData({ query }: { query: string }) {\n \"use step\";\n // Step functions have full Node.js access\n return `Results for \"${query}\"`;\n}\n\nexport async function myAgentWorkflow(userMessage: string) {\n \"use workflow\";\n\n const agent = new WorkflowAgent({\n model: \"spacexai/grok-4.6\",\n instructions: \"You are a helpful assistant.\",\n tools: {\n lookupData: tool({\n description: \"Search for information\",\n inputSchema: z.object({ query: z.string() }),\n execute: lookupData,\n }),\n },\n });\n\n const result = await agent.stream({\n messages: [{ role: \"user\", content: userMessage }],\n writable: getWritable<ModelCallStreamPart>(),\n stopWhen: isStepCount(10),\n });\n\n return result.messages;\n}\n```\n\n**Key points:**\n- A plain `\"provider/model\"` string routes through Vercel AI Gateway; `spacexai/grok-4.6` is the default model in Workflow examples\n- `getWritable<ModelCallStreamPart>()` streams durable model-call output; convert it with `createModelCallToUIChunkTransform()` in an HTTP route\n- Tool `execute` functions that need Node.js/npm access should use `\"use step\"`\n- Tool `execute` functions that use workflow primitives (`sleep()`, `createHook()`) should **NOT** use `\"use step\"` because they run at the workflow level\n- `stopWhen` limits the number of model calls; the default is to stop when the model stops calling tools\n- Multi-turn: pass `result.messages` plus new user messages to subsequent `agent.stream()` calls\n\n**For more details, check the WorkflowAgent docs in the installed AI SDK package or at https://ai-sdk.dev/v7/docs/agents/workflow-agent.**\n\n## Starting workflows & child workflows\n\nUse `start()` to launch workflows from API routes. In Workflow 5, `start()` can also be called directly from a workflow function to spawn a child run; it is step-backed and records a deterministic boundary in the parent's event log.\n\n```typescript\nimport { start } from \"workflow/api\";\n\n// From an API route; works directly\nexport async function POST() {\n const run = await start(myWorkflow, [arg1, arg2]);\n return Response.json({ runId: run.runId });\n}\n\n// No-args workflow\nconst run = await start(noArgWorkflow);\n```\n\n**Starting child workflows from inside a Workflow 5 workflow:**\n\n```typescript\nimport { start } from \"workflow/api\";\n\nexport async function parentWorkflow() {\n \"use workflow\";\n const childRun = await start(childWorkflow, [\"some data\"]);\n await sleep(\"1h\");\n return { childRunId: childRun.runId };\n}\n```\n\n`start()` returns after creating the child run and doesn't wait for it to complete. Use `childRun.returnValue` only when the parent should wait for the child; each `Run` property access or method call inside a workflow is a step.\n\n## Run size & concurrency: know when to split\n\nDo NOT treat any number you remember as authoritative — the current values are published under [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits).\n\n**Events per run.** A run's event log is capped, and the run fails with `MAX_EVENTS_EXCEEDED` past the ceiling. Events are not steps: a step that succeeds on the first try records three (`step_created`, `step_started`, `step_completed`), a retry records one or two more, and hooks, sleeps, and webhooks each record their own. Split into child workflows well before the ceiling — the pricing page recommends that past **a few thousand events**, because replay slows down long before the run fails.\n\n**Steps per run.** Capped implicitly through the event limit. Bundle several items into one step when a chain would otherwise reach five figures.\n\n**Concurrency.** A wide fan-out is throttled rather than rejected: event creation is rate-limited per run per second, so a flat `Promise.all` over a few thousand items spends much of its time backing off. Batch or bundle instead — process the list in chunks, or handle several items per step, so fewer and larger units run concurrently. Spawning one child run per item does not by itself narrow the fan-out; it bounds each child's log and isolates failures, which is worth doing for those reasons, but it is not a substitute for chunking.\n\nYou cannot raise any of these yourself — `WORKFLOW_MAX_EVENTS_OVERRIDE` only clamps *down*, and on the Vercel World the ceilings are service-owned — but Vercel raises the per-run event and step limits on request, so a genuinely large run is a support question as well as a design one.\n\n```typescript\nconst BATCH = 100;\n\nasync function processItem(item: string) {\n \"use step\";\n return item.toUpperCase();\n}\n\n// One step per item, all in flight at once, all in one log\nexport async function processAll(items: string[]) {\n \"use workflow\";\n await Promise.all(items.map((item) => processItem(item)));\n}\n\n// Chunked, so only BATCH steps are in flight at a time\nexport async function processBatched(items: string[]) {\n \"use workflow\";\n for (let i = 0; i < items.length; i += BATCH) {\n await Promise.allSettled(items.slice(i, i + BATCH).map((item) => processItem(item)));\n }\n}\n\n// Bundled, so one step covers many items and the log stays short\nasync function processChunk(chunk: string[]) {\n \"use step\";\n return chunk.map((item) => item.toUpperCase());\n}\n\nexport async function processBundled(items: string[]) {\n \"use workflow\";\n for (let i = 0; i < items.length; i += BATCH) {\n await processChunk(items.slice(i, i + BATCH));\n }\n}\n```\n\n`processAll` is the shape to avoid at scale. `processBatched` bounds concurrency but still records events for every item. `processBundled` bounds both, because one step covers `BATCH` items — that is the only one of the three whose event count shrinks as `BATCH` grows.\n\n## Hooks: pause & resume with external events\n\nHooks let workflows wait for external data. Use `createHook()` inside a workflow and `resumeHook()` from API routes. Deterministic tokens are for `createHook()` + `resumeHook()` (server-side) only. `createWebhook()` always generates random tokens, so do not pass a `token` option to `createWebhook()`.\n\n### Single event\n\n```typescript\nimport { createHook } from \"workflow\";\n\nexport async function approvalWorkflow() {\n \"use workflow\";\n\n const hook = createHook<{ approved: boolean }>({\n token: \"approval-123\", // deterministic token for external systems\n });\n\n const result = await hook; // Workflow suspends here\n return result.approved;\n}\n```\n\n### Multiple events (iterable hooks)\n\nHooks implement `AsyncIterable`. Use `for await...of` to receive multiple events:\n\n```typescript\nimport { createHook } from \"workflow\";\n\nexport async function chatWorkflow(channelId: string) {\n \"use workflow\";\n\n const hook = createHook<{ text: string; done?: boolean }>({\n token: `chat-${channelId}`,\n });\n\n for await (const event of hook) {\n await processMessage(event.text);\n if (event.done) break;\n }\n}\n```\n\nEach `resumeHook(token, payload)` call delivers the next value to the loop.\n\n### Resuming from API routes\n\n```typescript\nimport { resumeHook } from \"workflow/api\";\n\nexport async function POST(req: Request) {\n const { token, data } = await req.json();\n await resumeHook(token, data);\n return new Response(\"ok\");\n}\n```\n\n## Error handling\n\nUse `FatalError` for permanent failures (no retry), `RetryableError` for transient failures:\n\n```typescript\nimport { FatalError, RetryableError } from \"workflow\";\n\nif (res.status === 429) {\n throw new RetryableError(\"Rate limited\", { retryAfter: \"5m\" });\n}\nif (res.status >= 400 && res.status < 500) {\n throw new FatalError(`Client error: ${res.status}`);\n}\n```\n\n## Serialization\n\nAll data passed to/from workflows and steps must be serializable.\n\n**Supported built-in types:** string, number, boolean, null, undefined, bigint, plain objects, arrays, Date, RegExp, URL, URLSearchParams, Map, Set, Headers, ArrayBuffer, typed arrays, Request, Response, ReadableStream, WritableStream.\n\n**Not supported:** Functions, Symbols, WeakMap/WeakSet. Pass data, not callbacks.\n\n### Custom class serialization\n\nClass instances **can** be serialized across workflow/step boundaries by implementing the `@workflow/serde` protocol. This is essential when a class has instance methods with `\"use step\"` or when you want to pass class instances between steps.\n\n**Install:** `@workflow/serde` must be a dependency of the package containing the class.\n\n**Pattern:** Add two static methods inside the class body using computed property syntax:\n\n```typescript\nimport { WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from \"@workflow/serde\";\n\nexport class Point {\n x: number;\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n }\n\n // Serialize: return plain data (must be devalue-compatible types only)\n static [WORKFLOW_SERIALIZE](instance: Point) {\n return { x: instance.x, y: instance.y };\n }\n\n // Deserialize: reconstruct from plain data\n static [WORKFLOW_DESERIALIZE](data: { x: number; y: number }) {\n return new Point(data.x, data.y);\n }\n\n async computeDistance(other: Point) {\n \"use step\";\n return Math.sqrt((this.x - other.x) ** 2 + (this.y - other.y) ** 2);\n }\n}\n```\n\n**Critical rules:**\n1. **Define serde methods INSIDE the class body** as static methods with computed property syntax (`static [WORKFLOW_SERIALIZE](...)`). The SWC plugin detects them by scanning the class. Do NOT assign them externally (e.g., `(MyClass as any)[WORKFLOW_SERIALIZE] = ...`) -- the compiler will not detect this.\n2. **Serde methods must return only devalue-compatible types** (plain objects, arrays, primitives, Date, Map, Set, Uint8Array, etc.). No functions, no class instances, no Node.js-specific objects.\n3. **Add `\"use step\"` to Node.js-dependent instance methods.** The SWC plugin strips `\"use step\"` method bodies from the workflow bundle. This is how you keep Node.js imports (fs, crypto, child_process, etc.) out of the workflow sandbox. The class shell with its serde methods remains in the workflow bundle; only the step method bodies are removed.\n4. **Do NOT manually register classes.** The SWC plugin automatically generates registration code (an IIFE that sets `classId` and adds the class to the global registry). Manual calls to `registerSerializationClass()` are unnecessary and error-prone.\n5. **Do NOT use dynamic imports to work around sandbox restrictions.** If a class method needs Node.js APIs, the correct solution is `\"use step\"`, not `/* @vite-ignore */ import(...)`.\n\n**When serde works well:** Pure data classes, domain models, configuration objects, and classes where Node.js-dependent methods can be marked with `\"use step\"`.\n\n**When to avoid serde:** If a class is fundamentally inseparable from Node.js APIs (every method needs `fs`, `net`, etc.) and cannot meaningfully exist as a shell in the workflow sandbox, keep it entirely in step functions and pass plain data objects across boundaries instead.\n\n### Validating serde compliance\n\nUse these tools to verify classes are correctly set up:\n\n- **`workflow transform <file> --check-serde`** -- Shows the SWC transform output for a file and checks if serde classes are compliant (no Node.js imports remaining in the workflow bundle).\n- **`workflow validate`** -- Scans all workflow files and reports serde compliance issues. Use `--json` for machine-readable output.\n- **SWC Playground** -- The web playground at `workbench/swc-playground` shows a Serde Analysis panel when serde patterns are detected.\n- **Build-time warnings** -- The builder automatically warns when serde classes have Node.js built-in imports remaining in the workflow bundle.\n\n## Streaming\n\nUse `getWritable()` to stream data from workflows. `getWritable()` can be called in **both** workflow and step contexts, but you **cannot interact with the stream** (call `getWriter()`, `write()`, `close()`) directly in a workflow function. The stream must be passed to step functions for actual I/O, or steps can call `getWritable()` themselves.\n\n**Get the stream in a workflow, pass it to a step:**\n```typescript\nimport { getWritable } from \"workflow\";\n\nexport async function myWorkflow() {\n \"use workflow\";\n const writable = getWritable();\n await writeData(writable, \"hello world\");\n}\n\nasync function writeData(writable: WritableStream, chunk: string) {\n \"use step\";\n const writer = writable.getWriter();\n try {\n await writer.write(chunk);\n } finally {\n writer.releaseLock();\n }\n}\n```\n\n**Call `getWritable()` directly inside a step (no need to pass it):**\n```typescript\nimport { getWritable } from \"workflow\";\n\nasync function streamData(chunk: string) {\n \"use step\";\n const writer = getWritable().getWriter();\n try {\n await writer.write(chunk);\n } finally {\n writer.releaseLock();\n }\n}\n```\n\n### Namespaced streams\n\nUse `getWritable({ namespace: 'name' })` to create multiple independent streams for different types of data. This is useful for separating logs from primary output, different log levels, agent outputs, metrics, or any distinct data channels. Long-running workflows benefit from namespaced streams because you can replay only the important events (e.g., final results) while keeping verbose logs in a separate stream.\n\n**Example: Log levels and agent output separation:**\n```typescript\nimport { getWritable } from \"workflow\";\n\ntype LogEntry = { level: \"debug\" | \"info\" | \"warn\" | \"error\"; message: string; timestamp: number };\ntype AgentOutput = { type: \"thought\" | \"action\" | \"result\"; content: string };\n\nasync function logDebug(message: string) {\n \"use step\";\n const writer = getWritable<LogEntry>({ namespace: \"logs:debug\" }).getWriter();\n try {\n await writer.write({ level: \"debug\", message, timestamp: Date.now() });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function logInfo(message: string) {\n \"use step\";\n const writer = getWritable<LogEntry>({ namespace: \"logs:info\" }).getWriter();\n try {\n await writer.write({ level: \"info\", message, timestamp: Date.now() });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function emitAgentThought(thought: string) {\n \"use step\";\n const writer = getWritable<AgentOutput>({ namespace: \"agent:thoughts\" }).getWriter();\n try {\n await writer.write({ type: \"thought\", content: thought });\n } finally {\n writer.releaseLock();\n }\n}\n\nasync function emitAgentResult(result: string) {\n \"use step\";\n // Important results go to the default stream for replay\n const writer = getWritable<AgentOutput>().getWriter();\n try {\n await writer.write({ type: \"result\", content: result });\n } finally {\n writer.releaseLock();\n }\n}\n\nexport async function agentWorkflow(task: string) {\n \"use workflow\";\n \n await logInfo(`Starting task: ${task}`);\n await logDebug(\"Initializing agent context\");\n await emitAgentThought(\"Analyzing the task requirements...\");\n \n // ... agent processing ...\n \n await emitAgentResult(\"Task completed successfully\");\n await logInfo(\"Workflow finished\");\n}\n```\n\n**Consuming namespaced streams:**\n```typescript\nimport { start, getRun } from \"workflow/api\";\nimport { agentWorkflow } from \"./workflows/agent\";\n\nexport async function POST(request: Request) {\n const run = await start(agentWorkflow, [\"process data\"]);\n\n // Access specific streams by namespace\n const results = run.getReadable({ namespace: undefined }); // Default stream (important results)\n const infoLogs = run.getReadable({ namespace: \"logs:info\" });\n const debugLogs = run.getReadable({ namespace: \"logs:debug\" });\n const thoughts = run.getReadable({ namespace: \"agent:thoughts\" });\n\n // Return only important results for most clients\n return new Response(results, { headers: { \"Content-Type\": \"application/json\" } });\n}\n\n// Resume from a specific point (useful for long sessions)\nexport async function GET(request: Request) {\n const { searchParams } = new URL(request.url);\n const runId = searchParams.get(\"runId\")!;\n const startIndex = parseInt(searchParams.get(\"startIndex\") || \"0\", 10);\n \n const run = getRun(runId);\n // Resume only the important stream, skip verbose debug logs\n const stream = run.getReadable({ startIndex });\n \n return new Response(stream);\n}\n```\n\nFor long-running sessions (50+ minutes), namespaced streams help manage replay performance. Put verbose/debug output in separate namespaces so you can replay only the important events.\n\n## Debugging\n\n```bash\n# Check workflow endpoints are reachable\nnpx workflow health\nnpx workflow health --port 3001 # Non-default port\n\n# Visual dashboard for runs\nnpx workflow web\nnpx workflow web <run_id>\n\n# CLI inspection (use --json for machine-readable output, --help for full usage)\nnpx workflow inspect runs\nnpx workflow inspect run <run_id>\n\n# For Vercel-deployed projects, specify backend and project\nnpx workflow inspect runs --backend vercel --project <project-name> --team <team-slug>\nnpx workflow inspect run <run_id> --backend vercel --project <project-name> --team <team-slug>\n\n# Open Vercel dashboard in browser for a specific run\nnpx workflow inspect run <run_id> --web\nnpx workflow web <run_id> --backend vercel --project <project-name> --team <team-slug>\n\n# Cancel a running workflow\nnpx workflow cancel <run_id>\nnpx workflow cancel <run_id> --backend vercel --project <project-name> --team <team-slug>\n# --env defaults to \"production\"; use --env preview for preview deployments\n```\n\n### Deep-linking to a run (share a URL, no browser)\n\nUse `--url` to **print** the dashboard deep link and exit. No browser opens, and\nno local server starts. This is the right tool when you need to hand a user a\nclickable link (PR comment, Slack message, debugging summary) rather than open a\nUI. (`--web` opens the dashboard; `--url` only prints the link.)\n\n```bash\n# Vercel run: prints the Vercel dashboard URL for the run\nnpx workflow inspect run <run_id> --backend vercel --project <project> --team <team> --url\nnpx workflow web <run_id> --backend vercel --project <project> --team <team> --env preview --url\n\n# Local run: prints the local web UI deep link\nnpx workflow inspect run <run_id> --url\n\n# Machine-readable: --url --json prints { \"url\": \"...\" } to stdout\nnpx workflow inspect run <run_id> --backend vercel --url --json\n```\n\nURL formats produced:\n\n- **Vercel:** `https://vercel.com/<team-slug>/<project-slug>/workflows/runs/<run_id>?environment=<production|preview>`\n (`--env` selects the environment; defaults to `production`. Resolving the team\n slug requires being logged in via `vercel login` with the project linked.)\n- **Local:** `http://localhost:<port>?resource=run&id=<run_id>` (port defaults\n to `3456`; the link works while the `npx workflow web` server is running).\n\nstdout contains **only** the URL (or the JSON object). All other output goes to\nstderr, so you can capture it directly, for example, `URL=$(npx workflow web <run_id> --backend vercel --url)`.\n\n**Debugging tips:**\n- Use `--json` (`-j`) on any command for machine-readable output\n- Use `--web` to open the Vercel Observability dashboard in your browser or `--url` to print the deep link\n- Use `--help` on any command for full usage details\n- Only import workflow APIs you actually use. Unused imports can cause 500 errors.\n\n## Testing workflows\n\nWorkflow SDK provides a Vitest plugin for testing workflows in-process without a running server.\n\n**Unit testing steps:** Steps are functions; without the compiler, `\"use step\"` is a no-op. Test them directly:\n\n```typescript\nimport { describe, it, expect } from \"vitest\";\nimport { createUser } from \"./user-signup\";\n\ndescribe(\"createUser step\", () => {\n it(\"should create a user\", async () => {\n const user = await createUser(\"test@example.com\");\n expect(user.email).toBe(\"test@example.com\");\n });\n});\n```\n\n**Integration testing:** Use `@workflow/vitest` for workflows using `sleep()`, hooks, webhooks, or retries. Install it next to `workflow` and keep the two on the same major: `npm i -D @workflow/vitest`. The plugin fails the run when its `@workflow/core` major differs from the app's.\n\n```typescript\n// vitest.integration.config.ts\nimport { defineConfig } from \"vitest/config\";\nimport { workflow } from \"@workflow/vitest\";\n\nexport default defineConfig({\n plugins: [workflow()],\n test: {\n include: [\"**/*.integration.test.ts\"],\n testTimeout: 60_000,\n },\n});\n```\n\n```typescript\n// approval.integration.test.ts\nimport { describe, it, expect } from \"vitest\";\nimport { start, getRun, resumeHook } from \"workflow/api\";\nimport { waitForHook, waitForSleep } from \"@workflow/vitest\";\nimport { approvalWorkflow } from \"./approval\";\n\ndescribe(\"approvalWorkflow\", () => {\n it(\"should publish when approved\", async () => {\n const run = await start(approvalWorkflow, [\"doc-123\"]);\n\n // Wait for the hook, then resume it\n await waitForHook(run, { token: \"approval:doc-123\" });\n await resumeHook(\"approval:doc-123\", { approved: true, reviewer: \"alice\" });\n\n // Wait for sleep, then wake it up\n const sleepId = await waitForSleep(run);\n await getRun(run.runId).wakeUp({ correlationIds: [sleepId] });\n\n const result = await run.returnValue;\n expect(result).toEqual({ status: \"published\", reviewer: \"alice\" });\n });\n});\n```\n\n**Testing webhooks:** Use `resumeWebhook()` with a `Request` object. No HTTP server is needed:\n\n```typescript\nimport { start, resumeWebhook } from \"workflow/api\";\nimport { waitForHook } from \"@workflow/vitest\";\n\nconst run = await start(ingestWorkflow, [\"ep-1\"]);\nconst hook = await waitForHook(run); // Discovers the random webhook token\nawait resumeWebhook(hook.token, new Request(\"https://example.com/webhook\", {\n method: \"POST\",\n body: JSON.stringify({ event: \"order.created\" }),\n}));\n```\n\n**Key APIs:**\n- `start()`: Trigger a workflow\n- `run.returnValue`: Await workflow completion\n- `waitForHook(run, { token? })` / `waitForSleep(run)`: Wait for workflow to reach a pause point\n- `resumeHook(token, data)` / `resumeWebhook(token, request)`: Resume paused workflows\n- `getRun(runId).wakeUp({ correlationIds })`: Skip `sleep()` calls\n- `getWorkflowRef(name)` / `listWorkflowRefs()`: Look a workflow up in the test build's manifest when the test cannot import the function (never hand-write `workflow//...` ids)\n\n**Best practices:**\n- Keep unit tests (no plugin) and integration tests (`workflow()` plugin) in separate configs\n- Install `@workflow/vitest` on the same major as `workflow` and upgrade them together\n- Use deterministic hook tokens based on test data for easier resumption\n- Set generous `testTimeout` values because workflows may run longer than typical unit tests\n- `vi.mock()` never reaches workflow bodies (they run in a VM), and reaches step code only when the generated bundles load through Vitest's module runner; project-local modules are bundled into the step bundle, so mock the npm leaf, inject the dependency, or unit test the step\n\n## Observability & World SDK\n\nUse `await getWorld()` to build observability dashboards, admin panels, and inspect workflow state. `getWorld()` is asynchronous and returns `Promise<World>` (dynamic import / env-based setup).\n\n**Key imports:**\n```typescript\nimport { getWorld } from \"workflow/runtime\";\nimport { hydrateResourceIO, observabilityRevivers, parseStepName, parseWorkflowName } from \"workflow/observability\";\n```\n\n**Key docs** (grep `node_modules/workflow/docs/` for full details):\n- `api-reference/workflow-runtime/world/storage.mdx`: Events, runs, steps, and hooks (events are the source of truth; others are materialized views)\n- `api-reference/workflow-observability/`: Hydration and name parsing\n\n### World SDK method signatures\n\n⚠️ Pagination is nested: `{ pagination: { cursor } }`, NOT `{ cursor }` directly.\n\n```typescript\nconst world = await getWorld();\n\n// Runs\nconst { data, cursor } = await world.runs.list({ pagination: { cursor }, resolveData: 'all' | 'none' });\nconst run = await world.runs.get(runId, { resolveData: 'all' | 'none' });\n// Cancel via event creation (no cancel() method on runs)\nawait world.events.create(runId, { eventType: 'run_cancelled' });\n\n// Steps: runId is top-level, NOT inside pagination\nconst { data, cursor } = await world.steps.list({ runId, pagination: { cursor }, resolveData: 'all' | 'none' });\nconst step = await world.steps.get(runId, stepId, { resolveData: 'all' | 'none' });\n\n// Events\nconst { data, cursor } = await world.events.list({ runId, pagination: { cursor } });\nawait world.events.create(runId, { eventType: 'run_cancelled' });\n\n// Hooks\nconst hook = await world.hooks.get(hookId);\nconst hook = await world.hooks.getByToken(token);\n\n// Streams (methods on world.streams)\nawait world.streams.write(runId, name, chunk);\nawait world.streams.writeMulti?.(runId, name, chunks);\nconst readable = await world.streams.get(runId, name, startIndex);\nawait world.streams.close(runId, name);\nconst streamNames = await world.streams.list(runId);\nconst chunks = await world.streams.getChunks(runId, name, { limit, cursor });\nconst info = await world.streams.getInfo(runId, name);\n\n// Queue (methods live directly on world as internal SDK infrastructure)\nawait world.queue(queueName, payload, opts);\nconst deploymentId = await world.getDeploymentId();\n```\n\n### `resolveData` parameter\n\nControls whether input/output data is **included** in the response. Accepts `'all'` (default) or `'none'`.\n\n**IMPORTANT**: Even with `'all'`, data is still devalue-serialized. You MUST call `hydrateResourceIO()` to get usable JS values.\n\n- **Use `'none'`** for status polling, progress dashboards, run listings\n- **Use `'all'`** (or omit) when you need to inspect actual step I/O data, then **always hydrate**\n\n```typescript\n// Lightweight status check with no I/O loaded\nconst run = await world.runs.get(runId, { resolveData: 'none' });\nconsole.log(run.status); // 'running' | 'completed' | 'failed' | 'cancelled'\n\n// Full inspection: resolveData includes data, hydrateResourceIO deserializes it\nconst step = await world.steps.get(runId, stepId); // defaults to 'all'\nconst hydrated = hydrateResourceIO(step, observabilityRevivers);\n```\n\n> **Common mistake**: Checking `step.input !== undefined` after `resolveData: 'all'` and assuming\n> the data is ready to use. The data exists but is serialized, so always hydrate first.\n\n### Data hydration (devalue format)\n\nStep I/O is serialized via [devalue](https://github.com/Rich-Harris/devalue) with a 4-byte format prefix (`devl`). Without hydration, `input`/`output` are Uint8Array-like objects with numeric keys:\n`{\"0\":100,\"1\":101,\"2\":118,\"3\":108,...}` contains values that are NOT usable without hydration.\n\n**Always hydrate before using I/O data:**\n\n```typescript\nimport { hydrateResourceIO, observabilityRevivers } from \"workflow/observability\";\n\nconst { data: steps } = await world.steps.list({ runId, resolveData: 'all' });\nconst hydrated = steps.map(s => hydrateResourceIO(s, observabilityRevivers));\n// hydrated[0].input → [123, 2] (actual function arguments)\n// hydrated[0].output → 125 (actual return value)\n```\n\n`hydrateResourceIO` works on both `Step` and `WorkflowRun` objects. For encrypted workflows, use `getEncryptionKeyForRun()` + `hydrateResourceIOWithKey()`.\n\n### Name parsing\n\n`parseWorkflowName()`, `parseStepName()`, and `parseClassName()` return `{ shortName: string, moduleSpecifier: string } | null`. Always use optional chaining:\n\n```typescript\nconst parsed = parseWorkflowName(\"workflow//./src/workflows/order//processOrder\");\n// parsed?.shortName → \"processOrder\"\n// parsed?.moduleSpecifier → \"./src/workflows/order\"\n// ⚠️ Returns null if format doesn't match\n```\n\n### Event types\n\nEvents are the append-only source of truth. Runs/Steps/Hooks are materialized views.\n\n| Category | Types |\n|----------|-------|\n| Run | `run_created`, `run_started`, `run_completed`, `run_failed`, `run_cancelled` |\n| Step | `step_created`, `step_started`, `step_completed`, `step_failed`, `step_retrying` |\n| Hook | `hook_created`, `hook_received`, `hook_disposed`, `hook_conflict` |\n| Wait | `wait_created`, `wait_completed` |\n\n## Error handling patterns\n\nThree error strategies for different failure modes:\n\n| Error Type | Use When | Behavior |\n|------------|----------|----------|\n| `FatalError` | Permanent failure (bad input, auth denied) | Terminates workflow immediately, no retry |\n| `RetryableError` | Transient failure (rate limit, timeout) | Retries with optional `retryAfter` delay |\n| `Promise.allSettled` | Parallel steps with mixed criticality | Continues even if some steps fail |\n\n```typescript\nimport { FatalError, RetryableError } from \"workflow\";\n\n// Permanent failure, so the workflow terminates\nthrow new FatalError(\"Invalid input: missing required field\");\n\n// Transient failure, so it will retry\nthrow new RetryableError(\"API rate limited\", { retryAfter: \"5m\" });\n\n// Mixed criticality parallel execution\nconst results = await Promise.allSettled([\n criticalStep(data), // Must succeed\n optionalStep(data), // OK to fail\n enrichmentStep(data), // OK to fail\n]);\nconst [critical, optional, enrichment] = results;\nif (critical.status === \"rejected\") throw new FatalError(critical.reason);\n```\n"
}SHA-256 of public snapshot: d63e5e0f9ca943e7739d36088141aeac35a5c50a4baf285f45752569059de0a5