workflow 5.0.1 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +6 -0
  2. package/dist/api-workflow.d.ts.map +1 -1
  3. package/dist/api-workflow.js +4 -2
  4. package/docs/ai/chat-session-modeling.mdx +8 -8
  5. package/docs/ai/human-in-the-loop.mdx +2 -2
  6. package/docs/ai/index.mdx +14 -14
  7. package/docs/ai/streaming-updates-from-tools.mdx +2 -2
  8. package/docs/api-reference/workflow-api/register-lifecycle-hooks.mdx +15 -5
  9. package/docs/api-reference/workflow-nest/index.mdx +4 -1
  10. package/docs/api-reference/workflow-nest/is-workflow-request.mdx +58 -0
  11. package/docs/api-reference/workflow-nest/meta.json +1 -0
  12. package/docs/api-reference/workflow-nest/workflow-controller.mdx +6 -2
  13. package/docs/api-reference/workflow-nest/workflow-module.mdx +9 -1
  14. package/docs/api-reference/workflow-observability/parse-step-name.mdx +1 -1
  15. package/docs/changelog/batched-event-writes.mdx +3 -3
  16. package/docs/configuration/framework-options.mdx +6 -0
  17. package/docs/configuration/runtime-tuning.mdx +7 -5
  18. package/docs/configuration/worlds.mdx +11 -8
  19. package/docs/cookbook/integrations/ai-sdk.mdx +8 -8
  20. package/docs/cookbook/integrations/chat-sdk.mdx +8 -8
  21. package/docs/cookbook/integrations/sandbox.mdx +8 -8
  22. package/docs/errors/node-js-module-in-workflow.mdx +36 -0
  23. package/docs/foundations/hooks.mdx +35 -0
  24. package/docs/foundations/serialization.mdx +16 -1
  25. package/docs/foundations/streaming.mdx +1 -1
  26. package/docs/getting-started/astro.mdx +7 -9
  27. package/docs/getting-started/express.mdx +4 -10
  28. package/docs/getting-started/fastify.mdx +4 -9
  29. package/docs/getting-started/hono.mdx +4 -10
  30. package/docs/getting-started/index.mdx +2 -2
  31. package/docs/getting-started/nestjs.mdx +157 -36
  32. package/docs/getting-started/next.mdx +15 -18
  33. package/docs/getting-started/nitro.mdx +4 -10
  34. package/docs/getting-started/nuxt.mdx +4 -10
  35. package/docs/getting-started/react-router/v7.mdx +6 -22
  36. package/docs/getting-started/react-router/v8.mdx +6 -22
  37. package/docs/getting-started/sveltekit.mdx +7 -9
  38. package/docs/getting-started/tanstack-start.mdx +7 -9
  39. package/docs/getting-started/vite.mdx +7 -9
  40. package/docs/how-it-works/code-transform.mdx +12 -8
  41. package/docs/how-it-works/encryption.mdx +3 -1
  42. package/docs/observability/lifecycle-hooks.mdx +69 -5
  43. package/docs/observability/tracing.mdx +3 -0
  44. package/docs/whats-new.mdx +7 -7
  45. package/docs/worlds/building-a-world.mdx +6 -1
  46. package/docs/worlds/local.mdx +4 -0
  47. package/docs/worlds/postgres.mdx +13 -33
  48. package/docs/worlds/upgrading-to-v5.mdx +1 -1
  49. package/docs/worlds/vercel.mdx +19 -9
  50. package/package.json +12 -12
@@ -52,12 +52,12 @@ const nextConfig: NextConfig = {
52
52
  export default withWorkflow(nextConfig); // [!code highlight]
53
53
  ```
54
54
 
55
- <Accordion type="single" collapsible>
56
- <AccordionItem value="typescript-intellisense" className="[&_h3]:my-0">
57
- <AccordionTrigger className="text-sm">
58
- ### Setup IntelliSense for TypeScript (Optional)
59
- </AccordionTrigger>
60
- <AccordionContent className="[&_p]:my-2">
55
+ <Details>
56
+ <Summary className="[&_h3]:my-0">
57
+
58
+ ### Setup IntelliSense for TypeScript (Optional)
59
+
60
+ </Summary>
61
61
 
62
62
  To enable helpful hints in your IDE, setup the workflow plugin in `tsconfig.json`:
63
63
 
@@ -74,16 +74,14 @@ To enable helpful hints in your IDE, setup the workflow plugin in `tsconfig.json
74
74
  }
