@workflow/world-testing 5.0.0-beta.53 → 5.0.0-beta.54

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.
@@ -20629,6 +20629,12 @@ function readRunRetention(attributes) {
20629
20629
  function purgesUserDataOnFinish(attributes) {
20630
20630
  return readRunRetention(attributes).mode === "none";
20631
20631
  }
20632
+ function validateAttributeEventDataSize2(eventData) {
20633
+ const bytes = textEncoder3.encode(JSON.stringify(eventData)).length;
20634
+ if (bytes > ATTRIBUTE_EVENT_DATA_MAX_BYTES2) {
20635
+ throw new AttributeValidationError2(`Attribute eventData exceeds limit ${ATTRIBUTE_EVENT_DATA_MAX_BYTES2} UTF-8 JSON bytes (received ${bytes} bytes). Split the changes into smaller setAttributes() calls.`);
20636
+ }
20637
+ }
20632
20638
  function assertValidAttributeKey2(key, allowReservedAttributes) {
20633
20639
  if (typeof key !== "string") {
20634
20640
  throw new AttributeValidationError2(`Attribute key must be a string, got ${typeof key}`);
@@ -20692,7 +20698,7 @@ function applyAttributeChanges(existing, changes) {
20692
20698
  }
20693
20699
  return next2;
20694
20700
  }
20695
- var RESERVED_ATTRIBUTE_KEY_PREFIX2, ROOT_RUN_ID_ATTRIBUTE2, PARENT_RUN_ID_ATTRIBUTE2, RETENTION_ATTRIBUTE2, RETENTION_ZERO, RETENTION_DEFAULT, RETENTION_INTEGER_PATTERN, ATTRIBUTE_KEY_MAX_LENGTH2, ATTRIBUTE_VALUE_MAX_BYTES2, ATTRIBUTE_MAX_PER_RUN2, textEncoder3, AttributeValidationError2;
20701
+ var RESERVED_ATTRIBUTE_KEY_PREFIX2, ROOT_RUN_ID_ATTRIBUTE2, PARENT_RUN_ID_ATTRIBUTE2, RETENTION_ATTRIBUTE2, RETENTION_ZERO, RETENTION_DEFAULT, RETENTION_INTEGER_PATTERN, ATTRIBUTE_KEY_MAX_LENGTH2, ATTRIBUTE_VALUE_MAX_BYTES2, ATTRIBUTE_MAX_PER_RUN2, ATTRIBUTE_EVENT_DATA_MAX_BYTES2, textEncoder3, AttributeValidationError2;
20696
20702
  var init_attributes_validation2 = __esm({
20697
20703
  "../world/dist/attributes-validation.js"() {
20698
20704
  "use strict";
@@ -20708,6 +20714,7 @@ var init_attributes_validation2 = __esm({
20708
20714
  ATTRIBUTE_KEY_MAX_LENGTH2 = 256;
20709
20715
  ATTRIBUTE_VALUE_MAX_BYTES2 = 256;
20710
20716
  ATTRIBUTE_MAX_PER_RUN2 = 64;
20717
+ ATTRIBUTE_EVENT_DATA_MAX_BYTES2 = 8192;
20711
20718
  textEncoder3 = new TextEncoder();
20712
20719
  AttributeValidationError2 = class extends Error {
20713
20720
  static {
@@ -20718,6 +20725,7 @@ var init_attributes_validation2 = __esm({
20718
20725
  this.name = "AttributeValidationError";
20719
20726
  }
20720
20727
  };
20728
+ __name(validateAttributeEventDataSize2, "validateAttributeEventDataSize");
20721
20729
  __name(assertValidAttributeKey2, "assertValidAttributeKey");
20722
20730
  __name(assertValidAttributeValue2, "assertValidAttributeValue");
20723
20731
  __name(attributeCountDelta2, "attributeCountDelta");
@@ -21899,6 +21907,11 @@ var init_queue2 = __esm({
21899
21907
  }));
21900
21908
  WorkflowInvokePayloadSchema2 = external_exports2.compile(external_exports2.object({
21901
21909
  runId: external_exports2.string(),
21910
+ /** Process this input and return the handler's result as response data. */
21911
+ invoke: external_exports2.literal(true).optional(),
21912
+ /** Identifies one input across retries, separately from the queue delivery ID. */
21913
+ requestId: external_exports2.string().optional(),
21914
+ input: external_exports2.unknown().optional(),
21902
21915
  traceCarrier: TraceCarrierSchema2.optional(),
21903
21916
  requestedAt: external_exports2.coerce.date().optional(),
21904
21917
  /**
@@ -22509,6 +22522,7 @@ __export(dist_exports, {
22509
22522
  ANALYTICS_MAX_ATTRIBUTE_FILTERS: () => ANALYTICS_MAX_ATTRIBUTE_FILTERS,
22510
22523
  ANALYTICS_PAGE_LIMIT: () => ANALYTICS_PAGE_LIMIT,
22511
22524
  ANALYTICS_RUN_SCOPED_PAGE_LIMIT: () => ANALYTICS_RUN_SCOPED_PAGE_LIMIT,
22525
+ ATTRIBUTE_EVENT_DATA_MAX_BYTES: () => ATTRIBUTE_EVENT_DATA_MAX_BYTES2,
22512
22526
  ATTRIBUTE_KEY_MAX_LENGTH: () => ATTRIBUTE_KEY_MAX_LENGTH2,
22513
22527
  ATTRIBUTE_MAX_PER_RUN: () => ATTRIBUTE_MAX_PER_RUN2,
22514
22528
  ATTRIBUTE_VALUE_MAX_BYTES: () => ATTRIBUTE_VALUE_MAX_BYTES2,
@@ -22633,6 +22647,7 @@ __export(dist_exports, {
22633
22647
  stripEventDataRefs: () => stripEventDataRefs,
22634
22648
  ulidToDate: () => ulidToDate,
22635
22649
  validateAttributeChanges: () => validateAttributeChanges2,
22650
+ validateAttributeEventDataSize: () => validateAttributeEventDataSize2,
22636
22651
  validateUlidTimestamp: () => validateUlidTimestamp,
22637
22652
  workflowRunIdSchema: () => workflowRunIdSchema2
22638
22653
  });
@@ -29272,7 +29287,7 @@ var require_dispatcher = __commonJS({
29272
29287
  "use strict";
29273
29288
  var EventEmitter3 = __require("node:events");
29274
29289
  var WrapHandler = require_wrap_handler();
29275
- var wrapInterceptor = /* @__PURE__ */ __name((dispatch) => (opts, handler) => dispatch(opts, WrapHandler.wrap(handler)), "wrapInterceptor");
29290
+ var wrapInterceptor = /* @__PURE__ */ __name((dispatch2) => (opts, handler) => dispatch2(opts, WrapHandler.wrap(handler)), "wrapInterceptor");
29276
29291
  var Dispatcher = class extends EventEmitter3 {
29277
29292
  static {
29278
29293
  __name(this, "Dispatcher");
@@ -29288,7 +29303,7 @@ var require_dispatcher = __commonJS({
29288
29303
  }
29289
29304
  compose(...args) {
29290
29305
  const interceptors = Array.isArray(args[0]) ? args[0] : args;
29291
- let dispatch = this.dispatch.bind(this);
29306
+ let dispatch2 = this.dispatch.bind(this);
29292
29307
  for (const interceptor of interceptors) {
29293
29308
  if (interceptor == null) {
29294
29309
  continue;
@@ -29296,14 +29311,14 @@ var require_dispatcher = __commonJS({
29296
29311
  if (typeof interceptor !== "function") {
29297
29312
  throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`);
29298
29313
  }
29299
- dispatch = interceptor(dispatch);
29300
- dispatch = wrapInterceptor(dispatch);
29301
- if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
29314
+ dispatch2 = interceptor(dispatch2);
29315
+ dispatch2 = wrapInterceptor(dispatch2);
29316
+ if (dispatch2 == null || typeof dispatch2 !== "function" || dispatch2.length !== 2) {
29302
29317
  throw new TypeError("invalid interceptor");
29303
29318
  }
29304
29319
  }
29305
29320
  return new Proxy(this, {
29306
- get: /* @__PURE__ */ __name((target2, key) => key === "dispatch" ? dispatch : target2[key], "get")
29321
+ get: /* @__PURE__ */ __name((target2, key) => key === "dispatch" ? dispatch2 : target2[key], "get")
29307
29322
  });
29308
29323
  }
29309
29324
  };
@@ -37913,7 +37928,7 @@ var require_retry_handler = __commonJS({
37913
37928
  static {
37914
37929
  __name(this, "RetryHandler");
37915
37930
  }
37916
- constructor(opts, { dispatch, handler }) {
37931
+ constructor(opts, { dispatch: dispatch2, handler }) {
37917
37932
  const { retryOptions, ...dispatchOpts } = opts;
37918
37933
  const {
37919
37934
  // Retry scoped
@@ -37930,7 +37945,7 @@ var require_retry_handler = __commonJS({
37930
37945
  throwOnError
37931
37946
  } = retryOptions ?? {};
37932
37947
  this.error = null;
37933
- this.dispatch = dispatch;
37948
+ this.dispatch = dispatch2;
37934
37949
  this.handler = WrapHandler.wrap(handler);
37935
37950
  this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) };
37936
37951
  this.retryOpts = {
@@ -39779,11 +39794,11 @@ var require_mock_utils = __commonJS({
39779
39794
  }
39780
39795
  __name(addMockDispatch, "addMockDispatch");
39781
39796
  function deleteMockDispatch(mockDispatches, key) {
39782
- const index = mockDispatches.findIndex((dispatch) => {
39783
- if (!dispatch.consumed) {
39797
+ const index = mockDispatches.findIndex((dispatch2) => {
39798
+ if (!dispatch2.consumed) {
39784
39799
  return false;
39785
39800
  }
39786
- return matchKey(dispatch, key);
39801
+ return matchKey(dispatch2, key);
39787
39802
  });
39788
39803
  if (index !== -1) {
39789
39804
  mockDispatches.splice(index, 1);
@@ -39911,7 +39926,7 @@ var require_mock_utils = __commonJS({
39911
39926
  const agent = this[kMockAgent];
39912
39927
  const origin = this[kOrigin];
39913
39928
  const originalDispatch = this[kOriginalDispatch];
39914
- return /* @__PURE__ */ __name(function dispatch(opts, handler) {
39929
+ return /* @__PURE__ */ __name(function dispatch2(opts, handler) {
39915
39930
  if (agent.isMockActive) {
39916
39931
  try {
39917
39932
  mockDispatch.call(this, opts, handler);
@@ -40714,7 +40729,7 @@ var require_mock_agent = __commonJS({
40714
40729
  }
40715
40730
  pendingInterceptors() {
40716
40731
  const mockAgentClients = this[kClients];
40717
- return Array.from(mockAgentClients.entries()).flatMap(([origin, result2]) => result2.dispatcher[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
40732
+ return Array.from(mockAgentClients.entries()).flatMap(([origin, result2]) => result2.dispatcher[kDispatches].map((dispatch2) => ({ ...dispatch2, origin }))).filter(({ pending }) => pending);
40718
40733
  }
40719
40734
  assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
40720
40735
  const pending = this.pendingInterceptors();
@@ -41648,14 +41663,14 @@ var require_redirect_handler = __commonJS({
41648
41663
  if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
41649
41664
  throw new InvalidArgumentError("maxRedirections must be a positive number");
41650
41665
  }
41651
- const dispatch = dispatcher.dispatch.bind(dispatcher);
41652
- return (opts, originalHandler) => dispatch(opts, new _RedirectHandler(dispatch, maxRedirections, opts, originalHandler));
41666
+ const dispatch2 = dispatcher.dispatch.bind(dispatcher);
41667
+ return (opts, originalHandler) => dispatch2(opts, new _RedirectHandler(dispatch2, maxRedirections, opts, originalHandler));
41653
41668
  }
41654
- constructor(dispatch, maxRedirections, opts, handler) {
41669
+ constructor(dispatch2, maxRedirections, opts, handler) {
41655
41670
  if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
41656
41671
  throw new InvalidArgumentError("maxRedirections must be a positive number");
41657
41672
  }
41658
- this.dispatch = dispatch;
41673
+ this.dispatch = dispatch2;
41659
41674
  this.location = null;
41660
41675
  const { maxRedirections: _, ...cleanOpts } = opts;
41661
41676
  this.opts = cleanOpts;
@@ -41787,15 +41802,15 @@ var require_redirect = __commonJS({
41787
41802
  "use strict";
41788
41803
  var RedirectHandler = require_redirect_handler();
41789
41804
  function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections } = {}) {
41790
- return (dispatch) => {
41805
+ return (dispatch2) => {
41791
41806
  return /* @__PURE__ */ __name(function Intercept(opts, handler) {
41792
41807
  const { maxRedirections = defaultMaxRedirections, ...rest } = opts;
41793
41808
  if (maxRedirections == null || maxRedirections === 0) {
41794
- return dispatch(opts, handler);
41809
+ return dispatch2(opts, handler);
41795
41810
  }
41796
41811
  const dispatchOpts = { ...rest };
41797
- const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler);
41798
- return dispatch(dispatchOpts, redirectHandler);
41812
+ const redirectHandler = new RedirectHandler(dispatch2, maxRedirections, dispatchOpts, handler);
41813
+ return dispatch2(dispatchOpts, redirectHandler);
41799
41814
  }, "Intercept");
41800
41815
  };
41801
41816
  }
@@ -41880,9 +41895,9 @@ var require_response_error = __commonJS({
41880
41895
  }
41881
41896
  };
41882
41897
  module.exports = () => {
41883
- return (dispatch) => {
41898
+ return (dispatch2) => {
41884
41899
  return /* @__PURE__ */ __name(function Intercept(opts, handler) {
41885
- return dispatch(opts, new ResponseErrorHandler(opts, { handler }));
41900
+ return dispatch2(opts, new ResponseErrorHandler(opts, { handler }));
41886
41901
  }, "Intercept");
41887
41902
  };
41888
41903
  };
@@ -41895,15 +41910,15 @@ var require_retry = __commonJS({
41895
41910
  "use strict";
41896
41911
  var RetryHandler = require_retry_handler();
41897
41912
  module.exports = (globalOpts) => {
41898
- return (dispatch) => {
41913
+ return (dispatch2) => {
41899
41914
  return /* @__PURE__ */ __name(function retryInterceptor(opts, handler) {
41900
- return dispatch(
41915
+ return dispatch2(
41901
41916
  opts,
41902
41917
  new RetryHandler(
41903
41918
  { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
41904
41919
  {
41905
41920
  handler,
41906
- dispatch
41921
+ dispatch: dispatch2
41907
41922
  }
41908
41923
  )
41909
41924
  );
@@ -41990,11 +42005,11 @@ var require_dump = __commonJS({
41990
42005
  function createDumpInterceptor({ maxSize: defaultMaxSize } = {
41991
42006
  maxSize: 1024 * 1024
41992
42007
  }) {
41993
- return (dispatch) => {
42008
+ return (dispatch2) => {
41994
42009
  return /* @__PURE__ */ __name(function Intercept(opts, handler) {
41995
42010
  const { dumpMaxSize = defaultMaxSize } = opts;
41996
42011
  const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler);
41997
- return dispatch(opts, dumpHandler);
42012
+ return dispatch2(opts, dumpHandler);
41998
42013
  }, "Intercept");
41999
42014
  };
42000
42015
  }
@@ -42329,13 +42344,13 @@ var require_dns = __commonJS({
42329
42344
  #controller = null;
42330
42345
  #newOrigin = null;
42331
42346
  #firstTry = true;
42332
- constructor(state, { origin, handler, dispatch, newOrigin }, opts) {
42347
+ constructor(state, { origin, handler, dispatch: dispatch2, newOrigin }, opts) {
42333
42348
  super(handler);
42334
42349
  this.#origin = origin;
42335
42350
  this.#newOrigin = newOrigin;
42336
42351
  this.#opts = { ...opts };
42337
42352
  this.#state = state;
42338
- this.#dispatch = dispatch;
42353
+ this.#dispatch = dispatch2;
42339
42354
  }
42340
42355
  onResponseError(controller, err) {
42341
42356
  switch (err.code) {
@@ -42424,11 +42439,11 @@ var require_dns = __commonJS({
42424
42439
  storage: interceptorOpts?.storage
42425
42440
  };
42426
42441
  const instance = new DNSInstance(opts);
42427
- return (dispatch) => {
42442
+ return (dispatch2) => {
42428
42443
  return /* @__PURE__ */ __name(function dnsInterceptor(origDispatchOpts, handler) {
42429
42444
  const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
42430
42445
  if (isIP(origin.hostname) !== 0) {
42431
- return dispatch(origDispatchOpts, handler);
42446
+ return dispatch2(origDispatchOpts, handler);
42432
42447
  }
42433
42448
  instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
42434
42449
  if (err) {
@@ -42441,10 +42456,10 @@ var require_dns = __commonJS({
42441
42456
  origin: newOrigin.origin,
42442
42457
  headers: withHostHeader(origin.host, origDispatchOpts.headers)
42443
42458
  };
42444
- dispatch(
42459
+ dispatch2(
42445
42460
  dispatchOpts,
42446
42461
  instance.getHandler(
42447
- { origin, dispatch, handler, newOrigin },
42462
+ { origin, dispatch: dispatch2, handler, newOrigin },
42448
42463
  origDispatchOpts
42449
42464
  )
42450
42465
  );
@@ -44465,7 +44480,7 @@ var require_cache3 = __commonJS({
44465
44480
  return now2 <= staleWhileRevalidateExpiry;
44466
44481
  }
44467
44482
  __name(withinStaleWhileRevalidateWindow, "withinStaleWhileRevalidateWindow");
44468
- function handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) {
44483
+ function handleUncachedResponse(dispatch2, globalOpts, cacheKey, handler, opts, reqCacheControl) {
44469
44484
  if (reqCacheControl?.["only-if-cached"]) {
44470
44485
  let aborted3 = false;
44471
44486
  try {
@@ -44493,7 +44508,7 @@ var require_cache3 = __commonJS({
44493
44508
  }
44494
44509
  return true;
44495
44510
  }
44496
- return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
44511
+ return dispatch2(opts, new CacheHandler(globalOpts, cacheKey, handler));
44497
44512
  }
44498
44513
  __name(handleUncachedResponse, "handleUncachedResponse");
44499
44514
  function sendCachedValue(handler, opts, result2, age, context2, isStale2) {
@@ -44551,13 +44566,13 @@ var require_cache3 = __commonJS({
44551
44566
  }
44552
44567
  }
44553
44568
  __name(sendCachedValue, "sendCachedValue");
44554
- function handleResult(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result2) {
44569
+ function handleResult(dispatch2, globalOpts, cacheKey, handler, opts, reqCacheControl, result2) {
44555
44570
  if (!result2) {
44556
- return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
44571
+ return handleUncachedResponse(dispatch2, globalOpts, cacheKey, handler, opts, reqCacheControl);
44557
44572
  }
44558
44573
  const now2 = Date.now();
44559
44574
  if (now2 > result2.deleteAt) {
44560
- return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
44575
+ return dispatch2(opts, new CacheHandler(globalOpts, cacheKey, handler));
44561
44576
  }
44562
44577
  const age = Math.round((now2 - result2.cachedAt) / 1e3);
44563
44578
  const requestMaxAgeExpired = reqCacheControl?.["max-age"] !== void 0 && age >= reqCacheControl["max-age"];
@@ -44565,13 +44580,13 @@ var require_cache3 = __commonJS({
44565
44580
  const revalidate = requestMaxAgeExpired || needsRevalidation(result2, reqCacheControl, opts);
44566
44581
  if (stale || revalidate) {
44567
44582
  if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
44568
- return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
44583
+ return dispatch2(opts, new CacheHandler(globalOpts, cacheKey, handler));
44569
44584
  }
44570
44585
  if (!revalidate && withinStaleWhileRevalidateWindow(result2, globalOpts.type)) {
44571
44586
  sendCachedValue(handler, opts, result2, age, null, true);
44572
44587
  queueMicrotask(() => {
44573
44588
  const headers2 = makeRevalidationHeaders(opts, result2);
44574
- dispatch(
44589
+ dispatch2(
44575
44590
  {
44576
44591
  ...opts,
44577
44592
  headers: headers2
@@ -44603,7 +44618,7 @@ var require_cache3 = __commonJS({
44603
44618
  }
44604
44619
  }
44605
44620
  const headers = makeRevalidationHeaders(opts, result2);
44606
- return dispatch(
44621
+ return dispatch2(
44607
44622
  {
44608
44623
  ...opts,
44609
44624
  headers
@@ -44617,7 +44632,7 @@ var require_cache3 = __commonJS({
44617
44632
  result2.body.on("error", nop).destroy();
44618
44633
  }
44619
44634
  deleteCachedValue(globalOpts.store, cacheKey);
44620
- return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
44635
+ return dispatch2(opts, new CacheHandler(globalOpts, cacheKey, handler));
44621
44636
  }
44622
44637
  if (revalidationResponseUpdatesCacheControl(headers2)) {
44623
44638
  deleteCachedValue(globalOpts.store, cacheKey);
@@ -44672,10 +44687,10 @@ var require_cache3 = __commonJS({
44672
44687
  safeMethodsToNotCache.push(method);
44673
44688
  }
44674
44689
  }
44675
- return (dispatch) => {
44690
+ return (dispatch2) => {
44676
44691
  return (opts2, handler) => {
44677
44692
  if (!opts2.origin || arrayIncludes(safeMethodsToNotCache, opts2.method)) {
44678
- return dispatch(opts2, handler);
44693
+ return dispatch2(opts2, handler);
44679
44694
  }
44680
44695
  if (origins !== void 0) {
44681
44696
  const requestOrigin = opts2.origin.toString().toLowerCase();
@@ -44693,7 +44708,7 @@ var require_cache3 = __commonJS({
44693
44708
  }
44694
44709
  }
44695
44710
  if (!isAllowed) {
44696
- return dispatch(opts2, handler);
44711
+ return dispatch2(opts2, handler);
44697
44712
  }
44698
44713
  }
44699
44714
  opts2 = {
@@ -44702,13 +44717,13 @@ var require_cache3 = __commonJS({
44702
44717
  };
44703
44718
  const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : hasPragmaNoCache(opts2.headers) ? { "no-cache": true } : void 0;
44704
44719
  if (reqCacheControl?.["no-store"]) {
44705
- return dispatch(opts2, handler);
44720
+ return dispatch2(opts2, handler);
44706
44721
  }
44707
44722
  const cacheKey = makeCacheKey(opts2);
44708
44723
  const result2 = store.get(cacheKey);
44709
44724
  if (result2 && typeof result2.then === "function") {
44710
44725
  return result2.then((result3) => handleResult(
44711
- dispatch,
44726
+ dispatch2,
44712
44727
  globalOpts,
44713
44728
  cacheKey,
44714
44729
  handler,
@@ -44718,7 +44733,7 @@ var require_cache3 = __commonJS({
44718
44733
  ));
44719
44734
  } else {
44720
44735
  return handleResult(
44721
- dispatch,
44736
+ dispatch2,
44722
44737
  globalOpts,
44723
44738
  cacheKey,
44724
44739
  handler,
@@ -44939,10 +44954,10 @@ var require_decompress = __commonJS({
44939
44954
  );
44940
44955
  warningEmitted = true;
44941
44956
  }
44942
- return (dispatch) => {
44957
+ return (dispatch2) => {
44943
44958
  return (opts, handler) => {
44944
44959
  const decompressHandler = new DecompressHandler(handler, options);
44945
- return dispatch(opts, decompressHandler);
44960
+ return dispatch2(opts, decompressHandler);
44946
44961
  };
44947
44962
  };
44948
44963
  }
@@ -45352,10 +45367,10 @@ var require_deduplicate = __commonJS({
45352
45367
  const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase()));
45353
45368
  const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase()));
45354
45369
  const pendingRequests = /* @__PURE__ */ new Map();
45355
- return (dispatch) => {
45370
+ return (dispatch2) => {
45356
45371
  return (opts2, handler) => {
45357
45372
  if (!opts2.origin || methods.includes(opts2.method) === false) {
45358
- return dispatch(opts2, handler);
45373
+ return dispatch2(opts2, handler);
45359
45374
  }
45360
45375
  opts2 = {
45361
45376
  ...opts2,
@@ -45364,7 +45379,7 @@ var require_deduplicate = __commonJS({
45364
45379
  if (skipHeaderNamesSet.size > 0) {
45365
45380
  for (const headerName of Object.keys(opts2.headers)) {
45366
45381
  if (skipHeaderNamesSet.has(headerName.toLowerCase())) {
45367
- return dispatch(opts2, handler);
45382
+ return dispatch2(opts2, handler);
45368
45383
  }
45369
45384
  }
45370
45385
  }
@@ -45375,7 +45390,7 @@ var require_deduplicate = __commonJS({
45375
45390
  if (pendingHandler.addWaitingHandler(handler)) {
45376
45391
  return true;
45377
45392
  }
45378
- return dispatch(opts2, handler);
45393
+ return dispatch2(opts2, handler);
45379
45394
  }
45380
45395
  const deduplicationHandler = new DeduplicationHandler(
45381
45396
  handler,
@@ -45391,7 +45406,7 @@ var require_deduplicate = __commonJS({
45391
45406
  if (pendingRequestsChannel.hasSubscribers) {
45392
45407
  pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "added" });
45393
45408
  }
45394
- return dispatch(opts2, deduplicationHandler);
45409
+ return dispatch2(opts2, deduplicationHandler);
45395
45410
  };
45396
45411
  };
45397
45412
  };
@@ -48451,7 +48466,7 @@ var require_fetch = __commonJS({
48451
48466
  })();
48452
48467
  }
48453
48468
  try {
48454
- const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody });
48469
+ const { body, status, statusText, headersList, socket } = await dispatch2({ body: requestBody });
48455
48470
  if (socket) {
48456
48471
  response = makeResponse({ status, statusText, headersList, socket });
48457
48472
  } else {
@@ -48548,7 +48563,7 @@ var require_fetch = __commonJS({
48548
48563
  }
48549
48564
  __name(onAborted, "onAborted");
48550
48565
  return response;
48551
- function dispatch({ body }) {
48566
+ function dispatch2({ body }) {
48552
48567
  const url3 = requestCurrentURL(request);
48553
48568
  const agent = fetchParams.controller.dispatcher;
48554
48569
  const path15 = url3.pathname + url3.search;
@@ -48729,7 +48744,7 @@ var require_fetch = __commonJS({
48729
48744
  }
48730
48745
  ));
48731
48746
  }
48732
- __name(dispatch, "dispatch");
48747
+ __name(dispatch2, "dispatch");
48733
48748
  }
48734
48749
  __name(httpNetworkFetch, "httpNetworkFetch");
48735
48750
  module.exports = {
@@ -53163,8 +53178,11 @@ function createQueue(config4) {
53163
53178
  const body = await new TypedJsonTransport().deserialize(req.body);
53164
53179
  try {
53165
53180
  const result2 = await handler(body, { attempt, queueName, messageId });
53181
+ if (typeof body === "object" && body !== null && "invoke" in body && body.invoke === true) {
53182
+ return Response.json({ result: result2 });
53183
+ }
53166
53184
  let timeoutSeconds = null;
53167
- if (typeof result2?.timeoutSeconds === "number") {
53185
+ if (typeof result2 === "object" && result2 !== null && "timeoutSeconds" in result2 && typeof result2.timeoutSeconds === "number") {
53168
53186
  timeoutSeconds = Math.min(result2.timeoutSeconds, LOCAL_QUEUE_MAX_VISIBILITY);
53169
53187
  }
53170
53188
  if (timeoutSeconds != null) {
@@ -61824,7 +61842,7 @@ var version4;
61824
61842
  var init_version3 = __esm({
61825
61843
  "../world-vercel/dist/version.js"() {
61826
61844
  "use strict";
61827
- version4 = "5.0.0-beta.48";
61845
+ version4 = "5.0.0-beta.49";
61828
61846
  }
61829
61847
  });
61830
61848
 
@@ -61872,7 +61890,7 @@ function deadlineInterceptor(timeoutMs) {
61872
61890
  super.onResponseError(controller, error121);
61873
61891
  }
61874
61892
  }
61875
- return (dispatch) => (opts, handler) => dispatch(opts, new DeadlineHandler(handler));
61893
+ return (dispatch2) => (opts, handler) => dispatch2(opts, new DeadlineHandler(handler));
61876
61894
  }
61877
61895
  function h2EventsEnabled() {
61878
61896
  return process.env.WORKFLOW_H2_MULTIPLEX !== "0";
@@ -61885,13 +61903,13 @@ function contentLength(headers) {
61885
61903
  const raw = record3["content-length"] ?? record3["Content-Length"];
61886
61904
  return typeof raw === "string" || typeof raw === "number" ? Number(raw) : Number.NaN;
61887
61905
  }
61888
- function h2MultiplexInterceptor(dispatch) {
61906
+ function h2MultiplexInterceptor(dispatch2) {
61889
61907
  return (opts, handler) => {
61890
61908
  const body = opts.body;
61891
61909
  const isAsyncIterable = !!body && typeof body !== "string" && !Buffer.isBuffer(body) && typeof body[Symbol.asyncIterator] === "function";
61892
61910
  const length = contentLength(opts.headers);
61893
61911
  if (!isAsyncIterable || !(length >= 0) || length > H2_REBUFFER_MAX_BYTES) {
61894
- return dispatch({ ...opts, idempotent: true }, handler);
61912
+ return dispatch2({ ...opts, idempotent: true }, handler);
61895
61913
  }
61896
61914
  void (async () => {
61897
61915
  try {
@@ -61899,7 +61917,7 @@ function h2MultiplexInterceptor(dispatch) {
61899
61917
  for await (const chunk of body) {
61900
61918
  chunks.push(Buffer.from(chunk));
61901
61919
  }
61902
- dispatch({ ...opts, body: Buffer.concat(chunks), idempotent: true }, handler);
61920
+ dispatch2({ ...opts, body: Buffer.concat(chunks), idempotent: true }, handler);
61903
61921
  } catch (error121) {
61904
61922
  handler.onError?.(error121);
61905
61923
  }
@@ -68629,13 +68647,13 @@ var require_functions2 = __commonJS({
68629
68647
  ipAddress: /* @__PURE__ */ __name(() => import_headers.ipAddress, "ipAddress"),
68630
68648
  next: /* @__PURE__ */ __name(() => import_middleware.next, "next"),
68631
68649
  rewrite: /* @__PURE__ */ __name(() => import_middleware.rewrite, "rewrite"),
68632
- waitUntil: /* @__PURE__ */ __name(() => import_wait_until4.waitUntil, "waitUntil")
68650
+ waitUntil: /* @__PURE__ */ __name(() => import_wait_until5.waitUntil, "waitUntil")
68633
68651
  });
68634
68652
  module.exports = __toCommonJS(src_exports);
68635
68653
  var import_headers = require_headers3();
68636
68654
  var import_get_env = require_get_env2();
68637
68655
  var import_deadline = require_deadline2();
68638
- var import_wait_until4 = require_wait_until2();
68656
+ var import_wait_until5 = require_wait_until2();
68639
68657
  var import_middleware = require_middleware2();
68640
68658
  var import_cache = require_cache5();
68641
68659
  var import_db_connections = require_db_connections2();
@@ -74767,7 +74785,7 @@ function createQueue2(config4) {
74767
74785
  attempt: metadata.deliveryCount,
74768
74786
  requestId
74769
74787
  });
74770
- if (typeof result2?.timeoutSeconds === "number") {
74788
+ if (!("invoke" in payload && payload.invoke === true) && typeof result2 === "object" && result2 !== null && "timeoutSeconds" in result2 && typeof result2.timeoutSeconds === "number") {
74771
74789
  const delaySeconds = result2.timeoutSeconds > 0 ? Math.min(result2.timeoutSeconds, MAX_DELAY_SECONDS) : void 0;
74772
74790
  await queue(queueName, payload, { deploymentId, delaySeconds });
74773
74791
  }
@@ -76566,6 +76584,15 @@ function validateWorkflowRunIdTimestamp(id) {
76566
76584
  function assertEventDataWireContractExhaustive() {
76567
76585
  }
76568
76586
  function splitEventDataForV4(data) {
76587
+ if (data.eventType === "attr_set") {
76588
+ try {
76589
+ validateAttributeEventDataSize2(data.eventData);
76590
+ } catch (error121) {
76591
+ if (!(error121 instanceof AttributeValidationError2))
76592
+ throw error121;
76593
+ throw new WorkflowWorldError2(error121.message, { status: 400 });
76594
+ }
76595
+ }
76569
76596
  const eventData = data.eventData ?? {};
76570
76597
  const payloadField = getEventDataPayloadField(data.eventType);
76571
76598
  const meta5 = {};
@@ -76905,6 +76932,7 @@ var init_events3 = __esm({
76905
76932
  "use strict";
76906
76933
  init_dist7();
76907
76934
  init_dist6();
76935
+ init_attributes_validation2();
76908
76936
  init_event_retry();
76909
76937
  init_events_v4();
76910
76938
  init_run_id();
@@ -79864,12 +79892,25 @@ async function awaitEarlierDeliveries(ctx, eventIndex, kind) {
79864
79892
  await new Promise((resolve3) => setTimeout(resolve3, 0));
79865
79893
  }
79866
79894
  }
79867
- function registerDeliveryBarrier(ctx, eventIndex, kind, options = {}) {
79895
+ function registerDeliveryBarrier(ctx, eventIndex, kind, options) {
79896
+ let deliveredToWorkflow = false;
79897
+ const deliver = /* @__PURE__ */ __name(() => {
79898
+ if (deliveredToWorkflow) {
79899
+ return false;
79900
+ }
79901
+ deliveredToWorkflow = true;
79902
+ ctx.advanceClock?.(options.deliveredAt);
79903
+ return true;
79904
+ }, "deliver");
79868
79905
  const barriers = ctx.pendingDeliveryBarriers;
79869
79906
  if (!barriers || eventIndex === void 0) {
79870
- return { markDelivered: /* @__PURE__ */ __name(() => {
79871
- }, "markDelivered"), arm: /* @__PURE__ */ __name(() => {
79872
- }, "arm") };
79907
+ return {
79908
+ markDelivered: /* @__PURE__ */ __name(() => {
79909
+ deliver();
79910
+ }, "markDelivered"),
79911
+ arm: /* @__PURE__ */ __name(() => {
79912
+ }, "arm")
79913
+ };
79873
79914
  }
79874
79915
  const install = /* @__PURE__ */ __name((armed) => {
79875
79916
  if (barriers.has(eventIndex)) {
@@ -79897,13 +79938,11 @@ function registerDeliveryBarrier(ctx, eventIndex, kind, options = {}) {
79897
79938
  return entry2;
79898
79939
  }, "install");
79899
79940
  let entry = install(options.armed ?? true);
79900
- let deliveredToWorkflow = false;
79901
79941
  return {
79902
79942
  markDelivered: /* @__PURE__ */ __name(() => {
79903
- if (deliveredToWorkflow) {
79943
+ if (!deliver()) {
79904
79944
  return;
79905
79945
  }
79906
- deliveredToWorkflow = true;
79907
79946
  entry.retire();
79908
79947
  }, "markDelivered"),
79909
79948
  arm: /* @__PURE__ */ __name(() => {
@@ -83812,7 +83851,9 @@ function createCreateAbortController(ctx) {
83812
83851
  if (event.eventType === "hook_received") {
83813
83852
  const rawPayload = event.eventData?.payload;
83814
83853
  const eventIndex = ctx.eventsConsumer.eventIndex;
83815
- const barrier = registerDeliveryBarrier(ctx, eventIndex, "hook");
83854
+ const barrier = registerDeliveryBarrier(ctx, eventIndex, "hook", {
83855
+ deliveredAt: +event.createdAt
83856
+ });
83816
83857
  const earlierDelivered = awaitEarlierDeliveries(ctx, eventIndex, "hook");
83817
83858
  ctx.pendingDeliveries++;
83818
83859
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
@@ -86000,7 +86041,7 @@ var version5;
86000
86041
  var init_version4 = __esm({
86001
86042
  "../core/dist/version.js"() {
86002
86043
  "use strict";
86003
- version5 = "5.0.0-beta.53";
86044
+ version5 = "5.0.0-beta.54";
86004
86045
  }
86005
86046
  });
86006
86047
 
@@ -86471,6 +86512,176 @@ var init_helpers3 = __esm({
86471
86512
  }
86472
86513
  });
86473
86514
 
86515
+ // ../core/dist/runtime/invocations.js
86516
+ async function handleInvocation(world, runId, requestId, payload) {
86517
+ const parsed = HookInvocationSchema2.safeParse(payload);
86518
+ if (!parsed.success || !requestId)
86519
+ throw new WorkflowWorldError2("Invalid invocation input", {
86520
+ status: 400,
86521
+ code: "INVALID_INPUT"
86522
+ });
86523
+ const input3 = parsed.data;
86524
+ const digest = Buffer.from(await crypto.subtle.digest("SHA-256", input3.payload)).toString("hex");
86525
+ try {
86526
+ const hook = await world.hooks.get(input3.hookId);
86527
+ if (hook.runId !== runId || hook.token !== input3.token)
86528
+ throw new HookNotFoundError2(input3.token);
86529
+ const run3 = await world.runs.get(runId, { resolveData: "none" });
86530
+ if (isTerminalWorkflowRunStatus2(run3.status))
86531
+ throw new HookNotFoundError2(input3.token);
86532
+ } catch (error121) {
86533
+ if (!isHookGone(error121))
86534
+ throw error121;
86535
+ const run3 = await world.runs.get(runId, { resolveData: "none" });
86536
+ if (run3.expiredAt || isTerminalWorkflowRunStatus2(run3.status) && readRunRetention(run3.attributes).mode === "none") {
86537
+ throw new WorkflowWorldError2("Invocation data has expired under the run retention policy", { status: 410, code: "INVOCATION_DATA_EXPIRED" });
86538
+ }
86539
+ if (!world.capabilities?.hookResumeDedup || !await hasResume(world, runId, input3.hookId, requestId)) {
86540
+ throw error121;
86541
+ }
86542
+ }
86543
+ await world.events.create(runId, {
86544
+ eventType: "hook_received",
86545
+ correlationId: input3.hookId,
86546
+ specVersion: SPEC_VERSION_CURRENT2,
86547
+ eventData: { token: input3.token, payload: input3.payload }
86548
+ }, {
86549
+ ...world.capabilities?.hookResumeDedup ? { resumeId: requestId, resumePayloadDigest: digest } : {}
86550
+ });
86551
+ return { status: "accepted" };
86552
+ }
86553
+ function isHookGone(error121) {
86554
+ return HookNotFoundError2.is(error121) || RunExpiredError2.is(error121) || WorkflowRunNotFoundError2.is(error121);
86555
+ }
86556
+ async function hasResume(world, runId, hookId, requestId) {
86557
+ let cursor = null;
86558
+ do {
86559
+ const page = await world.events.listByCorrelationId({
86560
+ runId,
86561
+ correlationId: hookId,
86562
+ resolveData: "none",
86563
+ pagination: { limit: 100, ...cursor ? { cursor } : {} }
86564
+ });
86565
+ if (page.data.some((event) => event.eventType === "hook_received" && event.resumeId === requestId))
86566
+ return true;
86567
+ cursor = page.hasMore ? page.cursor : null;
86568
+ } while (cursor);
86569
+ return false;
86570
+ }
86571
+ function withRunInputs(world) {
86572
+ return (handler) => {
86573
+ const sessions = /* @__PURE__ */ new Map();
86574
+ return async (message, metadata) => {
86575
+ if (HealthCheckPayloadSchema2.safeParse(message).success)
86576
+ return handler(message, metadata);
86577
+ const parsed = WorkflowInvokePayloadSchema2.safeParse(message);
86578
+ if (!world.capabilities?.invoke || !parsed.success || parsed.data.stepId)
86579
+ return handler(message, metadata);
86580
+ const input3 = parsed.data;
86581
+ let session = sessions.get(input3.runId);
86582
+ if (!session) {
86583
+ session = {
86584
+ activity: new RunInputActivity(),
86585
+ admission: Promise.resolve(),
86586
+ references: 0
86587
+ };
86588
+ sessions.set(input3.runId, session);
86589
+ }
86590
+ const current = session;
86591
+ current.references++;
86592
+ try {
86593
+ if (input3.invoke) {
86594
+ if (!input3.requestId)
86595
+ throw new WorkflowRuntimeError2("Invocation requestId is required");
86596
+ const requestId = input3.requestId;
86597
+ const decision = current.admission.then(() => trace5("workflow.invoke.receive", async (span) => {
86598
+ span?.setAttributes({
86599
+ ...WorkflowRunId4(input3.runId),
86600
+ "workflow.invocation.id": requestId
86601
+ });
86602
+ const result2 = await handleInvocation(world, input3.runId, requestId, input3.input);
86603
+ if (result2.status === "accepted")
86604
+ current.activity.notify();
86605
+ return result2;
86606
+ }));
86607
+ current.admission = decision.catch(() => {
86608
+ });
86609
+ return await decision;
86610
+ }
86611
+ if (current.execution)
86612
+ return await current.execution;
86613
+ const execution = handler(message, metadata, current.activity);
86614
+ current.execution = execution;
86615
+ try {
86616
+ return await execution;
86617
+ } finally {
86618
+ if (current.execution === execution)
86619
+ current.execution = void 0;
86620
+ }
86621
+ } finally {
86622
+ current.references--;
86623
+ if (current.references === 0 && sessions.get(input3.runId) === current)
86624
+ sessions.delete(input3.runId);
86625
+ }
86626
+ };
86627
+ };
86628
+ }
86629
+ var HookInvocationSchema2, HookInvocationResultSchema2, RunInputActivity;
86630
+ var init_invocations2 = __esm({
86631
+ "../core/dist/runtime/invocations.js"() {
86632
+ "use strict";
86633
+ init_dist7();
86634
+ init_dist6();
86635
+ init_zod2();
86636
+ init_semantic_conventions2();
86637
+ init_telemetry4();
86638
+ HookInvocationSchema2 = external_exports2.object({
86639
+ type: external_exports2.literal("hook_resume"),
86640
+ version: external_exports2.literal(1),
86641
+ hookId: external_exports2.string(),
86642
+ token: external_exports2.string(),
86643
+ payload: external_exports2.instanceof(Uint8Array)
86644
+ });
86645
+ HookInvocationResultSchema2 = external_exports2.discriminatedUnion("status", [
86646
+ external_exports2.object({ status: external_exports2.literal("accepted") }),
86647
+ external_exports2.object({
86648
+ status: external_exports2.literal("rejected"),
86649
+ code: external_exports2.enum(["HOOK_NOT_FOUND", "INVALID_INPUT"])
86650
+ })
86651
+ ]);
86652
+ __name(handleInvocation, "handleInvocation");
86653
+ __name(isHookGone, "isHookGone");
86654
+ __name(hasResume, "hasResume");
86655
+ RunInputActivity = class {
86656
+ static {
86657
+ __name(this, "RunInputActivity");
86658
+ }
86659
+ revision = 0;
86660
+ listeners = /* @__PURE__ */ new Set();
86661
+ notify() {
86662
+ this.revision++;
86663
+ for (const notify of this.listeners)
86664
+ notify();
86665
+ }
86666
+ async waitForActivity(since, timeoutMs = 100) {
86667
+ if (this.revision !== since)
86668
+ return true;
86669
+ await new Promise((resolve3) => {
86670
+ const finish = /* @__PURE__ */ __name(() => {
86671
+ clearTimeout(timer);
86672
+ this.listeners.delete(finish);
86673
+ resolve3();
86674
+ }, "finish");
86675
+ const timer = setTimeout(finish, timeoutMs);
86676
+ this.listeners.add(finish);
86677
+ });
86678
+ return this.revision !== since;
86679
+ }
86680
+ };
86681
+ __name(withRunInputs, "withRunInputs");
86682
+ }
86683
+ });
86684
+
86474
86685
  // ../core/dist/runtime/wait-until.js
86475
86686
  function waitUntil3(promise3) {
86476
86687
  void Promise.resolve().then(() => __toESM(require_functions2(), 1)).then(({ waitUntil: waitUntil4 }) => {
@@ -86687,6 +86898,26 @@ async function resumeHookImpl2(tokenOrHook, payload, encryptionKeyOverride, hook
86687
86898
  if (originLink) {
86688
86899
  span?.addLink?.(originLink);
86689
86900
  }
86901
+ if (world.capabilities?.invoke === true && !v1Compat && dehydratedPayload instanceof Uint8Array) {
86902
+ if (!world.invoke) {
86903
+ throw new WorkflowRuntimeError2("World advertises invoke without implementing it");
86904
+ }
86905
+ span?.setAttributes({ "workflow.hook.resume_strategy": "invoke" });
86906
+ const result2 = HookInvocationResultSchema2.parse(await world.invoke(hook.runId, {
86907
+ type: "hook_resume",
86908
+ version: 1,
86909
+ hookId: hook.hookId,
86910
+ token: hook.token,
86911
+ payload: dehydratedPayload
86912
+ }, { idempotencyKey: generateResumeId2() }));
86913
+ if (result2.status === "rejected") {
86914
+ if (result2.code === "HOOK_NOT_FOUND")
86915
+ throw new HookNotFoundError2(hook.token);
86916
+ throw new WorkflowRuntimeError2("Executor rejected the hook invocation input");
86917
+ }
86918
+ span?.setAttributes(HookResumeCommitted2(true));
86919
+ return asLazyMetadataHook2(hook);
86920
+ }
86690
86921
  const queueName = getWorkflowQueueName2(resumeContext.workflowName);
86691
86922
  const queueOptions = {
86692
86923
  deploymentId: resumeContext.deploymentId,
@@ -86811,6 +87042,7 @@ var init_resume_hook2 = __esm({
86811
87042
  init_telemetry4();
86812
87043
  init_get_world_lazy2();
86813
87044
  init_helpers3();
87045
+ init_invocations2();
86814
87046
  init_wait_until2();
86815
87047
  generateResumeId2 = monotonicFactory2();
86816
87048
  __name(computeResumePayloadDigest2, "computeResumePayloadDigest");
@@ -87900,6 +88132,11 @@ function createForwardedWritable2({ global: global2, ops, runId, name, key, depl
87900
88132
  return serialize5.writable;
87901
88133
  }
87902
88134
  function getRunReadableStream2(global2, ops, runId, name, startIndex, cryptoKey) {
88135
+ return getLazyReadableStream2((onReadableState) => getExternalRevivers2(global2, ops, runId, cryptoKey, {
88136
+ onReadableState
88137
+ }).ReadableStream({ name, startIndex }));
88138
+ }
88139
+ function getLazyReadableStream2(reviveReadable, onReadableState) {
87903
88140
  let reader;
87904
88141
  let lockState;
87905
88142
  let lockPollingStarted = false;
@@ -87909,15 +88146,16 @@ function getRunReadableStream2(global2, ops, runId, name, startIndex, cryptoKey)
87909
88146
  async pull(controller) {
87910
88147
  try {
87911
88148
  if (!reader) {
87912
- const stream = getExternalRevivers2(global2, ops, runId, cryptoKey, {
87913
- onReadableState: /* @__PURE__ */ __name((state) => {
87914
- lockState = state;
87915
- }, "onReadableState")
87916
- }).ReadableStream({ name, startIndex });
88149
+ const stream = reviveReadable((state) => {
88150
+ lockState = state;
88151
+ });
87917
88152
  reader = stream.getReader();
87918
88153
  if (lockState && !lockPollingStarted) {
87919
88154
  lockPollingStarted = true;
87920
- pollReadableLock2(userReadable, lockState);
88155
+ if (onReadableState)
88156
+ onReadableState(lockState);
88157
+ else
88158
+ pollReadableLock2(userReadable, lockState);
87921
88159
  }
87922
88160
  }
87923
88161
  const result2 = await reader.read();
@@ -87941,6 +88179,48 @@ function getRunReadableStream2(global2, ops, runId, name, startIndex, cryptoKey)
87941
88179
  return userReadable;
87942
88180
  }
87943
88181
  function getExternalRevivers2(global2 = globalThis, ops, runId, cryptoKey, options) {
88182
+ function reviveReadableStream(value, onReadableState = options?.onReadableState) {
88183
+ if (value.type === "bytes") {
88184
+ const readable2 = new WorkflowServerReadableStream2(runId, value.name, value.startIndex);
88185
+ const state2 = createFlushableState2();
88186
+ ops.push(state2.promise);
88187
+ const { readable: userReadable, writable } = value.framing === "framed-v1" ? getByteUnframingStream2() : new global2.TransformStream();
88188
+ flushablePipe2(readable2, writable, state2).catch(() => {
88189
+ });
88190
+ if (onReadableState)
88191
+ onReadableState(state2);
88192
+ else
88193
+ pollReadableLock2(userReadable, state2);
88194
+ return userReadable;
88195
+ }
88196
+ let keyPromise;
88197
+ const resolveKey = /* @__PURE__ */ __name(() => {
88198
+ keyPromise ??= resolveEncryptionKey2(cryptoKey);
88199
+ return keyPromise;
88200
+ }, "resolveKey");
88201
+ const readable = createReconnectingFramedStream2(runId, value.name, value.startIndex, resolveKey);
88202
+ const transform3 = getDeserializeStream2(getExternalRevivers2(global2, ops, runId, resolveKey, {
88203
+ lazyStreams: options?.lazyStreams,
88204
+ liveAbortSignals: options?.liveAbortSignals
88205
+ }), resolveKey);
88206
+ const state = createFlushableState2();
88207
+ ops.push(state.promise);
88208
+ flushablePipe2(readable, transform3.writable, state).catch(() => {
88209
+ });
88210
+ if (onReadableState)
88211
+ onReadableState(state);
88212
+ else
88213
+ pollReadableLock2(transform3.readable, state);
88214
+ return transform3.readable;
88215
+ }
88216
+ __name(reviveReadableStream, "reviveReadableStream");
88217
+ function reviveAbortSnapshot(value) {
88218
+ const controller = new AbortController();
88219
+ if (value.aborted)
88220
+ controller.abort(value.reason);
88221
+ return controller;
88222
+ }
88223
+ __name(reviveAbortSnapshot, "reviveAbortSnapshot");
87944
88224
  return {
87945
88225
  ...getCommonRevivers4(global2),
87946
88226
  // StepFunction should not be returned from workflows to clients
@@ -87981,36 +88261,7 @@ function getExternalRevivers2(global2 = globalThis, ops, runId, cryptoKey, optio
87981
88261
  const response = new global2.Response(bodyInit);
87982
88262
  return response.body;
87983
88263
  }
87984
- if (value.type === "bytes") {
87985
- const readable = new WorkflowServerReadableStream2(runId, value.name, value.startIndex);
87986
- const state = createFlushableState2();
87987
- ops.push(state.promise);
87988
- const { readable: userReadable, writable } = value.framing === "framed-v1" ? getByteUnframingStream2() : new global2.TransformStream();
87989
- flushablePipe2(readable, writable, state).catch(() => {
87990
- });
87991
- if (options?.onReadableState)
87992
- options.onReadableState(state);
87993
- else
87994
- pollReadableLock2(userReadable, state);
87995
- return userReadable;
87996
- } else {
87997
- let keyPromise;
87998
- const resolveKey = /* @__PURE__ */ __name(() => {
87999
- keyPromise ??= resolveEncryptionKey2(cryptoKey);
88000
- return keyPromise;
88001
- }, "resolveKey");
88002
- const readable = createReconnectingFramedStream2(runId, value.name, value.startIndex, resolveKey);
88003
- const transform3 = getDeserializeStream2(getExternalRevivers2(global2, ops, runId, resolveKey), resolveKey);
88004
- const state = createFlushableState2();
88005
- ops.push(state.promise);
88006
- flushablePipe2(readable, transform3.writable, state).catch(() => {
88007
- });
88008
- if (options?.onReadableState)
88009
- options.onReadableState(state);
88010
- else
88011
- pollReadableLock2(transform3.readable, state);
88012
- return transform3.readable;
88013
- }
88264
+ return options?.lazyStreams ? getLazyReadableStream2((onReadableState) => reviveReadableStream(value, onReadableState), options.onReadableState) : reviveReadableStream(value);
88014
88265
  }, "ReadableStream"),
88015
88266
  WritableStream: /* @__PURE__ */ __name((value) => {
88016
88267
  const targetRunId = typeof value.runId === "string" ? value.runId : runId;
@@ -88025,8 +88276,8 @@ function getExternalRevivers2(global2 = globalThis, ops, runId, cryptoKey, optio
88025
88276
  encryptionPublicKey: value.encryptionPublicKey
88026
88277
  });
88027
88278
  }, "WritableStream"),
88028
- AbortController: /* @__PURE__ */ __name((value) => reviveAbortController2(value, ops, runId), "AbortController"),
88029
- AbortSignal: /* @__PURE__ */ __name((value) => reviveAbortSignal2(value, ops, runId), "AbortSignal")
88279
+ AbortController: /* @__PURE__ */ __name((value) => options?.liveAbortSignals === false ? reviveAbortSnapshot(value) : reviveAbortController2(value, ops, runId), "AbortController"),
88280
+ AbortSignal: /* @__PURE__ */ __name((value) => options?.liveAbortSignals === false ? reviveAbortSnapshot(value).signal : reviveAbortSignal2(value, ops, runId), "AbortSignal")
88030
88281
  };
88031
88282
  }
88032
88283
  function getWorkflowRevivers(global2 = globalThis) {
@@ -88902,6 +89153,7 @@ var init_serialization4 = __esm({
88902
89153
  __name(tagForwardedWritableTarget2, "tagForwardedWritableTarget");
88903
89154
  __name(createForwardedWritable2, "createForwardedWritable");
88904
89155
  __name(getRunReadableStream2, "getRunReadableStream");
89156
+ __name(getLazyReadableStream2, "getLazyReadableStream");
88905
89157
  __name(getExternalRevivers2, "getExternalRevivers");
88906
89158
  __name(getWorkflowRevivers, "getWorkflowRevivers");
88907
89159
  __name(getStepRevivers2, "getStepRevivers");
@@ -89153,6 +89405,751 @@ var init_constants3 = __esm({
89153
89405
  }
89154
89406
  });
89155
89407
 
89408
+ // ../core/dist/types.js
89409
+ import { types as types6 } from "node:util";
89410
+ function getErrorName(v) {
89411
+ if (types6.isNativeError(v)) {
89412
+ return v.name;
89413
+ }
89414
+ return "Error";
89415
+ }
89416
+ function getErrorStack(v) {
89417
+ if (types6.isNativeError(v)) {
89418
+ return v.stack ?? "";
89419
+ }
89420
+ return "";
89421
+ }
89422
+ function describeErrorLink(value) {
89423
+ if (typeof value !== "object" || value === null) {
89424
+ return String(value);
89425
+ }
89426
+ const { name, message, code: code3 } = value;
89427
+ const label = typeof name === "string" && name ? name : "Error";
89428
+ const text = typeof message === "string" && message ? `${label}: ${message}` : label;
89429
+ return typeof code3 === "string" && code3 && !text.includes(code3) ? `${text} (${code3})` : text;
89430
+ }
89431
+ function formatErrorCauseChain(value) {
89432
+ const lines = [];
89433
+ const seen = /* @__PURE__ */ new Set();
89434
+ try {
89435
+ for (let current = causeOf(value); current != null && lines.length <= MAX_CAUSE_LINKS; current = causeOf(current)) {
89436
+ if (typeof current !== "object") {
89437
+ lines.push(String(current));
89438
+ break;
89439
+ }
89440
+ if (seen.has(current))
89441
+ break;
89442
+ seen.add(current);
89443
+ lines.push(describeErrorLink(current), ...aggregatedLinks(current));
89444
+ }
89445
+ } catch {
89446
+ lines.push("[unavailable cause]");
89447
+ }
89448
+ return lines.length > MAX_CAUSE_LINKS ? [...lines.slice(0, MAX_CAUSE_LINKS), "\u2026"].join("\n") : lines.join("\n");
89449
+ }
89450
+ function causeOf(value) {
89451
+ return typeof value === "object" && value !== null ? value.cause : void 0;
89452
+ }
89453
+ function aggregatedLinks(value) {
89454
+ const errors = value.errors;
89455
+ return Array.isArray(errors) ? errors.slice(0, MAX_CAUSE_LINKS).map(describeErrorLink) : [];
89456
+ }
89457
+ function isAbortError(value) {
89458
+ return typeof value === "object" && value !== null && "name" in value && value.name === "AbortError" && "message" in value && typeof value.message === "string" && (!("stack" in value) || value.stack === void 0 || typeof value.stack === "string");
89459
+ }
89460
+ function promoteAbortErrorToFatal(value) {
89461
+ if (!isAbortError(value) || FatalError2.is(value)) {
89462
+ return value;
89463
+ }
89464
+ const fatalError = new FatalError2(`Aborted: ${value.message}`);
89465
+ if (value.stack) {
89466
+ fatalError.stack = value.stack;
89467
+ }
89468
+ return fatalError;
89469
+ }
89470
+ function isThenable(value) {
89471
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
89472
+ }
89473
+ function normalizeSyncError(v) {
89474
+ if (types6.isNativeError(v)) {
89475
+ return {
89476
+ name: v.name,
89477
+ message: v.message,
89478
+ stack: v.stack ?? ""
89479
+ };
89480
+ }
89481
+ if (typeof v === "string") {
89482
+ return {
89483
+ name: "Error",
89484
+ message: v,
89485
+ stack: ""
89486
+ };
89487
+ }
89488
+ try {
89489
+ return {
89490
+ name: "Error",
89491
+ message: JSON.stringify(v),
89492
+ stack: ""
89493
+ };
89494
+ } catch {
89495
+ return {
89496
+ name: "Error",
89497
+ message: String(v),
89498
+ stack: ""
89499
+ };
89500
+ }
89501
+ }
89502
+ async function normalizeUnknownError(value) {
89503
+ if (isThenable(value)) {
89504
+ try {
89505
+ const resolved = await value;
89506
+ const normalized = await normalizeUnknownError(resolved);
89507
+ return {
89508
+ ...normalized,
89509
+ message: `Promise rejection: ${normalized.message}`
89510
+ };
89511
+ } catch (rejection) {
89512
+ const normalized = await normalizeUnknownError(rejection);
89513
+ return {
89514
+ ...normalized,
89515
+ message: `Promise rejection: ${normalized.message}`
89516
+ };
89517
+ }
89518
+ }
89519
+ return normalizeSyncError(value);
89520
+ }
89521
+ var MAX_CAUSE_LINKS;
89522
+ var init_types4 = __esm({
89523
+ "../core/dist/types.js"() {
89524
+ "use strict";
89525
+ init_dist7();
89526
+ __name(getErrorName, "getErrorName");
89527
+ __name(getErrorStack, "getErrorStack");
89528
+ MAX_CAUSE_LINKS = 4;
89529
+ __name(describeErrorLink, "describeErrorLink");
89530
+ __name(formatErrorCauseChain, "formatErrorCauseChain");
89531
+ __name(causeOf, "causeOf");
89532
+ __name(aggregatedLinks, "aggregatedLinks");
89533
+ __name(isAbortError, "isAbortError");
89534
+ __name(promoteAbortErrorToFatal, "promoteAbortErrorToFatal");
89535
+ __name(isThenable, "isThenable");
89536
+ __name(normalizeSyncError, "normalizeSyncError");
89537
+ __name(normalizeUnknownError, "normalizeUnknownError");
89538
+ }
89539
+ });
89540
+
89541
+ // ../core/dist/attribute-changes.js
89542
+ var init_attribute_changes = __esm({
89543
+ "../core/dist/attribute-changes.js"() {
89544
+ "use strict";
89545
+ init_dist7();
89546
+ init_attributes_validation2();
89547
+ }
89548
+ });
89549
+
89550
+ // ../core/dist/runtime/vm-mode.js
89551
+ function getWorkflowVmFromEnv2(env = process.env) {
89552
+ const raw = env.WORKFLOW_VM;
89553
+ if (raw === void 0 || raw === "")
89554
+ return void 0;
89555
+ if (WORKFLOW_VMS2.includes(raw)) {
89556
+ return raw;
89557
+ }
89558
+ throw new WorkflowRuntimeError2(`Invalid WORKFLOW_VM value: "${raw}". Expected one of: ${WORKFLOW_VMS2.join(", ")}.`);
89559
+ }
89560
+ function useQuickJSVm(workflowRun) {
89561
+ const vmFromRun = workflowRun.executionContext?.workflowVm;
89562
+ if (vmFromRun !== void 0) {
89563
+ if (!WORKFLOW_VMS2.includes(vmFromRun)) {
89564
+ throw new WorkflowRuntimeError2(`Invalid executionContext.workflowVm value: "${vmFromRun}". Expected one of: ${WORKFLOW_VMS2.join(", ")}.`);
89565
+ }
89566
+ return vmFromRun === "quickjs";
89567
+ }
89568
+ return getWorkflowVmFromEnv2() === "quickjs";
89569
+ }
89570
+ var WORKFLOW_VMS2;
89571
+ var init_vm_mode = __esm({
89572
+ "../core/dist/runtime/vm-mode.js"() {
89573
+ "use strict";
89574
+ init_dist7();
89575
+ WORKFLOW_VMS2 = ["node", "quickjs"];
89576
+ __name(getWorkflowVmFromEnv2, "getWorkflowVmFromEnv");
89577
+ __name(useQuickJSVm, "useQuickJSVm");
89578
+ }
89579
+ });
89580
+
89581
+ // ../core/dist/runtime/start.js
89582
+ var ulid7, latestNoOpWarning2;
89583
+ var init_start = __esm({
89584
+ "../core/dist/runtime/start.js"() {
89585
+ "use strict";
89586
+ init_dist7();
89587
+ init_dist5();
89588
+ init_dist6();
89589
+ init_node2();
89590
+ init_attribute_changes();
89591
+ init_capabilities2();
89592
+ init_classify_error();
89593
+ init_encryption4();
89594
+ init_logger2();
89595
+ init_sealed_box2();
89596
+ init_serialization4();
89597
+ init_context_storage2();
89598
+ init_semantic_conventions2();
89599
+ init_telemetry4();
89600
+ init_version4();
89601
+ init_get_world_lazy2();
89602
+ init_helpers3();
89603
+ init_run();
89604
+ init_vm_mode();
89605
+ init_wait_until2();
89606
+ init_world_compatibility2();
89607
+ ulid7 = monotonicFactory2();
89608
+ latestNoOpWarning2 = globalSingleton2("@workflow/core//latestNoOpWarning", 1, () => ({ warned: false }));
89609
+ }
89610
+ });
89611
+
89612
+ // ../core/dist/runtime/runs.js
89613
+ async function wakeUpRun2(world, runId, options) {
89614
+ try {
89615
+ const run3 = await world.runs.get(runId, { resolveData: "none" });
89616
+ const compatMode = isLegacySpecVersion2(run3.specVersion);
89617
+ const allEvents = [];
89618
+ let cursor = null;
89619
+ do {
89620
+ const eventsResult = await world.events.list({
89621
+ runId,
89622
+ pagination: { sortOrder: "asc", ...cursor ? { cursor } : {} },
89623
+ resolveData: "none"
89624
+ });
89625
+ allEvents.push(...eventsResult.data);
89626
+ cursor = eventsResult.hasMore ? eventsResult.cursor : null;
89627
+ } while (cursor);
89628
+ const waitCreatedEvents = allEvents.filter((event) => event.eventType === "wait_created");
89629
+ const waitCompletedCorrelationIds = new Set(allEvents.filter((event) => event.eventType === "wait_completed").map((event) => event.correlationId));
89630
+ let pendingWaits = waitCreatedEvents.filter((event) => !waitCompletedCorrelationIds.has(event.correlationId));
89631
+ if (options?.correlationIds && options.correlationIds.length > 0) {
89632
+ const targetCorrelationIds = new Set(options.correlationIds);
89633
+ pendingWaits = pendingWaits.filter((event) => event.correlationId && targetCorrelationIds.has(event.correlationId));
89634
+ }
89635
+ const errors = [];
89636
+ let stoppedCount = 0;
89637
+ for (const waitEvent of pendingWaits) {
89638
+ if (!waitEvent.correlationId)
89639
+ continue;
89640
+ const eventData = compatMode ? {
89641
+ eventType: "wait_completed",
89642
+ correlationId: waitEvent.correlationId
89643
+ } : {
89644
+ eventType: "wait_completed",
89645
+ correlationId: waitEvent.correlationId,
89646
+ specVersion: run3.specVersion,
89647
+ eventData: {
89648
+ resumeAt: waitEvent.eventData.resumeAt
89649
+ }
89650
+ };
89651
+ try {
89652
+ await world.events.create(runId, eventData, { v1Compat: compatMode });
89653
+ stoppedCount++;
89654
+ } catch (err) {
89655
+ if (EntityConflictError2.is(err)) {
89656
+ stoppedCount++;
89657
+ } else {
89658
+ errors.push(err instanceof Error ? err : new Error(String(err)));
89659
+ }
89660
+ }
89661
+ }
89662
+ if (stoppedCount > 0) {
89663
+ await world.queue(getWorkflowQueueName2(run3.workflowName, options?.namespace), {
89664
+ runId
89665
+ }, {
89666
+ deploymentId: run3.deploymentId,
89667
+ specVersion: run3.specVersion ?? SPEC_VERSION_LEGACY2
89668
+ });
89669
+ }
89670
+ if (errors.length > 0) {
89671
+ throw new AggregateError(errors, `Failed to complete ${errors.length}/${pendingWaits.length} pending wait(s) for run ${runId}`);
89672
+ }
89673
+ return { stoppedCount };
89674
+ } catch (err) {
89675
+ if (err instanceof AggregateError) {
89676
+ throw err;
89677
+ }
89678
+ throw new Error(`Failed to wake up run ${runId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
89679
+ }
89680
+ }
89681
+ var init_runs4 = __esm({
89682
+ "../core/dist/runtime/runs.js"() {
89683
+ "use strict";
89684
+ init_dist7();
89685
+ init_dist6();
89686
+ init_encryption5();
89687
+ init_serialization4();
89688
+ init_helpers3();
89689
+ init_start();
89690
+ __name(wakeUpRun2, "wakeUpRun");
89691
+ }
89692
+ });
89693
+
89694
+ // ../core/dist/runtime/run.js
89695
+ function getReturnValuePollIntervalMs2() {
89696
+ return envNumber2("WORKFLOW_RETURN_VALUE_POLL_INTERVAL_MS", RETURN_VALUE_POLL_INTERVAL_MS2, { integer: true, min: 1 });
89697
+ }
89698
+ function getReturnValueWaitTimeoutMs2() {
89699
+ return envNumber2("WORKFLOW_RETURN_VALUE_WAIT_MS", RETURN_VALUE_WAIT_TIMEOUT_MS2, { integer: true, min: 1 });
89700
+ }
89701
+ function getReturnValueMaxLongPolls2() {
89702
+ return envNumber2("WORKFLOW_RETURN_VALUE_MAX_LONG_POLLS", RETURN_VALUE_MAX_LONG_POLLS2, { integer: true, min: 1 });
89703
+ }
89704
+ function isReturnValueLongPollEnabled2() {
89705
+ const raw = process.env.WORKFLOW_RETURN_VALUE_LONG_POLL;
89706
+ if (raw === void 0 || raw === "")
89707
+ return true;
89708
+ return !(raw === "0" || raw.toLowerCase() === "false");
89709
+ }
89710
+ var RETURN_VALUE_POLL_INTERVAL_MS2, PAYLOAD_TERMINAL_RUN_STATUSES2, NOT_FOUND_RETRY_DELAYS2, RETURN_VALUE_WAIT_TIMEOUT_MS2, RETURN_VALUE_MAX_LONG_POLLS2, Run2;
89711
+ var init_run = __esm({
89712
+ "../core/dist/runtime/run.js"() {
89713
+ "use strict";
89714
+ init_dist7();
89715
+ init_dist12();
89716
+ init_env_config2();
89717
+ init_spec_version2();
89718
+ init_encryption5();
89719
+ init_serialization4();
89720
+ init_util5();
89721
+ init_get_world_lazy2();
89722
+ init_runs4();
89723
+ RETURN_VALUE_POLL_INTERVAL_MS2 = 1e3;
89724
+ PAYLOAD_TERMINAL_RUN_STATUSES2 = /* @__PURE__ */ new Set([
89725
+ "completed",
89726
+ "failed"
89727
+ ]);
89728
+ NOT_FOUND_RETRY_DELAYS2 = [1e3, 3e3, 6e3];
89729
+ __name(getReturnValuePollIntervalMs2, "getReturnValuePollIntervalMs");
89730
+ RETURN_VALUE_WAIT_TIMEOUT_MS2 = 5e4;
89731
+ __name(getReturnValueWaitTimeoutMs2, "getReturnValueWaitTimeoutMs");
89732
+ RETURN_VALUE_MAX_LONG_POLLS2 = 10;
89733
+ __name(getReturnValueMaxLongPolls2, "getReturnValueMaxLongPolls");
89734
+ __name(isReturnValueLongPollEnabled2, "isReturnValueLongPollEnabled");
89735
+ Run2 = class _Run2 {
89736
+ static {
89737
+ __name(this, "Run");
89738
+ }
89739
+ static [WORKFLOW_SERIALIZE2](instance) {
89740
+ return { runId: instance.runId, resilientStart: instance.#resilientStart };
89741
+ }
89742
+ static [WORKFLOW_DESERIALIZE2](data) {
89743
+ return new _Run2(data.runId, { resilientStart: data.resilientStart });
89744
+ }
89745
+ /**
89746
+ * The ID of the workflow run.
89747
+ */
89748
+ runId;
89749
+ /**
89750
+ * The world object.
89751
+ * @internal
89752
+ */
89753
+ #worldPromise;
89754
+ get #lazyWorldPromise() {
89755
+ if (!this.#worldPromise)
89756
+ this.#worldPromise = getWorldLazy2();
89757
+ return this.#worldPromise;
89758
+ }
89759
+ /**
89760
+ * Cached encryption key resolution. Resolved once on first use and
89761
+ * reused for returnValue, getReadable(), etc.
89762
+ * @internal
89763
+ */
89764
+ #encryptionKeyPromise = null;
89765
+ /**
89766
+ * When true, run_created failed and the run may not exist yet (the
89767
+ * resilient start path will create it via run_started). pollReturnValue
89768
+ * retries on WorkflowRunNotFoundError only when this flag is set so
89769
+ * that normal runs fail fast on 404.
89770
+ * @internal
89771
+ */
89772
+ #resilientStart = false;
89773
+ constructor(runId, opts) {
89774
+ this.runId = runId;
89775
+ this.#resilientStart = opts?.resilientStart ?? false;
89776
+ }
89777
+ /**
89778
+ * Resolves and caches the encryption key for this run.
89779
+ * The key is the same for the lifetime of a run, so it only needs
89780
+ * to be resolved once.
89781
+ * @internal
89782
+ */
89783
+ #getEncryptionKey(run3) {
89784
+ if (!this.#encryptionKeyPromise) {
89785
+ this.#encryptionKeyPromise = (async () => {
89786
+ const world = await this.#lazyWorldPromise;
89787
+ const runData = run3 ?? await world.runs.get(this.runId);
89788
+ const rawKey = await world.getEncryptionKeyForRun?.(runData);
89789
+ return rawKey ? await deriveRunPayloadKeys2(rawKey) : void 0;
89790
+ })();
89791
+ }
89792
+ return this.#encryptionKeyPromise;
89793
+ }
89794
+ /**
89795
+ * Defers fetching the run and its encryption key until a readable is first
89796
+ * consumed. The first pull prefetches it so an encrypted first frame can join
89797
+ * the lookup; this also applies to an empty consumed stream.
89798
+ * @internal
89799
+ */
89800
+ #getEncryptionKeyLazily() {
89801
+ return () => this.#getEncryptionKey();
89802
+ }
89803
+ /**
89804
+ * Interrupts pending `sleep()` calls, resuming the workflow early.
89805
+ *
89806
+ * @param options - Optional settings to target specific sleep calls by correlation ID.
89807
+ * If not provided, all pending sleep calls will be interrupted.
89808
+ * @returns A {@link StopSleepResult} object containing the number of sleep calls that were interrupted.
89809
+ */
89810
+ async wakeUp(options) {
89811
+ "use step";
89812
+ return wakeUpRun2(await this.#lazyWorldPromise, this.runId, options);
89813
+ }
89814
+ /**
89815
+ * Cancels the workflow run.
89816
+ *
89817
+ * @param options - Optional cancellation settings. `cancelReason` records a
89818
+ * free-text reason (max 512 chars) on the run_cancelled event, surfaced in
89819
+ * the run detail view.
89820
+ */
89821
+ async cancel(options) {
89822
+ "use step";
89823
+ const world = await this.#lazyWorldPromise;
89824
+ await world.events.create(this.runId, {
89825
+ eventType: "run_cancelled",
89826
+ specVersion: SPEC_VERSION_CURRENT2,
89827
+ ...options?.cancelReason !== void 0 ? { eventData: { cancelReason: options.cancelReason } } : {}
89828
+ });
89829
+ }
89830
+ /**
89831
+ * Whether the workflow run exists.
89832
+ */
89833
+ get exists() {
89834
+ "use step";
89835
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, { resolveData: "none" }).then(() => true).catch((error121) => {
89836
+ if (WorkflowRunNotFoundError2.is(error121)) {
89837
+ return false;
89838
+ }
89839
+ throw error121;
89840
+ }));
89841
+ }
89842
+ /**
89843
+ * The status of the workflow run.
89844
+ */
89845
+ get status() {
89846
+ "use step";
89847
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, { resolveData: "none" }).then((run3) => run3.status));
89848
+ }
89849
+ /**
89850
+ * The return value of the workflow run.
89851
+ * Polls the workflow return value until the workflow run completes.
89852
+ */
89853
+ get returnValue() {
89854
+ "use step";
89855
+ return this.#pollReturnValue();
89856
+ }
89857
+ /**
89858
+ * The name of the workflow.
89859
+ */
89860
+ get workflowName() {
89861
+ "use step";
89862
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, { resolveData: "none" }).then((run3) => run3.workflowName));
89863
+ }
89864
+ /**
89865
+ * The timestamp when the workflow run was created.
89866
+ */
89867
+ get createdAt() {
89868
+ "use step";
89869
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, { resolveData: "none" }).then((run3) => run3.createdAt));
89870
+ }
89871
+ /**
89872
+ * The timestamp when the workflow run started execution.
89873
+ * Returns undefined if the workflow has not started yet.
89874
+ */
89875
+ get startedAt() {
89876
+ "use step";
89877
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, { resolveData: "none" }).then((run3) => run3.startedAt));
89878
+ }
89879
+ /**
89880
+ * The timestamp when the workflow run completed.
89881
+ * Returns undefined if the workflow has not completed yet.
89882
+ */
89883
+ get completedAt() {
89884
+ "use step";
89885
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, { resolveData: "none" }).then((run3) => run3.completedAt));
89886
+ }
89887
+ /**
89888
+ * The readable stream of the workflow run.
89889
+ */
89890
+ get readable() {
89891
+ return this.getReadable();
89892
+ }
89893
+ /**
89894
+ * Retrieves the workflow run's default readable stream, which reads chunks
89895
+ * written to the corresponding writable stream {@link getWritable}.
89896
+ *
89897
+ * The returned stream has an additional {@link WorkflowReadableStream.getTailIndex | getTailIndex()}
89898
+ * helper that returns the index of the last known chunk. This is useful when
89899
+ * building reconnection endpoints that need to inform clients where the
89900
+ * stream starts.
89901
+ *
89902
+ * @param options - The options for the readable stream.
89903
+ * @returns A `WorkflowReadableStream` for the workflow run.
89904
+ */
89905
+ getReadable(options = {}) {
89906
+ "use step";
89907
+ const { ops = [], global: global2 = globalThis, startIndex, namespace } = options;
89908
+ const name = getWorkflowRunStreamId2(this.runId, namespace);
89909
+ const encryptionKey = this.#getEncryptionKeyLazily();
89910
+ const stream = getRunReadableStream2(global2, ops, this.runId, name, startIndex, encryptionKey);
89911
+ const worldPromise = this.#lazyWorldPromise;
89912
+ const runId = this.runId;
89913
+ return Object.assign(stream, {
89914
+ getTailIndex: /* @__PURE__ */ __name(async () => {
89915
+ const world = await worldPromise;
89916
+ const info = await world.streams.getInfo(runId, name);
89917
+ return info.tailIndex;
89918
+ }, "getTailIndex")
89919
+ });
89920
+ }
89921
+ /** The writable stream of the workflow run. */
89922
+ get writable() {
89923
+ return this.getWritable();
89924
+ }
89925
+ /**
89926
+ * Returns a writable that appends to this run's stream.
89927
+ *
89928
+ * Initialization is deferred until the first write. The run must already
89929
+ * exist. The writable may be forwarded through `start()` and into steps, but
89930
+ * grants no read access or additional authorization.
89931
+ *
89932
+ * @remarks
89933
+ * `writer.close()` closes the shared stream. Contributors should call
89934
+ * `releaseLock()`, which also drains pending writes.
89935
+ *
89936
+ * @param options - The writable stream options.
89937
+ */
89938
+ getWritable(options = {}) {
89939
+ "use step";
89940
+ const { ops = [], global: global2 = globalThis, namespace } = options;
89941
+ const name = getWorkflowRunStreamId2(this.runId, namespace);
89942
+ let targetPromise;
89943
+ let writable;
89944
+ const resolveTarget = /* @__PURE__ */ __name(() => {
89945
+ targetPromise ??= this.#getMetadata().then(async (run3) => {
89946
+ const target2 = {
89947
+ key: await getForwardedWritableEncryptionKey2(this.runId, run3.deploymentId, run3.encryptionPublicKey),
89948
+ deploymentId: run3.deploymentId,
89949
+ encryptionPublicKey: run3.encryptionPublicKey
89950
+ };
89951
+ tagForwardedWritableTarget2(writable, target2);
89952
+ return target2;
89953
+ });
89954
+ return targetPromise;
89955
+ }, "resolveTarget");
89956
+ writable = createForwardedWritable2({
89957
+ global: global2,
89958
+ ops,
89959
+ runId: this.runId,
89960
+ name,
89961
+ key: /* @__PURE__ */ __name(() => resolveTarget().then(({ key }) => key), "key")
89962
+ });
89963
+ return writable;
89964
+ }
89965
+ /** Reads metadata, briefly retrying resilient starts. @internal */
89966
+ async #getMetadata() {
89967
+ const world = await this.#lazyWorldPromise;
89968
+ const maxRetries = this.#resilientStart ? NOT_FOUND_RETRY_DELAYS2.length : 0;
89969
+ let attempt = 0;
89970
+ while (true) {
89971
+ try {
89972
+ return await world.runs.get(this.runId, { resolveData: "none" });
89973
+ } catch (error121) {
89974
+ if (!WorkflowRunNotFoundError2.is(error121) || attempt >= maxRetries) {
89975
+ throw error121;
89976
+ }
89977
+ const delay = NOT_FOUND_RETRY_DELAYS2[attempt];
89978
+ attempt++;
89979
+ await new Promise((resolve3) => setTimeout(resolve3, delay));
89980
+ }
89981
+ }
89982
+ }
89983
+ /** @internal */
89984
+ async #resolveTerminalReturnValue(run3) {
89985
+ const expiredAt = run3.expiredAt;
89986
+ if (expiredAt != null && expiredAt <= /* @__PURE__ */ new Date()) {
89987
+ throw new RunExpiredError2(`Run "${this.runId}" ${run3.status === "completed" ? "completed" : `is ${run3.status}`}, but its data expired at ${expiredAt.toISOString()} and is no longer readable.`, this.runId, run3.status, expiredAt);
89988
+ }
89989
+ if (run3.status === "completed") {
89990
+ const encryptionKey = await this.#getEncryptionKey(run3);
89991
+ return await hydrateWorkflowReturnValue2(run3.output, this.runId, encryptionKey);
89992
+ }
89993
+ if (run3.status === "cancelled") {
89994
+ throw new WorkflowRunCancelledError2(this.runId);
89995
+ }
89996
+ if (run3.status === "failed") {
89997
+ const encryptionKey = await this.#getEncryptionKey(run3);
89998
+ let hydratedError;
89999
+ try {
90000
+ hydratedError = await hydrateRunError2(run3.error, this.runId, encryptionKey);
90001
+ } catch {
90002
+ hydratedError = new Error("Failed to hydrate workflow run error");
90003
+ }
90004
+ throw new WorkflowRunFailedError2(this.runId, hydratedError, {
90005
+ errorCode: run3.errorCode
90006
+ });
90007
+ }
90008
+ throw new WorkflowRunNotCompletedError2(this.runId, run3.status);
90009
+ }
90010
+ /**
90011
+ * Polls the workflow return value until the workflow run completes.
90012
+ * @internal
90013
+ * @returns The workflow return value.
90014
+ */
90015
+ async #pollReturnValue() {
90016
+ const world = await this.#lazyWorldPromise;
90017
+ let notFoundRetries = 0;
90018
+ const NOT_FOUND_MAX_RETRIES = this.#resilientStart ? NOT_FOUND_RETRY_DELAYS2.length : 0;
90019
+ const waitForTerminalStatus = isReturnValueLongPollEnabled2() ? world.runs.waitForTerminalStatus?.bind(world.runs) : void 0;
90020
+ let longPolls = 0;
90021
+ const maxLongPolls = getReturnValueMaxLongPolls2();
90022
+ while (true) {
90023
+ const iterationStartedAt = Date.now();
90024
+ try {
90025
+ const useLongPoll = waitForTerminalStatus && longPolls < maxLongPolls;
90026
+ if (useLongPoll)
90027
+ longPolls++;
90028
+ const runMetadata = useLongPoll ? await waitForTerminalStatus(this.runId, {
90029
+ timeoutMs: getReturnValueWaitTimeoutMs2(),
90030
+ resolveData: "none"
90031
+ }) : await world.runs.get(this.runId, {
90032
+ resolveData: "none"
90033
+ });
90034
+ if (runMetadata.status === "cancelled") {
90035
+ throw new WorkflowRunCancelledError2(this.runId);
90036
+ }
90037
+ if (PAYLOAD_TERMINAL_RUN_STATUSES2.has(runMetadata.status)) {
90038
+ const run3 = await world.runs.get(this.runId, {
90039
+ resolveData: "all"
90040
+ });
90041
+ return await this.#resolveTerminalReturnValue(run3);
90042
+ }
90043
+ throw new WorkflowRunNotCompletedError2(this.runId, runMetadata.status);
90044
+ } catch (error121) {
90045
+ if (WorkflowRunNotCompletedError2.is(error121)) {
90046
+ const remainingIntervalMs = getReturnValuePollIntervalMs2() - (Date.now() - iterationStartedAt);
90047
+ if (remainingIntervalMs > 0) {
90048
+ await new Promise((resolve3) => setTimeout(resolve3, remainingIntervalMs));
90049
+ }
90050
+ continue;
90051
+ }
90052
+ if (WorkflowRunNotFoundError2.is(error121) && notFoundRetries < NOT_FOUND_MAX_RETRIES) {
90053
+ const delay = NOT_FOUND_RETRY_DELAYS2[notFoundRetries];
90054
+ notFoundRetries++;
90055
+ await new Promise((resolve3) => setTimeout(resolve3, delay));
90056
+ continue;
90057
+ }
90058
+ throw error121;
90059
+ }
90060
+ }
90061
+ }
90062
+ };
90063
+ }
90064
+ });
90065
+
90066
+ // ../core/dist/runtime/lifecycle-hooks.js
90067
+ function getRegistry3() {
90068
+ if (!Object.hasOwn(globalThis, REGISTRY_KEY)) {
90069
+ Object.defineProperty(globalThis, REGISTRY_KEY, {
90070
+ value: [],
90071
+ writable: false,
90072
+ enumerable: false,
90073
+ configurable: false
90074
+ });
90075
+ }
90076
+ return globalThis[REGISTRY_KEY];
90077
+ }
90078
+ function dispatch(runId, workflowName, event, prepare, invoke) {
90079
+ const registered = getRegistry3().filter((hooks) => hooks[event]);
90080
+ if (registered.length === 0) {
90081
+ return;
90082
+ }
90083
+ safeWaitUntil2(
90084
+ trace5(`workflow.lifecycle.${event}`, async () => {
90085
+ const params = await prepare();
90086
+ for (const hooks of registered) {
90087
+ try {
90088
+ await invoke(hooks, params);
90089
+ } catch (err) {
90090
+ runtimeLogger2.error(`Workflow lifecycle ${event} handler threw`, {
90091
+ workflowRunId: runId,
90092
+ workflowName,
90093
+ errorName: getErrorName(err),
90094
+ errorMessage: err instanceof Error ? err.message : String(err),
90095
+ errorStack: getErrorStack(err)
90096
+ });
90097
+ }
90098
+ }
90099
+ }),
90100
+ // Covers a `prepare()` rejection; handler failures are caught above.
90101
+ (err) => {
90102
+ runtimeLogger2.error(`Workflow lifecycle ${event} dispatch failed`, {
90103
+ workflowRunId: runId,
90104
+ workflowName,
90105
+ errorName: getErrorName(err),
90106
+ errorMessage: err instanceof Error ? err.message : String(err),
90107
+ errorStack: getErrorStack(err)
90108
+ });
90109
+ }
90110
+ );
90111
+ }
90112
+ function dispatchRunCompletedHooks(runId, workflowName) {
90113
+ dispatch(runId, workflowName, "onRunCompleted", async () => ({ run: new Run2(runId), workflowName }), (hooks, params) => hooks.onRunCompleted?.(params));
90114
+ }
90115
+ async function hydrateForHandlers(error121, runId, encryptionKey) {
90116
+ try {
90117
+ const ops = [];
90118
+ return await hydrateRunError2(error121, runId, encryptionKey, ops, globalThis, getExternalRevivers2(globalThis, ops, runId, encryptionKey, {
90119
+ lazyStreams: true,
90120
+ liveAbortSignals: false
90121
+ }));
90122
+ } catch {
90123
+ return new Error("Failed to hydrate workflow run error");
90124
+ }
90125
+ }
90126
+ function dispatchRunFailedHooks(runId, workflowName, error121, encryptionKey, errorCode) {
90127
+ dispatch(runId, workflowName, "onRunFailed", async () => ({
90128
+ run: new Run2(runId),
90129
+ workflowName,
90130
+ error: new WorkflowRunFailedError2(runId, await hydrateForHandlers(error121, runId, encryptionKey), { errorCode })
90131
+ }), (hooks, params) => hooks.onRunFailed?.(params));
90132
+ }
90133
+ var REGISTRY_KEY;
90134
+ var init_lifecycle_hooks = __esm({
90135
+ "../core/dist/runtime/lifecycle-hooks.js"() {
90136
+ "use strict";
90137
+ init_dist7();
90138
+ init_logger2();
90139
+ init_serialization4();
90140
+ init_telemetry4();
90141
+ init_types4();
90142
+ init_run();
90143
+ init_wait_until2();
90144
+ REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@workflow/core//lifecycleHooks");
90145
+ __name(getRegistry3, "getRegistry");
90146
+ __name(dispatch, "dispatch");
90147
+ __name(dispatchRunCompletedHooks, "dispatchRunCompletedHooks");
90148
+ __name(hydrateForHandlers, "hydrateForHandlers");
90149
+ __name(dispatchRunFailedHooks, "dispatchRunFailedHooks");
90150
+ }
90151
+ });
90152
+
89156
90153
  // ../core/dist/runtime/replay-budget.js
