workflow 5.0.0-beta.2 → 5.0.0-beta.4
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/docs/cookbook/{common-patterns → advanced}/child-workflows.mdx +1 -1
- package/docs/cookbook/advanced/distributed-abort-controller.mdx +318 -0
- package/docs/cookbook/advanced/meta.json +2 -3
- package/docs/cookbook/advanced/publishing-libraries.mdx +83 -26
- package/docs/cookbook/advanced/serializable-steps.mdx +15 -3
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +205 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +50 -91
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +148 -171
- package/docs/cookbook/agent-patterns/meta.json +1 -7
- package/docs/cookbook/common-patterns/batching.mdx +44 -118
- package/docs/cookbook/common-patterns/meta.json +4 -4
- package/docs/cookbook/common-patterns/saga.mdx +126 -31
- package/docs/cookbook/common-patterns/scheduling.mdx +70 -194
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +99 -0
- package/docs/cookbook/common-patterns/workflow-composition.mdx +118 -0
- package/docs/cookbook/index.mdx +13 -16
- package/docs/cookbook/integrations/ai-sdk.mdx +296 -140
- package/docs/cookbook/integrations/chat-sdk.mdx +251 -151
- package/docs/cookbook/integrations/sandbox.mdx +469 -81
- package/docs/cookbook/meta.json +1 -1
- package/docs/foundations/index.mdx +0 -3
- package/docs/foundations/meta.json +0 -1
- package/docs/foundations/serialization.mdx +1 -1
- package/docs/foundations/starting-workflows.mdx +1 -1
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +60 -8
- package/docs/migration-guides/migrating-from-inngest.mdx +38 -6
- package/docs/migration-guides/migrating-from-temporal.mdx +38 -4
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +52 -11
- package/package.json +11 -11
- 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/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,155 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Sequential & Parallel Execution
|
|
3
|
+
description: Compose steps with familiar async/await patterns — sequential await, Promise.all, and Promise.race.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Workflows are just async functions, so all the standard composition primitives (await, Promise.all, Promise.race) apply unchanged — including racing webhooks against durable sleeps.
|
|
6
|
+
related:
|
|
7
|
+
- /docs/foundations/workflows-and-steps
|
|
8
|
+
- /cookbook/common-patterns/timeouts
|
|
9
|
+
- /cookbook/common-patterns/scheduling
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
Workflows are written in plain async/await — there's no new control-flow API to learn. Sequential awaits chain steps that depend on each other, `Promise.all` runs independent steps in parallel, and `Promise.race` returns whichever finishes first. These compose with workflow primitives like [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) since those are also just promises.
|
|
13
|
+
|
|
14
|
+
## When to use this
|
|
15
|
+
|
|
16
|
+
- **Pipelines** — each step depends on the previous step's output (validate → process → store)
|
|
17
|
+
- **Independent fan-out** — fetch multiple resources or perform multiple actions that don't depend on each other
|
|
18
|
+
- **Race conditions** — return as soon as one of N operations completes (timeout, first-responder, deadline)
|
|
19
|
+
- **Mixing primitives** — running steps, sleeps, and webhooks side-by-side in the same control-flow expression
|
|
20
|
+
|
|
21
|
+
## Pattern
|
|
22
|
+
|
|
23
|
+
### Sequential
|
|
24
|
+
|
|
25
|
+
The simplest way to orchestrate steps is to execute them one after another, where each step depends on the previous step's output.
|
|
26
|
+
|
|
27
|
+
```typescript lineNumbers
|
|
28
|
+
declare function validateData(data: unknown): Promise<string>; // @setup
|
|
29
|
+
declare function processData(data: string): Promise<string>; // @setup
|
|
30
|
+
declare function storeData(data: string): Promise<string>; // @setup
|
|
31
|
+
|
|
32
|
+
export async function dataPipelineWorkflow(data: unknown) {
|
|
33
|
+
"use workflow";
|
|
34
|
+
|
|
35
|
+
const validated = await validateData(data);
|
|
36
|
+
const processed = await processData(validated);
|
|
37
|
+
const stored = await storeData(processed);
|
|
38
|
+
|
|
39
|
+
return stored;
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Parallel with `Promise.all`
|
|
44
|
+
|
|
45
|
+
When steps don't depend on each other, run them concurrently with `Promise.all`. The workflow waits until all of them resolve.
|
|
46
|
+
|
|
47
|
+
```typescript lineNumbers
|
|
48
|
+
declare function fetchUser(userId: string): Promise<{ name: string }>; // @setup
|
|
49
|
+
declare function fetchOrders(userId: string): Promise<{ items: string[] }>; // @setup
|
|
50
|
+
declare function fetchPreferences(userId: string): Promise<{ theme: string }>; // @setup
|
|
51
|
+
|
|
52
|
+
export async function fetchUserData(userId: string) {
|
|
53
|
+
"use workflow";
|
|
54
|
+
|
|
55
|
+
const [user, orders, preferences] = await Promise.all([ // [!code highlight]
|
|
56
|
+
fetchUser(userId), // [!code highlight]
|
|
57
|
+
fetchOrders(userId), // [!code highlight]
|
|
58
|
+
fetchPreferences(userId), // [!code highlight]
|
|
59
|
+
]); // [!code highlight]
|
|
60
|
+
|
|
61
|
+
return { user, orders, preferences };
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Race with `Promise.race`
|
|
66
|
+
|
|
67
|
+
`Promise.race` resolves as soon as the first promise settles. Since [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) return promises, they compose naturally — for example, waiting for a webhook callback with a deadline:
|
|
68
|
+
|
|
69
|
+
```typescript lineNumbers
|
|
70
|
+
import { sleep, createWebhook } from "workflow";
|
|
71
|
+
|
|
72
|
+
declare function executeExternalTask(webhookUrl: string): Promise<void>; // @setup
|
|
73
|
+
|
|
74
|
+
export async function runExternalTask(userId: string) {
|
|
75
|
+
"use workflow";
|
|
76
|
+
|
|
77
|
+
const webhook = createWebhook();
|
|
78
|
+
await executeExternalTask(webhook.url);
|
|
79
|
+
|
|
80
|
+
await Promise.race([ // [!code highlight]
|
|
81
|
+
webhook, // [!code highlight]
|
|
82
|
+
sleep("1 day"), // [!code highlight]
|
|
83
|
+
]); // [!code highlight]
|
|
84
|
+
|
|
85
|
+
console.log("Done");
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
For racing operations against deadlines specifically (timeouts), see the dedicated [Timeouts](/cookbook/common-patterns/timeouts) recipe — it covers result discrimination, `FatalError` semantics, and the "loser keeps running" caveat.
|
|
90
|
+
|
|
91
|
+
### Combining sequential, parallel, and durable primitives
|
|
92
|
+
|
|
93
|
+
Most real workflows combine all three. Here's a simplified version of the [birthday card generator demo](https://github.com/vercel/workflow-examples/tree/main/birthday-card-generator) — sequential card generation, parallel RSVP fan-out, non-blocking webhook collection, and a durable sleep until the birthday:
|
|
94
|
+
|
|
95
|
+
```typescript lineNumbers
|
|
96
|
+
import { createWebhook, sleep, type Webhook } from "workflow";
|
|
97
|
+
|
|
98
|
+
declare function makeCardText(prompt: string): Promise<string>; // @setup
|
|
99
|
+
declare function makeCardImage(text: string): Promise<string>; // @setup
|
|
100
|
+
declare function sendRSVPEmail(friend: string, webhook: Webhook): Promise<void>; // @setup
|
|
101
|
+
declare function sendBirthdayCard(text: string, image: string, rsvps: unknown[], email: string): Promise<void>; // @setup
|
|
102
|
+
|
|
103
|
+
export async function birthdayWorkflow(
|
|
104
|
+
prompt: string,
|
|
105
|
+
email: string,
|
|
106
|
+
friends: string[],
|
|
107
|
+
birthday: Date
|
|
108
|
+
) {
|
|
109
|
+
"use workflow";
|
|
110
|
+
|
|
111
|
+
const text = await makeCardText(prompt); // [!code highlight]
|
|
112
|
+
const image = await makeCardImage(text); // [!code highlight]
|
|
113
|
+
|
|
114
|
+
const webhooks = friends.map(() => createWebhook());
|
|
115
|
+
|
|
116
|
+
await Promise.all( // [!code highlight]
|
|
117
|
+
friends.map((friend, i) => sendRSVPEmail(friend, webhooks[i])) // [!code highlight]
|
|
118
|
+
); // [!code highlight]
|
|
119
|
+
|
|
120
|
+
const rsvps: unknown[] = [];
|
|
121
|
+
webhooks.map((webhook) =>
|
|
122
|
+
webhook.then((req) => req.json()).then(({ rsvp }) => rsvps.push(rsvp))
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
await sleep(birthday); // [!code highlight]
|
|
126
|
+
|
|
127
|
+
await sendBirthdayCard(text, image, rsvps, email);
|
|
128
|
+
|
|
129
|
+
return { text, image, status: "Sent" };
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## How it works
|
|
134
|
+
|
|
135
|
+
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()`.
|
|
136
|
+
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. Failures propagate — if any promise rejects, the whole `Promise.all` rejects.
|
|
137
|
+
3. **`Promise.race` resolves on the first settle.** The losing promises keep running in the background but their results are discarded by the workflow.
|
|
138
|
+
4. **All primitives are promises.** `sleep("1 day")` and `createWebhook()` return promises, so they compose with `Promise.all` / `Promise.race` exactly like steps do — this is what makes patterns like "race a webhook against a 24-hour deadline" a one-liner.
|
|
139
|
+
|
|
140
|
+
## Adapting to your use case
|
|
141
|
+
|
|
142
|
+
- **Replace `Promise.all` with `Promise.allSettled`** when partial failures should not abort the rest. You'll get an array of `{ status, value | reason }` instead of throwing on the first rejection.
|
|
143
|
+
- **Bound the parallelism** — `Promise.all` over 1000 items will fan out 1000 concurrent steps. If your downstream APIs can't handle that, batch the array into chunks (see [Batching](/cookbook/common-patterns/batching)).
|
|
144
|
+
- **Add a deadline to any race** — pair the operation with `sleep("30s").then(() => "timeout" as const)` and check the discriminated result. See [Timeouts](/cookbook/common-patterns/timeouts).
|
|
145
|
+
- **Mix steps and hooks in a race** — wait for an external signal *or* a deadline *or* a step result, all in the same `Promise.race`. The first one to resolve wins.
|
|
146
|
+
|
|
147
|
+
## Key APIs
|
|
148
|
+
|
|
149
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
|
|
150
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions with full Node.js access
|
|
151
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep) — durable sleep that survives restarts
|
|
152
|
+
- [`createWebhook()`](/docs/api-reference/workflow/create-webhook) — webhook URL the workflow can race against
|
|
153
|
+
- [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) — wait for all promises
|
|
154
|
+
- [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — wait for the first to settle
|
|
155
|
+
- [`Promise.allSettled()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) — wait for all, including failures
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Timeouts
|
|
3
|
+
description: Add deadlines to slow operations by racing them against a durable sleep.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Use `Promise.race` with `sleep()` to bound the time any step, hook, or webhook is allowed to take — and recover gracefully when the deadline fires first.
|
|
6
|
+
related:
|
|
7
|
+
- /docs/api-reference/workflow/sleep
|
|
8
|
+
- /docs/foundations/hooks
|
|
9
|
+
- /cookbook/common-patterns/scheduling
|
|
10
|
+
- /cookbook/common-patterns/webhooks
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
A common requirement is bounding how long a workflow waits for something to finish — a slow step, an external webhook, a human approval. Race the operation against a durable `sleep()` with `Promise.race()` — whichever finishes first wins, and the loser keeps running but its result is ignored.
|
|
14
|
+
|
|
15
|
+
## When to use this
|
|
16
|
+
|
|
17
|
+
- **Slow steps** — bound the time spent waiting on third-party APIs, model calls, or expensive computation
|
|
18
|
+
- **External callbacks** — give webhooks a deadline so the workflow doesn't hang forever waiting for an event that may never arrive
|
|
19
|
+
- **Human approvals** — auto-decline or escalate when a hook isn't resumed within a window
|
|
20
|
+
- **Polling loops** — give an outer poll-until-ready loop an overall budget
|
|
21
|
+
|
|
22
|
+
## Pattern
|
|
23
|
+
|
|
24
|
+
### Timeout on a slow step
|
|
25
|
+
|
|
26
|
+
```typescript lineNumbers
|
|
27
|
+
import { sleep } from "workflow";
|
|
28
|
+
|
|
29
|
+
declare function processData(data: string): Promise<string>; // @setup
|
|
30
|
+
|
|
31
|
+
export async function processWithTimeout(data: string) {
|
|
32
|
+
"use workflow";
|
|
33
|
+
|
|
34
|
+
const result = await Promise.race([ // [!code highlight]
|
|
35
|
+
processData(data), // [!code highlight]
|
|
36
|
+
sleep("30s").then(() => "timeout" as const), // [!code highlight]
|
|
37
|
+
]); // [!code highlight]
|
|
38
|
+
|
|
39
|
+
if (result === "timeout") {
|
|
40
|
+
throw new Error("Processing timed out after 30 seconds");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Timeout on a webhook
|
|
48
|
+
|
|
49
|
+
The same pattern works for any promise — including hooks and webhooks. Here a webhook waits for an external service to call back, with a hard deadline of 7 days:
|
|
50
|
+
|
|
51
|
+
```typescript lineNumbers
|
|
52
|
+
import { sleep, createWebhook } from "workflow";
|
|
53
|
+
|
|
54
|
+
declare function sendApprovalRequest(requestId: string, webhookUrl: string): Promise<void>; // @setup
|
|
55
|
+
|
|
56
|
+
export async function waitForApproval(requestId: string) {
|
|
57
|
+
"use workflow";
|
|
58
|
+
|
|
59
|
+
const webhook = createWebhook<{ approved: boolean }>();
|
|
60
|
+
await sendApprovalRequest(requestId, webhook.url);
|
|
61
|
+
|
|
62
|
+
const result = await Promise.race([ // [!code highlight]
|
|
63
|
+
webhook.then((req) => req.json()), // [!code highlight]
|
|
64
|
+
sleep("7 days").then(() => ({ timedOut: true }) as const), // [!code highlight]
|
|
65
|
+
]); // [!code highlight]
|
|
66
|
+
|
|
67
|
+
if ("timedOut" in result) {
|
|
68
|
+
throw new Error("Approval request expired after 7 days");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return result.approved;
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## How it works
|
|
76
|
+
|
|
77
|
+
1. **Durable sleep** — `sleep("30s")` persists through restarts at zero compute cost. The workflow resumes precisely when the timer fires.
|
|
78
|
+
2. **Race** — `Promise.race([work, sleep(...)])` returns the value of whichever promise resolves first. The loser keeps running in the background but its result is ignored by the workflow.
|
|
79
|
+
3. **Discriminated result** — tagging the sleep branch with a sentinel value (`"timeout" as const`, `{ timedOut: true }`) lets TypeScript narrow the result and pick the right branch.
|
|
80
|
+
4. **Throw to fail the workflow** — inside a workflow function, throwing an `Error` exits the run with that error. Use `FatalError` inside steps; throw plain errors inside workflows.
|
|
81
|
+
|
|
82
|
+
<Callout type="warn">
|
|
83
|
+
**The losing operation keeps running.** `Promise.race` doesn't cancel — when the sleep wins, the underlying step (or model call, or HTTP request) continues to completion in the background. This is fine for idempotent reads but matters when the operation has side effects or costs money. For hard cancellation across processes, see [Distributed Abort Controller](/cookbook/advanced/distributed-abort-controller).
|
|
84
|
+
</Callout>
|
|
85
|
+
|
|
86
|
+
## Adapting to your use case
|
|
87
|
+
|
|
88
|
+
- **Different durations** — `sleep()` accepts duration strings (`"30s"`, `"5m"`, `"7 days"`), milliseconds, or `Date` objects for absolute deadlines.
|
|
89
|
+
- **Soft timeout (retry)** — instead of throwing, loop and retry with a fresh `Promise.race` and a backoff.
|
|
90
|
+
- **Soft timeout (fallback)** — return a default value when the timer wins instead of throwing: `if (result === "timeout") return cachedFallback`.
|
|
91
|
+
- **Combine with cancellation** — race three promises: the operation, a deadline `sleep()`, and a cancellation hook. See the [Scheduling cookbook](/cookbook/common-patterns/scheduling) for the cancellation half of this pattern.
|
|
92
|
+
- **Per-step deadlines** — wrap each step in its own `Promise.race` for independent budgets, or use a single outer race for an overall workflow deadline.
|
|
93
|
+
|
|
94
|
+
## Key APIs
|
|
95
|
+
|
|
96
|
+
- [`sleep()`](/docs/api-reference/workflow/sleep) — durable wait (survives restarts, zero compute cost)
|
|
97
|
+
- [`createWebhook()`](/docs/api-reference/workflow/create-webhook) — create a webhook URL the workflow can race against
|
|
98
|
+
- [`defineHook()`](/docs/api-reference/workflow/define-hook) — typed hook for in-process cancellation
|
|
99
|
+
- [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — race operations against deadlines
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Workflow Composition
|
|
3
|
+
description: Call workflows from other workflows by direct await (flatten into the parent) or background spawn via start() (separate run).
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Compose workflows two ways — direct await flattens the child into the parent's event log, while background spawn via start() runs the child as an independent run.
|
|
6
|
+
related:
|
|
7
|
+
- /cookbook/advanced/child-workflows
|
|
8
|
+
- /docs/api-reference/workflow-api/start
|
|
9
|
+
- /docs/api-reference/workflow-api/get-run
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or wants to fire the child off as an independent run (background spawn). For massive fan-out with polling and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
|
|
13
|
+
|
|
14
|
+
## When to use this
|
|
15
|
+
|
|
16
|
+
- **Direct await** — the parent needs the child's result before continuing, and you want a single unified event log
|
|
17
|
+
- **Background spawn** — the parent doesn't need to wait, and you want the child to be observable as a separate run with its own `runId`
|
|
18
|
+
|
|
19
|
+
## Pattern
|
|
20
|
+
|
|
21
|
+
### Direct await (flattening)
|
|
22
|
+
|
|
23
|
+
Call a child workflow with `await` and the child's steps execute inline within the parent — they appear in the parent's event log as if you'd called them directly.
|
|
24
|
+
|
|
25
|
+
```typescript lineNumbers
|
|
26
|
+
declare function sendEmail(userId: string): Promise<void>; // @setup
|
|
27
|
+
declare function sendPushNotification(userId: string): Promise<void>; // @setup
|
|
28
|
+
declare function createAccount(userId: string): Promise<void>; // @setup
|
|
29
|
+
declare function setupPreferences(userId: string): Promise<void>; // @setup
|
|
30
|
+
|
|
31
|
+
// Child workflow
|
|
32
|
+
export async function sendNotifications(userId: string) {
|
|
33
|
+
"use workflow";
|
|
34
|
+
|
|
35
|
+
await sendEmail(userId);
|
|
36
|
+
await sendPushNotification(userId);
|
|
37
|
+
return { notified: true };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Parent workflow calls the child directly
|
|
41
|
+
export async function onboardUser(userId: string) {
|
|
42
|
+
"use workflow";
|
|
43
|
+
|
|
44
|
+
await createAccount(userId);
|
|
45
|
+
await sendNotifications(userId); // [!code highlight]
|
|
46
|
+
await setupPreferences(userId);
|
|
47
|
+
|
|
48
|
+
return { userId, status: "onboarded" };
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The parent waits for the child to finish before continuing. Both functions share a single workflow run, a single retry boundary, and a single event log.
|
|
53
|
+
|
|
54
|
+
### Background spawn via `start()`
|
|
55
|
+
|
|
56
|
+
To run a child workflow independently without blocking the parent, call [`start()`](/docs/api-reference/workflow-api/start) from a step. This launches the child as a separate workflow run with its own `runId`.
|
|
57
|
+
|
|
58
|
+
```typescript lineNumbers
|
|
59
|
+
import { start } from "workflow/api";
|
|
60
|
+
|
|
61
|
+
declare function generateReport(reportId: string): Promise<void>; // @setup
|
|
62
|
+
declare function fulfillOrder(orderId: string): Promise<{ id: string }>; // @setup
|
|
63
|
+
declare function sendConfirmation(orderId: string): Promise<void>; // @setup
|
|
64
|
+
|
|
65
|
+
async function triggerReportGeneration(reportId: string) {
|
|
66
|
+
"use step"; // [!code highlight]
|
|
67
|
+
|
|
68
|
+
const run = await start(generateReport, [reportId]); // [!code highlight]
|
|
69
|
+
return run.runId;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function processOrder(orderId: string) {
|
|
73
|
+
"use workflow";
|
|
74
|
+
|
|
75
|
+
const order = await fulfillOrder(orderId);
|
|
76
|
+
|
|
77
|
+
const reportRunId = await triggerReportGeneration(orderId); // [!code highlight]
|
|
78
|
+
|
|
79
|
+
await sendConfirmation(orderId);
|
|
80
|
+
|
|
81
|
+
return { orderId, reportRunId };
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The parent continues immediately after `start()` returns. The child runs independently and can be monitored separately using the returned `runId` (e.g., via [`getRun()`](/docs/api-reference/workflow-api/get-run)).
|
|
86
|
+
|
|
87
|
+
<Callout type="info">
|
|
88
|
+
If you want the child workflow to run on the latest deployment rather than the current one, pass [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest) in the `start()` options. This is currently a Vercel-specific feature. Be aware that the child workflow's function name, file path, argument types, and return type must remain compatible across deployments — renaming the function or changing its location will change the workflow ID, and modifying expected inputs or outputs can cause serialization failures.
|
|
89
|
+
</Callout>
|
|
90
|
+
|
|
91
|
+
## How it works
|
|
92
|
+
|
|
93
|
+
1. **Direct await flattens.** When a workflow function awaits another workflow function, the child's `"use workflow"` directive is treated as inline — the child's steps emit into the parent's event log and share the parent's run ID.
|
|
94
|
+
2. **`start()` mints a new run.** The child gets its own `runId`, its own event log, and its own retry boundary. The parent only sees the `runId` returned by `start()`.
|
|
95
|
+
3. **`start()` must be called from a step.** Calling `start()` directly from a workflow function is not allowed — wrap it in a `"use step"` function. This keeps the spawn deterministic across replays.
|
|
96
|
+
|
|
97
|
+
## Choosing between the two modes
|
|
98
|
+
|
|
99
|
+
| | Direct await | Background spawn (`start()`) |
|
|
100
|
+
| --- | --- | --- |
|
|
101
|
+
| Parent waits for child | Yes | No |
|
|
102
|
+
| Has its own `runId` | No (shares parent's) | Yes |
|
|
103
|
+
| Has its own event log | No | Yes |
|
|
104
|
+
| Has its own retry boundary | No | Yes |
|
|
105
|
+
| Best for | Sequential composition, helper workflows | Independent work, fire-and-forget, fan-out |
|
|
106
|
+
|
|
107
|
+
## Adapting to your use case
|
|
108
|
+
|
|
109
|
+
- **Spawn many children at once** — call `start()` in a loop inside a step. For more advanced fan-out (chunking, polling, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
|
|
110
|
+
- **Wait for a background child to finish** — combine `start()` with `getRun()` polling. The [Child Workflows](/cookbook/advanced/child-workflows) page covers the full polling loop.
|
|
111
|
+
- **Pass results back from background children** — the spawn step returns the `runId`; later, a poll step uses `getRun(runId).returnValue` to fetch the final result.
|
|
112
|
+
|
|
113
|
+
## Key APIs
|
|
114
|
+
|
|
115
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
|
|
116
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions with full Node.js access
|
|
117
|
+
- [`start()`](/docs/api-reference/workflow-api/start) — spawn a child workflow as a separate run
|
|
118
|
+
- [`getRun()`](/docs/api-reference/workflow-api/get-run) — retrieve a workflow run's status and return value
|
package/docs/cookbook/index.mdx
CHANGED
|
@@ -6,36 +6,33 @@ type: overview
|
|
|
6
6
|
|
|
7
7
|
A curated collection of workflow patterns with clean, copy-paste code examples for real use cases.
|
|
8
8
|
|
|
9
|
+
## Agent Patterns
|
|
10
|
+
|
|
11
|
+
- [**Durable Agent**](/cookbook/agent-patterns/durable-agent) — Replace a stateless AI agent with one that survives crashes and retries tool calls
|
|
12
|
+
- [**Human-in-the-Loop**](/cookbook/agent-patterns/human-in-the-loop) — Pause an agent for human approval, then resume based on the decision
|
|
13
|
+
- [**Agent Cancellation**](/cookbook/agent-patterns/agent-cancellation) — Stop a running agent immediately via `run.cancel()` or gracefully via a hook + `Promise.race`
|
|
14
|
+
|
|
9
15
|
## Common Patterns
|
|
10
16
|
|
|
17
|
+
- [**Sequential & Parallel Execution**](/cookbook/common-patterns/sequential-and-parallel) — Compose steps with `await`, `Promise.all`, and `Promise.race` against durable sleeps and webhooks
|
|
18
|
+
- [**Workflow Composition**](/cookbook/common-patterns/workflow-composition) — Call workflows from other workflows by direct await or background spawn via `start()`
|
|
11
19
|
- [**Saga**](/cookbook/common-patterns/saga) — Coordinate multi-step transactions with automatic rollback when a step fails
|
|
12
20
|
- [**Batching**](/cookbook/common-patterns/batching) — Process large collections in parallel batches with failure isolation
|
|
13
21
|
- [**Rate Limiting**](/cookbook/common-patterns/rate-limiting) — Handle 429 responses and transient failures with RetryableError and backoff
|
|
14
|
-
- [**Fan-Out**](/cookbook/common-patterns/fan-out) — Send to multiple channels in parallel with independent failure handling
|
|
15
22
|
- [**Scheduling**](/cookbook/common-patterns/scheduling) — Use durable sleep to schedule actions minutes, hours, or weeks ahead
|
|
23
|
+
- [**Timeouts**](/cookbook/common-patterns/timeouts) — Add deadlines to slow steps, hooks, and webhooks by racing them against a durable sleep
|
|
16
24
|
- [**Idempotency**](/cookbook/common-patterns/idempotency) — Ensure side effects happen exactly once, even when steps retry
|
|
17
25
|
- [**Webhooks**](/cookbook/common-patterns/webhooks) — Receive HTTP callbacks from external services and process them durably
|
|
18
|
-
- [**Conditional Routing**](/cookbook/common-patterns/content-router) — Route payloads to different step handlers based on content
|
|
19
|
-
- [**Child Workflows**](/cookbook/common-patterns/child-workflows) — Spawn and orchestrate child workflows from a parent
|
|
20
|
-
|
|
21
|
-
## Agent Patterns
|
|
22
|
-
|
|
23
|
-
- [**Durable Agent**](/cookbook/agent-patterns/durable-agent) — Replace a stateless AI agent with one that survives crashes and retries tool calls
|
|
24
|
-
- [**Tool Streaming**](/cookbook/agent-patterns/tool-streaming) — Stream real-time progress updates from tools to the UI
|
|
25
|
-
- [**Human-in-the-Loop**](/cookbook/agent-patterns/human-in-the-loop) — Pause an agent for human approval, then resume based on the decision
|
|
26
|
-
- [**Tool Orchestration**](/cookbook/agent-patterns/tool-orchestration) — Choose between step-level and workflow-level tools, or combine both
|
|
27
|
-
- [**Stop Workflow**](/cookbook/agent-patterns/stop-workflow) — Gracefully cancel a running agent workflow using a hook signal
|
|
28
26
|
|
|
29
27
|
## Integrations
|
|
30
28
|
|
|
31
|
-
- [**AI SDK**](/cookbook/integrations/ai-sdk) — Use
|
|
29
|
+
- [**AI SDK**](/cookbook/integrations/ai-sdk) — Use streamText() directly inside a workflow for lower-level control over model calls and tool execution
|
|
32
30
|
- [**Chat SDK**](/cookbook/integrations/chat-sdk) — Build durable chat sessions with workflow persistence and AI SDK chat primitives
|
|
33
31
|
- [**Sandbox**](/cookbook/integrations/sandbox) — Orchestrate Vercel Sandbox lifecycle inside durable workflows
|
|
34
32
|
|
|
35
33
|
## Advanced
|
|
36
34
|
|
|
37
|
-
- [**
|
|
38
|
-
- [**
|
|
39
|
-
- [**
|
|
40
|
-
- [**Custom Serialization**](/cookbook/advanced/custom-serialization) — Make custom classes survive workflow serialization
|
|
35
|
+
- [**Child Workflows**](/cookbook/advanced/child-workflows) — Spawn and orchestrate child workflows from a parent
|
|
36
|
+
- [**Distributed Abort Controller**](/cookbook/advanced/distributed-abort-controller) — Build a cross-process abort controller using workflow streams and hooks
|
|
37
|
+
- [**Serializable Steps**](/cookbook/advanced/serializable-steps) — Wrap non-serializable third-party objects so they cross the workflow boundary
|
|
41
38
|
- [**Publishing Libraries**](/cookbook/advanced/publishing-libraries) — Ship npm packages that export reusable workflow functions
|