workflow 5.0.0-beta.2 → 5.0.0-beta.20

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 (169) hide show
  1. package/dist/api-workflow.d.ts +1 -1
  2. package/dist/api-workflow.d.ts.map +1 -1
  3. package/dist/api-workflow.js +2 -2
  4. package/dist/api.d.ts +5 -1
  5. package/dist/api.d.ts.map +1 -1
  6. package/dist/api.js +14 -2
  7. package/dist/internal/builtins.d.ts +17 -0
  8. package/dist/internal/builtins.d.ts.map +1 -1
  9. package/dist/internal/builtins.js +65 -1
  10. package/dist/observability.d.ts +1 -1
  11. package/dist/observability.js +2 -2
  12. package/dist/runtime.d.ts +1 -1
  13. package/dist/runtime.d.ts.map +1 -1
  14. package/dist/runtime.js +2 -2
  15. package/docs/ai/index.mdx +27 -23
  16. package/docs/api-reference/index.mdx +24 -0
  17. package/docs/api-reference/meta.json +8 -0
  18. package/docs/api-reference/vitest/index.mdx +28 -7
  19. package/docs/api-reference/workflow/create-hook.mdx +38 -0
  20. package/docs/api-reference/workflow/create-webhook.mdx +1 -0
  21. package/docs/api-reference/workflow/experimental-set-attributes.mdx +65 -0
  22. package/docs/api-reference/workflow/fetch.mdx +5 -0
  23. package/docs/api-reference/workflow/index.mdx +3 -0
  24. package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
  25. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +7 -0
  26. package/docs/api-reference/workflow-api/get-run.mdx +6 -0
  27. package/docs/api-reference/workflow-api/index.mdx +6 -8
  28. package/docs/api-reference/workflow-api/resume-hook.mdx +57 -0
  29. package/docs/api-reference/workflow-api/start.mdx +13 -5
  30. package/docs/api-reference/workflow-astro/index.mdx +18 -0
  31. package/docs/api-reference/workflow-astro/meta.json +4 -0
  32. package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
  33. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
  34. package/docs/api-reference/workflow-errors/index.mdx +85 -0
  35. package/docs/api-reference/workflow-errors/meta.json +5 -0
  36. package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
  37. package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
  38. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
  39. package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
  40. package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
  41. package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
  42. package/docs/api-reference/workflow-nest/index.mdx +31 -0
  43. package/docs/api-reference/workflow-nest/meta.json +9 -0
  44. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
  45. package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
  46. package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
  47. package/docs/api-reference/workflow-next/with-workflow.mdx +34 -2
  48. package/docs/api-reference/workflow-nitro/index.mdx +59 -0
  49. package/docs/api-reference/workflow-nuxt/index.mdx +47 -0
  50. package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
  51. package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
  52. package/docs/api-reference/workflow-observability/index.mdx +64 -0
  53. package/docs/api-reference/workflow-observability/meta.json +11 -0
  54. package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
  55. package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
  56. package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
  57. package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
  58. package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
  59. package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
  60. package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +7 -10
  61. package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
  62. package/docs/api-reference/workflow-runtime/index.mdx +43 -0
  63. package/docs/api-reference/workflow-runtime/meta.json +12 -0
  64. package/docs/api-reference/workflow-runtime/set-world.mdx +49 -0
  65. package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +42 -0
  66. package/docs/api-reference/{workflow-api → workflow-runtime}/world/index.mdx +5 -8
  67. package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
  68. package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +2 -2
  69. package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +11 -4
  70. package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +2 -2
  71. package/docs/api-reference/workflow-serde/index.mdx +0 -1
  72. package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +1 -2
  73. package/docs/api-reference/workflow-serde/workflow-serialize.mdx +1 -2
  74. package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
  75. package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
  76. package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
  77. package/docs/api-reference/workflow-vite/index.mdx +18 -0
  78. package/docs/api-reference/workflow-vite/meta.json +4 -0
  79. package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
  80. package/docs/changelog/attributes-mvp.mdx +380 -0
  81. package/docs/changelog/eager-processing.mdx +269 -0
  82. package/docs/changelog/index.mdx +2 -1
  83. package/docs/changelog/lazy-event-creation.md +127 -0
  84. package/docs/changelog/meta.json +6 -1
  85. package/docs/changelog/resilient-start.mdx +31 -283
  86. package/docs/cookbook/advanced/child-workflows.mdx +315 -0
  87. package/docs/cookbook/advanced/meta.json +2 -3
  88. package/docs/cookbook/advanced/publishing-libraries.mdx +87 -29
  89. package/docs/cookbook/advanced/serializable-steps.mdx +17 -5
  90. package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
  91. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +156 -0
  92. package/docs/cookbook/agent-patterns/durable-agent.mdx +11 -184
  93. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +150 -173
  94. package/docs/cookbook/agent-patterns/meta.json +1 -7
  95. package/docs/cookbook/common-patterns/batching.mdx +44 -118
  96. package/docs/cookbook/common-patterns/idempotency.mdx +36 -52
  97. package/docs/cookbook/common-patterns/meta.json +4 -4
  98. package/docs/cookbook/common-patterns/rate-limiting.mdx +1 -1
  99. package/docs/cookbook/common-patterns/saga.mdx +128 -33
  100. package/docs/cookbook/common-patterns/scheduling.mdx +77 -193
  101. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
  102. package/docs/cookbook/common-patterns/timeouts.mdx +100 -0
  103. package/docs/cookbook/common-patterns/workflow-composition.mdx +117 -0
  104. package/docs/cookbook/index.mdx +14 -17
  105. package/docs/cookbook/integrations/ai-sdk.mdx +330 -142
  106. package/docs/cookbook/integrations/chat-sdk.mdx +264 -151
  107. package/docs/cookbook/integrations/sandbox.mdx +482 -81
  108. package/docs/cookbook/meta.json +1 -1
  109. package/docs/deploying/building-a-world.mdx +1 -1
  110. package/docs/deploying/world/postgres-world.mdx +5 -3
  111. package/docs/deploying/world/vercel-world.mdx +2 -0
  112. package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
  113. package/docs/errors/corrupted-event-log.mdx +5 -5
  114. package/docs/errors/hook-conflict.mdx +56 -4
  115. package/docs/errors/index.mdx +9 -0
  116. package/docs/errors/replay-divergence.mdx +27 -0
  117. package/docs/errors/runtime-decryption-failed.mdx +77 -0
  118. package/docs/errors/step-executed-multiple-times.mdx +23 -0
  119. package/docs/errors/step-not-registered.mdx +1 -1
  120. package/docs/foundations/cancellation.mdx +459 -0
  121. package/docs/foundations/errors-and-retries.mdx +7 -3
  122. package/docs/foundations/hooks.mdx +29 -0
  123. package/docs/foundations/idempotency.mdx +236 -11
  124. package/docs/foundations/index.mdx +3 -3
  125. package/docs/foundations/meta.json +3 -2
  126. package/docs/foundations/serialization.mdx +78 -42
  127. package/docs/foundations/starting-workflows.mdx +6 -2
  128. package/docs/foundations/streaming.mdx +14 -23
  129. package/docs/foundations/versioning.mdx +263 -0
  130. package/docs/getting-started/astro.mdx +6 -0
  131. package/docs/getting-started/index.mdx +6 -7
  132. package/docs/getting-started/meta.json +1 -0
  133. package/docs/getting-started/nestjs.mdx +9 -0
  134. package/docs/getting-started/next.mdx +5 -3
  135. package/docs/getting-started/nitro.mdx +22 -0
  136. package/docs/getting-started/sveltekit.mdx +6 -0
  137. package/docs/getting-started/tanstack-start.mdx +241 -0
  138. package/docs/how-it-works/cancellation.mdx +287 -0
  139. package/docs/how-it-works/code-transform.mdx +2 -2
  140. package/docs/how-it-works/encryption.mdx +2 -2
  141. package/docs/how-it-works/event-sourcing.mdx +2 -2
  142. package/docs/how-it-works/meta.json +2 -1
  143. package/docs/internal/index.mdx +21 -0
  144. package/docs/internal/meta.json +10 -0
  145. package/docs/internal/nitro-native-build.mdx +38 -0
  146. package/docs/internal/nitro-web-ui.mdx +24 -0
  147. package/docs/internal/serializable-abort-controller.mdx +148 -0
  148. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +63 -16
  149. package/docs/migration-guides/migrating-from-inngest.mdx +44 -22
  150. package/docs/migration-guides/migrating-from-temporal.mdx +43 -14
  151. package/docs/migration-guides/migrating-from-trigger-dev.mdx +59 -27
  152. package/docs/observability/attributes.mdx +87 -0
  153. package/docs/observability/index.mdx +25 -1
  154. package/docs/observability/meta.json +1 -1
  155. package/docs/observability/tracing.mdx +106 -0
  156. package/docs/testing/index.mdx +2 -2
  157. package/package.json +14 -13
  158. package/docs/api-reference/workflow-api/world/meta.json +0 -4
  159. package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
  160. package/docs/cookbook/advanced/custom-serialization.mdx +0 -168
  161. package/docs/cookbook/advanced/durable-objects.mdx +0 -148
  162. package/docs/cookbook/advanced/isomorphic-packages.mdx +0 -145
  163. package/docs/cookbook/agent-patterns/stop-workflow.mdx +0 -216
  164. package/docs/cookbook/agent-patterns/tool-orchestration.mdx +0 -255
  165. package/docs/cookbook/agent-patterns/tool-streaming.mdx +0 -181
  166. package/docs/cookbook/common-patterns/child-workflows.mdx +0 -372
  167. package/docs/cookbook/common-patterns/content-router.mdx +0 -207
  168. package/docs/cookbook/common-patterns/fan-out.mdx +0 -208
  169. package/docs/foundations/common-patterns.mdx +0 -265