75
75
  ```
76
76
 
77
- </AccordionContent>
78
- </AccordionItem>
79
- </Accordion>
77
+ </Details>
78
+
79
+ <Details>
80
+ <Summary className="[&_h3]:my-0">
80
81
 
81
- <Accordion type="single" collapsible>
82
- <AccordionItem value="configure-proxy-handler" className="[&_h3]:my-0">
83
- <AccordionTrigger className="text-sm">
84
- <h3 id="configure-proxy-handler">Configure Proxy Handler (if applicable)</h3>
85
- </AccordionTrigger>
86
- <AccordionContent className="[&_p]:my-2">
82
+ <h3 id="configure-proxy-handler" className="scroll-m-28">Configure Proxy Handler (if applicable)</h3>
83
+
84
+ </Summary>
87
85
 
88
86
  If your Next.js app has a [proxy handler](https://nextjs.org/docs/app/api-reference/file-conventions/proxy)
89
87
  (formerly known as "middleware"), you'll need to update the matcher pattern to exclude Workflow's
@@ -113,9 +111,8 @@ export const config = {
113
111
  ```
114
112
 
115
113
  This ensures that internal Workflow paths are not intercepted by your middleware, which could interfere with workflow execution and resumption.
116
- </AccordionContent>
117
- </AccordionItem>
118
- </Accordion>
114
+
115
+ </Details>
119
116
 
120
117
  </Step>
121
118
 
