workflow 5.0.0-beta.1 → 5.0.0-beta.3

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 (72) hide show
  1. package/README.md +4 -4
  2. package/dist/api-workflow.d.ts +1 -1
  3. package/dist/api-workflow.d.ts.map +1 -1
  4. package/dist/api-workflow.js +2 -2
  5. package/dist/api.js +1 -1
  6. package/dist/astro.js +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/internal/builtins.js +1 -1
  9. package/dist/internal/class-serialization.js +1 -1
  10. package/dist/internal/errors.js +1 -1
  11. package/dist/nest.js +1 -1
  12. package/dist/next.cjs +1 -1
  13. package/dist/nitro.js +1 -1
  14. package/dist/nuxt.js +1 -1
  15. package/dist/observability.js +1 -1
  16. package/dist/runtime.js +1 -1
  17. package/dist/stdlib.js +1 -1
  18. package/dist/sveltekit.js +1 -1
  19. package/dist/typescript-plugin.cjs +1 -1
  20. package/dist/vite.js +1 -1
  21. package/dist/workflow.js +1 -1
  22. package/docs/ai/resumable-streams.mdx +1 -1
  23. package/docs/api-reference/workflow/create-webhook.mdx +37 -18
  24. package/docs/api-reference/workflow/get-workflow-metadata.mdx +34 -0
  25. package/docs/api-reference/workflow-ai/durable-agent.mdx +0 -4
  26. package/docs/api-reference/workflow-ai/index.mdx +0 -5
  27. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +0 -4
  28. package/docs/cookbook/advanced/child-workflows.mdx +372 -0
  29. package/docs/cookbook/advanced/distributed-abort-controller.mdx +318 -0
  30. package/docs/cookbook/advanced/meta.json +9 -0
  31. package/docs/cookbook/advanced/publishing-libraries.mdx +336 -0
  32. package/docs/cookbook/advanced/serializable-steps.mdx +147 -0
  33. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +205 -0
  34. package/docs/cookbook/agent-patterns/durable-agent.mdx +150 -0
  35. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +255 -0
  36. package/docs/cookbook/agent-patterns/meta.json +4 -0
  37. package/docs/cookbook/common-patterns/batching.mdx +105 -0
  38. package/docs/cookbook/common-patterns/idempotency.mdx +107 -0
  39. package/docs/cookbook/common-patterns/meta.json +15 -0
  40. package/docs/cookbook/common-patterns/rate-limiting.mdx +228 -0
  41. package/docs/cookbook/common-patterns/saga.mdx +247 -0
  42. package/docs/cookbook/common-patterns/scheduling.mdx +125 -0
  43. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
  44. package/docs/cookbook/common-patterns/timeouts.mdx +99 -0
  45. package/docs/cookbook/common-patterns/webhooks.mdx +185 -0
  46. package/docs/cookbook/common-patterns/workflow-composition.mdx +118 -0
  47. package/docs/cookbook/index.mdx +38 -0
  48. package/docs/cookbook/integrations/ai-sdk.mdx +360 -0
  49. package/docs/cookbook/integrations/chat-sdk.mdx +303 -0
  50. package/docs/cookbook/integrations/meta.json +4 -0
  51. package/docs/cookbook/integrations/sandbox.mdx +516 -0
  52. package/docs/cookbook/meta.json +5 -0
  53. package/docs/deploying/world/local-world.mdx +1 -1
  54. package/docs/deploying/world/postgres-world.mdx +1 -1
  55. package/docs/deploying/world/vercel-world.mdx +1 -1
  56. package/docs/errors/start-invalid-workflow-function.mdx +1 -1
  57. package/docs/foundations/index.mdx +0 -3
  58. package/docs/foundations/meta.json +0 -1
  59. package/docs/foundations/serialization.mdx +1 -1
  60. package/docs/foundations/starting-workflows.mdx +1 -1
  61. package/docs/getting-started/index.mdx +8 -1
  62. package/docs/getting-started/meta.json +2 -1
  63. package/docs/getting-started/python.mdx +165 -0
  64. package/docs/meta.json +1 -0
  65. package/docs/migration-guides/index.mdx +34 -0
  66. package/docs/migration-guides/meta.json +9 -0
  67. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +363 -0
  68. package/docs/migration-guides/migrating-from-inngest.mdx +314 -0
  69. package/docs/migration-guides/migrating-from-temporal.mdx +318 -0
  70. package/docs/migration-guides/migrating-from-trigger-dev.mdx +337 -0
  71. package/package.json +13 -13
  72. package/docs/foundations/common-patterns.mdx +0 -265
