@workflow/core 5.4.0 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/classify-error.d.ts +1 -1
  2. package/dist/classify-error.js +4 -4
  3. package/dist/private.d.ts.map +1 -1
  4. package/dist/private.js +11 -49
  5. package/dist/replay-payload-cache.d.ts +3 -0
  6. package/dist/replay-payload-cache.d.ts.map +1 -1
  7. package/dist/replay-payload-cache.js +4 -1
  8. package/dist/runtime/child-run-completion.d.ts +3 -2
  9. package/dist/runtime/child-run-completion.d.ts.map +1 -1
  10. package/dist/runtime/child-run-completion.js +109 -37
  11. package/dist/runtime/helpers.d.ts +4 -19
  12. package/dist/runtime/helpers.d.ts.map +1 -1
  13. package/dist/runtime/helpers.js +6 -21
  14. package/dist/runtime/invocations.d.ts +1 -1
  15. package/dist/runtime/out-of-band-observation.d.ts +25 -4
  16. package/dist/runtime/out-of-band-observation.d.ts.map +1 -1
  17. package/dist/runtime/out-of-band-observation.js +18 -9
  18. package/dist/runtime/queue-auth.d.ts +53 -0
  19. package/dist/runtime/queue-auth.d.ts.map +1 -0
  20. package/dist/runtime/queue-auth.js +149 -0
  21. package/dist/runtime/quickjs-log-view.d.ts +42 -0
  22. package/dist/runtime/quickjs-log-view.d.ts.map +1 -1
  23. package/dist/runtime/quickjs-log-view.js +90 -1
  24. package/dist/runtime/quickjs-runtime.d.ts +32 -0
  25. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  26. package/dist/runtime/quickjs-runtime.js +128 -68
  27. package/dist/runtime/resume-hook.d.ts.map +1 -1
  28. package/dist/runtime/resume-hook.js +10 -1
  29. package/dist/runtime/run.d.ts +3 -7
  30. package/dist/runtime/run.d.ts.map +1 -1
  31. package/dist/runtime/run.js +7 -17
  32. package/dist/runtime/runs.d.ts +2 -1
  33. package/dist/runtime/runs.d.ts.map +1 -1
  34. package/dist/runtime/runs.js +3 -2
  35. package/dist/runtime/spec8/constants.d.ts +1 -49
  36. package/dist/runtime/spec8/constants.d.ts.map +1 -1
  37. package/dist/runtime/spec8/constants.js +2 -65
  38. package/dist/runtime/spec8/delivery.d.ts.map +1 -1
  39. package/dist/runtime/spec8/delivery.js +21 -26
  40. package/dist/runtime/spec8/inline-steps-in-flight.d.ts +5 -5
  41. package/dist/runtime/spec8/inline-steps-in-flight.d.ts.map +1 -1
  42. package/dist/runtime/spec8/inline-steps-in-flight.js +6 -8
  43. package/dist/runtime/spec8/step-executor.d.ts +8 -0
  44. package/dist/runtime/spec8/step-executor.d.ts.map +1 -1
  45. package/dist/runtime/spec8/step-executor.js +17 -3
  46. package/dist/runtime/spec8/step-single-flight.d.ts +1 -1
  47. package/dist/runtime/spec8/step-single-flight.js +2 -2
  48. package/dist/runtime/spec8/suspension-handler.d.ts +1 -1
  49. package/dist/runtime/spec8/suspension-handler.d.ts.map +1 -1
  50. package/dist/runtime/spec8/suspension-handler.js +3 -4
  51. package/dist/runtime/spec9/consume-after-commit.d.ts +5 -1
  52. package/dist/runtime/spec9/consume-after-commit.d.ts.map +1 -1
  53. package/dist/runtime/spec9/consume-after-commit.js +8 -3
  54. package/dist/runtime/spec9/delivery.d.ts.map +1 -1
  55. package/dist/runtime/spec9/delivery.js +255 -101
  56. package/dist/runtime/spec9/in-band-writer.d.ts +7 -0
  57. package/dist/runtime/spec9/in-band-writer.d.ts.map +1 -1
  58. package/dist/runtime/spec9/in-band-writer.js +18 -3
  59. package/dist/runtime/spec9/live-feed.d.ts +55 -9
  60. package/dist/runtime/spec9/live-feed.d.ts.map +1 -1
  61. package/dist/runtime/spec9/live-feed.js +90 -13
  62. package/dist/runtime/spec9/log-index.d.ts +74 -0
  63. package/dist/runtime/spec9/log-index.d.ts.map +1 -0
  64. package/dist/runtime/spec9/log-index.js +199 -0
  65. package/dist/runtime/spec9/log-state.d.ts +26 -8
  66. package/dist/runtime/spec9/log-state.d.ts.map +1 -1
  67. package/dist/runtime/spec9/log-state.js +42 -14
  68. package/dist/runtime/spec9/quickjs-entrypoint.d.ts +18 -5
  69. package/dist/runtime/spec9/quickjs-entrypoint.d.ts.map +1 -1
  70. package/dist/runtime/spec9/quickjs-entrypoint.js +820 -44
  71. package/dist/runtime/spec9/run-ahead.d.ts +11 -2
  72. package/dist/runtime/spec9/run-ahead.d.ts.map +1 -1
  73. package/dist/runtime/spec9/run-ahead.js +3 -2
  74. package/dist/runtime/spec9/step-delivery.d.ts +35 -0
  75. package/dist/runtime/spec9/step-delivery.d.ts.map +1 -1
  76. package/dist/runtime/spec9/step-delivery.js +47 -1
  77. package/dist/runtime/spec9/step-executor.d.ts +8 -0
  78. package/dist/runtime/spec9/step-executor.d.ts.map +1 -1
  79. package/dist/runtime/spec9/step-executor.js +17 -3
  80. package/dist/runtime/spec9/step-handler.d.ts.map +1 -1
  81. package/dist/runtime/spec9/step-handler.js +43 -4
  82. package/dist/runtime/start-hook-binding.d.ts +7 -6
  83. package/dist/runtime/start-hook-binding.d.ts.map +1 -1
  84. package/dist/runtime/start-hook-binding.js +13 -10
  85. package/dist/runtime/start.d.ts +2 -2
  86. package/dist/runtime/start.js +3 -3
  87. package/dist/runtime/step-latency.js +2 -2
  88. package/dist/runtime/world-compatibility.d.ts +4 -4
  89. package/dist/runtime/world-compatibility.js +5 -5
  90. package/dist/runtime.d.ts.map +1 -1
  91. package/dist/runtime.js +47 -15
  92. package/dist/serialization/codec-devalue.d.ts.map +1 -1
  93. package/dist/serialization/codec-devalue.js +26 -1
  94. package/dist/serialization/codec.d.ts +15 -0
  95. package/dist/serialization/codec.d.ts.map +1 -1
  96. package/dist/serialization/codec.js +1 -1
  97. package/dist/serialization/state-recovery.d.ts +21 -0
  98. package/dist/serialization/state-recovery.d.ts.map +1 -0
  99. package/dist/serialization/state-recovery.js +104 -0
  100. package/dist/serialization/state-refs.d.ts +229 -0
  101. package/dist/serialization/state-refs.d.ts.map +1 -0
  102. package/dist/serialization/state-refs.js +981 -0
  103. package/dist/serialization/step.d.ts.map +1 -1
  104. package/dist/serialization/step.js +22 -4
  105. package/dist/serialization-format.d.ts +8 -15
  106. package/dist/serialization-format.d.ts.map +1 -1
  107. package/dist/serialization-format.js +41 -4
  108. package/dist/serialization.d.ts +5 -2
  109. package/dist/serialization.d.ts.map +1 -1
  110. package/dist/serialization.js +68 -6
  111. package/dist/state-resolver.d.ts +44 -0
  112. package/dist/state-resolver.d.ts.map +1 -0
  113. package/dist/state-resolver.js +40 -0
  114. package/dist/state.d.ts +56 -0
  115. package/dist/state.d.ts.map +1 -0
  116. package/dist/state.js +202 -0
  117. package/dist/step/get-step-metadata.d.ts +11 -0
  118. package/dist/step/get-step-metadata.d.ts.map +1 -1
  119. package/dist/step/get-step-metadata.js +1 -1
  120. package/dist/telemetry/semantic-conventions.d.ts +9 -1
  121. package/dist/telemetry/semantic-conventions.d.ts.map +1 -1
  122. package/dist/telemetry/semantic-conventions.js +8 -2
  123. package/dist/telemetry.d.ts +12 -0
  124. package/dist/telemetry.d.ts.map +1 -1
  125. package/dist/telemetry.js +27 -1
  126. package/dist/test-support/append-only-world.d.ts +23 -2
  127. package/dist/test-support/append-only-world.d.ts.map +1 -1
  128. package/dist/test-support/append-only-world.js +34 -8
  129. package/dist/test-support/orchestrator-harness.d.ts +2 -0
  130. package/dist/test-support/orchestrator-harness.d.ts.map +1 -1
  131. package/dist/version.d.ts +1 -1
  132. package/dist/version.js +2 -2
  133. package/dist/workflow/hook.d.ts +6 -0
  134. package/dist/workflow/hook.d.ts.map +1 -1
  135. package/dist/workflow/hook.js +20 -1
  136. package/dist/workflow.d.ts.map +1 -1
  137. package/dist/workflow.js +11 -3
  138. package/docs/api-reference/create-hook.mdx +2 -2
  139. package/docs/api-reference/get-step-metadata.mdx +19 -0
  140. package/docs/foundations/errors-and-retries.mdx +3 -1
  141. package/docs/foundations/serialization.mdx +80 -0
  142. package/docs/how-it-works/event-sourcing.mdx +2 -2
  143. package/package.json +19 -18