@@ -72,12 +72,9 @@ export default defineConfig({
72
72
  | `runtime` | `string` | `'nodejs22.x'` | Node.js runtime version for Vercel Functions (e.g. `'nodejs22.x'`, `'nodejs24.x'`). |
73
73
  | `sourcemap` | `boolean \| 'inline' \| 'linked' \| 'external' \| 'both'` | `'inline'` (dev) / `false` (prod) | Controls source maps on generated workflow bundles. Accepts the same values as esbuild's `sourcemap` option. Defaults to `'inline'` in development and `false` in production (smaller function bundles, which helps stay under the Vercel 250 MB function size limit). Set it explicitly, or use the `WORKFLOW_SOURCEMAP` environment variable, to override in either environment. |
74
74
 
75
- <Accordion type="single" collapsible>
76
- <AccordionItem value="typescript-intellisense" className="[&_h3]:my-0">
77
- <AccordionTrigger className="[&_p]:my-0 text-lg [&_p]:text-foreground">
78
- Set up IntelliSense for TypeScript (optional)
79
- </AccordionTrigger>
80
- <AccordionContent className="[&_p]:my-2">
75
+ <Details>
76
+ <Summary>Set up IntelliSense for TypeScript (optional)</Summary>
77
+
81
78
  To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.json`:
82
79
 
83
80
  ```json title="tsconfig.json" lineNumbers
@@ -93,10 +90,7 @@ To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.jso
93
90
  }
94
91
  ```
95
92
 
96
- </AccordionContent>
97
-
98
- </AccordionItem>
99
- </Accordion>
93
+ </Details>
100
94
 
101
95
  </Step>
102
96
 
@@ -51,12 +51,9 @@ export default defineNuxtConfig({
51
51
 
52
52
  This will also automatically enable the TypeScript plugin, which provides helpful IntelliSense hints in your IDE for workflow and step functions.
53
53
 
54
- <Accordion type="single" collapsible>
55
- <AccordionItem value="typescript-intellisense" className="[&_h3]:my-0">
56
- <AccordionTrigger className="[&_p]:my-0 text-lg [&_p]:text-foreground">
57
- Disable TypeScript Plugin (Optional)
58
- </AccordionTrigger>
59
- <AccordionContent className="[&_p]:my-2">
54
+ <Details>
55
+ <Summary>Disable TypeScript Plugin (Optional)</Summary>
56
+
60
57
  The TypeScript plugin is enabled by default. If you need to disable it, you can configure it in your `nuxt.config.ts`:
61
58
 
62
59
  {/* @skip-typecheck: incomplete code sample */}
@@ -70,10 +67,7 @@ export default defineNuxtConfig({
70
67
  });
71
68
  ```
72
69
 
73
- </AccordionContent>
74
-
75
- </AccordionItem>
76
- </Accordion>
70
+ </Details>
77
71
 
78
72
  </Step>
79
73
 
@@ -18,41 +18,25 @@ This guide starts with an existing React Router v7 framework-mode app. It is ver
18
18
 
19
19
  ## Install Nitro and Workflow SDK
20
20
 
21
- <Tabs items={["npm", "pnpm", "bun", "yarn"]} defaultValue="pnpm">
21
+ <CodeBlockTabs defaultValue="pnpm">
22
22
 
23
- <Tab value="npm">
24
-
25
- ```bash
23
+ ```bash tab="npm"
26
24
  npm install nitro workflow
27
25
  ```
28
26
 
29
- </Tab>
30
-
31
- <Tab value="pnpm">
32
-
33
- ```bash
27
+ ```bash tab="pnpm"
34
28
  pnpm add nitro workflow
35
29
  ```
36
30
 
37
- </Tab>
38
-
39
- <Tab value="bun">
40
-
41
- ```bash
31
+ ```bash tab="bun"
42
32
  bun add nitro workflow
43
33
  ```
44
34
 
45
- </Tab>
46
-
47
- <Tab value="yarn">
48
-
49
- ```bash
35
+ ```bash tab="yarn"
50
36
  yarn add nitro workflow
51
37
  ```
52
38
 
53
- </Tab>
54
-
55
- </Tabs>
39
+ </CodeBlockTabs>
56
40
 
57
41
  This integration requires Nitro v3.
58
42
 
@@ -18,41 +18,25 @@ This guide starts with an existing React Router v8 framework-mode app.
18
18
 
19
19
  ## Install Nitro and Workflow SDK
20
20
 
21
- <Tabs items={["npm", "pnpm", "bun", "yarn"]} defaultValue="pnpm">
21
+ <CodeBlockTabs defaultValue="pnpm">
22
22
 
23
- <Tab value="npm">
24
-
25
- ```bash
23
+ ```bash tab="npm"
26
24
  npm install nitro workflow
27
25
  ```
28
26
 
29
- </Tab>
30
-
31
- <Tab value="pnpm">
32
-
33
- ```bash
27
+ ```bash tab="pnpm"
34
28
  pnpm add nitro workflow
35
29
  ```
36
30
 
37
- </Tab>
38
-
39
- <Tab value="bun">
40
-
41
- ```bash
31
+ ```bash tab="bun"
42
32
  bun add nitro workflow
43
33
  ```
44
34
 
45
- </Tab>
46
-
47
- <Tab value="yarn">
48
-
49
- ```bash
35
+ ```bash tab="yarn"
50
36
  yarn add nitro workflow
51
37
  ```
52
38
 
53
- </Tab>
54
-
55
- </Tabs>
39
+ </CodeBlockTabs>
56
40
 
57
41
  This integration requires Nitro v3.
58
42
 
@@ -56,12 +56,12 @@ export default defineConfig({
56
56
  | --- | --- | --- | --- |
57
57
  | `sourcemap` | `boolean \| 'inline' \| 'linked' \| 'external' \| 'both'` | `'inline'` (dev) / `false` (prod) | Controls source maps on generated workflow bundles. Accepts the same values as esbuild's `sourcemap` option. Defaults to `'inline'` in development and `false` in production (smaller function bundles, which helps stay under the Vercel 250 MB function size limit). Set it explicitly, or use the `WORKFLOW_SOURCEMAP` environment variable, to override in either environment. |
58
58
 
59
- <Accordion type="single" collapsible>
60
- <AccordionItem value="typescript-intellisense" className="[&_h3]:my-0">
61
- <AccordionTrigger className="text-sm">
62
- ### Set up IntelliSense for TypeScript (optional)
63
- </AccordionTrigger>
64
- <AccordionContent className="[&_p]:my-2">
59
+ <Details>
60
+ <Summary className="[&_h3]:my-0">
61
+
62
+ ### Set up IntelliSense for TypeScript (optional)
63
+
64
+ </Summary>
65
65
 
66
66
  To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.json`:
67
67
 
@@ -78,9 +78,7 @@ To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.jso
78
78
  }
79
79
  ```
80
80
 
81
- </AccordionContent>
82
- </AccordionItem>
83
- </Accordion>
81
+ </Details>
84
82
 
85
83
  </Step>
86
84
 
@@ -57,12 +57,12 @@ export default defineConfig({
57
57
  });
58
58
  ```
59
59
 
60
- <Accordion type="single" collapsible>
61
- <AccordionItem value="typescript-intellisense" className="[&_h3]:my-0">
62
- <AccordionTrigger className="text-sm">
63
- ### Set up IntelliSense for TypeScript (optional)
64
- </AccordionTrigger>
65
- <AccordionContent className="[&_p]:my-2">
60
+ <Details>
61
+ <Summary className="[&_h3]:my-0">
62
+
63
+ ### Set up IntelliSense for TypeScript (optional)
64
+
65
+ </Summary>
66
66
 
67
67
  To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.json`:
68
68
 
@@ -79,9 +79,7 @@ To enable helpful hints in your IDE, set up the workflow plugin in `tsconfig.jso
79
79
  }
80
80
  ```
81
81
 
82
- </AccordionContent>
83
- </AccordionItem>
84
- </Accordion>
82
+ </Details>
85
83
 
86
84
  </Step>
87
85
 
@@ -61,12 +61,12 @@ export default defineConfig({
61
61
  });
62
62
  ```
63
63
 
64
- <Accordion type="single" collapsible>
65
- <AccordionItem value="typescript-intellisense" className="[&_h3]:my-0">
66
- <AccordionTrigger className="text-sm">
67
- ### Setup IntelliSense for TypeScript (Optional)
68
- </AccordionTrigger>
69
- <AccordionContent className="[&_p]:my-2">
64
+ <Details>
65
+ <Summary className="[&_h3]:my-0">
66
+
67
+ ### Setup IntelliSense for TypeScript (Optional)
68
+
69
+ </Summary>
70
70
 
71
71
  To enable helpful hints in your IDE, setup the workflow plugin in `tsconfig.json`:
72
72
 
@@ -83,9 +83,7 @@ To enable helpful hints in your IDE, setup the workflow plugin in `tsconfig.json
83
83
  }
84
84
  ```
85
85
 
86
- </AccordionContent>
87
- </AccordionItem>
88
- </Accordion>
86
+ </Details>
89
87
 
90
88
  </Step>
91
89
 
@@ -74,8 +74,9 @@ flowchart LR
74
74
 
75
75
  ## Detailed transformation examples
76
76
 
77
- <Tabs items={["Step Mode", "Workflow Mode", "Detect Mode"]}>
78
- <Tab value="Step Mode">
77
+ <TabsWithChildren tabs={["Step Mode","Workflow Mode","Detect Mode"]}>
78
+
79
+ <TabContent order={1}>
79
80
 
80
81
  **Step Mode** creates the registration bundle that the combined flow handler imports (it is not an HTTP route), and is also the transform framework loaders apply to your application code.
81
82
 
@@ -126,8 +127,9 @@ handleUserSignup.workflowId = "workflow//workflows/user.js//handleUserSignup"; /
126
127
 
127
128
  **ID format:** Step IDs follow the pattern `step//{filepath}//{functionName}`, where the file path is relative to your project root.
128
129
 
129
- </Tab>
130
- <Tab value="Workflow Mode">
130
+ </TabContent>
131
+
132
+ <TabContent order={2}>
131
133
 
132
134
  **Workflow Mode** creates the workflow execution bundle served at `/.well-known/workflow/v1/flow`.
133
135
 
@@ -176,8 +178,9 @@ handleUserSignup.workflowId = "workflow//workflows/user.js//handleUserSignup"; /
176
178
 
177
179
  **ID format:** Workflow IDs follow the pattern `workflow//{filepath}//{functionName}`. The `workflowId` property is attached to the function so [`start()`](/docs/api-reference/workflow-api/start) works at runtime.
178
180
 
179
- </Tab>
180
- <Tab value="Detect Mode">
181
+ </TabContent>
182
+
183
+ <TabContent order={3}>
181
184
 
182
185
  **Detect Mode** is a lightweight, non-transforming mode used during the build's discovery phase.
183
186
 
@@ -216,8 +219,9 @@ export async function handleUserSignup(email: string) {
216
219
  **Working without the app-code loader:** Frameworks apply the step-mode transform to application code by default, which is what gives `start(handleUserSignup)` its automatic IDs and type safety. If your setup can't run the loader, you can instead construct workflow IDs manually using the pattern `workflow//{filepath}//{functionName}`, look them up in the build manifest, and pass them to `start()` as strings.
217
220
  </Callout>
218
221
 
219
- </Tab>
220
- </Tabs>
222
+ </TabContent>
223
+
224
+ </TabsWithChildren>
221
225
 
222
226
  ## Generated files
223
227
 
@@ -36,7 +36,9 @@ Metadata such as workflow names, step names, entity IDs, timestamps, and lifecyc
36
36
 
37
37
  ### Compression
38
38
 
39
- Payloads are compressed before encryption. A format prefix on the stored value records the compression codec (gzip, with zstd support in the format), and the inner payload keeps its own serialization format prefix after decompression. Repetitive payloads compress heavily. AI token streams average around 80% smaller, reducing storage and network transfer. Like encryption, compression is automatic and requires no code changes.
39
+ Payloads are compressed before encryption. A format prefix on the stored value records the compression codec, and the inner payload keeps its own serialization format prefix after decompression. Repetitive payloads compress heavily. AI token streams average around 80% smaller, reducing storage and network transfer. Like encryption, compression is automatic and requires no code changes.
40
+
41
+ The codec is zstd when both the writer and the run's deployment run Node.js 22.15+ (or 23.8+), and gzip otherwise. Runs started on an older Node.js version stay readable after you upgrade the project's Node.js version. To force a codec, set [`WORKFLOW_COMPRESSION_CODEC`](/docs/configuration/runtime-tuning#workflow_compression_codec).
40
42
 
41
43
  ### Key management
42
44
 
@@ -15,7 +15,24 @@ Lifecycle hooks let you register global handlers that observe workflow runs comp
15
15
 
16
16
  ## Registering hooks
17
17
 
18
- Call `registerLifecycleHooks` from `workflow/api` early in your application's lifecycle, so the handlers exist before the first run finishes. In Next.js, [`instrumentation.ts`](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation) is the natural place; in any other app, any module that loads at startup works.
18
+ Call `registerLifecycleHooks` from `workflow/api` in the **host process that executes workflows**, before it handles requests. Registering in a different server or Vercel Function does not populate the executor's registry.
19
+
20
+ ### Framework support
21
+
22
+ | Integration / deployment | Where to register | Limitations |
23
+ | --- | --- | --- |
24
+ | Next.js 16.3.0 and later | [`instrumentation.ts`](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation), using the guarded dynamic import below | Earlier Next.js versions can handle a cold Vercel invocation before async instrumentation finishes, skipping hooks. Upgrade to 16.3.0 or later for this pattern. |
25
+ | SvelteKit | `init` in `src/hooks.server.ts`, before serving requests | Re-running initialization during hot reload can append duplicate registrations. |
26
+ | Nitro v3, including the Nitro-based Vite, TanStack Start, Express, Hono, and Fastify integrations | A server plugin with a static import and synchronous registration | Nitro does not await async plugin registration. Do not copy the Next.js dynamic-import pattern into a Nitro plugin. Vite server reloads can re-run plugins in the same process. |
27
+ | Nuxt 4 / Nitro v2 with the Vercel preset | App startup registration is not supported for lifecycle hooks on this target | The generated standalone workflow function does not load Nitro app plugins. |
28
+ | Astro on Vercel | App startup registration is not supported for lifecycle hooks on this target | The generated standalone workflow function does not load Astro middleware. |
29
+ | Nest on Vercel | App startup registration is not supported for lifecycle hooks on this target | The generated standalone workflow function does not load Nest bootstrap code. |
30
+ | CLI `vercel-build-output-api` target | App startup registration is not supported for lifecycle hooks on this target | The generated standalone workflow function does not load the application's startup module. |
31
+ | A shared Node.js server on other hosts | Bootstrap before accepting requests | The bootstrap must run in every process serving workflow queue handlers. |
32
+
33
+ The unsupported Vercel targets above emit a separate `.well-known/workflow/v1/flow.func`. App-startup hooks never reach it, so callbacks do not fire there. Do not work around this by registering at the top level of a workflow file: its VM bundle resolves `workflow/api` to a throwing stub. Registration inside a step also throws; it would otherwise accumulate a handler on every execution.
34
+
35
+ ### Next.js registration
19
36
 
20
37
  ```typescript title="instrumentation.ts" lineNumbers
21
38
  export async function register() {
@@ -41,6 +58,8 @@ Keep the dynamic `workflow/api` import inside the `NEXT_RUNTIME === "nodejs"` gu
41
58
 
42
59
  `registerLifecycleHooks` returns an unregister function. You can register multiple hook sets, and handlers run in registration order. Registrations are not deduplicated: register each hook set once per process, and call its unregister function before registering it again during hot reload or module re-evaluation. Otherwise, repeated registrations invoke the same handler multiple times for each transition.
43
60
 
61
+ **Restart `next dev` after changing handlers registered by `instrumentation.ts`.** Next.js memoizes instrumentation registration per process, so edits may not take effect until restart. For other hot-reloading hosts, preserve the unregister function in process-wide state across module re-evaluation, or restart the server. A module-local variable may be reset by the reload.
62
+
44
63
  ## Handler parameters
45
64
 
46
65
  Both handlers receive a `workflowName` string and the [`Run`](/docs/api-reference/workflow-api/get-run) instance for the transitioned run. `workflowName` is the machine-readable workflow identifier, such as `workflow//./src/workflows/order//processOrder`. Use this parameter to filter runs without a backend read. `run.runId` is also available without a read.
@@ -50,11 +69,56 @@ The `Run` instance hydrates lazily. Accessors such as `run.workflowName`, `run.s
50
69
  `onRunFailed` additionally receives a `WorkflowRunFailedError` hydrated for reporting. Unlike `run.returnValue`, it defers readable stream I/O and uses persisted abort snapshots:
51
70
 
52
71
  - `error.errorCode`: the failure classification (`USER_ERROR`, `RUNTIME_ERROR`, `MAX_DELIVERIES_EXCEEDED`, and more). See [error codes](/docs/errors) for the full list.
53
- - `error.cause`: the thrown value hydrated from the persisted error data, with registered Error subclass identity, message, stack, and cause chain preserved. Readable streams load lazily when consumed, and abort signals reflect their persisted state without live subscriptions. Writable streams retain their normal forwarding pipe and lock-polling setup during hydration. If hydration fails, the cause is a generic `Error`, matching `run.returnValue`'s fallback. Any JavaScript value can be thrown, so this is typed `unknown`.
72
+ - `error.cause`: the thrown value hydrated from the persisted error data, including its message, stack, and cause chain. Custom serialization revives registered classes using the runtime's module copy; constructor identity may differ from the handler's copy. Plain user-defined Error subclasses without custom serialization revive as generic errors with their name preserved. Readable streams load lazily when consumed, and abort signals reflect their persisted state without live subscriptions. Writable streams retain their normal forwarding setup: **writes still reach the failed run's stream, or the parent run's stream for a forwarded writable**. If hydration fails, the SDK logs the reason and supplies a generic `Error`, matching `run.returnValue`'s fallback. Any JavaScript value can be thrown, so this is typed `unknown`.
54
73
 
55
74
  In `onRunFailed`, `run.returnValue` rejects because the run failed. Use `error.cause` to inspect or report the thrown value instead of awaiting `run.returnValue`.
56
75
 
57
- The invocation's `waitUntil` scope includes background stream operations from the hydrated cause, even after a handler returns or throws. Close or release stream reader and writer locks when finished so that work can settle. Await other asynchronous reporting work in your handler, such as `Sentry.flush()` below, to keep it in the same lifetime scope.
76
+ ### Identifying errors across module copies
77
+
78
+ Handler parameters come from the runtime's module copy. For example, Next.js bundles instrumentation separately from app routes. The shared registry connects those copies, but `run instanceof Run`, `error instanceof WorkflowRunFailedError`, and checks against custom error constructors can be false. Use `WorkflowRunFailedError.is(error)` and `FatalError.is(error.cause)` for SDK errors, and inspect `errorCode`, the cause's `name`, or your own serialized discriminator for application errors:
79
+
80
+ ```typescript title="report-failure.ts" lineNumbers
81
+ import { FatalError } from "workflow";
82
+ import { WorkflowRunFailedError } from "workflow/errors";
83
+
84
+ export function reportFailure(error: unknown) {
85
+ if (!WorkflowRunFailedError.is(error)) return;
86
+ const cause = error.cause;
87
+ const name = typeof cause === "object" && cause !== null && "name" in cause
88
+ ? cause.name
89
+ : undefined;
90
+ console.error({ errorCode: error.errorCode, name, fatal: FatalError.is(cause) });
91
+ }
92
+ ```
93
+
94
+ Load this reporting module from the host registration module, using the guarded dynamic import on Next.js.
95
+
96
+ ### Stream lifetime
97
+
98
+ On Vercel, the invocation's `waitUntil` scope drains background stream operations from **`error.cause`**, even after a handler returns or throws. This does not automatically cover pipes from `await run.returnValue` in `onRunCompleted`, or consumption scheduled after the handler returns with timers or other detached work. Await consumption and other asynchronous reporting work in the handler, such as `Sentry.flush()` below. Other hosts run handlers as detached work and may stop them when the process freezes or terminates.
99
+
100
+ <Callout type="warn">
101
+ A readable or writable lock left open can keep the drain and lifecycle span pending until the Vercel Function's maximum duration. Close or release locks when finished. If you only need part of a readable, cancel its reader in a `finally` block:
102
+ </Callout>
103
+
104
+ ```typescript lineNumbers
105
+ import type { RunFailedHookParams } from "workflow/api";
106
+
107
+ async function onRunFailed({ error }: RunFailedHookParams) {
108
+ if (!(error.cause instanceof ReadableStream)) return;
109
+ const reader = error.cause.getReader();
110
+ try {
111
+ const first = await reader.read();
112
+ console.error(first.value);
113
+ } finally {
114
+ try {
115
+ await reader.cancel();
116
+ } finally {
117
+ reader.releaseLock();
118
+ }
119
+ }
120
+ }
121
+ ```
58
122
 
59
123
  ## Reporting failed runs to Sentry
60
124
 
@@ -88,8 +152,8 @@ export async function register() {
88
152
 
89
153
  ## How handlers behave
90
154
 
91
- - **Host-only.** Handlers run with full Node.js access, never inside the workflow's sandboxed VM. Calling `registerLifecycleHooks` from workflow code throws.
155
+ - **Host startup only.** Handlers run with full Node.js access, never inside the workflow's sandboxed VM. Calling `registerLifecycleHooks` from workflow or step code throws.
92
156
  - **Fire-and-forget.** Handlers cannot delay or change the run's outcome. The runtime logs and swallows a throwing handler, and the remaining handlers still run. On Vercel, `waitUntil` keeps the invocation alive while handlers finish, subject to the invocation's duration limit. On other hosts, handlers run as detached work. If the host freezes or terminates the process after the response, handlers may not complete.
93
157
  - **Best-effort delivery.** Each registered handler is invoked at most once by the invocation that writes the terminal event. For a failure, this happens after any workflow or step retries are exhausted. Callbacks are not retried if they throw or the process dies, so a callback may never run or may stop before completing. The [event log](/docs/how-it-works/event-sourcing) is the system of record, not lifecycle callbacks.
94
158
  - **Fires where the transition is recorded.** Terminal transitions recorded outside your app's compute do **not** fire handlers. For example, when you cancel a run from the CLI or the Vercel dashboard, the backend writes that transition, so no handler runs.
95
- - **Register everywhere your workflows run.** The terminal write can happen in any function invocation that processes the run's queue messages, so registration must run at startup in every instance of the app (which `instrumentation.ts` guarantees).
159
+ - **Register in each executor.** The terminal write can happen in any process that handles the run's queue messages. Use the [framework support table](#framework-support) to check whether app startup reaches that process.
@@ -40,6 +40,7 @@ No workflow-specific configuration is required. As soon as a tracer provider and
40
40
  | `workflow.start <name>` | internal | `start()` is called in your application code |
41
41
  | `workflow.execute <name>` | consumer (root) | a queue delivery invokes the workflow; replay, orchestration, and inline steps run under it |
42
42
  | `step.execute <name>` | internal (inline) / consumer + root (queue-delivered) | a step function executes |
43
+ | `workflow.lifecycle.onRunCompleted` / `workflow.lifecycle.onRunFailed` | internal | registered lifecycle handlers observe a persisted terminal transition; includes parameter hydration, handler execution, and the failure-cause stream drain |
43
44
  | `http <method>` | client | the SDK calls the workflow backend (event reads/writes) |
44
45
  | `workflow.stream.write` | client | a stream chunk (or the stream close) is flushed to the backend |
45
46
  | `workflow.stream.flush` | client | a buffered batch of stream writes settles; back-dated to the batch's first `write()`, so its duration is the app-perceived batch latency (buffer dwell + RPC) |
@@ -52,6 +53,8 @@ No workflow-specific configuration is required. As soon as a tracer provider and
52
53
 
53
54
  Stream spans are emitted by the SDK's world backend on the client that writes or reads the stream, and (like all SDK spans) are no-ops when no OpenTelemetry SDK is registered. The `workflow.stream.read` span only appears once the first non-empty chunk arrives.
54
55
 
56
+ [Lifecycle hook](/docs/observability/lifecycle-hooks) spans carry `workflow.run.id` and `workflow.name`. Caught handler, hydration, and stream-operation failures emit `workflow.lifecycle.failure` events with a `phase` and exception details. The span may still have OK status because reporting failures are isolated from workflow execution; inspect its failure events. A retained stream lock extends the span's duration through the drain, so follow the [stream cleanup guidance](/docs/observability/lifecycle-hooks#stream-lifetime).
57
+
55
58
  ## Key attributes
56
59
 
57
60
  | Attribute | Description |
@@ -105,21 +105,21 @@ See [Attributes](/docs/observability/attributes).
105
105
 
106
106
  ### Richer serialization
107
107
 
108
- Everything that crosses a workflow/step boundary is serialized, and v5 widens what survives the trip with its identity intact. Errors, including your own classes and built-ins like `TypeError`, keep their class and `cause` chain through `WorkflowRunFailedError.cause`:
108
+ Everything that crosses a workflow/step boundary is serialized. In v5, built-in errors such as `TypeError` preserve their type, message, stack, and `cause` chain through `WorkflowRunFailedError.cause`. Plain user-defined Error subclasses preserve their name but revive as generic errors unless they implement [custom serialization](/docs/foundations/serialization). Bundled module copies can still have distinct constructors, so use SDK error `.is()` helpers instead of `instanceof`:
109
109
 
110
110
  ```typescript lineNumbers
111
+ import { FatalError } from "workflow";
111
112
  import { WorkflowRunFailedError } from "workflow/errors";
112
113
  import { getRun } from "workflow/api";
113
- declare class PaymentDeclinedError extends Error {} // @setup
114
114
 
115
115
  try {
116
116
  await getRun(runId).returnValue;
117
117
  } catch (error) {
118
118
  if (
119
- error instanceof WorkflowRunFailedError &&
120
- error.cause instanceof PaymentDeclinedError // [!code highlight]
119
+ WorkflowRunFailedError.is(error) &&
120
+ FatalError.is(error.cause) // [!code highlight]
121
121
  ) {
122
- // your class, not a flattened generic Error
122
+ console.error(error.errorCode, error.cause.message);
123
123
  }
124
124
  }
125
125
  ```
@@ -152,9 +152,9 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
152
152
  - **Support for more frameworks.** [React Router](/docs/getting-started/react-router) (v7 and v8, via Nitro) and [NestJS](/docs/getting-started/nestjs) are now supported.
153
153
  - **A misrouted delivery no longer fails a run.** Runs are pinned to the deployment that created them. A delivery that arrives at a different deployment is now re-routed to the pinned one with backoff instead of failing, and only gives up with the new [`DEPLOYMENT_MISMATCH`](/docs/errors/deployment-mismatch) error once the recovery budget is spent. Nothing executes on the wrong deployment while this happens. In 4.x the same situation surfaced as an unexplained decryption failure.
154
154
  - **A run cannot be forked across environments.** `start()` stamps the environment it was called from onto the queue message, and a deployment refuses a delivery whose run was created in a different environment. Previously a preview client and a production deployment could each hold half of one run ID.
155
- - **An experimental QuickJS VM engine.** Set [`WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to run workflow functions in a QuickJS VM compiled to WebAssembly instead of `node:vm`, for platforms that do not provide `node:vm`. Replay semantics are identical, but the available globals are not: check the differences before switching an existing deployment.
155
+ - **An experimental QuickJS VM engine.** Set [`WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to run workflow functions in a QuickJS VM compiled to WebAssembly instead of `node:vm`, for platforms that do not provide `node:vm`. Replay semantics are identical, but the available globals are not: check the differences before switching an existing deployment. By default, an encrypted QuickJS run that passes 1,000 events resumes from a VM-memory snapshot instead of replaying its full event log (see [`WORKFLOW_SNAPSHOT_THRESHOLD`](/docs/configuration/runtime-tuning#workflow_snapshot_threshold)).
156
156
  - **Experimental dynamic workflows.** Pass workflow source as a string to `start()` to run orchestration assembled after deployment over steps already deployed with your app. The code is stored with the run (encrypted on Vercel), so replays always execute the code the run started with. Off unless the deployment sets `WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS=1`. See [Dynamic Workflows](/docs/advanced/dynamic-workflows).
157
- - **An opt-in WebSocket transport for event writes** on the Vercel World, which ships a run's events over one socket instead of one HTTP request each. Set [`WORKFLOW_EVENTS_TRANSPORT=ws`](/worlds/vercel#workflow_events_transport) to opt in. Any other value, including unset, keeps HTTP. Tracing is unaffected: each write still emits an `http POST` client span, synthesized around the frame, with the transport on `workflow.events.transport`.
157
+ - **A WebSocket transport for event writes** on the Vercel World, which ships a run's events over one socket instead of one HTTP request each. It is the default; set [`WORKFLOW_EVENTS_TRANSPORT=http`](/worlds/vercel#workflow_events_transport) to opt out. Tracing is unaffected: each write still emits an `http POST` client span, synthesized around the frame, with the transport on `workflow.events.transport`.
158
158
  - **`await run.returnValue` waits instead of polling.** Reading a run's result long-polls the World until the run reaches a terminal status, rather than asking again on a fixed interval. A result is observed as soon as it exists, and an idle wait costs one open request instead of a request per tick. Worlds that do not implement the long poll keep the interval.
159
159
  - **An event arriving mid-replay no longer fails the run.** A hook resume or step completion landing while a replay is in flight used to be able to fail it with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log). Writes now come back with the events the replay had not seen, and the event is held for whichever part of the workflow awaits it. A run only fails when the log is genuinely missing a position.
160
160
 
@@ -158,6 +158,8 @@ interface Storage {
158
158
 
159
159
  **Batch writes:** `events.createBatch()` is optional, and implementing it is what declares it. The runtime folds a suspension's `step_created` and `wait_created` writes into batches only when the method exists, and otherwise takes the single-event path unchanged. Implement it with real atomicity per attempt, so a lost race leaves nothing behind, or do not implement it at all. The events land in request order at consecutive positions, and a concurrent writer may push the whole batch above the caller's view of the log. No skipped-event report accompanies the result, so a position-tracking caller compares the committed positions against what it expected and reloads. Reject the whole batch, with a request-level error, for `run_created`, `run_started`, `run_cancelled`, `hook_created`, `hook_disposed`, `attr_set`, for more events targeting one entity than a single write can express, and for a batch over your own size caps. The one legal same-entity pair is `step_created` followed by `step_started`, which creates the step born-running, and there the input must ride the `step_created`.
160
160
 
161
+ **Throttled step results:** `step_completed`, `step_retrying`, and a `step_failed` marked with `afterStepBody: true` in `CreateEventParams` record a step body that already ran. If your World retries throttled writes, keep these waiting longer than other writes, because losing one to queue redelivery runs the body again. `@workflow/world-vercel` waits until the invocation's deadline. The flag is advisory, and a World may ignore it.
162
+
161
163
  **Run creation:** For `run_created` events, the `runId` parameter may be a client-provided string or `null`. When `null`, your World generates and returns a new `runId`.
162
164
 
163
165
  **Event data resolution:** `events.list()` and `events.create()` accept `resolveData: 'skip-step-inputs'`, and the runtime replays with it. The World may leave `input` out of `step_created` and `step_started` events, and returns everything else as for `'all'`. Treat any value other than `'none'` as `'all'`, because a World that tests `resolveData === 'all'` strips step results and breaks every replay. Map the value with `entityResolveData()` from `@workflow/world` before passing it to an entity read.
@@ -449,7 +451,10 @@ that lifetime, so the session's `write(chunkSeq, chunks)` receives a sequence
449
451
  number that is writer-local rather than stream-global. That is what lets a
450
452
  World order concurrent writers to the same stream. The session's `close()` must
451
453
  not resolve before every prior write is durable; `dispose()` is optional and
452
- releases transport resources without ending the stream. A World that does not
454
+ releases transport resources without ending the stream. Optional `release()`
455
+ retires an idle transport after the runtime drains a released writer. Unlike
456
+ `dispose()`, it must leave later `write()` and `close()` usable, for example
457
+ by switching that writer to stateless HTTP. A World that does not
453
458
  implement `createWriteSession` is unaffected: the runtime uses
454
459
  `write`/`writeMulti`/`close` exactly as before.
455
460
 
@@ -117,6 +117,10 @@ WORKFLOW_TARGET_WORLD="./my-world.ts"
117
117
 
118
118
  `createWorld()` also accepts `tag`, which scopes local storage files to a suffix. It is mainly used by test harnesses that share one `.workflow-data` directory.
119
119
 
120
+ ## Data directory layout
121
+
122
+ Each run's event and step files are stored in their own directory (`events/<runId>/`, `steps/<runId>/`). A directory that mixes both layouts, or holds `.json` files in `events/` or `steps/` that the World did not write, is never deleted: starting fails with a `DataDirLayoutError` that lists the files.
123
+
120
124
  ## Limitations
121
125
 
122
126
  The Local World is designed for development, not production: