workflow 5.2.2 → 5.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -137,7 +137,11 @@ import { getHookByToken, resumeHook } from "workflow/api";
137
137
 
138
138
  export async function POST(request: Request) {
139
139
  const { token, data } = await request.json();
140
- const expectedEnv = process.env.VERCEL_ENV || "development";
140
+ // On Vercel the platform sets these: `VERCEL_TARGET_ENV` carries a custom
141
+ // environment's slug, where `VERCEL_ENV` reports `preview`. Running against
142
+ // the Local World, hooks are recorded as `local`.
143
+ const expectedEnv =
144
+ process.env.VERCEL_TARGET_ENV ?? process.env.VERCEL_ENV ?? "local";
141
145
 
142
146
  try {
143
147
  const hook = await getHookByToken(token); // [!code highlight]
@@ -120,8 +120,10 @@ carries the owning team, and this takes precedence over a `VERCEL_TOKEN` set in
120
120
  the function's environment. A `VERCEL_TOKEN` belongs to a *user* and carries no
121
121
  team, so authenticating with it scopes the lookup to that user's default team
122
122
  and fails with a 404 whenever that is not the team that owns the deployment.
123
- Outside a deployment (CLI, CI, the dashboard) `VERCEL_TOKEN` is still used;
124
- configure the World's `teamId` so the request is scoped explicitly.
123
+ Outside a deployment (CLI, CI, the dashboard) the SDK uses the World's
124
+ `token`, falling back to `VERCEL_TOKEN`; configure the World's `teamId` so the
125
+ request is scoped explicitly. See
126
+ [Starting runs from outside a deployment](/worlds/vercel#starting-runs-from-outside-a-deployment).
125
127
  </Callout>
126
128
 
127
129
  <Callout type="warn">
@@ -43,7 +43,7 @@ const world = await getWorld(); // [!code highlight]
43
43
  The World SDK is the low-level foundation that higher-level functions like [`getRun()`](/docs/api-reference/workflow-api/get-run) and [`start()`](/docs/api-reference/workflow-api/start) are built on. Use it when you need capabilities beyond what those functions provide.
44
44
  </Callout>
45
45
 
46
- Beyond these namespaces, the `World` interface carries several top-level members for World authors: `specVersion`, `capabilities`, lifecycle hooks (`start()`/`close()`), `getEncryptionKeyForRun()`, and the optional `createRunId()` / `describeRun()` hooks behind regional run placement and World-specific `inspect` output. [Building a World](/worlds/building-a-world) documents these members.
46
+ Beyond these namespaces, the `World` interface carries several top-level members for World authors: `specVersion`, `capabilities`, lifecycle hooks (`start()`/`close()`), `getEncryptionKeyForRun()`, and the optional `createRunId()` / `regionForRunId()` / `describeRun()` hooks behind regional run placement and World-specific `inspect` output. [Building a World](/worlds/building-a-world) documents these members.
47
47
 
48
48
  ## Data hydration
49
49
 
@@ -70,6 +70,8 @@ The `resilientStart` flag is not set on the `Run` instance in this case (409 is
70
70
 
71
71
  The normal `run_created` path and the resilient start path can race on creating the run entity. In `world-local`, both paths use `writeExclusive` (O_CREAT|O_EXCL), atomic at the OS level, so exactly one writer wins and the other gets EEXIST. The normal path throws `EntityConflictError` on conflict (handled by `start()` as 409); the resilient start path re-reads the run from disk on conflict.
72
72
 
73
+ Local World now restores a lost `run_created` from the run record before the run's first lifecycle event.
74
+
73
75
  In `world-postgres`, the resilient start path uses `onConflictDoNothing` plus a re-read on conflict for the same effect, with the same outcome on either side of the race.
74
76
 
75
77
  The narrow crash window in `world-postgres` between the run insert and the event insert is acceptable: if the run insert succeeds but the event insert crashes, the run exists and `run_started` will still proceed normally (the event log will be missing a `run_created` entry, but the run itself is functional).
@@ -12,6 +12,8 @@ The Workflow CLI uses flags first, then environment variables, then defaults or
12
12
 
13
13
  Vercel project and auth settings can often be inferred from `.vercel/project.json` and your Vercel CLI login.
14
14
 
15
+ Whichever way they are resolved, the CLI ends up building a Vercel World from an auth token plus a project ID, team ID, and environment — the same four values any external client needs. Set them explicitly when there is no interactive `vercel login` to infer from, or when writing your own script instead of using the CLI; see [Connecting from outside a deployment](/worlds/vercel#connecting-from-outside-a-deployment).
16
+
15
17
  ## Target backend
16
18
 
17
19
  ### `--backend` / `-b`
@@ -49,7 +51,7 @@ Vercel project and auth settings can often be inferred from `.vercel/project.jso
49
51
  - Environment variable: `WORKFLOW_VERCEL_ENV`
50
52
  - Default: `production`
51
53
  - Vercel environment for `--backend vercel`.
52
- - Accepts `production` or `preview`.
54
+ - Accepts `production` or `preview`; any other value, including one set through `WORKFLOW_VERCEL_ENV`, is rejected. To reach a custom environment, configure the World programmatically with the environment's slug instead; see [Connecting from outside a deployment](/worlds/vercel#connecting-from-outside-a-deployment).
53
55
 
54
56
  ## Web UI
55
57
 
@@ -74,6 +74,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
74
74
  - Positive-integer event limit reported by the Local World and enforced by the runtime as `MAX_EVENTS_EXCEEDED`.
75
75
  - The Local and Postgres Worlds also use it as the maximum number of events returned when `events.list()` is called without a limit. If more events exist, the response includes `hasMore: true` and a continuation cursor.
76
76
  - The Vercel World receives its event limit from the service; this environment variable does not override that service-owned value. See [Vercel World limits](/worlds/vercel#per-run-limits).
77
+ - Runs started on the QuickJS engine with snapshotting enabled (see [`WORKFLOW_SNAPSHOT_THRESHOLD`](#workflow_snapshot_threshold)) are exempt from this limit on the Local and Vercel Worlds. See [max-events-exceeded](/docs/errors/max-events-exceeded).
77
78
  - Invalid or non-positive values fall back to the default.
78
79
 
79
80
  ### `WORKFLOW_REPLAY_DIVERGENCE_MAX_RETRIES`
@@ -238,7 +239,8 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
238
239
  - Choosing a value: a restore costs roughly the same regardless of log length (tens of milliseconds to decompress and restore the heap, plus fetching the snapshot), while a full replay grows with the log (tens of milliseconds at a few hundred events, seconds at several thousand). Restoring starts to pay off at a few hundred events, so values in the hundreds suit most long-running workflows. Very low values mostly add snapshot saves to runs that replay quickly anyway.
239
240
  - Snapshots are an optimization, not a source of truth: the event log remains authoritative, and a missing, corrupt, oversized, or incompatible snapshot automatically falls back to a full replay. Snapshots over 32 MB uncompressed are not saved.
240
241
  - Set `0` to opt out and always replay the full event log.
241
- - Like `WORKFLOW_VM`, an explicitly set policy is stamped into the run's `executionContext` at start, so a run keeps the snapshot policy it started with. Runs without a stamped policy use the handler's value, or the default. `start()` rejects an invalid value. An invalid value on the workflow handler disables snapshotting with a warning.
242
+ - Like `WORKFLOW_VM`, the policy is stamped into the run's `executionContext` at start, so a run keeps the snapshot policy it started with. Runs started with `WORKFLOW_VM=quickjs` are stamped with this value, or the default when unset. Runs without a stamped policy use the handler's value, or the default. `start()` rejects an invalid value. An invalid value on the workflow handler disables snapshotting with a warning.
243
+ - Runs stamped with `workflowVm: "quickjs"` and a positive threshold are exempt from the default [per-run event limit](/docs/errors/max-events-exceeded) on the Local and Vercel Worlds.
242
244
  - A snapshot can only be restored by the exact QuickJS engine build that captured it. On Vercel, runs keep executing on the deployment they started on, so deploys don't affect in-flight snapshots. If your deployment serves in-flight runs from new code (for example, a self-hosted rolling update), an upgrade that changes the embedded engine makes every in-flight run fall back to a full replay at its next resume, all at once, before re-snapshotting at its next qualifying suspension. Plan for that one-time replay load when upgrading.
243
245
 
244
246
  What a snapshot contains, and how it is protected:
@@ -416,3 +418,4 @@ These variables are primarily for tests, debugging, or unusual deployments.
416
418
  - Lowers the per-run event ceiling supplied by the World. A run whose event log reaches the ceiling fails with `MAX_EVENTS_EXCEEDED`, which stops a runaway loop from growing its log without bound.
417
419
  - Clamp-down only: it never raises the World's limit, and it applies even when the World supplies none. With no World limit and no override, nothing is enforced.
418
420
  - The Local and Vercel Worlds both supply a limit; the Local World defaults to 25,000 and is configurable with [`WORKFLOW_MAX_EVENTS`](/docs/configuration/worlds#workflow_max_events). The Vercel World's ceiling is documented under [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits).
421
+ - QuickJS runs with snapshotting are exempt from the World's default limit, but this override still applies to them.
@@ -129,6 +129,7 @@ The Local World is the default outside Vercel and is intended for development.
129
129
 
130
130
  - Default: `25000`
131
131
  - Per-run event ceiling reported to the runtime. A run whose event log reaches it fails with `MAX_EVENTS_EXCEEDED`, bounding a runaway loop. See [`WORKFLOW_MAX_EVENTS_OVERRIDE`](/docs/configuration/runtime-tuning#workflow_max_events_override) for the runtime-side clamp.
132
+ - Runs started on the QuickJS engine with snapshotting enabled are exempt, matching the Vercel World. See [max-events-exceeded](/docs/errors/max-events-exceeded).
132
133
 
133
134
  ## Postgres World
134
135
 
@@ -146,6 +147,7 @@ The Postgres World is a self-hosted durable backend for long-running server proc
146
147
  - Environment variable: none
147
148
  - Default: new `pg.Pool`
148
149
  - Existing `pg.Pool` to use instead of constructing one from `connectionString`.
150
+ - The World attaches no `'error'` listeners to a pool you pass. Listen on the pool and on each client it connects, or a connection the server ends will end the process. See [passing a `pg.Pool`](/worlds/postgres#programmatic-configuration).
149
151
 
150
152
  ### `jobPrefix`
151
153
 
@@ -205,6 +207,8 @@ The Vercel World is configured automatically inside Vercel deployments. The plat
205
207
 
206
208
  Most applications should not set `WORKFLOW_VERCEL_*` variables on Vercel. They configure tooling that talks to a Vercel Workflow project from outside a deployment, such as the Workflow CLI, the web user interface (UI), continuous integration (CI), or tests. The runtime warns if these variables are set in a deployed Vercel Function because they do not control runtime configuration there.
207
209
 
210
+ The entries below are the individual knobs. For a walkthrough of authenticating a local script or a CI job with a Vercel auth token — which variables are needed together, and how to pass them to the World factory — see [Connecting from outside a deployment](/worlds/vercel#connecting-from-outside-a-deployment).
211
+
208
212
  Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, and `VERCEL_DEPLOYMENT_KEY` are read by the runtime inside Vercel deployments. Do not set them yourself; keep [system environment variables](/worlds/vercel#system-environment-variables) enabled for the project so that Vercel provides them.
209
213
 
210
214
  ### `token`
@@ -213,13 +217,14 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
213
217
  - CLI flag: `--authToken`
214
218
  - Default: inferred when possible
215
219
  - Vercel API token for external tooling. Keep it secret.
220
+ - Only meaningful alongside `projectConfig.projectId` and `projectConfig.teamId` — set all three together. Supplying both IDs but no token throws rather than failing later with a `401`.
216
221
 
217
222
  ### `projectConfig.environment`
218
223
 
219
224
  - Environment variable: `WORKFLOW_VERCEL_ENV`
220
225
  - CLI flag: `--env` or `-e`
221
226
  - Default: `production`
222
- - Vercel environment targeted by tooling. Accepts `production` or `preview`.
227
+ - Vercel environment targeted by tooling. Accepts `production`, `preview`, or a custom environment's **slug** — configure the slug, not the environment's ID.
223
228
 
224
229
  ### `projectConfig.projectId`
225
230
 
@@ -20,8 +20,8 @@ When a workflow run fails, its `errorCode` identifies the failure category. You
20
20
  | [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) | The run's event log cannot be replayed because it contains orphaned or mismatched events, a gap, or an unreadable stored payload. |
21
21
  | [`REPLAY_DIVERGENCE`](/docs/errors/replay-divergence) | One replay could not consume the event log deterministically. The runtime automatically retries before treating repeated divergence as a corrupted event log. |
22
22
  | `MAX_DELIVERIES_EXCEEDED` | The run exceeded the maximum number of queue deliveries, usually because a persistent failure kept causing redelivery. |
23
- | `MAX_EVENTS_EXCEEDED` | The run reached the World's per-run event limit. Split unbounded work into child workflows before reaching the limit. |
24
- | `REPLAY_TIMEOUT` | Workflow replay exceeded the configured duration limit. This measures workflow execution and event-log replay between step boundaries, not time spent inside step functions. |
23
+ | [`MAX_EVENTS_EXCEEDED`](/docs/errors/max-events-exceeded) | The run reached the World's per-run event limit. Run long-running workflows on the QuickJS VM with snapshotting, which is exempt from the default limit, or split unbounded work into child workflows. |
24
+ | [`REPLAY_TIMEOUT`](/docs/errors/replay-timeout) | Workflow replay exceeded the configured duration limit. This measures workflow execution and event-log replay between step boundaries, not time spent inside step functions. |
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. |
@@ -0,0 +1,80 @@
1
+ ---
2
+ title: max-events-exceeded
3
+ description: A workflow run reached the World's per-run event limit and was failed.
4
+ type: troubleshooting
5
+ summary: Run long-running workflows on the QuickJS VM with snapshotting, which is exempt from the default event limit, or split the work into child workflows.
6
+ prerequisites:
7
+ - /docs/how-it-works/event-sourcing
8
+ related:
9
+ - /docs/configuration/runtime-tuning#workflow_vm
10
+ - /docs/errors/replay-timeout
11
+ - /cookbook/advanced/child-workflows
12
+ ---
13
+
14
+ Every step, hook, sleep, and lifecycle transition adds events to a run's [event log](/docs/how-it-works/event-sourcing). The World supplies a per-run ceiling on that log, and the runtime fails a run whose log reaches it with the `MAX_EVENTS_EXCEEDED` error code. The ceiling is a backstop against runaway loops that would otherwise grow a log without bound.
15
+
16
+ For the Vercel World's ceiling, see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits). The Local World's ceiling is set by [`WORKFLOW_MAX_EVENTS`](/docs/configuration/runtime-tuning#workflow_max_events).
17
+
18
+ ## Error message
19
+
20
+ ```text
21
+ Workflow exceeded the maximum of <limit> events per run
22
+ ├▶ hint: Run long-running workflows on the QuickJS VM with snapshotting by setting WORKFLOW_VM=quickjs ...
23
+ ╰▶ docs: https://workflow-sdk.dev/err/max-events-exceeded
24
+ ```
25
+
26
+ Before a run reaches the limit, the runtime logs a warning in your function logs at 50%, 80%, and 95% of the ceiling:
27
+
28
+ ```text
29
+ Workflow run is approaching the per-run event limit (<count> of <limit> events, 50%). ...
30
+ ```
31
+
32
+ ## Why it happens
33
+
34
+ - **The workflow is long-running by design.** Agents, chat sessions, and loops that wait on hooks or sleeps for days accumulate events with every iteration.
35
+ - **The workflow has unbounded work.** For example, a loop that keeps creating steps without a termination condition.
36
+
37
+ ## How to fix it
38
+
39
+ ### Run on the QuickJS VM with snapshotting
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.
43
+ </Callout>
44
+
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.
46
+
47
+ Set `WORKFLOW_VM=quickjs` in the environment that starts runs (the process that calls [`start()`](/docs/api-reference/workflow-api/start)). On Vercel that's your project's environment variables:
48
+
49
+ ```bash
50
+ WORKFLOW_VM=quickjs
51
+ ```
52
+
53
+ Snapshotting is on by default under QuickJS. Leave [`WORKFLOW_SNAPSHOT_THRESHOLD`](/docs/configuration/runtime-tuning#workflow_snapshot_threshold) unset, or set it to a positive integer. `WORKFLOW_SNAPSHOT_THRESHOLD=0` disables snapshotting, and those runs keep the limit.
54
+
55
+ A run qualifies when its `executionContext` records `workflowVm: "quickjs"` and a positive `snapshotThreshold`. `start()` records both when the run is created, so:
56
+
57
+ - Only runs started after the change are exempt. Runs keep the VM and snapshot policy they started with.
58
+ - Runs that have already failed with `MAX_EVENTS_EXCEEDED` are not revived. Start them again.
59
+ - On the Local World and Postgres World, snapshots are only stored when [`WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED=1`](/docs/configuration/runtime-tuning#workflow_snapshot_allow_unencrypted) is set. Without it, exempt runs still replay the full log on every invocation.
60
+
61
+ ### Split the work into child workflows
62
+
63
+ If a run doesn't need to be a single long-lived run, start [child workflows](/cookbook/advanced/child-workflows) for each batch or session and keep the parent's log small. This also works on the default engine.
64
+
65
+ ### Fix unbounded loops
66
+
67
+ If the run wasn't expected to grow this large, check the workflow function for loops that create steps, hooks, or sleeps without terminating.
68
+
69
+ ## This error cannot be caught
70
+
71
+ `MAX_EVENTS_EXCEEDED` is recorded by the runtime, not thrown into your workflow function. Check the run status from outside instead:
72
+
73
+ ```typescript lineNumbers
74
+ import { getRun } from "workflow/api";
75
+
76
+ const run = getRun("wrun_abc123");
77
+ if ((await run.status) === "failed") {
78
+ console.error("Run failed");
79
+ }
80
+ ```
@@ -0,0 +1,48 @@
1
+ ---
2
+ title: replay-timeout
3
+ description: Workflow replay exceeded its time budget on repeated deliveries and the run was failed.
4
+ type: troubleshooting
5
+ summary: Reduce replay cost by running on the QuickJS VM with snapshotting, or by moving heavy synchronous work out of the workflow function.
6
+ prerequisites:
7
+ - /docs/how-it-works/event-sourcing
8
+ related:
9
+ - /docs/configuration/runtime-tuning#workflow_replay_timeout_ms
10
+ - /docs/errors/max-events-exceeded
11
+ ---
12
+
13
+ Each time a run resumes, the runtime re-runs the workflow function against the recorded [event log](/docs/how-it-works/event-sourcing) to rebuild its state. That replay has a time budget per handler invocation ([`WORKFLOW_REPLAY_TIMEOUT_MS`](/docs/configuration/runtime-tuning#workflow_replay_timeout_ms)). Time spent inside `"use step"` bodies doesn't count against it.
14
+
15
+ When replay exceeds the budget, the delivery is retried. After [`WORKFLOW_REPLAY_TIMEOUT_MAX_RETRIES`](/docs/configuration/runtime-tuning#workflow_replay_timeout_max_retries) attempts, the run is failed with the `REPLAY_TIMEOUT` error code.
16
+
17
+ ## Error message
18
+
19
+ ```text
20
+ Workflow replay exceeded maximum duration (240s) after 4 attempts
21
+ ├▶ hint: Replay time grows with the size of the event log. Run long-running workflows on the QuickJS VM with snapshotting ...
22
+ ╰▶ docs: https://workflow-sdk.dev/err/replay-timeout
23
+ ```
24
+
25
+ ## Why it happens
26
+
27
+ - **The event log is very large.** On the default engine, replay time grows with the number of events in the run.
28
+ - **The workflow function does heavy synchronous work** outside of steps, such as parsing large payloads or tight loops.
29
+
30
+ ## How to fix it
31
+
32
+ ### Run on the QuickJS VM with snapshotting
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.
36
+ </Callout>
37
+
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).
39
+
40
+ Set `WORKFLOW_VM=quickjs` in the environment that starts runs. Snapshotting is on by default under QuickJS. Only runs started after the change use the new engine. See [max-events-exceeded](/docs/errors/max-events-exceeded#run-on-the-quickjs-vm-with-snapshotting) for the full eligibility rules.
41
+
42
+ ### Move heavy work into steps
43
+
44
+ Steps run with full Node.js access, their results are recorded once, and replay reuses those results without re-running the body. Move expensive parsing, transformation, and computation out of the workflow function into steps.
45
+
46
+ ### Raise the budget
47
+
48
+ As a short-term mitigation, raise [`WORKFLOW_REPLAY_TIMEOUT_MS`](/docs/configuration/runtime-tuning#workflow_replay_timeout_ms). This doesn't reduce replay cost, which keeps growing with the log on the default engine.
@@ -38,7 +38,9 @@ Two ways to reach it:
38
38
  error rather than treating it as an edge case. See
39
39
  [Data retention](/docs/observability/retention).
40
40
  - **The run simply aged out.** It finished long enough ago that the World's
41
- default retention window has passed.
41
+ default retention window has passed. For the Vercel World's retention
42
+ rules, see the
43
+ [Vercel Workflows docs](https://vercel.com/docs/workflows/retention).
42
44
 
43
45
  ## How to respond
44
46
 
@@ -201,9 +201,9 @@ try {
201
201
  | Code | Meaning |
202
202
  | --- | --- |
203
203
  | `USER_ERROR` | An error thrown in your workflow or step code (including propagated step failures like `FatalError`) |
204
- | `MAX_EVENTS_EXCEEDED` | The run reached the World's per-run event ceiling (for the Vercel World, see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits)). Split unbounded loops into [child workflows](/cookbook/advanced/child-workflows) well before the ceiling; see [Vercel World limits](/worlds/vercel#per-run-limits) and [Limits](/docs/configuration/runtime-tuning#limits) |
204
+ | `MAX_EVENTS_EXCEEDED` | The run reached the World's per-run event ceiling (for the Vercel World, see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits)). Run long-running workflows on the QuickJS VM with snapshotting, which is exempt from the default ceiling, or split unbounded loops into [child workflows](/cookbook/advanced/child-workflows) well before the ceiling. See [max-events-exceeded](/docs/errors/max-events-exceeded) |
205
205
  | `MAX_DELIVERIES_EXCEEDED` | The run exceeded the maximum number of queue deliveries |
206
- | `REPLAY_TIMEOUT` | A workflow replay exceeded the maximum allowed duration |
206
+ | `REPLAY_TIMEOUT` | A workflow replay exceeded the maximum allowed duration. See [replay-timeout](/docs/errors/replay-timeout) |
207
207
  | `REPLAY_DIVERGENCE` | A replay could not consume the event log deterministically, usually because of non-deterministic workflow code. |
208
208
  | `CORRUPTED_EVENT_LOG` | The event log cannot be replayed: it contains orphaned or mismatched events, or one of its stored payloads is no longer readable from the World's storage. If you see this, please [file an issue](https://github.com/vercel/workflow/issues) |
209
209
  | `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` |
@@ -99,7 +99,7 @@ getEncryptionKeyForRun?(
99
99
  ): Promise<Uint8Array | undefined>;
100
100
  ```
101
101
 
102
- Use `getEncryptionKeyForRun(run)` when the run entity already exists. Use `getEncryptionKeyForRun(runId, context?)` in runtime paths like `start()` where the run has not been created yet but the world may still need context such as `deploymentId`.
102
+ Use `getEncryptionKeyForRun(run)` when the runtime already holds the run entity. Use `getEncryptionKeyForRun(runId, context?)` everywhere else: in paths like `start()` where the run does not exist yet, and in paths that have a run id but no reason to load the run's payloads, such as resolving the key for a stream read. Either way `context` carries whatever the World needs to find the key, such as `deploymentId`.
103
103
 
104
104
  To add encryption support to a custom `World`:
105
105
 
@@ -207,7 +207,7 @@ Events are categorized by the entity type they affect. Each event contains metad
207
207
 
208
208
  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.
209
209
 
210
- 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. 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.
210
+ 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.
211
211
 
212
212
  ## Terminal states
213
213
 
@@ -287,7 +287,7 @@ Both save a reload, so the rule for which writes send them is not about the even
287
287
  | `run_created` | `start()` | Nothing | No log exists yet. |
288
288
  | `run_started` | Replay, first write of a delivery | `eventCount` when a log is loaded; no cursor | The `run_started` response already carries the full log as a preload. |
289
289
  | `step_created`, `wait_created`, `hook_disposed`, `attr_set` | Suspension handler | `eventCount` | The handler keeps writing from this log and the replay resumes from it. |
290
- | `hook_created` | Suspension handler | `eventCount` and `sinceCursor` (only when the suspension creates exactly one hook) | The delta is how a hook whose payload already arrived resolves without another invocation. Two creates diffing against one cursor would give two deltas of which only the first could be taken. |
290
+ | `hook_created` | Suspension handler | `eventCount` and `sinceCursor` for a lone hook; independent concurrent Node.js registrations in a hooks-only suspension defer both | A lone create returns a delta. Concurrent registrations reconcile their committed events together and reload when the responses do not cover a consecutive history suffix. |
291
291
  | `hook_received` | Replay resuming a hook | `eventCount` | The replay continues from the log right after. |
292
292
  | `hook_received` | Webhook or `resumeHook()` | Nothing | Out-of-band. It enqueues a delivery that loads the log. |
293
293
  | `wait_completed` | Replay completing an elapsed wait | `eventCount` | The replay continues from the log right after. |
@@ -80,6 +80,8 @@ To inspect workflows running on Vercel, ensure you're logged in to the Vercel CL
80
80
  npx workflow inspect runs --backend vercel
81
81
  ```
82
82
 
83
+ Without an interactive `vercel login`, such as in CI, pass the auth token, project ID, team ID, and environment explicitly. See [Connecting from outside a deployment](/worlds/vercel#connecting-from-outside-a-deployment).
84
+
83
85
  When deployed to Vercel, workflow data is [encrypted end-to-end](/docs/how-it-works/encryption). Encrypted fields display as locked placeholders until you choose to decrypt them using the **Decrypt** button in the web UI or the `--decrypt` flag in the CLI.
84
86
 
85
87
  ## More observability features
@@ -15,6 +15,14 @@ each of its steps, the payloads on its event log, and anything written to its
15
15
  streams. How long that data is kept is decided by the World you are running
16
16
  on, not by the SDK.
17
17
 
18
+ <Callout type="info">
19
+ For the [Vercel World](/worlds/vercel), retention is documented in the
20
+ [Vercel Workflows docs](https://vercel.com/docs/workflows/retention): how long
21
+ run payloads stay readable and when they're deleted, how long run metadata is
22
+ kept, where run data is stored, and how to check whether a run's data has
23
+ expired.
24
+ </Callout>
25
+
18
26
  `experimental_retention` on [`start()`](/docs/api-reference/workflow-api/start)
19
27
  lets a run ask for a specific retention period, rather than the World's default.
20
28
 
@@ -205,7 +205,7 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
205
205
  | Default trace mode is `linked` | Update dashboards that assume one trace per run, or set `WORKFLOW_TRACE_MODE=continuous`. |
206
206
  | The event-creation precondition guard is gone | `WORKFLOW_PRECONDITION_GUARD` no longer exists, and no World in the SDK rejects a write for a stale snapshot. Remove the variable if you set it. A replay that is behind now learns what it missed from the write it makes next instead of from a rejection, and [`PreconditionFailedError`](/docs/api-reference/workflow-errors/precondition-failed-error) remains only for a custom World that would still rather refuse. |
207
207
  | Event IDs are slot numbers, not ULIDs | An event ID is now its 1-based position in the run's log (`evnt_00000000000000000000000042`). It is unique only within a run, so pair it with the `runId` as a key, and it carries no timestamp: decoding one yields the Unix epoch rather than a creation time, so read `createdAt` off the event instead. Other entity IDs are unchanged. See [Event IDs](/docs/how-it-works/event-sourcing#event-ids). |
208
- | A per-run event limit is enforced | The World supplies the ceiling; for the Vercel World see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits). A run that reaches it fails with `MAX_EVENTS_EXCEEDED`. Split unbounded loops into [child workflows](/cookbook/advanced/child-workflows). [`WORKFLOW_MAX_EVENTS`](/docs/configuration/runtime-tuning#workflow_max_events) tunes the ceiling on the Local and Postgres Worlds; the Vercel World's is service-owned and the variable does not override it. |
208
+ | A per-run event limit is enforced | The World supplies the ceiling; for the Vercel World see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits). A run that reaches it fails with `MAX_EVENTS_EXCEEDED`. Split unbounded loops into [child workflows](/cookbook/advanced/child-workflows), or run long-running workflows on the QuickJS VM with snapshotting, which is [exempt from the default ceiling](/docs/errors/max-events-exceeded). [`WORKFLOW_MAX_EVENTS`](/docs/configuration/runtime-tuning#workflow_max_events) tunes the ceiling on the Local and Postgres Worlds; the Vercel World's is service-owned and the variable does not override it. |
209
209
  | Stream writes flush the first chunk immediately | The leading-edge flush window defaults to `0` instead of 10ms. Restore a window with `streamFlushIntervalMs` or `WORKFLOW_STREAM_FLUSH_INTERVAL_MS`. |
210
210
  | The workflow sandbox is stricter about nondeterminism | `WeakRef`, `FinalizationRegistry`, `Atomics.waitAsync`, and async `WebAssembly` compilation are no longer available inside workflow functions, and `crypto.subtle.digest` computes synchronously (same results, deterministic timing). Move code that needs them into a step. |
211
211
  | `Date()` without `new` returns a string inside workflow functions | This matches the language spec, and 4.x returned a `Date` object. Use `new Date()` where you need the object. Subclassing `Date` now works, so libraries like `TZDate` keep their identity across the sandbox boundary. |
@@ -56,6 +56,7 @@ interface World extends Storage, Queue, Streamer {
56
56
  getEncryptionKeyForRun?(run: WorkflowRun): Promise<Uint8Array | undefined>;
57
57
  getEncryptionKeyForRun?(runId: string, context?: Record<string, unknown>): Promise<Uint8Array | undefined>;
58
58
  createRunId?(options?: Readonly<Record<string, unknown>>): string;
59
+ regionForRunId?(runId: string): string | null;
59
60
  describeRun?(run: Readonly<Record<string, unknown>>): Record<string, string | null> | null | Promise<Record<string, string | null> | null>;
60
61
  processExitTriggersQueueRedelivery?: boolean;
61
62
  }
@@ -73,20 +74,21 @@ The remaining optional members:
73
74
  - `start()` initializes background tasks (for example, queue polling); `close()` releases resources like connection pools and listeners.
74
75
  - `getEncryptionKeyForRun()` returns the AES-256 key used to encrypt data for a run; if it is not implemented, encryption is disabled.
75
76
  - `createRunId()` mints the ID for a new run. Implementations may embed World-specific metadata as long as the result remains a valid ULID. This is how [multi-region placement](/worlds/vercel#multi-region) works. `@workflow/world-vercel` reads `options.region` from the `start()` options and embeds a region tag. When omitted, the runtime generates a standard monotonic ULID.
77
+ - `regionForRunId()` is the inverse of `createRunId()` for Worlds that embed a region: it returns the region an existing run's data lives in, from the ID alone. `recreateRunFromExisting()` uses it so a replayed run lands in the original run's region. Return `null` for an ID you don't recognize; omit the method if your World has no regional dimension.
76
78
  - `describeRun()` returns world-specific display fields for a run (for example, a region decoded from its ID) that tooling like `workflow inspect` renders as extra columns. It must be cheap, tolerate missing fields, and never throw.
77
79
  - `processExitTriggersQueueRedelivery` tells the runtime how to handle an exhausted replay budget. When `true`, it exits and relies on queue redelivery. When `false` or absent, it attempts to write `run_failed` and returns.
78
80
 
79
81
  ### Declaring the spec version
80
82
 
81
- `specVersion` is the protocol version your World implements, and the version stamped on every run it creates. Export `SPEC_VERSION_CURRENT` from `@workflow/world` rather than writing a number:
83
+ `specVersion` is the protocol version your World implements, and the version stamped on every run it creates. Declare `mintedSpecVersion()` from `@workflow/world` rather than writing a number:
82
84
 
83
85
  {/* @skip-typecheck - partial World, the other members are elided */}
84
86
  ```typescript
85
- import { SPEC_VERSION_CURRENT } from '@workflow/world';
87
+ import { mintedSpecVersion } from '@workflow/world';
86
88
 
87
89
  export function createWorld(): World {
88
90
  return {
89
- specVersion: SPEC_VERSION_CURRENT,
91
+ specVersion: mintedSpecVersion(),
90
92
  // ...
91
93
  };
92
94
  }
@@ -94,7 +96,9 @@ export function createWorld(): World {
94
96
 
95
97
  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.
96
98
 
97
- Using the constant keeps that 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 leaves your World a version behind the next bump, and the runtime rejects it. Keep `@workflow/world` in the same release channel as the `workflow` version your users install.
99
+ `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.
100
+
101
+ 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.
98
102
 
99
103
  ## The event log model
100
104
 
@@ -235,6 +239,16 @@ The version a World stamps comes from `mintedSpecVersion()`: 8 by default or the
235
239
 
236
240
  Not every write carries `eventCount`, and a World is free to skip the report read for event types whose writer never holds a log to merge it into (the step executor's `step_started`, `step_retrying`, `step_completed`, and `step_failed`, and the run-terminal `run_completed`, `run_failed`, and `run_cancelled`). Which writes send `eventCount` or `sinceCursor`, and why, is tabulated in [Events returned on a write](/docs/how-it-works/event-sourcing#events-returned-on-a-write). When a write carries both, the `sinceCursor` delta is a superset of the report, so return the delta and skip the report.
237
241
 
242
+ Independent concurrent hook registrations in a hooks-only suspension deliberately omit `eventCount` and `sinceCursor`, even though the worker holds a loaded log. The Node.js runtime waits for every registration to settle and verifies that their returned events fill every position immediately after that log. A gap, incomplete response, or missing committed-event cursor keeps the normal history reload. Mixed suspensions, forced claims, and same-token lifecycle operations keep their usual catch-up parameters.
243
+
244
+ ### Optional: returning a committed-event cursor
245
+
246
+ An `events.create()` result may include `eventCursor`: a World-owned cursor that its own ascending `events.list()` accepts as an exclusive position immediately after the returned `event`. It is distinct from a history-page `cursor`, and does not assert that the caller has loaded earlier events.
247
+
248
+ Returning `eventCursor` opts into using the returned `event` as replay input. That event **must equal the event returned by `events.list()` for the same position and `resolveData` option**, including its stored `createdAt`, normalized `tokenRetentionUntil`, resolved metadata bytes, and any `hook_conflict` details such as `conflictingRunId` or `forceRefusedReason`. Return the persisted event rather than reconstructing it from the creation request.
249
+
250
+ The runtime uses the cursor only after proving that the committed responses extend its loaded prefix without a hole. This is optional: a World that omits `eventCursor` remains supported and retains the reload path. The runtime never interprets a World's cursor encoding.
251
+
238
252
  ### Optional: rejecting a stale write
239
253
 
240
254
  A replay writes events derived from the event log it loaded, so a write made from an event log that no longer matches the store can commit events no correct replay would produce. Rejecting one means answering `events.create()` with a `PreconditionFailedError` when the run's log already holds more events than the caller's `eventCount` says it had loaded.
@@ -246,7 +260,7 @@ Implement rejection when your store allocates positions outside the commit and c
246
260
  Two rules make this safe:
247
261
 
248
262
  - **Only reject on evidence.** If your record of a run's events is incomplete, expired, or cannot answer the question, accept the creation. A rejection must always indicate a real discrepancy because the runtime responds by discarding a replay.
249
- - **Accept a creation that carries no `eventCount`.** It came from a caller with no loaded log that could be stale, such as a queued step body or out-of-band writer, rather than a caller claiming the log is empty.
263
+ - **Accept a creation that carries no `eventCount`.** The caller is not claiming the log is empty. It may have no loaded log, as with a queued step body or out-of-band writer, or may deliberately defer catch-up until concurrent hook registrations settle. Without a count there is no evidence for count-based rejection; independent ownership checks and write fences still apply.
250
264
 
251
265
  A rejection may include the events the caller was missing as `{ events, cursor }` on the error's `details`. Include them only when you can prove that the set fully accounts for the discrepancy, isn't truncated, and contains only events from the run being written. The runtime merges them directly into the replay's event log, so incorrect data is worse than no delta. Otherwise, omit them, and the runtime performs a full reload.
252
266
 
@@ -68,6 +68,24 @@ bunx --package @workflow/world-postgres bootstrap
68
68
  The migration is idempotent and can safely be run as a post-deployment lifecycle script. Run it again when you upgrade `@workflow/world-postgres`: a release can add migrations that the upgraded World needs before it handles workflows.
69
69
  </Callout>
70
70
 
71
+ <Callout type="warn">
72
+ Migration 0027 converts every timestamp column to `timestamp with time zone`.
73
+ On a server whose time zone is UTC (the default on most hosted providers) it
74
+ only changes the catalog and rebuilds one small index, and the upgrade order
75
+ does not matter. On a server in another time zone it also rewrites each
76
+ `created_at` value from local time to the instant it recorded, about one
77
+ rewrite of each table, holding the tables' locks until it finishes. There, stop
78
+ the previous version's workers, run `bootstrap`, then start the upgraded app:
79
+ older versions read the converted columns shifted by the server's UTC offset,
80
+ so you cannot roll back past this migration either. If your app's connection
81
+ pool set a session time zone other than the server's, pass it to the migration
82
+ with `?options=-c%20workflow.legacy_timezone%3DEurope%2FBerlin` in the
83
+ connection string, or with `ALTER DATABASE ... SET workflow.legacy_timezone =
84
+ 'Europe/Berlin'` where your pooler drops startup `options`. The migration waits
85
+ at most 10 seconds for its locks; if a long transaction holds them,
86
+ `bootstrap` fails and can be run again.
87
+ </Callout>
88
+
71
89
  ## Starting the World
72
90
 
73
91
  ### Experimental invocation delivery
@@ -320,14 +338,31 @@ export default createWorld({
320
338
  });
321
339
  ```
322
340
 
323
- You can also pass an existing `pg.Pool` as `pool` instead of a connection string. On a pool it creates, the World logs and drops an idle connection that the database closes, for example on a restart. A pool you pass needs its own `pool.on("error", ...)` listener. Without one, Node.js throws the error as an uncaught exception and the process exits.
324
-
325
341
  Options passed to `createWorld()` take precedence over the environment variables above. Export the World from a module and point `WORKFLOW_TARGET_WORLD` at that module:
326
342
 
327
343
  ```bash title=".env"
328
344
  WORKFLOW_TARGET_WORLD="./my-world.ts"
329
345
  ```
330
346
 
347
+ You can also pass an existing `pg.Pool` as `pool` instead of a connection string. The World then leaves that pool's `'error'` events to you. A connection the server ends, in a restart, a failover or an idle timeout, emits one, and an `'error'` event with no listener ends the process. Listen on each client the pool connects as well as on the pool: pg-pool listens only on idle clients, and the World holds a checked-out client across a transaction's statements.
348
+
349
+ {/*@skip-typecheck: requires pg, which the docs type-check does not install*/}
350
+
351
+ ```typescript title="my-world.ts" lineNumbers
352
+ import { createWorld } from "@workflow/world-postgres";
353
+ import { Pool } from "pg";
354
+
355
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
356
+ pool.on("connect", (client) =>
357
+ client.on("error", (error) => console.error(error.message))
358
+ );
359
+ pool.on("error", () => {}); // An idle client's error, logged just above
360
+
361
+ export default createWorld({ pool });
362
+ ```
363
+
364
+ A pool the World creates from `connectionString` already has these listeners.
365
+
331
366
  ### Queue consumers other than the Workflow SDK
332
367
 
333
368
  The worker delivers every job over HTTP, and by default to the Workflow SDK's flow route, `/.well-known/workflow/v1/flow`. A library that consumes messages of its own on the same World, such as a durable agent harness, uses its own queue prefix (`__{namespace}_wkf_workflow_`) and registers where those go: `world.registerRoute(prefix, "/api/agent/queue")` to deliver them to its own route, or `world.registerHandler(prefix, handler)` to deliver them inside the process that took the job, without HTTP. A job keeps the prefix it was enqueued under and the route its producer had registered, so a worker in another process delivers it to the same place. Register before calling `start()`, which re-enqueues each active run to the queue namespace it recorded at creation (`executionContext.queueNamespace`).
@@ -145,6 +145,7 @@ None of this is required. Each entry is a hook the runtime uses if your World pr
145
145
  | `getRuntimeDeadline()` | The absolute time the current invocation will be terminated. The runtime derives its inline replay budget from this, so a host with a long function timeout gets more work per invocation. Without it, the budget is a flat two minutes. See [`WORKFLOW_V2_TIMEOUT_MS`](/docs/configuration/runtime-tuning#workflow_v2_timeout_ms). |
146
146
  | `getEnvironment()` | The environment your World's writes are attributed to. Must be synchronous, side-effect free, and match what the backend will actually apply. A wrong answer is worse than `undefined`, because callers use it to detect cross-environment mismatches. Worlds with a single tenant should omit it. |
147
147
  | `createRunId(options)` | Mints the bare run ID; the core adds the `wrun_` prefix. Return a valid ULID. You may embed World-specific metadata in it, as `@workflow/world-vercel` does with a region identifier. Read only the option keys you recognize and ignore the rest. |
148
+ | `regionForRunId(runId)` | The region an existing run's data lives in, decoded from its ID. Lets replays keep the original run's region. Omit it if your World has no regional dimension. |
148
149
  | `describeRun(run)` | World-specific display fields for observability surfaces. |
149
150
  | `getEncryptionKeyForRun()` | Returns a ready-to-use 32-byte AES-256 key. Without it, data is stored unencrypted. Two overloads: pass the `WorkflowRun` when you have it, or a `runId` plus opaque World context when the entity is not available locally. |
150
151
  | `resolveLatestDeploymentId()` | Resolves `deploymentId: 'latest'`. Only meaningful for Worlds where deployment routing exists. |
@@ -28,7 +28,7 @@ Vercel automatically:
28
28
  - Selects the Vercel World backend
29
29
  - Configures authentication using OIDC tokens
30
30
  - Provisions storage and queuing infrastructure
31
- - Isolates data per environment (production, preview, development)
31
+ - Isolates data per environment (production, preview, and any custom environments)
32
32
 
33
33
  <FluidComputeCallout />
34
34
 
@@ -69,6 +69,7 @@ Setting `WORKFLOW_TARGET_WORLD=vercel` is not a workaround. The Vercel World nee
69
69
  For complete details on pricing, usage limits, and included allotments on Vercel, see the official Vercel documentation:
70
70
 
71
71
  - **[Vercel Workflow](https://vercel.com/docs/workflows)**: Pricing details, concepts, and observability for Workflow on Vercel
72
+ - **[Vercel Workflow data retention](https://vercel.com/docs/workflows/retention)**: How long run data is kept, where it is stored, and how to delete it sooner
72
73
  - **[Vercel limits](https://vercel.com/docs/limits)**: Platform-wide limits, including Workflow-specific constraints
73
74
  - **[Vercel Hobby plan](https://vercel.com/docs/plans/hobby)**: Free-tier included usage for Workflow and other resources
74
75
 
@@ -80,6 +81,8 @@ The Vercel World caps how large a single run can get. It caps the run's [event l
80
81
 
81
82
  Treat both caps as backstops, not budgets. Replay cost grows with the log, so a run slows down well before it fails. We recommend splitting a run into [child workflows](/cookbook/advanced/child-workflows) once a run would grow past a few thousand events. Size for that recommendation rather than for the cap.
82
83
 
84
+ Runs started on the QuickJS engine with snapshotting enabled (`WORKFLOW_VM=quickjs`) are exempt from the event cap. Snapshotting keeps their resume cost flat as the log grows. See [max-events-exceeded](/docs/errors/max-events-exceeded).
85
+
83
86
  Vercel raises the per-run event and step limits on request, so an unusually large run that genuinely cannot be split is worth raising with support rather than working around.
84
87
 
85
88
  ## Multi-region
@@ -128,6 +131,12 @@ const run = await start(myWorkflow, [input], { region: "sfo1" });
128
131
  - Runs created by 4.x SDKs, including runs that existed before you upgraded, live in `iad1` and are unaffected by an upgrade. There is no migration.
129
132
  - **Hook tokens are currently stored in `iad1`** for every run, regardless of the run's region. The token-to-run mapping that powers [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) and [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) lives there so tokens without region information can always be resolved. Hook *payloads* are not affected. A received payload is recorded on the run's event log, which lives in the run's region like all other run data. This token placement may become a project-level setting in the future.
130
133
 
134
+ ## Data retention
135
+
136
+ Retention for the Vercel World is documented in the [Vercel Workflows docs](https://vercel.com/docs/workflows/retention): how long run payloads stay readable and when they're deleted, how long run metadata is kept, where run data is stored, and how to delete run data sooner.
137
+
138
+ To delete a run's payloads as soon as it finishes, start it with [`experimental_retention: 0`](/docs/observability/retention).
139
+
131
140
  ## Queue consumers other than the Workflow SDK
132
141
 
133
142
  The Vercel World delivers each queue message to the functions subscribed to its topic, not to a fixed path. The Workflow SDK's build integration subscribes the generated flow route to `__wkf_workflow_*` (or `__{namespace}_wkf_workflow_*`). A library that consumes messages of its own on the same World, such as a durable agent harness, uses its own queue prefix and subscribes its own route to that prefix's topics:
@@ -188,6 +197,143 @@ npx workflow inspect runs \
188
197
 
189
198
  Learn more in the [Observability](/docs/observability) documentation.
190
199
 
200
+ ## Connecting from outside a deployment
201
+
202
+ Inside a Vercel deployment there is nothing to authenticate: the platform injects a per-request OIDC token and the Vercel World uses it automatically. A process that is *not* a deployment has no such token — a script on your laptop, a CI job driving end-to-end tests against a preview, a one-off backfill. Those clients authenticate with a **Vercel auth token** instead. Vercel checks that token against your team and project permissions, and attributes the request to the environment you name.
203
+
204
+ <Callout type="warn">
205
+ Do not reuse the `VERCEL_OIDC_TOKEN` that `vercel env pull` writes into
206
+ `.env.local` as your Workflow credential. It is a local artifact of your
207
+ linked project, not a credential for the Workflow API: requests made with it
208
+ are attributed to the environment carried in the token itself, not to the
209
+ `production` or `preview` data you mean to reach. Authenticate with a Vercel
210
+ auth token instead. A pulled OIDC token is still the right thing for
211
+ [bypassing deployment
212
+ protection](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/trusted-sources)
213
+ when your script has to fetch a protected preview URL; that is a separate
214
+ credential from the one that talks to the Workflow API.
215
+ </Callout>
216
+
217
+ ### Environment variables
218
+
219
+ These four values are what an external client needs. The names are the convention shared by the `workflow` CLI and the web UI:
220
+
221
+ | Variable | Value | Notes |
222
+ | --- | --- | --- |
223
+ | `WORKFLOW_VERCEL_AUTH_TOKEN` | Vercel auth token | Keep it secret. Create one under [account settings → tokens](https://vercel.com/account/tokens), scoped to the team that owns the project. |
224
+ | `WORKFLOW_VERCEL_TEAM` | Vercel team ID (`team_...`) | Required. Set it together with the token and the project ID. |
225
+ | `WORKFLOW_VERCEL_PROJECT` | Vercel project ID (`prj_...`) | Required. Set it together with the token and the team ID. |
226
+ | `WORKFLOW_VERCEL_ENV` | `production`, `preview`, or a custom environment's slug | Defaults to `production`. See [`WORKFLOW_VERCEL_ENV`](#workflow_vercel_env). |
227
+
228
+ Both IDs are in `.vercel/project.json` after `vercel link` — `projectId` is the project, `orgId` the team or user that owns it — or on the project's settings page.
229
+
230
+ Three more are situational:
231
+
232
+ - `VERCEL_DEPLOYMENT_ID` — required to **start** runs, not to read them. See [Starting runs](#starting-runs-from-outside-a-deployment).
233
+ - `WORKFLOW_VERCEL_PROJECT_NAME` — the project slug, used only to build dashboard links.
234
+ - `VERCEL_TOKEN` — a fallback the World reads for the Vercel API calls it makes alongside your Workflow requests (fetching a run's encryption key, resolving `deploymentId: "latest"`). A client that passes `token` explicitly, as below, already covers those calls and does not need it.
235
+
236
+ For a custom environment, set `WORKFLOW_VERCEL_ENV` to the environment's **slug**, not its ID — the slug is what the consuming deployment compares against. The `workflow` CLI's `--env` flag reads the same variable but only accepts `production` or `preview`, so a custom environment is reachable from your own script, not from the CLI.
237
+
238
+ <Callout type="info">
239
+ The Workflow SDK does not read `WORKFLOW_VERCEL_*` from the environment on
240
+ your behalf — the runtime's own `createWorld()` deliberately ignores them, so
241
+ that a stray variable on a deployed project cannot redirect a live
242
+ application. Read them in your own code and pass them to the World factory,
243
+ as below. Setting them on a deployed Vercel project has no effect on runtime
244
+ configuration, and the runtime warns when it sees them there.
245
+ </Callout>
246
+
247
+ ### Wiring it up in a script
248
+
249
+ Build the Vercel World with an explicit config and install it with [`setWorld()`](/docs/api-reference/workflow-runtime/set-world) before the first `workflow/api` call:
250
+
251
+ {/*@skip-typecheck: incomplete code sample*/}
252
+
253
+ ```typescript title="scripts/start-run.ts" lineNumbers
254
+ import { start } from "workflow/api";
255
+ import { setWorld } from "workflow/runtime";
256
+ import { createWorld } from "@workflow/world-vercel";
257
+ import { myWorkflow } from "../workflows/my-workflow";
258
+
259
+ setWorld(
260
+ createWorld({
261
+ token: process.env.WORKFLOW_VERCEL_AUTH_TOKEN, // [!code highlight]
262
+ projectConfig: {
263
+ projectId: process.env.WORKFLOW_VERCEL_PROJECT, // [!code highlight]
264
+ teamId: process.env.WORKFLOW_VERCEL_TEAM, // [!code highlight]
265
+ environment: process.env.WORKFLOW_VERCEL_ENV, // [!code highlight]
266
+ },
267
+ })
268
+ );
269
+
270
+ const run = await start(myWorkflow, ["input"]);
271
+ console.log(run.runId);
272
+ ```
273
+
274
+ Supply `token`, `projectId`, and `teamId` together. Setting the two IDs without a token fails immediately, with a message naming the missing token, rather than surfacing later as an opaque `401`.
275
+
276
+ The same token authorizes the per-run key fetch that decrypts run and step data, so reads come back as values rather than opaque bytes — see [Encryption](/docs/how-it-works/encryption).
277
+
278
+ This is exactly what the `workflow` CLI does under the hood. It resolves the same four values — from `--authToken` / `--project` / `--team` / `--env`, then the `WORKFLOW_VERCEL_*` variables, then `.vercel/project.json` and your `vercel login` credentials — and constructs the World with them. Passing them explicitly is the non-interactive equivalent of being logged in and linked.
279
+
280
+ ### Starting runs from outside a deployment
281
+
282
+ [`start()`](/docs/api-reference/workflow-api/start) has to name a deployment, because a run executes the code of the deployment that created it. Inside a deployment that is the current one; outside, there is nothing to infer, so set `VERCEL_DEPLOYMENT_ID` to the deployment whose code should run the workflow:
283
+
284
+ ```bash
285
+ # `vercel inspect` prints the dpl_... ID for a deployment URL
286
+ vercel inspect https://my-app-abc123.vercel.app
287
+ ```
288
+
289
+ Reads such as [`getRun()`](/docs/api-reference/workflow-api/get-run) do not need it. `start(..., { deploymentId: "latest" })` does: it resolves the newest deployment sharing that deployment's environment, so it needs one to start from.
290
+
291
+ <Callout type="warn">
292
+ The environment you authenticate as and the deployment you target must
293
+ agree. A client that creates a run in `preview` but points it at a
294
+ production deployment creates a run that never executes: environments are
295
+ isolated from each other, so a deployment refuses work created in a
296
+ different one. If a run stays `pending` and the deployment logs a refusal
297
+ naming two environments, check `WORKFLOW_VERCEL_ENV` against the environment
298
+ of the deployment in `VERCEL_DEPLOYMENT_ID`.
299
+ </Callout>
300
+
301
+ ### In CI
302
+
303
+ Wait for the deployment under test, then hand its ID to the test step alongside the four auth variables:
304
+
305
+ ```yaml title=".github/workflows/e2e.yml" lineNumbers
306
+ jobs:
307
+ e2e:
308
+ runs-on: ubuntu-latest
309
+ permissions:
310
+ contents: read # check out the repository
311
+ deployments: read # find the deployment to wait for
312
+ statuses: read # read its deployment status and ID
313
+ steps:
314
+ - uses: actions/checkout@v4
315
+
316
+ - name: Wait for the Vercel deployment
317
+ id: deployment
318
+ uses: vercel/wait-for-deployment-action@0e2b0c5c5cce31f1648108aeec56467187aca037
319
+ with:
320
+ project-slug: my-app
321
+ environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
322
+
323
+ - name: Run end-to-end tests
324
+ run: pnpm test:e2e
325
+ env:
326
+ WORKFLOW_VERCEL_AUTH_TOKEN: ${{ secrets.VERCEL_TOKEN }}
327
+ WORKFLOW_VERCEL_TEAM: team_xxxxxxxxxxxxxxxx
328
+ WORKFLOW_VERCEL_PROJECT: prj_xxxxxxxxxxxxxxxx
329
+ WORKFLOW_VERCEL_ENV: ${{ github.ref == 'refs/heads/main' && 'production' || 'preview' }}
330
+ VERCEL_DEPLOYMENT_ID: ${{ steps.deployment.outputs.deployment-id }}
331
+ ```
332
+
333
+ Store the token as an encrypted secret and derive `WORKFLOW_VERCEL_ENV` from the branch, so a pull request run never authenticates as `production`.
334
+
335
+ If the deployment is behind deployment protection, the job also needs a way to reach its URL. Add `id-token: write` to the job's `permissions` and mint a short-lived OIDC token from the runner for the `x-vercel-trusted-oidc-idp-token` header; that credential is for [Trusted Sources](https://vercel.com/docs/deployment-protection/methods-to-bypass-deployment-protection/trusted-sources) only and is separate from the Vercel auth token above.
336
+
191
337
  ## Testing & compatibility
192
338
 
193
339
  <WorldTestingPerformance worldId="vercel" />
@@ -202,9 +348,11 @@ Most users never need to set the `WORKFLOW_VERCEL_*` variables below. They are o
202
348
 
203
349
  For example, you might set them when running `workflow inspect runs --backend vercel` from CI without an interactive `vercel login`, or when running tests against a specific preview deployment. In normal local development, the CLI infers these values from your `.vercel` directory and Vercel CLI login. In a deployed Vercel function, these variables have no effect on runtime configuration, and the runtime warns if they are set there.
204
350
 
351
+ For the task-oriented version of this — which variables a local script or CI job needs, and how to hand them to the SDK — see [Connecting from outside a deployment](#connecting-from-outside-a-deployment).
352
+
205
353
  ### `WORKFLOW_VERCEL_ENV`
206
354
 
207
- The Vercel environment to target. Options: `production`, `preview`. Default: `production`.
355
+ The Vercel environment to target. Options: `production`, `preview`, or a custom environment's slug. Default: `production`. See [Environment variables](#environment-variables) for how a custom environment is resolved.
208
356
 
209
357
  ### `WORKFLOW_VERCEL_AUTH_TOKEN`
210
358
 
@@ -344,7 +492,7 @@ The client splits its own large requests, which needs a Vercel World backend tha
344
492
 
345
493
  ### Programmatic configuration
346
494
 
347
- `createWorld()` accepts explicit API configuration. It does not read `WORKFLOW_VERCEL_*` automatically, so pass the environment values yourself when you want a configured World module:
495
+ `createWorld()` accepts explicit API configuration. It does not read `WORKFLOW_VERCEL_*` automatically, so pass the environment values yourself when you want a configured World module. To configure a client at the point of use instead of through `WORKFLOW_TARGET_WORLD`, see [Wiring it up in a script](#wiring-it-up-in-a-script).
348
496
 
349
497
  {/*@skip-typecheck: incomplete code sample*/}
350
498
 
@@ -414,6 +562,6 @@ The Vercel World uses Vercel's infrastructure for workflow execution:
414
562
 
415
563
  - **Storage**: Workflow data is stored in Vercel's cloud with automatic replication and [end-to-end encryption](/docs/how-it-works/encryption)
416
564
  - **Queuing**: Steps are distributed across Vercel Functions through [Vercel Queues](https://vercel.com/docs/queues) with automatic retries and [consumer function security](#consumer-function-security)
417
- - **Authentication**: OIDC tokens provide secure, automatic authentication
565
+ - **Authentication**: OIDC tokens provide secure, automatic authentication inside deployments; clients outside one authenticate with a [Vercel auth token](#connecting-from-outside-a-deployment)
418
566
 
419
567
  For more details, see the [Vercel Workflow documentation](https://vercel.com/docs/workflows).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workflow",
3
- "version": "5.2.2",
3
+ "version": "5.2.3",
4
4
  "description": "Workflow SDK - Build durable, resilient, and observable workflows",
5
5
  "main": "dist/typescript-plugin.cjs",
6
6
  "type": "module",
@@ -58,19 +58,19 @@
58
58
  }
59
59
  },
60
60
  "dependencies": {
61
- "@workflow/astro": "5.0.5",
62
- "@workflow/cli": "5.0.5",
63
- "@workflow/core": "5.2.2",
64
- "@workflow/errors": "5.0.4",
61
+ "@workflow/astro": "5.0.6",
62
+ "@workflow/cli": "5.0.6",
63
+ "@workflow/core": "5.2.3",
64
+ "@workflow/errors": "5.0.5",
65
65
  "@workflow/typescript-plugin": "5.0.0",
66
66
  "@workflow/utils": "5.0.2",
67
67
  "ms": "2.1.3",
68
- "@workflow/next": "5.0.5",
69
- "@workflow/nest": "5.1.3",
70
- "@workflow/nitro": "5.0.5",
71
- "@workflow/nuxt": "5.0.5",
72
- "@workflow/sveltekit": "5.0.5",
73
- "@workflow/rollup": "5.0.5"
68
+ "@workflow/next": "5.0.6",
69
+ "@workflow/nest": "5.1.4",
70
+ "@workflow/nitro": "5.0.6",
71
+ "@workflow/nuxt": "5.0.6",
72
+ "@workflow/sveltekit": "5.0.6",
73
+ "@workflow/rollup": "5.0.6"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@types/ms": "2.1.0",