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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/dist/api-workflow.d.ts +1 -1
  2. package/dist/api-workflow.d.ts.map +1 -1
  3. package/dist/api-workflow.js +2 -2
  4. package/dist/api.d.ts +5 -1
  5. package/dist/api.d.ts.map +1 -1
  6. package/dist/api.js +14 -2
  7. package/dist/internal/builtins.d.ts +17 -0
  8. package/dist/internal/builtins.d.ts.map +1 -1
  9. package/dist/internal/builtins.js +65 -1
  10. package/dist/observability.d.ts +1 -1
  11. package/dist/observability.js +2 -2
  12. package/dist/runtime.d.ts +1 -1
  13. package/dist/runtime.d.ts.map +1 -1
  14. package/dist/runtime.js +2 -2
  15. package/docs/ai/index.mdx +27 -23
  16. package/docs/api-reference/index.mdx +24 -0
  17. package/docs/api-reference/meta.json +8 -0
  18. package/docs/api-reference/vitest/index.mdx +28 -7
  19. package/docs/api-reference/workflow/create-hook.mdx +38 -0
  20. package/docs/api-reference/workflow/create-webhook.mdx +1 -0
  21. package/docs/api-reference/workflow/experimental-set-attributes.mdx +65 -0
  22. package/docs/api-reference/workflow/fetch.mdx +5 -0
  23. package/docs/api-reference/workflow/index.mdx +3 -0
  24. package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
  25. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +7 -0
  26. package/docs/api-reference/workflow-api/get-run.mdx +6 -0
  27. package/docs/api-reference/workflow-api/index.mdx +6 -8
  28. package/docs/api-reference/workflow-api/resume-hook.mdx +57 -0
  29. package/docs/api-reference/workflow-api/start.mdx +13 -5
  30. package/docs/api-reference/workflow-astro/index.mdx +18 -0
  31. package/docs/api-reference/workflow-astro/meta.json +4 -0
  32. package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
  33. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
  34. package/docs/api-reference/workflow-errors/index.mdx +85 -0
  35. package/docs/api-reference/workflow-errors/meta.json +5 -0
  36. package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
  37. package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
  38. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
  39. package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
  40. package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
  41. package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
  42. package/docs/api-reference/workflow-nest/index.mdx +31 -0
  43. package/docs/api-reference/workflow-nest/meta.json +9 -0
  44. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
  45. package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
  46. package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
  47. package/docs/api-reference/workflow-next/with-workflow.mdx +34 -2
  48. package/docs/api-reference/workflow-nitro/index.mdx +59 -0
  49. package/docs/api-reference/workflow-nuxt/index.mdx +47 -0
  50. package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
  51. package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
  52. package/docs/api-reference/workflow-observability/index.mdx +64 -0
  53. package/docs/api-reference/workflow-observability/meta.json +11 -0
  54. package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
  55. package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
  56. package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
  57. package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
  58. package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
  59. package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
  60. package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +7 -10
  61. package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
  62. package/docs/api-reference/workflow-runtime/index.mdx +43 -0
  63. package/docs/api-reference/workflow-runtime/meta.json +12 -0
  64. package/docs/api-reference/workflow-runtime/set-world.mdx +49 -0
  65. package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +42 -0
  66. package/docs/api-reference/{workflow-api → workflow-runtime}/world/index.mdx +5 -8
  67. package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
  68. package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +2 -2
  69. package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +11 -4
  70. package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +2 -2
  71. package/docs/api-reference/workflow-serde/index.mdx +0 -1
  72. package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +1 -2
  73. package/docs/api-reference/workflow-serde/workflow-serialize.mdx +1 -2
  74. package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
  75. package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
  76. package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
  77. package/docs/api-reference/workflow-vite/index.mdx +18 -0
  78. package/docs/api-reference/workflow-vite/meta.json +4 -0
  79. package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
  80. package/docs/changelog/attributes-mvp.mdx +380 -0
  81. package/docs/changelog/eager-processing.mdx +269 -0
  82. package/docs/changelog/index.mdx +2 -1
  83. package/docs/changelog/lazy-event-creation.md +127 -0
  84. package/docs/changelog/meta.json +6 -1
  85. package/docs/changelog/resilient-start.mdx +31 -283
  86. package/docs/cookbook/advanced/child-workflows.mdx +315 -0
  87. package/docs/cookbook/advanced/meta.json +2 -3
  88. package/docs/cookbook/advanced/publishing-libraries.mdx +87 -29
  89. package/docs/cookbook/advanced/serializable-steps.mdx +17 -5
  90. package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
  91. package/docs/cookbook/agent-patterns/agent-cancellation.mdx +156 -0
  92. package/docs/cookbook/agent-patterns/durable-agent.mdx +11 -184
  93. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +150 -173
  94. package/docs/cookbook/agent-patterns/meta.json +1 -7
  95. package/docs/cookbook/common-patterns/batching.mdx +44 -118
  96. package/docs/cookbook/common-patterns/idempotency.mdx +36 -52
  97. package/docs/cookbook/common-patterns/meta.json +4 -4
  98. package/docs/cookbook/common-patterns/rate-limiting.mdx +1 -1
  99. package/docs/cookbook/common-patterns/saga.mdx +128 -33
  100. package/docs/cookbook/common-patterns/scheduling.mdx +77 -193
  101. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
  102. package/docs/cookbook/common-patterns/timeouts.mdx +100 -0
  103. package/docs/cookbook/common-patterns/workflow-composition.mdx +117 -0
  104. package/docs/cookbook/index.mdx +14 -17
  105. package/docs/cookbook/integrations/ai-sdk.mdx +330 -142
  106. package/docs/cookbook/integrations/chat-sdk.mdx +264 -151
  107. package/docs/cookbook/integrations/sandbox.mdx +482 -81
  108. package/docs/cookbook/meta.json +1 -1
  109. package/docs/deploying/building-a-world.mdx +1 -1
  110. package/docs/deploying/world/postgres-world.mdx +5 -3
  111. package/docs/deploying/world/vercel-world.mdx +2 -0
  112. package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
  113. package/docs/errors/corrupted-event-log.mdx +5 -5
  114. package/docs/errors/hook-conflict.mdx +56 -4
  115. package/docs/errors/index.mdx +9 -0
  116. package/docs/errors/replay-divergence.mdx +27 -0
  117. package/docs/errors/runtime-decryption-failed.mdx +77 -0
  118. package/docs/errors/step-executed-multiple-times.mdx +23 -0
  119. package/docs/errors/step-not-registered.mdx +1 -1
  120. package/docs/foundations/cancellation.mdx +459 -0
  121. package/docs/foundations/errors-and-retries.mdx +7 -3
  122. package/docs/foundations/hooks.mdx +29 -0
  123. package/docs/foundations/idempotency.mdx +236 -11
  124. package/docs/foundations/index.mdx +3 -3
  125. package/docs/foundations/meta.json +3 -2
  126. package/docs/foundations/serialization.mdx +78 -42
  127. package/docs/foundations/starting-workflows.mdx +6 -2
  128. package/docs/foundations/streaming.mdx +14 -23
  129. package/docs/foundations/versioning.mdx +263 -0
  130. package/docs/getting-started/astro.mdx +6 -0
  131. package/docs/getting-started/index.mdx +6 -7
  132. package/docs/getting-started/meta.json +1 -0
  133. package/docs/getting-started/nestjs.mdx +9 -0
  134. package/docs/getting-started/next.mdx +5 -3
  135. package/docs/getting-started/nitro.mdx +22 -0
  136. package/docs/getting-started/sveltekit.mdx +6 -0
  137. package/docs/getting-started/tanstack-start.mdx +241 -0
  138. package/docs/how-it-works/cancellation.mdx +287 -0
  139. package/docs/how-it-works/code-transform.mdx +2 -2
  140. package/docs/how-it-works/encryption.mdx +2 -2
  141. package/docs/how-it-works/event-sourcing.mdx +2 -2
  142. package/docs/how-it-works/meta.json +2 -1
  143. package/docs/internal/index.mdx +21 -0
  144. package/docs/internal/meta.json +10 -0
  145. package/docs/internal/nitro-native-build.mdx +38 -0
  146. package/docs/internal/nitro-web-ui.mdx +24 -0
  147. package/docs/internal/serializable-abort-controller.mdx +148 -0
  148. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +63 -16
  149. package/docs/migration-guides/migrating-from-inngest.mdx +44 -22
  150. package/docs/migration-guides/migrating-from-temporal.mdx +43 -14
  151. package/docs/migration-guides/migrating-from-trigger-dev.mdx +59 -27
  152. package/docs/observability/attributes.mdx +87 -0
  153. package/docs/observability/index.mdx +25 -1
  154. package/docs/observability/meta.json +1 -1
  155. package/docs/observability/tracing.mdx +106 -0
  156. package/docs/testing/index.mdx +2 -2
  157. package/package.json +14 -13
  158. package/docs/api-reference/workflow-api/world/meta.json +0 -4
  159. package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
  160. package/docs/cookbook/advanced/custom-serialization.mdx +0 -168
  161. package/docs/cookbook/advanced/durable-objects.mdx +0 -148
  162. package/docs/cookbook/advanced/isomorphic-packages.mdx +0 -145
  163. package/docs/cookbook/agent-patterns/stop-workflow.mdx +0 -216
  164. package/docs/cookbook/agent-patterns/tool-orchestration.mdx +0 -255
  165. package/docs/cookbook/agent-patterns/tool-streaming.mdx +0 -181
  166. package/docs/cookbook/common-patterns/child-workflows.mdx +0 -372
  167. package/docs/cookbook/common-patterns/content-router.mdx +0 -207
  168. package/docs/cookbook/common-patterns/fan-out.mdx +0 -208
  169. package/docs/foundations/common-patterns.mdx +0 -265
