workflow 5.0.0-beta.1 → 5.0.0-beta.3
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 -1
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +2 -2
- 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 +1 -1
- package/dist/nitro.js +1 -1
- package/dist/nuxt.js +1 -1
- package/dist/observability.js +1 -1
- 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 +34 -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/cookbook/advanced/child-workflows.mdx +372 -0
- package/docs/cookbook/advanced/distributed-abort-controller.mdx +318 -0
- package/docs/cookbook/advanced/meta.json +9 -0
- package/docs/cookbook/advanced/publishing-libraries.mdx +336 -0
- package/docs/cookbook/advanced/serializable-steps.mdx +147 -0
- package/docs/cookbook/agent-patterns/agent-cancellation.mdx +205 -0
- package/docs/cookbook/agent-patterns/durable-agent.mdx +150 -0
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +255 -0
- package/docs/cookbook/agent-patterns/meta.json +4 -0
- package/docs/cookbook/common-patterns/batching.mdx +105 -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 +247 -0
- package/docs/cookbook/common-patterns/scheduling.mdx +125 -0
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +155 -0
- package/docs/cookbook/common-patterns/timeouts.mdx +99 -0
- package/docs/cookbook/common-patterns/webhooks.mdx +185 -0
- package/docs/cookbook/common-patterns/workflow-composition.mdx +118 -0
- package/docs/cookbook/index.mdx +38 -0
- package/docs/cookbook/integrations/ai-sdk.mdx +360 -0
- package/docs/cookbook/integrations/chat-sdk.mdx +303 -0
- package/docs/cookbook/integrations/meta.json +4 -0
- package/docs/cookbook/integrations/sandbox.mdx +516 -0
- package/docs/cookbook/meta.json +5 -0
- package/docs/deploying/world/local-world.mdx +1 -1
- package/docs/deploying/world/postgres-world.mdx +1 -1
- package/docs/deploying/world/vercel-world.mdx +1 -1
- package/docs/errors/start-invalid-workflow-function.mdx +1 -1
- package/docs/foundations/index.mdx +0 -3
- package/docs/foundations/meta.json +0 -1
- package/docs/foundations/serialization.mdx +1 -1
- package/docs/foundations/starting-workflows.mdx +1 -1
- package/docs/getting-started/index.mdx +8 -1
- package/docs/getting-started/meta.json +2 -1
- package/docs/getting-started/python.mdx +165 -0
- 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 +363 -0
- package/docs/migration-guides/migrating-from-inngest.mdx +314 -0
- package/docs/migration-guides/migrating-from-temporal.mdx +318 -0
- package/docs/migration-guides/migrating-from-trigger-dev.mdx +337 -0
- package/package.json +13 -13
- package/docs/foundations/common-patterns.mdx +0 -265
|
@@ -0,0 +1,336 @@
|
|
|
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
|
+
import { File, Folder, Files } from "fumadocs-ui/components/files";
|
|
9
|
+
|
|
10
|
+
<Callout>
|
|
11
|
+
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.
|
|
12
|
+
</Callout>
|
|
13
|
+
|
|
14
|
+
## Package Structure
|
|
15
|
+
|
|
16
|
+
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()`.
|
|
17
|
+
|
|
18
|
+
<Files>
|
|
19
|
+
<Folder name="my-media-lib" defaultOpen>
|
|
20
|
+
<Folder name="src" defaultOpen>
|
|
21
|
+
<File name="index.ts" />
|
|
22
|
+
<File name="types.ts" />
|
|
23
|
+
<Folder name="workflows" defaultOpen>
|
|
24
|
+
<File name="index.ts" />
|
|
25
|
+
<File name="transcode.ts" />
|
|
26
|
+
<File name="generate-thumbnails.ts" />
|
|
27
|
+
</Folder>
|
|
28
|
+
<Folder name="lib" defaultOpen>
|
|
29
|
+
<File name="api-client.ts" />
|
|
30
|
+
</Folder>
|
|
31
|
+
</Folder>
|
|
32
|
+
<Folder name="test-server" defaultOpen>
|
|
33
|
+
<File name="workflows.ts" />
|
|
34
|
+
</Folder>
|
|
35
|
+
<File name="tsup.config.ts" />
|
|
36
|
+
<File name="package.json" />
|
|
37
|
+
<File name="tsconfig.json" />
|
|
38
|
+
</Folder>
|
|
39
|
+
</Files>
|
|
40
|
+
|
|
41
|
+
Key files:
|
|
42
|
+
|
|
43
|
+
- **`src/index.ts`** — Package entry point. Exports the public API.
|
|
44
|
+
- **`src/types.ts`** — Shared TypeScript types.
|
|
45
|
+
- **`src/workflows/index.ts`** — Re-exports every workflow so consumers can pull them in under one specifier (see [Entry Points and Exports](#entry-points-and-exports)).
|
|
46
|
+
- **`src/workflows/*.ts`** — One file per workflow function (e.g. `transcode.ts`, `generate-thumbnails.ts`).
|
|
47
|
+
- **`src/lib/`** — Internal helpers. Plain async code, *not* marked with `"use workflow"` or `"use step"`.
|
|
48
|
+
- **`test-server/workflows.ts`** — Re-export file used by integration tests (see [Testing Workflow Libraries](#testing-workflow-libraries)).
|
|
49
|
+
|
|
50
|
+
### Entry Points and Exports
|
|
51
|
+
|
|
52
|
+
Use the `exports` field in `package.json` to expose separate entry points for the main API and the raw workflow functions:
|
|
53
|
+
|
|
54
|
+
```json
|
|
55
|
+
{
|
|
56
|
+
"name": "@acme/media",
|
|
57
|
+
"type": "module",
|
|
58
|
+
"exports": {
|
|
59
|
+
".": {
|
|
60
|
+
"types": { "import": "./dist/index.d.ts" },
|
|
61
|
+
"import": "./dist/index.js"
|
|
62
|
+
},
|
|
63
|
+
"./workflows": {
|
|
64
|
+
"types": { "import": "./dist/workflows/index.d.ts" },
|
|
65
|
+
"import": "./dist/workflows/index.js"
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"files": ["dist"]
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
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.
|
|
73
|
+
|
|
74
|
+
### Source Files
|
|
75
|
+
|
|
76
|
+
The package entry re-exports workflows alongside any utilities:
|
|
77
|
+
|
|
78
|
+
```typescript lineNumbers
|
|
79
|
+
// src/index.ts
|
|
80
|
+
export * from "./types";
|
|
81
|
+
export * as workflows from "./workflows";
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The workflows barrel file re-exports each workflow:
|
|
85
|
+
|
|
86
|
+
```typescript lineNumbers
|
|
87
|
+
// src/workflows/index.ts
|
|
88
|
+
export * from "./transcode";
|
|
89
|
+
export * from "./generate-thumbnails";
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Build Configuration
|
|
93
|
+
|
|
94
|
+
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:
|
|
95
|
+
|
|
96
|
+
```typescript lineNumbers
|
|
97
|
+
// tsup.config.ts
|
|
98
|
+
import { defineConfig } from "tsup";
|
|
99
|
+
|
|
100
|
+
export default defineConfig({
|
|
101
|
+
entry: [
|
|
102
|
+
"src/index.ts",
|
|
103
|
+
"src/workflows/index.ts",
|
|
104
|
+
],
|
|
105
|
+
format: ["esm"],
|
|
106
|
+
dts: true,
|
|
107
|
+
sourcemap: true,
|
|
108
|
+
clean: true,
|
|
109
|
+
external: ["workflow"], // [!code highlight]
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Re-Exporting for Workflow ID Stability
|
|
114
|
+
|
|
115
|
+
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.
|
|
116
|
+
|
|
117
|
+
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.
|
|
118
|
+
|
|
119
|
+
### Consumer Setup
|
|
120
|
+
|
|
121
|
+
```typescript lineNumbers
|
|
122
|
+
// workflows/media.ts (in the consumer's project)
|
|
123
|
+
// Re-export library workflows so the build system assigns stable IDs
|
|
124
|
+
export * from "@acme/media/workflows"; // [!code highlight]
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
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.
|
|
128
|
+
|
|
129
|
+
### Why This Is Necessary
|
|
130
|
+
|
|
131
|
+
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.
|
|
132
|
+
|
|
133
|
+
The re-export pattern ensures:
|
|
134
|
+
|
|
135
|
+
1. **Stable IDs** — the compiler assigns IDs based on the consumer's source tree
|
|
136
|
+
2. **Replay safety** — IDs persist across deployments and cold starts
|
|
137
|
+
3. **Version upgrades** — re-exported IDs remain stable as long as the consumer's file doesn't change
|
|
138
|
+
|
|
139
|
+
## Keeping Step I/O Clean
|
|
140
|
+
|
|
141
|
+
When you publish a workflow library, every step function's inputs and outputs are recorded in the event log. This has two implications:
|
|
142
|
+
|
|
143
|
+
### 1. Everything Must Be Serializable
|
|
144
|
+
|
|
145
|
+
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/foundations/serialization#custom-class-serialization). See the [serialization reference](/docs/foundations/serialization) for the full list of supported types. Do not pass or return:
|
|
146
|
+
|
|
147
|
+
- Functions or closures
|
|
148
|
+
- `WeakRef`, `WeakMap`, or `WeakSet`
|
|
149
|
+
|
|
150
|
+
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.
|
|
151
|
+
|
|
152
|
+
{/* @skip-typecheck - good/bad comparison with duplicate function names */}
|
|
153
|
+
```typescript lineNumbers
|
|
154
|
+
// Good: pass serializable config, construct inside the step
|
|
155
|
+
async function callExternalApi(endpoint: string, params: Record<string, string>) {
|
|
156
|
+
"use step";
|
|
157
|
+
const client = createApiClient(process.env.API_KEY!);
|
|
158
|
+
return await client.request(endpoint, params);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Bad: pass a pre-constructed client object
|
|
162
|
+
async function callExternalApi(client: ApiClient, params: Record<string, string>) {
|
|
163
|
+
"use step";
|
|
164
|
+
// ApiClient is not serializable — this will fail on replay
|
|
165
|
+
return await client.request(params);
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
See [Serializable Steps](/docs/cookbook/advanced/serializable-steps) for the step-as-factory pattern.
|
|
170
|
+
|
|
171
|
+
### 2. Credentials
|
|
172
|
+
|
|
173
|
+
With workflow encryption enabled, credentials passed as step arguments are encrypted in the event log, so either approach is valid:
|
|
174
|
+
|
|
175
|
+
{/* @skip-typecheck - good/bad comparison with duplicate function names */}
|
|
176
|
+
```typescript lineNumbers
|
|
177
|
+
// Option A: resolve credentials from environment inside the step
|
|
178
|
+
async function fetchData(query: string) {
|
|
179
|
+
"use step";
|
|
180
|
+
const client = createClient(process.env.API_KEY!);
|
|
181
|
+
return await client.fetch(query);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Option B: pass credentials as step arguments (encrypted in the event log)
|
|
185
|
+
async function fetchData(apiKey: string, query: string) {
|
|
186
|
+
"use step";
|
|
187
|
+
const client = createClient(apiKey);
|
|
188
|
+
return await client.fetch(query);
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
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.
|
|
193
|
+
|
|
194
|
+
## Testing Workflow Libraries
|
|
195
|
+
|
|
196
|
+
Library authors need integration tests that exercise workflows through the full Workflow SDK runtime — not just unit tests of individual functions.
|
|
197
|
+
|
|
198
|
+
### Test Server Pattern
|
|
199
|
+
|
|
200
|
+
Create a minimal test server that re-exports your library's workflows, just like a consumer would:
|
|
201
|
+
|
|
202
|
+
```typescript lineNumbers
|
|
203
|
+
// test-server/workflows.ts
|
|
204
|
+
export * from "@acme/media/workflows"; // [!code highlight]
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
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.
|
|
208
|
+
|
|
209
|
+
### Vitest Configuration
|
|
210
|
+
|
|
211
|
+
Use a dedicated Vitest config for integration tests that run against the Workflow SDK runtime:
|
|
212
|
+
|
|
213
|
+
```typescript lineNumbers
|
|
214
|
+
// vitest.workflowsdk.config.ts
|
|
215
|
+
import { defineConfig } from "vitest/config";
|
|
216
|
+
|
|
217
|
+
export default defineConfig({
|
|
218
|
+
test: {
|
|
219
|
+
include: ["tests/integration/**/*.workflowsdk.test.ts"],
|
|
220
|
+
testTimeout: 120_000, // Workflows may take time to complete
|
|
221
|
+
setupFiles: ["./tests/setup.ts"],
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Run these tests separately from your unit tests:
|
|
227
|
+
|
|
228
|
+
```bash
|
|
229
|
+
# Unit tests (fast, no workflow runtime)
|
|
230
|
+
pnpm vitest run tests/unit
|
|
231
|
+
|
|
232
|
+
# Integration tests (requires workflow runtime)
|
|
233
|
+
pnpm vitest run --config vitest.workflowsdk.config.ts
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### What to Test
|
|
237
|
+
|
|
238
|
+
- **Happy path**: workflow starts, all steps execute, and the final result is correct
|
|
239
|
+
- **Serialization round-trip**: inputs and outputs survive the event log
|
|
240
|
+
- **Replay**: kill and restart a workflow mid-execution to verify deterministic replay
|
|
241
|
+
- **Error handling**: verify that step failures produce the expected errors
|
|
242
|
+
|
|
243
|
+
## Working With and Without Workflow Installed
|
|
244
|
+
|
|
245
|
+
Some libraries want to be useful to consumers who *aren't* using Workflow SDK at all — the library picks up durable behavior when a workflow runtime is present and falls back to plain async execution otherwise.
|
|
246
|
+
|
|
247
|
+
<Callout type="info">
|
|
248
|
+
Two rules for isomorphic packages:
|
|
249
|
+
|
|
250
|
+
1. **Any runtime reference to the `workflow` package must be loaded via dynamic `import("workflow")` inside a try/catch.** A static top-level import makes the module fail to load for consumers who haven't installed workflow.
|
|
251
|
+
2. **The `"use workflow"` and `"use step"` directives are safe to keep in your library source.** When a consumer compiles your code with the Workflow SDK toolchain (via the [re-export pattern](#re-exporting-for-workflow-id-stability) above), the SWC plugin transforms them into durable-execution glue. When they're not compiled — plain Node, plain tests, a consumer without the runtime — they are just string expression statements and run as no-ops.
|
|
252
|
+
</Callout>
|
|
253
|
+
|
|
254
|
+
### Optional peer dependency
|
|
255
|
+
|
|
256
|
+
Declare `workflow` as an **optional** peer so consumers without the runtime aren't forced to install it:
|
|
257
|
+
|
|
258
|
+
```json
|
|
259
|
+
{
|
|
260
|
+
"peerDependencies": {
|
|
261
|
+
"workflow": ">=4.0.0"
|
|
262
|
+
},
|
|
263
|
+
"peerDependenciesMeta": {
|
|
264
|
+
"workflow": {
|
|
265
|
+
"optional": true
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### Runtime detection
|
|
272
|
+
|
|
273
|
+
Wrap a dynamic `import("workflow")` in try/catch. If either the module isn't installed *or* `getWorkflowMetadata()` throws (call site isn't inside a workflow run), fall through to the standalone path.
|
|
274
|
+
|
|
275
|
+
```typescript lineNumbers
|
|
276
|
+
async function getWorkflowRunId(): Promise<string | null> { // [!code highlight]
|
|
277
|
+
try {
|
|
278
|
+
const wf = await import("workflow");
|
|
279
|
+
const { workflowRunId } = wf.getWorkflowMetadata();
|
|
280
|
+
return workflowRunId;
|
|
281
|
+
} catch {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### A concrete use case: replay-safe idempotency keys
|
|
288
|
+
|
|
289
|
+
A payments utility that uses the workflow run ID as a Stripe idempotency key when available, and a fresh UUID otherwise:
|
|
290
|
+
|
|
291
|
+
{/* @skip-typecheck - depends on getWorkflowRunId defined in the previous block */}
|
|
292
|
+
```typescript lineNumbers
|
|
293
|
+
export async function processPayment(amount: number, currency: string) {
|
|
294
|
+
const runId = await getWorkflowRunId();
|
|
295
|
+
const idempotencyKey = runId ?? crypto.randomUUID(); // [!code highlight]
|
|
296
|
+
|
|
297
|
+
const res = await fetch("https://api.stripe.com/v1/charges", {
|
|
298
|
+
method: "POST",
|
|
299
|
+
headers: {
|
|
300
|
+
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
|
|
301
|
+
"Idempotency-Key": idempotencyKey, // [!code highlight]
|
|
302
|
+
},
|
|
303
|
+
body: new URLSearchParams({ amount: String(amount), currency }),
|
|
304
|
+
});
|
|
305
|
+
return res.json();
|
|
306
|
+
}
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
When called from inside a workflow run, the step wrapping this utility gets a stable idempotency key across replays — Stripe dedupes retries for free. When called from a plain Node.js process, it behaves like any other function and a fresh UUID is generated.
|
|
310
|
+
|
|
311
|
+
### In production
|
|
312
|
+
|
|
313
|
+
Packages in the wild built on Workflow SDK:
|
|
314
|
+
|
|
315
|
+
- **[`@mux/ai`](https://github.com/muxinc/ai)** — Reusable video AI workflows (summaries, chapters, content moderation, translation, embeddings) exported with `"use workflow"` / `"use step"` directives. In a standard Node environment the directives are no-ops and the SDK runs as a plain async library; in a Workflow SDK environment the consumer's compiler transforms them into durable, resumable steps with automatic retries and observability. Written up in detail in [*How Mux shipped durable video workflows with their @mux/ai SDK*](https://vercel.com/blog/how-mux-shipped-durable-video-workflows-with-their-mux-ai-sdk) on the Vercel blog.
|
|
316
|
+
- **World ID** — Human-in-the-loop "proof of human" primitive for agent workflows. Developers drop a World ID step into any workflow to require a zero-knowledge cryptographic proof that a real, unique human authorized a specific action (deploy approvals, large payments, sensitive data access, etc.). Because it runs as a workflow step, every verification is durable, replay-safe, and viewable inside the run's execution timeline — giving you a provable audit record of which human approved what. Available on npm and announced in [*World ID for agents: Browserbase, Exa, Okta, and Vercel*](https://world.org/blog/announcements/browserbase-exa-okta-world-id-for-agentic-web) on the World blog.
|
|
317
|
+
|
|
318
|
+
## Checklist
|
|
319
|
+
|
|
320
|
+
Before publishing a workflow library:
|
|
321
|
+
|
|
322
|
+
- [ ] `workflow` is listed as an **optional** peer dependency
|
|
323
|
+
- [ ] Separate `./workflows` export in `package.json` for the raw workflow functions
|
|
324
|
+
- [ ] `workflow` is marked as **external** in your bundler config
|
|
325
|
+
- [ ] Documentation tells consumers to re-export from `@your-lib/workflows`
|
|
326
|
+
- [ ] Credentials are either resolved from environment variables or passed explicitly (both are safe with encryption enabled)
|
|
327
|
+
- [ ] All step I/O uses [supported serializable types](/docs/foundations/serialization)
|
|
328
|
+
- [ ] Integration tests use a test server with re-exported workflows
|
|
329
|
+
- [ ] Both with-workflow and without-workflow code paths are tested
|
|
330
|
+
|
|
331
|
+
## Key APIs
|
|
332
|
+
|
|
333
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
334
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — marks functions for durable execution
|
|
335
|
+
- [`start`](/docs/api-reference/workflow/start) — starts a workflow run
|
|
336
|
+
- [`getWorkflowMetadata`](/docs/api-reference/workflow/get-workflow-metadata) — runtime detection and run ID access
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Serializable Steps
|
|
3
|
+
description: Wrap non-serializable third-party objects (like AI model providers) inside step factory functions so they can cross the workflow boundary.
|
|
4
|
+
type: guide
|
|
5
|
+
summary: Return a callback from a step to defer construction of a non-owned class (AI SDK models, cloud SDK clients) until execution time, making them usable inside durable workflows.
|
|
6
|
+
related:
|
|
7
|
+
- /docs/foundations/serialization
|
|
8
|
+
- /docs/foundations/serialization#custom-class-serialization
|
|
9
|
+
- /docs/api-reference/workflow/use-step
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
<Callout>
|
|
13
|
+
This is an advanced guide. It dives into workflow internals and is not required reading to use workflow.
|
|
14
|
+
</Callout>
|
|
15
|
+
|
|
16
|
+
## When to use this pattern
|
|
17
|
+
|
|
18
|
+
Workflow functions run inside a sandboxed VM where every value that crosses a function boundary must be serializable. There are two ways to get a non-serializable object across that boundary, depending on whether you own the class:
|
|
19
|
+
|
|
20
|
+
- **You own the class** — implement the [`WORKFLOW_SERIALIZE` / `WORKFLOW_DESERIALIZE` protocol](/docs/foundations/serialization#custom-class-serialization). The instance becomes a first-class serializable value: you can pass it as a workflow input, return it from a step, and call `"use step"` instance methods on it directly. This is the right tool when the class is yours to modify.
|
|
21
|
+
- **You don't own the class** — you can't add methods to `openai("gpt-4o")` from `@ai-sdk/openai` or `new S3Client({...})` from `@aws-sdk/client-s3`. Instead, wrap construction in a `"use step"` factory function and pass the factory across the boundary. That's what this page covers.
|
|
22
|
+
|
|
23
|
+
## The Problem
|
|
24
|
+
|
|
25
|
+
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, and you can't bolt `WORKFLOW_SERIALIZE` onto a third-party class.
|
|
26
|
+
|
|
27
|
+
```typescript lineNumbers
|
|
28
|
+
import { openai } from "@ai-sdk/openai";
|
|
29
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
30
|
+
import { getWritable } from "workflow";
|
|
31
|
+
import type { UIMessageChunk } from "ai";
|
|
32
|
+
|
|
33
|
+
export async function brokenAgent(prompt: string) {
|
|
34
|
+
"use workflow";
|
|
35
|
+
|
|
36
|
+
const writable = getWritable<UIMessageChunk>();
|
|
37
|
+
const agent = new DurableAgent({
|
|
38
|
+
// This fails — the model object is not serializable
|
|
39
|
+
model: openai("gpt-4o"),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
await agent.stream({ messages: [{ role: "user", content: prompt }], writable });
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## The Solution: Step-as-Factory
|
|
47
|
+
|
|
48
|
+
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.
|
|
49
|
+
|
|
50
|
+
```typescript lineNumbers
|
|
51
|
+
import { openai as openaiProvider } from "@ai-sdk/openai";
|
|
52
|
+
|
|
53
|
+
// Returns a step function, not a model object
|
|
54
|
+
export function openai(...args: Parameters<typeof openaiProvider>) {
|
|
55
|
+
return async () => {
|
|
56
|
+
"use step";
|
|
57
|
+
return openaiProvider(...args); // [!code highlight]
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
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.
|
|
63
|
+
|
|
64
|
+
## How `@workflow/ai` Uses This
|
|
65
|
+
|
|
66
|
+
The `@workflow/ai` package ships pre-wrapped providers for all major AI SDK backends. Each one follows the same pattern:
|
|
67
|
+
|
|
68
|
+
```typescript lineNumbers
|
|
69
|
+
// packages/ai/src/providers/anthropic.ts
|
|
70
|
+
import { anthropic as anthropicProvider } from "@ai-sdk/anthropic";
|
|
71
|
+
|
|
72
|
+
export function anthropic(...args: Parameters<typeof anthropicProvider>) {
|
|
73
|
+
return async () => {
|
|
74
|
+
"use step";
|
|
75
|
+
return anthropicProvider(...args); // [!code highlight]
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
This means you import from `@workflow/ai` instead of `@ai-sdk/*` directly:
|
|
81
|
+
|
|
82
|
+
```typescript lineNumbers
|
|
83
|
+
import { anthropic } from "@workflow/ai/anthropic";
|
|
84
|
+
import { DurableAgent } from "@workflow/ai/agent";
|
|
85
|
+
import { getWritable } from "workflow";
|
|
86
|
+
import type { UIMessageChunk } from "ai";
|
|
87
|
+
|
|
88
|
+
export async function chatAgent(prompt: string) {
|
|
89
|
+
"use workflow";
|
|
90
|
+
|
|
91
|
+
const writable = getWritable<UIMessageChunk>();
|
|
92
|
+
const agent = new DurableAgent({
|
|
93
|
+
model: anthropic("claude-sonnet-4-20250514"), // [!code highlight]
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
await agent.stream({ messages: [{ role: "user", content: prompt }], writable });
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Writing Your Own Serializable Wrapper
|
|
101
|
+
|
|
102
|
+
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**.
|
|
103
|
+
|
|
104
|
+
```typescript lineNumbers
|
|
105
|
+
import type { S3Client as S3ClientType } from "@aws-sdk/client-s3";
|
|
106
|
+
|
|
107
|
+
// The arguments (region, bucket) are plain strings — serializable
|
|
108
|
+
export function createS3Client(region: string) {
|
|
109
|
+
return async (): Promise<S3ClientType> => {
|
|
110
|
+
"use step";
|
|
111
|
+
const { S3Client } = await import("@aws-sdk/client-s3");
|
|
112
|
+
return new S3Client({ region });
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Usage in a workflow
|
|
117
|
+
export async function processUpload(region: string, key: string) {
|
|
118
|
+
"use workflow";
|
|
119
|
+
|
|
120
|
+
const getClient = createS3Client(region); // [!code highlight]
|
|
121
|
+
// getClient is a serializable step reference, not an S3Client
|
|
122
|
+
await uploadFile(getClient, key);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function uploadFile(
|
|
126
|
+
getClient: () => Promise<S3ClientType>,
|
|
127
|
+
key: string
|
|
128
|
+
) {
|
|
129
|
+
"use step";
|
|
130
|
+
const client = await getClient(); // [!code highlight]
|
|
131
|
+
// Now you have a real S3Client with full Node.js access
|
|
132
|
+
await client.send(/* ... */);
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Why This Works
|
|
137
|
+
|
|
138
|
+
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).
|
|
139
|
+
2. **Closure tracking**: The compiler tracks which variables the step function closes over. Only serializable values (strings, numbers, plain objects) can be captured.
|
|
140
|
+
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.
|
|
141
|
+
|
|
142
|
+
## Key APIs
|
|
143
|
+
|
|
144
|
+
- [`"use step"`](/docs/api-reference/workflow/use-step) — marks a function for extraction and serialization
|
|
145
|
+
- [`"use workflow"`](/docs/api-reference/workflow/use-workflow) — declares the orchestrator function
|
|
146
|
+
- [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent) — accepts a model factory for durable AI agent streaming
|
|
147
|
+
- [Custom class serialization](/docs/foundations/serialization#custom-class-serialization) — the companion pattern for classes you own (`WORKFLOW_SERIALIZE` / `WORKFLOW_DESERIALIZE`)
|