workflow 5.0.0-beta.5 → 5.0.0-beta.51

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 (256) hide show
  1. package/README.md +68 -23
  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 +3 -3
  6. package/dist/api.d.ts.map +1 -1
  7. package/dist/api.js +5 -7
  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 +20 -3
  12. package/dist/internal/builtins.d.ts.map +1 -1
  13. package/dist/internal/builtins.js +68 -4
  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 +4 -1
  28. package/docs/ai/chat-session-modeling.mdx +176 -422
  29. package/docs/ai/defining-tools.mdx +6 -7
  30. package/docs/ai/human-in-the-loop.mdx +11 -11
  31. package/docs/ai/index.mdx +71 -75
  32. package/docs/ai/message-queueing.mdx +71 -110
  33. package/docs/ai/meta.json +1 -0
  34. package/docs/ai/resumable-streams.mdx +40 -28
  35. package/docs/ai/sleep-and-delays.mdx +10 -10
  36. package/docs/ai/streaming-updates-from-tools.mdx +6 -6
  37. package/docs/api-reference/index.mdx +25 -1
  38. package/docs/api-reference/meta.json +8 -0
  39. package/docs/api-reference/vitest/index.mdx +9 -15
  40. package/docs/api-reference/workflow/create-hook.mdx +89 -10
  41. package/docs/api-reference/workflow/create-webhook.mdx +16 -15
  42. package/docs/api-reference/workflow/define-hook.mdx +35 -33
  43. package/docs/api-reference/workflow/fatal-error.mdx +30 -8
  44. package/docs/api-reference/workflow/fetch.mdx +14 -10
  45. package/docs/api-reference/workflow/get-step-metadata.mdx +2 -2
  46. package/docs/api-reference/workflow/get-workflow-metadata.mdx +3 -3
  47. package/docs/api-reference/workflow/get-writable.mdx +7 -7
  48. package/docs/api-reference/workflow/index.mdx +4 -1
  49. package/docs/api-reference/workflow/retryable-error.mdx +1 -1
  50. package/docs/api-reference/workflow/set-attributes.mdx +61 -0
  51. package/docs/api-reference/workflow/sleep.mdx +4 -4
  52. package/docs/api-reference/workflow-ai/durable-agent.mdx +63 -101
  53. package/docs/api-reference/workflow-ai/index.mdx +5 -5
  54. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +67 -24
  55. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +26 -12
  56. package/docs/api-reference/workflow-api/get-run.mdx +43 -8
  57. package/docs/api-reference/workflow-api/index.mdx +6 -10
  58. package/docs/api-reference/workflow-api/resume-hook.mdx +73 -12
  59. package/docs/api-reference/workflow-api/resume-webhook.mdx +11 -9
  60. package/docs/api-reference/workflow-api/start.mdx +60 -13
  61. package/docs/api-reference/workflow-astro/index.mdx +18 -0
  62. package/docs/api-reference/workflow-astro/meta.json +4 -0
  63. package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
  64. package/docs/api-reference/workflow-errors/entity-conflict-error.mdx +4 -4
  65. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
  66. package/docs/api-reference/workflow-errors/hook-not-found-error.mdx +8 -8
  67. package/docs/api-reference/workflow-errors/index.mdx +88 -0
  68. package/docs/api-reference/workflow-errors/meta.json +6 -0
  69. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +68 -0
  70. package/docs/api-reference/workflow-errors/run-expired-error.mdx +2 -2
  71. package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
  72. package/docs/api-reference/workflow-errors/step-not-registered-error.mdx +5 -5
  73. package/docs/api-reference/workflow-errors/throttle-error.mdx +2 -2
  74. package/docs/api-reference/workflow-errors/too-early-error.mdx +2 -2
  75. package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
  76. package/docs/api-reference/workflow-errors/workflow-not-registered-error.mdx +5 -6
  77. package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +6 -6
  78. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +5 -5
  79. package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
  80. package/docs/api-reference/workflow-errors/workflow-run-not-found-error.mdx +4 -4
  81. package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
  82. package/docs/api-reference/workflow-errors/workflow-world-error.mdx +8 -8
  83. package/docs/api-reference/workflow-globals.mdx +14 -10
  84. package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
  85. package/docs/api-reference/workflow-nest/index.mdx +31 -0
  86. package/docs/api-reference/workflow-nest/meta.json +9 -0
  87. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
  88. package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
  89. package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
  90. package/docs/api-reference/workflow-next/with-workflow.mdx +39 -17
  91. package/docs/api-reference/workflow-nitro/index.mdx +60 -0
  92. package/docs/api-reference/workflow-nuxt/index.mdx +48 -0
  93. package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
  94. package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
  95. package/docs/api-reference/workflow-observability/index.mdx +62 -0
  96. package/docs/api-reference/workflow-observability/meta.json +11 -0
  97. package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
  98. package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
  99. package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
  100. package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
  101. package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
  102. package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
  103. package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +11 -14
  104. package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
  105. package/docs/api-reference/workflow-runtime/index.mdx +41 -0
  106. package/docs/api-reference/workflow-runtime/meta.json +12 -0
  107. package/docs/api-reference/workflow-runtime/set-world.mdx +51 -0
  108. package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +43 -0
  109. package/docs/api-reference/workflow-runtime/world/analytics.mdx +315 -0
  110. package/docs/api-reference/workflow-runtime/world/index.mdx +60 -0
  111. package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
  112. package/docs/api-reference/workflow-runtime/world/queue.mdx +88 -0
  113. package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +98 -34
  114. package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +8 -8
  115. package/docs/api-reference/workflow-serde/index.mdx +1 -2
  116. package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +3 -4
  117. package/docs/api-reference/workflow-serde/workflow-serialize.mdx +8 -8
  118. package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
  119. package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
  120. package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
  121. package/docs/api-reference/workflow-vite/index.mdx +18 -0
  122. package/docs/api-reference/workflow-vite/meta.json +4 -0
  123. package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
  124. package/docs/changelog/attributes-mvp.mdx +380 -0
  125. package/docs/changelog/batched-event-writes.mdx +79 -0
  126. package/docs/changelog/eager-processing.mdx +110 -436
  127. package/docs/changelog/index.mdx +4 -2
  128. package/docs/changelog/lazy-event-creation.md +127 -0
  129. package/docs/changelog/lazy-hook-resume.mdx +78 -0
  130. package/docs/changelog/meta.json +11 -1
  131. package/docs/changelog/resilient-resume.mdx +32 -0
  132. package/docs/changelog/resilient-start.mdx +33 -285
  133. package/docs/changelog/step-message-ownership.mdx +360 -0
  134. package/docs/changelog/turbo-mode.md +87 -0
  135. package/docs/comparisons/index.mdx +66 -0
  136. package/docs/comparisons/meta.json +11 -0
  137. package/docs/comparisons/workflow-sdk-vs-aws-agentcore.mdx +55 -0
  138. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +111 -0
  139. package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +71 -0
  140. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +102 -0
  141. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +123 -0
  142. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +104 -0
  143. package/docs/configuration/build-and-diagnostics.mdx +70 -0
  144. package/docs/configuration/cli-and-web-ui.mdx +241 -0
  145. package/docs/configuration/framework-options.mdx +165 -0
  146. package/docs/configuration/index.mdx +32 -0
  147. package/docs/configuration/meta.json +12 -0
  148. package/docs/configuration/runtime-tuning.mdx +381 -0
  149. package/docs/configuration/worlds.mdx +313 -0
  150. package/docs/cookbook/advanced/child-workflows.mdx +211 -264
  151. package/docs/cookbook/advanced/meta.json +6 -1
  152. package/docs/cookbook/advanced/publishing-libraries.mdx +65 -56
  153. package/docs/cookbook/advanced/serializable-steps.mdx +48 -68
  154. package/docs/cookbook/advanced/upgrading-workflows.mdx +199 -0
  155. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +78 -60
  156. package/docs/cookbook/agent-patterns/durable-agent.mdx +23 -131
  157. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +180 -195
  158. package/docs/cookbook/common-patterns/batching.mdx +18 -14
  159. package/docs/cookbook/common-patterns/idempotency.mdx +41 -53
  160. package/docs/cookbook/common-patterns/rate-limiting.mdx +8 -4
  161. package/docs/cookbook/common-patterns/saga.mdx +23 -19
  162. package/docs/cookbook/common-patterns/scheduling.mdx +34 -22
  163. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +29 -25
  164. package/docs/cookbook/common-patterns/timeouts.mdx +26 -21
  165. package/docs/cookbook/common-patterns/webhooks.mdx +10 -6
  166. package/docs/cookbook/common-patterns/workflow-composition.mdx +30 -27
  167. package/docs/cookbook/index.mdx +22 -21
  168. package/docs/cookbook/integrations/ai-sdk.mdx +86 -48
  169. package/docs/cookbook/integrations/chat-sdk.mdx +50 -33
  170. package/docs/cookbook/integrations/sandbox.mdx +62 -45
  171. package/docs/deploying.mdx +95 -0
  172. package/docs/errors/abort-signal-timeout-in-workflow.mdx +16 -12
  173. package/docs/errors/corrupted-event-log.mdx +39 -18
  174. package/docs/errors/deployment-mismatch.mdx +71 -0
  175. package/docs/errors/fetch-in-workflow.mdx +15 -14
  176. package/docs/errors/hook-conflict.mdx +69 -13
  177. package/docs/errors/index.mdx +2 -36
  178. package/docs/errors/node-js-module-in-workflow.mdx +9 -5
  179. package/docs/errors/replay-divergence.mdx +27 -0
  180. package/docs/errors/run-expired.mdx +85 -0
  181. package/docs/errors/runtime-decryption-failed.mdx +77 -0
  182. package/docs/errors/serialization-failed.mdx +44 -12
  183. package/docs/errors/start-invalid-workflow-function.mdx +9 -5
  184. package/docs/errors/step-executed-multiple-times.mdx +23 -0
  185. package/docs/errors/step-not-registered.mdx +6 -6
  186. package/docs/errors/timeout-in-workflow.mdx +12 -8
  187. package/docs/errors/webhook-invalid-respond-with-value.mdx +18 -18
  188. package/docs/errors/webhook-response-not-sent.mdx +20 -16
  189. package/docs/errors/workflow-not-registered.mdx +5 -5
  190. package/docs/foundations/cancellation.mdx +31 -32
  191. package/docs/foundations/errors-and-retries.mdx +42 -11
  192. package/docs/foundations/hooks.mdx +64 -35
  193. package/docs/foundations/idempotency.mdx +244 -12
  194. package/docs/foundations/index.mdx +1 -23
  195. package/docs/foundations/meta.json +2 -1
  196. package/docs/foundations/serialization.mdx +21 -22
  197. package/docs/foundations/starting-workflows.mdx +106 -30
  198. package/docs/foundations/streaming.mdx +108 -60
  199. package/docs/foundations/versioning.mdx +263 -0
  200. package/docs/foundations/workflows-and-steps.mdx +9 -9
  201. package/docs/getting-started/astro.mdx +22 -18
  202. package/docs/getting-started/express.mdx +15 -11
  203. package/docs/getting-started/fastify.mdx +15 -11
  204. package/docs/getting-started/hono.mdx +15 -11
  205. package/docs/getting-started/index.mdx +10 -3
  206. package/docs/getting-started/meta.json +3 -1
  207. package/docs/getting-started/nestjs.mdx +87 -20
  208. package/docs/getting-started/next.mdx +22 -16
  209. package/docs/getting-started/nitro.mdx +22 -18
  210. package/docs/getting-started/nuxt.mdx +15 -11
  211. package/docs/getting-started/python.mdx +190 -41
  212. package/docs/getting-started/react-router/index.mdx +33 -0
  213. package/docs/getting-started/react-router/meta.json +5 -0
  214. package/docs/getting-started/react-router/v7.mdx +237 -0
  215. package/docs/getting-started/react-router/v8.mdx +232 -0
  216. package/docs/getting-started/sveltekit.mdx +20 -16
  217. package/docs/getting-started/tanstack-start.mdx +17 -13
  218. package/docs/getting-started/vite.mdx +15 -11
  219. package/docs/how-it-works/cancellation.mdx +63 -63
  220. package/docs/how-it-works/code-transform.mdx +83 -67
  221. package/docs/how-it-works/encryption.mdx +30 -26
  222. package/docs/how-it-works/event-sourcing.mdx +125 -34
  223. package/docs/how-it-works/framework-integrations.mdx +96 -337
  224. package/docs/how-it-works/understanding-directives.mdx +22 -22
  225. package/docs/internal/index.mdx +6 -4
  226. package/docs/internal/meta.json +6 -1
  227. package/docs/internal/nitro-native-build.mdx +38 -0
  228. package/docs/internal/nitro-web-ui.mdx +24 -0
  229. package/docs/internal/serializable-abort-controller.mdx +7 -7
  230. package/docs/meta.json +3 -2
  231. package/docs/observability/attributes.mdx +134 -0
  232. package/docs/observability/index.mdx +32 -10
  233. package/docs/observability/meta.json +1 -1
  234. package/docs/observability/retention.mdx +95 -0
  235. package/docs/observability/tracing.mdx +124 -0
  236. package/docs/testing/index.mdx +36 -36
  237. package/docs/testing/server-based.mdx +10 -10
  238. package/docs/whats-new.mdx +186 -0
  239. package/package.json +17 -14
  240. package/docs/api-reference/workflow-api/world/index.mdx +0 -58
  241. package/docs/api-reference/workflow-api/world/meta.json +0 -4
  242. package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
  243. package/docs/api-reference/workflow-api/world/queue.mdx +0 -86
  244. package/docs/deploying/building-a-world.mdx +0 -251
  245. package/docs/deploying/index.mdx +0 -95
  246. package/docs/deploying/meta.json +0 -4
  247. package/docs/deploying/world/local-world.mdx +0 -84
  248. package/docs/deploying/world/meta.json +0 -4
  249. package/docs/deploying/world/postgres-world.mdx +0 -224
  250. package/docs/deploying/world/vercel-world.mdx +0 -179
  251. package/docs/migration-guides/index.mdx +0 -34
  252. package/docs/migration-guides/meta.json +0 -9
  253. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +0 -363
  254. package/docs/migration-guides/migrating-from-inngest.mdx +0 -314
  255. package/docs/migration-guides/migrating-from-temporal.mdx +0 -318
  256. package/docs/migration-guides/migrating-from-trigger-dev.mdx +0 -337
