workflow 5.0.0-beta.3 → 5.0.0-beta.31

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 (176) 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 +1 -1
  4. package/dist/api.d.ts +5 -1
  5. package/dist/api.d.ts.map +1 -1
  6. package/dist/api.js +12 -2
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +6 -1
  10. package/dist/internal/builtins.d.ts +17 -0
  11. package/dist/internal/builtins.d.ts.map +1 -1
  12. package/dist/internal/builtins.js +65 -1
  13. package/dist/observability.d.ts +1 -1
  14. package/dist/observability.js +2 -2
  15. package/dist/runtime.d.ts +2 -1
  16. package/dist/runtime.d.ts.map +1 -1
  17. package/dist/runtime.js +5 -2
  18. package/docs/ai/chat-session-modeling.mdx +7 -3
  19. package/docs/ai/defining-tools.mdx +2 -2
  20. package/docs/ai/index.mdx +28 -23
  21. package/docs/ai/message-queueing.mdx +10 -10
  22. package/docs/ai/resumable-streams.mdx +9 -1
  23. package/docs/api-reference/index.mdx +24 -0
  24. package/docs/api-reference/meta.json +8 -0
  25. package/docs/api-reference/vitest/index.mdx +28 -7
  26. package/docs/api-reference/workflow/create-hook.mdx +38 -0
  27. package/docs/api-reference/workflow/create-webhook.mdx +1 -0
  28. package/docs/api-reference/workflow/fetch.mdx +5 -0
  29. package/docs/api-reference/workflow/index.mdx +3 -0
  30. package/docs/api-reference/workflow/set-attributes.mdx +65 -0
  31. package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
  32. package/docs/api-reference/workflow-ai/index.mdx +2 -2
  33. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +44 -1
  34. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +7 -0
  35. package/docs/api-reference/workflow-api/get-run.mdx +25 -0
  36. package/docs/api-reference/workflow-api/index.mdx +6 -8
  37. package/docs/api-reference/workflow-api/resume-hook.mdx +57 -0
  38. package/docs/api-reference/workflow-api/start.mdx +13 -5
  39. package/docs/api-reference/workflow-astro/index.mdx +18 -0
  40. package/docs/api-reference/workflow-astro/meta.json +4 -0
  41. package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
  42. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
  43. package/docs/api-reference/workflow-errors/index.mdx +85 -0
  44. package/docs/api-reference/workflow-errors/meta.json +5 -0
  45. package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
  46. package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
  47. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
  48. package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
  49. package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
  50. package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
  51. package/docs/api-reference/workflow-nest/index.mdx +31 -0
  52. package/docs/api-reference/workflow-nest/meta.json +9 -0
  53. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
  54. package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
  55. package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
  56. package/docs/api-reference/workflow-next/with-workflow.mdx +56 -2
  57. package/docs/api-reference/workflow-nitro/index.mdx +60 -0
  58. package/docs/api-reference/workflow-nuxt/index.mdx +48 -0
  59. package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
  60. package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
  61. package/docs/api-reference/workflow-observability/index.mdx +64 -0
  62. package/docs/api-reference/workflow-observability/meta.json +11 -0
  63. package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
  64. package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
  65. package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
  66. package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
  67. package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
  68. package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
  69. package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +7 -10
  70. package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
  71. package/docs/api-reference/workflow-runtime/index.mdx +43 -0
  72. package/docs/api-reference/workflow-runtime/meta.json +12 -0
  73. package/docs/api-reference/workflow-runtime/set-world.mdx +49 -0
  74. package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +42 -0
  75. package/docs/api-reference/{workflow-api → workflow-runtime}/world/index.mdx +5 -8
  76. package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
  77. package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +4 -2
  78. package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +11 -4
  79. package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +2 -2
  80. package/docs/api-reference/workflow-serde/index.mdx +0 -1
  81. package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +1 -2
  82. package/docs/api-reference/workflow-serde/workflow-serialize.mdx +1 -2
  83. package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
  84. package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
  85. package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
  86. package/docs/api-reference/workflow-vite/index.mdx +18 -0
  87. package/docs/api-reference/workflow-vite/meta.json +4 -0
  88. package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
  89. package/docs/changelog/attributes-mvp.mdx +380 -0
  90. package/docs/changelog/eager-processing.mdx +269 -0
  91. package/docs/changelog/index.mdx +2 -1
  92. package/docs/changelog/lazy-event-creation.md +127 -0
  93. package/docs/changelog/meta.json +8 -1
  94. package/docs/changelog/resilient-start.mdx +31 -283
  95. package/docs/changelog/step-message-ownership.mdx +360 -0
  96. package/docs/changelog/turbo-mode.md +87 -0
  97. package/docs/configuration/build-and-diagnostics.mdx +51 -0
  98. package/docs/configuration/cli-and-web-ui.mdx +154 -0
  99. package/docs/configuration/framework-options.mdx +165 -0
  100. package/docs/configuration/index.mdx +32 -0
  101. package/docs/configuration/meta.json +12 -0
  102. package/docs/configuration/runtime-tuning.mdx +156 -0
  103. package/docs/configuration/worlds.mdx +228 -0
  104. package/docs/cookbook/advanced/child-workflows.mdx +199 -256
  105. package/docs/cookbook/advanced/meta.json +1 -1
  106. package/docs/cookbook/advanced/publishing-libraries.mdx +13 -12
  107. package/docs/cookbook/advanced/serializable-steps.mdx +8 -4
  108. package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
  109. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +31 -76
  110. package/docs/cookbook/agent-patterns/durable-agent.mdx +11 -143
  111. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +7 -3
  112. package/docs/cookbook/common-patterns/idempotency.mdx +36 -52
  113. package/docs/cookbook/common-patterns/rate-limiting.mdx +1 -1
  114. package/docs/cookbook/common-patterns/saga.mdx +2 -2
  115. package/docs/cookbook/common-patterns/scheduling.mdx +8 -0
  116. package/docs/cookbook/common-patterns/timeouts.mdx +2 -1
  117. package/docs/cookbook/common-patterns/workflow-composition.mdx +15 -16
  118. package/docs/cookbook/index.mdx +3 -3
  119. package/docs/cookbook/integrations/ai-sdk.mdx +60 -28
  120. package/docs/cookbook/integrations/chat-sdk.mdx +13 -0
  121. package/docs/cookbook/integrations/sandbox.mdx +13 -0
  122. package/docs/deploying/building-a-world.mdx +1 -1
  123. package/docs/deploying/index.mdx +1 -0
  124. package/docs/deploying/world/local-world.mdx +23 -6
  125. package/docs/deploying/world/postgres-world.mdx +79 -13
  126. package/docs/deploying/world/vercel-world.mdx +47 -12
  127. package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
  128. package/docs/errors/corrupted-event-log.mdx +5 -5
  129. package/docs/errors/hook-conflict.mdx +56 -4
  130. package/docs/errors/index.mdx +1 -35
  131. package/docs/errors/replay-divergence.mdx +27 -0
  132. package/docs/errors/runtime-decryption-failed.mdx +77 -0
  133. package/docs/errors/step-executed-multiple-times.mdx +23 -0
  134. package/docs/errors/step-not-registered.mdx +1 -1
  135. package/docs/foundations/cancellation.mdx +459 -0
  136. package/docs/foundations/errors-and-retries.mdx +7 -3
  137. package/docs/foundations/hooks.mdx +29 -0
  138. package/docs/foundations/idempotency.mdx +236 -11
  139. package/docs/foundations/index.mdx +1 -23
  140. package/docs/foundations/meta.json +3 -1
  141. package/docs/foundations/serialization.mdx +77 -41
  142. package/docs/foundations/starting-workflows.mdx +5 -1
  143. package/docs/foundations/streaming.mdx +14 -23
  144. package/docs/foundations/versioning.mdx +263 -0
  145. package/docs/getting-started/astro.mdx +6 -0
  146. package/docs/getting-started/index.mdx +6 -7
  147. package/docs/getting-started/meta.json +1 -0
  148. package/docs/getting-started/nestjs.mdx +9 -0
  149. package/docs/getting-started/next.mdx +5 -3
  150. package/docs/getting-started/nitro.mdx +22 -0
  151. package/docs/getting-started/sveltekit.mdx +6 -0
  152. package/docs/getting-started/tanstack-start.mdx +241 -0
  153. package/docs/how-it-works/cancellation.mdx +287 -0
  154. package/docs/how-it-works/code-transform.mdx +2 -2
  155. package/docs/how-it-works/encryption.mdx +2 -2
  156. package/docs/how-it-works/event-sourcing.mdx +2 -2
  157. package/docs/how-it-works/meta.json +2 -1
  158. package/docs/internal/index.mdx +21 -0
  159. package/docs/internal/meta.json +10 -0
  160. package/docs/internal/nitro-native-build.mdx +38 -0
  161. package/docs/internal/nitro-web-ui.mdx +24 -0
  162. package/docs/internal/serializable-abort-controller.mdx +148 -0
  163. package/docs/meta.json +1 -1
  164. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +7 -12
  165. package/docs/migration-guides/migrating-from-inngest.mdx +7 -17
  166. package/docs/migration-guides/migrating-from-temporal.mdx +6 -11
  167. package/docs/migration-guides/migrating-from-trigger-dev.mdx +8 -17
  168. package/docs/observability/attributes.mdx +81 -0
  169. package/docs/observability/index.mdx +18 -1
  170. package/docs/observability/meta.json +1 -1
  171. package/docs/observability/tracing.mdx +119 -0
  172. package/docs/testing/index.mdx +2 -2
  173. package/package.json +14 -13
  174. package/docs/api-reference/workflow-api/world/meta.json +0 -4
  175. package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
  176. package/docs/cookbook/advanced/distributed-abort-controller.mdx +0 -318