@@ -1,10 +1,9 @@
1
1
  {
2
2
  "title": "Advanced",
3
3
  "pages": [
4
+ "child-workflows",
5
+ "upgrading-workflows",
4
6
  "serializable-steps",
5
- "durable-objects",
6
- "isomorphic-packages",
7
- "custom-serialization",
8
7
  "publishing-libraries"
9
8
  ]
10
9
  }
@@ -5,6 +5,8 @@ type: guide
5
5
  summary: Learn how to build, export, and test npm packages that ship workflow and step functions — including package.json exports, re-exporting for stable workflow IDs, keeping step I/O clean, and integration testing.
6
6
  ---
7
7
 
8
+ import { File, Folder, Files } from "fumadocs-ui/components/files";
9
+
8
10
  <Callout>
9
11
  This is an advanced guide for library authors who want to publish reusable workflow functions as npm packages. It assumes familiarity with `"use workflow"`, `"use step"`, and the workflow execution model.
10
12
  </Callout>
@@ -13,23 +15,37 @@ This is an advanced guide for library authors who want to publish reusable workf
13
15
 
14
16
  A workflow library follows a standard TypeScript package layout with a dedicated `workflows/` directory. Each workflow file exports one or more workflow functions that consumers can import and pass to `start()`.
15
17
 
