workflow 5.0.0-beta.4 → 5.0.0-beta.40

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 (227) hide show
  1. package/README.md +63 -20
  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 +1 -1
  5. package/dist/api.d.ts +5 -1
  6. package/dist/api.d.ts.map +1 -1
  7. package/dist/api.js +12 -2
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +6 -1
  11. package/dist/internal/builtins.d.ts +17 -0
  12. package/dist/internal/builtins.d.ts.map +1 -1
  13. package/dist/internal/builtins.js +65 -1
  14. package/dist/internal/errors.d.ts +1 -1
  15. package/dist/internal/errors.d.ts.map +1 -1
  16. package/dist/internal/errors.js +2 -2
  17. package/dist/nest-builder.d.ts +2 -0
  18. package/dist/nest-builder.d.ts.map +1 -0
  19. package/dist/nest-builder.js +2 -0
  20. package/dist/nest-vercel-builder.d.ts +2 -0
  21. package/dist/nest-vercel-builder.d.ts.map +1 -0
  22. package/dist/nest-vercel-builder.js +2 -0
  23. package/dist/observability.d.ts +1 -1
  24. package/dist/observability.js +2 -2
  25. package/dist/runtime.d.ts +2 -1
  26. package/dist/runtime.d.ts.map +1 -1
  27. package/dist/runtime.js +5 -2
  28. package/docs/ai/chat-session-modeling.mdx +7 -3
  29. package/docs/ai/defining-tools.mdx +2 -2
  30. package/docs/ai/index.mdx +30 -25
  31. package/docs/ai/message-queueing.mdx +10 -10
  32. package/docs/ai/resumable-streams.mdx +9 -1
  33. package/docs/api-reference/index.mdx +24 -0
  34. package/docs/api-reference/meta.json +8 -0
  35. package/docs/api-reference/vitest/index.mdx +28 -7
  36. package/docs/api-reference/workflow/create-hook.mdx +79 -0
  37. package/docs/api-reference/workflow/create-webhook.mdx +1 -0
  38. package/docs/api-reference/workflow/define-hook.mdx +26 -24
  39. package/docs/api-reference/workflow/fatal-error.mdx +29 -7
  40. package/docs/api-reference/workflow/fetch.mdx +8 -4
  41. package/docs/api-reference/workflow/index.mdx +3 -0
  42. package/docs/api-reference/workflow/set-attributes.mdx +61 -0
  43. package/docs/api-reference/workflow/sleep.mdx +1 -1
  44. package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
  45. package/docs/api-reference/workflow-ai/index.mdx +2 -2
  46. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +44 -1
  47. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +9 -0
  48. package/docs/api-reference/workflow-api/get-run.mdx +25 -0
  49. package/docs/api-reference/workflow-api/index.mdx +6 -8
  50. package/docs/api-reference/workflow-api/resume-hook.mdx +60 -1
  51. package/docs/api-reference/workflow-api/resume-webhook.mdx +6 -4
  52. package/docs/api-reference/workflow-api/start.mdx +39 -6
  53. package/docs/api-reference/workflow-astro/index.mdx +18 -0
  54. package/docs/api-reference/workflow-astro/meta.json +4 -0
  55. package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
  56. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
  57. package/docs/api-reference/workflow-errors/index.mdx +88 -0
  58. package/docs/api-reference/workflow-errors/meta.json +6 -0
  59. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +68 -0
  60. package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
  61. package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
  62. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
  63. package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
  64. package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
  65. package/docs/api-reference/workflow-globals.mdx +4 -1
  66. package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
  67. package/docs/api-reference/workflow-nest/index.mdx +31 -0
  68. package/docs/api-reference/workflow-nest/meta.json +9 -0
  69. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
  70. package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
  71. package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
  72. package/docs/api-reference/workflow-next/with-workflow.mdx +56 -2
  73. package/docs/api-reference/workflow-nitro/index.mdx +60 -0
  74. package/docs/api-reference/workflow-nuxt/index.mdx +48 -0
  75. package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
  76. package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
  77. package/docs/api-reference/workflow-observability/index.mdx +64 -0
  78. package/docs/api-reference/workflow-observability/meta.json +11 -0
  79. package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
  80. package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
  81. package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
  82. package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
  83. package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
  84. package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
  85. package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +7 -10
  86. package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
  87. package/docs/api-reference/workflow-runtime/index.mdx +43 -0
  88. package/docs/api-reference/workflow-runtime/meta.json +12 -0
  89. package/docs/api-reference/workflow-runtime/set-world.mdx +49 -0
  90. package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +42 -0
  91. package/docs/api-reference/workflow-runtime/world/analytics.mdx +138 -0
  92. package/docs/api-reference/{workflow-api → workflow-runtime}/world/index.mdx +10 -10
  93. package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
  94. package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +8 -6
  95. package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +18 -5
  96. package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +2 -2
  97. package/docs/api-reference/workflow-serde/index.mdx +0 -1
  98. package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +1 -2
  99. package/docs/api-reference/workflow-serde/workflow-serialize.mdx +2 -2
  100. package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
  101. package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
  102. package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
  103. package/docs/api-reference/workflow-vite/index.mdx +18 -0
  104. package/docs/api-reference/workflow-vite/meta.json +4 -0
  105. package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
  106. package/docs/changelog/attributes-mvp.mdx +380 -0
  107. package/docs/changelog/eager-processing.mdx +269 -0
  108. package/docs/changelog/index.mdx +3 -1
  109. package/docs/changelog/lazy-event-creation.md +127 -0
  110. package/docs/changelog/meta.json +9 -1
  111. package/docs/changelog/resilient-resume.mdx +22 -0
  112. package/docs/changelog/resilient-start.mdx +31 -283
  113. package/docs/changelog/step-message-ownership.mdx +360 -0
  114. package/docs/changelog/turbo-mode.md +87 -0
  115. package/docs/comparisons/index.mdx +66 -0
  116. package/docs/comparisons/meta.json +11 -0
  117. package/docs/comparisons/workflow-sdk-vs-aws-agentcore.mdx +55 -0
  118. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +111 -0
  119. package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +71 -0
  120. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +102 -0
  121. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +123 -0
  122. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +103 -0
  123. package/docs/configuration/build-and-diagnostics.mdx +70 -0
  124. package/docs/configuration/cli-and-web-ui.mdx +182 -0
  125. package/docs/configuration/framework-options.mdx +165 -0
  126. package/docs/configuration/index.mdx +32 -0
  127. package/docs/configuration/meta.json +12 -0
  128. package/docs/configuration/runtime-tuning.mdx +276 -0
  129. package/docs/configuration/worlds.mdx +275 -0
  130. package/docs/cookbook/advanced/child-workflows.mdx +203 -256
  131. package/docs/cookbook/advanced/meta.json +1 -1
  132. package/docs/cookbook/advanced/publishing-libraries.mdx +33 -24
  133. package/docs/cookbook/advanced/serializable-steps.mdx +12 -4
  134. package/docs/cookbook/advanced/upgrading-workflows.mdx +199 -0
  135. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +34 -75
  136. package/docs/cookbook/agent-patterns/durable-agent.mdx +14 -142
  137. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +11 -3
  138. package/docs/cookbook/common-patterns/batching.mdx +4 -0
  139. package/docs/cookbook/common-patterns/idempotency.mdx +40 -52
  140. package/docs/cookbook/common-patterns/rate-limiting.mdx +5 -1
  141. package/docs/cookbook/common-patterns/saga.mdx +6 -2
  142. package/docs/cookbook/common-patterns/scheduling.mdx +12 -0
  143. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +4 -0
  144. package/docs/cookbook/common-patterns/timeouts.mdx +6 -1
  145. package/docs/cookbook/common-patterns/webhooks.mdx +4 -0
  146. package/docs/cookbook/common-patterns/workflow-composition.mdx +19 -16
  147. package/docs/cookbook/index.mdx +3 -3
  148. package/docs/cookbook/integrations/ai-sdk.mdx +64 -28
  149. package/docs/cookbook/integrations/chat-sdk.mdx +17 -0
  150. package/docs/cookbook/integrations/sandbox.mdx +17 -0
  151. package/docs/{deploying/index.mdx → deploying.mdx} +7 -7
  152. package/docs/errors/abort-signal-timeout-in-workflow.mdx +84 -0
  153. package/docs/errors/corrupted-event-log.mdx +5 -5
  154. package/docs/errors/deployment-mismatch.mdx +71 -0
  155. package/docs/errors/fetch-in-workflow.mdx +4 -0
  156. package/docs/errors/hook-conflict.mdx +60 -4
  157. package/docs/errors/index.mdx +1 -35
  158. package/docs/errors/node-js-module-in-workflow.mdx +4 -0
  159. package/docs/errors/replay-divergence.mdx +27 -0
  160. package/docs/errors/runtime-decryption-failed.mdx +77 -0
  161. package/docs/errors/serialization-failed.mdx +4 -0
  162. package/docs/errors/start-invalid-workflow-function.mdx +4 -0
  163. package/docs/errors/step-executed-multiple-times.mdx +23 -0
  164. package/docs/errors/step-not-registered.mdx +1 -1
  165. package/docs/errors/timeout-in-workflow.mdx +4 -0
  166. package/docs/errors/webhook-response-not-sent.mdx +4 -0
  167. package/docs/foundations/cancellation.mdx +459 -0
  168. package/docs/foundations/errors-and-retries.mdx +7 -3
  169. package/docs/foundations/hooks.mdx +29 -0
  170. package/docs/foundations/idempotency.mdx +243 -11
  171. package/docs/foundations/index.mdx +1 -23
  172. package/docs/foundations/meta.json +3 -1
  173. package/docs/foundations/serialization.mdx +77 -41
  174. package/docs/foundations/starting-workflows.mdx +79 -2
  175. package/docs/foundations/streaming.mdx +14 -23
  176. package/docs/foundations/versioning.mdx +263 -0
  177. package/docs/getting-started/astro.mdx +12 -2
  178. package/docs/getting-started/express.mdx +6 -2
  179. package/docs/getting-started/fastify.mdx +6 -2
  180. package/docs/getting-started/hono.mdx +6 -2
  181. package/docs/getting-started/index.mdx +16 -10
  182. package/docs/getting-started/meta.json +4 -1
  183. package/docs/getting-started/nestjs.mdx +77 -3
  184. package/docs/getting-started/next.mdx +12 -6
  185. package/docs/getting-started/nitro.mdx +28 -2
  186. package/docs/getting-started/nuxt.mdx +6 -2
  187. package/docs/getting-started/python.mdx +24 -18
  188. package/docs/getting-started/react-router/index.mdx +33 -0
  189. package/docs/getting-started/react-router/meta.json +5 -0
  190. package/docs/getting-started/react-router/v7.mdx +237 -0
  191. package/docs/getting-started/react-router/v8.mdx +232 -0
  192. package/docs/getting-started/sveltekit.mdx +12 -2
  193. package/docs/getting-started/tanstack-start.mdx +245 -0
  194. package/docs/getting-started/vite.mdx +6 -2
  195. package/docs/how-it-works/cancellation.mdx +287 -0
  196. package/docs/how-it-works/code-transform.mdx +21 -17
  197. package/docs/how-it-works/encryption.mdx +5 -5
  198. package/docs/how-it-works/event-sourcing.mdx +6 -6
  199. package/docs/how-it-works/framework-integrations.mdx +96 -337
  200. package/docs/how-it-works/meta.json +2 -1
  201. package/docs/internal/index.mdx +21 -0
  202. package/docs/internal/meta.json +10 -0
  203. package/docs/internal/nitro-native-build.mdx +38 -0
  204. package/docs/internal/nitro-web-ui.mdx +24 -0
  205. package/docs/internal/serializable-abort-controller.mdx +148 -0
  206. package/docs/meta.json +2 -2
  207. package/docs/observability/attributes.mdx +112 -0
  208. package/docs/observability/index.mdx +20 -1
  209. package/docs/observability/meta.json +1 -1
  210. package/docs/observability/tracing.mdx +124 -0
  211. package/docs/testing/index.mdx +2 -2
  212. package/package.json +17 -13
  213. package/docs/api-reference/workflow-api/world/meta.json +0 -4
  214. package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
  215. package/docs/cookbook/advanced/distributed-abort-controller.mdx +0 -318
  216. package/docs/deploying/building-a-world.mdx +0 -251
  217. package/docs/deploying/meta.json +0 -4
  218. package/docs/deploying/world/local-world.mdx +0 -84
  219. package/docs/deploying/world/meta.json +0 -4
  220. package/docs/deploying/world/postgres-world.mdx +0 -222
  221. package/docs/deploying/world/vercel-world.mdx +0 -179
  222. package/docs/migration-guides/index.mdx +0 -34
  223. package/docs/migration-guides/meta.json +0 -9
  224. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +0 -363
  225. package/docs/migration-guides/migrating-from-inngest.mdx +0 -314
  226. package/docs/migration-guides/migrating-from-temporal.mdx +0 -318
  227. package/docs/migration-guides/migrating-from-trigger-dev.mdx +0 -337
