workflow 5.0.0-beta.2 → 5.0.0-beta.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-workflow.d.ts +1 -1
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +2 -2
- package/dist/api.d.ts +5 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +14 -2
- package/dist/internal/builtins.d.ts +17 -0
- package/dist/internal/builtins.d.ts.map +1 -1
- package/dist/internal/builtins.js +65 -1
- package/dist/observability.d.ts +1 -1
- package/dist/observability.js +2 -2
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2 -2
- package/docs/ai/index.mdx +27 -23
- package/docs/api-reference/index.mdx +24 -0
- package/docs/api-reference/meta.json +8 -0
- package/docs/api-reference/vitest/index.mdx +28 -7
- package/docs/api-reference/workflow/create-hook.mdx +38 -0
- package/docs/api-reference/workflow/create-webhook.mdx +1 -0
- package/docs/api-reference/workflow/experimental-set-attributes.mdx +65 -0
- package/docs/api-reference/workflow/fetch.mdx +5 -0
- package/docs/api-reference/workflow/index.mdx +3 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
- package/docs/api-reference/workflow-api/get-hook-by-token.mdx +7 -0
- package/docs/api-reference/workflow-api/get-run.mdx +6 -0
- package/docs/api-reference/workflow-api/index.mdx +6 -8
- package/docs/api-reference/workflow-api/resume-hook.mdx +57 -0
- package/docs/api-reference/workflow-api/start.mdx +13 -5
- package/docs/api-reference/workflow-astro/index.mdx +18 -0
- package/docs/api-reference/workflow-astro/meta.json +4 -0
- package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
- package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
- package/docs/api-reference/workflow-errors/index.mdx +85 -0
- package/docs/api-reference/workflow-errors/meta.json +5 -0
- package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
- package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
- package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
- package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
- package/docs/api-reference/workflow-nest/index.mdx +31 -0
- package/docs/api-reference/workflow-nest/meta.json +9 -0
- package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
- package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
- package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
- package/docs/api-reference/workflow-next/with-workflow.mdx +56 -2
- package/docs/api-reference/workflow-nitro/index.mdx +59 -0
- package/docs/api-reference/workflow-nuxt/index.mdx +47 -0
- package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
- package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
- package/docs/api-reference/workflow-observability/index.mdx +64 -0
- package/docs/api-reference/workflow-observability/meta.json +11 -0
- package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
- package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
- package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
- package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
- package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
- package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +7 -10
- package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
- package/docs/api-reference/workflow-runtime/index.mdx +43 -0
- package/docs/api-reference/workflow-runtime/meta.json +12 -0
- package/docs/api-reference/workflow-runtime/set-world.mdx +49 -0
- package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +42 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/index.mdx +5 -8
- package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +2 -2
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +11 -4
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +2 -2
- package/docs/api-reference/workflow-serde/index.mdx +0 -1
- package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +1 -2
- package/docs/api-reference/workflow-serde/workflow-serialize.mdx +1 -2
- package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
- package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
- package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
- package/docs/api-reference/workflow-vite/index.mdx +18 -0
- package/docs/api-reference/workflow-vite/meta.json +4 -0
- package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
- package/docs/changelog/attributes-mvp.mdx +380 -0
- package/docs/changelog/eager-processing.mdx +269 -0
- package/docs/changelog/index.mdx +2 -1
- package/docs/changelog/lazy-event-creation.md +127 -0
- package/docs/changelog/meta.json +7 -1
- package/docs/changelog/resilient-start.mdx +31 -283
- package/docs/changelog/turbo-mode.md +87 -0
- package/docs/cookbook/advanced/child-workflows.mdx +315 -0
- package/docs/cookbook/advanced/meta.json +2 -3
- package/docs/cookbook/advanced/publishing-libraries.mdx +87 -29
- package/docs/cookbook/advanced/serializable-steps.mdx +17 -5
- package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +156 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +11 -184
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +150 -173
- package/docs/cookbook/agent-patterns/meta.json +1 -7
- package/docs/cookbook/common-patterns/batching.mdx +44 -118
- package/docs/cookbook/common-patterns/idempotency.mdx +36 -52
- package/docs/cookbook/common-patterns/meta.json +4 -4
- package/docs/cookbook/common-patterns/rate-limiting.mdx +1 -1
- package/docs/cookbook/common-patterns/saga.mdx +128 -33
- package/docs/cookbook/common-patterns/scheduling.mdx +77 -193
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +100 -0
- package/docs/cookbook/common-patterns/workflow-composition.mdx +117 -0
- package/docs/cookbook/index.mdx +14 -17
- package/docs/cookbook/integrations/ai-sdk.mdx +330 -142
- package/docs/cookbook/integrations/chat-sdk.mdx +264 -151
- package/docs/cookbook/integrations/sandbox.mdx +482 -81
- package/docs/cookbook/meta.json +1 -1
- package/docs/deploying/building-a-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +5 -3
- package/docs/deploying/world/vercel-world.mdx +2 -0
- package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
- package/docs/errors/corrupted-event-log.mdx +5 -5
- package/docs/errors/hook-conflict.mdx +56 -4
- package/docs/errors/index.mdx +9 -0
- package/docs/errors/replay-divergence.mdx +27 -0
- package/docs/errors/runtime-decryption-failed.mdx +77 -0
- package/docs/errors/step-executed-multiple-times.mdx +23 -0
- package/docs/errors/step-not-registered.mdx +1 -1
- package/docs/foundations/cancellation.mdx +459 -0
- package/docs/foundations/errors-and-retries.mdx +7 -3
- package/docs/foundations/hooks.mdx +29 -0
- package/docs/foundations/idempotency.mdx +236 -11
- package/docs/foundations/index.mdx +3 -3
- package/docs/foundations/meta.json +3 -2
- package/docs/foundations/serialization.mdx +78 -42
- package/docs/foundations/starting-workflows.mdx +6 -2
- package/docs/foundations/streaming.mdx +14 -23
- package/docs/foundations/versioning.mdx +263 -0
- package/docs/getting-started/astro.mdx +6 -0
- package/docs/getting-started/index.mdx +6 -7
- package/docs/getting-started/meta.json +1 -0
- package/docs/getting-started/nestjs.mdx +9 -0
- package/docs/getting-started/next.mdx +5 -3
- package/docs/getting-started/nitro.mdx +22 -0
- package/docs/getting-started/sveltekit.mdx +6 -0
- package/docs/getting-started/tanstack-start.mdx +241 -0
- package/docs/how-it-works/cancellation.mdx +287 -0
- package/docs/how-it-works/code-transform.mdx +2 -2
- package/docs/how-it-works/encryption.mdx +2 -2
- package/docs/how-it-works/event-sourcing.mdx +2 -2
- package/docs/how-it-works/meta.json +2 -1
- package/docs/internal/index.mdx +21 -0
- package/docs/internal/meta.json +10 -0
- package/docs/internal/nitro-native-build.mdx +38 -0
- package/docs/internal/nitro-web-ui.mdx +24 -0
- package/docs/internal/serializable-abort-controller.mdx +148 -0
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +63 -16
- package/docs/migration-guides/migrating-from-inngest.mdx +44 -22
- package/docs/migration-guides/migrating-from-temporal.mdx +43 -14
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +59 -27
- package/docs/observability/attributes.mdx +87 -0
- package/docs/observability/index.mdx +25 -1
- package/docs/observability/meta.json +1 -1
- package/docs/observability/tracing.mdx +106 -0
- package/docs/testing/index.mdx +2 -2
- package/package.json +14 -13
- package/docs/api-reference/workflow-api/world/meta.json +0 -4
- package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
- package/docs/cookbook/advanced/custom-serialization.mdx +0 -168
- package/docs/cookbook/advanced/durable-objects.mdx +0 -148
- package/docs/cookbook/advanced/isomorphic-packages.mdx +0 -145
- package/docs/cookbook/agent-patterns/stop-workflow.mdx +0 -216
- package/docs/cookbook/agent-patterns/tool-orchestration.mdx +0 -255
- package/docs/cookbook/agent-patterns/tool-streaming.mdx +0 -181
- package/docs/cookbook/common-patterns/child-workflows.mdx +0 -372
- package/docs/cookbook/common-patterns/content-router.mdx +0 -207
- package/docs/cookbook/common-patterns/fan-out.mdx +0 -208
- package/docs/foundations/common-patterns.mdx +0 -265
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Child Workflows
|
|
3
|
+
description: Spawn child workflows from a parent and wait for completion via hook resume.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Orchestrate independent child workflows from a parent using start(), defineHook(), and startAndWait() — the child resumes the parent's hook when done instead of polling getRun().status.
|
|
6
|
+
related:
|
|
7
|
+
- /docs/api-reference/workflow-api/start
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
Use child workflows when a single workflow needs to orchestrate many independent units of work. Each child runs as its own workflow with a separate event log, retry boundary, and failure scope -- if one child fails, it doesn't take down the parent or siblings.
|
|
11
|
+
|
|
12
|
+
## When to use child workflows
|
|
13
|
+
|
|
14
|
+
Child workflows are the right choice when:
|
|
15
|
+
|
|
16
|
+
- **Work units are independent.** Each child can run without knowing about the others (e.g., processing individual documents, generating separate reports).
|
|
17
|
+
- **You need isolated failure boundaries.** A failing child should not abort unrelated work. The parent decides how to handle failures.
|
|
18
|
+
- **You want massive fan-out.** Spawning 50 or 500 children is practical because each runs on its own infrastructure.
|
|
19
|
+
- **You need per-item observability.** Each child workflow has its own run ID, status, and event log for monitoring.
|
|
20
|
+
|
|
21
|
+
For simpler cases where steps share a single event log, use [direct await composition](/cookbook/common-patterns/workflow-composition#direct-await-flattening) instead.
|
|
22
|
+
|
|
23
|
+
## Basic pattern: spawn and wait via hook
|
|
24
|
+
|
|
25
|
+
The recommended pattern has four parts:
|
|
26
|
+
|
|
27
|
+
1. A **completion hook** the parent creates and awaits — zero compute while waiting
|
|
28
|
+
2. A **wrapped child export** that runs the real child in try/catch/finally and resumes the parent's hook from a step in `finally`
|
|
29
|
+
3. A **`start()` call** that spawns the wrapped child with the hook token (directly from the workflow in v5)
|
|
30
|
+
4. A **`startAndWait()` helper** that ties the hook, spawn, and typed result together
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
import { defineHook, getWorkflowMetadata } from "workflow";
|
|
34
|
+
import { start } from "workflow/api";
|
|
35
|
+
import { z } from "zod";
|
|
36
|
+
|
|
37
|
+
declare function fetchDocument(documentId: string): Promise<string>; // @setup
|
|
38
|
+
declare function analyzeContent(content: string): Promise<string>; // @setup
|
|
39
|
+
declare function generateSummary(analysis: string): Promise<string>; // @setup
|
|
40
|
+
|
|
41
|
+
const childCompletionHook = defineHook({
|
|
42
|
+
schema: z.discriminatedUnion("status", [
|
|
43
|
+
z.object({ status: z.literal("completed"), value: z.unknown() }),
|
|
44
|
+
z.object({ status: z.literal("failed"), error: z.string() }),
|
|
45
|
+
]),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
function completionToken(parentRunId: string, key: string) {
|
|
49
|
+
return `child-completion:${parentRunId}:${key}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function resumeParentCompletion(
|
|
53
|
+
token: string,
|
|
54
|
+
result:
|
|
55
|
+
| { status: "completed"; value: unknown }
|
|
56
|
+
| { status: "failed"; error: string }
|
|
57
|
+
) {
|
|
58
|
+
"use step";
|
|
59
|
+
await childCompletionHook.resume(token, result);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function withChildCompletionHook<TResult>(
|
|
63
|
+
runChild: () => Promise<TResult>,
|
|
64
|
+
completionTokenArg: string
|
|
65
|
+
) {
|
|
66
|
+
let result:
|
|
67
|
+
| { status: "completed"; value: TResult }
|
|
68
|
+
| { status: "failed"; error: string }
|
|
69
|
+
| undefined;
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const value = await runChild();
|
|
73
|
+
result = { status: "completed", value };
|
|
74
|
+
} catch (error) {
|
|
75
|
+
result = {
|
|
76
|
+
status: "failed",
|
|
77
|
+
error: error instanceof Error ? error.message : String(error),
|
|
78
|
+
};
|
|
79
|
+
} finally {
|
|
80
|
+
if (result) {
|
|
81
|
+
await resumeParentCompletion(completionTokenArg, result);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Child workflow -- processes a single document
|
|
87
|
+
export async function processDocument(documentId: string) {
|
|
88
|
+
"use workflow";
|
|
89
|
+
|
|
90
|
+
const content = await fetchDocument(documentId);
|
|
91
|
+
const analysis = await analyzeContent(content);
|
|
92
|
+
const summary = await generateSummary(analysis);
|
|
93
|
+
|
|
94
|
+
return { documentId, summary };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Spawnable wrapper -- explicit export so `start()` can register it
|
|
98
|
+
export async function processDocumentWithCompletion(
|
|
99
|
+
documentId: string,
|
|
100
|
+
completionTokenArg: string
|
|
101
|
+
) {
|
|
102
|
+
"use workflow";
|
|
103
|
+
|
|
104
|
+
await withChildCompletionHook(
|
|
105
|
+
() => processDocument(documentId),
|
|
106
|
+
completionTokenArg
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function startAndWait<TResult>(
|
|
111
|
+
key: string,
|
|
112
|
+
startChild: (completionTokenArg: string) => Promise<void>
|
|
113
|
+
): Promise<TResult> {
|
|
114
|
+
const { workflowRunId } = getWorkflowMetadata();
|
|
115
|
+
const token = completionToken(workflowRunId, key);
|
|
116
|
+
const hook = childCompletionHook.create({ token }); // [!code highlight]
|
|
117
|
+
|
|
118
|
+
await startChild(token);
|
|
119
|
+
|
|
120
|
+
const completion = await hook; // [!code highlight]
|
|
121
|
+
if (completion.status === "failed") {
|
|
122
|
+
throw new Error(completion.error);
|
|
123
|
+
}
|
|
124
|
+
return completion.value as TResult;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Parent workflow -- orchestrates document processing
|
|
128
|
+
export async function processDocumentBatch(documentIds: string[]) {
|
|
129
|
+
"use workflow";
|
|
130
|
+
|
|
131
|
+
const results = await Promise.all(
|
|
132
|
+
documentIds.map((documentId) =>
|
|
133
|
+
startAndWait<{ documentId: string; summary: string }>(documentId, (token) =>
|
|
134
|
+
start(processDocumentWithCompletion, [documentId, token]).then(() => undefined) // [!code highlight]
|
|
135
|
+
)
|
|
136
|
+
)
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
return { processed: results.length, results };
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Why hooks instead of polling?
|
|
144
|
+
|
|
145
|
+
Polling with `getRun().status` in a `sleep()` loop works, but hook resume is preferable because:
|
|
146
|
+
|
|
147
|
+
- **Zero compute while waiting** — the parent suspends on the hook instead of waking every poll interval
|
|
148
|
+
- **Immediate wake-up** — the parent resumes as soon as the child finishes, not on the next poll tick
|
|
149
|
+
- **Typed payloads** — the child sends `{ status, value | error }` directly; no separate `returnValue` fetch step
|
|
150
|
+
- **No worker-pool pressure** — `Run#returnValue` polling inside steps can hold worker slots while waiting for children (see [Eager Processing](/docs/changelog/eager-processing))
|
|
151
|
+
|
|
152
|
+
When a parent calls a child workflow inline with `await` (flattened into the same run), the same wrapper and hook handshake still works — pass the token and `await processDocumentWithCompletion(...)` inside `startAndWait()` instead of calling `start()`.
|
|
153
|
+
|
|
154
|
+
## Fan-out pattern: chunked spawning
|
|
155
|
+
|
|
156
|
+
When spawning hundreds of children, batch the `start()` calls to avoid overwhelming the system. Each child still gets its own completion hook keyed by a stable identifier (document ID, report ID, index).
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import { start } from "workflow/api";
|
|
160
|
+
|
|
161
|
+
declare function startAndWait<TResult>(
|
|
162
|
+
key: string,
|
|
163
|
+
startChild: (completionTokenArg: string) => Promise<void>
|
|
164
|
+
): Promise<TResult>; // @setup
|
|
165
|
+
|
|
166
|
+
const CHUNK_SIZE = 10;
|
|
167
|
+
|
|
168
|
+
export async function largeReportBatch(
|
|
169
|
+
reportConfigs: Array<{ id: string; query: string }>
|
|
170
|
+
) {
|
|
171
|
+
"use workflow";
|
|
172
|
+
|
|
173
|
+
const results = [];
|
|
174
|
+
for (let i = 0; i < reportConfigs.length; i += CHUNK_SIZE) {
|
|
175
|
+
const chunk = reportConfigs.slice(i, i + CHUNK_SIZE);
|
|
176
|
+
const chunkResults = await Promise.all(
|
|
177
|
+
chunk.map((config) =>
|
|
178
|
+
startAndWait<{ reportId: string; formatted: string }>(config.id, (token) =>
|
|
179
|
+
start(generateReportWithCompletion, [
|
|
180
|
+
config.id,
|
|
181
|
+
config.query,
|
|
182
|
+
token,
|
|
183
|
+
]).then(() => undefined)
|
|
184
|
+
)
|
|
185
|
+
)
|
|
186
|
+
);
|
|
187
|
+
results.push(...chunkResults);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return { total: results.length, results };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function generateReportWithCompletion(
|
|
194
|
+
reportId: string,
|
|
195
|
+
query: string,
|
|
196
|
+
completionTokenArg: string
|
|
197
|
+
) {
|
|
198
|
+
"use workflow";
|
|
199
|
+
|
|
200
|
+
await withChildCompletionHook(
|
|
201
|
+
() => generateReport(reportId, query),
|
|
202
|
+
completionTokenArg
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function generateReport(reportId: string, query: string) {
|
|
207
|
+
"use workflow";
|
|
208
|
+
|
|
209
|
+
const data = await queryDatabase(reportId, query);
|
|
210
|
+
const formatted = await formatReport(reportId, data);
|
|
211
|
+
return { reportId, formatted };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
declare function queryDatabase(reportId: string, query: string): Promise<string>; // @setup
|
|
215
|
+
declare function formatReport(reportId: string, data: string): Promise<string>; // @setup
|
|
216
|
+
declare function withChildCompletionHook<TResult>(
|
|
217
|
+
runChild: () => Promise<TResult>,
|
|
218
|
+
completionTokenArg: string
|
|
219
|
+
): Promise<void>; // @setup
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## Error handling
|
|
223
|
+
|
|
224
|
+
### Tolerating partial failures
|
|
225
|
+
|
|
226
|
+
Use `Promise.allSettled` with `startAndWait()` so one failing child doesn't abort siblings. The hook payload already carries `{ status: "failed", error }` — no status polling required.
|
|
227
|
+
|
|
228
|
+
```typescript
|
|
229
|
+
import { start } from "workflow/api";
|
|
230
|
+
|
|
231
|
+
declare function startAndWait<TResult>(
|
|
232
|
+
key: string,
|
|
233
|
+
startChild: (completionTokenArg: string) => Promise<void>
|
|
234
|
+
): Promise<TResult>; // @setup
|
|
235
|
+
declare function processDocumentWithCompletion(
|
|
236
|
+
documentId: string,
|
|
237
|
+
completionTokenArg: string
|
|
238
|
+
): Promise<void>; // @setup
|
|
239
|
+
|
|
240
|
+
export async function processDocumentBatchTolerant(documentIds: string[]) {
|
|
241
|
+
"use workflow";
|
|
242
|
+
|
|
243
|
+
const settled = await Promise.allSettled(
|
|
244
|
+
documentIds.map((documentId) =>
|
|
245
|
+
startAndWait<{ documentId: string; summary: string }>(documentId, (token) =>
|
|
246
|
+
start(processDocumentWithCompletion, [documentId, token]).then(
|
|
247
|
+
() => undefined
|
|
248
|
+
)
|
|
249
|
+
)
|
|
250
|
+
)
|
|
251
|
+
);
|
|
252
|
+
|
|
253
|
+
const results = settled
|
|
254
|
+
.filter(
|
|
255
|
+
(entry): entry is PromiseFulfilledResult<{ documentId: string; summary: string }> =>
|
|
256
|
+
entry.status === "fulfilled"
|
|
257
|
+
)
|
|
258
|
+
.map((entry) => entry.value);
|
|
259
|
+
|
|
260
|
+
const failed = settled.filter((entry) => entry.status === "rejected").length;
|
|
261
|
+
|
|
262
|
+
return { processed: results.length, failed, results };
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
### Retrying failed children
|
|
267
|
+
|
|
268
|
+
When a child fails, spawn a replacement with a fresh hook token. Track restart counts to prevent infinite retry loops.
|
|
269
|
+
|
|
270
|
+
```typescript
|
|
271
|
+
declare function startAndWait<TResult>(
|
|
272
|
+
key: string,
|
|
273
|
+
startChild: (completionTokenArg: string) => Promise<void>
|
|
274
|
+
): Promise<TResult>; // @setup
|
|
275
|
+
declare function spawnProcessDocument(
|
|
276
|
+
documentId: string,
|
|
277
|
+
completionTokenArg: string
|
|
278
|
+
): Promise<void>; // @setup
|
|
279
|
+
|
|
280
|
+
async function startAndWaitWithRetries(
|
|
281
|
+
documentId: string,
|
|
282
|
+
maxRestarts: number
|
|
283
|
+
): Promise<{ documentId: string; summary: string }> {
|
|
284
|
+
for (let attempt = 0; attempt <= maxRestarts; attempt++) {
|
|
285
|
+
try {
|
|
286
|
+
return await startAndWait<{ documentId: string; summary: string }>(
|
|
287
|
+
`${documentId}:${attempt}`,
|
|
288
|
+
(token) => spawnProcessDocument(documentId, token)
|
|
289
|
+
);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (attempt === maxRestarts) throw error;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
throw new Error("unreachable");
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
## Tips
|
|
300
|
+
|
|
301
|
+
- **`defineHook().resume()` must be called from a step.** The wrapped child's `finally` block calls a step that resumes the parent hook.
|
|
302
|
+
- **Export wrapped children at module scope.** The SDK registers `"use workflow"` functions statically — a runtime higher-order function returned from `withChildCompletionHook()` cannot be passed to `start()`.
|
|
303
|
+
- **Use stable hook keys** — document ID, job ID, or index — so parallel children inside one parent run don't collide on tokens.
|
|
304
|
+
- **Use chunked spawning for large batches.** Starting 500 children at once can create a large burst of work. Break it into chunks of 10-50.
|
|
305
|
+
- **Each child has its own retry semantics.** Steps inside child workflows retry independently. The parent sees the final `{ status, value | error }` payload from the hook.
|
|
306
|
+
- **Use `deploymentId: "latest"`** if children should run on the most recent deployment. See [Versioning](/docs/foundations/versioning) for the full model and the [`start()` API reference](/docs/api-reference/workflow-api/start#using-deploymentid-latest) for compatibility considerations.
|
|
307
|
+
|
|
308
|
+
## Key APIs
|
|
309
|
+
|
|
310
|
+
- [`start()`](/docs/api-reference/workflow-api/start) -- spawn a new workflow run and get its run ID
|
|
311
|
+
- [`defineHook()`](/docs/api-reference/workflow/define-hook) -- typed hook for parent/child completion handshakes
|
|
312
|
+
- [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) -- resume a waiting parent from a step (called by the child wrapper)
|
|
313
|
+
- [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata) -- read the parent run ID for deterministic hook tokens
|
|
314
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) -- marks the orchestrator function
|
|
315
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps) -- marks functions with full Node.js access
|
|
@@ -5,6 +5,8 @@ type: guide
|
|
|
5
5
|
summary: Learn how to build, export, and test npm packages that ship workflow and step functions — including package.json exports, re-exporting for stable workflow IDs, keeping step I/O clean, and integration testing.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
+
import { File, Folder, Files } from "fumadocs-ui/components/files";
|
|
9
|
+
|
|
8
10
|
<Callout>
|
|
9
11
|
This is an advanced guide for library authors who want to publish reusable workflow functions as npm packages. It assumes familiarity with `"use workflow"`, `"use step"`, and the workflow execution model.
|
|
10
12
|
</Callout>
|
|
@@ -13,23 +15,37 @@ This is an advanced guide for library authors who want to publish reusable workf
|
|
|
13
15
|
|
|
14
16
|
A workflow library follows a standard TypeScript package layout with a dedicated `workflows/` directory. Each workflow file exports one or more workflow functions that consumers can import and pass to `start()`.
|
|
15
17
|
|
|
16
|
-
|
|
17
|
-
my-media-lib
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
18
|
+
<Files>
|
|
19
|
+
<Folder name="my-media-lib" defaultOpen>
|
|
20
|
+
<Folder name="src" defaultOpen>
|
|
21
|
+
<File name="index.ts" />
|
|
22
|
+
<File name="types.ts" />
|
|
23
|
+
<Folder name="workflows" defaultOpen>
|
|
24
|
+
<File name="index.ts" />
|
|
25
|
+
<File name="transcode.ts" />
|
|
26
|
+
<File name="generate-thumbnails.ts" />
|
|
27
|
+
</Folder>
|
|
28
|
+
<Folder name="lib" defaultOpen>
|
|
29
|
+
<File name="api-client.ts" />
|
|
30
|
+
</Folder>
|
|
31
|
+
</Folder>
|
|
32
|
+
<Folder name="test-server" defaultOpen>
|
|
33
|
+
<File name="workflows.ts" />
|
|
34
|
+
</Folder>
|
|
35
|
+
<File name="tsup.config.ts" />
|
|
36
|
+
<File name="package.json" />
|
|
37
|
+
<File name="tsconfig.json" />
|
|
38
|
+
</Folder>
|
|
39
|
+
</Files>
|
|
40
|
+
|
|
41
|
+
Key files:
|
|
42
|
+
|
|
43
|
+
- **`src/index.ts`** — Package entry point. Exports the public API.
|
|
44
|
+
- **`src/types.ts`** — Shared TypeScript types.
|
|
45
|
+
- **`src/workflows/index.ts`** — Re-exports every workflow so consumers can pull them in under one specifier (see [Entry Points and Exports](#entry-points-and-exports)).
|
|
46
|
+
- **`src/workflows/*.ts`** — One file per workflow function (e.g. `transcode.ts`, `generate-thumbnails.ts`).
|
|
47
|
+
- **`src/lib/`** — Internal helpers. Plain async code, *not* marked with `"use workflow"` or `"use step"`.
|
|
48
|
+
- **`test-server/workflows.ts`** — Re-export file used by integration tests (see [Testing Workflow Libraries](#testing-workflow-libraries)).
|
|
33
49
|
|
|
34
50
|
### Entry Points and Exports
|
|
35
51
|
|
|
@@ -126,7 +142,7 @@ When you publish a workflow library, every step function's inputs and outputs ar
|
|
|
126
142
|
|
|
127
143
|
### 1. Everything Must Be Serializable
|
|
128
144
|
|
|
129
|
-
Step inputs and outputs must be serializable. The workflow runtime supports a rich set of types beyond plain JSON — including `Date`, `RegExp`, `Map`, `Set`, `BigInt`, `Uint8Array`, `URL`, `Error`, and class instances that implement [custom class serialization](/docs/
|
|
145
|
+
Step inputs and outputs must be serializable. The workflow runtime supports a rich set of types beyond plain JSON — including `Date`, `RegExp`, `Map`, `Set`, `BigInt`, `Uint8Array`, `URL`, `Error`, and class instances that implement [custom class serialization](/docs/foundations/serialization#custom-class-serialization). See the [serialization reference](/docs/foundations/serialization) for the full list of supported types. Do not pass or return:
|
|
130
146
|
|
|
131
147
|
- Functions or closures
|
|
132
148
|
- `WeakRef`, `WeakMap`, or `WeakSet`
|
|
@@ -226,7 +242,18 @@ pnpm vitest run --config vitest.workflowsdk.config.ts
|
|
|
226
242
|
|
|
227
243
|
## Working With and Without Workflow Installed
|
|
228
244
|
|
|
229
|
-
|
|
245
|
+
Some libraries want to be useful to consumers who *aren't* using Workflow SDK at all — the library picks up durable behavior when a workflow runtime is present and falls back to plain async execution otherwise.
|
|
246
|
+
|
|
247
|
+
<Callout type="info">
|
|
248
|
+
Two rules for isomorphic packages:
|
|
249
|
+
|
|
250
|
+
1. **Any runtime reference to the `workflow` package must be loaded via dynamic `import("workflow")` inside a try/catch.** A static top-level import makes the module fail to load for consumers who haven't installed workflow.
|
|
251
|
+
2. **The `"use workflow"` and `"use step"` directives are safe to keep in your library source.** When a consumer compiles your code with the Workflow SDK toolchain (via the [re-export pattern](#re-exporting-for-workflow-id-stability) above), the SWC plugin transforms them into durable-execution glue. When they're not compiled — plain Node, plain tests, a consumer without the runtime — they are just string expression statements and run as no-ops.
|
|
252
|
+
</Callout>
|
|
253
|
+
|
|
254
|
+
### Optional peer dependency
|
|
255
|
+
|
|
256
|
+
Declare `workflow` as an **optional** peer so consumers without the runtime aren't forced to install it:
|
|
230
257
|
|
|
231
258
|
```json
|
|
232
259
|
{
|
|
@@ -241,22 +268,53 @@ If your library should work both as a standalone package and inside Workflow SDK
|
|
|
241
268
|
}
|
|
242
269
|
```
|
|
243
270
|
|
|
244
|
-
|
|
271
|
+
### Runtime detection
|
|
272
|
+
|
|
273
|
+
Wrap a dynamic `import("workflow")` in try/catch. If either the module isn't installed *or* `getStepMetadata()` throws (call site isn't inside a workflow step), fall through to the standalone path.
|
|
245
274
|
|
|
246
275
|
```typescript lineNumbers
|
|
247
|
-
async function
|
|
276
|
+
async function getWorkflowStepId(): Promise<string | null> { // [!code highlight]
|
|
248
277
|
try {
|
|
249
278
|
const wf = await import("workflow");
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
return true;
|
|
279
|
+
const { stepId } = wf.getStepMetadata();
|
|
280
|
+
return stepId;
|
|
253
281
|
} catch {
|
|
254
|
-
return
|
|
282
|
+
return null;
|
|
255
283
|
}
|
|
256
284
|
}
|
|
257
285
|
```
|
|
258
286
|
|
|
259
|
-
|
|
287
|
+
### A concrete use case: replay-safe idempotency keys
|
|
288
|
+
|
|
289
|
+
A payments utility that uses the current workflow step ID as a Stripe idempotency key when available, and a fresh UUID otherwise:
|
|
290
|
+
|
|
291
|
+
```typescript lineNumbers
|
|
292
|
+
declare function getWorkflowStepId(): Promise<string | null>; // @setup (defined in the previous block)
|
|
293
|
+
|
|
294
|
+
export async function processPayment(amount: number, currency: string) {
|
|
295
|
+
const stepId = await getWorkflowStepId();
|
|
296
|
+
const idempotencyKey = stepId ? `payment:${stepId}` : crypto.randomUUID(); // [!code highlight]
|
|
297
|
+
|
|
298
|
+
const res = await fetch("https://api.stripe.com/v1/charges", {
|
|
299
|
+
method: "POST",
|
|
300
|
+
headers: {
|
|
301
|
+
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
|
|
302
|
+
"Idempotency-Key": idempotencyKey, // [!code highlight]
|
|
303
|
+
},
|
|
304
|
+
body: new URLSearchParams({ amount: String(amount), currency }),
|
|
305
|
+
});
|
|
306
|
+
return res.json();
|
|
307
|
+
}
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
When called from inside a workflow step, the utility gets a stable idempotency key for that step across retries — Stripe dedupes retries for free. When called from a plain Node.js process, it behaves like any other function and a fresh UUID is generated. For more patterns, see [Idempotency](/docs/foundations/idempotency).
|
|
311
|
+
|
|
312
|
+
### In production
|
|
313
|
+
|
|
314
|
+
Packages in the wild built on Workflow SDK:
|
|
315
|
+
|
|
316
|
+
- **[`@mux/ai`](https://github.com/muxinc/ai)** — Reusable video AI workflows (summaries, chapters, content moderation, translation, embeddings) exported with `"use workflow"` / `"use step"` directives. In a standard Node environment the directives are no-ops and the SDK runs as a plain async library; in a Workflow SDK environment the consumer's compiler transforms them into durable, resumable steps with automatic retries and observability. Written up in detail in [*How Mux shipped durable video workflows with their @mux/ai SDK*](https://vercel.com/blog/how-mux-shipped-durable-video-workflows-with-their-mux-ai-sdk) on the Vercel blog.
|
|
317
|
+
- **World ID** — Human-in-the-loop "proof of human" primitive for agent workflows. Developers drop a World ID step into any workflow to require a zero-knowledge cryptographic proof that a real, unique human authorized a specific action (deploy approvals, large payments, sensitive data access, etc.). Because it runs as a workflow step, every verification is durable, replay-safe, and viewable inside the run's execution timeline — giving you a provable audit record of which human approved what. Available on npm and announced in [*World ID for agents: Browserbase, Exa, Okta, and Vercel*](https://world.org/blog/announcements/browserbase-exa-okta-world-id-for-agentic-web) on the World blog.
|
|
260
318
|
|
|
261
319
|
## Checklist
|
|
262
320
|
|
|
@@ -273,7 +331,7 @@ Before publishing a workflow library:
|
|
|
273
331
|
|
|
274
332
|
## Key APIs
|
|
275
333
|
|
|
276
|
-
- [`"use workflow"`](/docs/
|
|
277
|
-
- [`"use step"`](/docs/
|
|
278
|
-
- [`start`](/docs/api-reference/workflow/start) — starts a workflow run
|
|
334
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) — declares the orchestrator function
|
|
335
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) — marks functions for durable execution
|
|
336
|
+
- [`start`](/docs/api-reference/workflow-api/start) — starts a workflow run
|
|
279
337
|
- [`getWorkflowMetadata`](/docs/api-reference/workflow/get-workflow-metadata) — runtime detection and run ID access
|
|
@@ -1,17 +1,28 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Serializable Steps
|
|
3
|
-
description: Wrap non-serializable objects (like AI model providers) inside step functions so they can cross the workflow boundary.
|
|
3
|
+
description: Wrap non-serializable third-party objects (like AI model providers) inside step factory functions so they can cross the workflow boundary.
|
|
4
4
|
type: guide
|
|
5
|
-
summary: Return a callback from a step to defer
|
|
5
|
+
summary: Return a callback from a step to defer construction of a non-owned class (AI SDK models, cloud SDK clients) until execution time, making them usable inside durable workflows.
|
|
6
|
+
related:
|
|
7
|
+
- /docs/foundations/serialization
|
|
8
|
+
- /docs/foundations/serialization#custom-class-serialization
|
|
9
|
+
- /docs/foundations/workflows-and-steps#step-functions
|
|
6
10
|
---
|
|
7
11
|
|
|
8
12
|
<Callout>
|
|
9
13
|
This is an advanced guide. It dives into workflow internals and is not required reading to use workflow.
|
|
10
14
|
</Callout>
|
|
11
15
|
|
|
16
|
+
## When to use this pattern
|
|
17
|
+
|
|
18
|
+
Workflow functions run inside a sandboxed VM where every value that crosses a function boundary must be serializable. There are two ways to get a non-serializable object across that boundary, depending on whether you own the class:
|
|
19
|
+
|
|
20
|
+
- **You own the class** — implement the [`WORKFLOW_SERIALIZE` / `WORKFLOW_DESERIALIZE` protocol](/docs/foundations/serialization#custom-class-serialization). The instance becomes a first-class serializable value: you can pass it as a workflow input, return it from a step, and call `"use step"` instance methods on it directly. This is the right tool when the class is yours to modify.
|
|
21
|
+
- **You don't own the class** — you can't add methods to `openai("gpt-4o")` from `@ai-sdk/openai` or `new S3Client({...})` from `@aws-sdk/client-s3`. Instead, wrap construction in a `"use step"` factory function and pass the factory across the boundary. That's what this page covers.
|
|
22
|
+
|
|
12
23
|
## The Problem
|
|
13
24
|
|
|
14
|
-
|
|
25
|
+
AI SDK model providers — `openai("gpt-4o")`, `anthropic("claude-sonnet-4-20250514")`, etc. — return complex objects with methods, closures, and internal state. Passing one directly into a step causes a serialization error, and you can't bolt `WORKFLOW_SERIALIZE` onto a third-party class.
|
|
15
26
|
|
|
16
27
|
```typescript lineNumbers
|
|
17
28
|
import { openai } from "@ai-sdk/openai";
|
|
@@ -130,6 +141,7 @@ async function uploadFile(
|
|
|
130
141
|
|
|
131
142
|
## Key APIs
|
|
132
143
|
|
|
133
|
-
- [`"use step"`](/docs/
|
|
134
|
-
- [`"use workflow"`](/docs/
|
|
144
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) — marks a function for extraction and serialization
|
|
145
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) — declares the orchestrator function
|
|
135
146
|
- [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — accepts a model factory for durable AI agent streaming
|
|
147
|
+
- [Custom class serialization](/docs/foundations/serialization#custom-class-serialization) — the companion pattern for classes you own (`WORKFLOW_SERIALIZE` / `WORKFLOW_DESERIALIZE`)
|