workflow 5.3.0 → 5.4.0

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 (28) hide show
  1. package/docs/api-reference/workflow/create-hook.mdx +1 -1
  2. package/docs/api-reference/workflow/create-webhook.mdx +1 -1
  3. package/docs/api-reference/workflow/fetch.mdx +1 -5
  4. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +2 -2
  5. package/docs/api-reference/workflow-api/resume-hook.mdx +2 -2
  6. package/docs/api-reference/workflow-api/start.mdx +12 -8
  7. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +2 -2
  8. package/docs/api-reference/workflow-errors/index.mdx +1 -1
  9. package/docs/api-reference/workflow-errors/workflow-start-error.mdx +5 -5
  10. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -1
  11. package/docs/changelog/eager-processing.mdx +2 -0
  12. package/docs/configuration/cli-and-web-ui.mdx +4 -2
  13. package/docs/configuration/runtime-tuning.mdx +7 -0
  14. package/docs/configuration/worlds.mdx +1 -1
  15. package/docs/cookbook/advanced/child-workflows.mdx +126 -186
  16. package/docs/cookbook/common-patterns/idempotency.mdx +2 -2
  17. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +1 -1
  18. package/docs/cookbook/common-patterns/workflow-composition.mdx +5 -5
  19. package/docs/errors/fetch-in-workflow.mdx +15 -35
  20. package/docs/foundations/hooks.mdx +1 -1
  21. package/docs/foundations/idempotency.mdx +11 -11
  22. package/docs/foundations/starting-workflows.mdx +3 -7
  23. package/docs/whats-new.mdx +1 -1
  24. package/docs/worlds/building-a-world.mdx +4 -4
  25. package/docs/worlds/postgres.mdx +7 -11
  26. package/docs/worlds/upgrading-to-v5.mdx +1 -1
  27. package/docs/worlds/vercel.mdx +3 -7
  28. package/package.json +10 -10
@@ -1,14 +1,14 @@
1
1
  ---
2
2
  title: Child Workflows
3
- description: Spawn child workflows from a parent and wait for completion via hook resume.
3
+ description: Spawn child workflows from a parent and wait for them without polling.
4
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.
5
+ summary: Orchestrate independent child workflows from a parent with start() and await run.returnValue. The parent suspends on a system hook the child resumes when it finishes, so waiting costs no compute and never polls.
6
6
  related:
7
7
  - /docs/api-reference/workflow-api/start
8
8
  ---
9
9
 
10
10
  <CopyPrompt
11
- text="Refactor this workflow to use child workflows. Keep the parent as an exported `&quot;use workflow&quot;` function. Move independent units of durable work into separate exported child workflow functions. From the parent, call `start(childWorkflow, [args])` from `workflow/api` or the documented `startAndWait`/hook pattern where completion must resume the parent. Pass only serializable state to children. For fan-out, start children in parallel with `Promise.all` or bounded batches, collect run IDs, handle partial failures with `Promise.allSettled`, and use `getRun(runId)` when status, cancellation, streams, or return values are needed. Verify child start, completion, failure, and parent resume behavior."
11
+ text="Refactor this workflow to use child workflows. Keep the parent as an exported `&quot;use workflow&quot;` function. Move independent units of durable work into separate exported child workflow functions. From the parent, call `start(childWorkflow, [args])` from `workflow/api` and `await run.returnValue` where the parent needs the child's result: the parent suspends on a system hook the child resumes when it finishes, so no polling or hand-written completion hook is needed. Pass only serializable state to children. For fan-out, start children in parallel with `Promise.all` or bounded batches, handle partial failures with `Promise.allSettled`, and catch `WorkflowRunFailedError` / `WorkflowRunCancelledError` for failed or canceled children. Verify child start, completion, failure, and parent resume behavior."
12
12
  />
13
13
 
14
14
  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.
@@ -25,69 +25,17 @@ Child workflows are the right choice when:
25
25
 