@@ -0,0 +1,199 @@
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
+ <CopyPrompt
14
+ text="Add a safe self-upgrade point to this long-running workflow. Identify the loop boundary where no step is mid-side-effect. Define a serializable state object that contains all progress needed to continue. At the boundary, call `start(self, [state], { deploymentId: &quot;latest&quot; })` or the documented replacement workflow with the carried state, then return from the old run. If upgrades should be manual, add a `defineHook()` upgrade signal and resume it from an API route with `resumeHook()` from `workflow/api`. Make the handoff idempotent so retries do not start duplicate successor runs, and verify old-to-new handoff plus duplicate prevention."
15
+ />
16
+
17
+ 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.
18
+
19
+ <Callout type="info">
20
+ 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.
21
+ </Callout>
22
+
23
+ A clean upgrade point is any spot in the workflow where:
24
+
25
+ - All in-progress side effects have completed or aren't needed by the next iteration.
26
+ - The relevant state can be serialized into the workflow's input arguments.
27
+ - The workflow can create a checkpoint after handling an external event, completing a batch, or finishing a logical phase.
28
+
29
+ There are two ways to apply this:
30
+
31
+ 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. This method needs no extra triggers, but every event incurs the respawn cost.
32
+ 2. **Upgrade on demand through 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 respawns only when an `upgradeHook` fires. A separate endpoint resumes that hook from your control plane, for example, after a deployment. This method provides more control and fewer respawns at the cost of an explicit trigger.
33
+
34
+ ### When to use each
35
+
36
+ - **Use Method 1** when iterations are short and frequent, the work is inexpensive to checkpoint, and you want shipped fixes to apply on the next event. Long-lived session workflows, such as subscriptions, queues, and finite-state machines (FSMs), that already process events one at a time fit this method.
37
+ - **Use Method 2** when iterations are infrequent or expensive, or when you need to roll out a fix to a fleet of in-flight runs after a deployment by fanning out to a control-plane endpoint. This method also fits when an upgrade should be an explicit operation rather than a side effect of handling each event.
38
+
39
+ ## Method 1: Upgrade on every iteration
40
+
41
+ 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"`.
42
+
43
+ ```typescript lineNumbers
44
+ import { defineHook, getWorkflowMetadata } from "workflow";
45
+ import { start } from "workflow/api";
46
+
47
+ declare function processItem(itemId: string): Promise<void>; // @setup
48
+
49
+ interface QueueState {
50
+ processed: number;
51
+ cursor: string | null;
52
+ }
53
+
54
+ export const nextItemHook = defineHook<{ itemId: string }>();
55
+
56
+ export async function longRunningQueue(
57
+ state: QueueState = { processed: 0, cursor: null },
58
+ ): Promise<void> {
59
+ "use workflow";
60
+
61
+ const { workflowRunId } = getWorkflowMetadata();
62
+
63
+ // Block until something fires the hook. Could be hours, days, or longer.
64
+ // Per-run hook tokens (workflowRunId) keep concurrent chains isolated.
65
+ const { itemId } = await nextItemHook.create({ token: workflowRunId }); // [!code highlight]
66
+
67
+ await processItem(itemId);
68
+
69
+ // Hand off to a fresh run on the latest deployment. THIS run ends here.
70
+ // `deploymentId: "latest"` resolves to whichever deployment is current
71
+ // when this spawn lands, NOT the deployment running this code.
72
+ await start( // [!code highlight]
73
+ longRunningQueue, // [!code highlight]
74
+ [{ processed: state.processed + 1, cursor: itemId }], // [!code highlight]
75
+ { deploymentId: "latest" }, // [!code highlight]
76
+ );
77
+ }
78
+ ```
79
+
80
+ ### Resuming the hook
81
+
82
+ Any server-side code can resume the currently-active iteration by calling `.resume()` with the run ID:
83
+
84
+ ```typescript
85
+ import { nextItemHook } from "@/workflows/long-running-queue";
86
+
87
+ export async function POST(req: Request) {
88
+ const { runId, itemId } = await req.json();
89
+
90
+ await nextItemHook.resume(runId, { itemId }); // [!code highlight]
91
+
92
+ return Response.json({ success: true });
93
+ }
94
+ ```
95
+
96
+ The caller tracks the active `runId`, such as in a database or returned from the previous iteration, and updates it whenever the chain advances.
97
+
98
+ ## Method 2: Upgrade on demand via a dedicated hook
99
+
100
+ 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.
101
+
102
+ ```typescript lineNumbers
103
+ import { defineHook, getWorkflowMetadata } from "workflow";
104
+ import { start } from "workflow/api";
105
+
106
+ declare function processItem(itemId: string): Promise<void>; // @setup
107
+
108
+ interface QueueState {
109
+ processed: number;
110
+ cursor: string | null;
111
+ }
112
+
113
+ export const nextItemHook = defineHook<{ itemId: string }>();
114
+ export const upgradeHook = defineHook<{ reason?: string }>(); // [!code highlight]
115
+
116
+ export async function longRunningQueue(
117
+ state: QueueState = { processed: 0, cursor: null },
118
+ ): Promise<void> {
119
+ "use workflow";
120
+
121
+ const { workflowRunId } = getWorkflowMetadata();
122
+
123
+ while (true) {
124
+ // Race a normal work event against the upgrade signal.
125
+ const event = await Promise.race([ // [!code highlight]
126
+ nextItemHook
127
+ .create({ token: workflowRunId })
128
+ .then((payload) => ({ kind: "work" as const, payload })),
129
+ upgradeHook // [!code highlight]
130
+ .create({ token: workflowRunId }) // [!code highlight]
131
+ .then(() => ({ kind: "upgrade" as const })), // [!code highlight]
132
+ ]);
133
+
134
+ if (event.kind === "upgrade") { // [!code highlight]
135
+ // Checkpoint current state and hand off to a fresh run
136
+ // on whatever deployment is live now. THIS run ends here.
137
+ await start(longRunningQueue, [state], { // [!code highlight]
138
+ deploymentId: "latest", // [!code highlight]
139
+ }); // [!code highlight]
140
+ return; // [!code highlight]
141
+ }
142
+
143
+ await processItem(event.payload.itemId);
144
+ state = {
145
+ processed: state.processed + 1,
146
+ cursor: event.payload.itemId,
147
+ };
148
+ }
149
+ }
150
+ ```
151
+
152
+ ### Triggering the upgrade
153
+
154
+ Expose a separate endpoint that resumes `upgradeHook` for a given run. Call it from your deployment pipeline, an admin UI, or a fan-out script that iterates over every active run after shipping a fix.
155
+
156
+ ```typescript
157
+ import { upgradeHook } from "@/workflows/long-running-queue";
158
+
159
+ export async function POST(req: Request) {
160
+ const { runId, reason } = await req.json();
161
+
162
+ // The workflow exits its loop, captures state, and respawns
163
+ // on the latest deployment.
164
+ await upgradeHook.resume(runId, { reason }); // [!code highlight]
165
+
166
+ return Response.json({ success: true });
167
+ }
168
+ ```
169
+
170
+ To upgrade a fleet of runs after a deployment, list active runs from a tracking store and call this endpoint for each run.
171
+
172
+ ## How it works
173
+
174
+ 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.
175
+ 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, so no manual `"use step"` wrapper is required.
176
+ 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.
177
+ 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.
178
+ 5. **Method 1 vs Method 2 is only 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.
179
+
180
+ ## Adapting to your use case
181
+
182
+ - **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.
183
+ - **Use stateless successors**: If the next iteration doesn't need the previous state, such as for a pure event router, call `start(longRunningQueue, [], { deploymentId: "latest" })` and skip the argument plumbing.
184
+ - **Persist state externally**: If state needs to be readable from outside the workflow for dashboards, debugging, or recovery, write it to a database in a step before spawning the next run.
185
+ - **Track the active `runId` externally**: The system that resumes the hook needs to know the current run. Capture the `runId` returned by `start()` and write it to a database keyed by a stable session identifier in a step, so resumers always look up the latest run.
186
+
187
+ ## Caveats
188
+
189
+ - **Maintain backward compatibility**: 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).
190
+ - **Keep the workflow identity stable**: The function name and file path form the workflow identity. Renaming the function or moving the file across a deployment changes the workflow ID, so the next iteration will fail to resolve.
191
+ - **Account for the gap between iterations**: The current run ends as soon as `start()` returns, and 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.
192
+ - **Track active Method 2 runs externally**: Because Method 2's runs are long-lived, the set of in-flight runs changes only 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`, update the tracked run ID once the new run reports back, as you would in Method 1.
193
+
194
+ ## Key APIs
195
+
196
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps): Marks the orchestrator function.
197
+ - [`start()`](/docs/api-reference/workflow-api/start) with [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest): Spawns the successor on the newest deployment.
198
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook): Suspends the workflow until an external event resumes it.
199
+ - [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata): Exposes `workflowRunId` for per-run hook tokens.
@@ -1,46 +1,59 @@
1
1
  ---