16
- ```
17
- my-media-lib/
18
- ├── src/
19
- │ ├── index.ts # Package entry point
20
- │ ├── types.ts # Shared types
21
- │ ├── workflows/
22
- │ │ ├── index.ts # Re-exports all workflows
23
- │ │ ├── transcode.ts # Workflow: transcode a video
24
- │ │ └── generate-thumbnails.ts
25
- │ └── lib/
26
- │ └── api-client.ts # Internal helpers (NOT steps)
27
- ├── test-server/
28
- │ └── workflows.ts # Re-export for integration tests
29
- ├── tsup.config.ts
30
- ├── package.json
31
- └── tsconfig.json
32
- ```
18
+ <Files>
19
+ <Folder name="my-media-lib" defaultOpen>
20
+ <Folder name="src" defaultOpen>
21
+ <File name="index.ts" />
22
+ <File name="types.ts" />
23
+ <Folder name="workflows" defaultOpen>
24
+ <File name="index.ts" />
25
+ <File name="transcode.ts" />
26
+ <File name="generate-thumbnails.ts" />
27
+ </Folder>
28
+ <Folder name="lib" defaultOpen>
29
+ <File name="api-client.ts" />
30
+ </Folder>
31
+ </Folder>
32
+ <Folder name="test-server" defaultOpen>
33
+ <File name="workflows.ts" />
34
+ </Folder>
35
+ <File name="tsup.config.ts" />
36
+ <File name="package.json" />
37
+ <File name="tsconfig.json" />
38
+ </Folder>
39
+ </Files>
40
+
41
+ Key files:
42
+
43
+ - **`src/index.ts`** — Package entry point. Exports the public API.
44
+ - **`src/types.ts`** — Shared TypeScript types.
45
+ - **`src/workflows/index.ts`** — Re-exports every workflow so consumers can pull them in under one specifier (see [Entry Points and Exports](#entry-points-and-exports)).
46
+ - **`src/workflows/*.ts`** — One file per workflow function (e.g. `transcode.ts`, `generate-thumbnails.ts`).
47
+ - **`src/lib/`** — Internal helpers. Plain async code, *not* marked with `"use workflow"` or `"use step"`.
48
+ - **`test-server/workflows.ts`** — Re-export file used by integration tests (see [Testing Workflow Libraries](#testing-workflow-libraries)).
33
49
 
34
50
  ### Entry Points and Exports
35
51
 
@@ -126,7 +142,7 @@ When you publish a workflow library, every step function's inputs and outputs ar
126
142
 
127
143
  ### 1. Everything Must Be Serializable
128
144
 
129
- Step inputs and outputs must be serializable. The workflow runtime supports a rich set of types beyond plain JSON — including `Date`, `RegExp`, `Map`, `Set`, `BigInt`, `Uint8Array`, `URL`, `Error`, and class instances that implement [custom class serialization](/docs/cookbook/advanced/custom-serialization). See the [serialization reference](/docs/foundations/serialization) for the full list of supported types. Do not pass or return:
145
+ Step inputs and outputs must be serializable. The workflow runtime supports a rich set of types beyond plain JSON — including `Date`, `RegExp`, `Map`, `Set`, `BigInt`, `Uint8Array`, `URL`, `Error`, and class instances that implement [custom class serialization](/docs/foundations/serialization#custom-class-serialization). See the [serialization reference](/docs/foundations/serialization) for the full list of supported types. Do not pass or return:
130
146
 
131
147
  - Functions or closures
132
148
  - `WeakRef`, `WeakMap`, or `WeakSet`
@@ -226,7 +242,18 @@ pnpm vitest run --config vitest.workflowsdk.config.ts
226
242
 
227
243
  ## Working With and Without Workflow Installed
228
244
 
229
- If your library should work both as a standalone package and inside Workflow SDK, declare `workflow` as an optional peer dependency:
245
+ Some libraries want to be useful to consumers who *aren't* using Workflow SDK at all — the library picks up durable behavior when a workflow runtime is present and falls back to plain async execution otherwise.
246
+
247
+ <Callout type="info">
248
+ Two rules for isomorphic packages:
249
+
250
+ 1. **Any runtime reference to the `workflow` package must be loaded via dynamic `import("workflow")` inside a try/catch.** A static top-level import makes the module fail to load for consumers who haven't installed workflow.
251
+ 2. **The `"use workflow"` and `"use step"` directives are safe to keep in your library source.** When a consumer compiles your code with the Workflow SDK toolchain (via the [re-export pattern](#re-exporting-for-workflow-id-stability) above), the SWC plugin transforms them into durable-execution glue. When they're not compiled — plain Node, plain tests, a consumer without the runtime — they are just string expression statements and run as no-ops.
252
+ </Callout>
253
+
254
+ ### Optional peer dependency
255
+
256
+ Declare `workflow` as an **optional** peer so consumers without the runtime aren't forced to install it:
230
257
 
231
258
  ```json
232
259
  {
@@ -241,22 +268,53 @@ If your library should work both as a standalone package and inside Workflow SDK
241
268
  }
242
269
  ```
243
270
 
244
- Use dynamic imports and runtime detection so your library gracefully degrades when workflow is not installed:
271
+ ### Runtime detection
272
+
273
+ Wrap a dynamic `import("workflow")` in try/catch. If either the module isn't installed *or* `getStepMetadata()` throws (call site isn't inside a workflow step), fall through to the standalone path.
245
274
 
246
275
  ```typescript lineNumbers
247
- async function isWorkflowRuntime(): Promise<boolean> {
276
+ async function getWorkflowStepId(): Promise<string | null> { // [!code highlight]
248
277
  try {
249
278
  const wf = await import("workflow");
250
- if (typeof wf.getWorkflowMetadata !== "function") return false;
251
- wf.getWorkflowMetadata(); // [!code highlight]
252
- return true;
279
+ const { stepId } = wf.getStepMetadata();
280
+ return stepId;
253
281
  } catch {
254
- return false;
282
+ return null;
255
283
  }
256
284
  }
257
285
  ```
258
286
 
259
- See [Isomorphic Packages](/docs/cookbook/advanced/isomorphic-packages) for the full pattern including feature detection, dynamic imports, and dual-path execution.
287
+ ### A concrete use case: replay-safe idempotency keys
288
+
289
+ A payments utility that uses the current workflow step ID as a Stripe idempotency key when available, and a fresh UUID otherwise:
290
+
291
+ ```typescript lineNumbers
292
+ declare function getWorkflowStepId(): Promise<string | null>; // @setup (defined in the previous block)
293
+
294
+ export async function processPayment(amount: number, currency: string) {
295
+ const stepId = await getWorkflowStepId();
296
+ const idempotencyKey = stepId ? `payment:${stepId}` : crypto.randomUUID(); // [!code highlight]
297
+
298
+ const res = await fetch("https://api.stripe.com/v1/charges", {
299
+ method: "POST",
300
+ headers: {
301
+ Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
302
+ "Idempotency-Key": idempotencyKey, // [!code highlight]
303
+ },
304
+ body: new URLSearchParams({ amount: String(amount), currency }),
305
+ });
306
+ return res.json();
307
+ }
308
+ ```
309
+
310
+ When called from inside a workflow step, the utility gets a stable idempotency key for that step across retries — Stripe dedupes retries for free. When called from a plain Node.js process, it behaves like any other function and a fresh UUID is generated. For more patterns, see [Idempotency](/docs/foundations/idempotency).
311
+
312
+ ### In production
313
+
314
+ Packages in the wild built on Workflow SDK:
315
+
316
+ - **[`@mux/ai`](https://github.com/muxinc/ai)** — Reusable video AI workflows (summaries, chapters, content moderation, translation, embeddings) exported with `"use workflow"` / `"use step"` directives. In a standard Node environment the directives are no-ops and the SDK runs as a plain async library; in a Workflow SDK environment the consumer's compiler transforms them into durable, resumable steps with automatic retries and observability. Written up in detail in [*How Mux shipped durable video workflows with their @mux/ai SDK*](https://vercel.com/blog/how-mux-shipped-durable-video-workflows-with-their-mux-ai-sdk) on the Vercel blog.
317
+ - **World ID** — Human-in-the-loop "proof of human" primitive for agent workflows. Developers drop a World ID step into any workflow to require a zero-knowledge cryptographic proof that a real, unique human authorized a specific action (deploy approvals, large payments, sensitive data access, etc.). Because it runs as a workflow step, every verification is durable, replay-safe, and viewable inside the run's execution timeline — giving you a provable audit record of which human approved what. Available on npm and announced in [*World ID for agents: Browserbase, Exa, Okta, and Vercel*](https://world.org/blog/announcements/browserbase-exa-okta-world-id-for-agentic-web) on the World blog.
260
318
 
261
319
  ## Checklist
262
320
 
@@ -273,7 +331,7 @@ Before publishing a workflow library:
273
331
 
274
332
  ## Key APIs
275
333
 
276
- - [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
277
- - [`"use step"`](/docs/api-reference/workflow/use-step) — marks functions for durable execution
278
- - [`start`](/docs/api-reference/workflow/start) — starts a workflow run
334
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) — declares the orchestrator function
335
+ - [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) — marks functions for durable execution
336
+ - [`start`](/docs/api-reference/workflow-api/start) — starts a workflow run
279
337
  - [`getWorkflowMetadata`](/docs/api-reference/workflow/get-workflow-metadata) — runtime detection and run ID access
@@ -1,17 +1,28 @@
1
1
  ---
2
2
  title: Serializable Steps
3
- description: Wrap non-serializable objects (like AI model providers) inside step functions so they can cross the workflow boundary.
3
+ description: Wrap non-serializable third-party objects (like AI model providers) inside step factory functions so they can cross the workflow boundary.
4
4
  type: guide
5
- summary: Return a callback from a step to defer provider initialization, making non-serializable AI SDK models work inside durable workflows.
5
+ summary: Return a callback from a step to defer construction of a non-owned class (AI SDK models, cloud SDK clients) until execution time, making them usable inside durable workflows.
6
+ related:
7
+ - /docs/foundations/serialization
8
+ - /docs/foundations/serialization#custom-class-serialization
9
+ - /docs/foundations/workflows-and-steps#step-functions
6
10
  ---
7
11
 
8
12
  <Callout>
9
13
  This is an advanced guide. It dives into workflow internals and is not required reading to use workflow.
10
14
  </Callout>
11
15
 
16
+ ## When to use this pattern
17
+
18
+ Workflow functions run inside a sandboxed VM where every value that crosses a function boundary must be serializable. There are two ways to get a non-serializable object across that boundary, depending on whether you own the class:
19
+
20
+ - **You own the class** — implement the [`WORKFLOW_SERIALIZE` / `WORKFLOW_DESERIALIZE` protocol](/docs/foundations/serialization#custom-class-serialization). The instance becomes a first-class serializable value: you can pass it as a workflow input, return it from a step, and call `"use step"` instance methods on it directly. This is the right tool when the class is yours to modify.
21
+ - **You don't own the class** — you can't add methods to `openai("gpt-4o")` from `@ai-sdk/openai` or `new S3Client({...})` from `@aws-sdk/client-s3`. Instead, wrap construction in a `"use step"` factory function and pass the factory across the boundary. That's what this page covers.
22
+
12
23
  ## The Problem
13
24
 
14
- Workflow functions run inside a sandboxed VM where every value that crosses a function boundary must be serializable (JSON-safe). AI SDK model providers — `openai("gpt-4o")`, `anthropic("claude-sonnet-4-20250514")`, etc. — return complex objects with methods, closures, and internal state. Passing one directly into a step causes a serialization error.
25
+ AI SDK model providers — `openai("gpt-4o")`, `anthropic("claude-sonnet-4-20250514")`, etc. — return complex objects with methods, closures, and internal state. Passing one directly into a step causes a serialization error, and you can't bolt `WORKFLOW_SERIALIZE` onto a third-party class.
15
26
 
16
27
  ```typescript lineNumbers
17
28
  import { openai } from "@ai-sdk/openai";
@@ -130,6 +141,7 @@ async function uploadFile(
130
141
 
131
142
  ## Key APIs
132
143
 
133
- - [`"use step"`](/docs/api-reference/workflow/use-step) — marks a function for extraction and serialization
134
- - [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
144
+ - [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) — marks a function for extraction and serialization
145
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) — declares the orchestrator function
135
146
  - [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — accepts a model factory for durable AI agent streaming
147
+ - [Custom class serialization](/docs/foundations/serialization#custom-class-serialization) — the companion pattern for classes you own (`WORKFLOW_SERIALIZE` / `WORKFLOW_DESERIALIZE`)
@@ -0,0 +1,195 @@
1
+ ---
2
+ title: Upgrading Workflows
3
+ description: Identify a clean upgrade point in a long-running workflow and spawn a fresh run on the latest deployment carrying state forward.
4
+ type: guide
5
+ summary: 'Identify a clean upgrade point and hand off to a fresh run via `start(self, [state], { deploymentId: "latest" })` — either automatically on every iteration, or on demand via a dedicated upgrade hook.'
6
+ related:
7
+ - /docs/foundations/versioning
8
+ - /cookbook/common-patterns/workflow-composition
9
+ - /docs/api-reference/workflow-api/start
10
+ - /docs/foundations/hooks
11
+ ---
12
+
13
+ Workflows that block on external events for days, weeks, or months can outlive many deployments. **The key is to identify a clean upgrade point in the workflow** — a moment where it's safe to checkpoint state and start fresh — and then call [`start()`](/docs/api-reference/workflow-api/start) with `deploymentId: "latest"` to spawn a new run carrying that state forward. The current run ends; the next run begins on whatever deployment is live at that moment, so shipped fixes apply immediately without ever migrating an in-flight run.
14
+
15
+ <Callout type="info">
16
+ For the underlying model — why runs pin to a deployment by default, how cancel-and-rerun works, and how state crosses the version boundary — see [Versioning](/docs/foundations/versioning). This recipe focuses on event-driven workflows that need to keep advancing across deployments.
17
+ </Callout>
18
+
19
+ A clean upgrade point is any spot in the workflow where:
20
+
21
+ - All in-progress side effects have completed (or aren't needed by the next iteration)
22
+ - The relevant state can be serialized into the workflow's input arguments
23
+ - It's natural for the workflow to "checkpoint" — typically right after handling an external event, completing a batch, or finishing a logical phase
24
+
25
+ There are two ways to apply this:
26
+
27
+ 1. **Upgrade on every iteration** ([Method 1](#method-1-upgrade-on-every-iteration)). Each run handles a single event and unconditionally hands off to a fresh run on the latest deployment before exiting. Simple — no extra triggers — but every event pays the respawn cost.
28
+ 2. **Upgrade on demand via a dedicated hook** ([Method 2](#method-2-upgrade-on-demand-via-a-dedicated-hook)). A single long-lived run handles many events in a loop and only respawns when an `upgradeHook` fires. A separate endpoint resumes that hook from your control plane (e.g. after a deploy). More control and fewer respawns, at the cost of an explicit trigger.
29
+
30
+ ### When to use each
31
+
32
+ - **Method 1** when iterations are short and frequent, the work is cheap to checkpoint, and you want shipped fixes to apply on the very next event. Long-lived "session" workflows (subscriptions, queues, FSMs) that already process events one at a time fit this naturally.
33
+ - **Method 2** when iterations are infrequent or expensive (you don't want to respawn on every event), or when you need to roll out a fix to a fleet of in-flight runs after a deploy by fanning out to a control-plane endpoint. Also fits when "upgrade" should be an explicit operation rather than a side effect of handling each event.
34
+
35
+ ## Method 1: Upgrade on every iteration
36
+
37
+ Each run inherits state via its argument, blocks on a hook, processes the resume, then unconditionally hands off to its successor by calling `start()` directly from the workflow body with `deploymentId: "latest"`.
38
+
39
+ ```typescript lineNumbers
40
+ import { defineHook, getWorkflowMetadata } from "workflow";
41
+ import { start } from "workflow/api";
42
+
43
+ declare function processItem(itemId: string): Promise<void>; // @setup
44
+
45
+ interface QueueState {
46
+ processed: number;
47
+ cursor: string | null;
48
+ }
49
+
50
+ export const nextItemHook = defineHook<{ itemId: string }>();
51
+
52
+ export async function longRunningQueue(
53
+ state: QueueState = { processed: 0, cursor: null },
54
+ ): Promise<void> {
55
+ "use workflow";
56
+
57
+ const { workflowRunId } = getWorkflowMetadata();
58
+
59
+ // Block until something fires the hook — could be hours, days, or longer.
60
+ // Per-run hook tokens (workflowRunId) keep concurrent chains isolated.
61
+ const { itemId } = await nextItemHook.create({ token: workflowRunId }); // [!code highlight]
62
+
63
+ await processItem(itemId);
64
+
65
+ // Hand off to a fresh run on the latest deployment. THIS run ends here.
66
+ // `deploymentId: "latest"` resolves to whichever deployment is current
67
+ // when this spawn lands — NOT the deployment running this code.
68
+ await start( // [!code highlight]
69
+ longRunningQueue, // [!code highlight]
70
+ [{ processed: state.processed + 1, cursor: itemId }], // [!code highlight]
71
+ { deploymentId: "latest" }, // [!code highlight]
72
+ );
73
+ }
74
+ ```
75
+
76
+ ### Resuming the hook
77
+
78
+ Any server-side code can resume the currently-active iteration by calling `.resume()` with the run ID:
79
+
80
+ ```typescript
81
+ import { nextItemHook } from "@/workflows/long-running-queue";
82
+
83
+ export async function POST(req: Request) {
84
+ const { runId, itemId } = await req.json();
85
+
86
+ await nextItemHook.resume(runId, { itemId }); // [!code highlight]
87
+
88
+ return Response.json({ success: true });
89
+ }
90
+ ```
91
+
92
+ The caller tracks the active `runId` (e.g. in a database, KV, or returned from the previous iteration) and updates it whenever the chain advances.
93
+
94
+ ## Method 2: Upgrade on demand via a dedicated hook
95
+
96
+ Use a single long-running workflow that handles events in a loop. Define a second hook — `upgradeHook` — alongside the work hook, and race them. While only the work hook fires, the run keeps handling events on its current deployment. When `upgradeHook` resumes, the workflow captures current state and respawns on the latest deployment, then exits.
97
+
98
+ ```typescript lineNumbers
99
+ import { defineHook, getWorkflowMetadata } from "workflow";
100
+ import { start } from "workflow/api";
101
+
102
+ declare function processItem(itemId: string): Promise<void>; // @setup
103
+
104
+ interface QueueState {
105
+ processed: number;
106
+ cursor: string | null;
107
+ }
108
+
109
+ export const nextItemHook = defineHook<{ itemId: string }>();
110
+ export const upgradeHook = defineHook<{ reason?: string }>(); // [!code highlight]
111
+
112
+ export async function longRunningQueue(
113
+ state: QueueState = { processed: 0, cursor: null },
114
+ ): Promise<void> {
115
+ "use workflow";
116
+
117
+ const { workflowRunId } = getWorkflowMetadata();
118
+
119
+ while (true) {
120
+ // Race a normal work event against the upgrade signal.
121
+ const event = await Promise.race([ // [!code highlight]
122
+ nextItemHook
123
+ .create({ token: workflowRunId })
124
+ .then((payload) => ({ kind: "work" as const, payload })),
125
+ upgradeHook // [!code highlight]
126
+ .create({ token: workflowRunId }) // [!code highlight]
127
+ .then(() => ({ kind: "upgrade" as const })), // [!code highlight]
128
+ ]);
129
+
130
+ if (event.kind === "upgrade") { // [!code highlight]
131
+ // Checkpoint current state and hand off to a fresh run
132
+ // on whatever deployment is live now. THIS run ends here.
133
+ await start(longRunningQueue, [state], { // [!code highlight]
134
+ deploymentId: "latest", // [!code highlight]
135
+ }); // [!code highlight]
136
+ return; // [!code highlight]
137
+ }
138
+
139
+ await processItem(event.payload.itemId);
140
+ state = {
141
+ processed: state.processed + 1,
142
+ cursor: event.payload.itemId,
143
+ };
144
+ }
145
+ }
146
+ ```
147
+
148
+ ### Triggering the upgrade
149
+
150
+ Expose a separate endpoint that resumes `upgradeHook` for a given run. Call it from your deploy pipeline, an admin UI, or a fan-out script that iterates over every active run after shipping a fix.
151
+
152
+ ```typescript
153
+ import { upgradeHook } from "@/workflows/long-running-queue";
154
+
155
+ export async function POST(req: Request) {
156
+ const { runId, reason } = await req.json();
157
+
158
+ // The workflow exits its loop, captures state, and respawns
159
+ // on the latest deployment.
160
+ await upgradeHook.resume(runId, { reason }); // [!code highlight]
161
+
162
+ return Response.json({ success: true });
163
+ }
164
+ ```
165
+
166
+ To upgrade a fleet of runs after a deploy, list active runs (e.g. from a tracking store) and call this endpoint for each.
167
+
168
+ ## How it works
169
+
170
+ 1. **`deploymentId: "latest"` is the upgrade knob.** Without it, the spawn pins to the current deployment. With it, the new run resolves to whatever deployment is current when the runtime picks it up — so any shipped fix applies starting from that respawn. Both methods rely on this.
171
+ 2. **`start()` runs directly from the workflow body.** In v5, [`start()`](/docs/api-reference/workflow-api/start) is step-backed, so it can be called from a workflow function and still records a deterministic step boundary in the event log — no manual `"use step"` wrapper is required.
172
+ 3. **State carries through the function argument.** The accumulating context flows from run N to run N+1 as a serialized argument. No external store is required for the state itself.
173
+ 4. **Per-run hook tokens.** Using `workflowRunId` as the hook token scopes each iteration's wait to its own run, so multiple chains can run concurrently without interfering.
174
+ 5. **Method 1 vs Method 2 is just where the spawn happens.** In Method 1 every run spawns its successor unconditionally before exiting — there is no long-lived process to migrate. In Method 2 the spawn happens only when the upgrade hook fires; otherwise the loop keeps handling events on the same run.
175
+
176
+ ## Adapting to your use case
177
+
178
+ - **Combine with a sleep.** Race the hook against `sleep()` so iterations also tick on a timer: `Promise.race([hook, sleep("1d")])` lets the workflow advance even if no external event arrives.
179
+ - **Stateless successors.** If the next iteration doesn't need the previous state (e.g. a pure event router), call `start(longRunningQueue, [], { deploymentId: "latest" })` and skip the argument plumbing.
180
+ - **Persist state externally.** If state needs to be readable from outside the workflow (dashboards, debugging, recovery), write it to a database in a step before spawning the next run.
181
+ - **Track the active runId externally.** Whatever resumes the hook needs to know the current run. Capture the `runId` returned by `start()` and write it to a KV/database keyed by a stable session identifier (in a step) so resumers always look up the latest one.
182
+
183
+ ## Caveats
184
+
185
+ - **Backward compatibility matters.** Because the next run executes on a different deployment, the workflow's input arguments and return type must remain compatible across deployments. Adding required fields, removing fields, or changing types can cause serialization failures. See the [`deploymentId: "latest"` callout](/docs/api-reference/workflow-api/start#using-deploymentid-latest).
186
+ - **Workflow identity is the function name + file path.** Renaming the function or moving the file across a deployment changes the workflow ID — the next iteration will fail to resolve. Treat the workflow's name and location as stable interfaces.
187
+ - **There is a tiny gap between iterations.** The current run ends as soon as `start()` returns; the next run starts asynchronously. A resume that arrives in that window can fail with "hook not found." Make resumers retry, or have the API persist pending payloads and apply them once the next iteration is ready.
188
+ - **Method 2: track active runs externally.** Because Method 2's runs are long-lived, the set of in-flight runs only changes when one starts, completes, or upgrades. Persist run IDs (and clean them up on completion or upgrade) so a rollout script can fan out reliably. After resuming `upgradeHook`, also update the tracked run ID once the new run reports back, the same way you would in Method 1.
189
+
190
+ ## Key APIs
191
+
192
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
193
+ - [`start()`](/docs/api-reference/workflow-api/start) with [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest) — spawn the successor on the newest deployment
194
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook) — suspend the workflow until an external event resumes it
195
+ - [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata) — exposes `workflowRunId` for per-run hook tokens
@@ -0,0 +1,156 @@
1
+ ---
2
+ title: Agent Cancellation
3
+ description: Cancel a running agent from the outside using AbortSignal — a hook fires the abort, the agent step bails out of the model stream, and the client gets a clean stop notification.
4
+ type: guide
5
+ summary: Cancel a running agent cooperatively with AbortController. A stop hook fires controller.abort(), the signal propagates into the agent step to cancel the model stream, and a data-stopped part is emitted to streaming clients before the workflow returns.
6
+ ---
7
+
8
+ Cancel a running agent from the outside — for example, a "Stop" button in a chat UI, an admin cancellation endpoint, or a timeout fallback.
9
+
10
+ ## Pattern
11
+
12
+ Create an `AbortController` in the workflow and race the agent (passing its signal) against a stop hook. When the hook fires, `controller.abort()` is called — the signal propagates into the agent step and cancels the underlying model stream. Before returning, a `data-stopped` part is written to the stream so any streaming clients can render a clean end state.
13
+
14
+ ```typescript lineNumbers
15
+ import { DurableAgent } from "@workflow/ai/agent";
16
+ import { defineHook, getWritable, getWorkflowMetadata } from "workflow";
17
+ import { z } from "zod";
18
+ import type { ModelMessage, UIMessageChunk } from "ai";
19
+
20
+ export const stopHook = defineHook({
21
+ schema: z.object({ reason: z.string().optional() }),
22
+ });
23
+
24
+ async function searchWeb({ query }: { query: string }) {
25
+ "use step";
26
+ await new Promise((r) => setTimeout(r, 1500));
27
+ return { results: [{ title: `${query} - Wikipedia`, snippet: `Overview of ${query}...` }] };
28
+ }
29
+
30
+ async function analyzeData({ topic }: { topic: string }) {
31
+ "use step";
32
+ await new Promise((r) => setTimeout(r, 1200));
33
+ return { summary: `Analysis of ${topic}: significant developments found.`, confidence: 0.85 };
34
+ }
35
+
36
+ async function emitStopSignal(details: { reason?: string }) {
37
+ "use step";
38
+ const writer = getWritable<UIMessageChunk>().getWriter();
39
+ try {
40
+ await writer.write({ type: "data-stopped", id: "stop-signal", data: details } as UIMessageChunk);
41
+ } finally {
42
+ writer.releaseLock();
43
+ }
44
+ }
45
+
46
+ export async function stoppableAgent(messages: ModelMessage[]) {
47
+ "use workflow";
48
+
49
+ const { workflowRunId } = getWorkflowMetadata();
50
+ const controller = new AbortController(); // [!code highlight]
51
+ const hook = stopHook.create({ token: `stop:${workflowRunId}` });
52
+
53
+ const agent = new DurableAgent({
54
+ model: "anthropic/claude-haiku-4.5",
55
+ instructions: "You are a research assistant. Search and analyze data as needed.",
56
+ tools: {
57
+ searchWeb: {
58
+ description: "Search the web for information",
59
+ inputSchema: z.object({ query: z.string() }),
60
+ execute: searchWeb,
61
+ },
62
+ analyzeData: {
63
+ description: "Analyze a piece of data",
64
+ inputSchema: z.object({ topic: z.string() }),
65
+ execute: analyzeData,
66
+ },
67
+ },
68
+ });
69
+
70
+ const result = await Promise.race([
71
+ agent
72
+ .stream({
73
+ messages,
74
+ writable: getWritable<UIMessageChunk>(),
75
+ abortSignal: controller.signal, // [!code highlight]
76
+ maxSteps: 15,
77
+ })
78
+ .then((r) => ({ type: "complete" as const, messages: r.messages })),
79
+ hook.then(({ reason }) => {
80
+ controller.abort(reason); // [!code highlight]
81
+ return { type: "stopped" as const, reason };
82
+ }),
83
+ ]);
84
+
85
+ if (result.type === "stopped") {
86
+ await emitStopSignal({ reason: result.reason });
87
+ }
88
+
89
+ return result;
90
+ }
91
+ ```
92
+
93
+ ### API Route to Trigger Stop
94
+
95
+ ```typescript lineNumbers
96
+ import { stopHook } from "@/workflows/stoppable-agent";
97
+
98
+ export async function POST(
99
+ request: Request,
100
+ { params }: { params: Promise<{ runId: string }> }
101
+ ) {
102
+ const { runId } = await params;
103
+ const { reason } = await request.json();
104
+
105
+ await stopHook.resume(`stop:${runId}`, {
106
+ reason: reason || "User requested stop",
107
+ });
108
+
109
+ return Response.json({ success: true });
110
+ }
111
+ ```
112
+
113
+ ### Client Stop Button
114
+
115
+ ```tsx lineNumbers
116
+ "use client";
117
+
118
+ export function StopButton({ runId }: { runId: string }) {
119
+ const handleStop = async () => {
120
+ await fetch(`/api/chat/${runId}/stop`, {
121
+ method: "POST",
122
+ headers: { "Content-Type": "application/json" },
123
+ body: JSON.stringify({ reason: "User clicked stop" }),
124
+ });
125
+ };
126
+
127
+ return (
128
+ <button type="button" onClick={handleStop}>
129
+ Stop Agent
130
+ </button>
131
+ );
132
+ }
133
+ ```
134
+
135
+ ## How it works
136
+
137
+ 1. An `AbortController` is created at the start of the workflow
138
+ 2. A hook is created with token `stop:${workflowRunId}`
139
+ 3. `Promise.race` runs the agent stream and the stop hook concurrently
140
+ 4. The agent receives `controller.signal` — when aborted, the underlying model stream is cancelled
141
+ 5. When the stop API resumes the hook, `controller.abort()` is called — the race resolves and the workflow exits
142
+ 6. `emitStopSignal` writes a `data-stopped` part to the stream so the client renders a clean stop state
143
+
144
+ ## Adapting this
145
+
146
+ * **Add a timeout** — race a third `sleep()` promise to auto-stop after a deadline
147
+ * **Audit logging** — include a `reason` field in the stop schema to record who stopped and why
148
+ * **Cross-process** — the hook token is deterministic, so any process can call `stopHook.resume()` with the run ID
149
+ * **Step limits** — combine with `maxSteps` on the agent to cap execution even without manual stop
150
+
151
+ ## Key APIs
152
+
153
+ * [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook for the stop signal
154
+ * [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata) — access the run ID for deterministic hook tokens
155
+ * [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream output and the stop notification to the client
156
+ * [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — the agent that respects the abort signal via its `signal` option