@workflow/web 5.0.0-beta.47 → 5.0.0-beta.49

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 (24) hide show
  1. package/build/client/assets/{arrow-up-right-C52N96YH.js → arrow-up-right-CSovqivK.js} +1 -1
  2. package/build/client/assets/{highlighted-body-B3W2YXNL-BzCKp954.js → highlighted-body-B3W2YXNL-BO5_Ufo-.js} +1 -1
  3. package/build/client/assets/{home-CXFjRmpa.js → home-BbyW_T74.js} +3 -3
  4. package/build/client/assets/{loader-circle-BQzzSKVU.js → loader-circle-BX6ycuOI.js} +1 -1
  5. package/build/client/assets/{manifest-9ff1658d.js → manifest-34c486ef.js} +1 -1
  6. package/build/client/assets/{mermaid-3ZIDBTTL-BrUzeGHN.js → mermaid-3ZIDBTTL-BKwl_LgA.js} +73 -7
  7. package/build/client/assets/{root-DBp4o4Ap.js → root-qx_45_fH.js} +3 -3
  8. package/build/client/assets/{run-detail-7tPGLWpY.js → run-detail-BoGFG1Fe.js} +4 -4
  9. package/build/client/assets/{workflow-graph-viewer-BI72rVK-.js → workflow-graph-viewer-C-1D0sAn.js} +1 -1
  10. package/build/client/assets/{zstd-browser-decoder-C5OUdy0l.js → zstd-browser-decoder-By3hr1F0.js} +1 -1
  11. package/build/server/assets/{app-z0qVD1ZU.js → app-BktG_kyr.js} +1511 -787
  12. package/build/server/assets/{highlighted-body-B3W2YXNL-BRzynHFv.js → highlighted-body-B3W2YXNL-B3n-nCiA.js} +1 -1
  13. package/build/server/assets/{index-jQkBA81b.js → index-EldBi9Vs.js} +1 -1
  14. package/build/server/assets/index-SGZlzYCB.js +173 -0
  15. package/build/server/assets/{mermaid-3ZIDBTTL-CNWRBcN0.js → mermaid-3ZIDBTTL-CG8N1j_9.js} +1 -1
  16. package/build/server/assets/{token-BSEhy2T4.js → token-tFJ2cDc9.js} +1 -1
  17. package/build/server/assets/{token-util-D_gzpVW2.js → token-util-C4igRPyO.js} +1 -1
  18. package/build/server/assets/{websocket-server-CDTVQU5X.js → websocket-server-Czz0Pxs-.js} +1 -1
  19. package/build/server/assets/{wrapper-BxieYZVg.js → wrapper-BPjS6joc.js} +3 -3
  20. package/build/server/assets/{ws-transport-DbDOLT7f.js → ws-transport-DUA3rYTp.js} +2 -2
  21. package/build/server/assets/{zstd-browser-decoder-CtzWlfs5.js → zstd-browser-decoder-BhzrSkhl.js} +1 -1
  22. package/build/server/index.js +3 -3
  23. package/package.json +10 -10
  24. package/build/server/assets/index-DDMGTwh_.js +0 -166
@@ -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, _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, _worldPromise, _Run_instances, lazyWorldPromise_get, _encryptionKeyPromise, _resilientStart, getEncryptionKey_fn, getEncryptionKeyLazily_fn, resolveTerminalReturnValue_fn, pollReturnValue_fn;
16
+ var _a2, _b, _c, _d, _listeners, _onabort, _reader, _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, _worldPromise, _Run_instances, lazyWorldPromise_get, _encryptionKeyPromise, _resilientStart, getEncryptionKey_fn, getEncryptionKeyLazily_fn, getMetadata_fn, resolveTerminalReturnValue_fn, pollReturnValue_fn;
17
17
  import { createRequire as __wkfCreateRequire } from "node:module";
18
18
  if (typeof require === "undefined") {
19
19
  globalThis.require = __wkfCreateRequire(import.meta.url);
@@ -56873,6 +56873,25 @@ const z$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty(
56873
56873
  const RESERVED_ATTRIBUTE_KEY_PREFIX = "$";
56874
56874
  const ROOT_RUN_ID_ATTRIBUTE = `${RESERVED_ATTRIBUTE_KEY_PREFIX}rootRunId`;
56875
56875
  const PARENT_RUN_ID_ATTRIBUTE = `${RESERVED_ATTRIBUTE_KEY_PREFIX}parentRunId`;
56876
+ const RETENTION_ATTRIBUTE = `${RESERVED_ATTRIBUTE_KEY_PREFIX}retention`;
56877
+ const RETENTION_ZERO = "0";
56878
+ const RETENTION_DEFAULT = "default";
56879
+ const RETENTION_INTEGER_PATTERN = /^(?:0|[1-9]\d*)$/;
56880
+ function readRunRetention(attributes) {
56881
+ const raw2 = attributes == null ? void 0 : attributes[RETENTION_ATTRIBUTE];
56882
+ if (raw2 === void 0) {
56883
+ return { mode: "default", wellFormed: false, unsupported: false };
56884
+ }
56885
+ if (RETENTION_INTEGER_PATTERN.test(raw2)) {
56886
+ return raw2 === RETENTION_ZERO ? { mode: "none", raw: raw2, wellFormed: true, unsupported: false } : { mode: "default", raw: raw2, wellFormed: true, unsupported: true };
56887
+ }
56888
+ return {
56889
+ mode: "default",
56890
+ raw: raw2,
56891
+ wellFormed: false,
56892
+ unsupported: raw2 !== RETENTION_DEFAULT
56893
+ };
56894
+ }
56876
56895
  const ATTRIBUTE_KEY_MAX_LENGTH = 256;
56877
56896
  const ATTRIBUTE_VALUE_MAX_BYTES = 256;
56878
56897
  const ATTRIBUTE_MAX_PER_RUN = 64;
@@ -57594,7 +57613,7 @@ const WorkflowRunSchema = discriminatedUnion("status", [
57594
57613
  // Completed state - output can be v1 or v2 format
57595
57614
  WorkflowRunBaseSchema.extend({
57596
57615
  status: literal("completed"),
57597
- output: SerializedDataSchema,
57616
+ output: SerializedDataSchema.optional(),
57598
57617
  error: _undefined().optional(),
57599
57618
  completedAt: date$2()
57600
57619
  }),
@@ -57602,7 +57621,7 @@ const WorkflowRunSchema = discriminatedUnion("status", [
57602
57621
  WorkflowRunBaseSchema.extend({
57603
57622
  status: literal("failed"),
57604
57623
  output: _undefined().optional(),
57605
- error: SerializedDataSchema,
57624
+ error: SerializedDataSchema.optional(),
57606
57625
  completedAt: date$2()
57607
57626
  })
57608
57627
  ]);
@@ -57812,10 +57831,13 @@ const AnalyticsWaitSchema = object$1({
57812
57831
  const AnalyticsAttributeKeySchema = object$1({
57813
57832
  key: string$3(),
57814
57833
  runCount: number$2(),
57815
- firstSeenAt: date$2(),
57816
- lastSeenAt: date$2()
57834
+ firstSeenAt: UTCDateSchema,
57835
+ lastSeenAt: UTCDateSchema
57817
57836
  });
57818
57837
  const ANALYTICS_EVENTS_GET_MANY_LIMIT = 100;
57838
+ const ANALYTICS_RUN_SCOPED_PAGE_LIMIT = 1e3;
57839
+ const ANALYTICS_PAGE_LIMIT = 100;
57840
+ const ANALYTICS_MAX_ATTRIBUTE_FILTERS = 8;
57819
57841
  const WarnedEnvValuesKey = Symbol.for("@workflow/world//warnedEnvValues/v1");
57820
57842
  const globalStore = globalThis;
57821
57843
  const warnedEnvValues = globalStore[WarnedEnvValuesKey] ?? (globalStore[WarnedEnvValuesKey] = /* @__PURE__ */ new Set());
@@ -58531,10 +58553,10 @@ function findDuplicateEventIds(events2, { isCompleteHistory }) {
58531
58553
  return foldDuplicates(ordered);
58532
58554
  }
58533
58555
  const WORKFLOW_ULID_BODY = "[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}";
58534
- const STEP_ID_PATTERN = new RegExp(`^step_(${WORKFLOW_ULID_BODY})$`, "i");
58535
- const WAIT_ID_PATTERN = new RegExp(`^wait_(${WORKFLOW_ULID_BODY})$`, "i");
58536
- const HOOK_ID_PATTERN = new RegExp(`^hook_(${WORKFLOW_ULID_BODY})$`, "i");
58537
- const EVENT_ID_PATTERN = new RegExp(`^evnt_(${WORKFLOW_ULID_BODY})$`, "i");
58556
+ const STEP_ID_PATTERN$1 = new RegExp(`^step_(${WORKFLOW_ULID_BODY})$`, "i");
58557
+ const WAIT_ID_PATTERN$1 = new RegExp(`^wait_(${WORKFLOW_ULID_BODY})$`, "i");
58558
+ const HOOK_ID_PATTERN$1 = new RegExp(`^hook_(${WORKFLOW_ULID_BODY})$`, "i");
58559
+ const EVENT_ID_PATTERN$1 = new RegExp(`^evnt_(${WORKFLOW_ULID_BODY})$`, "i");
58538
58560
  const WORKFLOW_ID_PREFIX_PATTERN = /^(step_|wait_|hook_|evnt_|wrun_)/i;
58539
58561
  function matchPrefixedId(pattern2, prefix, kind, query) {
58540
58562
  const match2 = query.match(pattern2);
@@ -58548,7 +58570,7 @@ function parseExactWorkflowSearchId(query) {
58548
58570
  if (!trimmed) {
58549
58571
  return null;
58550
58572
  }
58551
- return matchPrefixedId(STEP_ID_PATTERN, "step", "step", trimmed) ?? matchPrefixedId(WAIT_ID_PATTERN, "wait", "wait", trimmed) ?? matchPrefixedId(HOOK_ID_PATTERN, "hook", "hook", trimmed) ?? matchPrefixedId(EVENT_ID_PATTERN, "evnt", "event", trimmed);
58573
+ return matchPrefixedId(STEP_ID_PATTERN$1, "step", "step", trimmed) ?? matchPrefixedId(WAIT_ID_PATTERN$1, "wait", "wait", trimmed) ?? matchPrefixedId(HOOK_ID_PATTERN$1, "hook", "hook", trimmed) ?? matchPrefixedId(EVENT_ID_PATTERN$1, "evnt", "event", trimmed);
58552
58574
  }
58553
58575
  function looksLikeWorkflowIdSearchInput(query) {
58554
58576
  const trimmed = query.trim();
@@ -59438,6 +59460,10 @@ function stringify_primitive(thing) {
59438
59460
  if (type === "bigint") return `["BigInt","${thing}"]`;
59439
59461
  return String(thing);
59440
59462
  }
59463
+ const RUN_ERROR_CODES = {
59464
+ /** Workflow stream infrastructure failed while reading or writing data */
59465
+ STREAM_ERROR: "STREAM_ERROR"
59466
+ };
59441
59467
  const BASE_URL = "https://workflow-sdk.dev/err";
59442
59468
  function isError(value) {
59443
59469
  return typeof value === "object" && value !== null && "name" in value && "message" in value;
@@ -59499,11 +59525,18 @@ class WorkflowWorldError extends WorkflowError {
59499
59525
  __publicField(this, "url");
59500
59526
  /** Retry-After value in seconds, present on 429 and 425 responses */
59501
59527
  __publicField(this, "retryAfter");
59528
+ /**
59529
+ * The offending argument, present on client-side validation failures
59530
+ * (`code: 'INVALID_ARGUMENT'`). Lets a caller correct the specific
59531
+ * parameter without parsing the message.
59532
+ */
59533
+ __publicField(this, "field");
59502
59534
  this.name = "WorkflowWorldError";
59503
59535
  this.status = options == null ? void 0 : options.status;
59504
59536
  this.code = options == null ? void 0 : options.code;
59505
59537
  this.url = options == null ? void 0 : options.url;
59506
59538
  this.retryAfter = options == null ? void 0 : options.retryAfter;
59539
+ this.field = options == null ? void 0 : options.field;
59507
59540
  }
59508
59541
  static is(value) {
59509
59542
  return isError(value) && value.name === "WorkflowWorldError";
@@ -59654,14 +59687,34 @@ class EntityConflictError extends WorkflowWorldError {
59654
59687
  }
59655
59688
  }
59656
59689
  class RunExpiredError extends WorkflowWorldError {
59657
- constructor(message2) {
59658
- super(message2);
59690
+ constructor(message2, runId, runStatus, expiredAt) {
59691
+ super(message2, { status: 410, code: "run-expired" });
59692
+ __publicField(this, "runId");
59693
+ __publicField(this, "runStatus");
59694
+ __publicField(this, "expiredAt");
59695
+ this.runId = runId;
59696
+ this.runStatus = runStatus;
59697
+ this.expiredAt = expiredAt;
59659
59698
  this.name = "RunExpiredError";
59660
59699
  }
59661
59700
  static is(value) {
59662
59701
  return isError(value) && value.name === "RunExpiredError";
59663
59702
  }
59664
59703
  }
59704
+ class StreamError extends WorkflowWorldError {
59705
+ constructor(message2, options) {
59706
+ super(message2, {
59707
+ code: RUN_ERROR_CODES.STREAM_ERROR,
59708
+ cause: options == null ? void 0 : options.cause,
59709
+ url: options == null ? void 0 : options.url,
59710
+ status: options == null ? void 0 : options.status
59711
+ });
59712
+ this.name = "StreamError";
59713
+ }
59714
+ static is(value) {
59715
+ return isError(value) && value.name === "StreamError";
59716
+ }
59717
+ }
59665
59718
  class StreamExpiredError extends WorkflowWorldError {
59666
59719
  constructor(message2, runId, streamId, expiredAt) {
59667
59720
  super(message2, { status: 410, code: "stream-expired" });
@@ -59769,6 +59822,7 @@ const FATAL_ERROR_KEY = Symbol.for("@workflow/errors//FatalError");
59769
59822
  const RETRYABLE_ERROR_KEY = Symbol.for("@workflow/errors//RetryableError");
59770
59823
  const HOOK_CONFLICT_ERROR_KEY = Symbol.for("@workflow/errors//HookConflictError");
59771
59824
  const RUNTIME_DECRYPTION_ERROR_KEY = Symbol.for("@workflow/errors//RuntimeDecryptionError");
59825
+ const STREAM_ERROR_KEY = Symbol.for("@workflow/errors//StreamError");
59772
59826
  if (typeof globalThis !== "undefined") {
59773
59827
  if (!Object.hasOwn(globalThis, FATAL_ERROR_KEY)) {
59774
59828
  Object.defineProperty(globalThis, FATAL_ERROR_KEY, {
@@ -59802,6 +59856,14 @@ if (typeof globalThis !== "undefined") {
59802
59856
  configurable: false
59803
59857
  });
59804
59858
  }
59859
+ if (!Object.hasOwn(globalThis, STREAM_ERROR_KEY)) {
59860
+ Object.defineProperty(globalThis, STREAM_ERROR_KEY, {
59861
+ value: StreamError,
59862
+ writable: false,
59863
+ enumerable: false,
59864
+ configurable: false
59865
+ });
59866
+ }
59805
59867
  }
59806
59868
  const NONCE_LENGTH = 12;
59807
59869
  const TAG_LENGTH = 128;
@@ -60883,6 +60945,18 @@ function getWebRevivers() {
60883
60945
  error2.stack = value.stack;
60884
60946
  return error2;
60885
60947
  },
60948
+ StreamError: (value) => {
60949
+ const opts = "cause" in value ? { cause: value.cause } : void 0;
60950
+ const error2 = new Error(value.message, opts);
60951
+ error2.name = "StreamError";
60952
+ if (value.status !== void 0)
60953
+ error2.status = value.status;
60954
+ if (value.url !== void 0)
60955
+ error2.url = value.url;
60956
+ if (value.stack !== void 0)
60957
+ error2.stack = value.stack;
60958
+ return error2;
60959
+ },
60886
60960
  DOMException: (value) => {
60887
60961
  const G2 = globalThis;
60888
60962
  if (typeof G2.DOMException === "function") {
@@ -61033,7 +61107,7 @@ function replaceEncryptedAndExpiredWithMarkers(resource) {
61033
61107
  }
61034
61108
  async function hydrateResourceIOAsync(resource, key) {
61035
61109
  const { hydrateDataWithKey: hydrateDataWithKey2, deriveRunPayloadKeys: deriveRunPayloadKeys2 } = await Promise.resolve().then(() => serializationFormat);
61036
- const { ensureZstdDecoderRegistered } = await import("./zstd-browser-decoder-CtzWlfs5.js");
61110
+ const { ensureZstdDecoderRegistered } = await import("./zstd-browser-decoder-BhzrSkhl.js");
61037
61111
  ensureZstdDecoderRegistered();
61038
61112
  const cryptoKey = key ? await deriveRunPayloadKeys2(key) : void 0;
61039
61113
  const revivers = getRevivers();
@@ -91972,7 +92046,7 @@ var tn = f("block", "before:content-[counter(line)]", "before:inline-block", "be
91972
92046
  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 });
91973
92047
  var Se = reactExports.createContext({ code: "" }), de = () => reactExports.useContext(Se);
91974
92048
  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 }) });
91975
- var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-BRzynHFv.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
92049
+ var cn$1 = /\n+$/, dn = reactExports.lazy(() => import("./highlighted-body-B3W2YXNL-B3n-nCiA.js").then((e) => ({ default: e.HighlightedCodeBlockBody }))), rt = ({ code: e, language: t, className: o, children: n, isIncomplete: s2 = false, ...r2 }) => {
91976
92050
  let i = reactExports.useMemo(() => e.replace(cn$1, ""), [e]), c = reactExports.useMemo(() => ({ bg: "transparent", fg: "inherit", tokens: i.split(`
91977
92051
  `).map((a2) => [{ content: a2, color: "inherit", bgColor: "transparent", htmlStyle: {}, offset: 0 }]) }), [i]);
91978
92052
  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 }) })] }) });
@@ -92294,7 +92368,7 @@ var Dt = ({ children: e, className: t, onDownload: o, onError: n }) => {
92294
92368
  }, []), 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] });
92295
92369
  };
92296
92370
  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 }) })] });
92297
- var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-CNWRBcN0.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
92371
+ var Jn = reactExports.lazy(() => import("./mermaid-3ZIDBTTL-CG8N1j_9.js").then((e) => ({ default: e.Mermaid }))), Kn = /language-([^\s]+)/;
92298
92372
  function ke(e, t) {
92299
92373
  if (!(e != null && e.position || t != null && t.position)) return true;
92300
92374
  if (!(e != null && e.position && (t != null && t.position))) return false;
@@ -100701,11 +100775,18 @@ function Logo({ className } = {}) {
100701
100775
  }
100702
100776
  );
100703
100777
  }
100704
- const RETRYABLE_WORLD_ERROR_CODES = /* @__PURE__ */ new Set(["TRANSPORT", "TIMEOUT"]);
100778
+ const RETRYABLE_WORLD_ERROR_CODES = /* @__PURE__ */ new Set([
100779
+ "TRANSPORT",
100780
+ "TIMEOUT",
100781
+ RUN_ERROR_CODES.STREAM_ERROR
100782
+ ]);
100705
100783
  function isRetryableWorldError(err) {
100706
100784
  if (ThrottleError.is(err)) {
100707
100785
  return true;
100708
100786
  }
100787
+ if (StreamError.is(err)) {
100788
+ return err.status === void 0 || err.status >= 500;
100789
+ }
100709
100790
  if (!WorkflowWorldError.is(err)) {
100710
100791
  return false;
100711
100792
  }
@@ -102096,6 +102177,19 @@ function getCommonReducers(_global = globalThis) {
102096
102177
  }
102097
102178
  return reduced;
102098
102179
  },
102180
+ StreamError: (value) => {
102181
+ const base = reduceNamedErrorSubclassBase("StreamError", value);
102182
+ if (!base)
102183
+ return false;
102184
+ const reduced = { ...base };
102185
+ const status = readProperty(value, "status");
102186
+ const url2 = readProperty(value, "url");
102187
+ if (typeof status === "number")
102188
+ reduced.status = status;
102189
+ if (typeof url2 === "string")
102190
+ reduced.url = url2;
102191
+ return reduced;
102192
+ },
102099
102193
  SyntaxError: makeErrorSubclassReducer("SyntaxError"),
102100
102194
  TypeError: makeErrorSubclassReducer("TypeError"),
102101
102195
  URIError: makeErrorSubclassReducer("URIError"),
@@ -102241,6 +102335,17 @@ function getCommonRevivers$1(global2 = globalThis) {
102241
102335
  error2.stack = value.stack;
102242
102336
  return error2;
102243
102337
  },
102338
+ StreamError: (value) => {
102339
+ const Ctor = global2[Symbol.for("@workflow/errors//StreamError")] ?? StreamError;
102340
+ const error2 = new Ctor(value.message, {
102341
+ ..."cause" in value ? { cause: value.cause } : {},
102342
+ status: value.status,
102343
+ url: value.url
102344
+ });
102345
+ if (value.stack !== void 0)
102346
+ error2.stack = value.stack;
102347
+ return error2;
102348
+ },
102244
102349
  SyntaxError: makeErrorSubclassReviver(global2, "SyntaxError"),
102245
102350
  TypeError: makeErrorSubclassReviver(global2, "TypeError"),
102246
102351
  URIError: makeErrorSubclassReviver(global2, "URIError"),
@@ -102983,6 +103088,18 @@ function recordReadTimeToFirstChunk(startEpochMs, runId, name2, startIndex, conn
102983
103088
  });
102984
103089
  })();
102985
103090
  }