@@ -61,6 +61,25 @@ async function chargeUser(userId: string, amount: number) {
61
61
  <a href="/docs/foundations/idempotency">Idempotency</a> guide.
62
62
  </Callout>
63
63
 
64
+ ### Example: handle the last attempt differently
65
+
66
+ ```typescript lineNumbers
67
+ import { getStepMetadata } from "workflow";
68
+
69
+ async function welcomeUser(userId: string) {
70
+ "use step";
71
+ const { attempt, maxAttempts } = getStepMetadata();
72
+
73
+ try {
74
+ return await sendWelcomeEmail(userId);
75
+ } catch (error) {
76
+ if (attempt < maxAttempts) throw error; // [!code highlight]
77
+ console.error(`Giving up on the welcome email for ${userId}`, error);
78
+ return null;
79
+ }
80
+ }
81
+ ```
82
+
64
83
  ## API signature
65
84
 
66
85
  ### Parameters
@@ -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
@@ -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.
@@ -304,7 +304,7 @@ A World that supports this returns the page in `events`, `cursor`, and `hasMore`
304
304
 
305
305
  ## Sealed positions (noop events)
306
306
 
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.
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_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
308
 
309
309
  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
310
 
@@ -372,7 +372,7 @@ All entities in the Workflow SDK use a consistent ID format: a 4-character prefi
372
372
 
373
373
  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
374
 
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).
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.
376
376
 
