@workflow/web 5.0.3 → 5.0.5

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-ychoyK1y.js → arrow-up-right-BjmInfWj.js} +1 -1
  2. package/build/client/assets/{highlighted-body-B3W2YXNL-C53ps5L5.js → highlighted-body-B3W2YXNL-Fxz5Vhrs.js} +1 -1
  3. package/build/client/assets/{home-C3xDSPLC.js → home-Cj8BA1xg.js} +3 -3
  4. package/build/client/assets/{loader-circle-BaPqCMKN.js → loader-circle-BHf0PB8D.js} +1 -1
  5. package/build/client/assets/{manifest-4e8be598.js → manifest-9875bf74.js} +1 -1
  6. package/build/client/assets/{mermaid-3ZIDBTTL-COEB4Hc6.js → mermaid-3ZIDBTTL-C-jkx8xu.js} +73 -42
  7. package/build/client/assets/{root-DixDz_si.js → root-D1LRhSwl.js} +3 -3
  8. package/build/client/assets/{run-detail-CEQc0q3W.js → run-detail-L1jBcQcp.js} +3 -3
  9. package/build/client/assets/{workflow-graph-viewer-B9ovZj-2.js → workflow-graph-viewer-BRI-aUt7.js} +1 -1
  10. package/build/client/assets/{zstd-browser-decoder-D9w7uXpQ.js → zstd-browser-decoder-HGSvkFdF.js} +1 -1
  11. package/build/server/assets/{app-C8tzXy8V.js → app-C7EyOacb.js} +1123 -635
  12. package/build/server/assets/{highlighted-body-B3W2YXNL-B7OeHZjS.js → highlighted-body-B3W2YXNL-99nXCMDQ.js} +1 -1
  13. package/build/server/assets/{index-oHATtR_7.js → index-CI1MEtXX.js} +1 -1
  14. package/build/server/assets/{index-DB6rD0OI.js → index-TQ324kzl.js} +94 -90
  15. package/build/server/assets/{mermaid-3ZIDBTTL-h6E4ztpF.js → mermaid-3ZIDBTTL-Csd1n701.js} +1 -1
  16. package/build/server/assets/{token-zIvY_X5M.js → token-C7Y4VFl0.js} +1 -1
  17. package/build/server/assets/{token-util-BIJWXlXW.js → token-util-DCNDhnc8.js} +1 -1
  18. package/build/server/assets/{wrapper-DiM8LB2q.js → wrapper-CA2LUUpa.js} +9 -9
  19. package/build/server/assets/{zstd-browser-decoder-B2bHyQlS.js → zstd-browser-decoder-BJ5qrMmm.js} +1 -1
  20. package/build/server/index.js +2 -2
  21. package/package.json +8 -8
@@ -13,7 +13,7 @@ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot
13
13
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
14
14
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
15
15
  var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
16
- var _a2, _b, _c, _d, _listeners, _onabort, _reader, _worldPromise, _Run_instances, lazyWorldPromise_get, _encryptionKeyPromise, _resilientStart, getEncryptionKey_fn, getEncryptionKeyLazily_fn, getMetadata_fn, resolveTerminalReturnValue_fn, pollReturnValue_fn, _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _AST_instances, fillNegs_fn, _AST_static, parseAST_fn, canAdoptWithSpace_fn, canAdopt_fn, canAdoptType_fn, adoptWithSpace_fn, adopt_fn, canUsurpType_fn, canUsurp_fn, usurp_fn, flatten_fn, partsToRegExp_fn, parseGlob_fn, _Minimatch_instances, matchGlobstar_fn, matchGlobStarBodySections_fn, matchOne_fn;
16
+ var _a2, _b, _c, _d, _e2, _f, _listeners, _onabort, _reader, _worldPromise, _Run_instances, lazyWorldPromise_get, _encryptionKeyPromise, _resilientStart, getEncryptionKey_fn, getEncryptionKeyLazily_fn, getMetadata_fn, resolveTerminalReturnValue_fn, pollReturnValue_fn, _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _AST_instances, fillNegs_fn, _AST_static, parseAST_fn, canAdoptWithSpace_fn, canAdopt_fn, canAdoptType_fn, adoptWithSpace_fn, adopt_fn, canUsurpType_fn, canUsurp_fn, usurp_fn, flatten_fn, partsToRegExp_fn, parseGlob_fn, _Minimatch_instances, matchGlobstar_fn, matchGlobStarBodySections_fn, matchOne_fn;
17
17
  import { createRequire as __wkfCreateRequire } from "node:module";