@@ -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
@@ -1,70 +1,19 @@
1
1
  ---
2
2
  title: Agent Cancellation
3
- description: Cancel a running agent from the outside — either immediately via run.cancel() or gracefully via a stop signal hook.
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
4
  type: guide
5
- summary: Two patterns for cancelling a running agent Hard Cancellation via getRun(runId).cancel() for forced termination, or Stop Signal via a hook + Promise.race for a clean exit with cleanup and final stream notification.
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
6
  ---
7
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. Two patterns are available depending on whether you need the agent to exit cleanly or just need the run to stop: **Hard Cancellation** via `getRun(runId).cancel()` for immediate forced termination, or **Stop Signal** via a hook + `Promise.race` for a graceful exit that runs cleanup and notifies streaming clients before returning.
9
-
10
- ## When to use this
11
-
12
- * **Chat stop buttons** — let users cancel a long-running agent from the browser
13
- * **Admin cancellation** — stop an agent from a different process or API
14
- * **Timeout fallback** — combine with `sleep()` to auto-stop after a deadline
15
-
16
- ## Choosing an approach
17
-
18
- Pick the option that matches what your endpoint needs to deliver to the caller:
19
-
20
- * **Hard Cancellation** — terminates the run immediately with no opportunity for cleanup or client notification. A single line of code, but the workflow throws `WorkflowRunCancelledError` and any streaming clients see an abrupt connection close.
21
- * **Stop Signal** — the workflow exits as soon as the hook fires, runs any pending cleanup, emits a final `data-stopped` part to the stream so the client can render cleanly, and returns a real result.
22
-
23
- The trade-offs at a glance:
24
-
25
- | | Hard Cancellation | Stop Signal |
26
- | --- | --- | --- |
27
- | Mechanism | `getRun(runId).cancel()` | Hook + `Promise.race` |
28
- | Speed to terminate | Immediate | At the next `await` boundary in the workflow |
29
- | Runs `finally` / cleanup | No | Yes |
30
- | Final stream notification | No (abrupt close) | Yes (`data-stopped` part) |
31
- | `run.returnValue` | Throws `WorkflowRunCancelledError` | Returns the workflow's result |
32
- | Code complexity | One line | Hook + race + signal step |
33
- | Best for | Stuck or unresponsive runs, forced termination | User-facing stop, admin cancel, timeouts |
34
-
35
- ## Hard Cancellation
36
-
37
- Call `.cancel()` on a run to terminate it immediately:
38
-
39
- ```typescript lineNumbers
40
- import { getRun } from "workflow/api";
41
-
42
- export async function POST(
43
- _request: Request,
44
- { params }: { params: Promise<{ runId: string }> }
45
- ) {
46
- const { runId } = await params;
47
- await getRun(runId).cancel(); // [!code highlight]
48
- return Response.json({ success: true });
49
- }
50
- ```
51
-
52
- This is an abrupt termination — the run is stopped mid-step with no opportunity to exit cleanly:
53
-
54
- * **No cleanup runs** — `finally` blocks, defer-style step cleanup, and any logic after the current step are all skipped
55
- * **No final notification to the client** — the writable closes abruptly, so a streaming UI just sees the connection drop with no `data-stopped` part to render a clean ending
56
- * **`run.returnValue` throws** — anyone awaiting the result receives [`WorkflowRunCancelledError`](/docs/api-reference/workflow-errors/workflow-run-cancelled-error) instead of a meaningful payload
57
- * **Underlying step keeps running** — same caveat as the Stop Signal pattern below: the model stream or HTTP call inside the current step continues to completion in the background
58
-
59
- Hard Cancellation is the appropriate choice when the run is stuck or unresponsive, has exceeded its expected runtime, or you don't need a clean exit. For everything else — chat stop buttons, admin "stop" actions, timeout fallbacks — you typically want the Stop Signal pattern: the agent finishes its current step, emits a final stream part so the client renders a clean ending, and returns a real result.
60
-
61
- ## Stop Signal
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.
62
9
 