@@ -0,0 +1,287 @@
1
+ ---
2
+ title: How Cancellation Works
3
+ description: Learn how AbortController is made durable using hooks and streams under the hood.
4
+ type: conceptual
5
+ summary: Understand the hook and stream backing that makes AbortSignal work across workflow boundaries.
6
+ prerequisites:
7
+ - /docs/foundations/cancellation
8
+ - /docs/how-it-works/event-sourcing
9
+ related:
10
+ - /docs/foundations/hooks
11
+ - /docs/foundations/streaming
12
+ - /docs/foundations/serialization
13
+ ---
14
+
15
+ <Callout>
16
+ This guide explains how cancellation works internally. Understanding these details is helpful for debugging and advanced use cases, but is not required to use `AbortController` in workflows. For usage patterns, see the [Cancellation](/docs/foundations/cancellation) guide.
17
+ </Callout>
18
+
19
+ When you write `new AbortController()` in a workflow function, Workflow DevKit creates a durable controller backed by two existing primitives: a [hook](/docs/foundations/hooks) and a [stream](/docs/foundations/streaming). This page explains why both are needed and how they work together.
20
+
21
+ ## The Problem
22
+
23
+ `AbortController` and `AbortSignal` are inherently stateful — an abort happens once and is permanent. In a durable workflow, this state must:
24
+
25
+ 1. **Survive replay** — If `abort()` was called, `signal.aborted` must return `true` on every subsequent replay of the workflow.
26
+ 2. **Propagate in real-time** — A running step on a different compute instance must receive the abort immediately, not on the next replay.
27
+
28
+ No single primitive solves both. Hooks provide durable event log state but can't reach into a running step. Streams provide real-time cross-process communication but aren't part of the event log. The solution is to use both.
29
+
30
+ ## Dual Backing: Hook + Stream
31
+
32
+ Every `AbortController` in the workflow context is backed by:
33
+
34
+ ### Hook (Durable State)
35
+
36
+ When `new AbortController()` is called in a workflow, an internal hook is created — similar to calling `createHook()`. This hook is registered in the workflow's invocations queue and produces events in the [event log](/docs/how-it-works/event-sourcing):
37
+
38
+ - **On creation**: A `hook_created` event records that the controller exists
39
+ - **On abort**: The hook is resumed (producing a `hook_received` event), recording the abort permanently
40
+ - **On replay**: The event consumer processes the `hook_received` event and updates `signal.aborted` to `true` at the same point in the replay as the original abort
41
+
42
+ This gives the workflow deterministic access to the abort state — `controller.signal.aborted` always returns the correct value, even after cold starts.
43
+
44
+ ### Stream (Real-Time Propagation)
45
+
46
+ When `controller.signal` is serialized as a step argument, a stream name is included in the serialized form. Inside the step, the deserialized `AbortSignal` listens on this stream:
47
+
48
+ - **On abort**: A cancellation packet is written to the stream
49
+ - **In the step**: A background reader receives the packet and calls `abort()` on the local `AbortController`, firing the signal immediately
50
+
51
+ This gives steps real-time cancellation without waiting for the workflow to replay.
52
+
53
+ ### Why Both?
54
+
55
+ | Mechanism | Solves | Doesn't Solve |
56
+ |---|---|---|
57
+ | Hook only | Deterministic replay, event log consistency | Can't reach into a running step on another instance |
58
+ | Stream only | Real-time propagation to running steps | Not part of the event log, lost on replay |
59
+ | Hook + Stream | Both | — |
60
+
61
+ ## Lifecycle
62
+
63
+ ### 1. Controller Created in Workflow
64
+
65
+ ```
66
+ new AbortController()
67
+
68
+ ├─→ Internal hook created (registered in invocations queue)
69
+ └─→ Stream name generated (deterministic ULID)
70
+ ```
71
+
72
+ ### 2. Signal Passed to Step
73
+
74
+ ```
75
+ stepFunction(controller.signal)
76
+
77
+ ├─→ Signal serialized as { streamName, hookToken, aborted }
78
+ └─→ In the step: deserialized as real AbortSignal
79
+
80
+ └─→ Background reader listens on stream for abort packet
81
+ ```
82
+
83
+ ### 3. abort() Called in Workflow
84
+
85
+ ```
86
+ controller.abort()
87
+
88
+ ├─→ signal.aborted set to true (synchronous, local state)
89
+ ├─→ Hook marked for resumption in invocations queue
90
+ └─→ Workflow suspends (reaches next step/sleep/hook await)
91
+
92
+ ├─→ Suspension handler creates hook_received event
93
+ ├─→ Suspension handler writes cancellation packet to stream
94
+ │ │
95
+ │ └─→ Step receives packet → local signal fires → fetch cancelled
96
+ └─→ Workflow re-enqueued for replay
97
+ ```
98
+
99
+ ### 4. Workflow Replays After Abort
100
+
101
+ ```
102
+ Replay starts → events loaded
103
+
104
+ ├─→ new AbortController() → hook created → event consumer subscribes
105
+ ├─→ hook_created event consumed
106
+ ├─→ hook_received event consumed → signal.aborted re-asserted as true
107
+ └─→ Workflow code sees signal.aborted === true at the correct point in replay
108
+ ```
109
+
110
+ On replay, the events consumer re-applies the abort by calling `_setAborted` when it encounters the `hook_received` event in the log — at the same point in execution where the original `abort()` happened. This is what makes the abort deterministic across replays.
111
+
112
+ ## Where the Hook Is Created
113
+
114
+ The backing hook is set up whenever an `AbortController` or `AbortSignal` enters the workflow context:
115
+
116
+ **`new AbortController()` in a workflow function** — The workflow VM provides a durable `AbortController` implementation (similar to how it provides deterministic `Date` and serializable `Request`/`Response`). The hook is created in the constructor using the orchestrator context injected via VM globals.
117
+
118
+ **Returned from a step** — A step can create a plain `new AbortController()` and return it. The step-side serializer generates a stream name and hook token (using a random ULID) and includes them in the serialized payload. When the return value is deserialized into the workflow via `hydrateStepReturnValue`, the workflow reviver reads the token from the payload and sets up the hook with that token. Since the serialized payload is stored in the event log (as part of the `step_completed` event), the same token is used on every replay — no deterministic generation needed in the workflow.
119
+
120
+ **Passed as workflow input** — Conceptually the same as "returned from a step". The **external reducer** handles it at serialization time:
121
+
122
+ 1. Generates a stream name and hook token (random ULID)
123
+ 2. Attaches an `abort` event listener on the source signal: when the external code calls `controller.abort()`, the listener writes the cancellation packet to the stream
124
+ 3. Pushes the listener's async work into `ops` (awaited via `waitUntil`)
125
+ 4. Serializes the reference as `{ streamName, hookToken, aborted }`
126
+
127
+ The serialized payload (including the generated token) is stored in the event log as part of the workflow's input. When the workflow deserializes the input, the reviver reads the token from the payload and creates the hook — identical to the "returned from a step" case. On replay, the same token is read from the event log, so the hook matches the same events.
128
+
129
+ If the external code calls `abort()` while the process is still alive (within the `waitUntil` window), the stream packet arrives in the workflow, and the workflow can resume the hook to record it in the event log.
130
+
131
+ <Callout type="info">
132
+ Since the external `AbortController` is a plain JavaScript object (not the workflow VM's durable version), the stream write depends on the originating process still being alive. This is the same constraint that applies to passing a `ReadableStream` as a workflow argument — the stream pipe runs via `waitUntil` and requires the process to remain active until the data is written.
133
+ </Callout>
134
+
135
+ ## Serialization & Deserialization
136
+
137
+ ### Serialized Form
138
+
139
+ An `AbortController` or `AbortSignal` is serialized as:
140
+
141
+ {/* @skip-typecheck: type definition, not runnable code */}
142
+ ```typescript
143
+ {
144
+ streamName: string; // e.g., "abrt_01HWKZ..."
145
+ hookToken: string; // Generated at serialization time, used by workflow reviver to create the hook
146
+ aborted: boolean; // Current state at serialization time
147
+ reason?: unknown; // The abort reason, if any
148
+ }
149
+ ```
150
+
151
+ The `streamName` and `hookToken` are generated once at serialization time (in the step or external context) and stored in the event log as part of the serialized payload. On replay, the workflow reviver reads them from the payload — it never generates them itself. This is the same pattern used by `ReadableStream` and `WritableStream` serialization.
152
+
153
+ ### Reducers (Serialization)
154
+
155
+ **In step context** (`getStepReducers`): When a step returns an `AbortController`, the reducer captures the stream name. If `abort()` was called in the step, `aborted: true` is recorded.
156
+
157
+ **In workflow context** (`getWorkflowReducers`): The reducer captures the stream name and hook token. These are handles — no I/O happens during serialization in the workflow.
158
+
159
+ **In external context** (`getExternalReducers`): When an `AbortController` is passed as a workflow argument from outside, the reducer creates the backing stream and serializes the reference.
160
+
161
+ ### Revivers (Deserialization)
162
+
163
+ **Into step context** (`getStepRevivers`): Creates a real `AbortController`. If `aborted: true`, calls `abort()` immediately. Otherwise, pushes a stream reader into the step's `ops` array that listens for the cancellation packet and calls `abort()` when received.
164
+
165
+ **Into workflow context** (`getWorkflowRevivers`): Creates the durable AbortController with hook backing. Subscribes to the events consumer for the hook's correlation ID. If the event log contains a `hook_received` event, `signal.aborted` is `true`.
166
+
167
+ ### abort() in a Step
168
+
169
+ When `abort()` is called on a deserialized `AbortController` inside a step:
170
+
171
+ 1. The local signal is aborted synchronously (standard behavior)
172
+ 2. The stream write (cancellation packet) is pushed into `ctx.ops`
173
+ 3. The hook resume (`resumeHook`) is pushed into `ctx.ops`
174
+
175
+ The step's `ops` array is awaited via `waitUntil(Promise.all(ops))` after the step function returns — the same mechanism used by [`getWritable()`](/docs/api-reference/workflow/get-writable). This keeps `abort()` synchronous from the caller's perspective while ensuring the async work completes.
176
+
177
+ ### Abort Errors Are Wrapped in FatalError
178
+
179
+ When a step throws due to an abort — whether from `fetch` throwing `AbortError`, `signal.throwIfAborted()`, or any other abort-induced error — the step executor wraps the error in `FatalError` before recording it in the event log. This ensures:
180
+
181
+ - **No retries**: An abort is intentional cancellation, not a transient failure. Retrying would just abort again.
182
+ - **Immediate propagation**: The error bubbles up to the workflow as a `FatalError`, which the workflow can catch with `FatalError.is(err)`.
183
+
184
+ The wrapping happens in `runtime/step-executor.ts` during error hydration. When the step's thrown error is an `AbortError` (checked via `err.name === 'AbortError'`), it is treated as fatal regardless of the step's `maxRetries` configuration.
185
+
186
+ ### abort() in the Workflow
187
+
188
+ When `abort()` is called in the workflow context:
189
+
190
+ 1. `signal.aborted` is updated to `true` immediately (so subsequent reads and serialization capture the correct state)
191
+ 2. The internal hook is marked for resumption in the invocations queue (same pattern as `hook.dispose()`)
192
+ 3. The workflow continues until it reaches the next suspension point (step call, hook await, or sleep) or completes
193
+ 4. The pending queue items are processed:
194
+ - Creates a `hook_received` event in the event log
195
+ - Writes the cancellation packet to the stream (for real-time step propagation)
196
+ - Re-enqueues the workflow for replay
197
+ 4. On replay, the event consumer processes the `hook_received` event, updating `signal.aborted` to `true` at the deterministically correct point
198
+
199
+ `signal.aborted` is updated synchronously so that the workflow can immediately check the state and serialization captures `aborted: true` when passing the signal to steps. On replay, the event consumer also processes the `hook_received` event, ensuring the state is consistent.
200
+
201
+ For abort specifically, this ensures that:
202
+
203
+ - The abort's `hook_received` event is created in the event log
204
+ - The cancellation stream packet is written to propagate to running steps
205
+
206
+ ## Race Conditions
207
+
208
+ ### Abort Before Hook Exists
209
+
210
+ When an `AbortSignal` is passed as a workflow argument via `start()`, the external reducer attaches a listener at serialization time. If the external code calls `abort()` before the workflow has started and created the internal hook, the stream packet is written but the hook doesn't exist yet.
211
+
212
+ This is resolved through eventual consistency:
213
+
214
+ 1. The stream packet is durable — it persists in storage
215
+ 2. When the workflow runs and passes the signal to a step, the step's reviver reads from the stream starting at index 0
216
+ 3. The step sees the existing packet, aborts locally, and resumes the hook (via `ops`)
217
+ 4. On the next workflow replay, the hook event is in the log and `signal.aborted` is `true`
218
+
219
+ **Important:** There is a window where the workflow's `signal.aborted` returns `false` even though the external code has already called `abort()`. This lasts until a step processes the stream packet and resumes the hook. This is analogous to hooks — `resumeHook()` doesn't take effect until the workflow replays.
220
+
221
+ ### Abort at Serialization Time
222
+
223
+ To prevent a micro-window where `abort()` is called between checking `signal.aborted` and attaching the listener, the external reducer uses this order:
224
+
225
+ 1. Attach the `abort` event listener first
226
+ 2. Then check `signal.aborted` — if already `true`, the listener won't fire, so handle immediately
227
+
228
+ This ensures no abort events are missed regardless of timing.
229
+
230
+ ## Stream/Hook Consistency
231
+
232
+ Since abort involves two operations (stream write + hook resume), partial failure is possible:
233
+
234
+ ### Stream Succeeds, Hook Fails
235
+
236
+ - Steps see the abort and throw `AbortError` (stream worked)
237
+ - Workflow doesn't see `signal.aborted === true` on the next replay (hook not resumed)
238
+ - The workflow sees the step failure as an error, which it can handle with try/catch
239
+ - **Recovery:** The step-side `resumeHook` call is best-effort — if it throws, the failure is swallowed. Convergence comes from the next replay: when the step's reviver re-reads the stream, it sees the abort packet and calls `resumeHook` again. There's no in-process retry loop; the dual-mechanism design relies on either the stream or the hook eventually landing.
240
+
241
+ ### Hook Succeeds, Stream Fails
242
+
243
+ - Workflow sees `signal.aborted === true` on replay (hook worked)
244
+ - Steps don't receive real-time cancellation (stream failed) — they run to completion
245
+ - On the next suspension, the workflow knows the abort happened and can stop calling more steps
246
+ - **Recovery:** Natural convergence — no active harm, just missed real-time cancellation for in-flight steps.
247
+
248
+ ### Both Fail
249
+
250
+ - Abort is lost — no propagation
251
+ - No crash or corruption — the system continues as if abort was never called
252
+ - **Recovery:** The caller can retry the abort. If using a hook for external cancellation, the hook's retry semantics apply.
253
+
254
+ The dual mechanism provides natural resilience — if either one succeeds, the system converges on the correct state.
255
+
256
+ ## `AbortSignal.timeout()` in Workflow VM
257
+
258
+ `AbortSignal.timeout()` is blocked in the workflow VM because it depends on real-time timers, which break deterministic replay. Calling it throws an error with a suggestion to use `sleep()` + `AbortController` instead. See [AbortSignal.timeout() in Workflow](/docs/errors/abort-signal-timeout-in-workflow) for details.
259
+
260
+ `AbortSignal.timeout()` works normally in step functions, which have full Node.js runtime access.
261
+
262
+ ## Request.signal
263
+
264
+ A `Request`'s `.signal` is forwarded by the `Request` reducer in two cases:
265
+
266
+ 1. **The signal is already aborted.** The serialized payload preserves `aborted: true` and the abort `reason`, so the deserialized step sees the cancellation that happened before the boundary.
267
+ 2. **The signal is workflow-managed** (i.e., it has the `ABORT_STREAM_NAME` symbol — produced by a workflow-context `AbortController`). Its hook + stream backing carries through, and the deserialized step listens on the stream as usual.
268
+
269
+ Plain non-aborted native signals are intentionally dropped, including the auto-generated signal that `new Request(url)` synthesizes when no `signal` is passed. Forwarding every Request signal would mint stream infrastructure for the throwaway auto-signals on every Request, even ones the caller never intended to use for cancellation.
270
+
271
+ If you want cross-boundary cancellation through a `Request`, build it with a signal from a workflow-context `AbortController`:
272
+
273
+ {/* @skip-typecheck: conceptual snippet */}
274
+ ```typescript
275
+ const controller = new AbortController(); // in workflow function
276
+ const req = new Request(url, { signal: controller.signal });
277
+ await fetchStep(req); // signal carries through
278
+ controller.abort(); // step-side fetch sees the abort
279
+ ```
280
+
281
+ ## Related Documentation
282
+
283
+ - [Cancellation](/docs/foundations/cancellation) — Usage patterns and API
284
+ - [Event Sourcing](/docs/how-it-works/event-sourcing) — How the event log works
285
+ - [Hooks](/docs/foundations/hooks) — The hook primitive
286
+ - [Streaming](/docs/foundations/streaming) — The stream primitive
287
+ - [Serialization](/docs/foundations/serialization) — Serializable types
@@ -53,18 +53,20 @@ flowchart LR
53
53
  A["Source Code<br/>with directives"] --> B["Step Mode"]
54
54
  A --> C["Workflow Mode"]
55
55
  A --> D["Client Mode"]
56
- B --> E["step.js<br/>(Step Execution)"]
57
- C --> F["flow.js<br/>(Workflow Execution)"]
56
+ B --> E["Step registration bundle"]
57
+ C --> F["Workflow bundle"]
58
+ E --> H["Combined flow handler"]
59
+ F --> H
58
60
  D --> G["Your App Code<br/>(Enables `start`)"]
59
61
  ```
60
62
 
61
63
  ### Comparison Table
62
64
 
63
- | Mode | Used In | Purpose | Output API Route | Required? |
64
- |----------|------------|--------------------------------|------------------------------------|-----------|
65
- | Step | Build time | Bundles step handlers | `.well-known/workflow/v1/step` | Yes |
66
- | Workflow | Build time | Bundles workflow orchestrators | `.well-known/workflow/v1/flow` | Yes |
67
- | Client | Build/Runtime | Provides workflow IDs and types to `start` | Your application code | Optional* |
65
+ | Mode | Used In | Purpose | Runtime role | Required? |
66
+ |----------|------------|--------------------------------|--------------|-----------|
67
+ | Step | Build time | Registers executable step functions | Imported by the combined flow handler | Yes |
68
+ | Workflow | Build time | Bundles workflow orchestrators | Executed by `.well-known/workflow/v1/flow` | Yes |
69
+ | Client | Build/Runtime | Provides workflow IDs and types to `start` | Your application code | Optional* |
68
70
 
69
71
  \* Client mode is **recommended** for better developer experience—it provides automatic ID generation and type safety. Without it, you must manually construct workflow IDs or use the build manifest.
70
72
 
@@ -73,7 +75,7 @@ flowchart LR
73
75
  <Tabs items={["Step Mode", "Workflow Mode", "Client Mode"]}>
74
76
  <Tab value="Step Mode">
75
77
 
76
- **Step Mode** creates the step execution bundle served at `/.well-known/workflow/v1/step`.
78
+ **Step Mode** creates a registration bundle that the combined flow handler imports. It is not an HTTP route.
77
79
 
78
80
  **Input:**
79
81
 
@@ -193,7 +195,7 @@ handleUserSignup.workflowId = "workflow//workflows/user.js//handleUserSignup"; /
193
195
  - The `workflowId` property is added (same as workflow mode)
194
196
  - Step functions are not transformed in client mode
195
197
 
196
- **Why this transformation?** Workflow functions cannot be called directly—they must be started using [`start()`](/docs/api-reference/workflow-api/start). The error prevents accidental direct execution while the `workflowId` property allows the `start()` function to identify which workflow to launch.
198
+ **Why this transformation?** Workflow functions cannot be called directly from application code—they must be started using [`start()`](/docs/api-reference/workflow-api/start). The error prevents accidental direct execution while the `workflowId` property allows the `start()` function to identify which workflow to launch.
197
199
 
198
200
  The IDs are generated exactly like in workflow mode to ensure they can be directly referenced at runtime.
199
201
 
@@ -211,7 +213,7 @@ The IDs are generated exactly like in workflow mode to ensure they can be direct
211
213
 
212
214
  ## Generated Files
213
215
 
214
- When you build your application, the Workflow SDK generates three handler files in `.well-known/workflow/v1/`:
216
+ When you build your application, the Workflow SDK generates a combined flow handler, an internal step registration bundle, and a webhook handler. Exact filenames vary by framework.
215
217
 
216
218
  ### `flow.js`
217
219
 
@@ -245,15 +247,17 @@ Most invalid patterns cause **build-time errors**, catching issues before deploy
245
247
  **Why a VM?** Workflow functions must be deterministic to support replay. The VM sandbox prevents accidental use of non-deterministic APIs or side effects. All side effects should be performed in [step functions](/docs/foundations/workflows-and-steps#step-functions) instead.
246
248
  </Callout>
247
249
 
248
- ### `step.js`
250
+ ### `__step_registrations.js`
249
251
 
250
- Contains all step functions transformed in **step mode**. This file is imported by your framework to handle step execution requests at `POST /.well-known/workflow/v1/step`.
252
+ Contains all step functions transformed in **step mode**. The combined flow handler imports this module for its registration side effects.
251
253
 
252
254
  **What it does:**
253
255
 
254
- - Exports a `POST` handler that accepts Web standard `Request` objects
255
- - Executes individual steps with full runtime access
256
- - Returns step results to the orchestration layer
256
+ - Adds step functions to the runtime step registry
257
+ - Keeps step bodies in the full host runtime
258
+ - Makes registered steps available when a flow queue message includes `stepId` and `stepName`
259
+
260
+ This module must not be exposed as an HTTP endpoint.
257
261
 
258
262
  ### `webhook.js`
259
263
 
@@ -321,7 +325,7 @@ The compiler generates stable IDs for workflows and steps based on file paths an
321
325
  - **Portable**: Works across different runtimes and deployments
322
326
 
323
327
  <Callout type="info">
324
- Although IDs can change when files are moved or functions are renamed, Workflow SDK function assume atomic versioning in the World. This means changing IDs won't break old workflows from running, but will prevent run from being upgraded and will cause your workflow/step names to change in the observability across deployments.
328
+ Although IDs can change when files are moved or functions are renamed, Workflow SDK functions assume [atomic versioning](/docs/foundations/versioning) in the World. This means changing IDs won't break old workflows from running, but will prevent runs from being upgraded and will cause your workflow/step names to change in observability across deployments.
325
329
  </Callout>
326
330
 
327
331
  ## Framework Integration
@@ -336,7 +340,7 @@ These transformations are framework-agnostic—they output standard JavaScript t
336
340
 
337
341
  If you need to debug transformation issues, you can inspect the generated files:
338
342
 
339
- 1. **Look in `.well-known/workflow/v1/`**: Check the generated `flow.js`, `step.js`,`webhook.js`, and other emitted debug files.
343
+ 1. **Inspect the generated output**: Check the combined flow handler, step registration bundle, webhook handler, and emitted debug files.
340
344
  2. **Check build logs**: Most frameworks log transformation activity during builds
341
345
  3. **Verify directives**: Ensure `"use workflow"` and `"use step"` are the first statements in functions
342
346
  4. **Check file locations**: Transformations only apply to files in configured source directories
@@ -7,7 +7,7 @@ prerequisites:
7
7
  - /docs/how-it-works/event-sourcing
8
8
  related:
9
9
  - /docs/observability
10
- - /docs/deploying/world/vercel-world
10
+ - /worlds/vercel
11
11
  ---
12
12
 
13
13
  <Callout>
@@ -38,7 +38,7 @@ Metadata such as workflow names, step names, entity IDs, timestamps, and lifecyc
38
38
 
39
39
  Each workflow run is encrypted with its own unique key, provided by the `World` implementation via `getEncryptionKeyForRun()`. How the key is generated and stored is up to the `World`.
40
40
 
41
- For example, the [Vercel World](/docs/deploying/world/vercel-world) provides unique keys per run and execution environment, ensuring that a given run can only decrypt data from that run itself.
41
+ For example, the [Vercel World](/worlds/vercel) provides unique keys per run and execution environment, ensuring that a given run can only decrypt data from that run itself.
42
42
 
43
43
  ### Encryption Algorithm
44
44
 
@@ -105,8 +105,8 @@ To add encryption support to a custom `World`:
105
105
  import type { WorkflowRun, World } from "@workflow/world";
106
106
 
107
107
  export const getEncryptionKeyForRun: World["getEncryptionKeyForRun"] = async (
108
- run,
109
- context
108
+ run: WorkflowRun | string,
109
+ context?: Record<string, unknown>
110
110
  ) => {
111
111
  const runId = typeof run === "string" ? run : run.runId;
112
112
  const deploymentId =
@@ -127,4 +127,4 @@ async function lookupRunKey(
127
127
  }
128
128
  ```
129
129
 
130
- The [Vercel World](/docs/deploying/world/vercel-world) implementation uses HKDF derivation from a deployment-scoped key, but any consistent key management scheme will work.
130
+ The [Vercel World](/worlds/vercel) implementation uses HKDF derivation from a deployment-scoped key, but any consistent key management scheme will work.
@@ -121,15 +121,15 @@ flowchart TD
121
121
 
122
122
  **Hook states:**
123
123
 
124
- - `active`: Ready to receive payloads (hook exists in storage)
125
- - `disposed`: No longer accepting payloads (hook is deleted from storage)
124
+ - `active`: Ready to receive payloads
125
+ - `disposed`: No longer accepting payloads
126
126
  - `conflicted`: Hook creation failed because the token is already in use by another workflow
127
127
 
128
- Unlike other entities, hooks don't have a `status` field—the states above are conceptual. An "active" hook is one that exists in storage, while "disposed" means the hook has been deleted. When a `hook_disposed` event is created, the hook record is removed rather than updated.
128
+ Unlike other entities, hooks don't have a `status` field—the states above are conceptual. When a `hook_disposed` event is created, the hook record is removed rather than updated.
129
129
 
130
- While a hook is active, its token is reserved and cannot be used by other workflows. If a workflow attempts to create a hook with a token that is already in use by another active hook, a `hook_conflict` event is recorded instead of `hook_created`. This causes the hook's promise to reject with a `HookConflictError`, which you can detect with `HookConflictError.is(error)`. See the [hook-conflict error](/docs/errors/hook-conflict) documentation for more details.
130
+ While a hook is active, its token is reserved and cannot be used by other workflows. If a workflow attempts to create a hook with a token reserved by another run either by an active hook or by `experimental_minRetention` after its run ended — a `hook_conflict` event is recorded instead of `hook_created`. Current worlds include the token and the run ID that owns it, though older persisted events or world implementations may only include the token. This causes `hook.getConflict()` to resolve with the conflicting run and the hook's payload promise to reject with a `HookConflictError`, which you can detect with `HookConflictError.is(error)`. See the [hook-conflict error](/docs/errors/hook-conflict) documentation for more details.
131
131
 
132
- When a hook is disposed (either explicitly or when its workflow completes), the token is released and can be claimed by future workflows. Hooks are automatically disposed when a workflow reaches a terminal state (`completed`, `failed`, or `cancelled`). The `hook_disposed` event is only needed for explicit disposal before workflow completion.
132
+ When a workflow ends, its Hooks can no longer be resumed. They are normally removed and their tokens become available again. With `experimental_minRetention`, a Hook remains readable and its token remains unavailable until retention ends. A `hook_disposed` event removes the Hook and makes its token available immediately.
133
133
 
134
134
  See [Hooks & Webhooks](/docs/foundations/hooks) for more on how hooks and webhooks work.
135
135
 
@@ -188,7 +188,7 @@ Events are categorized by the entity type they affect. Each event contains metad
188
188
  | Event | Description |
189
189
  |-------|-------------|
190
190
  | `hook_created` | Creates a new hook in `active` state. Contains the hook token and optional metadata. |
191
- | `hook_conflict` | Records that hook creation failed because the token is already in use by another active hook. The hook is not created, and awaiting the hook will reject with a `HookConflictError`. |
191
+ | `hook_conflict` | Records that hook creation failed because another run owns the token. Contains the token and, for current worlds, the owner's run ID. The hook is not created: `hook.getConflict()` resolves with the conflicting run, and awaiting the hook payload rejects with a `HookConflictError`. |
192
192
  | `hook_received` | Records that a payload was delivered to the hook. The hook remains `active` and can receive more payloads. |
193
193
  | `hook_disposed` | Deletes the hook from storage (conceptually transitioning to `disposed` state). The token is released for reuse by future workflows. |
194
194