workflow 5.0.0-beta.0 → 5.0.0-beta.2
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 +4 -4
- package/dist/api-workflow.d.ts +1 -3
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +2 -6
- package/dist/api.js +1 -1
- package/dist/astro.js +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/builtins.js +1 -1
- package/dist/internal/class-serialization.js +1 -1
- package/dist/internal/errors.js +1 -1
- package/dist/nest.js +1 -1
- package/dist/next.cjs +4 -2
- package/dist/next.d.cts +1 -1
- package/dist/next.d.cts.map +1 -1
- package/dist/nitro.js +1 -1
- package/dist/nuxt.js +1 -1
- package/dist/observability.d.ts +1 -1
- package/dist/observability.js +2 -2
- package/dist/runtime.js +1 -1
- package/dist/stdlib.js +1 -1
- package/dist/sveltekit.js +1 -1
- package/dist/typescript-plugin.cjs +1 -1
- package/dist/vite.js +1 -1
- package/dist/workflow.js +1 -1
- package/docs/ai/resumable-streams.mdx +1 -1
- package/docs/api-reference/workflow/create-webhook.mdx +37 -18
- package/docs/api-reference/workflow/get-workflow-metadata.mdx +61 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +0 -4
- package/docs/api-reference/workflow-ai/index.mdx +0 -5
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +0 -4
- package/docs/api-reference/workflow-api/get-world.mdx +6 -6
- package/docs/api-reference/workflow-api/index.mdx +1 -1
- package/docs/api-reference/workflow-api/world/index.mdx +2 -2
- package/docs/api-reference/workflow-api/world/observability.mdx +1 -1
- package/docs/api-reference/workflow-api/world/queue.mdx +1 -1
- package/docs/api-reference/workflow-api/world/storage.mdx +8 -8
- package/docs/api-reference/workflow-api/world/streams.mdx +38 -36
- package/docs/cookbook/advanced/custom-serialization.mdx +168 -0
- package/docs/cookbook/advanced/durable-objects.mdx +148 -0
- package/docs/cookbook/advanced/isomorphic-packages.mdx +145 -0
- package/docs/cookbook/advanced/meta.json +10 -0
- package/docs/cookbook/advanced/publishing-libraries.mdx +279 -0
- package/docs/cookbook/advanced/serializable-steps.mdx +135 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +191 -0
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +278 -0
- package/docs/cookbook/agent-patterns/meta.json +10 -0
- package/docs/cookbook/agent-patterns/stop-workflow.mdx +216 -0
- package/docs/cookbook/agent-patterns/tool-orchestration.mdx +255 -0
- package/docs/cookbook/agent-patterns/tool-streaming.mdx +181 -0
- package/docs/cookbook/common-patterns/batching.mdx +179 -0
- package/docs/cookbook/common-patterns/child-workflows.mdx +372 -0
- package/docs/cookbook/common-patterns/content-router.mdx +207 -0
- package/docs/cookbook/common-patterns/fan-out.mdx +208 -0
- package/docs/cookbook/common-patterns/idempotency.mdx +107 -0
- package/docs/cookbook/common-patterns/meta.json +15 -0
- package/docs/cookbook/common-patterns/rate-limiting.mdx +228 -0
- package/docs/cookbook/common-patterns/saga.mdx +152 -0
- package/docs/cookbook/common-patterns/scheduling.mdx +249 -0
- package/docs/cookbook/common-patterns/webhooks.mdx +185 -0
- package/docs/cookbook/index.mdx +41 -0
- package/docs/cookbook/integrations/ai-sdk.mdx +204 -0
- package/docs/cookbook/integrations/chat-sdk.mdx +203 -0
- package/docs/cookbook/integrations/meta.json +4 -0
- package/docs/cookbook/integrations/sandbox.mdx +128 -0
- package/docs/cookbook/meta.json +5 -0
- package/docs/deploying/building-a-world.mdx +45 -43
- package/docs/deploying/world/local-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +10 -5
- package/docs/deploying/world/vercel-world.mdx +1 -1
- package/docs/errors/start-invalid-workflow-function.mdx +1 -1
- package/docs/getting-started/index.mdx +8 -1
- package/docs/getting-started/meta.json +2 -1
- package/docs/getting-started/next.mdx +24 -0
- package/docs/getting-started/python.mdx +165 -0
- package/docs/how-it-works/code-transform.mdx +6 -5
- package/docs/meta.json +1 -0
- package/docs/migration-guides/index.mdx +34 -0
- package/docs/migration-guides/meta.json +9 -0
- package/docs/migration-guides/migrating-from-aws-step-functions.mdx +311 -0
- package/docs/migration-guides/migrating-from-inngest.mdx +282 -0
- package/docs/migration-guides/migrating-from-temporal.mdx +284 -0
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +296 -0
- package/package.json +13 -14
- package/dist/internal/private.d.ts +0 -6
- package/dist/internal/private.d.ts.map +0 -1
- package/dist/internal/private.js +0 -6
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Publishing Libraries
|
|
3
|
+
description: Structure and publish npm packages that export workflow functions for consumers to use with Workflow SDK.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Learn how to build, export, and test npm packages that ship workflow and step functions — including package.json exports, re-exporting for stable workflow IDs, keeping step I/O clean, and integration testing.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
<Callout>
|
|
9
|
+
This is an advanced guide for library authors who want to publish reusable workflow functions as npm packages. It assumes familiarity with `"use workflow"`, `"use step"`, and the workflow execution model.
|
|
10
|
+
</Callout>
|
|
11
|
+
|
|
12
|
+
## Package Structure
|
|
13
|
+
|
|
14
|
+
A workflow library follows a standard TypeScript package layout with a dedicated `workflows/` directory. Each workflow file exports one or more workflow functions that consumers can import and pass to `start()`.
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
my-media-lib/
|
|
18
|
+
├── src/
|
|
19
|
+
│ ├── index.ts # Package entry point
|
|
20
|
+
│ ├── types.ts # Shared types
|
|
21
|
+
│ ├── workflows/
|
|
22
|
+
│ │ ├── index.ts # Re-exports all workflows
|
|
23
|
+
│ │ ├── transcode.ts # Workflow: transcode a video
|
|
24
|
+
│ │ └── generate-thumbnails.ts
|
|
25
|
+
│ └── lib/
|
|
26
|
+
│ └── api-client.ts # Internal helpers (NOT steps)
|
|
27
|
+
├── test-server/
|
|
28
|
+
│ └── workflows.ts # Re-export for integration tests
|
|
29
|
+
├── tsup.config.ts
|
|
30
|
+
├── package.json
|
|
31
|
+
└── tsconfig.json
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Entry Points and Exports
|
|
35
|
+
|
|
36
|
+
Use the `exports` field in `package.json` to expose separate entry points for the main API and the raw workflow functions:
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"name": "@acme/media",
|
|
41
|
+
"type": "module",
|
|
42
|
+
"exports": {
|
|
43
|
+
".": {
|
|
44
|
+
"types": { "import": "./dist/index.d.ts" },
|
|
45
|
+
"import": "./dist/index.js"
|
|
46
|
+
},
|
|
47
|
+
"./workflows": {
|
|
48
|
+
"types": { "import": "./dist/workflows/index.d.ts" },
|
|
49
|
+
"import": "./dist/workflows/index.js"
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"files": ["dist"]
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The main entry point (`@acme/media`) exports types, utilities, and convenience wrappers. The `./workflows` entry point (`@acme/media/workflows`) exports the raw workflow functions that consumers need for the build system.
|
|
57
|
+
|
|
58
|
+
### Source Files
|
|
59
|
+
|
|
60
|
+
The package entry re-exports workflows alongside any utilities:
|
|
61
|
+
|
|
62
|
+
```typescript lineNumbers
|
|
63
|
+
// src/index.ts
|
|
64
|
+
export * from "./types";
|
|
65
|
+
export * as workflows from "./workflows";
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The workflows barrel file re-exports each workflow:
|
|
69
|
+
|
|
70
|
+
```typescript lineNumbers
|
|
71
|
+
// src/workflows/index.ts
|
|
72
|
+
export * from "./transcode";
|
|
73
|
+
export * from "./generate-thumbnails";
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Build Configuration
|
|
77
|
+
|
|
78
|
+
Use a bundler like `tsup` with separate entry points for each export. Mark `workflow` as external so it's resolved from the consumer's project:
|
|
79
|
+
|
|
80
|
+
```typescript lineNumbers
|
|
81
|
+
// tsup.config.ts
|
|
82
|
+
import { defineConfig } from "tsup";
|
|
83
|
+
|
|
84
|
+
export default defineConfig({
|
|
85
|
+
entry: [
|
|
86
|
+
"src/index.ts",
|
|
87
|
+
"src/workflows/index.ts",
|
|
88
|
+
],
|
|
89
|
+
format: ["esm"],
|
|
90
|
+
dts: true,
|
|
91
|
+
sourcemap: true,
|
|
92
|
+
clean: true,
|
|
93
|
+
external: ["workflow"], // [!code highlight]
|
|
94
|
+
});
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Re-Exporting for Workflow ID Stability
|
|
98
|
+
|
|
99
|
+
Workflow SDK's compiler assigns each workflow function a stable ID based on its position in the source file that the build system processes. When a consumer imports a pre-built workflow from an npm package, the compiler never sees the original source — it only sees the compiled output. This means workflow IDs won't match between the library's development environment and the consumer's app.
|
|
100
|
+
|
|
101
|
+
The fix is a **re-export file**. The consumer creates a file in their `workflows/` directory that re-exports the library's workflows. The build system then processes this file and assigns stable IDs.
|
|
102
|
+
|
|
103
|
+
### Consumer Setup
|
|
104
|
+
|
|
105
|
+
```typescript lineNumbers
|
|
106
|
+
// workflows/media.ts (in the consumer's project)
|
|
107
|
+
// Re-export library workflows so the build system assigns stable IDs
|
|
108
|
+
export * from "@acme/media/workflows"; // [!code highlight]
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
This one-line file is all that's needed. The workflow compiler transforms this file, discovers the workflow and step functions from the library, and assigns IDs that are stable across deployments.
|
|
112
|
+
|
|
113
|
+
### Why This Is Necessary
|
|
114
|
+
|
|
115
|
+
Without re-exporting, the workflow runtime cannot match a running workflow to its function definition. When a workflow run is replayed after a cold start, the runtime looks up functions by their compiler-assigned IDs. If the IDs don't exist (because the compiler never processed the library's source), replay fails.
|
|
116
|
+
|
|
117
|
+
The re-export pattern ensures:
|
|
118
|
+
|
|
119
|
+
1. **Stable IDs** — the compiler assigns IDs based on the consumer's source tree
|
|
120
|
+
2. **Replay safety** — IDs persist across deployments and cold starts
|
|
121
|
+
3. **Version upgrades** — re-exported IDs remain stable as long as the consumer's file doesn't change
|
|
122
|
+
|
|
123
|
+
## Keeping Step I/O Clean
|
|
124
|
+
|
|
125
|
+
When you publish a workflow library, every step function's inputs and outputs are recorded in the event log. This has two implications:
|
|
126
|
+
|
|
127
|
+
### 1. Everything Must Be Serializable
|
|
128
|
+
|
|
129
|
+
Step inputs and outputs must be serializable. The workflow runtime supports a rich set of types beyond plain JSON — including `Date`, `RegExp`, `Map`, `Set`, `BigInt`, `Uint8Array`, `URL`, `Error`, and class instances that implement [custom class serialization](/docs/cookbook/advanced/custom-serialization). See the [serialization reference](/docs/foundations/serialization) for the full list of supported types. Do not pass or return:
|
|
130
|
+
|
|
131
|
+
- Functions or closures
|
|
132
|
+
- `WeakRef`, `WeakMap`, or `WeakSet`
|
|
133
|
+
|
|
134
|
+
If your library works with complex objects that don't implement custom class serialization, pass serializable configuration into steps and reconstruct the objects inside the step body.
|
|
135
|
+
|
|
136
|
+
{/* @skip-typecheck - good/bad comparison with duplicate function names */}
|
|
137
|
+
```typescript lineNumbers
|
|
138
|
+
// Good: pass serializable config, construct inside the step
|
|
139
|
+
async function callExternalApi(endpoint: string, params: Record<string, string>) {
|
|
140
|
+
"use step";
|
|
141
|
+
const client = createApiClient(process.env.API_KEY!);
|
|
142
|
+
return await client.request(endpoint, params);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Bad: pass a pre-constructed client object
|
|
146
|
+
async function callExternalApi(client: ApiClient, params: Record<string, string>) {
|
|
147
|
+
"use step";
|
|
148
|
+
// ApiClient is not serializable — this will fail on replay
|
|
149
|
+
return await client.request(params);
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
See [Serializable Steps](/docs/cookbook/advanced/serializable-steps) for the step-as-factory pattern.
|
|
154
|
+
|
|
155
|
+
### 2. Credentials
|
|
156
|
+
|
|
157
|
+
With workflow encryption enabled, credentials passed as step arguments are encrypted in the event log, so either approach is valid:
|
|
158
|
+
|
|
159
|
+
{/* @skip-typecheck - good/bad comparison with duplicate function names */}
|
|
160
|
+
```typescript lineNumbers
|
|
161
|
+
// Option A: resolve credentials from environment inside the step
|
|
162
|
+
async function fetchData(query: string) {
|
|
163
|
+
"use step";
|
|
164
|
+
const client = createClient(process.env.API_KEY!);
|
|
165
|
+
return await client.fetch(query);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Option B: pass credentials as step arguments (encrypted in the event log)
|
|
169
|
+
async function fetchData(apiKey: string, query: string) {
|
|
170
|
+
"use step";
|
|
171
|
+
const client = createClient(apiKey);
|
|
172
|
+
return await client.fetch(query);
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
The choice is a matter of library API design preference. Resolving from environment variables keeps the step signature simpler, while passing credentials explicitly makes dependencies visible and can be easier to test.
|
|
177
|
+
|
|
178
|
+
## Testing Workflow Libraries
|
|
179
|
+
|
|
180
|
+
Library authors need integration tests that exercise workflows through the full Workflow SDK runtime — not just unit tests of individual functions.
|
|
181
|
+
|
|
182
|
+
### Test Server Pattern
|
|
183
|
+
|
|
184
|
+
Create a minimal test server that re-exports your library's workflows, just like a consumer would:
|
|
185
|
+
|
|
186
|
+
```typescript lineNumbers
|
|
187
|
+
// test-server/workflows.ts
|
|
188
|
+
export * from "@acme/media/workflows"; // [!code highlight]
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
This test server acts as a stand-in consumer app. Point your test runner at it to exercise the full workflow lifecycle: start, replay, and completion.
|
|
192
|
+
|
|
193
|
+
### Vitest Configuration
|
|
194
|
+
|
|
195
|
+
Use a dedicated Vitest config for integration tests that run against the Workflow SDK runtime:
|
|
196
|
+
|
|
197
|
+
```typescript lineNumbers
|
|
198
|
+
// vitest.workflowsdk.config.ts
|
|
199
|
+
import { defineConfig } from "vitest/config";
|
|
200
|
+
|
|
201
|
+
export default defineConfig({
|
|
202
|
+
test: {
|
|
203
|
+
include: ["tests/integration/**/*.workflowsdk.test.ts"],
|
|
204
|
+
testTimeout: 120_000, // Workflows may take time to complete
|
|
205
|
+
setupFiles: ["./tests/setup.ts"],
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Run these tests separately from your unit tests:
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
# Unit tests (fast, no workflow runtime)
|
|
214
|
+
pnpm vitest run tests/unit
|
|
215
|
+
|
|
216
|
+
# Integration tests (requires workflow runtime)
|
|
217
|
+
pnpm vitest run --config vitest.workflowsdk.config.ts
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
### What to Test
|
|
221
|
+
|
|
222
|
+
- **Happy path**: workflow starts, all steps execute, and the final result is correct
|
|
223
|
+
- **Serialization round-trip**: inputs and outputs survive the event log
|
|
224
|
+
- **Replay**: kill and restart a workflow mid-execution to verify deterministic replay
|
|
225
|
+
- **Error handling**: verify that step failures produce the expected errors
|
|
226
|
+
|
|
227
|
+
## Working With and Without Workflow Installed
|
|
228
|
+
|
|
229
|
+
If your library should work both as a standalone package and inside Workflow SDK, declare `workflow` as an optional peer dependency:
|
|
230
|
+
|
|
231
|
+
```json
|
|
232
|
+
{
|
|
233
|
+
"peerDependencies": {
|
|
234
|
+
"workflow": ">=4.0.0"
|
|
235
|
+
},
|
|
236
|
+
"peerDependenciesMeta": {
|
|
237
|
+
"workflow": {
|
|
238
|
+
"optional": true
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Use dynamic imports and runtime detection so your library gracefully degrades when workflow is not installed:
|
|
245
|
+
|
|
246
|
+
```typescript lineNumbers
|
|
247
|
+
async function isWorkflowRuntime(): Promise<boolean> {
|
|
248
|
+
try {
|
|
249
|
+
const wf = await import("workflow");
|
|
250
|
+
if (typeof wf.getWorkflowMetadata !== "function") return false;
|
|
251
|
+
wf.getWorkflowMetadata(); // [!code highlight]
|
|
252
|
+
return true;
|
|
253
|
+
} catch {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
See [Isomorphic Packages](/docs/cookbook/advanced/isomorphic-packages) for the full pattern including feature detection, dynamic imports, and dual-path execution.
|
|
260
|
+
|
|
261
|
+
## Checklist
|
|
262
|
+
|
|
263
|
+
Before publishing a workflow library:
|
|
264
|
+
|
|
265
|
+
- [ ] `workflow` is listed as an **optional** peer dependency
|
|
266
|
+
- [ ] Separate `./workflows` export in `package.json` for the raw workflow functions
|
|
267
|
+
- [ ] `workflow` is marked as **external** in your bundler config
|
|
268
|
+
- [ ] Documentation tells consumers to re-export from `@your-lib/workflows`
|
|
269
|
+
- [ ] Credentials are either resolved from environment variables or passed explicitly (both are safe with encryption enabled)
|
|
270
|
+
- [ ] All step I/O uses [supported serializable types](/docs/foundations/serialization)
|
|
271
|
+
- [ ] Integration tests use a test server with re-exported workflows
|
|
272
|
+
- [ ] Both with-workflow and without-workflow code paths are tested
|
|
273
|
+
|
|
274
|
+
## Key APIs
|
|
275
|
+
|
|
276
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
277
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — marks functions for durable execution
|
|
278
|
+
- [`start`](/docs/api-reference/workflow/start) — starts a workflow run
|
|
279
|
+
- [`getWorkflowMetadata`](/docs/api-reference/workflow/get-workflow-metadata) — runtime detection and run ID access
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Serializable Steps
|
|
3
|
+
description: Wrap non-serializable objects (like AI model providers) inside step functions so they can cross the workflow boundary.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Return a callback from a step to defer provider initialization, making non-serializable AI SDK models work inside durable workflows.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
<Callout>
|
|
9
|
+
This is an advanced guide. It dives into workflow internals and is not required reading to use workflow.
|
|
10
|
+
</Callout>
|
|
11
|
+
|
|
12
|
+
## The Problem
|
|
13
|
+
|
|
14
|
+
Workflow functions run inside a sandboxed VM where every value that crosses a function boundary must be serializable (JSON-safe). AI SDK model providers — `openai("gpt-4o")`, `anthropic("claude-sonnet-4-20250514")`, etc. — return complex objects with methods, closures, and internal state. Passing one directly into a step causes a serialization error.
|
|
15
|
+
|
|
16
|
+
```typescript lineNumbers
|
|
17
|
+
import { openai } from "@ai-sdk/openai";
|
|
18
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
19
|
+
import { getWritable } from "workflow";
|
|
20
|
+
import type { UIMessageChunk } from "ai";
|
|
21
|
+
|
|
22
|
+
export async function brokenAgent(prompt: string) {
|
|
23
|
+
"use workflow";
|
|
24
|
+
|
|
25
|
+
const writable = getWritable<UIMessageChunk>();
|
|
26
|
+
const agent = new DurableAgent({
|
|
27
|
+
// This fails — the model object is not serializable
|
|
28
|
+
model: openai("gpt-4o"),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
await agent.stream({ messages: [{ role: "user", content: prompt }], writable });
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## The Solution: Step-as-Factory
|
|
36
|
+
|
|
37
|
+
Instead of passing the model object, pass a **callback function** that returns the model. Marking that callback with `"use step"` tells the compiler to serialize the *function reference* (which is just a string identifier) rather than its return value. The provider is only instantiated at execution time, inside the step's full Node.js runtime.
|
|
38
|
+
|
|
39
|
+
```typescript lineNumbers
|
|
40
|
+
import { openai as openaiProvider } from "@ai-sdk/openai";
|
|
41
|
+
|
|
42
|
+
// Returns a step function, not a model object
|
|
43
|
+
export function openai(...args: Parameters<typeof openaiProvider>) {
|
|
44
|
+
return async () => {
|
|
45
|
+
"use step";
|
|
46
|
+
return openaiProvider(...args); // [!code highlight]
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The `DurableAgent` receives a function (`() => Promise<LanguageModel>`) instead of a model object. When the agent needs to call the LLM, it invokes the factory inside a step where the real provider can be constructed with full Node.js access.
|
|
52
|
+
|
|
53
|
+
## How `@workflow/ai` Uses This
|
|
54
|
+
|
|
55
|
+
The `@workflow/ai` package ships pre-wrapped providers for all major AI SDK backends. Each one follows the same pattern:
|
|
56
|
+
|
|
57
|
+
```typescript lineNumbers
|
|
58
|
+
// packages/ai/src/providers/anthropic.ts
|
|
59
|
+
import { anthropic as anthropicProvider } from "@ai-sdk/anthropic";
|
|
60
|
+
|
|
61
|
+
export function anthropic(...args: Parameters<typeof anthropicProvider>) {
|
|
62
|
+
return async () => {
|
|
63
|
+
"use step";
|
|
64
|
+
return anthropicProvider(...args); // [!code highlight]
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
This means you import from `@workflow/ai` instead of `@ai-sdk/*` directly:
|
|
70
|
+
|
|
71
|
+
```typescript lineNumbers
|
|
72
|
+
import { anthropic } from "@workflow/ai/anthropic";
|
|
73
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
74
|
+
import { getWritable } from "workflow";
|
|
75
|
+
import type { UIMessageChunk } from "ai";
|
|
76
|
+
|
|
77
|
+
export async function chatAgent(prompt: string) {
|
|
78
|
+
"use workflow";
|
|
79
|
+
|
|
80
|
+
const writable = getWritable<UIMessageChunk>();
|
|
81
|
+
const agent = new DurableAgent({
|
|
82
|
+
model: anthropic("claude-sonnet-4-20250514"), // [!code highlight]
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
await agent.stream({ messages: [{ role: "user", content: prompt }], writable });
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Writing Your Own Serializable Wrapper
|
|
90
|
+
|
|
91
|
+
Apply the same pattern to any non-serializable dependency. The key rule: **the outer function captures serializable arguments, and the inner `"use step"` function constructs the real object at runtime**.
|
|
92
|
+
|
|
93
|
+
```typescript lineNumbers
|
|
94
|
+
import type { S3Client as S3ClientType } from "@aws-sdk/client-s3";
|
|
95
|
+
|
|
96
|
+
// The arguments (region, bucket) are plain strings — serializable
|
|
97
|
+
export function createS3Client(region: string) {
|
|
98
|
+
return async (): Promise<S3ClientType> => {
|
|
99
|
+
"use step";
|
|
100
|
+
const { S3Client } = await import("@aws-sdk/client-s3");
|
|
101
|
+
return new S3Client({ region });
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Usage in a workflow
|
|
106
|
+
export async function processUpload(region: string, key: string) {
|
|
107
|
+
"use workflow";
|
|
108
|
+
|
|
109
|
+
const getClient = createS3Client(region); // [!code highlight]
|
|
110
|
+
// getClient is a serializable step reference, not an S3Client
|
|
111
|
+
await uploadFile(getClient, key);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function uploadFile(
|
|
115
|
+
getClient: () => Promise<S3ClientType>,
|
|
116
|
+
key: string
|
|
117
|
+
) {
|
|
118
|
+
"use step";
|
|
119
|
+
const client = await getClient(); // [!code highlight]
|
|
120
|
+
// Now you have a real S3Client with full Node.js access
|
|
121
|
+
await client.send(/* ... */);
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Why This Works
|
|
126
|
+
|
|
127
|
+
1. **Compiler transformation**: `"use step"` tells the SWC plugin to extract the function into a separate bundle. The workflow VM only sees a serializable reference (function ID + captured arguments).
|
|
128
|
+
2. **Closure tracking**: The compiler tracks which variables the step function closes over. Only serializable values (strings, numbers, plain objects) can be captured.
|
|
129
|
+
3. **Deferred construction**: The actual provider/client is only constructed when the step executes in the Node.js runtime — never in the sandboxed workflow VM.
|
|
130
|
+
|
|
131
|
+
## Key APIs
|
|
132
|
+
|
|
133
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — marks a function for extraction and serialization
|
|
134
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
135
|
+
- [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — accepts a model factory for durable AI agent streaming
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Durable Agent
|
|
3
|
+
description: Replace a stateless AI agent with a durable one that survives crashes, retries tool calls, and streams output.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Convert an AI SDK Agent into a DurableAgent backed by a workflow, with tools as retryable steps.
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
Use this pattern to make any AI SDK agent durable. The agent becomes a workflow, tools become steps, and the framework handles retries, streaming, and state persistence automatically.
|
|
9
|
+
|
|
10
|
+
## Pattern
|
|
11
|
+
|
|
12
|
+
Replace `Agent` with `DurableAgent`, wrap the function in `"use workflow"`, mark each tool with `"use step"`, and stream output through `getWritable()`.
|
|
13
|
+
|
|
14
|
+
### Simplified
|
|
15
|
+
|
|
16
|
+
```typescript lineNumbers
|
|
17
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
18
|
+
import { getWritable } from "workflow";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import type { ModelMessage, UIMessageChunk } from "ai";
|
|
21
|
+
|
|
22
|
+
declare function searchFlights(args: { from: string; to: string; date: string }): Promise<{ flights: { id: string; price: number }[] }>; // @setup
|
|
23
|
+
declare function bookFlight(args: { flightId: string; passenger: string }): Promise<{ confirmationId: string }>; // @setup
|
|
24
|
+
|
|
25
|
+
export async function flightAgent(messages: ModelMessage[]) {
|
|
26
|
+
"use workflow";
|
|
27
|
+
|
|
28
|
+
const agent = new DurableAgent({ // [!code highlight]
|
|
29
|
+
model: "anthropic/claude-haiku-4.5",
|
|
30
|
+
instructions: "You are a helpful flight booking assistant.",
|
|
31
|
+
tools: {
|
|
32
|
+
searchFlights: {
|
|
33
|
+
description: "Search for available flights",
|
|
34
|
+
inputSchema: z.object({
|
|
35
|
+
from: z.string(),
|
|
36
|
+
to: z.string(),
|
|
37
|
+
date: z.string(),
|
|
38
|
+
}),
|
|
39
|
+
execute: searchFlights,
|
|
40
|
+
},
|
|
41
|
+
bookFlight: {
|
|
42
|
+
description: "Book a specific flight",
|
|
43
|
+
inputSchema: z.object({
|
|
44
|
+
flightId: z.string(),
|
|
45
|
+
passenger: z.string(),
|
|
46
|
+
}),
|
|
47
|
+
execute: bookFlight,
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
await agent.stream({ // [!code highlight]
|
|
53
|
+
messages,
|
|
54
|
+
writable: getWritable<UIMessageChunk>(),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Full Implementation
|
|
60
|
+
|
|
61
|
+
```typescript lineNumbers
|
|
62
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
63
|
+
import { getWritable } from "workflow";
|
|
64
|
+
import { z } from "zod";
|
|
65
|
+
import type { ModelMessage, UIMessageChunk } from "ai";
|
|
66
|
+
|
|
67
|
+
// Step: Search flights with full Node.js access and automatic retries
|
|
68
|
+
async function searchFlights({
|
|
69
|
+
from,
|
|
70
|
+
to,
|
|
71
|
+
date,
|
|
72
|
+
}: {
|
|
73
|
+
from: string;
|
|
74
|
+
to: string;
|
|
75
|
+
date: string;
|
|
76
|
+
}) {
|
|
77
|
+
"use step";
|
|
78
|
+
|
|
79
|
+
const response = await fetch(
|
|
80
|
+
`https://api.example.com/flights?from=${from}&to=${to}&date=${date}`
|
|
81
|
+
);
|
|
82
|
+
if (!response.ok) throw new Error(`Search failed: ${response.status}`);
|
|
83
|
+
return response.json();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Step: Book a flight — retries on transient failures
|
|
87
|
+
async function bookFlight({
|
|
88
|
+
flightId,
|
|
89
|
+
passenger,
|
|
90
|
+
}: {
|
|
91
|
+
flightId: string;
|
|
92
|
+
passenger: string;
|
|
93
|
+
}) {
|
|
94
|
+
"use step";
|
|
95
|
+
|
|
96
|
+
const response = await fetch("https://api.example.com/bookings", {
|
|
97
|
+
method: "POST",
|
|
98
|
+
headers: { "Content-Type": "application/json" },
|
|
99
|
+
body: JSON.stringify({ flightId, passenger }),
|
|
100
|
+
});
|
|
101
|
+
if (!response.ok) throw new Error(`Booking failed: ${response.status}`);
|
|
102
|
+
return response.json();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Step: Check flight status
|
|
106
|
+
async function checkStatus({ flightId }: { flightId: string }) {
|
|
107
|
+
"use step";
|
|
108
|
+
|
|
109
|
+
const response = await fetch(
|
|
110
|
+
`https://api.example.com/flights/${flightId}/status`
|
|
111
|
+
);
|
|
112
|
+
return response.json();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function flightAgent(messages: ModelMessage[]) {
|
|
116
|
+
"use workflow";
|
|
117
|
+
|
|
118
|
+
const writable = getWritable<UIMessageChunk>(); // [!code highlight]
|
|
119
|
+
|
|
120
|
+
const agent = new DurableAgent({ // [!code highlight]
|
|
121
|
+
model: "anthropic/claude-haiku-4.5",
|
|
122
|
+
instructions: "You are a helpful flight booking assistant.",
|
|
123
|
+
tools: {
|
|
124
|
+
searchFlights: {
|
|
125
|
+
description: "Search for available flights between two airports",
|
|
126
|
+
inputSchema: z.object({
|
|
127
|
+
from: z.string().describe("Departure airport code"),
|
|
128
|
+
to: z.string().describe("Arrival airport code"),
|
|
129
|
+
date: z.string().describe("Travel date (YYYY-MM-DD)"),
|
|
130
|
+
}),
|
|
131
|
+
execute: searchFlights,
|
|
132
|
+
},
|
|
133
|
+
bookFlight: {
|
|
134
|
+
description: "Book a specific flight for a passenger",
|
|
135
|
+
inputSchema: z.object({
|
|
136
|
+
flightId: z.string().describe("Flight ID from search results"),
|
|
137
|
+
passenger: z.string().describe("Passenger full name"),
|
|
138
|
+
}),
|
|
139
|
+
execute: bookFlight,
|
|
140
|
+
},
|
|
141
|
+
checkStatus: {
|
|
142
|
+
description: "Check the current status of a flight",
|
|
143
|
+
inputSchema: z.object({
|
|
144
|
+
flightId: z.string().describe("Flight ID to check"),
|
|
145
|
+
}),
|
|
146
|
+
execute: checkStatus,
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
const result = await agent.stream({ // [!code highlight]
|
|
152
|
+
messages,
|
|
153
|
+
writable,
|
|
154
|
+
maxSteps: 10,
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
return { messages: result.messages };
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### API Route
|
|
162
|
+
|
|
163
|
+
```typescript lineNumbers
|
|
164
|
+
import { createUIMessageStreamResponse } from "ai";
|
|
165
|
+
import { start } from "workflow/api";
|
|
166
|
+
import { flightAgent } from "@/workflows/flight-agent";
|
|
167
|
+
import type { UIMessage } from "ai";
|
|
168
|
+
import { convertToModelMessages } from "ai";
|
|
169
|
+
|
|
170
|
+
export async function POST(req: Request) {
|
|
171
|
+
const { messages }: { messages: UIMessage[] } = await req.json();
|
|
172
|
+
const modelMessages = await convertToModelMessages(messages);
|
|
173
|
+
|
|
174
|
+
const run = await start(flightAgent, [modelMessages]); // [!code highlight]
|
|
175
|
+
|
|
176
|
+
return createUIMessageStreamResponse({
|
|
177
|
+
stream: run.readable,
|
|
178
|
+
headers: {
|
|
179
|
+
"x-workflow-run-id": run.runId,
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## Key APIs
|
|
186
|
+
|
|
187
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
188
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — declares step functions with retries and full Node.js access
|
|
189
|
+
- [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — durable wrapper around AI SDK's Agent
|
|
190
|
+
- [`getWritable()`](/docs/api-reference/workflow/get-writable) — streams agent output to the client
|
|
191
|
+
- [`start()`](/docs/api-reference/workflow-api/start) — starts a workflow run from an API route
|