@workflow/web 5.0.0 → 5.0.1

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 (21) hide show
  1. package/build/client/assets/{arrow-up-right-jHPcOZmb.js → arrow-up-right-CIRm41Zm.js} +1 -1
  2. package/build/client/assets/{highlighted-body-B3W2YXNL-CBBI0JQ-.js → highlighted-body-B3W2YXNL-DQ3Je3B9.js} +1 -1
  3. package/build/client/assets/{home-BcIEUw9E.js → home-Dl1wTnFS.js} +3 -3
  4. package/build/client/assets/{loader-circle-HeezuKOU.js → loader-circle-CD4z6T9x.js} +1 -1
  5. package/build/client/assets/{manifest-a541ae9e.js → manifest-7d7b25b4.js} +1 -1
  6. package/build/client/assets/{mermaid-3ZIDBTTL-ClcCzUqi.js → mermaid-3ZIDBTTL-fKP9rqOT.js} +76 -3
  7. package/build/client/assets/{root-DLS5V7HU.js → root-ESATuWiF.js} +3 -3
  8. package/build/client/assets/{run-detail-DWoMKBqC.js → run-detail-ClvtUP5Y.js} +3 -3
  9. package/build/client/assets/{workflow-graph-viewer-syfKq6DB.js → workflow-graph-viewer-DWfB9i-1.js} +1 -1
  10. package/build/client/assets/{zstd-browser-decoder-D2p6f8lN.js → zstd-browser-decoder-Cg5apldO.js} +1 -1
  11. package/build/server/assets/{app-CLF3fhv7.js → app-DB1r_8VA.js} +1062 -280
  12. package/build/server/assets/{highlighted-body-B3W2YXNL-D21NaJQ0.js → highlighted-body-B3W2YXNL-CHWCmTRA.js} +1 -1
  13. package/build/server/assets/{index-DnTW8Yiv.js → index-B2Fjee_4.js} +1 -1
  14. package/build/server/assets/{index-y9xp70jn.js → index-CvPUU1wY.js} +63 -60
  15. package/build/server/assets/{mermaid-3ZIDBTTL-DlUUmZjL.js → mermaid-3ZIDBTTL-CNO9LDDa.js} +1 -1
  16. package/build/server/assets/{token-DXiZgST4.js → token-C2ZfbDqj.js} +1 -1
  17. package/build/server/assets/{token-util-BvEnPXwK.js → token-util-Df3UC21b.js} +1 -1
  18. package/build/server/assets/{wrapper-BsMfBV09.js → wrapper-D66LMJdl.js} +9 -9
  19. package/build/server/assets/{zstd-browser-decoder-d2YJZBik.js → zstd-browser-decoder-DF4c9PWF.js} +1 -1
  20. package/build/server/index.js +2 -2
  21. package/package.json +7 -7
