workflow 5.0.0-beta.8 → 5.0.0
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 +68 -23
- package/dist/api-workflow.d.ts +3 -1
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +2 -1
- package/dist/api.d.ts +5 -4
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +6 -7
- 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 +4 -4
- package/dist/internal/builtins.js +6 -6
- 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/runtime.d.ts +2 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +4 -1
- package/docs/advanced/dynamic-workflows.mdx +224 -0
- package/docs/ai/chat-session-modeling.mdx +176 -422
- package/docs/ai/defining-tools.mdx +6 -7
- package/docs/ai/human-in-the-loop.mdx +11 -11
- package/docs/ai/index.mdx +67 -72
- package/docs/ai/message-queueing.mdx +71 -110
- package/docs/ai/meta.json +1 -0
- package/docs/ai/resumable-streams.mdx +40 -28
- package/docs/ai/sleep-and-delays.mdx +10 -10
- package/docs/ai/streaming-updates-from-tools.mdx +6 -6
- package/docs/api-reference/index.mdx +25 -1
- package/docs/api-reference/meta.json +8 -0
- package/docs/api-reference/vitest/index.mdx +68 -15
- package/docs/api-reference/workflow/create-hook.mdx +166 -10
- package/docs/api-reference/workflow/create-webhook.mdx +16 -15
- package/docs/api-reference/workflow/define-hook.mdx +37 -33
- package/docs/api-reference/workflow/fatal-error.mdx +30 -8
- package/docs/api-reference/workflow/fetch.mdx +14 -10
- package/docs/api-reference/workflow/get-step-metadata.mdx +2 -2
- package/docs/api-reference/workflow/get-workflow-metadata.mdx +3 -3
- package/docs/api-reference/workflow/get-writable.mdx +7 -7
- package/docs/api-reference/workflow/index.mdx +4 -1
- package/docs/api-reference/workflow/retryable-error.mdx +1 -1
- package/docs/api-reference/workflow/set-attributes.mdx +63 -0
- package/docs/api-reference/workflow/sleep.mdx +4 -4
- package/docs/api-reference/workflow-ai/durable-agent.mdx +63 -101
- package/docs/api-reference/workflow-ai/index.mdx +5 -5
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +67 -24
- package/docs/api-reference/workflow-api/get-hook-by-token.mdx +28 -12
- package/docs/api-reference/workflow-api/get-run.mdx +43 -8
- package/docs/api-reference/workflow-api/index.mdx +8 -9
- package/docs/api-reference/workflow-api/register-lifecycle-hooks.mdx +87 -0
- package/docs/api-reference/workflow-api/resume-hook.mdx +73 -12
- package/docs/api-reference/workflow-api/resume-webhook.mdx +11 -9
- package/docs/api-reference/workflow-api/start.mdx +107 -12
- 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/entity-conflict-error.mdx +4 -4
- package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +60 -0
- package/docs/api-reference/workflow-errors/hook-force-claimed-error.mdx +70 -0
- package/docs/api-reference/workflow-errors/hook-not-found-error.mdx +8 -8
- package/docs/api-reference/workflow-errors/index.mdx +91 -0
- package/docs/api-reference/workflow-errors/meta.json +7 -0
- package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +68 -0
- package/docs/api-reference/workflow-errors/run-expired-error.mdx +2 -2
- package/docs/api-reference/workflow-errors/run-not-supported-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/step-not-registered-error.mdx +5 -5
- package/docs/api-reference/workflow-errors/throttle-error.mdx +2 -2
- package/docs/api-reference/workflow-errors/too-early-error.mdx +2 -2
- package/docs/api-reference/workflow-errors/workflow-error.mdx +52 -0
- package/docs/api-reference/workflow-errors/workflow-not-registered-error.mdx +5 -6
- package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +13 -6
- package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +12 -5
- package/docs/api-reference/workflow-errors/workflow-run-not-completed-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-run-not-found-error.mdx +4 -4
- package/docs/api-reference/workflow-errors/workflow-runtime-error.mdx +58 -0
- package/docs/api-reference/workflow-errors/workflow-world-error.mdx +8 -8
- package/docs/api-reference/workflow-globals.mdx +15 -11
- package/docs/api-reference/workflow-nest/configure-workflow-controller.mdx +37 -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 +46 -0
- package/docs/api-reference/workflow-nest/workflow-module.mdx +134 -0
- package/docs/api-reference/workflow-next/with-workflow.mdx +39 -17
- 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 +62 -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 +11 -14
- package/docs/api-reference/workflow-runtime/health-check.mdx +51 -0
- package/docs/api-reference/workflow-runtime/index.mdx +41 -0
- package/docs/api-reference/workflow-runtime/meta.json +12 -0
- package/docs/api-reference/workflow-runtime/set-world.mdx +51 -0
- package/docs/api-reference/workflow-runtime/workflow-entrypoint.mdx +43 -0
- package/docs/api-reference/workflow-runtime/world/analytics.mdx +315 -0
- package/docs/api-reference/workflow-runtime/world/index.mdx +60 -0
- package/docs/api-reference/workflow-runtime/world/meta.json +4 -0
- package/docs/api-reference/workflow-runtime/world/queue.mdx +88 -0
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/storage.mdx +104 -35
- package/docs/api-reference/{workflow-api → workflow-runtime}/world/streams.mdx +8 -8
- package/docs/api-reference/workflow-serde/index.mdx +1 -2
- package/docs/api-reference/workflow-serde/workflow-deserialize.mdx +3 -4
- package/docs/api-reference/workflow-serde/workflow-serialize.mdx +8 -8
- 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 +61 -46
- package/docs/changelog/batched-event-writes.mdx +79 -0
- package/docs/changelog/eager-processing.mdx +110 -436
- package/docs/changelog/index.mdx +4 -2
- package/docs/changelog/lazy-event-creation.md +127 -0
- package/docs/changelog/lazy-hook-resume.mdx +78 -0
- package/docs/changelog/meta.json +11 -1
- package/docs/changelog/resilient-resume.mdx +32 -0
- package/docs/changelog/resilient-start.mdx +33 -285
- 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 +104 -0
- package/docs/configuration/build-and-diagnostics.mdx +79 -0
- package/docs/configuration/cli-and-web-ui.mdx +241 -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 +399 -0
- package/docs/configuration/worlds.mdx +315 -0
- package/docs/cookbook/advanced/child-workflows.mdx +33 -25
- package/docs/cookbook/advanced/publishing-libraries.mdx +65 -56
- package/docs/cookbook/advanced/serializable-steps.mdx +48 -68
- package/docs/cookbook/advanced/upgrading-workflows.mdx +35 -31
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +78 -60
- package/docs/cookbook/agent-patterns/durable-agent.mdx +23 -135
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +180 -195
- package/docs/cookbook/common-patterns/batching.mdx +20 -14
- package/docs/cookbook/common-patterns/idempotency.mdx +41 -53
- package/docs/cookbook/common-patterns/rate-limiting.mdx +8 -4
- package/docs/cookbook/common-patterns/saga.mdx +23 -19
- package/docs/cookbook/common-patterns/scheduling.mdx +30 -22
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +29 -25
- package/docs/cookbook/common-patterns/timeouts.mdx +26 -21
- package/docs/cookbook/common-patterns/webhooks.mdx +10 -6
- package/docs/cookbook/common-patterns/workflow-composition.mdx +27 -17
- package/docs/cookbook/index.mdx +22 -22
- package/docs/cookbook/integrations/ai-sdk.mdx +63 -48
- package/docs/cookbook/integrations/chat-sdk.mdx +46 -33
- package/docs/cookbook/integrations/sandbox.mdx +58 -45
- package/docs/deploying.mdx +106 -0
- package/docs/errors/abort-signal-timeout-in-workflow.mdx +16 -12
- package/docs/errors/corrupted-event-log.mdx +39 -18
- package/docs/errors/deployment-mismatch.mdx +71 -0
- package/docs/errors/fetch-in-workflow.mdx +15 -14
- package/docs/errors/hook-conflict.mdx +38 -11
- package/docs/errors/hook-force-claimed.mdx +96 -0
- package/docs/errors/index.mdx +24 -37
- package/docs/errors/node-js-module-in-workflow.mdx +9 -5
- package/docs/errors/replay-divergence.mdx +27 -0
- package/docs/errors/run-expired.mdx +85 -0
- package/docs/errors/runtime-decryption-failed.mdx +77 -0
- package/docs/errors/serialization-failed.mdx +44 -12
- package/docs/errors/start-invalid-workflow-function.mdx +9 -5
- package/docs/errors/step-executed-multiple-times.mdx +23 -0
- package/docs/errors/step-not-registered.mdx +6 -6
- package/docs/errors/timeout-in-workflow.mdx +12 -8
- package/docs/errors/webhook-invalid-respond-with-value.mdx +18 -18
- package/docs/errors/webhook-response-not-sent.mdx +20 -16
- package/docs/errors/workflow-not-registered.mdx +5 -5
- package/docs/foundations/cancellation.mdx +31 -32
- package/docs/foundations/errors-and-retries.mdx +54 -11
- package/docs/foundations/hooks.mdx +98 -35
- package/docs/foundations/idempotency.mdx +267 -12
- package/docs/foundations/index.mdx +1 -26
- package/docs/foundations/serialization.mdx +22 -22
- package/docs/foundations/starting-workflows.mdx +104 -30
- package/docs/foundations/streaming.mdx +108 -60
- package/docs/foundations/versioning.mdx +4 -4
- package/docs/foundations/workflows-and-steps.mdx +9 -9
- package/docs/getting-started/astro.mdx +22 -18
- package/docs/getting-started/express.mdx +15 -11
- package/docs/getting-started/fastify.mdx +15 -11
- package/docs/getting-started/hono.mdx +15 -11
- package/docs/getting-started/index.mdx +10 -3
- package/docs/getting-started/meta.json +3 -1
- package/docs/getting-started/nestjs.mdx +264 -21
- package/docs/getting-started/next.mdx +18 -14
- package/docs/getting-started/nitro.mdx +22 -18
- package/docs/getting-started/nuxt.mdx +15 -11
- package/docs/getting-started/python.mdx +190 -41
- 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 +20 -16
- package/docs/getting-started/tanstack-start.mdx +17 -13
- package/docs/getting-started/vite.mdx +15 -11
- package/docs/how-it-works/cancellation.mdx +63 -63
- package/docs/how-it-works/code-transform.mdx +82 -66
- package/docs/how-it-works/encryption.mdx +30 -26
- package/docs/how-it-works/event-sourcing.mdx +132 -35
- package/docs/how-it-works/framework-integrations.mdx +96 -337
- package/docs/how-it-works/understanding-directives.mdx +22 -22
- package/docs/internal/index.mdx +6 -4
- package/docs/internal/meta.json +6 -1
- 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 +7 -7
- package/docs/meta.json +4 -2
- package/docs/observability/attributes.mdx +136 -0
- package/docs/observability/index.mdx +32 -10
- package/docs/observability/lifecycle-hooks.mdx +95 -0
- package/docs/observability/meta.json +1 -1
- package/docs/observability/retention.mdx +95 -0
- package/docs/observability/tracing.mdx +124 -0
- package/docs/testing/index.mdx +120 -38
- package/docs/testing/server-based.mdx +10 -10
- package/docs/whats-new.mdx +190 -0
- package/docs/worlds/building-a-world.mdx +538 -0
- package/docs/worlds/local.mdx +129 -0
- package/docs/worlds/meta.json +10 -0
- package/docs/worlds/postgres.mdx +424 -0
- package/docs/worlds/upgrading-to-v5.mdx +162 -0
- package/docs/worlds/vercel.mdx +345 -0
- package/package.json +17 -14
- package/docs/api-reference/workflow-api/world/index.mdx +0 -58
- package/docs/api-reference/workflow-api/world/meta.json +0 -4
- package/docs/api-reference/workflow-api/world/observability.mdx +0 -164
- package/docs/api-reference/workflow-api/world/queue.mdx +0 -86
- package/docs/deploying/building-a-world.mdx +0 -251
- package/docs/deploying/index.mdx +0 -95
- 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 -224
- package/docs/deploying/world/vercel-world.mdx +0 -181
- 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 -358
- package/docs/migration-guides/migrating-from-inngest.mdx +0 -304
- package/docs/migration-guides/migrating-from-temporal.mdx +0 -313
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +0 -328
|
@@ -1,46 +1,59 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Agent Cancellation
|
|
3
|
-
description: Cancel a running
|
|
3
|
+
description: Cancel a running WorkflowAgent from the outside using AbortSignal and a durable stop hook.
|
|
4
4
|
type: guide
|
|
5
|
-
summary: Cancel a running
|
|
5
|
+
summary: Cancel a running WorkflowAgent cooperatively with AbortController so the model stream stops and the workflow can return a clean status.
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
<CopyPrompt
|
|
9
|
+
text="Add cancellation to this AI SDK WorkflowAgent. For hard cancellation, expose a server route that receives `runId` and calls `getRun(runId).cancel()` from `workflow/api`. For graceful cancellation, define `stopHook` with `defineHook()` from `workflow`, create it with a stable token such as the workflow run ID, and race `WorkflowAgent.stream()` against the stop hook using `Promise.race`. Pass an `AbortController` signal to the agent, forward the tool execution signal to cancellable I/O, and wait for the agent branch to settle after aborting before returning a stopped status. Wire the UI Stop button to the route that resumes the hook or falls back to `getRun(runId).cancel()`, and verify stale run IDs are handled."
|
|
10
|
+
/>
|
|
11
|
+
|
|
12
|
+
Cancel a running agent from the outside through a **Stop** button in a chat user interface (UI), an admin cancellation endpoint, or a timeout fallback.
|
|
9
13
|
|
|
10
14
|
## Pattern
|
|
11
15
|
|
|
12
|
-
Create an `AbortController` in the workflow and race the agent (passing its signal) against a stop hook. When the hook fires, `controller.abort()
|
|
16
|
+
Create an `AbortController` in the workflow and race the agent (passing its signal) against a stop hook. When the hook fires, call `controller.abort()`, then wait for the agent branch to observe the signal and settle before the workflow returns. The signal cancels the underlying model stream and is passed to tool execution; each tool must forward it to cancellable I/O. The workflow return value records whether it completed or stopped; read that value through the run API or persist it in application state.
|
|
13
17
|
|
|
18
|
+
{/* @skip-typecheck: requires AI SDK 7 and @ai-sdk/workflow */}
|
|
14
19
|
```typescript lineNumbers
|
|
15
|
-
import {
|
|
20
|
+
import { WorkflowAgent, type ModelCallStreamPart } from "@ai-sdk/workflow";
|
|
21
|
+
import {
|
|
22
|
+
isStepCount,
|
|
23
|
+
tool,
|
|
24
|
+
type ModelMessage,
|
|
25
|
+
type ToolExecutionOptions,
|
|
26
|
+
} from "ai";
|
|
16
27
|
import { defineHook, getWritable, getWorkflowMetadata } from "workflow";
|
|
17
28
|
import { z } from "zod";
|
|
18
|
-
import type { ModelMessage, UIMessageChunk } from "ai";
|
|
19
29
|
|
|
20
30
|
export const stopHook = defineHook({
|
|
21
31
|
schema: z.object({ reason: z.string().optional() }),
|
|
22
32
|
});
|
|
23
33
|
|
|
24
|
-
async function searchWeb(
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
async function analyzeData({ topic }: { topic: string }) {
|
|
34
|
+
async function searchWeb(
|
|
35
|
+
{ query }: { query: string },
|
|
36
|
+
{ abortSignal }: ToolExecutionOptions<unknown>,
|
|
37
|
+
) {
|
|
31
38
|
"use step";
|
|
32
|
-
|
|
33
|
-
|
|
39
|
+
const response = await fetch(
|
|
40
|
+
`https://api.example.com/search?q=${encodeURIComponent(query)}`,
|
|
41
|
+
{ signal: abortSignal }, // [!code highlight]
|
|
42
|
+
);
|
|
43
|
+
return response.json();
|
|
34
44
|
}
|
|
35
45
|
|
|
36
|
-
async function
|
|
46
|
+
async function analyzeData(
|
|
47
|
+
{ topic }: { topic: string },
|
|
48
|
+
{ abortSignal }: ToolExecutionOptions<unknown>,
|
|
49
|
+
) {
|
|
37
50
|
"use step";
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
51
|
+
const response = await fetch("https://api.example.com/analyze", {
|
|
52
|
+
method: "POST",
|
|
53
|
+
body: JSON.stringify({ topic }),
|
|
54
|
+
signal: abortSignal, // [!code highlight]
|
|
55
|
+
});
|
|
56
|
+
return response.json();
|
|
44
57
|
}
|
|
45
58
|
|
|
46
59
|
export async function stoppableAgent(messages: ModelMessage[]) {
|
|
@@ -50,47 +63,52 @@ export async function stoppableAgent(messages: ModelMessage[]) {
|
|
|
50
63
|
const controller = new AbortController(); // [!code highlight]
|
|
51
64
|
const hook = stopHook.create({ token: `stop:${workflowRunId}` });
|
|
52
65
|
|
|
53
|
-
const agent = new
|
|
54
|
-
model: "
|
|
66
|
+
const agent = new WorkflowAgent({
|
|
67
|
+
model: "spacexai/grok-4.6",
|
|
55
68
|
instructions: "You are a research assistant. Search and analyze data as needed.",
|
|
56
69
|
tools: {
|
|
57
|
-
searchWeb: {
|
|
70
|
+
searchWeb: tool({
|
|
58
71
|
description: "Search the web for information",
|
|
59
72
|
inputSchema: z.object({ query: z.string() }),
|
|
60
73
|
execute: searchWeb,
|
|
61
|
-
},
|
|
62
|
-
analyzeData: {
|
|
74
|
+
}),
|
|
75
|
+
analyzeData: tool({
|
|
63
76
|
description: "Analyze a piece of data",
|
|
64
77
|
inputSchema: z.object({ topic: z.string() }),
|
|
65
78
|
execute: analyzeData,
|
|
66
|
-
},
|
|
79
|
+
}),
|
|
67
80
|
},
|
|
68
81
|
});
|
|
69
82
|
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
})
|
|
83
|
+
const agentPromise = agent.stream({
|
|
84
|
+
messages,
|
|
85
|
+
writable: getWritable<ModelCallStreamPart>(),
|
|
86
|
+
abortSignal: controller.signal, // [!code highlight]
|
|
87
|
+
stopWhen: isStepCount(15),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const outcome = await Promise.race([
|
|
91
|
+
agentPromise.then((result) => ({
|
|
92
|
+
type: "complete" as const,
|
|
93
|
+
messages: result.messages,
|
|
94
|
+
})),
|
|
95
|
+
hook.then(({ reason }) => ({
|
|
96
|
+
type: "stop-requested" as const,
|
|
97
|
+
reason,
|
|
98
|
+
})),
|
|
83
99
|
]);
|
|
84
100
|
|
|
85
|
-
if (
|
|
86
|
-
|
|
101
|
+
if (outcome.type === "stop-requested") {
|
|
102
|
+
controller.abort(outcome.reason); // [!code highlight]
|
|
103
|
+
await agentPromise; // Wait until the losing branch has stopped. // [!code highlight]
|
|
104
|
+
return { type: "stopped" as const, reason: outcome.reason };
|
|
87
105
|
}
|
|
88
106
|
|
|
89
|
-
return
|
|
107
|
+
return outcome;
|
|
90
108
|
}
|
|
91
109
|
```
|
|
92
110
|
|
|
93
|
-
### API
|
|
111
|
+
### API route to trigger stop
|
|
94
112
|
|
|
95
113
|
```typescript lineNumbers
|
|
96
114
|
import { stopHook } from "@/workflows/stoppable-agent";
|
|
@@ -110,7 +128,7 @@ export async function POST(
|
|
|
110
128
|
}
|
|
111
129
|
```
|
|
112
130
|
|
|
113
|
-
### Client
|
|
131
|
+
### Client stop button
|
|
114
132
|
|
|
115
133
|
```tsx lineNumbers
|
|
116
134
|
"use client";
|
|
@@ -134,23 +152,23 @@ export function StopButton({ runId }: { runId: string }) {
|
|
|
134
152
|
|
|
135
153
|
## How it works
|
|
136
154
|
|
|
137
|
-
1.
|
|
138
|
-
2.
|
|
139
|
-
3. `Promise.race` runs the agent stream and the stop hook concurrently
|
|
140
|
-
4. The agent receives `controller.signal
|
|
141
|
-
5. When the stop API resumes the hook,
|
|
142
|
-
6.
|
|
155
|
+
1. The workflow creates an `AbortController` when it starts.
|
|
156
|
+
2. The workflow creates a hook with the token `stop:${workflowRunId}`.
|
|
157
|
+
3. `Promise.race` runs the agent stream and the stop hook concurrently.
|
|
158
|
+
4. The agent receives `controller.signal`. When aborted, the signal cancels the active model stream, propagates to tool execution, and prevents another model step from starting. Tool implementations must forward it to operations such as `fetch` that support cancellation.
|
|
159
|
+
5. When the stop API resumes the hook, the race reports a stop request. The workflow aborts the controller and awaits `agentPromise`, so it does not return while that branch is still running.
|
|
160
|
+
6. After the agent branch settles, the workflow returns a `stopped` result. That return value is not written to the model-call stream automatically; the application can read `run.returnValue` or persist the status separately.
|
|
143
161
|
|
|
144
162
|
## Adapting this
|
|
145
163
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
164
|
+
- **Add a timeout**: Race a third `sleep()` promise to stop automatically after a deadline.
|
|
165
|
+
- **Audit logging**: Include a `reason` field in the stop schema to record who stopped the agent and why.
|
|
166
|
+
- **Cross-process**: The hook token is deterministic, so any process can call `stopHook.resume()` with the run ID.
|
|
167
|
+
- **Step limits**: Combine the pattern with `stopWhen: isStepCount(...)` to cap execution without a manual stop.
|
|
150
168
|
|
|
151
169
|
## Key APIs
|
|
152
170
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
171
|
+
- [`defineHook()`](/docs/api-reference/workflow/define-hook): Defines a type-safe hook for the stop signal.
|
|
172
|
+
- [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata): Provides the run ID for deterministic hook tokens.
|
|
173
|
+
- [`getWritable()`](/docs/api-reference/workflow/get-writable): Stores durable model-call output from the agent.
|
|
174
|
+
- [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent): AI SDK's durable agent that applies the abort signal to model calls and replaces `DurableAgent`.
|
|
@@ -1,154 +1,42 @@
|
|
|
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 durable agents in Workflow 5. It replaces `DurableAgent` and keeps the current agent pattern in the AI SDK package.
|
|
16
15
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
## Pattern
|
|
22
|
-
|
|
23
|
-
Replace `Agent` with `DurableAgent`, wrap the function in `"use workflow"`, mark each tool with `"use step"`, and stream output through `getWritable()`.
|
|
24
|
-
|
|
25
|
-
### Workflow
|
|
16
|
+
- Import `WorkflowAgent` from `@ai-sdk/workflow` and run it inside a `"use workflow"` function.
|
|
17
|
+
- Pass `"spacexai/grok-4.6"` as a plain model string so AI SDK routes requests through Vercel AI Gateway.
|
|
18
|
+
- Stream `ModelCallStreamPart` chunks with `getWritable()`, then convert the run stream to UI message chunks with `createModelCallToUIChunkTransform()` in your route.
|
|
19
|
+
- Mark tool `execute` functions with `"use step"` when they should run as durable workflow steps with retry and observability behavior.
|
|
26
20
|
|
|
27
21
|
```typescript
|
|
28
|
-
import {
|
|
22
|
+
import { WorkflowAgent, type ModelCallStreamPart } from "@ai-sdk/workflow";
|
|
29
23
|
import { getWritable } from "workflow";
|
|
30
|
-
import { z } from "zod";
|
|
31
|
-
import type { ModelMessage, UIMessageChunk } from "ai";
|
|
32
|
-
|
|
33
|
-
async function searchFlights({ from, to, date }: {
|
|
34
|
-
from: string;
|
|
35
|
-
to: string;
|
|
36
|
-
date: string;
|
|
37
|
-
}) {
|
|
38
|
-
"use step"; // [!code highlight]
|
|
39
|
-
const res = await fetch(
|
|
40
|
-
`https://api.example.com/flights?from=${from}&to=${to}&date=${date}`
|
|
41
|
-
);
|
|
42
|
-
if (!res.ok) throw new Error(`Search failed: ${res.status}`);
|
|
43
|
-
return res.json();
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
async function bookFlight({ flightId, passenger }: {
|
|
47
|
-
flightId: string;
|
|
48
|
-
passenger: string;
|
|
49
|
-
}) {
|
|
50
|
-
"use step"; // [!code highlight]
|
|
51
|
-
const res = await fetch("https://api.example.com/bookings", {
|
|
52
|
-
method: "POST",
|
|
53
|
-
headers: { "Content-Type": "application/json" },
|
|
54
|
-
body: JSON.stringify({ flightId, passenger }),
|
|
55
|
-
});
|
|
56
|
-
if (!res.ok) throw new Error(`Booking failed: ${res.status}`);
|
|
57
|
-
return res.json();
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async function checkWeather({ city }: { city: string }) {
|
|
61
|
-
"use step"; // [!code highlight]
|
|
62
|
-
const res = await fetch(`https://api.weather.com/forecast?city=${city}`);
|
|
63
|
-
return res.json();
|
|
64
|
-
}
|
|
65
24
|
|
|
66
|
-
export async function
|
|
25
|
+
export async function agentWorkflow(prompt: string) {
|
|
67
26
|
"use workflow";
|
|
68
27
|
|
|
69
|
-
const agent = new
|
|
70
|
-
model: "
|
|
71
|
-
instructions: "You are a helpful
|
|
72
|
-
tools: {
|
|
73
|
-
searchFlights: {
|
|
74
|
-
description: "Search for available flights between two airports",
|
|
75
|
-
inputSchema: z.object({
|
|
76
|
-
from: z.string().describe("Departure airport code"),
|
|
77
|
-
to: z.string().describe("Arrival airport code"),
|
|
78
|
-
date: z.string().describe("Travel date (YYYY-MM-DD)"),
|
|
79
|
-
}),
|
|
80
|
-
execute: searchFlights,
|
|
81
|
-
},
|
|
82
|
-
bookFlight: {
|
|
83
|
-
description: "Book a specific flight for a passenger",
|
|
84
|
-
inputSchema: z.object({
|
|
85
|
-
flightId: z.string().describe("Flight ID from search results"),
|
|
86
|
-
passenger: z.string().describe("Passenger full name"),
|
|
87
|
-
}),
|
|
88
|
-
execute: bookFlight,
|
|
89
|
-
},
|
|
90
|
-
checkWeather: {
|
|
91
|
-
description: "Check the weather forecast for a city",
|
|
92
|
-
inputSchema: z.object({
|
|
93
|
-
city: z.string().describe("City name"),
|
|
94
|
-
}),
|
|
95
|
-
execute: checkWeather,
|
|
96
|
-
},
|
|
97
|
-
},
|
|
28
|
+
const agent = new WorkflowAgent({
|
|
29
|
+
model: "spacexai/grok-4.6",
|
|
30
|
+
instructions: "You are a helpful assistant.",
|
|
98
31
|
});
|
|
99
32
|
|
|
100
|
-
|
|
101
|
-
messages,
|
|
102
|
-
writable: getWritable<
|
|
103
|
-
maxSteps: 10,
|
|
33
|
+
return agent.stream({
|
|
34
|
+
messages: [{ role: "user", content: prompt }],
|
|
35
|
+
writable: getWritable<ModelCallStreamPart>(),
|
|
104
36
|
});
|
|
105
|
-
|
|
106
|
-
return { messages: result.messages };
|
|
107
37
|
}
|
|
108
38
|
```
|
|
109
39
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
import type { UIMessage } from "ai";
|
|
114
|
-
import { convertToModelMessages, createUIMessageStreamResponse } from "ai";
|
|
115
|
-
import { start } from "workflow/api";
|
|
116
|
-
import { flightAgent } from "@/app/workflows/flight-agent";
|
|
117
|
-
|
|
118
|
-
export async function POST(req: Request) {
|
|
119
|
-
const { messages }: { messages: UIMessage[] } = await req.json();
|
|
120
|
-
const modelMessages = await convertToModelMessages(messages); // [!code highlight]
|
|
121
|
-
|
|
122
|
-
const run = await start(flightAgent, [modelMessages]); // [!code highlight]
|
|
123
|
-
|
|
124
|
-
return createUIMessageStreamResponse({ // [!code highlight]
|
|
125
|
-
stream: run.readable,
|
|
126
|
-
headers: {
|
|
127
|
-
"x-workflow-run-id": run.runId,
|
|
128
|
-
},
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
## How it works
|
|
134
|
-
|
|
135
|
-
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.
|
|
136
|
-
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.
|
|
137
|
-
3. **Streaming** — `getWritable<UIMessageChunk>()` streams the agent's output (text chunks, tool calls, tool results) to the client in real time via `createUIMessageStreamResponse`.
|
|
138
|
-
4. **maxSteps** — limits the total number of LLM calls the agent can make, preventing runaway tool loops.
|
|
139
|
-
|
|
140
|
-
## Adapting to your use case
|
|
141
|
-
|
|
142
|
-
- **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"`).
|
|
143
|
-
- **Add tools** — define a new `"use step"` function with a Zod schema. Each tool automatically gets retries and persistence.
|
|
144
|
-
- **Workflow-level tools** — if a tool needs workflow primitives like `sleep()` or `createHook()`, omit `"use step"` so it runs in the workflow context instead.
|
|
145
|
-
- **Multi-turn** — pass `result.messages` plus new user messages to subsequent `agent.stream()` calls for multi-turn conversations.
|
|
146
|
-
- **Client integration** — use `useChat()` from `@ai-sdk/react` with `WorkflowChatTransport` from `@workflow/ai` for a full chat UI with reconnection support.
|
|
147
|
-
|
|
148
|
-
## Key APIs
|
|
149
|
-
|
|
150
|
-
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
151
|
-
- [`"use step"`](/docs/api-reference/workflow/use-step) — declares step functions with retries and full Node.js access
|
|
152
|
-
- [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — durable wrapper around AI SDK's Agent
|
|
153
|
-
- [`getWritable()`](/docs/api-reference/workflow/get-writable) — streams agent output to the client
|
|
154
|
-
- [`start()`](/docs/api-reference/workflow-api/start) — starts a workflow run from an API route
|
|
40
|
+
<Callout type="warn">
|
|
41
|
+
`DurableAgent` is deprecated and remains documented for existing code only. See the [migration guide](https://ai-sdk.dev/v7/docs/agents/workflow-agent#migrating-from-durableagent), or the [`DurableAgent` API reference](/docs/api-reference/workflow-ai/durable-agent) while migrating.
|
|
42
|
+
</Callout>
|