2
2
  title: Agent Cancellation
3
- description: Cancel a running agent from the outside using AbortSignal — a hook fires the abort, the agent step bails out of the model stream, and the client gets a clean stop notification.
3
+ description: Cancel a running WorkflowAgent from the outside using AbortSignal and a durable stop hook.
4
4
  type: guide
5
- summary: Cancel a running agent cooperatively with AbortController. A stop hook fires controller.abort(), the signal propagates into the agent step to cancel the model stream, and a data-stopped part is emitted to streaming clients before the workflow returns.
5
+ summary: Cancel a running WorkflowAgent cooperatively with AbortController so the model stream stops and the workflow can return a clean status.
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.
8
+ <CopyPrompt
9
+ text="Add cancellation to this AI SDK WorkflowAgent. For hard cancellation, expose a server route that receives `runId` and calls `getRun(runId).cancel()` from `workflow/api`. For graceful cancellation, define `stopHook` with `defineHook()` from `workflow`, create it with a stable token such as the workflow run ID, and race `WorkflowAgent.stream()` against the stop hook using `Promise.race`. Pass an `AbortController` signal to the agent, forward the tool execution signal to cancellable I/O, and wait for the agent branch to settle after aborting before returning a stopped status. Wire the UI Stop button to the route that resumes the hook or falls back to `getRun(runId).cancel()`, and verify stale run IDs are handled."
10
+ />
11
+
12
+ Cancel a running agent from the outside through a **Stop** button in a chat user interface (UI), an admin cancellation endpoint, or a timeout fallback.
9
13
 
