workflow 5.0.0-beta.2 → 5.0.0-beta.21
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/dist/api-workflow.d.ts +1 -1
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +2 -2
- package/dist/api.d.ts +5 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +14 -2
- 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/observability.d.ts +1 -1
- package/dist/observability.js +2 -2
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2 -2
- package/docs/ai/index.mdx +27 -23
- 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 +38 -0
- package/docs/api-reference/workflow/create-webhook.mdx +1 -0
- package/docs/api-reference/workflow/experimental-set-attributes.mdx +65 -0
- package/docs/api-reference/workflow/fetch.mdx +5 -0
- package/docs/api-reference/workflow/index.mdx +3 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +7 -45
- package/docs/api-reference/workflow-api/get-hook-by-token.mdx +7 -0
- package/docs/api-reference/workflow-api/get-run.mdx +6 -0
- package/docs/api-reference/workflow-api/index.mdx +6 -8
- package/docs/api-reference/workflow-api/resume-hook.mdx +57 -0
- package/docs/api-reference/workflow-api/start.mdx +13 -5
- 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 +85 -0
- package/docs/api-reference/workflow-errors/meta.json +5 -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-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 +59 -0
- package/docs/api-reference/workflow-nuxt/index.mdx +47 -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-api → workflow-runtime}/world/index.mdx +5 -8
- package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/queue.mdx +2 -2
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +11 -4
- 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 +1 -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 +2 -1
- package/docs/changelog/lazy-event-creation.md +127 -0
- package/docs/changelog/meta.json +7 -1
- package/docs/changelog/resilient-start.mdx +31 -283
- package/docs/changelog/turbo-mode.md +87 -0
- package/docs/cookbook/advanced/child-workflows.mdx +315 -0
- package/docs/cookbook/advanced/meta.json +2 -3
- package/docs/cookbook/advanced/publishing-libraries.mdx +87 -29
- package/docs/cookbook/advanced/serializable-steps.mdx +17 -5
- package/docs/cookbook/advanced/upgrading-workflows.mdx +195 -0
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +156 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +11 -184
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +150 -173
- package/docs/cookbook/agent-patterns/meta.json +1 -7
- package/docs/cookbook/common-patterns/batching.mdx +44 -118
- package/docs/cookbook/common-patterns/idempotency.mdx +36 -52
- package/docs/cookbook/common-patterns/meta.json +4 -4
- package/docs/cookbook/common-patterns/rate-limiting.mdx +1 -1
- package/docs/cookbook/common-patterns/saga.mdx +128 -33
- package/docs/cookbook/common-patterns/scheduling.mdx +77 -193
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +100 -0
- package/docs/cookbook/common-patterns/workflow-composition.mdx +117 -0
- package/docs/cookbook/index.mdx +14 -17
- package/docs/cookbook/integrations/ai-sdk.mdx +330 -142
- package/docs/cookbook/integrations/chat-sdk.mdx +264 -151
- package/docs/cookbook/integrations/sandbox.mdx +482 -81
- package/docs/cookbook/meta.json +1 -1
- package/docs/deploying/building-a-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +5 -3
- package/docs/deploying/world/vercel-world.mdx +2 -0
- package/docs/errors/abort-signal-timeout-in-workflow.mdx +80 -0
- package/docs/errors/corrupted-event-log.mdx +5 -5
- package/docs/errors/hook-conflict.mdx +56 -4
- package/docs/errors/index.mdx +9 -0
- package/docs/errors/replay-divergence.mdx +27 -0
- package/docs/errors/runtime-decryption-failed.mdx +77 -0
- package/docs/errors/step-executed-multiple-times.mdx +23 -0
- package/docs/errors/step-not-registered.mdx +1 -1
- 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 +236 -11
- package/docs/foundations/index.mdx +3 -3
- package/docs/foundations/meta.json +3 -2
- package/docs/foundations/serialization.mdx +78 -42
- package/docs/foundations/starting-workflows.mdx +6 -2
- package/docs/foundations/streaming.mdx +14 -23
- package/docs/foundations/versioning.mdx +263 -0
- package/docs/getting-started/astro.mdx +6 -0
- package/docs/getting-started/index.mdx +6 -7
- package/docs/getting-started/meta.json +1 -0
- package/docs/getting-started/nestjs.mdx +9 -0
- package/docs/getting-started/next.mdx +5 -3
- package/docs/getting-started/nitro.mdx +22 -0
- package/docs/getting-started/sveltekit.mdx +6 -0
- package/docs/getting-started/tanstack-start.mdx +241 -0
- package/docs/how-it-works/cancellation.mdx +287 -0
- package/docs/how-it-works/code-transform.mdx +2 -2
- package/docs/how-it-works/encryption.mdx +2 -2
- package/docs/how-it-works/event-sourcing.mdx +2 -2
- 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/migration-guides/migrating-from-aws-step-functions.mdx +63 -16
- package/docs/migration-guides/migrating-from-inngest.mdx +44 -22
- package/docs/migration-guides/migrating-from-temporal.mdx +43 -14
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +59 -27
- package/docs/observability/attributes.mdx +87 -0
- package/docs/observability/index.mdx +25 -1
- package/docs/observability/meta.json +1 -1
- package/docs/observability/tracing.mdx +106 -0
- package/docs/testing/index.mdx +2 -2
- package/package.json +14 -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/custom-serialization.mdx +0 -168
- package/docs/cookbook/advanced/durable-objects.mdx +0 -148
- package/docs/cookbook/advanced/isomorphic-packages.mdx +0 -145
- package/docs/cookbook/agent-patterns/stop-workflow.mdx +0 -216
- package/docs/cookbook/agent-patterns/tool-orchestration.mdx +0 -255
- package/docs/cookbook/agent-patterns/tool-streaming.mdx +0 -181
- package/docs/cookbook/common-patterns/child-workflows.mdx +0 -372
- package/docs/cookbook/common-patterns/content-router.mdx +0 -207
- package/docs/cookbook/common-patterns/fan-out.mdx +0 -208
- package/docs/foundations/common-patterns.mdx +0 -265
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Upgrading Workflows
|
|
3
|
+
description: Identify a clean upgrade point in a long-running workflow and spawn a fresh run on the latest deployment carrying state forward.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: 'Identify a clean upgrade point and hand off to a fresh run via `start(self, [state], { deploymentId: "latest" })` — either automatically on every iteration, or on demand via a dedicated upgrade hook.'
|
|
6
|
+
related:
|
|
7
|
+
- /docs/foundations/versioning
|
|
8
|
+
- /cookbook/common-patterns/workflow-composition
|
|
9
|
+
- /docs/api-reference/workflow-api/start
|
|
10
|
+
- /docs/foundations/hooks
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
Workflows that block on external events for days, weeks, or months can outlive many deployments. **The key is to identify a clean upgrade point in the workflow** — a moment where it's safe to checkpoint state and start fresh — and then call [`start()`](/docs/api-reference/workflow-api/start) with `deploymentId: "latest"` to spawn a new run carrying that state forward. The current run ends; the next run begins on whatever deployment is live at that moment, so shipped fixes apply immediately without ever migrating an in-flight run.
|
|
14
|
+
|
|
15
|
+
<Callout type="info">
|
|
16
|
+
For the underlying model — why runs pin to a deployment by default, how cancel-and-rerun works, and how state crosses the version boundary — see [Versioning](/docs/foundations/versioning). This recipe focuses on event-driven workflows that need to keep advancing across deployments.
|
|
17
|
+
</Callout>
|
|
18
|
+
|
|
19
|
+
A clean upgrade point is any spot in the workflow where:
|
|
20
|
+
|
|
21
|
+
- All in-progress side effects have completed (or aren't needed by the next iteration)
|
|
22
|
+
- The relevant state can be serialized into the workflow's input arguments
|
|
23
|
+
- It's natural for the workflow to "checkpoint" — typically right after handling an external event, completing a batch, or finishing a logical phase
|
|
24
|
+
|
|
25
|
+
There are two ways to apply this:
|
|
26
|
+
|
|
27
|
+
1. **Upgrade on every iteration** ([Method 1](#method-1-upgrade-on-every-iteration)). Each run handles a single event and unconditionally hands off to a fresh run on the latest deployment before exiting. Simple — no extra triggers — but every event pays the respawn cost.
|
|
28
|
+
2. **Upgrade on demand via a dedicated hook** ([Method 2](#method-2-upgrade-on-demand-via-a-dedicated-hook)). A single long-lived run handles many events in a loop and only respawns when an `upgradeHook` fires. A separate endpoint resumes that hook from your control plane (e.g. after a deploy). More control and fewer respawns, at the cost of an explicit trigger.
|
|
29
|
+
|
|
30
|
+
### When to use each
|
|
31
|
+
|
|
32
|
+
- **Method 1** when iterations are short and frequent, the work is cheap to checkpoint, and you want shipped fixes to apply on the very next event. Long-lived "session" workflows (subscriptions, queues, FSMs) that already process events one at a time fit this naturally.
|
|
33
|
+
- **Method 2** when iterations are infrequent or expensive (you don't want to respawn on every event), or when you need to roll out a fix to a fleet of in-flight runs after a deploy by fanning out to a control-plane endpoint. Also fits when "upgrade" should be an explicit operation rather than a side effect of handling each event.
|
|
34
|
+
|
|
35
|
+
## Method 1: Upgrade on every iteration
|
|
36
|
+
|
|
37
|
+
Each run inherits state via its argument, blocks on a hook, processes the resume, then unconditionally hands off to its successor by calling `start()` directly from the workflow body with `deploymentId: "latest"`.
|
|
38
|
+
|
|
39
|
+
```typescript lineNumbers
|
|
40
|
+
import { defineHook, getWorkflowMetadata } from "workflow";
|
|
41
|
+
import { start } from "workflow/api";
|
|
42
|
+
|
|
43
|
+
declare function processItem(itemId: string): Promise<void>; // @setup
|
|
44
|
+
|
|
45
|
+
interface QueueState {
|
|
46
|
+
processed: number;
|
|
47
|
+
cursor: string | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const nextItemHook = defineHook<{ itemId: string }>();
|
|
51
|
+
|
|
52
|
+
export async function longRunningQueue(
|
|
53
|
+
state: QueueState = { processed: 0, cursor: null },
|
|
54
|
+
): Promise<void> {
|
|
55
|
+
"use workflow";
|
|
56
|
+
|
|
57
|
+
const { workflowRunId } = getWorkflowMetadata();
|
|
58
|
+
|
|
59
|
+
// Block until something fires the hook — could be hours, days, or longer.
|
|
60
|
+
// Per-run hook tokens (workflowRunId) keep concurrent chains isolated.
|
|
61
|
+
const { itemId } = await nextItemHook.create({ token: workflowRunId }); // [!code highlight]
|
|
62
|
+
|
|
63
|
+
await processItem(itemId);
|
|
64
|
+
|
|
65
|
+
// Hand off to a fresh run on the latest deployment. THIS run ends here.
|
|
66
|
+
// `deploymentId: "latest"` resolves to whichever deployment is current
|
|
67
|
+
// when this spawn lands — NOT the deployment running this code.
|
|
68
|
+
await start( // [!code highlight]
|
|
69
|
+
longRunningQueue, // [!code highlight]
|
|
70
|
+
[{ processed: state.processed + 1, cursor: itemId }], // [!code highlight]
|
|
71
|
+
{ deploymentId: "latest" }, // [!code highlight]
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Resuming the hook
|
|
77
|
+
|
|
78
|
+
Any server-side code can resume the currently-active iteration by calling `.resume()` with the run ID:
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import { nextItemHook } from "@/workflows/long-running-queue";
|
|
82
|
+
|
|
83
|
+
export async function POST(req: Request) {
|
|
84
|
+
const { runId, itemId } = await req.json();
|
|
85
|
+
|
|
86
|
+
await nextItemHook.resume(runId, { itemId }); // [!code highlight]
|
|
87
|
+
|
|
88
|
+
return Response.json({ success: true });
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
The caller tracks the active `runId` (e.g. in a database, KV, or returned from the previous iteration) and updates it whenever the chain advances.
|
|
93
|
+
|
|
94
|
+
## Method 2: Upgrade on demand via a dedicated hook
|
|
95
|
+
|
|
96
|
+
Use a single long-running workflow that handles events in a loop. Define a second hook — `upgradeHook` — alongside the work hook, and race them. While only the work hook fires, the run keeps handling events on its current deployment. When `upgradeHook` resumes, the workflow captures current state and respawns on the latest deployment, then exits.
|
|
97
|
+
|
|
98
|
+
```typescript lineNumbers
|
|
99
|
+
import { defineHook, getWorkflowMetadata } from "workflow";
|
|
100
|
+
import { start } from "workflow/api";
|
|
101
|
+
|
|
102
|
+
declare function processItem(itemId: string): Promise<void>; // @setup
|
|
103
|
+
|
|
104
|
+
interface QueueState {
|
|
105
|
+
processed: number;
|
|
106
|
+
cursor: string | null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export const nextItemHook = defineHook<{ itemId: string }>();
|
|
110
|
+
export const upgradeHook = defineHook<{ reason?: string }>(); // [!code highlight]
|
|
111
|
+
|
|
112
|
+
export async function longRunningQueue(
|
|
113
|
+
state: QueueState = { processed: 0, cursor: null },
|
|
114
|
+
): Promise<void> {
|
|
115
|
+
"use workflow";
|
|
116
|
+
|
|
117
|
+
const { workflowRunId } = getWorkflowMetadata();
|
|
118
|
+
|
|
119
|
+
while (true) {
|
|
120
|
+
// Race a normal work event against the upgrade signal.
|
|
121
|
+
const event = await Promise.race([ // [!code highlight]
|
|
122
|
+
nextItemHook
|
|
123
|
+
.create({ token: workflowRunId })
|
|
124
|
+
.then((payload) => ({ kind: "work" as const, payload })),
|
|
125
|
+
upgradeHook // [!code highlight]
|
|
126
|
+
.create({ token: workflowRunId }) // [!code highlight]
|
|
127
|
+
.then(() => ({ kind: "upgrade" as const })), // [!code highlight]
|
|
128
|
+
]);
|
|
129
|
+
|
|
130
|
+
if (event.kind === "upgrade") { // [!code highlight]
|
|
131
|
+
// Checkpoint current state and hand off to a fresh run
|
|
132
|
+
// on whatever deployment is live now. THIS run ends here.
|
|
133
|
+
await start(longRunningQueue, [state], { // [!code highlight]
|
|
134
|
+
deploymentId: "latest", // [!code highlight]
|
|
135
|
+
}); // [!code highlight]
|
|
136
|
+
return; // [!code highlight]
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
await processItem(event.payload.itemId);
|
|
140
|
+
state = {
|
|
141
|
+
processed: state.processed + 1,
|
|
142
|
+
cursor: event.payload.itemId,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Triggering the upgrade
|
|
149
|
+
|
|
150
|
+
Expose a separate endpoint that resumes `upgradeHook` for a given run. Call it from your deploy pipeline, an admin UI, or a fan-out script that iterates over every active run after shipping a fix.
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
import { upgradeHook } from "@/workflows/long-running-queue";
|
|
154
|
+
|
|
155
|
+
export async function POST(req: Request) {
|
|
156
|
+
const { runId, reason } = await req.json();
|
|
157
|
+
|
|
158
|
+
// The workflow exits its loop, captures state, and respawns
|
|
159
|
+
// on the latest deployment.
|
|
160
|
+
await upgradeHook.resume(runId, { reason }); // [!code highlight]
|
|
161
|
+
|
|
162
|
+
return Response.json({ success: true });
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
To upgrade a fleet of runs after a deploy, list active runs (e.g. from a tracking store) and call this endpoint for each.
|
|
167
|
+
|
|
168
|
+
## How it works
|
|
169
|
+
|
|
170
|
+
1. **`deploymentId: "latest"` is the upgrade knob.** Without it, the spawn pins to the current deployment. With it, the new run resolves to whatever deployment is current when the runtime picks it up — so any shipped fix applies starting from that respawn. Both methods rely on this.
|
|
171
|
+
2. **`start()` runs directly from the workflow body.** In v5, [`start()`](/docs/api-reference/workflow-api/start) is step-backed, so it can be called from a workflow function and still records a deterministic step boundary in the event log — no manual `"use step"` wrapper is required.
|
|
172
|
+
3. **State carries through the function argument.** The accumulating context flows from run N to run N+1 as a serialized argument. No external store is required for the state itself.
|
|
173
|
+
4. **Per-run hook tokens.** Using `workflowRunId` as the hook token scopes each iteration's wait to its own run, so multiple chains can run concurrently without interfering.
|
|
174
|
+
5. **Method 1 vs Method 2 is just where the spawn happens.** In Method 1 every run spawns its successor unconditionally before exiting — there is no long-lived process to migrate. In Method 2 the spawn happens only when the upgrade hook fires; otherwise the loop keeps handling events on the same run.
|
|
175
|
+
|
|
176
|
+
## Adapting to your use case
|
|
177
|
+
|
|
178
|
+
- **Combine with a sleep.** Race the hook against `sleep()` so iterations also tick on a timer: `Promise.race([hook, sleep("1d")])` lets the workflow advance even if no external event arrives.
|
|
179
|
+
- **Stateless successors.** If the next iteration doesn't need the previous state (e.g. a pure event router), call `start(longRunningQueue, [], { deploymentId: "latest" })` and skip the argument plumbing.
|
|
180
|
+
- **Persist state externally.** If state needs to be readable from outside the workflow (dashboards, debugging, recovery), write it to a database in a step before spawning the next run.
|
|
181
|
+
- **Track the active runId externally.** Whatever resumes the hook needs to know the current run. Capture the `runId` returned by `start()` and write it to a KV/database keyed by a stable session identifier (in a step) so resumers always look up the latest one.
|
|
182
|
+
|
|
183
|
+
## Caveats
|
|
184
|
+
|
|
185
|
+
- **Backward compatibility matters.** Because the next run executes on a different deployment, the workflow's input arguments and return type must remain compatible across deployments. Adding required fields, removing fields, or changing types can cause serialization failures. See the [`deploymentId: "latest"` callout](/docs/api-reference/workflow-api/start#using-deploymentid-latest).
|
|
186
|
+
- **Workflow identity is the function name + file path.** Renaming the function or moving the file across a deployment changes the workflow ID — the next iteration will fail to resolve. Treat the workflow's name and location as stable interfaces.
|
|
187
|
+
- **There is a tiny gap between iterations.** The current run ends as soon as `start()` returns; the next run starts asynchronously. A resume that arrives in that window can fail with "hook not found." Make resumers retry, or have the API persist pending payloads and apply them once the next iteration is ready.
|
|
188
|
+
- **Method 2: track active runs externally.** Because Method 2's runs are long-lived, the set of in-flight runs only changes when one starts, completes, or upgrades. Persist run IDs (and clean them up on completion or upgrade) so a rollout script can fan out reliably. After resuming `upgradeHook`, also update the tracked run ID once the new run reports back, the same way you would in Method 1.
|
|
189
|
+
|
|
190
|
+
## Key APIs
|
|
191
|
+
|
|
192
|
+
- [`"use workflow"`](/docs/foundations/workflows-and-steps) — marks the orchestrator function
|
|
193
|
+
- [`start()`](/docs/api-reference/workflow-api/start) with [`deploymentId: "latest"`](/docs/api-reference/workflow-api/start#using-deploymentid-latest) — spawn the successor on the newest deployment
|
|
194
|
+
- [`defineHook()`](/docs/api-reference/workflow/define-hook) — suspend the workflow until an external event resumes it
|
|
195
|
+
- [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata) — exposes `workflowRunId` for per-run hook tokens
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Agent Cancellation
|
|
3
|
+
description: Cancel a running agent from the outside using AbortSignal — a hook fires the abort, the agent step bails out of the model stream, and the client gets a clean stop notification.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Cancel a running agent cooperatively with AbortController. A stop hook fires controller.abort(), the signal propagates into the agent step to cancel the model stream, and a data-stopped part is emitted to streaming clients before the workflow returns.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
Cancel a running agent from the outside — for example, a "Stop" button in a chat UI, an admin cancellation endpoint, or a timeout fallback.
|
|
9
|
+
|
|
10
|
+
## Pattern
|
|
11
|
+
|
|
12
|
+
Create an `AbortController` in the workflow and race the agent (passing its signal) against a stop hook. When the hook fires, `controller.abort()` is called — the signal propagates into the agent step and cancels the underlying model stream. Before returning, a `data-stopped` part is written to the stream so any streaming clients can render a clean end state.
|
|
13
|
+
|
|
14
|
+
```typescript lineNumbers
|
|
15
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
16
|
+
import { defineHook, getWritable, getWorkflowMetadata } from "workflow";
|
|
17
|
+
import { z } from "zod";
|
|
18
|
+
import type { ModelMessage, UIMessageChunk } from "ai";
|
|
19
|
+
|
|
20
|
+
export const stopHook = defineHook({
|
|
21
|
+
schema: z.object({ reason: z.string().optional() }),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
async function searchWeb({ query }: { query: string }) {
|
|
25
|
+
"use step";
|
|
26
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
27
|
+
return { results: [{ title: `${query} - Wikipedia`, snippet: `Overview of ${query}...` }] };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function analyzeData({ topic }: { topic: string }) {
|
|
31
|
+
"use step";
|
|
32
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
33
|
+
return { summary: `Analysis of ${topic}: significant developments found.`, confidence: 0.85 };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function emitStopSignal(details: { reason?: string }) {
|
|
37
|
+
"use step";
|
|
38
|
+
const writer = getWritable<UIMessageChunk>().getWriter();
|
|
39
|
+
try {
|
|
40
|
+
await writer.write({ type: "data-stopped", id: "stop-signal", data: details } as UIMessageChunk);
|
|
41
|
+
} finally {
|
|
42
|
+
writer.releaseLock();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function stoppableAgent(messages: ModelMessage[]) {
|
|
47
|
+
"use workflow";
|
|
48
|
+
|
|
49
|
+
const { workflowRunId } = getWorkflowMetadata();
|
|
50
|
+
const controller = new AbortController(); // [!code highlight]
|
|
51
|
+
const hook = stopHook.create({ token: `stop:${workflowRunId}` });
|
|
52
|
+
|
|
53
|
+
const agent = new DurableAgent({
|
|
54
|
+
model: "anthropic/claude-haiku-4.5",
|
|
55
|
+
instructions: "You are a research assistant. Search and analyze data as needed.",
|
|
56
|
+
tools: {
|
|
57
|
+
searchWeb: {
|
|
58
|
+
description: "Search the web for information",
|
|
59
|
+
inputSchema: z.object({ query: z.string() }),
|
|
60
|
+
execute: searchWeb,
|
|
61
|
+
},
|
|
62
|
+
analyzeData: {
|
|
63
|
+
description: "Analyze a piece of data",
|
|
64
|
+
inputSchema: z.object({ topic: z.string() }),
|
|
65
|
+
execute: analyzeData,
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const result = await Promise.race([
|
|
71
|
+
agent
|
|
72
|
+
.stream({
|
|
73
|
+
messages,
|
|
74
|
+
writable: getWritable<UIMessageChunk>(),
|
|
75
|
+
abortSignal: controller.signal, // [!code highlight]
|
|
76
|
+
maxSteps: 15,
|
|
77
|
+
})
|
|
78
|
+
.then((r) => ({ type: "complete" as const, messages: r.messages })),
|
|
79
|
+
hook.then(({ reason }) => {
|
|
80
|
+
controller.abort(reason); // [!code highlight]
|
|
81
|
+
return { type: "stopped" as const, reason };
|
|
82
|
+
}),
|
|
83
|
+
]);
|
|
84
|
+
|
|
85
|
+
if (result.type === "stopped") {
|
|
86
|
+
await emitStopSignal({ reason: result.reason });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### API Route to Trigger Stop
|
|
94
|
+
|
|
95
|
+
```typescript lineNumbers
|
|
96
|
+
import { stopHook } from "@/workflows/stoppable-agent";
|
|
97
|
+
|
|
98
|
+
export async function POST(
|
|
99
|
+
request: Request,
|
|
100
|
+
{ params }: { params: Promise<{ runId: string }> }
|
|
101
|
+
) {
|
|
102
|
+
const { runId } = await params;
|
|
103
|
+
const { reason } = await request.json();
|
|
104
|
+
|
|
105
|
+
await stopHook.resume(`stop:${runId}`, {
|
|
106
|
+
reason: reason || "User requested stop",
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
return Response.json({ success: true });
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Client Stop Button
|
|
114
|
+
|
|
115
|
+
```tsx lineNumbers
|
|
116
|
+
"use client";
|
|
117
|
+
|
|
118
|
+
export function StopButton({ runId }: { runId: string }) {
|
|
119
|
+
const handleStop = async () => {
|
|
120
|
+
await fetch(`/api/chat/${runId}/stop`, {
|
|
121
|
+
method: "POST",
|
|
122
|
+
headers: { "Content-Type": "application/json" },
|
|
123
|
+
body: JSON.stringify({ reason: "User clicked stop" }),
|
|
124
|
+
});
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
return (
|
|
128
|
+
<button type="button" onClick={handleStop}>
|
|
129
|
+
Stop Agent
|
|
130
|
+
</button>
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## How it works
|
|
136
|
+
|
|
137
|
+
1. An `AbortController` is created at the start of the workflow
|
|
138
|
+
2. A hook is created with token `stop:${workflowRunId}`
|
|
139
|
+
3. `Promise.race` runs the agent stream and the stop hook concurrently
|
|
140
|
+
4. The agent receives `controller.signal` — when aborted, the underlying model stream is cancelled
|
|
141
|
+
5. When the stop API resumes the hook, `controller.abort()` is called — the race resolves and the workflow exits
|
|
142
|
+
6. `emitStopSignal` writes a `data-stopped` part to the stream so the client renders a clean stop state
|
|
143
|
+
|
|
144
|
+
## Adapting this
|
|
145
|
+
|
|
146
|
+
* **Add a timeout** — race a third `sleep()` promise to auto-stop after a deadline
|
|
147
|
+
* **Audit logging** — include a `reason` field in the stop schema to record who stopped and why
|
|
148
|
+
* **Cross-process** — the hook token is deterministic, so any process can call `stopHook.resume()` with the run ID
|
|
149
|
+
* **Step limits** — combine with `maxSteps` on the agent to cap execution even without manual stop
|
|
150
|
+
|
|
151
|
+
## Key APIs
|
|
152
|
+
|
|
153
|
+
* [`defineHook()`](/docs/api-reference/workflow/define-hook) — type-safe hook for the stop signal
|
|
154
|
+
* [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata) — access the run ID for deterministic hook tokens
|
|
155
|
+
* [`getWritable()`](/docs/api-reference/workflow/get-writable) — stream output and the stop notification to the client
|
|
156
|
+
* [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — the agent that respects the abort signal via its `signal` option
|
|
@@ -1,191 +1,18 @@
|
|
|
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
|
+
## WorkflowAgent from AI SDK v7
|
|
9
9
|
|
|
10
|
-
|
|
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
|
-
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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>
|