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.
Files changed (170) hide show
  1. package/dist/api-workflow.d.ts +1 -1
  2. package/dist/api-workflow.d.ts.map +1 -1
  3. package/dist/api-workflow.js +2 -2
  4. package/dist/api.d.ts +5 -1
  5. package/dist/api.d.ts.map +1 -1
  6. package/dist/api.js +14 -2
  7. package/dist/internal/builtins.d.ts +17 -0
  8. package/dist/internal/builtins.d.ts.map +1 -1
  9. package/dist/internal/builtins.js +65 -1
  10. package/dist/observability.d.ts +1 -1
  11. package/dist/observability.js +2 -2
  12. package/dist/runtime.d.ts +1 -1
  13. package/dist/runtime.d.ts.map +1 -1
  14. package/dist/runtime.js +2 -2
  15. package/docs/ai/index.mdx +27 -23
  16. package/docs/api-reference/index.mdx +24 -0
  17. package/docs/api-reference/meta.json +8 -0
  18. package/docs/api-reference/vitest/index.mdx +28 -7
  19. package/docs/api-reference/workflow/create-hook.mdx +38 -0
  20. package/docs/api-reference/workflow/create-webhook.mdx +1 -0
  21. package/docs/api-reference/workflow/experimental-set-attributes.mdx +65 -0
  22. package/docs/api-reference/workflow/fetch.mdx +5 -0
  23. package/docs/api-reference/workflow/index.mdx +3 -0
  24. package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
  25. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +7 -0
  26. package/docs/api-reference/workflow-api/get-run.mdx +6 -0
  27. package/docs/api-reference/workflow-api/index.mdx +6 -8
  28. package/docs/api-reference/workflow-api/resume-hook.mdx +57 -0
  29. package/docs/api-reference/workflow-api/start.mdx +13 -5
  30. package/docs/api-reference/workflow-astro/index.mdx +18 -0
  31. package/docs/api-reference/workflow-astro/meta.json +4 -0
  32. package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
  33. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
  34. package/docs/api-reference/workflow-errors/index.mdx +85 -0
  35. package/docs/api-reference/workflow-errors/meta.json +5 -0
  36. package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
  37. package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
  38. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
  39. package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
  40. package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
  41. package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
  42. package/docs/api-reference/workflow-nest/index.mdx +31 -0
  43. package/docs/api-reference/workflow-nest/meta.json +9 -0
  44. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
  45. package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
  46. package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
  47. package/docs/api-reference/workflow-next/with-workflow.mdx +56 -2
  48. package/docs/api-reference/workflow-nitro/index.mdx +59 -0
  49. package/docs/api-reference/workflow-nuxt/index.mdx +47 -0
  50. package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
  51. package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
  52. package/docs/api-reference/workflow-observability/index.mdx +64 -0
  53. package/docs/api-reference/workflow-observability/meta.json +11 -0
  54. package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
  55. package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
  56. package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
  57. package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
  58. package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
  59. package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
  60. package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +7 -10
  61. package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
  62. package/docs/api-reference/workflow-runtime/index.mdx +43 -0
  63. package/docs/api-reference/workflow-runtime/meta.json +12 -0
  64. package/docs/api-reference/workflow-runtime/set-world.mdx +49 -0
  65. package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +42 -0
  66. package/docs/api-reference/{workflow-api → workflow-runtime}/world/index.mdx +5 -8
  67. package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
  68. package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +2 -2
  69. package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +11 -4
  70. package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +2 -2
  71. package/docs/api-reference/workflow-serde/index.mdx +0 -1
  72. package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +1 -2
  73. package/docs/api-reference/workflow-serde/workflow-serialize.mdx +1 -2
  74. package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
  75. package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
  76. package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
  77. package/docs/api-reference/workflow-vite/index.mdx +18 -0
  78. package/docs/api-reference/workflow-vite/meta.json +4 -0
  79. package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
  80. package/docs/changelog/attributes-mvp.mdx +380 -0
  81. package/docs/changelog/eager-processing.mdx +269 -0
  82. package/docs/changelog/index.mdx +2 -1
  83. package/docs/changelog/lazy-event-creation.md +127 -0
  84. package/docs/changelog/meta.json +7 -1
  85. package/docs/changelog/resilient-start.mdx +31 -283
  86. package/docs/changelog/turbo-mode.md +87 -0
  87. package/docs/cookbook/advanced/child-workflows.mdx +315 -0
  88. package/docs/cookbook/advanced/meta.json +2 -3
  89. package/docs/cookbook/advanced/publishing-libraries.mdx +87 -29
  90. package/docs/cookbook/advanced/serializable-steps.mdx +17 -5
  91. package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
  92. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +156 -0
  93. package/docs/cookbook/agent-patterns/durable-agent.mdx +11 -184
  94. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +150 -173
  95. package/docs/cookbook/agent-patterns/meta.json +1 -7
  96. package/docs/cookbook/common-patterns/batching.mdx +44 -118
  97. package/docs/cookbook/common-patterns/idempotency.mdx +36 -52
  98. package/docs/cookbook/common-patterns/meta.json +4 -4
  99. package/docs/cookbook/common-patterns/rate-limiting.mdx +1 -1
  100. package/docs/cookbook/common-patterns/saga.mdx +128 -33
  101. package/docs/cookbook/common-patterns/scheduling.mdx +77 -193
  102. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
  103. package/docs/cookbook/common-patterns/timeouts.mdx +100 -0
  104. package/docs/cookbook/common-patterns/workflow-composition.mdx +117 -0
  105. package/docs/cookbook/index.mdx +14 -17
  106. package/docs/cookbook/integrations/ai-sdk.mdx +330 -142
  107. package/docs/cookbook/integrations/chat-sdk.mdx +264 -151
  108. package/docs/cookbook/integrations/sandbox.mdx +482 -81
  109. package/docs/cookbook/meta.json +1 -1
  110. package/docs/deploying/building-a-world.mdx +1 -1
  111. package/docs/deploying/world/postgres-world.mdx +5 -3
  112. package/docs/deploying/world/vercel-world.mdx +2 -0
  113. package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
  114. package/docs/errors/corrupted-event-log.mdx +5 -5
  115. package/docs/errors/hook-conflict.mdx +56 -4
  116. package/docs/errors/index.mdx +9 -0
  117. package/docs/errors/replay-divergence.mdx +27 -0
  118. package/docs/errors/runtime-decryption-failed.mdx +77 -0
  119. package/docs/errors/step-executed-multiple-times.mdx +23 -0
  120. package/docs/errors/step-not-registered.mdx +1 -1
  121. package/docs/foundations/cancellation.mdx +459 -0
  122. package/docs/foundations/errors-and-retries.mdx +7 -3
  123. package/docs/foundations/hooks.mdx +29 -0
  124. package/docs/foundations/idempotency.mdx +236 -11
  125. package/docs/foundations/index.mdx +3 -3
  126. package/docs/foundations/meta.json +3 -2
  127. package/docs/foundations/serialization.mdx +78 -42
  128. package/docs/foundations/starting-workflows.mdx +6 -2
  129. package/docs/foundations/streaming.mdx +14 -23
  130. package/docs/foundations/versioning.mdx +263 -0
  131. package/docs/getting-started/astro.mdx +6 -0
  132. package/docs/getting-started/index.mdx +6 -7
  133. package/docs/getting-started/meta.json +1 -0
  134. package/docs/getting-started/nestjs.mdx +9 -0
  135. package/docs/getting-started/next.mdx +5 -3
  136. package/docs/getting-started/nitro.mdx +22 -0
  137. package/docs/getting-started/sveltekit.mdx +6 -0
  138. package/docs/getting-started/tanstack-start.mdx +241 -0
  139. package/docs/how-it-works/cancellation.mdx +287 -0
  140. package/docs/how-it-works/code-transform.mdx +2 -2
  141. package/docs/how-it-works/encryption.mdx +2 -2
  142. package/docs/how-it-works/event-sourcing.mdx +2 -2
  143. package/docs/how-it-works/meta.json +2 -1
  144. package/docs/internal/index.mdx +21 -0
  145. package/docs/internal/meta.json +10 -0
  146. package/docs/internal/nitro-native-build.mdx +38 -0
  147. package/docs/internal/nitro-web-ui.mdx +24 -0
  148. package/docs/internal/serializable-abort-controller.mdx +148 -0
  149. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +63 -16
  150. package/docs/migration-guides/migrating-from-inngest.mdx +44 -22
  151. package/docs/migration-guides/migrating-from-temporal.mdx +43 -14
  152. package/docs/migration-guides/migrating-from-trigger-dev.mdx +59 -27
  153. package/docs/observability/attributes.mdx +87 -0
  154. package/docs/observability/index.mdx +25 -1
  155. package/docs/observability/meta.json +1 -1
  156. package/docs/observability/tracing.mdx +106 -0
  157. package/docs/testing/index.mdx +2 -2
  158. package/package.json +14 -13
  159. package/docs/api-reference/workflow-api/world/meta.json +0 -4
  160. package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
  161. package/docs/cookbook/advanced/custom-serialization.mdx +0 -168
  162. package/docs/cookbook/advanced/durable-objects.mdx +0 -148
  163. package/docs/cookbook/advanced/isomorphic-packages.mdx +0 -145
  164. package/docs/cookbook/agent-patterns/stop-workflow.mdx +0 -216
  165. package/docs/cookbook/agent-patterns/tool-orchestration.mdx +0 -255
  166. package/docs/cookbook/agent-patterns/tool-streaming.mdx +0 -181
  167. package/docs/cookbook/common-patterns/child-workflows.mdx +0 -372
  168. package/docs/cookbook/common-patterns/content-router.mdx +0 -207
  169. package/docs/cookbook/common-patterns/fan-out.mdx +0 -208
  170. 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