@@ -1,191 +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
- ## Pattern
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` in v5 and keeps the current agent pattern in the AI SDK package.
11
11
 
12
- Replace `Agent` with `DurableAgent`, wrap the function in `"use workflow"`, mark each tool with `"use step"`, and stream output through `getWritable()`.
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.
13
15
 
14
- ### Simplified
15
-
16
- ```typescript lineNumbers
17
- import { DurableAgent } from "@workflow/ai/agent";
18
- import { getWritable } from "workflow";
19
- import { z } from "zod";
20
- import type { ModelMessage, UIMessageChunk } from "ai";
21
-
22
- declare function searchFlights(args: { from: string; to: string; date: string }): Promise<{ flights: { id: string; price: number }[] }>; // @setup
23
- declare function bookFlight(args: { flightId: string; passenger: string }): Promise<{ confirmationId: string }>; // @setup
24
-
25
- export async function flightAgent(messages: ModelMessage[]) {
26
- "use workflow";
27
-
28
- const agent = new DurableAgent({ // [!code highlight]
29
- model: "anthropic/claude-haiku-4.5",
30
- instructions: "You are a helpful flight booking assistant.",
31
- tools: {
32
- searchFlights: {
33
- description: "Search for available flights",
34
- inputSchema: z.object({
35
- from: z.string(),
36
- to: z.string(),
37
- date: z.string(),
38
- }),
39
- execute: searchFlights,
40
- },
41
- bookFlight: {
42
- description: "Book a specific flight",
43
- inputSchema: z.object({
44
- flightId: z.string(),
45
- passenger: z.string(),
46
- }),
47
- execute: bookFlight,
48
- },
49
- },
50
- });
51
-
52
- await agent.stream({ // [!code highlight]
53
- messages,
54
- writable: getWritable<UIMessageChunk>(),
55
- });
56
- }
57
- ```
58
-
59
- ### Full Implementation
60
-
61
- ```typescript lineNumbers
62
- import { DurableAgent } from "@workflow/ai/agent";
63
- import { getWritable } from "workflow";
64
- import { z } from "zod";
65
- import type { ModelMessage, UIMessageChunk } from "ai";
66
-
67
- // Step: Search flights with full Node.js access and automatic retries
68
- async function searchFlights({
69
- from,
70
- to,
71
- date,
72
- }: {
73
- from: string;
74
- to: string;
75
- date: string;
76
- }) {
77
- "use step";
78
-
79
- const response = await fetch(
80
- `https://api.example.com/flights?from=${from}&to=${to}&date=${date}`
81
- );
82
- if (!response.ok) throw new Error(`Search failed: ${response.status}`);
83
- return response.json();
84
- }
85
-
86
- // Step: Book a flight — retries on transient failures
87
- async function bookFlight({
88
- flightId,
89
- passenger,
90
- }: {
91
- flightId: string;
92
- passenger: string;
93
- }) {
94
- "use step";
95
-
96
- const response = await fetch("https://api.example.com/bookings", {
97
- method: "POST",
98
- headers: { "Content-Type": "application/json" },
99
- body: JSON.stringify({ flightId, passenger }),
100
- });
101
- if (!response.ok) throw new Error(`Booking failed: ${response.status}`);
102
- return response.json();
103
- }
104
-
105
- // Step: Check flight status
106
- async function checkStatus({ flightId }: { flightId: string }) {
107
- "use step";
108
-
109
- const response = await fetch(
110
- `https://api.example.com/flights/${flightId}/status`
111
- );
112
- return response.json();
113
- }
114
-
115
- export async function flightAgent(messages: ModelMessage[]) {
116
- "use workflow";
117
-
118
- const writable = getWritable<UIMessageChunk>(); // [!code highlight]
119
-
120
- const agent = new DurableAgent({ // [!code highlight]
121
- model: "anthropic/claude-haiku-4.5",
122
- instructions: "You are a helpful flight booking assistant.",
123
- tools: {
124
- searchFlights: {
125
- description: "Search for available flights between two airports",
126
- inputSchema: z.object({
127
- from: z.string().describe("Departure airport code"),
128
- to: z.string().describe("Arrival airport code"),
129
- date: z.string().describe("Travel date (YYYY-MM-DD)"),
130
- }),
131
- execute: searchFlights,
132
- },
133
- bookFlight: {
134
- description: "Book a specific flight for a passenger",
135
- inputSchema: z.object({
136
- flightId: z.string().describe("Flight ID from search results"),
137
- passenger: z.string().describe("Passenger full name"),
138
- }),
139
- execute: bookFlight,
140
- },
141
- checkStatus: {
142
- description: "Check the current status of a flight",
143
- inputSchema: z.object({
144
- flightId: z.string().describe("Flight ID to check"),
145
- }),
146
- execute: checkStatus,
147
- },
148
- },
149
- });
150
-
151
- const result = await agent.stream({ // [!code highlight]
152
- messages,
153
- writable,
154
- maxSteps: 10,
155
- });
156
-
157
- return { messages: result.messages };
158
- }
159
- ```
160
-
161
- ### API Route
162
-
163
- ```typescript lineNumbers
164
- import { createUIMessageStreamResponse } from "ai";
165
- import { start } from "workflow/api";
166
- import { flightAgent } from "@/workflows/flight-agent";
167
- import type { UIMessage } from "ai";
168
- import { convertToModelMessages } from "ai";
169
-
170
- export async function POST(req: Request) {
171
- const { messages }: { messages: UIMessage[] } = await req.json();
172
- const modelMessages = await convertToModelMessages(messages);
173
-
174
- const run = await start(flightAgent, [modelMessages]); // [!code highlight]
175
-
176
- return createUIMessageStreamResponse({
177
- stream: run.readable,
178
- headers: {
179
- "x-workflow-run-id": run.runId,
180
- },
181
- });
182
- }
183
- ```
184
-
185
- ## Key APIs
186
-
187
- - [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
188
- - [`"use step"`](/docs/api-reference/workflow/use-step) — declares step functions with retries and full Node.js access
189
- - [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — durable wrapper around AI SDK's Agent
190
- - [`getWritable()`](/docs/api-reference/workflow/get-writable) — streams agent output to the client
191
- - [`start()`](/docs/api-reference/workflow-api/start) — starts a workflow run from an API route
16
+ <Callout type="warn">
17
+ `DurableAgent` is deprecated in v5 and remains documented for existing code only. Existing `DurableAgent` users can refer to the [`DurableAgent` API reference](/docs/api-reference/workflow-ai/durable-agent) while migrating.
18
+ </Callout>
@@ -7,165 +7,141 @@ summary: Use defineHook with the tool call ID to suspend an agent for human appr
7
7
 
8
8
  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
9
 
10
- ## Pattern
11
-
12
- Create a typed hook using `defineHook()`. When the agent calls the approval tool, the tool creates a hook instance using the tool call ID as the token, then awaits it. The UI renders approval controls, and an API route resumes the hook with the decision.
13
-
14
- ### Simplified
10
+ ## When to use this
15
11
 
16
- ```typescript lineNumbers
17
- import { DurableAgent } from "@workflow/ai/agent";
18
- import { defineHook, sleep, getWritable } from "workflow";
19
- import { z } from "zod";
20
- import type { ModelMessage, UIMessageChunk } from "ai";
21
-
22
- export const bookingApprovalHook = defineHook({
23
- schema: z.object({
24
- approved: z.boolean(),
25
- comment: z.string().optional(),
26
- }),
27
- });
28
-
29
- declare function confirmBooking(args: { flightId: string; passenger: string }): Promise<{ confirmationId: string }>; // @setup
30
-
31
- // This tool runs at the workflow level (no "use step") because hooks are workflow primitives
32
- async function requestBookingApproval(
33
- { flightId, passenger, price }: { flightId: string; passenger: string; price: number },
34
- { toolCallId }: { toolCallId: string }
35
- ) {
36
- const hook = bookingApprovalHook.create({ token: toolCallId }); // [!code highlight]
37
-
38
- const result = await Promise.race([ // [!code highlight]
39
- hook.then((payload) => ({ type: "decision" as const, ...payload })),
40
- sleep("24h").then(() => ({ type: "timeout" as const, approved: false })),
41
- ]);
12
+ - Booking confirmations where users must approve before charges are made
13
+ - Content publishing gates where an editor must sign off
14
+ - Any agent action where the cost of getting it wrong justifies a human check
15
+ - Actions with side effects that can't be easily undone
42
16
 
43
- if (result.type === "timeout") return "Booking request expired after 24 hours.";
44
- if (!result.approved) return `Booking rejected: ${result.comment || "No reason given"}`;
45
-
46
- const booking = await confirmBooking({ flightId, passenger });
47
- return `Booked! Confirmation: ${booking.confirmationId}`;
48
- }
49
-
50
- export async function bookingAgent(messages: ModelMessage[]) {
51
- "use workflow";
52
-
53
- const agent = new DurableAgent({
54
- model: "anthropic/claude-haiku-4.5",
55
- instructions: "You help book flights. Always request approval before booking.",
56
- tools: {
57
- requestBookingApproval: {
58
- description: "Request human approval before booking a flight",
59
- inputSchema: z.object({
60
- flightId: z.string(),
61
- passenger: z.string(),
62
- price: z.number(),
63
- }),
64
- execute: requestBookingApproval,
65
- },
66
- },
67
- });
17
+ ## Pattern
68
18
 
69
- await agent.stream({ // [!code highlight]
70
- messages,
71
- writable: getWritable<UIMessageChunk>(),
72
- });
73
- }
74
- ```
19
+ Create a typed hook using `defineHook()`. When the agent calls the approval tool, the tool emits a custom data part to the stream so the client can render approval controls, then creates a hook and suspends. An API route resumes the hook with the decision.
75
20
 
76
- ### Full Implementation
21
+ ### Workflow
77
22
 
78
- ```typescript lineNumbers
23
+ ```typescript
79
24
  import { DurableAgent } from "@workflow/ai/agent";
80
25
  import { defineHook, sleep, getWritable } from "workflow";
81
26
  import { z } from "zod";
82
27
  import type { ModelMessage, UIMessageChunk } from "ai";
83
28
 
84
- // Define the approval hook with schema validation
85
- export const bookingApprovalHook = defineHook({
29
+ // Exported so the approval API route can call .resume()
30
+ export const bookingApprovalHook = defineHook({ // [!code highlight]
86
31
  schema: z.object({
87
32
  approved: z.boolean(),
88
33
  comment: z.string().optional(),
89
34
  }),
90
35
  });
91
36
 
92
- // Step: Search for flights (full Node.js access, automatic retries)
93
- async function searchFlights({
94
- from,
95
- to,
96
- date,
97
- }: {
37
+ async function searchFlights({ from, to, date }: {
98
38
  from: string;
99
39
  to: string;
100
40
  date: string;
101
41
  }) {
102
42
  "use step";
43
+ const res = await fetch(
44
+ `https://api.example.com/flights?from=${from}&to=${to}&date=${date}`
45
+ );
46
+ return res.json();
47
+ }
103
48
 
