workflow 5.3.0 → 5.5.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.
Files changed (60) hide show
  1. package/dist/observability.d.ts +1 -1
  2. package/dist/observability.d.ts.map +1 -1
  3. package/dist/observability.js +2 -2
  4. package/docs/ai/chat-session-modeling.mdx +1 -1
  5. package/docs/ai/resumable-streams.mdx +1 -1
  6. package/docs/api-reference/workflow/create-hook.mdx +3 -3
  7. package/docs/api-reference/workflow/create-webhook.mdx +1 -1
  8. package/docs/api-reference/workflow/fetch.mdx +1 -5
  9. package/docs/api-reference/workflow/get-step-metadata.mdx +19 -0
  10. package/docs/api-reference/workflow-ai/durable-agent.mdx +2 -1
  11. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +4 -4
  12. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +2 -2
  13. package/docs/api-reference/workflow-api/resume-hook.mdx +2 -2
  14. package/docs/api-reference/workflow-api/start.mdx +12 -8
  15. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +2 -2
  16. package/docs/api-reference/workflow-errors/index.mdx +1 -1
  17. package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +1 -1
  18. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +1 -1
  19. package/docs/api-reference/workflow-errors/workflow-start-error.mdx +5 -5
  20. package/docs/api-reference/workflow-next/with-workflow.mdx +57 -0
  21. package/docs/api-reference/workflow-observability/create-state-resolver.mdx +56 -0
  22. package/docs/api-reference/workflow-observability/index.mdx +5 -0
  23. package/docs/api-reference/workflow-observability/meta.json +1 -0
  24. package/docs/api-reference/workflow-runtime/world/storage.mdx +2 -3
  25. package/docs/changelog/attributes-mvp.mdx +1 -1
  26. package/docs/changelog/batched-event-writes.mdx +0 -2
  27. package/docs/changelog/eager-processing.mdx +3 -1
  28. package/docs/changelog/lazy-event-creation.md +1 -1
  29. package/docs/changelog/spec-9.mdx +268 -120
  30. package/docs/changelog/step-message-ownership.mdx +2 -7
  31. package/docs/configuration/build-and-diagnostics.mdx +2 -0
  32. package/docs/configuration/cli-and-web-ui.mdx +13 -2
  33. package/docs/configuration/framework-options.mdx +7 -0
  34. package/docs/configuration/runtime-tuning.mdx +26 -74
  35. package/docs/configuration/worlds.mdx +55 -23
  36. package/docs/cookbook/advanced/child-workflows.mdx +126 -186
  37. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +1 -1
  38. package/docs/cookbook/common-patterns/idempotency.mdx +2 -2
  39. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +1 -1
  40. package/docs/cookbook/common-patterns/workflow-composition.mdx +5 -5
  41. package/docs/cookbook/integrations/ai-sdk.mdx +2 -2
  42. package/docs/errors/corrupted-event-log.mdx +1 -1
  43. package/docs/errors/fetch-in-workflow.mdx +15 -35
  44. package/docs/errors/hook-force-claimed.mdx +1 -1
  45. package/docs/errors/runtime-decryption-failed.mdx +1 -1
  46. package/docs/foundations/errors-and-retries.mdx +3 -1
  47. package/docs/foundations/hooks.mdx +1 -1
  48. package/docs/foundations/idempotency.mdx +11 -11
  49. package/docs/foundations/serialization.mdx +80 -0
  50. package/docs/foundations/starting-workflows.mdx +3 -7
  51. package/docs/getting-started/next.mdx +2 -0
  52. package/docs/how-it-works/event-sourcing.mdx +2 -2
  53. package/docs/observability/index.mdx +2 -0
  54. package/docs/whats-new.mdx +4 -4
  55. package/docs/worlds/building-a-world.mdx +22 -7
  56. package/docs/worlds/local.mdx +11 -7
  57. package/docs/worlds/postgres.mdx +17 -24
  58. package/docs/worlds/upgrading-to-v5.mdx +3 -3
  59. package/docs/worlds/vercel.mdx +13 -12
  60. package/package.json +14 -14
@@ -15,6 +15,6 @@
15
15
  * // hydrated.input and hydrated.output are now plain JS objects
16
16
  * ```
17
17
  */
18
- export { hydrateData, hydrateResourceIO, observabilityRevivers, type Revivers, } from '@workflow/core/serialization-format';
18
+ export { createStateResolver, hydrateData, hydrateResourceIO, observabilityRevivers, type Revivers, type StateResolver, stateSourceId, } from '@workflow/core/serialization-format';
19
19
  export { parseClassName, parseStepName, parseWorkflowName, } from '@workflow/utils';
20
20
  //# sourceMappingURL=observability.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../src/observability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,qBAAqB,EACrB,KAAK,QAAQ,GACd,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EACL,cAAc,EACd,aAAa,EACb,iBAAiB,GAClB,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../src/observability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,qBAAqB,EACrB,KAAK,QAAQ,EACb,KAAK,aAAa,EAClB,aAAa,GACd,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EACL,cAAc,EACd,aAAa,EACb,iBAAiB,GAClB,MAAM,iBAAiB,CAAC"}
@@ -15,6 +15,6 @@
15
15
  * // hydrated.input and hydrated.output are now plain JS objects
16
16
  * ```
17
17
  */
18
- export { hydrateData, hydrateResourceIO, observabilityRevivers, } from '@workflow/core/serialization-format';
18
+ export { createStateResolver, hydrateData, hydrateResourceIO, observabilityRevivers, stateSourceId, } from '@workflow/core/serialization-format';
19
19
  export { parseClassName, parseStepName, parseWorkflowName, } from '@workflow/utils';
