workflow 5.4.0 → 5.6.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 (111) hide show
  1. package/dist/api-workflow.js +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/astro.js +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/internal/builtins.js +1 -1
  6. package/dist/internal/class-serialization.js +1 -1
  7. package/dist/internal/errors.js +1 -1
  8. package/dist/nest-builder.js +1 -1
  9. package/dist/nest-vercel-builder.js +1 -1
  10. package/dist/nest.js +1 -1
  11. package/dist/next.cjs +1 -1
  12. package/dist/nitro.js +1 -1
  13. package/dist/nuxt.js +1 -1
  14. package/dist/observability.d.ts +1 -1
  15. package/dist/observability.js +2 -2
  16. package/dist/runtime.js +1 -1
  17. package/dist/stdlib.js +1 -1
  18. package/dist/sveltekit.js +1 -1
  19. package/dist/typescript-plugin.cjs +1 -1
  20. package/dist/vite.js +1 -1
  21. package/dist/workflow.js +1 -1
  22. package/docs/ai/chat-session-modeling.mdx +1 -1
  23. package/docs/ai/resumable-streams.mdx +1 -1
  24. package/docs/api-reference/workflow/create-hook.mdx +2 -2
  25. package/docs/api-reference/workflow/get-step-metadata.mdx +19 -0
  26. package/docs/api-reference/workflow-ai/durable-agent.mdx +2 -1
  27. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +4 -4
  28. package/docs/api-reference/workflow-api/get-run.mdx +0 -4
  29. package/docs/api-reference/workflow-api/resume-hook.mdx +1 -1
  30. package/docs/api-reference/workflow-api/start.mdx +1 -1
  31. package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +0 -3
  32. package/docs/api-reference/workflow-errors/index.mdx +1 -1
  33. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +0 -2
  34. package/docs/api-reference/workflow-errors/workflow-not-registered-error.mdx +1 -1
  35. package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +1 -1
  36. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +1 -1
  37. package/docs/api-reference/workflow-next/with-workflow.mdx +57 -0
  38. package/docs/api-reference/workflow-observability/create-state-resolver.mdx +56 -0
  39. package/docs/api-reference/workflow-observability/index.mdx +5 -0
  40. package/docs/api-reference/workflow-observability/meta.json +1 -0
  41. package/docs/api-reference/workflow-runtime/world/queue.mdx +70 -3
  42. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -2
  43. package/docs/comparisons/index.mdx +4 -1
  44. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +3 -1
  45. package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +4 -1
  46. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +271 -28
  47. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +6 -2
  48. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +2 -0
  49. package/docs/configuration/build-and-diagnostics.mdx +2 -0
  50. package/docs/configuration/cli-and-web-ui.mdx +40 -1
  51. package/docs/configuration/framework-options.mdx +7 -0
  52. package/docs/configuration/runtime-tuning.mdx +31 -85
  53. package/docs/configuration/worlds.mdx +69 -40
  54. package/docs/cookbook/advanced/child-workflows.mdx +3 -3
  55. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +1 -1
  56. package/docs/cookbook/common-patterns/batching.mdx +1 -1
  57. package/docs/cookbook/integrations/ai-sdk.mdx +2 -2
  58. package/docs/errors/corrupted-event-log.mdx +1 -1
  59. package/docs/errors/hook-force-claimed.mdx +1 -1
  60. package/docs/errors/index.mdx +1 -0
  61. package/docs/errors/max-events-exceeded.mdx +2 -2
  62. package/docs/errors/replay-timeout.mdx +2 -2
  63. package/docs/errors/runtime-decryption-failed.mdx +1 -1
  64. package/docs/errors/workflow-not-registered.mdx +1 -1
  65. package/docs/foundations/errors-and-retries.mdx +4 -5
  66. package/docs/foundations/serialization.mdx +80 -0
  67. package/docs/getting-started/next.mdx +2 -0
  68. package/docs/how-it-works/event-sourcing.mdx +4 -7
  69. package/docs/how-it-works/framework-integrations.mdx +2 -2
  70. package/docs/internal/index.mdx +1 -0
  71. package/docs/internal/nitro-native-build.mdx +1 -0
  72. package/docs/internal/nitro-web-ui.mdx +1 -0
  73. package/docs/internal/serializable-abort-controller.mdx +1 -0
  74. package/docs/observability/index.mdx +4 -0
  75. package/docs/whats-new.mdx +5 -5
  76. package/docs/worlds/building-a-world.mdx +63 -6
  77. package/docs/worlds/local.mdx +115 -26
  78. package/docs/worlds/postgres.mdx +110 -33
  79. package/docs/worlds/upgrading-to-v5.mdx +6 -6
  80. package/docs/worlds/vercel.mdx +194 -81
  81. package/package.json +17 -15
  82. package/dist/api-workflow.d.ts.map +0 -1
  83. package/dist/api.d.ts.map +0 -1
  84. package/dist/astro.d.ts.map +0 -1
  85. package/dist/index.d.ts.map +0 -1
  86. package/dist/internal/builtins.d.ts.map +0 -1
  87. package/dist/internal/class-serialization.d.ts.map +0 -1
  88. package/dist/internal/errors.d.ts.map +0 -1
  89. package/dist/nest-builder.d.ts.map +0 -1
  90. package/dist/nest-vercel-builder.d.ts.map +0 -1
  91. package/dist/nest.d.ts.map +0 -1
  92. package/dist/nitro.d.ts.map +0 -1
  93. package/dist/nuxt.d.ts.map +0 -1
  94. package/dist/observability.d.ts.map +0 -1
  95. package/dist/runtime.d.ts.map +0 -1
  96. package/dist/stdlib.d.ts.map +0 -1
  97. package/dist/sveltekit.d.ts.map +0 -1
  98. package/dist/vite.d.ts.map +0 -1
  99. package/dist/workflow.d.ts.map +0 -1
  100. package/docs/changelog/attributes-mvp.mdx +0 -380
  101. package/docs/changelog/batched-event-writes.mdx +0 -79
  102. package/docs/changelog/eager-processing.mdx +0 -273
  103. package/docs/changelog/index.mdx +0 -19
  104. package/docs/changelog/lazy-event-creation.md +0 -127
  105. package/docs/changelog/lazy-hook-resume.mdx +0 -78
  106. package/docs/changelog/meta.json +0 -16
  107. package/docs/changelog/resilient-resume.mdx +0 -32
  108. package/docs/changelog/resilient-start.mdx +0 -77
  109. package/docs/changelog/spec-9.mdx +0 -4019
  110. package/docs/changelog/step-message-ownership.mdx +0 -360
  111. package/docs/changelog/turbo-mode.md +0 -91
@@ -25,6 +25,7 @@ When a workflow run fails, its `errorCode` identifies the failure category. You
25
25
  | `STREAM_ERROR` | Workflow stream infrastructure failed while reading or writing data. This is an SDK or backend failure rather than an error in workflow code. |
26
26
  | `WORLD_CONTRACT_ERROR` | A World returned data that violated the SDK contract and could not be retried safely. This usually indicates a World implementation bug. |
