workflow 5.0.1 → 5.2.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 +6 -0
- package/dist/api-workflow.d.ts.map +1 -1
- package/dist/api-workflow.js +4 -2
- package/docs/ai/chat-session-modeling.mdx +8 -8
- package/docs/ai/human-in-the-loop.mdx +2 -2
- package/docs/ai/index.mdx +14 -14
- package/docs/ai/streaming-updates-from-tools.mdx +2 -2
- package/docs/api-reference/workflow-api/register-lifecycle-hooks.mdx +15 -5
- package/docs/api-reference/workflow-nest/index.mdx +4 -1
- package/docs/api-reference/workflow-nest/is-workflow-request.mdx +58 -0
- package/docs/api-reference/workflow-nest/meta.json +1 -0
- package/docs/api-reference/workflow-nest/workflow-controller.mdx +6 -2
- package/docs/api-reference/workflow-nest/workflow-module.mdx +9 -1
- package/docs/api-reference/workflow-observability/parse-step-name.mdx +1 -1
- package/docs/changelog/batched-event-writes.mdx +3 -3
- package/docs/configuration/framework-options.mdx +6 -0
- package/docs/configuration/runtime-tuning.mdx +7 -5
- package/docs/configuration/worlds.mdx +11 -8
- package/docs/cookbook/integrations/ai-sdk.mdx +8 -8
- package/docs/cookbook/integrations/chat-sdk.mdx +8 -8
- package/docs/cookbook/integrations/sandbox.mdx +8 -8
- package/docs/errors/node-js-module-in-workflow.mdx +36 -0
- package/docs/foundations/hooks.mdx +35 -0
- package/docs/foundations/serialization.mdx +16 -1
- package/docs/foundations/streaming.mdx +1 -1
- package/docs/getting-started/astro.mdx +7 -9
- package/docs/getting-started/express.mdx +4 -10
- package/docs/getting-started/fastify.mdx +4 -9
- package/docs/getting-started/hono.mdx +4 -10
- package/docs/getting-started/index.mdx +2 -2
- package/docs/getting-started/nestjs.mdx +157 -36
- package/docs/getting-started/next.mdx +15 -18
- package/docs/getting-started/nitro.mdx +4 -10
- package/docs/getting-started/nuxt.mdx +4 -10
- package/docs/getting-started/react-router/v7.mdx +6 -22
- package/docs/getting-started/react-router/v8.mdx +6 -22
- package/docs/getting-started/sveltekit.mdx +7 -9
- package/docs/getting-started/tanstack-start.mdx +7 -9
- package/docs/getting-started/vite.mdx +7 -9
- package/docs/how-it-works/code-transform.mdx +12 -8
- package/docs/how-it-works/encryption.mdx +3 -1
- package/docs/observability/lifecycle-hooks.mdx +69 -5
- package/docs/observability/tracing.mdx +3 -0
- package/docs/whats-new.mdx +7 -7
- package/docs/worlds/building-a-world.mdx +6 -1
- package/docs/worlds/local.mdx +4 -0
- package/docs/worlds/postgres.mdx +13 -33
- package/docs/worlds/upgrading-to-v5.mdx +1 -1
- package/docs/worlds/vercel.mdx +19 -9
- package/package.json +12 -12
package/README.md
CHANGED
|
@@ -65,6 +65,12 @@ Choose your framework in the
|
|
|
65
65
|
|
|
66
66
|
## Run anywhere
|
|
67
67
|
|
|
68
|
+
For application-level completion and failure reporting, `registerLifecycleHooks`
|
|
69
|
+
from `workflow/api` registers handlers in the workflow executor's host startup.
|
|
70
|
+
Calling it inside a workflow or step throws. Check the
|
|
71
|
+
[lifecycle hooks guide](https://workflow-sdk.dev/v5/docs/observability/lifecycle-hooks)
|
|
72
|
+
for supported framework/deployment combinations and stream cleanup requirements.
|
|
73
|
+
|
|
68
74
|
Local development uses the bundled backend with no configuration. Deploy to
|
|
69
75
|
Vercel for managed storage, queuing, scaling, and observability. To self-host,
|
|
70
76
|
use the Postgres backend or implement a custom
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-workflow.d.ts","sourceRoot":"","sources":["../src/api-workflow.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,6BAA6B,EAC7B,WAAW,EACX,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AACjD,OAAO,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAQrD,eAAO,MAAM,MAAM,aAA+B,CAAC;AACnD,eAAO,MAAM,cAAc,aAAuC,CAAC;AACnE,eAAO,MAAM,UAAU,aAAmC,CAAC;AAC3D,eAAO,MAAM,aAAa,aAAsC,CAAC;AACjE,eAAO,MAAM,OAAO,aAAgC,CAAC;AACrD,eAAO,MAAM,sBAAsB,
|
|
1
|
+
{"version":3,"file":"api-workflow.d.ts","sourceRoot":"","sources":["../src/api-workflow.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,6BAA6B,EAC7B,WAAW,EACX,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AACjD,OAAO,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAQrD,eAAO,MAAM,MAAM,aAA+B,CAAC;AACnD,eAAO,MAAM,cAAc,aAAuC,CAAC;AACnE,eAAO,MAAM,UAAU,aAAmC,CAAC;AAC3D,eAAO,MAAM,aAAa,aAAsC,CAAC;AACjE,eAAO,MAAM,OAAO,aAAgC,CAAC;AACrD,eAAO,MAAM,sBAAsB,aAIlC,CAAC;AACF,YAAY,EACV,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,wCAAwC,CAAC"}
|
package/dist/api-workflow.js
CHANGED
|
@@ -8,5 +8,7 @@ export const getHookByToken = () => workflowStub('getHookByToken');
|
|
|
8
8
|
export const resumeHook = () => workflowStub('resumeHook');
|
|
9
9
|
export const resumeWebhook = () => workflowStub('resumeWebhook');
|
|
10
10
|
export const runStep = () => workflowStub('runStep');
|
|
11
|
-
export const registerLifecycleHooks = () =>
|
|
12
|
-
|
|
11
|
+
export const registerLifecycleHooks = () => {
|
|
12
|
+
throw new Error('registerLifecycleHooks must be called at host startup, not inside a workflow or step function. Register before handling workflow requests (for example, in instrumentation.ts on Next.js).');
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBpLXdvcmtmbG93LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2FwaS13b3JrZmxvdy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFXQSxPQUFPLEVBQUUsR0FBRyxFQUFFLE1BQU0sNEJBQTRCLENBQUM7QUFDakQsT0FBTyxFQUFFLEtBQUssRUFBRSxNQUFNLDhCQUE4QixDQUFDO0FBRXJELE1BQU0sWUFBWSxHQUFHLENBQUMsSUFBWSxFQUFFLEVBQUU7SUFDcEMsTUFBTSxJQUFJLEtBQUssQ0FDYixnRUFBZ0UsSUFBSSwyRkFBMkYsQ0FDaEssQ0FBQztBQUNKLENBQUMsQ0FBQztBQUVGLE1BQU0sQ0FBQyxNQUFNLE1BQU0sR0FBRyxHQUFHLEVBQUUsQ0FBQyxZQUFZLENBQUMsUUFBUSxDQUFDLENBQUM7QUFDbkQsTUFBTSxDQUFDLE1BQU0sY0FBYyxHQUFHLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxnQkFBZ0IsQ0FBQyxDQUFDO0FBQ25FLE1BQU0sQ0FBQyxNQUFNLFVBQVUsR0FBRyxHQUFHLEVBQUUsQ0FBQyxZQUFZLENBQUMsWUFBWSxDQUFDLENBQUM7QUFDM0QsTUFBTSxDQUFDLE1BQU0sYUFBYSxHQUFHLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxlQUFlLENBQUMsQ0FBQztBQUNqRSxNQUFNLENBQUMsTUFBTSxPQUFPLEdBQUcsR0FBRyxFQUFFLENBQUMsWUFBWSxDQUFDLFNBQVMsQ0FBQyxDQUFDO0FBQ3JELE1BQU0sQ0FBQyxNQUFNLHNCQUFzQixHQUFHLEdBQUcsRUFBRTtJQUN6QyxNQUFNLElBQUksS0FBSyxDQUNiLDRMQUE0TCxDQUM3TCxDQUFDO0FBQ0osQ0FBQyxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHR5cGUge1xuICBDYW5jZWxSdW5PcHRpb25zLFxuICBFdmVudCxcbiAgU3RhcnRPcHRpb25zLFxuICBTdG9wU2xlZXBPcHRpb25zLFxuICBTdG9wU2xlZXBSZXN1bHQsXG4gIFdvcmtmbG93UmVhZGFibGVTdHJlYW1PcHRpb25zLFxuICBXb3JrZmxvd1J1bixcbiAgV29ya2Zsb3dSdW5Xcml0YWJsZVN0cmVhbU9wdGlvbnMsXG59IGZyb20gJ0B3b3JrZmxvdy9jb3JlL3J1bnRpbWUnO1xuXG5leHBvcnQgeyBSdW4gfSBmcm9tICdAd29ya2Zsb3cvY29yZS9ydW50aW1lL3J1bic7XG5leHBvcnQgeyBzdGFydCB9IGZyb20gJ0B3b3JrZmxvdy9jb3JlL3J1bnRpbWUvc3RhcnQnO1xuXG5jb25zdCB3b3JrZmxvd1N0dWIgPSAoaXRlbTogc3RyaW5nKSA9PiB7XG4gIHRocm93IG5ldyBFcnJvcihcbiAgICBgVGhlIHdvcmtmbG93IGVudmlyb25tZW50IGRvZXNuJ3QgYWxsb3cgdGhpcyBydW50aW1lIHVzYWdlIG9mICR7aXRlbX0uIE1vdmUgdGhpcyBjYWxsIHRvIGEgc3RlcCBmdW5jdGlvbiAoXCJ1c2Ugc3RlcFwiKSBvciBjYWxsIGl0IG91dHNpZGUgdGhlIHdvcmtmbG93IGNvbnRleHQuYFxuICApO1xufTtcblxuZXhwb3J0IGNvbnN0IGdldFJ1biA9ICgpID0+IHdvcmtmbG93U3R1YignZ2V0UnVuJyk7XG5leHBvcnQgY29uc3QgZ2V0SG9va0J5VG9rZW4gPSAoKSA9PiB3b3JrZmxvd1N0dWIoJ2dldEhvb2tCeVRva2VuJyk7XG5leHBvcnQgY29uc3QgcmVzdW1lSG9vayA9ICgpID0+IHdvcmtmbG93U3R1YigncmVzdW1lSG9vaycpO1xuZXhwb3J0IGNvbnN0IHJlc3VtZVdlYmhvb2sgPSAoKSA9PiB3b3JrZmxvd1N0dWIoJ3Jlc3VtZVdlYmhvb2snKTtcbmV4cG9ydCBjb25zdCBydW5TdGVwID0gKCkgPT4gd29ya2Zsb3dTdHViKCdydW5TdGVwJyk7XG5leHBvcnQgY29uc3QgcmVnaXN0ZXJMaWZlY3ljbGVIb29rcyA9ICgpID0+IHtcbiAgdGhyb3cgbmV3IEVycm9yKFxuICAgICdyZWdpc3RlckxpZmVjeWNsZUhvb2tzIG11c3QgYmUgY2FsbGVkIGF0IGhvc3Qgc3RhcnR1cCwgbm90IGluc2lkZSBhIHdvcmtmbG93IG9yIHN0ZXAgZnVuY3Rpb24uIFJlZ2lzdGVyIGJlZm9yZSBoYW5kbGluZyB3b3JrZmxvdyByZXF1ZXN0cyAoZm9yIGV4YW1wbGUsIGluIGluc3RydW1lbnRhdGlvbi50cyBvbiBOZXh0LmpzKS4nXG4gICk7XG59O1xuZXhwb3J0IHR5cGUge1xuICBSdW5Db21wbGV0ZWRIb29rUGFyYW1zLFxuICBSdW5GYWlsZWRIb29rUGFyYW1zLFxuICBXb3JrZmxvd0xpZmVjeWNsZUhvb2tzLFxufSBmcm9tICdAd29ya2Zsb3cvY29yZS9ydW50aW1lL2xpZmVjeWNsZS1ob29rcyc7XG4iXX0=
|
|
@@ -267,9 +267,9 @@ Use the multi-turn pattern when:
|
|
|
267
267
|
|
|
268
268
|
The multi-turn pattern also supports messages from system events, external services, and multiple users. Every source resumes the same Hook; the workflow queues those messages and processes them between model turns.
|
|
269
269
|
|
|
270
|
-
<
|
|
270
|
+
<TabsWithChildren tabs={["System event","External service","Multiple users"]}>
|
|
271
271
|
|
|
272
|
-
<
|
|
272
|
+
<TabContent order={1}>
|
|
273
273
|
|
|
274
274
|
Scheduled tasks, background jobs, or database triggers can inject updates into an active conversation:
|
|
275
275
|
|
|
@@ -287,9 +287,9 @@ export async function POST(request: Request) {
|
|
|
287
287
|
}
|
|
288
288
|
```
|
|
289
289
|
|
|
290
|
-
</
|
|
290
|
+
</TabContent>
|
|
291
291
|
|
|
292
|
-
<
|
|
292
|
+
<TabContent order={2}>
|
|
293
293
|
|
|
294
294
|
A third-party webhook can notify the conversation about an external event:
|
|
295
295
|
|
|
@@ -309,9 +309,9 @@ export async function POST(request: Request) {
|
|
|
309
309
|
}
|
|
310
310
|
```
|
|
311
311
|
|
|
312
|
-
</
|
|
312
|
+
</TabContent>
|
|
313
313
|
|
|
314
|
-
<
|
|
314
|
+
<TabContent order={3}>
|
|
315
315
|
|
|
316
316
|
Multiple authenticated users can participate in the same workflow-owned session. Include attribution when resuming the Hook:
|
|
317
317
|
|
|
@@ -337,9 +337,9 @@ export async function POST(
|
|
|
337
337
|
|
|
338
338
|
To preserve structured attribution across refreshes, persist the corresponding `UIMessage` using the application-history approach described above.
|
|
339
339
|
|
|
340
|
-
</
|
|
340
|
+
</TabContent>
|
|
341
341
|
|
|
342
|
-
</
|
|
342
|
+
</TabsWithChildren>
|
|
343
343
|
|
|
344
344
|
## Related documentation
|
|
345
345
|
|
|
@@ -189,7 +189,7 @@ export function BookingApproval({ toolCallId, input, output }: BookingApprovalPr
|
|
|
189
189
|
if (output) {
|
|
190
190
|
return (
|
|
191
191
|
<div className="border rounded-lg p-4">
|
|
192
|
-
<p className="text-sm text-
|
|
192
|
+
<p className="text-sm text-gray-900">{output}</p>
|
|
193
193
|
</div>
|
|
194
194
|
);
|
|
195
195
|
}
|
|
@@ -211,7 +211,7 @@ export function BookingApproval({ toolCallId, input, output }: BookingApprovalPr
|
|
|
211
211
|
<div className="border rounded-lg p-4 space-y-4">
|
|
212
212
|
<div className="space-y-2">
|
|
213
213
|
<p className="font-medium">Approve this booking?</p>
|
|
214
|
-
<div className="text-sm text-
|
|
214
|
+
<div className="text-sm text-gray-900">
|
|
215
215
|
{input && (
|
|
216
216
|
<div className="space-y-2">
|
|
217
217
|
<div>Flight: {input.flightNumber}</div>
|
package/docs/ai/index.mdx
CHANGED
|
@@ -59,9 +59,9 @@ cd workflow-examples/flight-booking-app
|
|
|
59
59
|
|
|
60
60
|
### Configure model access
|
|
61
61
|
|
|
62
|
-
<
|
|
62
|
+
<TabsWithChildren tabs={["AI Gateway","Provider package"]}>
|
|
63
63
|
|
|
64
|
-
<
|
|
64
|
+
<TabContent order={1}>
|
|
65
65
|
|
|
66
66
|
AI SDK uses [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) as its default global provider, so plain `"provider/model"` strings need no provider-specific package. Vercel deployments authenticate with OIDC automatically. For local development, link the project and pull a short-lived OIDC token:
|
|
67
67
|
|
|
@@ -72,9 +72,9 @@ vercel env pull .env.local
|
|
|
72
72
|
|
|
73
73
|
You can alternatively set `AI_GATEWAY_API_KEY` from the [AI Gateway authentication](https://vercel.com/docs/ai-gateway/authentication) page.
|
|
74
74
|
|
|
75
|
-
</
|
|
75
|
+
</TabContent>
|
|
76
76
|
|
|
77
|
-
<
|
|
77
|
+
<TabContent order={2}>
|
|
78
78
|
|
|
79
79
|
`WorkflowAgent` accepts any AI SDK provider. To use OpenAI, install its provider package:
|
|
80
80
|
|
|
@@ -98,9 +98,9 @@ const model = openai("gpt-5.6-sol");
|
|
|
98
98
|
|
|
99
99
|
See the [AI SDK provider guide](https://ai-sdk.dev/providers/ai-sdk-providers) for Anthropic, Google, Amazon Bedrock, and other providers.
|
|
100
100
|
|
|
101
|
-
</
|
|
101
|
+
</TabContent>
|
|
102
102
|
|
|
103
|
-
</
|
|
103
|
+
</TabsWithChildren>
|
|
104
104
|
</Step>
|
|
105
105
|
|
|
106
106
|
<Step>
|
|
@@ -111,9 +111,9 @@ Run the app with `npm run dev` and open [http://localhost:3000](http://localhost
|
|
|
111
111
|
|
|
112
112
|
The following sections break down the core code. You don't need to make changes yet.
|
|
113
113
|
|
|
114
|
-
<
|
|
114
|
+
<TabsWithChildren tabs={["API Route","Tools","Client"]}>
|
|
115
115
|
|
|
116
|
-
<
|
|
116
|
+
<TabContent order={1}>
|
|
117
117
|
|
|
118
118
|
Our API route calls [AI SDK's `ToolLoopAgent` class](https://ai-sdk.dev/docs/agents/overview), which encapsulates the LLM call, tool execution loop, and stopping conditions on top of [AI SDK's `streamText` function](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text#streamtext). This is also where we pass tools to the agent.
|
|
119
119
|
|
|
@@ -137,9 +137,9 @@ export async function POST(req: Request) {
|
|
|
137
137
|
}
|
|
138
138
|
```
|
|
139
139
|
|
|
140
|
-
</
|
|
140
|
+
</TabContent>
|
|
141
141
|
|
|
142
|
-
<
|
|
142
|
+
<TabContent order={2}>
|
|
143
143
|
|
|
144
144
|
Our tools are mostly mocked out for the sake of the example. We use AI SDK's `tool` function to define the tool, and pass it to the agent. In your own app, this might be any kind of tool call, like database queries, calls to external services, etc.
|
|
145
145
|
|
|
@@ -160,9 +160,9 @@ async function searchFlights({ from, to, date }: { from: string; to: string; dat
|
|
|
160
160
|
}
|
|
161
161
|
```
|
|
162
162
|
|
|
163
|
-
</
|
|
163
|
+
</TabContent>
|
|
164
164
|
|
|
165
|
-
<
|
|
165
|
+
<TabContent order={3}>
|
|
166
166
|
|
|
167
167
|
Our `ChatPage` component contains logic for displaying chat messages, but its core responsibility is managing input and output for the [`useChat` hook](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat#usechat) from AI SDK.
|
|
168
168
|
|
|
@@ -207,9 +207,9 @@ export default function ChatPage() {
|
|
|
207
207
|
}
|
|
208
208
|
```
|
|
209
209
|
|
|
210
|
-
</
|
|
210
|
+
</TabContent>
|
|
211
211
|
|
|
212
|
-
</
|
|
212
|
+
</TabsWithChildren>
|
|
213
213
|
|
|
214
214
|
</Step>
|
|
215
215
|
|
|
@@ -120,9 +120,9 @@ Update your chat component to detect and render the custom data parts. Data part
|
|
|
120
120
|
to: string; // [!code highlight]
|
|
121
121
|
}; // [!code highlight]
|
|
122
122
|
return ( // [!code highlight]
|
|
123
|
-
<div key={`${part.id}-${flight.flightNumber}`} className="p-3 bg-
|
|
123
|
+
<div key={`${part.id}-${flight.flightNumber}`} className="p-3 bg-gray-100 rounded-md"> // [!code highlight]
|
|
124
124
|
<div className="font-medium">{flight.airline} - {flight.flightNumber}</div> // [!code highlight]
|
|
125
|
-
<div className="text-
|
|
125
|
+
<div className="text-gray-900">{flight.from} → {flight.to}</div> // [!code highlight]
|
|
126
126
|
</div> // [!code highlight]
|
|
127
127
|
); // [!code highlight]
|
|
128
128
|
} // [!code highlight]
|
|
@@ -12,7 +12,9 @@ related:
|
|
|
12
12
|
|
|
13
13
|
Registers global workflow lifecycle handlers, invoked by the runtime on the compute that records a run's terminal transition. Use it for best-effort centralized reporting, such as forwarding failed runs to Sentry, without wrapping each workflow body.
|
|
14
14
|
|
|
15
|
-
Register
|
|
15
|
+
Register in the host process that executes workflows, before it handles requests. In **Next.js 16.3.0 and later**, use `instrumentation.ts` as below. Earlier Next.js versions can process a cold Vercel invocation before async registration finishes. See the [framework support table](/docs/observability/lifecycle-hooks#framework-support) for registration locations and a full Sentry example in the guide.
|
|
16
|
+
|
|
17
|
+
App startup registration does not reach the standalone workflow functions emitted on Vercel by Nuxt 4 / Nitro v2, Astro, Nest, or the CLI `vercel-build-output-api` target. Those targets do not yet support this registration pattern. In Nitro v3, use a static import and synchronous server-plugin registration; Nitro does not await async plugins. Do not register from a workflow file or a step function.
|
|
16
18
|
|
|
17
19
|
```typescript title="instrumentation.ts" lineNumbers
|
|
18
20
|
export async function register() {
|
|
@@ -36,6 +38,8 @@ export async function register() {
|
|
|
36
38
|
|
|
37
39
|
Keep the dynamic import inside the `NEXT_RUNTIME === "nodejs"` guard. Next.js also compiles `instrumentation.ts` for the Edge runtime. A top-level static import of `workflow/api` pulls Node.js-only dependencies into that compilation and breaks webpack Edge builds, even if the registration call is guarded.
|
|
38
40
|
|
|
41
|
+
Restart `next dev` after editing instrumentation handlers: Next.js memoizes registration per process, so edits may not take effect until restart. Other hot-reloading hosts can re-register in the same process; keep the unregister function in process-wide state across reloads, or restart the server.
|
|
42
|
+
|
|
39
43
|
## API Signature
|
|
40
44
|
|
|
41
45
|
### Parameters
|
|
@@ -55,6 +59,8 @@ Returns a function that unregisters these hooks. Registrations are not deduplica
|
|
|
55
59
|
|
|
56
60
|
Both handlers receive a `workflowName` string and a lazily hydrated [`Run`](/docs/api-reference/workflow-api/get-run) instance. Use the `workflowName` parameter to filter without a backend read; `run.runId` also requires no read. Accessors such as `run.workflowName`, `run.status`, and `run.returnValue` still fetch from the backend when used. In particular, `workflowName` is a string, while `run.workflowName` is a `Promise<string>`. Lazy access defers those reads rather than eliminating them.
|
|
57
61
|
|
|
62
|
+
Parameters come from the runtime's module copy, which may differ from the handler's copy in a bundled app. Avoid `instanceof` checks against `Run`, SDK errors, or your own bundled error classes. Use `WorkflowRunFailedError.is(error)` (`workflow/errors`), `FatalError.is(error.cause)` (`workflow`), `error.errorCode`, and the cause's `name` or your own serialized discriminator. See [identifying errors across module copies](/docs/observability/lifecycle-hooks#identifying-errors-across-module-copies) for an example.
|
|
63
|
+
|
|
58
64
|
### `onRunCompleted`
|
|
59
65
|
|
|
60
66
|
Invoked when a workflow run completes successfully.
|
|
@@ -74,14 +80,18 @@ Invoked when a workflow run fails terminally (after any retries).
|
|
|
74
80
|
| `params.workflowName` | `string` | The machine-readable workflow identifier, such as `workflow//./src/workflows/order//processOrder`. Available without a backend read. |
|
|
75
81
|
| `params.error` | `WorkflowRunFailedError` | The persisted failure hydrated for reporting: `error.errorCode` carries the classification (e.g. `USER_ERROR`) and `error.cause` is the hydrated thrown value. |
|
|
76
82
|
|
|
77
|
-
Unlike `run.returnValue`, `error.cause` defers readable stream I/O until consumption and revives abort signals as persisted snapshots without live subscriptions. Writable streams retain their normal forwarding
|
|
83
|
+
Unlike `run.returnValue`, `error.cause` defers readable stream I/O until consumption and revives abort signals as persisted snapshots without live subscriptions. Writable streams retain their normal forwarding setup, and writes still reach the failed run's stream or the parent run's stream for a forwarded writable. Custom serialization revives registered classes using the runtime's module copy; plain user-defined Error subclasses without custom serialization revive as generic errors with their name preserved. If hydration fails, the SDK logs the reason and the cause is a generic `Error`, matching `run.returnValue`'s fallback. In `onRunFailed`, `run.returnValue` rejects because the run failed. Use `error.cause` to inspect or report the thrown value instead.
|
|
84
|
+
|
|
85
|
+
On Vercel, the invocation's `waitUntil` scope drains background stream operations from **`error.cause`**, even after a handler returns or throws. It does not automatically cover pipes from `await run.returnValue` in `onRunCompleted`, or consumption scheduled after the handler returns. Await consumption and other reporting work in your handler. Other hosts may stop detached work when the process freezes or terminates.
|
|
78
86
|
|
|
79
|
-
|
|
87
|
+
<Callout type="warn">
|
|
88
|
+
A stream lock left open can keep the drain and lifecycle span pending until the function's maximum duration. Close or release reader and writer locks when finished; cancel a partially consumed reader in `finally`. See the [stream cleanup example](/docs/observability/lifecycle-hooks#stream-lifetime).
|
|
89
|
+
</Callout>
|
|
80
90
|
|
|
81
91
|
## Behavior
|
|
82
92
|
|
|
83
|
-
- Handlers run on the host (full Node.js), never inside the workflow VM. Calling `registerLifecycleHooks` from workflow code throws.
|
|
93
|
+
- Register at host startup. Handlers run on the host (full Node.js), never inside the workflow VM. Calling `registerLifecycleHooks` from workflow or step code throws.
|
|
84
94
|
- Handlers are fire-and-forget. They cannot delay or change the run's outcome, and the runtime logs and swallows a throwing handler. On Vercel, `waitUntil` keeps the invocation alive while handlers finish, subject to the invocation's duration limit. On other hosts, handlers run as detached work and may not complete if the host freezes or terminates the process after the response.
|
|
85
95
|
- Delivery is best effort. Each registered handler is invoked at most once by the invocation that writes the terminal event. Callbacks are not retried if they throw or the process dies, so they may never run or may stop before completing. The [event log](/docs/how-it-works/event-sourcing) is the system of record.
|
|
86
96
|
- Handlers fire only on the invocation that wrote the terminal event. Transitions recorded outside your app's compute (e.g. a run cancelled from the CLI or dashboard) do not fire handlers.
|
|
87
|
-
- You can register multiple hook sets, and handlers run in registration order.
|
|
97
|
+
- You can register multiple hook sets, and handlers run in registration order. Registrations are not deduplicated; unregister a previous hook set before registering it again in the same process.
|
|
@@ -10,7 +10,7 @@ related:
|
|
|
10
10
|
NestJS integration for Workflow SDK. The `WorkflowModule` builds the workflow bundles on application startup and registers the controller that serves the workflow runtime routes.
|
|
11
11
|
|
|
12
12
|
<Callout>
|
|
13
|
-
NestJS integration is
|
|
13
|
+
NestJS integration is in beta. Both `@nestjs/platform-express` and `@nestjs/platform-fastify` are supported, and deploying to Vercel goes through [`workflow-nest build --vercel`](/docs/getting-started/nestjs#deploy-to-vercel). The same exports are also available from the `@workflow/nest` package.
|
|
14
14
|
</Callout>
|
|
15
15
|
|
|
16
16
|
## Exports
|
|
@@ -25,6 +25,9 @@ NestJS integration is experimental and not yet supported for deployment to Verce
|
|
|
25
25
|
<Card title="WorkflowController" href="/docs/api-reference/workflow-nest/workflow-controller">
|
|
26
26
|
Controller that serves the workflow runtime routes under `.well-known/workflow/v1`
|
|
27
27
|
</Card>
|
|
28
|
+
<Card title="isWorkflowRequest()" href="/docs/api-reference/workflow-nest/is-workflow-request">
|
|
29
|
+
Recognises a workflow request in a guard, so queue deliveries and webhooks are not rejected by your own auth
|
|
30
|
+
</Card>
|
|
28
31
|
<Card title="configureWorkflowController()" href="/docs/api-reference/workflow-nest/configure-workflow-controller">
|
|
29
32
|
Points `WorkflowController` at the directory containing the generated workflow bundles
|
|
30
33
|
</Card>
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: isWorkflowRequest
|
|
3
|
+
description: Recognise a Workflow SDK request inside a NestJS guard or interceptor.
|
|
4
|
+
type: reference
|
|
5
|
+
summary: Let queue deliveries and webhooks past an application guard.
|
|
6
|
+
prerequisites:
|
|
7
|
+
- /docs/getting-started/nestjs
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
Returns `true` when NestJS routed the request an `ExecutionContext` is handling to [`WorkflowController`](/docs/api-reference/workflow-nest/workflow-controller), which serves the Workflow SDK's protocol routes under `.well-known/workflow/v1`. The check is on the selected controller rather than the URL, so an application route that can be reached through a URL containing `.well-known/workflow/v1` (a wildcard such as `files/*path`) is still treated as your route.
|
|
11
|
+
|
|
12
|
+
[`WorkflowController`](/docs/api-reference/workflow-nest/workflow-controller) is a controller inside your application, so a global guard runs for it too. A guard that rejects unauthenticated requests rejects every queue delivery and webhook with `403`, and runs stop making progress with no other symptom. Use this helper to exempt them.
|
|
13
|
+
|
|
14
|
+
The workflow routes authenticate their own callers — queue deliveries are signed and webhook tokens are single-use secrets — so letting them past an application guard exposes nothing.
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
{/* @skip-typecheck - NestJS decorators require special TypeScript config */}
|
|
19
|
+
|
|
20
|
+
```typescript title="src/auth.guard.ts" lineNumbers
|
|
21
|
+
import {
|
|
22
|
+
Injectable,
|
|
23
|
+
type CanActivate,
|
|
24
|
+
type ExecutionContext,
|
|
25
|
+
} from "@nestjs/common";
|
|
26
|
+
import { isWorkflowRequest } from "workflow/nest"; // [!code highlight]
|
|
27
|
+
|
|
28
|
+
@Injectable()
|
|
29
|
+
export class AuthGuard implements CanActivate {
|
|
30
|
+
canActivate(context: ExecutionContext) {
|
|
31
|
+
if (isWorkflowRequest(context)) return true; // [!code highlight]
|
|
32
|
+
return this.authenticate(context);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## API signature
|
|
38
|
+
|
|
39
|
+
### Parameters
|
|
40
|
+
|
|
41
|
+
| Parameter | Type | Description |
|
|
42
|
+
| --- | --- | --- |
|
|
43
|
+
| `context` | `ExecutionContext` | The execution context NestJS passes to a guard or interceptor. |
|
|
44
|
+
|
|
45
|
+
### Returns
|
|
46
|
+
|
|
47
|
+
`boolean`. `false` for a request to any other route, and for non-HTTP execution contexts (RPC, WebSockets), where there is no workflow route to match.
|
|
48
|
+
|
|
49
|
+
## Related exports
|
|
50
|
+
|
|
51
|
+
| Export | Description |
|
|
52
|
+
| --- | --- |
|
|
53
|
+
| `isWorkflowRoutePath(path, globalPrefix?)` | Whether a raw URL or path addresses a workflow route, for middleware that has a request rather than an `ExecutionContext`. The match is anchored to `globalPrefix` (default `''`), so pass the prefix given to `app.setGlobalPrefix()` unless it excludes the workflow routes. |
|
|
54
|
+
| `WORKFLOW_ROUTE_PREFIX` | `'.well-known/workflow/v1'`, the path the controller is mounted at. |
|
|
55
|
+
|
|
56
|
+
<Callout type="info">
|
|
57
|
+
Interceptors and exception filters need no exemption. The workflow handlers write through `@Res()`, so the exact status and body the workflow runtime produced reach the caller, which is what the queue and third-party webhook senders key off.
|
|
58
|
+
</Callout>
|
|
@@ -9,9 +9,13 @@ prerequisites:
|
|
|
9
9
|
|
|
10
10
|
NestJS controller that handles the well-known workflow endpoints under `.well-known/workflow/v1`. It dynamically imports the generated workflow bundles and converts between Express/Fastify requests and the Web API `Request`/`Response` objects the workflow runtime expects. Both the Express and Fastify HTTP adapters are supported.
|
|
11
11
|
|
|
12
|
-
The conversion preserves bytes in both directions
|
|
12
|
+
The conversion preserves bytes in both directions. [`WorkflowModule`](/docs/api-reference/workflow-nest/workflow-module) keeps the application's body parsers off these routes, so the request body is normally read straight from the stream; a `req.rawBody` left by `{ rawBody: true }`, or a `Buffer`/string body left by a parser, is used when one is present. Responses are written as bytes, and every `set-cookie` value is kept. See [Request bodies and body parsers](/docs/getting-started/nestjs#request-bodies-and-body-parsers).
|
|
13
13
|
|
|
14
|
-
Handlers take `@Res()
|
|
14
|
+
Handlers take `@Res()` and write the response themselves, so an interceptor or exception filter cannot reshape it. That is deliberate: the queue and third-party webhook senders key off the exact status and body the workflow runtime produces.
|
|
15
|
+
|
|
16
|
+
Guards do run, because NestJS runs them before the handler. A global guard that rejects unauthenticated requests rejects queue deliveries too; see [`isWorkflowRequest`](/docs/api-reference/workflow-nest/is-workflow-request).
|
|
17
|
+
|
|
18
|
+
The controller is registered as `VERSION_NEUTRAL`, so `app.enableVersioning()` does not move these routes away from the paths the SDK generates URLs for. A global prefix does apply, and `WorkflowModule` adopts it automatically.
|
|
15
19
|
|
|
16
20
|
[`WorkflowModule.forRoot()`](/docs/api-reference/workflow-nest/workflow-module) registers this controller automatically. You only register it yourself if you are not using `WorkflowModule`.
|
|
17
21
|
|
|
@@ -86,6 +86,7 @@ Extends [`NestBuilderOptions`](/docs/api-reference/workflow-nest/nest-local-buil
|
|
|
86
86
|
| `basePath` | `string` | adopted from `app.setGlobalPrefix()` | Route prefix the workflow endpoints are served under, applied to generated callback and webhook URLs. Set it when a reverse proxy mounts the app on a sub-path NestJS cannot see. |
|
|
87
87
|
| `manageWorldLifecycle` | `boolean` | `false` | Start the target World's background workers with the app and close them on shutdown. Required for self-hosted Worlds, which otherwise never pick up runs. |
|
|
88
88
|
| `preloadBundles` | `boolean` | `false` when `VERCEL` is set, else `true` | Load the generated bundles during startup instead of on the first request. On Vercel, dedicated functions serve the bundles, so there is nothing to preload. |
|
|
89
|
+
| `bypassBodyParser` | `boolean` | `true` | Keep the application's body parsers away from `.well-known/workflow/v1`, so queue deliveries are not rejected by Express's 100 KB limit and signed webhook bodies stay byte-exact. The application's own routes are untouched. On Fastify, where the body limit is enforced per instance rather than per route, nothing is patched and a limit low enough to reject deliveries is reported at startup instead. |
|
|
89
90
|
| `workingDir` | `string` | `process.cwd()` | Working directory for the NestJS application. |
|
|
90
91
|
| `dirs` | `string[]` | `['src']` | Directories to scan for workflow files. |
|
|
91
92
|
| `outDir` | `string` | `'.nestjs/workflow'` (relative to `workingDir`) | Output directory for generated workflow bundles. |
|
|
@@ -126,9 +127,16 @@ The older `WORKFLOW_OPTIONS` token resolves to the same value and is kept for co
|
|
|
126
127
|
|
|
127
128
|
| Hook | Behaviour |
|
|
128
129
|
| --- | --- |
|
|
129
|
-
| `onModuleInit` |
|
|
130
|
+
| `onModuleInit` | Takes the application's body parsers off the workflow routes (unless `bypassBodyParser` is `false`), reconciles the base path against `app.setGlobalPrefix()`, builds the bundles (or verifies they exist when `skipBuild` is set), optionally starts the World, and preloads the bundles. |
|
|
130
131
|
| `onApplicationShutdown` | Closes the World when `manageWorldLifecycle` is set. Call `app.enableShutdownHooks()` so this runs on a signal. |
|
|
131
132
|
|
|
133
|
+
<Callout type="warn">
|
|
134
|
+
`WorkflowModule` reads NestJS's global prefix and HTTP adapter through the
|
|
135
|
+
injector, which only works while a single copy of `@nestjs/core` is installed.
|
|
136
|
+
With two copies the injection tokens differ, prefix handling and the
|
|
137
|
+
body-parser bypass both stop working, and a warning is logged at startup.
|
|
138
|
+
</Callout>
|
|
139
|
+
|
|
132
140
|
<Callout type="warn">
|
|
133
141
|
Workflows and steps run outside the NestJS injector, so providers cannot be injected into `"use workflow"` or `"use step"` code. See [NestJS dependency injection is not available in workflows and steps](/docs/getting-started/nestjs#nestjs-dependency-injection-is-not-available-in-workflows-and-steps).
|
|
134
142
|
</Callout>
|
|
@@ -33,7 +33,7 @@ const parsed = parseStepName("step//./src/workflows/order//processPayment"); //
|
|
|
33
33
|
|
|
34
34
|
| Property | Description |
|
|
35
35
|
|----------|-------------|
|
|
36
|
-
| `shortName` | The display name: the last segment of the function name. For nested steps like `processOrder/chargeCard`, this is `"chargeCard"`. |
|
|
36
|
+
| `shortName` | The display name: the last segment of the function name. For nested steps like `processOrder/chargeCard`, this is `"chargeCard"`. When same-named nested steps require disambiguation, the generated `~N` suffix is preserved (for example, `"chargeCard~1"`). |
|
|
37
37
|
| `moduleSpecifier` | The module the step is defined in: a relative path (`./src/workflows/order`) or a package specifier (`@myorg/tasks@2.0.0`). |
|
|
38
38
|
| `functionName` | The full function name including nesting (e.g. `processOrder/chargeCard`). |
|
|
39
39
|
|
|
@@ -62,11 +62,11 @@ The contract:
|
|
|
62
62
|
|
|
63
63
|
## The runtime integration (suspension fan-out fold)
|
|
64
64
|
|
|
65
|
-
**On by default.** The suspension handler folds a **clean fan-out** (the suspension's eager `step_created` and `wait_created` writes) into `createBatch` calls of at most
|
|
65
|
+
**On by default.** The suspension handler folds a **clean fan-out** (the suspension's eager `step_created` and `wait_created` writes) into `createBatch` calls of at most 16 events. The server's transaction budgets allow more; 16 is a latency choice (see **Per-chunk continuation**). Chunks of a larger fan-out commit **concurrently**: slot assignment is the World's, so parallel chunks race for slot ranges exactly like the pre-fold path's parallel single writes did, and per-entity conditions, not commit order, carry correctness. The fold only engages when the World implements `createBatch`, the run is on slot identity, and the suspension carries no attribute writes and no resilient step dispatch; everything else keeps the single-event path byte-for-byte. A suspension that also creates or disposes hooks still folds: hook writes are not batchable, so they go through the single-event path **concurrently** with the fold rather than ahead of it.
|
|
66
66
|
|
|
67
|
-
**Per-chunk continuation.** Each chunk's follow-on work starts the moment **that chunk** commits, not when the whole fold does: a chunk's step-execution queue messages publish right off its own commit (publish-after-create holds per step), and only the chunk carrying the inline pairs gates the replay's continuation: trailing chunks' commits and publishes are joined before the invocation can acknowledge its message, so the durability contract ("every create durable before ack") is unchanged.
|
|
67
|
+
**Per-chunk continuation.** Each chunk's follow-on work starts the moment **that chunk** commits, not when the whole fold does: a chunk's step-execution queue messages publish right off its own commit (publish-after-create holds per step), and only the chunk carrying the inline pairs gates the replay's continuation: trailing chunks' commits and publishes are joined before the invocation can acknowledge its message, so the durability contract ("every create durable before ack") is unchanged. A queued step's message therefore waits on two hops in series, its chunk's commit and then its chunk's batched publish, and both grow with the chunk's size, so smaller chunks start a wide fan-out's queued branches sooner. More chunks also means more concurrent batch writes per run, and from about 16 of them the pair chunk, and with it the first inline branch, slows down. The 16-event cap is where production measurements balanced the two: on 64- and 128-branch fan-outs the last branch started about 90 to 200 ms sooner than at 32 events, with no first-branch cost at those widths.
|
|
68
68
|
|
|
69
|
-
**Pre-claimed inline pairs.** When the fold engages with at least two inline steps, the steps the runtime is about to execute inline join the batch as adjacent `[step_created, step_started]` pairs: the created row carrying the input, the started row a bare ownership-stamped claim the World folds into a born-running create. The pairs commit in a chunk of their own, ahead of the plain `step_created` and `wait_created` chunks, so the write the inline bodies wait for carries only two rows per inline step (a small transaction that commits faster than a full
|
|
69
|
+
**Pre-claimed inline pairs.** When the fold engages with at least two inline steps, the steps the runtime is about to execute inline join the batch as adjacent `[step_created, step_started]` pairs: the created row carrying the input, the started row a bare ownership-stamped claim the World folds into a born-running create. The pairs commit in a chunk of their own, ahead of the plain `step_created` and `wait_created` chunks, so the write the inline bodies wait for carries only two rows per inline step (a small transaction that commits faster than a full 16-event chunk) while the plain creates commit concurrently beside it. The inline bodies start straight off the pair chunk's commit (in parallel with the queue publishes and the sibling chunks) with no per-step claim POST at all, and a pair that loses its atomic create-claim to a concurrent delivery skips its body exactly as a lost lazy claim does. A lone inline step keeps the optimistic lazy-start path (one row, whose claim overlaps the body) even when eager creates batch beside it: the pairs share no round trip with those creates, so only two or more inline steps make a pair chunk worth the trade. The exception is a lone inline step in a suspension that creates a hook: the runtime never starts a body before its claim settles while a hook is being created, and a lazy claim could only be sent after the hook write committed, so the step's pair is folded instead and its claim commits concurrently with the hook write. A plain partition of exactly one `step_created` or `wait_created` beside the pairs is written through the ordinary single path rather than a one-row batch, and its queue message still waits for that write.
|
|
70
70
|
|
|
71
71
|
Per-event `409`s are tolerated the same way the single path tolerates `EntityConflictError` (a concurrent delivery already created the entity); any other per-event failure fails the suspension write the way a single-path rejection would. A batch carrying a `step_started` (that is, any batch with inline pairs) is **not** retried in-process on a transport blip: a pair's `409` cannot be told apart from the caller's own earlier attempt having committed it, so recovery goes through queue redelivery instead, where the step's ownership stamp routes it back to the same invocation.
|
|
72
72
|
|
|
@@ -126,6 +126,12 @@ Configure Workflow through `WorkflowModule.forRoot()`.
|
|
|
126
126
|
- Default: `false`
|
|
127
127
|
- Skips bundle generation when bundles are already pre-built.
|
|
128
128
|
|
|
129
|
+
### `bypassBodyParser`
|
|
130
|
+
|
|
131
|
+
- Environment override: none
|
|
132
|
+
- Default: `true`
|
|
133
|
+
- Keeps the application's body parsers away from `.well-known/workflow/v1`, so queue deliveries are not rejected by Express's 100 KB limit and signed webhook bodies stay byte-exact. Other routes are untouched. On Fastify, where the body limit is enforced per instance rather than per route, nothing is patched and a limit low enough to reject deliveries is reported at startup instead.
|
|
134
|
+
|
|
129
135
|
## Astro
|
|
130
136
|
|
|
131
137
|
### `sourcemap`
|
|
@@ -239,14 +239,15 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
239
239
|
|
|
240
240
|
### `WORKFLOW_SNAPSHOT_THRESHOLD`
|
|
241
241
|
|
|
242
|
-
- Default: `
|
|
243
|
-
- Values: non-negative integer
|
|
242
|
+
- Default: `1000` when the QuickJS engine is selected
|
|
243
|
+
- Values: non-negative integer. `0` disables snapshotting.
|
|
244
244
|
- Experimental. Only used by the QuickJS engine (`WORKFLOW_VM=quickjs`), and only with a World that provides snapshot storage (world-local, world-postgres, and world-vercel do).
|
|
245
|
-
- When
|
|
245
|
+
- When above `0`, the runtime persists a **VM-memory snapshot** at a suspension once at least this many events have been processed since the last snapshot. Subsequent invocations restore the VM from the snapshot and replay only the events recorded since, instead of re-executing the workflow from the top against the full event log.
|
|
246
246
|
- Short-lived runs below the threshold never pay the snapshot cost; long-running or unbounded runs stop scaling their resume cost with total event-log length. `1` snapshots at every qualifying suspension.
|
|
247
247
|
- Choosing a value: a restore costs roughly the same regardless of log length (tens of milliseconds to decompress and restore the heap, plus fetching the snapshot), while a full replay grows with the log (tens of milliseconds at a few hundred events, seconds at several thousand). Restoring starts to pay off at a few hundred events, so values in the hundreds suit most long-running workflows. Very low values mostly add snapshot saves to runs that replay quickly anyway.
|
|
248
248
|
- Snapshots are an optimization, not a source of truth: the event log remains authoritative, and a missing, corrupt, oversized, or incompatible snapshot automatically falls back to a full replay. Snapshots over 32 MB uncompressed are not saved.
|
|
249
|
-
-
|
|
249
|
+
- Set `0` to opt out and always replay the full event log.
|
|
250
|
+
- Like `WORKFLOW_VM`, an explicitly set policy is stamped into the run's `executionContext` at start, so a run keeps the snapshot policy it started with. Runs without a stamped policy use the handler's value, or the default. `start()` rejects an invalid value. An invalid value on the workflow handler disables snapshotting with a warning.
|
|
250
251
|
- A snapshot can only be restored by the exact QuickJS engine build that captured it. On Vercel, runs keep executing on the deployment they started on, so deploys don't affect in-flight snapshots. If your deployment serves in-flight runs from new code (for example, a self-hosted rolling update), an upgrade that changes the embedded engine makes every in-flight run fall back to a full replay at its next resume, all at once, before re-snapshotting at its next qualifying suspension. Plan for that one-time replay load when upgrading.
|
|
251
252
|
|
|
252
253
|
What a snapshot contains, and how it is protected:
|
|
@@ -284,6 +285,7 @@ What a snapshot contains, and how it is protected:
|
|
|
284
285
|
- Default: automatic
|
|
285
286
|
- Forces the write-side codec to `zstd` or `gzip`.
|
|
286
287
|
- Invalid values are ignored. Automatic mode prefers `zstd` when the current Node.js runtime supports it, otherwise it falls back to `gzip`.
|
|
288
|
+
- Writes for a run on another deployment (for example `resumeHook()` reaching a run that started before the project moved to a newer Node.js version) use `zstd` only when that run's deployment runs Node.js 22.15+ (or 23.8+), and `gzip` otherwise, since older Node.js versions cannot decode `zstd`. Runs created before `@workflow/core` recorded the Node.js version always receive `gzip`. Setting this to `zstd` does not override that check.
|
|
287
289
|
|
|
288
290
|
### `WORKFLOW_TRACE_MODE`
|
|
289
291
|
|
|
@@ -315,7 +317,7 @@ What a snapshot contains, and how it is protected:
|
|
|
315
317
|
|
|
316
318
|
Node's own modules do less than the client they replace, so enabling this drops the per-call-site tuning the Worlds configure:
|
|
317
319
|
|
|
318
|
-
- Event-log requests lose HTTP/2, so concurrent reads and writes no longer share one connection, and the enlarged HTTP/2 receive windows no longer apply. This is the largest difference, and it slows down replays that read a big event log. It does not apply to event writes on the
|
|
320
|
+
- Event-log requests lose HTTP/2, so concurrent reads and writes no longer share one connection, and the enlarged HTTP/2 receive windows no longer apply. This is the largest difference, and it slows down replays that read a big event log. It does not apply to event writes on the [WebSocket events transport](/docs/configuration/worlds#workflow_events_transport), which is the default and takes neither transport.
|
|
319
321
|
- Requests lose their transport-level retry. Failures still surface to the layers above, which retry event writes and redeliver queue messages, so nothing is silently dropped, but a failure that a same-connection retry would have hidden now costs a full redelivery.
|
|
320
322
|
- Stream close loses its retry of retriable server errors. A transient failure at close can leave a stream marked closing until the run expires, where it would previously have resolved on the retry.
|
|
321
323
|
|
|
@@ -293,9 +293,12 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
|
|
|
293
293
|
|
|
294
294
|
- Factory option: none
|
|
295
295
|
- CLI flag: none
|
|
296
|
-
- Default: `
|
|
297
|
-
-
|
|
298
|
-
-
|
|
296
|
+
- Default: `ws`
|
|
297
|
+
- Stream writes upgrade to a WebSocket (`workflow-stream-ws/v1`). Set to `http` (case-insensitive, surrounding whitespace ignored) to opt out; any other value, including unset, empty, or `ws`, uses the WebSocket. Stream reads always use HTTP.
|
|
298
|
+
- A writer's first two write groups go over HTTP, and the socket opens in the background after that, so no write waits for the upgrade. The server accepts or declines each upgrade; a declined or failed upgrade leaves that writer on HTTP for its lifetime.
|
|
299
|
+
- Ignored when the World is configured with `projectConfig` and routes through the `api-workflow` proxy, which does not forward a WebSocket upgrade, so stream writes stay on HTTP.
|
|
300
|
+
- The server pings idle sockets to keep them open, and the client must answer. The `ws` library the Vercel World uses does so automatically.
|
|
301
|
+
- Each WebSocket message is at most `WORKFLOW_WS_MAX_MESSAGE_BYTES`. Larger write groups are sent as several ordered requests, and a single chunk too large for one message is written over HTTP.
|
|
299
302
|
- A throttled (429) socket write or close is retried after the server's `Retry-After`, as over HTTP. It moves to HTTP if the connection ends during the wait or the cumulative wait passes 30 seconds.
|
|
300
303
|
|
|
301
304
|
### `WORKFLOW_DISABLE_ANALYTICS_READS`
|
|
@@ -311,14 +314,14 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
|
|
|
311
314
|
- Default: on
|
|
312
315
|
- Set to `0` (or `false`) to **disable** batched event writes, the escape hatch that restores the exact prior one-write-per-event path.
|
|
313
316
|
|
|
314
|
-
When enabled (the default), a suspension's eager `step_created` and `wait_created` writes fold into batched `events.createBatch` calls (one durable write with per-event outcomes) on Worlds that implement the optional batch API. The fold only engages when the World implements `events.createBatch` (the Vercel World does; Local and Postgres do not), the run's spec version supports slot identity (≥ 6), and the suspension carries no attribute writes or resilient step dispatch. Hook writes in the same suspension go through the single-event path concurrently with the batch. Everything else keeps the single-event path unchanged, so disabling is only needed as an operational escape hatch. Batches are capped at
|
|
317
|
+
When enabled (the default), a suspension's eager `step_created` and `wait_created` writes fold into batched `events.createBatch` calls (one durable write with per-event outcomes) on Worlds that implement the optional batch API. The fold only engages when the World implements `events.createBatch` (the Vercel World does; Local and Postgres do not), the run's spec version supports slot identity (≥ 6), and the suspension carries no attribute writes or resilient step dispatch. Hook writes in the same suspension go through the single-event path concurrently with the batch. Everything else keeps the single-event path unchanged, so disabling is only needed as an operational escape hatch. Batches are capped at 16 events; larger fan-outs commit in several batches at once. See the [batched event writes changelog](/docs/changelog/batched-event-writes) for the World API contract.
|
|
315
318
|
|
|
316
319
|
### `WORKFLOW_EVENTS_TRANSPORT`
|
|
317
320
|
|
|
318
321
|
- Factory option: none
|
|
319
322
|
- CLI flag: none
|
|
320
|
-
- Default: `
|
|
321
|
-
-
|
|
323
|
+
- Default: `ws`
|
|
324
|
+
- Ships workflow run events to the Vercel World over a WebSocket instead of one HTTP request each. Set to exactly `http` to opt out; any other value, including unset or empty, uses the WebSocket.
|
|
322
325
|
- Ignored when the World is configured with `projectConfig` and routes through the `api-workflow` proxy: that endpoint is an HTTP-only REST gateway and does not forward a WebSocket upgrade, so events stay on HTTP.
|
|
323
326
|
|
|
324
327
|
### `WORKFLOW_EVENTS_TRANSPORT_WS_OVERRIDE_WORKFLOWS`
|
|
@@ -326,8 +329,8 @@ When enabled (the default), a suspension's eager `step_created` and `wait_create
|
|
|
326
329
|
- Factory option: none
|
|
327
330
|
- CLI flag: none
|
|
328
331
|
- Default: none
|
|
329
|
-
- Comma-separated workflows whose runs use the WebSocket events transport even when `WORKFLOW_EVENTS_TRANSPORT` is `http
|
|
330
|
-
- Has no effect
|
|
332
|
+
- Comma-separated workflows whose runs use the WebSocket events transport even when `WORKFLOW_EVENTS_TRANSPORT` is `http`. Each entry is a function name (`processOrder`) or a full workflow name (`workflow//./src/workflows/order//processOrder`), matched exactly and case-sensitively.
|
|
333
|
+
- Has no effect unless `WORKFLOW_EVENTS_TRANSPORT=http`, since every workflow already uses the WebSocket by default.
|
|
331
334
|
- See [`WORKFLOW_EVENTS_TRANSPORT_WS_OVERRIDE_WORKFLOWS`](/worlds/vercel#workflow_events_transport_ws_override_workflows) for details.
|
|
332
335
|
|
|
333
336
|
### `WORKFLOW_WS_MAX_MESSAGE_BYTES`
|
|
@@ -41,9 +41,9 @@ One workflow run represents one full conversation. The workflow suspends between
|
|
|
41
41
|
Because the conversation is one workflow run, it stays on the deployment that started it. If each turn should run on the latest deployment while preserving selected state or streams, see [Versioning](/docs/foundations/versioning) for the child-run continuation pattern.
|
|
42
42
|
</Callout>
|
|
43
43
|
|
|
44
|
-
<
|
|
44
|
+
<TabsWithChildren tabs={["Workflow","API Route","Client"]}>
|
|
45
45
|
|
|
46
|
-
<
|
|
46
|
+
<TabContent order={1}>
|
|
47
47
|
|
|
48
48
|
```typescript title="workflows/support.ts" lineNumbers
|
|
49
49
|
import { streamText, stepCountIs } from "ai";
|
|
@@ -129,9 +129,9 @@ export async function supportWorkflow(initialMessages: ModelMessage[]) {
|
|
|
129
129
|
}
|
|
130
130
|
```
|
|
131
131
|
|
|
132
|
-
</
|
|
132
|
+
</TabContent>
|
|
133
133
|
|
|
134
|
-
<
|
|
134
|
+
<TabContent order={2}>
|
|
135
135
|
|
|
136
136
|
One endpoint handles first turn, follow-ups, and the `/done` exit. The client sends `runId` in the body to distinguish first vs follow-up.
|
|
137
137
|
|
|
@@ -246,9 +246,9 @@ export async function POST(req: Request) {
|
|
|
246
246
|
}
|
|
247
247
|
```
|
|
248
248
|
|
|
249
|
-
</
|
|
249
|
+
</TabContent>
|
|
250
250
|
|
|
251
|
-
<
|
|
251
|
+
<TabContent order={3}>
|
|
252
252
|
|
|
253
253
|
Store the `runId` in a ref and pass it in the body of every follow-up. `WorkflowChatTransport` forwards it for you.
|
|
254
254
|
|
|
@@ -299,9 +299,9 @@ export function SupportChat() {
|
|
|
299
299
|
}
|
|
300
300
|
```
|
|
301
301
|
|
|
302
|
-
</
|
|
302
|
+
</TabContent>
|
|
303
303
|
|
|
304
|
-
</
|
|
304
|
+
</TabsWithChildren>
|
|
305
305
|
|
|
306
306
|
## How it works
|
|
307
307
|
|