@@ -1,10 +1,9 @@
1
1
  {
2
2
  "title": "Advanced",
3
3
  "pages": [
4
+ "child-workflows",
5
+ "upgrading-workflows",
4
6
  "serializable-steps",
5
- "durable-objects",
6
- "isomorphic-packages",
7
- "custom-serialization",
8
7
  "publishing-libraries"
9
8
  ]
10
9
  }
@@ -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
- ├── src/
19
- │ ├── index.ts # Package entry point
20
- │ ├── types.ts # Shared types
21
- │ ├── workflows/
22
- │ │ ├── index.ts # Re-exports all workflows
23
- │ │ ├── transcode.ts # Workflow: transcode a video
24
- │ │ └── generate-thumbnails.ts
25
- │ └── lib/
26
- │ └── api-client.ts # Internal helpers (NOT steps)
27
- ├── test-server/
28
- │ └── workflows.ts # Re-export for integration tests
29
- ├── tsup.config.ts
30
- ├── package.json
31
- └── tsconfig.json
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/cookbook/advanced/custom-serialization). See the [serialization reference](/docs/foundations/serialization) for the full list of supported types. Do not pass or return:
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
- If your library should work both as a standalone package and inside Workflow SDK, declare `workflow` as an optional peer dependency:
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
- Use dynamic imports and runtime detection so your library gracefully degrades when workflow is not installed:
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 isWorkflowRuntime(): Promise<boolean> {
276
+ async function getWorkflowStepId(): Promise<string | null> { // [!code highlight]
248
277
  try {
249
278
  const wf = await import("workflow");
250
- if (typeof wf.getWorkflowMetadata !== "function") return false;
251
- wf.getWorkflowMetadata(); // [!code highlight]
252
- return true;
279
+ const { stepId } = wf.getStepMetadata();
280
+ return stepId;
253
281
  } catch {
254
- return false;
282
+ return null;
255
283
  }
256
284
  }
257
285
  ```
258
286
 
259
- See [Isomorphic Packages](/docs/cookbook/advanced/isomorphic-packages) for the full pattern including feature detection, dynamic imports, and dual-path execution.
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/api-reference/workflow/use-workflow) — declares the orchestrator function
277
- - [`"use step"`](/docs/api-reference/workflow/use-step) — marks functions for durable execution
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 provider initialization, making non-serializable AI SDK models work inside durable workflows.
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
- Workflow functions run inside a sandboxed VM where every value that crosses a function boundary must be serializable (JSON-safe). 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.
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/api-reference/workflow/use-step) — marks a function for extraction and serialization
134
- - [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
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`)