89157
90154
  async function handleReplayBudgetExhausted(args) {
89158
90155
  const { runId, workflowName, requestId, attempt, limitMs, slotSnapshot } = args;
@@ -89177,14 +90174,17 @@ async function handleReplayBudgetExhausted(args) {
89177
90174
  });
89178
90175
  const getEncryptionKey = memoizeEncryptionKey(world, runId);
89179
90176
  const timeoutErr = new FatalError2(`Workflow replay exceeded maximum duration (${limitMs / 1e3}s) after ${attempt} attempts`);
90177
+ const encryptionKey = await getEncryptionKey();
90178
+ const dehydratedError = await dehydrateRunError(timeoutErr, runId, encryptionKey);
89180
90179
  await world.events.create(runId, {
89181
90180
  eventType: "run_failed",
89182
90181
  specVersion: SPEC_VERSION_CURRENT2,
89183
90182
  eventData: {
89184
- error: await dehydrateRunError(timeoutErr, runId, await getEncryptionKey()),
90183
+ error: dehydratedError,
89185
90184
  errorCode: RUN_ERROR_CODES2.REPLAY_TIMEOUT
89186
90185
  }
89187
90186
  }, { requestId, ...slotSnapshot });
90187
+ dispatchRunFailedHooks(runId, workflowName, dehydratedError, encryptionKey, RUN_ERROR_CODES2.REPLAY_TIMEOUT);
89188
90188
  }