26
26
  For simpler cases where steps share a single event log, use [direct await composition](/cookbook/common-patterns/workflow-composition#direct-await-flattening) instead.
27
27
 
28
- ## Basic pattern: spawn and wait via hook
28
+ ## Waiting for a child
29
29
 
30
- The recommended pattern has four parts:
31
-
32
- 1. A **completion hook** the parent creates and awaits, with zero compute while waiting
33
- 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`
34
- 3. A **`start()` call** that spawns the wrapped child with the hook token (directly from the workflow in v5)
35
- 4. A **`startAndWait()` helper** that ties the hook, spawn, and typed result together
30
+ Start the child with [`start()`](/docs/api-reference/workflow-api/start) and await its `returnValue`:
36
31
 
37
32
  ```typescript
38
- import { defineHook, getWorkflowMetadata } from "workflow";
39
33
  import { start } from "workflow/api";
40
- import { z } from "zod";
41
34
 
42
35
  declare function fetchDocument(documentId: string): Promise<string>; // @setup
43
36
  declare function analyzeContent(content: string): Promise<string>; // @setup
44
37
  declare function generateSummary(analysis: string): Promise<string>; // @setup
45
38
 
46
- const childCompletionHook = defineHook({
47
- schema: z.discriminatedUnion("status", [
48
- z.object({ status: z.literal("completed"), value: z.unknown() }),
49
- z.object({ status: z.literal("failed"), error: z.string() }),
50
- ]),
51
- });
52
-
53
- function completionToken(parentRunId: string, key: string) {
54
- return `child-completion:${parentRunId}:${key}`;
55
- }
56
-
57
- async function resumeParentCompletion(
58
- token: string,
59
- result:
60
- | { status: "completed"; value: unknown }
61
- | { status: "failed"; error: string }
62
- ) {
63
- "use step";
64
- await childCompletionHook.resume(token, result);
65
- }
66
-
67
- async function withChildCompletionHook<TResult>(
68
- runChild: () => Promise<TResult>,
69
- completionTokenArg: string
70
- ) {
71
- let result:
72
- | { status: "completed"; value: TResult }
73
- | { status: "failed"; error: string }
74
- | undefined;
75
-
76
- try {
77
- const value = await runChild();
78
- result = { status: "completed", value };
79
- } catch (error) {
80
- result = {
81
- status: "failed",
82
- error: error instanceof Error ? error.message : String(error),
83
- };
84
- } finally {
85
- if (result) {
86
- await resumeParentCompletion(completionTokenArg, result);
87
- }
88
- }
89
- }
90
-
91
39
  // Child workflow -- processes a single document
92
40
  export async function processDocument(documentId: string) {
93
41
  "use workflow";
@@ -99,77 +47,86 @@ export async function processDocument(documentId: string) {
99
47
  return { documentId, summary };
100
48
  }
101
49
 
102
- // Spawnable wrapper -- explicit export so `start()` can register it
103
- export async function processDocumentWithCompletion(
104
- documentId: string,
105
- completionTokenArg: string
106
- ) {
50
+ // Parent workflow -- orchestrates document processing
51
+ export async function processDocumentBatch(documentIds: string[]) {
107
52
  "use workflow";
108
53
 
109
- await withChildCompletionHook(
110
- () => processDocument(documentId),
111
- completionTokenArg
54
+ const runs = await Promise.all(
55
+ documentIds.map((documentId) => start(processDocument, [documentId])) // [!code highlight]
112
56
  );
57
+ const results = await Promise.all(runs.map((run) => run.returnValue)); // [!code highlight]
58
+
59
+ return { processed: results.length, results };
113
60
  }
61
+ ```
114
62
 
115
- async function startAndWait<TResult>(
116
- key: string,
117
- startChild: (completionTokenArg: string) => Promise<void>
118
- ): Promise<TResult> {
119
- const { workflowRunId } = getWorkflowMetadata();
120
- const token = completionToken(workflowRunId, key);
121
- const hook = childCompletionHook.create({ token }); // [!code highlight]
63
+ `returnValue` is typed from the child's return type. A child that fails or is canceled rejects it with [`WorkflowRunFailedError`](/docs/api-reference/workflow-errors/workflow-run-failed-error) or [`WorkflowRunCancelledError`](/docs/api-reference/workflow-errors/workflow-run-cancelled-error).
122
64
 
123
- await startChild(token);
65
+ ### How the parent waits
124
66
 
125
- const completion = await hook; // [!code highlight]
126
- if (completion.status === "failed") {
127
- throw new Error(completion.error);
128
- }
129
- return completion.value as TResult;
130
- }
67
+ Awaiting `returnValue` of a run the workflow started does not poll. The SDK waits on a **system hook**, the same handshake you would otherwise write by hand, but with one hook for the whole parent rather than one per child:
131
68
 
132
- // Parent workflow -- orchestrates document processing
133
- export async function processDocumentBatch(documentIds: string[]) {
134
- "use workflow";
69
+ 1. `start()` records the parent's run ID on the child, and remembers the parent on the returned `Run`.
70
+ 2. When the parent awaits a child, it registers its completion hook (a system hook whose token is derived from the parent's run ID) if it is not already open, then reads every child it started waiting on since its last read, in one step. A child that already finished is answered from that read.
71
+ 3. Otherwise the parent suspends on the hook. When a child completes, fails, or is canceled, its runtime resumes the parent's hook with that child's run ID, and the parent reads that child's result.
72
+ 4. Once the parent is no longer waiting on any child, it disposes the hook, so children it never awaits do not wake it.
135
73
 
136
- const results = await Promise.all(
137
- documentIds.map((documentId) =>
138
- startAndWait<{ documentId: string; summary: string }>(documentId, (token) =>
139
- start(processDocumentWithCompletion, [documentId, token]).then(() => undefined) // [!code highlight]
140
- )
141
- )
142
- );
74
+ This gives you:
143
75
 
144
- return { processed: results.length, results };
145
- }
146
- ```
76
+ - **Zero compute while waiting**: The parent is suspended rather than waking on a poll interval, and holds no worker slot. Worker-based Worlds such as [Postgres](/worlds/postgres) do not need a slot per waiting parent.
77
+ - **Immediate wake-up**: The parent resumes as soon as a child finishes, not on the next poll tick.
78
+ - **A slim parent log**: Fanning out to many children adds one system hook and one status read to the parent, plus, per child, the notification and the read of its result.
79
+ - **No wiring**: There is no hook to define, no token to pass, and no wrapper workflow to export.
80
+
81
+ The `Run` keeps this behavior when it travels within the parent: a step of the parent that calls `start()` and returns the `Run` hands the parent a handle it can await the same way. Awaiting the same child twice shares one wait.
82
+
83
+ ### Cancellations that bypass the SDK
147
84
 
148
- ### Why hooks instead of polling?
85
+ <Callout type="warn">
86
+ A parent is notified **immediately** only when the child's own runtime records its outcome, or when the child is canceled through the SDK. A cancellation written to the World without going through the SDK is not delivered to the parent, which keeps waiting until its next safety-net check.
87
+ </Callout>
149
88
 
150
- Polling with `getRun().status` in a `sleep()` loop works, but hook resume is preferable because:
89
+ | How the child finished | Parent resumes |
90
+ | --- | --- |
91
+ | The child completed or failed | Immediately |
92
+ | Canceled with `run.cancel()`, `cancelRun()`, or `cancelRuns()` | Immediately |
93
+ | Canceled with `workflow cancel` or from `workflow web` | Immediately (both call `cancelRun()`) |
94
+ | Canceled by any other tool that writes the cancellation to the World or its backend directly, without the SDK | At the next safety-net check |
95
+ | The child's invocation crashed after recording its outcome but before resuming the parent | At the next safety-net check |
151
96
 
152
- - **Zero compute while waiting**: The parent suspends on the hook instead of waking every poll interval.
153
- - **Immediate wake-up**: The parent resumes as soon as the child finishes, not on the next poll tick.
154
- - **Typed payloads**: The child sends `{ status, value | error }` directly, with no separate `returnValue` fetch step.
155
- - **No worker-pool pressure**: `Run#returnValue` polling inside steps can hold worker slots while waiting for children (see [Eager Processing](/docs/changelog/eager-processing)).
97
+ The safety net: while a parent waits on children, it keeps one sleep open and, when it fires, reads every child it is still waiting on. The first check runs 5 minutes after the parent starts waiting, then the interval doubles up to every 6 hours. A missed notification therefore delays the parent but never strands it. Each check costs the parent one sleep and one step, so a child that runs for a day adds about a dozen of each.
156
98
 
157
- 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()`.
99
+ If a parent must react to a cancellation faster than that, cancel children through the SDK.
100
+
101
+ ### When `returnValue` polls instead
102
+
103
+ `returnValue` falls back to polling the child, inside a step that holds its worker slot until the child finishes, when the waiting code is not the workflow that started it:
104
+
105
+ - a step, API route, or other server code (for example, a step that calls `start()` and awaits the result itself)
106
+ - a different workflow that was handed the `Run` as an argument
107
+
108
+ It also polls for a child started on another deployment (`deploymentId`) whose SDK predates the system hook, and for every child started while [`WORKFLOW_CHILD_RUN_COMPLETION_HOOK=0`](/docs/configuration/runtime-tuning#workflow_child_run_completion_hook) is set.
158
109
 
159
110
  ## Fan-out pattern: chunked spawning
160
111
 
161
- 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).
112
+ When spawning hundreds of children, batch the `start()` calls to avoid overwhelming the system. Each awaited child gets its own system hook, so a chunk costs nothing while it waits.
162
113
 
163
114
  ```typescript
164
115
  import { start } from "workflow/api";
165
116
 
166
- declare function startAndWait<TResult>(
167
- key: string,
168
- startChild: (completionTokenArg: string) => Promise<void>
169
- ): Promise<TResult>; // @setup
117
+ declare function queryDatabase(reportId: string, query: string): Promise<string>; // @setup
118
+ declare function formatReport(reportId: string, data: string): Promise<string>; // @setup
170
119
 
171
120
  const CHUNK_SIZE = 10;
172
121
 
122
+ export async function generateReport(reportId: string, query: string) {
123
+ "use workflow";
124
+
125
+ const data = await queryDatabase(reportId, query);
126
+ const formatted = await formatReport(reportId, data);
127
+ return { reportId, formatted };
128
+ }
129
+
173
130
  export async function largeReportBatch(
174
131
  reportConfigs: Array<{ id: string; query: string }>
175
132
  ) {
@@ -178,82 +135,36 @@ export async function largeReportBatch(
178
135
  const results = [];
179
136
  for (let i = 0; i < reportConfigs.length; i += CHUNK_SIZE) {
180
137
  const chunk = reportConfigs.slice(i, i + CHUNK_SIZE);
181
- const chunkResults = await Promise.all(
182
- chunk.map((config) =>
183
- startAndWait<{ reportId: string; formatted: string }>(config.id, (token) =>
184
- start(generateReportWithCompletion, [
185
- config.id,
186
- config.query,
187
- token,
188
- ]).then(() => undefined)
189
- )
190
- )
138
+ const runs = await Promise.all(
139
+ chunk.map((config) => start(generateReport, [config.id, config.query]))
191
140
  );
192
- results.push(...chunkResults);
141
+ results.push(...(await Promise.all(runs.map((run) => run.returnValue))));
193
142
  }
194
143
 
195
144
  return { total: results.length, results };
196
145
  }
197
-
198
- async function generateReportWithCompletion(
199
- reportId: string,
200
- query: string,
201
- completionTokenArg: string
202
- ) {
203
- "use workflow";
204
-
205
- await withChildCompletionHook(
206
- () => generateReport(reportId, query),
207
- completionTokenArg
208
- );
209
- }
210
-
211
- async function generateReport(reportId: string, query: string) {
212
- "use workflow";
213
-
214
- const data = await queryDatabase(reportId, query);
215
- const formatted = await formatReport(reportId, data);
216
- return { reportId, formatted };
217
- }
218
-
219
- declare function queryDatabase(reportId: string, query: string): Promise<string>; // @setup
220
- declare function formatReport(reportId: string, data: string): Promise<string>; // @setup
221
- declare function withChildCompletionHook<TResult>(
222
- runChild: () => Promise<TResult>,
223
- completionTokenArg: string
224
- ): Promise<void>; // @setup
225
146
  ```
226
147
 
227
148
  ## Error handling
228
149
 
229
150
  ### Tolerating partial failures
230
151
 
231
- Use `Promise.allSettled` with `startAndWait()` so one failing child doesn't abort siblings. The hook payload already carries `{ status: "failed", error }`, so no status polling is required.
152
+ Use `Promise.allSettled` over the children's `returnValue` so one failing child doesn't abort its siblings. A failed child's entry is rejected with `WorkflowRunFailedError`, whose `cause` is the error the child threw.
232
153
 
233
154
  ```typescript
234
155
  import { start } from "workflow/api";
235
156
 
236
- declare function startAndWait<TResult>(
237
- key: string,
238
- startChild: (completionTokenArg: string) => Promise<void>
239
- ): Promise<TResult>; // @setup
240
- declare function processDocumentWithCompletion(
241
- documentId: string,
242
- completionTokenArg: string
243
- ): Promise<void>; // @setup
157
+ declare function processDocument(
158
+ documentId: string
159
+ ): Promise<{ documentId: string; summary: string }>; // @setup
244
160
 
245
161
  export async function processDocumentBatchTolerant(documentIds: string[]) {
246
162
  "use workflow";
247
163
 
248
- const settled = await Promise.allSettled(
249
- documentIds.map((documentId) =>
250
- startAndWait<{ documentId: string; summary: string }>(documentId, (token) =>
251
- start(processDocumentWithCompletion, [documentId, token]).then(
252
- () => undefined
253
- )
254
- )
255
- )
164
+ const runs = await Promise.all(
165
+ documentIds.map((documentId) => start(processDocument, [documentId]))
256
166
  );
167
+ const settled = await Promise.allSettled(runs.map((run) => run.returnValue));
257
168
 
258
169
  const results = settled
259
170
  .filter(
@@ -270,52 +181,81 @@ export async function processDocumentBatchTolerant(documentIds: string[]) {
270
181
 
271
182
  ### Retrying failed children
272
183
 
273
- When a child fails, spawn a replacement with a fresh hook token. Track restart counts to prevent infinite retry loops.
184
+ When a child fails, start a replacement. Track restart counts to prevent infinite retry loops.
274
185
 
275
186
  ```typescript
276
- declare function startAndWait<TResult>(
277
- key: string,
278
- startChild: (completionTokenArg: string) => Promise<void>
279
- ): Promise<TResult>; // @setup
280
- declare function spawnProcessDocument(
281
- documentId: string,
282
- completionTokenArg: string
283
- ): Promise<void>; // @setup
187
+ import { start } from "workflow/api";
188
+
189
+ declare function processDocument(
190
+ documentId: string
191
+ ): Promise<{ documentId: string; summary: string }>; // @setup
284
192
 
285
- async function startAndWaitWithRetries(
193
+ async function processDocumentWithRetries(
286
194
  documentId: string,
287
195
  maxRestarts: number
288
196
  ): Promise<{ documentId: string; summary: string }> {
289
- for (let attempt = 0; attempt <= maxRestarts; attempt++) {
197
+ for (let attempt = 0; ; attempt++) {
198
+ const run = await start(processDocument, [documentId]);
290
199
  try {
291
- return await startAndWait<{ documentId: string; summary: string }>(
292
- `${documentId}:${attempt}`,
293
- (token) => spawnProcessDocument(documentId, token)
294
- );
200
+ return await run.returnValue;
295
201
  } catch (error) {
296
- if (attempt === maxRestarts) throw error;
202
+ if (attempt >= maxRestarts) throw error;
297
203
  }
298
204
  }
205
+ }
206
+ ```
207
+
208
+ ## Signaling the parent before the child finishes
209
+
210
+ The system hook fires only when the child finishes. When the parent needs to hear from a child mid-run (a progress milestone, an approval request, a partial result), create a [hook](/docs/foundations/hooks) in the parent and pass its token to the child, which resumes it from a step:
211
+
212
+ ```typescript
213
+ import { createHook } from "workflow";
214
+ import { resumeHook, start } from "workflow/api";
215
+
216
+ declare function prepareDraft(documentId: string): Promise<string>; // @setup
217
+ declare function publishDraft(draft: string): Promise<void>; // @setup
218
+
219
+ async function notifyDraftReady(token: string, draft: string) {
220
+ "use step";
221
+ await resumeHook(token, { draft });
222
+ }
223
+
224
+ export async function draftDocument(documentId: string, draftToken: string) {
225
+ "use workflow";
226
+
227
+ const draft = await prepareDraft(documentId);
228
+ await notifyDraftReady(draftToken, draft); // the parent continues from here
229
+ await publishDraft(draft);
230
+ return { documentId, published: true };
231
+ }
232
+
233
+ export async function reviewDocument(documentId: string) {
234
+ "use workflow";
235
+
236
+ const draftReady = createHook<{ draft: string }>();
237
+ const run = await start(draftDocument, [documentId, draftReady.token]);
299
238
 
300
- throw new Error("unreachable");
239
+ const { draft } = await draftReady; // mid-run signal from the child
240
+ const result = await run.returnValue; // completion, via the system hook
241
+ return { draft, ...result };
301
242
  }
302
243
  ```
303
244
 
304
245
  ## Tips
305
246
 
306
- - **Call `defineHook().resume()` from a step**: The wrapped child's `finally` block calls a step that resumes the parent hook.
307
- - **Export wrapped children at module scope**: The SDK registers `"use workflow"` functions statically, so a runtime higher-order function returned from `withChildCompletionHook()` cannot be passed to `start()`.
308
- - **Use stable hook keys**: Document IDs, job IDs, or indexes prevent token collisions between parallel children in one parent run.
247
+ - **Await only the children you need**: A child whose parent is not waiting on any child when it finishes costs one extra hook lookup and nothing in the parent. One that finishes while the parent waits on its siblings adds a notification to the parent's log.
309
248
  - **Use chunked spawning for large batches**: Starting 500 children at once can create a large burst of work. Break the work into chunks of 10–50.
310
- - **Watch the parent's log too**: The parent records events for spawning and collecting every child. On the default runtime, count those events against the parent's [event limit](/worlds/vercel#per-run-limits) and consider another layer of intermediate runs if needed. QuickJS with snapshotting reduces replay overhead and exempts eligible parent runs from the default event cap, but does not reduce their event count or remove payload and storage limits.
311
- - **Account for each child's retry semantics**: Steps inside child workflows retry independently. The parent sees the final `{ status, value | error }` payload from the hook.
249
+ - **Watch the parent's log too**: The parent records events for spawning and collecting every child (the spawn step, the child's notification on the parent's completion hook, and the step that reads its result). On the default runtime, count those events against the parent's [event limit](/worlds/vercel#per-run-limits) and consider another layer of intermediate runs if needed. QuickJS with snapshotting reduces replay overhead and exempts eligible parent runs from the default event cap, but does not reduce their event count or remove payload and storage limits.
250
+ - **Account for each child's retry semantics**: Steps inside child workflows retry independently. The parent only sees the child's final result or error.
251
+ - **Cancel children through the SDK**: [`run.cancel()`](/docs/api-reference/workflow-api/get-run), `cancelRun()`, `cancelRuns()`, `workflow cancel`, and `workflow web` resume a waiting parent immediately. Any other cancellation reaches the parent only at its next safety-net check; see [Cancellations that bypass the SDK](#cancellations-that-bypass-the-sdk).
312
252
  - **Use `deploymentId: "latest"` when 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.
313
253
 
314
254
  ## Key APIs
315
255
 
316
- - [`start()`](/docs/api-reference/workflow-api/start): Spawns a new workflow run and returns its run ID.
317
- - [`defineHook()`](/docs/api-reference/workflow/define-hook): Defines a typed hook for parent-child completion handshakes.
318
- - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes a waiting parent from a step called by the child wrapper.
319
- - [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata): Returns the parent run ID for deterministic hook tokens.
256
+ - [`start()`](/docs/api-reference/workflow-api/start): Spawns a new workflow run and returns a `Run` whose `returnValue` the parent can await.
257
+ - [`getRun()`](/docs/api-reference/workflow-api/get-run): Documents the `Run` handle, with `returnValue`, `status`, and `cancel()`.
258
+ - [`createHook()`](/docs/api-reference/workflow/create-hook): Creates a hook for signals from a child before it finishes.
259
+ - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes a parent's hook from a step in the child.
320
260
  - [`"use workflow"`](/docs/foundations/workflows-and-steps): Marks the orchestrator function.
321
261
  - [`"use step"`](/docs/foundations/workflows-and-steps): Marks functions with full Node.js access.
@@ -71,7 +71,7 @@ export async function POST(request: Request) {
71
71
 
72
72
  try {
73
73
  const run = await start(processOrder, [orderId], {
74
- hook: { token: `order:${orderId}` }, // [!code highlight]
74
+ experimental_hook: { token: `order:${orderId}` }, // [!code highlight]
75
75
  });
76
76
  return Response.json({ runId: run.runId, reused: false });
77
77
  } catch (error) {
@@ -91,4 +91,4 @@ The run's start Hook can be resumed as soon as `start()` returns, so a duplicate
91
91
  - [`createHook()`](/docs/api-reference/workflow/create-hook): Creates a hook with an optional deterministic token.
92
92
  - [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token): Finds the hook that owns a token.
93
93
  - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes the active hook when the duplicate request carries data.
94
- - [`start()`](/docs/api-reference/workflow-api/start): Starts a new workflow run, at most once per `hook.token`.
94
+ - [`start()`](/docs/api-reference/workflow-api/start): Starts a new workflow run, at most once per `experimental_hook.token`.
@@ -138,7 +138,7 @@ export async function birthdayWorkflow(
138
138
 
139
139
  1. **`await` is durable**: When the workflow awaits a step, the runtime persists the step's input, suspends the workflow, runs the step, and replays the workflow with the step's result on resume. The same applies to `sleep()` and `createWebhook()`.
140
140
  2. **`Promise.all` runs steps concurrently**: Each promise in the array is suspended on its own, and the workflow resumes only when all have settled. If any promise rejects, the whole `Promise.all` rejects.
141
- 3. **`Promise.race` resolves when the first promise settles**: The losing promises keep running in the background, but the workflow discards their results.
141
+ 3. **`Promise.race` resolves when the first promise settles**: As in plain JavaScript, the losing promises keep running in the background, but the workflow discards their results.
142
142
  4. **All primitives are promises**: `sleep("1 day")` and `createWebhook()` return promises, so they compose with `Promise.all` and `Promise.race` like steps do. This behavior enables patterns such as racing a webhook against a 24-hour deadline.
143
143
 
144
144
  ## Adapting to your use case
@@ -14,7 +14,7 @@ related:
14
14
  text="Compose these workflows. For direct composition, `await` the child workflow function from the parent &quot;use workflow&quot; function: the child's steps flatten into the parent's event log and run as a single run sharing the parent's lifecycle. For independent background work, spawn the child with `start()` from `workflow/api` called directly in the workflow (in v5, `start()` is step-backed and records a deterministic step boundary) and return `run.runId` so callers can track it with `getRun()`. Choose flattening when the parent needs the child's result; choose background spawn when the child should have its own run, retries, and lifetime. Keep all inputs and outputs serializable. Verify flattened execution, background spawn with a separate runId, and replay determinism."
15
15
  />
16
16
 
17
- Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or starts the child as an independent run (background spawn). For large fan-out operations with hook-based waiting and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
17
+ Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or starts the child as an independent run (background spawn). For large fan-out operations, waiting on children, and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
18
18
 
19
19
  ## When to use this
20
20
 
@@ -100,7 +100,7 @@ If you want the child workflow to run on the latest deployment rather than the c
100
100
 
101
101
  | | Direct await | Background spawn (`start()`) |
102
102
  | --- | --- | --- |
103
- | Parent waits for child | Yes | No |
103
+ | Parent waits for child | Yes | Optional (`await run.returnValue`) |
104
104
  | Has its own `runId` | No (shares parent's) | Yes |
105
105
  | Has its own event log | No | Yes |
106
106
  | Has its own retry boundary | No | Yes |
@@ -108,9 +108,9 @@ If you want the child workflow to run on the latest deployment rather than the c
108
108
 
109
109
  ## Adapting to your use case
110
110
 
111
- - **Spawn many children at once**: call `start()` in a loop from the workflow. For more advanced fan-out (chunking, hook-based waiting, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
112
- - **Wait for a background child to finish**: combine `start()` with a completion hook the child resumes when done. The [Child Workflows](/cookbook/advanced/child-workflows) page covers the recommended `startAndWait()` pattern.
113
- - **Pass results back from background children**: the wrapped child resumes the parent's hook in `finally` with `{ status, value | error }`; the parent awaits the hook instead of polling `getRun().status`.
111
+ - **Spawn many children at once**: call `start()` in a loop from the workflow. For more advanced fan-out (chunking, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
112
+ - **Wait for a background child to finish**: `await run.returnValue` on the `Run` that `start()` returned. The parent suspends on a system hook the child resumes when it finishes, so it waits without polling. See [How the parent waits](/cookbook/advanced/child-workflows#how-the-parent-waits).
113
+ - **Hear from a background child before it finishes**: create a hook in the parent and pass its token to the child, which resumes it from a step. See [Signaling the parent before the child finishes](/cookbook/advanced/child-workflows#signaling-the-parent-before-the-child-finishes).
114
114
 
115
115
  ## Key APIs
116
116
 
@@ -1,8 +1,8 @@
1
1
  ---
2
2
  title: fetch-in-workflow
3
- description: Use the workflow fetch step function instead of global fetch in workflows.
3
+ description: Make HTTP requests from step functions instead of workflow functions.
4
4
  type: troubleshooting
5
- summary: Resolve the fetch-in-workflow error by using the workflow fetch function.
5
+ summary: Resolve the fetch-in-workflow error by moving HTTP requests into a step function.
6
6
  prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
@@ -29,7 +29,7 @@ Many libraries make HTTP requests under the hood. For example, the AI SDK's `gen
29
29
 
30
30
  ## Quick fix
31
31
 
32
- Import the `fetch` step function from the `workflow` package and assign it to `globalThis.fetch` inside your workflow function. This version of `fetch` is a step function that wraps the standard `fetch` API, automatically handling serialization and providing retry capabilities. This will also make `fetch()` available to all functions and libraries in the current workflow function.
32
+ Move the code that makes the request into a step function, and call that step from the workflow. Steps have full Node.js access, so `fetch()` and libraries that call it work as usual.
33
33
 
34
34
  **Before:**
35
35
 
@@ -53,14 +53,11 @@ export async function chatWorkflow(prompt: string) {
53
53
 
54
54
  ```typescript lineNumbers title="workflows/ai.ts"
55
55
  import { generateText } from "ai";
56
- import { fetch } from "workflow"; // [!code highlight]
57
56
 
58
- export async function chatWorkflow(prompt: string) {
59
- "use workflow";
60
-
61
- globalThis.fetch = fetch; // [!code highlight]
57
+ async function generate(prompt: string) {
58
+ "use step"; // [!code highlight]
62
59
 
63
- // Now generateText() can make HTTP requests via the fetch step
60
+ // generateText calls fetch() under the hood
64
61
  const result = await generateText({
65
62
  model: "spacexai/grok-4.6",
66
63
  prompt,
@@ -68,42 +65,25 @@ export async function chatWorkflow(prompt: string) {
68
65
 
69
66
  return result.text;
70
67
  }
71
- ```
72
-
73
- ## Common scenarios
74
68
 
75
- ### AI SDK integration
76
-
77
- This is the most common scenario - using AI SDK functions that make HTTP requests:
78
-
79
- ```typescript lineNumbers
80
- import { generateText } from "ai";
81
- import { fetch } from "workflow"; // [!code highlight]
82
-
83
- export async function aiWorkflow(userMessage: string) {
69
+ export async function chatWorkflow(prompt: string) {
84
70
  "use workflow";
85
71
 
86
- globalThis.fetch = fetch; // [!code highlight]
87
-
88
- // generateText makes an HTTP request under the hood
89
- const response = await generateText({
90
- model: "spacexai/grok-4.6",
91
- prompt: userMessage,
92
- maxRetries: 0, // [!code highlight]
93
- });
94
-
95
- return response.text;
72
+ return await generate(prompt); // [!code highlight]
96
73
  }
97
74
  ```
98
75
 
99
- #### AI SDK limitations in workflow functions
76
+ ## Common scenarios
77
+
78
+ ### AI SDK integration
79
+
80
+ For agents, use AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) or [`HarnessAgent`](https://ai-sdk.dev/v7/docs/ai-sdk-harnesses/workflow-utilities), which run model calls as steps.
100
81
 
101
- - **Set `maxRetries: 0`.** When a provider returns a retryable status such as 429 or 5xx, the AI SDK waits with `setTimeout` before it retries, and [timers are not available in workflow functions](/docs/errors/timeout-in-workflow). With the default `maxRetries`, the run fails with a timer error instead of the provider's error. To retry these calls, put the `generateText()` call inside a step function, which the workflow retries on failure.
102
- - **Streaming is not supported.** `streamText()` and other streaming calls pipe the response through web streams, which are not available in workflow functions. Use [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent), or call `streamText()` inside a step function.
82
+ For single AI SDK calls, use a step function as shown above.
103
83
 
104
84
  ### Direct API calls
105
85
 
106
- You can also use the fetch step function directly for your own HTTP requests:
86
+ For simple requests, you can use the `fetch` step function from `workflow` directly:
107
87
 
108
88
  ```typescript lineNumbers
109
89
  import { fetch } from "workflow";
@@ -112,7 +112,7 @@ export async function orderWorkflow(orderId: string) {
112
112
  }
113
113
  ```
114
114
 
115
- Calling `createHook()` on its own does not register the hook; registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies. A run started with [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) already owns its token: `createHook({ token })` with that token binds to the run's start Hook, and `getConflict()` resolves `null` without suspending.
115
+ Calling `createHook()` on its own does not register the hook; registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies. A run started with [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) already owns its token: `createHook({ token })` with that token binds to the run's start Hook, and `getConflict()` resolves `null` without suspending.
116
116
 
117
117
  Awaiting the registration costs one write, not a round trip through the queue: the invocation that commits the registration is the one that carries on past the awaiter, and it runs the steps the workflow started beside the awaiter — as in `await Promise.all([hook.getConflict(), prepare()])` — in that same invocation, once the registration is recorded. That covers the steps the invocation runs inline; a fan-out wider than the free inline slots ([`WORKFLOW_MAX_INLINE_STEPS`](/docs/configuration/runtime-tuning#workflow_max_inline_steps), less any inline steps the invocation is still running) queues the rest alongside the hook, so await `hook.getConflict()` before the step when the ordering itself matters. See [`createHook()`](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
118
118