377
377
  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
378
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workflow/core",
3
- "version": "5.4.0",
3
+ "version": "5.5.0",
4
4
  "description": "Core runtime and engine for Workflow SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -84,39 +84,40 @@
84
84
  "./_workflow": "./dist/workflow/index.js"
85
85
  },
86
86
  "dependencies": {
87
- "@aws-sdk/credential-provider-web-identity": "3.972.49",
87
+ "@aws-sdk/credential-provider-web-identity": "3.972.88",
88
88
  "@jridgewell/trace-mapping": "0.3.31",
89
- "@standard-schema/spec": "1.0.0",
89
+ "@standard-schema/spec": "1.1.0",
90
90
  "@types/ms": "2.1.0",
91
- "@vercel/functions": "^3.8.0",
92
- "@workflow/errors": "5.1.0",
91
+ "@vercel/functions": "^3.11.1",
92
+ "@workflow/errors": "5.1.1",
93
93
  "@workflow/serde": "5.0.0",
94
- "@workflow/utils": "5.0.2",
95
- "@workflow/world": "5.1.0",
96
- "@workflow/world-local": "5.2.1",
97
- "@workflow/world-vercel": "5.4.0",
98
- "acorn": "8.15.0",
94
+ "@workflow/utils": "5.1.0",
95
+ "@workflow/world": "5.2.0",
96
+ "@workflow/world-local": "5.3.0",
97
+ "@workflow/world-vercel": "5.5.0",
98
+ "acorn": "8.19.0",
99
99
  "debug": "4.4.3",
100
100
  "devalue": "6.0.3",
101
101
  "ms": "2.1.3",
102
102
  "quickjs-wasi": "3.4.0",
103
103
  "seedrandom": "3.0.5",
104
- "semver": "7.7.4",
105
- "ulid": "~3.0.1",
106
- "zod": "~4.5.4"
104
+ "semver": "7.8.6",
105
+ "ulid": "~3.0.2",
106
+ "zod": "~4.6.7"
107
107
  },
108
108
  "devDependencies": {
109
109
  "@opentelemetry/api": "1.9.0",
110
110
  "@opentelemetry/context-async-hooks": "1.30.1",
111
111
  "@opentelemetry/core": "1.30.1",
112
112
  "@opentelemetry/sdk-trace-base": "1.30.1",
113
- "@types/debug": "4.1.12",
114
- "@types/node": "22.19.0",
113
+ "@types/debug": "4.1.13",
114
+ "@types/node": "22.19.21",
115
115
  "@types/seedrandom": "3.0.8",
116
- "@types/semver": "7.7.1",
116
+ "@types/semver": "7.8.0",
117
117
  "@workflow/tsconfig": "5.0.0",
118
118
  "cross-env": "10.1.0",
119
119
  "genversion": "3.2.0",
120
+ "immer": "10.1.1",
120
121
  "typescript": "^6.0.3"
121
122
  },
122
123
  "peerDependencies": {
@@ -131,8 +132,8 @@
131
132
  "build": "genversion --es6 src/version.ts && node scripts/build-quickjs-assets.js && tsc",
132
133
  "dev": "genversion --es6 src/version.ts && tsc --watch",
133
134
  "clean": "tsc --build --clean && rm -rf dist src/version.ts docs ||:",
134
- "test": "cross-env WORKFLOW_TARGET_WORLD=local vitest run src e2e/utils.test.ts",
135
- "test:e2e": "vitest run e2e",
135
+ "test": "cross-env WORKFLOW_TARGET_WORLD=local vitest run --config=../../vitest.config.ts src e2e/utils.test.ts",
136
+ "test:e2e": "vitest run --config=../../vitest.config.ts e2e",
136
137
  "typecheck": "genversion --es6 src/version.ts && tsc --noEmit"
137
138
  }
138
139
  }