89189
90189
  var ReplayBudget, ReplayTimeoutRetryError;
89190
90190
  var init_replay_budget = __esm({
@@ -89197,6 +90197,7 @@ var init_replay_budget = __esm({
89197
90197
  init_serialization4();
89198
90198
  init_constants3();
89199
90199
  init_helpers3();
90200
+ init_lifecycle_hooks();
89200
90201
  init_world();
89201
90202
  ReplayBudget = class {
89202
90203
  static {
@@ -89452,139 +90453,6 @@ var init_run_id_time = __esm({
89452
90453
  }
89453
90454
  });
89454
90455
 
89455
- // ../core/dist/types.js
89456
- import { types as types6 } from "node:util";
89457
- function getErrorName(v) {
89458
- if (types6.isNativeError(v)) {
89459
- return v.name;
89460
- }
89461
- return "Error";
89462
- }
89463
- function getErrorStack(v) {
89464
- if (types6.isNativeError(v)) {
89465
- return v.stack ?? "";
89466
- }
89467
- return "";
89468
- }
89469
- function describeErrorLink(value) {
89470
- if (typeof value !== "object" || value === null) {
89471
- return String(value);
89472
- }
89473
- const { name, message, code: code3 } = value;
89474
- const label = typeof name === "string" && name ? name : "Error";
89475
- const text = typeof message === "string" && message ? `${label}: ${message}` : label;
89476
- return typeof code3 === "string" && code3 && !text.includes(code3) ? `${text} (${code3})` : text;
89477
- }
89478
- function formatErrorCauseChain(value) {
89479
- const lines = [];
89480
- const seen = /* @__PURE__ */ new Set();
89481
- try {
89482
- for (let current = causeOf(value); current != null && lines.length <= MAX_CAUSE_LINKS; current = causeOf(current)) {
89483
- if (typeof current !== "object") {
89484
- lines.push(String(current));
89485
- break;
89486
- }
89487
- if (seen.has(current))
89488
- break;
89489
- seen.add(current);
89490
- lines.push(describeErrorLink(current), ...aggregatedLinks(current));
89491
- }
89492
- } catch {
89493
- lines.push("[unavailable cause]");
89494
- }
89495
- return lines.length > MAX_CAUSE_LINKS ? [...lines.slice(0, MAX_CAUSE_LINKS), "\u2026"].join("\n") : lines.join("\n");
89496
- }
89497
- function causeOf(value) {
89498
- return typeof value === "object" && value !== null ? value.cause : void 0;
89499
- }
89500
- function aggregatedLinks(value) {
89501
- const errors = value.errors;
89502
- return Array.isArray(errors) ? errors.slice(0, MAX_CAUSE_LINKS).map(describeErrorLink) : [];
89503
- }
89504
- function isAbortError(value) {
89505
- return typeof value === "object" && value !== null && "name" in value && value.name === "AbortError" && "message" in value && typeof value.message === "string" && (!("stack" in value) || value.stack === void 0 || typeof value.stack === "string");
89506
- }
89507
- function promoteAbortErrorToFatal(value) {
89508
- if (!isAbortError(value) || FatalError2.is(value)) {
89509
- return value;
89510
- }
89511
- const fatalError = new FatalError2(`Aborted: ${value.message}`);
89512
- if (value.stack) {
89513
- fatalError.stack = value.stack;
89514
- }
89515
- return fatalError;
89516
- }
89517
- function isThenable(value) {
89518
- return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
89519
- }
89520
- function normalizeSyncError(v) {
89521
- if (types6.isNativeError(v)) {
89522
- return {
89523
- name: v.name,
89524
- message: v.message,
89525
- stack: v.stack ?? ""
89526
- };
89527
- }
89528
- if (typeof v === "string") {
89529
- return {
89530
- name: "Error",
89531
- message: v,
89532
- stack: ""
89533
- };
89534
- }
89535
- try {
89536
- return {
89537
- name: "Error",
89538
- message: JSON.stringify(v),
89539
- stack: ""
89540
- };
89541
- } catch {
89542
- return {
89543
- name: "Error",
89544
- message: String(v),
89545
- stack: ""
89546
- };
89547
- }
89548
- }
89549
- async function normalizeUnknownError(value) {
89550
- if (isThenable(value)) {
89551
- try {
89552
- const resolved = await value;
89553
- const normalized = await normalizeUnknownError(resolved);
89554
- return {
89555
- ...normalized,
89556
- message: `Promise rejection: ${normalized.message}`
89557
- };
89558
- } catch (rejection) {
89559
- const normalized = await normalizeUnknownError(rejection);
89560
- return {
89561
- ...normalized,
89562
- message: `Promise rejection: ${normalized.message}`
89563
- };
89564
- }
89565
- }
89566
- return normalizeSyncError(value);
89567
- }
89568
- var MAX_CAUSE_LINKS;
89569
- var init_types4 = __esm({
89570
- "../core/dist/types.js"() {
89571
- "use strict";
89572
- init_dist7();
89573
- __name(getErrorName, "getErrorName");
89574
- __name(getErrorStack, "getErrorStack");
89575
- MAX_CAUSE_LINKS = 4;
89576
- __name(describeErrorLink, "describeErrorLink");
89577
- __name(formatErrorCauseChain, "formatErrorCauseChain");
89578
- __name(causeOf, "causeOf");
89579
- __name(aggregatedLinks, "aggregatedLinks");
89580
- __name(isAbortError, "isAbortError");
89581
- __name(promoteAbortErrorToFatal, "promoteAbortErrorToFatal");
89582
- __name(isThenable, "isThenable");
89583
- __name(normalizeSyncError, "normalizeSyncError");
89584
- __name(normalizeUnknownError, "normalizeUnknownError");
89585
- }
89586
- });
89587
-
89588
90456
  // ../core/dist/runtime/get-port-lazy.js
89589
90457
  import { createRequire as createRequire3 } from "node:module";
89590
90458
  import { pathToFileURL as pathToFileURL2 } from "node:url";
@@ -90602,12 +91470,12 @@ var init_step_single_flight = __esm({
90602
91470
 
90603
91471
  // ../core/dist/runtime/wait-continuation.js
90604
91472
  function getWaitContinuationDispatch(timeoutSeconds, waitCorrelationId, now2 = Date.now(), attempt = 0) {
90605
- const dispatch = waitContinuationDispatchForAttemptZero(timeoutSeconds, waitCorrelationId, now2);
91473
+ const dispatch2 = waitContinuationDispatchForAttemptZero(timeoutSeconds, waitCorrelationId, now2);
90606
91474
  if (attempt <= 0)
90607
- return dispatch;
91475
+ return dispatch2;
90608
91476
  return {
90609
- delaySeconds: dispatch.delaySeconds,
90610
- idempotencyKey: `${dispatch.idempotencyKey}:a${attempt}`
91477
+ delaySeconds: dispatch2.delaySeconds,
91478
+ idempotencyKey: `${dispatch2.idempotencyKey}:a${attempt}`
90611
91479
  };
90612
91480
  }
90613
91481
  function waitContinuationDispatchForAttemptZero(timeoutSeconds, waitCorrelationId, now2) {
@@ -97201,6 +98069,40 @@ async function startQuickJSWorkflow(options) {
97201
98069
  }
97202
98070
  }
97203
98071
  serde.installProcessEnv(process.env);
98072
+ const historicalAttributeIds = /* @__PURE__ */ new Set();
98073
+ for (const event of events) {
98074
+ if (event.eventType === "attr_set" && event.correlationId !== void 0) {
98075
+ historicalAttributeIds.add(event.correlationId);
98076
+ }
98077
+ }
98078
+ {
98079
+ const env_5 = { stack: [], error: void 0, hasError: false };
98080
+ try {
98081
+ const validateAttributeWrite = __addDisposableResource3(env_5, vm.newFunction("__validateAttributeWrite", (correlationId, changes, allowReservedAttributes) => {
98082
+ if (historicalAttributeIds.has(correlationId.toString())) {
98083
+ return vm.undefined;
98084
+ }
98085
+ try {
98086
+ validateAttributeEventDataSize2({
98087
+ changes: vm.dump(changes),
98088
+ writer: { type: "workflow" },
98089
+ ...allowReservedAttributes.toBoolean() ? { allowReservedAttributes: true } : {}
98090
+ });
98091
+ } catch (err) {
98092
+ if (!(err instanceof AttributeValidationError2))
98093
+ throw err;
98094
+ return vm.newString(err.message);
98095
+ }
98096
+ return vm.undefined;
98097
+ }), false);
98098
+ vm.setProp(vm.global, "__validateAttributeWrite", validateAttributeWrite);
98099
+ } catch (e_5) {
98100
+ env_5.error = e_5;
98101
+ env_5.hasError = true;
98102
+ } finally {
98103
+ __disposeResources3(env_5);
98104
+ }
98105
+ }
97204
98106
  if (!baselineSnapshot) {
97205
98107
  try {
97206
98108
  vm.evalCode(workflowCode2, workflowId || "workflow.js").dispose();
@@ -97277,8 +98179,11 @@ async function startQuickJSWorkflow(options) {
97277
98179
  let maxIterations = 100;
97278
98180
  let madeProgress;
97279
98181
  do {
97280
- madeProgress = await processEvents(vm, serde, events, advanceClock, options.encryptionKey);
97281
98182
  let batch;
98183
+ do {
98184
+ batch = vm.executePendingJobs();
98185
+ } while (batch > 0);
98186
+ madeProgress = await processEvents(vm, serde, events, advanceClock, options.encryptionKey);
97282
98187
  do {
97283
98188
  batch = vm.executePendingJobs();
97284
98189
  if (batch > 0)
@@ -97292,7 +98197,7 @@ async function startQuickJSWorkflow(options) {
97292
98197
  });
97293
98198
  }
97294
98199
  }
97295
- return makeLiveSession(vm, serde, interruptBudget, advanceClock, options.encryptionKey);
98200
+ return makeLiveSession(vm, serde, interruptBudget, advanceClock, historicalAttributeIds, options.encryptionKey);
97296
98201
  }
97297
98202
  __name(runWorkflowInVM, "runWorkflowInVM");
97298
98203
  }
@@ -97306,7 +98211,7 @@ function makeSettledSession(result2) {
97306
98211
  }, "dispose")
97307
98212
  };
97308
98213
  }
97309
- function makeLiveSession(vm, serde, interruptBudget, advanceClock, encryptionKey) {
98214
+ function makeLiveSession(vm, serde, interruptBudget, advanceClock, historicalAttributeIds, encryptionKey) {
97310
98215
  const result2 = checkWorkflowState(vm, serde, { keepAliveOnSuspend: true });
97311
98216
  let alive = !!result2.suspended;
97312
98217
  const session = {
@@ -97316,11 +98221,19 @@ function makeLiveSession(vm, serde, interruptBudget, advanceClock, encryptionKey
97316
98221
  throw new Error("QuickJS workflow session is not alive \u2014 continueWithEvents is only valid while suspended");
97317
98222
  }
97318
98223
  interruptBudget.start = Date.now();
98224
+ for (const event of newEvents) {
98225
+ if (event.eventType === "attr_set" && event.correlationId !== void 0) {
98226
+ historicalAttributeIds.add(event.correlationId);
98227
+ }
98228
+ }
97319
98229
  let maxIterations = 100;
97320
98230
  let madeProgress;
97321
98231
  do {
97322
- madeProgress = await processEvents(vm, serde, newEvents, advanceClock, encryptionKey);
97323
98232
  let batch;
98233
+ do {
98234
+ batch = vm.executePendingJobs();
98235
+ } while (batch > 0);
98236
+ madeProgress = await processEvents(vm, serde, newEvents, advanceClock, encryptionKey);
97324
98237
  do {
97325
98238
  batch = vm.executePendingJobs();
97326
98239
  if (batch > 0)
@@ -97695,9 +98608,9 @@ function ensurePendingByteCache(vm) {
97695
98608
  return cache;
97696
98609
  }
97697
98610
  function dumpPendingOps(vm, serde, filterExpr, byteCache) {
97698
- const env_5 = { stack: [], error: void 0, hasError: false };
98611
+ const env_6 = { stack: [], error: void 0, hasError: false };
97699
98612
  try {
97700
- const projected = __addDisposableResource3(env_5, vm.evalCode(`(function(){
98613
+ const projected = __addDisposableResource3(env_6, vm.evalCode(`(function(){
97701
98614
  var ops = ${filterExpr};
97702
98615
  globalThis.__rawFields = [];
97703
98616
  // Settled ops \u2014 created, resolver-less, no abort in flight \u2014 are
@@ -97736,7 +98649,7 @@ function dumpPendingOps(vm, serde, filterExpr, byteCache) {
97736
98649
  }
97737
98650
  }
97738
98651
  }
97739
- const rawFields = __addDisposableResource3(env_5, vm.evalCode("globalThis.__rawFields"), false);
98652
+ const rawFields = __addDisposableResource3(env_6, vm.evalCode("globalThis.__rawFields"), false);
97740
98653
  for (const op of plainOps) {
97741
98654
  const rawIndices = op.__rawIndices ?? {};
97742
98655
  delete op.__rawIndices;
@@ -97747,9 +98660,9 @@ function dumpPendingOps(vm, serde, filterExpr, byteCache) {
97747
98660
  const cacheKey = `${op.correlationId}:${field}`;
97748
98661
  let bytes = byteCache?.get(cacheKey);
97749
98662
  if (!bytes) {
97750
- const env_6 = { stack: [], error: void 0, hasError: false };
98663
+ const env_7 = { stack: [], error: void 0, hasError: false };
97751
98664
  try {
97752
- const valueHandle = __addDisposableResource3(env_6, rawFields.getProp(String(index)), false);
98665
+ const valueHandle = __addDisposableResource3(env_7, rawFields.getProp(String(index)), false);
97753
98666
  try {
97754
98667
  bytes = serde.serialize(valueHandle);
97755
98668
  } catch (err) {
@@ -97761,11 +98674,11 @@ function dumpPendingOps(vm, serde, filterExpr, byteCache) {
97761
98674
  throw err;
97762
98675
  }
97763
98676
  byteCache?.set(cacheKey, bytes);
97764
- } catch (e_5) {
97765
- env_6.error = e_5;
97766
- env_6.hasError = true;
98677
+ } catch (e_6) {
98678
+ env_7.error = e_6;
98679
+ env_7.hasError = true;
97767
98680
  } finally {
97768
- __disposeResources3(env_6);
98681
+ __disposeResources3(env_7);
97769
98682
  }
97770
98683
  }
97771
98684
  op[field] = bytes;
@@ -97773,11 +98686,11 @@ function dumpPendingOps(vm, serde, filterExpr, byteCache) {
97773
98686
  }
97774
98687
  vm.evalCode("delete globalThis.__rawFields").dispose();
97775
98688
  return plainOps;
97776
- } catch (e_6) {
97777
- env_5.error = e_6;
97778
- env_5.hasError = true;
98689
+ } catch (e_7) {
98690
+ env_6.error = e_7;
98691
+ env_6.hasError = true;
97779
98692
  } finally {
97780
- __disposeResources3(env_5);
98693
+ __disposeResources3(env_6);
97781
98694
  }
97782
98695
  }
97783
98696
  function collectDrainOperations(vm, serde) {
@@ -97815,13 +98728,13 @@ function collectDrainOperations(vm, serde) {
97815
98728
  }
97816
98729
  function checkWorkflowState(vm, serde, opts = {}) {
97817
98730
  {
97818
- const env_7 = { stack: [], error: void 0, hasError: false };
98731
+ const env_8 = { stack: [], error: void 0, hasError: false };
97819
98732
  try {
97820
- const done = __addDisposableResource3(env_7, vm.evalCode("globalThis.__workflowDone === true"), false);
98733
+ const done = __addDisposableResource3(env_8, vm.evalCode("globalThis.__workflowDone === true"), false);
97821
98734
  if (done.toBoolean()) {
97822
- const env_8 = { stack: [], error: void 0, hasError: false };
98735
+ const env_9 = { stack: [], error: void 0, hasError: false };
97823
98736
  try {
97824
- const h = __addDisposableResource3(env_8, vm.evalCode("globalThis.__workflowResult"), false);
98737
+ const h = __addDisposableResource3(env_9, vm.evalCode("globalThis.__workflowResult"), false);
97825
98738
  const resultBytes = serde.serialize(h);
97826
98739
  const drainOperations = collectDrainOperations(vm, serde);
97827
98740
  vm.dispose();
@@ -97831,42 +98744,42 @@ function checkWorkflowState(vm, serde, opts = {}) {
97831
98744
  ...drainOperations.length > 0 ? { drainOperations } : {}
97832
98745
  }
97833
98746
  };
97834
- } catch (e_7) {
97835
- env_8.error = e_7;
97836
- env_8.hasError = true;
98747
+ } catch (e_8) {
98748
+ env_9.error = e_8;
98749
+ env_9.hasError = true;
97837
98750
  } finally {
97838
- __disposeResources3(env_8);
98751
+ __disposeResources3(env_9);
97839
98752
  }
97840
98753
  }
97841
- } catch (e_8) {
97842
- env_7.error = e_8;
97843
- env_7.hasError = true;
98754
+ } catch (e_9) {
98755
+ env_8.error = e_9;
98756
+ env_8.hasError = true;
97844
98757
  } finally {
97845
- __disposeResources3(env_7);
98758
+ __disposeResources3(env_8);
97846
98759
  }
97847
98760
  }
97848
98761
  {
97849
- const env_9 = { stack: [], error: void 0, hasError: false };
98762
+ const env_10 = { stack: [], error: void 0, hasError: false };
97850
98763
  try {
97851
- const h = __addDisposableResource3(env_9, vm.evalCode("globalThis.__workflowError"), false);
98764
+ const h = __addDisposableResource3(env_10, vm.evalCode("globalThis.__workflowError"), false);
97852
98765
  if (!h.isUndefined) {
97853
98766
  const errorObj = h.isString ? h.toString() : (() => {
97854
- const env_12 = { stack: [], error: void 0, hasError: false };
98767
+ const env_13 = { stack: [], error: void 0, hasError: false };
97855
98768
  try {
97856
- const plain = __addDisposableResource3(env_12, vm.evalCode("(function(e){return {message: e.message, stack: e.stack, name: e.name};})(globalThis.__workflowError)"), false);
98769
+ const plain = __addDisposableResource3(env_13, vm.evalCode("(function(e){return {message: e.message, stack: e.stack, name: e.name};})(globalThis.__workflowError)"), false);
97857
98770
  return vm.dump(plain);
97858
- } catch (e_12) {
97859
- env_12.error = e_12;
97860
- env_12.hasError = true;
98771
+ } catch (e_13) {
98772
+ env_13.error = e_13;
98773
+ env_13.hasError = true;
97861
98774
  } finally {
97862
- __disposeResources3(env_12);
98775
+ __disposeResources3(env_13);
97863
98776
  }
97864
98777
  })();
97865
98778
  let valueBytes;
97866
98779
  if (!h.isString) {
97867
- const env_10 = { stack: [], error: void 0, hasError: false };
98780
+ const env_11 = { stack: [], error: void 0, hasError: false };
97868
98781
  try {
97869
- const rawValue = __addDisposableResource3(env_10, h.getProp("value"), false);
98782
+ const rawValue = __addDisposableResource3(env_11, h.getProp("value"), false);
97870
98783
  try {
97871
98784
  valueBytes = serde.serialize(rawValue);
97872
98785
  } catch (serializeErr) {
@@ -97874,11 +98787,11 @@ function checkWorkflowState(vm, serde, opts = {}) {
97874
98787
  message: serializeErr instanceof Error ? serializeErr.message : String(serializeErr)
97875
98788
  });
97876
98789
  }
97877
- } catch (e_9) {
97878
- env_10.error = e_9;
97879
- env_10.hasError = true;
98790
+ } catch (e_10) {
98791
+ env_11.error = e_10;
98792
+ env_11.hasError = true;
97880
98793
  } finally {
97881
- __disposeResources3(env_10);
98794
+ __disposeResources3(env_11);
97882
98795
  }
97883
98796
  }
97884
98797
  const failed = typeof errorObj === "string" ? { message: errorObj } : {
@@ -97901,17 +98814,17 @@ function checkWorkflowState(vm, serde, opts = {}) {
97901
98814
  }
97902
98815
  };
97903
98816
  }
97904
- } catch (e_10) {
97905
- env_9.error = e_10;
97906
- env_9.hasError = true;
98817
+ } catch (e_11) {
98818
+ env_10.error = e_11;
98819
+ env_10.hasError = true;
97907
98820
  } finally {
97908
- __disposeResources3(env_9);
98821
+ __disposeResources3(env_10);
97909
98822
  }
97910
98823
  }
97911
98824
  {
97912
- const env_11 = { stack: [], error: void 0, hasError: false };
98825
+ const env_12 = { stack: [], error: void 0, hasError: false };
97913
98826
  try {
97914
- const h = __addDisposableResource3(env_11, vm.evalCode("Object.keys(globalThis.__resolvers).length > 0 || globalThis.__pending.some(function(p){return!p.hasCreatedEvent;})"), false);
98827
+ const h = __addDisposableResource3(env_12, vm.evalCode("Object.keys(globalThis.__resolvers).length > 0 || globalThis.__pending.some(function(p){return!p.hasCreatedEvent;})"), false);
97915
98828
  if (vm.dump(h)) {
97916
98829
  const pendingOps = dumpPendingOps(vm, serde, `globalThis.__pending.filter(function(p){return!!globalThis.__resolvers[p.correlationId] || !p.hasCreatedEvent || p.abortRequested;})`, ensurePendingByteCache(vm));
97917
98830
  if (!opts.keepAliveOnSuspend)
@@ -97922,11 +98835,11 @@ function checkWorkflowState(vm, serde, opts = {}) {
97922
98835
  }
97923
98836
  };
97924
98837
  }
97925
- } catch (e_11) {
97926
- env_11.error = e_11;
97927
- env_11.hasError = true;
98838
+ } catch (e_12) {
98839
+ env_12.error = e_12;
98840
+ env_12.hasError = true;
97928
98841
  } finally {
97929
- __disposeResources3(env_11);
98842
+ __disposeResources3(env_12);
97930
98843
  }
97931
98844
  }
97932
98845
  vm.dispose();
@@ -97963,6 +98876,7 @@ var init_quickjs_runtime = __esm({
97963
98876
  init_dist7();
97964
98877
  init_dist5();
97965
98878
  init_dist6();
98879
+ init_attributes_validation2();
97966
98880
  init_nanoid();
97967
98881
  init_dist13();
97968
98882
  import_seedrandom2 = __toESM(require_seedrandom2(), 1);
@@ -98586,18 +99500,28 @@ globalThis[Symbol.for("WORKFLOW_CREATE_HOOK")] = function(options) {
98586
99500
  };
98587
99501
 
98588
99502
  // setAttributes \u2014 attaches plaintext metadata to the current run.
98589
- // Validation happens in library code (normalizeAttributeChanges) before
99503
+ // Per-change validation happens in library code (normalizeAttributeChanges) before
98590
99504
  // this dispatcher is invoked, so "changes" is already normalized. The
98591
99505
  // returned promise resolves when the matching attr_set event is
98592
99506
  // observed during event processing \u2014 mirroring the node:vm engine's
98593
99507
  // createSetAttributes (attribute-dispatcher.ts).
99508
+ // Baseline hydrate placeholder; module-scope calls draw a ULID and disable snapshots.
99509
+ globalThis.__validateAttributeWrite = function() {};
98594
99510
  globalThis[Symbol.for("WORKFLOW_SET_ATTRIBUTES")] = function(changes, options) {
98595
99511
  var correlationId = "attr_" + globalThis.__generateUlid();
99512
+ var allowReservedAttributes = !!(options && options.allowReservedAttributes);
99513
+ var validationError = globalThis.__validateAttributeWrite(correlationId, changes, allowReservedAttributes);
99514
+ if (validationError !== undefined) {
99515
+ var error = new Error(validationError);
99516
+ error.name = "FatalError";
99517
+ error.fatal = true;
99518
+ return Promise.reject(error);
99519
+ }
98596
99520
  globalThis.__pending.push({
98597
99521
  type: "attribute",
98598
99522
  correlationId: correlationId,
98599
99523
  changes: changes,
98600
- allowReservedAttributes: !!(options && options.allowReservedAttributes),
99524
+ allowReservedAttributes: allowReservedAttributes,
98601
99525
  hasCreatedEvent: false,
98602
99526
  });
98603
99527
  return new Promise(function(resolve, reject) {
@@ -99738,6 +100662,7 @@ async function runWorkflowWithQuickJS(params) {
99738
100662
  }
99739
100663
  });
99740
100664
  wfdiag("exit_completed", { result: "run_completed_written" });
100665
+ dispatchRunCompletedHooks(runId, workflowName);
99741
100666
  } catch (err) {
99742
100667
  if (EntityConflictError2.is(err) || RunExpiredError2.is(err)) {
99743
100668
  runtimeLogger2.warn("Workflow already finished, skipping run_completed", { workflowRunId: runId });
@@ -99948,6 +100873,7 @@ async function runWorkflowWithQuickJS(params) {
99948
100873
  });
99949
100874
  throw err;
99950
100875
  }
100876
+ dispatchRunFailedHooks(runId, workflowName, dehydratedError, encryptionKey, errorCode);
99951
100877
  wfdiag("exit_failed", { result: "run_failed_written" });
99952
100878
  }
99953
100879
  }
@@ -99967,6 +100893,7 @@ var init_quickjs_entrypoint = __esm({
99967
100893
  init_constants3();
99968
100894
  init_get_port_lazy();
99969
100895
  init_helpers3();
100896
+ init_lifecycle_hooks();
99970
100897
  init_quickjs_log_view();
99971
100898
  init_quickjs_runtime();
99972
100899
  init_replay_budget();
@@ -125560,6 +126487,13 @@ var init_zod = __esm2({
125560
126487
  init_external();
125561
126488
  }
125562
126489
  });
126490
+ function validateAttributeEventDataSize(eventData) {
126491
+ const bytes = textEncoder.encode(JSON.stringify(eventData)).length;
126492
+ if (bytes > ATTRIBUTE_EVENT_DATA_MAX_BYTES) {
126493
+ throw new AttributeValidationError(`Attribute eventData exceeds limit ${ATTRIBUTE_EVENT_DATA_MAX_BYTES} UTF-8 JSON bytes (received ${bytes} bytes). Split the changes into smaller setAttributes() calls.`);
126494
+ }
126495
+ }
126496
+ __name(validateAttributeEventDataSize, "validateAttributeEventDataSize");
125563
126497
  function assertValidAttributeKey(key, allowReservedAttributes) {
125564
126498
  if (typeof key !== "string") {
125565
126499
  throw new AttributeValidationError(`Attribute key must be a string, got ${typeof key}`);
@@ -125622,6 +126556,7 @@ var RETENTION_ATTRIBUTE;
125622
126556
  var ATTRIBUTE_KEY_MAX_LENGTH;
125623
126557
  var ATTRIBUTE_VALUE_MAX_BYTES;
125624
126558
  var ATTRIBUTE_MAX_PER_RUN;
126559
+ var ATTRIBUTE_EVENT_DATA_MAX_BYTES;
125625
126560
  var textEncoder;
125626
126561
  var AttributeValidationError;
125627
126562
  var init_attributes_validation = __esm2({
@@ -125634,6 +126569,7 @@ var init_attributes_validation = __esm2({
125634
126569
  ATTRIBUTE_KEY_MAX_LENGTH = 256;
125635
126570
  ATTRIBUTE_VALUE_MAX_BYTES = 256;
125636
126571
  ATTRIBUTE_MAX_PER_RUN = 64;
126572
+ ATTRIBUTE_EVENT_DATA_MAX_BYTES = 8192;
125637
126573
  textEncoder = new TextEncoder();
125638
126574
  AttributeValidationError = class extends Error {
125639
126575
  static {
@@ -125647,6 +126583,7 @@ var init_attributes_validation = __esm2({
125647
126583
  this.name = "AttributeValidationError";
125648
126584
  }
125649
126585
  };
126586
+ __name2(validateAttributeEventDataSize, "validateAttributeEventDataSize");
125650
126587
  __name2(assertValidAttributeKey, "assertValidAttributeKey");
125651
126588
  __name2(assertValidAttributeValue, "assertValidAttributeValue");
125652
126589
  __name2(attributeCountDelta, "attributeCountDelta");
@@ -126731,6 +127668,11 @@ var init_queue = __esm2({
126731
127668
  }));
126732
127669
  WorkflowInvokePayloadSchema = external_exports.compile(external_exports.object({
126733
127670
  runId: external_exports.string(),
127671
+ /** Process this input and return the handler's result as response data. */
127672
+ invoke: external_exports.literal(true).optional(),
127673
+ /** Identifies one input across retries, separately from the queue delivery ID. */
127674
+ requestId: external_exports.string().optional(),
127675
+ input: external_exports.unknown().optional(),
126734
127676
  traceCarrier: TraceCarrierSchema.optional(),
126735
127677
  requestedAt: external_exports.coerce.date().optional(),
126736
127678
  /**
@@ -133422,7 +134364,7 @@ var version2;
133422
134364
  var init_version = __esm2({
133423
134365
  "../core/dist/version.js"() {
133424
134366
  "use strict";
133425
- version2 = "5.0.0-beta.53";
134367
+ version2 = "5.0.0-beta.54";
133426
134368
  }
133427
134369
  });
133428
134370
  function getWorkflowQueueName(workflowName, namespace) {
@@ -133609,6 +134551,37 @@ var init_helpers = __esm2({
133609
134551
  __name2(healthCheck, "healthCheck");
133610
134552
  }
133611
134553
  });
134554
+ var HookInvocationSchema;
134555
+ var HookInvocationResultSchema;
134556
+ var init_invocations = __esm2({
134557
+ "../core/dist/runtime/invocations.js"() {
134558
+ "use strict";
134559
+ init_dist2();
134560
+ init_dist4();
134561
+ init_zod();
134562
+ init_semantic_conventions();
134563
+ init_telemetry();
134564
+ HookInvocationSchema = external_exports.object({
134565
+ type: external_exports.literal("hook_resume"),
134566
+ version: external_exports.literal(1),
134567
+ hookId: external_exports.string(),
134568
+ token: external_exports.string(),
134569
+ payload: external_exports.instanceof(Uint8Array)
134570
+ });
134571
+ HookInvocationResultSchema = external_exports.discriminatedUnion("status", [
134572
+ external_exports.object({
134573
+ status: external_exports.literal("accepted")
134574
+ }),
134575
+ external_exports.object({
134576
+ status: external_exports.literal("rejected"),
134577
+ code: external_exports.enum([
134578
+ "HOOK_NOT_FOUND",
134579
+ "INVALID_INPUT"
134580
+ ])
134581
+ })
134582
+ ]);
134583
+ }
134584
+ });
133612
134585
  var require_headers = __commonJS2({
133613
134586
  "../../node_modules/.pnpm/@vercel+functions@3.8.0_@aws-sdk+credential-provider-web-identity@3.972.49_ws@8.20.0/node_modules/@vercel/functions/headers.js"(exports, module) {
133614
134587
  "use strict";
@@ -138808,6 +139781,29 @@ async function resumeHookImpl(tokenOrHook, payload, encryptionKeyOverride, hookF
138808
139781
  if (originLink) {
138809
139782
  span?.addLink?.(originLink);
138810
139783
  }
139784
+ if (world.capabilities?.invoke === true && !v1Compat && dehydratedPayload instanceof Uint8Array) {
139785
+ if (!world.invoke) {
139786
+ throw new WorkflowRuntimeError("World advertises invoke without implementing it");
139787
+ }
139788
+ span?.setAttributes({
139789
+ "workflow.hook.resume_strategy": "invoke"
139790
+ });
139791
+ const result2 = HookInvocationResultSchema.parse(await world.invoke(hook.runId, {
139792
+ type: "hook_resume",
139793
+ version: 1,
139794
+ hookId: hook.hookId,
139795
+ token: hook.token,
139796
+ payload: dehydratedPayload
139797
+ }, {
139798
+ idempotencyKey: generateResumeId()
139799
+ }));
139800
+ if (result2.status === "rejected") {
139801
+ if (result2.code === "HOOK_NOT_FOUND") throw new HookNotFoundError(hook.token);
139802
+ throw new WorkflowRuntimeError("Executor rejected the hook invocation input");
139803
+ }
139804
+ span?.setAttributes(HookResumeCommitted(true));
139805
+ return asLazyMetadataHook(hook);
139806
+ }
138811
139807
  const queueName = getWorkflowQueueName(resumeContext.workflowName);
138812
139808
  const queueOptions = {
138813
139809
  deploymentId: resumeContext.deploymentId,
@@ -138948,6 +139944,7 @@ var init_resume_hook = __esm2({
138948
139944
  init_telemetry();
138949
139945
  init_get_world_lazy();
138950
139946
  init_helpers();
139947
+ init_invocations();
138951
139948
  init_wait_until();
138952
139949
  generateResumeId = monotonicFactory();
138953
139950
  __name2(computeResumePayloadDigest, "computeResumePayloadDigest");
@@ -140021,6 +141018,15 @@ function createForwardedWritable({ global: global2, ops, runId, name, key, deplo
140021
141018
  }
140022
141019
  __name(createForwardedWritable, "createForwardedWritable");
140023
141020
  function getRunReadableStream(global2, ops, runId, name, startIndex, cryptoKey) {
141021
+ return getLazyReadableStream((onReadableState) => getExternalRevivers(global2, ops, runId, cryptoKey, {
141022
+ onReadableState
141023
+ }).ReadableStream({
141024
+ name,
141025
+ startIndex
141026
+ }));
141027
+ }
141028
+ __name(getRunReadableStream, "getRunReadableStream");
141029
+ function getLazyReadableStream(reviveReadable, onReadableState) {
140024
141030
  let reader;
140025
141031
  let lockState;
140026
141032
  let lockPollingStarted = false;
@@ -140030,18 +141036,14 @@ function getRunReadableStream(global2, ops, runId, name, startIndex, cryptoKey)
140030
141036
  async pull(controller) {
140031
141037
  try {
140032
141038
  if (!reader) {
140033
- const stream = getExternalRevivers(global2, ops, runId, cryptoKey, {
140034
- onReadableState: /* @__PURE__ */ __name2((state) => {
140035
- lockState = state;
140036
- }, "onReadableState")
140037
- }).ReadableStream({
140038
- name,
140039
- startIndex
141039
+ const stream = reviveReadable((state) => {
141040
+ lockState = state;
140040
141041
  });
140041
141042
  reader = stream.getReader();
140042
141043
  if (lockState && !lockPollingStarted) {
140043
141044
  lockPollingStarted = true;
140044
- pollReadableLock(userReadable, lockState);
141045
+ if (onReadableState) onReadableState(lockState);
141046
+ else pollReadableLock(userReadable, lockState);
140045
141047
  }
140046
141048
  }
140047
141049
  const result2 = await reader.read();
@@ -140064,8 +141066,47 @@ function getRunReadableStream(global2, ops, runId, name, startIndex, cryptoKey)
140064
141066
  );
140065
141067
  return userReadable;
140066
141068
  }
140067
- __name(getRunReadableStream, "getRunReadableStream");
141069
+ __name(getLazyReadableStream, "getLazyReadableStream");
140068
141070
  function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey, options) {
141071
+ function reviveReadableStream(value, onReadableState = options?.onReadableState) {
141072
+ if (value.type === "bytes") {
141073
+ const readable2 = new WorkflowServerReadableStream(runId, value.name, value.startIndex);
141074
+ const state2 = createFlushableState();
141075
+ ops.push(state2.promise);
141076
+ const { readable: userReadable, writable } = value.framing === "framed-v1" ? getByteUnframingStream() : new global2.TransformStream();
141077
+ flushablePipe(readable2, writable, state2).catch(() => {
141078
+ });
141079
+ if (onReadableState) onReadableState(state2);
141080
+ else pollReadableLock(userReadable, state2);
141081
+ return userReadable;
141082
+ }
141083
+ let keyPromise;
141084
+ const resolveKey = /* @__PURE__ */ __name2(() => {
141085
+ keyPromise ??= resolveEncryptionKey(cryptoKey);
141086
+ return keyPromise;
141087
+ }, "resolveKey");
141088
+ const readable = createReconnectingFramedStream(runId, value.name, value.startIndex, resolveKey);
141089
+ const transform22 = getDeserializeStream(getExternalRevivers(global2, ops, runId, resolveKey, {
141090
+ lazyStreams: options?.lazyStreams,
141091
+ liveAbortSignals: options?.liveAbortSignals
141092
+ }), resolveKey);
141093
+ const state = createFlushableState();
141094
+ ops.push(state.promise);
141095
+ flushablePipe(readable, transform22.writable, state).catch(() => {
141096
+ });
141097
+ if (onReadableState) onReadableState(state);
141098
+ else pollReadableLock(transform22.readable, state);
141099
+ return transform22.readable;
141100
+ }
141101
+ __name(reviveReadableStream, "reviveReadableStream");
141102
+ __name2(reviveReadableStream, "reviveReadableStream");
141103
+ function reviveAbortSnapshot(value) {
141104
+ const controller = new AbortController();
141105
+ if (value.aborted) controller.abort(value.reason);
141106
+ return controller;
141107
+ }
141108
+ __name(reviveAbortSnapshot, "reviveAbortSnapshot");
141109
+ __name2(reviveAbortSnapshot, "reviveAbortSnapshot");
140069
141110
  return {
140070
141111
  ...getCommonRevivers2(global2),
140071
141112
  // StepFunction should not be returned from workflows to clients
@@ -140106,32 +141147,7 @@ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey, option
140106
141147
  const response = new global2.Response(bodyInit);
140107
141148
  return response.body;
140108
141149
  }
140109
- if (value.type === "bytes") {
140110
- const readable = new WorkflowServerReadableStream(runId, value.name, value.startIndex);
140111
- const state = createFlushableState();
140112
- ops.push(state.promise);
140113
- const { readable: userReadable, writable } = value.framing === "framed-v1" ? getByteUnframingStream() : new global2.TransformStream();
140114
- flushablePipe(readable, writable, state).catch(() => {
140115
- });
140116
- if (options?.onReadableState) options.onReadableState(state);
140117
- else pollReadableLock(userReadable, state);
140118
- return userReadable;
140119
- } else {
140120
- let keyPromise;
140121
- const resolveKey = /* @__PURE__ */ __name2(() => {
140122
- keyPromise ??= resolveEncryptionKey(cryptoKey);
140123
- return keyPromise;
140124
- }, "resolveKey");
140125
- const readable = createReconnectingFramedStream(runId, value.name, value.startIndex, resolveKey);
140126
- const transform22 = getDeserializeStream(getExternalRevivers(global2, ops, runId, resolveKey), resolveKey);
140127
- const state = createFlushableState();
140128
- ops.push(state.promise);
140129
- flushablePipe(readable, transform22.writable, state).catch(() => {
140130
- });
140131
- if (options?.onReadableState) options.onReadableState(state);
140132
- else pollReadableLock(transform22.readable, state);
140133
- return transform22.readable;
140134
- }
141150
+ return options?.lazyStreams ? getLazyReadableStream((onReadableState) => reviveReadableStream(value, onReadableState), options.onReadableState) : reviveReadableStream(value);
140135
141151
  }, "ReadableStream"),
140136
141152
  WritableStream: /* @__PURE__ */ __name2((value) => {
140137
141153
  const targetRunId = typeof value.runId === "string" ? value.runId : runId;
@@ -140146,8 +141162,8 @@ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey, option
140146
141162
  encryptionPublicKey: value.encryptionPublicKey
140147
141163
  });
140148
141164
  }, "WritableStream"),
140149
- AbortController: /* @__PURE__ */ __name2((value) => reviveAbortController(value, ops, runId), "AbortController"),
140150
- AbortSignal: /* @__PURE__ */ __name2((value) => reviveAbortSignal(value, ops, runId), "AbortSignal")
141165
+ AbortController: /* @__PURE__ */ __name2((value) => options?.liveAbortSignals === false ? reviveAbortSnapshot(value) : reviveAbortController(value, ops, runId), "AbortController"),
141166
+ AbortSignal: /* @__PURE__ */ __name2((value) => options?.liveAbortSignals === false ? reviveAbortSnapshot(value).signal : reviveAbortSignal(value, ops, runId), "AbortSignal")
140151
141167
  };
140152
141168
  }
140153
141169
  __name(getExternalRevivers, "getExternalRevivers");
@@ -140874,6 +141890,7 @@ var init_serialization2 = __esm2({
140874
141890
  __name2(tagForwardedWritableTarget, "tagForwardedWritableTarget");
140875
141891
  __name2(createForwardedWritable, "createForwardedWritable");
140876
141892
  __name2(getRunReadableStream, "getRunReadableStream");
141893
+ __name2(getLazyReadableStream, "getLazyReadableStream");
140877
141894
  __name2(getExternalRevivers, "getExternalRevivers");
140878
141895
  __name2(getStepRevivers, "getStepRevivers");
140879
141896
  __name2(dehydrateWorkflowArguments, "dehydrateWorkflowArguments");
@@ -141011,7 +142028,7 @@ init_dist4();
141011
142028
  init_node();
141012
142029
  init_dist2();
141013
142030
  init_attributes_validation();
141014
- function normalizeAttributeChanges(attrs, options = {}) {
142031
+ function normalizeAttributeChanges(attrs, options = {}, writer) {
141015
142032
  if (attrs === null || typeof attrs !== "object" || Array.isArray(attrs)) {
141016
142033
  throw new FatalError(`setAttributes requires a plain object, got ${attrs === null ? "null" : Array.isArray(attrs) ? "array" : typeof attrs}`);
141017
142034
  }
@@ -141025,6 +142042,15 @@ function normalizeAttributeChanges(attrs, options = {}) {
141025
142042
  validateAttributeChanges(changes, {
141026
142043
  allowReservedAttributes
141027
142044
  });
142045
+ if (writer) {
142046
+ validateAttributeEventDataSize({
142047
+ changes,
142048
+ writer,
142049
+ ...allowReservedAttributes ? {
142050
+ allowReservedAttributes: true
142051
+ } : {}
142052
+ });
142053
+ }
141028
142054
  } catch (err) {
141029
142055
  if (err instanceof AttributeValidationError) {
141030
142056
  throw new FatalError(err.message);
@@ -141375,7 +142401,7 @@ __name2(start, "start");
141375
142401
  value: "start",
141376
142402
  configurable: true
141377
142403
  });
141378
- })(start, "step//@workflow/core/runtime/start@5.0.0-beta.53//start");
142404
+ })(start, "step//@workflow/core/runtime/start@5.0.0-beta.54//start");
141379
142405
  async function wakeUpRun(world, runId, options) {
141380
142406
  try {
141381
142407
  const run22 = await world.runs.get(runId, {
@@ -141637,27 +142663,35 @@ var Run = class _Run {
141637
142663
  * The name of the workflow.
141638
142664
  */
141639
142665
  get workflowName() {
141640
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId).then((run22) => run22.workflowName));
142666
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, {
142667
+ resolveData: "none"
142668
+ }).then((run22) => run22.workflowName));
141641
142669
  }
141642
142670
  /**
141643
142671
  * The timestamp when the workflow run was created.
141644
142672
  */
141645
142673
  get createdAt() {
141646
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId).then((run22) => run22.createdAt));
142674
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, {
142675
+ resolveData: "none"
142676
+ }).then((run22) => run22.createdAt));
141647
142677
  }
141648
142678
  /**
141649
142679
  * The timestamp when the workflow run started execution.
141650
142680
  * Returns undefined if the workflow has not started yet.
141651
142681
  */
141652
142682
  get startedAt() {
141653
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId).then((run22) => run22.startedAt));
142683
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, {
142684
+ resolveData: "none"
142685
+ }).then((run22) => run22.startedAt));
141654
142686
  }
141655
142687
  /**
141656
142688
  * The timestamp when the workflow run completed.
141657
142689
  * Returns undefined if the workflow has not completed yet.
141658
142690
  */
141659
142691
  get completedAt() {
141660
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId).then((run22) => run22.completedAt));
142692
+ return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, {
142693
+ resolveData: "none"
142694
+ }).then((run22) => run22.completedAt));
141661
142695
  }
141662
142696
  /**
141663
142697
  * The readable stream of the workflow run.
@@ -141842,7 +142876,7 @@ var Run = class _Run {
141842
142876
  value: "wakeUp",
141843
142877
  configurable: true
141844
142878
  });
141845
- })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#wakeUp");
142879
+ })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#wakeUp");
141846
142880
  (function(__wf_fn, __wf_id) {
141847
142881
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141848
142882
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141851,7 +142885,7 @@ var Run = class _Run {
141851
142885
  value: "cancel",
141852
142886
  configurable: true
141853
142887
  });
141854
- })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#cancel");
142888
+ })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#cancel");
141855
142889
  (function(__wf_fn, __wf_id) {
141856
142890
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141857
142891
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141860,7 +142894,7 @@ var Run = class _Run {
141860
142894
  value: "getReadable",
141861
142895
  configurable: true
141862
142896
  });
141863
- })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#getReadable");
142897
+ })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#getReadable");
141864
142898
  (function(__wf_fn, __wf_id) {
141865
142899
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141866
142900
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141869,7 +142903,7 @@ var Run = class _Run {
141869
142903
  value: "getWritable",
141870
142904
  configurable: true
141871
142905
  });
141872
- })(Run.prototype["getWritable"], "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#getWritable");
142906
+ })(Run.prototype["getWritable"], "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#getWritable");
141873
142907
  (function(__wf_fn, __wf_id) {
141874
142908
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141875
142909
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141878,7 +142912,7 @@ var Run = class _Run {
141878
142912
  value: "exists",
141879
142913
  configurable: true
141880
142914
  });
141881
- })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#exists");
142915
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#exists");
141882
142916
  (function(__wf_fn, __wf_id) {
141883
142917
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141884
142918
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141887,7 +142921,7 @@ var Run = class _Run {
141887
142921
  value: "status",
141888
142922
  configurable: true
141889
142923
  });
141890
- })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#status");
142924
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#status");
141891
142925
  (function(__wf_fn, __wf_id) {
141892
142926
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141893
142927
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141896,7 +142930,7 @@ var Run = class _Run {
141896
142930
  value: "returnValue",
141897
142931
  configurable: true
141898
142932
  });
141899
- })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#returnValue");
142933
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#returnValue");
141900
142934
  (function(__wf_fn, __wf_id) {
141901
142935
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141902
142936
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141905,7 +142939,7 @@ var Run = class _Run {
141905
142939
  value: "workflowName",
141906
142940
  configurable: true
141907
142941
  });
141908
- })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#workflowName");
142942
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#workflowName");
141909
142943
  (function(__wf_fn, __wf_id) {
141910
142944
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141911
142945
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141914,7 +142948,7 @@ var Run = class _Run {
141914
142948
  value: "createdAt",
141915
142949
  configurable: true
141916
142950
  });
141917
- })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#createdAt");
142951
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#createdAt");
141918
142952
  (function(__wf_fn, __wf_id) {
141919
142953
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141920
142954
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141923,7 +142957,7 @@ var Run = class _Run {
141923
142957
  value: "startedAt",
141924
142958
  configurable: true
141925
142959
  });
141926
- })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#startedAt");
142960
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#startedAt");
141927
142961
  (function(__wf_fn, __wf_id) {
141928
142962
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141929
142963
  __wf_reg.set(__wf_id, __wf_fn);
@@ -141932,7 +142966,7 @@ var Run = class _Run {
141932
142966
  value: "completedAt",
141933
142967
  configurable: true
141934
142968
  });
141935
- })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.53//Run#completedAt");
142969
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.54//Run#completedAt");
141936
142970
  (function(__wf_cls, __wf_id) {
141937
142971
  var __wf_sym = /* @__PURE__ */ Symbol.for("workflow-class-registry"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
141938
142972
  __wf_reg.set(__wf_id, __wf_cls);
@@ -141942,7 +142976,7 @@ var Run = class _Run {
141942
142976
  enumerable: false,
141943
142977
  configurable: false
141944
142978
  });
141945
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.53//Run");
142979
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.54//Run");
141946
142980
  async function fetch2(...args) {
141947
142981
  return globalThis.fetch(...args);
141948
142982
  }
@@ -142698,6 +143732,7 @@ init_logger2();
142698
143732
  init_serialization4();
142699
143733
  init_semantic_conventions2();
142700
143734
  init_constants3();
143735
+ init_lifecycle_hooks();
142701
143736
  var MAX_REROUTE_DELAY_SECONDS = 8;
142702
143737
  var CONTINUE = { outcome: "continue" };
142703
143738
  function result(outcome, pinnedDeploymentId, attempts) {
@@ -142711,7 +143746,7 @@ function result(outcome, pinnedDeploymentId, attempts) {
142711
143746
  };
142712
143747
  }
142713
143748
  __name(result, "result");
142714
- async function guardDeploymentAffinity({ world, run: run3, requestId, retryCount = 0, reenqueue, isDeploymentUnavailableError, beforeStop }) {
143749
+ async function guardDeploymentAffinity({ world, run: run3, workflowName, requestId, retryCount = 0, reenqueue, isDeploymentUnavailableError, beforeStop }) {
142715
143750
  if (world.capabilities?.deploymentAffinity !== true) {
142716
143751
  return CONTINUE;
142717
143752
  }
@@ -142731,17 +143766,16 @@ async function guardDeploymentAffinity({ world, run: run3, requestId, retryCount
142731
143766
  const failRun = /* @__PURE__ */ __name(async (recoveryAttempts, cause) => {
142732
143767
  const error121 = new WorkflowDeploymentMismatchError(run3.runId, run3.deploymentId, currentDeploymentId, { recoveryAttempts, cause });
142733
143768
  try {
143769
+ const dehydratedError = await dehydrateRunError(error121, run3.runId, void 0, void 0, (run3.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION2);
142734
143770
  await world.events.create(run3.runId, {
142735
143771
  eventType: "run_failed",
142736
143772
  specVersion: SPEC_VERSION_CURRENT2,
142737
143773
  eventData: {
142738
- // Unencrypted (undefined key): see the note on
142739
- // `guardDeploymentAffinity`. dehydrate/hydrate are self-describing,
142740
- // so this reads back without a key.
142741
- error: await dehydrateRunError(error121, run3.runId, void 0, void 0, (run3.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION2),
143774
+ error: dehydratedError,
142742
143775
  errorCode: RUN_ERROR_CODES2.DEPLOYMENT_MISMATCH
142743
143776
  }
142744
143777
  }, { requestId });
143778
+ dispatchRunFailedHooks(run3.runId, workflowName, dehydratedError, void 0, RUN_ERROR_CODES2.DEPLOYMENT_MISMATCH);
142745
143779
  } catch (failError) {
142746
143780
  if (!EntityConflictError2.is(failError) && !RunExpiredError2.is(failError)) {
142747
143781
  throw failError;
@@ -142780,6 +143814,8 @@ __name(guardDeploymentAffinity, "guardDeploymentAffinity");
142780
143814
 
142781
143815
  // ../core/dist/runtime.js
142782
143816
  init_helpers3();
143817
+ init_invocations2();
143818
+ init_lifecycle_hooks();
142783
143819
  init_replay_budget();
142784
143820
  init_replay_recovery_reporter();
142785
143821
  init_resume_latency();
@@ -143714,32 +144750,8 @@ function isWorldValidationFailure(err) {
143714
144750
  }
143715
144751
  __name(isWorldValidationFailure, "isWorldValidationFailure");
143716
144752
 
143717
- // ../core/dist/runtime/vm-mode.js
143718
- init_dist7();
143719
- var WORKFLOW_VMS2 = ["node", "quickjs"];
143720
- function getWorkflowVmFromEnv2(env = process.env) {
143721
- const raw = env.WORKFLOW_VM;
143722
- if (raw === void 0 || raw === "")
143723
- return void 0;
143724
- if (WORKFLOW_VMS2.includes(raw)) {
143725
- return raw;
143726
- }
143727
- throw new WorkflowRuntimeError2(`Invalid WORKFLOW_VM value: "${raw}". Expected one of: ${WORKFLOW_VMS2.join(", ")}.`);
143728
- }
143729
- __name(getWorkflowVmFromEnv2, "getWorkflowVmFromEnv");
143730
- function useQuickJSVm(workflowRun) {
143731
- const vmFromRun = workflowRun.executionContext?.workflowVm;
143732
- if (vmFromRun !== void 0) {
143733
- if (!WORKFLOW_VMS2.includes(vmFromRun)) {
143734
- throw new WorkflowRuntimeError2(`Invalid executionContext.workflowVm value: "${vmFromRun}". Expected one of: ${WORKFLOW_VMS2.join(", ")}.`);
143735
- }
143736
- return vmFromRun === "quickjs";
143737
- }
143738
- return getWorkflowVmFromEnv2() === "quickjs";
143739
- }
143740
- __name(useQuickJSVm, "useQuickJSVm");
143741
-
143742
144753
  // ../core/dist/runtime.js
144754
+ init_vm_mode();
143743
144755
  init_wait_continuation();
143744
144756
  init_world();
143745
144757
  init_serialization4();
@@ -143898,7 +144910,9 @@ function createUseStep(ctx) {
143898
144910
  if (event.eventType === "step_failed") {
143899
144911
  ctx.invocationsQueue.delete(event.correlationId);
143900
144912
  const eventIndex = ctx.eventsConsumer.eventIndex;
143901
- const barrier = registerDeliveryBarrier(ctx, eventIndex, "step");
144913
+ const barrier = registerDeliveryBarrier(ctx, eventIndex, "step", {
144914
+ deliveredAt: +event.createdAt
144915
+ });
143902
144916
  let rejection;
143903
144917
  const earlierDelivered = awaitEarlierDeliveries(ctx, eventIndex, "step");
143904
144918
  ctx.pendingDeliveries++;
@@ -143927,7 +144941,9 @@ function createUseStep(ctx) {
143927
144941
  const completedEventId = event.eventId;
143928
144942
  const serializedResult = event.eventData.result;
143929
144943
  const eventIndex = ctx.eventsConsumer.eventIndex;
143930
- const barrier = registerDeliveryBarrier(ctx, eventIndex, "step");
144944
+ const barrier = registerDeliveryBarrier(ctx, eventIndex, "step", {
144945
+ deliveredAt: +event.createdAt
144946
+ });
143931
144947
  let outcome;
143932
144948
  const earlierDelivered = awaitEarlierDeliveries(ctx, eventIndex, "step");
143933
144949
  ctx.pendingDeliveries++;
@@ -144591,12 +145607,26 @@ init_abort_controller2();
144591
145607
  // ../core/dist/workflow/attribute-dispatcher.js
144592
145608
  init_dist7();
144593
145609
  init_dist5();
145610
+ init_attributes_validation2();
144594
145611
  init_events_consumer2();
144595
145612
  init_private2();
144596
145613
  function createSetAttributes(ctx) {
144597
145614
  return /* @__PURE__ */ __name(async function setAttributes(changes, options = {}) {
144598
145615
  const { promise: promise3, resolve: resolve3 } = withResolvers2();
144599
145616
  const correlationId = `attr_${ctx.generateUlid()}`;
145617
+ try {
145618
+ validateAttributeEventDataSize2({
145619
+ changes,
145620
+ writer: { type: "workflow" },
145621
+ ...options.allowReservedAttributes === true ? { allowReservedAttributes: true } : {}
145622
+ });
145623
+ } catch (error121) {
145624
+ if (!(error121 instanceof AttributeValidationError2))
145625
+ throw error121;
145626
+ const persisted = ctx.eventsConsumer.events.some((event) => event.eventType === "attr_set" && event.correlationId === correlationId);
145627
+ if (!persisted)
145628
+ throw new FatalError2(error121.message);
145629
+ }
144600
145630
  const queueItem = {
144601
145631
  type: "attribute",
144602
145632
  correlationId,
@@ -144685,6 +145715,26 @@ function createCreateHook(ctx) {
144685
145715
  let hasConflict = false;
144686
145716
  let conflictErrorRef = null;
144687
145717
  let conflictRunRef = null;
145718
+ let registrationDelivered = Promise.resolve();
145719
+ function deliverRegistration(deliveredAt, settle) {
145720
+ const eventIndex = ctx.eventsConsumer.eventIndex;
145721
+ const barrier = registerDeliveryBarrier(ctx, eventIndex, "hook", {
145722
+ deliveredAt
145723
+ });
145724
+ const earlierDelivered = awaitEarlierDeliveries(ctx, eventIndex, "hook");
145725
+ registrationDelivered = ctx.promiseQueue.then(() => earlierDelivered).then(() => {
145726
+ barrier.markDelivered();
145727
+ settle();
145728
+ });
145729
+ }
145730
+ __name(deliverRegistration, "deliverRegistration");
145731
+ function afterRegistration(settle) {
145732
+ const delivered = registrationDelivered;
145733
+ ctx.promiseQueue = ctx.promiseQueue.then(() => {
145734
+ void delivered.then(settle);
145735
+ });
145736
+ }
145737
+ __name(afterRegistration, "afterRegistration");
144688
145738
  const seenResumeIds = /* @__PURE__ */ new Set();
144689
145739
  webhookLogger2.debug("Hook consumer setup", { correlationId, token });
144690
145740
  ctx.eventsConsumer.subscribe((event) => {
@@ -144714,7 +145764,7 @@ function createCreateHook(ctx) {
144714
145764
  hasCreated = true;
144715
145765
  const pendingGetConflictPromises = getConflictPromises.slice();
144716
145766
  getConflictPromises.length = 0;
144717
- ctx.promiseQueue = ctx.promiseQueue.then(() => {
145767
+ deliverRegistration(+event.createdAt, () => {
144718
145768
  for (const resolver2 of pendingGetConflictPromises) {
144719
145769
  resolver2.resolve(null);
144720
145770
  }
@@ -144732,7 +145782,7 @@ function createCreateHook(ctx) {
144732
145782
  promises.length = 0;
144733
145783
  const pendingGetConflictPromises = getConflictPromises.slice();
144734
145784
  getConflictPromises.length = 0;
144735
- ctx.promiseQueue = ctx.promiseQueue.then(() => {
145785
+ deliverRegistration(+event.createdAt, () => {
144736
145786
  for (const resolver2 of pendingPromises) {
144737
145787
  resolver2.reject(conflictError);
144738
145788
  }
@@ -144757,7 +145807,8 @@ function createCreateHook(ctx) {
144757
145807
  const eventIndex = ctx.eventsConsumer.eventIndex;
144758
145808
  const hasWaitingConsumer = promises.length > 0;
144759
145809
  const barrier = registerDeliveryBarrier(ctx, eventIndex, "hook", {
144760
- armed: hasWaitingConsumer
145810
+ armed: hasWaitingConsumer,
145811
+ deliveredAt: +event.createdAt
144761
145812
  });
144762
145813
  if (hasWaitingConsumer) {
144763
145814
  const earlierDelivered = awaitEarlierDeliveries(ctx, eventIndex, "hook");
@@ -144829,7 +145880,7 @@ function createCreateHook(ctx) {
144829
145880
  function createHookPromise() {
144830
145881
  const resolvers = withResolvers2();
144831
145882
  if (hasConflict && conflictErrorRef) {
144832
- ctx.promiseQueue = ctx.promiseQueue.then(() => {
145883
+ afterRegistration(() => {
144833
145884
  resolvers.reject(conflictErrorRef);
144834
145885
  });
144835
145886
  return resolvers.promise;
@@ -144850,13 +145901,13 @@ function createCreateHook(ctx) {
144850
145901
  function createGetConflictPromise() {
144851
145902
  const resolvers = withResolvers2();
144852
145903
  if (hasCreated) {
144853
- ctx.promiseQueue = ctx.promiseQueue.then(() => {
145904
+ afterRegistration(() => {
144854
145905
  resolvers.resolve(null);
144855
145906
  });
144856
145907
  return resolvers.promise;
144857
145908
  }
144858
145909
  if (hasConflict) {
144859
- ctx.promiseQueue = ctx.promiseQueue.then(() => {
145910
+ afterRegistration(() => {
144860
145911
  if (conflictRunRef) {
144861
145912
  resolvers.resolve(conflictRunRef);
144862
145913
  } else {
@@ -144972,7 +146023,9 @@ function createSleep(ctx) {
144972
146023
  }
144973
146024
  ctx.invocationsQueue.delete(correlationId);
144974
146025
  const eventIndex = ctx.eventsConsumer.eventIndex;
144975
- const barrier = registerDeliveryBarrier(ctx, eventIndex, "wait");
146026
+ const barrier = registerDeliveryBarrier(ctx, eventIndex, "wait", {
146027
+ deliveredAt: +event.createdAt
146028
+ });
144976
146029
  const earlierDelivered = awaitEarlierDeliveries(ctx, eventIndex, "wait");
144977
146030
  const queueAtCompletion = ctx.promiseQueue;
144978
146031
  void queueAtCompletion.then(() => earlierDelivered).then(() => {
@@ -145141,14 +146194,13 @@ async function createWorkflowSessionInner({ workflowCode: workflowCode2, workflo
145141
146194
  const promiseQueueHolder = { current: Promise.resolve() };
145142
146195
  const deliveryIdleHolder = { current: /* @__PURE__ */ __name(() => true, "current") };
145143
146196
  let clock = fixedTimestamp;
146197
+ const advanceClock = /* @__PURE__ */ __name((at) => {
146198
+ if (at > clock) {
146199
+ clock = at;
146200
+ updateTimestamp(at);
146201
+ }
146202
+ }, "advanceClock");
145144
146203
  const eventsConsumer = new EventsConsumer(events, {
145145
- onConsumedEvent: /* @__PURE__ */ __name((event) => {
145146
- const at = +event.createdAt;
145147
- if (at > clock) {
145148
- clock = at;
145149
- updateTimestamp(at);
145150
- }
145151
- }, "onConsumedEvent"),
145152
146204
  onUnconsumedEvent: /* @__PURE__ */ __name((event) => {
145153
146205
  onWorkflowError(new ReplayDivergenceError(`Replay could not consume event: eventType=${event.eventType}, correlationId=${event.correlationId}, eventId=${event.eventId}. ${describeDivergenceContext(event, workflowContext.invocationsQueue, eventsConsumer)}`, { eventId: event.eventId }));
145154
146206
  }, "onUnconsumedEvent"),
@@ -145201,6 +146253,7 @@ async function createWorkflowSessionInner({ workflowCode: workflowCode2, workflo
145201
146253
  pendingDeliveries: 0,
145202
146254
  suspensionGeneration: 0,
145203
146255
  pendingDeliveryBarriers: /* @__PURE__ */ new Map(),
146256
+ advanceClock,
145204
146257
  replayPayloadCache
145205
146258
  };
145206
146259
  deliveryIdleHolder.current = () => isDeliveryIdle(workflowContext);
@@ -145735,481 +146788,9 @@ __name(createWorkflowSessionInner, "createWorkflowSessionInner");
145735
146788
  init_global2();
145736
146789
  init_helpers3();
145737
146790
  init_resume_hook2();
145738
-
145739
- // ../core/dist/runtime/run.js
145740
- init_dist7();
145741
- init_dist12();
145742
- init_env_config2();
145743
- init_spec_version2();
145744
- init_encryption5();
145745
- init_serialization4();
145746
- init_util5();
145747
- init_get_world_lazy2();
145748
-
145749
- // ../core/dist/runtime/runs.js
145750
- init_dist7();
145751
- init_dist6();
145752
- init_encryption5();
145753
- init_serialization4();
145754
- init_helpers3();
145755
-
145756
- // ../core/dist/runtime/start.js
145757
- init_dist7();
145758
- init_dist5();
145759
- init_dist6();
145760
- init_node2();
145761
-
145762
- // ../core/dist/attribute-changes.js
145763
- init_dist7();
145764
- init_attributes_validation2();
145765
-
145766
- // ../core/dist/runtime/start.js
145767
- init_capabilities2();
145768
- init_classify_error();
145769
- init_encryption4();
145770
- init_logger2();
145771
- init_sealed_box2();
145772
- init_serialization4();
145773
- init_context_storage2();
145774
- init_semantic_conventions2();
145775
- init_telemetry4();
145776
- init_version4();
145777
- init_get_world_lazy2();
145778
- init_helpers3();
145779
- init_wait_until2();
145780
- init_world_compatibility2();
145781
- var ulid7 = monotonicFactory2();
145782
- var latestNoOpWarning2 = globalSingleton2("@workflow/core//latestNoOpWarning", 1, () => ({ warned: false }));
145783
-
145784
- // ../core/dist/runtime/runs.js
145785
- async function wakeUpRun2(world, runId, options) {
145786
- try {
145787
- const run3 = await world.runs.get(runId, { resolveData: "none" });
145788
- const compatMode = isLegacySpecVersion2(run3.specVersion);
145789
- const allEvents = [];
145790
- let cursor = null;
145791
- do {
145792
- const eventsResult = await world.events.list({
145793
- runId,
145794
- pagination: { sortOrder: "asc", ...cursor ? { cursor } : {} },
145795
- resolveData: "none"
145796
- });
145797
- allEvents.push(...eventsResult.data);
145798
- cursor = eventsResult.hasMore ? eventsResult.cursor : null;
145799
- } while (cursor);
145800
- const waitCreatedEvents = allEvents.filter((event) => event.eventType === "wait_created");
145801
- const waitCompletedCorrelationIds = new Set(allEvents.filter((event) => event.eventType === "wait_completed").map((event) => event.correlationId));
145802
- let pendingWaits = waitCreatedEvents.filter((event) => !waitCompletedCorrelationIds.has(event.correlationId));
145803
- if (options?.correlationIds && options.correlationIds.length > 0) {
145804
- const targetCorrelationIds = new Set(options.correlationIds);
145805
- pendingWaits = pendingWaits.filter((event) => event.correlationId && targetCorrelationIds.has(event.correlationId));
145806
- }
145807
- const errors = [];
145808
- let stoppedCount = 0;
145809
- for (const waitEvent of pendingWaits) {
145810
- if (!waitEvent.correlationId)
145811
- continue;
145812
- const eventData = compatMode ? {
145813
- eventType: "wait_completed",
145814
- correlationId: waitEvent.correlationId
145815
- } : {
145816
- eventType: "wait_completed",
145817
- correlationId: waitEvent.correlationId,
145818
- specVersion: run3.specVersion,
145819
- eventData: {
145820
- resumeAt: waitEvent.eventData.resumeAt
145821
- }
145822
- };
145823
- try {
145824
- await world.events.create(runId, eventData, { v1Compat: compatMode });
145825
- stoppedCount++;
145826
- } catch (err) {
145827
- if (EntityConflictError2.is(err)) {
145828
- stoppedCount++;
145829
- } else {
145830
- errors.push(err instanceof Error ? err : new Error(String(err)));
145831
- }
145832
- }
145833
- }
145834
- if (stoppedCount > 0) {
145835
- await world.queue(getWorkflowQueueName2(run3.workflowName, options?.namespace), {
145836
- runId
145837
- }, {
145838
- deploymentId: run3.deploymentId,
145839
- specVersion: run3.specVersion ?? SPEC_VERSION_LEGACY2
145840
- });
145841
- }
145842
- if (errors.length > 0) {
145843
- throw new AggregateError(errors, `Failed to complete ${errors.length}/${pendingWaits.length} pending wait(s) for run ${runId}`);
145844
- }
145845
- return { stoppedCount };
145846
- } catch (err) {
145847
- if (err instanceof AggregateError) {
145848
- throw err;
145849
- }
145850
- throw new Error(`Failed to wake up run ${runId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
145851
- }
145852
- }
145853
- __name(wakeUpRun2, "wakeUpRun");
145854
-
145855
- // ../core/dist/runtime/run.js
145856
- var RETURN_VALUE_POLL_INTERVAL_MS2 = 1e3;
145857
- var PAYLOAD_TERMINAL_RUN_STATUSES2 = /* @__PURE__ */ new Set([
145858
- "completed",
145859
- "failed"
145860
- ]);
145861
- var NOT_FOUND_RETRY_DELAYS2 = [1e3, 3e3, 6e3];
145862
- function getReturnValuePollIntervalMs2() {
145863
- return envNumber2("WORKFLOW_RETURN_VALUE_POLL_INTERVAL_MS", RETURN_VALUE_POLL_INTERVAL_MS2, { integer: true, min: 1 });
145864
- }
145865
- __name(getReturnValuePollIntervalMs2, "getReturnValuePollIntervalMs");
145866
- var RETURN_VALUE_WAIT_TIMEOUT_MS2 = 5e4;
145867
- function getReturnValueWaitTimeoutMs2() {
145868
- return envNumber2("WORKFLOW_RETURN_VALUE_WAIT_MS", RETURN_VALUE_WAIT_TIMEOUT_MS2, { integer: true, min: 1 });
145869
- }
145870
- __name(getReturnValueWaitTimeoutMs2, "getReturnValueWaitTimeoutMs");
145871
- var RETURN_VALUE_MAX_LONG_POLLS2 = 10;
145872
- function getReturnValueMaxLongPolls2() {
145873
- return envNumber2("WORKFLOW_RETURN_VALUE_MAX_LONG_POLLS", RETURN_VALUE_MAX_LONG_POLLS2, { integer: true, min: 1 });
145874
- }
145875
- __name(getReturnValueMaxLongPolls2, "getReturnValueMaxLongPolls");
145876
- function isReturnValueLongPollEnabled2() {
145877
- const raw = process.env.WORKFLOW_RETURN_VALUE_LONG_POLL;
145878
- if (raw === void 0 || raw === "")
145879
- return true;
145880
- return !(raw === "0" || raw.toLowerCase() === "false");
145881
- }
145882
- __name(isReturnValueLongPollEnabled2, "isReturnValueLongPollEnabled");
145883
- var Run2 = class _Run2 {
145884
- static {
145885
- __name(this, "Run");
145886
- }
145887
- static [WORKFLOW_SERIALIZE2](instance) {
145888
- return { runId: instance.runId, resilientStart: instance.#resilientStart };
145889
- }
145890
- static [WORKFLOW_DESERIALIZE2](data) {
145891
- return new _Run2(data.runId, { resilientStart: data.resilientStart });
145892
- }
145893
- /**
145894
- * The ID of the workflow run.
145895
- */
145896
- runId;
145897
- /**
145898
- * The world object.
145899
- * @internal
145900
- */
145901
- #worldPromise;
145902
- get #lazyWorldPromise() {
145903
- if (!this.#worldPromise)
145904
- this.#worldPromise = getWorldLazy2();
145905
- return this.#worldPromise;
145906
- }
145907
- /**
145908
- * Cached encryption key resolution. Resolved once on first use and
145909
- * reused for returnValue, getReadable(), etc.
145910
- * @internal
145911
- */
145912
- #encryptionKeyPromise = null;
145913
- /**
145914
- * When true, run_created failed and the run may not exist yet (the
145915
- * resilient start path will create it via run_started). pollReturnValue
145916
- * retries on WorkflowRunNotFoundError only when this flag is set so
145917
- * that normal runs fail fast on 404.
145918
- * @internal
145919
- */
145920
- #resilientStart = false;
145921
- constructor(runId, opts) {
145922
- this.runId = runId;
145923
- this.#resilientStart = opts?.resilientStart ?? false;
145924
- }
145925
- /**
145926
- * Resolves and caches the encryption key for this run.
145927
- * The key is the same for the lifetime of a run, so it only needs
145928
- * to be resolved once.
145929
- * @internal
145930
- */
145931
- #getEncryptionKey(run3) {
145932
- if (!this.#encryptionKeyPromise) {
145933
- this.#encryptionKeyPromise = (async () => {
145934
- const world = await this.#lazyWorldPromise;
145935
- const runData = run3 ?? await world.runs.get(this.runId);
145936
- const rawKey = await world.getEncryptionKeyForRun?.(runData);
145937
- return rawKey ? await deriveRunPayloadKeys2(rawKey) : void 0;
145938
- })();
145939
- }
145940
- return this.#encryptionKeyPromise;
145941
- }
145942
- /**
145943
- * Defers fetching the run and its encryption key until a readable is first
145944
- * consumed. The first pull prefetches it so an encrypted first frame can join
145945
- * the lookup; this also applies to an empty consumed stream.
145946
- * @internal
145947
- */
145948
- #getEncryptionKeyLazily() {
145949
- return () => this.#getEncryptionKey();
145950
- }
145951
- /**
145952
- * Interrupts pending `sleep()` calls, resuming the workflow early.
145953
- *
145954
- * @param options - Optional settings to target specific sleep calls by correlation ID.
145955
- * If not provided, all pending sleep calls will be interrupted.
145956
- * @returns A {@link StopSleepResult} object containing the number of sleep calls that were interrupted.
145957
- */
145958
- async wakeUp(options) {
145959
- "use step";
145960
- return wakeUpRun2(await this.#lazyWorldPromise, this.runId, options);
145961
- }
145962
- /**
145963
- * Cancels the workflow run.
145964
- *
145965
- * @param options - Optional cancellation settings. `cancelReason` records a
145966
- * free-text reason (max 512 chars) on the run_cancelled event, surfaced in
145967
- * the run detail view.
145968
- */
145969
- async cancel(options) {
145970
- "use step";
145971
- const world = await this.#lazyWorldPromise;
145972
- await world.events.create(this.runId, {
145973
- eventType: "run_cancelled",
145974
- specVersion: SPEC_VERSION_CURRENT2,
145975
- ...options?.cancelReason !== void 0 ? { eventData: { cancelReason: options.cancelReason } } : {}
145976
- });
145977
- }
145978
- /**
145979
- * Whether the workflow run exists.
145980
- */
145981
- get exists() {
145982
- "use step";
145983
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, { resolveData: "none" }).then(() => true).catch((error121) => {
145984
- if (WorkflowRunNotFoundError2.is(error121)) {
145985
- return false;
145986
- }
145987
- throw error121;
145988
- }));
145989
- }
145990
- /**
145991
- * The status of the workflow run.
145992
- */
145993
- get status() {
145994
- "use step";
145995
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId, { resolveData: "none" }).then((run3) => run3.status));
145996
- }
145997
- /**
145998
- * The return value of the workflow run.
145999
- * Polls the workflow return value until the workflow run completes.
146000
- */
146001
- get returnValue() {
146002
- "use step";
146003
- return this.#pollReturnValue();
146004
- }
146005
- /**
146006
- * The name of the workflow.
146007
- */
146008
- get workflowName() {
146009
- "use step";
146010
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId).then((run3) => run3.workflowName));
146011
- }
146012
- /**
146013
- * The timestamp when the workflow run was created.
146014
- */
146015
- get createdAt() {
146016
- "use step";
146017
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId).then((run3) => run3.createdAt));
146018
- }
146019
- /**
146020
- * The timestamp when the workflow run started execution.
146021
- * Returns undefined if the workflow has not started yet.
146022
- */
146023
- get startedAt() {
146024
- "use step";
146025
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId).then((run3) => run3.startedAt));
146026
- }
146027
- /**
146028
- * The timestamp when the workflow run completed.
146029
- * Returns undefined if the workflow has not completed yet.
146030
- */
146031
- get completedAt() {
146032
- "use step";
146033
- return this.#lazyWorldPromise.then((world) => world.runs.get(this.runId).then((run3) => run3.completedAt));
146034
- }
146035
- /**
146036
- * The readable stream of the workflow run.
146037
- */
146038
- get readable() {
146039
- return this.getReadable();
146040
- }
146041
- /**
146042
- * Retrieves the workflow run's default readable stream, which reads chunks
146043
- * written to the corresponding writable stream {@link getWritable}.
146044
- *
146045
- * The returned stream has an additional {@link WorkflowReadableStream.getTailIndex | getTailIndex()}
146046
- * helper that returns the index of the last known chunk. This is useful when
146047
- * building reconnection endpoints that need to inform clients where the
146048
- * stream starts.
146049
- *
146050
- * @param options - The options for the readable stream.
146051
- * @returns A `WorkflowReadableStream` for the workflow run.
146052
- */
146053
- getReadable(options = {}) {
146054
- "use step";
146055
- const { ops = [], global: global2 = globalThis, startIndex, namespace } = options;
146056
- const name = getWorkflowRunStreamId2(this.runId, namespace);
146057
- const encryptionKey = this.#getEncryptionKeyLazily();
146058
- const stream = getRunReadableStream2(global2, ops, this.runId, name, startIndex, encryptionKey);
146059
- const worldPromise = this.#lazyWorldPromise;
146060
- const runId = this.runId;
146061
- return Object.assign(stream, {
146062
- getTailIndex: /* @__PURE__ */ __name(async () => {
146063
- const world = await worldPromise;
146064
- const info = await world.streams.getInfo(runId, name);
146065
- return info.tailIndex;
146066
- }, "getTailIndex")
146067
- });
146068
- }
146069
- /** The writable stream of the workflow run. */
146070
- get writable() {
146071
- return this.getWritable();
146072
- }
146073
- /**
146074
- * Returns a writable that appends to this run's stream.
146075
- *
146076
- * Initialization is deferred until the first write. The run must already
146077
- * exist. The writable may be forwarded through `start()` and into steps, but
146078
- * grants no read access or additional authorization.
146079
- *
146080
- * @remarks
146081
- * `writer.close()` closes the shared stream. Contributors should call
146082
- * `releaseLock()`, which also drains pending writes.
146083
- *
146084
- * @param options - The writable stream options.
146085
- */
146086
- getWritable(options = {}) {
146087
- "use step";
146088
- const { ops = [], global: global2 = globalThis, namespace } = options;
146089
- const name = getWorkflowRunStreamId2(this.runId, namespace);
146090
- let targetPromise;
146091
- let writable;
146092
- const resolveTarget = /* @__PURE__ */ __name(() => {
146093
- targetPromise ??= this.#getMetadata().then(async (run3) => {
146094
- const target2 = {
146095
- key: await getForwardedWritableEncryptionKey2(this.runId, run3.deploymentId, run3.encryptionPublicKey),
146096
- deploymentId: run3.deploymentId,
146097
- encryptionPublicKey: run3.encryptionPublicKey
146098
- };
146099
- tagForwardedWritableTarget2(writable, target2);
146100
- return target2;
146101
- });
146102
- return targetPromise;
146103
- }, "resolveTarget");
146104
- writable = createForwardedWritable2({
146105
- global: global2,
146106
- ops,
146107
- runId: this.runId,
146108
- name,
146109
- key: /* @__PURE__ */ __name(() => resolveTarget().then(({ key }) => key), "key")
146110
- });
146111
- return writable;
146112
- }
146113
- /** Reads metadata, briefly retrying resilient starts. @internal */
146114
- async #getMetadata() {
146115
- const world = await this.#lazyWorldPromise;
146116
- const maxRetries = this.#resilientStart ? NOT_FOUND_RETRY_DELAYS2.length : 0;
146117
- let attempt = 0;
146118
- while (true) {
146119
- try {
146120
- return await world.runs.get(this.runId, { resolveData: "none" });
146121
- } catch (error121) {
146122
- if (!WorkflowRunNotFoundError2.is(error121) || attempt >= maxRetries) {
146123
- throw error121;
146124
- }
146125
- const delay = NOT_FOUND_RETRY_DELAYS2[attempt];
146126
- attempt++;
146127
- await new Promise((resolve3) => setTimeout(resolve3, delay));
146128
- }
146129
- }
146130
- }
146131
- /** @internal */
146132
- async #resolveTerminalReturnValue(run3) {
146133
- const expiredAt = run3.expiredAt;
146134
- if (expiredAt != null && expiredAt <= /* @__PURE__ */ new Date()) {
146135
- throw new RunExpiredError2(`Run "${this.runId}" ${run3.status === "completed" ? "completed" : `is ${run3.status}`}, but its data expired at ${expiredAt.toISOString()} and is no longer readable.`, this.runId, run3.status, expiredAt);
146136
- }
146137
- if (run3.status === "completed") {
146138
- const encryptionKey = await this.#getEncryptionKey(run3);
146139
- return await hydrateWorkflowReturnValue2(run3.output, this.runId, encryptionKey);
146140
- }
146141
- if (run3.status === "cancelled") {
146142
- throw new WorkflowRunCancelledError2(this.runId);
146143
- }
146144
- if (run3.status === "failed") {
146145
- const encryptionKey = await this.#getEncryptionKey(run3);
146146
- let hydratedError;
146147
- try {
146148
- hydratedError = await hydrateRunError2(run3.error, this.runId, encryptionKey);
146149
- } catch {
146150
- hydratedError = new Error("Failed to hydrate workflow run error");
146151
- }
146152
- throw new WorkflowRunFailedError2(this.runId, hydratedError, {
146153
- errorCode: run3.errorCode
146154
- });
146155
- }
146156
- throw new WorkflowRunNotCompletedError2(this.runId, run3.status);
146157
- }
146158
- /**
146159
- * Polls the workflow return value until the workflow run completes.
146160
- * @internal
146161
- * @returns The workflow return value.
146162
- */
146163
- async #pollReturnValue() {
146164
- const world = await this.#lazyWorldPromise;
146165
- let notFoundRetries = 0;
146166
- const NOT_FOUND_MAX_RETRIES = this.#resilientStart ? NOT_FOUND_RETRY_DELAYS2.length : 0;
146167
- const waitForTerminalStatus = isReturnValueLongPollEnabled2() ? world.runs.waitForTerminalStatus?.bind(world.runs) : void 0;
146168
- let longPolls = 0;
146169
- const maxLongPolls = getReturnValueMaxLongPolls2();
146170
- while (true) {
146171
- const iterationStartedAt = Date.now();
146172
- try {
146173
- const useLongPoll = waitForTerminalStatus && longPolls < maxLongPolls;
146174
- if (useLongPoll)
146175
- longPolls++;
146176
- const runMetadata = useLongPoll ? await waitForTerminalStatus(this.runId, {
146177
- timeoutMs: getReturnValueWaitTimeoutMs2(),
146178
- resolveData: "none"
146179
- }) : await world.runs.get(this.runId, {
146180
- resolveData: "none"
146181
- });
146182
- if (runMetadata.status === "cancelled") {
146183
- throw new WorkflowRunCancelledError2(this.runId);
146184
- }
146185
- if (PAYLOAD_TERMINAL_RUN_STATUSES2.has(runMetadata.status)) {
146186
- const run3 = await world.runs.get(this.runId, {
146187
- resolveData: "all"
146188
- });
146189
- return await this.#resolveTerminalReturnValue(run3);
146190
- }
146191
- throw new WorkflowRunNotCompletedError2(this.runId, runMetadata.status);
146192
- } catch (error121) {
146193
- if (WorkflowRunNotCompletedError2.is(error121)) {
146194
- const remainingIntervalMs = getReturnValuePollIntervalMs2() - (Date.now() - iterationStartedAt);
146195
- if (remainingIntervalMs > 0) {
146196
- await new Promise((resolve3) => setTimeout(resolve3, remainingIntervalMs));
146197
- }
146198
- continue;
146199
- }
146200
- if (WorkflowRunNotFoundError2.is(error121) && notFoundRetries < NOT_FOUND_MAX_RETRIES) {
146201
- const delay = NOT_FOUND_RETRY_DELAYS2[notFoundRetries];
146202
- notFoundRetries++;
146203
- await new Promise((resolve3) => setTimeout(resolve3, delay));
146204
- continue;
146205
- }
146206
- throw error121;
146207
- }
146208
- }
146209
- }
146210
- };
146211
-
146212
- // ../core/dist/runtime.js
146791
+ init_run();
146792
+ init_runs4();
146793
+ init_start();
146213
146794
  init_world();
146214
146795
  function clampMaxEvents(serverValue) {
146215
146796
  const override = getMaxEventsOverride();
@@ -146273,19 +146854,23 @@ function isStepMissingError(err) {
146273
146854
  return /step/i.test(err.message) && /not found/i.test(err.message);
146274
146855
  }
146275
146856
  __name(isStepMissingError, "isStepMissingError");
146276
- async function recordFatalRunError({ world, workflowRun, runId, requestId, err, errorCode, logMessage }) {
146857
+ async function recordFatalRunError({ world, workflowRun, runId, workflowName, requestId, err, errorCode, logMessage }) {
146277
146858
  runtimeLogger2.error(logMessage, {
146278
146859
  workflowRunId: runId,
146279
146860
  errorCode,
146280
146861
  error: err instanceof Error ? err.message : String(err)
146281
146862
  });
146863
+ let encryptionKey;
146864
+ let dehydratedError;
146282
146865
  try {
146283
146866
  const getEncryptionKey = memoizeEncryptionKey(world, workflowRun ?? runId);
146867
+ encryptionKey = await getEncryptionKey();
146868
+ dehydratedError = await dehydrateRunError(err, runId, encryptionKey, globalThis, (workflowRun?.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION2);
146284
146869
  await world.events.create(runId, {
146285
146870
  eventType: "run_failed",
146286
146871
  specVersion: SPEC_VERSION_CURRENT2,
146287
146872
  eventData: {
146288
- error: await dehydrateRunError(err, runId, await getEncryptionKey(), globalThis, (workflowRun?.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION2),
146873
+ error: dehydratedError,
146289
146874
  errorCode
146290
146875
  }
146291
146876
  }, { requestId });
@@ -146303,6 +146888,7 @@ async function recordFatalRunError({ world, workflowRun, runId, requestId, err,
146303
146888
  }
146304
146889
  throw failErr;
146305
146890
  }
146891
+ dispatchRunFailedHooks(runId, workflowName, dehydratedError, encryptionKey, errorCode);
146306
146892
  }
146307
146893
  __name(recordFatalRunError, "recordFatalRunError");
146308
146894
  function findRecordedTerminalRunEvent(events, runId) {
@@ -146353,7 +146939,7 @@ function openHookAndWaitState(events) {
146353
146939
  return { openHook: hooks.size > 0, openWait: waits.size > 0 };
146354
146940
  }
146355
146941
  __name(openHookAndWaitState, "openHookAndWaitState");
146356
- function getRetentionDecision({ suspension, serializationBlockerCount, hookContinuation = false }) {
146942
+ function getRetentionDecision({ suspension, serializationBlockerCount, hookContinuation = false, invocationContinuation = false }) {
146357
146943
  if (!isVmRetentionEnabled()) {
146358
146944
  return { retain: false, reason: "disabled" };
146359
146945
  }
@@ -146366,7 +146952,7 @@ function getRetentionDecision({ suspension, serializationBlockerCount, hookConti
146366
146952
  if (hookContinuation) {
146367
146953
  return { retain: true };
146368
146954
  }
146369
- if (suspension.stepCount === 0 && suspension.attributeCount === 0) {
146955
+ if (!invocationContinuation && suspension.stepCount === 0 && suspension.attributeCount === 0) {
146370
146956
  return { retain: false, reason: "no_replay_driver" };
146371
146957
  }
146372
146958
  return { retain: true };
@@ -146425,7 +147011,7 @@ function workflowEntrypoint(workflowCode2, options) {
146425
147011
  setWorkflowBasePath(options?.basePath);
146426
147012
  const namespace = resolveQueueNamespace2(options?.namespace);
146427
147013
  const workflowPrefix = getQueueTopicPrefix2("workflow", namespace);
146428
- const handler = /* @__PURE__ */ __name((worldHandlers) => worldHandlers.createQueueHandler(workflowPrefix, async (message_, metadata) => {
147014
+ const handler = /* @__PURE__ */ __name((worldHandlers) => worldHandlers.createQueueHandler(workflowPrefix, withRunInputs(worldHandlers)(async (message_, metadata, activity) => {
146429
147015
  const handlerEnteredAtMs = Date.now();
146430
147016
  const healthCheck3 = parseHealthCheckPayload(message_);
146431
147017
  if (healthCheck3) {
@@ -146456,14 +147042,17 @@ function workflowEntrypoint(workflowCode2, options) {
146456
147042
  const world = await getWorld();
146457
147043
  const getEncryptionKey = memoizeEncryptionKey(world, runId);
146458
147044
  const err = new FatalError2(`Workflow exceeded maximum queue deliveries (${metadata.attempt}/${maxQueueDeliveries})`);
147045
+ const encryptionKey = await getEncryptionKey();
147046
+ const dehydratedError = await dehydrateRunError(err, runId, encryptionKey);
146459
147047
  await world.events.create(runId, {
146460
147048
  eventType: "run_failed",
146461
147049
  specVersion: SPEC_VERSION_CURRENT2,
146462
147050
  eventData: {
146463
- error: await dehydrateRunError(err, runId, await getEncryptionKey()),
147051
+ error: dehydratedError,
146464
147052
  errorCode: RUN_ERROR_CODES2.MAX_DELIVERIES_EXCEEDED
146465
147053
  }
146466
147054
  }, { requestId });
147055
+ dispatchRunFailedHooks(runId, workflowName, dehydratedError, encryptionKey, RUN_ERROR_CODES2.MAX_DELIVERIES_EXCEEDED);
146467
147056
  } catch (err) {
146468
147057
  if (EntityConflictError2.is(err) || RunExpiredError2.is(err)) {
146469
147058
  return;
@@ -146621,6 +147210,7 @@ function workflowEntrypoint(workflowCode2, options) {
146621
147210
  world,
146622
147211
  workflowRun,
146623
147212
  runId,
147213
+ workflowName,
146624
147214
  requestId,
146625
147215
  err,
146626
147216
  errorCode,
@@ -146735,6 +147325,7 @@ function workflowEntrypoint(workflowCode2, options) {
146735
147325
  const { outcome, spanAttributes } = await guardDeploymentAffinity({
146736
147326
  world,
146737
147327
  run: run3,
147328
+ workflowName,
146738
147329
  requestId,
146739
147330
  retryCount: deploymentMismatchRetryCount,
146740
147331
  beforeStop,
@@ -146893,6 +147484,14 @@ function workflowEntrypoint(workflowCode2, options) {
146893
147484
  if (stepResult.type === "throttled") {
146894
147485
  return { timeoutSeconds: stepResult.timeoutSeconds };
146895
147486
  }
147487
+ if (world.capabilities?.invoke && stepResult.type !== "gone") {
147488
+ await queueMessage(world, getWorkflowQueueName2(workflowName, namespace), {
147489
+ runId,
147490
+ traceCarrier: await nextTraceCarrier(),
147491
+ requestedAt: /* @__PURE__ */ new Date()
147492
+ });
147493
+ return;
147494
+ }
146896
147495
  if (stepResult.type === "completed" && stepResult.hasPendingOps) {
146897
147496
  await queueMessage(world, getWorkflowQueueName2(workflowName, namespace), {
146898
147497
  runId,
@@ -146976,6 +147575,7 @@ function workflowEntrypoint(workflowCode2, options) {
146976
147575
  world,
146977
147576
  workflowRun,
146978
147577
  runId,
147578
+ workflowName,
146979
147579
  requestId,
146980
147580
  err,
146981
147581
  errorCode,
@@ -147304,6 +147904,7 @@ function workflowEntrypoint(workflowCode2, options) {
147304
147904
  const continuedHookIds = /* @__PURE__ */ new Set();
147305
147905
  const publishedStepCorrelationIds = /* @__PURE__ */ new Set();
147306
147906
  while (true) {
147907
+ const invocationRevision = activity?.revision ?? 0;
147307
147908
  loopIteration++;
147308
147909
  if (replayBudget.isExhausted()) {
147309
147910
  await handleReplayBudgetExhausted({
@@ -147530,6 +148131,7 @@ function workflowEntrypoint(workflowCode2, options) {
147530
148131
  }
147531
148132
  throw err;
147532
148133
  }
148134
+ dispatchRunCompletedHooks(runId, workflowName);
147533
148135
  span?.setAttributes({
147534
148136
  ...WorkflowRunStatus2("completed")
147535
148137
  });
@@ -147613,13 +148215,17 @@ function workflowEntrypoint(workflowCode2, options) {
147613
148215
  errorName: suspensionError.name,
147614
148216
  errorMessage: suspensionError.message
147615
148217
  });
148218
+ let failureKey;
148219
+ let dehydratedError;
147616
148220
  try {
147617
148221
  await awaitRunReady();
148222
+ failureKey = await encryptionKey.value;
148223
+ dehydratedError = await dehydrateRunError(suspensionError, runId, failureKey, globalThis, (workflowRun?.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION2);
147618
148224
  await createEvent({
147619
148225
  eventType: "run_failed",
147620
148226
  specVersion: SPEC_VERSION_CURRENT2,
147621
148227
  eventData: {
147622
- error: await dehydrateRunError(suspensionError, runId, await encryptionKey.value, globalThis, (workflowRun?.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION2),
148228
+ error: dehydratedError,
147623
148229
  errorCode
147624
148230
  }
147625
148231
  }, { requestId });
@@ -147633,6 +148239,7 @@ function workflowEntrypoint(workflowCode2, options) {
147633
148239
  }
147634
148240
  throw failErr;
147635
148241
  }
148242
+ dispatchRunFailedHooks(runId, workflowName, dehydratedError, failureKey, errorCode);
147636
148243
  span?.setAttributes({
147637
148244
  ...WorkflowRunStatus2("failed"),
147638
148245
  ...WorkflowErrorCode2(errorCode),
@@ -147652,7 +148259,8 @@ function workflowEntrypoint(workflowCode2, options) {
147652
148259
  // This suspension committed the event a hook's
147653
148260
  // own awaiter is parked on; the continuation
147654
148261
  // below drives the next iteration in-process.
147655
- hookContinuation: suspensionResult.hasAwaitedHookCreation || suspensionResult.hasHookConflict
148262
+ hookContinuation: suspensionResult.hasAwaitedHookCreation || suspensionResult.hasHookConflict,
148263
+ invocationContinuation: activity !== void 0
147656
148264
  }) : void 0;
147657
148265
  if (retentionDecision?.retain === false) {
147658
148266
  retainedSession = null;
@@ -147861,6 +148469,10 @@ function workflowEntrypoint(workflowCode2, options) {
147861
148469
  }
147862
148470
  return await reinvoke(0);
147863
148471
  }
148472
+ if (activity && Date.now() - invocationStartTime < noInlineReplayAfterMs && await activity.waitForActivity(invocationRevision)) {
148473
+ eventLog = nextEventLogLoad(eventLog);
148474
+ continue;
148475
+ }
147864
148476
  return;
147865
148477
  }
147866
148478
  const openHookWaitState = openHookWait.value;
@@ -148185,13 +148797,17 @@ function workflowEntrypoint(workflowCode2, options) {
148185
148797
  if (types9.isNativeError(terminalError) && errorStack) {
148186
148798
  terminalError.stack = errorStack;
148187
148799
  }
148800
+ let failureKey;
148801
+ let dehydratedError;
148188
148802
  try {
148189
148803
  await awaitRunReady();
148804
+ failureKey = await encryptionKey.value;
148805
+ dehydratedError = await dehydrateRunError(terminalError, runId, failureKey, globalThis, (workflowRun?.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION2);
148190
148806
  await createEvent({
148191
148807
  eventType: "run_failed",
148192
148808
  specVersion: SPEC_VERSION_CURRENT2,
148193
148809
  eventData: {
148194
- error: await dehydrateRunError(terminalError, runId, await encryptionKey.value, globalThis, (workflowRun?.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION2),
148810
+ error: dehydratedError,
148195
148811
  errorCode
148196
148812
  }
148197
148813
  }, {
@@ -148218,6 +148834,7 @@ function workflowEntrypoint(workflowCode2, options) {
148218
148834
  }
148219
148835
  throw failErr;
148220
148836
  }
148837
+ dispatchRunFailedHooks(runId, workflowName, dehydratedError, failureKey, errorCode);
148221
148838
  span?.setAttributes({
148222
148839
  ...WorkflowRunStatus2("failed"),
148223
148840
  ...WorkflowErrorCode2(errorCode),
@@ -148232,7 +148849,7 @@ function workflowEntrypoint(workflowCode2, options) {
148232
148849
  });
148233
148850
  });
148234
148851
  });
148235
- }), "handler");
148852
+ })), "handler");
148236
148853
  let cachedHandler;
148237
148854
  let invocationCount = 0;
148238
148855
  const entrypointCreatedAt = Date.now();
@@ -149119,11 +149736,11 @@ var Run = class _Run {
149119
149736
  return this.getWritable();
149120
149737
  }
149121
149738
  };
149122
- Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#wakeUp");
149123
- Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#cancel");
149124
- Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#getReadable");
149125
- Run.prototype["getWritable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#getWritable");
149126
- var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#exists");
149739
+ Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#wakeUp");
149740
+ Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#cancel");
149741
+ Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#getReadable");
149742
+ Run.prototype["getWritable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#getWritable");
149743
+ var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#exists");
149127
149744
  Object.defineProperty(Run.prototype, "exists", {
149128
149745
  get() {
149129
149746
  return __step_Run$exists.call(this);
@@ -149131,7 +149748,7 @@ Object.defineProperty(Run.prototype, "exists", {
149131
149748
  configurable: true,
149132
149749
  enumerable: false
149133
149750
  });
149134
- var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#status");
149751
+ var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#status");
149135
149752
  Object.defineProperty(Run.prototype, "status", {
149136
149753
  get() {
149137
149754
  return __step_Run$status.call(this);
@@ -149139,7 +149756,7 @@ Object.defineProperty(Run.prototype, "status", {
149139
149756
  configurable: true,
149140
149757
  enumerable: false
149141
149758
  });
149142
- var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#returnValue");
149759
+ var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#returnValue");
149143
149760
  Object.defineProperty(Run.prototype, "returnValue", {
149144
149761
  get() {
149145
149762
  return __step_Run$returnValue.call(this);
@@ -149147,7 +149764,7 @@ Object.defineProperty(Run.prototype, "returnValue", {
149147
149764
  configurable: true,
149148
149765
  enumerable: false
149149
149766
  });
149150
- var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#workflowName");
149767
+ var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#workflowName");
149151
149768
  Object.defineProperty(Run.prototype, "workflowName", {
149152
149769
  get() {
149153
149770
  return __step_Run$workflowName.call(this);
@@ -149155,7 +149772,7 @@ Object.defineProperty(Run.prototype, "workflowName", {
149155
149772
  configurable: true,
149156
149773
  enumerable: false
149157
149774
  });
149158
- var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#createdAt");
149775
+ var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#createdAt");
149159
149776
  Object.defineProperty(Run.prototype, "createdAt", {
149160
149777
  get() {
149161
149778
  return __step_Run$createdAt.call(this);
@@ -149163,7 +149780,7 @@ Object.defineProperty(Run.prototype, "createdAt", {
149163
149780
  configurable: true,
149164
149781
  enumerable: false
149165
149782
  });
149166
- var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#startedAt");
149783
+ var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#startedAt");
149167
149784
  Object.defineProperty(Run.prototype, "startedAt", {
149168
149785
  get() {
149169
149786
  return __step_Run$startedAt.call(this);
@@ -149171,7 +149788,7 @@ Object.defineProperty(Run.prototype, "startedAt", {
149171
149788
  configurable: true,
149172
149789
  enumerable: false
149173
149790
  });
149174
- var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.53//Run#completedAt");
149791
+ var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.54//Run#completedAt");
149175
149792
  Object.defineProperty(Run.prototype, "completedAt", {
149176
149793
  get() {
149177
149794
  return __step_Run$completedAt.call(this);
@@ -149188,7 +149805,7 @@ Object.defineProperty(Run.prototype, "completedAt", {
149188
149805
  enumerable: false,
149189
149806
  configurable: false
149190
149807
  });
149191
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.53//Run");
149808
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.54//Run");
149192
149809
 
149193
149810
  // ../core/dist/workflow/create-hook.js
149194
149811
  aliasSerializationClass(RUN_CLASS_ID, Run);
@@ -156784,7 +157401,7 @@ globalThis.__private_workflows.set("workflow//./workflows/inline-execution//hook
156784
157401
  var latestNoOpWarning = globalSingleton("@workflow/core//latestNoOpWarning", 1, () => ({
156785
157402
  warned: false
156786
157403
  }));
156787
- var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.0.0-beta.53//start");
157404
+ var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.0.0-beta.54//start");
156788
157405
 
156789
157406
  // workflows/lineage.ts
156790
157407
  var noop = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//./workflows/lineage//noop");