workflow 5.0.0-beta.4 → 5.0.0-beta.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -20
- package/dist/api-workflow.d.ts +1 -1
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +1 -1
- package/dist/api.d.ts +5 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +12 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/internal/builtins.d.ts +17 -0
- package/dist/internal/builtins.d.ts.map +1 -1
- package/dist/internal/builtins.js +65 -1
- package/dist/internal/errors.d.ts +1 -1
- package/dist/internal/errors.d.ts.map +1 -1
- package/dist/internal/errors.js +2 -2
- package/dist/nest-builder.d.ts +2 -0
- package/dist/nest-builder.d.ts.map +1 -0
- package/dist/nest-builder.js +2 -0
- package/dist/nest-vercel-builder.d.ts +2 -0
- package/dist/nest-vercel-builder.d.ts.map +1 -0
- package/dist/nest-vercel-builder.js +2 -0
- package/dist/observability.d.ts +1 -1
- package/dist/observability.js +2 -2
- package/dist/runtime.d.ts +2 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +5 -2
- package/docs/ai/chat-session-modeling.mdx +7 -3
- package/docs/ai/defining-tools.mdx +2 -2
- package/docs/ai/index.mdx +30 -25
- package/docs/ai/message-queueing.mdx +10 -10
- package/docs/ai/resumable-streams.mdx +9 -1
- package/docs/api-reference/index.mdx +24 -0
- package/docs/api-reference/meta.json +8 -0
- package/docs/api-reference/vitest/index.mdx +28 -7
- package/docs/api-reference/workflow/create-hook.mdx +79 -0
- package/docs/api-reference/workflow/create-webhook.mdx +1 -0
- package/docs/api-reference/workflow/define-hook.mdx +26 -24
- package/docs/api-reference/workflow/fatal-error.mdx +29 -7
- package/docs/api-reference/workflow/fetch.mdx +8 -4
- package/docs/api-reference/workflow/index.mdx +3 -0
- package/docs/api-reference/workflow/set-attributes.mdx +61 -0
- package/docs/api-reference/workflow/sleep.mdx +1 -1
- package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
- package/docs/api-reference/workflow-ai/index.mdx +2 -2
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +44 -1
- package/docs/api-reference/workflow-api/get-hook-by-token.mdx +9 -0
- package/docs/api-reference/workflow-api/get-run.mdx +25 -0
- package/docs/api-reference/workflow-api/index.mdx +6 -8
- package/docs/api-reference/workflow-api/resume-hook.mdx +60 -1
- package/docs/api-reference/workflow-api/resume-webhook.mdx +6 -4
- package/docs/api-reference/workflow-api/start.mdx +39 -6
- package/docs/api-reference/workflow-astro/index.mdx +18 -0
- package/docs/api-reference/workflow-astro/meta.json +4 -0
- package/docs/api-reference/workflow-astro/workflow.mdx +45 -0
- package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
- package/docs/api-reference/workflow-errors/index.mdx +88 -0
- package/docs/api-reference/workflow-errors/meta.json +6 -0
- package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +68 -0
- package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
- package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +16 -6
- package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
- package/docs/api-reference/workflow-globals.mdx +4 -1
- package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +33 -0
- package/docs/api-reference/workflow-nest/index.mdx +31 -0
- package/docs/api-reference/workflow-nest/meta.json +9 -0
- package/docs/api-reference/workflow-nest/nest-local-builder.mdx +64 -0
- package/docs/api-reference/workflow-nest/workflow-controller.mdx +40 -0
- package/docs/api-reference/workflow-nest/workflow-module.mdx +74 -0
- package/docs/api-reference/workflow-next/with-workflow.mdx +56 -2
- package/docs/api-reference/workflow-nitro/index.mdx +60 -0
- package/docs/api-reference/workflow-nuxt/index.mdx +48 -0
- package/docs/api-reference/workflow-observability/hydrate-data.mdx +35 -0
- package/docs/api-reference/workflow-observability/hydrate-resource-io.mdx +62 -0
- package/docs/api-reference/workflow-observability/index.mdx +64 -0
- package/docs/api-reference/workflow-observability/meta.json +11 -0
- package/docs/api-reference/workflow-observability/observability-revivers.mdx +50 -0
- package/docs/api-reference/workflow-observability/parse-class-name.mdx +41 -0
- package/docs/api-reference/workflow-observability/parse-step-name.mdx +40 -0
- package/docs/api-reference/workflow-observability/parse-workflow-name.mdx +55 -0
- package/docs/api-reference/workflow-runtime/create-world.mdx +39 -0
- package/docs/api-reference/workflow-runtime/get-world-handlers.mdx +44 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/get-world.mdx +7 -10
- package/docs/api-reference/workflow-runtime/health-check.mdx +50 -0
- package/docs/api-reference/workflow-runtime/index.mdx +43 -0
- package/docs/api-reference/workflow-runtime/meta.json +12 -0
- package/docs/api-reference/workflow-runtime/set-world.mdx +49 -0
- package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +42 -0
- package/docs/api-reference/workflow-runtime/world/analytics.mdx +138 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/index.mdx +10 -10
- package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +8 -6
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +18 -5
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +2 -2
- package/docs/api-reference/workflow-serde/index.mdx +0 -1
- package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +1 -2
- package/docs/api-reference/workflow-serde/workflow-serialize.mdx +2 -2
- package/docs/api-reference/workflow-sveltekit/index.mdx +18 -0
- package/docs/api-reference/workflow-sveltekit/meta.json +4 -0
- package/docs/api-reference/workflow-sveltekit/workflow-plugin.mdx +42 -0
- package/docs/api-reference/workflow-vite/index.mdx +18 -0
- package/docs/api-reference/workflow-vite/meta.json +4 -0
- package/docs/api-reference/workflow-vite/workflow.mdx +48 -0
- package/docs/changelog/attributes-mvp.mdx +380 -0
- package/docs/changelog/eager-processing.mdx +269 -0
- package/docs/changelog/index.mdx +3 -1
- package/docs/changelog/lazy-event-creation.md +127 -0
- package/docs/changelog/meta.json +9 -1
- package/docs/changelog/resilient-resume.mdx +22 -0
- package/docs/changelog/resilient-start.mdx +31 -283
- package/docs/changelog/step-message-ownership.mdx +360 -0
- package/docs/changelog/turbo-mode.md +87 -0
- package/docs/comparisons/index.mdx +66 -0
- package/docs/comparisons/meta.json +11 -0
- package/docs/comparisons/workflow-sdk-vs-aws-agentcore.mdx +55 -0
- package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +111 -0
- package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +71 -0
- package/docs/comparisons/workflow-sdk-vs-inngest.mdx +102 -0
- package/docs/comparisons/workflow-sdk-vs-temporal.mdx +123 -0
- package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +103 -0
- package/docs/configuration/build-and-diagnostics.mdx +70 -0
- package/docs/configuration/cli-and-web-ui.mdx +182 -0
- package/docs/configuration/framework-options.mdx +165 -0
- package/docs/configuration/index.mdx +32 -0
- package/docs/configuration/meta.json +12 -0
- package/docs/configuration/runtime-tuning.mdx +276 -0
- package/docs/configuration/worlds.mdx +275 -0
- package/docs/cookbook/advanced/child-workflows.mdx +203 -256
- package/docs/cookbook/advanced/meta.json +1 -1
- package/docs/cookbook/advanced/publishing-libraries.mdx +33 -24
- package/docs/cookbook/advanced/serializable-steps.mdx +12 -4
- package/docs/cookbook/advanced/upgrading-workflows.mdx +199 -0
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +34 -75
- package/docs/cookbook/agent-patterns/durable-agent.mdx +14 -142
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +11 -3
- package/docs/cookbook/common-patterns/batching.mdx +4 -0
- package/docs/cookbook/common-patterns/idempotency.mdx +40 -52
- package/docs/cookbook/common-patterns/rate-limiting.mdx +5 -1
- package/docs/cookbook/common-patterns/saga.mdx +6 -2
- package/docs/cookbook/common-patterns/scheduling.mdx +12 -0
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +4 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +6 -1
- package/docs/cookbook/common-patterns/webhooks.mdx +4 -0
- package/docs/cookbook/common-patterns/workflow-composition.mdx +19 -16
- package/docs/cookbook/index.mdx +3 -3
- package/docs/cookbook/integrations/ai-sdk.mdx +64 -28
- package/docs/cookbook/integrations/chat-sdk.mdx +17 -0
- package/docs/cookbook/integrations/sandbox.mdx +17 -0
- package/docs/{deploying/index.mdx → deploying.mdx} +7 -7
- package/docs/errors/abort-signal-timeout-in-workflow.mdx +84 -0
- package/docs/errors/corrupted-event-log.mdx +5 -5
- package/docs/errors/deployment-mismatch.mdx +71 -0
- package/docs/errors/fetch-in-workflow.mdx +4 -0
- package/docs/errors/hook-conflict.mdx +60 -4
- package/docs/errors/index.mdx +1 -35
- package/docs/errors/node-js-module-in-workflow.mdx +4 -0
- package/docs/errors/replay-divergence.mdx +27 -0
- package/docs/errors/runtime-decryption-failed.mdx +77 -0
- package/docs/errors/serialization-failed.mdx +4 -0
- package/docs/errors/start-invalid-workflow-function.mdx +4 -0
- package/docs/errors/step-executed-multiple-times.mdx +23 -0
- package/docs/errors/step-not-registered.mdx +1 -1
- package/docs/errors/timeout-in-workflow.mdx +4 -0
- package/docs/errors/webhook-response-not-sent.mdx +4 -0
- package/docs/foundations/cancellation.mdx +459 -0
- package/docs/foundations/errors-and-retries.mdx +7 -3
- package/docs/foundations/hooks.mdx +29 -0
- package/docs/foundations/idempotency.mdx +243 -11
- package/docs/foundations/index.mdx +1 -23
- package/docs/foundations/meta.json +3 -1
- package/docs/foundations/serialization.mdx +77 -41
- package/docs/foundations/starting-workflows.mdx +79 -2
- package/docs/foundations/streaming.mdx +14 -23
- package/docs/foundations/versioning.mdx +263 -0
- package/docs/getting-started/astro.mdx +12 -2
- package/docs/getting-started/express.mdx +6 -2
- package/docs/getting-started/fastify.mdx +6 -2
- package/docs/getting-started/hono.mdx +6 -2
- package/docs/getting-started/index.mdx +16 -10
- package/docs/getting-started/meta.json +4 -1
- package/docs/getting-started/nestjs.mdx +77 -3
- package/docs/getting-started/next.mdx +12 -6
- package/docs/getting-started/nitro.mdx +28 -2
- package/docs/getting-started/nuxt.mdx +6 -2
- package/docs/getting-started/python.mdx +24 -18
- package/docs/getting-started/react-router/index.mdx +33 -0
- package/docs/getting-started/react-router/meta.json +5 -0
- package/docs/getting-started/react-router/v7.mdx +237 -0
- package/docs/getting-started/react-router/v8.mdx +232 -0
- package/docs/getting-started/sveltekit.mdx +12 -2
- package/docs/getting-started/tanstack-start.mdx +245 -0
- package/docs/getting-started/vite.mdx +6 -2
- package/docs/how-it-works/cancellation.mdx +287 -0
- package/docs/how-it-works/code-transform.mdx +21 -17
- package/docs/how-it-works/encryption.mdx +5 -5
- package/docs/how-it-works/event-sourcing.mdx +6 -6
- package/docs/how-it-works/framework-integrations.mdx +96 -337
- package/docs/how-it-works/meta.json +2 -1
- package/docs/internal/index.mdx +21 -0
- package/docs/internal/meta.json +10 -0
- package/docs/internal/nitro-native-build.mdx +38 -0
- package/docs/internal/nitro-web-ui.mdx +24 -0
- package/docs/internal/serializable-abort-controller.mdx +148 -0
- package/docs/meta.json +2 -2
- package/docs/observability/attributes.mdx +112 -0
- package/docs/observability/index.mdx +20 -1
- package/docs/observability/meta.json +1 -1
- package/docs/observability/tracing.mdx +124 -0
- package/docs/testing/index.mdx +2 -2
- package/package.json +17 -13
- package/docs/api-reference/workflow-api/world/meta.json +0 -4
- package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
- package/docs/cookbook/advanced/distributed-abort-controller.mdx +0 -318
- package/docs/deploying/building-a-world.mdx +0 -251
- package/docs/deploying/meta.json +0 -4
- package/docs/deploying/world/local-world.mdx +0 -84
- package/docs/deploying/world/meta.json +0 -4
- package/docs/deploying/world/postgres-world.mdx +0 -222
- package/docs/deploying/world/vercel-world.mdx +0 -179
- package/docs/migration-guides/index.mdx +0 -34
- package/docs/migration-guides/meta.json +0 -9
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +0 -363
- package/docs/migration-guides/migrating-from-inngest.mdx +0 -314
- package/docs/migration-guides/migrating-from-temporal.mdx +0 -318
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +0 -337
|
@@ -1,150 +1,22 @@
|
|
|
1
1
|
---
|
|
2
|
-
title:
|
|
3
|
-
description:
|
|
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:
|
|
5
|
+
summary: Build durable, resumable AI agents with AI SDK v7's WorkflowAgent.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
|
|
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 `"use workflow"`. Mark side-effectful tool `execute` functions with `"use step"` 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
|
-
##
|
|
12
|
+
## WorkflowAgent from AI SDK v7
|
|
11
13
|
|
|
12
|
-
|
|
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 new durable agent work. It replaces `DurableAgent` and keeps the current agent pattern in the AI SDK package.
|
|
16
15
|
|
|
17
|
-
|
|
16
|
+
- Import `WorkflowAgent` from `@ai-sdk/workflow` and run it inside a `"use workflow"` function.
|
|
17
|
+
- Stream `ModelCallStreamPart` chunks with `getWritable()`, then convert the run stream to UI message chunks with `createModelCallToUIChunkTransform()` in your route.
|
|
18
|
+
- Mark tool `execute` functions with `"use step"` when they should run as durable workflow steps with retry and observability behavior.
|
|
18
19
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
|
20
|
+
<Callout type="warn">
|
|
21
|
+
`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.
|
|
22
|
+
</Callout>
|
|
@@ -5,6 +5,14 @@ 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
|
+
<CopyPrompt
|
|
9
|
+
text="Add a human approval gate to this AI workflow. Define a typed hook with `defineHook()` from `workflow` for approval payloads. At the approval point, create the hook once with a stable token, await it inside the `"use workflow"` function, and branch on approved/rejected input. Add a server route that receives the human decision and calls `resumeHook(token, payload)` from `workflow/api`. If the approval should expire, race the hook against `sleep()` from `workflow`. Update the UI to show the pending approval and call the resume route. Verify approve, reject, timeout, and duplicate resume behavior."
|
|
10
|
+
/>
|
|
11
|
+
|
|
12
|
+
<Callout type="warn">
|
|
13
|
+
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.
|
|
14
|
+
</Callout>
|
|
15
|
+
|
|
8
16
|
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
17
|
|
|
10
18
|
## When to use this
|
|
@@ -247,9 +255,9 @@ const approvalResult = messages
|
|
|
247
255
|
|
|
248
256
|
## Key APIs
|
|
249
257
|
|
|
250
|
-
- [`"use workflow"`](/docs/
|
|
251
|
-
- [`"use step"`](/docs/
|
|
258
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) — declares the orchestrator function
|
|
259
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) — declares step functions with retries
|
|
252
260
|
- [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook with schema validation
|
|
253
261
|
- [`sleep()`](/docs/api-reference/workflow/sleep) — durable timeout for approval expiry
|
|
254
262
|
- [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream custom data parts from steps
|
|
255
|
-
- [`
|
|
263
|
+
- [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) — AI SDK's durable agent (replaces `DurableAgent`)
|
|
@@ -5,6 +5,10 @@ type: guide
|
|
|
5
5
|
summary: Split items into fixed-size batches, process each batch concurrently with Promise.allSettled, and pace batches with sleep to avoid overloading downstream services.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
+
<CopyPrompt
|
|
9
|
+
text="Implement durable batch processing. Import `sleep` from `workflow`. In an exported "use workflow" function, split the input records into chunks of a fixed `batchSize`. For each batch, call a "use step" helper such as `processRecord(record)` for every record using `Promise.allSettled` so one record failure does not hide the rest. Record successes and failures in a serializable result object. Between batches, `await sleep("1s")` or another configured delay to respect downstream rate limits. Make the step idempotent using record IDs or external idempotency keys. Verify all-success, partial-failure, and rate-paced execution paths."
|
|
10
|
+
/>
|
|
11
|
+
|
|
8
12
|
Use batching when you need to process a large list of items in parallel while controlling concurrency. Items are split into fixed-size batches, each batch runs concurrently, and failures in one batch don't affect others.
|
|
9
13
|
|
|
10
14
|
## When to use this
|
|
@@ -1,45 +1,29 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Idempotency
|
|
3
|
-
description:
|
|
3
|
+
description: Make step retries safe and coordinate duplicate workflow starts with hook tokens.
|
|
4
4
|
type: guide
|
|
5
|
-
summary: Use step IDs
|
|
5
|
+
summary: Use step IDs for retry-safe external calls, and use deterministic hook tokens when duplicate requests must route to one active workflow.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
<CopyPrompt
|
|
9
|
+
text="Make this workflow's side effects idempotent. For retry-safe external calls, read the deterministic step ID inside the "use step" function with `getStepMetadata()` from `workflow` and pass `stepId` as the idempotency key to the external API (for example Stripe's `Idempotency-Key` header) so step retries deduplicate. For duplicate workflow starts, derive a deterministic hook token from the domain key (for example `order:${orderId}`): in the API route, look up the active hook with `getHookByToken(token)` from `workflow/api` — catching `HookNotFoundError` from `workflow/errors` — and reuse its `runId`, otherwise call `start(...)`; inside the workflow, create the hook with the same token and check `await hook.getConflict()` before duplicate-sensitive work. Verify retried steps deduplicate, duplicate starts reuse the active run, and conflicts are handled."
|
|
10
|
+
/>
|
|
11
|
+
|
|
12
|
+
Use idempotency when a retry or duplicate request should not repeat the underlying work. In Workflow, there are two common patterns: use the step ID for retry-safe external calls, and use hook tokens to coordinate duplicate workflow starts.
|
|
9
13
|
|
|
10
14
|
## When to use this
|
|
11
15
|
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
- Creating records in external systems where duplicates are harmful
|
|
15
|
-
- Any step that has side effects in systems you don't control
|
|
16
|
+
- A step charges a payment, sends an email, enqueues work, or creates an external record.
|
|
17
|
+
- A route may receive duplicate requests that should map to one active workflow run.
|
|
16
18
|
|
|
17
|
-
##
|
|
19
|
+
## Step idempotency
|
|
18
20
|
|
|
19
21
|
Every step has a unique, deterministic `stepId` available via `getStepMetadata()`. Pass this as the idempotency key to external APIs:
|
|
20
22
|
|
|
21
23
|
```typescript
|
|
22
24
|
import { getStepMetadata } from "workflow";
|
|
23
25
|
|
|
24
|
-
|
|
25
|
-
declare function sendReceipt(customerId: string, chargeId: string): Promise<void>; // @setup
|
|
26
|
-
|
|
27
|
-
export async function chargeCustomer(customerId: string, amount: number) {
|
|
28
|
-
"use workflow";
|
|
29
|
-
|
|
30
|
-
const charge = await createCharge(customerId, amount);
|
|
31
|
-
await sendReceipt(customerId, charge.id);
|
|
32
|
-
|
|
33
|
-
return { customerId, chargeId: charge.id, status: "completed" };
|
|
34
|
-
}
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
### Step function with idempotency key
|
|
38
|
-
|
|
39
|
-
```typescript
|
|
40
|
-
import { getStepMetadata } from "workflow";
|
|
41
|
-
|
|
42
|
-
async function createCharge(
|
|
26
|
+
export async function createCharge(
|
|
43
27
|
customerId: string,
|
|
44
28
|
amount: number
|
|
45
29
|
): Promise<{ id: string }> {
|
|
@@ -69,39 +53,43 @@ async function createCharge(
|
|
|
69
53
|
|
|
70
54
|
return charge.json();
|
|
71
55
|
}
|
|
72
|
-
|
|
73
|
-
async function sendReceipt(customerId: string, chargeId: string): Promise<void> {
|
|
74
|
-
"use step";
|
|
75
|
-
|
|
76
|
-
const { stepId } = getStepMetadata();
|
|
77
|
-
|
|
78
|
-
await fetch("https://api.example.com/receipts", {
|
|
79
|
-
method: "POST",
|
|
80
|
-
headers: { "Idempotency-Key": stepId },
|
|
81
|
-
body: JSON.stringify({ customerId, chargeId }),
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
56
|
```
|
|
85
57
|
|
|
86
|
-
|
|
58
|
+
See [Step Idempotency](/docs/foundations/idempotency#step-idempotency) for why `stepId` is stable across retries and how to think about external API conflicts.
|
|
87
59
|
|
|
88
|
-
|
|
60
|
+
## Run idempotency
|
|
89
61
|
|
|
90
|
-
-
|
|
91
|
-
- **Don't use check-then-act patterns** like "read a flag, then write if not set" -- another run could read the same flag between your read and write.
|
|
62
|
+
For duplicate workflow-start requests, derive a hook token from your domain key. You can avoid obvious duplicate starts by checking whether an active hook already owns that token before calling `start()`:
|
|
92
63
|
|
|
93
|
-
|
|
64
|
+
```typescript
|
|
65
|
+
import { getHookByToken, start } from "workflow/api";
|
|
66
|
+
import { HookNotFoundError } from "workflow/errors";
|
|
67
|
+
import { processOrder } from "./workflows/process-order";
|
|
68
|
+
|
|
69
|
+
export async function POST(request: Request) {
|
|
70
|
+
const { orderId } = await request.json();
|
|
71
|
+
const token = `order:${orderId}`;
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const hook = await getHookByToken(token); // [!code highlight]
|
|
75
|
+
return Response.json({ runId: hook.runId, reused: true });
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (!HookNotFoundError.is(error)) throw error;
|
|
78
|
+
}
|
|
94
79
|
|
|
95
|
-
|
|
80
|
+
const run = await start(processOrder, [orderId]); // [!code highlight]
|
|
81
|
+
return Response.json({ runId: run.runId, reused: false });
|
|
82
|
+
}
|
|
83
|
+
```
|
|
96
84
|
|
|
97
|
-
-
|
|
98
|
-
- **Always provide idempotency keys for non-idempotent external calls.** Even if you think a step won't be retried, cold-start replay will re-execute it.
|
|
99
|
-
- **Handle 409/conflict as success.** If an external API returns "already processed," treat that as a successful result, not an error.
|
|
100
|
-
- **Make your own APIs idempotent** where possible. Accept an idempotency key and return the cached result on duplicate requests.
|
|
85
|
+
The workflow should create the deterministic hook and check `await hook.getConflict()` before duplicate-sensitive work — awaiting `getConflict()` suspends the workflow to commit the hook registration and resolves with the conflicting run when another active run already owns the token (or `null` once the hook is registered). See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for the full pattern, including how to steer an active run with `resumeHook()` and how to handle the current race between `start()` and hook registration.
|
|
101
86
|
|
|
102
87
|
## Key APIs
|
|
103
88
|
|
|
104
|
-
- [`"use workflow"`](/docs/
|
|
105
|
-
- [`"use step"`](/docs/
|
|
106
|
-
- [`getStepMetadata()`](/docs/api-reference/
|
|
89
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) -- declares the orchestrator function
|
|
90
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) -- declares step functions with full Node.js access
|
|
91
|
+
- [`getStepMetadata()`](/docs/api-reference/workflow/get-step-metadata) -- provides the deterministic `stepId` for idempotency keys
|
|
92
|
+
- [`createHook()`](/docs/api-reference/workflow/create-hook) -- creates a hook with an optional deterministic token
|
|
93
|
+
- [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) -- finds the Hook that owns a token
|
|
94
|
+
- [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) -- resumes the active hook when the duplicate request carries data
|
|
107
95
|
- [`start()`](/docs/api-reference/workflow-api/start) -- starts a new workflow run
|
|
@@ -5,6 +5,10 @@ type: guide
|
|
|
5
5
|
summary: When an external API returns 429, throw RetryableError with the Retry-After value so the workflow runtime automatically reschedules the step after the specified delay.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
+
<CopyPrompt
|
|
9
|
+
text="Add durable rate-limit handling to external API steps. Import `RetryableError`, `FatalError`, `getStepMetadata`, and `sleep` from `workflow` as needed. In each HTTP-calling "use step" helper, if the response status is 429, read the `Retry-After` header and throw `new RetryableError("Rate limited", { retryAfter })`. For transient 5xx/network failures, throw `RetryableError` with an exponential delay based on `getStepMetadata().attempt`. For permanent 4xx failures, throw `FatalError`. If the dependency is completely down, add a workflow-level circuit breaker that `await sleep("30s")` before probing again. Make requests idempotent with stable keys, and verify 429, 5xx, fatal 4xx, and circuit-breaker behavior."
|
|
10
|
+
/>
|
|
11
|
+
|
|
8
12
|
Use this pattern when calling external APIs that enforce rate limits. Instead of writing manual retry loops, throw `RetryableError` with a `retryAfter` value and let the workflow runtime handle rescheduling.
|
|
9
13
|
|
|
10
14
|
## When to use this
|
|
@@ -224,5 +228,5 @@ export async function downloadWithRetry(url: string) {
|
|
|
224
228
|
- [`"use step"`](/docs/foundations/workflows-and-steps) -- marks functions that run with full Node.js access
|
|
225
229
|
- [`RetryableError`](/docs/api-reference/workflow/retryable-error) -- signals the runtime to retry after a delay
|
|
226
230
|
- [`FatalError`](/docs/api-reference/workflow/fatal-error) -- signals a permanent failure, skipping retries
|
|
227
|
-
- [`getStepMetadata()`](/docs/api-reference/
|
|
231
|
+
- [`getStepMetadata()`](/docs/api-reference/workflow/get-step-metadata) -- provides the current attempt number and step ID
|
|
228
232
|
- [`sleep()`](/docs/api-reference/workflow/sleep) -- durable pause for circuit breaker cooldowns
|
|
@@ -5,6 +5,10 @@ type: guide
|
|
|
5
5
|
summary: Run a sequence of steps where each registers a compensation. If any step throws a FatalError, compensations execute in reverse order to restore consistency.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
+
<CopyPrompt
|
|
9
|
+
text="Implement a saga-style workflow. Import `FatalError` from `workflow`. In the exported "use workflow" function, keep a compensation stack such as `const compensations: Array<() => Promise<void>> = []`. For each forward side effect, create a "use step" helper, await it, then push the matching compensation "use step" helper onto the stack. Throw `FatalError` for permanent business failures and normal errors for retryable failures. In the workflow catch block, run compensations in reverse order with `for (const compensate of compensations.reverse()) await compensate()`, then rethrow or return a failed status. Make each compensation idempotent. Verify successful completion, a fatal failure after multiple steps, and a replay/retry during rollback."
|
|
10
|
+
/>
|
|
11
|
+
|
|
8
12
|
Use the saga pattern when a business transaction spans multiple services and you need automatic rollback if any step fails. Each forward step registers a compensation, and on failure the workflow unwinds them in reverse order.
|
|
9
13
|
|
|
10
14
|
## When to use this
|
|
@@ -241,7 +245,7 @@ export async function subscriptionUpgradeSaga(accountId: string, seats: number)
|
|
|
241
245
|
|
|
242
246
|
## Key APIs
|
|
243
247
|
|
|
244
|
-
- [`"use workflow"`](/docs/
|
|
245
|
-
- [`"use step"`](/docs/
|
|
248
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions) -- declares the orchestrator function
|
|
249
|
+
- [`"use step"`](/docs/foundations/workflows-and-steps#step-functions) -- declares step functions with full Node.js access
|
|
246
250
|
- [`FatalError`](/docs/api-reference/workflow/fatal-error) -- non-retryable error that triggers compensation
|
|
247
251
|
- [`getWritable()`](/docs/api-reference/workflow/get-writable) -- streams data from workflows for real-time UI updates
|
|
@@ -5,8 +5,16 @@ type: guide
|
|
|
5
5
|
summary: Schedule future actions with durable sleep that survives cold starts, and race sleeps against hooks to let external events cancel the workflow early.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
+
<CopyPrompt
|
|
9
|
+
text="Create an interruptible scheduled workflow. Import `defineHook` and `sleep` from `workflow`. Define a cancellation hook such as `export const cancelDrip = defineHook<{ reason?: string }>()`. In an exported workflow function with "use workflow", create the hook once, send the first message in a "use step" helper, then `await Promise.race([sleep("2d").then(() => false), cancelHook.then(() => true)])` before each delayed action. If the hook wins, return a cancelled status; if sleep wins, continue to the next step. Add an API route that calls `cancelDrip.resume(runIdOrToken, { reason })` or `resumeHook()` from `workflow/api`. Verify scheduled delivery, cancellation before sleep completes, and resume after server restart."
|
|
10
|
+
/>
|
|
11
|
+
|
|
8
12
|
Workflow's `sleep()` is durable — it survives cold starts, restarts, and deployments. Combined with `defineHook()` and `Promise.race()`, it becomes the foundation for interruptible scheduled workflows like drip campaigns, reminders, and timed sequences.
|
|
9
13
|
|
|
14
|
+
<Callout type="info">
|
|
15
|
+
Scheduled workflows are still pinned to the deployment that started them. If you are building recurring or indefinitely running schedules that should adopt newer code over time, see [Versioning](/docs/foundations/versioning) for the explicit `deploymentId: "latest"` continuation pattern.
|
|
16
|
+
</Callout>
|
|
17
|
+
|
|
10
18
|
## When to use this
|
|
11
19
|
|
|
12
20
|
- Sending emails on a schedule (drip campaigns, onboarding sequences, reminders)
|
|
@@ -102,6 +110,10 @@ export async function POST(req: Request) {
|
|
|
102
110
|
3. **Race** — `Promise.race([sleep(...), hook])` blocks until either the timer fires or the hook is resumed, whichever comes first.
|
|
103
111
|
4. **Fresh hooks per window** — after a sleep completes normally, the previous hook instance is consumed. A new `.create()` call registers a fresh hook for the next sleep window, reusing the same token.
|
|
104
112
|
|
|
113
|
+
<Callout type="info">
|
|
114
|
+
Deterministic hook tokens can also serve as the idempotency point for scheduled runs. If duplicate schedule starts would send duplicate campaigns or reminders, create a hook with a token derived from the campaign key near the beginning of the workflow and route retries through that hook. If two scheduled starts race, the duplicate run can detect the conflict early with `await hook.getConflict()`, which resolves with the active owner so the duplicate can defer to it. See [Idempotency](/docs/foundations/idempotency).
|
|
115
|
+
</Callout>
|
|
116
|
+
|
|
105
117
|
## Adapting to your use case
|
|
106
118
|
|
|
107
119
|
- **Change durations** — replace `"2d"` with any duration string (`"1h"`, `"7d"`, `"30m"`) or a `Date` object for absolute times.
|
|
@@ -9,6 +9,10 @@ related:
|
|
|
9
9
|
- /cookbook/common-patterns/scheduling
|
|
10
10
|
---
|
|
11
11
|
|
|
12
|
+
<CopyPrompt
|
|
13
|
+
text="Compose these workflow steps with standard async/await patterns. In the exported "use workflow" function, chain dependent "use step" calls with sequential `await`; run independent steps concurrently by starting them without `await` and awaiting `Promise.all([...])`; and use `Promise.race([...])` to act on whichever promise settles first. These compose with durable primitives — race a step or a webhook from `createWebhook()` against `sleep()` from `workflow` for deadlines. Keep every step input and output serializable, and remember `Promise.race` does not cancel the losing branch — it keeps running — so side-effectful losers need idempotency keys. Verify sequential ordering, parallel execution, and both race outcomes."
|
|
14
|
+
/>
|
|
15
|
+
|
|
12
16
|
Workflows are written in plain async/await — there's no new control-flow API to learn. Sequential awaits chain steps that depend on each other, `Promise.all` runs independent steps in parallel, and `Promise.race` returns whichever finishes first. These compose with workflow primitives like [`sleep()`](/docs/api-reference/workflow/sleep) and [`createWebhook()`](/docs/api-reference/workflow/create-webhook) since those are also just promises.
|
|
13
17
|
|
|
14
18
|
## When to use this
|
|
@@ -10,6 +10,10 @@ related:
|
|
|
10
10
|
- /cookbook/common-patterns/webhooks
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
+
<CopyPrompt
|
|
14
|
+
text="Add a deadline to this slow workflow operation. Import `sleep` from `workflow`. In the exported "use workflow" function, race the operation against a durable sleep: `await Promise.race([slowStep(...), deadline("10m")])`, where `deadline` is a helper that awaits `sleep(duration)` and returns a sentinel value or throws. Branch on the winner: continue normally on success, run the fallback or compensation path on timeout. Use the same pattern to bound hooks and webhooks. `Promise.race` does not cancel the loser — the underlying step keeps running — so pass an `AbortSignal` into the step for cooperative cancellation and make non-idempotent side effects retry-safe with idempotency keys. Verify the fast path, the timeout path, and side-effect safety when the loser completes late."
|
|
15
|
+
/>
|
|
16
|
+
|
|
13
17
|
A common requirement is bounding how long a workflow waits for something to finish — a slow step, an external webhook, a human approval. Race the operation against a durable `sleep()` with `Promise.race()` — whichever finishes first wins, and the loser keeps running but its result is ignored.
|
|
14
18
|
|
|
15
19
|
## When to use this
|
|
@@ -80,7 +84,7 @@ export async function waitForApproval(requestId: string) {
|
|
|
80
84
|
4. **Throw to fail the workflow** — inside a workflow function, throwing an `Error` exits the run with that error. Use `FatalError` inside steps; throw plain errors inside workflows.
|
|
81
85
|
|
|
82
86
|
<Callout type="warn">
|
|
83
|
-
**The losing operation keeps running.** `Promise.race` doesn't cancel — when the sleep wins, the underlying step (or model call, or HTTP request) continues to completion in the background. This is fine for idempotent reads but matters when the operation has side effects or costs money.
|
|
87
|
+
**The losing operation keeps running.** `Promise.race` doesn't cancel — when the sleep wins, the underlying step (or model call, or HTTP request) continues to completion in the background. This is fine for idempotent reads but matters when the operation has side effects or costs money. Pass an `AbortSignal` into the step to cancel it cooperatively, and use idempotency keys for non-idempotent side effects. See the [Cancellation Guide](/docs/foundations/cancellation) and [Idempotency](/docs/foundations/idempotency) for patterns.
|
|
84
88
|
</Callout>
|
|
85
89
|
|
|
86
90
|
## Adapting to your use case
|
|
@@ -96,4 +100,5 @@ export async function waitForApproval(requestId: string) {
|
|
|
96
100
|
- [`sleep()`](/docs/api-reference/workflow/sleep) — durable wait (survives restarts, zero compute cost)
|
|
97
101
|
- [`createWebhook()`](/docs/api-reference/workflow/create-webhook) — create a webhook URL the workflow can race against
|
|
98
102
|
- [`defineHook()`](/docs/api-reference/workflow/define-hook) — typed hook for in-process cancellation
|
|
103
|
+
- [Idempotency](/docs/foundations/idempotency) — protect side effects that may keep running after a timeout
|
|
99
104
|
- [`Promise.race()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) — race operations against deadlines
|
|
@@ -5,6 +5,10 @@ type: guide
|
|
|
5
5
|
summary: Create webhook endpoints that your workflow can await, process incoming requests in steps, and respond to the caller — all within durable workflow context.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
+
<CopyPrompt
|
|
9
|
+
text="Implement durable webhook handling for this workflow. Use `createWebhook()` from `workflow` inside the "use workflow" function when the workflow needs a generated callback URL. Use `createWebhook({ respondWith: "manual" })` when the workflow must validate the request before sending an HTTP response. Await the webhook request, pass the `RequestWithResponse` into a "use step" function for validation and side effects, and call `request.respondWith(Response.json(...))` on every code path. Race the webhook against `sleep()` for deadlines and throw `FatalError` for permanent timeout/failure paths. For fixed public callbacks or large payloads, use `defineHook()` plus `resumeHook()` from `workflow/api` and pass only a token or blob reference into the hook payload. Verify success response, invalid response, timeout, duplicate callback, and large-payload behavior."
|
|
10
|
+
/>
|
|
11
|
+
|
|
8
12
|
Use webhooks when external services push events to your application via HTTP callbacks. The workflow creates a webhook URL, suspends with zero compute cost, and resumes when a request arrives.
|
|
9
13
|
|
|
10
14
|
## When to use this
|
|
@@ -5,11 +5,16 @@ type: guide
|
|
|
5
5
|
summary: Compose workflows two ways — direct await flattens the child into the parent's event log, while background spawn via start() runs the child as an independent run.
|
|
6
6
|
related:
|
|
7
7
|
- /cookbook/advanced/child-workflows
|
|
8
|
+
- /cookbook/common-patterns/idempotency
|
|
8
9
|
- /docs/api-reference/workflow-api/start
|
|
9
10
|
- /docs/api-reference/workflow-api/get-run
|
|
10
11
|
---
|
|
11
12
|
|
|
12
|
-
|
|
13
|
+
<CopyPrompt
|
|
14
|
+
text="Compose these workflows. For direct composition, `await` the child workflow function from the parent "use workflow" function — the child's steps flatten into the parent's event log and run as a single run sharing the parent's lifecycle. For independent background work, spawn the child with `start()` from `workflow/api` called directly in the workflow (in v5, `start()` is step-backed and records a deterministic step boundary) and return `run.runId` so callers can track it with `getRun()`. Choose flattening when the parent needs the child's result; choose background spawn when the child should have its own run, retries, and lifetime. Keep all inputs and outputs serializable. Verify flattened execution, background spawn with a separate runId, and replay determinism."
|
|
15
|
+
/>
|
|
16
|
+
|
|
17
|
+
Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or wants to fire the child off as an independent run (background spawn). For massive fan-out with hook-based waiting and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
|
|
13
18
|
|
|
14
19
|
## When to use this
|
|
15
20
|
|
|
@@ -53,7 +58,7 @@ The parent waits for the child to finish before continuing. Both functions share
|
|
|
53
58
|
|
|
54
59
|
### Background spawn via `start()`
|
|
55
60
|
|
|
56
|
-
To run a child workflow independently without blocking the parent, call [`start()`](/docs/api-reference/workflow-api/start) from
|
|
61
|
+
To run a child workflow independently without blocking the parent, call [`start()`](/docs/api-reference/workflow-api/start) from the parent workflow. This launches the child as a separate workflow run with its own `runId`.
|
|
57
62
|
|
|
58
63
|
```typescript lineNumbers
|
|
59
64
|
import { start } from "workflow/api";
|
|
@@ -62,37 +67,34 @@ declare function generateReport(reportId: string): Promise<void>; // @setup
|
|
|
62
67
|
declare function fulfillOrder(orderId: string): Promise<{ id: string }>; // @setup
|
|
63
68
|
declare function sendConfirmation(orderId: string): Promise<void>; // @setup
|
|
64
69
|
|
|
65
|
-
async function triggerReportGeneration(reportId: string) {
|
|
66
|
-
"use step"; // [!code highlight]
|
|
67
|
-
|
|
68
|
-
const run = await start(generateReport, [reportId]); // [!code highlight]
|
|
69
|
-
return run.runId;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
70
|
export async function processOrder(orderId: string) {
|
|
73
71
|
"use workflow";
|
|
74
72
|
|
|
75
73
|
const order = await fulfillOrder(orderId);
|
|
76
74
|
|
|
77
|
-
const
|
|
75
|
+
const reportRun = await start(generateReport, [orderId]); // [!code highlight]
|
|
78
76
|
|
|
79
77
|
await sendConfirmation(orderId);
|
|
80
78
|
|
|
81
|
-
return { orderId, reportRunId };
|
|
79
|
+
return { orderId, reportRunId: reportRun.runId };
|
|
82
80
|
}
|
|
83
81
|
```
|
|
84
82
|
|
|
85
83
|
The parent continues immediately after `start()` returns. The child runs independently and can be monitored separately using the returned `runId` (e.g., via [`getRun()`](/docs/api-reference/workflow-api/get-run)).
|
|
86
84
|
|
|
87
85
|
<Callout type="info">
|
|
88
|
-
|
|
86
|
+
Each background spawn creates a separate run. If duplicate requests must route to one active child workflow, have the child create a deterministic hook token from the business key and use that hook as the idempotency point. If concurrent starts race, the losing child can detect the conflict early with `await hook.getConflict()`, which resolves with the active owner so the child can point callers at it. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
|
|
87
|
+
</Callout>
|
|
88
|
+
|
|
89
|
+
<Callout type="info">
|
|
90
|
+
If you want the child workflow to run on the latest deployment rather than the current one, pass [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest) in the `start()` options. See [Versioning](/docs/foundations/versioning) for the full model. This is currently a Vercel-specific feature, and other Worlds may map the concept to their own deployment runtimes. Be aware that the child workflow's function name, file path, argument types, and return type must remain compatible across deployments — renaming the function or changing its location will change the workflow ID, and modifying expected inputs or outputs can cause serialization failures.
|
|
89
91
|
</Callout>
|
|
90
92
|
|
|
91
93
|
## How it works
|
|
92
94
|
|
|
93
95
|
1. **Direct await flattens.** When a workflow function awaits another workflow function, the child's `"use workflow"` directive is treated as inline — the child's steps emit into the parent's event log and share the parent's run ID.
|
|
94
96
|
2. **`start()` mints a new run.** The child gets its own `runId`, its own event log, and its own retry boundary. The parent only sees the `runId` returned by `start()`.
|
|
95
|
-
3. **`start()`
|
|
97
|
+
3. **`start()` can run inside workflows.** In v5, `start()` is step-backed, so it can be called directly from a workflow function and still records a deterministic step boundary in the event log.
|
|
96
98
|
|
|
97
99
|
## Choosing between the two modes
|
|
98
100
|
|
|
@@ -106,9 +108,9 @@ If you want the child workflow to run on the latest deployment rather than the c
|
|
|
106
108
|
|
|
107
109
|
## Adapting to your use case
|
|
108
110
|
|
|
109
|
-
- **Spawn many children at once** — call `start()` in a loop
|
|
110
|
-
- **Wait for a background child to finish** — combine `start()` with
|
|
111
|
-
- **Pass results back from background children** — the
|
|
111
|
+
- **Spawn many children at once** — call `start()` in a loop from the workflow. For more advanced fan-out (chunking, hook-based waiting, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
|
|
112
|
+
- **Wait for a background child to finish** — combine `start()` with a completion hook the child resumes when done. The [Child Workflows](/cookbook/advanced/child-workflows) page covers the recommended `startAndWait()` pattern.
|
|
113
|
+
- **Pass results back from background children** — the wrapped child resumes the parent's hook in `finally` with `{ status, value | error }`; the parent awaits the hook instead of polling `getRun().status`.
|
|
112
114
|
|
|
113
115
|
## Key APIs
|
|
114
116
|
|
|
@@ -116,3 +118,4 @@ If you want the child workflow to run on the latest deployment rather than the c
|
|
|
116
118
|
- [`"use step"`](/docs/foundations/workflows-and-steps) — marks functions with full Node.js access
|
|
117
119
|
- [`start()`](/docs/api-reference/workflow-api/start) — spawn a child workflow as a separate run
|
|
118
120
|
- [`getRun()`](/docs/api-reference/workflow-api/get-run) — retrieve a workflow run's status and return value
|
|
121
|
+
- [Idempotency](/docs/foundations/idempotency) — deduplicate step side effects and workflow starts
|
package/docs/cookbook/index.mdx
CHANGED
|
@@ -8,7 +8,7 @@ A curated collection of workflow patterns with clean, copy-paste code examples f
|
|
|
8
8
|
|
|
9
9
|
## Agent Patterns
|
|
10
10
|
|
|
11
|
-
- [**
|
|
11
|
+
- [**WorkflowAgent**](/cookbook/agent-patterns/durable-agent) — Build durable, resumable AI agents with AI SDK's WorkflowAgent
|
|
12
12
|
- [**Human-in-the-Loop**](/cookbook/agent-patterns/human-in-the-loop) — Pause an agent for human approval, then resume based on the decision
|
|
13
13
|
- [**Agent Cancellation**](/cookbook/agent-patterns/agent-cancellation) — Stop a running agent immediately via `run.cancel()` or gracefully via a hook + `Promise.race`
|
|
14
14
|
|
|
@@ -21,7 +21,7 @@ A curated collection of workflow patterns with clean, copy-paste code examples f
|
|
|
21
21
|
- [**Rate Limiting**](/cookbook/common-patterns/rate-limiting) — Handle 429 responses and transient failures with RetryableError and backoff
|
|
22
22
|
- [**Scheduling**](/cookbook/common-patterns/scheduling) — Use durable sleep to schedule actions minutes, hours, or weeks ahead
|
|
23
23
|
- [**Timeouts**](/cookbook/common-patterns/timeouts) — Add deadlines to slow steps, hooks, and webhooks by racing them against a durable sleep
|
|
24
|
-
- [**Idempotency**](/cookbook/common-patterns/idempotency) — Ensure side effects
|
|
24
|
+
- [**Idempotency**](/cookbook/common-patterns/idempotency) — Ensure side effects and duplicate starts are safe to retry
|
|
25
25
|
- [**Webhooks**](/cookbook/common-patterns/webhooks) — Receive HTTP callbacks from external services and process them durably
|
|
26
26
|
|
|
27
27
|
## Integrations
|
|
@@ -33,6 +33,6 @@ A curated collection of workflow patterns with clean, copy-paste code examples f
|
|
|
33
33
|
## Advanced
|
|
34
34
|
|
|
35
35
|
- [**Child Workflows**](/cookbook/advanced/child-workflows) — Spawn and orchestrate child workflows from a parent
|
|
36
|
-
- [**
|
|
36
|
+
- [**Upgrading Workflows**](/cookbook/advanced/upgrading-workflows) — Identify a clean upgrade point in a long-running workflow and spawn a fresh run on the latest deployment carrying state forward
|
|
37
37
|
- [**Serializable Steps**](/cookbook/advanced/serializable-steps) — Wrap non-serializable third-party objects so they cross the workflow boundary
|
|
38
38
|
- [**Publishing Libraries**](/cookbook/advanced/publishing-libraries) — Ship npm packages that export reusable workflow functions
|