workflow

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CRITICAL: Always Use Correct
workflow
Documentation

重要提示: 始终使用正确的
workflow
文档

Your knowledge of
workflow
is outdated.
The
workflow
documentation outlined below matches the installed version of the Workflow DevKit. Follow these instructions before starting on any
workflow
-related tasks:
Search the bundled documentation in
node_modules/workflow/docs/
:
  1. Find docs:
    glob "node_modules/workflow/docs/**/*.mdx"
  2. Search content:
    grep "your query" node_modules/workflow/docs/
Documentation structure in
node_modules/workflow/docs/
:
  • getting-started/
    - Framework setup (next.mdx, express.mdx, hono.mdx, etc.)
  • 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
  • errors/
    - Error code documentation
Related packages also include bundled docs:
  • @workflow/ai
    :
    node_modules/@workflow/ai/docs/
    - DurableAgent and AI integration
  • @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.
你所掌握的
workflow
知识已过时。
以下列出的
workflow
文档与已安装的Workflow DevKit版本匹配。在开始任何与
workflow
相关的任务前,请遵循以下说明:
node_modules/workflow/docs/
中搜索捆绑的文档:
  1. 查找文档
    glob "node_modules/workflow/docs/**/*.mdx"
  2. 搜索内容
    grep "your query" node_modules/workflow/docs/
node_modules/workflow/docs/
中的文档结构:
  • getting-started/
    - 框架设置(next.mdx、express.mdx、hono.mdx等)
  • foundations/
    - 核心概念(workflows-and-steps.mdx、hooks.mdx、streaming.mdx等)
  • api-reference/workflow/
    - API文档(sleep.mdx、create-hook.mdx、fatal-error.mdx等)
  • api-reference/workflow-api/
    - 客户端API(start.mdx、get-run.mdx、resume-hook.mdx等)
  • ai/
    - AI SDK集成文档
  • errors/
    - 错误码文档
相关包也包含捆绑文档:
  • @workflow/ai
    node_modules/@workflow/ai/docs/
    - DurableAgent与AI集成
  • @workflow/core
    node_modules/@workflow/core/docs/
    - 核心运行时(基础原理、工作机制)
  • @workflow/next
    node_modules/@workflow/next/docs/
    - Next.js集成
如有疑问,请更新到Workflow DevKit的最新版本。

Official Resources

官方资源

Quick Reference

快速参考

Directives:
typescript
"use workflow";  // First line - makes async function durable
"use step";      // First line - makes function a cached, retryable unit
Essential imports:
typescript
// Workflow primitives
import { sleep, fetch, createHook, createWebhook, getWritable } from "workflow";
import { FatalError, RetryableError } from "workflow";
import { getWorkflowMetadata, getStepMetadata } from "workflow";

// API operations
import { start, getRun, resumeHook, resumeWebhook } from "workflow/api";

// 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
指令:
typescript
"use workflow";  // 第一行 - 使异步函数具备持久化能力
"use step";      // 第一行 - 使函数成为可缓存、可重试的单元
必要导入:
typescript
// Workflow原语
import { sleep, fetch, createHook, createWebhook, getWritable } from "workflow";
import { FatalError, RetryableError } from "workflow";
import { getWorkflowMetadata, getStepMetadata } from "workflow";

// API操作
import { start, getRun, resumeHook, resumeWebhook } from "workflow/api";

// 框架集成
import { withWorkflow } from "workflow/next";
import { workflow } from "workflow/vite";
import { workflow } from "workflow/astro";
// 或使用模块:["workflow/nitro"] 用于Nitro/Nuxt

Prefer Step Functions to Avoid Sandbox Errors

优先使用Step函数以避免沙箱错误

"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.
typescript
// Steps have full Node.js and npm access
async function fetchUserData(userId: string) {
  "use step";
  const response = await fetch(`https://api.example.com/users/${userId}`);
  return response.json();
}

async function processWithAI(data: any) {
  "use step";
  // AI SDK works in steps without workarounds
  return await generateText({
    model: openai("gpt-4"),
    prompt: `Process: ${JSON.stringify(data)}`,
  });
}

// Workflow orchestrates steps - no sandbox issues
export async function dataProcessingWorkflow(userId: string) {
  "use workflow";
  const data = await fetchUserData(userId);
  const processed = await processWithAI(data);
  return { success: true, processed };
}
Benefits: Steps have automatic retry, results are persisted for replay, and no sandbox restrictions.
"use workflow"
函数在沙箱化VM中运行。
"use step"
函数拥有完整的Node.js访问权限。将你的逻辑放在step中,仅用workflow函数进行编排。
typescript
// Step拥有完整的Node.js和npm访问权限
async function fetchUserData(userId: string) {
  "use step";
  const response = await fetch(`https://api.example.com/users/${userId}`);
  return response.json();
}