10
14
  ## Pattern
11
15
 
12
- Create an `AbortController` in the workflow and race the agent (passing its signal) against a stop hook. When the hook fires, `controller.abort()` is called — the signal propagates into the agent step and cancels the underlying model stream. Before returning, a `data-stopped` part is written to the stream so any streaming clients can render a clean end state.
16
+ Create an `AbortController` in the workflow and race the agent (passing its signal) against a stop hook. When the hook fires, call `controller.abort()`, then wait for the agent branch to observe the signal and settle before the workflow returns. The signal cancels the underlying model stream and is passed to tool execution; each tool must forward it to cancellable I/O. The workflow return value records whether it completed or stopped; read that value through the run API or persist it in application state.
13
17
 
18
+ {/* @skip-typecheck: requires AI SDK 7 and @ai-sdk/workflow */}
14
19
  ```typescript lineNumbers
15
- import { DurableAgent } from "@workflow/ai/agent";
20
+ import { WorkflowAgent, type ModelCallStreamPart } from "@ai-sdk/workflow";
21
+ import {
22
+ isStepCount,
23
+ tool,
24
+ type ModelMessage,
25
+ type ToolExecutionOptions,
26
+ } from "ai";
16
27
  import { defineHook, getWritable, getWorkflowMetadata } from "workflow";
17
28
  import { z } from "zod";
18
- import type { ModelMessage, UIMessageChunk } from "ai";
19
29
 
20
30
  export const stopHook = defineHook({
21
31
  schema: z.object({ reason: z.string().optional() }),
22
32
  });
23
33
 
24
- async function searchWeb({ query }: { query: string }) {
25
- "use step";
26
- await new Promise((r) => setTimeout(r, 1500));
27
- return { results: [{ title: `${query} - Wikipedia`, snippet: `Overview of ${query}...` }] };
28
- }
29
-
30
- async function analyzeData({ topic }: { topic: string }) {
34
+ async function searchWeb(
35
+ { query }: { query: string },
36
+ { abortSignal }: ToolExecutionOptions<unknown>,
37
+ ) {
31
38
  "use step";
32
- await new Promise((r) => setTimeout(r, 1200));
33
- return { summary: `Analysis of ${topic}: significant developments found.`, confidence: 0.85 };
39
+ const response = await fetch(
40
+ `https://api.example.com/search?q=${encodeURIComponent(query)}`,
41
+ { signal: abortSignal }, // [!code highlight]
42
+ );
43
+ return response.json();
34
44
  }