63
10
  <Callout type="warn">
64
- **Limitation:** This pattern does not cancel the underlying model stream. The agent step writing to the writable continues running in the background until it completes — tokens generated after the stop signal are still produced (and billed by your model provider). What this pattern *does* is exit the workflow function as soon as the hook fires and emit a `data-stopped` part so the client can stop rendering. For hard cross-process cancellation that signals the inner step to bail out, see [Distributed Abort Controller](/cookbook/advanced/distributed-abort-controller).
11
+ This recipe uses the deprecated `DurableAgent` API. For new agents, use AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) and follow the [migration guide](https://ai-sdk.dev/v7/docs/agents/workflow-agent#migrating-from-durableagent). The cancellation patterns here (`run.cancel()`, stop-signal hook + `Promise.race`, `AbortController`) apply to either API.
65
12
  </Callout>
66
13
 
67
- ### Example
14
+ ## Pattern
15
+
16
+ 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.
68
17
 
69
18
  ```typescript lineNumbers
70
19
  import { DurableAgent } from "@workflow/ai/agent";
@@ -88,7 +37,7 @@ async function analyzeData({ topic }: { topic: string }) {
88
37
  return { summary: `Analysis of ${topic}: significant developments found.`, confidence: 0.85 };
89
38
  }
90
39
 
91
- async function emitStopSignal(details: { reason?: string }) { // [!code highlight]
40
+ async function emitStopSignal(details: { reason?: string }) {
92
41
  "use step";
93
42
  const writer = getWritable<UIMessageChunk>().getWriter();
94
43
  try {
@@ -102,7 +51,8 @@ export async function stoppableAgent(messages: ModelMessage[]) {
102
51
  "use workflow";
103
52
 
104
53
  const { workflowRunId } = getWorkflowMetadata();
105
- const hook = stopHook.create({ token: `stop:${workflowRunId}` }); // [!code highlight]
54
+ const controller = new AbortController(); // [!code highlight]
55
+ const hook = stopHook.create({ token: `stop:${workflowRunId}` });
106
56
 
107
57
  const agent = new DurableAgent({
108
58
  model: "anthropic/claude-haiku-4.5",
@@ -121,15 +71,23 @@ export async function stoppableAgent(messages: ModelMessage[]) {
121
71
  },
122
72
  });
123
73
 
124
- const result = await Promise.race([ // [!code highlight]
74
+ const result = await Promise.race([
125
75
  agent
126
- .stream({ messages, writable: getWritable<UIMessageChunk>(), maxSteps: 15 })
76
+ .stream({
77
+ messages,
78
+ writable: getWritable<UIMessageChunk>(),
79
+ abortSignal: controller.signal, // [!code highlight]
80
+ maxSteps: 15,
81
+ })
127
82
  .then((r) => ({ type: "complete" as const, messages: r.messages })),
128
- hook.then(({ reason }) => ({ type: "stopped" as const, reason })), // [!code highlight]
83
+ hook.then(({ reason }) => {
84
+ controller.abort(reason); // [!code highlight]
85
+ return { type: "stopped" as const, reason };
86
+ }),
129
87
  ]);
130
88
 
131
89
  if (result.type === "stopped") {
132
- await emitStopSignal({ reason: result.reason }); // [!code highlight]
90
+ await emitStopSignal({ reason: result.reason });
133
91
  }
134
92
 
135
93
  return result;
@@ -148,7 +106,7 @@ export async function POST(
148
106
  const { runId } = await params;
149
107
  const { reason } = await request.json();
150
108
 
151
- await stopHook.resume(`stop:${runId}`, { // [!code highlight]
109
+ await stopHook.resume(`stop:${runId}`, {
152
110
  reason: reason || "User requested stop",
153
111
  });
154
112
 
@@ -180,13 +138,12 @@ export function StopButton({ runId }: { runId: string }) {
180
138
 
181
139
  ## How it works
182
140
 
183
- 1. A hook is created with token `stop:${workflowRunId}` when the workflow starts
184
- 2. `Promise.race` runs the agent stream and the stop hook concurrently
185
- 3. When the stop API resumes the hook, the race resolves immediately — the workflow exits
186
- 4. Before returning, `emitStopSignal` writes a `data-stopped` part to the stream so the client knows the agent was stopped (not just disconnected)
187
- 5. The client detects `data-stopped` and updates the UI accordingly
188
-
189
- This is the same pattern used by the [Distributed Abort Controller](/cookbook/advanced/distributed-abort-controller) — race a long-running operation against a hook signal.
141
+ 1. An `AbortController` is created at the start of the workflow
142
+ 2. A hook is created with token `stop:${workflowRunId}`
143
+ 3. `Promise.race` runs the agent stream and the stop hook concurrently
144
+ 4. The agent receives `controller.signal` when aborted, the underlying model stream is cancelled
145
+ 5. When the stop API resumes the hook, `controller.abort()` is called the race resolves and the workflow exits
146
+ 6. `emitStopSignal` writes a `data-stopped` part to the stream so the client renders a clean stop state
190
147
 
191
148
  ## Adapting this
192
149
 
@@ -194,12 +151,10 @@ This is the same pattern used by the [Distributed Abort Controller](/cookbook/ad
194
151
  * **Audit logging** — include a `reason` field in the stop schema to record who stopped and why
195
152
  * **Cross-process** — the hook token is deterministic, so any process can call `stopHook.resume()` with the run ID
196
153
  * **Step limits** — combine with `maxSteps` on the agent to cap execution even without manual stop
197
- * **Hard Cancellation as a fallback** — wire your stop endpoint to fall back to `getRun(runId).cancel()` if the hook resume errors with `not found` / `expired` (for example, the hook was already consumed). This guarantees the run is terminated even when the Stop Signal path is unavailable.
198
154
 
199
155
  ## Key APIs
200
156
 
201
157
  * [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook for the stop signal
202
158
  * [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata) — access the run ID for deterministic hook tokens
203
- * [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream a stop notification to the client
204
- * [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — the agent that gets raced against the stop hook
205
- * [`getRun()`](/docs/api-reference/workflow-api/get-run) — entry point for Hard Cancellation: `getRun(runId).cancel()`
159
+ * [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream output and the stop notification to the client
160
+ * [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) — AI SDK's durable agent that respects the abort signal (replaces `DurableAgent`)
@@ -1,150 +1,18 @@
1
1
  ---
2
- title: Durable Agent
3
- description: Replace a stateless AI agent with a durable one that survives crashes, retries tool calls, and streams output.
2
+ title: DurableAgent is now WorkflowAgent
3
+ description: Use AI SDK v7's WorkflowAgent for durable, resumable AI agents.
4
4
  type: guide
5
- summary: Convert an AI SDK Agent into a DurableAgent backed by a workflow, with tools as retryable steps.
5
+ summary: Build durable, resumable AI agents with AI SDK v7's WorkflowAgent.
6
6
  ---
7
7
 
8
- Use this pattern to make any AI SDK agent durable. The agent becomes a workflow, tools become steps, and the framework handles retries, streaming, and state persistence automatically.
8
+ ## WorkflowAgent from AI SDK v7
9
9
 
10
- ## When to use this
10
+ Use AI SDK v7's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) for new durable agent work. It replaces `DurableAgent` and keeps the current agent pattern in the AI SDK package.
11
11
 
12
- - Any AI agent with tool calls that should survive crashes and restarts
13
- - Agents where tool calls hit external APIs that need automatic retries
14
- - Long-running agent sessions where losing progress is unacceptable
15
- - Agents that need per-step observability in the workflow event log
12
+ - Import `WorkflowAgent` from `@ai-sdk/workflow` and run it inside a `"use workflow"` function.
13
+ - Stream `ModelCallStreamPart` chunks with `getWritable()`, then convert the run stream to UI message chunks with `createModelCallToUIChunkTransform()` in your route.
14
+ - Mark tool `execute` functions with `"use step"` when they should run as durable workflow steps with retry and observability behavior.
16
15
 
17
- ## Pattern
18
-
19
- Replace `Agent` with `DurableAgent`, wrap the function in `"use workflow"`, mark each tool with `"use step"`, and stream output through `getWritable()`.
20
-
21
- ### Workflow
22
-
23
- ```typescript
24
- import { DurableAgent } from "@workflow/ai/agent";
25
- import { getWritable } from "workflow";
26
- import { z } from "zod";
27
- import type { ModelMessage, UIMessageChunk } from "ai";
28
-
29
- async function searchFlights({ from, to, date }: {
30
- from: string;
31
- to: string;
32
- date: string;
33
- }) {
34
- "use step"; // [!code highlight]
35
- const res = await fetch(
36
- `https://api.example.com/flights?from=${from}&to=${to}&date=${date}`
37
- );
38
- if (!res.ok) throw new Error(`Search failed: ${res.status}`);
39
- return res.json();
40
- }
41
-
42
- async function bookFlight({ flightId, passenger }: {
43
- flightId: string;
44
- passenger: string;
45
- }) {
46
- "use step"; // [!code highlight]
47
- const res = await fetch("https://api.example.com/bookings", {
48
- method: "POST",
49
- headers: { "Content-Type": "application/json" },
50
- body: JSON.stringify({ flightId, passenger }),
51
- });
52
- if (!res.ok) throw new Error(`Booking failed: ${res.status}`);
53
- return res.json();
54
- }
55
-
56
- async function checkWeather({ city }: { city: string }) {
57
- "use step"; // [!code highlight]
58
- const res = await fetch(`https://api.weather.com/forecast?city=${city}`);
59
- return res.json();
60
- }
61
-
62
- export async function flightAgent(messages: ModelMessage[]) {
63
- "use workflow";
64
-
65
- const agent = new DurableAgent({ // [!code highlight]
66
- model: "anthropic/claude-haiku-4.5",
67
- instructions: "You are a helpful flight booking assistant.",
68
- tools: {
69
- searchFlights: {
70
- description: "Search for available flights between two airports",
71
- inputSchema: z.object({
72
- from: z.string().describe("Departure airport code"),
73
- to: z.string().describe("Arrival airport code"),
74
- date: z.string().describe("Travel date (YYYY-MM-DD)"),
75
- }),
76
- execute: searchFlights,
77
- },
78
- bookFlight: {
79
- description: "Book a specific flight for a passenger",
80
- inputSchema: z.object({
81
- flightId: z.string().describe("Flight ID from search results"),
82
- passenger: z.string().describe("Passenger full name"),
83
- }),
84
- execute: bookFlight,
85
- },
86
- checkWeather: {
87
- description: "Check the weather forecast for a city",
88
- inputSchema: z.object({
89
- city: z.string().describe("City name"),
90
- }),
91
- execute: checkWeather,
92
- },
93
- },
94
- });
95
-
96
- const result = await agent.stream({ // [!code highlight]
97
- messages,
98
- writable: getWritable<UIMessageChunk>(), // [!code highlight]
99
- maxSteps: 10,
100
- });
101
-
102
- return { messages: result.messages };
103
- }
104
- ```
105
-
106
- ### API route
107
-
108
- ```typescript
109
- import type { UIMessage } from "ai";
110
- import { convertToModelMessages, createUIMessageStreamResponse } from "ai";
111
- import { start } from "workflow/api";
112
- import { flightAgent } from "@/app/workflows/flight-agent";
113
-
114
- export async function POST(req: Request) {
115
- const { messages }: { messages: UIMessage[] } = await req.json();
116
- const modelMessages = await convertToModelMessages(messages); // [!code highlight]
117
-
118
- const run = await start(flightAgent, [modelMessages]); // [!code highlight]
119
-
120
- return createUIMessageStreamResponse({ // [!code highlight]
121
- stream: run.readable,
122
- headers: {
123
- "x-workflow-run-id": run.runId,
124
- },
125
- });
126
- }
127
- ```
128
-
129
- ## How it works
130
-
131
- 1. **DurableAgent wraps Agent** — same API as AI SDK's `Agent`, but backed by a workflow. If the process crashes, the agent resumes from the last completed step on replay.
132
- 2. **Tools as steps** — each tool's `execute` function uses `"use step"`, giving it automatic retries, full Node.js access, and an entry in the workflow event log.
133
- 3. **Streaming** — `getWritable<UIMessageChunk>()` streams the agent's output (text chunks, tool calls, tool results) to the client in real time via `createUIMessageStreamResponse`.
134
- 4. **maxSteps** — limits the total number of LLM calls the agent can make, preventing runaway tool loops.
135
-
136
- ## Adapting to your use case
137
-
138
- - **Change the model** — replace `"anthropic/claude-haiku-4.5"` with any AI Gateway model string (e.g. `"openai/gpt-4o"`, `"anthropic/claude-sonnet-4-5"`).
139
- - **Add tools** — define a new `"use step"` function with a Zod schema. Each tool automatically gets retries and persistence.
140
- - **Workflow-level tools** — if a tool needs workflow primitives like `sleep()` or `createHook()`, omit `"use step"` so it runs in the workflow context instead.
141
- - **Multi-turn** — pass `result.messages` plus new user messages to subsequent `agent.stream()` calls for multi-turn conversations.
142
- - **Client integration** — use `useChat()` from `@ai-sdk/react` with `WorkflowChatTransport` from `@workflow/ai` for a full chat UI with reconnection support.
143
-
144
- ## Key APIs
145
-
146
- - [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
147
- - [`"use step"`](/docs/api-reference/workflow/use-step) — declares step functions with retries and full Node.js access
148
- - [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — durable wrapper around AI SDK's Agent
149
- - [`getWritable()`](/docs/api-reference/workflow/get-writable) — streams agent output to the client
150
- - [`start()`](/docs/api-reference/workflow-api/start) — starts a workflow run from an API route
16
+ <Callout type="warn">
17
+ `DurableAgent` is deprecated and remains documented for existing code only. See the [migration guide](https://ai-sdk.dev/v7/docs/agents/workflow-agent#migrating-from-durableagent), or the [`DurableAgent` API reference](/docs/api-reference/workflow-ai/durable-agent) while migrating.
18
+ </Callout>
@@ -5,6 +5,10 @@ type: guide
5
5
  summary: Use defineHook with the tool call ID to suspend an agent for human approval, with an optional timeout.
6
6
  ---
7
7
 
8
+ <Callout type="warn">
9
+ This recipe uses the deprecated `DurableAgent` API. For new agents, use AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) and follow the [migration guide](https://ai-sdk.dev/v7/docs/agents/workflow-agent#migrating-from-durableagent). The human-in-the-loop pattern here (hooks, `Promise.race`, approval gating) applies to either API.
10
+ </Callout>
11
+
8
12
  Use this pattern when an AI agent needs human confirmation before performing a consequential action like booking, purchasing, or publishing. The workflow suspends without consuming resources until the human responds.
9
13
 
10
14
  ## When to use this
@@ -247,9 +251,9 @@ const approvalResult = messages
247
251
 
248
252
  ## Key APIs
249
253
 
250
- - [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
251
- - [`"use step"`](/docs/api-reference/workflow/use-step) — declares step functions with retries
254
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) — declares the orchestrator function
255
+ - [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) — declares step functions with retries
252
256
  - [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook with schema validation
253
257
  - [`sleep()`](/docs/api-reference/workflow/sleep) — durable timeout for approval expiry
254
258
  - [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream custom data parts from steps
255
- - [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — durable agent with tool definitions
259
+ - [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) — AI SDK's durable agent (replaces `DurableAgent`)