20
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJpbGl0eS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9vYnNlcnZhYmlsaXR5LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7O0dBZ0JHO0FBQ0gsT0FBTyxFQUNMLFdBQVcsRUFDWCxpQkFBaUIsRUFDakIscUJBQXFCLEdBRXRCLE1BQU0scUNBQXFDLENBQUM7QUFFN0MsT0FBTyxFQUNMLGNBQWMsRUFDZCxhQUFhLEVBQ2IsaUJBQWlCLEdBQ2xCLE1BQU0saUJBQWlCLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIE9ic2VydmFiaWxpdHkgdXRpbGl0aWVzIGZvciBoeWRyYXRpbmcgc2VyaWFsaXplZCB3b3JrZmxvdyBkYXRhLlxuICpcbiAqIFVzZSB0aGVzZSB3aGVuIGluc3BlY3Rpbmcgd29ya2Zsb3cgc3RlcCBJL08sIHJ1biBpbnB1dHMvb3V0cHV0cyxcbiAqIG9yIGV2ZW50IGRhdGEgZnJvbSB0aGUgV29ya2Zsb3cgU0RLJ3Mgd29ybGQgQVBJcy5cbiAqXG4gKiBAZXhhbXBsZVxuICogYGBgdHNcbiAqIGltcG9ydCB7IGdldFdvcmxkIH0gZnJvbSAnd29ya2Zsb3cvcnVudGltZSc7XG4gKiBpbXBvcnQgeyBoeWRyYXRlUmVzb3VyY2VJTywgb2JzZXJ2YWJpbGl0eVJldml2ZXJzIH0gZnJvbSAnd29ya2Zsb3cvb2JzZXJ2YWJpbGl0eSc7XG4gKlxuICogY29uc3Qgd29ybGQgPSBhd2FpdCBnZXRXb3JsZCgpO1xuICogY29uc3Qgc3RlcCA9IGF3YWl0IHdvcmxkLnN0ZXBzLmdldChydW5JZCwgc3RlcElkLCB7IHJlc29sdmVEYXRhOiAnYWxsJyB9KTtcbiAqIGNvbnN0IGh5ZHJhdGVkID0gaHlkcmF0ZVJlc291cmNlSU8oc3RlcCwgb2JzZXJ2YWJpbGl0eVJldml2ZXJzKTtcbiAqIC8vIGh5ZHJhdGVkLmlucHV0IGFuZCBoeWRyYXRlZC5vdXRwdXQgYXJlIG5vdyBwbGFpbiBKUyBvYmplY3RzXG4gKiBgYGBcbiAqL1xuZXhwb3J0IHtcbiAgaHlkcmF0ZURhdGEsXG4gIGh5ZHJhdGVSZXNvdXJjZUlPLFxuICBvYnNlcnZhYmlsaXR5UmV2aXZlcnMsXG4gIHR5cGUgUmV2aXZlcnMsXG59IGZyb20gJ0B3b3JrZmxvdy9jb3JlL3NlcmlhbGl6YXRpb24tZm9ybWF0JztcblxuZXhwb3J0IHtcbiAgcGFyc2VDbGFzc05hbWUsXG4gIHBhcnNlU3RlcE5hbWUsXG4gIHBhcnNlV29ya2Zsb3dOYW1lLFxufSBmcm9tICdAd29ya2Zsb3cvdXRpbHMnO1xuIl19
20
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJpbGl0eS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9vYnNlcnZhYmlsaXR5LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7Ozs7Ozs7O0dBZ0JHO0FBQ0gsT0FBTyxFQUNMLG1CQUFtQixFQUNuQixXQUFXLEVBQ1gsaUJBQWlCLEVBQ2pCLHFCQUFxQixFQUdyQixhQUFhLEdBQ2QsTUFBTSxxQ0FBcUMsQ0FBQztBQUU3QyxPQUFPLEVBQ0wsY0FBYyxFQUNkLGFBQWEsRUFDYixpQkFBaUIsR0FDbEIsTUFBTSxpQkFBaUIsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogT2JzZXJ2YWJpbGl0eSB1dGlsaXRpZXMgZm9yIGh5ZHJhdGluZyBzZXJpYWxpemVkIHdvcmtmbG93IGRhdGEuXG4gKlxuICogVXNlIHRoZXNlIHdoZW4gaW5zcGVjdGluZyB3b3JrZmxvdyBzdGVwIEkvTywgcnVuIGlucHV0cy9vdXRwdXRzLFxuICogb3IgZXZlbnQgZGF0YSBmcm9tIHRoZSBXb3JrZmxvdyBTREsncyB3b3JsZCBBUElzLlxuICpcbiAqIEBleGFtcGxlXG4gKiBgYGB0c1xuICogaW1wb3J0IHsgZ2V0V29ybGQgfSBmcm9tICd3b3JrZmxvdy9ydW50aW1lJztcbiAqIGltcG9ydCB7IGh5ZHJhdGVSZXNvdXJjZUlPLCBvYnNlcnZhYmlsaXR5UmV2aXZlcnMgfSBmcm9tICd3b3JrZmxvdy9vYnNlcnZhYmlsaXR5JztcbiAqXG4gKiBjb25zdCB3b3JsZCA9IGF3YWl0IGdldFdvcmxkKCk7XG4gKiBjb25zdCBzdGVwID0gYXdhaXQgd29ybGQuc3RlcHMuZ2V0KHJ1bklkLCBzdGVwSWQsIHsgcmVzb2x2ZURhdGE6ICdhbGwnIH0pO1xuICogY29uc3QgaHlkcmF0ZWQgPSBoeWRyYXRlUmVzb3VyY2VJTyhzdGVwLCBvYnNlcnZhYmlsaXR5UmV2aXZlcnMpO1xuICogLy8gaHlkcmF0ZWQuaW5wdXQgYW5kIGh5ZHJhdGVkLm91dHB1dCBhcmUgbm93IHBsYWluIEpTIG9iamVjdHNcbiAqIGBgYFxuICovXG5leHBvcnQge1xuICBjcmVhdGVTdGF0ZVJlc29sdmVyLFxuICBoeWRyYXRlRGF0YSxcbiAgaHlkcmF0ZVJlc291cmNlSU8sXG4gIG9ic2VydmFiaWxpdHlSZXZpdmVycyxcbiAgdHlwZSBSZXZpdmVycyxcbiAgdHlwZSBTdGF0ZVJlc29sdmVyLFxuICBzdGF0ZVNvdXJjZUlkLFxufSBmcm9tICdAd29ya2Zsb3cvY29yZS9zZXJpYWxpemF0aW9uLWZvcm1hdCc7XG5cbmV4cG9ydCB7XG4gIHBhcnNlQ2xhc3NOYW1lLFxuICBwYXJzZVN0ZXBOYW1lLFxuICBwYXJzZVdvcmtmbG93TmFtZSxcbn0gZnJvbSAnQHdvcmtmbG93L3V0aWxzJztcbiJdfQ==
@@ -76,7 +76,7 @@ export async function POST(request: Request) {
76
76
  "use client";
77
77
 
78
78
  import { useChat } from "@ai-sdk/react";
79
- import { WorkflowChatTransport } from "@ai-sdk/workflow";
79
+ import { WorkflowChatTransport } from "@ai-sdk/workflow/client";
80
80
  import { useMemo } from "react";
81
81
 
82
82
  export function Chat({ initialMessages }) {
@@ -117,7 +117,7 @@ Replace the default transport in AI SDK's `useChat` with [`WorkflowChatTransport
117
117
  "use client";
118
118
 
119
119
  import { useChat } from "@ai-sdk/react";
120
- import { WorkflowChatTransport } from "@ai-sdk/workflow"; // [!code highlight]
120
+ import { WorkflowChatTransport } from "@ai-sdk/workflow/client"; // [!code highlight]
121
121
  import { useMemo, useState } from "react";
122
122
 
123
123
  export default function ChatPage() {
@@ -180,7 +180,7 @@ On a conflict, the resolved value is a `Run` handle for the run that owns the to
180
180
 
181
181
  Work started *beside* the awaiter, rather than after it, is not slowed down by it. In `await Promise.all([hook.getConflict(), prepare()])` the registration and the step are scheduled together: the runtime commits the registration, resolves the awaiter in the same invocation, and then runs `prepare()` there too, so the step does not pay an extra round trip through the queue for having been started next to a `getConflict()`.
182
182
 
183
- This is a scheduling improvement, not an ordering guarantee. Only the steps the invocation runs inline start after the registration is recorded: the first [`WORKFLOW_MAX_INLINE_STEPS`](/docs/configuration/runtime-tuning#workflow_max_inline_steps) of them, less any inline steps the invocation is still running from an earlier part of the workflow (see [`WORKFLOW_INLINE_EARLY_ADVANCE`](/docs/configuration/runtime-tuning#workflow_inline_early_advance)). A wider fan-out beside the awaiter has its remaining steps created and queued alongside the hook, exactly as described above, so they can start before the registration commits and can start even if it conflicts. When the ordering is what you need, await `hook.getConflict()` *before* calling the step.
183
+ This is a scheduling improvement, not an ordering guarantee. Only the steps the invocation runs inline start after the registration is recorded: the first [`WORKFLOW_MAX_INLINE_STEPS`](/docs/configuration/runtime-tuning#workflow_max_inline_steps) of them, less any inline steps the invocation is still running from an earlier part of the workflow. A wider fan-out beside the awaiter has its remaining steps created and queued alongside the hook, exactly as described above, so they can start before the registration commits and can start even if it conflicts. When the ordering is what you need, await `hook.getConflict()` *before* calling the step.
184
184
 
185
185
  <Callout type="info">
186
186
  Custom hook tokens are the recommended way to coordinate active workflow runs. Use a deterministic token from your domain, such as an order ID or conversation ID, create the hook near the beginning of the workflow, and check `await hook.getConflict()` before work that depends on owning the token. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
@@ -188,7 +188,7 @@ Custom hook tokens are the recommended way to coordinate active workflow runs. U
188
188
 
189
189
  ### Open the run's start Hook
190
190
 
191
- A run started with [`start(workflow, args, { hook: { token } })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) already owns its token through its start Hook. Calling `createHook({ token })` with that token in the run returns a handle bound to the start Hook instead of registering a new one: it adds no step, `await hook.getConflict()` resolves `null`, and payloads resumed before the call are delivered in order. Set `metadata` and `experimental_minRetention` on `start({ hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to this `createHook()` throws. Open it with `const`: disposing the handle frees the token, as for any Hook, and a later `start()` with it is then admitted as a new run (see [Take care with the start Hook's lifecycle](/docs/api-reference/workflow-api/start#take-care-with-the-start-hooks-lifecycle)). See [Receive the payloads in the workflow](/docs/foundations/idempotency#receive-the-payloads-in-the-workflow).
191
+ A run started with [`start(workflow, args, { experimental_hook: { token } })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) already owns its token through its start Hook. Calling `createHook({ token })` with that token in the run returns a handle bound to the start Hook instead of registering a new one: it adds no step, `await hook.getConflict()` resolves `null`, and payloads resumed before the call are delivered in order. Set `metadata` and `experimental_minRetention` on `start({ experimental_hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to this `createHook()` throws. Open it with `const`: disposing the handle frees the token, as for any Hook, and a later `start()` with it is then admitted as a new run (see [Take care with the start Hook's lifecycle](/docs/api-reference/workflow-api/start#take-care-with-the-start-hooks-lifecycle)). See [Receive the payloads in the workflow](/docs/foundations/idempotency#receive-the-payloads-in-the-workflow).
192
192
 
193
193
  ### Keep a token unavailable after the run ends
194
194
 
@@ -266,7 +266,7 @@ With `experimental_force`, this run always ends up owning the token:
266
266
  The takeover is durable. If either run's compute fails partway through, the next request for the token completes it, so the token never ends up held by nobody or by both runs. The previous owner's wake is durable too: if the new owner's compute fails between registering the Hook and waking the previous owner, the new owner's next invocation republishes the wake, whatever else the new owner has recorded since (a step it started alongside the Hook, for example). Every invocation of the new owner within 24 hours of the takeover republishes it under the same idempotency key, which collapses the repeats into one wake; a repeat that does get through only replays the previous owner, which finds nothing new.
267
267
 
268
268
  <Callout type="info">
269
- A token can only be taken from a run whose runtime understands being taken from. Runs started at a Workflow spec version below 8, which includes every run started by an older SDK release, a Python SDK run, or a deployment with `WORKFLOW_SEALED_LOG=0`, would never learn that their Hook was disposed. The World declines to take their token and the forced Hook rejects with the ordinary [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) instead, exactly as if `experimental_force` had not been set. Finished runs holding a retained token are taken over at any version.
269
+ A token can only be taken from a run whose runtime understands being taken from. Runs started at a Workflow spec version below 8, which includes every run started by an older SDK release, a Python SDK run, or a deployment with `WORKFLOW_SPEC_VERSION` set below 8, would never learn that their Hook was disposed. The World declines to take their token and the forced Hook rejects with the ordinary [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) instead, exactly as if `experimental_force` had not been set. Finished runs holding a retained token are taken over at any version.
270
270
  </Callout>
271
271
 
272
272
  `hook.getConflict()` on a forced Hook resolves with `null` once the takeover succeeds: the token is this run's by construction. If the World declines the takeover because the current owner predates spec version 8, `getConflict()` behaves as it does for an ordinary conflict and resolves with that owner's `Run`. Read `hook.claimedFrom` on the value returned by [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) to find out which run, if any, the token was taken from.
@@ -53,7 +53,7 @@ showSections={['returns']}
53
53
 
54
54
  The returned `Webhook` object has:
55
55
 
56
- - `url`: The HTTP endpoint URL that external systems can call
56
+ - `url`: The HTTP endpoint URL that external systems can call. On Vercel, it uses the deployment URL. Elsewhere, it's `http://localhost` on the `PORT` environment variable, or on the detected server port when `PORT` is unset
57
57
  - `token`: The unique token identifying this webhook
58
58
  - `getConflict()`: A promise that resolves with the conflicting run if another active hook already owns this token, or `null` once the webhook endpoint has been registered. The endpoint is registered alongside the steps the workflow starts at the same time, not ahead of them, so await `getConflict()` before a step that hands `url` to a caller who may request it right away. See [Registering a hook before a step uses it](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
59
59
  - Implements `AsyncIterable<T>` for handling multiple requests, where `T` is `Request` (default) or `RequestWithResponse` (manual mode)
@@ -91,11 +91,7 @@ We call `fetch()` with a URL and optional request options, like the standard fet
91
91
 
92
92
  This API lets you use `fetch` in a workflow. You can also implement a custom fetch for different error handling and retry logic.
93
93
 
94
- ### Reading the response body
95
-
96
- Inside a workflow function, `response.json()`, `response.text()`, and `response.arrayBuffer()` each read the body through a step, so the result is recorded in the event log and replays deterministically.
97
-
98
- `response.body` can also be read with `getReader()` or `for await`, which is how libraries such as the AI SDK read responses. The whole body is loaded through a single step and delivered as one chunk. The body is not marked as used after a read: each new reader or body method runs its own step, so read the body once and reuse the result. Incremental streaming APIs such as `pipeThrough()` and `tee()` are not available in workflow functions. To process a response as a stream, read it inside a step function.
94
+ Libraries that call `fetch` internally, like AI SDK calls, should be called from a step function. For agents, use AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent). See [`fetch-in-workflow`](/docs/errors/fetch-in-workflow).
99
95
 
100
96
  ### Customizing fetch behavior
101
97
 
@@ -61,6 +61,25 @@ async function chargeUser(userId: string, amount: number) {
61
61
  <a href="/docs/foundations/idempotency">Idempotency</a> guide.
62
62
  </Callout>
63
63
 
64
+ ### Example: handle the last attempt differently
65
+
66
+ ```typescript lineNumbers
67
+ import { getStepMetadata } from "workflow";
68
+
69
+ async function welcomeUser(userId: string) {
70
+ "use step";
71
+ const { attempt, maxAttempts } = getStepMetadata();
72
+
73
+ try {
74
+ return await sendWelcomeEmail(userId);
75
+ } catch (error) {
76
+ if (attempt < maxAttempts) throw error; // [!code highlight]
77
+ console.error(`Giving up on the welcome email for ${userId}`, error);
78
+ return null;
79
+ }
80
+ }
81
+ ```
82
+
64
83
  ## API signature
65
84
 
66
85
  ### Parameters
@@ -13,7 +13,7 @@ related:
13
13
  `DurableAgent` is deprecated. Use AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) for new durable agents. See the [migration guide](https://ai-sdk.dev/v7/docs/agents/workflow-agent#migrating-from-durableagent).
14
14
  </Callout>
15
15
 
16
- This reference is kept for existing applications that still import `DurableAgent` from `@workflow/ai/agent`. Do not use `DurableAgent` for new code.
16
+ This reference is kept for existing applications that still import `DurableAgent` from `@workflow/ai/agent`. Do not use `DurableAgent` for new code. `@workflow/ai` supports AI SDK 6 only (`ai@^6`); AI SDK 7 apps use `WorkflowAgent` from `@ai-sdk/workflow`.
17
17
 
18
18
  For current examples and implementation guidance, see AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) docs. For legacy code, the API surface below documents the existing `DurableAgent` exports.
19
19
 
@@ -718,6 +718,7 @@ async function agentWithToolChoice() {
718
718
 
719
719
  Use `experimental_context` to pass shared context to tool executions:
720
720
 
721
+ {/* @skip-typecheck: DurableAgent tools use the AI SDK 6 tool options; docs samples are checked against AI SDK 7 */}
721
722
  ```typescript
722
723
  import { DurableAgent } from "@workflow/ai/agent";
723
724
  import { getWritable } from "workflow";
@@ -31,7 +31,7 @@ export default function Chat() {
31
31
  return (
32
32
  <div>
33
33
  {messages.map((m) => (
34
- <div key={m.id}>{m.content}</div>
34
+ <div key={m.id}>{m.parts.map((part) => (part.type === "text" ? part.text : "")).join("")}</div>
35
35
  ))}
36
36
  </div>
37
37
  );
@@ -96,7 +96,7 @@ export default function BasicChat() {
96
96
  <div className="space-y-4">
97
97
  {messages.map((m) => (
98
98
  <div key={m.id}>
99
- <strong>{m.role}:</strong> {m.content}
99
+ <strong>{m.role}:</strong> {m.parts.map((part) => (part.type === "text" ? part.text : "")).join("")}
100
100
  </div>
101
101
  ))}
102
102
  </div>
@@ -164,7 +164,7 @@ export default function ChatWithResumption() {
164
164
  <div className="space-y-4">
165
165
  {messages.map((m) => (
166
166
  <div key={m.id}>
167
- <strong>{m.role}:</strong> {m.content}
167
+ <strong>{m.role}:</strong> {m.parts.map((part) => (part.type === "text" ? part.text : "")).join("")}
168
168
  </div>
169
169
  ))}
170
170
  </div>
@@ -231,7 +231,7 @@ export default function ChatWithCustomConfig() {
231
231
  <div className="space-y-4">
232
232
  {messages.map((m) => (
233
233
  <div key={m.id}>
234
- <strong>{m.role}:</strong> {m.content}
234
+ <strong>{m.role}:</strong> {m.parts.map((part) => (part.type === "text" ? part.text : "")).join("")}
235
235
  </div>
236
236
  ))}
237
237
  </div>
@@ -13,7 +13,7 @@ Retrieves a hook by its unique token, returning the associated workflow run info
13
13
 
14
14
  When `experimental_minRetention` is set, this function continues to return the Hook after its workflow ends until retention ends. That Hook cannot be resumed. Use `getRun(hook.runId)` to inspect the finished run.
15
15
 
16
- A run started with [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) has its start Hook from the moment it is admitted, so this function returns it right away, with the `hook.metadata` passed to `start()`, even before the run starts executing.
16
+ A run started with [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) has its start Hook from the moment it is admitted, so this function returns it right away, with the `hook.metadata` passed to `start()`, even before the run starts executing.
17
17
 
18
18
  When the Hook was created with [`experimental_force`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds) and took its token from another run, `hook.claimedFrom` names that run and its Hook. A lookup always follows the token to its current owner, so the same token returns the new Hook as soon as the takeover happens.
19
19
 
@@ -28,7 +28,7 @@ To deliver several payloads to the same Hook, store the returned Hook and pass i
28
28
  </Callout>
29
29
 
30
30
  <Callout type="info">
31
- Looking up a deterministic hook token is useful in hook-based idempotency flows, but it is only an advisory check. If no hook exists yet, another request can still start the same workflow before your `start()` call registers its hook. Use the lookup to avoid obvious duplicate starts, and handle the race inside the workflow by checking `await hook.getConflict()` before duplicate-sensitive work. On a conflict it resolves with the run that owns the token, so the duplicate can route the caller to the active owner. To reject duplicates before a workflow body runs, use [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) instead. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
31
+ Looking up a deterministic hook token is useful in hook-based idempotency flows, but it is only an advisory check. If no hook exists yet, another request can still start the same workflow before your `start()` call registers its hook. Use the lookup to avoid obvious duplicate starts, and handle the race inside the workflow by checking `await hook.getConflict()` before duplicate-sensitive work. On a conflict it resolves with the run that owns the token, so the duplicate can route the caller to the active owner. To reject duplicates before a workflow body runs, use [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) instead. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
32
32
  </Callout>
33
33
 
34
34
  ```typescript lineNumbers
@@ -16,7 +16,7 @@ It durably writes the `hook_received` event and only then publishes a workflow w
16
16
 
17
17
  `resumeHook()` throws `HookNotFoundError` when no hook holds the token or when its `hook_received` write is refused because the hook was disposed or the run ended. See [durable hook resume](/docs/changelog/lazy-hook-resume).
18
18
 
19
- A run started with [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) has its start Hook from the moment it is admitted, so `resumeHook()` with that token works right away, even before the run starts executing. Payloads sent before the workflow calls `createHook({ token })` are kept and delivered in order once it does. See [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner).
19
+ A run started with [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) has its start Hook from the moment it is admitted, so `resumeHook()` with that token works right away, even before the run starts executing. Payloads sent before the workflow calls `createHook({ token })` are kept and delivered in order once it does. See [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner).
20
20
 
21
21
  Other errors can occur before or after persistence. A lost write response leaves
22
22
  the write's outcome unknown; a failed workflow wake can leave an already durable
@@ -222,7 +222,7 @@ export async function POST(request: Request) {
222
222
 
223
223
  A common endpoint shape is "resume or start": one route that resumes the active workflow run for a business key if one exists, or starts a new run otherwise. This comes up when the workflow uses a deterministic hook token as its idempotency key, for example, one active run per order or conversation.
224
224
 
225
- On a World that supports [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts), flip the order: start with the token first, and on `HookConflictError` resume the owner's start Hook, which accepts payloads right away. See [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner). Without it, use the pattern below.
225
+ On a World that supports [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts), flip the order: start with the token first, and on `HookConflictError` resume the owner's start Hook, which accepts payloads right away. See [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner). Without it, use the pattern below.
226
226
 
227
227
  `resumeHook()` is the resume half of that flow. Try it first; if it throws `HookNotFoundError`, no active run owns the token yet, so start the workflow. One subtlety: `start()` returns before the new run executes and registers its hook, so you cannot resume immediately after starting. Retry the resume until the hook is registered: if you drop the payload and only start the workflow, the data from this request is lost.
228
228
 
@@ -57,7 +57,7 @@ Learn more about [`WorkflowReadableStreamOptions`](/docs/api-reference/workflow-
57
57
  * In v5, you can also call `start()` directly from a workflow function to spawn a child run or continue work in a new run. See [Workflow Composition](/cookbook/common-patterns/workflow-composition) and [Versioning](/docs/foundations/versioning).
58
58
  * This is different from calling workflow functions directly, which is the typical pattern in Next.js applications.
59
59
  * The function returns immediately after enqueuing the workflow. It doesn't wait for the workflow to complete.
60
- * Each call to `start()` creates a new workflow run, unless you pass `hook`. With a deterministic `hook.token`, at most one run can own the token, and a duplicate start throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) naming the owner instead of creating a run. See [Prevent duplicate starts](#prevent-duplicate-starts) and [Idempotency](/docs/foundations/idempotency#run-idempotency).
60
+ * Each call to `start()` creates a new workflow run, unless you pass `experimental_hook`. With a deterministic `experimental_hook.token`, at most one run can own the token, and a duplicate start throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) naming the owner instead of creating a run. See [Prevent duplicate starts](#prevent-duplicate-starts) and [Idempotency](/docs/foundations/idempotency#run-idempotency).
61
61
  * All arguments must be [serializable](/docs/foundations/serialization).
62
62
  * When you provide `deploymentId`, the argument types and return type become `unknown` because the workflow function's types may differ across deployments.
63
63
  * When `deploymentId` names a deployment other than the caller's, the run is stamped with the spec version the *target* deployment reports on its capability probe (capped at the caller's own), since the target is what executes it. `start()` waits up to 10 seconds for the first probe to a deployment and returns as soon as the target answers; later starts to the same deployment reuse the answer. If the target does not answer in time, the run is stamped with spec version 6, the lowest version a v5 runtime executes; a target on an older major version (such as `stable`) cannot execute such a run, so it logs a warning. In either case, the `attributes` and `experimental_retention` checks below apply to the stamped version, and fail naming the target deployment.
@@ -74,7 +74,7 @@ If `start()` throws `'start' received an invalid workflow function. Ensure the W
74
74
 
75
75
  ### Prevent duplicate starts
76
76
 
77
- Pass a `hook` with a token from your domain to make the start idempotent. The World admits the run and creates its start Hook in one atomic step, before any workflow code runs:
77
+ Pass an `experimental_hook` with a token from your domain to make the start idempotent. The World admits the run and creates its start Hook in one atomic step, before any workflow code runs:
78
78
 
79
79
  ```typescript lineNumbers
80
80
  import { start } from "workflow/api";
@@ -86,7 +86,7 @@ export async function POST(request: Request) {
86
86
 
87
87
  try {
88
88
  const run = await start(processOrder, [orderId], {
89
- hook: { // [!code highlight]
89
+ experimental_hook: { // [!code highlight]
90
90
  token: `order:${orderId}`, // [!code highlight]
91
91
  experimental_minRetention: "30 days", // [!code highlight]
92
92
  metadata: { orderId }, // [!code highlight]
@@ -106,7 +106,7 @@ export async function POST(request: Request) {
106
106
  }
107
107
  ```
108
108
 
109
- `hook` takes:
109
+ `experimental_hook` takes:
110
110
 
111
111
  | Option | Description |
112
112
  | --- | --- |
@@ -116,13 +116,13 @@ export async function POST(request: Request) {
116
116
 
117
117
  * Exactly one run owns the token. A duplicate throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) with the owner's `conflictingRunId`. The duplicate never becomes a run, and none of its code runs.
118
118
  * The start Hook exists from the moment the run is admitted, so [`resumeHook(token, payload)`](/docs/api-reference/workflow-api/resume-hook) works right away, even before the run starts executing. Payloads resumed before the workflow opens the Hook are kept and delivered in order once it does.
119
- * In the workflow, `createHook({ token })` with the same token returns a handle bound to the start Hook. It doesn't register a new Hook, so it adds no step, and `getConflict()` resolves `null`. Set `metadata` and `experimental_minRetention` on `start({ hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to that `createHook()` throws. If the workflow never opens the Hook, the token is only an idempotency key: the run completes normally and unread payloads are left unread.
119
+ * In the workflow, `createHook({ token })` with the same token returns a handle bound to the start Hook. It doesn't register a new Hook, so it adds no step, and `getConflict()` resolves `null`. Set `metadata` and `experimental_minRetention` on `start({ experimental_hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to that `createHook()` throws. If the workflow never opens the Hook, the token is only an idempotency key: the run completes normally and unread payloads are left unread.
120
120
  * The start Hook follows the ordinary Hook lifecycle. The token is released when the run ends, or once `experimental_minRetention` has passed if that is later. Disposing the start Hook releases it at once; see [Take care with the start Hook's lifecycle](#take-care-with-the-start-hooks-lifecycle). On a World without Hook retention, `experimental_minRetention` makes `start()` throw.
121
121
  * If `start()` cannot confirm whether the run was queued or admitted, it asks the World again a few times with the same candidate, then throws [`WorkflowStartError`](/docs/api-reference/workflow-errors/workflow-start-error) with the candidate's `runId` and the `stage` that failed. Retrying with the same token is safe: the retry either becomes the owner or throws `HookConflictError` naming it. Inside a workflow, the `start()` step retries it automatically, while a `HookConflictError` (or a permanent rejection) reaches the workflow on the first attempt.
122
122
  * If the run named by a `HookConflictError` is still `pending` more than a minute after it was created (its first queue message was most likely lost, so nothing will start it), the refused `start()` re-publishes that run's orchestrator message in the background, at most once a minute per run (per process, for a single-orchestrator run), and throws without waiting for it. The run then starts; the refusal itself is unchanged.
123
123
  * Rarely, a `HookConflictError` names a candidate that was admitted but never became a run, because the writer that admitted it died. `getRun()` doesn't find it. While the World can still create the run, resuming the token waits and may throw a retryable error with `retryAfter`; once it can't, the World releases the token and resuming throws `HookNotFoundError`. Start again with the same token then.
124
124
  * Stream arguments (for example a webhook's `request.body`) are read only once the run is admitted, so a refused duplicate leaves them untouched. Because `start()` confirms an uncertain admission before giving up, an admitted run usually still gets its input. If it throws `WorkflowStartError` anyway, the run may have been admitted and be waiting on input that will never arrive. Cancel it with [`getRun(error.runId).cancel()`](/docs/api-reference/workflow-api/get-run), which also works when the run doesn't exist yet (see [`WorkflowStartError`](/docs/api-reference/workflow-errors/workflow-start-error)).
125
- * The World must support atomic start Hooks (and Hook retention, when you set one). The Local World does; on the Postgres World it is behind [`WORKFLOW_POSTGRES_EXPERIMENTAL_START_HOOK`](/worlds/postgres#workflow_postgres_experimental_start_hook) and on the Vercel World behind [`WORKFLOW_VERCEL_EXPERIMENTAL_START_HOOK`](/worlds/vercel#workflow_vercel_experimental_start_hook). Otherwise `start()` throws before it enqueues anything. For a cross-deployment start, the target deployment must support it too. `hook` is not supported for [dynamic workflows](/docs/advanced/dynamic-workflows).
125
+ * The World must support atomic start Hooks (and Hook retention, when you set one). The Local, Postgres and Vercel Worlds do (the Postgres World after [migration `0028`](/worlds/postgres#start-hooks)). Otherwise `start()` throws before it enqueues anything. For a cross-deployment start, the target deployment must support it too. `hook` is not supported for [dynamic workflows](/docs/advanced/dynamic-workflows).
126
126
 
127
127
  To route a duplicate's payload to the run that owns the token, resume the owner's start Hook on a conflict. See [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner).
128
128
 
@@ -214,13 +214,17 @@ export async function parentWorkflow(value: number) {
214
214
  ```
215
215
 
216
216
  <Callout type="info">
217
- The returned `Run` object is fully functional inside a workflow. Each property access or method call (`.status`, `.returnValue`, `.cancel()`) executes as a separate step. See [Workflow Composition](/cookbook/common-patterns/workflow-composition) for choosing between spawning a child run and awaiting a workflow function directly.
217
+ The returned `Run` object is fully functional inside a workflow. Each property access or method call (`.status`, `.cancel()`) executes as a separate step. See [Workflow Composition](/cookbook/common-patterns/workflow-composition) for choosing between spawning a child run and awaiting a workflow function directly.
218
218
  </Callout>
219
219
 
220
+ Awaiting `returnValue` of a run the workflow started does not poll. The parent suspends on its system completion hook, a single hook shared by all of its children, and each child resumes it when it completes, fails, or is canceled through the SDK, so the wait costs no compute or worker slot and the parent resumes as soon as the child finishes. The same holds when the `Run` was returned from a step of the parent that called `start()`. See [Child Workflows](/cookbook/advanced/child-workflows#how-the-parent-waits).
221
+
220
222
  <Callout type="warn">
221
- `returnValue` polls the child run every second and holds the polling step's worker slot open for as long as the child takes to finish. For long-running children, spawn without awaiting `returnValue` and have the child resume a [hook](/docs/foundations/hooks) when it completes. See the [`startAndWait()` pattern](/cookbook/advanced/child-workflows).
223
+ A child canceled without the SDK (by a tool that writes the cancellation to the World directly) does not notify its parent. The parent finds out at its next safety-net check, 5 minutes after it starts waiting and then at doubling intervals up to 6 hours. See [Cancellations that bypass the SDK](/cookbook/advanced/child-workflows#cancellations-that-bypass-the-sdk).
222
224
  </Callout>
223
225
 
226
+ `returnValue` still polls when the waiting code is not the parent: a step, an API route, or another workflow handed the `Run`. It also polls for a child on another deployment (`deploymentId`) that predates the system hook, and for every child while `WORKFLOW_CHILD_RUN_COMPLETION_HOOK=0` is set. A polling step holds its worker slot until the child finishes.
227
+
224
228
  ### Dynamic Workflow Source
225
229
 
226
230
  <Callout type="warning">
@@ -2,7 +2,7 @@
2
2
  title: HookConflictError
3
3
  description: Thrown when creating a hook, or starting a run with a hook, whose token another workflow run owns.
4
4
  type: reference
5
- summary: Catch HookConflictError when a hook token is already owned by another workflow run, including a duplicate start({ hook }).
5
+ summary: Catch HookConflictError when a hook token is already owned by another workflow run, including a duplicate start({ experimental_hook }).
6
6
  related:
7
7
  - /docs/api-reference/workflow/create-hook
8
8
  - /docs/foundations/hooks
@@ -10,7 +10,7 @@ related:
10
10
  - /docs/foundations/idempotency
11
11
  ---
12
12
 
13
- `HookConflictError` is thrown when creating a hook, or calling [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts), with a token that another workflow run owns. From `start()` it always carries `conflictingRunId`, and no run was created for the duplicate. The owner may still be running, or may have finished while an `experimental_minRetention` holds the token. To deliver the duplicate's data instead, resume the owner's start Hook: see [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner).
13
+ `HookConflictError` is thrown when creating a hook, or calling [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts), with a token that another workflow run owns. From `start()` it always carries `conflictingRunId`, and no run was created for the duplicate. The owner may still be running, or may have finished while an `experimental_minRetention` holds the token. To deliver the duplicate's data instead, resume the owner's start Hook: see [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner).
14
14
 
15
15
  When creating a hook, it means the token is already in use by another active workflow run. Hook tokens must be unique across all running workflows. See the [hook-conflict](/docs/errors/hook-conflict) error guide for resolution strategies. To take the token over instead, create the hook with [`experimental_force: true`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds).
16
16
 
@@ -52,7 +52,7 @@ All errors extend [`WorkflowError`](/docs/api-reference/workflow-errors/workflow
52
52
  Thrown when the workflow runtime encounters an execution error, such as serialization failures or timeouts.
53
53
  </Card>
54
54
  <Card href="/docs/api-reference/workflow-errors/workflow-start-error" title="WorkflowStartError">
55
- Thrown when `start({ hook })` cannot confirm whether its run was queued or admitted.
55
+ Thrown when `start({ experimental_hook })` cannot confirm whether its run was queued or admitted.
56
56
  </Card>
57
57
  <Card href="/docs/api-reference/workflow-errors/run-expired-error" title="RunExpiredError">
58
58
  Thrown when a workflow run has expired and can no longer be operated on.
@@ -12,7 +12,7 @@ related:
12
12
 
13
13
  You can check for cancellation before awaiting by inspecting `run.status`.
14
14
 
15
- A canceled run is terminal, so this error is non-retryable (`fatal: true`). Inside a workflow, `await run.returnValue` runs as a step, and that step fails on its first attempt instead of spending its retry budget re-reading a run that cannot change. Errors from *failing to read* the run, such as a transport blip, stay retryable.
15
+ A canceled run is terminal, so this error is non-retryable (`fatal: true`). Inside a workflow, `await run.returnValue` reads the result in a step, and that step fails on its first attempt instead of spending its retry budget re-reading a run that cannot change. Errors from *failing to read* the run, such as a transport blip, stay retryable.
16
16
 
17
17
  ```typescript lineNumbers
18
18
  import { WorkflowRunCancelledError } from "workflow/errors"
@@ -13,7 +13,7 @@ related:
13
13
 
14
14
  The `cause` property holds the original thrown value, hydrated through the workflow serialization pipeline so its type identity (e.g. `FatalError`, `RetryableError`, custom `Error` subclasses), `cause` chain, and custom properties are preserved. Because any JavaScript value can be thrown, `cause` is typed as `unknown`, so narrow it with `instanceof Error` (or a more specific check) before accessing fields like `message`. The high-level error classification is exposed as the top-level `errorCode` property.
15
15
 
16
- A failed run is terminal, so this error is non-retryable (`fatal: true`). Inside a workflow, `await run.returnValue` runs as a step, and that step fails on its first attempt instead of spending its retry budget re-reading a run that cannot change: the remote failure reaches the caller immediately, and the caller catches a `WorkflowRunFailedError` rather than a retry-exhaustion wrapper. Errors from *failing to read* the run, such as a transport blip, stay retryable.
16
+ A failed run is terminal, so this error is non-retryable (`fatal: true`). Inside a workflow, `await run.returnValue` reads the result in a step, and that step fails on its first attempt instead of spending its retry budget re-reading a run that cannot change: the remote failure reaches the caller immediately, and the caller catches a `WorkflowRunFailedError` rather than a retry-exhaustion wrapper. Errors from *failing to read* the run, such as a transport blip, stay retryable.
17
17
 
18
18
  ```typescript lineNumbers
19
19
  import { WorkflowRunFailedError } from "workflow/errors"
@@ -2,13 +2,13 @@
2
2
  title: WorkflowStartError
3
3
  description: Thrown when start with a hook cannot confirm whether its run was queued or admitted.
4
4
  type: reference
5
- summary: Catch WorkflowStartError to identify a start({ hook }) candidate whose outcome is unknown, then retry with the same token.
5
+ summary: Catch WorkflowStartError to identify a start({ experimental_hook }) candidate whose outcome is unknown, then retry with the same token.
6
6
  related:
7
7
  - /docs/api-reference/workflow-api/start
8
8
  - /docs/foundations/idempotency
9
9
  ---
10
10
 
11
- `WorkflowStartError` is thrown when [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) cannot confirm whether its candidate run was queued or admitted, for example because the World timed out. The outcome is unknown, not failed: the candidate may still become the run that owns the token.
11
+ `WorkflowStartError` is thrown when [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) cannot confirm whether its candidate run was queued or admitted, for example because the World timed out. The outcome is unknown, not failed: the candidate may still become the run that owns the token.
12
12
 
13
13
  ```typescript lineNumbers
14
14
  import { start } from "workflow/api";
@@ -19,13 +19,13 @@ declare const orderId: string; // @setup
19
19
  async function startOrder() {
20
20
  try {
21
21
  return await start(processOrder, [orderId], {
22
- hook: { token: `order:${orderId}`, experimental_minRetention: "1h" },
22
+ experimental_hook: { token: `order:${orderId}`, experimental_minRetention: "1h" },
23
23
  });
24
24
  } catch (error) {
25
25
  if (WorkflowStartError.is(error)) { // [!code highlight]
26
26
  console.warn(`Unconfirmed start ${error.runId} (${error.stage}); retrying`);
27
27
  return await start(processOrder, [orderId], {
28
- hook: { token: `order:${orderId}`, experimental_minRetention: "1h" },
28
+ experimental_hook: { token: `order:${orderId}`, experimental_minRetention: "1h" },
29
29
  });
30
30
  }
31
31
  throw error;
@@ -33,7 +33,7 @@ async function startOrder() {
33
33
  }
34
34
  ```
35
35
 
36
- `WorkflowStartError` is only thrown by a start that passes `hook`, and retrying it with the same token is safe while the token is held. If the first candidate was admitted and still holds the token, the retry throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) with `conflictingRunId` set to it; if it was not admitted, the retry's run becomes the owner. The owner holds the token until it ends, then for any `experimental_minRetention`, unless it [disposes its start Hook](/docs/api-reference/workflow-api/start#take-care-with-the-start-hooks-lifecycle) first, which releases the token at once. A retry after the token is released is admitted as a new run, which is why the example sets a retention that covers its retry window. Either way, a payload you meant for the run can go to [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) after a conflict, as in [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner). Inside a workflow, the `start()` step retries it on its own. It extends `WorkflowError`, not `WorkflowWorldError`: it is not a World response, so World error checks never classify it as permanent.
36
+ `WorkflowStartError` is only thrown by a start that passes `experimental_hook`, and retrying it with the same token is safe while the token is held. If the first candidate was admitted and still holds the token, the retry throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) with `conflictingRunId` set to it; if it was not admitted, the retry's run becomes the owner. The owner holds the token until it ends, then for any `experimental_minRetention`, unless it [disposes its start Hook](/docs/api-reference/workflow-api/start#take-care-with-the-start-hooks-lifecycle) first, which releases the token at once. A retry after the token is released is admitted as a new run, which is why the example sets a retention that covers its retry window. Either way, a payload you meant for the run can go to [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) after a conflict, as in [Start or route to the owner](/docs/foundations/idempotency#start-or-route-to-the-owner). Inside a workflow, the `start()` step retries it on its own. It extends `WorkflowError`, not `WorkflowWorldError`: it is not a World response, so World error checks never classify it as permanent.
37
37
 
38
38
  ## API Signature
39
39
 
@@ -104,6 +104,7 @@ export default withWorkflow(nextConfig, {
104
104
  | --- | --- | --- | --- |
105
105
  | `workflows.local.port` | `number` | — | Overrides the `PORT` environment variable for local development. Has no effect when deployed to Vercel. |
106
106
  | `workflows.sourcemap` | `boolean \| 'inline' \| 'linked' \| 'external' \| 'both'` | `'inline'` (dev) / `false` (prod) | Controls source maps on generated workflow bundles. See [Source maps](#source-maps) below. |
107
+ | `workflows.experimentalRoutePrefix` | `string` | — | Serves the generated workflow routes below a route segment this app owns, such as `/dashboard`. See [Workflow route prefix](#workflow-route-prefix) below. |
107
108
 
108
109
  ### Source maps
109
110
 
@@ -129,6 +130,62 @@ The option can also be set via the `WORKFLOW_SOURCEMAP` environment variable, wh
129
130
  The `workflows.local` options only affect local development. When deployed to Vercel, the runtime ignores `local` settings and uses the Vercel world automatically.
130
131
  </Callout>
131
132
 
133
+ ### Workflow route prefix
134
+
135
+ By default the integration generates its routes at the root of your app, so the flow route answers at `/.well-known/workflow/v1/flow`. Some deployments cannot own those paths. In a [Microfrontends](https://vercel.com/docs/microfrontends) setup, for example, a child app is routed a path such as `/dashboard/*` while requests for `/.well-known/*` go to the default app, so queue deliveries and webhooks aimed at the root never reach the child.
136
+
137
+ `workflows.experimentalRoutePrefix` moves the generated workflow routes below a segment the app does own:
138
+
139
+ ```typescript title="next.config.ts" lineNumbers
140
+ import type { NextConfig } from "next";
141
+ import { withWorkflow } from "workflow/next";
142
+
143
+ const nextConfig: NextConfig = {};
144
+
145
+ export default withWorkflow(nextConfig, {
146
+ workflows: {
147
+ experimentalRoutePrefix: "/dashboard", // [!code highlight]
148
+ },
149
+ });
150
+ ```
151
+
152
+ With that prefix, the build emits:
153
+
154
+ | Artifact | Path |
155
+ | --- | --- |
156
+ | Flow route | `app/dashboard/.well-known/workflow/v1/flow/route.js` |
157
+ | Webhook route | `app/dashboard/.well-known/workflow/v1/webhook/[token]/route.js` |
158
+ | Vercel function config | `app/dashboard/.well-known/workflow/v1/config.json` |
159
+ | Manifest | `app/dashboard/.well-known/workflow/v1/manifest.json` |
160
+
161
+ The queue trigger that makes the flow route a queue consumer is written next to the prefixed route, so deliveries reach it without any additional routing configuration. Webhook URLs, health checks, and the local and Postgres queue targets are all built from the prefix, so `createWebhook()` returns a URL under `/dashboard/.well-known/workflow/v1/webhook/:token`. `getWorkflowMetadata().url` includes the prefix too (for example `https://example.com/dashboard`), so don't build URLs to the rest of your app from it.
162
+
163
+ The prefix is a plain path of one or more segments. Leading and trailing slashes are optional. Anything Next.js would not serve at a fixed path is rejected when the config is created: dynamic segments such as `/[team]`, route groups such as `/(group)`, and `_`-prefixed segments, which Next.js excludes from routing entirely. Segments starting with `.` are rejected too, because the build could not clean up routes generated below them after the prefix changes.
164
+
165
+ <Callout type="warn">
166
+ If you cache your build with Turborepo, update the `outputs` globs to the prefixed paths. `app/.well-known/workflow/**` no longer matches `app/dashboard/.well-known/workflow/**`, and a cache hit would restore a build with no workflow routes in it.
167
+ </Callout>
168
+
169
+ <Callout type="warn">
170
+ If the app has `proxy.ts` or middleware, its matcher must exclude the prefixed path. A pattern such as `/((?!.well-known/workflow/).*)` only matches from the start of the path, so it no longer skips `/dashboard/.well-known/workflow/v1/flow`; exclude `dashboard/.well-known/workflow/` instead.
171
+ </Callout>
172
+
173
+ <Callout type="warn">
174
+ Your routing layer must send the prefixed paths to this app. With Microfrontends, that means choosing a prefix the child app is already routed in the group's [routing configuration](https://vercel.com/docs/microfrontends/routing).
175
+ </Callout>
176
+
177
+ This option is experimental and its name may change.
178
+
179
+ #### Compared with `basePath`
180
+
181
+ The integration already honors Next.js' [`basePath`](https://nextjs.org/docs/app/api-reference/config/next-config-js/basePath): Next.js serves every route, including the generated workflow routes, below it, and `withWorkflow` passes it to the runtime so webhook and queue URLs include it. That only helps when the whole app can move under one path. A Microfrontends child app usually can't: its pages already live at `app/dashboard/...`, so `basePath: "/dashboard"` would serve them at `/dashboard/dashboard/...`.
182
+
183
+ `experimentalRoutePrefix` moves only the generated workflow routes and their function config into the app tree; the rest of your routes keep their paths. The two compose: with `basePath: "/v2"` and `experimentalRoutePrefix: "/dashboard"`, the flow route answers at `/v2/dashboard/.well-known/workflow/v1/flow`.
184
+
185
+ <Callout type="info">
186
+ The local CLI and web UI find a prefixed manifest such as `app/dashboard/.well-known/workflow/v1/manifest.json` on their own; set [`WORKFLOW_MANIFEST_PATH`](/docs/configuration/cli-and-web-ui#workflow_manifest_path) to pick another. Pass the base path to [`workflow health`](/docs/configuration/cli-and-web-ui#--base-path), for example `workflow health --base-path /dashboard`.
187
+ </Callout>
188
+
132
189
  ## Exporting a function
133
190
 
134
191
 
@@ -0,0 +1,56 @@
1
+ ---
2
+ title: createStateResolver
3
+ description: Rebuild frozen state that a run stored by reference, so inspection tools show actual values.
4
+ type: reference
5
+ summary: Use createStateResolver to show the actual values of step inputs and outputs that hold frozen state stored by reference.
6
+ related:
7
+ - /docs/api-reference/workflow-observability/hydrate-data
8
+ - /docs/api-reference/workflow-observability/observability-revivers
9
+ - /docs/foundations/serialization
10
+ ---
11
+
12
+ Deeply frozen values passed between steps are stored by reference: a step input that holds one is written as a reference to an earlier step's output, and a step output as its change from the value it was made from. See [Serialization](/docs/foundations/serialization). Workflow rebuilds them during replay, so your code always receives whole values. An inspection tool reading the stored payloads directly has to rebuild them too, from the run's earlier records.
13
+
14
+ Create one resolver per run, feed it the run's persisted payloads once, in event-log order, and merge its revivers over the ones you hydrate with:
15
+
16
+ ```typescript lineNumbers
17
+ import { createStateResolver, hydrateData, observabilityRevivers, stateSourceId } from "workflow/observability"; // [!code highlight]
18
+ declare const runInput: unknown; // @setup
19
+ declare const events: { eventId: string; eventType: string; eventData?: { payload?: unknown; result?: unknown } }[]; // @setup
20
+ declare const stepInput: unknown; // @setup
21
+
22
+ const resolver = createStateResolver(observabilityRevivers); // [!code highlight]
23
+ resolver.add(runInput, stateSourceId("run-input"));
24
+ for (const event of events) {
25
+ if (event.eventType === "hook_received") resolver.add(event.eventData?.payload, stateSourceId(event));
26
+ if (event.eventType === "step_completed") resolver.add(event.eventData?.result);
27
+ }
28
+
29
+ const input = hydrateData(stepInput, { ...observabilityRevivers, ...resolver.revivers }); // [!code highlight]
30
+ ```
31
+
32
+ Pass decrypted payloads. Keep the resolver for the run and reuse it across inspections, so the history is read once.
33
+
34
+ A web inspector built on `@workflow/web-shared` can use `createRunStateHydrator()` instead. It reads the run's history through loaders you give it, only as far as the inspected value needs, and handles encrypted and compressed payloads. The Workflow web UI uses it for its span details, and `workflow inspect` rebuilds values the same way.
35
+
36
+ ## API signature
37
+
38
+ ### Parameters
39
+
40
+ | Parameter | Type | Description |
41
+ |-----------|------|-------------|
42
+ | `revivers` | `Revivers` | Optional. Revivers for the other types inside the stored payloads. Use [`observabilityRevivers`](/docs/api-reference/workflow-observability/observability-revivers) for standard use. |
43
+
44
+ ### Returns
45
+
46
+ A `StateResolver`:
47
+
48
+ | Property | Type | Description |
49
+ |----------|------|-------------|
50
+ | `add(data, source?)` | `(data: unknown, source?: string) => void` | Reads one persisted payload. Pass `stateSourceId(event)` for a `hook_received` payload and `stateSourceId("run-input")` for the run input, so state can refer to their strings. A step output with no state records is skipped. |
51
+ | `revivers` | `Revivers` | Revivers that rebuild state records from what has been added. Merge them over your own. |
52
+ | `unresolved` | `number` | How many records referred to history that hasn't been added yet. Those show as `<state …>` placeholders; add more of the history and hydrate again. |
53
+
54
+ ## stateSourceId
55
+
56
+ `stateSourceId(event)` returns the id a `hook_received` event's payload is registered under, and `stateSourceId("run-input")` the id for the run input. Use the same ids the runtime uses, or state that refers to those payloads' strings stays unresolved.
@@ -8,6 +8,7 @@ keywords:
8
8
  - hydrateResourceIO
9
9
  - observabilityRevivers
10
10
  - hydrateData
11
+ - createStateResolver
11
12
  - parseStepName
12
13
  - parseWorkflowName
13
14
  - parseClassName
@@ -23,6 +24,7 @@ import { // [!code highlight]
23
24
  hydrateResourceIO, // [!code highlight]
24
25
  observabilityRevivers, // [!code highlight]
25
26
  hydrateData, // [!code highlight]
27
+ createStateResolver, // [!code highlight]
26
28
  parseStepName, // [!code highlight]
27
29
  parseWorkflowName, // [!code highlight]
28
30
  parseClassName, // [!code highlight]
@@ -41,6 +43,9 @@ import { // [!code highlight]
41
43
  <Card href="/docs/api-reference/workflow-observability/hydrate-data" title="hydrateData()">
42
44
  Hydrate a single serialized value (lower-level than hydrateResourceIO).
43
45
  </Card>
46
+ <Card href="/docs/api-reference/workflow-observability/create-state-resolver" title="createStateResolver()">
47
+ Rebuild frozen state a run stored by reference, so inspected values show in full.
48
+ </Card>
44
49
  </Cards>
45
50
 
46
51
  ## Name parsing
@@ -4,6 +4,7 @@
4
4
  "hydrate-resource-io",
5
5
  "observability-revivers",
6
6
  "hydrate-data",
7
+ "create-state-resolver",
7
8
  "parse-step-name",
8
9
  "parse-workflow-name",
9
10
  "parse-class-name"