@@ -13088,11 +13088,11 @@ function requireReactDomServerLegacy_node_production() {
13088
13088
  throw Error(
13089
13089
  "Expected the resume to render <" + node$jscomp$0[0] + "> in this slot but instead it rendered <" + name2 + ">. The tree doesn't match so React will fallback to client rendering."
13090
13090
  );
13091
- var childNodes = node$jscomp$0[2];
13091
+ var childNodes2 = node$jscomp$0[2];
13092
13092
  name2 = node$jscomp$0[3];
13093
13093
  keyOrIndex = task.node;
13094
13094
  task.replay = {
13095
- nodes: childNodes,
13095
+ nodes: childNodes2,
13096
13096
  slots: name2,
13097
13097
  pendingTasks: 1
13098
13098
  };
@@ -13114,7 +13114,7 @@ function requireReactDomServerLegacy_node_production() {
13114
13114
  abortRemainingReplayNodes(
13115
13115
  request2,
13116
13116
  key,
13117
- childNodes,
13117
+ childNodes2,
13118
13118
  name2,
13119
13119
  type,
13120
13120
  props
@@ -13168,10 +13168,10 @@ function requireReactDomServerLegacy_node_production() {
13168
13168
  break b;
13169
13169
  }
13170
13170
  } catch (error2) {
13171
- props.status = 4, childNodes = getThrownInfo(task.componentStack), replay = logRecoverableError(
13171
+ props.status = 4, childNodes2 = getThrownInfo(task.componentStack), replay = logRecoverableError(
13172
13172
  request2,
13173
13173
  error2,
13174
- childNodes
13174
+ childNodes2
13175
13175
  ), props.errorDigest = replay, task.replay.pendingTasks--, request2.clientRenderedBoundaries.push(props);
13176
13176
  } finally {
13177
13177
  task.blockedBoundary = parentBoundary, task.hoistableState = parentHoistableState, task.replay = previousReplaySet, task.keyPath = prevKeyPath;
@@ -13212,8 +13212,8 @@ function requireReactDomServerLegacy_node_production() {
13212
13212
  "Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render."
13213
13213
  );
13214
13214
  case REACT_LAZY_TYPE:
13215
- childNodes = node2._init;
13216
- node2 = childNodes(node2._payload);
13215
+ childNodes2 = node2._init;
13216
+ node2 = childNodes2(node2._payload);
13217
13217
  if (12 === request2.status) throw null;
13218
13218
  renderNodeDestructive(request2, task, node2, childIndex);
13219
13219
  return;
@@ -13222,13 +13222,13 @@ function requireReactDomServerLegacy_node_production() {
13222
13222
  renderChildrenArray(request2, task, node2, childIndex);
13223
13223
  return;
13224
13224
  }
13225
- null === node2 || "object" !== typeof node2 ? childNodes = null : (childNodes = MAYBE_ITERATOR_SYMBOL && node2[MAYBE_ITERATOR_SYMBOL] || node2["@@iterator"], childNodes = "function" === typeof childNodes ? childNodes : null);
13226
- if (childNodes && (childNodes = childNodes.call(node2))) {
13227
- node2 = childNodes.next();
13225
+ null === node2 || "object" !== typeof node2 ? childNodes2 = null : (childNodes2 = MAYBE_ITERATOR_SYMBOL && node2[MAYBE_ITERATOR_SYMBOL] || node2["@@iterator"], childNodes2 = "function" === typeof childNodes2 ? childNodes2 : null);
13226
+ if (childNodes2 && (childNodes2 = childNodes2.call(node2))) {
13227
+ node2 = childNodes2.next();
13228
13228
  if (!node2.done) {
13229
13229
  props = [];
13230
13230
  do
13231
- props.push(node2.value), node2 = childNodes.next();
13231
+ props.push(node2.value), node2 = childNodes2.next();
13232
13232
  while (!node2.done);
13233
13233
  renderChildrenArray(request2, task, props, childIndex);
13234
13234
  }
@@ -17725,11 +17725,11 @@ function requireReactDomServer_node_production() {
17725
17725
  throw Error(
17726
17726
  "Expected the resume to render <" + node$jscomp$0[0] + "> in this slot but instead it rendered <" + name2 + ">. The tree doesn't match so React will fallback to client rendering."
17727
17727
  );
17728
- var childNodes = node$jscomp$0[2];
17728
+ var childNodes2 = node$jscomp$0[2];
17729
17729
  name2 = node$jscomp$0[3];
17730
17730
  keyOrIndex = task.node;
17731
17731
  task.replay = {
17732
- nodes: childNodes,
17732
+ nodes: childNodes2,
17733
17733
  slots: name2,
17734
17734
  pendingTasks: 1
17735
17735
  };
@@ -17751,7 +17751,7 @@ function requireReactDomServer_node_production() {
17751
17751
  abortRemainingReplayNodes(
17752
17752
  request2,
17753
17753
  key,
17754
- childNodes,
17754
+ childNodes2,
17755
17755
  name2,
17756
17756
  type,
17757
17757
  props
@@ -17805,10 +17805,10 @@ function requireReactDomServer_node_production() {
17805
17805
  break b;
17806
17806
  }
17807
17807
  } catch (error2) {
17808
- props.status = 4, childNodes = getThrownInfo(task.componentStack), replay = logRecoverableError(
17808
+ props.status = 4, childNodes2 = getThrownInfo(task.componentStack), replay = logRecoverableError(
17809
17809
  request2,
17810
17810
  error2,
17811
- childNodes
17811
+ childNodes2
17812
17812
  ), props.errorDigest = replay, task.replay.pendingTasks--, request2.clientRenderedBoundaries.push(props);
17813
17813
  } finally {
17814
17814
  task.blockedBoundary = parentBoundary, task.hoistableState = parentHoistableState, task.replay = previousReplaySet, task.keyPath = prevKeyPath;
@@ -17849,8 +17849,8 @@ function requireReactDomServer_node_production() {
17849
17849
  "Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render."
17850
17850
  );
17851
17851
  case REACT_LAZY_TYPE:
17852
- childNodes = node2._init;
17853
- node2 = childNodes(node2._payload);
17852
+ childNodes2 = node2._init;
17853
+ node2 = childNodes2(node2._payload);
17854
17854
  if (12 === request2.status) throw null;
17855
17855
  renderNodeDestructive(request2, task, node2, childIndex);
17856
17856
  return;
@@ -17859,13 +17859,13 @@ function requireReactDomServer_node_production() {
17859
17859
  renderChildrenArray(request2, task, node2, childIndex);
17860
17860
  return;
17861
17861
  }
17862
- null === node2 || "object" !== typeof node2 ? childNodes = null : (childNodes = MAYBE_ITERATOR_SYMBOL && node2[MAYBE_ITERATOR_SYMBOL] || node2["@@iterator"], childNodes = "function" === typeof childNodes ? childNodes : null);
17863
- if (childNodes && (childNodes = childNodes.call(node2))) {
17864
- node2 = childNodes.next();
17862
+ null === node2 || "object" !== typeof node2 ? childNodes2 = null : (childNodes2 = MAYBE_ITERATOR_SYMBOL && node2[MAYBE_ITERATOR_SYMBOL] || node2["@@iterator"], childNodes2 = "function" === typeof childNodes2 ? childNodes2 : null);
17863
+ if (childNodes2 && (childNodes2 = childNodes2.call(node2))) {
17864
+ node2 = childNodes2.next();
17865
17865
  if (!node2.done) {
17866
17866
  props = [];
17867
17867
  do
17868
- props.push(node2.value), node2 = childNodes.next();
17868
+ props.push(node2.value), node2 = childNodes2.next();
17869
17869
  while (!node2.done);
17870
17870
  renderChildrenArray(request2, task, props, childIndex);
17871
17871
  }
@@ -23099,10 +23099,10 @@ function requireReactDomServerLegacy_node_development() {
23099
23099
  throw Error(
23100
23100
  "Expected the resume to render <" + node2[0] + "> in this slot but instead it rendered <" + name2 + ">. The tree doesn't match so React will fallback to client rendering."
23101
23101
  );
23102
- var childNodes = node2[2];
23102
+ var childNodes2 = node2[2];
23103
23103
  node2 = node2[3];
23104
23104
  name2 = task.node;
23105
- task.replay = { nodes: childNodes, slots: node2, pendingTasks: 1 };
23105
+ task.replay = { nodes: childNodes2, slots: node2, pendingTasks: 1 };
23106
23106
  try {
23107
23107
  renderElement(request2, task, keyPath, type, props, ref2);
23108
23108
  if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
@@ -23123,7 +23123,7 @@ function requireReactDomServerLegacy_node_development() {
23123
23123
  abortRemainingReplayNodes(
23124
23124
  props,
23125
23125
  request2,
23126
- childNodes,
23126
+ childNodes2,
23127
23127
  ref2,
23128
23128
  keyPath,
23129
23129
  node2,
@@ -23175,12 +23175,12 @@ function requireReactDomServerLegacy_node_development() {
23175
23175
  break a;
23176
23176
  }
23177
23177
  } catch (error2) {
23178
- props.status = CLIENT_RENDERED, childNodes = getThrownInfo(task.componentStack), replay = logRecoverableError(
23178
+ props.status = CLIENT_RENDERED, childNodes2 = getThrownInfo(task.componentStack), replay = logRecoverableError(
23179
23179
  request2,
23180
23180
  error2,
23181
- childNodes,
23181
+ childNodes2,
23182
23182
  task.debugTask
23183
- ), encodeErrorForBoundary(props, replay, error2, childNodes, false), task.replay.pendingTasks--, request2.clientRenderedBoundaries.push(props);
23183
+ ), encodeErrorForBoundary(props, replay, error2, childNodes2, false), task.replay.pendingTasks--, request2.clientRenderedBoundaries.push(props);
23184
23184
  } finally {
23185
23185
  task.blockedBoundary = parentBoundary, task.hoistableState = parentHoistableState, task.replay = previousReplaySet, task.keyPath = prevKeyPath;
23186
23186
  }
@@ -29727,10 +29727,10 @@ function requireReactDomServer_node_development() {
29727
29727
  throw Error(
29728
29728
  "Expected the resume to render <" + node2[0] + "> in this slot but instead it rendered <" + name2 + ">. The tree doesn't match so React will fallback to client rendering."
29729
29729
  );
29730
- var childNodes = node2[2];
29730
+ var childNodes2 = node2[2];
29731
29731
  node2 = node2[3];
29732
29732
  name2 = task.node;
29733
- task.replay = { nodes: childNodes, slots: node2, pendingTasks: 1 };
29733
+ task.replay = { nodes: childNodes2, slots: node2, pendingTasks: 1 };
29734
29734
  try {
29735
29735
  renderElement(request2, task, keyPath, type, props, ref2);
29736
29736
  if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
@@ -29751,7 +29751,7 @@ function requireReactDomServer_node_development() {
29751
29751
  abortRemainingReplayNodes(
29752
29752
  props,
29753
29753
  request2,
29754
- childNodes,
29754
+ childNodes2,
29755
29755
  ref2,
29756
29756
  keyPath,
29757
29757
  node2,
@@ -29803,12 +29803,12 @@ function requireReactDomServer_node_development() {
29803
29803
  break a;
29804
29804
  }
29805
29805
  } catch (error2) {
29806
- props.status = CLIENT_RENDERED, childNodes = getThrownInfo(task.componentStack), replay = logRecoverableError(
29806
+ props.status = CLIENT_RENDERED, childNodes2 = getThrownInfo(task.componentStack), replay = logRecoverableError(
29807
29807
  request2,
29808
29808
  error2,
29809
- childNodes,
29809
+ childNodes2,
29810
29810
  task.debugTask
29811
- ), encodeErrorForBoundary(props, replay, error2, childNodes, false), task.replay.pendingTasks--, request2.clientRenderedBoundaries.push(props);
29811
+ ), encodeErrorForBoundary(props, replay, error2, childNodes2, false), task.replay.pendingTasks--, request2.clientRenderedBoundaries.push(props);
29812
29812
  } finally {
29813
29813
  task.blockedBoundary = parentBoundary, task.hoistableState = parentHoistableState, task.replay = previousReplaySet, task.keyPath = prevKeyPath;
29814
29814
  }
@@ -49002,6 +49002,115 @@ function eventIdToSlot(eventId) {
49002
49002
  const slot = Number(body2);
49003
49003
  return Number.isSafeInteger(slot) && slot >= FIRST_EVENT_SLOT ? slot : null;
49004
49004
  }
49005
+ const SnapshotMetadataSchema = object$1({
49006
+ /**
49007
+ * Pagination cursor for events.list() — the snapshot was taken at
49008
+ * this point in the event log. On restore, only events AFTER this
49009
+ * cursor need to be fetched.
49010
+ */
49011
+ eventsCursor: string$2().nullable(),
49012
+ /** Timestamp when the snapshot was created */
49013
+ createdAt: date$2(),
49014
+ /**
49015
+ * Number of events the run had processed when the snapshot was taken.
49016
+ * Restores see only the delta after `eventsCursor`, so guards that need
49017
+ * the TOTAL log size (the server-supplied max-events ceiling) add this
49018
+ * to the delta. Optional for snapshots written before the field existed
49019
+ * (treated as 0 — the ceiling degrades to delta-only for those, exactly
49020
+ * the pre-field behavior).
49021
+ */
49022
+ eventCount: number$3().int().nonnegative().optional(),
49023
+ /**
49024
+ * Number of draws the run's seeded PRNG had consumed when the snapshot
49025
+ * was taken. On restore the runtime re-seeds from the run's BASE seed
49026
+ * and fast-forwards this many draws, so correlation-id generation
49027
+ * continues at the exact position full replay would have reached —
49028
+ * keeping ids identical across snapshot generations AND identical to a
49029
+ * no-snapshot run (which is what makes concurrent invocations restored
49030
+ * from different snapshots of the same run still collide on the world's
49031
+ * per-(runId, correlationId) dedup).
49032
+ */
49033
+ rngDraws: number$3().int().nonnegative().optional(),
49034
+ /**
49035
+ * Snapshot-portable token of the engine's host-serde capture root: the
49036
+ * container of pristine intrinsics/samples/symbols captured before any
49037
+ * user code ran, whose box lives inside the snapshot's memory image. A
49038
+ * restore re-adopts it by this token so serde initialization executes
49039
+ * no guest code after user code has run. Required to restore (format
49040
+ * version >= 2); snapshots without it are treated as a miss.
49041
+ */
49042
+ serdeRootPtr: number$3().int().optional(),
49043
+ /**
49044
+ * The monotonic correlation-id ULID factory's last output when the
49045
+ * snapshot was taken (undefined if the run had drawn none). The
49046
+ * factory's state lives host-side and does not survive into the memory
49047
+ * image; on restore the runtime continues the sequence from this value
49048
+ * (same-timestamp base32 increment), so a restored invocation emits
49049
+ * the exact ids a full replay would — keeping concurrent invocations
49050
+ * of the same run dedupable via per-(runId, correlationId) uniqueness.
49051
+ */
49052
+ lastUlid: string$2().optional(),
49053
+ /**
49054
+ * Exact engine build (quickjs-wasi package version) that captured the
49055
+ * heap image. The image's own QJSS header is identical across builds,
49056
+ * so restoring under a different build would pass deserialization and
49057
+ * execute as undefined behavior in the interpreter — a real hazard
49058
+ * during a rolling deploy that bumps quickjs-wasi, when live snapshots
49059
+ * from the old build meet instances running the new one. Readers MUST
49060
+ * treat a mismatch (or absence) as a clean miss.
49061
+ */
49062
+ engineVersion: string$2().optional(),
49063
+ /**
49064
+ * The deterministic replay clock's high-water mark (ms since epoch) at
49065
+ * capture. The clock lives host-side; without this a restored VM's
49066
+ * `Date.now()` regresses to the run-creation time until the first
49067
+ * delta event advances it, so restores initialize the clock to
49068
+ * `max(derived, clockMs)`.
49069
+ */
49070
+ clockMs: number$3().optional(),
49071
+ /**
49072
+ * Snapshot format tag. A reader that doesn't recognize the version
49073
+ * treats the snapshot as a clean miss (full replay) instead of handing
49074
+ * an incompatible heap to the WASM engine.
49075
+ */
49076
+ formatVersion: number$3().int().optional()
49077
+ });
49078
+ const ENVELOPE_MAGIC = [87, 83, 78, 80];
49079
+ const ENVELOPE_VERSION = 1;
49080
+ const ENVELOPE_HEADER_LEN = 9;
49081
+ function encodeSnapshotEnvelope(metadata, data2) {
49082
+ const metaBytes = new TextEncoder().encode(JSON.stringify(metadata));
49083
+ const out = new Uint8Array(ENVELOPE_HEADER_LEN + metaBytes.length + data2.length);
49084
+ out.set(ENVELOPE_MAGIC, 0);
49085
+ out[4] = ENVELOPE_VERSION;
49086
+ new DataView(out.buffer).setUint32(5, metaBytes.length, true);
49087
+ out.set(metaBytes, ENVELOPE_HEADER_LEN);
49088
+ out.set(data2, ENVELOPE_HEADER_LEN + metaBytes.length);
49089
+ return out;
49090
+ }
49091
+ function decodeSnapshotEnvelope(bytes) {
49092
+ if (bytes.length < ENVELOPE_HEADER_LEN)
49093
+ return null;
49094
+ for (let i = 0; i < ENVELOPE_MAGIC.length; i++) {
49095
+ if (bytes[i] !== ENVELOPE_MAGIC[i])
49096
+ return null;
49097
+ }
49098
+ if (bytes[4] !== ENVELOPE_VERSION)
49099
+ return null;
49100
+ const metaLen = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(5, true);
49101
+ if (ENVELOPE_HEADER_LEN + metaLen > bytes.length)
49102
+ return null;
49103
+ try {
49104
+ const metaJson = new TextDecoder().decode(bytes.subarray(ENVELOPE_HEADER_LEN, ENVELOPE_HEADER_LEN + metaLen));
49105
+ const metadata = SnapshotMetadataSchema.passthrough().parse(JSON.parse(metaJson));
49106
+ return {
49107
+ metadata,
49108
+ data: bytes.subarray(ENVELOPE_HEADER_LEN + metaLen)
49109
+ };
49110
+ } catch {
49111
+ return null;
49112
+ }
49113
+ }
49005
49114
  const SPEC_VERSION_LEGACY = 1;
49006
49115
  const SPEC_VERSION_SUPPORTS_EVENT_SOURCING = 2;
49007
49116
  const SPEC_VERSION_SUPPORTS_CBOR_QUEUE_TRANSPORT = 3;
@@ -55132,7 +55241,7 @@ function replaceEncryptedAndExpiredWithMarkers(resource) {
55132
55241
  }
55133
55242
  async function hydrateResourceIOAsync(resource, key) {
55134
55243
  const { hydrateDataWithKey: hydrateDataWithKey2, deriveRunPayloadKeys: deriveRunPayloadKeys2 } = await Promise.resolve().then(() => serializationFormat);
55135
- const { ensureZstdDecoderRegistered } = await import("./zstd-browser-decoder-d2YJZBik.js");
55244
+ const { ensureZstdDecoderRegistered } = await import("./zstd-browser-decoder-DF4c9PWF.js");
55136
55245
  ensureZstdDecoderRegistered();
55137
55246
  const cryptoKey = key ? await deriveRunPayloadKeys2(key) : void 0;
55138
55247
  const revivers = getRevivers();
@@ -59952,7 +60061,7 @@ const deserializer = ($2, _2) => {
59952
60061
  return unpair;
59953
60062
  };
59954
60063
  const deserialize$3 = (serialized) => deserializer(/* @__PURE__ */ new Map(), serialized)(0);
59955
- const EMPTY = "";
60064
+ const EMPTY$1 = "";
59956
60065
  const { toString: toString$2 } = {};
59957
60066
  const { keys } = Object;
59958
60067
  const typeOf = (value) => {
@@ -59962,17 +60071,17 @@ const typeOf = (value) => {
59962
60071
  const asString = toString$2.call(value).slice(8, -1);
59963
60072
  switch (asString) {
59964
60073
  case "Array":
59965
- return [ARRAY, EMPTY];
60074
+ return [ARRAY, EMPTY$1];
59966
60075
  case "Object":
59967
- return [OBJECT$2, EMPTY];
60076
+ return [OBJECT$2, EMPTY$1];
59968
60077
  case "Date":
59969
- return [DATE, EMPTY];
60078
+ return [DATE, EMPTY$1];
59970
60079
  case "RegExp":
59971
- return [REGEXP, EMPTY];
60080
+ return [REGEXP, EMPTY$1];
59972
60081
  case "Map":
59973
- return [MAP, EMPTY];
60082
+ return [MAP, EMPTY$1];
59974
60083
  case "Set":
59975
- return [SET, EMPTY];
60084
+ return [SET, EMPTY$1];
59976
60085
  case "DataView":
59977
60086
  return [ARRAY, asString];
59978
60087
  }
@@ -86076,7 +86185,7 @@ var tn = f("block", "before:content-[counter(line)]", "before:inline-block", "be
86076
86185
  var et = ({ className: e, language: t, style: o, isIncomplete: n, ...s2 }) => jsxRuntimeExports.jsx("div", { className: f("my-4 flex w-full flex-col gap-2 rounded-xl border border-border bg-sidebar p-2", e), "data-incomplete": n || void 0, "data-language": t, "data-streamdown": "code-block", style: { contentVisibility: "auto", containIntrinsicSize: "auto 200px", ...o }, ...s2 });
86077
86186
  var Se = reactExports.createContext({ code: "" }), de = () => reactExports.useContext(Se);
86078
86187
  var ot = ({ language: e }) => jsxRuntimeExports.jsx("div", { className: "flex h-8 items-center text-muted-foreground text-xs", "data-language": e, "data-streamdown": "code-block-header", children: jsxRuntimeExports.jsx("span", { className: "ml-1 font-mono lowercase", children: e }) });
86079
- var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-D21NaJQ0.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
86188
+ var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-CHWCmTRA.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
86080
86189
  let i = reactExports.useMemo(() => e.replace(cn$1, ""), [e]), c = reactExports.useMemo(() => ({ bg: "transparent", fg: "inherit", tokens: i.split(`
86081
86190
  `).map((a2) => [{ content: a2, color: "inherit", bgColor: "transparent", htmlStyle: {}, offset: 0 }]) }), [i]);
86082
86191
  return jsxRuntimeExports.jsx(Se.Provider, { value: { code: e }, children: jsxRuntimeExports.jsxs(et, { isIncomplete: s2, language: t, children: [jsxRuntimeExports.jsx(ot, { language: t }), n ? jsxRuntimeExports.jsx("div", { className: "pointer-events-none sticky top-2 z-10 -mt-10 flex h-8 items-center justify-end", children: jsxRuntimeExports.jsx("div", { className: "pointer-events-auto flex shrink-0 items-center gap-2 rounded-md border border-sidebar bg-sidebar/80 px-1.5 py-1 supports-[backdrop-filter]:bg-sidebar/70 supports-[backdrop-filter]:backdrop-blur", "data-streamdown": "code-block-actions", children: n }) }) : null, jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: jsxRuntimeExports.jsx(Qe, { className: o, language: t, result: c, ...r2 }), children: jsxRuntimeExports.jsx(dn, { className: o, code: i, language: t, raw: c, ...r2 }) })] }) });
@@ -86398,7 +86507,7 @@ var Dt = ({ children: e, className: t, onDownload: o, onError: n }) => {
86398
86507
  }, []), jsxRuntimeExports.jsxs("div", { className: "relative", ref: i, children: [jsxRuntimeExports.jsx("button", { className: f("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50", t), disabled: c, onClick: () => r2(!s2), title: "Download table", type: "button", children: e != null ? e : jsxRuntimeExports.jsx(Z, { size: 14 }) }), s2 ? jsxRuntimeExports.jsxs("div", { className: "absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg", children: [jsxRuntimeExports.jsx("button", { className: "w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40", onClick: () => a2("csv"), title: "Download table as CSV", type: "button", children: "CSV" }), jsxRuntimeExports.jsx("button", { className: "w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40", onClick: () => a2("markdown"), title: "Download table as Markdown", type: "button", children: "Markdown" })] }) : null] });
86399
86508
  };
86400
86509
  var Vt = ({ children: e, className: t, showControls: o, ...n }) => jsxRuntimeExports.jsxs("div", { className: "my-4 flex flex-col gap-2 rounded-lg border border-border bg-sidebar p-2", "data-streamdown": "table-wrapper", children: [o ? jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-end gap-1", children: [jsxRuntimeExports.jsx(Ht, {}), jsxRuntimeExports.jsx(Dt, {})] }) : null, jsxRuntimeExports.jsx("div", { className: "border-collapse overflow-x-auto overscroll-y-auto rounded-md border border-border bg-background", children: jsxRuntimeExports.jsx("table", { className: f("w-full divide-y divide-border", t), "data-streamdown": "table", ...n, children: e }) })] });
86401
- var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-DlUUmZjL.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
86510
+ var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-CNO9LDDa.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
86402
86511
  function ke(e, t) {
86403
86512
  if (!(e != null && e.position || t != null && t.position)) return true;
86404
86513
  if (!(e != null && e.position && (t != null && t.position))) return false;
@@ -95337,7 +95446,7 @@ async function linkToTraceCarrier(carrier) {
95337
95446
  return { context };
95338
95447
  }
95339
95448
  function matchesDebugNamespace(namespace2, patternList) {
95340
- if (!patternList) {
95449
+ if (typeof patternList !== "string" || !patternList) {
95341
95450
  return false;
95342
95451
  }
95343
95452
  let enabled = false;
@@ -95988,7 +96097,14 @@ function headersToEntries(value) {
95988
96097
  recordProxy(value);
95989
96098
  return Array.from(value);
95990
96099
  }
95991
- return [...headersIterator(value)];
96100
+ try {
96101
+ return [...headersIterator(value)];
96102
+ } catch (error2) {
96103
+ if (!(error2 instanceof TypeError))
96104
+ throw error2;
96105
+ recordGuestCode("method", "Headers[Symbol.iterator]");
96106
+ return Array.from(value);
96107
+ }
95992
96108
  }
95993
96109
  function mapToEntries(value) {
95994
96110
  return [...mapEntries(value)];
@@ -96820,7 +96936,7 @@ function isZstdAvailable() {
96820
96936
  function isGzipAvailable() {
96821
96937
  return typeof CompressionStream === "function" && typeof DecompressionStream === "function";
96822
96938
  }
96823
- async function pipeThroughTransform(data2, transform2) {
96939
+ async function pipeThroughTransform(data2, transform2, maxOutputBytes) {
96824
96940
  const writer = transform2.writable.getWriter();
96825
96941
  const writePromise = writer.write(data2).then(() => writer.close());
96826
96942
  writePromise.catch(() => {
@@ -96847,22 +96963,26 @@ async function pipeThroughTransform(data2, transform2) {
96847
96963
  async function gzipBytes(data2) {
96848
96964
  return pipeThroughTransform(data2, new CompressionStream("gzip"));
96849
96965
  }
96850
- async function gunzipBytes(data2) {
96966
+ async function gunzipBytes(data2, maxOutputBytes) {
96851
96967
  return pipeThroughTransform(data2, new DecompressionStream("gzip"));
96852
96968
  }
96853
- function zstdBytes(data2) {
96969
+ function zstdOpts(z2) {
96854
96970
  var _a3;
96855
- const z2 = getNodeZlib$1();
96856
96971
  const level = (_a3 = z2 == null ? void 0 : z2.constants) == null ? void 0 : _a3.ZSTD_c_compressionLevel;
96857
- const opts = level !== void 0 ? { params: { [level]: ZSTD_LEVEL } } : void 0;
96858
- return new Uint8Array(z2.zstdCompressSync(data2, opts));
96972
+ return level !== void 0 ? { params: { [level]: ZSTD_LEVEL } } : void 0;
96973
+ }
96974
+ function zstdBytes(data2) {
96975
+ const z2 = getNodeZlib$1();
96976
+ return new Uint8Array(z2.zstdCompressSync(data2, zstdOpts(z2)));
96859
96977
  }
96860
- function unzstdBytes(data2) {
96978
+ function unzstdBytes(data2, maxOutputBytes) {
96861
96979
  const z2 = getNodeZlib$1();
96862
96980
  if (!(z2 == null ? void 0 : z2.zstdDecompressSync)) {
96863
96981
  throw new Error("Compressed (zstd) workflow data encountered but node:zlib zstd support is not available in this runtime (requires Node.js 22.15+). In the browser, register a zstd decoder via registerZstdDecoder (serialization-format.ts).");
96864
96982
  }
96865
- return new Uint8Array(z2.zstdDecompressSync(data2));
96983
+ {
96984
+ return new Uint8Array(z2.zstdDecompressSync(data2));
96985
+ }
96866
96986
  }
96867
96987
  function recordStats(stats2, codec, uncompressedBytes, storedBytes) {
96868
96988
  if (!stats2)
@@ -96883,7 +97003,7 @@ function selectWriteCodec() {
96883
97003
  return "gzip";
96884
97004
  return "none";
96885
97005
  }
96886
- async function compress(data2, enabled, stats2) {
97006
+ async function compress(data2, enabled, stats2, opts) {
96887
97007
  if (!(data2 instanceof Uint8Array))
96888
97008
  return data2;
96889
97009
  if (!enabled || data2.length < COMPRESSION_MIN_BYTES || isCompressionDisabledByEnv()) {
@@ -96905,7 +97025,7 @@ async function compress(data2, enabled, stats2) {
96905
97025
  recordStats(stats2, codec, data2.length, wrappedLength);
96906
97026
  return encodeWithFormatPrefix(format2, compressed);
96907
97027
  }
96908
- async function decompress$2(data2, stats2) {
97028
+ async function decompress$2(data2, stats2, opts) {
96909
97029
  if (!(data2 instanceof Uint8Array))
96910
97030
  return data2;
96911
97031
  const prefix = peekFormatPrefix$1(data2);
@@ -104635,14 +104755,23 @@ Parser2.acorn = {
104635
104755
  function parse$2(input, options) {
104636
104756
  return Parser2.parse(input, options);
104637
104757
  }
104758
+ function dynamicStartRefusal(message2, options) {
104759
+ return Object.assign(new WorkflowRuntimeError(message2, options), {
104760
+ fatal: true
104761
+ });
104762
+ }
104763
+ function dynamicStartRefusalFrom(error2) {
104764
+ return dynamicStartRefusal(error2 instanceof Error ? error2.message : String(error2), { cause: error2 });
104765
+ }
104638
104766
  const DYNAMIC_WORKFLOW_SOURCE_MAX_BYTES = 128 * 1024;
104639
104767
  const DYNAMIC_WORKFLOW_CODE_INLINE_MAX_BYTES = 24 * 1024;
104640
104768
  const SAFE_DYNAMIC_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
104769
+ const DYNAMIC_WORKFLOW_EXPORT_NAME_MAX_LENGTH = 64;
104641
104770
  const SAFE_DYNAMIC_EXPORT_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
104642
104771
  const UNSUPPORTED_DYNAMIC_MODULE_SYNTAX = /^[ \t]*(?:import(?:\s+[\w$]|\s*(?:[*{(]|['"]))|export(?:\s+(?:async\s+)?(?:function|const|let|var|class|default)\b|\s*[{*]))/m;
104643
104772
  function assertDynamicWorkflowIdentifier(kind, value) {
104644
104773
  if (!SAFE_DYNAMIC_IDENTIFIER.test(value)) {
104645
- throw new WorkflowRuntimeError(`Invalid dynamic workflow ${kind} ${JSON.stringify(value)}. Use a valid JavaScript identifier: letters, digits, "_" and "$", not starting with a digit.`);
104774
+ throw dynamicStartRefusal(`Invalid dynamic workflow ${kind} ${JSON.stringify(value)}. Use a valid JavaScript identifier: letters, digits, "_" and "$", not starting with a digit.`);
104646
104775
  }
104647
104776
  }
104648
104777
  function stableJsonStringify(value) {
@@ -104659,7 +104788,7 @@ async function sha256Hex(input) {
104659
104788
  return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
104660
104789
  }
104661
104790
  const DYNAMIC_WORKFLOW_ECMA_VERSION = 2024;
104662
- function parseDynamicWorkflowSource(source) {
104791
+ function parseDynamicWorkflowSource(source, exportName) {
104663
104792
  try {
104664
104793
  return parse$2(source, {
104665
104794
  ecmaVersion: DYNAMIC_WORKFLOW_ECMA_VERSION,
@@ -104667,7 +104796,7 @@ function parseDynamicWorkflowSource(source) {
104667
104796
  });
104668
104797
  } catch (error2) {
104669
104798
  const message2 = error2 instanceof Error ? error2.message : String(error2);
104670
- throw new WorkflowRuntimeError(`Dynamic workflow source is not valid JavaScript: ${message2}. The source is evaluated as-is, so it cannot contain TypeScript syntax or module declarations.`);
104799
+ throw dynamicStartRefusal(`Dynamic workflow source is not valid JavaScript: ${message2}. The source is evaluated as-is, so it cannot contain TypeScript syntax or module declarations. If the error is at an \`await\`, declare the function as \`async function ${exportName}(...)\`.`);
104671
104800
  }
104672
104801
  }
104673
104802
  function assertGeneratedWorkflowCodeParses(workflowCode) {
@@ -104678,35 +104807,70 @@ function assertGeneratedWorkflowCodeParses(workflowCode) {
104678
104807
  });
104679
104808
  } catch (error2) {
104680
104809
  const message2 = error2 instanceof Error ? error2.message : String(error2);
104681
- throw new WorkflowRuntimeError(`Generated dynamic workflow code is not valid JavaScript: ${message2}.`);
104810
+ throw dynamicStartRefusal(`Generated dynamic workflow code is not valid JavaScript: ${message2}.`);
104682
104811
  }
104683
104812
  }
104684
104813
  function validateDynamicWorkflowSource(source, exportName) {
104685
104814
  const byteLength = new TextEncoder().encode(source).byteLength;
104686
104815
  if (byteLength > DYNAMIC_WORKFLOW_SOURCE_MAX_BYTES) {
104687
- throw new WorkflowRuntimeError(`Dynamic workflow source is ${byteLength} bytes, over the ${DYNAMIC_WORKFLOW_SOURCE_MAX_BYTES}-byte limit.`);
104816
+ throw dynamicStartRefusal(`Dynamic workflow source is ${byteLength} bytes, over the ${DYNAMIC_WORKFLOW_SOURCE_MAX_BYTES}-byte limit.`);
104688
104817
  }
104689
104818
  if (UNSUPPORTED_DYNAMIC_MODULE_SYNTAX.test(source)) {
104690
- throw new WorkflowRuntimeError("Dynamic workflow source cannot use `import` or `export`. Reach registered steps through the injected `steps` object instead.");
104691
- }
104692
- const program = parseDynamicWorkflowSource(source);
104693
- const declarations = program.body.filter((node2) => node2.type === "FunctionDeclaration" && node2.id.name === exportName);
104694
- const declaration = declarations.length === 1 ? declarations[0] : void 0;
104695
- if (!declaration || !declaration.async || declaration.generator) {
104696
- throw new WorkflowRuntimeError(`Dynamic workflow source must declare \`async function ${exportName}(...)\` at top level.`);
104819
+ throw dynamicStartRefusal("Dynamic workflow source cannot use `import` or `export`. Reach registered steps through the injected `steps` object instead.");
104697
104820
  }
104821
+ const program = parseDynamicWorkflowSource(source, exportName);
104822
+ const declaration = findWorkflowDeclaration(program, exportName);
104698
104823
  const firstStatement = declaration.body.body[0];
104699
104824
  if ((firstStatement == null ? void 0 : firstStatement.type) !== "ExpressionStatement" || firstStatement.directive !== "use workflow") {
104700
- throw new WorkflowRuntimeError(`Dynamic workflow function ${JSON.stringify(exportName)} must open with a "use workflow" directive.`);
104825
+ throw dynamicStartRefusal(`Dynamic workflow function ${JSON.stringify(exportName)} must open with a "use workflow" directive.`);
104826
+ }
104827
+ if (hasDirective(program, "use step")) {
104828
+ throw dynamicStartRefusal('Dynamic workflow source cannot declare "use step" functions. Register the step with the deployment and expose it through `experimental_dynamic.steps` instead.');
104701
104829
  }
104702
- if (/(?:"use step"|'use step')/.test(source)) {
104703
- throw new WorkflowRuntimeError('Dynamic workflow source cannot declare "use step" functions. Register the step with the deployment and expose it through `experimental_dynamic.steps` instead.');
104830
+ }
104831
+ function findWorkflowDeclaration(program, exportName) {
104832
+ const expected = `Dynamic workflow source must declare \`async function ${exportName}(...)\` at top level`;
104833
+ const declarations = program.body.filter((node2) => node2.type === "FunctionDeclaration" && node2.id.name === exportName);
104834
+ const [declaration] = declarations;
104835
+ let problem = "";
104836
+ if (declarations.length > 1) {
104837
+ problem = ` exactly once, but declares \`function ${exportName}\` ${declarations.length} times`;
104838
+ } else if (declaration == null ? void 0 : declaration.generator) {
104839
+ problem = `, but \`${exportName}\` is a generator function`;
104840
+ } else if (declaration && !declaration.async) {
104841
+ problem = `, but \`${exportName}\` is not async`;
104842
+ }
104843
+ if (!declaration || problem) {
104844
+ throw dynamicStartRefusal(`${expected}${problem}.`);
104845
+ }
104846
+ return declaration;
104847
+ }
104848
+ function hasDirective(program, directive) {
104849
+ const pending = [program];
104850
+ while (pending.length > 0) {
104851
+ const node2 = pending.pop();
104852
+ if (node2.directive === directive)
104853
+ return true;
104854
+ for (const child of childNodes(node2))
104855
+ pending.push(child);
104856
+ }
104857
+ return false;
104858
+ }
104859
+ function childNodes(node2) {
104860
+ const children2 = [];
104861
+ for (const value of Object.values(node2)) {
104862
+ for (const child of Array.isArray(value) ? value : [value]) {
104863
+ if (child && typeof child === "object" && "type" in child) {
104864
+ children2.push(child);
104865
+ }
104866
+ }
104704
104867
  }
104868
+ return children2;
104705
104869
  }
104706
104870
  function resolveStepId(alias, value) {
104707
104871
  const stepId = value && typeof value === "object" || typeof value === "function" ? value.stepId : void 0;
104708
104872
  if (typeof stepId !== "string" || stepId.length === 0) {
104709
- throw new WorkflowRuntimeError(`Dynamic workflow step ${JSON.stringify(alias)} must be an imported step function or an object with a non-empty \`stepId\`.`);
104873
+ throw dynamicStartRefusal(`Dynamic workflow step ${JSON.stringify(alias)} must be an imported step function or an object with a non-empty \`stepId\`.`);
104710
104874
  }
104711
104875
  return stepId;
104712
104876
  }
@@ -104715,13 +104879,16 @@ function dynamicWorkflowName(metadata) {
104715
104879
  }
104716
104880
  async function compileDynamicWorkflow(source, options) {
104717
104881
  const exportName = options.exportName ?? "workflow";
104882
+ if (exportName.length > DYNAMIC_WORKFLOW_EXPORT_NAME_MAX_LENGTH) {
104883
+ throw dynamicStartRefusal(`Dynamic workflow exportName is ${exportName.length} characters, over the ${DYNAMIC_WORKFLOW_EXPORT_NAME_MAX_LENGTH}-character limit. It becomes part of the workflow id and queue name.`);
104884
+ }
104718
104885
  assertDynamicWorkflowIdentifier("exportName", exportName);
104719
104886
  if (!SAFE_DYNAMIC_EXPORT_NAME.test(exportName)) {
104720
- throw new WorkflowRuntimeError(`Invalid dynamic workflow exportName ${JSON.stringify(exportName)}. Use letters, digits, and "_", not starting with a digit; "$" cannot appear in workflow queue names.`);
104887
+ throw dynamicStartRefusal(`Invalid dynamic workflow exportName ${JSON.stringify(exportName)}. Use letters, digits, and "_", not starting with a digit; "$" cannot appear in workflow queue names.`);
104721
104888
  }
104722
104889
  validateDynamicWorkflowSource(source, exportName);
104723
104890
  if (!options.steps || Object.keys(options.steps).length === 0) {
104724
- throw new WorkflowRuntimeError("Dynamic workflow options must expose at least one registered step through `experimental_dynamic.steps`.");
104891
+ throw dynamicStartRefusal("Dynamic workflow options must expose at least one registered step through `experimental_dynamic.steps`.");
104725
104892
  }
104726
104893
  const stepEntries = Object.entries(options.steps).sort(([a2], [b2]) => a2 < b2 ? -1 : a2 > b2 ? 1 : 0).map(([alias, value]) => {
104727
104894
  assertDynamicWorkflowIdentifier("step alias", alias);
@@ -104783,7 +104950,7 @@ function readDynamicWorkflowMetadata(executionContext) {
104783
104950
  steps: candidate.steps && typeof candidate.steps === "object" ? candidate.steps : {}
104784
104951
  };
104785
104952
  }
104786
- const version$1 = "5.0.0";
104953
+ const version$1 = "5.0.1";
104787
104954
  const DEFAULT_HEALTH_CHECK_TIMEOUT = 3e4;
104788
104955
  const SAFE_WORKFLOW_NAME_PATTERN = /^[a-zA-Z0-9_\-./@()[\]]+$/;
104789
104956
  function getWorkflowQueueName(workflowName, namespace2) {
@@ -106956,8 +107123,18 @@ function getWorkflowVmFromEnv(env2 = process.env) {
106956
107123
  }
106957
107124
  throw new WorkflowRuntimeError(`Invalid WORKFLOW_VM value: "${raw2}". Expected one of: ${WORKFLOW_VMS.join(", ")}.`);
106958
107125
  }
107126
+ function getSnapshotThresholdFromEnv(env2 = process.env) {
107127
+ const raw2 = env2.WORKFLOW_SNAPSHOT_THRESHOLD;
107128
+ if (raw2 === void 0 || raw2 === "")
107129
+ return void 0;
107130
+ const parsed = /^\d+$/.test(raw2) ? Number(raw2) : Number.NaN;
107131
+ if (!Number.isSafeInteger(parsed)) {
107132
+ throw new WorkflowRuntimeError(`Invalid WORKFLOW_SNAPSHOT_THRESHOLD value: "${raw2}". Expected a non-negative integer (0 disables snapshotting).`);
107133
+ }
107134
+ return parsed;
107135
+ }
106959
107136
  function waitUntil(promise2) {
106960
- void import("./index-DnTW8Yiv.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => {
107137
+ void import("./index-B2Fjee_4.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => {
106961
107138
  waitUntil2(promise2);
106962
107139
  });
106963
107140
  }
@@ -107054,7 +107231,7 @@ async function probeCrossDeployment(world, options) {
107054
107231
  }
107055
107232
  function assertDynamicWorkflowsEnabled() {
107056
107233
  if (!isDynamicWorkflowsEnabled()) {
107057
- throw new WorkflowRuntimeError(`Dynamic workflows are disabled on this deployment, so no run was created. Set ${DYNAMIC_WORKFLOWS_ENV}=1 on the deployment to enable them.`);
107234
+ throw dynamicStartRefusal(`Dynamic workflows are disabled on this deployment, so no run was created. Set ${DYNAMIC_WORKFLOWS_ENV}=1 on the deployment to enable them.`);
107058
107235
  }
107059
107236
  }
107060
107237
  async function start$1(workflow, argsOrOptions, options) {
@@ -107072,7 +107249,7 @@ async function start$1(workflow, argsOrOptions, options) {
107072
107249
  if (typeof workflow === "string") {
107073
107250
  const dynamicOptions = opts.experimental_dynamic;
107074
107251
  if (!dynamicOptions) {
107075
- throw new WorkflowRuntimeError("'start' was given workflow source but no `experimental_dynamic` options. Pass `{ experimental_dynamic: { steps } }` to declare which registered steps the source may call.");
107252
+ throw dynamicStartRefusal("'start' was given workflow source but no `experimental_dynamic` options. Pass `{ experimental_dynamic: { steps } }` to declare which registered steps the source may call.");
107076
107253
  }
107077
107254
  const compiled = await compileDynamicWorkflow(workflow, dynamicOptions);
107078
107255
  assertDynamicWorkflowsEnabled();
@@ -107127,12 +107304,12 @@ async function start$1(workflow, argsOrOptions, options) {
107127
107304
  }
107128
107305
  const crossDeployment = deploymentId !== currentDeploymentId;
107129
107306
  if (dynamicWorkflow && crossDeployment) {
107130
- const current2 = currentDeploymentId === void 0 ? "an unknown current deployment" : JSON.stringify(currentDeploymentId);
107131
- throw new WorkflowRuntimeError(`Dynamic workflows can only start on the current deployment. This start targets ${JSON.stringify(deploymentId)} from ${current2}, so no run was created.`);
107307
+ const message2 = `Dynamic workflows can only start on the current deployment. This start targets ${JSON.stringify(deploymentId)} from ${currentDeploymentId === void 0 ? "an unknown current deployment" : JSON.stringify(currentDeploymentId)}, so no run was created.`;
107308
+ throw currentDeploymentId === void 0 ? new WorkflowRuntimeError(message2) : dynamicStartRefusal(message2);
107132
107309
  }
107133
107310
  const runId = `wrun_${world.createRunId ? world.createRunId(opts) : ulid()}`;
107134
107311
  if (dynamicWorkflow && !((_a3 = world.capabilities) == null ? void 0 : _a3.dynamicWorkflowCode)) {
107135
- throw new WorkflowRuntimeError("Dynamic workflows require a World that declares `capabilities.dynamicWorkflowCode`. This World does not, so no run was created.");
107312
+ throw dynamicStartRefusal("Dynamic workflows require a World that declares `capabilities.dynamicWorkflowCode`. This World does not, so no run was created.");
107136
107313
  }
107137
107314
  let framedByteStreams;
107138
107315
  let targetSupportsCompression;
@@ -107240,17 +107417,23 @@ async function start$1(workflow, argsOrOptions, options) {
107240
107417
  encryptionPublicKey = rawKey ? bytesToBase64((await deriveRunKeyPair(rawKey)).publicKey) : void 0;
107241
107418
  }
107242
107419
  const workflowVm = getWorkflowVmFromEnv();
107420
+ const snapshotThreshold = getSnapshotThresholdFromEnv();
107243
107421
  const executionContext = {
107244
107422
  traceCarrier,
107245
107423
  workflowCoreVersion: version$1,
107246
107424
  features: { encryption: !!encryptionKey },
107247
107425
  ...targetHookResumeInputVersion !== void 0 ? { hookResumeInputVersion: targetHookResumeInputVersion } : {},
107248
107426
  ...workflowVm ? { workflowVm } : {},
107427
+ ...snapshotThreshold !== void 0 ? { snapshotThreshold } : {},
107249
107428
  ...opts.replayedFromRunId ? { replayedFromRunId: opts.replayedFromRunId } : {},
107250
107429
  ...dynamicWorkflow ? { dynamicWorkflow: dynamicWorkflow.metadata } : {}
107251
107430
  };
107252
107431
  if (dynamicWorkflow) {
107253
- (_d2 = world.validateRunExecutionContext) == null ? void 0 : _d2.call(world, executionContext);
107432
+ try {
107433
+ (_d2 = world.validateRunExecutionContext) == null ? void 0 : _d2.call(world, executionContext);
107434
+ } catch (err) {
107435
+ throw dynamicStartRefusalFrom(err);
107436
+ }
107254
107437
  }
107255
107438
  const compression = targetSupportsCompression && specVersion >= SPEC_VERSION_SUPPORTS_COMPRESSION;
107256
107439
  const workflowArguments = await dehydrateWorkflowArguments(args, runId, encryptionKey, ops, globalThis, v1Compat, framedByteStreams, compression);
@@ -107275,20 +107458,27 @@ async function start$1(workflow, argsOrOptions, options) {
107275
107458
  ...dynamicWorkflowCodeRef ? { dynamicWorkflowCodeRef } : {}
107276
107459
  } : {};
107277
107460
  const creatorEnvironment = (_e2 = world.getEnvironment) == null ? void 0 : _e2.call(world);
107461
+ const runCreated = world.events.create(runId, {
107462
+ eventType: "run_created",
107463
+ specVersion,
107464
+ eventData: {
107465
+ deploymentId,
107466
+ workflowName,
107467
+ input: workflowArguments,
107468
+ executionContext,
107469
+ ...encryptionPublicKey ? { encryptionPublicKey } : {},
107470
+ ...attributeSeed,
107471
+ ...dynamicWorkflowSeed
107472
+ }
107473
+ }, { v1Compat });
107474
+ if (dynamicWorkflow) {
107475
+ const { run: run2 } = await runCreated;
107476
+ if (run2.dynamicWorkflowCode === void 0) {
107477
+ throw new WorkflowRuntimeError(`Workflow run ${runId} was created, but this deployment's Workflow backend did not store its dynamic workflow code, so the run can never be replayed. It was not queued, so it will not execute. Dynamic workflows require a backend with encrypted dynamic-source storage; upgrade it, or start a workflow function from the build-time manifest instead.`);
107478
+ }
107479
+ }
107278
107480
  const [runCreatedResult, queueResult] = await Promise.allSettled([
107279
- world.events.create(runId, {
107280
- eventType: "run_created",
107281
- specVersion,
107282
- eventData: {
107283
- deploymentId,
107284
- workflowName,
107285
- input: workflowArguments,
107286
- executionContext,
107287
- ...encryptionPublicKey ? { encryptionPublicKey } : {},
107288
- ...attributeSeed,
107289
- ...dynamicWorkflowSeed
107290
- }
107291
- }, { v1Compat }),
107481
+ runCreated,
107292
107482
  world.queue(queueName, {
107293
107483
  runId,
107294
107484
  traceCarrier,
@@ -107333,9 +107523,6 @@ async function start$1(workflow, argsOrOptions, options) {
107333
107523
  if (!v1Compat && result.run.runId !== runId) {
107334
107524
  throw new WorkflowRuntimeError(`Server returned different runId than requested: expected ${runId}, got ${result.run.runId}`);
107335
107525
  }
107336
- if (dynamicWorkflow && result.run.dynamicWorkflowCode === void 0) {
107337
- throw new WorkflowRuntimeError(`Workflow run ${runId} was created, but this deployment's Workflow backend did not store its dynamic workflow code, so the run can never be replayed. Dynamic workflows require a backend with encrypted dynamic-source storage; upgrade it, or start a workflow function from the build-time manifest instead.`);
107338
- }
107339
107526
  }
107340
107527
  safeWaitUntil(Promise.all(ops), (err) => {
107341
107528
  runtimeLogger.warn("Background flush of workflow argument streams failed", {
@@ -140691,6 +140878,34 @@ function createEventsStorage(basedir, tag) {
140691
140878
  });
140692
140879
  return { ...storage, create: create2 };
140693
140880
  }
140881
+ function createSnapshotsStorage$1(basedir) {
140882
+ const snapshotsDir = path$3.join(basedir, "snapshots");
140883
+ function envelopePath(runId) {
140884
+ assertSafeEntityId("runId", runId);
140885
+ return resolveWithinBase(snapshotsDir, `${runId}.snapshot`);
140886
+ }
140887
+ return {
140888
+ async save(runId, data2, metadata) {
140889
+ await ensureDir(snapshotsDir);
140890
+ await write(envelopePath(runId), Buffer.from(encodeSnapshotEnvelope(metadata, data2)), { overwrite: true });
140891
+ },
140892
+ async load(runId) {
140893
+ let envelope;
140894
+ try {
140895
+ envelope = await readBuffer(envelopePath(runId));
140896
+ } catch (error2) {
140897
+ if (error2.code === "ENOENT") {
140898
+ return null;
140899
+ }
140900
+ throw error2;
140901
+ }
140902
+ return decodeSnapshotEnvelope(new Uint8Array(envelope.buffer, envelope.byteOffset, envelope.byteLength));
140903
+ },
140904
+ async delete(runId) {
140905
+ await fs$1.rm(envelopePath(runId), { force: true });
140906
+ }
140907
+ };
140908
+ }
140694
140909
  function createStepsStorage(basedir, tag) {
140695
140910
  return {
140696
140911
  get: (async (runId, stepId, params) => {
@@ -140737,11 +140952,13 @@ function createStorage$1(basedir, tag) {
140737
140952
  const steps = createStepsStorage(basedir, tag);
140738
140953
  const events2 = createEventsStorage(basedir, tag);
140739
140954
  const hooks = createHooksStorage(basedir, tag);
140955
+ const snapshots = createSnapshotsStorage$1(basedir);
140740
140956
  return {
140741
140957
  runs: instrumentObject$1("world.runs", runs),
140742
140958
  steps: instrumentObject$1("world.steps", steps),
140743
140959
  events: instrumentObject$1("world.events", events2),
140744
140960
  hooks: instrumentObject$1("world.hooks", hooks),
140961
+ experimental_snapshots: instrumentObject$1("world.experimental_snapshots", snapshots),
140745
140962
  clearCache: () => events2.clearCache()
140746
140963
  };
140747
140964
  }
@@ -140803,7 +141020,7 @@ function createWorld$2(args) {
140803
141020
  const basedir = mergedConfig.dataDir;
140804
141021
  const hooksDir = path$3.join(basedir, "hooks");
140805
141022
  const taggedHookFiles = await listTaggedFiles(hooksDir, tag);
140806
- const { HookSchema: HookSchema2 } = await import("./index-y9xp70jn.js");
141023
+ const { HookSchema: HookSchema2 } = await import("./index-CvPUU1wY.js");
140807
141024
  await Promise.all(taggedHookFiles.map(async (hookFile) => {
140808
141025
  const hook = await readJSON(path$3.join(hooksDir, hookFile), HookSchema2);
140809
141026
  if (hook == null ? void 0 : hook.token) {
@@ -140986,8 +141203,8 @@ function requireGetVercelOidcToken() {
140986
141203
  }
140987
141204
  try {
140988
141205
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
140989
- await import("./token-util-BvEnPXwK.js").then((n) => n.t),
140990
- await import("./token-DXiZgST4.js").then((n) => n.t)
141206
+ await import("./token-util-Df3UC21b.js").then((n) => n.t),
141207
+ await import("./token-C2ZfbDqj.js").then((n) => n.t)
140991
141208
  ]);
140992
141209
  if (!token || isExpired(getTokenPayload(token), options == null ? void 0 : options.expirationBufferMs)) {
140993
141210
  await refreshToken(options);
@@ -141550,7 +141767,7 @@ function requireDist() {
141550
141767
  return dist;
141551
141768
  }
141552
141769
  var distExports = requireDist();
141553
- const version = "5.0.0";
141770
+ const version = "5.0.1";
141554
141771
  const pools = globalSingleton("@workflow/world-vercel//httpPools", 1, () => ({
141555
141772
  dispatcher: void 0,
141556
141773
  queueDispatcher: void 0,
@@ -141862,12 +142079,15 @@ function createEventsDispatcher(agentOverrides) {
141862
142079
  ...h2 ? EVENTS_AGENT_OPTIONS : EVENTS_AGENT_OPTIONS_NO_H2,
141863
142080
  ...agentOverrides
141864
142081
  }), EVENTS_RETRY_AGENT_OPTIONS);
141865
- if (!h2) {
142082
+ if (!h2 || !supportsCompose(agent2)) {
141866
142083
  return agent2;
141867
142084
  }
141868
142085
  const streamedBodyAgent = new undiciExports.RetryAgent(new undiciExports.Agent({ ...EVENTS_AGENT_OPTIONS_NO_H2, ...agentOverrides }), EVENTS_RETRY_AGENT_OPTIONS);
141869
142086
  return withBoundLifecycle(agent2, agent2.compose(createH2MultiplexInterceptor(streamedBodyAgent)), streamedBodyAgent);
141870
142087
  }
142088
+ function supportsCompose(dispatcher2) {
142089
+ return typeof dispatcher2.compose === "function";
142090
+ }
141871
142091
  function withBoundLifecycle(agent2, composed, companion) {
141872
142092
  return new Proxy(composed, {
141873
142093
  get: (target2, key) => {
@@ -141888,7 +142108,8 @@ function createStreamDispatcher(retryOptions, agentOverrides) {
141888
142108
  return new undiciExports.RetryAgent(new undiciExports.Agent({ ...STREAM_AGENT_OPTIONS, ...agentOverrides }), retryOptions);
141889
142109
  }
141890
142110
  function createQueueDispatcher() {
141891
- return new undiciExports.RetryAgent(new undiciExports.Agent(getQueueAgentOptions()).compose(deadlineInterceptor(getQueueRequestTimeoutMs())), RETRY_AGENT_OPTIONS);
142111
+ const agent2 = new undiciExports.Agent(getQueueAgentOptions());
142112
+ return new undiciExports.RetryAgent(supportsCompose(agent2) ? agent2.compose(deadlineInterceptor(getQueueRequestTimeoutMs())) : agent2, RETRY_AGENT_OPTIONS);
141892
142113
  }
141893
142114
  function getDefaultQueueDispatcher() {
141894
142115
  pools.queueDispatcher ?? (pools.queueDispatcher = createQueueDispatcher());
@@ -142034,6 +142255,8 @@ const StepStsoMs = SemanticConvention("step.stso_ms");
142034
142255
  const StepLatencyOptimizations = SemanticConvention("step.latency_optimizations");
142035
142256
  const WorkflowWsUrl = SemanticConvention("workflow.events.ws.url");
142036
142257
  const WorkflowWsRequestId = SemanticConvention("workflow.events.ws.req_id");
142258
+ const WorkflowWsRequestParts = SemanticConvention("workflow.events.ws.request_parts");
142259
+ const WorkflowWsReplyParts = SemanticConvention("workflow.events.ws.reply_parts");
142037
142260
  const WorkflowWsReconnectAttempt = SemanticConvention("workflow.events.ws.reconnect_attempt");
142038
142261
  const REQUEST_TIMEOUT_MS = 6e4;
142039
142262
  const TRANSIENT_TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
@@ -142149,7 +142372,7 @@ function parseRetryAfter(value) {
142149
142372
  const parsed = parseInt(value, 10);
142150
142373
  return Number.isNaN(parsed) ? void 0 : parsed;
142151
142374
  }
142152
- function headersToRecord(headers2) {
142375
+ function headersToRecord$1(headers2) {
142153
142376
  const out = {};
142154
142377
  headers2.forEach((value, key) => {
142155
142378
  out[key] = value;
@@ -143278,11 +143501,11 @@ function validateRunExecutionContext(value) {
143278
143501
  }
143279
143502
  const bytes = new TextEncoder().encode(json).byteLength;
143280
143503
  if (bytes > MAX_EXECUTION_CONTEXT_BYTES) {
143281
- throw new WorkflowRuntimeError(`Dynamic workflow execution context is ${bytes} bytes, exceeding the ${MAX_EXECUTION_CONTEXT_BYTES}-byte limit, so no run was created. Bind fewer steps through \`experimental_dynamic.steps\` or use shorter aliases.`);
143504
+ throw new WorkflowRuntimeError(`Dynamic workflow execution context is ${bytes} bytes, exceeding the ${MAX_EXECUTION_CONTEXT_BYTES}-byte limit, so no run was created. Each step binding counts its alias and its step ID, which comes from the step's file path and function name and is usually the longer of the two; the \`exportName\` counts too. Bind fewer steps through \`experimental_dynamic.steps\`, or shorten the aliases, the step files' paths or names, or the \`exportName\`.`);
143282
143505
  }
143283
143506
  }
143284
143507
  async function getDeadline() {
143285
- const { getDeadline: getDeadline2 } = await import("./index-DnTW8Yiv.js").then((n) => n.i);
143508
+ const { getDeadline: getDeadline2 } = await import("./index-B2Fjee_4.js").then((n) => n.i);
143286
143509
  return getDeadline2();
143287
143510
  }
143288
143511
  const WORKFLOW_SERVER_SERVICE = {
@@ -148280,6 +148503,23 @@ function isWsEventsTransportEnabled() {
148280
148503
  var _a3;
148281
148504
  return ((_a3 = process.env.WORKFLOW_EVENTS_TRANSPORT) == null ? void 0 : _a3.trim().toLowerCase()) === "ws";
148282
148505
  }
148506
+ function wsEventsTransportOverrideWorkflows() {
148507
+ const raw2 = process.env.WORKFLOW_EVENTS_TRANSPORT_WS_OVERRIDE_WORKFLOWS;
148508
+ if (!raw2)
148509
+ return [];
148510
+ return raw2.split(",").map((token) => token.trim()).filter((token) => token.length > 0);
148511
+ }
148512
+ function isWsEventsTransportEnabledForWorkflow(workflowName) {
148513
+ if (isWsEventsTransportEnabled())
148514
+ return true;
148515
+ if (!workflowName)
148516
+ return false;
148517
+ const functionName = workflowName.slice(workflowName.lastIndexOf("//") + 2);
148518
+ return wsEventsTransportOverrideWorkflows().some((token) => token === workflowName || token === functionName);
148519
+ }
148520
+ function isWsEventsTransportPossible() {
148521
+ return isWsEventsTransportEnabled() || wsEventsTransportOverrideWorkflows().length > 0;
148522
+ }
148283
148523
  function isWsEventsTransportStrict() {
148284
148524
  const raw2 = process.env.WORKFLOW_INTERNAL_EVENTS_TRANSPORT_STRICT;
148285
148525
  return raw2 === "1" || raw2 === "true";
@@ -148435,7 +148675,14 @@ function getRunIdFromPayload(payload) {
148435
148675
  }
148436
148676
  return void 0;
148437
148677
  }
148438
- const wsEventsChannelForInvocation = (runId, config2) => {
148678
+ function getWorkflowNameFromQueueName(queueName) {
148679
+ try {
148680
+ return parseQueueName(queueName).id;
148681
+ } catch {
148682
+ return void 0;
148683
+ }
148684
+ }
148685
+ const wsEventsChannelForInvocation = (runId, workflowName, config2) => {
148439
148686
  let claim2;
148440
148687
  return {
148441
148688
  /**
@@ -148446,9 +148693,10 @@ const wsEventsChannelForInvocation = (runId, config2) => {
148446
148693
  * the claim it is releasing.
148447
148694
  */
148448
148695
  open() {
148449
- if (!runId || !isWsEventsTransportEnabled())
148696
+ if (!runId || !isWsEventsTransportEnabledForWorkflow(workflowName)) {
148450
148697
  return;
148451
- claim2 = Promise.resolve().then(() => wsTransport).then(({ openWsChannel: openWsChannel2 }) => openWsChannel2(runId, config2)).catch(() => void 0);
148698
+ }
148699
+ claim2 = Promise.resolve().then(() => wsTransport).then(({ openWsChannel: openWsChannel2 }) => openWsChannel2(runId, config2, { workflowName })).catch(() => void 0);
148452
148700
  },
148453
148701
  /**
148454
148702
  * Awaited, unlike the open: work scheduled after the handler returns is not
@@ -148656,7 +148904,7 @@ function createQueue$1(config2) {
148656
148904
  const invocation = invocationStorage.getStore();
148657
148905
  const requestId = invocation == null ? void 0 : invocation.requestId;
148658
148906
  const { payload, queueName, deploymentId } = MessageWrapper.parse(message2);
148659
- const wsEvents = wsEventsChannelForInvocation(getRunIdFromPayload(payload), config2);
148907
+ const wsEvents = wsEventsChannelForInvocation(getRunIdFromPayload(payload), getWorkflowNameFromQueueName(queueName), config2);
148660
148908
  const collectStepIds = !("stepId" in payload && typeof payload.stepId === "string");
148661
148909
  wsEvents.open();
148662
148910
  try {
@@ -148931,7 +149179,21 @@ function isRetryableEventPostError(err) {
148931
149179
  }
148932
149180
  return collectErrorMarkers(err).some((m2) => TRANSIENT_CODES.has(m2));
148933
149181
  }
148934
- const sleep$1 = (ms2) => new Promise((resolve2) => setTimeout(resolve2, ms2));
149182
+ const sleep$1 = (ms2, signal) => new Promise((resolve2, reject) => {
149183
+ if (signal == null ? void 0 : signal.aborted) {
149184
+ reject(signal.reason);
149185
+ return;
149186
+ }
149187
+ const onAbort = () => {
149188
+ clearTimeout(timer2);
149189
+ reject(signal == null ? void 0 : signal.reason);
149190
+ };
149191
+ const timer2 = setTimeout(() => {
149192
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
149193
+ resolve2();
149194
+ }, ms2);
149195
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
149196
+ });
148935
149197
  const RETRY_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
148936
149198
  function logRetry(message2, fields) {
148937
149199
  if (!RETRY_DEBUG_ENABLED)
@@ -148945,21 +149207,21 @@ function errorMarker(err) {
148945
149207
  }
148946
149208
  return collectErrorMarkers(err)[0] ?? (err instanceof Error ? err.name : "unknown");
148947
149209
  }
148948
- function createThrottleWaiter(eventType) {
149210
+ function createThrottleWaiter(target2) {
148949
149211
  let waitedMs = 0;
148950
- return async (err) => {
149212
+ return async (err, signal) => {
148951
149213
  const waitMs = Math.max(1, typeof err.retryAfter === "number" ? err.retryAfter : DEFAULT_THROTTLE_RETRY_AFTER_SECONDS) * 1e3;
148952
149214
  if (waitedMs + waitMs > THROTTLE_RETRY_BUDGET_MS) {
148953
- logRetry("throttle retry budget exhausted; surfacing to the queue", {
148954
- eventType,
149215
+ logRetry("throttle retry budget exhausted", {
149216
+ target: target2,
148955
149217
  waitedMs,
148956
149218
  retryAfter: err.retryAfter
148957
149219
  });
148958
149220
  throw err;
148959
149221
  }
148960
149222
  waitedMs += waitMs;
148961
- console.warn(`[workflow] Throttled (429) writing ${eventType} event; retrying in-process in ${waitMs / 1e3}s`);
148962
- await sleep$1(waitMs);
149223
+ console.warn(`[workflow] Throttled (429) writing ${target2}; retrying in-process in ${waitMs / 1e3}s`);
149224
+ await sleep$1(waitMs, signal);
148963
149225
  };
148964
149226
  }
148965
149227
  function isEligibleForTransientRetry(eventType, options) {
@@ -148971,7 +149233,7 @@ function isEligibleForTransientRetry(eventType, options) {
148971
149233
  }
148972
149234
  async function withEventPostRetry(fn2, eventType, options) {
148973
149235
  const retryable = isEligibleForTransientRetry(eventType, options);
148974
- const waitOutThrottle = createThrottleWaiter(eventType);
149236
+ const waitOutThrottle = createThrottleWaiter(`${eventType} event`);
148975
149237
  for (let attempt = 0; ; ) {
148976
149238
  try {
148977
149239
  return await fn2();
@@ -149017,6 +149279,29 @@ function encodeFrame(meta, body2) {
149017
149279
  out.set(body2, 4 + metaBytes.byteLength + 4);
149018
149280
  return out;
149019
149281
  }
149282
+ function decodeFrame(raw2) {
149283
+ const view = new DataView(raw2.buffer, raw2.byteOffset, raw2.byteLength);
149284
+ if (raw2.byteLength < 4) {
149285
+ throw new Error("ws frame shorter than the meta length prefix");
149286
+ }
149287
+ const metaEnd = 4 + view.getUint32(0, false);
149288
+ if (raw2.byteLength < metaEnd + 4) {
149289
+ throw new Error("ws frame too short for meta + body length prefix");
149290
+ }
149291
+ const meta = decode$1(raw2.subarray(4, metaEnd));
149292
+ if (meta === null || typeof meta !== "object" || Array.isArray(meta)) {
149293
+ throw new Error("ws frame meta must be a CBOR map");
149294
+ }
149295
+ const bodyStart = metaEnd + 4;
149296
+ const bodyEnd = bodyStart + view.getUint32(metaEnd, false);
149297
+ if (raw2.byteLength !== bodyEnd) {
149298
+ throw new Error(raw2.byteLength < bodyEnd ? "ws frame shorter than its declared body length" : `ws frame has ${raw2.byteLength - bodyEnd} trailing bytes`);
149299
+ }
149300
+ return {
149301
+ meta,
149302
+ body: raw2.subarray(bodyStart, bodyEnd)
149303
+ };
149304
+ }
149020
149305
  async function* decodeFrames(source) {
149021
149306
  const chunks = Symbol.asyncIterator in source ? source[Symbol.asyncIterator]() : readerToIterator(source.getReader());
149022
149307
  let buffer2 = new Uint8Array(0);
@@ -149285,7 +149570,7 @@ async function fetchV4(url, init2, config2, opName, attributes) {
149285
149570
  logLabel: opName,
149286
149571
  // Read the body as bytes, not text: a CBOR error body (the fence 412
149287
149572
  // carries event payloads back) does not survive a UTF-8 decode.
149288
- buildError: async (response3) => errorFromV4Response(response3.status, headersToRecord(response3.headers), new Uint8Array(await response3.arrayBuffer()), opName, url)
149573
+ buildError: async (response3) => errorFromV4Response(response3.status, headersToRecord$1(response3.headers), new Uint8Array(await response3.arrayBuffer()), opName, url)
149289
149574
  });
149290
149575
  if (!response2.body) {
149291
149576
  noteEventsTransportOutcome(dispatcher2);
@@ -149671,14 +149956,14 @@ async function postWorkflowRunEventV4(input, responseType, config2) {
149671
149956
  }
149672
149957
  const STRICT_WS_EVENT_TYPES = /* @__PURE__ */ new Set(["step_completed"]);
149673
149958
  function assertWsFallbackAllowed(eventType) {
149674
- if (!isWsEventsTransportStrict())
149959
+ if (!isWsEventsTransportStrict() || !isWsEventsTransportEnabled())
149675
149960
  return;
149676
149961
  if (!STRICT_WS_EVENT_TYPES.has(eventType))
149677
149962
  return;
149678
149963
  throw new Error(`world-vercel: ${eventType} fell back to the HTTP events transport while the WS gate was on. WORKFLOW_INTERNAL_EVENTS_TRANSPORT_STRICT is set, so this is a failure rather than a silent demotion: no channel was resolvable for this run at write time.`);
149679
149964
  }
149680
149965
  async function createWorkflowRunEventV4(input, config2) {
149681
- if (isWsEventsTransportEnabled()) {
149966
+ if (isWsEventsTransportPossible()) {
149682
149967
  const reply = await postEventFrameOverWs(input, config2);
149683
149968
  if (reply)
149684
149969
  return decodeCreateEventResponse(reply, input.eventType);
@@ -149805,6 +150090,11 @@ function replyMetaToHeaderRecord(meta) {
149805
150090
  out["x-vercel-mitigated"] = meta.mitigated;
149806
150091
  return out;
149807
150092
  }
150093
+ function recordWsReplyParts(span, reply) {
150094
+ const { replyParts = 1 } = reply;
150095
+ if (replyParts > 1)
150096
+ span == null ? void 0 : span.setAttributes({ ...WorkflowWsReplyParts(replyParts) });
150097
+ }
149808
150098
  function wsReplyStatus(reply, endpoint) {
149809
150099
  const { status } = reply.meta;
149810
150100
  if (typeof status !== "number") {
@@ -149845,6 +150135,14 @@ async function postEventFrameOverWs(input, config2) {
149845
150135
  reply = await transport.request((reqId) => {
149846
150136
  span == null ? void 0 : span.setAttributes({ ...WorkflowWsRequestId(reqId) });
149847
150137
  return encodeFrame({ reqId, type: "event", event: buildPostFrameMeta(input) }, input.payload ?? new Uint8Array(0));
150138
+ }, {
150139
+ // Also before sending, for the same reason: a split request that
150140
+ // ends in a close or a timeout is the case worth spotting.
150141
+ onMessages: (count2) => {
150142
+ if (count2 > 1) {
150143
+ span == null ? void 0 : span.setAttributes({ ...WorkflowWsRequestParts(count2) });
150144
+ }
150145
+ }
149848
150146
  });
149849
150147
  } catch (err) {
149850
150148
  const error2 = new WorkflowWorldError(`POST ${endpoint} transport failure: ${err instanceof Error ? err.message : String(err)}`, { url: wsUrl, code: "TRANSPORT", cause: err });
@@ -149853,6 +150151,7 @@ async function postEventFrameOverWs(input, config2) {
149853
150151
  throw error2;
149854
150152
  }
149855
150153
  const ms2 = Date.now() - start2;
150154
+ recordWsReplyParts(span, reply);
149856
150155
  const status = wsReplyStatus(reply, endpoint);
149857
150156
  const headerRecord = replyMetaToHeaderRecord(reply.meta);
149858
150157
  const headers2 = {
@@ -150792,7 +151091,126 @@ async function getHookByToken$1(token, config2) {
150792
151091
  throw error2;
150793
151092
  }
150794
151093
  }
151094
+ function headersToRecord(headers2) {
151095
+ const record2 = {};
151096
+ for (const [key, value] of headers2) {
151097
+ record2[key] = value;
151098
+ }
151099
+ return record2;
151100
+ }
151101
+ function snapshotDiag(fields) {
151102
+ if (!HTTP_DEBUG_ENABLED)
151103
+ return;
151104
+ console.debug("[workflow:world-vercel:http] WORLD_SNAPSHOT_DIAG", fields);
151105
+ }
151106
+ const MAX_SNAPSHOT_ENVELOPE_BYTES = 64 * 1024 * 1024;
151107
+ function createSnapshotsStorage(config2) {
151108
+ return {
151109
+ async save(runId, data2, metadata) {
151110
+ const t0 = performance.now();
151111
+ const { baseUrl, headers: headers2 } = await getHttpConfig(config2);
151112
+ const url = `${baseUrl}/v2/runs/${encodeURIComponent(runId)}/snapshot`;
151113
+ const envelope = encodeSnapshotEnvelope(metadata, data2);
151114
+ if (envelope.byteLength > MAX_SNAPSHOT_ENVELOPE_BYTES) {
151115
+ snapshotDiag({
151116
+ op: "save",
151117
+ runId,
151118
+ outcome: "too_large",
151119
+ wireBytes: envelope.byteLength
151120
+ });
151121
+ throw new WorkflowWorldError(`Snapshot for run ${runId} is ${envelope.byteLength} bytes, over the ${MAX_SNAPSHOT_ENVELOPE_BYTES}-byte limit; not uploading`, { url });
151122
+ }
151123
+ headers2.set("Content-Type", "application/octet-stream");
151124
+ headers2.set("X-Snapshot-Events-Cursor", metadata.eventsCursor ?? "");
151125
+ headers2.set("X-Snapshot-Created-At", metadata.createdAt.toISOString());
151126
+ await injectTraceContextIntoHeaders(headers2);
151127
+ const putStart = performance.now();
151128
+ const response2 = await undiciExports.request(url, {
151129
+ method: "PUT",
151130
+ body: envelope,
151131
+ headers: headersToRecord(headers2),
151132
+ dispatcher: getDispatcher(config2)
151133
+ });
151134
+ const putDurationMs = Math.round(performance.now() - putStart);
151135
+ if (response2.statusCode < 200 || response2.statusCode >= 300) {
151136
+ const text2 = await response2.body.text().catch(() => "");
151137
+ throw new WorkflowWorldError(`PUT /v2/runs/${runId}/snapshot -> HTTP ${response2.statusCode}: ${text2}`, { url, status: response2.statusCode });
151138
+ }
151139
+ await response2.body.text();
151140
+ snapshotDiag({
151141
+ op: "save",
151142
+ runId,
151143
+ // Bytes received from the core — already compressed and
151144
+ // encrypted upstream. The world transports them opaquely
151145
+ // (envelope framing adds the metadata header).
151146
+ wireBytes: envelope.byteLength,
151147
+ putDurationMs,
151148
+ totalDurationMs: Math.round(performance.now() - t0)
151149
+ });
151150
+ },
151151
+ async load(runId) {
151152
+ const t0 = performance.now();
151153
+ const { baseUrl, headers: headers2 } = await getHttpConfig(config2);
151154
+ const url = `${baseUrl}/v2/runs/${encodeURIComponent(runId)}/snapshot`;
151155
+ headers2.set("Accept", "application/octet-stream");
151156
+ await injectTraceContextIntoHeaders(headers2);
151157
+ const getStart = performance.now();
151158
+ const response2 = await fetch(url, {
151159
+ method: "GET",
151160
+ headers: headers2,
151161
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher
151162
+ dispatcher: getDispatcher(config2)
151163
+ });
151164
+ const getDurationMs = Math.round(performance.now() - getStart);
151165
+ if (response2.status === 404) {
151166
+ await response2.text().catch(() => {
151167
+ });
151168
+ snapshotDiag({
151169
+ op: "load",
151170
+ runId,
151171
+ outcome: "not_found",
151172
+ getDurationMs,
151173
+ totalDurationMs: Math.round(performance.now() - t0)
151174
+ });
151175
+ return null;
151176
+ }
151177
+ if (!response2.ok) {
151178
+ const text2 = await response2.text().catch(() => "");
151179
+ throw new WorkflowWorldError(`GET /v2/runs/${runId}/snapshot -> HTTP ${response2.status}: ${text2}`, { url, status: response2.status });
151180
+ }
151181
+ const buffer2 = await response2.arrayBuffer();
151182
+ const envelope = new Uint8Array(buffer2);
151183
+ const decoded = decodeSnapshotEnvelope(envelope);
151184
+ snapshotDiag({
151185
+ op: "load",
151186
+ runId,
151187
+ outcome: decoded ? "ok" : "undecodable_envelope",
151188
+ wireBytes: envelope.byteLength,
151189
+ getDurationMs,
151190
+ totalDurationMs: Math.round(performance.now() - t0)
151191
+ });
151192
+ return decoded;
151193
+ },
151194
+ async delete(runId) {
151195
+ const { baseUrl, headers: headers2 } = await getHttpConfig(config2);
151196
+ const url = `${baseUrl}/v2/runs/${encodeURIComponent(runId)}/snapshot`;
151197
+ await injectTraceContextIntoHeaders(headers2);
151198
+ const response2 = await fetch(url, {
151199
+ method: "DELETE",
151200
+ headers: headers2,
151201
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher
151202
+ dispatcher: getDispatcher(config2)
151203
+ });
151204
+ if (!response2.ok && response2.status !== 404) {
151205
+ const text2 = await response2.text().catch(() => "");
151206
+ throw new WorkflowWorldError(`DELETE /v2/runs/${runId}/snapshot -> HTTP ${response2.status}: ${text2}`, { url, status: response2.status });
151207
+ }
151208
+ await response2.text();
151209
+ }
151210
+ };
151211
+ }
150795
151212
  function createStorage(config2) {
151213
+ const snapshots = createSnapshotsStorage(config2);
150796
151214
  const storage = {
150797
151215
  // Storage interface with namespaced methods
150798
151216
  runs: {
@@ -150824,7 +151242,8 @@ function createStorage(config2) {
150824
151242
  runs: instrumentObject("world.runs", storage.runs),
150825
151243
  steps: instrumentObject("world.steps", storage.steps),
150826
151244
  events: instrumentObject("world.events", storage.events),
150827
- hooks: instrumentObject("world.hooks", storage.hooks)
151245
+ hooks: instrumentObject("world.hooks", storage.hooks),
151246
+ experimental_snapshots: instrumentObject("world.experimental_snapshots", snapshots)
150828
151247
  };
150829
151248
  }
150830
151249
  const MAX_CHUNKS_PER_STREAM_WRITE = 1e3;
@@ -150856,6 +151275,8 @@ function encodeNormalizedMultiChunks(binaryChunks) {
150856
151275
  }
150857
151276
  const STREAM_WS_V1_MAX_CHUNKS_PER_WRITE = MAX_CHUNKS_PER_STREAM_WRITE;
150858
151277
  const STREAM_WS_V1_MAX_CHUNK_BYTES = 10 * 1024 * 1024;
151278
+ const STREAM_WS_V1_WRITE_ENVELOPE_MAX_BYTES = 128;
151279
+ const CHUNK_RECORD_PREFIX_BYTES = 4;
150859
151280
  const NonnegativeIntegerSchema = number$3().int().nonnegative();
150860
151281
  const RequestIdSchema = NonnegativeIntegerSchema;
150861
151282
  const StreamWriterIdSchema = string$2().regex(/^wrtr_[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/);
@@ -150885,7 +151306,8 @@ const StreamWsErrorMetaSchema = object$1({
150885
151306
  type: literal$1("error"),
150886
151307
  reqId: RequestIdSchema.optional(),
150887
151308
  status: number$3().int(),
150888
- message: string$2().optional()
151309
+ message: string$2().optional(),
151310
+ retryAfter: string$2().optional()
150889
151311
  });
150890
151312
  const StreamWsDrainMetaSchema = object$1({
150891
151313
  type: literal$1("drain"),
@@ -150920,6 +151342,18 @@ function encodeStreamWsWriteRequest(meta, chunks) {
150920
151342
  }
150921
151343
  return encodeFrame(parsed, encodeNormalizedMultiChunks(binaryChunks));
150922
151344
  }
151345
+ function streamWsWriteBatchEnd(chunks, start2, maxMessageBytes) {
151346
+ const countEnd = Math.min(chunks.length, start2 + STREAM_WS_V1_MAX_CHUNKS_PER_WRITE);
151347
+ let bytes = STREAM_WS_V1_WRITE_ENVELOPE_MAX_BYTES + CHUNK_RECORD_PREFIX_BYTES + chunks[start2].byteLength;
151348
+ let end = start2 + 1;
151349
+ while (end < countEnd) {
151350
+ bytes += CHUNK_RECORD_PREFIX_BYTES + chunks[end].byteLength;
151351
+ if (bytes > maxMessageBytes)
151352
+ break;
151353
+ end++;
151354
+ }
151355
+ return end;
151356
+ }
150923
151357
  function encodeStreamWsCloseRequest(meta) {
150924
151358
  return encodeFrame(StreamWsCloseRequestMetaSchema.parse(meta), new Uint8Array());
150925
151359
  }
@@ -150929,6 +151363,209 @@ function parseStreamWsReply(meta, body2) {
150929
151363
  }
150930
151364
  return StreamWsReplyMetaSchema.parse(meta);
150931
151365
  }
151366
+ const WS_FLAGS_HEADER = "x-workflow-ws-flags";
151367
+ const WS_FLAG_FRAME_PARTS = "frame-parts";
151368
+ const WS_CLIENT_FLAGS = [WS_FLAG_FRAME_PARTS];
151369
+ const WS_PART_TYPE = "part";
151370
+ const DEFAULT_WS_MAX_MESSAGE_BYTES = 12 * 1024 * 1024;
151371
+ const MAX_WS_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
151372
+ const MIN_WS_MAX_MESSAGE_BYTES = 2 * 1024 * 1024;
151373
+ function wsMaxMessageBytes() {
151374
+ return envNumber("WORKFLOW_WS_MAX_MESSAGE_BYTES", DEFAULT_WS_MAX_MESSAGE_BYTES, {
151375
+ min: MIN_WS_MAX_MESSAGE_BYTES,
151376
+ max: MAX_WS_MAX_MESSAGE_BYTES,
151377
+ integer: true
151378
+ });
151379
+ }
151380
+ function encodeWsFrameMessages(meta, body2, maxMessageBytes) {
151381
+ const whole = encodeFrame(meta, body2);
151382
+ if (whole.byteLength <= maxMessageBytes)
151383
+ return [whole];
151384
+ if (body2.byteLength > WS_MAX_FRAME_BYTES) {
151385
+ throw new WsFrameTooLargeError(`ws frame body of ${body2.byteLength} bytes is over the ${WS_MAX_FRAME_BYTES}-byte limit for a split frame`);
151386
+ }
151387
+ const reqId = meta.reqId;
151388
+ if (!isClientReqId(reqId)) {
151389
+ throw new Error(`ws frame of ${whole.byteLength} bytes exceeds the ${maxMessageBytes}-byte message limit and has no reqId to split it under`);
151390
+ }
151391
+ const bound = body2.byteLength + 1;
151392
+ const firstHeaderBytes = encodeFrame({ ...meta, partIndex: 0, partCount: bound }, EMPTY).byteLength;
151393
+ const continuationHeaderBytes = encodeFrame(continuationMeta(reqId, bound, bound), EMPTY).byteLength;
151394
+ const firstSlice = maxMessageBytes - firstHeaderBytes;
151395
+ const continuationSlice = maxMessageBytes - continuationHeaderBytes;
151396
+ if (firstSlice <= 0 || continuationSlice <= 0) {
151397
+ throw new Error(`ws frame meta does not fit in the ${maxMessageBytes}-byte message limit`);
151398
+ }
151399
+ const rest = body2.byteLength - firstSlice;
151400
+ const partCount = 1 + Math.ceil(rest / continuationSlice);
151401
+ if (partCount > WS_MAX_PART_COUNT) {
151402
+ throw new Error(`ws frame of ${whole.byteLength} bytes needs ${partCount} parts at a ${maxMessageBytes}-byte message limit; at most ${WS_MAX_PART_COUNT} are allowed`);
151403
+ }
151404
+ const messages = [
151405
+ encodeFrame({ ...meta, partIndex: 0, partCount }, body2.subarray(0, firstSlice))
151406
+ ];
151407
+ for (let index2 = 1; index2 < partCount; index2++) {
151408
+ const start2 = firstSlice + (index2 - 1) * continuationSlice;
151409
+ messages.push(encodeFrame(continuationMeta(reqId, index2, partCount), body2.subarray(start2, Math.min(start2 + continuationSlice, body2.byteLength))));
151410
+ }
151411
+ return messages;
151412
+ }
151413
+ const EMPTY = new Uint8Array(0);
151414
+ function splitEncodedFrame(frame2, maxMessageBytes) {
151415
+ if (frame2.byteLength <= maxMessageBytes)
151416
+ return [frame2];
151417
+ const { meta, body: body2 } = decodeFrame(frame2);
151418
+ return encodeWsFrameMessages(meta, body2, maxMessageBytes);
151419
+ }
151420
+ function continuationMeta(reqId, partIndex, partCount) {
151421
+ return { type: WS_PART_TYPE, reqId, partIndex, partCount };
151422
+ }
151423
+ class WsFrameTooLargeError extends Error {
151424
+ constructor() {
151425
+ super(...arguments);
151426
+ __publicField(this, "name", "WsFrameTooLargeError");
151427
+ }
151428
+ }
151429
+ class WsPartProtocolError extends Error {
151430
+ constructor() {
151431
+ super(...arguments);
151432
+ __publicField(this, "name", "WsPartProtocolError");
151433
+ }
151434
+ }
151435
+ const WS_MAX_FRAME_BYTES = 256 * 1024 * 1024;
151436
+ const WS_MAX_OPEN_FRAMES = 1;
151437
+ const WS_MAX_PART_COUNT = 257;
151438
+ class WsPartAssembler {
151439
+ constructor(options = {}) {
151440
+ __publicField(this, "open", /* @__PURE__ */ new Map());
151441
+ __publicField(this, "maxFrameBytes");
151442
+ __publicField(this, "maxBodyBytes");
151443
+ __publicField(this, "onTooLarge");
151444
+ __publicField(this, "maxOpenFrames");
151445
+ __publicField(this, "maxPartCount");
151446
+ __publicField(this, "wanted");
151447
+ __publicField(this, "onDiscarded");
151448
+ this.maxFrameBytes = options.maxFrameBytes ?? WS_MAX_FRAME_BYTES;
151449
+ this.maxBodyBytes = Math.min(options.maxBodyBytes ?? this.maxFrameBytes, this.maxFrameBytes);
151450
+ this.onTooLarge = options.onTooLarge ?? (() => {
151451
+ });
151452
+ this.maxOpenFrames = options.maxOpenFrames ?? WS_MAX_OPEN_FRAMES;
151453
+ this.maxPartCount = options.maxPartCount ?? WS_MAX_PART_COUNT;
151454
+ this.wanted = options.wanted ?? (() => true);
151455
+ this.onDiscarded = options.onDiscarded ?? (() => {
151456
+ });
151457
+ }
151458
+ accept(frame2) {
151459
+ const { meta, body: body2 } = frame2;
151460
+ if (meta.type === WS_PART_TYPE)
151461
+ return this.continue(meta, body2);
151462
+ const { reqId, partIndex, partCount } = meta;
151463
+ if (!("partIndex" in meta) && !("partCount" in meta)) {
151464
+ if (isClientReqId(reqId) && this.open.has(reqId)) {
151465
+ throw new WsPartProtocolError(`whole frame for reqId ${reqId} while its split frame is open`);
151466
+ }
151467
+ return frame2;
151468
+ }
151469
+ if (!isClientReqId(reqId)) {
151470
+ throw new WsPartProtocolError("first part has no valid reqId");
151471
+ }
151472
+ if (partIndex !== 0) {
151473
+ throw new WsPartProtocolError(`first part for reqId ${reqId} has partIndex ${String(partIndex)}, expected 0`);
151474
+ }
151475
+ if (!isPartCount(partCount) || partCount > this.maxPartCount) {
151476
+ throw new WsPartProtocolError(`first part for reqId ${reqId} has invalid partCount ${String(partCount)} (2..${this.maxPartCount})`);
151477
+ }
151478
+ if (this.open.has(reqId)) {
151479
+ throw new WsPartProtocolError(`second first part for reqId ${reqId} while one is open`);
151480
+ }
151481
+ if (this.open.size >= this.maxOpenFrames) {
151482
+ throw new WsPartProtocolError(`more than ${this.maxOpenFrames} split frames open at once`);
151483
+ }
151484
+ const { partIndex: _index, partCount: _count, ...frameMeta } = meta;
151485
+ const entry2 = {
151486
+ meta: frameMeta,
151487
+ partCount,
151488
+ nextIndex: 1,
151489
+ chunks: [],
151490
+ bytes: 0,
151491
+ discard: !this.wanted(reqId),
151492
+ tooLarge: false
151493
+ };
151494
+ this.open.set(reqId, entry2);
151495
+ this.addChunk(reqId, entry2, body2);
151496
+ return void 0;
151497
+ }
151498
+ /** Number of split frames still arriving. */
151499
+ get openFrames() {
151500
+ return this.open.size;
151501
+ }
151502
+ continue(meta, body2) {
151503
+ const keys2 = Object.keys(meta);
151504
+ if (keys2.length !== 4 || !("reqId" in meta) || !("partIndex" in meta) || !("partCount" in meta)) {
151505
+ throw new WsPartProtocolError(`continuation part must have exactly type, reqId, partIndex and partCount, got ${keys2.join(", ")}`);
151506
+ }
151507
+ const { reqId, partIndex, partCount } = meta;
151508
+ if (!isClientReqId(reqId)) {
151509
+ throw new WsPartProtocolError("continuation part has no valid reqId");
151510
+ }
151511
+ const entry2 = this.open.get(reqId);
151512
+ if (!entry2) {
151513
+ throw new WsPartProtocolError(`continuation part for reqId ${reqId} with no open frame`);
151514
+ }
151515
+ if (partCount !== entry2.partCount) {
151516
+ throw new WsPartProtocolError(`continuation part for reqId ${reqId} has partCount ${String(partCount)}, expected ${entry2.partCount}`);
151517
+ }
151518
+ if (partIndex !== entry2.nextIndex) {
151519
+ throw new WsPartProtocolError(`continuation part for reqId ${reqId} has partIndex ${String(partIndex)}, expected ${entry2.nextIndex}`);
151520
+ }
151521
+ const last = entry2.nextIndex === entry2.partCount - 1;
151522
+ this.addChunk(reqId, entry2, body2);
151523
+ entry2.nextIndex++;
151524
+ if (!last)
151525
+ return void 0;
151526
+ this.close(reqId);
151527
+ if (entry2.tooLarge) {
151528
+ this.onTooLarge(reqId, entry2.bytes);
151529
+ return void 0;
151530
+ }
151531
+ if (entry2.discard) {
151532
+ this.onDiscarded(reqId);
151533
+ return void 0;
151534
+ }
151535
+ const joined = new Uint8Array(entry2.bytes);
151536
+ let offset3 = 0;
151537
+ for (const chunk of entry2.chunks) {
151538
+ joined.set(chunk, offset3);
151539
+ offset3 += chunk.byteLength;
151540
+ }
151541
+ return { meta: entry2.meta, body: joined };
151542
+ }
151543
+ addChunk(reqId, entry2, body2) {
151544
+ if (entry2.bytes + body2.byteLength > this.maxFrameBytes) {
151545
+ this.close(reqId);
151546
+ throw new WsPartProtocolError(`frame for reqId ${reqId} exceeds ${this.maxFrameBytes} bytes`);
151547
+ }
151548
+ entry2.bytes += body2.byteLength;
151549
+ if (!entry2.discard && entry2.bytes > this.maxBodyBytes) {
151550
+ entry2.discard = true;
151551
+ entry2.tooLarge = true;
151552
+ entry2.chunks = [];
151553
+ }
151554
+ if (entry2.discard)
151555
+ return;
151556
+ entry2.chunks.push(body2.slice());
151557
+ }
151558
+ /** Forget an open frame, releasing its buffered bytes. */
151559
+ close(reqId) {
151560
+ this.open.delete(reqId);
151561
+ }
151562
+ }
151563
+ function isClientReqId(value) {
151564
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
151565
+ }
151566
+ function isPartCount(value) {
151567
+ return typeof value === "number" && Number.isInteger(value) && value >= 2;
151568
+ }
150932
151569
  const STREAM_WS_INITIAL_CONNECT_TIMEOUT_MS = 1e4;
150933
151570
  const STREAM_WS_RECONNECT_BUDGET_MS = 250;
150934
151571
  const STREAM_WS_CLOSE_BUDGET_MS = 250;
@@ -150957,7 +151594,7 @@ function beginNormalWsClose(ws, reason) {
150957
151594
  await observed;
150958
151595
  span == null ? void 0 : span.setAttribute("workflow.stream.ws.close_cleanup_timeout", timedOut);
150959
151596
  });
150960
- void import("./index-DnTW8Yiv.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => waitUntil2(cleanup)).catch(() => {
151597
+ void import("./index-B2Fjee_4.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => waitUntil2(cleanup)).catch(() => {
150961
151598
  });
150962
151599
  void cleanup.catch(() => {
150963
151600
  });
@@ -151027,18 +151664,19 @@ class StreamWsRequestNotSentError extends Error {
151027
151664
  this.name = "StreamWsRequestNotSentError";
151028
151665
  }
151029
151666
  }
151030
- async function decodeOne(raw2) {
151031
- let frame2;
151032
- for await (const candidate of decodeFrames((async function* () {
151033
- yield raw2;
151034
- })())) {
151035
- if (frame2)
151036
- throw new Error("stream WebSocket message has multiple frames");
151037
- frame2 = candidate;
151667
+ class StreamWsThrottledError extends Error {
151668
+ constructor(message2, retryAfter) {
151669
+ super(message2);
151670
+ __publicField(this, "retryAfter");
151671
+ this.retryAfter = retryAfter;
151672
+ this.name = "StreamWsThrottledError";
151673
+ }
151674
+ }
151675
+ class StreamWsCloseRetriableError extends Error {
151676
+ constructor(message2) {
151677
+ super(message2);
151678
+ this.name = "StreamWsCloseRetriableError";
151038
151679
  }
151039
- if (!frame2)
151040
- throw new Error("stream WebSocket message has no frame");
151041
- return frame2;
151042
151680
  }
151043
151681
  function asBytes(raw2) {
151044
151682
  if (raw2 instanceof Uint8Array)
@@ -151065,6 +151703,10 @@ class VercelStreamWriteSession {
151065
151703
  __publicField(this, "nextReqId", 1);
151066
151704
  __publicField(this, "pending");
151067
151705
  __publicField(this, "poisonError");
151706
+ /** The socket that returned a 429 whose retry is still waiting. */
151707
+ __publicField(this, "throttledSocket");
151708
+ /** Aborted on dispose or poison, ending any throttle wait early. */
151709
+ __publicField(this, "terminated", new AbortController());
151068
151710
  __publicField(this, "wsUrl");
151069
151711
  __publicField(this, "closeAcknowledged", false);
151070
151712
  __publicField(this, "idleReconnects", 0);
@@ -151114,29 +151756,45 @@ class VercelStreamWriteSession {
151114
151756
  await this.transportDecision;
151115
151757
  this.assertUsable();
151116
151758
  if (this.mode === "http") {
151117
- await this.writeHttp(chunks);
151759
+ await this.writeHttpOrFail(chunks);
151118
151760
  return;
151119
151761
  }
151120
- for (let offset3 = 0; offset3 < chunks.length; offset3 += STREAM_WS_V1_MAX_CHUNKS_PER_WRITE) {
151121
- const batch = chunks.slice(offset3, offset3 + STREAM_WS_V1_MAX_CHUNKS_PER_WRITE);
151762
+ const maxMessageBytes = wsMaxMessageBytes();
151763
+ const binaryChunks = normalizeStreamChunks(chunks);
151764
+ for (let offset3 = 0; offset3 < chunks.length; ) {
151765
+ const end = streamWsWriteBatchEnd(binaryChunks, offset3, maxMessageBytes);
151766
+ const batch = binaryChunks.slice(offset3, end);
151122
151767
  let reply;
151123
151768
  try {
151124
- reply = await this.request((reqId) => encodeStreamWsWriteRequest({
151769
+ reply = await this.requestRetryingThrottle("write", (reqId) => encodeStreamWsWriteRequest({
151125
151770
  type: "write",
151126
151771
  reqId,
151127
151772
  chunkSeq: chunkSeq + offset3,
151128
151773
  numChunks: batch.length
151129
- }, batch), offset3 === 0 ? timing : void 0, { chunkSeq: chunkSeq + offset3, numChunks: batch.length });
151774
+ }, batch), offset3 === 0 ? timing : void 0, { chunkSeq: chunkSeq + offset3, numChunks: batch.length }, maxMessageBytes);
151130
151775
  } catch (error2) {
151131
151776
  if (!(error2 instanceof StreamWsRequestNotSentError))
151132
151777
  throw error2;
151133
151778
  this.fallbackToHttpBeforeSend();
151134
- await this.writeHttp(chunks.slice(offset3));
151779
+ await this.writeHttpOrFail(chunks.slice(offset3));
151135
151780
  return;
151136
151781
  }
151137
151782
  if (reply.type !== "write_ack") {
151138
151783
  throw this.poison(new Error(`stream WebSocket write received ${reply.type}`));
151139
151784
  }
151785
+ offset3 = end;
151786
+ }
151787
+ }
151788
+ /**
151789
+ * An HTTP write whose outcome may be unknown fails the writer, as on every
151790
+ * other transport, so a queued write cannot apply ahead of it.
151791
+ */
151792
+ async writeHttpOrFail(chunks) {
151793
+ try {
151794
+ await this.writeHttp(chunks);
151795
+ } catch (error2) {
151796
+ this.failUnknown(error2);
151797
+ throw this.poisonError;
151140
151798
  }
151141
151799
  }
151142
151800
  shouldWriteHttpWhileConnecting() {
@@ -151195,6 +151853,7 @@ class VercelStreamWriteSession {
151195
151853
  if (this.mode === "closed")
151196
151854
  return;
151197
151855
  this.mode = "closed";
151856
+ this.terminated.abort();
151198
151857
  this.finishDrainWait();
151199
151858
  const pending = this.pending;
151200
151859
  this.pending = void 0;
@@ -151221,25 +151880,29 @@ class VercelStreamWriteSession {
151221
151880
  this.mode = "closed";
151222
151881
  return;
151223
151882
  }
151224
- let reply;
151225
- try {
151226
- reply = await this.request((reqId) => encodeStreamWsCloseRequest({ type: "close", reqId }));
151227
- } catch (error2) {
151228
- if (!(error2 instanceof StreamWsRequestNotSentError))
151229
- throw error2;
151230
- this.fallbackToHttpBeforeSend();
151231
- await this.closeHttp();
151232
- this.mode = "closed";
151233
- return;
151234
- }
151235
- if (reply.type !== "close_ack") {
151236
- throw this.poison(new Error(`stream WebSocket close received ${reply.type}`));
151237
- }
151238
- this.mode = "closed";
151239
- if (this.socket)
151240
- beginNormalWsClose(this.socket, "stream closed");
151883
+ await this.closeOverWs();
151241
151884
  });
151242
151885
  }
151886
+ async closeOverWs() {
151887
+ let reply;
151888
+ try {
151889
+ reply = await this.requestRetryingThrottle("close", (reqId) => encodeStreamWsCloseRequest({ type: "close", reqId }));
151890
+ } catch (error2) {
151891
+ const httpRetry = error2 instanceof StreamWsRequestNotSentError || error2 instanceof StreamWsCloseRetriableError;
151892
+ if (!httpRetry)
151893
+ throw error2;
151894
+ this.fallbackToHttpBeforeSend();
151895
+ await this.closeHttp();
151896
+ this.mode = "closed";
151897
+ return;
151898
+ }
151899
+ if (reply.type !== "close_ack") {
151900
+ throw this.poison(new Error(`stream WebSocket close received ${reply.type}`));
151901
+ }
151902
+ this.mode = "closed";
151903
+ if (this.socket)
151904
+ beginNormalWsClose(this.socket, "stream closed");
151905
+ }
151243
151906
  enqueue(operation) {
151244
151907
  const result = this.tail.then(operation);
151245
151908
  this.tail = result.catch(() => {
@@ -151309,7 +151972,7 @@ class VercelStreamWriteSession {
151309
151972
  return http3;
151310
151973
  });
151311
151974
  const [{ WebSocket: WebSocketImpl }, http2] = await Promise.all([
151312
- import("./wrapper-BsMfBV09.js"),
151975
+ import("./wrapper-D66LMJdl.js"),
151313
151976
  httpPromise
151314
151977
  ]);
151315
151978
  if (this.mode !== "connecting")
@@ -151338,7 +152001,7 @@ class VercelStreamWriteSession {
151338
152001
  return;
151339
152002
  timing.socketStartedAt = now$1();
151340
152003
  const ws = new WebSocketImpl(url, {
151341
- headers: headersToRecord(http2.headers)
152004
+ headers: headersToRecord$1(http2.headers)
151342
152005
  });
151343
152006
  this.socket = ws;
151344
152007
  ws.binaryType = "nodebuffer";
@@ -151375,7 +152038,13 @@ class VercelStreamWriteSession {
151375
152038
  fallback();
151376
152039
  return;
151377
152040
  }
151378
- this.failUnknown(error2);
152041
+ void this.inbound.then(() => {
152042
+ if (this.isIdleThrottledSocket(ws)) {
152043
+ this.leaveThrottledSocketForHttp();
152044
+ return;
152045
+ }
152046
+ this.failUnknown(error2);
152047
+ });
151379
152048
  });
151380
152049
  ws.once("close", (code2) => {
151381
152050
  if (!opened) {
@@ -151392,9 +152061,8 @@ class VercelStreamWriteSession {
151392
152061
  });
151393
152062
  }
151394
152063
  async handleMessage(raw2, receivedAt) {
151395
- var _a3;
151396
152064
  try {
151397
- const frame2 = await decodeOne(raw2);
152065
+ const frame2 = decodeFrame(raw2);
151398
152066
  const reply = parseStreamWsReply(frame2.meta, frame2.body);
151399
152067
  if (reply.type === "drain") {
151400
152068
  this.handleDrain(reply.reason, reply.graceMs);
@@ -151413,8 +152081,7 @@ class VercelStreamWriteSession {
151413
152081
  if (reply.type === "close_ack")
151414
152082
  this.closeAcknowledged = true;
151415
152083
  if (reply.type === "error") {
151416
- pending.reject(this.poison(new Error(`stream WebSocket request failed (${reply.status}): ${reply.message ?? "unknown error"}`)));
151417
- (_a3 = this.socket) == null ? void 0 : _a3.close(1011, "stream request failed");
152084
+ pending.reject(this.requestError(pending, reply));
151418
152085
  } else {
151419
152086
  if (reply.type === "write_ack")
151420
152087
  this.idleReconnects = 0;
@@ -151466,6 +152133,10 @@ class VercelStreamWriteSession {
151466
152133
  this.failUnknown(new Error("stream WebSocket closed before reply"));
151467
152134
  return;
151468
152135
  }
152136
+ if (socket && this.isIdleThrottledSocket(socket) && this.mode === "ws") {
152137
+ this.leaveThrottledSocketForHttp();
152138
+ return;
152139
+ }
151469
152140
  if (this.mode === "draining" && code2 !== 1001) {
151470
152141
  this.drainReason = void 0;
151471
152142
  this.mode = "http";
@@ -151502,7 +152173,7 @@ class VercelStreamWriteSession {
151502
152173
  this.connect = this.startConnect();
151503
152174
  this.transportDecision = this.makeTransportDecision(true);
151504
152175
  }
151505
- async request(buildFrame, writeTiming, writeMetadata) {
152176
+ async request(operation, buildFrame, writeTiming, writeMetadata, maxMessageBytes = wsMaxMessageBytes()) {
151506
152177
  this.assertUsable();
151507
152178
  const ws = this.socket;
151508
152179
  if (this.mode !== "ws" || !ws || ws.readyState !== 1) {
@@ -151515,6 +152186,9 @@ class VercelStreamWriteSession {
151515
152186
  } catch (error2) {
151516
152187
  throw new StreamWsRequestNotSentError(error2);
151517
152188
  }
152189
+ if (frame2.byteLength > maxMessageBytes) {
152190
+ throw new StreamWsRequestNotSentError(new Error(`stream WebSocket message is ${frame2.byteLength} bytes; maximum is ${maxMessageBytes}`));
152191
+ }
151518
152192
  const connectionTiming = this.connectionTiming;
151519
152193
  const connectionFirstWrite = (connectionTiming == null ? void 0 : connectionTiming.firstWriteSent) === false;
151520
152194
  const detailedTiming = writeTiming && (writeTiming.sessionFirstWrite || connectionFirstWrite) ? writeTiming : void 0;
@@ -151542,7 +152216,7 @@ class VercelStreamWriteSession {
151542
152216
  this.failUnknown(new Error(`stream WebSocket request ${reqId} timed out with no reply`));
151543
152217
  }, getRequestTimeoutMs());
151544
152218
  (_a3 = timer2.unref) == null ? void 0 : _a3.call(timer2);
151545
- pending = { reqId, resolve: resolve2, reject, timer: timer2 };
152219
+ pending = { reqId, operation, resolve: resolve2, reject, timer: timer2 };
151546
152220
  this.pending = pending;
151547
152221
  try {
151548
152222
  if (detailedTiming) {
@@ -151575,11 +152249,77 @@ class VercelStreamWriteSession {
151575
152249
  this.releaseDrainWait = void 0;
151576
152250
  release == null ? void 0 : release();
151577
152251
  }
151578
- fallbackToHttpBeforeSend() {
152252
+ fallbackToHttpBeforeSend(reason = "HTTP fallback before send") {
151579
152253
  var _a3;
151580
152254
  this.mode = "http";
151581
- (_a3 = this.socket) == null ? void 0 : _a3.close(1e3, "HTTP fallback before send");
152255
+ this.drainReason = void 0;
152256
+ (_a3 = this.socket) == null ? void 0 : _a3.close(1e3, reason);
151582
152257
  this.socket = void 0;
152258
+ this.finishDrainWait();
152259
+ }
152260
+ /**
152261
+ * Classifies a correlated error and applies its session effect
152262
+ * synchronously, before a close the server queued behind it is handled.
152263
+ */
152264
+ requestError(pending, reply) {
152265
+ var _a3;
152266
+ const detail = `(${reply.status}): ${reply.message ?? "unknown error"}`;
152267
+ if (reply.status === 429) {
152268
+ this.throttledSocket = this.socket;
152269
+ return new StreamWsThrottledError(`stream WebSocket ${pending.operation} throttled ${detail}`, parseRetryAfter(reply.retryAfter));
152270
+ }
152271
+ if (pending.operation === "close" && reply.status >= 500 && reply.status <= 599) {
152272
+ this.fallbackToHttpBeforeSend("stream close retried over HTTP");
152273
+ return new StreamWsCloseRetriableError(`stream WebSocket close failed ${detail}`);
152274
+ }
152275
+ const poisoned = this.poison(new Error(`stream WebSocket request failed ${detail}`));
152276
+ (_a3 = this.socket) == null ? void 0 : _a3.close(1011, "stream request failed");
152277
+ return poisoned;
152278
+ }
152279
+ /**
152280
+ * Sends one request, resending it (same frame contents, new reqId) after
152281
+ * each correlated 429 on the shared event-write throttle budget. A resend
152282
+ * whose socket closed meanwhile, or one past the budget, throws
152283
+ * StreamWsRequestNotSentError, which callers turn into an HTTP fallback.
152284
+ */
152285
+ async requestRetryingThrottle(operation, buildFrame, writeTiming, writeMetadata, maxMessageBytes) {
152286
+ const waitOutThrottle = createThrottleWaiter(operation === "write" ? "stream chunks" : "stream close");
152287
+ for (let attempt = 0; ; attempt++) {
152288
+ try {
152289
+ return await this.request(operation, buildFrame, attempt === 0 ? writeTiming : void 0, writeMetadata, maxMessageBytes);
152290
+ } catch (error2) {
152291
+ if (!(error2 instanceof StreamWsThrottledError))
152292
+ throw error2;
152293
+ await this.waitOutThrottle(waitOutThrottle, error2);
152294
+ }
152295
+ }
152296
+ }
152297
+ async waitOutThrottle(wait, error2) {
152298
+ try {
152299
+ await wait(error2, this.terminated.signal);
152300
+ } catch {
152301
+ this.assertUsable();
152302
+ this.fallbackToHttpBeforeSend("stream request throttled");
152303
+ throw new StreamWsRequestNotSentError(error2);
152304
+ } finally {
152305
+ this.throttledSocket = void 0;
152306
+ }
152307
+ await this.transportDecision;
152308
+ this.assertUsable();
152309
+ }
152310
+ isIdleThrottledSocket(socket) {
152311
+ return !this.pending && socket === this.throttledSocket && socket === this.socket;
152312
+ }
152313
+ /**
152314
+ * The connection ended after a retryable rejection with nothing outstanding:
152315
+ * the rejected request did not apply, so it and everything after it can go
152316
+ * over HTTP rather than reconnecting.
152317
+ */
152318
+ leaveThrottledSocketForHttp() {
152319
+ this.drainReason = void 0;
152320
+ this.mode = "http";
152321
+ this.socket = void 0;
152322
+ this.finishDrainWait();
151583
152323
  }
151584
152324
  failUnknown(error2) {
151585
152325
  var _a3;
@@ -151597,6 +152337,7 @@ class VercelStreamWriteSession {
151597
152337
  if (this.mode !== "poisoned") {
151598
152338
  this.mode = "poisoned";
151599
152339
  this.poisonError = error2;
152340
+ this.terminated.abort();
151600
152341
  }
151601
152342
  return this.poisonError;
151602
152343
  }
@@ -155550,15 +156291,6 @@ function readAuthorization(headers2) {
155550
156291
  }
155551
156292
  return null;
155552
156293
  }
155553
- async function decodeOneFrame(raw2) {
155554
- const source = (async function* () {
155555
- yield raw2;
155556
- })();
155557
- for await (const frame2 of decodeFrames(source)) {
155558
- return frame2;
155559
- }
155560
- throw new Error("ws-transport: received an empty/unframed message");
155561
- }
155562
156294
  function errorFrameMessage(body2) {
155563
156295
  if (body2.byteLength === 0)
155564
156296
  return "(no message)";
@@ -155601,18 +156333,20 @@ class WsEventsTransport {
155601
156333
  }
155602
156334
  /** Send one request frame and wait for its matching reply. `buildFrame`
155603
156335
  * receives the reqId to embed in the meta before framing. */
155604
- async request(buildFrame) {
156336
+ async request(buildFrame, options = {}) {
156337
+ var _a3;
155605
156338
  if (this.closed) {
155606
156339
  throw new WsTransportError(`workflow-server events WS channel for ${this.wsUrl} is closed`);
155607
156340
  }
155608
156341
  const conn = await this.ensureConnected();
155609
156342
  const reqId = conn.nextReqId++;
155610
- const frame2 = buildFrame(reqId);
156343
+ const messages = splitEncodedFrame(buildFrame(reqId), wsMaxMessageBytes());
156344
+ (_a3 = options.onMessages) == null ? void 0 : _a3.call(options, messages.length);
155611
156345
  const timeoutMs = getRequestTimeoutMs();
155612
156346
  let deadline;
155613
156347
  try {
155614
- return await new Promise((resolve2, reject) => {
155615
- var _a3;
156348
+ const reply = await new Promise((resolve2, reject) => {
156349
+ var _a4;
155616
156350
  conn.pending.set(reqId, { resolve: resolve2, reject });
155617
156351
  deadline = setTimeout(() => {
155618
156352
  if (!conn.pending.delete(reqId))
@@ -155620,15 +156354,18 @@ class WsEventsTransport {
155620
156354
  reject(new WsTransportError(`workflow-server events WS request ${reqId} to ${this.wsUrl} timed out after ${timeoutMs}ms with no reply`));
155621
156355
  this.failConnection(conn, `workflow-server events WS connection to ${this.wsUrl} abandoned after request ${reqId} timed out`);
155622
156356
  }, timeoutMs);
155623
- (_a3 = deadline.unref) == null ? void 0 : _a3.call(deadline);
155624
- conn.ws.send(frame2, (err) => {
156357
+ (_a4 = deadline.unref) == null ? void 0 : _a4.call(deadline);
156358
+ const onSent = (err) => {
155625
156359
  if (!err)
155626
156360
  return;
155627
156361
  if (conn.pending.delete(reqId)) {
155628
156362
  reject(new WsTransportError(`workflow-server events WS send failed: ${describeError(err)}`, { cause: err }));
155629
156363
  }
155630
- });
156364
+ };
156365
+ for (const message2 of messages)
156366
+ conn.ws.send(message2, onSent);
155631
156367
  });
156368
+ return { ...reply, requestParts: messages.length };
155632
156369
  } finally {
155633
156370
  if (deadline !== void 0)
155634
156371
  clearTimeout(deadline);
@@ -155743,6 +156480,7 @@ class WsEventsTransport {
155743
156480
  carrier.forEach((value, key) => {
155744
156481
  headers2[key] = value;
155745
156482
  });
156483
+ headers2[WS_FLAGS_HEADER] = WS_CLIENT_FLAGS.join(", ");
155746
156484
  return headers2;
155747
156485
  }
155748
156486
  consumeDrainReason() {
@@ -155797,7 +156535,18 @@ class WsEventsTransport {
155797
156535
  const headers2 = await this.resolveUpgradeHeaders();
155798
156536
  const ws2 = new WebSocket(this.wsUrl, { headers: headers2 });
155799
156537
  ws2.binaryType = "nodebuffer";
155800
- conn = { ws: ws2, nextReqId: 1, pending: /* @__PURE__ */ new Map() };
156538
+ const pending = /* @__PURE__ */ new Map();
156539
+ conn = {
156540
+ ws: ws2,
156541
+ nextReqId: 1,
156542
+ pending,
156543
+ // A split reply for a request that already settled (its deadline
156544
+ // or a send error) is read through, not buffered.
156545
+ parts: new WsPartAssembler({
156546
+ wanted: (reqId) => pending.has(reqId),
156547
+ onDiscarded: (reqId) => console.error(`world-vercel: ws events transport received a split reply for unknown reqId ${reqId} from ${this.wsUrl} (already settled); dropping it.`)
156548
+ })
156549
+ };
155801
156550
  } catch (err) {
155802
156551
  console.error(`world-vercel: ws events transport could not open a connection to ${this.wsUrl}: ${describeError(err)}`);
155803
156552
  reject(err instanceof WsTransportError ? err : new WsTransportError(`workflow-server events WS connection to ${this.wsUrl} could not be opened: ${describeError(err)}`, { cause: err }));
@@ -155817,7 +156566,7 @@ class WsEventsTransport {
155817
156566
  resolve2(conn);
155818
156567
  });
155819
156568
  ws.on("message", (raw2) => {
155820
- void this.handleMessage(conn, new Uint8Array(raw2));
156569
+ this.handleMessage(conn, new Uint8Array(raw2));
155821
156570
  });
155822
156571
  ws.on("error", (err) => {
155823
156572
  console.error(`world-vercel: ws events transport socket error (${this.wsUrl}): ${describeError(err)}`);
@@ -155871,16 +156620,22 @@ class WsEventsTransport {
155871
156620
  (_a3 = timer2.unref) == null ? void 0 : _a3.call(timer2);
155872
156621
  this.reconnectTimer = timer2;
155873
156622
  }
155874
- async handleMessage(conn, raw2) {
155875
- let decoded;
156623
+ /** Synchronous so parts of a split reply are always assembled in arrival
156624
+ * order. */
156625
+ handleMessage(conn, raw2) {
156626
+ let message2;
155876
156627
  try {
155877
- decoded = await decodeOneFrame(raw2);
156628
+ message2 = decodeFrame(raw2);
155878
156629
  } catch (err) {
155879
156630
  const detail = `could not decode a ${raw2.byteLength}-byte reply frame from ${this.wsUrl}: ${describeError(err)}`;
155880
156631
  console.error(`world-vercel: ws events transport ${detail}`);
155881
156632
  this.failConnection(conn, `workflow-server events WS transport ${detail}`);
155882
156633
  return;
155883
156634
  }
156635
+ const assembled = this.assemble(conn, message2);
156636
+ if (assembled === void 0)
156637
+ return;
156638
+ const { frame: decoded, parts: replyParts } = assembled;
155884
156639
  if (decoded.meta.type === "drain") {
155885
156640
  const reason = decoded.meta.reason === "auth_expiry" ? "auth_expiry" : "max_duration";
155886
156641
  this.lastDrainReason = reason;
@@ -155906,7 +156661,30 @@ class WsEventsTransport {
155906
156661
  return;
155907
156662
  }
155908
156663
  conn.pending.delete(reqId);
155909
- pending.resolve({ meta: decoded.meta, body: decoded.body });
156664
+ pending.resolve({ meta: decoded.meta, body: decoded.body, replyParts });
156665
+ }
156666
+ /**
156667
+ * Feed one decoded message to the connection's part assembler. Returns the
156668
+ * complete frame with the number of messages it arrived as, or `undefined`
156669
+ * while a split frame is still arriving. A part that breaks the protocol
156670
+ * leaves the rest of the stream unmatchable, the same as an undecodable
156671
+ * frame, so it fails the connection and also returns `undefined`.
156672
+ */
156673
+ assemble(conn, message2) {
156674
+ let frame2;
156675
+ try {
156676
+ frame2 = conn.parts.accept(message2);
156677
+ } catch (err) {
156678
+ const detail = err instanceof WsPartProtocolError ? `received a split reply from ${this.wsUrl} that breaks the part protocol: ${err.message}` : `could not assemble a split reply from ${this.wsUrl}: ${describeError(err)}`;
156679
+ console.error(`world-vercel: ws events transport ${detail}`);
156680
+ this.failConnection(conn, `workflow-server events WS transport ${detail}`);
156681
+ return void 0;
156682
+ }
156683
+ if (frame2 === void 0)
156684
+ return void 0;
156685
+ const { type, partCount } = message2.meta;
156686
+ const parts = type === "part" && typeof partCount === "number" ? partCount : 1;
156687
+ return { frame: frame2, parts };
155910
156688
  }
155911
156689
  failAllPending(conn, err) {
155912
156690
  for (const pending of conn.pending.values()) {
@@ -155965,9 +156743,10 @@ function toEventsWsUrl(baseUrl, runId) {
155965
156743
  url.pathname = `${url.pathname.replace(/\/$/, "")}/websockets/v1/runs/${encodeURIComponent(runId)}`;
155966
156744
  return url.toString();
155967
156745
  }
155968
- function openWsChannel(runId, config2) {
155969
- if (!isWsEventsTransportEnabled())
156746
+ function openWsChannel(runId, config2, options = {}) {
156747
+ if (!isWsEventsTransportEnabledForWorkflow(options.workflowName)) {
155970
156748
  return void 0;
156749
+ }
155971
156750
  const resolved = resolveChannelUrl(runId, config2);
155972
156751
  if (!resolved)
155973
156752
  return void 0;
@@ -155979,7 +156758,7 @@ function openWsChannel(runId, config2) {
155979
156758
  if (forceRefresh)
155980
156759
  await refreshOidcTokenBestEffort();
155981
156760
  const { headers: headers2 } = await getHttpConfig(config2);
155982
- return headersToRecord(headers2);
156761
+ return headersToRecord$1(headers2);
155983
156762
  });
155984
156763
  transport.open();
155985
156764
  let released = false;
@@ -171755,9 +172534,9 @@ function updateParentLookup(node2, parentLookup) {
171755
172534
  if (!node2.parentId) {
171756
172535
  return;
171757
172536
  }
171758
- const childNodes = parentLookup.get(node2.parentId);
171759
- if (childNodes) {
171760
- childNodes.set(node2.id, node2);
172537
+ const childNodes2 = parentLookup.get(node2.parentId);
172538
+ if (childNodes2) {
172539
+ childNodes2.set(node2.id, node2);
171761
172540
  } else {
171762
172541
  parentLookup.set(node2.parentId, /* @__PURE__ */ new Map([[node2.id, node2]]));
171763
172542
  }
@@ -173185,7 +173964,7 @@ function XYResizer({ domNode, nodeId, getStoreItems, onChange, onEnd }) {
173185
173964
  };
173186
173965
  let node2 = void 0;
173187
173966
  let containerBounds = null;
173188
- let childNodes = [];
173967
+ let childNodes2 = [];
173189
173968
  let parentNode = void 0;
173190
173969
  let parentExtent = void 0;
173191
173970
  let childExtent = void 0;
@@ -173220,11 +173999,11 @@ function XYResizer({ domNode, nodeId, getStoreItems, onChange, onEnd }) {
173220
173999
  parentNode = nodeLookup.get(node2.parentId);
173221
174000
  parentExtent = parentNode && node2.extent === "parent" ? nodeToParentExtent(parentNode) : void 0;
173222
174001
  }
173223
- childNodes = [];
174002
+ childNodes2 = [];
173224
174003
  childExtent = void 0;
173225
174004
  for (const [childId, child] of nodeLookup) {
173226
174005
  if (child.parentId === nodeId) {
173227
- childNodes.push({
174006
+ childNodes2.push({
173228
174007
  id: childId,
173229
174008
  position: { ...child.position },
173230
174009
  extent: child.extent
@@ -173271,10 +174050,10 @@ function XYResizer({ domNode, nodeId, getStoreItems, onChange, onEnd }) {
173271
174050
  change.y = isYPosChange ? y2 : prevValues.y;
173272
174051
  prevValues.x = change.x;
173273
174052
  prevValues.y = change.y;
173274
- if (childNodes.length > 0) {
174053
+ if (childNodes2.length > 0) {
173275
174054
  const xChange = x2 - prevX;
173276
174055
  const yChange = y2 - prevY;
173277
- for (const childNode of childNodes) {
174056
+ for (const childNode of childNodes2) {
173278
174057
  childNode.position = {
173279
174058
  x: childNode.position.x - xChange + nodeOrigin[0] * (width - prevWidth),
173280
174059
  y: childNode.position.y - yChange + nodeOrigin[1] * (height - prevHeight)
@@ -180571,7 +181350,7 @@ const route4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProper
180571
181350
  __proto__: null,
180572
181351
  loader
180573
181352
  }, Symbol.toStringTag, { value: "Module" }));
180574
- const serverManifest = { "entry": { "module": "/assets/entry.client-DmlDFlyx.js", "imports": ["/assets/index-thGVuYbY.js"], "css": [] }, "routes": { "root": { "id": "root", "parentId": void 0, "path": "", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": true, "module": "/assets/root-DLS5V7HU.js", "imports": ["/assets/index-thGVuYbY.js", "/assets/mermaid-3ZIDBTTL-ClcCzUqi.js", "/assets/loader-circle-HeezuKOU.js", "/assets/arrow-up-right-jHPcOZmb.js"], "css": ["/assets/root-grl25rxS.css", "/assets/mermaid-3ZIDBTTL-D8CjRQta.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/home": { "id": "routes/home", "parentId": "root", "path": void 0, "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/home-BcIEUw9E.js", "imports": ["/assets/index-thGVuYbY.js", "/assets/workflow-graph-viewer-syfKq6DB.js", "/assets/mermaid-3ZIDBTTL-ClcCzUqi.js", "/assets/loader-circle-HeezuKOU.js"], "css": ["/assets/workflow-graph-viewer-DnlNuQQH.css", "/assets/mermaid-3ZIDBTTL-D8CjRQta.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/run-detail": { "id": "routes/run-detail", "parentId": "root", "path": "run/:runId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/run-detail-DWoMKBqC.js", "imports": ["/assets/index-thGVuYbY.js", "/assets/workflow-graph-viewer-syfKq6DB.js", "/assets/mermaid-3ZIDBTTL-ClcCzUqi.js", "/assets/arrow-up-right-jHPcOZmb.js"], "css": ["/assets/run-detail-CWoGxu_0.css", "/assets/workflow-graph-viewer-DnlNuQQH.css", "/assets/mermaid-3ZIDBTTL-D8CjRQta.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.rpc": { "id": "routes/api.rpc", "parentId": "root", "path": "api/rpc", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.rpc-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.stream.$streamId": { "id": "routes/api.stream.$streamId", "parentId": "root", "path": "api/stream/:streamId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.stream._streamId-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 } }, "url": "/assets/manifest-a541ae9e.js", "version": "a541ae9e", "sri": void 0 };
181353
+ const serverManifest = { "entry": { "module": "/assets/entry.client-DmlDFlyx.js", "imports": ["/assets/index-thGVuYbY.js"], "css": [] }, "routes": { "root": { "id": "root", "parentId": void 0, "path": "", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": true, "module": "/assets/root-ESATuWiF.js", "imports": ["/assets/index-thGVuYbY.js", "/assets/mermaid-3ZIDBTTL-fKP9rqOT.js", "/assets/loader-circle-CD4z6T9x.js", "/assets/arrow-up-right-CIRm41Zm.js"], "css": ["/assets/root-grl25rxS.css", "/assets/mermaid-3ZIDBTTL-D8CjRQta.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/home": { "id": "routes/home", "parentId": "root", "path": void 0, "index": true, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/home-Dl1wTnFS.js", "imports": ["/assets/index-thGVuYbY.js", "/assets/workflow-graph-viewer-DWfB9i-1.js", "/assets/mermaid-3ZIDBTTL-fKP9rqOT.js", "/assets/loader-circle-CD4z6T9x.js"], "css": ["/assets/workflow-graph-viewer-DnlNuQQH.css", "/assets/mermaid-3ZIDBTTL-D8CjRQta.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/run-detail": { "id": "routes/run-detail", "parentId": "root", "path": "run/:runId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": true, "hasErrorBoundary": false, "module": "/assets/run-detail-ClvtUP5Y.js", "imports": ["/assets/index-thGVuYbY.js", "/assets/workflow-graph-viewer-DWfB9i-1.js", "/assets/mermaid-3ZIDBTTL-fKP9rqOT.js", "/assets/arrow-up-right-CIRm41Zm.js"], "css": ["/assets/run-detail-CWoGxu_0.css", "/assets/workflow-graph-viewer-DnlNuQQH.css", "/assets/mermaid-3ZIDBTTL-D8CjRQta.css"], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.rpc": { "id": "routes/api.rpc", "parentId": "root", "path": "api/rpc", "index": void 0, "caseSensitive": void 0, "hasAction": true, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.rpc-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 }, "routes/api.stream.$streamId": { "id": "routes/api.stream.$streamId", "parentId": "root", "path": "api/stream/:streamId", "index": void 0, "caseSensitive": void 0, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasClientMiddleware": false, "hasDefaultExport": false, "hasErrorBoundary": false, "module": "/assets/api.stream._streamId-l0sNRNKZ.js", "imports": [], "css": [], "clientActionModule": void 0, "clientLoaderModule": void 0, "clientMiddlewareModule": void 0, "hydrateFallbackModule": void 0 } }, "url": "/assets/manifest-7d7b25b4.js", "version": "7d7b25b4", "sri": void 0 };
180575
181354
  const assetsBuildDirectory = "build/client";
180576
181355
  const basename = "/";
180577
181356
  const future = { "unstable_optimizeDeps": false, "unstable_subResourceIntegrity": false, "unstable_trailingSlashAwareDataRequests": false, "unstable_previewServerPrerendering": false, "v8_middleware": false, "v8_splitRouteModules": false, "v8_viteEnvironmentApi": false };
@@ -180713,7 +181492,7 @@ export {
180713
181492
  RETENTION_ATTRIBUTE as Z,
180714
181493
  RETENTION_DEFAULT as _,
180715
181494
  ANALYTICS_MAX_ATTRIBUTE_FILTERS as a,
180716
- reenqueueActiveRuns as a$,
181495
+ mintedSpecVersion as a$,
180717
181496
  ROOT_RUN_ID_ATTRIBUTE as a0,
180718
181497
  RUN_ENTITY_KEY as a1,
180719
181498
  RunInputSchema as a2,
@@ -180724,87 +181503,90 @@ export {
180724
181503
  SPEC_VERSION_SUPPORTS_ATTRIBUTES as a7,
180725
181504
  SPEC_VERSION_SUPPORTS_CBOR_QUEUE_TRANSPORT as a8,
180726
181505
  SPEC_VERSION_SUPPORTS_COMPRESSION as a9,
180727
- entityEventClass as aA,
180728
- entityResolveData as aB,
180729
- envFlag as aC,
180730
- envNumber as aD,
180731
- eventIdToSlot as aE,
180732
- getEventDataPayloadField as aF,
180733
- getEventDataRefFields as aG,
180734
- getMaxEventsPerRun as aH,
180735
- getQueueTopicPrefix as aI,
180736
- isChildEntityCreationEvent as aJ,
180737
- isChildEntityCreationEventType as aK,
180738
- isHookEventRequiringExistence as aL,
180739
- isHookLifecycleEventType as aM,
180740
- isLegacySpecVersion as aN,
180741
- isNodeHttpEnabled as aO,
180742
- isSealedNoopEvent$1 as aP,
180743
- isSlotBody as aQ,
180744
- isSlotEventId as aR,
180745
- isStepEventType as aS,
180746
- isTerminalRunEventType as aT,
180747
- isTerminalStepEventType as aU,
180748
- isTerminalStepStatus as aV,
180749
- isTerminalWorkflowRunStatus as aW,
180750
- isWaitEventType as aX,
180751
- mintedSpecVersion as aY,
180752
- parseQueueName as aZ,
180753
- readRunRetention as a_,
181506
+ classifyEntityEvent as aA,
181507
+ decodeSnapshotEnvelope as aB,
181508
+ encodeSnapshotEnvelope as aC,
181509
+ entityEventClass as aD,
181510
+ entityResolveData as aE,
181511
+ envFlag as aF,
181512
+ envNumber as aG,
181513
+ eventIdToSlot as aH,
181514
+ getEventDataPayloadField as aI,
181515
+ getEventDataRefFields as aJ,
181516
+ getMaxEventsPerRun as aK,
181517
+ getQueueTopicPrefix as aL,
181518
+ isChildEntityCreationEvent as aM,
181519
+ isChildEntityCreationEventType as aN,
181520
+ isHookEventRequiringExistence as aO,
181521
+ isHookLifecycleEventType as aP,
181522
+ isLegacySpecVersion as aQ,
181523
+ isNodeHttpEnabled as aR,
181524
+ isSealedNoopEvent$1 as aS,
181525
+ isSlotBody as aT,
181526
+ isSlotEventId as aU,
181527
+ isStepEventType as aV,
181528
+ isTerminalRunEventType as aW,
181529
+ isTerminalStepEventType as aX,
181530
+ isTerminalStepStatus as aY,
181531
+ isTerminalWorkflowRunStatus as aZ,
181532
+ isWaitEventType as a_,
180754
181533
  SPEC_VERSION_SUPPORTS_EVENT_SOURCING as aa,
180755
181534
  SPEC_VERSION_SUPPORTS_HOOK_FORCE_CLAIM as ab,
180756
181535
  SPEC_VERSION_SUPPORTS_SLOT_IDENTITY as ac,
180757
181536
  STEP_EVENT_TYPES as ad,
180758
181537
  SerializedDataSchema as ae,
180759
- StepSchema as af,
180760
- StepStatusSchema as ag,
180761
- StructuredErrorSchema as ah,
180762
- TERMINAL_EVENT_CLASSES as ai,
180763
- TERMINAL_RUN_EVENT_TYPES as aj,
180764
- TERMINAL_STEP_EVENT_TYPES as ak,
180765
- TERMINAL_STEP_STATUSES as al,
180766
- TERMINAL_WORKFLOW_RUN_STATUSES as am,
180767
- TerminalRunEventTypeSchema as an,
180768
- TerminalStepStatusSchema as ao,
180769
- TerminalWorkflowRunStatusSchema as ap,
180770
- ValidQueueName as aq,
180771
- WAIT_EVENT_TYPES as ar,
180772
- WaitSchema as as,
180773
- WaitStatusSchema as at,
180774
- WorkflowInvokePayloadSchema as au,
180775
- WorkflowRunBaseSchema as av,
180776
- WorkflowRunSchema as aw,
180777
- WorkflowRunStatusSchema as ax,
180778
- applyAttributeChanges as ay,
180779
- classifyEntityEvent as az,
181538
+ SnapshotMetadataSchema as af,
181539
+ StepSchema as ag,
181540
+ StepStatusSchema as ah,
181541
+ StructuredErrorSchema as ai,
181542
+ TERMINAL_EVENT_CLASSES as aj,
181543
+ TERMINAL_RUN_EVENT_TYPES as ak,
181544
+ TERMINAL_STEP_EVENT_TYPES as al,
181545
+ TERMINAL_STEP_STATUSES as am,
181546
+ TERMINAL_WORKFLOW_RUN_STATUSES as an,
181547
+ TerminalRunEventTypeSchema as ao,
181548
+ TerminalStepStatusSchema as ap,
181549
+ TerminalWorkflowRunStatusSchema as aq,
181550
+ ValidQueueName as ar,
181551
+ WAIT_EVENT_TYPES as as,
181552
+ WaitSchema as at,
181553
+ WaitStatusSchema as au,
181554
+ WorkflowInvokePayloadSchema as av,
181555
+ WorkflowRunBaseSchema as aw,
181556
+ WorkflowRunSchema as ax,
181557
+ WorkflowRunStatusSchema as ay,
181558
+ applyAttributeChanges as az,
180780
181559
  ANALYTICS_PAGE_LIMIT as b,
180781
- requiresNewerWorld as b0,
180782
- resolveQueueNamespace as b1,
180783
- slotToEventId as b2,
180784
- stripEventDataRefs as b3,
180785
- ulidToDate as b4,
180786
- validateAttributeChanges as b5,
180787
- validateAttributeEventDataSize as b6,
180788
- validateUlidTimestamp as b7,
180789
- workflowRunIdSchema as b8,
180790
- reactExports as b9,
180791
- R as ba,
180792
- Ks as bb,
180793
- jsxRuntimeExports as bc,
180794
- Qe as bd,
180795
- registerZstdDecoder as be,
180796
- WebSocket as bf,
180797
- permessageDeflate as bg,
180798
- receiver as bh,
180799
- sender as bi,
180800
- websocketServer as bj,
180801
- stream as bk,
180802
- extension as bl,
180803
- subprotocol as bm,
180804
- getDefaultExportFromCjs as bn,
180805
- requireTokenUtil as bo,
180806
- requireTokenError as bp,
180807
- createFetchHandler as bq,
181560
+ parseQueueName as b0,
181561
+ readRunRetention as b1,
181562
+ reenqueueActiveRuns as b2,
181563
+ requiresNewerWorld as b3,
181564
+ resolveQueueNamespace as b4,
181565
+ slotToEventId as b5,
181566
+ stripEventDataRefs as b6,
181567
+ ulidToDate as b7,
181568
+ validateAttributeChanges as b8,
181569
+ validateAttributeEventDataSize as b9,
181570
+ validateUlidTimestamp as ba,
181571
+ workflowRunIdSchema as bb,
181572
+ reactExports as bc,
181573
+ R as bd,
181574
+ Ks as be,
181575
+ jsxRuntimeExports as bf,
181576
+ Qe as bg,
181577
+ registerZstdDecoder as bh,
181578
+ WebSocket as bi,
181579
+ permessageDeflate as bj,
181580
+ receiver as bk,
181581
+ sender as bl,
181582
+ websocketServer as bm,
181583
+ stream as bn,
181584
+ extension as bo,
181585
+ subprotocol as bp,
181586
+ getDefaultExportFromCjs as bq,
181587
+ requireTokenUtil as br,
181588
+ requireTokenError as bs,
181589
+ createFetchHandler as bt,
180808
181590
  ANALYTICS_RUN_SCOPED_PAGE_LIMIT as c,
180809
181591
  ATTRIBUTE_EVENT_DATA_MAX_BYTES as d,
180810
181592
  ATTRIBUTE_KEY_MAX_LENGTH as e,