27
27
  | [`DEPLOYMENT_MISMATCH`](/docs/errors/deployment-mismatch) | A run was delivered to a deployment other than the one it is pinned to, and automatic re-routing did not recover it. |
28
+ | [`WORKFLOW_NOT_REGISTERED`](/docs/errors/workflow-not-registered) | The deployment executing the run does not have the run's workflow registered, usually because the run targeted a deployment where the workflow was renamed, moved, or removed, or the build did not bundle it. |
28
29
 
29
30
  For guidance on catching failures, retry behavior, and inspecting `WorkflowRunFailedError`, see [Errors and retries](/docs/foundations/errors-and-retries).
30
31
 
@@ -38,8 +38,8 @@ Workflow run is approaching the per-run event limit (<count> of <limit> events,
38
38
 
39
39
  ### Run on the QuickJS VM with snapshotting
40
40
 
41
- <Callout type="warn">
42
- The QuickJS engine is experimental, and its global surface differs from the default engine. Review the [differences](/docs/configuration/runtime-tuning#workflow_vm) before switching an existing deployment.
41
+ <Callout type="info">
42
+ This is the recommended fix for long-running workflows. Workflow code runs unchanged unless it uses one of the few globals QuickJS does not provide in workflow functions (any `Intl.*` constructor, `toLocaleString()`-style methods called with a locale, `crypto.subtle`, `WebAssembly`); those calls move into a step. See the [full list](/docs/configuration/runtime-tuning#workflow_vm).
43
43
  </Callout>
44
44
 
45
45
  Runs that execute on the QuickJS VM with snapshotting enabled are exempt from the default per-run event limit. A snapshotted run restores its VM memory and replays only the events recorded since the last snapshot, so its resume cost doesn't grow with the length of the log.
@@ -31,8 +31,8 @@ Workflow replay exceeded maximum duration (240s) after 4 attempts
31
31
 
32
32
  ### Run on the QuickJS VM with snapshotting
33
33
 
34
- <Callout type="warn">
35
- The QuickJS engine is experimental, and its global surface differs from the default engine. Review the [differences](/docs/configuration/runtime-tuning#workflow_vm) before switching an existing deployment.
34
+ <Callout type="info">
35
+ This is the recommended fix for long-running workflows. Workflow code runs unchanged unless it uses one of the few globals QuickJS does not provide in workflow functions (any `Intl.*` constructor, `toLocaleString()`-style methods called with a locale, `crypto.subtle`, `WebAssembly`); those calls move into a step. See the [full list](/docs/configuration/runtime-tuning#workflow_vm).
36
36
  </Callout>
37
37
 
38
38
  Under QuickJS with snapshotting, a run restores its VM memory from a snapshot and replays only the events recorded since, so replay time stays roughly constant as the log grows. These runs are also exempt from the default [per-run event limit](/docs/errors/max-events-exceeded).
@@ -31,7 +31,7 @@ The thrown `RuntimeDecryptionError` carries a small `context` object with diagno
31
31
 
32
32
  Common causes, in rough order of likelihood:
33
33
 
34
- 1. **Ciphertext mutation or truncation in transit.** The encrypted payload reached the SDK with bytes that differ from what storage holds. Possible sources include a truncated HTTP response from a workflow-server ref endpoint, an edge-cache miss returning a partial 200, or a proxy drop during streaming. A truncated body whose first 4 bytes happen to still spell `encr` produces the exact "auth tag mismatch" symptom.
34
+ 1. **Ciphertext mutation or truncation in transit.** The encrypted payload reached the SDK with bytes that differ from what storage holds. Possible sources include a truncated HTTP response from a world backend ref endpoint, an edge-cache miss returning a partial 200, or a proxy drop during streaming. A truncated body whose first 4 bytes happen to still spell `encr` produces the exact "auth tag mismatch" symptom.
35
35
  2. **Key resolution mismatch.** The key used to decrypt is not the key that was used to encrypt, e.g. the run's `deploymentId` was not threaded through key resolution and the SDK fell back to the wrong deployment's key material.
36
36
  3. **Malformed encrypted envelope.** The envelope is too short to contain the GCM nonce (12 bytes) and auth tag (16 bytes), so decryption is rejected before it begins.
37
37
 
@@ -10,7 +10,7 @@ related:
10
10
  - /docs/api-reference/workflow-errors/workflow-not-registered-error
11
11
  ---
12
12
 
13
- This error occurs when the Workflow runtime tries to execute a workflow function that is not registered in the current deployment. When this happens, the run fails with a `RUNTIME_ERROR` error code.
13
+ This error occurs when the Workflow runtime tries to execute a workflow function that is not registered in the current deployment. When this happens, the run fails with the `WORKFLOW_NOT_REGISTERED` error code. Runs that failed on SDK versions before this code was introduced recorded `RUNTIME_ERROR` instead.
14
14
 
15
15
  ## Error message
16
16
 
@@ -136,7 +136,9 @@ callApi.maxRetries = 5; // Retry up to 5 times on failure (6 total attempts)
136
136
  <Callout type="info">
137
137
  Setting <code>maxRetries = 0</code> means the step will run once but will not
138
138
  be retried on failure. The default is <code>maxRetries = 3</code>, meaning the
139
- step can run up to 4 times total (1 initial attempt + 3 retries).
139
+ step can run up to 4 times total (1 initial attempt + 3 retries). Inside the
140
+ step, <code>getStepMetadata().maxAttempts</code> is that total, so a step can
141
+ <a href="/docs/api-reference/workflow/get-step-metadata#example-handle-the-last-attempt-differently">handle its last attempt differently</a>.
140
142
  </Callout>
141
143
 
142
144
  ## Serialization failures
@@ -211,6 +213,7 @@ try {
211
213
  | `STREAM_ERROR` | Workflow stream infrastructure failed while reading or writing data. This is an SDK or backend failure rather than an error in workflow code; retry the run and report persistent failures with the `runId` |
212
214
  | `WORLD_CONTRACT_ERROR` | A World response violated the SDK contract; points at a World implementation bug |
213
215
  | `DEPLOYMENT_MISMATCH` | The run was delivered to a deployment other than the one it is pinned to, and automatic re-routing did not recover it. See [deployment-mismatch](/docs/errors/deployment-mismatch) |
216
+ | `WORKFLOW_NOT_REGISTERED` | The deployment executing the run does not have the run's workflow registered. See [workflow-not-registered](/docs/errors/workflow-not-registered) |
214
217
  | `RUNTIME_ERROR` | An internal runtime error. If you see this, please [file an issue](https://github.com/vercel/workflow/issues) |
215
218
 
216
219
  <Callout type="info">
@@ -274,7 +277,3 @@ export async function placeOrderSaga(orderId: string) {
274
277
  }
275
278
  }
276
279
  ```
277
-
278
- ## Spec 9 (experimental)
279
-
280
- The experimental spec 9 runtime retries steps differently: a failed step is retried after about a second by default on its one queue message, and a `maxRetries = 0` step whose invocation dies after it started fails instead of running again. See [Retries on spec 9 runs](/docs/changelog/spec-9#retries).
@@ -116,10 +116,90 @@ async function updateUserStep(user: { id: string; name: string; email: string })
116
116
  }
117
117
  ```
118
118
 
119
+ <Callout>
120
+ Deeply frozen values are the exception: they come back frozen, and are stored by reference. See [Frozen values](#frozen-values).
121
+ </Callout>
122
+
119
123
  **Custom classes:**
120
124
 
121
125
  - Class instances that implement [`WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE`](#custom-class-serialization)
122
126
 
127
+ ## Frozen values
128
+
129
+ State that grows across steps, such as a conversation history passed into every step, is stored again by every step that receives it, so total storage grows with the square of the number of steps. If you pass that state as a **deeply frozen** value, Workflow stores each step's change instead:
130
+
131
+ - A step input that holds a value Workflow already stored is written as a reference to it, about 80 bytes.
132
+ - A step output is written as its change from the stored value it was made from, for example "the previous history plus two messages".
133
+
134
+ Workflow finds what changed by identity. A frozen object can't change, so an object that appears in both versions is unchanged and needs no comparison.
135
+
136
+ The easiest way to make deeply frozen values is [immer](https://immerjs.github.io/immer/)'s `produce`, which freezes its results and shares every unchanged object with the previous value:
137
+
138
+ ```typescript lineNumbers
139
+ import { produce } from "immer";
140
+
141
+ type Message = { role: "user" | "assistant"; content: string };
142
+ declare function reply(history: readonly Message[], text: string): Promise<string>; // @setup
143
+ declare const messages: AsyncIterable<{ text: string }>; // @setup
144
+
145
+ async function turn(history: readonly Message[], text: string) {
146
+ "use step";
147
+ const answer = await reply(history, text);
148
+ return produce(history, (draft) => {
149
+ draft.push({ role: "user", content: text }, { role: "assistant", content: answer });
150
+ });
151
+ }
152
+
153
+ export async function chat() {
154
+ "use workflow";
155
+ let history: readonly Message[] = Object.freeze([]);
156
+ for await (const { text } of messages) {
157
+ history = await turn(history, text); // each input is a reference, each output a change
158
+ }
159
+ }
160
+ ```
161
+
162
+ Without immer, freeze every object you create, and reuse the frozen objects you didn't change:
163
+
164
+ ```typescript lineNumbers
165
+ type Message = { role: "user" | "assistant"; content: string };
166
+ declare const history: readonly Message[]; // @setup
167
+ declare const text: string; // @setup
168
+
169
+ const next = Object.freeze([
170
+ ...history, // unchanged messages, already frozen, reused as they are
171
+ Object.freeze({ role: "user" as const, content: text }),
172
+ ]);
173
+ ```
174
+
175
+ ### Rules
176
+
177
+ - **Frozen values come back frozen.** Changing one in place throws a `TypeError`. Make the next version with `produce` (or a new frozen copy) instead.
178
+ - **`Date`, `Map`, `Set` and byte arrays are trusted.** Inside a frozen value they are treated as unchanging, even though JavaScript lets you change a `Date` or a `Map` after freezing. Change them only inside `produce` (see the note below).
179
+ - **Only deeply frozen plain data counts.** A value that isn't frozen, is only frozen at the top, or holds a class instance or another custom type, including inside a `Map` or `Set`, is stored in full.
180
+ - **Keep immer's auto-freeze on.** immer freezes what `produce` returns by default. With `setAutoFreeze(false)` its results aren't frozen, so they're stored in full every time: still correct, but the savings are gone. Turning it off is also how to opt a codebase out of storing values by reference.
181
+ - **A new value is linked by the objects it shares.** A value whose objects are all new, for example one made only of numbers and strings, is stored in full each time. That's fine for small values.
182
+ - **Some payloads are always stored in full:** run inputs, including values passed to another run through `start()`, workflow return values (so `run.returnValue` reads them as usual), and hook payloads.
183
+ - **Parallel steps.** Passing a frozen value to several parallel steps writes, in each step's input, a small reference if a step returned it unchanged, or only its change if you made the next version in workflow code with `produce` or `Object.freeze`. A frozen value built entirely in workflow code, sharing no objects with a step's output, is written in full to each input, because one step's input can't refer to another's.
184
+ - **A value is written whole again from time to time:** once its changes since the last whole copy pass half its size (for growing state, each time it doubles), or after 1,000 changes. That bounds how much a replay has to apply to about the value's own size.
185
+ - With `WORKFLOW_VM=quickjs`, values are stored in full, because that VM can't read references yet.
186
+
187
+ <Callout type="warn">
188
+ `Object.freeze` doesn't stop a `Map`, `Set` or `Date` from changing through its own methods (`map.set()`, `set.add()`, `date.setTime()`), and byte arrays can't be frozen at all. immer's `produce` makes the Maps and Sets it returns throw on those methods, but `Object.freeze` doesn't. Changing a `Date`, `Map`, `Set` or byte array in place inside a frozen value, for example with `date.setTime()`, `map.set()` or `bytes[0] = 1`, isn't recorded. A step that runs in the same invocation may still see the change, but a retried or queued step, and every replay, rebuilds the value from the stored records and sees the original. Make the change inside `produce` instead. Immer drafts a `Map` or `Set` once you call its `enableMapSet()`, and copies it when you change it. It doesn't draft a `Date` or a byte array, so replace those with new ones:
189
+
190
+ ```typescript
191
+ import { enableMapSet, produce } from "immer";
192
+ declare const state: { updatedAt: Date; tags: ReadonlySet<string> }; // @setup
193
+
194
+ enableMapSet(); // once, before producing state that holds a Map or Set
195
+
196
+ const next = produce(state, (draft) => {
197
+ draft.updatedAt = new Date(); // not draft.updatedAt.setTime(Date.now())
198
+ draft.tags.add("urgent"); // immer copies the Set
199
+ });
200
+ ```
201
+ </Callout>
202
+
123
203
  ## Streaming
124
204
 
125
205
  `ReadableStream` and `WritableStream` are supported as serializable types with special handling. These streams can be passed between workflow and step functions while maintaining their streaming capabilities.
@@ -308,6 +308,8 @@ Add the following to your `turbo.json`:
308
308
 
309
309
  Without this configuration, you may experience intermittent issues where workflows fail to register properly on cache hits, while working correctly on cache misses.
310
310
 
311
+ If you set [`workflows.experimentalRoutePrefix`](/docs/api-reference/workflow-next/with-workflow#workflow-route-prefix), include the prefix in these globs (for example `app/dashboard/.well-known/workflow/**`).
312
+
311
313
  ### `start()` says it received an invalid workflow function
312
314
 
313
315
  If you see this error:
@@ -172,6 +172,7 @@ Events are categorized by the entity type they affect. Each event contains metad
172
172
  | `run_completed` | Transitions the run to `completed` state with the workflow's return value. |
173
173
  | `run_failed` | Transitions the run to `failed` state with error details and optional error code. |
174
174
  | `run_cancelled` | Transitions the run to `cancelled` state. Can be triggered from `pending` or `running` states. |
175
+ | `attr_set` | Records attribute changes on the run, one event per [`setAttributes()`](/docs/api-reference/workflow/set-attributes) call. Contains the changes and their writer. A write from the workflow body carries a correlation ID; a write from a step body does not. Does not change the run's state. |
175
176
 
176
177
  ### Step events
177
178
 
@@ -207,7 +208,7 @@ Events are categorized by the entity type they affect. Each event contains metad
207
208
 
208
209
  ### How fast a log grows
209
210
 
210
- Counting the events above is how you size a run. A step that succeeds on the first attempt contributes three events; a retry adds another `step_started`, preceded by a `step_retrying` when the World emits one; a sleep contributes two, and a hook at least two.
211
+ Every action your run takes adds to the event log. For example, a step that succeeds on the first attempt contributes three events (`step_created`, `step_started`, `step_completed`). A retry adds another `step_started`, preceded by a `step_retrying` when the World emits one; a sleep contributes two events, and a hook at least two, plus one for each resume.
211
212
 
212
213
  A run's log is capped — the [Vercel World](/worlds/vercel#per-run-limits) fails anything past its ceiling with `MAX_EVENTS_EXCEEDED`. Replay reads the whole log, so a run gets slower as it grows and is worth splitting well before it fails: split into [child workflows](/cookbook/advanced/child-workflows) once a run would grow past a few thousand events. Runs on the QuickJS VM with snapshotting resume from a snapshot instead of replaying the whole log, and are exempt from the ceiling; see [max-events-exceeded](/docs/errors/max-events-exceeded). How much the growth costs depends on how often the run replays; [Steps and long runs](/docs/performance#steps-and-long-runs) shows how step-to-step overhead changes through a 1,020-step run.
213
214
 
@@ -304,7 +305,7 @@ A World that supports this returns the page in `events`, `cursor`, and `hasMore`
304
305
 
305
306
  ## Sealed positions (noop events)
306
307
 
307
- Runs at `specVersion` 7 and above use a *sealed log*. The backend gives each write its position from a per-run sequencer **before** the write commits, so concurrent writers hold distinct positions and never race for a slot. New runs use this behavior by default. [`WORKFLOW_SEALED_LOG=0`](/docs/configuration/runtime-tuning#workflow_sealed_log) returns a deployment to the previous scheme. Every runtime reads a sealed log regardless, and a run's version is fixed at creation, so changing the setting never affects an in-flight run. However, a writer can claim a position and then stop because of a crashed process or canceled transaction. This leaves a hole that no writer will fill, and a hole looks like an event the reader failed to load.
308
+ Runs at `specVersion` 7 and above use a *sealed log*. The backend gives each write its position from a per-run sequencer **before** the write commits, so concurrent writers hold distinct positions and never race for a slot. New runs use this behavior by default. [`WORKFLOW_SPEC_VERSION=6`](/docs/configuration/runtime-tuning#workflow_spec_version) returns a deployment to the previous scheme. Every runtime reads a sealed log regardless, and a run's version is fixed at creation, so changing the setting never affects an in-flight run. However, a writer can claim a position and then stop because of a crashed process or canceled transaction. This leaves a hole that no writer will fill, and a hole looks like an event the reader failed to load.
308
309
 
309
310
  The backend restores the dense log at read time by **sealing** these positions. Once a hole is provably abandoned, bounded by the commit time of later positions, the backend writes a `noop` event into it. Positions are assigned in order, so a committed later position proves how long the hole has been open. A `noop` occupies its position, and length-based completeness checks, cursors, and pagination all count it. It has no other effect:
310
311
 
@@ -372,7 +373,7 @@ All entities in the Workflow SDK use a consistent ID format: a 4-character prefi
372
373
 
373
374
  An event ID is a **slot number**: the event's 1-based position in the run's event log, zero-padded to the same width as a ULID. The world assigns it when the event is published, so two writers racing to append never claim the same position and a rejected write leaves no gap behind. Slots are dense, and unique only within a run, so an event ID identifies an event only when paired with its `runId`.
374
375
 
375
- Density is what lets a reader tell a complete log from an incomplete one by its length alone. A replay that loads a log with a position missing below the highest one it can see cannot tell an event that was never written from one it failed to read, so it fails the run with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) rather than replay across the hole. See [`WORKFLOW_SLOT_GAP_CHECK`](/docs/configuration/runtime-tuning#workflow_slot_gap_check).
376
+ Density is what lets a reader tell a complete log from an incomplete one by its length alone. A replay that loads a log with a position missing below the highest one it can see cannot tell an event that was never written from one it failed to read, so it fails the run with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) rather than replay across the hole.
376
377
 
377
378
  A slot ID carries no timestamp. Zero-padded decimal digits are a subset of the ULID alphabet, so a slot ID passes ULID validation and sorts correctly, but decoding its first 48 bits yields the Unix epoch instead of a creation time. Read `createdAt` on the event when you need to know when it was written, and don't decode the time from an `evnt_` ID you get back from an API, a log line, or a cursor.
378
379
 
@@ -383,7 +384,3 @@ Step-to-step overhead (STSO) measures the time the runtime adds between two step
383
384
  <MetricVideo metric="stso" />
384
385
 
385
386
  See [Step-to-step overhead](/docs/performance#step-to-step-overhead-stso) on the Performance page for how it's measured and the latest results.
386
-
387
- ## Spec 9 (experimental)
388
-
389
- The experimental spec 9 runtime writes the same event types with a different model: one orchestrator per run writes every decision behind an in-band fence, step and wait events are plain appends, and an inline step is created by its first `step_started`. See [The event log on spec 9 runs](/docs/changelog/spec-9#the-event-log).
@@ -206,7 +206,7 @@ Your integration can expose physical files, virtual modules, or framework-native
206
206
 
207
207
  ## Vercel queue configuration
208
208
 
209
- On Vercel, configure the flow function as the sole queue consumer. `getWorkflowQueueTrigger()` handles the optional queue namespace and `WORKFLOW_SEQUENTIAL_REPLAYS=1` behavior.
209
+ On Vercel, configure the flow function as the sole queue consumer. `getWorkflowQueueTrigger()` handles the optional queue namespace.
210
210
 
211
211
  ```typescript
212
212
  import { getWorkflowQueueTrigger } from "@workflow/builders";
@@ -235,7 +235,7 @@ The generated trigger listens to one topic family:
235
235
 
236
236
  Both orchestration messages and step messages use this topic family. A step message is distinguished by its payload, not by a second topic or function.
237
237
 
238
- If you construct the trigger yourself, add `maxConcurrency: 1` when `WORKFLOW_SEQUENTIAL_REPLAYS=1`. The exported `isSequentialReplaysEnabled()` helper implements that build-time check.
238
+ If you construct the trigger yourself, set no `maxConcurrency` on it. `isSequentialReplaysEnabled()` is deprecated and always returns `false`; remove any `maxConcurrency: 1` that depended on it.
239
239
 
240
240
  ## Security
241
241
 
@@ -2,6 +2,7 @@
2
2
  title: Internal
3
3
  description: Preview-only page for internal tools, draft changelogs, and testing utilities.
4
4
  type: overview
5
+ internal: true
5
6
  ---
6
7
 
7
8
  <Callout type="warn">
@@ -2,6 +2,7 @@
2
2
  title: Native Nitro v3 bundling for workflows
3
3
  description: Workflow routes are now bundled by Nitro v3, so steps run in your app's runtime and can call any server-side Nitro API.
4
4
  type: overview
5
+ internal: true
5
6
  ---
6
7
 
7
8
  # Native Nitro v3 bundling for workflows
@@ -2,6 +2,7 @@
2
2
  title: Local web UI in Nitro dev
3
3
  description: Inspect, monitor, and debug your workflow runs from the /_workflow route during Nitro development.
4
4
  type: overview
5
+ internal: true
5
6
  ---
6
7
 
7
8
  # Local web UI in Nitro dev
@@ -2,6 +2,7 @@
2
2
  title: Serializable AbortController and AbortSignal
3
3
  description: AbortController and AbortSignal now work across workflow and step boundaries using the standard Web API.
4
4
  type: overview
5
+ internal: true
5
6
  ---
6
7
 
7
8
  # Serializable AbortController and AbortSignal
@@ -47,6 +47,8 @@ in: open `/_workflow` while `nitro dev` is running. No separate command is requi
47
47
 
48
48
  In the runs table, select one or more runs and choose **Cancel** to cancel the batch in a single request. Runs that fail with a retryable error stay selected so you can retry them.
49
49
 
50
+ In a run's **Streams** tab, a byte stream that carries a PNG, JPEG, GIF, or WebP image is shown as an image preview, with a **Download Image** button for the original bytes.
51
+
50
52
  To share a link to a specific run without opening a browser, use the `--url`
51
53
  flag. It prints the dashboard deep link to stdout and exits (no browser, no
52
54
  local server), which is useful for scripts, PR comments, or automation. Add `--json` to
@@ -65,6 +67,8 @@ npx workflow inspect run <run_id> --backend vercel --url
65
67
  The Workflow SDK CLI can inspect data from any [World](/docs/deploying). By default, it inspects data in your local development environment. For example, if you are using Next.js to develop workflows locally, the
66
68
  CLI will find the data in your `.next/workflow-data/` directory.
67
69
 
70
+ On the Local World, the CLI and web UI also read the app's queue key from that directory and send it with every delivery to the app, for example when they start or recreate a run. Run them from the app's project directory (or set `WORKFLOW_LOCAL_DATA_DIR` to the app's data directory), and keep them on the same release as the app's `@workflow/world-local`. See [`WORKFLOW_QUEUE_AUTH`](/worlds/local#workflow_queue_auth).
71
+
68
72
  If you're deploying workflows to a production environment, but want to inspect the data by using the CLI, you can specify the world you are using by setting the `--backend` flag to your world's name or package name, e.g. `vercel`.
69
73
 
70
74
  <Callout>
@@ -46,11 +46,11 @@ The largest change in v5 has no API surface: the runtime does far less work per
46
46
 
47
47
  **Replay no longer downloads recorded step inputs.** Replay recomputes step arguments by re-running workflow code, so it reads the event log without the `input` of each step. For workflows that pass growing state into their steps, this removes the part of the replay transfer that grew quadratically with the run. Worlds opt in through [`resolveData: 'skip-step-inputs'`](/docs/api-reference/workflow-runtime/world/storage#eventslist), and Vercel Workflows supports it.
48
48
 
49
- **Resuming a hook takes one round trip instead of two.** `resumeHook()` writes the `hook_received` event and dispatches the queue message concurrently, with a `(runId, resumeId)` dedup constraint keeping the two writers converging on exactly one event. See [Resilient hook resumption](/docs/changelog/resilient-resume).
49
+ **Resuming a hook takes one round trip instead of two.** `resumeHook()` writes the `hook_received` event and dispatches the queue message concurrently, with a `(runId, resumeId)` dedup constraint keeping the two writers converging on exactly one event.
50
50
 
51
- **A suspension's writes go out as one batch.** The `step_created` and `wait_created` events a suspension produces are folded into a single durable write with a per-event outcome, instead of one request each, and a fan-out's inline step bodies start straight off that commit rather than each claiming its step first. This engages on Worlds that implement the batch API and can be turned off with [`WORKFLOW_BATCH_TRANSITIONS=0`](/docs/configuration/worlds#workflow_batch_transitions). See [Batched event writes](/docs/changelog/batched-event-writes).
51
+ **A suspension's writes go out as one batch.** The `step_created` and `wait_created` events a suspension produces are folded into a single durable write with a per-event outcome, instead of one request each, and a fan-out's inline step bodies start straight off that commit rather than each claiming its step first. This engages on Worlds that implement the batch API.
52
52
 
53
- **Concurrent writers no longer compete for a position in the log.** Each event's position used to be claimed by the write that filled it, so a wide fan-out serialized on that claim. Positions are now handed out ahead of the commit, which is what makes the fan-out above cheap. The cost is a position whose writer dies, which the backend closes with a `noop` event that replay steps over. Nothing about this is visible from workflow code; [`WORKFLOW_SEALED_LOG=0`](/docs/configuration/runtime-tuning#workflow_sealed_log) is the kill switch, and existing runs keep the scheme they were created on.
53
+ **Concurrent writers no longer compete for a position in the log.** Each event's position used to be claimed by the write that filled it, so a wide fan-out serialized on that claim. Positions are now handed out ahead of the commit, which is what makes the fan-out above cheap. The cost is a position whose writer dies, which the backend closes with a `noop` event that replay steps over. Nothing about this is visible from workflow code; [`WORKFLOW_SPEC_VERSION=6`](/docs/configuration/runtime-tuning#workflow_spec_version) creates new runs on the previous scheme, and existing runs keep the scheme they were created on.
54
54
 
55
55
  **Payloads are compressed** before they are encrypted and sent to the API. Repetitive payloads compress heavily; AI token streams average around 80% smaller. That is less stored data and less to move over the network.
56
56
 
@@ -185,10 +185,10 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
185
185
  - **Support for more frameworks.** [React Router](/docs/getting-started/react-router) (v7 and v8, via Nitro) and [NestJS](/docs/getting-started/nestjs) are now supported.
186
186
  - **A misrouted delivery no longer fails a run.** Runs are pinned to the deployment that created them. A delivery that arrives at a different deployment is now re-routed to the pinned one with backoff instead of failing, and only gives up with the new [`DEPLOYMENT_MISMATCH`](/docs/errors/deployment-mismatch) error once the recovery budget is spent. Nothing executes on the wrong deployment while this happens. In 4.x the same situation surfaced as an unexplained decryption failure.
187
187
  - **A run cannot be forked across environments.** `start()` stamps the environment it was called from onto the queue message, and a deployment refuses a delivery whose run was created in a different environment. Previously a preview client and a production deployment could each hold half of one run ID.
188
- - **An experimental QuickJS VM engine.** Set [`WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to run workflow functions in a QuickJS VM compiled to WebAssembly instead of `node:vm`, for platforms that do not provide `node:vm`. Replay semantics are identical, but the available globals are not: check the differences before switching an existing deployment. By default, an encrypted QuickJS run that passes 1,000 events resumes from a VM-memory snapshot instead of replaying its full event log (see [`WORKFLOW_SNAPSHOT_THRESHOLD`](/docs/configuration/runtime-tuning#workflow_snapshot_threshold)).
188
+ - **A QuickJS VM engine for long-running workflows.** Set [`WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to run workflow functions in a QuickJS VM compiled to WebAssembly instead of `node:vm`. Replay semantics are identical, and a few globals (such as `Intl` and `crypto.subtle`) move into steps. By default, an encrypted QuickJS run that passes 1,000 events resumes from a VM-memory snapshot instead of replaying its full event log, and is exempt from the default per-run event limit (see [`WORKFLOW_SNAPSHOT_THRESHOLD`](/docs/configuration/runtime-tuning#workflow_snapshot_threshold)). It also runs on platforms that do not provide `node:vm`.
189
189
  - **Experimental dynamic workflows.** Pass workflow source as a string to `start()` to run orchestration assembled after deployment over steps already deployed with your app. The code is stored with the run (encrypted on Vercel), so replays always execute the code the run started with. Off unless the deployment sets `WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS=1`. See [Dynamic Workflows](/docs/advanced/dynamic-workflows).
190
190
  - **A WebSocket transport for event and stream writes** on the Vercel World, which sends a run's event writes and stream writes over a socket instead of one HTTP request each. It is the default; set [`WORKFLOW_EVENTS_TRANSPORT=http`](/worlds/vercel#workflow_events_transport) or [`WORKFLOW_STREAMS_TRANSPORT=http`](/worlds/vercel#workflow_streams_transport) to opt out. Tracing is unaffected: each write still emits an `http POST` client span, synthesized around the frame, with the transport on `workflow.events.transport`.
191
- - **`await run.returnValue` waits instead of polling.** Reading a run's result long-polls the World until the run reaches a terminal status, rather than asking again on a fixed interval. A result is observed as soon as it exists, and an idle wait costs one open request instead of a request per tick. Worlds that do not implement the long poll keep the interval.
191
+ - **`await run.returnValue` waits instead of polling.** Reading a run's result long-polls the World until the run reaches a terminal status, rather than asking again on a fixed interval. A result is observed as soon as it exists, and an idle wait costs one open request instead of a request per tick. Worlds that do not implement the long poll keep the interval. Since 5.4.0, a parent awaiting a child run it started doesn't poll at all: it suspends on a system hook the child resumes when it finishes, so the wait uses no compute or worker slot. See [Child Workflows](/cookbook/advanced/child-workflows#how-the-parent-waits).
192
192
  - **An event arriving mid-replay no longer fails the run.** A hook resume or step completion landing while a replay is in flight used to be able to fail it with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log). Writes now come back with the events the replay had not seen, and the event is held for whichever part of the workflow awaits it. A run only fails when the log is genuinely missing a position.
193
193
 
194
194
  ## Breaking changes
@@ -45,6 +45,7 @@ interface WorldCapabilities {
45
45
  active: boolean;
46
46
  };
47
47
  maxConcurrency?: boolean;
48
+ experimental_queueHold?: boolean;
48
49
  inBandFence?: boolean;
49
50
  hookForceClaim?: boolean;
50
51
  dynamicWorkflowCode?: boolean;
@@ -67,7 +68,7 @@ interface World extends Storage, Queue, Streamer {
67
68
 
68
69
  `specVersion` is required. See [Declaring the spec version](#declaring-the-spec-version).
69
70
 
70
- The optional `capabilities` object advertises additional behavior, and every capability **fails closed**. A missing member means "unsupported," and the runtime keeps its conservative behavior. Set `hookRetention.active` to `true` only when the World implements hook token retention. Set `maxConcurrency` only when the World's queue supports `maxConcurrency`-limited consumption, which `WORKFLOW_SEQUENTIAL_REPLAYS=1` uses. Set `hookForceClaim` only when the World implements [hook token takeover](/worlds/upgrading-to-v5#new-optional-surface). Without it, `createHook({ experimental_force: true })` fails the workflow when it registers the hook. Set `dynamicWorkflowCode` only when the World persists `dynamicWorkflowCode` from `run_created` (and from a `run_started` that creates the run), echoes it on the created run, and returns it from `runs.get` with `resolveData: 'all'`. Without it, `start()` refuses [dynamic workflows](/docs/advanced/dynamic-workflows). The code is sent inline unless the World also implements `uploadDynamicWorkflowCode` for large definitions. Set `inBandFence` only when the World implements the [in-band writer fence](#optional-the-in-band-writer-fence). Set `atomicStartHook.active` only when the World implements [atomic start Hook admission](#optional-atomic-start-hook-admission). Without it, `start({ experimental_hook })` throws before it enqueues anything.
71
+ The optional `capabilities` object advertises additional behavior, and every capability **fails closed**. A missing member means "unsupported," and the runtime keeps its conservative behavior. Set `hookRetention.active` to `true` only when the World implements hook token retention. Set `maxConcurrency` only when the World's queue delivers a spec 9 run's orchestrator messages one at a time. Set `hookForceClaim` only when the World implements [hook token takeover](/worlds/upgrading-to-v5#new-optional-surface). Without it, `createHook({ experimental_force: true })` fails the workflow when it registers the hook. Set `dynamicWorkflowCode` only when the World persists `dynamicWorkflowCode` from `run_created` (and from a `run_started` that creates the run), echoes it on the created run, and returns it from `runs.get` with `resolveData: 'all'`. Without it, `start()` refuses [dynamic workflows](/docs/advanced/dynamic-workflows). The code is sent inline unless the World also implements `uploadDynamicWorkflowCode` for large definitions. Set `inBandFence` only when the World implements the [in-band writer fence](#optional-the-in-band-writer-fence). Set `atomicStartHook.active` only when the World implements [atomic start Hook admission](#optional-atomic-start-hook-admission). Without it, `start({ experimental_hook })` throws before it enqueues anything. Set `experimental_queueHold` only when `queue()` implements [holding a message for its sender](#optional-holding-a-message-for-its-sender-experimental). Without it, callers keep their own fallback and never ask for a hold.
71
72
 
72
73
  [Slot-numbered event IDs](#event-id-allocation) are a contract requirement rather than a capability, so there is no flag or fallback path.
73
74
 
@@ -99,9 +100,9 @@ export function createWorld(): World {
99
100
 
100
101
  The runtime checks this before it creates or replays anything and throws if the version is outside the range it supports, naming both the range and what your World declared. A version below the range means your World allocates event IDs the runtime cannot read positions out of; above it means your World speaks a protocol this runtime has not learned.
101
102
 
102
- `mintedSpecVersion()` returns the current spec version, or the slot-identity version when [`WORKFLOW_SEALED_LOG=0`](/docs/configuration/runtime-tuning#workflow_sealed_log) opts new runs out. Call it inside `createWorld()` so a process can create Worlds in both modes. It reads `process.env` by default; in a host without `process`, such as a browser, pass the environment as its argument.
103
+ `mintedSpecVersion()` returns the current spec version, or the version [`WORKFLOW_SPEC_VERSION`](/docs/configuration/runtime-tuning#workflow_spec_version) selects. Call it inside `createWorld()` so a process can create Worlds with different settings. It reads `process.env` by default; in a host without `process`, such as a browser, pass the environment as its argument.
103
104
 
104
- Calling it keeps the check passing across upgrades. It moves with the `@workflow/world` version your package resolves, so a spec bump raises your declaration and the runtime's requirement together. A hard-coded number, or `SPEC_VERSION_CURRENT`, which does not follow `WORKFLOW_SEALED_LOG`, leaves your World out of step. Keep `@workflow/world` in the same release channel as the `workflow` version your users install. See [Spec versions](/worlds/upgrading-to-v5#spec-versions) for what each version requires of a World.
105
+ Calling it keeps the check passing across upgrades. It moves with the `@workflow/world` version your package resolves, so a spec bump raises your declaration and the runtime's requirement together. A hard-coded number, or `SPEC_VERSION_CURRENT`, which does not follow `WORKFLOW_SPEC_VERSION`, leaves your World out of step. Keep `@workflow/world` in the same release channel as the `workflow` version your users install. See [Spec versions](/worlds/upgrading-to-v5#spec-versions) for what each version requires of a World.
105
106
 
106
107
  ## The event log model
107
108
 
@@ -236,7 +237,7 @@ Spec version 7 supports one alternative to allocate-at-commit for Worlds whose s
236
237
 
237
238
  The runtime skips `noop` events during replay. It never delivers them to a consumer or uses them to advance the deterministic clock, so a sealed log replays identically to one whose writers filled the holes. `noop` isn't user-creatable and is never sent to `events.create()`. Only your read path may write one. Worlds that allocate at the commit, through a synchronous counter or unique-constraint append, maintain perfect density and don't need sealing. `world-local` and `world-postgres` never seal, and a World that allocates at the commit is spec 7 compliant without additional work.
238
239
 
239
- The version a World stamps comes from `mintedSpecVersion()`: 8 by default or the slot-identity version (6) when [`WORKFLOW_SEALED_LOG=0`](/docs/configuration/runtime-tuning#workflow_sealed_log) disables it. Declare `mintedSpecVersion()` instead of a literal so your World moves with the fleet. A runtime other than the one that created a spec 7 run may read it, so readers must understand `noop` before anything stamps 7 in that environment.
240
+ The version a World stamps comes from `mintedSpecVersion()`: 8 by default, or the version [`WORKFLOW_SPEC_VERSION`](/docs/configuration/runtime-tuning#workflow_spec_version) selects, such as the slot-identity version (6). Declare `mintedSpecVersion()` instead of a literal so your World moves with the fleet. A runtime other than the one that created a spec 7 run may read it, so readers must understand `noop` before anything stamps 7 in that environment.
240
241
 
241
242
  `events.create()` params carry `eventCount`: how many events the writer held in the log it replayed from, which is the position it expects to land on minus one. Attempt `eventCount + 1`. When that position is taken, **do not reject the write**. Advance to the next free position, commit there, and return the events occupying the positions you skipped over on the success response, in `events` with a matching `cursor` and `hasMore`. The writer merges them into its own log and replays once, rather than paying a second round trip to discover it was behind. A caller with a stale count is the normal case for a fan-out, and rejecting it would serialize writes the runtime issues in parallel.
242
243
 
@@ -321,11 +322,15 @@ The Queue interface handles asynchronous workflow execution, including queued st
321
322
  interface Queue {
322
323
  getDeploymentId(): Promise<string>;
323
324
 
325
+ // How the runtime authenticates deliveries to the flow route. Optional:
326
+ // omitted means not checked. Required in SDK v6.
327
+ queueAuthMode?: 'loopback' | 'skip';
328
+
324
329
  queue(
325
330
  queueName: ValidQueueName,
326
331
  message: QueuePayload,
327
332
  opts?: QueueOptions
328
- ): Promise<{ messageId: MessageId | null }>;
333
+ ): Promise<QueueResult>; // { messageId: MessageId | null; experimental_hold?: QueueHoldResult }
329
334
 
330
335
  // Optional. Omit it and the runtime publishes one message at a time.
331
336
  queueBatch?(
@@ -354,6 +359,17 @@ interface Queue {
354
359
 
355
360
  `meta.messageId` should be stable across redeliveries of one message. The optional `meta.deliveryCount` is 1 on a message's first delivery and increments on every redelivery; leave it `undefined` when your queue cannot say. The optional `meta.createdAt` is when the message was first enqueued, unchanged across its redeliveries.
356
361
 
362
+ ### Authenticating deliveries
363
+
364
+ The Workflow SDK's flow route is mounted in the app like any other route, so a request from outside the app can reach it. Before it reads the body or touches any run, the runtime checks every request to that route against the World's `queueAuthMode` mode. The check runs in the flow route handler `@workflow/core` generates, not in `createQueueHandler()`, so a queue consumer's own route (served with `createQueueHandler()` and registered with `registerRoute()`) is not checked and must authenticate deliveries itself. The modes:
365
+
366
+ - `'loopback'`: for a queue that delivers back to the app's own flow route. The delivery must carry the app's queue key in the `QUEUE_AUTH_HEADER` (`x-workflow-auth`) header; a request without it gets a `401`, and no run is touched. "Loopback" means sent by the app's own processes, which share the key, not any request from `localhost`. The queue attaches the key to every delivery it sends, over HTTP or to an in-process handler, on every attempt. Set it when the delivery is sent, never store it with the message, and replace any copy a caller supplied in `opts.headers`. The runtime checks the key against the sources Worlds register with `setQueueAuthKeySource()` from `@workflow/utils`, one per data directory, accepting a key that matches any of them; when none is registered, it checks `getQueueAuthKey()`, a key held in memory by one process. `@workflow/world-local` registers the key in its data directory, which the app, the CLI and the web UI share (see [the Local World](/worlds/local#data-directory-layout)). A World whose queue reuses `@workflow/world-local`'s gets this for free. The mode is temporary: it exists while the Local World's queue delivers over the app's own HTTP route.
367
+ - `'skip'`: the runtime does not check. For a World whose platform guarantees that only its queue reaches the route, as the [Vercel World](/worlds/vercel#security) does with two layers: the route can be triggered only by Vercel Queues, and the handler receives only a message ID, and retrieves and leases the message through Vercel Queues. Declare `'skip'` only when both hold. `@workflow/world-postgres` declares it for now, until its messages are delivered in-process ([#5258](https://github.com/vercel/workflow/issues/5258)); its flow route accepts any well-formed request, so protect it at the network edge (see [the Postgres World](/worlds/postgres#protect-the-queue-route)).
368
+
369
+ A World that declares nothing is not checked, and the runtime logs a warning when its flow route starts (once, then at most once a minute when routes restart), saying the route is not authenticated and has to be protected at the network edge. The mode becomes required in SDK v6, so declare one now: `'loopback'` if the World's queue attaches the key, `'skip'` only when the route is protected as described above. Operators can turn the check off with [`WORKFLOW_QUEUE_AUTH=off`](/docs/configuration/runtime-tuning#workflow_queue_auth), except while dynamic workflows are enabled.
370
+
371
+ The runtime's `401` is marked: it carries the `x-workflow-auth-refused: 1` header (`QUEUE_AUTH_REFUSED_HEADER`) and `"code": "QUEUE_AUTH_REFUSED"` in its JSON body. A refused delivery carried a key other than the route's, for example one from before another process of the app wrote a new key. A queue that sees the marker (`isQueueAuthRefusal(response)` from `@workflow/utils`) should reload its key and retry at once if it changed, and otherwise retry a few times with a short backoff, then give the message up and log it once, rather than retry it for hours. A refused delivery reached no handler and touched no run, so retrying is safe, and it should not count as an attempt. `@workflow/world-local` gives up after 5 refusals its reload did not fix; a refusal followed by a new key is retried at once without counting, up to 16 times per message, after which it counts like any other. A `401` without the marker comes from something else in front of the app, such as a proxy, so keep retrying that one.
372
+
357
373
  ### Queue prefixes and delivery routes
358
374
 
359
375
  A queue name is a prefix followed by an id. The Workflow SDK uses the prefix `__wkf_workflow_`, or `__{namespace}_wkf_workflow_` when a queue namespace is set. A library that keeps its own runs in a World and consumes its own messages, such as a durable agent harness, uses a namespace of its own (`__agent_wkf_workflow_session`) so that its messages never reach the Workflow SDK's handler, and the Workflow SDK's never reach it.
@@ -435,6 +451,47 @@ type QueueBatchResult =
435
451
 
436
452
  Every message targets one logical `queueName`, but you may split the batch internally — by a transport cap, or by any per-message routing dimension you derive from the payload — as long as the returned order still matches the input. The runtime passes a distinct `idempotencyKey` per message, because its recovery for both a request-level failure and a retryable entry is to republish the whole batch.
437
453
 
454
+ ### Optional: holding a message for its sender (experimental)
455
+
456
+ `QueueOptions.experimental_hold` asks `queue()` to claim the message's first delivery for the process that sent it, before `queue()` returns. That process runs the message in the same request, and your queue is the crash backstop. The Workflow SDK runtime doesn't use it today; callers that drive a World directly do. Declare `capabilities.experimental_queueHold: true` only when you implement it. A World without it can ignore the option entirely: return `{ messageId }` with no `experimental_hold`, and callers treat the message as delivered by the queue.
457
+
458
+ {/* @skip-typecheck - interface definition, not runnable code */}
459
+ ```typescript
460
+ // QueueOptions.experimental_hold?: true | QueueHoldOptions (`true` means `{}`)
461
+ interface QueueHoldOptions {
462
+ consumerGroup?: string; // the group that would otherwise receive it
463
+ visibilityTimeoutSeconds?: number; // the hold's lease
464
+ }
465
+
466
+ type QueueHoldResult = HeldQueueMessage | NotHeldQueueMessage;
467
+
468
+ interface HeldQueueMessage {
469
+ readonly status: "held";
470
+ readonly messageId: MessageId;
471
+ readonly leaseExpiresAt: Date;
472
+ consume(handler: QueueHandler): Promise<void>;
473
+ release(delaySeconds?: number): Promise<void>;
474
+ }
475
+
476
+ interface NotHeldQueueMessage {
477
+ readonly status: "not_held";
478
+ readonly reason:
479
+ | "unsupported" | "deferred" | "lost" | "coalesced"
480
+ | "concurrency_limited" | "duplicate" | "error";
481
+ }
482
+ ```
483
+
484
+ When you implement it:
485
+
486
+ - **Accept `true` as `{}`.** `experimental_hold: true` asks for a hold with your defaults.
487
+ - **Return exactly one outcome per hold request.** Return `held` only when this process now owns the message's first delivery. In every other case return `not_held` with a reason, and make sure the message still gets delivered (or is covered by a delivery that's running).
488
+ - **Run `consume(handler)` as a delivery.** Use the same code path `createQueueHandler()` uses: the same `meta` (`deliveryCount: 1`), the same result rules (`{ timeoutSeconds }` redelivers the same message, a rejection retries), lease renewal while the handler runs, and an acknowledgment when it resolves.
489
+ - **Deliver a lapsed hold as usual.** If nothing renews the lease, deliver the message to `consumerGroup` about `visibilityTimeoutSeconds` after the last renewal, with the same `messageId` and the next `deliveryCount`.
490
+ - **Make `release(delaySeconds)` hand the message back.** It becomes visible again after `delaySeconds`.
491
+ - **Refuse what can't be held.** Throw a `TypeError` for a hold with `delaySeconds`. Don't hold a message pinned to another deployment: send it as usual and return `not_held` / `unsupported`. `queueBatch()` never holds.
492
+
493
+ `@workflow/world-vercel` implements this with Vercel Queues' send-and-hold. Its `queue()` and `createQueueHandler()` share one delivery callback, which is the simplest way to keep a held run and a pushed delivery identical.
494
+
438
495
  ### Queue names
439
496
 
440
497
  Queue names follow a specific pattern:
@@ -704,4 +761,4 @@ Your World will then appear on the [Worlds ecosystem](/worlds) page with its com
704
761
 
705
762
  ## Supporting spec 9 runs (experimental)
706
763
 
707
- Everything above is the contract for spec 8 runs, which every World needs. A World may also let its users opt in to the experimental spec 9 runtime (`WORKFLOW_SPEC_VERSION=9`). To do so it implements the [in-band writer fence](#optional-the-in-band-writer-fence), serializes each spec 9 run's orchestrator deliveries, follows the spec 9 queue and deduplication rules, declares `capabilities.inBandFence: true`, and passes it on as `mintedSpecVersion(process.env, { inBandFence: true })`. `mintedSpecVersion()` called with no options never returns 9, so a World that does none of this keeps creating spec 8 runs. See [Implementing spec 9 in a World](/docs/changelog/spec-9#implementing-spec-9-in-a-world) and [World contract changes](/docs/changelog/spec-9#world-contract-changes).
764
+ Everything above is the contract for spec 8 runs, which every World needs. A World may also let its users opt in to the experimental spec 9 runtime (`WORKFLOW_SPEC_VERSION=9`). To do so it implements the [in-band writer fence](#optional-the-in-band-writer-fence), serializes each spec 9 run's orchestrator deliveries, follows the spec 9 queue and deduplication rules, declares `capabilities.inBandFence: true`, and passes it on as `mintedSpecVersion(process.env, { inBandFence: true })`. `mintedSpecVersion()` called with no options never returns 9, so a World that does none of this keeps creating spec 8 runs.