18
18
  if (typeof require === "undefined") {
19
19
  globalThis.require = __wkfCreateRequire(import.meta.url);
@@ -3793,7 +3793,7 @@ async function parseResponseBody$1(response2) {
3793
3793
  return response2.text();
3794
3794
  }
3795
3795
  async function convertDataStrategyResultToDataResult(dataStrategyResult) {
3796
- var _a3, _b2, _c2, _d2, _e2;
3796
+ var _a3, _b2, _c2, _d2, _e3;
3797
3797
  let { result, type } = dataStrategyResult;
3798
3798
  if (isResponse(result)) {
3799
3799
  let data2;
@@ -3845,7 +3845,7 @@ async function convertDataStrategyResultToDataResult(dataStrategyResult) {
3845
3845
  type: "data",
3846
3846
  data: result.data,
3847
3847
  statusCode: (_d2 = result.init) == null ? void 0 : _d2.status,
3848
- headers: ((_e2 = result.init) == null ? void 0 : _e2.headers) ? new Headers(result.init.headers) : void 0
3848
+ headers: ((_e3 = result.init) == null ? void 0 : _e3.headers) ? new Headers(result.init.headers) : void 0
3849
3849
  };
3850
3850
  }
3851
3851
  return { type: "data", data: result };
@@ -34033,7 +34033,7 @@ function isTopLayer(element2) {
34033
34033
  return topLayerSelectors.some((selector2) => {
34034
34034
  try {
34035
34035
  return element2.matches(selector2);
34036
- } catch (_e2) {
34036
+ } catch (_e3) {
34037
34037
  return false;
34038
34038
  }
34039
34039
  });
@@ -34635,7 +34635,7 @@ function observeMove(element2, onMove) {
34635
34635
  // Handle <iframe>s
34636
34636
  root: root2.ownerDocument
34637
34637
  });
34638
- } catch (_e2) {
34638
+ } catch (_e3) {
34639
34639
  io2 = new IntersectionObserver(handleObserve, options);
34640
34640
  }
34641
34641
  io2.observe(element2);
@@ -35096,7 +35096,7 @@ var CONTENT_NAME$9 = "PopperContent";
35096
35096
  var [PopperContentProvider$1, useContentContext$1] = createPopperContext$1(CONTENT_NAME$9);
35097
35097
  var PopperContent$1 = reactExports.forwardRef(
35098
35098
  (props, forwardedRef) => {
35099
- var _a3, _b2, _c2, _d2, _e2, _f;
35099
+ var _a3, _b2, _c2, _d2, _e3, _f2;
35100
35100
  const {
35101
35101
  __scopePopper,
35102
35102
  side = "bottom",
@@ -35195,12 +35195,12 @@ var PopperContent$1 = reactExports.forwardRef(
35195
35195
  zIndex: contentZIndex,
35196
35196
  ["--radix-popper-transform-origin"]: [
35197
35197
  (_d2 = middlewareData.transformOrigin) == null ? void 0 : _d2.x,
35198
- (_e2 = middlewareData.transformOrigin) == null ? void 0 : _e2.y
35198
+ (_e3 = middlewareData.transformOrigin) == null ? void 0 : _e3.y
35199
35199
  ].join(" "),
35200
35200
  // hide the content if using the hide middleware and should be hidden
35201
35201
  // set visibility to hidden and disable pointer events so the UI behaves
35202
35202
  // as if the PopperContent isn't there at all
35203
- ...((_f = middlewareData.hide) == null ? void 0 : _f.referenceHidden) && {
35203
+ ...((_f2 = middlewareData.hide) == null ? void 0 : _f2.referenceHidden) && {
35204
35204
  visibility: "hidden",
35205
35205
  pointerEvents: "none"
35206
35206
  }
@@ -40527,7 +40527,7 @@ function attachSchema(issues, start2, inst) {
40527
40527
  }
40528
40528
  }
40529
40529
  function finalizeIssue(iss, ctx, config2) {
40530
- var _a4, _b2, _c2, _d2, _e2, _f, _g, _h, _i, _j;
40530
+ var _a4, _b2, _c2, _d2, _e3, _f2, _g, _h, _i, _j;
40531
40531
  var _a3;
40532
40532
  const traits = (_b2 = (_a4 = iss.inst) == null ? void 0 : _a4._zod) == null ? void 0 : _b2.traits;
40533
40533
  if (traits == null ? void 0 : traits.has("$ZodType")) {
@@ -40537,7 +40537,7 @@ function finalizeIssue(iss, ctx, config2) {
40537
40537
  iss.schema = iss.inst;
40538
40538
  }
40539
40539
  const schemaError = iss.schema !== iss.inst ? (_d2 = (_c2 = iss.schema) == null ? void 0 : _c2._zod.def) == null ? void 0 : _d2.error : void 0;
40540
- const message2 = iss.message ? iss.message : unwrapMessage((_g = (_f = (_e2 = iss.inst) == null ? void 0 : _e2._zod.def) == null ? void 0 : _f.error) == null ? void 0 : _g.call(_f, iss)) ?? unwrapMessage(schemaError == null ? void 0 : schemaError(iss)) ?? unwrapMessage((_h = ctx == null ? void 0 : ctx.error) == null ? void 0 : _h.call(ctx, iss)) ?? unwrapMessage((_i = config2.customError) == null ? void 0 : _i.call(config2, iss)) ?? unwrapMessage((_j = config2.localeError) == null ? void 0 : _j.call(config2, iss)) ?? "Invalid input";
40540
+ const message2 = iss.message ? iss.message : unwrapMessage((_g = (_f2 = (_e3 = iss.inst) == null ? void 0 : _e3._zod.def) == null ? void 0 : _f2.error) == null ? void 0 : _g.call(_f2, iss)) ?? unwrapMessage(schemaError == null ? void 0 : schemaError(iss)) ?? unwrapMessage((_h = ctx == null ? void 0 : ctx.error) == null ? void 0 : _h.call(ctx, iss)) ?? unwrapMessage((_i = config2.customError) == null ? void 0 : _i.call(config2, iss)) ?? unwrapMessage((_j = config2.localeError) == null ? void 0 : _j.call(config2, iss)) ?? "Invalid input";
40541
40541
  const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss;
40542
40542
  rest.path ?? (rest.path = []);
40543
40543
  rest.message = message2;
@@ -41075,7 +41075,7 @@ function timeSource(args) {
41075
41075
  function time(args) {
41076
41076
  return new RegExp(`^${timeSource(args)}$`);
41077
41077
  }
41078
- function datetime(args) {
41078
+ function datetime$1(args) {
41079
41079
  const opts = ["Z"];
41080
41080
  if (args.offset)
41081
41081
  opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
@@ -41822,7 +41822,7 @@ const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
41822
41822
  $ZodStringFormat.init(inst, def);
41823
41823
  });
41824
41824
  const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
41825
- def.pattern ?? (def.pattern = datetime(def));
41825
+ def.pattern ?? (def.pattern = datetime$1(def));
41826
41826
  $ZodStringFormat.init(inst, def);
41827
41827
  if (def.local || def.precision === -1) {
41828
41828
  inst._zod.bag.laxFormat = true;
@@ -47812,6 +47812,9 @@ function preprocess$1(fn2, schema) {
47812
47812
  out: schema
47813
47813
  });
47814
47814
  }
47815
+ function datetime(params) {
47816
+ return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
47817
+ }
47815
47818
  function number$2(params) {
47816
47819
  return /* @__PURE__ */ _coercedNumber(ZodNumber, params);
47817
47820
  }
@@ -48504,6 +48507,7 @@ function isChildEntityCreationEvent(event) {
48504
48507
  return true;
48505
48508
  return event.eventType === "step_started" && typeof ((_a3 = event.eventData) == null ? void 0 : _a3.stepName) === "string" && event.eventData.input !== void 0;
48506
48509
  }
48510
+ const IN_BAND_SEQ_AT_RUN_CREATION = 1;
48507
48511
  const WorkflowRunStatusSchema = compile(_enum(["pending", "running", "completed", "failed", "cancelled"]));
48508
48512
  const TerminalWorkflowRunStatusSchema = compile(WorkflowRunStatusSchema.extract(["completed", "failed", "cancelled"]));
48509
48513
  const TERMINAL_WORKFLOW_RUN_STATUSES = TerminalWorkflowRunStatusSchema.options;
@@ -48897,6 +48901,20 @@ function getQueueTopicPrefix(kind, namespace2) {
48897
48901
  }
48898
48902
  return "__wkf_workflow_";
48899
48903
  }
48904
+ const WORKFLOW_FLOW_ROUTE = "/.well-known/workflow/v1/flow";
48905
+ function parseQueueRoute(path2) {
48906
+ if (typeof path2 !== "string" || !path2.startsWith("/") || path2.startsWith("//") || /[?#\s]/.test(path2)) {
48907
+ throw new TypeError(`Invalid queue route "${String(path2)}": must be an absolute path such as "/api/agent/queue", without a query or fragment`);
48908
+ }
48909
+ return path2;
48910
+ }
48911
+ function getRunQueueNamespace(executionContext) {
48912
+ if (typeof executionContext !== "object" || executionContext === null || executionContext instanceof Uint8Array) {
48913
+ return void 0;
48914
+ }
48915
+ const namespace2 = executionContext.queueNamespace;
48916
+ return typeof namespace2 === "string" && QueueNamespace.safeParse(namespace2).success ? namespace2 : void 0;
48917
+ }
48900
48918
  function parseQueueName(name2) {
48901
48919
  const match2 = name2.match(/^(__(?:[a-z][a-z0-9]*_)?wkf_workflow_)(.+)$/);
48902
48920
  if (!match2) {
@@ -49240,7 +49258,8 @@ function isNodeHttpEnabled(env2 = process.env) {
49240
49258
  return envFlag(NODE_HTTP_ENV_VAR, NODE_HTTP_DEFAULT, env2);
49241
49259
  }
49242
49260
  async function reenqueueActiveRuns(runs, enqueue, label, namespace2) {
49243
- const workflowQueuePrefix = getQueueTopicPrefix("workflow", resolveQueueNamespace(namespace2));
49261
+ const defaultNamespace = resolveQueueNamespace(namespace2);
49262
+ getQueueTopicPrefix("workflow", defaultNamespace);
49244
49263
  let reenqueued = 0;
49245
49264
  let cursor;
49246
49265
  let hasMore = true;
@@ -49252,7 +49271,8 @@ async function reenqueueActiveRuns(runs, enqueue, label, namespace2) {
49252
49271
  });
49253
49272
  for (const run2 of page.data) {
49254
49273
  try {
49255
- const queueName = `${workflowQueuePrefix}${run2.workflowName}`;
49274
+ const prefix = getQueueTopicPrefix("workflow", getRunQueueNamespace(run2.executionContext) ?? defaultNamespace);
49275
+ const queueName = `${prefix}${run2.workflowName}`;
49256
49276
  await enqueue(queueName, { runId: run2.runId });
49257
49277
  reenqueued++;
49258
49278
  } catch (err) {
@@ -53186,7 +53206,17 @@ function createWorkflowBaseUrl(origin) {
53186
53206
  function createWorkflowUrl(baseUrl, route) {
53187
53207
  const url = new URL(baseUrl);
53188
53208
  url.pathname = `${url.pathname.replace(/\/+$/, "")}${WORKFLOW_ROUTE_BASE}/${getWorkflowRouteEndpoint(route)}`;
53189
- url.search = route.type === "health" ? "__health" : "";
53209
+ url.search = "";
53210
+ url.hash = "";
53211
+ return url.toString();
53212
+ }
53213
+ function createAppRouteUrl(baseUrl, path2) {
53214
+ if (!path2.startsWith("/")) {
53215
+ throw new TypeError(`App route "${path2}" must start with "/"`);
53216
+ }
53217
+ const url = new URL(baseUrl);
53218
+ url.pathname = `${url.pathname.replace(/\/+$/, "")}${path2}`;
53219
+ url.search = "";
53190
53220
  url.hash = "";
53191
53221
  return url.toString();
53192
53222
  }
@@ -53239,6 +53269,21 @@ class DevalueError extends Error {
53239
53269
  this.root = root2;
53240
53270
  }
53241
53271
  }
53272
+ const MAP_KEY = Symbol();
53273
+ function format_path(keys2, format_map_key) {
53274
+ const path2 = [];
53275
+ for (let i = 0; i < keys2.length; i += 1) {
53276
+ const segment = keys2[i];
53277
+ if (segment === MAP_KEY) {
53278
+ path2.push(`.get(${format_map_key(keys2[++i])})`);
53279
+ } else if (typeof segment === "number") {
53280
+ path2.push(`[${segment}]`);
53281
+ } else {
53282
+ path2.push(stringify_key(segment));
53283
+ }
53284
+ }
53285
+ return path2;
53286
+ }
53242
53287
  const object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
53243
53288
  function is_plain_object(thing) {
53244
53289
  const proto2 = Object.getPrototypeOf(thing);
@@ -53247,50 +53292,37 @@ function is_plain_object(thing) {
53247
53292
  function get_type(thing) {
53248
53293
  return Object.prototype.toString.call(thing).slice(8, -1);
53249
53294
  }
53250
- function get_escaped_char(char) {
53251
- switch (char) {
53252
- case '"':
53253
- return '\\"';
53254
- case "<":
53255
- return "\\u003C";
53256
- case "\\":
53257
- return "\\\\";
53258
- case "\n":
53259
- return "\\n";
53260
- case "\r":
53261
- return "\\r";
53262
- case " ":
53263
- return "\\t";
53264
- case "\b":
53265
- return "\\b";
53266
- case "\f":
53267
- return "\\f";
53268
- case "\u2028":
53269
- return "\\u2028";
53270
- case "\u2029":
53271
- return "\\u2029";
53272
- default:
53273
- return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : "";
53274
- }
53295
+ function is_buffer(thing) {
53296
+ return typeof Buffer !== "undefined" && Buffer.isBuffer(thing);
53297
+ }
53298
+ const needs_escape = /["<\\\u0000-\u001f\u2028\u2029]/;
53299
+ const json_leaves_raw = /[<\u2028\u2029]/g;
53300
+ const raw_escapes = { "<": "\\u003C", "\u2028": "\\u2028", "\u2029": "\\u2029" };
53301
+ function escape_raw(char) {
53302
+ return raw_escapes[char];
53275
53303
  }
53276
53304
  function stringify_string(str) {
53277
- let result = "";
53278
- let last_pos = 0;
53279
- const len = str.length;
53280
- for (let i = 0; i < len; i += 1) {
53281
- const char = str[i];
53282
- const replacement = get_escaped_char(char);
53283
- if (replacement) {
53284
- result += str.slice(last_pos, i) + replacement;
53285
- last_pos = i + 1;
53286
- }
53305
+ if (!needs_escape.test(str) && str.isWellFormed()) return `"${str}"`;
53306
+ return JSON.stringify(str).replace(json_leaves_raw, escape_raw);
53307
+ }
53308
+ const MAX_CACHED_KEY_LENGTH = 64;
53309
+ const quoted_keys = /* @__PURE__ */ new Map();
53310
+ function quote_key(key) {
53311
+ if (key.length > MAX_CACHED_KEY_LENGTH) return stringify_string(key);
53312
+ let quoted = quoted_keys.get(key);
53313
+ if (quoted === void 0) {
53314
+ if (quoted_keys.size >= 1024) quoted_keys.clear();
53315
+ quoted = stringify_string(key);
53316
+ quoted_keys.set(key, quoted);
53287
53317
  }
53288
- return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
53318
+ return quoted;
53289
53319
  }
53290
53320
  function enumerable_symbols(object2) {
53291
- return Object.getOwnPropertySymbols(object2).filter(
53292
- (symbol) => Object.getOwnPropertyDescriptor(object2, symbol).enumerable
53293
- );
53321
+ const symbols2 = Object.getOwnPropertySymbols(object2);
53322
+ return symbols2.length === 0 ? symbols2 : symbols2.filter((symbol) => {
53323
+ var _a3;
53324
+ return (_a3 = Object.getOwnPropertyDescriptor(object2, symbol)) == null ? void 0 : _a3.enumerable;
53325
+ });
53294
53326
  }
53295
53327
  const is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
53296
53328
  function stringify_key(key) {
@@ -53348,7 +53380,12 @@ function encode_legacy(array_buffer) {
53348
53380
  const chunk_size = 32768;
53349
53381
  for (let i = 0; i < array2.length; i += chunk_size) {
53350
53382
  const chunk = array2.subarray(i, i + chunk_size);
53351
- binary += String.fromCharCode.apply(null, chunk);
53383
+ binary += String.fromCharCode.apply(
53384
+ null,
53385
+ /** @type {number[]} */
53386
+ /** @type {unknown} */
53387
+ chunk
53388
+ );
53352
53389
  }
53353
53390
  return btoa(binary);
53354
53391
  }
@@ -53380,8 +53417,8 @@ function merge_operations(defaults2, overrides) {
53380
53417
  }
53381
53418
  return merged;
53382
53419
  }
53383
- const NOT_PLAIN = Object.freeze({ kind: "not-plain" });
53384
- const SYMBOL_KEYS = Object.freeze({ kind: "symbol-keys" });
53420
+ const NOT_PLAIN = /* @__PURE__ */ Object.freeze({ kind: "not-plain" });
53421
+ const SYMBOL_KEYS = /* @__PURE__ */ Object.freeze({ kind: "symbol-keys" });
53385
53422
  const stringify_operations = {
53386
53423
  identify: (value) => value,
53387
53424
  typeOf: (value) => value === null ? "null" : typeof value,
@@ -53395,13 +53432,16 @@ const stringify_operations = {
53395
53432
  regExpInfo: (regexp) => ({ source: regexp.source, flags: regexp.flags }),
53396
53433
  valuesOf: (set2) => set2,
53397
53434
  entriesOf: (map2) => map2,
53398
- viewInfo: (view) => ({
53399
- buffer: view.buffer,
53400
- byteOffset: view.byteOffset,
53401
- byteLength: view.byteLength,
53402
- length: view.length,
53403
- bufferByteLength: view.buffer.byteLength
53404
- }),
53435
+ viewInfo: (view) => {
53436
+ if (is_buffer(view)) view = new Uint8Array(view);
53437
+ return {
53438
+ buffer: view.buffer,
53439
+ byteOffset: view.byteOffset,
53440
+ byteLength: view.byteLength,
53441
+ length: view.length,
53442
+ bufferByteLength: view.buffer.byteLength
53443
+ };
53444
+ },
53405
53445
  toArrayBuffer: (buffer2) => buffer2,
53406
53446
  lengthOf: (array2) => array2.length,
53407
53447
  hasOwn: (value, key) => Object.hasOwn(value, key),
@@ -53416,7 +53456,12 @@ const stringify_operations = {
53416
53456
  },
53417
53457
  get: (value, key) => value[key]
53418
53458
  };
53419
- const default_stringify_operations = Object.freeze(stringify_operations);
53459
+ const default_stringify_operations = /* @__PURE__ */ Object.freeze(stringify_operations);
53460
+ const array_buffer_byte_length = (
53461
+ /** @type {() => number} */
53462
+ (_b = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")) == null ? void 0 : _b.get
53463
+ );
53464
+ const shared_array_buffer_byte_length = typeof SharedArrayBuffer === "undefined" ? void 0 : (_c = Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength")) == null ? void 0 : _c.get;
53420
53465
  const parse_operations = {
53421
53466
  fromPrimitive: (primitive) => primitive,
53422
53467
  fromISOString: (iso) => new Date(iso),
@@ -53428,6 +53473,12 @@ const parse_operations = {
53428
53473
  fromArrayBuffer: (buffer2) => buffer2,
53429
53474
  fromRegExpInfo: (source, flags) => new RegExp(source, flags),
53430
53475
  fromViewInfo: (tag, buffer2, byteOffset, length) => {
53476
+ try {
53477
+ array_buffer_byte_length.call(buffer2);
53478
+ } catch (error2) {
53479
+ if (!shared_array_buffer_byte_length) throw error2;
53480
+ shared_array_buffer_byte_length.call(buffer2);
53481
+ }
53431
53482
  const Constructor = (
53432
53483
  /** @type {any} */
53433
53484
  globalThis[tag]
@@ -53457,7 +53508,10 @@ const parse_operations = {
53457
53508
  map2.set(key, value);
53458
53509
  }
53459
53510
  };
53460
- const default_parse_operations = Object.freeze(parse_operations);
53511
+ const default_parse_operations = /* @__PURE__ */ Object.freeze(parse_operations);
53512
+ function invalid() {
53513
+ throw new Error("Invalid input");
53514
+ }
53461
53515
  function parse$6(serialized, revivers, options) {
53462
53516
  return unflatten(JSON.parse(serialized), revivers, options);
53463
53517
  }
@@ -53465,7 +53519,7 @@ function unflatten(parsed, revivers, options) {
53465
53519
  const ops = merge_operations(default_parse_operations, options == null ? void 0 : options.operations);
53466
53520
  if (typeof parsed === "number") return hydrate2(parsed, true);
53467
53521
  if (!Array.isArray(parsed) || parsed.length === 0) {
53468
- throw new Error("Invalid input");
53522
+ invalid();
53469
53523
  }
53470
53524
  const values = (
53471
53525
  /** @type {any[]} */
@@ -53473,6 +53527,12 @@ function unflatten(parsed, revivers, options) {
53473
53527
  );
53474
53528
  const hydrated = Array(values.length);
53475
53529
  let hydrating = null;
53530
+ function get_raw(index2) {
53531
+ if (!is_valid_array_index(index2) || index2 >= values.length) {
53532
+ invalid();
53533
+ }
53534
+ return values[index2];
53535
+ }
53476
53536
  function hydrate2(index2, standalone = false) {
53477
53537
  if (index2 === UNDEFINED$2) return ops.fromPrimitive(void 0);
53478
53538
  if (index2 === NAN) return ops.fromPrimitive(NaN);
@@ -53480,11 +53540,11 @@ function unflatten(parsed, revivers, options) {
53480
53540
  if (index2 === NEGATIVE_INFINITY) return ops.fromPrimitive(-Infinity);
53481
53541
  if (index2 === NEGATIVE_ZERO) return ops.fromPrimitive(-0);
53482
53542
  if (standalone || typeof index2 !== "number") {
53483
- throw new Error(`Invalid input`);
53543
+ invalid();
53484
53544
  }
53485
53545
  if (index2 in hydrated) return hydrated[index2];
53486
53546
  if (index2 >= values.length) {
53487
- throw new Error(`Invalid input`);
53547
+ invalid();
53488
53548
  }
53489
53549
  const value = values[index2];
53490
53550
  if (!value || typeof value !== "object") {
@@ -53533,8 +53593,13 @@ function unflatten(parsed, revivers, options) {
53533
53593
  break;
53534
53594
  case "Object": {
53535
53595
  const wrapped_index = value[1];
53536
- if (typeof values[wrapped_index] === "object" && values[wrapped_index][0] !== "BigInt") {
53537
- throw new Error("Invalid input");
53596
+ const is_boxable_sentinel = wrapped_index === NAN || wrapped_index === POSITIVE_INFINITY || wrapped_index === NEGATIVE_INFINITY || wrapped_index === NEGATIVE_ZERO;
53597
+ if (!is_boxable_sentinel) {
53598
+ const wrapped = get_raw(wrapped_index);
53599
+ const is_bigint = Array.isArray(wrapped) && wrapped[0] === "BigInt";
53600
+ if ((wrapped === void 0 || typeof wrapped === "object") && !is_bigint) {
53601
+ invalid();
53602
+ }
53538
53603
  }
53539
53604
  hydrated[index2] = ops.box(hydrate2(wrapped_index));
53540
53605
  break;
@@ -53546,10 +53611,14 @@ function unflatten(parsed, revivers, options) {
53546
53611
  const obj = ops.createNullPrototypeObject();
53547
53612
  hydrated[index2] = obj;
53548
53613
  for (let i = 1; i < value.length; i += 2) {
53549
- if (value[i] === "__proto__") {
53614
+ const key = value[i];
53615
+ if (typeof key !== "string") {
53616
+ throw new Error("Cannot parse an object with a non-string key");
53617
+ }
53618
+ if (key === "__proto__") {
53550
53619
  throw new Error("Cannot parse an object with a `__proto__` property");
53551
53620
  }
53552
- ops.set(obj, value[i], hydrate2(value[i + 1]));
53621
+ ops.set(obj, key, hydrate2(value[i + 1]));
53553
53622
  }
53554
53623
  break;
53555
53624
  case "Int8Array":
@@ -53565,10 +53634,12 @@ function unflatten(parsed, revivers, options) {
53565
53634
  case "BigInt64Array":
53566
53635
  case "BigUint64Array":
53567
53636
  case "DataView": {
53568
- if (values[value[1]][0] !== "ArrayBuffer") {
53569
- throw new Error("Invalid data");
53637
+ const buffer_index = value[1];
53638
+ const raw2 = get_raw(buffer_index);
53639
+ if (!Array.isArray(raw2) || raw2[0] !== "ArrayBuffer") {
53640
+ invalid();
53570
53641
  }
53571
- const buffer2 = hydrate2(value[1]);
53642
+ const buffer2 = hydrate2(buffer_index);
53572
53643
  hydrated[index2] = ops.fromViewInfo(type, buffer2, value[2], value[3]);
53573
53644
  break;
53574
53645
  }
@@ -53599,14 +53670,14 @@ function unflatten(parsed, revivers, options) {
53599
53670
  } else if (value[0] === SPARSE) {
53600
53671
  const len = value[1];
53601
53672
  if (!is_valid_array_len(len)) {
53602
- throw new Error("Invalid input");
53673
+ invalid();
53603
53674
  }
53604
53675
  const array2 = ops.createSparseArray(len);
53605
53676
  hydrated[index2] = array2;
53606
53677
  for (let i = 2; i < value.length; i += 2) {
53607
53678
  const idx = value[i];
53608
53679
  if (!is_valid_array_index(idx) || idx >= len) {
53609
- throw new Error("Invalid input");
53680
+ invalid();
53610
53681
  }
53611
53682
  ops.set(array2, idx, hydrate2(value[i + 1]));
53612
53683
  }
@@ -53647,8 +53718,16 @@ function run(async, value, reducers, options) {
53647
53718
  custom2.push({ key, fn: reducers[key] });
53648
53719
  }
53649
53720
  }
53650
- const keys2 = [];
53721
+ let keys2 = [];
53651
53722
  let p2 = 0;
53723
+ function error2(message2, thing) {
53724
+ const path2 = format_path(keys2, (key) => {
53725
+ const key_type = ops.typeOf(key);
53726
+ const key_is_primitive = key_type !== "object" && key_type !== "function" && key_type !== "symbol";
53727
+ return key_is_primitive ? stringify_primitive(ops.toPrimitive(key)) : "...";
53728
+ });
53729
+ throw new DevalueError(message2, path2, thing, value);
53730
+ }
53652
53731
  function flatten2(thing, index3) {
53653
53732
  const type = ops.typeOf(thing);
53654
53733
  if (type === "undefined") return UNDEFINED$2;
@@ -53676,22 +53755,25 @@ function run(async, value, reducers, options) {
53676
53755
  }
53677
53756
  }
53678
53757
  if (type === "function") {
53679
- throw new DevalueError(`Cannot stringify a function`, keys2, thing, value);
53758
+ error2(`Cannot stringify a function`, thing);
53680
53759
  } else if (type === "symbol") {
53681
- throw new DevalueError(`Cannot stringify a Symbol primitive`, keys2, thing, value);
53760
+ error2(`Cannot stringify a Symbol primitive`, thing);
53682
53761
  }
53683
53762
  let str = "";
53684
53763
  if (type !== "object") {
53685
53764
  str = stringify_primitive(type === "number" ? number2 : ops.toPrimitive(thing));
53686
53765
  } else if (ops.isThenable(thing)) {
53687
53766
  {
53688
- throw new DevalueError(
53689
- `Cannot stringify a Promise or thenable — use stringifyAsync instead`,
53690
- keys2,
53691
- thing,
53692
- value
53693
- );
53767
+ error2(`Cannot stringify a Promise or thenable — use stringifyAsync instead`, thing);
53694
53768
  }
53769
+ const prev_keys = keys2.slice();
53770
+ str = ops.toPromise(thing).then((value2) => {
53771
+ keys2 = prev_keys;
53772
+ const i = flatten2(value2, index3);
53773
+ if (i < 0) stringified[index3] = i;
53774
+ });
53775
+ str.catch(() => {
53776
+ });
53695
53777
  } else {
53696
53778
  const tag = ops.tagOf(thing);
53697
53779
  switch (tag) {
@@ -53721,7 +53803,7 @@ function run(async, value, reducers, options) {
53721
53803
  for (let i = 0; i < length; i += 1) {
53722
53804
  if (i > 0) str += ",";
53723
53805
  if (ops.hasOwn(thing, i)) {
53724
- keys2.push(`[${i}]`);
53806
+ keys2.push(i);
53725
53807
  str += flatten2(ops.get(thing, i));
53726
53808
  keys2.pop();
53727
53809
  } else if (mostly_dense) {
@@ -53736,7 +53818,7 @@ function run(async, value, reducers, options) {
53736
53818
  str = "[" + SPARSE + "," + length;
53737
53819
  for (let j2 = 0; j2 < populated_keys.length; j2++) {
53738
53820
  const key = populated_keys[j2];
53739
- keys2.push(`[${key}]`);
53821
+ keys2.push(+key);
53740
53822
  str += "," + key + "," + flatten2(ops.get(thing, key));
53741
53823
  keys2.pop();
53742
53824
  }
@@ -53760,13 +53842,10 @@ function run(async, value, reducers, options) {
53760
53842
  case "Map":
53761
53843
  str = '["Map"';
53762
53844
  for (const [key, value2] of ops.entriesOf(thing)) {
53763
- const key_type = ops.typeOf(key);
53764
- const key_is_primitive = key_type !== "object" && key_type !== "function" && key_type !== "symbol";
53765
- keys2.push(
53766
- `.get(${key_is_primitive ? stringify_primitive(ops.toPrimitive(key)) : "..."})`
53767
- );
53845
+ keys2.push(MAP_KEY, key);
53768
53846
  str += `,${flatten2(key)},${flatten2(value2)}`;
53769
53847
  keys2.pop();
53848
+ keys2.pop();
53770
53849
  }
53771
53850
  str += "]";
53772
53851
  break;
@@ -53817,24 +53896,19 @@ function run(async, value, reducers, options) {
53817
53896
  default: {
53818
53897
  const shape = ops.shapeOf(thing);
53819
53898
  if (shape.kind === "not-plain") {
53820
- throw new DevalueError(`Cannot stringify arbitrary non-POJOs`, keys2, thing, value);
53899
+ error2(`Cannot stringify arbitrary non-POJOs`, thing);
53821
53900
  }
53822
53901
  if (shape.kind === "symbol-keys") {
53823
- throw new DevalueError(`Cannot stringify POJOs with symbolic keys`, keys2, thing, value);
53902
+ error2(`Cannot stringify POJOs with symbolic keys`, thing);
53824
53903
  }
53825
53904
  if (shape.kind === "null-proto") {
53826
53905
  str = '["null"';
53827
53906
  for (const key of shape.keys) {
53828
53907
  if (key === "__proto__") {
53829
- throw new DevalueError(
53830
- `Cannot stringify objects with __proto__ keys`,
53831
- keys2,
53832
- thing,
53833
- value
53834
- );
53908
+ error2(`Cannot stringify objects with __proto__ keys`, thing);
53835
53909
  }
53836
- keys2.push(stringify_key(key));
53837
- str += `,${stringify_string(key)},${flatten2(ops.get(thing, key))}`;
53910
+ keys2.push(key);
53911
+ str += `,${quote_key(key)},${flatten2(ops.get(thing, key))}`;
53838
53912
  keys2.pop();
53839
53913
  }
53840
53914
  str += "]";
@@ -53843,17 +53917,12 @@ function run(async, value, reducers, options) {
53843
53917
  let started = false;
53844
53918
  for (const key of shape.keys) {
53845
53919
  if (key === "__proto__") {
53846
- throw new DevalueError(
53847
- `Cannot stringify objects with __proto__ keys`,
53848
- keys2,
53849
- thing,
53850
- value
53851
- );
53920
+ error2(`Cannot stringify objects with __proto__ keys`, thing);
53852
53921
  }
53853
53922
  if (started) str += ",";
53854
53923
  started = true;
53855
- keys2.push(stringify_key(key));
53856
- str += `${stringify_string(key)}:${flatten2(ops.get(thing, key))}`;
53924
+ keys2.push(key);
53925
+ str += `${quote_key(key)}:${flatten2(ops.get(thing, key))}`;
53857
53926
  keys2.pop();
53858
53927
  }
53859
53928
  str += "}";
@@ -54208,6 +54277,20 @@ class PreconditionFailedError extends WorkflowWorldError {
54208
54277
  return isError(value) && value.name === "PreconditionFailedError";
54209
54278
  }
54210
54279
  }
54280
+ const IN_BAND_SUPERSEDED_CODE = "in-band-superseded";
54281
+ class InBandSupersededError extends WorkflowWorldError {
54282
+ constructor(message2, options) {
54283
+ super(message2, { status: 412, code: IN_BAND_SUPERSEDED_CODE });
54284
+ __publicField(this, "seq");
54285
+ __publicField(this, "seqInBand");
54286
+ this.name = "InBandSupersededError";
54287
+ this.seq = options == null ? void 0 : options.seq;
54288
+ this.seqInBand = options == null ? void 0 : options.seqInBand;
54289
+ }
54290
+ static is(value) {
54291
+ return isError(value) && value.name === "InBandSupersededError";
54292
+ }
54293
+ }
54211
54294
  class WorkflowRunCancelledError extends WorkflowError {
54212
54295
  constructor(runId) {
54213
54296
  super(`Workflow run "${runId}" cancelled`, {});
@@ -55599,7 +55682,7 @@ function replaceEncryptedAndExpiredWithMarkers(resource) {
55599
55682
  }
55600
55683
  async function hydrateResourceIOAsync(resource, key) {
55601
55684
  const { hydrateDataWithKey: hydrateDataWithKey2, deriveRunPayloadKeys: deriveRunPayloadKeys2 } = await Promise.resolve().then(() => serializationFormat);
55602
- const { ensureZstdDecoderRegistered } = await import("./zstd-browser-decoder-B2bHyQlS.js");
55685
+ const { ensureZstdDecoderRegistered } = await import("./zstd-browser-decoder-BJ5qrMmm.js");
55603
55686
  ensureZstdDecoderRegistered();
55604
55687
  const cryptoKey = key ? await deriveRunPayloadKeys2(key) : void 0;
55605
55688
  const revivers = getRevivers();
@@ -58057,8 +58140,8 @@ function isObjectLike(value) {
58057
58140
  return typeof value === "object" && value !== null;
58058
58141
  }
58059
58142
  function isSameBytesDisplay(a2, b2) {
58060
- var _a3, _b2, _c2, _d2, _e2, _f;
58061
- return a2.text === b2.text && ((_a3 = a2.decodedFrom) == null ? void 0 : _a3.type) === ((_b2 = b2.decodedFrom) == null ? void 0 : _b2.type) && ((_c2 = a2.decodedFrom) == null ? void 0 : _c2.encoding) === ((_d2 = b2.decodedFrom) == null ? void 0 : _d2.encoding) && ((_e2 = a2.decodedFrom) == null ? void 0 : _e2.rawSummary) === ((_f = b2.decodedFrom) == null ? void 0 : _f.rawSummary);
58143
+ var _a3, _b2, _c2, _d2, _e3, _f2;
58144
+ return a2.text === b2.text && ((_a3 = a2.decodedFrom) == null ? void 0 : _a3.type) === ((_b2 = b2.decodedFrom) == null ? void 0 : _b2.type) && ((_c2 = a2.decodedFrom) == null ? void 0 : _c2.encoding) === ((_d2 = b2.decodedFrom) == null ? void 0 : _d2.encoding) && ((_e3 = a2.decodedFrom) == null ? void 0 : _e3.rawSummary) === ((_f2 = b2.decodedFrom) == null ? void 0 : _f2.rawSummary);
58062
58145
  }
58063
58146
  function haveSameIterableValues(a2, b2, seen) {
58064
58147
  const aIterator = a2[Symbol.iterator]();
@@ -85883,7 +85966,7 @@ var x = class u2 {
85883
85966
  return this.inlineQueue.push({ src: e, tokens: t }), t;
85884
85967
  }
85885
85968
  inlineTokens(e, t = []) {
85886
- var _a3, _b2, _c2, _d2, _e2;
85969
+ var _a3, _b2, _c2, _d2, _e3;
85887
85970
  let n = e, r2 = null;
85888
85971
  if (this.tokens.links) {
85889
85972
  let o = Object.keys(this.tokens.links);
@@ -85941,7 +86024,7 @@ var x = class u2 {
85941
86024
  continue;
85942
86025
  }
85943
86026
  let l = e;
85944
- if ((_e2 = this.options.extensions) == null ? void 0 : _e2.startInline) {
86027
+ if ((_e3 = this.options.extensions) == null ? void 0 : _e3.startInline) {
85945
86028
  let p2 = 1 / 0, c = e.slice(1), d2;
85946
86029
  this.options.extensions.startInline.forEach((h2) => {
85947
86030
  d2 = h2.call({ lexer: this }, c), typeof d2 == "number" && d2 >= 0 && (p2 = Math.min(p2, d2));
@@ -86267,7 +86350,7 @@ var b = class u3 {
86267
86350
  return n;
86268
86351
  }
86269
86352
  };
86270
- var P = (_b = class {
86353
+ var P = (_d = class {
86271
86354
  constructor(e) {
86272
86355
  __publicField(this, "options");
86273
86356
  __publicField(this, "block");
@@ -86291,7 +86374,7 @@ var P = (_b = class {
86291
86374
  provideParser() {
86292
86375
  return this.block ? b.parse : b.parseInline;
86293
86376
  }
86294
- }, __publicField(_b, "passThroughHooks", /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"])), __publicField(_b, "passThroughHooksRespectAsync", /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens"])), _b);
86377
+ }, __publicField(_d, "passThroughHooks", /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"])), __publicField(_d, "passThroughHooksRespectAsync", /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens"])), _d);
86295
86378
  var B = class {
86296
86379
  constructor(...e) {
86297
86380
  __publicField(this, "defaults", M());
@@ -86587,7 +86670,7 @@ var tn = f("block", "before:content-[counter(line)]", "before:inline-block", "be
86587
86670
  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 });
86588
86671
  var Se = reactExports.createContext({ code: "" }), de = () => reactExports.useContext(Se);
86589
86672
  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 }) });
86590
- var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-B7OeHZjS.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
86673
+ var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-99nXCMDQ.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
86591
86674
  let i = reactExports.useMemo(() => e.replace(cn$1, ""), [e]), c = reactExports.useMemo(() => ({ bg: "transparent", fg: "inherit", tokens: i.split(`
86592
86675
  `).map((a2) => [{ content: a2, color: "inherit", bgColor: "transparent", htmlStyle: {}, offset: 0 }]) }), [i]);
86593
86676
  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 }) })] }) });
@@ -86909,7 +86992,7 @@ var Dt = ({ children: e, className: t, onDownload: o, onError: n }) => {
86909
86992
  }, []), 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] });
86910
86993
  };
86911
86994
  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 }) })] });
86912
- var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-h6E4ztpF.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
86995
+ var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-Csd1n701.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
86913
86996
  function ke(e, t) {
86914
86997
  if (!(e != null && e.position || t != null && t.position)) return true;
86915
86998
  if (!(e != null && e.position && (t != null && t.position))) return false;
@@ -87769,7 +87852,7 @@ function runToSpan(run2, runEvents, nowTime) {
87769
87852
  const endTime = completedAt ?? now2;
87770
87853
  const wasCancelled = run2.status === "cancelled" || (terminalEvent == null ? void 0 : terminalEvent.eventType) === "run_cancelled";
87771
87854
  const cancelReason = (terminalEvent == null ? void 0 : terminalEvent.eventType) === "run_cancelled" && typeof ((_a3 = terminalEvent.eventData) == null ? void 0 : _a3.cancelReason) === "string" ? terminalEvent.eventData.cancelReason : null;
87772
- const { input: _i, output: _o2, error: _e2, ...runIdentity } = run2;
87855
+ const { input: _i, output: _o2, error: _e3, ...runIdentity } = run2;
87773
87856
  const attributes = {
87774
87857
  resource: "run",
87775
87858
  data: {
@@ -89502,11 +89585,11 @@ const escapedStringRegExp = /^'([^]*?)'?$/;
89502
89585
  const doubleQuoteRegExp = /''/g;
89503
89586
  const unescapedLatinCharacterRegExp = /[a-zA-Z]/;
89504
89587
  function format(date2, formatStr, options) {
89505
- var _a3, _b2, _c2, _d2, _e2, _f, _g, _h;
89588
+ var _a3, _b2, _c2, _d2, _e3, _f2, _g, _h;
89506
89589
  const defaultOptions2 = getDefaultOptions();
89507
89590
  const locale = (options == null ? void 0 : options.locale) ?? defaultOptions2.locale ?? enUS;
89508
89591
  const firstWeekContainsDate = (options == null ? void 0 : options.firstWeekContainsDate) ?? ((_b2 = (_a3 = options == null ? void 0 : options.locale) == null ? void 0 : _a3.options) == null ? void 0 : _b2.firstWeekContainsDate) ?? defaultOptions2.firstWeekContainsDate ?? ((_d2 = (_c2 = defaultOptions2.locale) == null ? void 0 : _c2.options) == null ? void 0 : _d2.firstWeekContainsDate) ?? 1;
89509
- const weekStartsOn = (options == null ? void 0 : options.weekStartsOn) ?? ((_f = (_e2 = options == null ? void 0 : options.locale) == null ? void 0 : _e2.options) == null ? void 0 : _f.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_h = (_g = defaultOptions2.locale) == null ? void 0 : _g.options) == null ? void 0 : _h.weekStartsOn) ?? 0;
89592
+ const weekStartsOn = (options == null ? void 0 : options.weekStartsOn) ?? ((_f2 = (_e3 = options == null ? void 0 : options.locale) == null ? void 0 : _e3.options) == null ? void 0 : _f2.weekStartsOn) ?? defaultOptions2.weekStartsOn ?? ((_h = (_g = defaultOptions2.locale) == null ? void 0 : _g.options) == null ? void 0 : _h.weekStartsOn) ?? 0;
89510
89593
  const originalDate = toDate(date2, options == null ? void 0 : options.in);
89511
89594
  if (!isValid(originalDate)) {
89512
89595
  throw new RangeError("Invalid time value");
@@ -95718,7 +95801,7 @@ function describeThrownValue(value) {
95718
95801
  }
95719
95802
  }
95720
95803
  function logOtelDiagnosticOnce$1(otel2, tracer) {
95721
- var _a3, _b2, _c2, _d2, _e2;
95804
+ var _a3, _b2, _c2, _d2, _e3;
95722
95805
  const debugEnabled = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
95723
95806
  if (otelDiagLogged$1 || !debugEnabled)
95724
95807
  return;
@@ -95733,7 +95816,7 @@ function logOtelDiagnosticOnce$1(otel2, tracer) {
95733
95816
  providerCtor: ((_b2 = provider == null ? void 0 : provider.constructor) == null ? void 0 : _b2.name) ?? null,
95734
95817
  delegateCtor: ((_c2 = delegate == null ? void 0 : delegate.constructor) == null ? void 0 : _c2.name) ?? null,
95735
95818
  tracerCtor: ((_d2 = tracer == null ? void 0 : tracer.constructor) == null ? void 0 : _d2.name) ?? null,
95736
- probeCtor: ((_e2 = probe == null ? void 0 : probe.constructor) == null ? void 0 : _e2.name) ?? null,
95819
+ probeCtor: ((_e3 = probe == null ? void 0 : probe.constructor) == null ? void 0 : _e3.name) ?? null,
95737
95820
  probeRecording: probe.isRecording()
95738
95821
  }));
95739
95822
  probe.end();
@@ -97295,6 +97378,7 @@ const devalueCodec = {
97295
97378
  };
97296
97379
  const COMPRESSION_MIN_BYTES = 1024;
97297
97380
  const COMPRESSION_MIN_SAVINGS_RATIO = 0.05;
97381
+ const COMPRESSION_ASYNC_MIN_BYTES = 256 * 1024;
97298
97382
  const ZSTD_LEVEL = 3;
97299
97383
  function isCompressionDisabledByEnv() {
97300
97384
  var _a3;
@@ -97367,6 +97451,20 @@ function zstdBytes(data2) {
97367
97451
  const z2 = getNodeZlib$1();
97368
97452
  return new Uint8Array(z2.zstdCompressSync(data2, zstdOpts(z2)));
97369
97453
  }
97454
+ function zstdBytesAsync(data2) {
97455
+ const z2 = getNodeZlib$1();
97456
+ if (typeof (z2 == null ? void 0 : z2.zstdCompress) !== "function") {
97457
+ return Promise.resolve(zstdBytes(data2));
97458
+ }
97459
+ return new Promise((resolve2, reject) => {
97460
+ z2.zstdCompress(data2, zstdOpts(z2), (err, result) => {
97461
+ if (err)
97462
+ reject(err);
97463
+ else
97464
+ resolve2(new Uint8Array(result));
97465
+ });
97466
+ });
97467
+ }
97370
97468
  function unzstdBytes(data2, maxOutputBytes) {
97371
97469
  const z2 = getNodeZlib$1();
97372
97470
  if (!(z2 == null ? void 0 : z2.zstdDecompressSync)) {
@@ -97408,7 +97506,7 @@ async function compress(data2, mode, stats2, opts) {
97408
97506
  recordStats(stats2, "none", data2.length, data2.length);
97409
97507
  return data2;
97410
97508
  }
97411
- const compressed = codec === "zstd" ? zstdBytes(data2) : await gzipBytes(data2);
97509
+ const compressed = codec === "zstd" ? (opts == null ? void 0 : opts.preferAsync) && data2.length >= COMPRESSION_ASYNC_MIN_BYTES ? await zstdBytesAsync(data2) : zstdBytes(data2) : await gzipBytes(data2);
97412
97510
  const format2 = codec === "zstd" ? SerializationFormat$1.ZSTD : SerializationFormat$1.GZIP;
97413
97511
  const wrappedLength = 4 + compressed.length;
97414
97512
  if (wrappedLength >= data2.length * (1 - COMPRESSION_MIN_SAVINGS_RATIO)) {
@@ -97464,7 +97562,7 @@ async function serialize$3(value, encryptionKey, options) {
97464
97562
  try {
97465
97563
  const payload = devalueCodec.serialize(value, "client", options);
97466
97564
  const prefixed = encodeWithFormatPrefix(SerializationFormat$1.DEVALUE_V1, payload);
97467
- const compressed = await compress(prefixed, (options == null ? void 0 : options.compression) ?? false, options == null ? void 0 : options.compressionStats);
97565
+ const compressed = await compress(prefixed, (options == null ? void 0 : options.compression) ?? false, options == null ? void 0 : options.compressionStats, { preferAsync: true });
97468
97566
  return encrypt(compressed, encryptionKey);
97469
97567
  } catch (error2) {
97470
97568
  rethrowIfRuntimeError(error2);
@@ -97548,13 +97646,13 @@ var EventConsumerResult;
97548
97646
  EventConsumerResult2[EventConsumerResult2["NotConsumed"] = 1] = "NotConsumed";
97549
97647
  EventConsumerResult2[EventConsumerResult2["Finished"] = 2] = "Finished";
97550
97648
  })(EventConsumerResult || (EventConsumerResult = {}));
97551
- _d = ABORT_STREAM_NAME, _c = ABORT_HOOK_TOKEN;
97649
+ _f = ABORT_STREAM_NAME, _e2 = ABORT_HOOK_TOKEN;
97552
97650
  class WorkflowAbortSignal {
97553
97651
  constructor(streamName, hookToken) {
97554
97652
  __publicField(this, "aborted", false);
97555
97653
  __publicField(this, "reason");
97556
- __publicField(this, _d);
97557
- __publicField(this, _c);
97654
+ __publicField(this, _f);
97655
+ __publicField(this, _e2);
97558
97656
  __privateAdd(this, _listeners, []);
97559
97657
  __privateAdd(this, _onabort, null);
97560
97658
  this[ABORT_STREAM_NAME] = streamName;
@@ -107377,7 +107475,7 @@ function getCompressionMode(capabilities) {
107377
107475
  }
107378
107476
  return capabilities.supportedFormats.has(SerializationFormat$1.ZSTD) ? true : "gzip";
107379
107477
  }
107380
- const version$1 = "5.2.0";
107478
+ const version$1 = "5.2.2";
107381
107479
  const DEFAULT_HEALTH_CHECK_TIMEOUT = 3e4;
107382
107480
  const SAFE_WORKFLOW_NAME_PATTERN = /^[a-zA-Z0-9_\-./@()[\]]+$/;
107383
107481
  function getWorkflowQueueName(workflowName, namespace2) {
@@ -107568,7 +107666,7 @@ function getSnapshotThresholdFromEnv(env2 = process.env) {
107568
107666
  return parsed;
107569
107667
  }
107570
107668
  function waitUntil(promise2) {
107571
- void import("./index-oHATtR_7.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => {
107669
+ void import("./index-CI1MEtXX.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => {
107572
107670
  waitUntil2(promise2);
107573
107671
  });
107574
107672
  }
@@ -107701,7 +107799,7 @@ async function start$1(workflow, argsOrOptions, options) {
107701
107799
  const queueName = getWorkflowQueueName(workflowName, opts.namespace);
107702
107800
  const spanName = `workflow.start ${workflowDisplayName(workflowName)}`;
107703
107801
  return trace$2(spanName, async (span) => {
107704
- var _a3, _b2, _c2, _d2, _e2;
107802
+ var _a3, _b2, _c2, _d2, _e3;
107705
107803
  span == null ? void 0 : span.setAttributes({
107706
107804
  ...WorkflowName(workflowName),
107707
107805
  ...WorkflowOperation("start")
@@ -107856,9 +107954,11 @@ async function start$1(workflow, argsOrOptions, options) {
107856
107954
  }
107857
107955
  const workflowVm = getWorkflowVmFromEnv();
107858
107956
  const snapshotThreshold = getSnapshotThresholdFromEnv();
107957
+ const queueNamespace = resolveQueueNamespace(opts.namespace);
107859
107958
  const executionContext = {
107860
107959
  traceCarrier,
107861
107960
  workflowCoreVersion: version$1,
107961
+ ...queueNamespace ? { queueNamespace } : {},
107862
107962
  ...targetNodeVersion ? { nodeVersion: targetNodeVersion } : {},
107863
107963
  features: { encryption: !!encryptionKey },
107864
107964
  ...targetHookResumeInputVersion !== void 0 ? { hookResumeInputVersion: targetHookResumeInputVersion } : {},
@@ -107875,7 +107975,8 @@ async function start$1(workflow, argsOrOptions, options) {
107875
107975
  }
107876
107976
  }
107877
107977
  const compression = specVersion >= SPEC_VERSION_SUPPORTS_COMPRESSION ? targetCompression : false;
107878
- const workflowArguments = await dehydrateWorkflowArguments(args, runId, encryptionKey, ops, globalThis, v1Compat, framedByteStreams, compression);
107978
+ const argumentCompression = opts.compressArguments === false ? false : compression;
107979
+ const workflowArguments = await dehydrateWorkflowArguments(args, runId, encryptionKey, ops, globalThis, v1Compat, framedByteStreams, argumentCompression);
107879
107980
  let dynamicWorkflowCode;
107880
107981
  let dynamicWorkflowCodeRef;
107881
107982
  if (dynamicWorkflow) {
@@ -107896,7 +107997,7 @@ async function start$1(workflow, argsOrOptions, options) {
107896
107997
  ...dynamicWorkflowCode ? { dynamicWorkflowCode } : {},
107897
107998
  ...dynamicWorkflowCodeRef ? { dynamicWorkflowCodeRef } : {}
107898
107999
  } : {};
107899
- const creatorEnvironment = (_e2 = world.getEnvironment) == null ? void 0 : _e2.call(world);
108000
+ const creatorEnvironment = (_e3 = world.getEnvironment) == null ? void 0 : _e3.call(world);
107900
108001
  const runCreated = world.events.create(runId, {
107901
108002
  eventType: "run_created",
107902
108003
  specVersion,
@@ -108783,6 +108884,25 @@ function once(fn2) {
108783
108884
  };
108784
108885
  return result;
108785
108886
  }
108887
+ function withInProcessLock(locks, key, fn2) {
108888
+ const prev = locks.get(key);
108889
+ const taskBox = {};
108890
+ const task = (async () => {
108891
+ if (prev) {
108892
+ await prev.catch(() => void 0);
108893
+ }
108894
+ try {
108895
+ return await fn2();
108896
+ } finally {
108897
+ if (locks.get(key) === taskBox.task) {
108898
+ locks.delete(key);
108899
+ }
108900
+ }
108901
+ })();
108902
+ taskBox.task = task;
108903
+ locks.set(key, task);
108904
+ return task;
108905
+ }
108786
108906
  const getDataDirFromEnv = () => {
108787
108907
  return process.env.WORKFLOW_LOCAL_DATA_DIR || ".workflow-data";
108788
108908
  };
@@ -111517,17 +111637,15 @@ async function inspectEntityDirs(dataDir) {
111517
111637
  runScoped: false
111518
111638
  };
111519
111639
  for (const entityDir of RUN_SCOPED_ENTITY_DIRS) {
111520
- let dir;
111521
111640
  try {
111522
- dir = await opendir(path$3.join(dataDir, entityDir));
111641
+ for await (const entry2 of await opendir(path$3.join(dataDir, entityDir))) {
111642
+ classifyEntityDirEntry(layout, entityDir, entry2);
111643
+ }
111523
111644
  } catch (error2) {
111524
111645
  if (error2.code === "ENOENT")
111525
111646
  continue;
111526
111647
  throw error2;
111527
111648
  }
111528
- for await (const entry2 of dir) {
111529
- classifyEntityDirEntry(layout, entityDir, entry2);
111530
- }
111531
111649
  }
111532
111650
  return layout;
111533
111651
  }
@@ -114880,7 +114998,7 @@ function requireUnwrapHandler() {
114880
114998
  var dispatcherBase;
114881
114999
  var hasRequiredDispatcherBase;
114882
115000
  function requireDispatcherBase() {
114883
- var _a3, _b2, _c2, _d2, _e2;
115001
+ var _a3, _b2, _c2, _d2, _e3;
114884
115002
  if (hasRequiredDispatcherBase) return dispatcherBase;
114885
115003
  hasRequiredDispatcherBase = 1;
114886
115004
  const Dispatcher = requireDispatcher();
@@ -114894,7 +115012,7 @@ function requireDispatcherBase() {
114894
115012
  const kOnDestroyed = Symbol("onDestroyed");
114895
115013
  const kOnClosed = Symbol("onClosed");
114896
115014
  const kWebSocketOptions = Symbol("webSocketOptions");
114897
- class DispatcherBase extends (_e2 = Dispatcher, _d2 = kDestroyed, _c2 = kOnDestroyed, _b2 = kClosed, _a3 = kOnClosed, _e2) {
115015
+ class DispatcherBase extends (_e3 = Dispatcher, _d2 = kDestroyed, _c2 = kOnDestroyed, _b2 = kClosed, _a3 = kOnClosed, _e3) {
114898
115016
  /**
114899
115017
  * @param {import('../../types/dispatcher').DispatcherOptions} [opts]
114900
115018
  */
@@ -121452,7 +121570,7 @@ function requireFixedQueue() {
121452
121570
  var poolBase;
121453
121571
  var hasRequiredPoolBase;
121454
121572
  function requirePoolBase() {
121455
- var _a3, _b2, _c2, _d2, _e2, _f, _g;
121573
+ var _a3, _b2, _c2, _d2, _e3, _f2, _g;
121456
121574
  if (hasRequiredPoolBase) return poolBase;
121457
121575
  hasRequiredPoolBase = 1;
121458
121576
  const { PoolStats } = requireStats();
@@ -121474,8 +121592,8 @@ function requirePoolBase() {
121474
121592
  constructor() {
121475
121593
  super(...arguments);
121476
121594
  __publicField(this, _g, new FixedQueue());
121477
- __publicField(this, _f, 0);
121478
- __publicField(this, _e2, []);
121595
+ __publicField(this, _f2, 0);
121596
+ __publicField(this, _e3, []);
121479
121597
  __publicField(this, _d2, false);
121480
121598
  __publicField(this, _c2, (origin, targets) => {
121481
121599
  this.emit("connect", origin, [this, ...targets]);
@@ -121487,7 +121605,7 @@ function requirePoolBase() {
121487
121605
  this.emit("connectionError", origin, [this, ...targets], err);
121488
121606
  });
121489
121607
  }
121490
- [(_g = kQueue, _f = kQueued, _e2 = kClients, _d2 = kNeedDrain, kOnDrain)](client2, origin, targets) {
121608
+ [(_g = kQueue, _f2 = kQueued, _e3 = kClients, _d2 = kNeedDrain, kOnDrain)](client2, origin, targets) {
121491
121609
  const queue = this[kQueue];
121492
121610
  let needDrain = false;
121493
121611
  while (!needDrain) {
@@ -123375,7 +123493,7 @@ function requireRetryHandler() {
123375
123493
  this.controllerProxy = new RetryController();
123376
123494
  }
123377
123495
  onResponseStartWithRetry(controller, statusCode, headers2, statusMessage, err) {
123378
- var _a3, _b2, _c2, _d2, _e2, _f;
123496
+ var _a3, _b2, _c2, _d2, _e3, _f2;
123379
123497
  if (this.retryOpts.throwOnError) {
123380
123498
  if (this.retryOpts.statusCodes.includes(statusCode) === false) {
123381
123499
  if (this.headersSent) {
@@ -123393,7 +123511,7 @@ function requireRetryHandler() {
123393
123511
  if (isDisturbed(this.opts.body)) {
123394
123512
  this.headersSent = true;
123395
123513
  this.checkpointResponseEnd(headers2);
123396
- (_f = (_e2 = this.handler).onResponseStart) == null ? void 0 : _f.call(_e2, this.controllerProxy, statusCode, headers2, statusMessage);
123514
+ (_f2 = (_e3 = this.handler).onResponseStart) == null ? void 0 : _f2.call(_e3, this.controllerProxy, statusCode, headers2, statusMessage);
123397
123515
  return;
123398
123516
  }
123399
123517
  function shouldRetry(passedErr) {
@@ -130764,7 +130882,7 @@ function requireDeduplicationHandler() {
130764
130882
  * @param {object} trailers
130765
130883
  */
130766
130884
  onResponseEnd(controller, trailers) {
130767
- var _a3, _b2, _c2, _d2, _e2;
130885
+ var _a3, _b2, _c2, _d2, _e3;
130768
130886
  if (__privateGet(this, _aborted) || __privateGet(this, _completed)) {
130769
130887
  return;
130770
130888
  }
@@ -130791,7 +130909,7 @@ function requireDeduplicationHandler() {
130791
130909
  waitingHandler.done = true;
130792
130910
  }
130793
130911
  __privateMethod(this, _DeduplicationHandler_instances, pruneDoneWaitingHandlers_fn).call(this);
130794
- (_e2 = __privateGet(this, _onComplete)) == null ? void 0 : _e2.call(this);
130912
+ (_e3 = __privateGet(this, _onComplete)) == null ? void 0 : _e3.call(this);
130795
130913
  }
130796
130914
  /**
130797
130915
  * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
@@ -135589,14 +135707,14 @@ function requireEvents() {
135589
135707
  });
135590
135708
  }
135591
135709
  static createFastMessageEvent(type, init2) {
135592
- var _a3, _b2, _c2, _d2, _e2;
135710
+ var _a3, _b2, _c2, _d2, _e3;
135593
135711
  const messageEvent = new _MessageEvent(kConstruct, type, init2);
135594
135712
  __privateSet(messageEvent, _eventInit, init2);
135595
135713
  (_a3 = __privateGet(messageEvent, _eventInit)).data ?? (_a3.data = null);
135596
135714
  (_b2 = __privateGet(messageEvent, _eventInit)).origin ?? (_b2.origin = "");
135597
135715
  (_c2 = __privateGet(messageEvent, _eventInit)).lastEventId ?? (_c2.lastEventId = "");
135598
135716
  (_d2 = __privateGet(messageEvent, _eventInit)).source ?? (_d2.source = null);
135599
- (_e2 = __privateGet(messageEvent, _eventInit)).ports ?? (_e2.ports = []);
135717
+ (_e3 = __privateGet(messageEvent, _eventInit)).ports ?? (_e3.ports = []);
135600
135718
  return messageEvent;
135601
135719
  }
135602
135720
  };
@@ -138734,6 +138852,11 @@ function createQueue$2(config2) {
138734
138852
  const closeSignal = closeController.signal;
138735
138853
  const inflightMessages = /* @__PURE__ */ new Map();
138736
138854
  const directHandlers = /* @__PURE__ */ new Map();
138855
+ const routes2 = /* @__PURE__ */ new Map();
138856
+ const deliveryUrl = (baseUrl, prefix) => {
138857
+ const route = routes2.get(prefix);
138858
+ return route ? createAppRouteUrl(baseUrl, route) : createWorkflowUrl(baseUrl, { type: "flow" });
138859
+ };
138737
138860
  const queue = async (queueName, message2, opts) => {
138738
138861
  const cleanup = [];
138739
138862
  if (opts == null ? void 0 : opts.idempotencyKey) {
@@ -138745,6 +138868,7 @@ function createQueue$2(config2) {
138745
138868
  const body2 = transport.serialize(message2);
138746
138869
  const { prefix } = parseQueueName(queueName);
138747
138870
  const messageId = MessageId.parse(`msg_${generateId2()}`);
138871
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
138748
138872
  const msg = message2;
138749
138873
  const runId = msg.runId ?? void 0;
138750
138874
  const stepId = msg.stepId ?? void 0;
@@ -138774,20 +138898,19 @@ function createQueue$2(config2) {
138774
138898
  "content-type": "application/json",
138775
138899
  "x-vqs-queue-name": queueName,
138776
138900
  "x-vqs-message-id": messageId,
138777
- "x-vqs-message-attempt": String(delivery + 1)
138901
+ "x-vqs-message-attempt": String(delivery + 1),
138902
+ "x-vqs-message-created-at": createdAt
138778
138903
  };
138779
138904
  const directHandler = directHandlers.get(prefix);
138780
138905
  let response2;
138781
138906
  let text2;
138782
138907
  try {
138783
138908
  if (directHandler) {
138784
- const req = new Request(createWorkflowUrl(resolveDirectBaseUrl(config2), {
138785
- type: "flow"
138786
- }), { method: "POST", headers: headers2, body: body2 });
138909
+ const req = new Request(deliveryUrl(resolveDirectBaseUrl(config2), prefix), { method: "POST", headers: headers2, body: body2 });
138787
138910
  response2 = await directHandler(req);
138788
138911
  } else {
138789
138912
  const baseUrl = await resolveBaseUrl(config2);
138790
- const url = createWorkflowUrl(baseUrl, { type: "flow" });
138913
+ const url = deliveryUrl(baseUrl, prefix);
138791
138914
  response2 = nodeHttpAgents ? await nodeHttpFetch(url, {
138792
138915
  method: "POST",
138793
138916
  headers: new Headers(headers2),
@@ -138848,7 +138971,10 @@ function createQueue$2(config2) {
138848
138971
  messageId,
138849
138972
  ...runId && { runId },
138850
138973
  ...stepId && { stepId },
138851
- handlerError: text2
138974
+ handlerError: text2,
138975
+ ...!directHandler && !routes2.has(prefix) && (response2.status === 400 || response2.status === 404) && {
138976
+ hint: `No route or handler is registered for queue prefix "${prefix}", so its messages go to the Workflow SDK's flow route (${WORKFLOW_FLOW_ROUTE}). A queue consumer of its own registers one with world.registerRoute(prefix, path) or world.registerHandler(prefix, handler).`
138977
+ }
138852
138978
  });
138853
138979
  await setTimeout$1(5e3, void 0, { signal: closeSignal });
138854
138980
  }
@@ -138886,7 +139012,11 @@ function createQueue$2(config2) {
138886
139012
  const HeaderParser = compile(object$1({
138887
139013
  "x-vqs-queue-name": ValidQueueName,
138888
139014
  "x-vqs-message-id": MessageId,
138889
- "x-vqs-message-attempt": number$2()
139015
+ "x-vqs-message-attempt": number$2(),
139016
+ // Sent by world-postgres, whose `attempt` restarts on a reschedule.
139017
+ "x-vqs-message-delivery-count": number$2().int().positive().optional(),
139018
+ // Absent on a delivery from a sender that predates it.
139019
+ "x-vqs-message-created-at": datetime().optional()
138890
139020
  }));
138891
139021
  const createQueueHandler = (prefix, handler) => {
138892
139022
  return async (req) => {
@@ -138899,12 +139029,25 @@ function createQueue$2(config2) {
138899
139029
  const queueName = headers2.data["x-vqs-queue-name"];
138900
139030
  const messageId = headers2.data["x-vqs-message-id"];
138901
139031
  const attempt = headers2.data["x-vqs-message-attempt"];
139032
+ const deliveryCountHeader = headers2.data["x-vqs-message-delivery-count"];
139033
+ const createdAtHeader = headers2.data["x-vqs-message-created-at"];
138902
139034
  if (!queueName.startsWith(prefix)) {
138903
- return Response.json({ error: "Unhandled queue" }, { status: 400 });
139035
+ return Response.json({
139036
+ error: "Unhandled queue",
139037
+ detail: `This route handles queue prefix "${prefix}", not "${queueName}".`
139038
+ }, { status: 400 });
138904
139039
  }
138905
139040
  const body2 = await new TypedJsonTransport().deserialize(req.body);
138906
139041
  try {
138907
- const result = await handler(body2, { attempt, queueName, messageId });
139042
+ const result = await handler(body2, {
139043
+ attempt,
139044
+ // Counts every delivery of this message that reached a handler,
139045
+ // starting at 1, including `{ timeoutSeconds }` redeliveries.
139046
+ deliveryCount: deliveryCountHeader ?? attempt,
139047
+ ...createdAtHeader ? { createdAt: new Date(createdAtHeader) } : {},
139048
+ queueName,
139049
+ messageId
139050
+ });
138908
139051
  if (typeof body2 === "object" && body2 !== null && "invoke" in body2 && body2.invoke === true) {
138909
139052
  return Response.json({ result });
138910
139053
  }
@@ -138932,6 +139075,9 @@ function createQueue$2(config2) {
138932
139075
  registerHandler(prefix, handler) {
138933
139076
  directHandlers.set(prefix, handler);
138934
139077
  },
139078
+ registerRoute(prefix, path2) {
139079
+ routes2.set(QueuePrefix.parse(prefix), parseQueueRoute(path2));
139080
+ },
138935
139081
  async close() {
138936
139082
  if (closeSignal.aborted)
138937
139083
  return;
@@ -139178,6 +139324,11 @@ const monotonicUlid = (seedTime) => chunkIds.next(seedTime);
139178
139324
  const RunStreamsSchema = compile(object$1({
139179
139325
  streams: array$1(string$2())
139180
139326
  }));
139327
+ const RUN_STREAMS_LOCK_OPTIONS = {
139328
+ realpath: false,
139329
+ stale: 1e4,
139330
+ retries: { retries: 150, factor: 1, minTimeout: 100, maxTimeout: 100 }
139331
+ };
139181
139332
  const EOF_MARKER = 1;
139182
139333
  function isEofByte(byte) {
139183
139334
  return byte === EOF_MARKER;
@@ -139268,21 +139419,65 @@ function createStreamer$1(basedir, tag) {
139268
139419
  const tagSuffix = tag ? `.${tag}` : "";
139269
139420
  const streamEmitter = new EventEmitter();
139270
139421
  const registeredStreams = /* @__PURE__ */ new Set();
139271
- async function registerStreamForRun(runId, streamName) {
139422
+ const runStreamsLocks = /* @__PURE__ */ new Map();
139423
+ let warnedRunStreamsLockFailure = false;
139424
+ async function readRunStreams(runId) {
139425
+ const data2 = await readJSONWithFallback(basedir, "streams/runs", runId, RunStreamsSchema, tag);
139426
+ return (data2 == null ? void 0 : data2.streams) ?? [];
139427
+ }
139428
+ async function registerStreamForRun(runId, streamName, { verify = false } = {}) {
139272
139429
  assertSafeEntityId("runId", runId);
139273
139430
  assertSafeEntityId("streamName", streamName);
139274
139431
  const cacheKey = `${runId}:${streamName}`;
139275
139432
  if (registeredStreams.has(cacheKey)) {
139276
- return;
139433
+ if (!verify)
139434
+ return;
139435
+ const listed = await readRunStreams(runId).catch(() => null);
139436
+ if (listed === null || listed.includes(streamName))
139437
+ return;
139438
+ registeredStreams.delete(cacheKey);
139277
139439
  }
139278
139440
  const runStreamsPath = taggedPath(basedir, "streams/runs", runId, tag);
139279
- const existing = await readJSONWithFallback(basedir, "streams/runs", runId, RunStreamsSchema, tag);
139280
- const streams = (existing == null ? void 0 : existing.streams) ?? [];
139281
- if (!streams.includes(streamName)) {
139282
- streams.push(streamName);
139283
- await writeJSON(runStreamsPath, { streams }, { overwrite: true });
139441
+ await withInProcessLock(runStreamsLocks, runStreamsPath, async () => {
139442
+ if (registeredStreams.has(cacheKey))
139443
+ return;
139444
+ if (await addToRunStreams(runStreamsPath, runId, streamName)) {
139445
+ registeredStreams.add(cacheKey);
139446
+ }
139447
+ });
139448
+ }
139449
+ async function addToRunStreams(runStreamsPath, runId, streamName) {
139450
+ await fs$1.mkdir(path$3.dirname(runStreamsPath), { recursive: true });
139451
+ let compromised = false;
139452
+ let release;
139453
+ try {
139454
+ release = await properLockfileExports.lock(runStreamsPath, {
139455
+ ...RUN_STREAMS_LOCK_OPTIONS,
139456
+ // The default handler throws from a timer, which would crash the
139457
+ // process.
139458
+ onCompromised: () => {
139459
+ compromised = true;
139460
+ }
139461
+ });
139462
+ } catch (error2) {
139463
+ if (!warnedRunStreamsLockFailure) {
139464
+ warnedRunStreamsLockFailure = true;
139465
+ console.warn(`[world-local] Could not lock the stream index of run ${runId}; updating it without the lock:`, error2 instanceof Error ? error2.message : error2);
139466
+ }
139467
+ }
139468
+ try {
139469
+ const streams = await readRunStreams(runId);
139470
+ if (!streams.includes(streamName)) {
139471
+ streams.push(streamName);
139472
+ await writeJSON(runStreamsPath, { streams }, { overwrite: true });
139473
+ }
139474
+ } finally {
139475
+ if (release && !compromised) {
139476
+ await release().catch(() => {
139477
+ });
139478
+ }
139284
139479
  }
139285
- registeredStreams.add(cacheKey);
139480
+ return !compromised;
139286
139481
  }
139287
139482
  function toBuffer(chunk) {
139288
139483
  if (typeof chunk === "string") {
@@ -139294,6 +139489,9 @@ function createStreamer$1(basedir, tag) {
139294
139489
  }
139295
139490
  }
139296
139491
  return {
139492
+ clearCache() {
139493
+ registeredStreams.clear();
139494
+ },
139297
139495
  streams: {
139298
139496
  async write(_runId, name2, chunk) {
139299
139497
  const chunkId = `chnk_${monotonicUlid()}`;
@@ -139345,15 +139543,14 @@ function createStreamer$1(basedir, tag) {
139345
139543
  async close(_runId, name2) {
139346
139544
  const chunkId = `chnk_${monotonicUlid()}`;
139347
139545
  const runId = await _runId;
139348
- await registerStreamForRun(runId, name2);
139546
+ await registerStreamForRun(runId, name2, { verify: true });
139349
139547
  const chunkPath = path$3.join(chunkDirForStream(path$3.join(basedir, "streams", "chunks"), name2), `${chunkId}${tagSuffix}.bin`);
139350
139548
  await write(chunkPath, serializeChunk({ chunk: Buffer.from([]), eof: true }));
139351
139549
  streamEmitter.emit(`close:${name2}`, { streamName: name2 });
139352
139550
  },
139353
139551
  async list(runId) {
139354
139552
  assertSafeEntityId("runId", runId);
139355
- const data2 = await readJSONWithFallback(basedir, "streams/runs", runId, RunStreamsSchema, tag);
139356
- return (data2 == null ? void 0 : data2.streams) ?? [];
139553
+ return readRunStreams(runId);
139357
139554
  },
139358
139555
  async getChunks(_runId, name2, options) {
139359
139556
  const limit = (options == null ? void 0 : options.limit) ?? 100;
@@ -140039,24 +140236,12 @@ async function pinCanonicalEventIdForLegacyClaim(basedir, token, runId, hookId,
140039
140236
  const existing = await readHookRecoveryMarker(markerPath);
140040
140237
  return (existing == null ? void 0 : existing.eventId) ?? null;
140041
140238
  }
140042
- function withInProcessLock(locks, key, fn2) {
140043
- const prev = locks.get(key);
140044
- const taskBox = {};
140045
- const task = (async () => {
140046
- if (prev) {
140047
- await prev.catch(() => void 0);
140048
- }
140049
- try {
140050
- return await fn2();
140051
- } finally {
140052
- if (locks.get(key) === taskBox.task) {
140053
- locks.delete(key);
140054
- }
140055
- }
140056
- })();
140057
- taskBox.task = task;
140058
- locks.set(key, task);
140059
- return task;
140239
+ function isDefinitiveRefusal(error2) {
140240
+ if (EntityConflictError.is(error2) || RunExpiredError.is(error2) || TooEarlyError.is(error2) || HookNotFoundError.is(error2) || HookForceClaimedError.is(error2) || WorkflowRunNotFoundError.is(error2) || RunNotSupportedError.is(error2)) {
140241
+ return true;
140242
+ }
140243
+ const status = error2 == null ? void 0 : error2.status;
140244
+ return typeof status === "number" && status >= 400 && status < 500;
140060
140245
  }
140061
140246
  async function deleteAllWaitsForRun(basedir, runId) {
140062
140247
  const waitsDir = path$3.join(basedir, "waits");
@@ -140086,6 +140271,19 @@ async function writeRunUnderLifecycleLock(basedir, runId, tag, proposed) {
140086
140271
  return { run: next2, purged };
140087
140272
  });
140088
140273
  }
140274
+ function inBandFenceState() {
140275
+ return globalSingleton("@workflow/world-local//inBandFence", 2, () => ({
140276
+ locks: /* @__PURE__ */ new Map()
140277
+ }));
140278
+ }
140279
+ const InBandCountSchema = object$1({
140280
+ seqInBand: number$3().int().nonnegative(),
140281
+ pending: number$3().int().nonnegative().optional()
140282
+ });
140283
+ function inBandCountPath(basedir, runId, tag) {
140284
+ const name2 = tag ? `${runId}.in-band.${tag}` : `${runId}.in-band`;
140285
+ return resolveWithinBase(basedir, ".locks", "runs", name2);
140286
+ }
140089
140287
  function createEventsStorage(basedir, tag) {
140090
140288
  const hookRetentionLimitMs = getHookRetentionLimitMs();
140091
140289
  const maxCachedEventBytes = 4 * 1024 * 1024;
@@ -141446,7 +141644,122 @@ function createEventsStorage(basedir, tag) {
141446
141644
  }
141447
141645
  return reportSkippedSlots(result, params.eventCount, resolveData);
141448
141646
  });
141449
- return { ...storage, create: create2 };
141647
+ const fenceState = inBandFenceState();
141648
+ const fenceKey = (runId) => `${path$3.resolve(basedir)}\0${slotStateKey(runId)}`;
141649
+ const readInBandCount = async (runId) => await readJSON(inBandCountPath(basedir, runId, tag), InBandCountSchema) ?? {
141650
+ seqInBand: IN_BAND_SEQ_AT_RUN_CREATION
141651
+ };
141652
+ const writeInBandCount = (runId, count2) => writeJSON(inBandCountPath(basedir, runId, tag), count2, {
141653
+ overwrite: true
141654
+ });
141655
+ async function readTopSlot(runId) {
141656
+ const state = runSlotState.get(slotStateKey(runId));
141657
+ if (state === null)
141658
+ return void 0;
141659
+ const scan = await scanRunEventIds(basedir, runId, tag);
141660
+ if (state === void 0 && scan.count > 0 && !scan.usesSlots) {
141661
+ return void 0;
141662
+ }
141663
+ return Math.max((state == null ? void 0 : state.published) ?? 0, scan.maxSlot);
141664
+ }
141665
+ async function settledInBandCount(runId) {
141666
+ const count2 = await readInBandCount(runId);
141667
+ if (count2.pending === void 0)
141668
+ return count2.seqInBand;
141669
+ const settled = Math.max(count2.seqInBand, count2.pending + 1);
141670
+ await writeInBandCount(runId, { seqInBand: settled });
141671
+ return settled;
141672
+ }
141673
+ async function supersededAt(runId, expected, current2) {
141674
+ const seq = await readTopSlot(runId).catch(() => void 0);
141675
+ return new InBandSupersededError(`In-band write on run ${runId} expected seqInBand ${expected}, but the run is at ${current2}. Another orchestrator wrote in-band events this one has not seen; stop writing and redeliver.`, { seqInBand: current2, ...seq !== void 0 ? { seq } : {} });
141676
+ }
141677
+ function withFenceLock(runId, fn2) {
141678
+ return withInProcessLock(fenceState.locks, fenceKey(runId), async () => {
141679
+ const countPath = inBandCountPath(basedir, runId, tag);
141680
+ await fs$1.mkdir(path$3.dirname(countPath), { recursive: true });
141681
+ let compromised;
141682
+ let release;
141683
+ try {
141684
+ release = await properLockfileExports.lock(countPath, {
141685
+ realpath: false,
141686
+ stale: 3e4,
141687
+ update: 1e3,
141688
+ retries: {
141689
+ retries: 350,
141690
+ factor: 1,
141691
+ minTimeout: 100,
141692
+ maxTimeout: 100
141693
+ },
141694
+ onCompromised(error2) {
141695
+ compromised = error2;
141696
+ }
141697
+ });
141698
+ } catch (error2) {
141699
+ throw new WorkflowWorldError(`Could not acquire the in-band fence lock of run ${runId}`, { cause: error2 });
141700
+ }
141701
+ let result;
141702
+ try {
141703
+ result = await fn2();
141704
+ } finally {
141705
+ if (!compromised)
141706
+ await release().catch(() => {
141707
+ });
141708
+ }
141709
+ if (compromised) {
141710
+ throw new WorkflowWorldError(`The in-band fence lock of run ${runId} was lost while a write held it`, { cause: compromised });
141711
+ }
141712
+ return result;
141713
+ });
141714
+ }
141715
+ const fencedCreate = (async (runId, request2, params) => {
141716
+ const data2 = request2;
141717
+ if (!(params == null ? void 0 : params.inBand) || !runId || request2.eventType === "run_created") {
141718
+ return create2(runId, data2, params);
141719
+ }
141720
+ const expected = params.expectedSeqInBand;
141721
+ if (expected === void 0 || !Number.isSafeInteger(expected) || expected < 0) {
141722
+ throw new WorkflowWorldError(`An in-band write to run ${runId} must carry a nonnegative integer expectedSeqInBand`, { status: 400 });
141723
+ }
141724
+ assertSafeEntityId("runId", runId);
141725
+ return withFenceLock(runId, async () => {
141726
+ const current2 = await settledInBandCount(runId);
141727
+ if (current2 !== expected)
141728
+ throw await supersededAt(runId, expected, current2);
141729
+ await writeInBandCount(runId, { seqInBand: current2, pending: current2 });
141730
+ let result;
141731
+ try {
141732
+ result = await create2(runId, data2, params);
141733
+ } catch (error2) {
141734
+ await writeInBandCount(runId, {
141735
+ seqInBand: isDefinitiveRefusal(error2) ? current2 : current2 + 1
141736
+ });
141737
+ throw error2;
141738
+ }
141739
+ const allocated = result.event ? 1 : 0;
141740
+ await writeInBandCount(runId, { seqInBand: current2 + allocated });
141741
+ return { ...result, allocated };
141742
+ });
141743
+ });
141744
+ async function readEventLogSnapshot(runId) {
141745
+ const { seqInBand } = await readInBandCount(runId);
141746
+ const state = runSlotState.get(slotStateKey(runId));
141747
+ if (state === null)
141748
+ return void 0;
141749
+ if (state !== void 0)
141750
+ return { seq: state.published, seqInBand };
141751
+ const scan = await scanRunEventIds(basedir, runId, tag);
141752
+ if (scan.count > 0 && !scan.usesSlots)
141753
+ return void 0;
141754
+ return { seq: scan.maxSlot, seqInBand };
141755
+ }
141756
+ const list = (async (params) => {
141757
+ assertSafeEntityId("runId", params.runId);
141758
+ const snapshot = await readEventLogSnapshot(params.runId);
141759
+ const result = await storage.list(params);
141760
+ return snapshot ? { ...result, snapshot } : result;
141761
+ });
141762
+ return { ...storage, create: fencedCreate, list };
141450
141763
  }
141451
141764
  function createSnapshotsStorage$1(basedir) {
141452
141765
  const snapshotsDir = path$3.join(basedir, "snapshots");
@@ -141559,6 +141872,7 @@ function createWorld$2(args) {
141559
141872
  const tag = mergedConfig.tag;
141560
141873
  const queue = createQueue$2(mergedConfig);
141561
141874
  const { clearCache: clearStorageCache, ...storage } = createStorage$1(mergedConfig.dataDir, tag);
141875
+ const { clearCache: clearStreamerCache, ...streamer } = createStreamer$1(mergedConfig.dataDir, tag);
141562
141876
  const recoverActiveRuns = resolveRecoverActiveRuns(mergedConfig);
141563
141877
  return {
141564
141878
  specVersion: mintedSpecVersion(),
@@ -141575,12 +141889,16 @@ function createWorld$2(args) {
141575
141889
  // The token claim lock serializes the takeover behind
141576
141890
  // `createHook({ experimental_force: true })`; see the hook_created
141577
141891
  // branch of storage/events-storage.ts.
141578
- hookForceClaim: true
141892
+ hookForceClaim: true,
141893
+ // A per-run in-band count on disk, under a lock file, so every process
141894
+ // on the data directory shares it; see the in-band writer fence in
141895
+ // storage/events-storage.ts.
141896
+ inBandFence: true
141579
141897
  },
141580
141898
  ...queue,
141581
141899
  ...storage,
141582
141900
  ...instrumentObject$1("world.streams", {
141583
- ...createStreamer$1(mergedConfig.dataDir, tag),
141901
+ ...streamer,
141584
141902
  ...mergedConfig.streamFlushIntervalMs !== void 0 && {
141585
141903
  streamFlushIntervalMs: mergedConfig.streamFlushIntervalMs
141586
141904
  }
@@ -141610,7 +141928,7 @@ function createWorld$2(args) {
141610
141928
  const basedir = mergedConfig.dataDir;
141611
141929
  const hooksDir = path$3.join(basedir, "hooks");
141612
141930
  const taggedHookFiles = await listTaggedFiles(hooksDir, tag);
141613
- const { HookSchema: HookSchema2 } = await import("./index-DB6rD0OI.js");
141931
+ const { HookSchema: HookSchema2 } = await import("./index-TQ324kzl.js");
141614
141932
  await settleAll(taggedHookFiles.map(async (hookFile) => {
141615
141933
  const hook = await readJSON(path$3.join(hooksDir, hookFile), HookSchema2);
141616
141934
  if (hook == null ? void 0 : hook.token) {
@@ -141676,6 +141994,7 @@ function createWorld$2(args) {
141676
141994
  await rm(mergedConfig.dataDir, { recursive: true, force: true });
141677
141995
  await initDataDir(mergedConfig.dataDir);
141678
141996
  }
141997
+ clearStreamerCache();
141679
141998
  }
141680
141999
  };
141681
142000
  }
@@ -141797,8 +142116,8 @@ function requireGetVercelOidcToken() {
141797
142116
  }
141798
142117
  try {
141799
142118
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
141800
- await import("./token-util-BIJWXlXW.js").then((n) => n.t),
141801
- await import("./token-zIvY_X5M.js").then((n) => n.t)
142119
+ await import("./token-util-DCNDhnc8.js").then((n) => n.t),
142120
+ await import("./token-C7Y4VFl0.js").then((n) => n.t)
141802
142121
  ]);
141803
142122
  if (!token || isExpired(getTokenPayload(token), options == null ? void 0 : options.expirationBufferMs)) {
141804
142123
  await refreshToken(options);
@@ -142361,7 +142680,7 @@ function requireDist() {
142361
142680
  return dist;
142362
142681
  }
142363
142682
  var distExports = requireDist();
142364
- const version = "5.2.0";
142683
+ const version = "5.2.2";
142365
142684
  const pools = globalSingleton("@workflow/world-vercel//httpPools", 1, () => ({
142366
142685
  dispatcher: void 0,
142367
142686
  queueDispatcher: void 0,
@@ -142495,9 +142814,10 @@ const EVENTS_RETRY_AGENT_OPTIONS = {
142495
142814
  ]
142496
142815
  };
142497
142816
  const STREAM_RETRY_OPTIONS = {
142498
- retryAfter: true,
142817
+ maxRetries: 0,
142499
142818
  methods: ["PUT"],
142500
- statusCodes: [429]
142819
+ statusCodes: [],
142820
+ errorCodes: []
142501
142821
  };
142502
142822
  const STREAM_CLOSE_RETRY_OPTIONS = {
142503
142823
  retryAfter: true,
@@ -142721,6 +143041,304 @@ function getDefaultStreamCloseDispatcher() {
142721
143041
  pools.streamCloseDispatcher ?? (pools.streamCloseDispatcher = createStreamDispatcher(STREAM_CLOSE_RETRY_OPTIONS));
142722
143042
  return pools.streamCloseDispatcher;
142723
143043
  }
143044
+ async function getDeadline() {
143045
+ const { getDeadline: getDeadline2 } = await import("./index-CI1MEtXX.js").then((n) => n.i);
143046
+ return getDeadline2();
143047
+ }
143048
+ class ReplayEventObserverError extends Error {
143049
+ constructor(error2) {
143050
+ super("Replay event observer failed", { cause: error2 });
143051
+ __publicField(this, "error");
143052
+ this.error = error2;
143053
+ this.name = "ReplayEventObserverError";
143054
+ }
143055
+ }
143056
+ class AfterCommitError extends Error {
143057
+ constructor(error2) {
143058
+ super("Event log read after a committed write failed", { cause: error2 });
143059
+ __publicField(this, "error");
143060
+ this.error = error2;
143061
+ this.name = "AfterCommitError";
143062
+ }
143063
+ }
143064
+ const STEP_OUTCOME_EVENT_TYPES = /* @__PURE__ */ new Set([
143065
+ "step_completed",
143066
+ "step_retrying"
143067
+ ]);
143068
+ function recordsStepOutcome(eventType) {
143069
+ return STEP_OUTCOME_EVENT_TYPES.has(eventType);
143070
+ }
143071
+ const EVENT_RETRY_ELIGIBILITY = {
143072
+ // Creates: conditional create → 409 EntityConflictError if it already exists.
143073
+ run_created: {
143074
+ retryable: true,
143075
+ reason: "conditional create → 409 if exists"
143076
+ },
143077
+ step_created: {
143078
+ retryable: true,
143079
+ reason: "conditional create → 409 if exists"
143080
+ },
143081
+ wait_created: {
143082
+ retryable: true,
143083
+ reason: "conditional create → 409 if exists"
143084
+ },
143085
+ hook_created: {
143086
+ retryable: true,
143087
+ reason: "transactional token uniqueness → 409 if exists"
143088
+ },
143089
+ // Run start: early-returns if already running, writes no duplicate row.
143090
+ run_started: {
143091
+ retryable: true,
143092
+ reason: "early-returns if already running, no duplicate row"
143093
+ },
143094
+ // Terminal transitions: conditional `.where()` excludes terminal states →
143095
+ // 409 before the event row is written.
143096
+ run_completed: {
143097
+ retryable: true,
143098
+ reason: "terminal-state guard → 409, no duplicate row"
143099
+ },
143100
+ run_failed: {
143101
+ retryable: true,
143102
+ reason: "terminal-state guard → 409, no duplicate row"
143103
+ },
143104
+ run_cancelled: {
143105
+ retryable: true,
143106
+ reason: "terminal-state guard → 409, no duplicate row"
143107
+ },
143108
+ step_completed: {
143109
+ retryable: true,
143110
+ reason: "terminal-state guard → 409, no duplicate row"
143111
+ },
143112
+ step_failed: {
143113
+ retryable: true,
143114
+ reason: "terminal-state guard → 409, no duplicate row"
143115
+ },
143116
+ wait_completed: {
143117
+ retryable: true,
143118
+ reason: "waiting-state guard → 409, no duplicate row"
143119
+ },
143120
+ hook_disposed: {
143121
+ retryable: true,
143122
+ reason: "conditional delete (exists) → 409, no duplicate row"
143123
+ },
143124
+ // True idempotency via a correlationId constraint that reuses the eventId.
143125
+ attr_set: {
143126
+ retryable: true,
143127
+ reason: "correlationId constraint reuses eventId (idempotent replay)"
143128
+ },
143129
+ // NOT safe to retry; see the module comment.
143130
+ step_started: {
143131
+ retryable: false,
143132
+ reason: "unconditional attempt increment → a retry double-counts attempts"
143133
+ },
143134
+ step_retrying: {
143135
+ retryable: false,
143136
+ reason: "no duplicate guard → a retry appends a second event row"
143137
+ },
143138
+ hook_received: {
143139
+ retryable: false,
143140
+ reason: "no server guard → a retry duplicates the row / re-delivers payload. EXCEPTION: the atomic lazy-resume shape (resumeId + digest) is deduplicated server-side by the (runId, resumeId) claim, so those writes opt in via withEventPostRetry({ idempotentHookResume })"
143141
+ },
143142
+ // Server-originated; the SDK never POSTs it.
143143
+ hook_conflict: {
143144
+ retryable: false,
143145
+ reason: "server-originated; never POSTed by the SDK"
143146
+ },
143147
+ // Server-originated sealed-log filler (specVersion 7); the SDK never
143148
+ // POSTs it. The server's read path writes it to seal an abandoned slot.
143149
+ noop: {
143150
+ retryable: false,
143151
+ reason: "server-originated; never POSTed by the SDK"
143152
+ }
143153
+ };
143154
+ const MAX_EVENT_POST_RETRIES = 2;
143155
+ const THROTTLE_RETRY_BUDGET_MS = 3e4;
143156
+ const THROTTLE_DEADLINE_RESERVE_MS = 15e3;
143157
+ const THROTTLE_RETRY_MAX_BUDGET_MS = 15 * 6e4;
143158
+ const DEFAULT_THROTTLE_RETRY_AFTER_SECONDS = 1;
143159
+ const EVENT_POST_RETRY_BASE_MS = 100;
143160
+ const EVENT_POST_RETRY_JITTER_MS = 50;
143161
+ const TRANSIENT_CODES = /* @__PURE__ */ new Set([
143162
+ "ECONNRESET",
143163
+ "ECONNREFUSED",
143164
+ "ENOTFOUND",
143165
+ "ENETDOWN",
143166
+ "ENETUNREACH",
143167
+ "EHOSTDOWN",
143168
+ "EHOSTUNREACH",
143169
+ "EPIPE",
143170
+ "ETIMEDOUT",
143171
+ "UND_ERR_SOCKET",
143172
+ "UND_ERR_REQ_RETRY",
143173
+ "UND_ERR_CONNECT_TIMEOUT",
143174
+ "UND_ERR_HEADERS_TIMEOUT",
143175
+ "UND_ERR_BODY_TIMEOUT",
143176
+ // Names (undici/Node surface these on the error or its cause).
143177
+ // `TimeoutError` is our own per-request deadline (`AbortSignal.timeout` in
143178
+ // makeRequest), a genuinely ambiguous failure worth retrying. We deliberately
143179
+ // do NOT include `AbortError`: that is how an external/caller-supplied
143180
+ // cancellation surfaces (makeRequest composes the caller's signal via
143181
+ // `AbortSignal.any`), and re-issuing a write the caller asked to cancel
143182
+ // (stalling the abort by the full backoff budget) would be wrong.
143183
+ "TimeoutError",
143184
+ "RequestRetryError"
143185
+ ]);
143186
+ function collectErrorMarkers(err, depth = 0) {
143187
+ if (depth > 5 || err === null || typeof err !== "object")
143188
+ return [];
143189
+ const markers = [];
143190
+ const e = err;
143191
+ if (typeof e.code === "string")
143192
+ markers.push(e.code);
143193
+ if (typeof e.name === "string")
143194
+ markers.push(e.name);
143195
+ if (e.cause)
143196
+ markers.push(...collectErrorMarkers(e.cause, depth + 1));
143197
+ return markers;
143198
+ }
143199
+ function isRetryableEventPostError(err) {
143200
+ if (err instanceof ReplayEventObserverError)
143201
+ return false;
143202
+ if (EntityConflictError.is(err) || // A takeover redirect is definitive for THIS target; the runtime's
143203
+ // resume path follows the token instead of re-issuing the write here.
143204
+ HookForceClaimedError.is(err) || RunExpiredError.is(err) || TooEarlyError.is(err) || ThrottleError.is(err)) {
143205
+ return false;
143206
+ }
143207
+ if (WorkflowWorldError.is(err) || StreamError.is(err)) {
143208
+ if (err.code === "PARSE_ERROR")
143209
+ return true;
143210
+ if (err.code === "TRANSPORT")
143211
+ return true;
143212
+ if (typeof err.status === "number") {
143213
+ return err.status >= 500 && err.status <= 599;
143214
+ }
143215
+ if (err.code === "STREAM_ERROR") {
143216
+ return !collectErrorMarkers(err).some((marker) => [
143217
+ "AbortError",
143218
+ "ABORT_ERR",
143219
+ "UND_ERR_ABORTED",
143220
+ "ERR_HTTP2_STREAM_CANCEL"
143221
+ ].includes(marker));
143222
+ }
143223
+ }
143224
+ return collectErrorMarkers(err).some((m2) => TRANSIENT_CODES.has(m2));
143225
+ }
143226
+ const sleep$1 = (ms2, signal) => new Promise((resolve2, reject) => {
143227
+ if (signal == null ? void 0 : signal.aborted) {
143228
+ reject(signal.reason);
143229
+ return;
143230
+ }
143231
+ const onAbort = () => {
143232
+ clearTimeout(timer2);
143233
+ reject(signal == null ? void 0 : signal.reason);
143234
+ };
143235
+ const timer2 = setTimeout(() => {
143236
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
143237
+ resolve2();
143238
+ }, ms2);
143239
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
143240
+ });
143241
+ const RETRY_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
143242
+ function logRetry(message2, fields) {
143243
+ if (!RETRY_DEBUG_ENABLED)
143244
+ return;
143245
+ const suffix = Object.entries(fields).map(([k2, v2]) => `${k2}=${v2}`).join(" ");
143246
+ console.debug(`[workflow:world-vercel:event-retry] ${message2} ${suffix}`);
143247
+ }
143248
+ function errorMarker(err) {
143249
+ if (WorkflowWorldError.is(err)) {
143250
+ return err.code ?? (err.status != null ? `status_${err.status}` : err.name);
143251
+ }
143252
+ return collectErrorMarkers(err)[0] ?? (err instanceof Error ? err.name : "unknown");
143253
+ }
143254
+ async function resolveDeadlineMs() {
143255
+ try {
143256
+ const deadline = await getDeadline();
143257
+ const ms2 = deadline == null ? void 0 : deadline.getTime();
143258
+ return ms2 !== void 0 && Number.isFinite(ms2) ? ms2 : void 0;
143259
+ } catch {
143260
+ return void 0;
143261
+ }
143262
+ }
143263
+ function createThrottleWaiter(target2, budget, beforeWait) {
143264
+ let waitedMs = 0;
143265
+ let limit;
143266
+ return async (err, signal) => {
143267
+ const waitMs = Math.max(1, typeof err.retryAfter === "number" ? err.retryAfter : DEFAULT_THROTTLE_RETRY_AFTER_SECONDS) * 1e3;
143268
+ if (limit === void 0) {
143269
+ const deadlineMs = await resolveDeadlineMs();
143270
+ limit = {
143271
+ budgetMs: budget === "invocation" && deadlineMs !== void 0 ? THROTTLE_RETRY_MAX_BUDGET_MS : THROTTLE_RETRY_BUDGET_MS,
143272
+ deadlineMs
143273
+ };
143274
+ }
143275
+ const outlastsInvocation = limit.deadlineMs !== void 0 && Date.now() + waitMs > limit.deadlineMs - THROTTLE_DEADLINE_RESERVE_MS;
143276
+ if (waitedMs + waitMs > limit.budgetMs || outlastsInvocation) {
143277
+ logRetry("throttle retry budget exhausted; surfacing to the queue", {
143278
+ target: target2,
143279
+ budget,
143280
+ waitedMs,
143281
+ retryAfter: err.retryAfter,
143282
+ outlastsInvocation
143283
+ });
143284
+ throw err;
143285
+ }
143286
+ waitedMs += waitMs;
143287
+ console.warn(`[workflow] Throttled (429) ${target2}; retrying in-process in ${waitMs / 1e3}s`);
143288
+ await (beforeWait == null ? void 0 : beforeWait());
143289
+ await sleep$1(waitMs, signal);
143290
+ };
143291
+ }
143292
+ function throttleBudgetFor(eventType, options) {
143293
+ if ((options == null ? void 0 : options.batchIdempotent) !== void 0)
143294
+ return "bounded";
143295
+ return (options == null ? void 0 : options.afterStepBody) === true || recordsStepOutcome(eventType) ? "invocation" : "bounded";
143296
+ }
143297
+ function isEligibleForTransientRetry(eventType, options) {
143298
+ var _a3;
143299
+ if ((options == null ? void 0 : options.inBand) === true)
143300
+ return false;
143301
+ if ((options == null ? void 0 : options.batchIdempotent) !== void 0) {
143302
+ return options.batchIdempotent;
143303
+ }
143304
+ return eventType === "hook_received" && (options == null ? void 0 : options.idempotentHookResume) === true || (((_a3 = EVENT_RETRY_ELIGIBILITY[eventType]) == null ? void 0 : _a3.retryable) ?? false);
143305
+ }
143306
+ async function withEventPostRetry(fn2, eventType, options) {
143307
+ const retryable = isEligibleForTransientRetry(eventType, options);
143308
+ const waitOutThrottle = createThrottleWaiter(`writing ${eventType} event`, throttleBudgetFor(eventType, options));
143309
+ for (let attempt = 0; ; ) {
143310
+ try {
143311
+ return await fn2();
143312
+ } catch (err) {
143313
+ if (err instanceof AfterCommitError)
143314
+ throw err;
143315
+ if (ThrottleError.is(err)) {
143316
+ await waitOutThrottle(err);
143317
+ continue;
143318
+ }
143319
+ if (!retryable || !isRetryableEventPostError(err)) {
143320
+ throw err;
143321
+ }
143322
+ if (attempt >= MAX_EVENT_POST_RETRIES) {
143323
+ logRetry("exhausted in-process retries; surfacing for queue redelivery", {
143324
+ eventType,
143325
+ attempts: attempt + 1,
143326
+ error: errorMarker(err)
143327
+ });
143328
+ throw err;
143329
+ }
143330
+ const backoff = EVENT_POST_RETRY_BASE_MS * 2 ** attempt + Math.floor(Math.random() * EVENT_POST_RETRY_JITTER_MS);
143331
+ attempt++;
143332
+ logRetry("retrying event POST after transient failure", {
143333
+ eventType,
143334
+ attempt,
143335
+ backoffMs: backoff,
143336
+ error: errorMarker(err)
143337
+ });
143338
+ await sleep$1(backoff);
143339
+ }
143340
+ }
143341
+ }
142724
143342
  const otel = globalSingleton("@workflow/world-vercel//telemetry", 1, () => ({
142725
143343
  // Lazy load OpenTelemetry API to make it optional
142726
143344
  apiPromise: null,
@@ -142742,7 +143360,7 @@ function workflowDebugEnabled() {
142742
143360
  }
142743
143361
  let otelDiagLogged = false;
142744
143362
  function logOtelDiagnosticOnce(otel2, tracer) {
142745
- var _a3, _b2, _c2, _d2, _e2;
143363
+ var _a3, _b2, _c2, _d2, _e3;
142746
143364
  if (otelDiagLogged || !workflowDebugEnabled())
142747
143365
  return;
142748
143366
  otelDiagLogged = true;
@@ -142756,7 +143374,7 @@ function logOtelDiagnosticOnce(otel2, tracer) {
142756
143374
  providerCtor: ((_b2 = provider == null ? void 0 : provider.constructor) == null ? void 0 : _b2.name) ?? null,
142757
143375
  delegateCtor: ((_c2 = delegate == null ? void 0 : delegate.constructor) == null ? void 0 : _c2.name) ?? null,
142758
143376
  tracerCtor: ((_d2 = tracer == null ? void 0 : tracer.constructor) == null ? void 0 : _d2.name) ?? null,
142759
- probeCtor: ((_e2 = probe == null ? void 0 : probe.constructor) == null ? void 0 : _e2.name) ?? null,
143377
+ probeCtor: ((_e3 = probe == null ? void 0 : probe.constructor) == null ? void 0 : _e3.name) ?? null,
142760
143378
  probeRecording: probe.isRecording()
142761
143379
  }));
142762
143380
  probe.end();
@@ -142842,6 +143460,9 @@ const WorkflowStreamStartIndex = SemanticConvention("workflow.stream.start_index
142842
143460
  const WorkflowEventsTransport = SemanticConvention("workflow.events.transport");
142843
143461
  const WorkflowHttpTransport = SemanticConvention("workflow.http.transport");
142844
143462
  const WorkflowEventType = SemanticConvention("workflow.event.type");
143463
+ const WorkflowEventInBand = SemanticConvention("workflow.event.in_band");
143464
+ const WorkflowEventExpectedSeqInBand = SemanticConvention("workflow.event.expected_seq_in_band");
143465
+ const WorkflowEventSeqInBand = SemanticConvention("workflow.event.seq_in_band");
142845
143466
  const WorkflowStepStartMode = SemanticConvention("workflow.step_start.mode");
142846
143467
  const WorkflowStepStartOwnerStamped = SemanticConvention("workflow.step_start.owner_stamped");
142847
143468
  const WorkflowClientVersion = SemanticConvention("workflow.client.version");
@@ -142964,7 +143585,10 @@ function parseRetryAfter(value) {
142964
143585
  if (!value)
142965
143586
  return void 0;
142966
143587
  const parsed = parseInt(value, 10);
142967
- return Number.isNaN(parsed) ? void 0 : parsed;
143588
+ if (!Number.isNaN(parsed))
143589
+ return parsed;
143590
+ const date2 = Date.parse(value);
143591
+ return Number.isNaN(date2) ? void 0 : Math.max(0, (date2 - Date.now()) / 1e3);
142968
143592
  }
142969
143593
  function headersToRecord$1(headers2) {
142970
143594
  const out = {};
@@ -142973,6 +143597,14 @@ function headersToRecord$1(headers2) {
142973
143597
  });
142974
143598
  return out;
142975
143599
  }
143600
+ function recordInBandRefusal(span, error2) {
143601
+ if (InBandSupersededError.is(error2) && error2.seqInBand !== void 0) {
143602
+ span == null ? void 0 : span.setAttributes(WorkflowEventSeqInBand(error2.seqInBand));
143603
+ }
143604
+ }
143605
+ function inBandCounter(value) {
143606
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
143607
+ }
142976
143608
  function errorForResponse(status, message2, opts = {}) {
142977
143609
  const { retryAfter, code: code2, url, mitigated, details } = opts;
142978
143610
  if (status === 409 && code2 === "hook-force-claimed") {
@@ -142989,6 +143621,13 @@ function errorForResponse(status, message2, opts = {}) {
142989
143621
  }
142990
143622
  return new RunExpiredError(message2);
142991
143623
  }
143624
+ if (status === 412 && code2 === IN_BAND_SUPERSEDED_CODE) {
143625
+ const counters = details && typeof details === "object" ? details : void 0;
143626
+ return new InBandSupersededError(message2, {
143627
+ seq: inBandCounter(counters == null ? void 0 : counters.seq),
143628
+ seqInBand: inBandCounter(counters == null ? void 0 : counters.seqInBand)
143629
+ });
143630
+ }
142992
143631
  if (status === 412)
142993
143632
  return new PreconditionFailedError(message2, { retryAfter, details });
142994
143633
  if (status === 425)
@@ -143061,16 +143700,56 @@ function recordClientSpanStatus(span, status) {
143061
143700
  span == null ? void 0 : span.setAttributes({ ...ErrorType(`HTTP ${status}`) });
143062
143701
  }
143063
143702
  }
143703
+ const STREAM_APPEND_MAX_RETRIES = 5;
143704
+ const STREAM_APPEND_CONNECT_ERROR_CODES = /* @__PURE__ */ new Set([
143705
+ "ECONNREFUSED",
143706
+ "ENOTFOUND",
143707
+ "EAI_AGAIN",
143708
+ "UND_ERR_CONNECT_TIMEOUT"
143709
+ ]);
143710
+ async function fetchStreamAppend(request2, signal) {
143711
+ let response2;
143712
+ const waitOutThrottle = createThrottleWaiter("appending stream chunks", "bounded", async () => {
143713
+ var _a3;
143714
+ await ((_a3 = response2.body) == null ? void 0 : _a3.cancel().catch(() => {
143715
+ }));
143716
+ });
143717
+ for (let retry2 = 0; ; retry2++) {
143718
+ try {
143719
+ response2 = await request2(retry2);
143720
+ } catch (error2) {
143721
+ const code2 = getTransientTransportCode(error2);
143722
+ if (retry2 === STREAM_APPEND_MAX_RETRIES || !code2 || !STREAM_APPEND_CONNECT_ERROR_CODES.has(code2)) {
143723
+ throw error2;
143724
+ }
143725
+ await sleep$1(500 * 2 ** retry2, signal);
143726
+ continue;
143727
+ }
143728
+ if (response2.status !== 429 || isFirewallChallenge429(response2.status, response2.headers.get("x-vercel-mitigated")) || retry2 === STREAM_APPEND_MAX_RETRIES) {
143729
+ return response2;
143730
+ }
143731
+ const throttle = {
143732
+ retryAfter: parseRetryAfter(response2.headers.get("Retry-After"))
143733
+ };
143734
+ try {
143735
+ await waitOutThrottle(throttle, signal);
143736
+ } catch (error2) {
143737
+ if (error2 === throttle)
143738
+ return response2;
143739
+ throw error2;
143740
+ }
143741
+ }
143742
+ }
143064
143743
  async function instrumentedFetch(opts) {
143065
- const { method, url, headers: headers2, body: body2, dispatcher: dispatcher2, peerService, timeoutMs = getRequestTimeoutMs(), signal: callerSignal, injectTraceContext: injectTraceContext2 = true, cacheBust = true, logLabel, buildError, spanName, attributes, durationAttribute, onTransportOutcome, deferTransportSuccessUntilBody = false, onRequestDispatched, transportErrorCode = "TRANSPORT" } = opts;
143744
+ const { method, url, headers: headers2, body: body2, dispatcher: dispatcher2, peerService, timeoutMs = getRequestTimeoutMs(), signal: callerSignal, retryStreamAppend = false, injectTraceContext: injectTraceContext2 = true, cacheBust = true, logLabel, buildError, spanName, attributes, durationAttribute, onTransportOutcome, deferTransportSuccessUntilBody = false, onRequestDispatched, transportErrorCode = "TRANSPORT" } = opts;
143066
143745
  const label = logLabel ?? url;
143067
143746
  validateHttpUrl(url);
143747
+ const retryAppend = retryStreamAppend && method === "PUT" && !!dispatcher2;
143748
+ const requestBody = retryAppend && body2 instanceof Uint8Array ? Uint8Array.from(body2) : body2;
143068
143749
  return withHttpClientSpan({ method, url, peerService, spanName, attributes }, async (span) => {
143069
- var _a3, _b2, _c2, _d2, _e2;
143750
+ var _a3, _b2, _c2, _d2, _e3;
143070
143751
  if (injectTraceContext2)
143071
143752
  await injectTraceContextIntoHeaders(headers2);
143072
- if (cacheBust)
143073
- headers2.set("X-Request-Time", Date.now().toString());
143074
143753
  const timeoutSignal = timeoutMs != null ? AbortSignal.timeout(timeoutMs) : void 0;
143075
143754
  const signal = callerSignal && timeoutSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : callerSignal ?? timeoutSignal;
143076
143755
  const nodeAgents = dispatcher2 ? void 0 : getNodeHttpAgents();
@@ -143079,11 +143758,14 @@ async function instrumentedFetch(opts) {
143079
143758
  });
143080
143759
  const start2 = Date.now();
143081
143760
  let response2;
143082
- try {
143083
- const request2 = nodeAgents ? nodeHttpFetch(url, {
143761
+ const request2 = (retry2 = 0) => {
143762
+ signal == null ? void 0 : signal.throwIfAborted();
143763
+ if (cacheBust)
143764
+ headers2.set("X-Request-Time", Date.now().toString());
143765
+ const pending = nodeAgents ? nodeHttpFetch(url, {
143084
143766
  method,
143085
143767
  headers: headers2,
143086
- body: body2,
143768
+ body: requestBody,
143087
143769
  signal,
143088
143770
  agents: nodeAgents,
143089
143771
  // Match undici's per-phase defaults (which the undici agents
@@ -143095,13 +143777,17 @@ async function instrumentedFetch(opts) {
143095
143777
  }) : fetch(url, {
143096
143778
  method,
143097
143779
  headers: headers2,
143098
- body: body2,
143780
+ body: requestBody,
143099
143781
  signal,
143100
143782
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher type doesn't match @types/node's RequestInit
143101
143783
  dispatcher: dispatcher2
143102
143784
  });
143103
- onRequestDispatched == null ? void 0 : onRequestDispatched();
143104
- response2 = await request2;
143785
+ if (retry2 === 0)
143786
+ onRequestDispatched == null ? void 0 : onRequestDispatched();
143787
+ return pending;
143788
+ };
143789
+ try {
143790
+ response2 = await (retryAppend ? fetchStreamAppend(request2, signal) : request2());
143105
143791
  } catch (error2) {
143106
143792
  const elapsed = Date.now() - start2;
143107
143793
  onTransportOutcome == null ? void 0 : onTransportOutcome(error2);
@@ -143164,6 +143850,7 @@ async function instrumentedFetch(opts) {
143164
143850
  throw cause;
143165
143851
  }
143166
143852
  onTransportOutcome == null ? void 0 : onTransportOutcome(void 0, response2);
143853
+ recordInBandRefusal(span, error3);
143167
143854
  (_d2 = span == null ? void 0 : span.recordException) == null ? void 0 : _d2.call(span, error3);
143168
143855
  throw error3;
143169
143856
  }
@@ -143178,7 +143865,7 @@ async function instrumentedFetch(opts) {
143178
143865
  url,
143179
143866
  retryAfter: parseRetryAfter(response2.headers.get("Retry-After"))
143180
143867
  });
143181
- (_e2 = span == null ? void 0 : span.recordException) == null ? void 0 : _e2.call(span, error2);
143868
+ (_e3 = span == null ? void 0 : span.recordException) == null ? void 0 : _e3.call(span, error2);
143182
143869
  throw error2;
143183
143870
  }
143184
143871
  return response2;
@@ -144098,10 +144785,6 @@ function validateRunExecutionContext(value) {
144098
144785
  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\`.`);
144099
144786
  }
144100
144787
  }
144101
- async function getDeadline() {
144102
- const { getDeadline: getDeadline2 } = await import("./index-oHATtR_7.js").then((n) => n.i);
144103
- return getDeadline2();
144104
- }
144105
144788
  const WORKFLOW_SERVER_SERVICE = {
144106
144789
  peerService: "workflow-server",
144107
144790
  rpcSystem: "http",
@@ -149739,297 +150422,6 @@ function createResolveLatestDeploymentId(config2) {
149739
150422
  return result.data.id;
149740
150423
  };
149741
150424
  }
149742
- class ReplayEventObserverError extends Error {
149743
- constructor(error2) {
149744
- super("Replay event observer failed", { cause: error2 });
149745
- __publicField(this, "error");
149746
- this.error = error2;
149747
- this.name = "ReplayEventObserverError";
149748
- }
149749
- }
149750
- class AfterCommitError extends Error {
149751
- constructor(error2) {
149752
- super("Event log read after a committed write failed", { cause: error2 });
149753
- __publicField(this, "error");
149754
- this.error = error2;
149755
- this.name = "AfterCommitError";
149756
- }
149757
- }
149758
- const STEP_OUTCOME_EVENT_TYPES = /* @__PURE__ */ new Set([
149759
- "step_completed",
149760
- "step_retrying"
149761
- ]);
149762
- function recordsStepOutcome(eventType) {
149763
- return STEP_OUTCOME_EVENT_TYPES.has(eventType);
149764
- }
149765
- const EVENT_RETRY_ELIGIBILITY = {
149766
- // Creates: conditional create → 409 EntityConflictError if it already exists.
149767
- run_created: {
149768
- retryable: true,
149769
- reason: "conditional create → 409 if exists"
149770
- },
149771
- step_created: {
149772
- retryable: true,
149773
- reason: "conditional create → 409 if exists"
149774
- },
149775
- wait_created: {
149776
- retryable: true,
149777
- reason: "conditional create → 409 if exists"
149778
- },
149779
- hook_created: {
149780
- retryable: true,
149781
- reason: "transactional token uniqueness → 409 if exists"
149782
- },
149783
- // Run start: early-returns if already running, writes no duplicate row.
149784
- run_started: {
149785
- retryable: true,
149786
- reason: "early-returns if already running, no duplicate row"
149787
- },
149788
- // Terminal transitions: conditional `.where()` excludes terminal states →
149789
- // 409 before the event row is written.
149790
- run_completed: {
149791
- retryable: true,
149792
- reason: "terminal-state guard → 409, no duplicate row"
149793
- },
149794
- run_failed: {
149795
- retryable: true,
149796
- reason: "terminal-state guard → 409, no duplicate row"
149797
- },
149798
- run_cancelled: {
149799
- retryable: true,
149800
- reason: "terminal-state guard → 409, no duplicate row"
149801
- },
149802
- step_completed: {
149803
- retryable: true,
149804
- reason: "terminal-state guard → 409, no duplicate row"
149805
- },
149806
- step_failed: {
149807
- retryable: true,
149808
- reason: "terminal-state guard → 409, no duplicate row"
149809
- },
149810
- wait_completed: {
149811
- retryable: true,
149812
- reason: "waiting-state guard → 409, no duplicate row"
149813
- },
149814
- hook_disposed: {
149815
- retryable: true,
149816
- reason: "conditional delete (exists) → 409, no duplicate row"
149817
- },
149818
- // True idempotency via a correlationId constraint that reuses the eventId.
149819
- attr_set: {
149820
- retryable: true,
149821
- reason: "correlationId constraint reuses eventId (idempotent replay)"
149822
- },
149823
- // NOT safe to retry; see the module comment.
149824
- step_started: {
149825
- retryable: false,
149826
- reason: "unconditional attempt increment → a retry double-counts attempts"
149827
- },
149828
- step_retrying: {
149829
- retryable: false,
149830
- reason: "no duplicate guard → a retry appends a second event row"
149831
- },
149832
- hook_received: {
149833
- retryable: false,
149834
- reason: "no server guard → a retry duplicates the row / re-delivers payload. EXCEPTION: the atomic lazy-resume shape (resumeId + digest) is deduplicated server-side by the (runId, resumeId) claim, so those writes opt in via withEventPostRetry({ idempotentHookResume })"
149835
- },
149836
- // Server-originated; the SDK never POSTs it.
149837
- hook_conflict: {
149838
- retryable: false,
149839
- reason: "server-originated; never POSTed by the SDK"
149840
- },
149841
- // Server-originated sealed-log filler (specVersion 7); the SDK never
149842
- // POSTs it. The server's read path writes it to seal an abandoned slot.
149843
- noop: {
149844
- retryable: false,
149845
- reason: "server-originated; never POSTed by the SDK"
149846
- }
149847
- };
149848
- const MAX_EVENT_POST_RETRIES = 2;
149849
- const THROTTLE_RETRY_BUDGET_MS = 3e4;
149850
- const THROTTLE_DEADLINE_RESERVE_MS = 15e3;
149851
- const THROTTLE_RETRY_MAX_BUDGET_MS = 15 * 6e4;
149852
- const DEFAULT_THROTTLE_RETRY_AFTER_SECONDS = 1;
149853
- const EVENT_POST_RETRY_BASE_MS = 100;
149854
- const EVENT_POST_RETRY_JITTER_MS = 50;
149855
- const TRANSIENT_CODES = /* @__PURE__ */ new Set([
149856
- "ECONNRESET",
149857
- "ECONNREFUSED",
149858
- "ENOTFOUND",
149859
- "ENETDOWN",
149860
- "ENETUNREACH",
149861
- "EHOSTDOWN",
149862
- "EHOSTUNREACH",
149863
- "EPIPE",
149864
- "ETIMEDOUT",
149865
- "UND_ERR_SOCKET",
149866
- "UND_ERR_REQ_RETRY",
149867
- "UND_ERR_CONNECT_TIMEOUT",
149868
- "UND_ERR_HEADERS_TIMEOUT",
149869
- "UND_ERR_BODY_TIMEOUT",
149870
- // Names (undici/Node surface these on the error or its cause).
149871
- // `TimeoutError` is our own per-request deadline (`AbortSignal.timeout` in
149872
- // makeRequest), a genuinely ambiguous failure worth retrying. We deliberately
149873
- // do NOT include `AbortError`: that is how an external/caller-supplied
149874
- // cancellation surfaces (makeRequest composes the caller's signal via
149875
- // `AbortSignal.any`), and re-issuing a write the caller asked to cancel
149876
- // (stalling the abort by the full backoff budget) would be wrong.
149877
- "TimeoutError",
149878
- "RequestRetryError"
149879
- ]);
149880
- function collectErrorMarkers(err, depth = 0) {
149881
- if (depth > 5 || err === null || typeof err !== "object")
149882
- return [];
149883
- const markers = [];
149884
- const e = err;
149885
- if (typeof e.code === "string")
149886
- markers.push(e.code);
149887
- if (typeof e.name === "string")
149888
- markers.push(e.name);
149889
- if (e.cause)
149890
- markers.push(...collectErrorMarkers(e.cause, depth + 1));
149891
- return markers;
149892
- }
149893
- function isRetryableEventPostError(err) {
149894
- if (err instanceof ReplayEventObserverError)
149895
- return false;
149896
- if (EntityConflictError.is(err) || // A takeover redirect is definitive for THIS target; the runtime's
149897
- // resume path follows the token instead of re-issuing the write here.
149898
- HookForceClaimedError.is(err) || RunExpiredError.is(err) || TooEarlyError.is(err) || ThrottleError.is(err)) {
149899
- return false;
149900
- }
149901
- if (WorkflowWorldError.is(err) || StreamError.is(err)) {
149902
- if (err.code === "PARSE_ERROR")
149903
- return true;
149904
- if (err.code === "TRANSPORT")
149905
- return true;
149906
- if (typeof err.status === "number") {
149907
- return err.status >= 500 && err.status <= 599;
149908
- }
149909
- if (err.code === "STREAM_ERROR") {
149910
- return !collectErrorMarkers(err).some((marker) => [
149911
- "AbortError",
149912
- "ABORT_ERR",
149913
- "UND_ERR_ABORTED",
149914
- "ERR_HTTP2_STREAM_CANCEL"
149915
- ].includes(marker));
149916
- }
149917
- }
149918
- return collectErrorMarkers(err).some((m2) => TRANSIENT_CODES.has(m2));
149919
- }
149920
- const sleep$1 = (ms2, signal) => new Promise((resolve2, reject) => {
149921
- if (signal == null ? void 0 : signal.aborted) {
149922
- reject(signal.reason);
149923
- return;
149924
- }
149925
- const onAbort = () => {
149926
- clearTimeout(timer2);
149927
- reject(signal == null ? void 0 : signal.reason);
149928
- };
149929
- const timer2 = setTimeout(() => {
149930
- signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
149931
- resolve2();
149932
- }, ms2);
149933
- signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
149934
- });
149935
- const RETRY_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
149936
- function logRetry(message2, fields) {
149937
- if (!RETRY_DEBUG_ENABLED)
149938
- return;
149939
- const suffix = Object.entries(fields).map(([k2, v2]) => `${k2}=${v2}`).join(" ");
149940
- console.debug(`[workflow:world-vercel:event-retry] ${message2} ${suffix}`);
149941
- }
149942
- function errorMarker(err) {
149943
- if (WorkflowWorldError.is(err)) {
149944
- return err.code ?? (err.status != null ? `status_${err.status}` : err.name);
149945
- }
149946
- return collectErrorMarkers(err)[0] ?? (err instanceof Error ? err.name : "unknown");
149947
- }
149948
- async function resolveDeadlineMs() {
149949
- try {
149950
- const deadline = await getDeadline();
149951
- const ms2 = deadline == null ? void 0 : deadline.getTime();
149952
- return ms2 !== void 0 && Number.isFinite(ms2) ? ms2 : void 0;
149953
- } catch {
149954
- return void 0;
149955
- }
149956
- }
149957
- function createThrottleWaiter(target2, budget) {
149958
- let waitedMs = 0;
149959
- let limit;
149960
- return async (err, signal) => {
149961
- const waitMs = Math.max(1, typeof err.retryAfter === "number" ? err.retryAfter : DEFAULT_THROTTLE_RETRY_AFTER_SECONDS) * 1e3;
149962
- if (limit === void 0) {
149963
- const deadlineMs = await resolveDeadlineMs();
149964
- limit = {
149965
- budgetMs: budget === "invocation" && deadlineMs !== void 0 ? THROTTLE_RETRY_MAX_BUDGET_MS : THROTTLE_RETRY_BUDGET_MS,
149966
- deadlineMs
149967
- };
149968
- }
149969
- const outlastsInvocation = limit.deadlineMs !== void 0 && Date.now() + waitMs > limit.deadlineMs - THROTTLE_DEADLINE_RESERVE_MS;
149970
- if (waitedMs + waitMs > limit.budgetMs || outlastsInvocation) {
149971
- logRetry("throttle retry budget exhausted; surfacing to the queue", {
149972
- target: target2,
149973
- budget,
149974
- waitedMs,
149975
- retryAfter: err.retryAfter,
149976
- outlastsInvocation
149977
- });
149978
- throw err;
149979
- }
149980
- waitedMs += waitMs;
149981
- console.warn(`[workflow] Throttled (429) ${target2}; retrying in-process in ${waitMs / 1e3}s`);
149982
- await sleep$1(waitMs, signal);
149983
- };
149984
- }
149985
- function throttleBudgetFor(eventType, options) {
149986
- if ((options == null ? void 0 : options.batchIdempotent) !== void 0)
149987
- return "bounded";
149988
- return (options == null ? void 0 : options.afterStepBody) === true || recordsStepOutcome(eventType) ? "invocation" : "bounded";
149989
- }
149990
- function isEligibleForTransientRetry(eventType, options) {
149991
- var _a3;
149992
- if ((options == null ? void 0 : options.batchIdempotent) !== void 0) {
149993
- return options.batchIdempotent;
149994
- }
149995
- return eventType === "hook_received" && (options == null ? void 0 : options.idempotentHookResume) === true || (((_a3 = EVENT_RETRY_ELIGIBILITY[eventType]) == null ? void 0 : _a3.retryable) ?? false);
149996
- }
149997
- async function withEventPostRetry(fn2, eventType, options) {
149998
- const retryable = isEligibleForTransientRetry(eventType, options);
149999
- const waitOutThrottle = createThrottleWaiter(`writing ${eventType} event`, throttleBudgetFor(eventType, options));
150000
- for (let attempt = 0; ; ) {
150001
- try {
150002
- return await fn2();
150003
- } catch (err) {
150004
- if (err instanceof AfterCommitError)
150005
- throw err;
150006
- if (ThrottleError.is(err)) {
150007
- await waitOutThrottle(err);
150008
- continue;
150009
- }
150010
- if (!retryable || !isRetryableEventPostError(err)) {
150011
- throw err;
150012
- }
150013
- if (attempt >= MAX_EVENT_POST_RETRIES) {
150014
- logRetry("exhausted in-process retries; surfacing for queue redelivery", {
150015
- eventType,
150016
- attempts: attempt + 1,
150017
- error: errorMarker(err)
150018
- });
150019
- throw err;
150020
- }
150021
- const backoff = EVENT_POST_RETRY_BASE_MS * 2 ** attempt + Math.floor(Math.random() * EVENT_POST_RETRY_JITTER_MS);
150022
- attempt++;
150023
- logRetry("retrying event POST after transient failure", {
150024
- eventType,
150025
- attempt,
150026
- backoffMs: backoff,
150027
- error: errorMarker(err)
150028
- });
150029
- await sleep$1(backoff);
150030
- }
150031
- }
150032
- }
150033
150425
  const V4_FRAME_CONTENT_TYPE = "application/vnd.workflow.v4-frames";
150034
150426
  class IncompleteFrameError extends Error {
150035
150427
  }
@@ -150411,7 +150803,14 @@ const CreateEventV4BodyBaseSchema = object$1({
150411
150803
  hook: HookSchema.optional(),
150412
150804
  wait: WaitSchema.optional(),
150413
150805
  stepCreated: literal$1(true).optional(),
150414
- maxEvents: number$3().int().positive().optional()
150806
+ maxEvents: number$3().int().positive().optional(),
150807
+ // Positions the backend allocated for this write, when it reports them
150808
+ // (`EventResult.allocated`): what an in-band writer advances its count by.
150809
+ // Passed on for a single create answered with this body. A batch's item
150810
+ // results reuse this schema, but a batch is one allocation for the whole
150811
+ // block and its count is not passed on, nor is one on the streamed
150812
+ // `run_started` and `hook_received` preload responses.
150813
+ allocated: number$3().int().nonnegative().optional()
150415
150814
  });
150416
150815
  const CreateEventV4PageSchema = union([
150417
150816
  object$1({
@@ -150462,10 +150861,38 @@ const CreateEventV4BodySchemas = {
150462
150861
  noop: CreateEventV4BodySchema
150463
150862
  };
150464
150863
  const MaxEventsHeaderSchema = compile(number$2().int().positive());
150864
+ const EventLogSnapshotWireSchema = compile(object$1({
150865
+ seq: number$3().int().nonnegative(),
150866
+ seqInBand: number$3().int().nonnegative()
150867
+ }).refine(({ seq, seqInBand }) => seqInBand <= seq));
150868
+ const SNAPSHOT_SEQ_HEADER = "x-wf-snapshot-seq";
150869
+ const SNAPSHOT_SEQ_IN_BAND_HEADER = "x-wf-snapshot-seq-in-band";
150870
+ const DECIMAL_COUNTER = /^\d+$/;
150871
+ function snapshotFromHeaders(headers2) {
150872
+ const seq = headers2.get(SNAPSHOT_SEQ_HEADER);
150873
+ const seqInBand = headers2.get(SNAPSHOT_SEQ_IN_BAND_HEADER);
150874
+ if (seq === null || seqInBand === null || !DECIMAL_COUNTER.test(seq) || !DECIMAL_COUNTER.test(seqInBand)) {
150875
+ return void 0;
150876
+ }
150877
+ const parsed = EventLogSnapshotWireSchema.safeParse({
150878
+ seq: Number(seq),
150879
+ seqInBand: Number(seqInBand)
150880
+ });
150881
+ return parsed.success ? parsed.data : void 0;
150882
+ }
150883
+ function snapshotFromEnd(snapshot) {
150884
+ if (snapshot === void 0)
150885
+ return void 0;
150886
+ const parsed = EventLogSnapshotWireSchema.safeParse(snapshot);
150887
+ return parsed.success ? parsed.data : void 0;
150888
+ }
150465
150889
  const EventStreamEndSchema = compile(object$1({
150466
150890
  _end: literal$1(1),
150467
150891
  next: string$2().optional(),
150468
- hasMore: boolean$2()
150892
+ hasMore: boolean$2(),
150893
+ // Read on its own (`snapshotFromEnd`): a malformed snapshot lists none
150894
+ // rather than failing the page.
150895
+ snapshot: unknown$1().optional()
150469
150896
  }));
150470
150897
  const EventStreamErrorSchema = compile(object$1({
150471
150898
  _error: literal$1(1),
@@ -150609,8 +151036,19 @@ function buildPostFrameMeta(input) {
150609
151036
  if (input.viaStepDispatch !== void 0) {
150610
151037
  meta.viaStepDispatch = input.viaStepDispatch;
150611
151038
  }
151039
+ if (input.inBand !== void 0)
151040
+ meta.inBand = input.inBand;
151041
+ if (input.expectedSeqInBand !== void 0) {
151042
+ meta.expectedSeqInBand = input.expectedSeqInBand;
151043
+ }
150612
151044
  return meta;
150613
151045
  }
151046
+ function inBandFenceAttributes(input) {
151047
+ return {
151048
+ ...input.inBand !== void 0 ? WorkflowEventInBand(input.inBand) : {},
151049
+ ...input.expectedSeqInBand !== void 0 ? WorkflowEventExpectedSeqInBand(input.expectedSeqInBand) : {}
151050
+ };
151051
+ }
150614
151052
  function errorFromV4Response(statusCode, responseHeaders, errorBody, opName, url) {
150615
151053
  let message2 = `v4 ${opName} failed: HTTP ${statusCode}`;
150616
151054
  let code2;
@@ -150623,8 +151061,9 @@ function errorFromV4Response(statusCode, responseHeaders, errorBody, opName, url
150623
151061
  code2 = record2.code;
150624
151062
  else if (typeof record2.error === "string")
150625
151063
  code2 = record2.error;
150626
- if (statusCode === 412)
150627
- details = decodePreconditionDetails(record2);
151064
+ if (statusCode === 412) {
151065
+ details = code2 === IN_BAND_SUPERSEDED_CODE ? decodeInBandSupersededDetails(record2) : decodePreconditionDetails(record2);
151066
+ }
150628
151067
  if (statusCode === 409 && code2 === "hook-force-claimed") {
150629
151068
  details = { claimedBy: record2.claimedBy };
150630
151069
  }
@@ -150640,6 +151079,14 @@ function errorFromV4Response(statusCode, responseHeaders, errorBody, opName, url
150640
151079
  ...details !== void 0 ? { details } : {}
150641
151080
  });
150642
151081
  }
151082
+ function decodeInBandSupersededDetails(json) {
151083
+ const seq = inBandCounter(json.seq);
151084
+ const seqInBand = inBandCounter(json.seqInBand);
151085
+ return {
151086
+ ...seq !== void 0 ? { seq } : {},
151087
+ ...seqInBand !== void 0 ? { seqInBand } : {}
151088
+ };
151089
+ }
150643
151090
  function parseV4ErrorBody(body2, contentType) {
150644
151091
  if (typeof body2 !== "string" && (contentType == null ? void 0 : contentType.includes("application/cbor"))) {
150645
151092
  try {
@@ -150711,6 +151158,7 @@ async function postWorkflowRunEventV4(input, responseType, config2) {
150711
151158
  ...WorkflowEventsTransport("http"),
150712
151159
  ...WorkflowEventType(input.eventType),
150713
151160
  ...WorkflowClientVersion(`@workflow/world-vercel/${version}`),
151161
+ ...inBandFenceAttributes(input),
150714
151162
  ...input.eventType === "step_started" ? {
150715
151163
  ...WorkflowStepStartMode(input.payload === void 0 ? input.ownerMessageId !== void 0 ? "single_owned_recovery" : "single_bare" : "single_lazy_create_claim"),
150716
151164
  ...WorkflowStepStartOwnerStamped(input.ownerMessageId !== void 0)
@@ -150827,6 +151275,8 @@ async function createWorkflowRunEventsBatchV4(input, config2) {
150827
151275
  const response2 = await fetchV4(url, { method: "POST", headers: headers2, body: body2 }, config2, "createEventBatch", {
150828
151276
  ...WorkflowEventsTransport("http"),
150829
151277
  "workflow.batch.bytes": body2.byteLength,
151278
+ // Every frame of a batch carries the same fence.
151279
+ ...inBandFenceAttributes(input.events[0]),
150830
151280
  ...input.events.some((event) => event.eventType === "step_started") ? {
150831
151281
  ...WorkflowStepStartMode(input.events.some((event) => event.eventType === "step_created") ? "batch_create_claim" : "batch_bare"),
150832
151282
  ...WorkflowStepStartOwnerStamped(input.events.some((event) => event.ownerMessageId !== void 0))
@@ -150895,6 +151345,7 @@ async function postEventFrameOverWs(input, config2) {
150895
151345
  ...WorkflowEventsTransport("ws"),
150896
151346
  ...WorkflowEventType(input.eventType),
150897
151347
  ...WorkflowClientVersion(`@workflow/world-vercel/${version}`),
151348
+ ...inBandFenceAttributes(input),
150898
151349
  ...input.stso !== void 0 ? StepStsoMs(input.stso) : {},
150899
151350
  ...input.optimizations !== void 0 ? StepLatencyOptimizations(input.optimizations) : {},
150900
151351
  ...input.eventType === "step_started" ? {
@@ -150938,6 +151389,7 @@ async function postEventFrameOverWs(input, config2) {
150938
151389
  recordClientSpanStatus(span, status);
150939
151390
  if (status < 200 || status >= 300) {
150940
151391
  const error2 = errorFromV4Response(status, headerRecord, new TextDecoder().decode(reply.body), "createEvent", endpoint);
151392
+ recordInBandRefusal(span, error2);
150941
151393
  (_b2 = span == null ? void 0 : span.recordException) == null ? void 0 : _b2.call(span, error2);
150942
151394
  throw error2;
150943
151395
  }
@@ -151041,11 +151493,13 @@ async function consumeEventFrameStream(response2, opName, replayEventObserver) {
151041
151493
  for await (const frame2 of decodeFrames(response2.body)) {
151042
151494
  if (frame2.meta._end === 1) {
151043
151495
  const end = EventStreamEndSchema.parse(frame2.meta);
151496
+ const snapshot = snapshotFromEnd(end.snapshot) ?? snapshotFromHeaders(response2.headers);
151044
151497
  return {
151045
151498
  kind: "complete",
151046
151499
  events: events2,
151047
151500
  cursor: end.next ?? null,
151048
- hasMore: end.hasMore
151501
+ hasMore: end.hasMore,
151502
+ ...snapshot ? { snapshot } : {}
151049
151503
  };
151050
151504
  }
151051
151505
  if (frame2.meta._error === 1) {
@@ -151203,7 +151657,10 @@ async function getWorkflowRunEventsV4(runId, params = {}, config2, replayEventOb
151203
151657
  return {
151204
151658
  events: events2,
151205
151659
  cursor: consumed.cursor || (partialStreamRetries > 0 ? cursor : null),
151206
- hasMore: consumed.hasMore
151660
+ hasMore: consumed.hasMore,
151661
+ // Only a complete response reaches its sentinel, and the loop ends on
151662
+ // the first one, so this is the first snapshot the read saw.
151663
+ ...consumed.kind === "complete" && consumed.snapshot ? { snapshot: consumed.snapshot } : {}
151207
151664
  };
151208
151665
  }
151209
151666
  async function getEventsByCorrelationIdV4(correlationId, runId, params = {}, config2) {
@@ -151595,7 +152052,10 @@ async function getWorkflowRunEvents(params, config2) {
151595
152052
  // The cursor is present even on the final page because it is also the
151596
152053
  // incremental-load resume point. `hasMore` is the pagination signal.
151597
152054
  cursor: result.cursor,
151598
- hasMore: result.hasMore
152055
+ hasMore: result.hasMore,
152056
+ // The in-band fence's counters, read before the listing, when the
152057
+ // backend reports them (see `capabilities.inBandFence` in index.ts).
152058
+ ...result.snapshot ? { snapshot: result.snapshot } : {}
151599
152059
  };
151600
152060
  }
151601
152061
  async function createWorkflowRunEventBatch(runId, events2, params, config2) {
@@ -151627,11 +152087,16 @@ async function createWorkflowRunEventBatch(runId, events2, params, config2) {
151627
152087
  // batched usage facts carry the same attribution.
151628
152088
  ...(params == null ? void 0 : params.requestId) ? { vercelId: params.requestId } : {},
151629
152089
  payload,
151630
- ...meta
152090
+ ...meta,
152091
+ // The batch is one fenced allocation: the backend requires every frame
152092
+ // to carry the same fence. Spread after `meta` so nothing derived from
152093
+ // the event data can override it.
152094
+ ...(params == null ? void 0 : params.inBand) !== void 0 ? { inBand: params.inBand } : {},
152095
+ ...(params == null ? void 0 : params.expectedSeqInBand) !== void 0 ? { expectedSeqInBand: params.expectedSeqInBand } : {}
151631
152096
  };
151632
152097
  });
151633
152098
  const retryConvergent = events2.every(({ event }) => event.eventType !== "step_started" && event.eventType !== "step_retrying");
151634
- const wire = await withEventPostRetry(() => createWorkflowRunEventsBatchV4({ runId, events: inputs }, config2), events2[0].event.eventType, { batchIdempotent: retryConvergent });
152099
+ const wire = await withEventPostRetry(() => createWorkflowRunEventsBatchV4({ runId, events: inputs }, config2), events2[0].event.eventType, { batchIdempotent: retryConvergent, inBand: (params == null ? void 0 : params.inBand) === true });
151635
152100
  return {
151636
152101
  results: wire.results.map((item) => {
151637
152102
  if (item.error !== void 0) {
@@ -151659,7 +152124,8 @@ async function createWorkflowRunEvent(id2, data2, params, config2) {
151659
152124
  // (runId, resumeId) claim, so its POST is idempotent-on-retry even
151660
152125
  // though plain hook_received is not; see EVENT_RETRY_ELIGIBILITY.
151661
152126
  idempotentHookResume: data2.eventType === "hook_received" && (params == null ? void 0 : params.resumeId) !== void 0 && (params == null ? void 0 : params.resumePayloadDigest) !== void 0,
151662
- afterStepBody: (params == null ? void 0 : params.afterStepBody) === true
152127
+ afterStepBody: (params == null ? void 0 : params.afterStepBody) === true,
152128
+ inBand: (params == null ? void 0 : params.inBand) === true
151663
152129
  });
151664
152130
  if (data2.eventType === "run_created" && !result.run) {
151665
152131
  throw new WorkflowWorldError(`${data2.eventType} response is missing the run entity`, { code: "SCHEMA_VALIDATION" });
@@ -151738,6 +152204,10 @@ async function createWorkflowRunEventInner(id2, data2, params, config2) {
151738
152204
  // `eventCount`.
151739
152205
  ...(params == null ? void 0 : params.eventCount) !== void 0 ? { maxSlot: params.eventCount } : {},
151740
152206
  replayDivergenceCount: params == null ? void 0 : params.replayDivergenceCount,
152207
+ // In-band writer fence. The backend refuses a stale in-band write with
152208
+ // 412 `in-band-superseded` (InBandSupersededError).
152209
+ ...(params == null ? void 0 : params.inBand) !== void 0 ? { inBand: params.inBand } : {},
152210
+ ...(params == null ? void 0 : params.expectedSeqInBand) !== void 0 ? { expectedSeqInBand: params.expectedSeqInBand } : {},
151741
152211
  occurredAt: (params == null ? void 0 : params.occurredAt) ?? /* @__PURE__ */ new Date(),
151742
152212
  // Opt-in inline-delta: forward the cursor the runtime held before
151743
152213
  // this write so the server can return the authoritative event-log
@@ -152396,7 +152866,7 @@ function beginNormalWsClose(ws, reason) {
152396
152866
  await observed;
152397
152867
  span == null ? void 0 : span.setAttribute("workflow.stream.ws.close_cleanup_timeout", timedOut);
152398
152868
  });
152399
- void import("./index-oHATtR_7.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => waitUntil2(cleanup)).catch(() => {
152869
+ void import("./index-CI1MEtXX.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => waitUntil2(cleanup)).catch(() => {
152400
152870
  });
152401
152871
  void cleanup.catch(() => {
152402
152872
  });
@@ -152781,7 +153251,7 @@ class VercelStreamWriteSession {
152781
153251
  return http3;
152782
153252
  });
152783
153253
  const [{ WebSocket: WebSocketImpl }, http2] = await Promise.all([
152784
- import("./wrapper-DiM8LB2q.js"),
153254
+ import("./wrapper-CA2LUUpa.js"),
152785
153255
  httpPromise
152786
153256
  ]);
152787
153257
  if (this.mode !== "connecting")
@@ -153227,6 +153697,7 @@ async function writeStreamSessionOverHttp(runId, name2, chunks, config2, attribu
153227
153697
  body: encodeMultiChunks(chunks.slice(offset3, offset3 + pageSize)),
153228
153698
  headers: httpConfig.headers,
153229
153699
  dispatcher: getStreamDispatcher(config2),
153700
+ retryStreamAppend: !(config2 == null ? void 0 : config2.dispatcher),
153230
153701
  timeoutMs: null,
153231
153702
  logLabel: url.pathname,
153232
153703
  spanName: "workflow.stream.write",
@@ -153281,6 +153752,7 @@ function createStreamer(config2) {
153281
153752
  body: chunk,
153282
153753
  headers: httpConfig.headers,
153283
153754
  dispatcher: getStreamDispatcher(config2),
153755
+ retryStreamAppend: !(config2 == null ? void 0 : config2.dispatcher),
153284
153756
  timeoutMs: null,
153285
153757
  transportErrorCode: "STREAM_ERROR",
153286
153758
  logLabel: url.pathname,
@@ -153312,6 +153784,7 @@ function createStreamer(config2) {
153312
153784
  body: body2,
153313
153785
  headers: httpConfig.headers,
153314
153786
  dispatcher: getStreamDispatcher(config2),
153787
+ retryStreamAppend: !(config2 == null ? void 0 : config2.dispatcher),
153315
153788
  timeoutMs: null,
153316
153789
  transportErrorCode: "STREAM_ERROR",
153317
153790
  logLabel: url.pathname,
@@ -157642,6 +158115,17 @@ function createWorld$1(config2) {
157642
158115
  // Vercel deployments are atomic and immutable, so a deployment id names
157643
158116
  // one fixed build for its whole lifetime.
157644
158117
  deploymentAffinity: true,
158118
+ // The backend fences in-band writes on every sealed-log run (spec >= 7,
158119
+ // the backend's event sequencer): a stale one is refused with 412
158120
+ // `in-band-superseded`, carrying the run's `seq` and `seqInBand`
158121
+ // (`InBandSupersededError`), and nothing is allocated for it. On an
158122
+ // older run an in-band write is a 400 `in-band-fence-unsupported`,
158123
+ // never an unfenced write, so a client fences by the run's spec
158124
+ // version. A list response carries `snapshot` and a single create
158125
+ // carries `allocated` where the backend reports them (events-v4.ts); a
158126
+ // run whose list carries no snapshot is still fenced, and its refusals
158127
+ // carry the counters.
158128
+ inBandFence: true,
157645
158129
  // The server implements the takeover protocol behind
157646
158130
  // `createHook({ experimental_force: true })` (workflow-server
157647
158131
  // docs/hook-force-claim.md). Static rather than attested per lookup,
@@ -158718,7 +159202,7 @@ async function resumeHookImpl(tokenOrHook, payload, encryptionKeyOverride, hookF
158718
159202
  });
158719
159203
  }
158720
159204
  async function resumeHookAttempt(world, span, tokenOrHook, payload, encryptionKeyOverride, hookFreshlyLookedUp, resumeRequestedAtMs, logicalResumeId, webhookOnly) {
158721
- var _a3, _b2, _c2, _d2, _e2;
159205
+ var _a3, _b2, _c2, _d2, _e3;
158722
159206
  try {
158723
159207
  const suppliedToken = typeof tokenOrHook === "string";
158724
159208
  let hook;
@@ -158870,7 +159354,7 @@ async function resumeHookAttempt(world, span, tokenOrHook, payload, encryptionKe
158870
159354
  // of the messages. Claim-less writes have no resumeId and
158871
159355
  // keep the previous behavior.
158872
159356
  ...resumeId ? { idempotencyKey: `hook-${resumeId}` } : {}
158873
- }), (_e2 = world.isDeploymentUnavailableError) == null ? void 0 : _e2.bind(world));
159357
+ }), (_e3 = world.isDeploymentUnavailableError) == null ? void 0 : _e3.bind(world));
158874
159358
  span == null ? void 0 : span.setAttributes(HookWakePublished(true));
158875
159359
  return asLazyMetadataHook(hook);
158876
159360
  } catch (err) {
@@ -160956,7 +161440,7 @@ var CONTENT_NAME$7 = "PopperContent";
160956
161440
  var [PopperContentProvider, useContentContext] = createPopperContext(CONTENT_NAME$7);
160957
161441
  var PopperContent = reactExports.forwardRef(
160958
161442
  (props, forwardedRef) => {
160959
- var _a3, _b2, _c2, _d2, _e2, _f;
161443
+ var _a3, _b2, _c2, _d2, _e3, _f2;
160960
161444
  const {
160961
161445
  __scopePopper,
160962
161446
  side = "bottom",
@@ -161055,12 +161539,12 @@ var PopperContent = reactExports.forwardRef(
161055
161539
  zIndex: contentZIndex,
161056
161540
  ["--radix-popper-transform-origin"]: [
161057
161541
  (_d2 = middlewareData.transformOrigin) == null ? void 0 : _d2.x,
161058
- (_e2 = middlewareData.transformOrigin) == null ? void 0 : _e2.y
161542
+ (_e3 = middlewareData.transformOrigin) == null ? void 0 : _e3.y
161059
161543
  ].join(" "),
161060
161544
  // hide the content if using the hide middleware and should be hidden
161061
161545
  // set visibility to hidden and disable pointer events so the UI behaves
161062
161546
  // as if the PopperContent isn't there at all
161063
- ...((_f = middlewareData.hide) == null ? void 0 : _f.referenceHidden) && {
161547
+ ...((_f2 = middlewareData.hide) == null ? void 0 : _f2.referenceHidden) && {
161064
161548
  visibility: "hidden",
161065
161549
  pointerEvents: "none"
161066
161550
  }
@@ -178687,7 +179171,7 @@ function getNodeIcon(nodeKind, label) {
178687
179171
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Zap, { className: "h-3.5 w-3.5 text-green-600 dark:text-green-400" });
178688
179172
  }
178689
179173
  function calculateEnhancedLayout(workflow, layoutConfig = LAYOUT$1) {
178690
- var _a3, _b2, _c2, _d2, _e2;
179174
+ var _a3, _b2, _c2, _d2, _e3;
178691
179175
  const nodes = workflow.nodes.map((node2) => ({ ...node2 }));
178692
179176
  const groupNodes = [];
178693
179177
  const additionalEdges = [];
@@ -178766,7 +179250,7 @@ function calculateEnhancedLayout(workflow, layoutConfig = LAYOUT$1) {
178766
179250
  if (thenNodes.length > 0 && elseNodes.length > 0) {
178767
179251
  const baseY = Math.min(
178768
179252
  ((_d2 = thenNodes[0]) == null ? void 0 : _d2.position.y) || 0,
178769
- ((_e2 = elseNodes[0]) == null ? void 0 : _e2.position.y) || 0
179253
+ ((_e3 = elseNodes[0]) == null ? void 0 : _e3.position.y) || 0
178770
179254
  );
178771
179255
  thenNodes.forEach((node2, idx) => {
178772
179256
  node2.position = {
@@ -182177,7 +182661,7 @@ const route4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProper
182177
182661
  __proto__: null,
182178
182662
  loader
182179
182663
  }, Symbol.toStringTag, { value: "Module" }));
182180
- const serverManifest = { "entry": { "module": "/assets/entry.client-GbcnkvKL.js", "imports": ["/assets/index-CRmVVsbP.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-DixDz_si.js", "imports": ["/assets/index-CRmVVsbP.js", "/assets/mermaid-3ZIDBTTL-COEB4Hc6.js", "/assets/loader-circle-BaPqCMKN.js", "/assets/arrow-up-right-ychoyK1y.js"], "css": ["/assets/root-D51qsCcK.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-C3xDSPLC.js", "imports": ["/assets/index-CRmVVsbP.js", "/assets/workflow-graph-viewer-B9ovZj-2.js", "/assets/mermaid-3ZIDBTTL-COEB4Hc6.js", "/assets/loader-circle-BaPqCMKN.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-CEQc0q3W.js", "imports": ["/assets/index-CRmVVsbP.js", "/assets/workflow-graph-viewer-B9ovZj-2.js", "/assets/mermaid-3ZIDBTTL-COEB4Hc6.js", "/assets/arrow-up-right-ychoyK1y.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-4e8be598.js", "version": "4e8be598", "sri": void 0 };
182664
+ const serverManifest = { "entry": { "module": "/assets/entry.client-GbcnkvKL.js", "imports": ["/assets/index-CRmVVsbP.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-D1LRhSwl.js", "imports": ["/assets/index-CRmVVsbP.js", "/assets/mermaid-3ZIDBTTL-C-jkx8xu.js", "/assets/loader-circle-BHf0PB8D.js", "/assets/arrow-up-right-BjmInfWj.js"], "css": ["/assets/root-D51qsCcK.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-Cj8BA1xg.js", "imports": ["/assets/index-CRmVVsbP.js", "/assets/workflow-graph-viewer-BRI-aUt7.js", "/assets/mermaid-3ZIDBTTL-C-jkx8xu.js", "/assets/loader-circle-BHf0PB8D.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-L1jBcQcp.js", "imports": ["/assets/index-CRmVVsbP.js", "/assets/workflow-graph-viewer-BRI-aUt7.js", "/assets/mermaid-3ZIDBTTL-C-jkx8xu.js", "/assets/arrow-up-right-BjmInfWj.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-9875bf74.js", "version": "9875bf74", "sri": void 0 };
182181
182665
  const assetsBuildDirectory = "build/client";
182182
182666
  const basename = "/";
182183
182667
  const future = { "unstable_optimizeDeps": false, "v8_passThroughRequests": false, "v8_trailingSlashAwareDataRequests": false, "unstable_previewServerPrerendering": false, "v8_middleware": false, "v8_splitRouteModules": false, "v8_viteEnvironmentApi": false };
@@ -182290,7 +182774,7 @@ function createFetchHandler(basename2 = "/") {
182290
182774
  return (request2) => handler(request2, loadContext);
182291
182775
  }
182292
182776
  export {
182293
- RETENTION_ZERO as $,
182777
+ RETENTION_DEFAULT as $,
182294
182778
  ANALYTICS_EVENTS_GET_MANY_LIMIT as A,
182295
182779
  BULK_CANCEL_MAX_RUN_IDS as B,
182296
182780
  CHILD_ENTITY_CREATION_EVENT_TYPES as C,
@@ -182307,113 +182791,117 @@ export {
182307
182791
  Nt as N,
182308
182792
  HookCreatedEventSchema as O,
182309
182793
  HookResumeCapabilitiesSchema as P,
182310
- LegacySerializedDataSchemaV1 as Q,
182311
- MessageId as R,
182312
- NODE_HTTP_DEFAULT as S,
182313
- NODE_HTTP_ENV_VAR as T,
182314
- PARENT_RUN_ID_ATTRIBUTE as U,
182315
- PaginatedResponseSchema as V,
182316
- QueuePayloadSchema as W,
182317
- QueuePrefix as X,
182318
- RESERVED_ATTRIBUTE_KEY_PREFIX as Y,
182319
- RETENTION_ATTRIBUTE as Z,
182320
- RETENTION_DEFAULT as _,
182794
+ IN_BAND_SEQ_AT_RUN_CREATION as Q,
182795
+ LegacySerializedDataSchemaV1 as R,
182796
+ MessageId as S,
182797
+ NODE_HTTP_DEFAULT as T,
182798
+ NODE_HTTP_ENV_VAR as U,
182799
+ PARENT_RUN_ID_ATTRIBUTE as V,
182800
+ PaginatedResponseSchema as W,
182801
+ QueuePayloadSchema as X,
182802
+ QueuePrefix as Y,
182803
+ RESERVED_ATTRIBUTE_KEY_PREFIX as Z,
182804
+ RETENTION_ATTRIBUTE as _,
182321
182805
  ANALYTICS_MAX_ATTRIBUTE_FILTERS as a,
182322
- mintedSpecVersion as a$,
182323
- ROOT_RUN_ID_ATTRIBUTE as a0,
182324
- RUN_ENTITY_KEY as a1,
182325
- RunInputSchema as a2,
182326
- SEALED_LOG_ENV_VAR as a3,
182327
- SPEC_VERSION_CURRENT as a4,
182328
- SPEC_VERSION_LEGACY as a5,
182329
- SPEC_VERSION_MAX_SUPPORTED as a6,
182330
- SPEC_VERSION_SUPPORTS_ATTRIBUTES as a7,
182331
- SPEC_VERSION_SUPPORTS_CBOR_QUEUE_TRANSPORT as a8,
182332
- SPEC_VERSION_SUPPORTS_COMPRESSION as a9,
182333
- classifyEntityEvent as aA,
182334
- decodeSnapshotEnvelope as aB,
182335
- encodeSnapshotEnvelope as aC,
182336
- entityEventClass as aD,
182337
- entityResolveData as aE,
182338
- envFlag as aF,
182339
- envNumber as aG,
182340
- eventIdToSlot as aH,
182341
- getEventDataPayloadField as aI,
182342
- getEventDataRefFields as aJ,
182343
- getMaxEventsPerRun as aK,
182344
- getQueueTopicPrefix as aL,
182345
- isChildEntityCreationEvent as aM,
182346
- isChildEntityCreationEventType as aN,
182347
- isHookEventRequiringExistence as aO,
182348
- isHookLifecycleEventType as aP,
182349
- isLegacySpecVersion as aQ,
182350
- isNodeHttpEnabled as aR,
182351
- isSealedNoopEvent$1 as aS,
182352
- isSlotBody as aT,
182353
- isSlotEventId as aU,
182354
- isStepEventType as aV,
182355
- isTerminalRunEventType as aW,
182356
- isTerminalStepEventType as aX,
182357
- isTerminalStepStatus as aY,
182358
- isTerminalWorkflowRunStatus as aZ,
182359
- isWaitEventType as a_,
182360
- SPEC_VERSION_SUPPORTS_EVENT_SOURCING as aa,
182361
- SPEC_VERSION_SUPPORTS_HOOK_FORCE_CLAIM as ab,
182362
- SPEC_VERSION_SUPPORTS_SLOT_IDENTITY as ac,
182363
- STEP_EVENT_TYPES as ad,
182364
- SerializedDataSchema as ae,
182365
- SnapshotMetadataSchema as af,
182366
- StepSchema as ag,
182367
- StepStatusSchema as ah,
182368
- StructuredErrorSchema as ai,
182369
- TERMINAL_EVENT_CLASSES as aj,
182370
- TERMINAL_RUN_EVENT_TYPES as ak,
182371
- TERMINAL_STEP_EVENT_TYPES as al,
182372
- TERMINAL_STEP_STATUSES as am,
182373
- TERMINAL_WORKFLOW_RUN_STATUSES as an,
182374
- TerminalRunEventTypeSchema as ao,
182375
- TerminalStepStatusSchema as ap,
182376
- TerminalWorkflowRunStatusSchema as aq,
182377
- ValidQueueName as ar,
182378
- WAIT_EVENT_TYPES as as,
182379
- WaitSchema as at,
182380
- WaitStatusSchema as au,
182381
- WorkflowInvokePayloadSchema as av,
182382
- WorkflowRunBaseSchema as aw,
182383
- WorkflowRunSchema as ax,
182384
- WorkflowRunStatusSchema as ay,
182385
- applyAttributeChanges as az,
182806
+ isTerminalStepStatus as a$,
182807
+ RETENTION_ZERO as a0,
182808
+ ROOT_RUN_ID_ATTRIBUTE as a1,
182809
+ RUN_ENTITY_KEY as a2,
182810
+ RunInputSchema as a3,
182811
+ SEALED_LOG_ENV_VAR as a4,
182812
+ SPEC_VERSION_CURRENT as a5,
182813
+ SPEC_VERSION_LEGACY as a6,
182814
+ SPEC_VERSION_MAX_SUPPORTED as a7,
182815
+ SPEC_VERSION_SUPPORTS_ATTRIBUTES as a8,
182816
+ SPEC_VERSION_SUPPORTS_CBOR_QUEUE_TRANSPORT as a9,
182817
+ WorkflowRunStatusSchema as aA,
182818
+ applyAttributeChanges as aB,
182819
+ classifyEntityEvent as aC,
182820
+ decodeSnapshotEnvelope as aD,
182821
+ encodeSnapshotEnvelope as aE,
182822
+ entityEventClass as aF,
182823
+ entityResolveData as aG,
182824
+ envFlag as aH,
182825
+ envNumber as aI,
182826
+ eventIdToSlot as aJ,
182827
+ getEventDataPayloadField as aK,
182828
+ getEventDataRefFields as aL,
182829
+ getMaxEventsPerRun as aM,
182830
+ getQueueTopicPrefix as aN,
182831
+ getRunQueueNamespace as aO,
182832
+ isChildEntityCreationEvent as aP,
182833
+ isChildEntityCreationEventType as aQ,
182834
+ isHookEventRequiringExistence as aR,
182835
+ isHookLifecycleEventType as aS,
182836
+ isLegacySpecVersion as aT,
182837
+ isNodeHttpEnabled as aU,
182838
+ isSealedNoopEvent$1 as aV,
182839
+ isSlotBody as aW,
182840
+ isSlotEventId as aX,
182841
+ isStepEventType as aY,
182842
+ isTerminalRunEventType as aZ,
182843
+ isTerminalStepEventType as a_,
182844
+ SPEC_VERSION_SUPPORTS_COMPRESSION as aa,
182845
+ SPEC_VERSION_SUPPORTS_EVENT_SOURCING as ab,
182846
+ SPEC_VERSION_SUPPORTS_HOOK_FORCE_CLAIM as ac,
182847
+ SPEC_VERSION_SUPPORTS_SLOT_IDENTITY as ad,
182848
+ STEP_EVENT_TYPES as ae,
182849
+ SerializedDataSchema as af,
182850
+ SnapshotMetadataSchema as ag,
182851
+ StepSchema as ah,
182852
+ StepStatusSchema as ai,
182853
+ StructuredErrorSchema as aj,
182854
+ TERMINAL_EVENT_CLASSES as ak,
182855
+ TERMINAL_RUN_EVENT_TYPES as al,
182856
+ TERMINAL_STEP_EVENT_TYPES as am,
182857
+ TERMINAL_STEP_STATUSES as an,
182858
+ TERMINAL_WORKFLOW_RUN_STATUSES as ao,
182859
+ TerminalRunEventTypeSchema as ap,
182860
+ TerminalStepStatusSchema as aq,
182861
+ TerminalWorkflowRunStatusSchema as ar,
182862
+ ValidQueueName as as,
182863
+ WAIT_EVENT_TYPES as at,
182864
+ WORKFLOW_FLOW_ROUTE as au,
182865
+ WaitSchema as av,
182866
+ WaitStatusSchema as aw,
182867
+ WorkflowInvokePayloadSchema as ax,
182868
+ WorkflowRunBaseSchema as ay,
182869
+ WorkflowRunSchema as az,
182386
182870
  ANALYTICS_PAGE_LIMIT as b,
182387
- parseQueueName as b0,
182388
- readRunRetention as b1,
182389
- reenqueueActiveRuns as b2,
182390
- requiresNewerWorld as b3,
182391
- resolveQueueNamespace as b4,
182392
- slotToEventId as b5,
182393
- stripEventDataRefs as b6,
182394
- ulidToDate as b7,
182395
- validateAttributeChanges as b8,
182396
- validateAttributeEventDataSize as b9,
182397
- validateUlidTimestamp as ba,
182398
- workflowRunIdSchema as bb,
182399
- reactExports as bc,
182400
- R as bd,
182401
- Ks as be,
182402
- jsxRuntimeExports as bf,
182403
- Qe as bg,
182404
- registerZstdDecoder as bh,
182405
- WebSocket as bi,
182406
- permessageDeflate as bj,
182407
- receiver as bk,
182408
- sender as bl,
182409
- websocketServer as bm,
182410
- stream as bn,
182411
- extension as bo,
182412
- subprotocol as bp,
182413
- getDefaultExportFromCjs as bq,
182414
- requireTokenUtil as br,
182415
- requireTokenError as bs,
182416
- createFetchHandler as bt,
182871
+ isTerminalWorkflowRunStatus as b0,
182872
+ isWaitEventType as b1,
182873
+ mintedSpecVersion as b2,
182874
+ parseQueueName as b3,
182875
+ parseQueueRoute as b4,
182876
+ readRunRetention as b5,
182877
+ reenqueueActiveRuns as b6,
182878
+ requiresNewerWorld as b7,
182879
+ resolveQueueNamespace as b8,
182880
+ slotToEventId as b9,
182881
+ stripEventDataRefs as ba,
182882
+ ulidToDate as bb,
182883
+ validateAttributeChanges as bc,
182884
+ validateAttributeEventDataSize as bd,
182885
+ validateUlidTimestamp as be,
182886
+ workflowRunIdSchema as bf,
182887
+ reactExports as bg,
182888
+ R as bh,
182889
+ Ks as bi,
182890
+ jsxRuntimeExports as bj,
182891
+ Qe as bk,
182892
+ registerZstdDecoder as bl,
182893
+ WebSocket as bm,
182894
+ permessageDeflate as bn,
182895
+ receiver as bo,
182896
+ sender as bp,
182897
+ websocketServer as bq,
182898
+ stream as br,
182899
+ extension as bs,
182900
+ subprotocol as bt,
182901
+ getDefaultExportFromCjs as bu,
182902
+ requireTokenUtil as bv,
182903
+ requireTokenError as bw,
182904
+ createFetchHandler as bx,
182417
182905
  ANALYTICS_RUN_SCOPED_PAGE_LIMIT as c,
182418
182906
  ATTRIBUTE_EVENT_DATA_MAX_BYTES as d,
182419
182907
  ATTRIBUTE_KEY_MAX_LENGTH as e,