104
- // Your real flight search API call here
105
- await new Promise((resolve) => setTimeout(resolve, 500));
106
- return {
107
- flights: [
108
- { id: "FL-100", airline: "Example Air", price: 299, from, to, date },
109
- { id: "FL-200", airline: "Demo Airlines", price: 349, from, to, date },
110
- ],
111
- };
49
+ async function confirmBooking({ flightId, passenger }: {
50
+ flightId: string;
51
+ passenger: string;
52
+ }) {
53
+ "use step";
54
+ const res = await fetch("https://api.example.com/bookings", {
55
+ method: "POST",
56
+ body: JSON.stringify({ flightId, passenger }),
57
+ });
58
+ return res.json();
112
59
  }
113
60
 
114
- // Step: Confirm the booking after approval
115
- async function confirmBooking({
116
- flightId,
117
- passenger,
118
- }: {
61
+ // Stream a custom data part so the client can render the approval UI.
62
+ // This MUST run before the hook suspends the workflow — otherwise
63
+ // the tool-invocation won't appear in the stream until the tool returns,
64
+ // and the client would have no way to show approval buttons.
65
+ async function emitApprovalRequest(details: {
119
66
  flightId: string;
120
67
  passenger: string;
68
+ price: number;
69
+ toolCallId: string;
121
70
  }) {
122
71
  "use step";
72
+ const writer = getWritable<UIMessageChunk>().getWriter();
73
+ try {
74
+ await writer.write({
75
+ type: "data-approval-needed", // [!code highlight]
76
+ id: details.toolCallId,
77
+ data: details,
78
+ } as UIMessageChunk);
79
+ } finally {
80
+ writer.releaseLock();
81
+ }
82
+ }
123
83
 
124
- await new Promise((resolve) => setTimeout(resolve, 500));
125
- return { confirmationId: `CONF-${flightId}-${Date.now().toString(36)}` };
84
+ // Stream the resolution so the client can update the approval card.
85
+ async function emitApprovalResolved(details: {
86
+ toolCallId: string;
87
+ result: string;
88
+ }) {
89
+ "use step";
90
+ const writer = getWritable<UIMessageChunk>().getWriter();
91
+ try {
92
+ await writer.write({
93
+ type: "data-approval-resolved", // [!code highlight]
94
+ id: details.toolCallId,
95
+ data: details,
96
+ } as UIMessageChunk);
97
+ } finally {
98
+ writer.releaseLock();
99
+ }
126
100
  }
127
101
 
128
- // Workflow-level tool: hooks must be created in workflow context, not inside steps
102
+ // No "use step" hooks are workflow-level primitives
129
103
  async function requestBookingApproval(
130
- {
131
- flightId,
132
- passenger,
133
- price,
134
- }: { flightId: string; passenger: string; price: number },
104
+ { flightId, passenger, price }: {
105
+ flightId: string;
106
+ passenger: string;
107
+ price: number;
108
+ },
135
109
  { toolCallId }: { toolCallId: string }
136
110
  ) {
137
- // No "use step" hooks are workflow-level primitives
111
+ // Emit to the stream before suspending so the UI can show buttons
112
+ await emitApprovalRequest({ flightId, passenger, price, toolCallId }); // [!code highlight]
138
113
 
139
- const hook = bookingApprovalHook.create({ token: toolCallId }); // [!code highlight]
114
+ const hook = bookingApprovalHook.create({ token: toolCallId });
140
115
 
141
- // Race: human approval vs. 24-hour timeout
142
- const result = await Promise.race([ // [!code highlight]
116
+ // Race: human decision vs. timeout
117
+ const result = await Promise.race([
143
118
  hook.then((payload) => ({ type: "decision" as const, ...payload })),
144
- sleep("24h").then(() => ({ type: "timeout" as const, approved: false })),
119
+ sleep("24h").then(() => ({ type: "timeout" as const, approved: false as const })),
145
120
  ]);
146
121
 
147
122
  if (result.type === "timeout") {
148
- return "Booking request expired after 24 hours.";
123
+ const msg = "Booking request expired.";
124
+ await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
125
+ return msg;
149
126
  }
150
-
151
127
  if (!result.approved) {
152
- return `Booking rejected: ${result.comment || "No reason given"}`;
128
+ const msg = `Rejected: ${result.comment || "No reason given"}`;
129
+ await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
130
+ return msg;
153
131
  }
154
132
 
155
- // Approved — proceed with booking
156
133
  const booking = await confirmBooking({ flightId, passenger });
157
- return `Flight ${flightId} booked for ${passenger}. Confirmation: ${booking.confirmationId}`;
134
+ const msg = `Booked! Confirmation: ${booking.confirmationId}`;
135
+ await emitApprovalResolved({ toolCallId, result: msg }); // [!code highlight]
136
+ return msg;
158
137
  }
159
138
 
160
139
  export async function bookingAgent(messages: ModelMessage[]) {
161
140
  "use workflow";
162
141
 
163
- const writable = getWritable<UIMessageChunk>();
164
-
165
142
  const agent = new DurableAgent({
166
143
  model: "anthropic/claude-haiku-4.5",
167
- instructions:
168
- "You are a flight booking assistant. Search for flights, then request approval before booking.",
144
+ instructions: "You help book flights. Always request approval before booking.",
169
145
  tools: {
170
146
  searchFlights: {
171
147
  description: "Search for available flights",
@@ -188,91 +164,92 @@ export async function bookingAgent(messages: ModelMessage[]) {
188
164
  },
189
165
  });
190
166
 
191
- await agent.stream({ messages, writable }); // [!code highlight]
167
+ await agent.stream({
168
+ messages,
169
+ writable: getWritable<UIMessageChunk>(),
170
+ });
192
171
  }
193
172
  ```
194
173
 
195
- ### API Route for Approvals
174
+ ### Approval API route
175
+
176
+ The approval route imports the hook definition and calls `.resume()` with the tool call ID as the token:
196
177
 
197
- ```typescript lineNumbers
198
- import { bookingApprovalHook } from "@/workflows/booking-agent";
178
+ ```typescript
179
+ import { bookingApprovalHook } from "@/app/workflows/booking-agent";
199
180
 
200
- export async function POST(request: Request) {
201
- const { toolCallId, approved, comment } = await request.json();
181
+ export async function POST(req: Request) {
182
+ const { toolCallId, approved, comment } = await req.json();
202
183
 
203
- // Schema validation happens automatically via defineHook
204
184
  await bookingApprovalHook.resume(toolCallId, { approved, comment }); // [!code highlight]
205
185
 
206
186
  return Response.json({ success: true });
207
187
  }
208
188
  ```
209
189
 
210
- ### Approval Component
211
-
212
- ```tsx lineNumbers
213
- "use client";
190
+ ### Client rendering
191
+
192
+ Listen for `data-approval-needed` and `data-approval-resolved` custom data parts in the message stream. The approval tool invocation itself won't appear until the tool returns, so the custom data parts are the mechanism for showing and updating the approval UI.
193
+
194
+ ```tsx
195
+ // Scan all messages for the resolution
196
+ const approvalResult = messages
197
+ .flatMap((m) => m.parts)
198
+ .find((p) => p.type === "data-approval-resolved")
199
+ ?.data?.result;
200
+
201
+ // In your message parts loop:
202
+ {message.parts.map((part, i) => {
203
+ if (part.type === "data-approval-needed") { // [!code highlight]
204
+ const { flightId, passenger, price, toolCallId } = part.data;
205
+ if (approvalResult) {
206
+ return <div key={i}>Result: {approvalResult}</div>;
207
+ }
208
+ return (
209
+ <div key={i} className="rounded-lg border p-4 space-y-3">
210
+ <div className="text-sm">
211
+ <div>Flight: {flightId}</div>
212
+ <div>Passenger: {passenger}</div>
213
+ <div>Price: ${price}</div>
214
+ </div>
215
+ <div className="flex gap-2">
216
+ <button onClick={() => approve(toolCallId)}>Approve</button> {/* [!code highlight] */}
217
+ <button onClick={() => reject(toolCallId)}>Reject</button> {/* [!code highlight] */}
218
+ </div>
219
+ </div>
220
+ );
221
+ }
222
+ // Hide the requestBookingApproval tool-invocation part
223
+ if (part.type === "tool-invocation" &&
224
+ part.toolInvocation.toolName === "requestBookingApproval") {
225
+ return null;
226
+ }
227
+ // ... other part types
228
+ })}
229
+ ```
214
230
 
215
- import { useState } from "react";
231
+ ## How it works
216
232
 
217
- export function BookingApproval({
218
- toolCallId,
219
- input,
220
- output,
221
- }: {
222
- toolCallId: string;
223
- input?: { flightId: string; passenger: string; price: number };
224
- output?: string;
225
- }) {
226
- const [comment, setComment] = useState("");
227
- const [isSubmitting, setIsSubmitting] = useState(false);
233
+ 1. **`defineHook()` with schema** — creates a typed hook with Zod validation. The approval payload is validated before the workflow receives it.
234
+ 2. **`toolCallId` as token** — the approval tool uses the tool call ID as the hook token, naturally linking the hook to the specific tool invocation.
235
+ 3. **`emitApprovalRequest` step** — writes a `data-approval-needed` custom data part to the stream *before* the hook suspends. Without this, the client would never see the approval controls because tool invocations don't stream until the tool returns.
236
+ 4. **No `"use step"` on the approval tool** — the tool runs at the workflow level because `defineHook().create()` is a workflow primitive. It calls step functions (`emitApprovalRequest`, `emitApprovalResolved`, `confirmBooking`) for I/O.
237
+ 5. **`Promise.race` with sleep** — the approval races against a durable timeout. If nobody responds, the workflow continues with an expiration message.
238
+ 6. **`emitApprovalResolved` step** — writes the outcome to the stream so the client can update the card immediately, without waiting for the tool-invocation result.
228
239
 
229
- if (output) {
230
- return <p className="text-sm text-muted-foreground">{output}</p>;
231
- }
240
+ ## Adapting to your use case
232
241
 
233
- const handleSubmit = async (approved: boolean) => {
234
- setIsSubmitting(true);
235
- await fetch("/api/hooks/approval", {
236
- method: "POST",
237
- headers: { "Content-Type": "application/json" },
238
- body: JSON.stringify({ toolCallId, approved, comment }),
239
- });
240
- setIsSubmitting(false);
241
- };
242
-
243
- return (
244
- <div className="border rounded-lg p-4 space-y-3">
245
- {input && (
246
- <div className="text-sm space-y-1">
247
- <div>Flight: {input.flightId}</div>
248
- <div>Passenger: {input.passenger}</div>
249
- <div>Price: ${input.price}</div>
250
- </div>
251
- )}
252
- <textarea
253
- value={comment}
254
- onChange={(e) => setComment(e.target.value)}
255
- placeholder="Add a comment (optional)..."
256
- className="w-full border rounded p-2 text-sm"
257
- rows={2}
258
- />
259
- <div className="flex gap-2">
260
- <button type="button" onClick={() => handleSubmit(true)} disabled={isSubmitting}>
261
- Approve
262
- </button>
263
- <button type="button" onClick={() => handleSubmit(false)} disabled={isSubmitting}>
264
- Reject
265
- </button>
266
- </div>
267
- </div>
268
- );
269
- }
270
- ```
242
+ - **Change the approval schema** add fields like `reason`, `amount`, `reviewerEmail` to match your domain.
243
+ - **Multiple approval gates** — the pattern works for any number of tools. Each tool creates its own hook with its own `toolCallId`.
244
+ - **Escalation** — if the first approver doesn't respond, use `sleep()` + another hook to escalate to a backup reviewer.
245
+ - **Adjust timeout** — use `"24h"` for production, shorter durations for demos.
246
+ - **Workflow-level vs step tools** — tools that use `sleep()`, `defineHook()`, or other workflow primitives must NOT use `"use step"`. Tools with only I/O (API calls, DB queries) should use `"use step"` for retries.
271
247
 
272
248
  ## Key APIs
273
249
 
274
- - [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
275
- - [`"use step"`](/docs/api-reference/workflow/use-step) — declares step functions with retries
250
+ - [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) — declares the orchestrator function
251
+ - [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) — declares step functions with retries
276
252
  - [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook with schema validation
277
253
  - [`sleep()`](/docs/api-reference/workflow/sleep) — durable timeout for approval expiry
254
+ - [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream custom data parts from steps
278
255
  - [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — durable agent with tool definitions
@@ -1,10 +1,4 @@
1
1
  {
2
2
  "title": "Agent Patterns",
3
- "pages": [
4
- "durable-agent",
5
- "tool-streaming",
6
- "human-in-the-loop",
7
- "tool-orchestration",
8
- "stop-workflow"
9
- ]
3
+ "pages": ["durable-agent", "human-in-the-loop", "agent-cancellation"]
10
4
  }