103091
+ function recordStreamReadKeyResolution(startEpochMs, runId, name2, succeeded) {
103092
+ void (async () => {
103093
+ await recordElapsedSpan("workflow.stream.read.resolve_key", startEpochMs, {
103094
+ kind: await getSpanKind$2("CLIENT"),
103095
+ attributes: {
103096
+ "workflow.run.id": runId,
103097
+ "workflow.stream.name": name2,
103098
+ "workflow.stream.read.key_succeeded": succeeded
103099
+ }
103100
+ });
103101
+ })();
103102
+ }
102986
103103
  function recordStreamReadComplete(startEpochMs, runId, name2, chunkCount, byteCount, reconnects) {
102987
103104
  void (async () => {
102988
103105
  await recordElapsedSpan("workflow.stream.read.complete", startEpochMs, {
@@ -103063,27 +103180,50 @@ const getFramedStreamMaxReconnects = () => envNumber("WORKFLOW_FRAMED_STREAM_MAX
103063
103180
  });
103064
103181
  const FRAMED_STREAM_MAX_TOTAL_RECONNECTS = 1e3;
103065
103182
  const getFramedStreamMaxTotalReconnects = () => envNumber("WORKFLOW_FRAMED_STREAM_MAX_TOTAL_RECONNECTS", FRAMED_STREAM_MAX_TOTAL_RECONNECTS, { integer: true, min: 1 });
103066
- function createReconnectingFramedStream(runId, name2, startIndex) {
103183
+ function createReconnectingFramedStream(runId, name2, startIndex, prefetchEncryptionKey = async () => void 0) {
103067
103184
  const reconnectSupported = startIndex === void 0 || startIndex >= 0;
103068
103185
  let currentStartIndex = startIndex ?? 0;
103069
103186
  let consumedFrames = 0;
103070
103187
  let reconnectCount = 0;
103071
103188
  let totalReconnectCount = 0;
103072
103189
  let reader;
103190
+ let canceled = false;
103191
+ let cancelReason;
103073
103192
  let buffer2 = new Uint8Array(0);
103074
103193
  let readStart;
103075
103194
  let connectMs;
103076
103195
  let firstChunkReported = false;
103077
103196
  let chunksDelivered = 0;
103078
103197
  let bytesDelivered = 0;
103198
+ let keyPrefetched = false;
103199
+ function prefetchKey() {
103200
+ if (keyPrefetched)
103201
+ return;
103202
+ keyPrefetched = true;
103203
+ const keyStart = Date.now();
103204
+ void prefetchEncryptionKey().then((key) => {
103205
+ if (key)
103206
+ recordStreamReadKeyResolution(keyStart, runId, name2, true);
103207
+ }, () => recordStreamReadKeyResolution(keyStart, runId, name2, false));
103208
+ }
103079
103209
  async function connect2() {
103210
+ if (canceled)
103211
+ return false;
103080
103212
  const world = await getWorldLazy();
103213
+ if (canceled)
103214
+ return false;
103081
103215
  const effectiveStartIndex = reconnectSupported ? currentStartIndex + consumedFrames : startIndex;
103082
103216
  const connectStart = Date.now();
103083
103217
  const stream = await world.streams.get(runId, name2, effectiveStartIndex);
103218
+ if (canceled) {
103219
+ await stream.cancel(cancelReason).catch(() => {
103220
+ });
103221
+ return false;
103222
+ }
103084
103223
  if (connectMs === void 0)
103085
103224
  connectMs = Date.now() - connectStart;
103086
103225
  reader = stream.getReader();
103226
+ return true;
103087
103227
  }
103088
103228
  async function isVerifiedComplete() {
103089
103229
  try {
@@ -103095,11 +103235,15 @@ function createReconnectingFramedStream(runId, name2, startIndex) {
103095
103235
  }
103096
103236
  }
103097
103237
  async function reconnect() {
103238
+ if (canceled)
103239
+ return false;
103098
103240
  if (reader) {
103099
103241
  await reader.cancel().catch(() => {
103100
103242
  });
103101
103243
  reader = void 0;
103102
103244
  }
103245
+ if (canceled)
103246
+ return false;
103103
103247
  currentStartIndex += consumedFrames;
103104
103248
  consumedFrames = 0;
103105
103249
  buffer2 = new Uint8Array(0);
@@ -103109,15 +103253,18 @@ function createReconnectingFramedStream(runId, name2, startIndex) {
103109
103253
  reconnectCount++;
103110
103254
  totalReconnectCount++;
103111
103255
  if (reconnectCount > maxReconnects) {
103112
- throw new Error(`Stream "${name2}" exceeded maximum reconnection attempts (${maxReconnects})`);
103256
+ throw new StreamError(`Stream "${name2}" exceeded maximum reconnection attempts (${maxReconnects})`);
103113
103257
  }
103114
103258
  if (totalReconnectCount > maxTotalReconnects) {
103115
- throw new Error(`Stream "${name2}" exceeded maximum total reconnection attempts (${maxTotalReconnects})`);
103259
+ throw new StreamError(`Stream "${name2}" exceeded maximum total reconnection attempts (${maxTotalReconnects})`);
103116
103260
  }
103117
103261
  try {
103118
- await connect2();
103119
- return;
103262
+ if (!await connect2())
103263
+ return false;
103264
+ return true;
103120
103265
  } catch (error2) {
103266
+ if (canceled)
103267
+ return false;
103121
103268
  if (StreamExpiredError.is(error2))
103122
103269
  throw error2;
103123
103270
  }
@@ -103125,13 +103272,19 @@ function createReconnectingFramedStream(runId, name2, startIndex) {
103125
103272
  }
103126
103273
  return new ReadableStream({
103127
103274
  pull: async (controller) => {
103275
+ if (canceled)
103276
+ return;
103128
103277
  if (readStart === void 0)
103129
103278
  readStart = Date.now();
103279
+ prefetchKey();
103130
103280
  for (; ; ) {
103131
103281
  if (!reader) {
103132
103282
  try {
103133
- await connect2();
103283
+ if (!await connect2())
103284
+ return;
103134
103285
  } catch (err) {
103286
+ if (canceled)
103287
+ return;
103135
103288
  controller.error(err);
103136
103289
  return;
103137
103290
  }
@@ -103140,23 +103293,32 @@ function createReconnectingFramedStream(runId, name2, startIndex) {
103140
103293
  try {
103141
103294
  result = await reader.read();
103142
103295
  } catch (err) {
103296
+ if (canceled)
103297
+ return;
103143
103298
  if (!reconnectSupported) {
103144
103299
  controller.error(err);
103145
103300
  return;
103146
103301
  }
103147
103302
  try {
103148
- await reconnect();
103303
+ if (!await reconnect())
103304
+ return;
103149
103305
  } catch (reconnectErr) {
103150
103306
  controller.error(reconnectErr);
103151
103307
  return;
103152
103308
  }
103153
103309
  continue;
103154
103310
  }
103311
+ if (canceled)
103312
+ return;
103155
103313
  if (result.done || !result.value) {
103156
103314
  reader = void 0;
103157
- if (reconnectSupported && !await isVerifiedComplete()) {
103315
+ const verifiedComplete = !reconnectSupported || await isVerifiedComplete();
103316
+ if (canceled)
103317
+ return;
103318
+ if (!verifiedComplete) {
103158
103319
  try {
103159
- await reconnect();
103320
+ if (!await reconnect())
103321
+ return;
103160
103322
  } catch (reconnectErr) {
103161
103323
  controller.error(reconnectErr);
103162
103324
  return;
@@ -103199,12 +103361,15 @@ function createReconnectingFramedStream(runId, name2, startIndex) {
103199
103361
  }
103200
103362
  }
103201
103363
  },
103202
- cancel: async () => {
103203
- if (reader) {
103204
- await reader.cancel().catch((err) => {
103364
+ cancel: async (reason) => {
103365
+ canceled = true;
103366
+ cancelReason = reason;
103367
+ const currentReader = reader;
103368
+ reader = void 0;
103369
+ if (currentReader) {
103370
+ await currentReader.cancel(reason).catch((err) => {
103205
103371
  console.warn("Error closing ReadableStream reader:", err);
103206
103372
  });
103207
- reader = void 0;
103208
103373
  }
103209
103374
  }
103210
103375
  });
@@ -103276,6 +103441,13 @@ class WorkflowServerWritableStream extends WritableStream {
103276
103441
  pendingRunReady = void 0;
103277
103442
  }
103278
103443
  };
103444
+ const writerId = `wrtr_${defaultUlid()}`;
103445
+ const writeSessionPromise = ensureRunReady().then(async () => {
103446
+ var _a3, _b2;
103447
+ const world = await worldPromise;
103448
+ return (_b2 = (_a3 = world.streams).createWriteSession) == null ? void 0 : _b2.call(_a3, runId, name2, { writerId });
103449
+ });
103450
+ let nextChunkSeq = 0;
103279
103451
  let buffer2 = [];
103280
103452
  let bufferBytes = 0;
103281
103453
  let inFlightChunks = 0;
@@ -103318,14 +103490,18 @@ class WorkflowServerWritableStream extends WritableStream {
103318
103490
  const sendGroup = async (group, bytes, groupT0) => {
103319
103491
  await ensureRunReady();
103320
103492
  const world = await worldPromise;
103493
+ const session = await writeSessionPromise;
103321
103494
  const dispatchAt = Date.now();
103322
- if (typeof world.streams.writeMulti === "function" && group.length > 1) {
103495
+ if (session) {
103496
+ await session.write(nextChunkSeq, group);
103497
+ } else if (typeof world.streams.writeMulti === "function" && group.length > 1) {
103323
103498
  await world.streams.writeMulti(runId, name2, group);
103324
103499
  } else {
103325
103500
  for (const chunk of group) {
103326
103501
  await world.streams.write(runId, name2, chunk);
103327
103502
  }
103328
103503
  }
103504
+ nextChunkSeq += group.length;
103329
103505
  if (groupT0 !== void 0) {
103330
103506
  recordStreamWriteFlush(groupT0, dispatchAt, runId, name2, group.length, bytes, Date.now() - dispatchAt);
103331
103507
  }
@@ -103440,11 +103616,17 @@ class WorkflowServerWritableStream extends WritableStream {
103440
103616
  await drain();
103441
103617
  await ensureRunReady();
103442
103618
  const world = await worldPromise;
103619
+ const session = await writeSessionPromise;
103443
103620
  const closeStart = Date.now();
103444
- await world.streams.close(runId, name2);
103621
+ if (session) {
103622
+ await session.close();
103623
+ } else {
103624
+ await world.streams.close(runId, name2);
103625
+ }
103445
103626
  recordStreamClose(closeStart, runId, name2);
103446
103627
  },
103447
103628
  async abort(reason) {
103629
+ var _a3;
103448
103630
  try {
103449
103631
  await drain();
103450
103632
  } catch {
@@ -103457,6 +103639,8 @@ class WorkflowServerWritableStream extends WritableStream {
103457
103639
  bufferBytes = 0;
103458
103640
  sinkError ?? (sinkError = reason ?? new Error("Stream aborted"));
103459
103641
  rejectWaiters(sinkError);
103642
+ const session = await writeSessionPromise.catch(() => void 0);
103643
+ await ((_a3 = session == null ? void 0 : session.dispose) == null ? void 0 : _a3.call(session));
103460
103644
  }
103461
103645
  });
103462
103646
  Object.defineProperty(this, STREAM_DRAIN_SYMBOL, {
@@ -103931,7 +104115,84 @@ async function getForwardedWritableEncryptionKey(runId, deploymentId, encryption
103931
104115
  const rawKey = deploymentId ? await world.getEncryptionKeyForRun(runId, { deploymentId }) : await world.getEncryptionKeyForRun(await world.runs.get(runId));
103932
104116
  return rawKey ? await importKey(rawKey, ["encrypt"]) : void 0;
103933
104117
  }
103934
- function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey) {
104118
+ function tagForwardedWritableTarget(writable, { deploymentId, encryptionPublicKey }) {
104119
+ if (typeof deploymentId === "string") {
104120
+ Object.defineProperty(writable, STREAM_SERVER_DEPLOYMENT_ID_SYMBOL, {
104121
+ value: deploymentId,
104122
+ writable: false
104123
+ });
104124
+ }
104125
+ if (typeof encryptionPublicKey === "string") {
104126
+ Object.defineProperty(writable, STREAM_SERVER_PUBLIC_KEY_SYMBOL, {
104127
+ value: encryptionPublicKey,
104128
+ writable: false
104129
+ });
104130
+ }
104131
+ }
104132
+ function createForwardedWritable({ global: global2, ops, runId, name: name2, key, deploymentId, encryptionPublicKey, runReadyBarrier }) {
104133
+ const serialize2 = getSerializeStream(getExternalReducers(global2, ops, runId, key), key);
104134
+ const serverWritable = new WorkflowServerWritableStream(runId, name2, runReadyBarrier);
104135
+ const state = createFlushableState();
104136
+ ops.push(state.promise);
104137
+ flushablePipe(serialize2.readable, serverWritable, state).catch(() => {
104138
+ });
104139
+ pollWritableLock(serialize2.writable, state);
104140
+ Object.defineProperty(serialize2.writable, STREAM_NAME_SYMBOL, {
104141
+ value: name2,
104142
+ writable: false
104143
+ });
104144
+ Object.defineProperty(serialize2.writable, STREAM_SERVER_RUN_ID_SYMBOL, {
104145
+ value: runId,
104146
+ writable: false
104147
+ });
104148
+ tagForwardedWritableTarget(serialize2.writable, {
104149
+ deploymentId,
104150
+ encryptionPublicKey
104151
+ });
104152
+ return serialize2.writable;
104153
+ }
104154
+ function getRunReadableStream(global2, ops, runId, name2, startIndex, cryptoKey) {
104155
+ let reader;
104156
+ let lockState;
104157
+ let lockPollingStarted = false;
104158
+ let userReadable;
104159
+ userReadable = new ReadableStream(
104160
+ {
104161
+ async pull(controller) {
104162
+ try {
104163
+ if (!reader) {
104164
+ const stream = getExternalRevivers(global2, ops, runId, cryptoKey, {
104165
+ onReadableState: (state) => {
104166
+ lockState = state;
104167
+ }
104168
+ }).ReadableStream({ name: name2, startIndex });
104169
+ reader = stream.getReader();
104170
+ if (lockState && !lockPollingStarted) {
104171
+ lockPollingStarted = true;
104172
+ pollReadableLock(userReadable, lockState);
104173
+ }
104174
+ }
104175
+ const result = await reader.read();
104176
+ if (result.done)
104177
+ controller.close();
104178
+ else
104179
+ controller.enqueue(result.value);
104180
+ } catch (error2) {
104181
+ controller.error(error2);
104182
+ }
104183
+ },
104184
+ async cancel(reason) {
104185
+ await (reader == null ? void 0 : reader.cancel(reason).catch(() => {
104186
+ }));
104187
+ }
104188
+ },
104189
+ // A positive default high-water mark would run pull at construction to
104190
+ // fill the queue, turning an unread Run.getReadable() into I/O.
104191
+ { highWaterMark: 0 }
104192
+ );
104193
+ return userReadable;
104194
+ }
104195
+ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey, options) {
103935
104196
  return {
103936
104197
  ...getCommonRevivers(global2),
103937
104198
  // StepFunction should not be returned from workflows to clients
@@ -103979,50 +104240,42 @@ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey) {
103979
104240
  const { readable: userReadable, writable } = value.framing === "framed-v1" ? getByteUnframingStream() : new global2.TransformStream();
103980
104241
  flushablePipe(readable2, writable, state).catch(() => {
103981
104242
  });
103982
- pollReadableLock(userReadable, state);
104243
+ if (options == null ? void 0 : options.onReadableState)
104244
+ options.onReadableState(state);
104245
+ else
104246
+ pollReadableLock(userReadable, state);
103983
104247
  return userReadable;
103984
104248
  } else {
103985
- const readable2 = createReconnectingFramedStream(runId, value.name, value.startIndex);
103986
- const transform2 = getDeserializeStream(getExternalRevivers(global2, ops, runId, cryptoKey), cryptoKey);
104249
+ let keyPromise;
104250
+ const resolveKey = () => {
104251
+ keyPromise ?? (keyPromise = resolveEncryptionKey(cryptoKey));
104252
+ return keyPromise;
104253
+ };
104254
+ const readable2 = createReconnectingFramedStream(runId, value.name, value.startIndex, resolveKey);
104255
+ const transform2 = getDeserializeStream(getExternalRevivers(global2, ops, runId, resolveKey), resolveKey);
103987
104256
  const state = createFlushableState();
103988
104257
  ops.push(state.promise);
103989
104258
  flushablePipe(readable2, transform2.writable, state).catch(() => {
103990
104259
  });
103991
- pollReadableLock(transform2.readable, state);
104260
+ if (options == null ? void 0 : options.onReadableState)
104261
+ options.onReadableState(state);
104262
+ else
104263
+ pollReadableLock(transform2.readable, state);
103992
104264
  return transform2.readable;
103993
104265
  }
103994
104266
  },
103995
104267
  WritableStream: (value) => {
103996
104268
  const targetRunId = typeof value.runId === "string" ? value.runId : runId;
103997
104269
  const targetKey = targetRunId === runId ? cryptoKey : getForwardedWritableEncryptionKey(targetRunId, value.deploymentId, value.encryptionPublicKey);
103998
- const serialize2 = getSerializeStream(getExternalReducers(global2, ops, targetRunId, targetKey), targetKey);
103999
- const serverWritable = new WorkflowServerWritableStream(targetRunId, value.name);
104000
- const state = createFlushableState();
104001
- ops.push(state.promise);
104002
- flushablePipe(serialize2.readable, serverWritable, state).catch(() => {
104003
- });
104004
- pollWritableLock(serialize2.writable, state);
104005
- Object.defineProperty(serialize2.writable, STREAM_NAME_SYMBOL, {
104006
- value: value.name,
104007
- writable: false
104270
+ return createForwardedWritable({
104271
+ global: global2,
104272
+ ops,
104273
+ runId: targetRunId,
104274
+ name: value.name,
104275
+ key: targetKey,
104276
+ deploymentId: value.deploymentId,
104277
+ encryptionPublicKey: value.encryptionPublicKey
104008
104278
  });
104009
- Object.defineProperty(serialize2.writable, STREAM_SERVER_RUN_ID_SYMBOL, {
104010
- value: targetRunId,
104011
- writable: false
104012
- });
104013
- if (typeof value.deploymentId === "string") {
104014
- Object.defineProperty(serialize2.writable, STREAM_SERVER_DEPLOYMENT_ID_SYMBOL, {
104015
- value: value.deploymentId,
104016
- writable: false
104017
- });
104018
- }
104019
- if (typeof value.encryptionPublicKey === "string") {
104020
- Object.defineProperty(serialize2.writable, STREAM_SERVER_PUBLIC_KEY_SYMBOL, {
104021
- value: value.encryptionPublicKey,
104022
- writable: false
104023
- });
104024
- }
104025
- return serialize2.writable;
104026
104279
  },
104027
104280
  AbortController: (value) => reviveAbortController(value, ops, runId),
104028
104281
  AbortSignal: (value) => reviveAbortSignal(value, ops, runId)
@@ -104479,7 +104732,7 @@ globalSingleton("@workflow/core//envWarnings", 1, () => ({
104479
104732
  maxInlineStepsValues: /* @__PURE__ */ new Set(),
104480
104733
  maxEventsValues: /* @__PURE__ */ new Set()
104481
104734
  }));
104482
- const version$1 = "5.0.0-beta.47";
104735
+ const version$1 = "5.0.0-beta.49";
104483
104736
  const DEFAULT_HEALTH_CHECK_TIMEOUT = 3e4;
104484
104737
  const SAFE_WORKFLOW_NAME_PATTERN = /^[a-zA-Z0-9_\-./@]+$/;
104485
104738
  function getWorkflowQueueName(workflowName, namespace2) {
@@ -105114,7 +105367,7 @@ async function write(filePath, data, opts) {
105114
105367
  }
105115
105368
  async function readJSON(filePath, decoder2) {
105116
105369
  try {
105117
- const content2 = await promises.readFile(filePath, "utf-8");
105370
+ const content2 = await withWindowsRetry(() => promises.readFile(filePath, "utf-8"));
105118
105371
  return decoder2.parse(JSON.parse(content2, jsonReviver));
105119
105372
  } catch (error2) {
105120
105373
  if (error2.code === "ENOENT")
@@ -132056,7 +132309,7 @@ function envTimeoutMs(name2, fallback) {
132056
132309
  const parsed = Number.parseInt(raw2, 10);
132057
132310
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
132058
132311
  }
132059
- function getQueueAgentOptions() {
132312
+ function getQueueAgentOptions$1() {
132060
132313
  return {
132061
132314
  bodyTimeout: envTimeoutMs("WORKFLOW_LOCAL_BODY_TIMEOUT_MS", DEFAULT_BODY_TIMEOUT_MS),
132062
132315
  connections: 1e3,
@@ -132079,7 +132332,7 @@ function isDetachedArrayBufferQueueError(error2) {
132079
132332
  return false;
132080
132333
  }
132081
132334
  function createQueue$2(config2) {
132082
- const agentOptions = getQueueAgentOptions();
132335
+ const agentOptions = getQueueAgentOptions$1();
132083
132336
  const nodeHttpAgents = isNodeHttpEnabled() ? createNodeHttpAgents({
132084
132337
  maxSockets: agentOptions.connections,
132085
132338
  keepAliveMs: agentOptions.keepAliveTimeout
@@ -134512,6 +134765,500 @@ async function deleteAllHooksForRun(basedir, runId) {
134512
134765
  await deleteHookByRunMarkerFile(basedir, marker.fileId);
134513
134766
  }
134514
134767
  }
134768
+ const chunkIds = globalSingleton("@workflow/world-local//streamerMonotonicUlid", 1, () => ({ next: monotonicFactory(() => Math.random()) }));
134769
+ const monotonicUlid = (seedTime) => chunkIds.next(seedTime);
134770
+ const RunStreamsSchema = object$1({
134771
+ streams: array$1(string$3())
134772
+ });
134773
+ const EOF_MARKER = 1;
134774
+ function isEofByte(byte) {
134775
+ return byte === EOF_MARKER;
134776
+ }
134777
+ function serializeChunk(chunk) {
134778
+ const eofByte = Buffer.from([chunk.eof ? EOF_MARKER : 0]);
134779
+ return Buffer.concat([eofByte, chunk.chunk]);
134780
+ }
134781
+ function isEofChunk(serialized) {
134782
+ return isEofByte(serialized[0]);
134783
+ }
134784
+ function deserializeChunk(serialized) {
134785
+ const eof = isEofChunk(serialized);
134786
+ const chunk = Buffer.from(serialized.subarray(1));
134787
+ return { eof, chunk };
134788
+ }
134789
+ async function listChunkEntries(chunksDir) {
134790
+ try {
134791
+ return await fs$1.readdir(chunksDir);
134792
+ } catch (error2) {
134793
+ if (error2.code === "ENOENT")
134794
+ return [];
134795
+ throw error2;
134796
+ }
134797
+ }
134798
+ function addChunkFilesByExtension(extMap, entries, sourceExtension, fileExtension = sourceExtension, include = () => true) {
134799
+ for (const entry2 of entries) {
134800
+ if (!entry2.endsWith(sourceExtension))
134801
+ continue;
134802
+ const file2 = entry2.slice(0, -sourceExtension.length);
134803
+ if (include(file2))
134804
+ extMap.set(file2, fileExtension);
134805
+ }
134806
+ }
134807
+ function chunkDirForStream(chunksBaseDir, name2) {
134808
+ assertSafeEntityId("streamName", name2);
134809
+ return path$3.join(chunksBaseDir, name2);
134810
+ }
134811
+ async function listChunkFilesForStream(chunksBaseDir, name2, tag) {
134812
+ const dir = chunkDirForStream(chunksBaseDir, name2);
134813
+ const entries = await listChunkEntries(dir);
134814
+ const extMap = /* @__PURE__ */ new Map();
134815
+ addChunkFilesByExtension(extMap, entries, ".json");
134816
+ addChunkFilesByExtension(extMap, entries, ".bin", ".bin", tag ? (file2) => !file2.endsWith(`.${tag}`) : void 0);
134817
+ if (tag) {
134818
+ const taggedExtension = `.${tag}.bin`;
134819
+ addChunkFilesByExtension(extMap, entries, taggedExtension);
134820
+ }
134821
+ const files = [...extMap.keys()].sort();
134822
+ return { files, extMap, dir };
134823
+ }
134824
+ const PURGED_STREAM_TOMBSTONE_ID = `chnk_${"0".repeat(26)}`;
134825
+ async function purgeRunStreamData(basedir, runId, tag) {
134826
+ const chunksBaseDir = path$3.join(basedir, "streams", "chunks");
134827
+ const tagSuffix = tag ? `.${tag}` : "";
134828
+ let names;
134829
+ try {
134830
+ assertSafeEntityId("runId", runId);
134831
+ const mapping = await readJSONWithFallback(basedir, "streams/runs", runId, RunStreamsSchema, tag);
134832
+ names = (mapping == null ? void 0 : mapping.streams) ?? [];
134833
+ } catch (error2) {
134834
+ logStreamPurgeFailure(`streams of ${runId}`, error2);
134835
+ return;
134836
+ }
134837
+ for (const name2 of names) {
134838
+ try {
134839
+ const dir = chunkDirForStream(chunksBaseDir, name2);
134840
+ await write(path$3.join(dir, `${PURGED_STREAM_TOMBSTONE_ID}${tagSuffix}.bin`), serializeChunk({ chunk: Buffer.from([]), eof: true }), { overwrite: true });
134841
+ for (const entry2 of await listChunkEntries(dir)) {
134842
+ if (entry2.startsWith(PURGED_STREAM_TOMBSTONE_ID))
134843
+ continue;
134844
+ if (!entry2.endsWith(".bin") && !entry2.endsWith(".json"))
134845
+ continue;
134846
+ await withWindowsRetry(() => fs$1.unlink(path$3.join(dir, entry2))).catch((error2) => {
134847
+ if (error2.code !== "ENOENT")
134848
+ logStreamPurgeFailure(entry2, error2);
134849
+ });
134850
+ }
134851
+ } catch (error2) {
134852
+ logStreamPurgeFailure(name2, error2);
134853
+ }
134854
+ }
134855
+ }
134856
+ function logStreamPurgeFailure(target2, error2) {
134857
+ console.warn(`[world-local] Failed to purge stream data for ${target2}:`, error2 instanceof Error ? error2.message : error2);
134858
+ }
134859
+ function createStreamer$1(basedir, tag) {
134860
+ const tagSuffix = tag ? `.${tag}` : "";
134861
+ const streamEmitter = new EventEmitter();
134862
+ const registeredStreams = /* @__PURE__ */ new Set();
134863
+ async function registerStreamForRun(runId, streamName) {
134864
+ assertSafeEntityId("runId", runId);
134865
+ assertSafeEntityId("streamName", streamName);
134866
+ const cacheKey = `${runId}:${streamName}`;
134867
+ if (registeredStreams.has(cacheKey)) {
134868
+ return;
134869
+ }
134870
+ const runStreamsPath = taggedPath(basedir, "streams/runs", runId, tag);
134871
+ const existing = await readJSONWithFallback(basedir, "streams/runs", runId, RunStreamsSchema, tag);
134872
+ const streams = (existing == null ? void 0 : existing.streams) ?? [];
134873
+ if (!streams.includes(streamName)) {
134874
+ streams.push(streamName);
134875
+ await writeJSON(runStreamsPath, { streams }, { overwrite: true });
134876
+ }
134877
+ registeredStreams.add(cacheKey);
134878
+ }
134879
+ function toBuffer(chunk) {
134880
+ if (typeof chunk === "string") {
134881
+ return Buffer.from(new TextEncoder().encode(chunk));
134882
+ } else if (chunk instanceof Buffer) {
134883
+ return chunk;
134884
+ } else {
134885
+ return Buffer.from(chunk);
134886
+ }
134887
+ }
134888
+ return {
134889
+ streams: {
134890
+ async write(_runId, name2, chunk) {
134891
+ const chunkId = `chnk_${monotonicUlid()}`;
134892
+ const runId = await _runId;
134893
+ await registerStreamForRun(runId, name2);
134894
+ const chunkBuffer = toBuffer(chunk);
134895
+ const serialized = serializeChunk({
134896
+ chunk: chunkBuffer,
134897
+ eof: false
134898
+ });
134899
+ const chunkPath = path$3.join(chunkDirForStream(path$3.join(basedir, "streams", "chunks"), name2), `${chunkId}${tagSuffix}.bin`);
134900
+ await write(chunkPath, serialized);
134901
+ const chunkData = Uint8Array.from(chunkBuffer);
134902
+ streamEmitter.emit(`chunk:${name2}`, {
134903
+ streamName: name2,
134904
+ chunkData,
134905
+ chunkId
134906
+ });
134907
+ },
134908
+ async writeMulti(_runId, name2, chunks) {
134909
+ if (chunks.length === 0)
134910
+ return;
134911
+ const chunkIds2 = chunks.map(() => `chnk_${monotonicUlid()}`);
134912
+ const runId = await _runId;
134913
+ await registerStreamForRun(runId, name2);
134914
+ const chunkBuffers = chunks.map((chunk) => toBuffer(chunk));
134915
+ const writePromises = chunkBuffers.map(async (chunkBuffer, i) => {
134916
+ const chunkId = chunkIds2[i];
134917
+ const serialized = serializeChunk({
134918
+ chunk: chunkBuffer,
134919
+ eof: false
134920
+ });
134921
+ const chunkPath = path$3.join(chunkDirForStream(path$3.join(basedir, "streams", "chunks"), name2), `${chunkId}${tagSuffix}.bin`);
134922
+ await write(chunkPath, serialized);
134923
+ return {
134924
+ chunkId,
134925
+ chunkData: Uint8Array.from(chunkBuffer)
134926
+ };
134927
+ });
134928
+ for (const writePromise of writePromises) {
134929
+ const { chunkId, chunkData } = await writePromise;
134930
+ streamEmitter.emit(`chunk:${name2}`, {
134931
+ streamName: name2,
134932
+ chunkData,
134933
+ chunkId
134934
+ });
134935
+ }
134936
+ },
134937
+ async close(_runId, name2) {
134938
+ const chunkId = `chnk_${monotonicUlid()}`;
134939
+ const runId = await _runId;
134940
+ await registerStreamForRun(runId, name2);
134941
+ const chunkPath = path$3.join(chunkDirForStream(path$3.join(basedir, "streams", "chunks"), name2), `${chunkId}${tagSuffix}.bin`);
134942
+ await write(chunkPath, serializeChunk({ chunk: Buffer.from([]), eof: true }));
134943
+ streamEmitter.emit(`close:${name2}`, { streamName: name2 });
134944
+ },
134945
+ async list(runId) {
134946
+ assertSafeEntityId("runId", runId);
134947
+ const data = await readJSONWithFallback(basedir, "streams/runs", runId, RunStreamsSchema, tag);
134948
+ return (data == null ? void 0 : data.streams) ?? [];
134949
+ },
134950
+ async getChunks(_runId, name2, options) {
134951
+ const limit = (options == null ? void 0 : options.limit) ?? 100;
134952
+ const chunksBaseDir = path$3.join(basedir, "streams", "chunks");
134953
+ const { files: chunkFiles, extMap: fileExtMap, dir: chunksDir } = await listChunkFilesForStream(chunksBaseDir, name2, tag);
134954
+ let startIndex = 0;
134955
+ if (options == null ? void 0 : options.cursor) {
134956
+ try {
134957
+ const decoded = JSON.parse(Buffer.from(options.cursor, "base64").toString("utf-8"));
134958
+ startIndex = decoded.i;
134959
+ } catch {
134960
+ startIndex = 0;
134961
+ }
134962
+ }
134963
+ let streamDone = false;
134964
+ const resultChunks = [];
134965
+ let dataIndex = 0;
134966
+ for (const file2 of chunkFiles) {
134967
+ const ext2 = fileExtMap.get(file2) ?? ".bin";
134968
+ const filePath = path$3.join(chunksDir, `${file2}${ext2}`);
134969
+ if (dataIndex < startIndex) {
134970
+ if (isEofByte(await readFirstByte(filePath))) {
134971
+ streamDone = true;
134972
+ break;
134973
+ }
134974
+ dataIndex++;
134975
+ continue;
134976
+ }
134977
+ if (resultChunks.length >= limit) {
134978
+ if (isEofByte(await readFirstByte(filePath))) {
134979
+ streamDone = true;
134980
+ } else {
134981
+ dataIndex++;
134982
+ }
134983
+ break;
134984
+ }
134985
+ const chunk = deserializeChunk(await readBuffer(filePath));
134986
+ if (chunk.eof) {
134987
+ streamDone = true;
134988
+ break;
134989
+ }
134990
+ resultChunks.push({
134991
+ index: dataIndex,
134992
+ data: Uint8Array.from(chunk.chunk)
134993
+ });
134994
+ dataIndex++;
134995
+ }
134996
+ const hasMore = !streamDone && dataIndex > startIndex + resultChunks.length;
134997
+ const nextIndex = startIndex + resultChunks.length;
134998
+ const nextCursor = hasMore ? Buffer.from(JSON.stringify({ i: nextIndex })).toString("base64") : null;
134999
+ return {
135000
+ data: resultChunks,
135001
+ cursor: nextCursor,
135002
+ hasMore,
135003
+ done: streamDone
135004
+ };
135005
+ },
135006
+ async getInfo(_runId, name2) {
135007
+ const chunksBaseDir = path$3.join(basedir, "streams", "chunks");
135008
+ const { files: chunkFiles, extMap: fileExtMap, dir: chunksDir } = await listChunkFilesForStream(chunksBaseDir, name2, tag);
135009
+ let streamDone = false;
135010
+ let dataCount = 0;
135011
+ for (const file2 of chunkFiles) {
135012
+ const ext2 = fileExtMap.get(file2) ?? ".bin";
135013
+ if (isEofByte(await readFirstByte(path$3.join(chunksDir, `${file2}${ext2}`)))) {
135014
+ streamDone = true;
135015
+ break;
135016
+ }
135017
+ dataCount++;
135018
+ }
135019
+ return { tailIndex: dataCount - 1, done: streamDone };
135020
+ },
135021
+ async get(_runId, name2, startIndex = 0) {
135022
+ const chunksBaseDir = path$3.join(basedir, "streams", "chunks");
135023
+ let teardown = () => {
135024
+ };
135025
+ let pollInterval = null;
135026
+ let streamClosed = false;
135027
+ return new ReadableStream({
135028
+ async start(controller) {
135029
+ const deliveredChunkIds = /* @__PURE__ */ new Set();
135030
+ const bufferedEventChunks = [];
135031
+ let isReadingFromDisk = true;
135032
+ let pendingClose = false;
135033
+ const chunkListener = (event) => {
135034
+ if (event.chunkData.byteLength === 0) {
135035
+ deliveredChunkIds.add(event.chunkId);
135036
+ return;
135037
+ }
135038
+ if (isReadingFromDisk) {
135039
+ deliveredChunkIds.add(event.chunkId);
135040
+ bufferedEventChunks.push({
135041
+ chunkId: event.chunkId,
135042
+ chunkData: Uint8Array.from(event.chunkData)
135043
+ });
135044
+ } else if (!deliveredChunkIds.has(event.chunkId)) {
135045
+ deliveredChunkIds.add(event.chunkId);
135046
+ controller.enqueue(Uint8Array.from(event.chunkData));
135047
+ }
135048
+ };
135049
+ const closeListener = () => {
135050
+ if (isReadingFromDisk) {
135051
+ pendingClose = true;
135052
+ return;
135053
+ }
135054
+ streamClosed = true;
135055
+ teardown();
135056
+ try {
135057
+ controller.close();
135058
+ } catch {
135059
+ }
135060
+ };
135061
+ teardown = () => {
135062
+ streamEmitter.off(`chunk:${name2}`, chunkListener);
135063
+ streamEmitter.off(`close:${name2}`, closeListener);
135064
+ if (pollInterval) {
135065
+ clearInterval(pollInterval);
135066
+ pollInterval = null;
135067
+ }
135068
+ };
135069
+ streamEmitter.on(`chunk:${name2}`, chunkListener);
135070
+ streamEmitter.on(`close:${name2}`, closeListener);
135071
+ const { files: chunkFiles, extMap: fileExtMap, dir: chunksDir } = await listChunkFilesForStream(chunksBaseDir, name2, tag);
135072
+ let dataChunkCount = chunkFiles.length;
135073
+ if (typeof startIndex === "number" && startIndex < 0 && chunkFiles.length > 0) {
135074
+ const lastFile = chunkFiles[chunkFiles.length - 1];
135075
+ const lastExt = fileExtMap.get(lastFile) ?? ".bin";
135076
+ if (isEofByte(await readFirstByte(path$3.join(chunksDir, `${lastFile}${lastExt}`)))) {
135077
+ dataChunkCount--;
135078
+ }
135079
+ }
135080
+ const resolvedStartIndex = typeof startIndex === "number" && startIndex < 0 ? Math.max(0, dataChunkCount + startIndex) : startIndex;
135081
+ let isComplete = false;
135082
+ for (let i = resolvedStartIndex; i < chunkFiles.length; i++) {
135083
+ const file2 = chunkFiles[i];
135084
+ const chunkId = file2;
135085
+ if (deliveredChunkIds.has(chunkId)) {
135086
+ continue;
135087
+ }
135088
+ const ext2 = fileExtMap.get(file2) ?? ".bin";
135089
+ const chunk = deserializeChunk(await readBuffer(path$3.join(chunksDir, `${file2}${ext2}`)));
135090
+ if ((chunk == null ? void 0 : chunk.eof) === true) {
135091
+ isComplete = true;
135092
+ break;
135093
+ }
135094
+ deliveredChunkIds.add(chunkId);
135095
+ if (chunk.chunk.byteLength) {
135096
+ controller.enqueue(Uint8Array.from(chunk.chunk));
135097
+ }
135098
+ }
135099
+ isReadingFromDisk = false;
135100
+ bufferedEventChunks.sort((a2, b2) => a2.chunkId.localeCompare(b2.chunkId));
135101
+ for (const buffered of bufferedEventChunks) {
135102
+ controller.enqueue(Uint8Array.from(buffered.chunkData));
135103
+ }
135104
+ if (isComplete) {
135105
+ streamClosed = true;
135106
+ teardown();
135107
+ try {
135108
+ controller.close();
135109
+ } catch {
135110
+ }
135111
+ return;
135112
+ }
135113
+ if (pendingClose) {
135114
+ streamClosed = true;
135115
+ teardown();
135116
+ try {
135117
+ controller.close();
135118
+ } catch {
135119
+ }
135120
+ return;
135121
+ }
135122
+ for (let i = 0; i < resolvedStartIndex && i < chunkFiles.length; i++) {
135123
+ deliveredChunkIds.add(chunkFiles[i]);
135124
+ }
135125
+ if (streamClosed) {
135126
+ teardown();
135127
+ return;
135128
+ }
135129
+ let isPolling = false;
135130
+ pollInterval = setInterval(async () => {
135131
+ if (isPolling)
135132
+ return;
135133
+ isPolling = true;
135134
+ try {
135135
+ const { files: currentFiles, extMap: currentExtMap } = await listChunkFilesForStream(chunksBaseDir, name2, tag);
135136
+ for (const file2 of currentFiles) {
135137
+ const chunkId = file2;
135138
+ if (deliveredChunkIds.has(chunkId))
135139
+ continue;
135140
+ deliveredChunkIds.add(chunkId);
135141
+ const ext2 = currentExtMap.get(file2) ?? ".bin";
135142
+ const chunk = deserializeChunk(await readBuffer(path$3.join(chunksDir, `${file2}${ext2}`)));
135143
+ if ((chunk == null ? void 0 : chunk.eof) === true) {
135144
+ streamClosed = true;
135145
+ teardown();
135146
+ try {
135147
+ controller.close();
135148
+ } catch {
135149
+ }
135150
+ return;
135151
+ }
135152
+ if (streamClosed)
135153
+ return;
135154
+ if (chunk.chunk.byteLength) {
135155
+ controller.enqueue(Uint8Array.from(chunk.chunk));
135156
+ }
135157
+ }
135158
+ } catch (err) {
135159
+ if (!(err instanceof Error && "code" in err)) {
135160
+ console.error("[world-local] Unexpected polling error:", err);
135161
+ }
135162
+ } finally {
135163
+ isPolling = false;
135164
+ }
135165
+ }, 100);
135166
+ },
135167
+ cancel() {
135168
+ streamClosed = true;
135169
+ teardown();
135170
+ }
135171
+ });
135172
+ }
135173
+ }
135174
+ };
135175
+ }
135176
+ function purgesUserDataOnFinish(attributes) {
135177
+ const retention = readRunRetention(attributes);
135178
+ if (retention.unsupported) {
135179
+ console.warn(`[world-local] Ignoring unrecognized ${RETENTION_ATTRIBUTE} value ${JSON.stringify(retention.raw)}; keeping the run's data.`);
135180
+ }
135181
+ return retention.mode === "none";
135182
+ }
135183
+ function withRunPayloadsPurged(run2, purgedAt) {
135184
+ return {
135185
+ ...run2,
135186
+ input: void 0,
135187
+ output: void 0,
135188
+ error: void 0,
135189
+ expiredAt: purgedAt
135190
+ };
135191
+ }
135192
+ async function purgeRunEntityData(basedir, runId, tag) {
135193
+ await Promise.all([
135194
+ scrubEntityFiles(path$3.join(basedir, "steps"), runId, (step) => {
135195
+ step.input = void 0;
135196
+ step.output = void 0;
135197
+ step.error = void 0;
135198
+ }),
135199
+ scrubEntityFiles(path$3.join(basedir, "events"), runId, (event) => {
135200
+ const eventData = event.eventData;
135201
+ if (!eventData || typeof eventData !== "object")
135202
+ return;
135203
+ for (const field of getEventDataRefFields(String(event.eventType))) {
135204
+ delete eventData[field];
135205
+ }
135206
+ }),
135207
+ scrubHookMetadata(basedir, runId),
135208
+ purgeRunStreamData(basedir, runId, tag)
135209
+ ]);
135210
+ }
135211
+ const RawEntitySchema = record(string$3(), any());
135212
+ async function scrubEntityFiles(directory, runId, scrub) {
135213
+ let fileIds;
135214
+ try {
135215
+ fileIds = await listJSONFiles(directory);
135216
+ } catch (error2) {
135217
+ logPurgeFailure(directory, error2);
135218
+ return;
135219
+ }
135220
+ for (const fileId of fileIds) {
135221
+ if (!fileId.startsWith(`${runId}-`))
135222
+ continue;
135223
+ const filePath = path$3.join(directory, `${fileId}.json`);
135224
+ try {
135225
+ const raw2 = await readJSON(filePath, RawEntitySchema);
135226
+ if (!raw2)
135227
+ continue;
135228
+ scrub(raw2);
135229
+ await writeJSON(filePath, raw2, { overwrite: true });
135230
+ } catch (error2) {
135231
+ logPurgeFailure(filePath, error2);
135232
+ }
135233
+ }
135234
+ }
135235
+ async function scrubHookMetadata(basedir, runId) {
135236
+ let markers;
135237
+ try {
135238
+ await ensureHookIndexes(basedir);
135239
+ markers = await listHookByRunMarkers(basedir, runId);
135240
+ } catch (error2) {
135241
+ logPurgeFailure(`hooks of ${runId}`, error2);
135242
+ return;
135243
+ }
135244
+ for (const marker of markers) {
135245
+ if (!marker.hookId)
135246
+ continue;
135247
+ try {
135248
+ const hookPath = taggedPath(basedir, "hooks", marker.hookId, marker.tag);
135249
+ const hook = await readJSON(hookPath, RawEntitySchema);
135250
+ if (!hook || hook.runId !== runId)
135251
+ continue;
135252
+ hook.metadata = void 0;
135253
+ await writeJSON(hookPath, hook, { overwrite: true });
135254
+ } catch (error2) {
135255
+ logPurgeFailure(marker.hookId, error2);
135256
+ }
135257
+ }
135258
+ }
135259
+ function logPurgeFailure(target2, error2) {
135260
+ console.warn(`[world-local] Failed to purge user data for ${target2}:`, error2 instanceof Error ? error2.message : error2);
135261
+ }
134515
135262
  const emitter = new EventEmitter();
134516
135263
  emitter.setMaxListeners(0);
134517
135264
  const RUN_STATUS_POLL_INTERVAL_MS = 100;
@@ -134585,13 +135332,18 @@ async function handleLegacyEvent(basedir, runId, data, currentRun, params) {
134585
135332
  updatedAt: now2,
134586
135333
  attributes: currentRun.attributes
134587
135334
  };
135335
+ const purged = purgesUserDataOnFinish(run2.attributes);
135336
+ const stored = purged ? withRunPayloadsPurged(run2, now2) : run2;
134588
135337
  const runPath = resolveWithinBase(basedir, "runs", `${runId}.json`);
134589
- await writeJSON(runPath, run2, { overwrite: true });
135338
+ await writeJSON(runPath, stored, { overwrite: true });
134590
135339
  signalRunTerminal(runId);
134591
135340
  await deleteAllHooksForRun(basedir, runId);
135341
+ if (purged) {
135342
+ await purgeRunEntityData(basedir, runId, void 0);
135343
+ }
134592
135344
  return {
134593
135345
  event: void 0,
134594
- run: filterRunData$1(run2, resolveData)
135346
+ run: filterRunData$1(stored, resolveData)
134595
135347
  };
134596
135348
  }
134597
135349
  case "wait_completed":
@@ -134891,17 +135643,19 @@ async function deleteAllWaitsForRun(basedir, runId) {
134891
135643
  async function writeRunUnderLifecycleLock(basedir, runId, tag, proposed) {
134892
135644
  return withRunFileLock(runId, async () => {
134893
135645
  const fresh = await readJSON(taggedPath(basedir, "runs", runId, tag), WorkflowRunSchema);
134894
- const next2 = {
134895
- ...proposed,
134896
- attributes: (fresh == null ? void 0 : fresh.attributes) ?? proposed.attributes
134897
- };
135646
+ const attributes = (fresh == null ? void 0 : fresh.attributes) ?? proposed.attributes;
135647
+ let next2 = { ...proposed, attributes };
135648
+ const purged = isTerminalWorkflowRunStatus(next2.status) && purgesUserDataOnFinish(attributes);
135649
+ if (purged) {
135650
+ next2 = withRunPayloadsPurged(next2, /* @__PURE__ */ new Date());
135651
+ }
134898
135652
  await writeJSON(taggedPath(basedir, "runs", runId, tag), next2, {
134899
135653
  overwrite: true
134900
135654
  });
134901
135655
  if (isTerminalWorkflowRunStatus(next2.status)) {
134902
135656
  signalRunTerminal(runId);
134903
135657
  }
134904
- return next2;
135658
+ return { run: next2, purged };
134905
135659
  });
134906
135660
  }
134907
135661
  function createEventsStorage(basedir, tag) {
@@ -135328,6 +136082,7 @@ function createEventsStorage(basedir, tag) {
135328
136082
  event = { ...event, eventData };
135329
136083
  }
135330
136084
  let run2;
136085
+ let runPurged = false;
135331
136086
  let step;
135332
136087
  let hook;
135333
136088
  let wait;
@@ -135391,7 +136146,7 @@ function createEventsStorage(basedir, tag) {
135391
136146
  maxEvents: getMaxEventsPerRun()
135392
136147
  };
135393
136148
  }
135394
- run2 = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
136149
+ const written = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
135395
136150
  runId: currentRun.runId,
135396
136151
  deploymentId: currentRun.deploymentId,
135397
136152
  workflowName: currentRun.workflowName,
@@ -135409,11 +136164,13 @@ function createEventsStorage(basedir, tag) {
135409
136164
  attributes: currentRun.attributes,
135410
136165
  encryptionPublicKey: currentRun.encryptionPublicKey
135411
136166
  });
136167
+ run2 = written.run;
136168
+ runPurged = written.purged;
135412
136169
  }
135413
136170
  } else if (data.eventType === "run_completed" && "eventData" in data) {
135414
136171
  const completedData = data.eventData;
135415
136172
  if (currentRun) {
135416
- run2 = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
136173
+ const written = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
135417
136174
  runId: currentRun.runId,
135418
136175
  deploymentId: currentRun.deploymentId,
135419
136176
  workflowName: currentRun.workflowName,
@@ -135431,6 +136188,8 @@ function createEventsStorage(basedir, tag) {
135431
136188
  attributes: currentRun.attributes,
135432
136189
  encryptionPublicKey: currentRun.encryptionPublicKey
135433
136190
  });
136191
+ run2 = written.run;
136192
+ runPurged = written.purged;
135434
136193
  await Promise.all([
135435
136194
  deleteAllHooksForRun(basedir, effectiveRunId),
135436
136195
  deleteAllWaitsForRun(basedir, effectiveRunId)
@@ -135439,7 +136198,7 @@ function createEventsStorage(basedir, tag) {
135439
136198
  } else if (data.eventType === "run_failed" && "eventData" in data) {
135440
136199
  const failedData = data.eventData;
135441
136200
  if (currentRun) {
135442
- run2 = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
136201
+ const written = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
135443
136202
  runId: currentRun.runId,
135444
136203
  deploymentId: currentRun.deploymentId,
135445
136204
  workflowName: currentRun.workflowName,
@@ -135458,6 +136217,8 @@ function createEventsStorage(basedir, tag) {
135458
136217
  attributes: currentRun.attributes,
135459
136218
  encryptionPublicKey: currentRun.encryptionPublicKey
135460
136219
  });
136220
+ run2 = written.run;
136221
+ runPurged = written.purged;
135461
136222
  await Promise.all([
135462
136223
  deleteAllHooksForRun(basedir, effectiveRunId),
135463
136224
  deleteAllWaitsForRun(basedir, effectiveRunId)
@@ -135465,7 +136226,7 @@ function createEventsStorage(basedir, tag) {
135465
136226
  }
135466
136227
  } else if (data.eventType === "run_cancelled") {
135467
136228
  if (currentRun) {
135468
- run2 = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
136229
+ const written = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
135469
136230
  runId: currentRun.runId,
135470
136231
  deploymentId: currentRun.deploymentId,
135471
136232
  workflowName: currentRun.workflowName,
@@ -135483,6 +136244,8 @@ function createEventsStorage(basedir, tag) {
135483
136244
  attributes: currentRun.attributes,
135484
136245
  encryptionPublicKey: currentRun.encryptionPublicKey
135485
136246
  });
136247
+ run2 = written.run;
136248
+ runPurged = written.purged;
135486
136249
  await Promise.all([
135487
136250
  deleteAllHooksForRun(basedir, effectiveRunId),
135488
136251
  deleteAllWaitsForRun(basedir, effectiveRunId)
@@ -135754,12 +136517,24 @@ function createEventsStorage(basedir, tag) {
135754
136517
  };
135755
136518
  const storedConflict = await storeEvent(conflictEvent);
135756
136519
  const resolveData2 = (params == null ? void 0 : params.resolveData) ?? DEFAULT_RESOLVE_DATA_OPTION$1;
135757
- return {
136520
+ const conflictDelta = typeof (params == null ? void 0 : params.sinceCursor) === "string" ? await queryRunEvents(effectiveRunId, {
136521
+ sortOrder: "asc",
136522
+ cursor: params.sinceCursor
136523
+ }) : void 0;
136524
+ const conflictResult = {
135758
136525
  event: stripEventDataRefs(storedConflict, resolveData2),
135759
136526
  run: run2,
135760
136527
  step,
135761
136528
  hook: void 0
135762
136529
  };
136530
+ if (!conflictDelta)
136531
+ return conflictResult;
136532
+ return {
136533
+ ...conflictResult,
136534
+ events: resolveData2 === "none" ? conflictDelta.data.map((delta) => stripEventDataRefs(delta, resolveData2)) : conflictDelta.data,
136535
+ cursor: conflictDelta.cursor,
136536
+ hasMore: conflictDelta.hasMore
136537
+ };
135763
136538
  }
135764
136539
  const persistedHookData = event.eventData;
135765
136540
  hook = {
@@ -135924,6 +136699,10 @@ function createEventsStorage(basedir, tag) {
135924
136699
  await writeHookByRunMarker(basedir, hook.runId, hook.hookId, tag);
135925
136700
  await writeJSON(taggedPath(basedir, "hooks", hook.hookId, tag), hook, hookEntityWriteOptions);
135926
136701
  }
136702
+ if (runPurged) {
136703
+ await purgeRunEntityData(basedir, effectiveRunId, tag);
136704
+ clearRunCache(effectiveRunId);
136705
+ }
135927
136706
  const resolveData = (params == null ? void 0 : params.resolveData) ?? DEFAULT_RESOLVE_DATA_OPTION$1;
135928
136707
  const filteredEvent = stripEventDataRefs(event, resolveData);
135929
136708
  let eventPage;
@@ -136122,379 +136901,6 @@ function createStorage$1(basedir, tag) {
136122
136901
  clearCache: () => events2.clearCache()
136123
136902
  };
136124
136903
  }
136125
- const chunkIds = globalSingleton("@workflow/world-local//streamerMonotonicUlid", 1, () => ({ next: monotonicFactory(() => Math.random()) }));
136126
- const monotonicUlid = (seedTime) => chunkIds.next(seedTime);
136127
- const RunStreamsSchema = object$1({
136128
- streams: array$1(string$3())
136129
- });
136130
- const EOF_MARKER = 1;
136131
- function isEofByte(byte) {
136132
- return byte === EOF_MARKER;
136133
- }
136134
- function serializeChunk(chunk) {
136135
- const eofByte = Buffer.from([chunk.eof ? EOF_MARKER : 0]);
136136
- return Buffer.concat([eofByte, chunk.chunk]);
136137
- }
136138
- function isEofChunk(serialized) {
136139
- return isEofByte(serialized[0]);
136140
- }
136141
- function deserializeChunk(serialized) {
136142
- const eof = isEofChunk(serialized);
136143
- const chunk = Buffer.from(serialized.subarray(1));
136144
- return { eof, chunk };
136145
- }
136146
- async function listChunkEntries(chunksDir) {
136147
- try {
136148
- return await fs$1.readdir(chunksDir);
136149
- } catch (error2) {
136150
- if (error2.code === "ENOENT")
136151
- return [];
136152
- throw error2;
136153
- }
136154
- }
136155
- function addChunkFilesByExtension(extMap, entries, sourceExtension, fileExtension = sourceExtension, include = () => true) {
136156
- for (const entry2 of entries) {
136157
- if (!entry2.endsWith(sourceExtension))
136158
- continue;
136159
- const file2 = entry2.slice(0, -sourceExtension.length);
136160
- if (include(file2))
136161
- extMap.set(file2, fileExtension);
136162
- }
136163
- }
136164
- function chunkDirForStream(chunksBaseDir, name2) {
136165
- assertSafeEntityId("streamName", name2);
136166
- return path$3.join(chunksBaseDir, name2);
136167
- }
136168
- async function listChunkFilesForStream(chunksBaseDir, name2, tag) {
136169
- const dir = chunkDirForStream(chunksBaseDir, name2);
136170
- const entries = await listChunkEntries(dir);
136171
- const extMap = /* @__PURE__ */ new Map();
136172
- addChunkFilesByExtension(extMap, entries, ".json");
136173
- addChunkFilesByExtension(extMap, entries, ".bin", ".bin", tag ? (file2) => !file2.endsWith(`.${tag}`) : void 0);
136174
- if (tag) {
136175
- const taggedExtension = `.${tag}.bin`;
136176
- addChunkFilesByExtension(extMap, entries, taggedExtension);
136177
- }
136178
- const files = [...extMap.keys()].sort();
136179
- return { files, extMap, dir };
136180
- }
136181
- function createStreamer$1(basedir, tag) {
136182
- const tagSuffix = tag ? `.${tag}` : "";
136183
- const streamEmitter = new EventEmitter();
136184
- const registeredStreams = /* @__PURE__ */ new Set();
136185
- async function registerStreamForRun(runId, streamName) {
136186
- assertSafeEntityId("runId", runId);
136187
- assertSafeEntityId("streamName", streamName);
136188
- const cacheKey = `${runId}:${streamName}`;
136189
- if (registeredStreams.has(cacheKey)) {
136190
- return;
136191
- }
136192
- const runStreamsPath = taggedPath(basedir, "streams/runs", runId, tag);
136193
- const existing = await readJSONWithFallback(basedir, "streams/runs", runId, RunStreamsSchema, tag);
136194
- const streams = (existing == null ? void 0 : existing.streams) ?? [];
136195
- if (!streams.includes(streamName)) {
136196
- streams.push(streamName);
136197
- await writeJSON(runStreamsPath, { streams }, { overwrite: true });
136198
- }
136199
- registeredStreams.add(cacheKey);
136200
- }
136201
- function toBuffer(chunk) {
136202
- if (typeof chunk === "string") {
136203
- return Buffer.from(new TextEncoder().encode(chunk));
136204
- } else if (chunk instanceof Buffer) {
136205
- return chunk;
136206
- } else {
136207
- return Buffer.from(chunk);
136208
- }
136209
- }
136210
- return {
136211
- streams: {
136212
- async write(_runId, name2, chunk) {
136213
- const chunkId = `chnk_${monotonicUlid()}`;
136214
- const runId = await _runId;
136215
- await registerStreamForRun(runId, name2);
136216
- const chunkBuffer = toBuffer(chunk);
136217
- const serialized = serializeChunk({
136218
- chunk: chunkBuffer,
136219
- eof: false
136220
- });
136221
- const chunkPath = path$3.join(chunkDirForStream(path$3.join(basedir, "streams", "chunks"), name2), `${chunkId}${tagSuffix}.bin`);
136222
- await write(chunkPath, serialized);
136223
- const chunkData = Uint8Array.from(chunkBuffer);
136224
- streamEmitter.emit(`chunk:${name2}`, {
136225
- streamName: name2,
136226
- chunkData,
136227
- chunkId
136228
- });
136229
- },
136230
- async writeMulti(_runId, name2, chunks) {
136231
- if (chunks.length === 0)
136232
- return;
136233
- const chunkIds2 = chunks.map(() => `chnk_${monotonicUlid()}`);
136234
- const runId = await _runId;
136235
- await registerStreamForRun(runId, name2);
136236
- const chunkBuffers = chunks.map((chunk) => toBuffer(chunk));
136237
- const writePromises = chunkBuffers.map(async (chunkBuffer, i) => {
136238
- const chunkId = chunkIds2[i];
136239
- const serialized = serializeChunk({
136240
- chunk: chunkBuffer,
136241
- eof: false
136242
- });
136243
- const chunkPath = path$3.join(chunkDirForStream(path$3.join(basedir, "streams", "chunks"), name2), `${chunkId}${tagSuffix}.bin`);
136244
- await write(chunkPath, serialized);
136245
- return {
136246
- chunkId,
136247
- chunkData: Uint8Array.from(chunkBuffer)
136248
- };
136249
- });
136250
- for (const writePromise of writePromises) {
136251
- const { chunkId, chunkData } = await writePromise;
136252
- streamEmitter.emit(`chunk:${name2}`, {
136253
- streamName: name2,
136254
- chunkData,
136255
- chunkId
136256
- });
136257
- }
136258
- },
136259
- async close(_runId, name2) {
136260
- const chunkId = `chnk_${monotonicUlid()}`;
136261
- const runId = await _runId;
136262
- await registerStreamForRun(runId, name2);
136263
- const chunkPath = path$3.join(chunkDirForStream(path$3.join(basedir, "streams", "chunks"), name2), `${chunkId}${tagSuffix}.bin`);
136264
- await write(chunkPath, serializeChunk({ chunk: Buffer.from([]), eof: true }));
136265
- streamEmitter.emit(`close:${name2}`, { streamName: name2 });
136266
- },
136267
- async list(runId) {
136268
- assertSafeEntityId("runId", runId);
136269
- const data = await readJSONWithFallback(basedir, "streams/runs", runId, RunStreamsSchema, tag);
136270
- return (data == null ? void 0 : data.streams) ?? [];
136271
- },
136272
- async getChunks(_runId, name2, options) {
136273
- const limit = (options == null ? void 0 : options.limit) ?? 100;
136274
- const chunksBaseDir = path$3.join(basedir, "streams", "chunks");
136275
- const { files: chunkFiles, extMap: fileExtMap, dir: chunksDir } = await listChunkFilesForStream(chunksBaseDir, name2, tag);
136276
- let startIndex = 0;
136277
- if (options == null ? void 0 : options.cursor) {
136278
- try {
136279
- const decoded = JSON.parse(Buffer.from(options.cursor, "base64").toString("utf-8"));
136280
- startIndex = decoded.i;
136281
- } catch {
136282
- startIndex = 0;
136283
- }
136284
- }
136285
- let streamDone = false;
136286
- const resultChunks = [];
136287
- let dataIndex = 0;
136288
- for (const file2 of chunkFiles) {
136289
- const ext2 = fileExtMap.get(file2) ?? ".bin";
136290
- const filePath = path$3.join(chunksDir, `${file2}${ext2}`);
136291
- if (dataIndex < startIndex) {
136292
- if (isEofByte(await readFirstByte(filePath))) {
136293
- streamDone = true;
136294
- break;
136295
- }
136296
- dataIndex++;
136297
- continue;
136298
- }
136299
- if (resultChunks.length >= limit) {
136300
- if (isEofByte(await readFirstByte(filePath))) {
136301
- streamDone = true;
136302
- } else {
136303
- dataIndex++;
136304
- }
136305
- break;
136306
- }
136307
- const chunk = deserializeChunk(await readBuffer(filePath));
136308
- if (chunk.eof) {
136309
- streamDone = true;
136310
- break;
136311
- }
136312
- resultChunks.push({
136313
- index: dataIndex,
136314
- data: Uint8Array.from(chunk.chunk)
136315
- });
136316
- dataIndex++;
136317
- }
136318
- const hasMore = !streamDone && dataIndex > startIndex + resultChunks.length;
136319
- const nextIndex = startIndex + resultChunks.length;
136320
- const nextCursor = hasMore ? Buffer.from(JSON.stringify({ i: nextIndex })).toString("base64") : null;
136321
- return {
136322
- data: resultChunks,
136323
- cursor: nextCursor,
136324
- hasMore,
136325
- done: streamDone
136326
- };
136327
- },
136328
- async getInfo(_runId, name2) {
136329
- const chunksBaseDir = path$3.join(basedir, "streams", "chunks");
136330
- const { files: chunkFiles, extMap: fileExtMap, dir: chunksDir } = await listChunkFilesForStream(chunksBaseDir, name2, tag);
136331
- let streamDone = false;
136332
- let dataCount = 0;
136333
- for (const file2 of chunkFiles) {
136334
- const ext2 = fileExtMap.get(file2) ?? ".bin";
136335
- if (isEofByte(await readFirstByte(path$3.join(chunksDir, `${file2}${ext2}`)))) {
136336
- streamDone = true;
136337
- break;
136338
- }
136339
- dataCount++;
136340
- }
136341
- return { tailIndex: dataCount - 1, done: streamDone };
136342
- },
136343
- async get(_runId, name2, startIndex = 0) {
136344
- const chunksBaseDir = path$3.join(basedir, "streams", "chunks");
136345
- let teardown = () => {
136346
- };
136347
- let pollInterval = null;
136348
- let streamClosed = false;
136349
- return new ReadableStream({
136350
- async start(controller) {
136351
- const deliveredChunkIds = /* @__PURE__ */ new Set();
136352
- const bufferedEventChunks = [];
136353
- let isReadingFromDisk = true;
136354
- let pendingClose = false;
136355
- const chunkListener = (event) => {
136356
- if (event.chunkData.byteLength === 0) {
136357
- deliveredChunkIds.add(event.chunkId);
136358
- return;
136359
- }
136360
- if (isReadingFromDisk) {
136361
- deliveredChunkIds.add(event.chunkId);
136362
- bufferedEventChunks.push({
136363
- chunkId: event.chunkId,
136364
- chunkData: Uint8Array.from(event.chunkData)
136365
- });
136366
- } else if (!deliveredChunkIds.has(event.chunkId)) {
136367
- deliveredChunkIds.add(event.chunkId);
136368
- controller.enqueue(Uint8Array.from(event.chunkData));
136369
- }
136370
- };
136371
- const closeListener = () => {
136372
- if (isReadingFromDisk) {
136373
- pendingClose = true;
136374
- return;
136375
- }
136376
- streamClosed = true;
136377
- teardown();
136378
- try {
136379
- controller.close();
136380
- } catch {
136381
- }
136382
- };
136383
- teardown = () => {
136384
- streamEmitter.off(`chunk:${name2}`, chunkListener);
136385
- streamEmitter.off(`close:${name2}`, closeListener);
136386
- if (pollInterval) {
136387
- clearInterval(pollInterval);
136388
- pollInterval = null;
136389
- }
136390
- };
136391
- streamEmitter.on(`chunk:${name2}`, chunkListener);
136392
- streamEmitter.on(`close:${name2}`, closeListener);
136393
- const { files: chunkFiles, extMap: fileExtMap, dir: chunksDir } = await listChunkFilesForStream(chunksBaseDir, name2, tag);
136394
- let dataChunkCount = chunkFiles.length;
136395
- if (typeof startIndex === "number" && startIndex < 0 && chunkFiles.length > 0) {
136396
- const lastFile = chunkFiles[chunkFiles.length - 1];
136397
- const lastExt = fileExtMap.get(lastFile) ?? ".bin";
136398
- if (isEofByte(await readFirstByte(path$3.join(chunksDir, `${lastFile}${lastExt}`)))) {
136399
- dataChunkCount--;
136400
- }
136401
- }
136402
- const resolvedStartIndex = typeof startIndex === "number" && startIndex < 0 ? Math.max(0, dataChunkCount + startIndex) : startIndex;
136403
- let isComplete = false;
136404
- for (let i = resolvedStartIndex; i < chunkFiles.length; i++) {
136405
- const file2 = chunkFiles[i];
136406
- const chunkId = file2;
136407
- if (deliveredChunkIds.has(chunkId)) {
136408
- continue;
136409
- }
136410
- const ext2 = fileExtMap.get(file2) ?? ".bin";
136411
- const chunk = deserializeChunk(await readBuffer(path$3.join(chunksDir, `${file2}${ext2}`)));
136412
- if ((chunk == null ? void 0 : chunk.eof) === true) {
136413
- isComplete = true;
136414
- break;
136415
- }
136416
- deliveredChunkIds.add(chunkId);
136417
- if (chunk.chunk.byteLength) {
136418
- controller.enqueue(Uint8Array.from(chunk.chunk));
136419
- }
136420
- }
136421
- isReadingFromDisk = false;
136422
- bufferedEventChunks.sort((a2, b2) => a2.chunkId.localeCompare(b2.chunkId));
136423
- for (const buffered of bufferedEventChunks) {
136424
- controller.enqueue(Uint8Array.from(buffered.chunkData));
136425
- }
136426
- if (isComplete) {
136427
- streamClosed = true;
136428
- teardown();
136429
- try {
136430
- controller.close();
136431
- } catch {
136432
- }
136433
- return;
136434
- }
136435
- if (pendingClose) {
136436
- streamClosed = true;
136437
- teardown();
136438
- try {
136439
- controller.close();
136440
- } catch {
136441
- }
136442
- return;
136443
- }
136444
- for (let i = 0; i < resolvedStartIndex && i < chunkFiles.length; i++) {
136445
- deliveredChunkIds.add(chunkFiles[i]);
136446
- }
136447
- if (streamClosed) {
136448
- teardown();
136449
- return;
136450
- }
136451
- let isPolling = false;
136452
- pollInterval = setInterval(async () => {
136453
- if (isPolling)
136454
- return;
136455
- isPolling = true;
136456
- try {
136457
- const { files: currentFiles, extMap: currentExtMap } = await listChunkFilesForStream(chunksBaseDir, name2, tag);
136458
- for (const file2 of currentFiles) {
136459
- const chunkId = file2;
136460
- if (deliveredChunkIds.has(chunkId))
136461
- continue;
136462
- deliveredChunkIds.add(chunkId);
136463
- const ext2 = currentExtMap.get(file2) ?? ".bin";
136464
- const chunk = deserializeChunk(await readBuffer(path$3.join(chunksDir, `${file2}${ext2}`)));
136465
- if ((chunk == null ? void 0 : chunk.eof) === true) {
136466
- streamClosed = true;
136467
- teardown();
136468
- try {
136469
- controller.close();
136470
- } catch {
136471
- }
136472
- return;
136473
- }
136474
- if (streamClosed)
136475
- return;
136476
- if (chunk.chunk.byteLength) {
136477
- controller.enqueue(Uint8Array.from(chunk.chunk));
136478
- }
136479
- }
136480
- } catch (err) {
136481
- if (!(err instanceof Error && "code" in err)) {
136482
- console.error("[world-local] Unexpected polling error:", err);
136483
- }
136484
- } finally {
136485
- isPolling = false;
136486
- }
136487
- }, 100);
136488
- },
136489
- cancel() {
136490
- streamClosed = true;
136491
- teardown();
136492
- }
136493
- });
136494
- }
136495
- }
136496
- };
136497
- }
136498
136904
  function createWorld$2(args) {
136499
136905
  const definedArgs = args ? Object.fromEntries(Object.entries(args).filter(([, value]) => value !== void 0)) : {};
136500
136906
  const mergedConfig = { ...config.value, ...definedArgs };
@@ -136546,7 +136952,7 @@ function createWorld$2(args) {
136546
136952
  const basedir = mergedConfig.dataDir;
136547
136953
  const hooksDir = path$3.join(basedir, "hooks");
136548
136954
  const taggedHookFiles = await listTaggedFiles(hooksDir, tag);
136549
- const { HookSchema: HookSchema2 } = await import("./index-DDMGTwh_.js");
136955
+ const { HookSchema: HookSchema2 } = await import("./index-SGZlzYCB.js");
136550
136956
  await Promise.all(taggedHookFiles.map(async (hookFile) => {
136551
136957
  const hook = await readJSON(path$3.join(hooksDir, hookFile), HookSchema2);
136552
136958
  if (hook == null ? void 0 : hook.token) {
@@ -136729,8 +137135,8 @@ function requireGetVercelOidcToken() {
136729
137135
  }
136730
137136
  try {
136731
137137
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
136732
- await import("./token-util-D_gzpVW2.js").then((n) => n.t),
136733
- await import("./token-BSEhy2T4.js").then((n) => n.t)
137138
+ await import("./token-util-C4igRPyO.js").then((n) => n.t),
137139
+ await import("./token-tFJ2cDc9.js").then((n) => n.t)
136734
137140
  ]);
136735
137141
  if (!token || isExpired(getTokenPayload(token), options == null ? void 0 : options.expirationBufferMs)) {
136736
137142
  await refreshToken(options);
@@ -137293,9 +137699,10 @@ function requireDist() {
137293
137699
  return dist;
137294
137700
  }
137295
137701
  var distExports = requireDist();
137296
- const version = "5.0.0-beta.43";
137702
+ const version = "5.0.0-beta.45";
137297
137703
  const pools = globalSingleton("@workflow/world-vercel//httpPools", 1, () => ({
137298
137704
  dispatcher: void 0,
137705
+ queueDispatcher: void 0,
137299
137706
  streamDispatcher: void 0,
137300
137707
  streamCloseDispatcher: void 0,
137301
137708
  nodeHttpAgents: void 0
@@ -137316,6 +137723,64 @@ const DEFAULT_AGENT_OPTIONS = {
137316
137723
  // head-of-line blocking that deadlocks the webhook respondWith mechanism.
137317
137724
  pipelining: 1
137318
137725
  };
137726
+ const QUEUE_AGENT_CONNECTIONS = 64;
137727
+ const QUEUE_REQUEST_TIMEOUT_MS = 3e4;
137728
+ const getQueueRequestTimeoutMs = () => envNumber("WORKFLOW_VERCEL_QUEUE_TIMEOUT_MS", QUEUE_REQUEST_TIMEOUT_MS, {
137729
+ integer: true,
137730
+ min: 5e3,
137731
+ max: 12e4
137732
+ });
137733
+ function getQueueAgentOptions() {
137734
+ const timeoutMs = getQueueRequestTimeoutMs();
137735
+ return {
137736
+ ...DEFAULT_AGENT_OPTIONS,
137737
+ connections: envNumber("WORKFLOW_VERCEL_QUEUE_CONNECTIONS", QUEUE_AGENT_CONNECTIONS, { integer: true, min: 1, max: 1024 }),
137738
+ headersTimeout: timeoutMs,
137739
+ bodyTimeout: timeoutMs
137740
+ };
137741
+ }
137742
+ const ForwardingHandler = undiciExports.DecoratorHandler;
137743
+ function deadlineInterceptor(timeoutMs) {
137744
+ var _expired, _controller, _timer, _DeadlineHandler_instances, abort_fn;
137745
+ class DeadlineHandler extends ForwardingHandler {
137746
+ constructor(handler) {
137747
+ var _a3, _b2;
137748
+ super(handler);
137749
+ __privateAdd(this, _DeadlineHandler_instances);
137750
+ __privateAdd(this, _expired, false);
137751
+ __privateAdd(this, _controller);
137752
+ __privateAdd(this, _timer);
137753
+ __privateSet(this, _timer, setTimeout(() => {
137754
+ __privateSet(this, _expired, true);
137755
+ __privateMethod(this, _DeadlineHandler_instances, abort_fn).call(this);
137756
+ }, timeoutMs));
137757
+ (_b2 = (_a3 = __privateGet(this, _timer)).unref) == null ? void 0 : _b2.call(_a3);
137758
+ }
137759
+ onRequestStart(controller, context) {
137760
+ __privateSet(this, _controller, controller);
137761
+ super.onRequestStart(controller, context);
137762
+ if (__privateGet(this, _expired))
137763
+ __privateMethod(this, _DeadlineHandler_instances, abort_fn).call(this);
137764
+ }
137765
+ onResponseEnd(controller, trailers) {
137766
+ clearTimeout(__privateGet(this, _timer));
137767
+ super.onResponseEnd(controller, trailers);
137768
+ }
137769
+ onResponseError(controller, error2) {
137770
+ clearTimeout(__privateGet(this, _timer));
137771
+ super.onResponseError(controller, error2);
137772
+ }
137773
+ }
137774
+ _expired = new WeakMap();
137775
+ _controller = new WeakMap();
137776
+ _timer = new WeakMap();
137777
+ _DeadlineHandler_instances = new WeakSet();
137778
+ abort_fn = function() {
137779
+ var _a3;
137780
+ (_a3 = __privateGet(this, _controller)) == null ? void 0 : _a3.abort(new Error(`Queue request exceeded its ${timeoutMs}ms deadline`));
137781
+ };
137782
+ return (dispatch2) => (opts, handler) => dispatch2(opts, new DeadlineHandler(handler));
137783
+ }
137319
137784
  const EVENTS_AGENT_OPTIONS = {
137320
137785
  ...BASE_AGENT_OPTIONS,
137321
137786
  allowH2: true,
@@ -137495,7 +137960,7 @@ function getDispatcher(config2) {
137495
137960
  return resolveDispatcher(config2, getDefaultDispatcher);
137496
137961
  }
137497
137962
  function getQueueDispatcher(config2) {
137498
- return (config2 == null ? void 0 : config2.dispatcher) ?? getDefaultDispatcher();
137963
+ return resolveDispatcher(config2, getDefaultQueueDispatcher);
137499
137964
  }
137500
137965
  function getEventsDispatcher(config2) {
137501
137966
  return resolveDispatcher(config2, () => eventsRecycler.get());
@@ -137528,6 +137993,13 @@ function withBoundLifecycle(agent2, composed) {
137528
137993
  function createStreamDispatcher(retryOptions, agentOverrides) {
137529
137994
  return new undiciExports.RetryAgent(new undiciExports.Agent({ ...STREAM_AGENT_OPTIONS, ...agentOverrides }), retryOptions);
137530
137995
  }
137996
+ function createQueueDispatcher() {
137997
+ return new undiciExports.RetryAgent(new undiciExports.Agent(getQueueAgentOptions()).compose(deadlineInterceptor(getQueueRequestTimeoutMs())), RETRY_AGENT_OPTIONS);
137998
+ }
137999
+ function getDefaultQueueDispatcher() {
138000
+ pools.queueDispatcher ?? (pools.queueDispatcher = createQueueDispatcher());
138001
+ return pools.queueDispatcher;
138002
+ }
137531
138003
  function getDefaultDispatcher() {
137532
138004
  pools.dispatcher ?? (pools.dispatcher = makeRetryDispatcher(DEFAULT_AGENT_OPTIONS, RETRY_AGENT_OPTIONS));
137533
138005
  return pools.dispatcher;
@@ -137665,6 +138137,33 @@ const WorkflowWsUrl = SemanticConvention("workflow.events.ws.url");
137665
138137
  const WorkflowWsRequestId = SemanticConvention("workflow.events.ws.req_id");
137666
138138
  const WorkflowWsReconnectAttempt = SemanticConvention("workflow.events.ws.reconnect_attempt");
137667
138139
  const REQUEST_TIMEOUT_MS = 6e4;
138140
+ const TRANSIENT_TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
138141
+ "UND_ERR_INFO",
138142
+ "UND_ERR_REQ_RETRY",
138143
+ "UND_ERR_SOCKET",
138144
+ "UND_ERR_CONNECT",
138145
+ "UND_ERR_CONNECT_TIMEOUT",
138146
+ "UND_ERR_HEADERS_TIMEOUT",
138147
+ "UND_ERR_BODY_TIMEOUT",
138148
+ "UND_ERR_CLOSED",
138149
+ "ECONNRESET",
138150
+ "ECONNREFUSED",
138151
+ "ENOTFOUND",
138152
+ "EAI_AGAIN",
138153
+ "EPIPE",
138154
+ "ETIMEDOUT"
138155
+ ]);
138156
+ function getTransientTransportCode(error2) {
138157
+ let current = error2;
138158
+ for (let depth = 0; current && depth < 8; depth++) {
138159
+ const code2 = current.code;
138160
+ if (typeof code2 === "string" && TRANSIENT_TRANSPORT_ERROR_CODES.has(code2)) {
138161
+ return code2;
138162
+ }
138163
+ current = current.cause;
138164
+ }
138165
+ return void 0;
138166
+ }
137668
138167
  const getRequestTimeoutMs = () => envNumber("WORKFLOW_REQUEST_TIMEOUT_MS", REQUEST_TIMEOUT_MS, {
137669
138168
  integer: true,
137670
138169
  min: 1e4,
@@ -137798,10 +138297,10 @@ function recordClientSpanStatus(span, status) {
137798
138297
  }
137799
138298
  }
137800
138299
  async function instrumentedFetch(opts) {
137801
- const { method, url: url2, headers: headers2, body: body2, dispatcher: dispatcher2, peerService, timeoutMs = getRequestTimeoutMs(), signal: callerSignal, injectTraceContext: injectTraceContext2 = true, cacheBust = true, logLabel, buildError, spanName, attributes, durationAttribute, onTransportOutcome } = opts;
138300
+ const { method, url: url2, headers: headers2, body: body2, dispatcher: dispatcher2, peerService, timeoutMs = getRequestTimeoutMs(), signal: callerSignal, injectTraceContext: injectTraceContext2 = true, cacheBust = true, logLabel, buildError, spanName, attributes, durationAttribute, onTransportOutcome, deferTransportSuccessUntilBody = false, transportErrorCode = "TRANSPORT" } = opts;
137802
138301
  const label = logLabel ?? url2;
137803
138302
  return withHttpClientSpan({ method, url: url2, peerService, spanName, attributes }, async (span) => {
137804
- var _a3, _b2, _c2;
138303
+ var _a3, _b2, _c2, _d2, _e2;
137805
138304
  if (injectTraceContext2)
137806
138305
  await injectTraceContextIntoHeaders(headers2);
137807
138306
  if (cacheBust)
@@ -137839,15 +138338,36 @@ async function instrumentedFetch(opts) {
137839
138338
  const elapsed = Date.now() - start2;
137840
138339
  onTransportOutcome == null ? void 0 : onTransportOutcome(error2);
137841
138340
  if (error2 instanceof Error && (error2.name === "TimeoutError" || error2.name === "AbortError")) {
137842
- const timeoutError = new WorkflowWorldError(`${method} ${label} timed out after ${elapsed}ms`, { url: url2, cause: error2 });
137843
- span == null ? void 0 : span.setAttributes({ ...ErrorType("TIMEOUT") });
138341
+ const message2 = `${method} ${label} timed out after ${elapsed}ms`;
138342
+ const errorCode = transportErrorCode === "STREAM_ERROR" ? "STREAM_ERROR" : "TIMEOUT";
138343
+ const timeoutError = errorCode === "STREAM_ERROR" ? new StreamError(message2, { url: url2, cause: error2 }) : new WorkflowWorldError(message2, {
138344
+ url: url2,
138345
+ code: errorCode,
138346
+ cause: error2
138347
+ });
138348
+ span == null ? void 0 : span.setAttributes({ ...ErrorType(errorCode) });
137844
138349
  (_a3 = span == null ? void 0 : span.recordException) == null ? void 0 : _a3.call(span, timeoutError);
137845
138350
  throw timeoutError;
137846
138351
  }
138352
+ const transportCode = getTransientTransportCode(error2);
138353
+ if (transportCode) {
138354
+ const message2 = `${method} ${label} transport failure after ${elapsed}ms (${transportCode})`;
138355
+ const errorCode = transportErrorCode === "STREAM_ERROR" ? "STREAM_ERROR" : "TRANSPORT";
138356
+ const transportError2 = errorCode === "STREAM_ERROR" ? new StreamError(message2, { url: url2, cause: error2 }) : new WorkflowWorldError(message2, {
138357
+ url: url2,
138358
+ code: errorCode,
138359
+ cause: error2
138360
+ });
138361
+ span == null ? void 0 : span.setAttributes({ ...ErrorType(errorCode) });
138362
+ (_b2 = span == null ? void 0 : span.recordException) == null ? void 0 : _b2.call(span, transportError2);
138363
+ throw transportError2;
138364
+ }
137847
138365
  throw error2;
137848
138366
  }
137849
138367
  const ms2 = Date.now() - start2;
137850
- onTransportOutcome == null ? void 0 : onTransportOutcome();
138368
+ if (response2.ok && !deferTransportSuccessUntilBody) {
138369
+ onTransportOutcome == null ? void 0 : onTransportOutcome(void 0, response2);
138370
+ }
137851
138371
  httpLog(method, label, response2, ms2);
137852
138372
  recordClientSpanStatus(span, response2.status);
137853
138373
  if (durationAttribute)
@@ -137855,16 +138375,42 @@ async function instrumentedFetch(opts) {
137855
138375
  if (!response2.ok) {
137856
138376
  logCurlRepro(method, url2, headers2);
137857
138377
  if (buildError) {
137858
- const error3 = await buildError(response2);
137859
- (_b2 = span == null ? void 0 : span.recordException) == null ? void 0 : _b2.call(span, error3);
138378
+ let error3;
138379
+ try {
138380
+ error3 = await buildError(response2);
138381
+ } catch (cause) {
138382
+ const transportCode = getTransientTransportCode(cause);
138383
+ if (transportCode) {
138384
+ onTransportOutcome == null ? void 0 : onTransportOutcome(cause, response2);
138385
+ const message2 = `${method} ${label} response body transport failure (${transportCode})`;
138386
+ const mappedError = transportErrorCode === "STREAM_ERROR" ? new StreamError(message2, { url: url2, cause }) : new WorkflowWorldError(message2, {
138387
+ url: url2,
138388
+ code: "TRANSPORT",
138389
+ cause
138390
+ });
138391
+ span == null ? void 0 : span.setAttributes({ ...ErrorType(transportErrorCode) });
138392
+ (_c2 = span == null ? void 0 : span.recordException) == null ? void 0 : _c2.call(span, mappedError);
138393
+ throw mappedError;
138394
+ }
138395
+ onTransportOutcome == null ? void 0 : onTransportOutcome(void 0, response2);
138396
+ throw cause;
138397
+ }
138398
+ onTransportOutcome == null ? void 0 : onTransportOutcome(void 0, response2);
138399
+ (_d2 = span == null ? void 0 : span.recordException) == null ? void 0 : _d2.call(span, error3);
137860
138400
  throw error3;
137861
138401
  }
137862
- const text2 = await response2.text().catch(() => "");
138402
+ let text2 = "";
138403
+ try {
138404
+ text2 = await response2.text();
138405
+ onTransportOutcome == null ? void 0 : onTransportOutcome(void 0, response2);
138406
+ } catch (cause) {
138407
+ onTransportOutcome == null ? void 0 : onTransportOutcome(cause, response2);
138408
+ }
137863
138409
  const error2 = errorForResponse(response2.status, `${method} ${label} -> HTTP ${response2.status}: ${response2.statusText}${text2 ? ` ${text2}` : ""}${formatVercelDiagnostics(response2.headers)}`, {
137864
138410
  url: url2,
137865
138411
  retryAfter: parseRetryAfter(response2.headers.get("Retry-After"))
137866
138412
  });
137867
- (_c2 = span == null ? void 0 : span.recordException) == null ? void 0 : _c2.call(span, error2);
138413
+ (_e2 = span == null ? void 0 : span.recordException) == null ? void 0 : _e2.call(span, error2);
137868
138414
  throw error2;
137869
138415
  }
137870
138416
  return response2;
@@ -137873,34 +138419,6 @@ async function instrumentedFetch(opts) {
137873
138419
  const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
137874
138420
  const MAX_BODY_PARSE_RETRIES = 2;
137875
138421
  const BODY_PARSE_RETRY_BASE_MS = 100;
137876
- const TRANSIENT_TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
137877
- "UND_ERR_REQ_RETRY",
137878
- "UND_ERR_SOCKET",
137879
- "UND_ERR_CONNECT",
137880
- "UND_ERR_CONNECT_TIMEOUT",
137881
- "UND_ERR_HEADERS_TIMEOUT",
137882
- "UND_ERR_BODY_TIMEOUT",
137883
- "UND_ERR_CLOSED",
137884
- "ECONNRESET",
137885
- "ECONNREFUSED",
137886
- "ENOTFOUND",
137887
- "EAI_AGAIN",
137888
- "EPIPE",
137889
- "ETIMEDOUT"
137890
- ]);
137891
- function getTransientTransportCode(error2) {
137892
- let current = error2;
137893
- for (let depth = 0; current != null && depth < 5; depth++) {
137894
- if (typeof current === "object" && "code" in current) {
137895
- const code2 = current.code;
137896
- if (typeof code2 === "string" && TRANSIENT_TRANSPORT_ERROR_CODES.has(code2)) {
137897
- return code2;
137898
- }
137899
- }
137900
- current = current == null ? void 0 : current.cause;
137901
- }
137902
- return void 0;
137903
- }
137904
138422
  const getWorkflowServerUrlOverride = () => process.env.VERCEL_WORKFLOW_SERVER_URL || "";
137905
138423
  const TEST_LIMIT_OVERRIDES_HEADER = "x-workflow-test-limit-overrides";
137906
138424
  const getTestLimitOverridesHeader = () => {
@@ -138146,9 +138664,94 @@ async function parseResponseBody(response2) {
138146
138664
  getDebugContext: () => `Content-Type: ${contentType}, ${text2.length} bytes, preview: ${createPreview(data)}`
138147
138665
  };
138148
138666
  }
138149
- function appendPagination(params, pagination) {
138150
- if (pagination == null ? void 0 : pagination.limit)
138667
+ const INVALID_ARGUMENT = "INVALID_ARGUMENT";
138668
+ function invalidArgument(method, field, detail) {
138669
+ return new WorkflowWorldError(`${method}: ${field} ${detail}`, {
138670
+ code: INVALID_ARGUMENT,
138671
+ field
138672
+ });
138673
+ }
138674
+ const ULID_BODY = "[01234567][0123456789ABCDEFGHJKMNPQRSTVWXYZ]{25}";
138675
+ const RUN_ID_PATTERN = new RegExp(`^wrun_${ULID_BODY}$`);
138676
+ const CORRELATION_ID_PATTERN = new RegExp(`^(?:step|hook|wait|attr)_${ULID_BODY}$`);
138677
+ const EVENT_ID_PATTERN = new RegExp(`^evnt_${ULID_BODY}$`);
138678
+ const STEP_ID_PATTERN = new RegExp(`^step_${ULID_BODY}$`);
138679
+ const HOOK_ID_PATTERN = new RegExp(`^hook_${ULID_BODY}$`);
138680
+ const WAIT_ID_PATTERN = new RegExp(`^wait_${ULID_BODY}$`);
138681
+ function assertPageLimit(method, limit, maxLimit) {
138682
+ if (!Number.isInteger(limit) || limit < 1 || limit > maxLimit) {
138683
+ throw invalidArgument(method, "pagination.limit", `must be an integer between 1 and ${maxLimit} (received ${limit})`);
138684
+ }
138685
+ }
138686
+ function assertRunId(method, runId) {
138687
+ if (!RUN_ID_PATTERN.test(runId)) {
138688
+ throw invalidArgument(method, "runId", `must be a workflow run id ('wrun_' followed by a ULID), received ${JSON.stringify(runId)}`);
138689
+ }
138690
+ }
138691
+ function assertCorrelationId(method, correlationId) {
138692
+ if (!CORRELATION_ID_PATTERN.test(correlationId)) {
138693
+ throw invalidArgument(method, "correlationId", `must be a step, hook, wait, or attribute id, received ${JSON.stringify(correlationId)}`);
138694
+ }
138695
+ }
138696
+ function assertEventId(method, eventId) {
138697
+ if (!EVENT_ID_PATTERN.test(eventId)) {
138698
+ throw invalidArgument(method, "eventId", `must be an event id ('evnt_' followed by a ULID), received ${JSON.stringify(eventId)}`);
138699
+ }
138700
+ }
138701
+ function assertStepId(method, stepId) {
138702
+ if (!STEP_ID_PATTERN.test(stepId)) {
138703
+ throw invalidArgument(method, "stepId", `must be a step id ('step_' followed by a ULID), received ${JSON.stringify(stepId)}`);
138704
+ }
138705
+ }
138706
+ function assertHookId(method, hookId) {
138707
+ if (!HOOK_ID_PATTERN.test(hookId)) {
138708
+ throw invalidArgument(method, "hookId", `must be a hook id ('hook_' followed by a ULID), received ${JSON.stringify(hookId)}`);
138709
+ }
138710
+ }
138711
+ function assertWaitId(method, waitId) {
138712
+ if (!WAIT_ID_PATTERN.test(waitId)) {
138713
+ throw invalidArgument(method, "waitId", `must be a wait id ('wait_' followed by a ULID), received ${JSON.stringify(waitId)}`);
138714
+ }
138715
+ }
138716
+ function assertAttributeFilters(method, attributes) {
138717
+ const entries = Object.entries(attributes);
138718
+ if (entries.length > ANALYTICS_MAX_ATTRIBUTE_FILTERS) {
138719
+ throw invalidArgument(method, "attributes", `may filter by at most ${ANALYTICS_MAX_ATTRIBUTE_FILTERS} pairs (received ${entries.length})`);
138720
+ }
138721
+ for (const [key, value] of entries) {
138722
+ if (!AttributeKeySchema.safeParse(key).success) {
138723
+ throw invalidArgument(method, "attributes", `key must be 1 to ${ATTRIBUTE_KEY_MAX_LENGTH} characters, received ${key.length} in ${JSON.stringify(key)}`);
138724
+ }
138725
+ if (!AttributeValueSchema.safeParse(value).success) {
138726
+ throw invalidArgument(method, "attributes", `value for ${JSON.stringify(key)} must be at most ${ATTRIBUTE_VALUE_MAX_BYTES} UTF-8 bytes (received ${new TextEncoder().encode(value).length})`);
138727
+ }
138728
+ }
138729
+ }
138730
+ function assertDateWindow(method, startTime, endTime) {
138731
+ if (startTime === void 0 && endTime === void 0)
138732
+ return;
138733
+ if (startTime === void 0 || endTime === void 0) {
138734
+ const given = startTime === void 0 ? "endTime" : "startTime";
138735
+ const missing = startTime === void 0 ? "startTime" : "endTime";
138736
+ throw invalidArgument(method, missing, `is required when ${given} is provided; supply both or neither`);
138737
+ }
138738
+ const start2 = new Date(startTime).getTime();
138739
+ const end = new Date(endTime).getTime();
138740
+ if (!Number.isFinite(start2)) {
138741
+ throw invalidArgument(method, "startTime", `must be a parseable datetime, received ${JSON.stringify(startTime)}`);
138742
+ }
138743
+ if (!Number.isFinite(end)) {
138744
+ throw invalidArgument(method, "endTime", `must be a parseable datetime, received ${JSON.stringify(endTime)}`);
138745
+ }
138746
+ if (start2 > end) {
138747
+ throw invalidArgument(method, "startTime", `must be before or equal to endTime (received startTime=${JSON.stringify(startTime)}, endTime=${JSON.stringify(endTime)})`);
138748
+ }
138749
+ }
138750
+ function appendPagination(method, params, pagination, maxLimit) {
138751
+ if ((pagination == null ? void 0 : pagination.limit) !== void 0) {
138752
+ assertPageLimit(method, pagination.limit, maxLimit);
138151
138753
  params.set("limit", pagination.limit.toString());
138754
+ }
138152
138755
  if (pagination == null ? void 0 : pagination.cursor)
138153
138756
  params.set("cursor", pagination.cursor);
138154
138757
  if (pagination == null ? void 0 : pagination.sortOrder)
@@ -138158,30 +138761,34 @@ function createQueryString(params) {
138158
138761
  const query = params.toString();
138159
138762
  return query ? `?${query}` : "";
138160
138763
  }
138161
- function normalizeEventIds(eventIds) {
138764
+ function normalizeEventIds(method, eventIds) {
138162
138765
  const uniqueEventIds = [...new Set(eventIds)];
138163
138766
  if (uniqueEventIds.length === 0) {
138164
- throw new RangeError("eventIds must contain at least one event ID");
138767
+ throw invalidArgument(method, "eventIds", "must contain at least one id");
138165
138768
  }
138166
138769
  if (uniqueEventIds.length > ANALYTICS_EVENTS_GET_MANY_LIMIT) {
138167
- throw new RangeError(`eventIds must contain at most ${ANALYTICS_EVENTS_GET_MANY_LIMIT} unique event IDs`);
138770
+ throw invalidArgument(method, "eventIds", `must contain at most ${ANALYTICS_EVENTS_GET_MANY_LIMIT} unique ids (received ${uniqueEventIds.length})`);
138168
138771
  }
138772
+ for (const eventId of uniqueEventIds)
138773
+ assertEventId(method, eventId);
138169
138774
  return uniqueEventIds;
138170
138775
  }
138171
- function appendAttributeListParams(searchParams, params) {
138172
- if (params.workflowName) {
138776
+ function appendAttributeListParams(method, searchParams, params) {
138777
+ assertDateWindow(method, params.startTime, params.endTime);
138778
+ if (params.workflowName !== void 0) {
138173
138779
  searchParams.set("workflowName", params.workflowName);
138174
138780
  }
138175
- if (params.startTime && params.endTime) {
138781
+ if (params.startTime !== void 0 && params.endTime !== void 0) {
138176
138782
  searchParams.set("startTime", params.startTime);
138177
138783
  searchParams.set("endTime", params.endTime);
138178
138784
  }
138179
- appendPagination(searchParams, params.pagination);
138785
+ appendPagination(method, searchParams, params.pagination, ANALYTICS_PAGE_LIMIT);
138180
138786
  }
138181
138787
  function createAnalytics(config2) {
138182
138788
  return {
138183
138789
  runs: {
138184
138790
  get(runId) {
138791
+ assertRunId("analytics.runs.get", runId);
138185
138792
  return makeRequest({
138186
138793
  endpoint: `/v2/analytics/runs/${encodeURIComponent(runId)}`,
138187
138794
  config: config2,
@@ -138189,21 +138796,23 @@ function createAnalytics(config2) {
138189
138796
  });
138190
138797
  },
138191
138798
  list(params = {}) {
138799
+ assertDateWindow("analytics.runs.list", params.startTime, params.endTime);
138192
138800
  const searchParams = new URLSearchParams();
138193
- if (params.workflowName) {
138801
+ if (params.workflowName !== void 0) {
138194
138802
  searchParams.set("workflowName", params.workflowName);
138195
138803
  }
138196
138804
  if (params.status) {
138197
138805
  searchParams.set("status", params.status);
138198
138806
  }
138199
- if (params.startTime && params.endTime) {
138807
+ if (params.startTime !== void 0 && params.endTime !== void 0) {
138200
138808
  searchParams.set("startTime", params.startTime);
138201
138809
  searchParams.set("endTime", params.endTime);
138202
138810
  }
138203
138811
  if (params.attributes && Object.keys(params.attributes).length > 0) {
138812
+ assertAttributeFilters("analytics.runs.list", params.attributes);
138204
138813
  searchParams.set("attributes", JSON.stringify(params.attributes));
138205
138814
  }
138206
- appendPagination(searchParams, params.pagination);
138815
+ appendPagination("analytics.runs.list", searchParams, params.pagination, ANALYTICS_PAGE_LIMIT);
138207
138816
  return makeRequest({
138208
138817
  endpoint: `/v2/analytics/runs${createQueryString(searchParams)}`,
138209
138818
  config: config2,
@@ -138214,7 +138823,7 @@ function createAnalytics(config2) {
138214
138823
  attributes: {
138215
138824
  list(params = {}) {
138216
138825
  const searchParams = new URLSearchParams();
138217
- appendAttributeListParams(searchParams, params);
138826
+ appendAttributeListParams("analytics.attributes.list", searchParams, params);
138218
138827
  return makeRequest({
138219
138828
  endpoint: `/v2/analytics/attributes${createQueryString(searchParams)}`,
138220
138829
  config: config2,
@@ -138224,6 +138833,8 @@ function createAnalytics(config2) {
138224
138833
  },
138225
138834
  steps: {
138226
138835
  get(runId, stepId) {
138836
+ assertRunId("analytics.steps.get", runId);
138837
+ assertStepId("analytics.steps.get", stepId);
138227
138838
  return makeRequest({
138228
138839
  endpoint: `/v2/analytics/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(stepId)}`,
138229
138840
  config: config2,
@@ -138231,8 +138842,9 @@ function createAnalytics(config2) {
138231
138842
  });
138232
138843
  },
138233
138844
  list(params) {
138845
+ assertRunId("analytics.steps.list", params.runId);
138234
138846
  const searchParams = new URLSearchParams();
138235
- appendPagination(searchParams, params.pagination);
138847
+ appendPagination("analytics.steps.list", searchParams, params.pagination, ANALYTICS_RUN_SCOPED_PAGE_LIMIT);
138236
138848
  return makeRequest({
138237
138849
  endpoint: `/v2/analytics/runs/${encodeURIComponent(params.runId)}/steps${createQueryString(searchParams)}`,
138238
138850
  config: config2,
@@ -138242,6 +138854,8 @@ function createAnalytics(config2) {
138242
138854
  },
138243
138855
  events: {
138244
138856
  get(runId, eventId) {
138857
+ assertRunId("analytics.events.get", runId);
138858
+ assertEventId("analytics.events.get", eventId);
138245
138859
  return makeRequest({
138246
138860
  endpoint: `/v2/analytics/runs/${encodeURIComponent(runId)}/events/${encodeURIComponent(eventId)}`,
138247
138861
  config: config2,
@@ -138249,33 +138863,47 @@ function createAnalytics(config2) {
138249
138863
  });
138250
138864
  },
138251
138865
  getMany(runId, eventIds) {
138866
+ assertRunId("analytics.events.getMany", runId);
138252
138867
  return makeRequest({
138253
138868
  endpoint: `/v2/analytics/runs/${encodeURIComponent(runId)}/events/get-many`,
138254
138869
  options: { method: "POST" },
138255
- data: { eventIds: normalizeEventIds(eventIds) },
138870
+ data: {
138871
+ eventIds: normalizeEventIds("analytics.events.getMany", eventIds)
138872
+ },
138256
138873
  config: config2,
138257
138874
  schema: AnalyticsEventSchema.array()
138258
138875
  });
138259
138876
  },
138260
138877
  list(params) {
138878
+ assertRunId("analytics.events.list", params.runId);
138261
138879
  const searchParams = new URLSearchParams();
138262
138880
  if (params.eventType) {
138263
138881
  searchParams.set("eventType", params.eventType);
138264
138882
  }
138265
- if (params.correlationId) {
138883
+ if (params.correlationId !== void 0) {
138884
+ assertCorrelationId("analytics.events.list", params.correlationId);
138266
138885
  searchParams.set("correlationId", params.correlationId);
138267
138886
  }
138268
- appendPagination(searchParams, params.pagination);
138887
+ appendPagination("analytics.events.list", searchParams, params.pagination, ANALYTICS_RUN_SCOPED_PAGE_LIMIT);
138269
138888
  return makeRequest({
138270
138889
  endpoint: `/v2/analytics/runs/${encodeURIComponent(params.runId)}/events${createQueryString(searchParams)}`,
138271
138890
  config: config2,
138272
138891
  schema: PaginatedResponseSchema(AnalyticsEventSchema)
138273
138892
  });
138274
138893
  },
138894
+ /**
138895
+ * @deprecated Use `list({ runId, correlationId })`. Kept as its own
138896
+ * implementation rather than delegating: `list` treats
138897
+ * `correlationId` as optional and skips an empty one, where this
138898
+ * method requires it, so a delegation would turn an empty id into an
138899
+ * unfiltered listing of the run.
138900
+ */
138275
138901
  listByCorrelationId(params) {
138902
+ assertRunId("analytics.events.listByCorrelationId", params.runId);
138903
+ assertCorrelationId("analytics.events.listByCorrelationId", params.correlationId);
138276
138904
  const searchParams = new URLSearchParams();
138277
138905
  searchParams.set("correlationId", params.correlationId);
138278
- appendPagination(searchParams, params.pagination);
138906
+ appendPagination("analytics.events.listByCorrelationId", searchParams, params.pagination, ANALYTICS_RUN_SCOPED_PAGE_LIMIT);
138279
138907
  return makeRequest({
138280
138908
  endpoint: `/v2/analytics/runs/${encodeURIComponent(params.runId)}/events${createQueryString(searchParams)}`,
138281
138909
  config: config2,
@@ -138285,8 +138913,10 @@ function createAnalytics(config2) {
138285
138913
  },
138286
138914
  hooks: {
138287
138915
  get(hookId, params) {
138916
+ assertHookId("analytics.hooks.get", hookId);
138288
138917
  const searchParams = new URLSearchParams();
138289
- if (params == null ? void 0 : params.runId) {
138918
+ if ((params == null ? void 0 : params.runId) !== void 0) {
138919
+ assertRunId("analytics.hooks.get", params.runId);
138290
138920
  searchParams.set("runId", params.runId);
138291
138921
  }
138292
138922
  return makeRequest({
@@ -138296,9 +138926,10 @@ function createAnalytics(config2) {
138296
138926
  });
138297
138927
  },
138298
138928
  list(params) {
138929
+ assertRunId("analytics.hooks.list", params.runId);
138299
138930
  const searchParams = new URLSearchParams();
138300
138931
  searchParams.set("runId", params.runId);
138301
- appendPagination(searchParams, params.pagination);
138932
+ appendPagination("analytics.hooks.list", searchParams, params.pagination, ANALYTICS_PAGE_LIMIT);
138302
138933
  return makeRequest({
138303
138934
  endpoint: `/v2/analytics/hooks${createQueryString(searchParams)}`,
138304
138935
  config: config2,
@@ -138308,6 +138939,8 @@ function createAnalytics(config2) {
138308
138939
  },
138309
138940
  waits: {
138310
138941
  get(runId, waitId) {
138942
+ assertRunId("analytics.waits.get", runId);
138943
+ assertWaitId("analytics.waits.get", waitId);
138311
138944
  return makeRequest({
138312
138945
  endpoint: `/v2/analytics/runs/${encodeURIComponent(runId)}/waits/${encodeURIComponent(waitId)}`,
138313
138946
  config: config2,
@@ -138315,11 +138948,12 @@ function createAnalytics(config2) {
138315
138948
  });
138316
138949
  },
138317
138950
  list(params) {
138951
+ assertRunId("analytics.waits.list", params.runId);
138318
138952
  const searchParams = new URLSearchParams();
138319
138953
  if (params.status) {
138320
138954
  searchParams.set("status", params.status);
138321
138955
  }
138322
- appendPagination(searchParams, params.pagination);
138956
+ appendPagination("analytics.waits.list", searchParams, params.pagination, ANALYTICS_RUN_SCOPED_PAGE_LIMIT);
138323
138957
  return makeRequest({
138324
138958
  endpoint: `/v2/analytics/runs/${encodeURIComponent(params.runId)}/waits${createQueryString(searchParams)}`,
138325
138959
  config: config2,
@@ -138654,7 +139288,7 @@ function createGetEncryptionKeyForRun(projectId, teamId, token, dispatcher2) {
138654
139288
  };
138655
139289
  }
138656
139290
  async function getDeadline() {
138657
- const { getDeadline: getDeadline2 } = await import("./index-jQkBA81b.js").then((n) => n.i);
139291
+ const { getDeadline: getDeadline2 } = await import("./index-EldBi9Vs.js").then((n) => n.i);
138658
139292
  return getDeadline2();
138659
139293
  }
138660
139294
  const WORKFLOW_SERVER_SERVICE = {
@@ -143607,7 +144241,7 @@ const wsEventsChannelForInvocation = (runId, config2) => {
143607
144241
  open() {
143608
144242
  if (!runId || !isWsEventsTransportEnabled())
143609
144243
  return;
143610
- claim = import("./ws-transport-DbDOLT7f.js").then(({ openWsChannel }) => openWsChannel(runId, config2)).catch(() => void 0);
144244
+ claim = import("./ws-transport-DUA3rYTp.js").then(({ openWsChannel }) => openWsChannel(runId, config2)).catch(() => void 0);
143611
144245
  },
143612
144246
  /**
143613
144247
  * Awaited, unlike the open: work scheduled after the handler returns is not
@@ -144335,7 +144969,7 @@ async function getStep(runId, stepId, params, config2) {
144335
144969
  }
144336
144970
  async function fetchV4(url2, init2, config2, opName, attributes) {
144337
144971
  const dispatcher2 = getEventsDispatcher(config2);
144338
- return instrumentedFetch({
144972
+ const response2 = await instrumentedFetch({
144339
144973
  method: init2.method,
144340
144974
  url: url2,
144341
144975
  headers: init2.headers,
@@ -144347,11 +144981,44 @@ async function fetchV4(url2, init2, config2, opName, attributes) {
144347
144981
  // service indefinitely, so without this every request routed onto it fails
144348
144982
  // until the compute instance is recycled. See noteEventsTransportOutcome.
144349
144983
  onTransportOutcome: (error2) => noteEventsTransportOutcome(dispatcher2, error2),
144984
+ deferTransportSuccessUntilBody: true,
144350
144985
  timeoutMs: null,
144986
+ transportErrorCode: "STREAM_ERROR",
144351
144987
  logLabel: opName,
144352
144988
  // Read the body as bytes, not text: a CBOR error body (the fence 412
144353
144989
  // carries event payloads back) does not survive a UTF-8 decode.
144354
- buildError: async (response2) => errorFromV4Response(response2.status, headersToRecord(response2.headers), new Uint8Array(await response2.arrayBuffer()), opName, url2)
144990
+ buildError: async (response3) => errorFromV4Response(response3.status, headersToRecord(response3.headers), new Uint8Array(await response3.arrayBuffer()), opName, url2)
144991
+ });
144992
+ if (!response2.body) {
144993
+ noteEventsTransportOutcome(dispatcher2);
144994
+ return response2;
144995
+ }
144996
+ const reader = response2.body.getReader();
144997
+ const body2 = new ReadableStream({
144998
+ async pull(controller) {
144999
+ try {
145000
+ const chunk = await reader.read();
145001
+ if (chunk.done) {
145002
+ noteEventsTransportOutcome(dispatcher2);
145003
+ controller.close();
145004
+ } else {
145005
+ controller.enqueue(chunk.value);
145006
+ }
145007
+ } catch (cause) {
145008
+ noteEventsTransportOutcome(dispatcher2, cause);
145009
+ const transportCode = getTransientTransportCode(cause);
145010
+ controller.error(transportCode ? new StreamError(`v4 ${opName}: response stream transport failure (${transportCode})`, { cause, url: url2 }) : cause);
145011
+ }
145012
+ },
145013
+ cancel(reason) {
145014
+ noteEventsTransportOutcome(dispatcher2);
145015
+ return reader.cancel(reason);
145016
+ }
145017
+ });
145018
+ return new Response(body2, {
145019
+ status: response2.status,
145020
+ statusText: response2.statusText,
145021
+ headers: response2.headers
144355
145022
  });
144356
145023
  }
144357
145024
  const EVENT_ID_HEADER = "x-wf-event-id";
@@ -144678,6 +145345,8 @@ async function decodeCreateEventResponse(response2, eventType) {
144678
145345
  try {
144679
145346
  bodyBytes = new Uint8Array(await response2.arrayBuffer());
144680
145347
  } catch (cause) {
145348
+ if (StreamError.is(cause))
145349
+ throw cause;
144681
145350
  throw new WorkflowWorldError("v4 createEvent: failed to read response body", { code: "TRANSPORT", cause });
144682
145351
  }
144683
145352
  if (bodyBytes.byteLength === 0) {
@@ -144787,7 +145456,7 @@ function wsReplyStatus(reply, endpoint) {
144787
145456
  return status;
144788
145457
  }
144789
145458
  async function postEventFrameOverWs(input, config2) {
144790
- const { resolveWsTransport } = await import("./ws-transport-DbDOLT7f.js");
145459
+ const { resolveWsTransport } = await import("./ws-transport-DUA3rYTp.js");
144791
145460
  const { runId } = input;
144792
145461
  const resolved = resolveWsTransport(runId, config2);
144793
145462
  if (!resolved)
@@ -144876,14 +145545,21 @@ async function getEventV4(runId, eventId, remoteRefBehavior, config2) {
144876
145545
  throw new Error(`v4 getEvent: expected ${V4_FRAME_CONTENT_TYPE}, got ${contentType ?? "(none)"}`);
144877
145546
  }
144878
145547
  const chunks = response2.body;
144879
- for await (const frame2 of decodeFrames(chunks)) {
144880
- if (frame2.meta._error === 1) {
144881
- throw streamErrorFrameToError(frame2.meta, "getEvent");
145548
+ try {
145549
+ for await (const frame2 of decodeFrames(chunks)) {
145550
+ if (frame2.meta._error === 1) {
145551
+ throw streamErrorFrameToError(frame2.meta, "getEvent");
145552
+ }
145553
+ if (Object.keys(frame2.meta).some((key) => key.startsWith("_"))) {
145554
+ throw new Error("v4 getEvent: unexpected control frame");
145555
+ }
145556
+ return decodeEventFrame(frame2);
144882
145557
  }
144883
- if (Object.keys(frame2.meta).some((key) => key.startsWith("_"))) {
144884
- throw new Error("v4 getEvent: unexpected control frame");
145558
+ } catch (cause) {
145559
+ if (cause instanceof IncompleteFrameError && StreamError.is(cause.cause)) {
145560
+ throw cause.cause;
144885
145561
  }
144886
- return decodeEventFrame(frame2);
145562
+ throw cause;
144887
145563
  }
144888
145564
  throw new Error(`v4 getEvent: empty frame stream for ${eventId}`);
144889
145565
  }
@@ -144953,6 +145629,9 @@ async function consumeEventFrameStream(response2, opName, replayEventObserver) {
144953
145629
  if (cause instanceof ReplayEventObserverError || CorruptedEventLogError.is(cause) || WorkflowWorldError.is(cause)) {
144954
145630
  throw cause;
144955
145631
  }
145632
+ if (cause instanceof IncompleteFrameError && StreamError.is(cause.cause)) {
145633
+ return partialEventFrameStream(events2, cause.cause);
145634
+ }
144956
145635
  if (!(cause instanceof IncompleteFrameError)) {
144957
145636
  throw new WorkflowWorldError(`v4 ${opName}: invalid event frame stream`, {
144958
145637
  code: "SCHEMA_VALIDATION",
@@ -145714,7 +146393,34 @@ function createStorage(config2) {
145714
146393
  hooks: instrumentObject("world.hooks", storage.hooks)
145715
146394
  };
145716
146395
  }
145717
- const MAX_CHUNKS_PER_REQUEST = 1e3;
146396
+ const MAX_CHUNKS_PER_STREAM_WRITE = 1e3;
146397
+ function normalizeStreamChunks(chunks) {
146398
+ const encoder2 = new TextEncoder();
146399
+ return chunks.map((chunk) => typeof chunk === "string" ? encoder2.encode(chunk) : chunk);
146400
+ }
146401
+ function encodeMultiChunks(chunks) {
146402
+ return encodeNormalizedMultiChunks(normalizeStreamChunks(chunks));
146403
+ }
146404
+ function encodeNormalizedMultiChunks(binaryChunks) {
146405
+ let totalSize = 0;
146406
+ for (const binary of binaryChunks) {
146407
+ totalSize += 4 + binary.length;
146408
+ if (totalSize > 4294967295) {
146409
+ throw new RangeError(`encoded stream chunks exceed the u32 body-length limit: ${totalSize} bytes`);
146410
+ }
146411
+ }
146412
+ const result = new Uint8Array(totalSize);
146413
+ const view = new DataView(result.buffer);
146414
+ let offset2 = 0;
146415
+ for (const binary of binaryChunks) {
146416
+ view.setUint32(offset2, binary.length, false);
146417
+ offset2 += 4;
146418
+ result.set(binary, offset2);
146419
+ offset2 += binary.length;
146420
+ }
146421
+ return result;
146422
+ }
146423
+ const MAX_CHUNKS_PER_REQUEST = MAX_CHUNKS_PER_STREAM_WRITE;
145718
146424
  const getMaxChunksPerRequest = () => envNumber("WORKFLOW_MAX_CHUNKS_PER_REQUEST", MAX_CHUNKS_PER_REQUEST, {
145719
146425
  integer: true,
145720
146426
  min: 1
@@ -145735,41 +146441,28 @@ function streamSpanAttributes(args) {
145735
146441
  }
145736
146442
  async function createStreamReadError(response2) {
145737
146443
  const fallback = `Failed to fetch stream: ${response2.status}`;
145738
- if (response2.status !== 410)
145739
- return new Error(fallback);
146444
+ if (response2.status !== 410) {
146445
+ return new StreamError(fallback, { status: response2.status });
146446
+ }
145740
146447
  try {
145741
146448
  const body2 = await response2.json();
145742
146449
  return errorForResponse(response2.status, typeof body2.message === "string" ? body2.message : fallback, { code: body2.error, details: body2.details });
145743
146450
  } catch {
145744
- return new Error(fallback);
146451
+ return new StreamError(fallback, { status: response2.status });
146452
+ }
146453
+ }
146454
+ function toStreamError(message2, cause) {
146455
+ if (WorkflowWorldError.is(cause) || EntityConflictError.is(cause) || RunExpiredError.is(cause) || StreamError.is(cause) || StreamExpiredError.is(cause) || TooEarlyError.is(cause) || ThrottleError.is(cause) || PreconditionFailedError.is(cause)) {
146456
+ return cause;
145745
146457
  }
146458
+ return new StreamError(message2, { cause });
145746
146459
  }
145747
146460
  function createStreamRequestError(operation, url2, response2, text2) {
145748
146461
  const context = [
145749
146462
  `PUT ${url2.origin}${url2.pathname}`,
145750
146463
  ...getVercelDiagnostics(response2.headers)
145751
146464
  ];
145752
- return new Error(`Stream ${operation} failed: HTTP ${response2.status} (${context.join("; ")}): ${text2}`);
145753
- }
145754
- function encodeMultiChunks(chunks) {
145755
- const encoder2 = new TextEncoder();
145756
- const binaryChunks = [];
145757
- let totalSize = 0;
145758
- for (const chunk of chunks) {
145759
- const binary = typeof chunk === "string" ? encoder2.encode(chunk) : chunk;
145760
- binaryChunks.push(binary);
145761
- totalSize += 4 + binary.length;
145762
- }
145763
- const result = new Uint8Array(totalSize);
145764
- const view = new DataView(result.buffer);
145765
- let offset2 = 0;
145766
- for (const binary of binaryChunks) {
145767
- view.setUint32(offset2, binary.length, false);
145768
- offset2 += 4;
145769
- result.set(binary, offset2);
145770
- offset2 += binary.length;
145771
- }
145772
- return result;
146465
+ return new StreamError(`Stream ${operation} failed: HTTP ${response2.status} (${context.join("; ")}): ${text2}`, { url: url2.toString(), status: response2.status });
145773
146466
  }
145774
146467
  const StreamInfoResponseSchema = object$1({
145775
146468
  tailIndex: number$3(),
@@ -145798,6 +146491,7 @@ function createStreamer(config2) {
145798
146491
  headers: httpConfig.headers,
145799
146492
  dispatcher: getStreamDispatcher(config2),
145800
146493
  timeoutMs: null,
146494
+ transportErrorCode: "STREAM_ERROR",
145801
146495
  logLabel: url2.pathname,
145802
146496
  spanName: "workflow.stream.write",
145803
146497
  durationAttribute: "workflow.stream.write.chunk_rtt",
@@ -145828,6 +146522,7 @@ function createStreamer(config2) {
145828
146522
  headers: httpConfig.headers,
145829
146523
  dispatcher: getStreamDispatcher(config2),
145830
146524
  timeoutMs: null,
146525
+ transportErrorCode: "STREAM_ERROR",
145831
146526
  logLabel: url2.pathname,
145832
146527
  spanName: "workflow.stream.write",
145833
146528
  durationAttribute: "workflow.stream.write.chunk_rtt",
@@ -145856,6 +146551,7 @@ function createStreamer(config2) {
145856
146551
  // 503s with the stream left durably closing.
145857
146552
  dispatcher: getStreamCloseDispatcher(config2),
145858
146553
  timeoutMs: null,
146554
+ transportErrorCode: "STREAM_ERROR",
145859
146555
  logLabel: url2.pathname,
145860
146556
  spanName: "workflow.stream.write",
145861
146557
  durationAttribute: "workflow.stream.write.chunk_rtt",
@@ -145881,6 +146577,7 @@ function createStreamer(config2) {
145881
146577
  headers: httpConfig.headers,
145882
146578
  dispatcher: void 0,
145883
146579
  timeoutMs: null,
146580
+ transportErrorCode: "STREAM_ERROR",
145884
146581
  logLabel: url2.pathname,
145885
146582
  spanName: "workflow.stream.read.connect",
145886
146583
  attributes: streamSpanAttributes({
@@ -145892,7 +146589,9 @@ function createStreamer(config2) {
145892
146589
  buildError: createStreamReadError
145893
146590
  });
145894
146591
  if (!response2.body) {
145895
- throw new Error("No response body for stream");
146592
+ throw new StreamError("No response body for stream", {
146593
+ url: url2.toString()
146594
+ });
145896
146595
  }
145897
146596
  return response2.body;
145898
146597
  },
@@ -145906,19 +146605,27 @@ function createStreamer(config2) {
145906
146605
  }
145907
146606
  const qs = params.toString();
145908
146607
  const endpoint = `/v2/runs/${encodeURIComponent(runId)}/streams/${encodeURIComponent(name2)}/chunks${qs ? `?${qs}` : ""}`;
145909
- return makeRequest({
145910
- endpoint,
145911
- config: config2,
145912
- schema: StreamChunksResponseSchema
145913
- });
146608
+ try {
146609
+ return await makeRequest({
146610
+ endpoint,
146611
+ config: config2,
146612
+ schema: StreamChunksResponseSchema
146613
+ });
146614
+ } catch (cause) {
146615
+ throw toStreamError(`Failed to read stream chunks for ${name2}`, cause);
146616
+ }
145914
146617
  },
145915
146618
  async getInfo(runId, name2) {
145916
146619
  const endpoint = `/v2/runs/${encodeURIComponent(runId)}/streams/${encodeURIComponent(name2)}/info`;
145917
- return makeRequest({
145918
- endpoint,
145919
- config: config2,
145920
- schema: StreamInfoResponseSchema
145921
- });
146620
+ try {
146621
+ return await makeRequest({
146622
+ endpoint,
146623
+ config: config2,
146624
+ schema: StreamInfoResponseSchema
146625
+ });
146626
+ } catch (cause) {
146627
+ throw toStreamError(`Failed to read stream info for ${name2}`, cause);
146628
+ }
145922
146629
  },
145923
146630
  async list(runId) {
145924
146631
  const httpConfig = await getHttpConfig(config2);
@@ -145929,10 +146636,18 @@ function createStreamer(config2) {
145929
146636
  headers: httpConfig.headers,
145930
146637
  dispatcher: void 0,
145931
146638
  timeoutMs: null,
146639
+ transportErrorCode: "STREAM_ERROR",
145932
146640
  logLabel: url2.pathname,
145933
- buildError: (res) => new Error(`Failed to list streams: ${res.status}`)
146641
+ buildError: (res) => new StreamError(`Failed to list streams: ${res.status}`, {
146642
+ url: url2.toString(),
146643
+ status: res.status
146644
+ })
145934
146645
  });
145935
- return await response2.json();
146646
+ try {
146647
+ return await response2.json();
146648
+ } catch (cause) {
146649
+ throw toStreamError("Failed to parse stream list response", cause);
146650
+ }
145936
146651
  }
145937
146652
  }
145938
146653
  };
@@ -146115,7 +146830,7 @@ globalSingleton("@workflow/core//devServerPort", 1, () => ({
146115
146830
  inFlight: void 0
146116
146831
  }));
146117
146832
  function waitUntil(promise2) {
146118
- void import("./index-jQkBA81b.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => {
146833
+ void import("./index-EldBi9Vs.js").then((n) => n.i).then(({ waitUntil: waitUntil2 }) => {
146119
146834
  waitUntil2(promise2);
146120
146835
  });
146121
146836
  }
@@ -149127,6 +149842,7 @@ function normalizeAttributeChanges(attrs, options = {}) {
149127
149842
  return changes;
149128
149843
  }
149129
149844
  const CROSS_DEPLOYMENT_CAPABILITY_PROBE_TIMEOUT_MS = 2e3;
149845
+ const RETENTION_ZERO_ATTRIBUTE_VALUE = "0";
149130
149846
  const ulid = monotonicFactory();
149131
149847
  function resolveLineageAttributes() {
149132
149848
  var _a3;
@@ -149225,11 +149941,23 @@ async function start$1(workflow, argsOrOptions, options) {
149225
149941
  });
149226
149942
  attributes = Object.fromEntries(changes.map(({ key, value }) => [key, value]));
149227
149943
  }
149944
+ let retentionAttribute;
149945
+ if (opts.experimental_retention !== void 0 && opts.experimental_retention !== "default") {
149946
+ if (opts.experimental_retention !== 0) {
149947
+ throw new WorkflowRuntimeError(`start({ experimental_retention }) must be 0 or 'default'; received ${JSON.stringify(opts.experimental_retention)}.`);
149948
+ }
149949
+ if (specVersion < SPEC_VERSION_SUPPORTS_ATTRIBUTES) {
149950
+ throw new WorkflowRuntimeError("start({ experimental_retention }) requires a World that supports spec version 4 or later.");
149951
+ }
149952
+ retentionAttribute = {
149953
+ [RETENTION_ATTRIBUTE]: RETENTION_ZERO_ATTRIBUTE_VALUE
149954
+ };
149955
+ }
149228
149956
  const lineage = specVersion >= SPEC_VERSION_SUPPORTS_ATTRIBUTES ? resolveLineageAttributes() : void 0;
149229
- const runAttributes = lineage ? { ...lineage, ...attributes } : attributes;
149957
+ const runAttributes = lineage || retentionAttribute ? { ...lineage, ...attributes, ...retentionAttribute } : attributes;
149230
149958
  const attributeSeed = runAttributes ? {
149231
149959
  attributes: runAttributes,
149232
- ...allowReservedAttributes || lineage != null ? { allowReservedAttributes: true } : {}
149960
+ ...allowReservedAttributes || lineage != null || retentionAttribute != null ? { allowReservedAttributes: true } : {}
149233
149961
  } : {};
149234
149962
  if (opts.replayedFromRunId !== void 0 && !workflowRunIdSchema.safeParse(opts.replayedFromRunId).success) {
149235
149963
  throw new WorkflowRuntimeError(`replayedFromRunId must be a run ID (wrun_<ulid>); received ${JSON.stringify(String(opts.replayedFromRunId).slice(0, 64))}.`);
@@ -149535,6 +150263,7 @@ const PAYLOAD_TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set([
149535
150263
  "completed",
149536
150264
  "failed"
149537
150265
  ]);
150266
+ const NOT_FOUND_RETRY_DELAYS = [1e3, 3e3, 6e3];
149538
150267
  function getReturnValuePollIntervalMs() {
149539
150268
  return envNumber("WORKFLOW_RETURN_VALUE_POLL_INTERVAL_MS", RETURN_VALUE_POLL_INTERVAL_MS, { integer: true, min: 1 });
149540
150269
  }
@@ -149694,10 +150423,7 @@ const _Run = class _Run {
149694
150423
  const { ops = [], global: global2 = globalThis, startIndex, namespace: namespace2 } = options;
149695
150424
  const name2 = getWorkflowRunStreamId(this.runId, namespace2);
149696
150425
  const encryptionKey = __privateMethod(this, _Run_instances, getEncryptionKeyLazily_fn).call(this);
149697
- const stream = getExternalRevivers(global2, ops, this.runId, encryptionKey).ReadableStream({
149698
- name: name2,
149699
- startIndex
149700
- });
150426
+ const stream = getRunReadableStream(global2, ops, this.runId, name2, startIndex, encryptionKey);
149701
150427
  const worldPromise = __privateGet(this, _Run_instances, lazyWorldPromise_get);
149702
150428
  const runId = this.runId;
149703
150429
  return Object.assign(stream, {
@@ -149708,6 +150434,50 @@ const _Run = class _Run {
149708
150434
  }
149709
150435
  });
149710
150436
  }
150437
+ /** The writable stream of the workflow run. */
150438
+ get writable() {
150439
+ return this.getWritable();
150440
+ }
150441
+ /**
150442
+ * Returns a writable that appends to this run's stream.
150443
+ *
150444
+ * Initialization is deferred until the first write. The run must already
150445
+ * exist. The writable may be forwarded through `start()` and into steps, but
150446
+ * grants no read access or additional authorization.
150447
+ *
150448
+ * @remarks
150449
+ * `writer.close()` closes the shared stream. Contributors should call
150450
+ * `releaseLock()`, which also drains pending writes.
150451
+ *
150452
+ * @param options - The writable stream options.
150453
+ */
150454
+ getWritable(options = {}) {
150455
+ "use step";
150456
+ const { ops = [], global: global2 = globalThis, namespace: namespace2 } = options;
150457
+ const name2 = getWorkflowRunStreamId(this.runId, namespace2);
150458
+ let targetPromise;
150459
+ let writable;
150460
+ const resolveTarget = () => {
150461
+ targetPromise ?? (targetPromise = __privateMethod(this, _Run_instances, getMetadata_fn).call(this).then(async (run2) => {
150462
+ const target2 = {
150463
+ key: await getForwardedWritableEncryptionKey(this.runId, run2.deploymentId, run2.encryptionPublicKey),
150464
+ deploymentId: run2.deploymentId,
150465
+ encryptionPublicKey: run2.encryptionPublicKey
150466
+ };
150467
+ tagForwardedWritableTarget(writable, target2);
150468
+ return target2;
150469
+ }));
150470
+ return targetPromise;
150471
+ };
150472
+ writable = createForwardedWritable({
150473
+ global: global2,
150474
+ ops,
150475
+ runId: this.runId,
150476
+ name: name2,
150477
+ key: () => resolveTarget().then(({ key }) => key)
150478
+ });
150479
+ return writable;
150480
+ }
149711
150481
  };
149712
150482
  _worldPromise = new WeakMap();
149713
150483
  _Run_instances = new WeakSet();
@@ -149737,15 +150507,36 @@ getEncryptionKey_fn = function(run2) {
149737
150507
  return __privateGet(this, _encryptionKeyPromise);
149738
150508
  };
149739
150509
  /**
149740
- * Defer fetching the run and its encryption key until serialized stream data
149741
- * is actually read. An empty or metadata-only stream must not start an
149742
- * unobserved run lookup.
150510
+ * Defers fetching the run and its encryption key until a readable is first
150511
+ * consumed. The first pull prefetches it so an encrypted first frame can join
150512
+ * the lookup; this also applies to an empty consumed stream.
149743
150513
  * @internal
149744
150514
  */
149745
150515
  getEncryptionKeyLazily_fn = function() {
149746
150516
  return () => __privateMethod(this, _Run_instances, getEncryptionKey_fn).call(this);
149747
150517
  };
150518
+ getMetadata_fn = async function() {
150519
+ const world = await __privateGet(this, _Run_instances, lazyWorldPromise_get);
150520
+ const maxRetries = __privateGet(this, _resilientStart) ? NOT_FOUND_RETRY_DELAYS.length : 0;
150521
+ let attempt = 0;
150522
+ while (true) {
150523
+ try {
150524
+ return await world.runs.get(this.runId, { resolveData: "none" });
150525
+ } catch (error2) {
150526
+ if (!WorkflowRunNotFoundError.is(error2) || attempt >= maxRetries) {
150527
+ throw error2;
150528
+ }
150529
+ const delay = NOT_FOUND_RETRY_DELAYS[attempt];
150530
+ attempt++;
150531
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
150532
+ }
150533
+ }
150534
+ };
149748
150535
  resolveTerminalReturnValue_fn = async function(run2) {
150536
+ const expiredAt = run2.expiredAt;
150537
+ if (expiredAt != null && expiredAt <= /* @__PURE__ */ new Date()) {
150538
+ throw new RunExpiredError(`Run "${this.runId}" ${run2.status === "completed" ? "completed" : `is ${run2.status}`}, but its data expired at ${expiredAt.toISOString()} and is no longer readable.`, this.runId, run2.status, expiredAt);
150539
+ }
149749
150540
  if (run2.status === "completed") {
149750
150541
  const encryptionKey = await __privateMethod(this, _Run_instances, getEncryptionKey_fn).call(this, run2);
149751
150542
  return await hydrateWorkflowReturnValue(run2.output, this.runId, encryptionKey);
@@ -149771,8 +150562,7 @@ pollReturnValue_fn = async function() {
149771
150562
  var _a3;
149772
150563
  const world = await __privateGet(this, _Run_instances, lazyWorldPromise_get);
149773
150564
  let notFoundRetries = 0;
149774
- const NOT_FOUND_MAX_RETRIES = __privateGet(this, _resilientStart) ? 3 : 0;
149775
- const NOT_FOUND_DELAYS = [1e3, 3e3, 6e3];
150565
+ const NOT_FOUND_MAX_RETRIES = __privateGet(this, _resilientStart) ? NOT_FOUND_RETRY_DELAYS.length : 0;
149776
150566
  const waitForTerminalStatus = isReturnValueLongPollEnabled() ? (_a3 = world.runs.waitForTerminalStatus) == null ? void 0 : _a3.bind(world.runs) : void 0;
149777
150567
  let longPolls = 0;
149778
150568
  const maxLongPolls = getReturnValueMaxLongPolls();
@@ -149807,7 +150597,7 @@ pollReturnValue_fn = async function() {
149807
150597
  continue;
149808
150598
  }
149809
150599
  if (WorkflowRunNotFoundError.is(error2) && notFoundRetries < NOT_FOUND_MAX_RETRIES) {
149810
- const delay = NOT_FOUND_DELAYS[notFoundRetries];
150600
+ const delay = NOT_FOUND_RETRY_DELAYS[notFoundRetries];
149811
150601
  notFoundRetries++;
149812
150602
  await new Promise((resolve2) => setTimeout(resolve2, delay));
149813
150603
  continue;
@@ -150312,36 +151102,6 @@ async function fetchRun(worldEnv, runId, resolveData = "all") {
150312
151102
  });
150313
151103
  }
150314
151104
  }
150315
- async function fetchSteps(worldEnv, runId, params) {
150316
- const { cursor, sortOrder = "asc", limit = 100 } = params;
150317
- try {
150318
- const world = await getWorldFromEnv(worldEnv);
150319
- const result = world.analytics ? await world.analytics.steps.list({
150320
- runId,
150321
- pagination: { cursor, limit, sortOrder }
150322
- }) : await world.steps.list({
150323
- runId,
150324
- pagination: { cursor, limit, sortOrder },
150325
- resolveData: "none"
150326
- });
150327
- return createResponse({
150328
- // StepWithoutData has undefined input/output, but after hydration the structure is compatible
150329
- data: result.data,
150330
- cursor: result.cursor ?? void 0,
150331
- hasMore: result.hasMore,
150332
- pageInfo: getPageInfo(result)
150333
- });
150334
- } catch (error2) {
150335
- return createServerActionError(
150336
- error2,
150337
- "world.steps.list",
150338
- {
150339
- runId,
150340
- ...params
150341
- }
150342
- );
150343
- }
150344
- }
150345
151105
  async function fetchStep(worldEnv, runId, stepId, resolveData = "all") {
150346
151106
  try {
150347
151107
  const world = await getWorldFromEnv(worldEnv);
@@ -150355,39 +151115,10 @@ async function fetchStep(worldEnv, runId, stepId, resolveData = "all") {
150355
151115
  });
150356
151116
  }
150357
151117
  }
150358
- function analyticsEventToEvent(event) {
150359
- const eventData = {
150360
- ...event.stepName ? { stepName: event.stepName } : {},
150361
- ...event.resumeAt ? { resumeAt: event.resumeAt } : {},
150362
- ...event.retryAfter ? { retryAfter: event.retryAfter } : {}
150363
- };
150364
- const base = {
150365
- runId: event.runId,
150366
- eventId: event.eventId,
150367
- eventType: event.eventType,
150368
- createdAt: event.createdAt,
150369
- ...event.correlationId ? { correlationId: event.correlationId } : {},
150370
- ...event.specVersion !== void 0 ? { specVersion: event.specVersion } : {},
150371
- ...Object.keys(eventData).length > 0 ? { eventData } : {}
150372
- };
150373
- return base;
150374
- }
150375
151118
  async function fetchEvents(worldEnv, runId, params) {
150376
151119
  const { cursor, sortOrder = "asc", limit = 1e3, withData = false } = params;
150377
151120
  try {
150378
151121
  const world = await getWorldFromEnv(worldEnv);
150379
- if (world.analytics && !withData) {
150380
- const result2 = await world.analytics.events.list({
150381
- runId,
150382
- pagination: { cursor, limit, sortOrder }
150383
- });
150384
- return createResponse({
150385
- data: result2.data.map(analyticsEventToEvent),
150386
- cursor: result2.cursor ?? void 0,
150387
- hasMore: result2.hasMore,
150388
- pageInfo: getPageInfo(result2)
150389
- });
150390
- }
150391
151122
  const result = await world.events.list({
150392
151123
  runId,
150393
151124
  pagination: { cursor, limit, sortOrder },
@@ -150433,19 +151164,6 @@ async function fetchEventsByCorrelationId(worldEnv, correlationId, params) {
150433
151164
  } = params;
150434
151165
  try {
150435
151166
  const world = await getWorldFromEnv(worldEnv);
150436
- if (world.analytics && !withData) {
150437
- const result2 = await world.analytics.events.listByCorrelationId({
150438
- correlationId,
150439
- runId,
150440
- pagination: { cursor, limit, sortOrder }
150441
- });
150442
- return createResponse({
150443
- data: result2.data.map(analyticsEventToEvent),
150444
- cursor: result2.cursor ?? void 0,
150445
- hasMore: result2.hasMore,
150446
- pageInfo: getPageInfo(result2)
150447
- });
150448
- }
150449
151167
  const result = await world.events.listByCorrelationId({
150450
151168
  correlationId,
150451
151169
  runId,
@@ -171936,7 +172654,7 @@ function BreadcrumbSeparator({
171936
172654
  }
171937
172655
  const INITIAL_PAGE_SIZE = 100;
171938
172656
  const LOAD_MORE_PAGE_SIZE = 100;
171939
- const MAX_CORRELATION_SEARCH_PAGES = 30;
172657
+ const MAX_CORRELATION_SEARCH_PAGES = 5;
171940
172658
  function useEventsListData(env2, runId, options = {}) {
171941
172659
  const { sortOrder = "asc", encryptionKey, enabled = true } = options;
171942
172660
  const [events2, setEvents] = reactExports.useState([]);
@@ -172874,7 +173592,6 @@ const route2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProper
172874
173592
  const handlers = {
172875
173593
  fetchRuns: (p2) => fetchRuns(p2.worldEnv ?? {}, p2.params ?? {}),
172876
173594
  fetchRun: (p2) => fetchRun(p2.worldEnv ?? {}, p2.runId, p2.resolveData),
172877
- fetchSteps: (p2) => fetchSteps(p2.worldEnv ?? {}, p2.runId, p2.params ?? {}),
172878
173595
  fetchStep: (p2) => fetchStep(p2.worldEnv ?? {}, p2.runId, p2.stepId, p2.resolveData),
172879
173596
  fetchEvents: (p2) => fetchEvents(p2.worldEnv ?? {}, p2.runId, p2.params ?? {}),
172880
173597
  fetchEvent: (p2) => fetchEvent(p2.worldEnv ?? {}, p2.runId, p2.eventId, p2.resolveData),
@@ -173028,7 +173745,7 @@ const route4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProper
173028
173745
  __proto__: null,
173029
173746
  loader
173030
173747
  }, Symbol.toStringTag, { value: "Module" }));
173031
- const serverManifest = { "entry": { "module": "/assets/entry.client-LwI3HNYl.js", "imports": ["/assets/index-PFjW8YjQ.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-DBp4o4Ap.js", "imports": ["/assets/index-PFjW8YjQ.js", "/assets/mermaid-3ZIDBTTL-BrUzeGHN.js", "/assets/loader-circle-BQzzSKVU.js", "/assets/arrow-up-right-C52N96YH.js"], "css": ["/assets/root-Bl5xphvU.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-CXFjRmpa.js", "imports": ["/assets/index-PFjW8YjQ.js", "/assets/workflow-graph-viewer-BI72rVK-.js", "/assets/mermaid-3ZIDBTTL-BrUzeGHN.js", "/assets/loader-circle-BQzzSKVU.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-7tPGLWpY.js", "imports": ["/assets/index-PFjW8YjQ.js", "/assets/workflow-graph-viewer-BI72rVK-.js", "/assets/mermaid-3ZIDBTTL-BrUzeGHN.js", "/assets/arrow-up-right-C52N96YH.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-9ff1658d.js", "version": "9ff1658d", "sri": void 0 };
173748
+ const serverManifest = { "entry": { "module": "/assets/entry.client-LwI3HNYl.js", "imports": ["/assets/index-PFjW8YjQ.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-qx_45_fH.js", "imports": ["/assets/index-PFjW8YjQ.js", "/assets/mermaid-3ZIDBTTL-BKwl_LgA.js", "/assets/loader-circle-BX6ycuOI.js", "/assets/arrow-up-right-CSovqivK.js"], "css": ["/assets/root-Bl5xphvU.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-BbyW_T74.js", "imports": ["/assets/index-PFjW8YjQ.js", "/assets/workflow-graph-viewer-C-1D0sAn.js", "/assets/mermaid-3ZIDBTTL-BKwl_LgA.js", "/assets/loader-circle-BX6ycuOI.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-BoGFG1Fe.js", "imports": ["/assets/index-PFjW8YjQ.js", "/assets/workflow-graph-viewer-C-1D0sAn.js", "/assets/mermaid-3ZIDBTTL-BKwl_LgA.js", "/assets/arrow-up-right-CSovqivK.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-34c486ef.js", "version": "34c486ef", "sri": void 0 };
173032
173749
  const assetsBuildDirectory = "build/client";
173033
173750
  const basename = "/";
173034
173751
  const future = { "unstable_optimizeDeps": false, "unstable_subResourceIntegrity": false, "unstable_trailingSlashAwareDataRequests": false, "unstable_previewServerPrerendering": false, "v8_middleware": false, "v8_splitRouteModules": false, "v8_viteEnvironmentApi": false };
@@ -173237,147 +173954,154 @@ function createFetchHandler(basename2 = "/") {
173237
173954
  return (request2) => handler(request2, loadContext);
173238
173955
  }
173239
173956
  export {
173240
- SPEC_VERSION_SUPPORTS_ATTRIBUTES as $,
173957
+ RUN_ENTITY_KEY as $,
173241
173958
  ANALYTICS_EVENTS_GET_MANY_LIMIT as A,
173242
173959
  BULK_CANCEL_MAX_RUN_IDS as B,
173243
173960
  CHILD_ENTITY_CREATION_EVENT_TYPES as C,
173244
173961
  DEFAULT_TIMESTAMP_THRESHOLD_FUTURE_MS as D,
173245
173962
  EVENT_ID_BODY_LENGTH as E,
173246
173963
  FIRST_EVENT_SLOT as F,
173247
- HealthCheckPayloadSchema as G,
173964
+ HOOK_LIFECYCLE_EVENT_TYPES as G,
173248
173965
  HookSchema as H,
173249
- HookCreatedEventSchema as I,
173250
- HookResumeCapabilitiesSchema as J,
173251
- NODE_HTTP_DEFAULT as K,
173252
- LegacySerializedDataSchemaV1 as L,
173253
- MessageId as M,
173966
+ HOOK_RESUME_DEDUP_VERSION as I,
173967
+ HOOK_RESUME_INPUT_VERSION as J,
173968
+ HealthCheckPayloadSchema as K,
173969
+ HookCreatedEventSchema as L,
173970
+ HookResumeCapabilitiesSchema as M,
173254
173971
  Nt as N,
173255
- NODE_HTTP_ENV_VAR as O,
173256
- PARENT_RUN_ID_ATTRIBUTE as P,
173257
- PaginatedResponseSchema as Q,
173258
- QueuePayloadSchema as R,
173259
- QueuePrefix as S,
173260
- RESERVED_ATTRIBUTE_KEY_PREFIX as T,
173261
- ROOT_RUN_ID_ATTRIBUTE as U,
173262
- RUN_ENTITY_KEY as V,
173263
- RunInputSchema as W,
173264
- SEALED_LOG_ENV_VAR as X,
173265
- SPEC_VERSION_CURRENT as Y,
173266
- SPEC_VERSION_LEGACY as Z,
173267
- SPEC_VERSION_MAX_SUPPORTED as _,
173268
- ATTRIBUTE_KEY_MAX_LENGTH as a,
173269
- Ks as a$,
173270
- SPEC_VERSION_SUPPORTS_CBOR_QUEUE_TRANSPORT as a0,
173271
- SPEC_VERSION_SUPPORTS_COMPRESSION as a1,
173272
- SPEC_VERSION_SUPPORTS_SEALED_LOG as a2,
173273
- SPEC_VERSION_SUPPORTS_SLOT_IDENTITY as a3,
173274
- STEP_EVENT_TYPES as a4,
173275
- SerializedDataSchema as a5,
173276
- StepSchema as a6,
173277
- StepStatusSchema as a7,
173278
- StructuredErrorSchema as a8,
173279
- TERMINAL_EVENT_CLASSES as a9,
173280
- isChildEntityCreationEventType as aA,
173281
- isHookEventRequiringExistence as aB,
173282
- isHookLifecycleEventType as aC,
173283
- isLegacySpecVersion as aD,
173284
- isNodeHttpEnabled as aE,
173285
- isSealedNoopEvent$1 as aF,
173286
- isSlotBody as aG,
173287
- isSlotEventId as aH,
173288
- isStepEventType as aI,
173289
- isTerminalRunEventType as aJ,
173290
- isTerminalStepEventType as aK,
173291
- isTerminalStepStatus as aL,
173292
- isTerminalWorkflowRunStatus as aM,
173293
- isWaitEventType as aN,
173294
- mintedSpecVersion as aO,
173295
- parseQueueName as aP,
173296
- reenqueueActiveRuns as aQ,
173297
- requiresNewerWorld as aR,
173298
- resolveQueueNamespace as aS,
173299
- slotToEventId as aT,
173300
- stripEventDataRefs as aU,
173301
- ulidToDate as aV,
173302
- validateAttributeChanges as aW,
173303
- validateUlidTimestamp as aX,
173304
- workflowRunIdSchema as aY,
173305
- reactExports as aZ,
173306
- R as a_,
173307
- TERMINAL_RUN_EVENT_TYPES as aa,
173308
- TERMINAL_STEP_EVENT_TYPES as ab,
173309
- TERMINAL_STEP_STATUSES as ac,
173310
- TERMINAL_WORKFLOW_RUN_STATUSES as ad,
173311
- TerminalRunEventTypeSchema as ae,
173312
- TerminalStepStatusSchema as af,
173313
- TerminalWorkflowRunStatusSchema as ag,
173314
- ValidQueueName as ah,
173315
- WAIT_EVENT_TYPES as ai,
173316
- WaitSchema as aj,
173317
- WaitStatusSchema as ak,
173318
- WorkflowInvokePayloadSchema as al,
173319
- WorkflowRunBaseSchema as am,
173320
- WorkflowRunSchema as an,
173321
- WorkflowRunStatusSchema as ao,
173322
- applyAttributeChanges as ap,
173323
- classifyEntityEvent as aq,
173324
- entityEventClass as ar,
173325
- envFlag as as,
173326
- envNumber as at,
173327
- eventIdToSlot as au,
173328
- getEventDataPayloadField as av,
173329
- getEventDataRefFields as aw,
173330
- getMaxEventsPerRun as ax,
173331
- getQueueTopicPrefix as ay,
173332
- isChildEntityCreationEvent as az,
173333
- ATTRIBUTE_MAX_PER_RUN as b,
173334
- jsxRuntimeExports as b0,
173335
- Qe as b1,
173336
- registerZstdDecoder as b2,
173337
- isWsEventsTransportEnabled as b3,
173338
- debugLog as b4,
173339
- getHttpUrl as b5,
173340
- globalSingleton as b6,
173341
- version as b7,
173342
- getHttpConfig as b8,
173343
- headersToRecord as b9,
173344
- getRequestTimeoutMs as ba,
173345
- injectTraceContextIntoHeaders as bb,
173346
- withHttpClientSpan as bc,
173347
- ErrorType as bd,
173348
- WorkflowWsReconnectAttempt as be,
173349
- NetworkProtocolName as bf,
173350
- WorkflowEventsTransport as bg,
173351
- distExports as bh,
173352
- decodeFrames as bi,
173353
- getDefaultExportFromCjs as bj,
173354
- requireTokenUtil as bk,
173355
- requireTokenError as bl,
173356
- getAugmentedNamespace as bm,
173357
- app as bn,
173358
- createFetchHandler as bo,
173359
- ATTRIBUTE_VALUE_MAX_BYTES as c,
173360
- AnalyticsAttributeKeySchema as d,
173361
- AnalyticsEventSchema as e,
173362
- AnalyticsHookSchema as f,
173363
- AnalyticsRunSchema as g,
173364
- AnalyticsStepSchema as h,
173365
- AnalyticsWaitSchema as i,
173366
- AttributeChangeSchema as j,
173367
- AttributeChangesSchema as k,
173368
- AttributeKeySchema as l,
173369
- AttributeValidationError as m,
173370
- AttributeValueSchema as n,
173371
- BaseEventSchema as o,
173372
- BulkCancelWorkflowRunResultSchema as p,
173373
- BulkCancelWorkflowRunsRequestSchema as q,
173374
- BulkCancelWorkflowRunsResultSchema as r,
173375
- DEFAULT_TIMESTAMP_THRESHOLD_PAST_MS as s,
173376
- EVENT_ID_PREFIX as t,
173377
- EventSchema as u,
173378
- EventTypeSchema as v,
173379
- HOOK_EVENTS_REQUIRING_EXISTENCE as w,
173380
- HOOK_LIFECYCLE_EVENT_TYPES as x,
173381
- HOOK_RESUME_DEDUP_VERSION as y,
173382
- HOOK_RESUME_INPUT_VERSION as z
173972
+ LegacySerializedDataSchemaV1 as O,
173973
+ MessageId as P,
173974
+ NODE_HTTP_DEFAULT as Q,
173975
+ NODE_HTTP_ENV_VAR as R,
173976
+ PARENT_RUN_ID_ATTRIBUTE as S,
173977
+ PaginatedResponseSchema as T,
173978
+ QueuePayloadSchema as U,
173979
+ QueuePrefix as V,
173980
+ RESERVED_ATTRIBUTE_KEY_PREFIX as W,
173981
+ RETENTION_ATTRIBUTE as X,
173982
+ RETENTION_DEFAULT as Y,
173983
+ RETENTION_ZERO as Z,
173984
+ ROOT_RUN_ID_ATTRIBUTE as _,
173985
+ ANALYTICS_MAX_ATTRIBUTE_FILTERS as a,
173986
+ stripEventDataRefs as a$,
173987
+ RunInputSchema as a0,
173988
+ SEALED_LOG_ENV_VAR as a1,
173989
+ SPEC_VERSION_CURRENT as a2,
173990
+ SPEC_VERSION_LEGACY as a3,
173991
+ SPEC_VERSION_MAX_SUPPORTED as a4,
173992
+ SPEC_VERSION_SUPPORTS_ATTRIBUTES as a5,
173993
+ SPEC_VERSION_SUPPORTS_CBOR_QUEUE_TRANSPORT as a6,
173994
+ SPEC_VERSION_SUPPORTS_COMPRESSION as a7,
173995
+ SPEC_VERSION_SUPPORTS_SEALED_LOG as a8,
173996
+ SPEC_VERSION_SUPPORTS_SLOT_IDENTITY as a9,
173997
+ eventIdToSlot as aA,
173998
+ getEventDataPayloadField as aB,
173999
+ getEventDataRefFields as aC,
174000
+ getMaxEventsPerRun as aD,
174001
+ getQueueTopicPrefix as aE,
174002
+ isChildEntityCreationEvent as aF,
174003
+ isChildEntityCreationEventType as aG,
174004
+ isHookEventRequiringExistence as aH,
174005
+ isHookLifecycleEventType as aI,
174006
+ isLegacySpecVersion as aJ,
174007
+ isNodeHttpEnabled as aK,
174008
+ isSealedNoopEvent$1 as aL,
174009
+ isSlotBody as aM,
174010
+ isSlotEventId as aN,
174011
+ isStepEventType as aO,
174012
+ isTerminalRunEventType as aP,
174013
+ isTerminalStepEventType as aQ,
174014
+ isTerminalStepStatus as aR,
174015
+ isTerminalWorkflowRunStatus as aS,
174016
+ isWaitEventType as aT,
174017
+ mintedSpecVersion as aU,
174018
+ parseQueueName as aV,
174019
+ readRunRetention as aW,
174020
+ reenqueueActiveRuns as aX,
174021
+ requiresNewerWorld as aY,
174022
+ resolveQueueNamespace as aZ,
174023
+ slotToEventId as a_,
174024
+ STEP_EVENT_TYPES as aa,
174025
+ SerializedDataSchema as ab,
174026
+ StepSchema as ac,
174027
+ StepStatusSchema as ad,
174028
+ StructuredErrorSchema as ae,
174029
+ TERMINAL_EVENT_CLASSES as af,
174030
+ TERMINAL_RUN_EVENT_TYPES as ag,
174031
+ TERMINAL_STEP_EVENT_TYPES as ah,
174032
+ TERMINAL_STEP_STATUSES as ai,
174033
+ TERMINAL_WORKFLOW_RUN_STATUSES as aj,
174034
+ TerminalRunEventTypeSchema as ak,
174035
+ TerminalStepStatusSchema as al,
174036
+ TerminalWorkflowRunStatusSchema as am,
174037
+ ValidQueueName as an,
174038
+ WAIT_EVENT_TYPES as ao,
174039
+ WaitSchema as ap,
174040
+ WaitStatusSchema as aq,
174041
+ WorkflowInvokePayloadSchema as ar,
174042
+ WorkflowRunBaseSchema as as,
174043
+ WorkflowRunSchema as at,
174044
+ WorkflowRunStatusSchema as au,
174045
+ applyAttributeChanges as av,
174046
+ classifyEntityEvent as aw,
174047
+ entityEventClass as ax,
174048
+ envFlag as ay,
174049
+ envNumber as az,
174050
+ ANALYTICS_PAGE_LIMIT as b,
174051
+ ulidToDate as b0,
174052
+ validateAttributeChanges as b1,
174053
+ validateUlidTimestamp as b2,
174054
+ workflowRunIdSchema as b3,
174055
+ reactExports as b4,
174056
+ R as b5,
174057
+ Ks as b6,
174058
+ jsxRuntimeExports as b7,
174059
+ Qe as b8,
174060
+ registerZstdDecoder as b9,
174061
+ isWsEventsTransportEnabled as ba,
174062
+ debugLog as bb,
174063
+ getHttpUrl as bc,
174064
+ globalSingleton as bd,
174065
+ version as be,
174066
+ getHttpConfig as bf,
174067
+ headersToRecord as bg,
174068
+ getRequestTimeoutMs as bh,
174069
+ injectTraceContextIntoHeaders as bi,
174070
+ withHttpClientSpan as bj,
174071
+ ErrorType as bk,
174072
+ WorkflowWsReconnectAttempt as bl,
174073
+ NetworkProtocolName as bm,
174074
+ WorkflowEventsTransport as bn,
174075
+ distExports as bo,
174076
+ decodeFrames as bp,
174077
+ getDefaultExportFromCjs as bq,
174078
+ requireTokenUtil as br,
174079
+ requireTokenError as bs,
174080
+ getAugmentedNamespace as bt,
174081
+ app as bu,
174082
+ createFetchHandler as bv,
174083
+ ANALYTICS_RUN_SCOPED_PAGE_LIMIT as c,
174084
+ ATTRIBUTE_KEY_MAX_LENGTH as d,
174085
+ ATTRIBUTE_MAX_PER_RUN as e,
174086
+ ATTRIBUTE_VALUE_MAX_BYTES as f,
174087
+ AnalyticsAttributeKeySchema as g,
174088
+ AnalyticsEventSchema as h,
174089
+ AnalyticsHookSchema as i,
174090
+ AnalyticsRunSchema as j,
174091
+ AnalyticsStepSchema as k,
174092
+ AnalyticsWaitSchema as l,
174093
+ AttributeChangeSchema as m,
174094
+ AttributeChangesSchema as n,
174095
+ AttributeKeySchema as o,
174096
+ AttributeValidationError as p,
174097
+ AttributeValueSchema as q,
174098
+ BaseEventSchema as r,
174099
+ BulkCancelWorkflowRunResultSchema as s,
174100
+ BulkCancelWorkflowRunsRequestSchema as t,
174101
+ BulkCancelWorkflowRunsResultSchema as u,
174102
+ DEFAULT_TIMESTAMP_THRESHOLD_PAST_MS as v,
174103
+ EVENT_ID_PREFIX as w,
174104
+ EventSchema as x,
174105
+ EventTypeSchema as y,
174106
+ HOOK_EVENTS_REQUIRING_EXISTENCE as z
173383
174107
  };