async function processWithAI(data: any) {
  "use step";
  // AI SDK在step中无需变通即可工作
  return await generateText({
    model: openai("gpt-4"),
    prompt: `Process: ${JSON.stringify(data)}`,
  });
}

// Workflow编排step - 无沙箱问题
export async function dataProcessingWorkflow(userId: string) {
  "use workflow";
  const data = await fetchUserData(userId);
  const processed = await processWithAI(data);
  return { success: true, processed };
}
优势: Step具备自动重试功能,结果会被持久化以便重放,且无沙箱限制。

Workflow Sandbox Limitations

Workflow沙箱限制

When you need logic directly in a workflow function (not in a step), these restrictions apply:
LimitationWorkaround
No
fetch()
import { fetch } from "workflow"
then
globalThis.fetch = fetch
No
setTimeout
/
setInterval
Use
sleep("5s")
from
"workflow"
No Node.js modules (fs, crypto, etc.)Move to a step function
Example - Using fetch in workflow context:
typescript
import { fetch } from "workflow";

export async function myWorkflow() {
  "use workflow";
  globalThis.fetch = fetch;  // Required for AI SDK and HTTP libraries
  // Now generateText() and other libraries work
}
Note:
DurableAgent
from
@workflow/ai
handles the fetch assignment automatically.
当你需要在workflow函数中直接编写逻辑(而非step中)时,以下限制适用:
限制解决方法
fetch()
"workflow"
导入
fetch
,然后执行
globalThis.fetch = fetch
setTimeout
/
setInterval
使用
"workflow"
中的
sleep("5s")
无Node.js模块(fs、crypto等)移至step函数中
示例 - 在workflow上下文中使用fetch:
typescript
import { fetch } from "workflow";

export async function myWorkflow() {
  "use workflow";
  globalThis.fetch = fetch;  // AI SDK和HTTP库需要此设置
  // 现在generateText()和其他库可以正常工作
}
注意:
@workflow/ai
中的
DurableAgent
会自动处理fetch的赋值。

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" });
}
对于永久性失败(不重试)使用
FatalError
,对于暂时性失败使用
RetryableError
typescript
import { FatalError, RetryableError } from "workflow";

if (res.status >= 400 && res.status < 500) {
  throw new FatalError(`客户端错误:${res.status}`);
}
if (res.status === 429) {
  throw new RetryableError("请求受限", { retryAfter: "5m" });
}

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.
Not supported: Functions, class instances, Symbols, WeakMap/WeakSet. Pass data, not callbacks.
所有在workflow与step之间传递的数据必须可序列化。
支持的类型: 字符串、数字、布尔值、null、undefined、bigint、普通对象、数组、Date、RegExp、URL、URLSearchParams、Map、Set、Headers、ArrayBuffer、类型化数组、Request、Response、ReadableStream、WritableStream。
不支持的类型: 函数、类实例、Symbol、WeakMap/WeakSet。传递数据,而非回调函数。

Streaming

流式处理

Use
getWritable()
in step functions to stream data:
typescript
async function streamData() {
  "use step";  // Required - streaming only works in steps
  const writer = getWritable();
  await writer.write(data);
  writer.releaseLock();  // Always release the lock
}

// Close when done
await getWritable().close();
在step函数中使用
getWritable()
进行流式数据传输:
typescript
async function streamData() {
  "use step";  // 必须设置 - 流式处理仅在step中生效
  const writer = getWritable();
  await writer.write(data);
  writer.releaseLock();  // 务必释放锁
}

// 完成后关闭
await getWritable().close();

Debugging

调试

bash
undefined
bash
undefined

Check workflow endpoints are reachable

检查工作流端点是否可达

npx workflow health npx workflow health --port 3001 # Non-default port
npx workflow health npx workflow health --port 3001 # 非默认端口

Visual dashboard for runs

运行实例的可视化仪表板

npx workflow web npx workflow web --app-url http://localhost:3001
npx workflow web npx workflow web --app-url http://localhost:3001

CLI inspection (for agents)

CLI检查(适用于代理)

npx workflow inspect runs npx workflow inspect run <run_id>

**Tip:** Only import workflow APIs you actually use. Unused imports can cause 500 errors.
npx workflow inspect runs npx workflow inspect run <run_id>

**提示:** 仅导入实际使用的workflow API。未使用的导入可能导致500错误。",