@@ -0,0 +1,185 @@
1
+ ---
2
+ title: Webhooks & External Callbacks
3
+ description: Receive HTTP callbacks from external services, process them durably, and respond inline.
4
+ type: guide
5
+ summary: Create webhook endpoints that your workflow can await, process incoming requests in steps, and respond to the caller — all within durable workflow context.
6
+ ---
7
+
8
+ Use webhooks when external services push events to your application via HTTP callbacks. The workflow creates a webhook URL, suspends with zero compute cost, and resumes when a request arrives.
9
+
10
+ ## When to use this
11
+
12
+ - Accepting callbacks from payment processors (Stripe, PayPal)
13
+ - Waiting for third-party verification or processing results
14
+ - Any integration where an external system calls you back asynchronously
15
+
16
+ ## Pattern: Processing webhook events
17
+
18
+ Create a webhook with manual response control, then iterate over incoming requests:
19
+
20
+ ```typescript
21
+ import { createWebhook, type RequestWithResponse } from "workflow";
22
+
23
+ declare function processEvent(request: RequestWithResponse): Promise<{ type: string }>; // @setup
24
+
25
+ export async function paymentWebhook(orderId: string) {
26
+ "use workflow";
27
+
28
+ const webhook = createWebhook({ respondWith: "manual" }); // [!code highlight]
29
+ // webhook.url is the URL to give to the external service
30
+
31
+ const ledger: { type: string }[] = [];
32
+
33
+ for await (const request of webhook) { // [!code highlight]
34
+ const entry = await processEvent(request);
35
+ ledger.push(entry);
36
+
37
+ // Break when we've received a terminal event
38
+ if (entry.type === "payment.succeeded" || entry.type === "refund.created") {
39
+ break;
40
+ }
41
+ }
42
+
43
+ return { orderId, webhookUrl: webhook.url, ledger, status: "settled" };
44
+ }
45
+ ```
46
+
47
+ ### Step function for processing
48
+
49
+ Each webhook request is processed in its own step, giving you full Node.js access for validation, database writes, and responding to the caller:
50
+
51
+ ```typescript
52
+ import { type RequestWithResponse } from "workflow";
53
+
54
+ async function processEvent(
55
+ request: RequestWithResponse
56
+ ): Promise<{ type: string }> {
57
+ "use step";
58
+
59
+ const body = await request.json().catch(() => ({}));
60
+ const type = body?.type ?? "unknown";
61
+
62
+ // Validate, process, and respond inline
63
+ if (type === "payment.succeeded") {
64
+ // Record the payment in your database
65
+ await request.respondWith(Response.json({ ack: true, action: "captured" })); // [!code highlight]
66
+ } else if (type === "payment.failed") {
67
+ await request.respondWith(Response.json({ ack: true, action: "flagged" }));
68
+ } else {
69
+ await request.respondWith(Response.json({ ack: true, action: "ignored" }));
70
+ }
71
+
72
+ return { type };
73
+ }
74
+ ```
75
+
76
+ ## Pattern: Async request-reply with timeout
77
+
78
+ Submit a request to an external service, pass it your webhook URL, then race the callback against a deadline:
79
+
80
+ ```typescript
81
+ import { createWebhook, sleep, FatalError, type RequestWithResponse } from "workflow";
82
+
83
+ export async function asyncVerification(documentId: string) {
84
+ "use workflow";
85
+
86
+ const webhook = createWebhook({ respondWith: "manual" });
87
+
88
+ // Submit to vendor, passing our webhook URL for the callback
89
+ await submitToVendor(documentId, webhook.url);
90
+
91
+ // Race: wait for callback OR timeout after 30 seconds
92
+ const result = await Promise.race([ // [!code highlight]
93
+ (async () => {
94
+ for await (const request of webhook) {
95
+ const body = await processCallback(request);
96
+ return body;
97
+ }
98
+ throw new FatalError("Webhook closed without callback");
99
+ })(),
100
+ sleep("30s").then(() => ({ status: "timed_out" as const })), // [!code highlight]
101
+ ]);
102
+
103
+ return { documentId, ...result };
104
+ }
105
+
106
+ async function submitToVendor(documentId: string, callbackUrl: string): Promise<void> {
107
+ "use step";
108
+ await fetch("https://vendor.example.com/verify", {
109
+ method: "POST",
110
+ body: JSON.stringify({ documentId, callbackUrl }),
111
+ });
112
+ }
113
+
114
+ async function processCallback(
115
+ request: RequestWithResponse
116
+ ): Promise<{ status: string; details: string }> {
117
+ "use step";
118
+ const body = await request.json();
119
+ await request.respondWith(Response.json({ ack: true }));
120
+ return {
121
+ status: body.approved ? "verified" : "rejected",
122
+ details: body.details ?? body.reason ?? "",
123
+ };
124
+ }
125
+ ```
126
+
127
+ ## Pattern: Large payload by reference
128
+
129
+ When payloads are too large to serialize into the event log, pass a lightweight reference (a "claim check") instead. Use a hook to signal when the data is ready:
130
+
131
+ ```typescript
132
+ import { defineHook } from "workflow";
133
+
134
+ export const blobReady = defineHook<{ blobToken: string }>(); // [!code highlight]
135
+
136
+ export async function importLargeFile(importId: string) {
137
+ "use workflow";
138
+
139
+ // Suspend until the external system signals the blob is uploaded
140
+ const { blobToken } = await blobReady.create({ token: `upload:${importId}` }); // [!code highlight]
141
+
142
+ // Process by reference -- the full payload never enters the event log
143
+ await processBlob(blobToken);
144
+
145
+ return { importId, blobToken, status: "indexed" };
146
+ }
147
+
148
+ async function processBlob(blobToken: string): Promise<void> {
149
+ "use step";
150
+ // Fetch the blob using the token, process it
151
+ const res = await fetch(`https://storage.example.com/blobs/${blobToken}`);
152
+ const data = await res.arrayBuffer();
153
+ // Index, transform, or store the data
154
+ }
155
+ ```
156
+
157
+ Resume from an API route when the upload completes:
158
+
159
+ ```typescript
160
+ import { resumeHook } from "workflow/api";
161
+
162
+ // POST /api/upload-complete
163
+ export async function POST(request: Request) {
164
+ const { importId, blobToken } = await request.json();
165
+ await resumeHook(`upload:${importId}`, { blobToken }); // [!code highlight]
166
+ return Response.json({ ok: true });
167
+ }
168
+ ```
169
+
170
+ ## Tips
171
+
172
+ - **`respondWith: "manual"`** gives you control over the HTTP response from inside a step. Use this when you need to validate the request before responding.
173
+ - **`for await` on a webhook** lets you process multiple events from the same URL. Use `break` to stop listening after a terminal event.
174
+ - **Webhooks auto-generate URLs** at `/.well-known/workflow/v1/webhook/:token`. Pass this URL to external services.
175
+ - **Race webhooks against `sleep()`** for deadlines. If the callback doesn't arrive in time, the workflow can take a fallback action.
176
+ - **For large payloads**, use a hook + reference token instead of passing the data through the workflow. The event log serializes all step inputs/outputs, so large payloads hurt performance.
177
+
178
+ ## Key APIs
179
+
180
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps) -- marks the orchestrator function
181
+ - [`"use step"`](/docs/foundations/workflows-and-steps) -- marks functions with full Node.js access
182
+ - [`createWebhook()`](/docs/api-reference/workflow/create-webhook) -- creates an HTTP endpoint the workflow can await
183
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook) -- creates a typed hook for signal-based patterns
184
+ - [`sleep()`](/docs/api-reference/workflow/sleep) -- durable timer for deadlines
185
+ - [`FatalError`](/docs/api-reference/workflow/fatal-error) -- prevents retry on permanent failures
@@ -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
@@ -0,0 +1,38 @@
1
+ ---
2
+ title: Cookbook
3
+ description: Best-practice workflow patterns with copy-paste code examples.
4
+ type: overview
5
+ ---
6
+
7
+ A curated collection of workflow patterns with clean, copy-paste code examples for real use cases.
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
+
15
+ ## Common Patterns
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()`
19
+ - [**Saga**](/cookbook/common-patterns/saga) — Coordinate multi-step transactions with automatic rollback when a step fails
20
+ - [**Batching**](/cookbook/common-patterns/batching) — Process large collections in parallel batches with failure isolation
21
+ - [**Rate Limiting**](/cookbook/common-patterns/rate-limiting) — Handle 429 responses and transient failures with RetryableError and backoff
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
24
+ - [**Idempotency**](/cookbook/common-patterns/idempotency) — Ensure side effects happen exactly once, even when steps retry
25
+ - [**Webhooks**](/cookbook/common-patterns/webhooks) — Receive HTTP callbacks from external services and process them durably
26
+
27
+ ## Integrations
28
+
29
+ - [**AI SDK**](/cookbook/integrations/ai-sdk) — Use streamText() directly inside a workflow for lower-level control over model calls and tool execution
30
+ - [**Chat SDK**](/cookbook/integrations/chat-sdk) — Build durable chat sessions with workflow persistence and AI SDK chat primitives
31
+ - [**Sandbox**](/cookbook/integrations/sandbox) — Orchestrate Vercel Sandbox lifecycle inside durable workflows
32
+
33
+ ## Advanced
34
+
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
38
+ - [**Publishing Libraries**](/cookbook/advanced/publishing-libraries) — Ship npm packages that export reusable workflow functions