35
45
 
36
- async function emitStopSignal(details: { reason?: string }) {
46
+ async function analyzeData(
47
+ { topic }: { topic: string },
48
+ { abortSignal }: ToolExecutionOptions<unknown>,
49
+ ) {
37
50
  "use step";
38
- const writer = getWritable<UIMessageChunk>().getWriter();
39
- try {
40
- await writer.write({ type: "data-stopped", id: "stop-signal", data: details } as UIMessageChunk);
41
- } finally {
42
- writer.releaseLock();
43
- }
51
+ const response = await fetch("https://api.example.com/analyze", {
52
+ method: "POST",
53
+ body: JSON.stringify({ topic }),
54
+ signal: abortSignal, // [!code highlight]
55
+ });
56
+ return response.json();
44
57
  }
45
58
 
46
59
  export async function stoppableAgent(messages: ModelMessage[]) {
@@ -50,47 +63,52 @@ export async function stoppableAgent(messages: ModelMessage[]) {
50
63
  const controller = new AbortController(); // [!code highlight]
51
64
  const hook = stopHook.create({ token: `stop:${workflowRunId}` });
52
65
 
53
- const agent = new DurableAgent({
54
- model: "anthropic/claude-haiku-4.5",
66
+ const agent = new WorkflowAgent({
67
+ model: "spacexai/grok-4.6",
55
68
  instructions: "You are a research assistant. Search and analyze data as needed.",
56
69
  tools: {
57
- searchWeb: {
70
+ searchWeb: tool({
58
71
  description: "Search the web for information",
59
72
  inputSchema: z.object({ query: z.string() }),
60
73
  execute: searchWeb,
61
- },
62
- analyzeData: {
74
+ }),
75
+ analyzeData: tool({
63
76
  description: "Analyze a piece of data",
64
77
  inputSchema: z.object({ topic: z.string() }),
65
78
  execute: analyzeData,
66
- },
79
+ }),
67
80
  },
68
81
  });
69
82
 
70
- const result = await Promise.race([
71
- agent
72
- .stream({
73
- messages,
74
- writable: getWritable<UIMessageChunk>(),
75
- abortSignal: controller.signal, // [!code highlight]
76
- maxSteps: 15,
77
- })
78
- .then((r) => ({ type: "complete" as const, messages: r.messages })),
79
- hook.then(({ reason }) => {
80
- controller.abort(reason); // [!code highlight]
81
- return { type: "stopped" as const, reason };
82
- }),
83
+ const agentPromise = agent.stream({
84
+ messages,
85
+ writable: getWritable<ModelCallStreamPart>(),
86
+ abortSignal: controller.signal, // [!code highlight]
87
+ stopWhen: isStepCount(15),
88
+ });
89
+
90
+ const outcome = await Promise.race([
91
+ agentPromise.then((result) => ({
92
+ type: "complete" as const,
93
+ messages: result.messages,
94
+ })),
95
+ hook.then(({ reason }) => ({
96
+ type: "stop-requested" as const,
97
+ reason,
98
+ })),
83
99
  ]);
84
100
 
85
- if (result.type === "stopped") {
86
- await emitStopSignal({ reason: result.reason });
101
+ if (outcome.type === "stop-requested") {
102
+ controller.abort(outcome.reason); // [!code highlight]
103
+ await agentPromise; // Wait until the losing branch has stopped. // [!code highlight]
104
+ return { type: "stopped" as const, reason: outcome.reason };
87
105
  }
88
106
 
89
- return result;
107
+ return outcome;
90
108
  }
91
109
  ```
92
110
 
93
- ### API Route to Trigger Stop
111
+ ### API route to trigger stop
94
112
 
95
113
  ```typescript lineNumbers
96
114
  import { stopHook } from "@/workflows/stoppable-agent";
@@ -110,7 +128,7 @@ export async function POST(
110
128
  }
111
129
  ```
112
130
 
113
- ### Client Stop Button
131
+ ### Client stop button
114
132
 
115
133
  ```tsx lineNumbers
116
134
  "use client";
@@ -134,23 +152,23 @@ export function StopButton({ runId }: { runId: string }) {
134
152
 
135
153
  ## How it works
136
154
 
137
- 1. An `AbortController` is created at the start of the workflow
138
- 2. A hook is created with token `stop:${workflowRunId}`
139
- 3. `Promise.race` runs the agent stream and the stop hook concurrently
140
- 4. The agent receives `controller.signal` — when aborted, the underlying model stream is cancelled
141
- 5. When the stop API resumes the hook, `controller.abort()` is called — the race resolves and the workflow exits
142
- 6. `emitStopSignal` writes a `data-stopped` part to the stream so the client renders a clean stop state
155
+ 1. The workflow creates an `AbortController` when it starts.
156
+ 2. The workflow creates a hook with the token `stop:${workflowRunId}`.
157
+ 3. `Promise.race` runs the agent stream and the stop hook concurrently.
158
+ 4. The agent receives `controller.signal`. When aborted, the signal cancels the active model stream, propagates to tool execution, and prevents another model step from starting. Tool implementations must forward it to operations such as `fetch` that support cancellation.
159
+ 5. When the stop API resumes the hook, the race reports a stop request. The workflow aborts the controller and awaits `agentPromise`, so it does not return while that branch is still running.
160
+ 6. After the agent branch settles, the workflow returns a `stopped` result. That return value is not written to the model-call stream automatically; the application can read `run.returnValue` or persist the status separately.
143
161
 
144
162
  ## Adapting this
145
163
 
146
- * **Add a timeout** — race a third `sleep()` promise to auto-stop after a deadline
147
- * **Audit logging** — include a `reason` field in the stop schema to record who stopped and why
148
- * **Cross-process** — the hook token is deterministic, so any process can call `stopHook.resume()` with the run ID
149
- * **Step limits** — combine with `maxSteps` on the agent to cap execution even without manual stop
164
+ - **Add a timeout**: Race a third `sleep()` promise to stop automatically after a deadline.
165
+ - **Audit logging**: Include a `reason` field in the stop schema to record who stopped the agent and why.
166
+ - **Cross-process**: The hook token is deterministic, so any process can call `stopHook.resume()` with the run ID.
167
+ - **Step limits**: Combine the pattern with `stopWhen: isStepCount(...)` to cap execution without a manual stop.
150
168
 
151
169
  ## Key APIs
152
170
 
153
- * [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook for the stop signal
154
- * [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata) — access the run ID for deterministic hook tokens
155
- * [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream output and the stop notification to the client
156
- * [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — the agent that respects the abort signal via its `signal` option
171
+ - [`defineHook()`](/docs/api-reference/workflow/define-hook): Defines a type-safe hook for the stop signal.
172
+ - [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata): Provides the run ID for deterministic hook tokens.
173
+ - [`getWritable()`](/docs/api-reference/workflow/get-writable): Stores durable model-call output from the agent.
174
+ - [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent): AI SDK's durable agent that applies the abort signal to model calls and replaces `DurableAgent`.
@@ -1,150 +1,42 @@
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
+ <CopyPrompt
9
+ text="Convert this stateless AI SDK agent to a durable agent with AI SDK v7's `WorkflowAgent`. Install/use `@ai-sdk/workflow` and `workflow`. Replace the manual `streamText` loop with `new WorkflowAgent(...)` from `@ai-sdk/workflow`, run inside an exported function with `&quot;use workflow&quot;`. Mark side-effectful tool `execute` functions with `&quot;use step&quot;` so they run as durable workflow steps with retries and observability. Stream `ModelCallStreamPart` chunks with `getWritable()` from `workflow`, convert the run stream to UI message chunks with `createModelCallToUIChunkTransform()` in the API route, and expose a route that starts or reconnects to the run. If migrating from the deprecated `DurableAgent`, follow the migration guide at https://ai-sdk.dev/v7/docs/agents/workflow-agent#migrating-from-durableagent. Verify tool retries, stream output, and resume/reconnect behavior."
10
+ />
9
11
 
10
- ## When to use this
12
+ ## WorkflowAgent from AI SDK v7
11
13
 
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
14
+ Use AI SDK v7's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) for durable agents in Workflow 5. It replaces `DurableAgent` and keeps the current agent pattern in the AI SDK package.
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
16
+ - Import `WorkflowAgent` from `@ai-sdk/workflow` and run it inside a `"use workflow"` function.
17
+ - Pass `"spacexai/grok-4.6"` as a plain model string so AI SDK routes requests through Vercel AI Gateway.
18
+ - Stream `ModelCallStreamPart` chunks with `getWritable()`, then convert the run stream to UI message chunks with `createModelCallToUIChunkTransform()` in your route.
19
+ - Mark tool `execute` functions with `"use step"` when they should run as durable workflow steps with retry and observability behavior.
22
20
 
23
21
  ```typescript
24
- import { DurableAgent } from "@workflow/ai/agent";
22
+ import { WorkflowAgent, type ModelCallStreamPart } from "@ai-sdk/workflow";
25
23
  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
24
 
62
- export async function flightAgent(messages: ModelMessage[]) {
25
+ export async function agentWorkflow(prompt: string) {
63
26
  "use workflow";
64
27
 
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
- },
28
+ const agent = new WorkflowAgent({
29
+ model: "spacexai/grok-4.6",
30
+ instructions: "You are a helpful assistant.",
94
31
  });
95
32
 
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
- },
33
+ return agent.stream({
34
+ messages: [{ role: "user", content: prompt }],
35
+ writable: getWritable<ModelCallStreamPart>(),
125
36
  });
126
37
  }
127
38
  ```
128
39
 
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
40
+ <Callout type="warn">
41
+ `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.
42
+ </Callout>