@workflow/world-testing 5.0.0-beta.34 → 5.0.0-beta.36

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.
@@ -14879,12 +14879,14 @@ function applyAttributeChanges(existing, changes) {
14879
14879
  }
14880
14880
  return next2;
14881
14881
  }
14882
- var RESERVED_ATTRIBUTE_KEY_PREFIX2, ATTRIBUTE_KEY_MAX_LENGTH2, ATTRIBUTE_VALUE_MAX_BYTES2, ATTRIBUTE_MAX_PER_RUN2, AttributeChangeSchema2, AttributeChangesSchema2, AttributeValidationError2, valueByteLength2;
14882
+ var RESERVED_ATTRIBUTE_KEY_PREFIX2, ROOT_RUN_ID_ATTRIBUTE2, PARENT_RUN_ID_ATTRIBUTE2, ATTRIBUTE_KEY_MAX_LENGTH2, ATTRIBUTE_VALUE_MAX_BYTES2, ATTRIBUTE_MAX_PER_RUN2, AttributeChangeSchema2, AttributeChangesSchema2, AttributeValidationError2, valueByteLength2;
14883
14883
  var init_attributes2 = __esm({
14884
14884
  "../world/dist/attributes.js"() {
14885
14885
  "use strict";
14886
14886
  init_zod2();
14887
14887
  RESERVED_ATTRIBUTE_KEY_PREFIX2 = "$";
14888
+ ROOT_RUN_ID_ATTRIBUTE2 = `${RESERVED_ATTRIBUTE_KEY_PREFIX2}rootRunId`;
14889
+ PARENT_RUN_ID_ATTRIBUTE2 = `${RESERVED_ATTRIBUTE_KEY_PREFIX2}parentRunId`;
14888
14890
  ATTRIBUTE_KEY_MAX_LENGTH2 = 256;
14889
14891
  ATTRIBUTE_VALUE_MAX_BYTES2 = 256;
14890
14892
  ATTRIBUTE_MAX_PER_RUN2 = 64;
@@ -15110,6 +15112,17 @@ var init_events2 = __esm({
15110
15112
  // stso.
15111
15113
  stepCount: external_exports2.number().int().positive().optional(),
15112
15114
  eventCount: external_exports2.number().int().positive().optional(),
15115
+ // Run-started-to-first-step: milliseconds from the `run_started` response
15116
+ // landing (or, under turbo, the local run synthesis instant) until this
15117
+ // step's start POST was issued. A sub-window of ttfs. Only reported
15118
+ // alongside the same eligibility as ttfs.
15119
+ rsfs: external_exports2.number().optional(),
15120
+ // Synchronous workflow-function replay duration of only the FINAL replay
15121
+ // pass within the rsfs window (the pass that scheduled the first step),
15122
+ // excluding awaited network I/O — not accumulated across earlier
15123
+ // pre-first-step passes, so it is not "the replay portion of rsfs". Only
15124
+ // present alongside rsfs, and only for the run's first step.
15125
+ finalSchedulingReplay: external_exports2.number().optional(),
15113
15126
  // Names of the runtime's optional startup-latency optimizations that were
15114
15127
  // active for this measurement (e.g. 'turbo', 'lazyStepStart',
15115
15128
  // 'optimisticStart'), so latency metrics can be segmented by them.
@@ -15191,6 +15204,7 @@ var init_events2 = __esm({
15191
15204
  correlationId: external_exports2.string(),
15192
15205
  eventData: external_exports2.object({
15193
15206
  token: external_exports2.string(),
15207
+ tokenRetentionUntil: external_exports2.coerce.date().optional(),
15194
15208
  metadata: SerializedDataSchema2.optional(),
15195
15209
  isWebhook: external_exports2.boolean().optional(),
15196
15210
  isSystem: external_exports2.boolean().optional()
@@ -15362,7 +15376,7 @@ var init_events2 = __esm({
15362
15376
  });
15363
15377
 
15364
15378
  // ../world/dist/runs.js
15365
- function isTerminalWorkflowRunStatus(status) {
15379
+ function isTerminalWorkflowRunStatus2(status) {
15366
15380
  return TERMINAL_WORKFLOW_RUN_STATUSES2.includes(status);
15367
15381
  }
15368
15382
  var WorkflowRunStatusSchema2, TerminalWorkflowRunStatusSchema2, TERMINAL_WORKFLOW_RUN_STATUSES2, WorkflowRunBaseSchema2, WorkflowRunSchema2;
@@ -15384,7 +15398,7 @@ var init_runs2 = __esm({
15384
15398
  "cancelled"
15385
15399
  ]);
15386
15400
  TERMINAL_WORKFLOW_RUN_STATUSES2 = TerminalWorkflowRunStatusSchema2.options;
15387
- __name(isTerminalWorkflowRunStatus, "isTerminalWorkflowRunStatus");
15401
+ __name(isTerminalWorkflowRunStatus2, "isTerminalWorkflowRunStatus");
15388
15402
  WorkflowRunBaseSchema2 = external_exports2.object({
15389
15403
  runId: external_exports2.string(),
15390
15404
  status: WorkflowRunStatusSchema2,
@@ -16208,10 +16222,12 @@ __export(dist_exports, {
16208
16222
  HookSchema: () => HookSchema2,
16209
16223
  LegacySerializedDataSchemaV1: () => LegacySerializedDataSchemaV12,
16210
16224
  MessageId: () => MessageId2,
16225
+ PARENT_RUN_ID_ATTRIBUTE: () => PARENT_RUN_ID_ATTRIBUTE2,
16211
16226
  PaginatedResponseSchema: () => PaginatedResponseSchema,
16212
16227
  QueuePayloadSchema: () => QueuePayloadSchema2,
16213
16228
  QueuePrefix: () => QueuePrefix2,
16214
16229
  RESERVED_ATTRIBUTE_KEY_PREFIX: () => RESERVED_ATTRIBUTE_KEY_PREFIX2,
16230
+ ROOT_RUN_ID_ATTRIBUTE: () => ROOT_RUN_ID_ATTRIBUTE2,
16215
16231
  RUN_EVENT_TYPES: () => RUN_EVENT_TYPES2,
16216
16232
  RunInputSchema: () => RunInputSchema2,
16217
16233
  SPEC_VERSION_CURRENT: () => SPEC_VERSION_CURRENT2,
@@ -16258,7 +16274,7 @@ __export(dist_exports, {
16258
16274
  isTerminalRunEventType: () => isTerminalRunEventType,
16259
16275
  isTerminalStepEventType: () => isTerminalStepEventType,
16260
16276
  isTerminalStepStatus: () => isTerminalStepStatus,
16261
- isTerminalWorkflowRunStatus: () => isTerminalWorkflowRunStatus,
16277
+ isTerminalWorkflowRunStatus: () => isTerminalWorkflowRunStatus2,
16262
16278
  isWaitEventType: () => isWaitEventType,
16263
16279
  parseQueueName: () => parseQueueName,
16264
16280
  reenqueueActiveRuns: () => reenqueueActiveRuns,
@@ -16646,6 +16662,8 @@ var init_error_codes2 = __esm({
16646
16662
  REPLAY_DIVERGENCE: "REPLAY_DIVERGENCE",
16647
16663
  /** Run exceeded the maximum number of queue deliveries */
16648
16664
  MAX_DELIVERIES_EXCEEDED: "MAX_DELIVERIES_EXCEEDED",
16665
+ /** Run exceeded the maximum number of events per run */
16666
+ MAX_EVENTS_EXCEEDED: "MAX_EVENTS_EXCEEDED",
16649
16667
  /** Workflow replay exceeded the maximum allowed duration */
16650
16668
  REPLAY_TIMEOUT: "REPLAY_TIMEOUT",
16651
16669
  /** World response violated the SDK contract and cannot be retried safely */
@@ -16679,7 +16697,7 @@ function buildFramedDetails2(hint3, slug) {
16679
16697
  out.push({ label: "docs", value: `${BASE_URL2}/${slug}` });
16680
16698
  return out;
16681
16699
  }
16682
- var BASE_URL2, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError, ReplayDivergenceError, RuntimeDecryptionError2, SerializationError2, StepNotRegisteredError2, WorkflowNotRegisteredError2, WorkflowRunNotFoundError2, HookConflictError2, HookNotFoundError2, EntityConflictError2, RunExpiredError, TooEarlyError, ThrottleError2, WorkflowRunCancelledError2, RunNotSupportedError, FatalError2, RetryableError2, FATAL_ERROR_KEY2, RETRYABLE_ERROR_KEY2, HOOK_CONFLICT_ERROR_KEY2, RUNTIME_DECRYPTION_ERROR_KEY2;
16700
+ var BASE_URL2, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError, ReplayDivergenceError, MaxEventsExceededError, RuntimeDecryptionError2, SerializationError2, StepNotRegisteredError2, WorkflowNotRegisteredError2, WorkflowRunNotFoundError2, HookConflictError2, HookNotFoundError2, EntityConflictError2, RunExpiredError, TooEarlyError, ThrottleError2, PreconditionFailedError, WorkflowRunCancelledError2, RunNotSupportedError, FatalError2, RetryableError2, FATAL_ERROR_KEY2, RETRYABLE_ERROR_KEY2, HOOK_CONFLICT_ERROR_KEY2, RUNTIME_DECRYPTION_ERROR_KEY2;
16683
16701
  var init_dist7 = __esm({
16684
16702
  "../errors/dist/index.js"() {
16685
16703
  "use strict";
@@ -16834,6 +16852,22 @@ Caused by: ${options.cause.stack}`;
16834
16852
  return isError2(value) && value.name === "ReplayDivergenceError" && typeof value.eventId === "string";
16835
16853
  }
16836
16854
  };
16855
+ MaxEventsExceededError = class extends WorkflowError2 {
16856
+ static {
16857
+ __name(this, "MaxEventsExceededError");
16858
+ }
16859
+ eventCount;
16860
+ limit;
16861
+ constructor(eventCount, limit, options) {
16862
+ super(`Workflow exceeded the maximum of ${limit} events per run`, options);
16863
+ this.name = "MaxEventsExceededError";
16864
+ this.eventCount = eventCount;
16865
+ this.limit = limit;
16866
+ }
16867
+ static is(value) {
16868
+ return isError2(value) && value.name === "MaxEventsExceededError";
16869
+ }
16870
+ };
16837
16871
  RuntimeDecryptionError2 = class extends WorkflowRuntimeError2 {
16838
16872
  static {
16839
16873
  __name(this, "RuntimeDecryptionError");
@@ -17004,6 +17038,18 @@ Caused by: ${options.cause.stack}`;
17004
17038
  return isError2(value) && value.name === "ThrottleError";
17005
17039
  }
17006
17040
  };
17041
+ PreconditionFailedError = class extends WorkflowWorldError2 {
17042
+ static {
17043
+ __name(this, "PreconditionFailedError");
17044
+ }
17045
+ constructor(message, options) {
17046
+ super(message, { status: 412, retryAfter: options?.retryAfter });
17047
+ this.name = "PreconditionFailedError";
17048
+ }
17049
+ static is(value) {
17050
+ return isError2(value) && value.name === "PreconditionFailedError";
17051
+ }
17052
+ };
17007
17053
  WorkflowRunCancelledError2 = class extends WorkflowError2 {
17008
17054
  static {
17009
17055
  __name(this, "WorkflowRunCancelledError");
@@ -20055,9 +20101,9 @@ var require_util = __commonJS({
20055
20101
  yield* this[kBody];
20056
20102
  }
20057
20103
  };
20058
- function noop2() {
20104
+ function noop3() {
20059
20105
  }
20060
- __name(noop2, "noop");
20106
+ __name(noop3, "noop");
20061
20107
  function wrapRequestBody(body) {
20062
20108
  if (isStream(body)) {
20063
20109
  if (bodyLength(body) === 0) {
@@ -20760,7 +20806,7 @@ var require_util = __commonJS({
20760
20806
  __name(errorRequest, "errorRequest");
20761
20807
  var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
20762
20808
  if (!opts.timeout) {
20763
- return noop2;
20809
+ return noop3;
20764
20810
  }
20765
20811
  let s1 = null;
20766
20812
  let s2 = null;
@@ -20776,7 +20822,7 @@ var require_util = __commonJS({
20776
20822
  };
20777
20823
  } : (socketWeakRef, opts) => {
20778
20824
  if (!opts.timeout) {
20779
- return noop2;
20825
+ return noop3;
20780
20826
  }
20781
20827
  let s1 = null;
20782
20828
  const fastTimer = timers.setFastTimeout(() => {
@@ -25496,13 +25542,13 @@ var require_body = __commonJS({
25496
25542
  var { runtimeFeatures } = require_runtime_features();
25497
25543
  var random = runtimeFeatures.has("crypto") ? __require("node:crypto").randomInt : (max) => Math.floor(Math.random() * max);
25498
25544
  var textEncoder = new TextEncoder();
25499
- function noop2() {
25545
+ function noop3() {
25500
25546
  }
25501
- __name(noop2, "noop");
25547
+ __name(noop3, "noop");
25502
25548
  var streamRegistry = new FinalizationRegistry((weakRef) => {
25503
25549
  const stream = weakRef.deref();
25504
25550
  if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {
25505
- stream.cancel("Response object has been garbage collected").catch(noop2);
25551
+ stream.cancel("Response object has been garbage collected").catch(noop3);
25506
25552
  }
25507
25553
  });
25508
25554
  function extractBody(object3, keepalive = false) {
@@ -27867,7 +27913,7 @@ var require_client = __commonJS({
27867
27913
  var getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => {
27868
27914
  throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
27869
27915
  };
27870
- var noop2 = /* @__PURE__ */ __name(() => {
27916
+ var noop3 = /* @__PURE__ */ __name(() => {
27871
27917
  }, "noop");
27872
27918
  function getPipelining(client) {
27873
27919
  return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1;
@@ -28174,7 +28220,7 @@ var require_client = __commonJS({
28174
28220
  return;
28175
28221
  }
28176
28222
  if (client.destroyed) {
28177
- util.destroy(socket.on("error", noop2), new ClientDestroyedError());
28223
+ util.destroy(socket.on("error", noop3), new ClientDestroyedError());
28178
28224
  client[kResume]();
28179
28225
  return;
28180
28226
  }
@@ -28182,7 +28228,7 @@ var require_client = __commonJS({
28182
28228
  try {
28183
28229
  client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
28184
28230
  } catch (err2) {
28185
- socket.destroy().on("error", noop2);
28231
+ socket.destroy().on("error", noop3);
28186
28232
  handleConnectError(client, err2, { host, hostname: hostname5, protocol, port });
28187
28233
  client[kResume]();
28188
28234
  return;
@@ -29846,7 +29892,7 @@ var require_proxy_agent = __commonJS({
29846
29892
  return new Pool(origin, opts);
29847
29893
  }
29848
29894
  __name(defaultFactory, "defaultFactory");
29849
- var noop2 = /* @__PURE__ */ __name(() => {
29895
+ var noop3 = /* @__PURE__ */ __name(() => {
29850
29896
  }, "noop");
29851
29897
  function defaultAgentFactory(origin, opts) {
29852
29898
  if (opts.connections === 1) {
@@ -29990,7 +30036,7 @@ var require_proxy_agent = __commonJS({
29990
30036
  };
29991
30037
  const { socket, statusCode } = await this[kClient].connect(connectParams);
29992
30038
  if (statusCode !== 200) {
29993
- socket.on("error", noop2).destroy();
30039
+ socket.on("error", noop3).destroy();
29994
30040
  callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`));
29995
30041
  return;
29996
30042
  }
@@ -30628,7 +30674,7 @@ var require_readable = __commonJS({
30628
30674
  var kContentLength = /* @__PURE__ */ Symbol("kContentLength");
30629
30675
  var kUsed = /* @__PURE__ */ Symbol("kUsed");
30630
30676
  var kBytesRead = /* @__PURE__ */ Symbol("kBytesRead");
30631
- var noop2 = /* @__PURE__ */ __name(() => {
30677
+ var noop3 = /* @__PURE__ */ __name(() => {
30632
30678
  }, "noop");
30633
30679
  var BodyReadable = class extends Readable {
30634
30680
  static {
@@ -30856,7 +30902,7 @@ var require_readable = __commonJS({
30856
30902
  } else {
30857
30903
  this.on("close", resolve2);
30858
30904
  }
30859
- this.on("error", noop2).on("data", () => {
30905
+ this.on("error", noop3).on("data", () => {
30860
30906
  if (this[kBytesRead] > limit) {
30861
30907
  this.destroy();
30862
30908
  }
@@ -31034,9 +31080,9 @@ var require_api_request = __commonJS({
31034
31080
  var { Readable } = require_readable();
31035
31081
  var { InvalidArgumentError, RequestAbortedError } = require_errors();
31036
31082
  var util = require_util();
31037
- function noop2() {
31083
+ function noop3() {
31038
31084
  }
31039
- __name(noop2, "noop");
31085
+ __name(noop3, "noop");
31040
31086
  var RequestHandler = class extends AsyncResource {
31041
31087
  static {
31042
31088
  __name(this, "RequestHandler");
@@ -31065,7 +31111,7 @@ var require_api_request = __commonJS({
31065
31111
  super("UNDICI_REQUEST");
31066
31112
  } catch (err) {
31067
31113
  if (util.isStream(body)) {
31068
- util.destroy(body.on("error", noop2), err);
31114
+ util.destroy(body.on("error", noop3), err);
31069
31115
  }
31070
31116
  throw err;
31071
31117
  }
@@ -31088,7 +31134,7 @@ var require_api_request = __commonJS({
31088
31134
  this.removeAbortListener = util.addAbortListener(signal, () => {
31089
31135
  this.reason = signal.reason ?? new RequestAbortedError();
31090
31136
  if (this.res) {
31091
- util.destroy(this.res.on("error", noop2), this.reason);
31137
+ util.destroy(this.res.on("error", noop3), this.reason);
31092
31138
  } else if (this.abort) {
31093
31139
  this.abort(this.reason);
31094
31140
  }
@@ -31142,7 +31188,7 @@ var require_api_request = __commonJS({
31142
31188
  });
31143
31189
  } catch (err) {
31144
31190
  this.res = null;
31145
- util.destroy(res.on("error", noop2), err);
31191
+ util.destroy(res.on("error", noop3), err);
31146
31192
  queueMicrotask(() => {
31147
31193
  throw err;
31148
31194
  });
@@ -31167,13 +31213,13 @@ var require_api_request = __commonJS({
31167
31213
  if (res) {
31168
31214
  this.res = null;
31169
31215
  queueMicrotask(() => {
31170
- util.destroy(res.on("error", noop2), err);
31216
+ util.destroy(res.on("error", noop3), err);
31171
31217
  });
31172
31218
  }
31173
31219
  if (body) {
31174
31220
  this.body = null;
31175
31221
  if (util.isStream(body)) {
31176
- body.on("error", noop2);
31222
+ body.on("error", noop3);
31177
31223
  util.destroy(body, err);
31178
31224
  }
31179
31225
  }
@@ -31273,9 +31319,9 @@ var require_api_stream = __commonJS({
31273
31319
  var { InvalidArgumentError, InvalidReturnValueError } = require_errors();
31274
31320
  var util = require_util();
31275
31321
  var { addSignal, removeSignal } = require_abort_signal();
31276
- function noop2() {
31322
+ function noop3() {
31277
31323
  }
31278
- __name(noop2, "noop");
31324
+ __name(noop3, "noop");
31279
31325
  var StreamHandler = class extends AsyncResource {
31280
31326
  static {
31281
31327
  __name(this, "StreamHandler");
@@ -31304,7 +31350,7 @@ var require_api_stream = __commonJS({
31304
31350
  super("UNDICI_STREAM");
31305
31351
  } catch (err) {
31306
31352
  if (util.isStream(body)) {
31307
- util.destroy(body.on("error", noop2), err);
31353
+ util.destroy(body.on("error", noop3), err);
31308
31354
  }
31309
31355
  throw err;
31310
31356
  }
@@ -31447,9 +31493,9 @@ var require_api_pipeline = __commonJS({
31447
31493
  } = require_errors();
31448
31494
  var util = require_util();
31449
31495
  var { addSignal, removeSignal } = require_abort_signal();
31450
- function noop2() {
31496
+ function noop3() {
31451
31497
  }
31452
- __name(noop2, "noop");
31498
+ __name(noop3, "noop");
31453
31499
  var kResume = /* @__PURE__ */ Symbol("resume");
31454
31500
  var PipelineRequest = class extends Readable {
31455
31501
  static {
@@ -31517,7 +31563,7 @@ var require_api_pipeline = __commonJS({
31517
31563
  this.abort = null;
31518
31564
  this.context = null;
31519
31565
  this.onInfo = onInfo || null;
31520
- this.req = new PipelineRequest().on("error", noop2);
31566
+ this.req = new PipelineRequest().on("error", noop3);
31521
31567
  this.ret = new Duplex({
31522
31568
  readableObjectMode: opts.objectMode,
31523
31569
  autoDestroy: true,
@@ -31588,7 +31634,7 @@ var require_api_pipeline = __commonJS({
31588
31634
  context: context2
31589
31635
  });
31590
31636
  } catch (err) {
31591
- this.res.on("error", noop2);
31637
+ this.res.on("error", noop3);
31592
31638
  throw err;
31593
31639
  }
31594
31640
  if (!body || typeof body.on !== "function") {
@@ -33943,7 +33989,7 @@ var require_redirect_handler = __commonJS({
33943
33989
  var EE = __require("node:events");
33944
33990
  var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
33945
33991
  var kBody = /* @__PURE__ */ Symbol("body");
33946
- var noop2 = /* @__PURE__ */ __name(() => {
33992
+ var noop3 = /* @__PURE__ */ __name(() => {
33947
33993
  }, "noop");
33948
33994
  var BodyAsyncIterable = class {
33949
33995
  static {
@@ -34012,14 +34058,14 @@ var require_redirect_handler = __commonJS({
34012
34058
  if ((statusCode === 301 || statusCode === 302) && this.opts.method === "POST") {
34013
34059
  this.opts.method = "GET";
34014
34060
  if (util.isStream(this.opts.body)) {
34015
- util.destroy(this.opts.body.on("error", noop2));
34061
+ util.destroy(this.opts.body.on("error", noop3));
34016
34062
  }
34017
34063
  this.opts.body = null;
34018
34064
  }
34019
34065
  if (statusCode === 303 && this.opts.method !== "HEAD") {
34020
34066
  this.opts.method = "GET";
34021
34067
  if (util.isStream(this.opts.body)) {
34022
- util.destroy(this.opts.body.on("error", noop2));
34068
+ util.destroy(this.opts.body.on("error", noop3));
34023
34069
  }
34024
34070
  this.opts.body = null;
34025
34071
  }
@@ -35569,9 +35615,9 @@ var require_cache_handler = __commonJS({
35569
35615
  isEtagUsable
35570
35616
  } = require_cache2();
35571
35617
  var { parseHttpDate } = require_date();
35572
- function noop2() {
35618
+ function noop3() {
35573
35619
  }
35574
- __name(noop2, "noop");
35620
+ __name(noop3, "noop");
35575
35621
  var HEURISTICALLY_CACHEABLE_STATUS_CODES = [
35576
35622
  200,
35577
35623
  203,
@@ -35654,7 +35700,7 @@ var require_cache_handler = __commonJS({
35654
35700
  const handler = this;
35655
35701
  if (!util.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
35656
35702
  try {
35657
- this.#store.delete(this.#cacheKey)?.catch?.(noop2);
35703
+ this.#store.delete(this.#cacheKey)?.catch?.(noop3);
35658
35704
  } catch {
35659
35705
  }
35660
35706
  return downstreamOnHeaders();
@@ -45121,7 +45167,7 @@ var init_log_format2 = __esm({
45121
45167
  function SemanticConvention3(...names) {
45122
45168
  return (value) => Object.fromEntries(names.map((name) => [name, value]));
45123
45169
  }
45124
- var WorkflowName2, WorkflowOperation2, WorkflowRunId3, WorkflowRunStatus2, WorkflowStartedAt2, WorkflowEventsCount2, WorkflowArgumentsCount2, WorkflowResultType2, WorkflowTracePropagated2, WorkflowTraceMode2, WorkflowTurbo2, WorkflowErrorName2, WorkflowErrorMessage2, WorkflowErrorCode2, WorkflowStepsCreated2, WorkflowHooksCreated2, WorkflowWaitsCreated2, WorkflowOwnedRecoverySteps2, WorkflowBackstopWakesArmed2, WorkflowRouteType2, WorkflowRouteHandlerCached2, WorkflowRouteInvocationCount2, WorkflowRouteEntrypointAgeMs2, WorkflowRouteModuleBodyInitMs2, StepName2, StepId3, StepAttempt2, StepStatus2, StepMaxRetries2, StepTracePropagated2, StepTtfsMs2, StepStsoMs2, StepLatencyOptimizations2, StepSkipped2, StepSkipReason2, StepArgumentsCount2, StepResultType2, StepErrorName2, StepErrorMessage2, StepFatalError2, StepRetryExhausted2, StepRetryTimeoutSeconds2, StepRetryWillRetry2, MessagingSystem2, MessagingDestinationName2, MessagingMessageId2, MessagingOperationType2, QueueOverheadMs2, DeploymentId2, HookToken2, HookId2, HookFound2, WebhookHandlersTriggered2, WorkflowSuspensionState2, WorkflowSuspensionHookCount2, WorkflowSuspensionStepCount2, WorkflowSuspensionWaitCount2, HttpRequestMethod2, HttpRoute2, UrlFull2, ServerAddress2, ServerPort2, HttpResponseStatusCode2, ErrorType2, WorldParseFormat2, WorkflowEventsPagesLoaded2, QueueDeserializeTimeMs2, QueueExecutionTimeMs2, QueueSerializeTimeMs2, SerializationOperation2, SerializationCompressed2, SerializationCodec2, SerializationUncompressedBytes2, SerializationStoredBytes2, SerializationCompressionRatio2, PeerService3, RpcSystem3, RpcService3, RpcMethod3, ErrorRetryable2, ErrorCategory2;
45170
+ var WorkflowName2, WorkflowOperation2, WorkflowRunId3, WorkflowRunStatus2, WorkflowStartedAt2, WorkflowEventsCount2, WorkflowArgumentsCount2, WorkflowResultType2, WorkflowTracePropagated2, WorkflowTraceMode2, WorkflowTurbo2, WorkflowErrorName2, WorkflowErrorMessage2, WorkflowErrorCode2, WorkflowStepsCreated2, WorkflowHooksCreated2, WorkflowWaitsCreated2, WorkflowOwnedRecoverySteps2, WorkflowBackstopWakesArmed2, WorkflowRouteType2, WorkflowRouteHandlerCached2, WorkflowRouteInvocationCount2, WorkflowRouteEntrypointAgeMs2, WorkflowRouteModuleBodyInitMs2, StepName2, StepId3, StepAttempt2, StepStatus2, StepMaxRetries2, StepTracePropagated2, StepTtfsMs2, StepStsoMs2, StepRsfsMs2, StepFinalSchedulingReplayMs2, StepLatencyOptimizations2, StepSkipped2, StepSkipReason2, StepArgumentsCount2, StepResultType2, StepErrorName2, StepErrorMessage2, StepFatalError2, StepRetryExhausted2, StepRetryTimeoutSeconds2, StepRetryWillRetry2, MessagingSystem2, MessagingDestinationName2, MessagingMessageId2, MessagingOperationType2, QueueOverheadMs2, DeploymentId2, HookToken2, HookId2, HookFound2, WebhookHandlersTriggered2, WorkflowSuspensionState2, WorkflowSuspensionHookCount2, WorkflowSuspensionStepCount2, WorkflowSuspensionWaitCount2, HttpRequestMethod2, HttpRoute2, UrlFull2, ServerAddress2, ServerPort2, HttpResponseStatusCode2, ErrorType2, WorldParseFormat2, WorkflowEventsPagesLoaded2, QueueDeserializeTimeMs2, QueueExecutionTimeMs2, QueueSerializeTimeMs2, SerializationOperation2, SerializationCompressed2, SerializationCodec2, SerializationUncompressedBytes2, SerializationStoredBytes2, SerializationCompressionRatio2, PeerService3, RpcSystem3, RpcService3, RpcMethod3, ErrorRetryable2, ErrorCategory2;
45125
45171
  var init_semantic_conventions2 = __esm({
45126
45172
  "../core/dist/telemetry/semantic-conventions.js"() {
45127
45173
  "use strict";
@@ -45158,6 +45204,8 @@ var init_semantic_conventions2 = __esm({
45158
45204
  StepTracePropagated2 = SemanticConvention3("step.trace.propagated");
45159
45205
  StepTtfsMs2 = SemanticConvention3("step.ttfs_ms");
45160
45206
  StepStsoMs2 = SemanticConvention3("step.stso_ms");
45207
+ StepRsfsMs2 = SemanticConvention3("step.rsfs_ms");
45208
+ StepFinalSchedulingReplayMs2 = SemanticConvention3("step.final_scheduling_replay_ms");
45161
45209
  StepLatencyOptimizations2 = SemanticConvention3("step.latency_optimizations");
45162
45210
  StepSkipped2 = SemanticConvention3("step.skipped");
45163
45211
  StepSkipReason2 = SemanticConvention3("step.skip_reason");
@@ -45504,370 +45552,6 @@ var init_logger2 = __esm({
45504
45552
  }
45505
45553
  });
45506
45554
 
45507
- // ../core/dist/encryption.js
45508
- async function importKey2(raw, usages = ["encrypt", "decrypt"]) {
45509
- if (raw.byteLength !== KEY_LENGTH2) {
45510
- throw new WorkflowRuntimeError2(`Encryption key must be exactly ${KEY_LENGTH2} bytes, got ${raw.byteLength}`);
45511
- }
45512
- return globalThis.crypto.subtle.importKey(
45513
- "raw",
45514
- raw,
45515
- "AES-GCM",
45516
- false,
45517
- // `KeyUsage` is a DOM-lib type that's not in scope under `es2022`.
45518
- // The `ReadonlyArray<'encrypt' | 'decrypt'>` parameter type matches
45519
- // a strict subset of `KeyUsage[]`, so this cast is sound.
45520
- usages
45521
- );
45522
- }
45523
- async function encrypt3(key, data) {
45524
- const nonce = globalThis.crypto.getRandomValues(new Uint8Array(NONCE_LENGTH2));
45525
- let ciphertext;
45526
- try {
45527
- ciphertext = await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, tagLength: TAG_LENGTH2 }, key, data);
45528
- } catch (cause) {
45529
- throw new RuntimeDecryptionError2(`AES-256-GCM encryption failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
45530
- cause,
45531
- context: {
45532
- operation: "encrypt",
45533
- byteLength: data.byteLength
45534
- }
45535
- });
45536
- }
45537
- const result = new Uint8Array(NONCE_LENGTH2 + ciphertext.byteLength);
45538
- result.set(nonce, 0);
45539
- result.set(new Uint8Array(ciphertext), NONCE_LENGTH2);
45540
- return result;
45541
- }
45542
- async function decrypt3(key, data) {
45543
- const minLength = NONCE_LENGTH2 + TAG_LENGTH2 / 8;
45544
- if (data.byteLength < minLength) {
45545
- throw new RuntimeDecryptionError2(`Encrypted data too short: expected at least ${minLength} bytes, got ${data.byteLength}`, {
45546
- context: {
45547
- operation: "decrypt",
45548
- byteLength: data.byteLength
45549
- }
45550
- });
45551
- }
45552
- const nonce = data.subarray(0, NONCE_LENGTH2);
45553
- const ciphertext = data.subarray(NONCE_LENGTH2);
45554
- let plaintext;
45555
- try {
45556
- plaintext = await globalThis.crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, tagLength: TAG_LENGTH2 }, key, ciphertext);
45557
- } catch (cause) {
45558
- const causeMsg = cause instanceof Error ? cause.message : String(cause);
45559
- throw new RuntimeDecryptionError2(`AES-256-GCM decryption failed: ${causeMsg}`, {
45560
- cause,
45561
- context: {
45562
- operation: "decrypt",
45563
- byteLength: data.byteLength
45564
- }
45565
- });
45566
- }
45567
- return new Uint8Array(plaintext);
45568
- }
45569
- var NONCE_LENGTH2, TAG_LENGTH2, KEY_LENGTH2;
45570
- var init_encryption3 = __esm({
45571
- "../core/dist/encryption.js"() {
45572
- "use strict";
45573
- init_dist7();
45574
- NONCE_LENGTH2 = 12;
45575
- TAG_LENGTH2 = 128;
45576
- KEY_LENGTH2 = 32;
45577
- __name(importKey2, "importKey");
45578
- __name(encrypt3, "encrypt");
45579
- __name(decrypt3, "decrypt");
45580
- }
45581
- });
45582
-
45583
- // ../core/dist/version.js
45584
- var version4;
45585
- var init_version3 = __esm({
45586
- "../core/dist/version.js"() {
45587
- "use strict";
45588
- version4 = "5.0.0-beta.34";
45589
- }
45590
- });
45591
-
45592
- // ../core/dist/runtime/get-world-lazy.js
45593
- async function getWorldLazy2() {
45594
- const g = globalThis;
45595
- if (g[WorldCacheKey2]) {
45596
- assertWorldSupportsRuntimeProtocol2(g[WorldCacheKey2]);
45597
- return g[WorldCacheKey2];
45598
- }
45599
- if (g[WorldCachePromiseKey2]) {
45600
- g[WorldCacheKey2] = await g[WorldCachePromiseKey2];
45601
- assertWorldSupportsRuntimeProtocol2(g[WorldCacheKey2]);
45602
- return g[WorldCacheKey2];
45603
- }
45604
- const getWorldFn = g[GetWorldFnKey3];
45605
- if (getWorldFn) {
45606
- const world = await getWorldFn();
45607
- assertWorldSupportsRuntimeProtocol2(world);
45608
- return world;
45609
- }
45610
- throw new Error("Workflow world runtime was not initialized. Import from the host workflow entrypoints (`workflow`, `workflow/api`, or `workflow/runtime`) so @workflow/core/runtime/world-init can register getWorld before getWorldLazy() is used.");
45611
- }
45612
- var WorldCacheKey2, WorldCachePromiseKey2, GetWorldFnKey3;
45613
- var init_get_world_lazy2 = __esm({
45614
- "../core/dist/runtime/get-world-lazy.js"() {
45615
- "use strict";
45616
- init_world_compatibility2();
45617
- WorldCacheKey2 = /* @__PURE__ */ Symbol.for("@workflow/world//cache");
45618
- WorldCachePromiseKey2 = /* @__PURE__ */ Symbol.for("@workflow/world//cachePromise");
45619
- GetWorldFnKey3 = /* @__PURE__ */ Symbol.for("@workflow/world//getWorldFn");
45620
- __name(getWorldLazy2, "getWorldLazy");
45621
- }
45622
- });
45623
-
45624
- // ../core/dist/runtime/helpers.js
45625
- function getWorkflowQueueName2(workflowName, namespace) {
45626
- if (!SAFE_WORKFLOW_NAME_PATTERN2.test(workflowName)) {
45627
- throw new Error(`Invalid workflow name "${workflowName}": must only contain alphanumeric characters, underscores, hyphens, dots, forward slashes, or at signs`);
45628
- }
45629
- const prefix = getQueueTopicPrefix2("workflow", resolveQueueNamespace2(namespace));
45630
- return `${prefix}${workflowName}`;
45631
- }
45632
- function getHealthCheckStreamName2(correlationId) {
45633
- return `__health_check__${correlationId}`;
45634
- }
45635
- function parseHealthCheckPayload(message) {
45636
- const result = HealthCheckPayloadSchema2.safeParse(message);
45637
- if (result.success) {
45638
- return result.data;
45639
- }
45640
- return void 0;
45641
- }
45642
- function generateHealthCheckRunId2(correlationId) {
45643
- return `wrun_hc_${correlationId}`;
45644
- }
45645
- async function handleHealthCheckMessage(healthCheck3, endpoint, worldSpecVersion) {
45646
- const world = await getWorldLazy2();
45647
- const streamName = getHealthCheckStreamName2(healthCheck3.correlationId);
45648
- const response = JSON.stringify({
45649
- healthy: true,
45650
- endpoint,
45651
- correlationId: healthCheck3.correlationId,
45652
- specVersion: worldSpecVersion ?? SPEC_VERSION_CURRENT2,
45653
- workflowCoreVersion: version4,
45654
- timestamp: Date.now()
45655
- });
45656
- const fakeRunId = generateHealthCheckRunId2(healthCheck3.correlationId);
45657
- await world.streams.write(fakeRunId, streamName, response);
45658
- await world.streams.close(fakeRunId, streamName);
45659
- }
45660
- function eventPaginationContractError(runId, message) {
45661
- return new WorkflowWorldError2(`Event pagination ${message} for workflow run "${runId}".`, { code: RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR });
45662
- }
45663
- function recordRequestedEventCursor(runId, cursor, requestedCursors) {
45664
- if (!cursor) {
45665
- return;
45666
- }
45667
- if (requestedCursors.has(cursor)) {
45668
- throw eventPaginationContractError(runId, "did not advance");
45669
- }
45670
- requestedCursors.add(cursor);
45671
- }
45672
- function appendUniqueEvents(target, targetIds, events) {
45673
- for (const event of events) {
45674
- if (!targetIds.has(event.eventId)) {
45675
- targetIds.add(event.eventId);
45676
- target.push(event);
45677
- }
45678
- }
45679
- }
45680
- function assertEventPaginationProgress(runId, hasMore, cursor, requestedCursors) {
45681
- if (!hasMore) {
45682
- return;
45683
- }
45684
- if (cursor === null) {
45685
- throw eventPaginationContractError(runId, "returned more pages without a cursor");
45686
- }
45687
- if (requestedCursors.has(cursor)) {
45688
- throw eventPaginationContractError(runId, "repeated a cursor");
45689
- }
45690
- }
45691
- function shouldRetryWithoutEventCursor(error95, cursor, alreadyRetried) {
45692
- return cursor !== null && !alreadyRetried && WorkflowWorldError2.is(error95) && error95.status === 400;
45693
- }
45694
- async function loadWorkflowRunEvents(runId, afterCursor) {
45695
- const incremental = afterCursor !== void 0;
45696
- return trace4(incremental ? "workflow.loadNewEvents" : "workflow.loadEvents", async (span) => {
45697
- span?.setAttributes({
45698
- ...WorkflowRunId3(runId)
45699
- });
45700
- const loadedEvents = [];
45701
- const loadedEventIds = /* @__PURE__ */ new Set();
45702
- const requestedCursors = /* @__PURE__ */ new Set();
45703
- let cursor = afterCursor ?? null;
45704
- let hasMore = true;
45705
- let pagesLoaded = 0;
45706
- let retriedWithoutCursor = false;
45707
- const world = await getWorldLazy2();
45708
- const loadStart = Date.now();
45709
- while (hasMore) {
45710
- const pageStart = Date.now();
45711
- const requestedCursor = cursor;
45712
- recordRequestedEventCursor(runId, requestedCursor, requestedCursors);
45713
- let response;
45714
- try {
45715
- response = await world.events.list({
45716
- runId,
45717
- pagination: {
45718
- sortOrder: "asc",
45719
- cursor: requestedCursor ?? void 0
45720
- }
45721
- });
45722
- } catch (error95) {
45723
- if (shouldRetryWithoutEventCursor(error95, requestedCursor, retriedWithoutCursor)) {
45724
- runtimeLogger2.warn("Event cursor was rejected; retrying with a full event reload.", { workflowRunId: runId });
45725
- loadedEvents.length = 0;
45726
- loadedEventIds.clear();
45727
- requestedCursors.clear();
45728
- cursor = null;
45729
- retriedWithoutCursor = true;
45730
- continue;
45731
- }
45732
- throw error95;
45733
- }
45734
- appendUniqueEvents(loadedEvents, loadedEventIds, response.data);
45735
- hasMore = response.hasMore;
45736
- assertEventPaginationProgress(runId, hasMore, response.cursor, requestedCursors);
45737
- cursor = response.cursor ?? cursor;
45738
- pagesLoaded++;
45739
- runtimeLogger2.debug("Loaded event page", {
45740
- workflowRunId: runId,
45741
- incremental,
45742
- page: pagesLoaded,
45743
- pageEvents: response.data.length,
45744
- totalEvents: loadedEvents.length,
45745
- hasMore,
45746
- pageMs: Date.now() - pageStart
45747
- });
45748
- }
45749
- runtimeLogger2.debug("Event load complete", {
45750
- workflowRunId: runId,
45751
- incremental,
45752
- totalEvents: loadedEvents.length,
45753
- pagesLoaded,
45754
- totalMs: Date.now() - loadStart
45755
- });
45756
- span?.setAttributes({
45757
- ...WorkflowEventsCount2(loadedEvents.length),
45758
- ...WorkflowEventsPagesLoaded2(pagesLoaded)
45759
- });
45760
- return { events: loadedEvents, cursor };
45761
- });
45762
- }
45763
- function withHealthCheck(handler, worldSpecVersion) {
45764
- return async (req) => {
45765
- const url3 = new URL(req.url);
45766
- const isHealthCheck = url3.searchParams.has("__health");
45767
- if (isHealthCheck) {
45768
- if (req.method === "OPTIONS") {
45769
- return new Response(null, {
45770
- status: 204,
45771
- headers: HEALTH_CHECK_CORS_HEADERS
45772
- });
45773
- }
45774
- return new Response(JSON.stringify({
45775
- healthy: true,
45776
- endpoint: url3.pathname,
45777
- specVersion: worldSpecVersion ?? SPEC_VERSION_CURRENT2,
45778
- workflowCoreVersion: version4
45779
- }), {
45780
- status: 200,
45781
- headers: {
45782
- "Content-Type": "application/json",
45783
- ...HEALTH_CHECK_CORS_HEADERS
45784
- }
45785
- });
45786
- }
45787
- return await handler(req);
45788
- };
45789
- }
45790
- async function queueMessage(world, ...args) {
45791
- const queueName = args[0];
45792
- await trace4("queue.publish", {
45793
- // Standard OTEL messaging conventions
45794
- attributes: {
45795
- ...MessagingSystem2("vercel-queue"),
45796
- ...MessagingDestinationName2(queueName),
45797
- ...MessagingOperationType2("publish"),
45798
- // Peer service for Datadog service maps
45799
- ...PeerService3("vercel-queue"),
45800
- ...RpcSystem3("vercel-queue"),
45801
- ...RpcService3("vqs"),
45802
- ...RpcMethod3("publish")
45803
- },
45804
- kind: await getSpanKind3("PRODUCER")
45805
- }, async (span) => {
45806
- const { messageId } = await world.queue(...args);
45807
- if (messageId) {
45808
- span?.setAttributes(MessagingMessageId2(messageId));
45809
- }
45810
- });
45811
- }
45812
- function getQueueOverhead(message) {
45813
- if (!message.requestedAt)
45814
- return;
45815
- try {
45816
- return QueueOverheadMs2(Date.now() - message.requestedAt.getTime());
45817
- } catch {
45818
- return;
45819
- }
45820
- }
45821
- function memoizeEncryptionKey(world, runOrId) {
45822
- let cached3;
45823
- return () => {
45824
- if (!cached3) {
45825
- cached3 = (async () => {
45826
- const rawKey = typeof runOrId === "string" ? await world.getEncryptionKeyForRun?.(runOrId) : await world.getEncryptionKeyForRun?.(runOrId);
45827
- return rawKey ? await importKey2(rawKey) : void 0;
45828
- })();
45829
- }
45830
- return cached3;
45831
- };
45832
- }
45833
- var SAFE_WORKFLOW_NAME_PATTERN2, generateId2, HEALTH_CHECK_CORS_HEADERS;
45834
- var init_helpers2 = __esm({
45835
- "../core/dist/runtime/helpers.js"() {
45836
- "use strict";
45837
- init_dist7();
45838
- init_dist5();
45839
- init_node2();
45840
- init_encryption3();
45841
- init_logger2();
45842
- init_semantic_conventions2();
45843
- init_telemetry2();
45844
- init_version3();
45845
- init_get_world_lazy2();
45846
- SAFE_WORKFLOW_NAME_PATTERN2 = /^[a-zA-Z0-9_\-./@]+$/;
45847
- __name(getWorkflowQueueName2, "getWorkflowQueueName");
45848
- generateId2 = monotonicFactory2();
45849
- __name(getHealthCheckStreamName2, "getHealthCheckStreamName");
45850
- __name(parseHealthCheckPayload, "parseHealthCheckPayload");
45851
- __name(generateHealthCheckRunId2, "generateHealthCheckRunId");
45852
- __name(handleHealthCheckMessage, "handleHealthCheckMessage");
45853
- __name(eventPaginationContractError, "eventPaginationContractError");
45854
- __name(recordRequestedEventCursor, "recordRequestedEventCursor");
45855
- __name(appendUniqueEvents, "appendUniqueEvents");
45856
- __name(assertEventPaginationProgress, "assertEventPaginationProgress");
45857
- __name(shouldRetryWithoutEventCursor, "shouldRetryWithoutEventCursor");
45858
- __name(loadWorkflowRunEvents, "loadWorkflowRunEvents");
45859
- HEALTH_CHECK_CORS_HEADERS = {
45860
- "Access-Control-Allow-Origin": "*",
45861
- "Access-Control-Allow-Methods": "POST, OPTIONS, GET, HEAD",
45862
- "Access-Control-Allow-Headers": "Content-Type"
45863
- };
45864
- __name(withHealthCheck, "withHealthCheck");
45865
- __name(queueMessage, "queueMessage");
45866
- __name(getQueueOverhead, "getQueueOverhead");
45867
- __name(memoizeEncryptionKey, "memoizeEncryptionKey");
45868
- }
45869
- });
45870
-
45871
45555
  // ../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/constants.js
45872
45556
  var UNDEFINED2, HOLE2, NAN2, POSITIVE_INFINITY2, NEGATIVE_INFINITY2, NEGATIVE_ZERO2, SPARSE2, MAX_ARRAY_LEN2, MAX_ARRAY_INDEX2;
45873
45557
  var init_constants2 = __esm({
@@ -46506,6 +46190,109 @@ var init_devalue2 = __esm({
46506
46190
  }
46507
46191
  });
46508
46192
 
46193
+ // ../core/dist/encryption.js
46194
+ async function importKey2(raw, usages = ["encrypt", "decrypt"]) {
46195
+ if (raw.byteLength !== KEY_LENGTH2) {
46196
+ throw new WorkflowRuntimeError2(`Encryption key must be exactly ${KEY_LENGTH2} bytes, got ${raw.byteLength}`);
46197
+ }
46198
+ return globalThis.crypto.subtle.importKey(
46199
+ "raw",
46200
+ raw,
46201
+ "AES-GCM",
46202
+ false,
46203
+ // `KeyUsage` is a DOM-lib type that's not in scope under `es2022`.
46204
+ // The `ReadonlyArray<'encrypt' | 'decrypt'>` parameter type matches
46205
+ // a strict subset of `KeyUsage[]`, so this cast is sound.
46206
+ usages
46207
+ );
46208
+ }
46209
+ async function encrypt3(key, data) {
46210
+ const nonce = globalThis.crypto.getRandomValues(new Uint8Array(NONCE_LENGTH2));
46211
+ let ciphertext;
46212
+ try {
46213
+ ciphertext = await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, tagLength: TAG_LENGTH2 }, key, data);
46214
+ } catch (cause) {
46215
+ throw new RuntimeDecryptionError2(`AES-256-GCM encryption failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
46216
+ cause,
46217
+ context: {
46218
+ operation: "encrypt",
46219
+ byteLength: data.byteLength
46220
+ }
46221
+ });
46222
+ }
46223
+ const result = new Uint8Array(NONCE_LENGTH2 + ciphertext.byteLength);
46224
+ result.set(nonce, 0);
46225
+ result.set(new Uint8Array(ciphertext), NONCE_LENGTH2);
46226
+ return result;
46227
+ }
46228
+ async function decrypt3(key, data) {
46229
+ const minLength = NONCE_LENGTH2 + TAG_LENGTH2 / 8;
46230
+ if (data.byteLength < minLength) {
46231
+ throw new RuntimeDecryptionError2(`Encrypted data too short: expected at least ${minLength} bytes, got ${data.byteLength}`, {
46232
+ context: {
46233
+ operation: "decrypt",
46234
+ byteLength: data.byteLength
46235
+ }
46236
+ });
46237
+ }
46238
+ const nonce = data.subarray(0, NONCE_LENGTH2);
46239
+ const ciphertext = data.subarray(NONCE_LENGTH2);
46240
+ let plaintext;
46241
+ try {
46242
+ plaintext = await globalThis.crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, tagLength: TAG_LENGTH2 }, key, ciphertext);
46243
+ } catch (cause) {
46244
+ const causeMsg = cause instanceof Error ? cause.message : String(cause);
46245
+ throw new RuntimeDecryptionError2(`AES-256-GCM decryption failed: ${causeMsg}`, {
46246
+ cause,
46247
+ context: {
46248
+ operation: "decrypt",
46249
+ byteLength: data.byteLength
46250
+ }
46251
+ });
46252
+ }
46253
+ return new Uint8Array(plaintext);
46254
+ }
46255
+ var NONCE_LENGTH2, TAG_LENGTH2, KEY_LENGTH2;
46256
+ var init_encryption3 = __esm({
46257
+ "../core/dist/encryption.js"() {
46258
+ "use strict";
46259
+ init_dist7();
46260
+ NONCE_LENGTH2 = 12;
46261
+ TAG_LENGTH2 = 128;
46262
+ KEY_LENGTH2 = 32;
46263
+ __name(importKey2, "importKey");
46264
+ __name(encrypt3, "encrypt");
46265
+ __name(decrypt3, "decrypt");
46266
+ }
46267
+ });
46268
+
46269
+ // ../core/dist/symbols.js
46270
+ var WORKFLOW_USE_STEP, WORKFLOW_SET_ATTRIBUTES, WORKFLOW_CREATE_HOOK, WORKFLOW_SLEEP, WORKFLOW_GET_STREAM_ID, STABLE_ULID2, STREAM_NAME_SYMBOL2, STREAM_TYPE_SYMBOL2, STREAM_FRAMING_SYMBOL2, STREAM_SERVER_RUN_ID_SYMBOL2, STREAM_SERVER_DEPLOYMENT_ID_SYMBOL2, STREAM_WRITE_BATCH_SYMBOL2, BODY_INIT_SYMBOL2, WEBHOOK_RESPONSE_WRITABLE2, WORKFLOW_CLASS_REGISTRY2, ABORT_STREAM_NAME2, ABORT_HOOK_TOKEN2, ABORT_LISTENER_ATTACHED2, ABORT_READER_CANCEL2;
46271
+ var init_symbols2 = __esm({
46272
+ "../core/dist/symbols.js"() {
46273
+ "use strict";
46274
+ WORKFLOW_USE_STEP = /* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP");
46275
+ WORKFLOW_SET_ATTRIBUTES = /* @__PURE__ */ Symbol.for("WORKFLOW_SET_ATTRIBUTES");
46276
+ WORKFLOW_CREATE_HOOK = /* @__PURE__ */ Symbol.for("WORKFLOW_CREATE_HOOK");
46277
+ WORKFLOW_SLEEP = /* @__PURE__ */ Symbol.for("WORKFLOW_SLEEP");
46278
+ WORKFLOW_GET_STREAM_ID = /* @__PURE__ */ Symbol.for("WORKFLOW_GET_STREAM_ID");
46279
+ STABLE_ULID2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STABLE_ULID");
46280
+ STREAM_NAME_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_NAME");
46281
+ STREAM_TYPE_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_TYPE");
46282
+ STREAM_FRAMING_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_FRAMING");
46283
+ STREAM_SERVER_RUN_ID_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_RUN_ID");
46284
+ STREAM_SERVER_DEPLOYMENT_ID_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_DEPLOYMENT_ID");
46285
+ STREAM_WRITE_BATCH_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_WRITE_BATCH");
46286
+ BODY_INIT_SYMBOL2 = /* @__PURE__ */ Symbol.for("BODY_INIT");
46287
+ WEBHOOK_RESPONSE_WRITABLE2 = /* @__PURE__ */ Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
46288
+ WORKFLOW_CLASS_REGISTRY2 = /* @__PURE__ */ Symbol.for("workflow-class-registry");
46289
+ ABORT_STREAM_NAME2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_STREAM_NAME");
46290
+ ABORT_HOOK_TOKEN2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_HOOK_TOKEN");
46291
+ ABORT_LISTENER_ATTACHED2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_LISTENER_ATTACHED");
46292
+ ABORT_READER_CANCEL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_READER_CANCEL");
46293
+ }
46294
+ });
46295
+
46509
46296
  // ../core/dist/flushable-stream.js
46510
46297
  function createFlushableState2() {
46511
46298
  const state = {
@@ -46588,7 +46375,11 @@ function pollReadableLock2(readable, state) {
46588
46375
  }, getLockPollIntervalMs2());
46589
46376
  state.readablePollingInterval = intervalId;
46590
46377
  }
46591
- async function flushablePipe2(source, sink, state) {
46378
+ function flushablePipe2(source, sink, state) {
46379
+ const batchWrite = sink[STREAM_WRITE_BATCH_SYMBOL2];
46380
+ return typeof batchWrite === "function" ? flushablePipeCoalescing2(source, sink, state, batchWrite) : flushablePipePerChunk2(source, sink, state);
46381
+ }
46382
+ async function flushablePipePerChunk2(source, sink, state) {
46592
46383
  const reader = source.getReader();
46593
46384
  const writer = sink.getWriter();
46594
46385
  let cancelReason;
@@ -46637,13 +46428,147 @@ async function flushablePipe2(source, sink, state) {
46637
46428
  writer.releaseLock();
46638
46429
  }
46639
46430
  }
46640
- var LOCK_POLL_INTERVAL_MS2, getLockPollIntervalMs2;
46431
+ function wake2(ctx, which) {
46432
+ const resolve2 = ctx[which];
46433
+ if (resolve2) {
46434
+ ctx[which] = null;
46435
+ resolve2();
46436
+ }
46437
+ }
46438
+ function nextBatchSize2(ctx) {
46439
+ let count2 = 0;
46440
+ let bytes = 0;
46441
+ for (const chunk of ctx.queue) {
46442
+ if (count2 >= ctx.maxChunksPerBatch)
46443
+ break;
46444
+ if (count2 > 0 && bytes + chunk.byteLength > ctx.maxBytesPerBatch)
46445
+ break;
46446
+ count2++;
46447
+ bytes += chunk.byteLength;
46448
+ }
46449
+ return count2;
46450
+ }
46451
+ async function drainBatches2(ctx) {
46452
+ while (true) {
46453
+ if (ctx.queue.length === 0) {
46454
+ if (ctx.sourceDone)
46455
+ return;
46456
+ await new Promise((resolve2) => {
46457
+ ctx.wakeConsumer = resolve2;
46458
+ });
46459
+ continue;
46460
+ }
46461
+ const count2 = nextBatchSize2(ctx);
46462
+ const batch = ctx.queue.slice(0, count2);
46463
+ ctx.queue = ctx.queue.slice(count2);
46464
+ await ctx.batchWrite(batch);
46465
+ ctx.state.pendingOps -= batch.length;
46466
+ wake2(ctx, "wakeProducer");
46467
+ }
46468
+ }
46469
+ function readNextChunk2(reader, writer, consumer) {
46470
+ return Promise.race([
46471
+ reader.read(),
46472
+ writer.closed.then(() => {
46473
+ throw new WorkflowRuntimeError2("Writable stream closed prematurely");
46474
+ }),
46475
+ consumer.then(() => {
46476
+ throw new WorkflowRuntimeError2("Stream consumer ended prematurely");
46477
+ }, (err) => {
46478
+ throw err;
46479
+ })
46480
+ ]);
46481
+ }
46482
+ async function awaitBackpressureRelief2(ctx, consumer, maxInflight) {
46483
+ if (ctx.state.pendingOps < maxInflight)
46484
+ return;
46485
+ await Promise.race([
46486
+ new Promise((resolve2) => {
46487
+ ctx.wakeProducer = resolve2;
46488
+ }),
46489
+ consumer.then(() => void 0, () => void 0)
46490
+ ]);
46491
+ }
46492
+ async function flushablePipeCoalescing2(source, sink, state, batchWrite) {
46493
+ const reader = source.getReader();
46494
+ const writer = sink.getWriter();
46495
+ const maxInflight = getMaxInflightChunks2();
46496
+ let cancelReason;
46497
+ const ctx = {
46498
+ state,
46499
+ batchWrite,
46500
+ queue: [],
46501
+ sourceDone: false,
46502
+ wakeConsumer: null,
46503
+ wakeProducer: null,
46504
+ maxChunksPerBatch: getMaxChunksPerBatch2(),
46505
+ maxBytesPerBatch: getMaxBytesPerBatch2()
46506
+ };
46507
+ const consumer = drainBatches2(ctx);
46508
+ try {
46509
+ while (!state.streamEnded) {
46510
+ const readResult = await readNextChunk2(reader, writer, consumer);
46511
+ if (state.streamEnded)
46512
+ return;
46513
+ if (readResult.done) {
46514
+ ctx.sourceDone = true;
46515
+ wake2(ctx, "wakeConsumer");
46516
+ await consumer;
46517
+ state.streamEnded = true;
46518
+ await writer.close();
46519
+ if (!state.doneResolved) {
46520
+ state.doneResolved = true;
46521
+ state.resolve();
46522
+ }
46523
+ return;
46524
+ }
46525
+ ctx.queue.push(readResult.value);
46526
+ state.pendingOps++;
46527
+ wake2(ctx, "wakeConsumer");
46528
+ await awaitBackpressureRelief2(ctx, consumer, maxInflight);
46529
+ }
46530
+ } catch (err) {
46531
+ state.streamEnded = true;
46532
+ cancelReason = err;
46533
+ ctx.sourceDone = true;
46534
+ wake2(ctx, "wakeConsumer");
46535
+ await consumer.catch(() => {
46536
+ });
46537
+ if (!state.doneResolved) {
46538
+ state.doneResolved = true;
46539
+ state.reject(err);
46540
+ }
46541
+ throw err;
46542
+ } finally {
46543
+ reader.cancel(cancelReason).catch(() => {
46544
+ });
46545
+ reader.releaseLock();
46546
+ writer.releaseLock();
46547
+ }
46548
+ }
46549
+ var MAX_INFLIGHT_CHUNKS2, getMaxInflightChunks2, MAX_CHUNKS_PER_BATCH2, getMaxChunksPerBatch2, MAX_BYTES_PER_BATCH2, getMaxBytesPerBatch2, LOCK_POLL_INTERVAL_MS2, getLockPollIntervalMs2;
46641
46550
  var init_flushable_stream2 = __esm({
46642
46551
  "../core/dist/flushable-stream.js"() {
46643
46552
  "use strict";
46644
46553
  init_dist7();
46645
46554
  init_dist6();
46646
46555
  init_dist5();
46556
+ init_symbols2();
46557
+ MAX_INFLIGHT_CHUNKS2 = 1e3;
46558
+ getMaxInflightChunks2 = /* @__PURE__ */ __name(() => envNumber2("WORKFLOW_STREAM_MAX_INFLIGHT_CHUNKS", MAX_INFLIGHT_CHUNKS2, {
46559
+ integer: true,
46560
+ min: 1
46561
+ }), "getMaxInflightChunks");
46562
+ MAX_CHUNKS_PER_BATCH2 = 1e3;
46563
+ getMaxChunksPerBatch2 = /* @__PURE__ */ __name(() => envNumber2("WORKFLOW_STREAM_MAX_CHUNKS_PER_BATCH", MAX_CHUNKS_PER_BATCH2, {
46564
+ integer: true,
46565
+ min: 1
46566
+ }), "getMaxChunksPerBatch");
46567
+ MAX_BYTES_PER_BATCH2 = 1024 * 1024;
46568
+ getMaxBytesPerBatch2 = /* @__PURE__ */ __name(() => envNumber2("WORKFLOW_STREAM_MAX_BYTES_PER_BATCH", MAX_BYTES_PER_BATCH2, {
46569
+ integer: true,
46570
+ min: 1
46571
+ }), "getMaxBytesPerBatch");
46647
46572
  LOCK_POLL_INTERVAL_MS2 = 10;
46648
46573
  getLockPollIntervalMs2 = /* @__PURE__ */ __name(() => envNumber2("WORKFLOW_LOCK_POLL_INTERVAL_MS", LOCK_POLL_INTERVAL_MS2, {
46649
46574
  integer: true,
@@ -46655,6 +46580,13 @@ var init_flushable_stream2 = __esm({
46655
46580
  __name(pollWritableLock2, "pollWritableLock");
46656
46581
  __name(pollReadableLock2, "pollReadableLock");
46657
46582
  __name(flushablePipe2, "flushablePipe");
46583
+ __name(flushablePipePerChunk2, "flushablePipePerChunk");
46584
+ __name(wake2, "wake");
46585
+ __name(nextBatchSize2, "nextBatchSize");
46586
+ __name(drainBatches2, "drainBatches");
46587
+ __name(readNextChunk2, "readNextChunk");
46588
+ __name(awaitBackpressureRelief2, "awaitBackpressureRelief");
46589
+ __name(flushablePipeCoalescing2, "flushablePipeCoalescing");
46658
46590
  }
46659
46591
  });
46660
46592
 
@@ -46786,6 +46718,38 @@ var init_private2 = __esm({
46786
46718
  }
46787
46719
  });
46788
46720
 
46721
+ // ../core/dist/runtime/get-world-lazy.js
46722
+ async function getWorldLazy2() {
46723
+ const g = globalThis;
46724
+ if (g[WorldCacheKey2]) {
46725
+ assertWorldSupportsRuntimeProtocol2(g[WorldCacheKey2]);
46726
+ return g[WorldCacheKey2];
46727
+ }
46728
+ if (g[WorldCachePromiseKey2]) {
46729
+ g[WorldCacheKey2] = await g[WorldCachePromiseKey2];
46730
+ assertWorldSupportsRuntimeProtocol2(g[WorldCacheKey2]);
46731
+ return g[WorldCacheKey2];
46732
+ }
46733
+ const getWorldFn = g[GetWorldFnKey3];
46734
+ if (getWorldFn) {
46735
+ const world = await getWorldFn();
46736
+ assertWorldSupportsRuntimeProtocol2(world);
46737
+ return world;
46738
+ }
46739
+ throw new Error("Workflow world runtime was not initialized. Import from the host workflow entrypoints (`workflow`, `workflow/api`, or `workflow/runtime`) so @workflow/core/runtime/world-init can register getWorld before getWorldLazy() is used.");
46740
+ }
46741
+ var WorldCacheKey2, WorldCachePromiseKey2, GetWorldFnKey3;
46742
+ var init_get_world_lazy2 = __esm({
46743
+ "../core/dist/runtime/get-world-lazy.js"() {
46744
+ "use strict";
46745
+ init_world_compatibility2();
46746
+ WorldCacheKey2 = /* @__PURE__ */ Symbol.for("@workflow/world//cache");
46747
+ WorldCachePromiseKey2 = /* @__PURE__ */ Symbol.for("@workflow/world//cachePromise");
46748
+ GetWorldFnKey3 = /* @__PURE__ */ Symbol.for("@workflow/world//getWorldFn");
46749
+ __name(getWorldLazy2, "getWorldLazy");
46750
+ }
46751
+ });
46752
+
46789
46753
  // ../serde/dist/index.js
46790
46754
  var WORKFLOW_SERIALIZE2, WORKFLOW_DESERIALIZE2;
46791
46755
  var init_dist8 = __esm({
@@ -46796,32 +46760,6 @@ var init_dist8 = __esm({
46796
46760
  }
46797
46761
  });
46798
46762
 
46799
- // ../core/dist/symbols.js
46800
- var WORKFLOW_USE_STEP, WORKFLOW_SET_ATTRIBUTES, WORKFLOW_CREATE_HOOK, WORKFLOW_SLEEP, WORKFLOW_GET_STREAM_ID, STABLE_ULID2, STREAM_NAME_SYMBOL2, STREAM_TYPE_SYMBOL2, STREAM_FRAMING_SYMBOL2, STREAM_SERVER_RUN_ID_SYMBOL2, STREAM_SERVER_DEPLOYMENT_ID_SYMBOL2, BODY_INIT_SYMBOL2, WEBHOOK_RESPONSE_WRITABLE2, WORKFLOW_CLASS_REGISTRY2, ABORT_STREAM_NAME2, ABORT_HOOK_TOKEN2, ABORT_LISTENER_ATTACHED2, ABORT_READER_CANCEL2;
46801
- var init_symbols2 = __esm({
46802
- "../core/dist/symbols.js"() {
46803
- "use strict";
46804
- WORKFLOW_USE_STEP = /* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP");
46805
- WORKFLOW_SET_ATTRIBUTES = /* @__PURE__ */ Symbol.for("WORKFLOW_SET_ATTRIBUTES");
46806
- WORKFLOW_CREATE_HOOK = /* @__PURE__ */ Symbol.for("WORKFLOW_CREATE_HOOK");
46807
- WORKFLOW_SLEEP = /* @__PURE__ */ Symbol.for("WORKFLOW_SLEEP");
46808
- WORKFLOW_GET_STREAM_ID = /* @__PURE__ */ Symbol.for("WORKFLOW_GET_STREAM_ID");
46809
- STABLE_ULID2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STABLE_ULID");
46810
- STREAM_NAME_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_NAME");
46811
- STREAM_TYPE_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_TYPE");
46812
- STREAM_FRAMING_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_FRAMING");
46813
- STREAM_SERVER_RUN_ID_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_RUN_ID");
46814
- STREAM_SERVER_DEPLOYMENT_ID_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_DEPLOYMENT_ID");
46815
- BODY_INIT_SYMBOL2 = /* @__PURE__ */ Symbol.for("BODY_INIT");
46816
- WEBHOOK_RESPONSE_WRITABLE2 = /* @__PURE__ */ Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
46817
- WORKFLOW_CLASS_REGISTRY2 = /* @__PURE__ */ Symbol.for("workflow-class-registry");
46818
- ABORT_STREAM_NAME2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_STREAM_NAME");
46819
- ABORT_HOOK_TOKEN2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_HOOK_TOKEN");
46820
- ABORT_LISTENER_ATTACHED2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_LISTENER_ATTACHED");
46821
- ABORT_READER_CANCEL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_READER_CANCEL");
46822
- }
46823
- });
46824
-
46825
46763
  // ../core/dist/class-serialization.js
46826
46764
  function getRegistry2(global2 = globalThis) {
46827
46765
  const g = global2;
@@ -48077,7 +48015,8 @@ function createCreateAbortController(ctx) {
48077
48015
  try {
48078
48016
  if (rawPayload !== void 0) {
48079
48017
  try {
48080
- const hydrated = await hydrateStepReturnValue(rawPayload, ctx.runId, ctx.encryptionKey, ctx.globalThis);
48018
+ const prepared = await ctx.replayPayloadCache.prepareEventPayload(event.eventId, "payload", rawPayload);
48019
+ const hydrated = await hydrateStepReturnValue(rawPayload, ctx.runId, ctx.encryptionKey, ctx.globalThis, {}, prepared);
48081
48020
  if (hydrated && typeof hydrated === "object" && "reason" in hydrated) {
48082
48021
  reason = hydrated.reason;
48083
48022
  }
@@ -50227,6 +50166,307 @@ var init_capabilities2 = __esm({
50227
50166
  }
50228
50167
  });
50229
50168
 
50169
+ // ../core/dist/version.js
50170
+ var version4;
50171
+ var init_version3 = __esm({
50172
+ "../core/dist/version.js"() {
50173
+ "use strict";
50174
+ version4 = "5.0.0-beta.36";
50175
+ }
50176
+ });
50177
+
50178
+ // ../core/dist/runtime/helpers.js
50179
+ function getWorkflowQueueName2(workflowName, namespace) {
50180
+ if (!SAFE_WORKFLOW_NAME_PATTERN2.test(workflowName)) {
50181
+ throw new Error(`Invalid workflow name "${workflowName}": must only contain alphanumeric characters, underscores, hyphens, dots, forward slashes, or at signs`);
50182
+ }
50183
+ const prefix = getQueueTopicPrefix2("workflow", resolveQueueNamespace2(namespace));
50184
+ return `${prefix}${workflowName}`;
50185
+ }
50186
+ function getHealthCheckStreamName2(correlationId) {
50187
+ return `__health_check__${correlationId}`;
50188
+ }
50189
+ function parseHealthCheckPayload(message) {
50190
+ const result = HealthCheckPayloadSchema2.safeParse(message);
50191
+ if (result.success) {
50192
+ return result.data;
50193
+ }
50194
+ return void 0;
50195
+ }
50196
+ function generateHealthCheckRunId2(correlationId) {
50197
+ return `wrun_hc_${correlationId}`;
50198
+ }
50199
+ async function handleHealthCheckMessage(healthCheck3, endpoint, worldSpecVersion) {
50200
+ const world = await getWorldLazy2();
50201
+ const streamName = getHealthCheckStreamName2(healthCheck3.correlationId);
50202
+ const response = JSON.stringify({
50203
+ healthy: true,
50204
+ endpoint,
50205
+ correlationId: healthCheck3.correlationId,
50206
+ specVersion: worldSpecVersion ?? SPEC_VERSION_CURRENT2,
50207
+ workflowCoreVersion: version4,
50208
+ timestamp: Date.now()
50209
+ });
50210
+ const fakeRunId = generateHealthCheckRunId2(healthCheck3.correlationId);
50211
+ await world.streams.write(fakeRunId, streamName, response);
50212
+ await world.streams.close(fakeRunId, streamName);
50213
+ }
50214
+ function eventPaginationContractError(runId, message) {
50215
+ return new WorkflowWorldError2(`Event pagination ${message} for workflow run "${runId}".`, { code: RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR });
50216
+ }
50217
+ function recordRequestedEventCursor(runId, cursor, requestedCursors) {
50218
+ if (!cursor) {
50219
+ return;
50220
+ }
50221
+ if (requestedCursors.has(cursor)) {
50222
+ throw eventPaginationContractError(runId, "did not advance");
50223
+ }
50224
+ requestedCursors.add(cursor);
50225
+ }
50226
+ function appendUniqueEvents(target, targetIds, events) {
50227
+ for (const event of events) {
50228
+ if (!targetIds.has(event.eventId)) {
50229
+ targetIds.add(event.eventId);
50230
+ target.push(event);
50231
+ }
50232
+ }
50233
+ }
50234
+ function assertEventPaginationProgress(runId, hasMore, cursor, requestedCursors) {
50235
+ if (!hasMore) {
50236
+ return;
50237
+ }
50238
+ if (cursor === null) {
50239
+ throw eventPaginationContractError(runId, "returned more pages without a cursor");
50240
+ }
50241
+ if (requestedCursors.has(cursor)) {
50242
+ throw eventPaginationContractError(runId, "repeated a cursor");
50243
+ }
50244
+ }
50245
+ function shouldRetryWithoutEventCursor(error95, cursor, alreadyRetried) {
50246
+ return cursor !== null && !alreadyRetried && WorkflowWorldError2.is(error95) && error95.status === 400;
50247
+ }
50248
+ async function loadWorkflowRunEvents(runId, afterCursor) {
50249
+ const incremental = afterCursor !== void 0;
50250
+ return trace4(incremental ? "workflow.loadNewEvents" : "workflow.loadEvents", async (span) => {
50251
+ span?.setAttributes({
50252
+ ...WorkflowRunId3(runId)
50253
+ });
50254
+ const loadedEvents = [];
50255
+ const loadedEventIds = /* @__PURE__ */ new Set();
50256
+ const requestedCursors = /* @__PURE__ */ new Set();
50257
+ let cursor = afterCursor ?? null;
50258
+ let hasMore = true;
50259
+ let pagesLoaded = 0;
50260
+ let retriedWithoutCursor = false;
50261
+ const world = await getWorldLazy2();
50262
+ const loadStart = Date.now();
50263
+ while (hasMore) {
50264
+ const pageStart = Date.now();
50265
+ const requestedCursor = cursor;
50266
+ recordRequestedEventCursor(runId, requestedCursor, requestedCursors);
50267
+ let response;
50268
+ try {
50269
+ response = await world.events.list({
50270
+ runId,
50271
+ pagination: {
50272
+ sortOrder: "asc",
50273
+ cursor: requestedCursor ?? void 0
50274
+ }
50275
+ });
50276
+ } catch (error95) {
50277
+ if (shouldRetryWithoutEventCursor(error95, requestedCursor, retriedWithoutCursor)) {
50278
+ runtimeLogger2.warn("Event cursor was rejected; retrying with a full event reload.", { workflowRunId: runId });
50279
+ loadedEvents.length = 0;
50280
+ loadedEventIds.clear();
50281
+ requestedCursors.clear();
50282
+ cursor = null;
50283
+ retriedWithoutCursor = true;
50284
+ continue;
50285
+ }
50286
+ throw error95;
50287
+ }
50288
+ appendUniqueEvents(loadedEvents, loadedEventIds, response.data);
50289
+ hasMore = response.hasMore;
50290
+ assertEventPaginationProgress(runId, hasMore, response.cursor, requestedCursors);
50291
+ cursor = response.cursor ?? cursor;
50292
+ pagesLoaded++;
50293
+ runtimeLogger2.debug("Loaded event page", {
50294
+ workflowRunId: runId,
50295
+ incremental,
50296
+ page: pagesLoaded,
50297
+ pageEvents: response.data.length,
50298
+ totalEvents: loadedEvents.length,
50299
+ hasMore,
50300
+ pageMs: Date.now() - pageStart
50301
+ });
50302
+ }
50303
+ runtimeLogger2.debug("Event load complete", {
50304
+ workflowRunId: runId,
50305
+ incremental,
50306
+ totalEvents: loadedEvents.length,
50307
+ pagesLoaded,
50308
+ totalMs: Date.now() - loadStart
50309
+ });
50310
+ span?.setAttributes({
50311
+ ...WorkflowEventsCount2(loadedEvents.length),
50312
+ ...WorkflowEventsPagesLoaded2(pagesLoaded)
50313
+ });
50314
+ return { events: loadedEvents, cursor };
50315
+ });
50316
+ }
50317
+ function isPreconditionGuardEnabled() {
50318
+ return process.env.WORKFLOW_PRECONDITION_GUARD !== "0";
50319
+ }
50320
+ function latestEventStateUpdatedAt(events) {
50321
+ const last = events[events.length - 1];
50322
+ if (!last) {
50323
+ return void 0;
50324
+ }
50325
+ const eventId = last.eventId;
50326
+ const underscore = eventId.lastIndexOf("_");
50327
+ const rawUlid = underscore === -1 ? eventId : eventId.slice(underscore + 1);
50328
+ const time5 = ulidToDate(rawUlid)?.getTime();
50329
+ if (time5 === void 0) {
50330
+ runtimeLogger2.debug("Precondition guard: latest event id is not a decodable ULID; sending no snapshot", { eventId });
50331
+ return void 0;
50332
+ }
50333
+ return time5;
50334
+ }
50335
+ function stateUpdatedAtForCreate(events) {
50336
+ return isPreconditionGuardEnabled() ? latestEventStateUpdatedAt(events) : void 0;
50337
+ }
50338
+ async function withPreconditionRetry(runId, log, op) {
50339
+ for (let attempt = 0; ; attempt++) {
50340
+ try {
50341
+ return await op(stateUpdatedAtForCreate(log.events));
50342
+ } catch (error95) {
50343
+ if (!PreconditionFailedError.is(error95) || attempt >= PRECONDITION_MAX_RELOAD_RETRIES) {
50344
+ throw error95;
50345
+ }
50346
+ runtimeLogger2.info("Event creation rejected as stale; reloading event log and retrying", {
50347
+ workflowRunId: runId,
50348
+ attempt: attempt + 1,
50349
+ maxRetries: PRECONDITION_MAX_RELOAD_RETRIES
50350
+ });
50351
+ const loaded = await loadWorkflowRunEvents(runId, log.cursor ?? void 0);
50352
+ appendUniqueEvents(log.events, new Set(log.events.map((e) => e.eventId)), loaded.events);
50353
+ log.cursor = loaded.cursor ?? log.cursor;
50354
+ }
50355
+ }
50356
+ }
50357
+ function withHealthCheck(handler, worldSpecVersion) {
50358
+ return async (req) => {
50359
+ const url3 = new URL(req.url);
50360
+ const isHealthCheck = url3.searchParams.has("__health");
50361
+ if (isHealthCheck) {
50362
+ if (req.method === "OPTIONS") {
50363
+ return new Response(null, {
50364
+ status: 204,
50365
+ headers: HEALTH_CHECK_CORS_HEADERS
50366
+ });
50367
+ }
50368
+ return new Response(JSON.stringify({
50369
+ healthy: true,
50370
+ endpoint: url3.pathname,
50371
+ specVersion: worldSpecVersion ?? SPEC_VERSION_CURRENT2,
50372
+ workflowCoreVersion: version4
50373
+ }), {
50374
+ status: 200,
50375
+ headers: {
50376
+ "Content-Type": "application/json",
50377
+ ...HEALTH_CHECK_CORS_HEADERS
50378
+ }
50379
+ });
50380
+ }
50381
+ return await handler(req);
50382
+ };
50383
+ }
50384
+ async function queueMessage(world, ...args) {
50385
+ const queueName = args[0];
50386
+ await trace4("queue.publish", {
50387
+ // Standard OTEL messaging conventions
50388
+ attributes: {
50389
+ ...MessagingSystem2("vercel-queue"),
50390
+ ...MessagingDestinationName2(queueName),
50391
+ ...MessagingOperationType2("publish"),
50392
+ // Peer service for Datadog service maps
50393
+ ...PeerService3("vercel-queue"),
50394
+ ...RpcSystem3("vercel-queue"),
50395
+ ...RpcService3("vqs"),
50396
+ ...RpcMethod3("publish")
50397
+ },
50398
+ kind: await getSpanKind3("PRODUCER")
50399
+ }, async (span) => {
50400
+ const { messageId } = await world.queue(...args);
50401
+ if (messageId) {
50402
+ span?.setAttributes(MessagingMessageId2(messageId));
50403
+ }
50404
+ });
50405
+ }
50406
+ function getQueueOverhead(message) {
50407
+ if (!message.requestedAt)
50408
+ return;
50409
+ try {
50410
+ return QueueOverheadMs2(Date.now() - message.requestedAt.getTime());
50411
+ } catch {
50412
+ return;
50413
+ }
50414
+ }
50415
+ function memoizeEncryptionKey(world, runOrId) {
50416
+ let cached3;
50417
+ return () => {
50418
+ if (!cached3) {
50419
+ cached3 = (async () => {
50420
+ const rawKey = typeof runOrId === "string" ? await world.getEncryptionKeyForRun?.(runOrId) : await world.getEncryptionKeyForRun?.(runOrId);
50421
+ return rawKey ? await importKey2(rawKey) : void 0;
50422
+ })();
50423
+ }
50424
+ return cached3;
50425
+ };
50426
+ }
50427
+ var SAFE_WORKFLOW_NAME_PATTERN2, generateId2, PRECONDITION_MAX_RELOAD_RETRIES, HEALTH_CHECK_CORS_HEADERS;
50428
+ var init_helpers2 = __esm({
50429
+ "../core/dist/runtime/helpers.js"() {
50430
+ "use strict";
50431
+ init_dist7();
50432
+ init_dist5();
50433
+ init_node2();
50434
+ init_encryption3();
50435
+ init_logger2();
50436
+ init_semantic_conventions2();
50437
+ init_telemetry2();
50438
+ init_version3();
50439
+ init_get_world_lazy2();
50440
+ SAFE_WORKFLOW_NAME_PATTERN2 = /^[a-zA-Z0-9_\-./@]+$/;
50441
+ __name(getWorkflowQueueName2, "getWorkflowQueueName");
50442
+ generateId2 = monotonicFactory2();
50443
+ __name(getHealthCheckStreamName2, "getHealthCheckStreamName");
50444
+ __name(parseHealthCheckPayload, "parseHealthCheckPayload");
50445
+ __name(generateHealthCheckRunId2, "generateHealthCheckRunId");
50446
+ __name(handleHealthCheckMessage, "handleHealthCheckMessage");
50447
+ __name(eventPaginationContractError, "eventPaginationContractError");
50448
+ __name(recordRequestedEventCursor, "recordRequestedEventCursor");
50449
+ __name(appendUniqueEvents, "appendUniqueEvents");
50450
+ __name(assertEventPaginationProgress, "assertEventPaginationProgress");
50451
+ __name(shouldRetryWithoutEventCursor, "shouldRetryWithoutEventCursor");
50452
+ __name(loadWorkflowRunEvents, "loadWorkflowRunEvents");
50453
+ PRECONDITION_MAX_RELOAD_RETRIES = 2;
50454
+ __name(isPreconditionGuardEnabled, "isPreconditionGuardEnabled");
50455
+ __name(latestEventStateUpdatedAt, "latestEventStateUpdatedAt");
50456
+ __name(stateUpdatedAtForCreate, "stateUpdatedAtForCreate");
50457
+ __name(withPreconditionRetry, "withPreconditionRetry");
50458
+ HEALTH_CHECK_CORS_HEADERS = {
50459
+ "Access-Control-Allow-Origin": "*",
50460
+ "Access-Control-Allow-Methods": "POST, OPTIONS, GET, HEAD",
50461
+ "Access-Control-Allow-Headers": "Content-Type"
50462
+ };
50463
+ __name(withHealthCheck, "withHealthCheck");
50464
+ __name(queueMessage, "queueMessage");
50465
+ __name(getQueueOverhead, "getQueueOverhead");
50466
+ __name(memoizeEncryptionKey, "memoizeEncryptionKey");
50467
+ }
50468
+ });
50469
+
50230
50470
  // ../../node_modules/.pnpm/@vercel+functions@3.4.3_@aws-sdk+credential-provider-web-identity@3.972.49/node_modules/@vercel/functions/headers.js
50231
50471
  var require_headers3 = __commonJS({
50232
50472
  "../../node_modules/.pnpm/@vercel+functions@3.4.3_@aws-sdk+credential-provider-web-identity@3.972.49/node_modules/@vercel/functions/headers.js"(exports, module) {
@@ -51372,16 +51612,20 @@ __export(resume_hook_exports2, {
51372
51612
  resumeHook: () => resumeHook2,
51373
51613
  resumeWebhook: () => resumeWebhook2
51374
51614
  });
51375
- async function getHookByTokenWithKey2(token) {
51615
+ async function getHookAndRun2(token) {
51376
51616
  const world = await getWorldLazy2();
51377
51617
  const hook = await world.hooks.getByToken(token);
51378
51618
  const run3 = await world.runs.get(hook.runId);
51379
- const rawKey = await world.getEncryptionKeyForRun?.(run3);
51619
+ return { hook, run: run3 };
51620
+ }
51621
+ async function getHookByTokenWithKey2(token) {
51622
+ const { hook, run: run3 } = await getHookAndRun2(token);
51623
+ const rawKey = await (await getWorldLazy2()).getEncryptionKeyForRun?.(run3);
51380
51624
  const encryptionKey = rawKey ? await importKey2(rawKey) : void 0;
51381
51625
  if (typeof hook.metadata !== "undefined") {
51382
51626
  hook.metadata = await hydrateStepArguments2(hook.metadata, hook.runId, encryptionKey);
51383
51627
  }
51384
- return { hook, run: run3, encryptionKey };
51628
+ return { hook, encryptionKey };
51385
51629
  }
51386
51630
  async function getHookByToken2(token) {
51387
51631
  const { hook } = await getHookByTokenWithKey2(token);
@@ -51394,27 +51638,27 @@ async function resumeHook2(tokenOrHook, payload, encryptionKeyOverride) {
51394
51638
  try {
51395
51639
  let hook;
51396
51640
  let workflowRun;
51397
- let encryptionKey;
51398
51641
  if (typeof tokenOrHook === "string") {
51399
- const result = await getHookByTokenWithKey2(tokenOrHook);
51642
+ const result = await getHookAndRun2(tokenOrHook);
51400
51643
  hook = result.hook;
51401
51644
  workflowRun = result.run;
51402
- encryptionKey = encryptionKeyOverride ?? result.encryptionKey;
51403
51645
  } else {
51404
51646
  hook = tokenOrHook;
51405
51647
  workflowRun = await world.runs.get(hook.runId);
51406
- if (encryptionKeyOverride) {
51407
- encryptionKey = encryptionKeyOverride;
51408
- } else {
51409
- const rawKey = await world.getEncryptionKeyForRun?.(workflowRun);
51410
- encryptionKey = rawKey ? await importKey2(rawKey) : void 0;
51411
- }
51412
51648
  }
51413
51649
  span?.setAttributes({
51414
51650
  ...HookToken2(hook.token),
51415
51651
  ...HookId2(hook.hookId),
51416
51652
  ...WorkflowRunId3(hook.runId)
51417
51653
  });
51654
+ if (isTerminalWorkflowRunStatus2(workflowRun.status)) {
51655
+ throw new HookNotFoundError2(hook.token);
51656
+ }
51657
+ let encryptionKey = encryptionKeyOverride;
51658
+ if (!encryptionKey) {
51659
+ const rawKey = await world.getEncryptionKeyForRun?.(workflowRun);
51660
+ encryptionKey = rawKey ? await importKey2(rawKey) : void 0;
51661
+ }
51418
51662
  const rawVersion = workflowRun.executionContext?.workflowCoreVersion;
51419
51663
  const capabilities = getRunCapabilities2(typeof rawVersion === "string" ? rawVersion : void 0);
51420
51664
  if (!capabilities.supportedFormats.has(SerializationFormat2.ENCRYPTED)) {
@@ -51519,6 +51763,7 @@ var init_resume_hook2 = __esm({
51519
51763
  init_get_world_lazy2();
51520
51764
  init_helpers2();
51521
51765
  init_wait_until2();
51766
+ __name(getHookAndRun2, "getHookAndRun");
51522
51767
  __name(getHookByTokenWithKey2, "getHookByTokenWithKey");
51523
51768
  __name(getHookByToken2, "getHookByToken");
51524
51769
  __name(resumeHook2, "resumeHook");
@@ -52757,14 +53002,8 @@ function getStepRevivers2(global2 = globalThis, ops, runId, cryptoKey, deploymen
52757
53002
  async function maybeEncrypt(data, key) {
52758
53003
  return await encrypt4(data, key);
52759
53004
  }
52760
- async function maybeDecrypt2(data, key) {
52761
- return decrypt4(data, key);
52762
- }
52763
- async function hydrateWorkflowArguments(value, _runId, key, global2 = globalThis, extraRevivers = {}) {
52764
- const compressionStats = {};
52765
- const inflated = await decompress2(await maybeDecrypt2(value, key), compressionStats);
52766
- await recordCompression2(compressionStats, "deserialize");
52767
- return deserialize5(inflated, {
53005
+ function deserializePreparedReplayPayload(prepared, global2 = globalThis, extraRevivers = {}) {
53006
+ return deserialize5(prepared.data, {
52768
53007
  global: global2,
52769
53008
  extraRevivers: {
52770
53009
  ...getStreamAndRequestRevivers2(getWorkflowRevivers(global2)),
@@ -52772,6 +53011,27 @@ async function hydrateWorkflowArguments(value, _runId, key, global2 = globalThis
52772
53011
  }
52773
53012
  });
52774
53013
  }
53014
+ function deserializePreparedStepError(prepared, global2 = globalThis, extraRevivers = {}) {
53015
+ const { data } = prepared;
53016
+ if (!(data instanceof Uint8Array)) {
53017
+ return unflatten2(data, {
53018
+ ...getWorkflowRevivers(global2),
53019
+ ...extraRevivers
53020
+ });
53021
+ }
53022
+ const { format, payload } = decodeFormatPrefix2(data);
53023
+ if (format === SerializationFormat2.DEVALUE_V1) {
53024
+ const str = new TextDecoder().decode(payload);
53025
+ return parse6(str, {
53026
+ ...getWorkflowRevivers(global2),
53027
+ ...extraRevivers
53028
+ });
53029
+ }
53030
+ throw new Error(`Unsupported serialization format: ${format}`);
53031
+ }
53032
+ async function hydrateWorkflowArguments(value, _runId, key, global2 = globalThis, extraRevivers = {}, prepared) {
53033
+ return deserializePreparedReplayPayload(prepared ?? await prepareReplayPayload(value, key), global2, extraRevivers);
53034
+ }
52775
53035
  async function dehydrateWorkflowReturnValue(value, _runId, key, global2 = globalThis, v1Compat = false, compression = false) {
52776
53036
  if (v1Compat) {
52777
53037
  const str = stringify2(value, getWorkflowReducers2(global2));
@@ -52877,25 +53137,8 @@ async function dehydrateStepError(value, runId, key, ops = [], global2 = globalT
52877
53137
  throw new SerializationError2(message, { hint: hint3, cause });
52878
53138
  }
52879
53139
  }
52880
- async function hydrateStepError(value, _runId, key, global2 = globalThis, extraRevivers = {}) {
52881
- const compressionStats = {};
52882
- const decrypted = await decompress2(await maybeDecrypt2(value, key), compressionStats);
52883
- await recordCompression2(compressionStats, "deserialize");
52884
- if (!(decrypted instanceof Uint8Array)) {
52885
- return unflatten2(decrypted, {
52886
- ...getWorkflowRevivers(global2),
52887
- ...extraRevivers
52888
- });
52889
- }
52890
- const { format, payload } = decodeFormatPrefix2(decrypted);
52891
- if (format === SerializationFormat2.DEVALUE_V1) {
52892
- const str = new TextDecoder().decode(payload);
52893
- return parse6(str, {
52894
- ...getWorkflowRevivers(global2),
52895
- ...extraRevivers
52896
- });
52897
- }
52898
- throw new Error(`Unsupported serialization format: ${format}`);
53140
+ async function hydrateStepError(value, _runId, key, global2 = globalThis, extraRevivers = {}, prepared) {
53141
+ return deserializePreparedStepError(prepared ?? await prepareReplayPayload(value, key), global2, extraRevivers);
52899
53142
  }
52900
53143
  async function dehydrateRunError(value, _runId, key, global2 = globalThis, compression = false) {
52901
53144
  try {
@@ -52915,7 +53158,7 @@ async function dehydrateRunError(value, _runId, key, global2 = globalThis, compr
52915
53158
  }
52916
53159
  async function hydrateRunError2(value, runId, key, ops = [], global2 = globalThis, extraRevivers = {}) {
52917
53160
  const compressionStats = {};
52918
- const decrypted = await decompress2(await maybeDecrypt2(value, key), compressionStats);
53161
+ const decrypted = await decompress2(await decrypt4(value, key), compressionStats);
52919
53162
  await recordCompression2(compressionStats, "deserialize");
52920
53163
  if (!(decrypted instanceof Uint8Array)) {
52921
53164
  return unflatten2(decrypted, {
@@ -52933,17 +53176,8 @@ async function hydrateRunError2(value, runId, key, ops = [], global2 = globalThi
52933
53176
  }
52934
53177
  throw new Error(`Unsupported serialization format: ${format}`);
52935
53178
  }
52936
- async function hydrateStepReturnValue(value, _runId, key, global2 = globalThis, extraRevivers = {}) {
52937
- const compressionStats = {};
52938
- const inflated = await decompress2(await maybeDecrypt2(value, key), compressionStats);
52939
- await recordCompression2(compressionStats, "deserialize");
52940
- return deserialize5(inflated, {
52941
- global: global2,
52942
- extraRevivers: {
52943
- ...getStreamAndRequestRevivers2(getWorkflowRevivers(global2)),
52944
- ...extraRevivers
52945
- }
52946
- });
53179
+ async function hydrateStepReturnValue(value, _runId, key, global2 = globalThis, extraRevivers = {}, prepared) {
53180
+ return deserializePreparedReplayPayload(prepared ?? await prepareReplayPayload(value, key), global2, extraRevivers);
52947
53181
  }
52948
53182
  function getStreamAndRequestReducers2(allReducers) {
52949
53183
  const extra = {};
@@ -52963,7 +53197,7 @@ function getStreamAndRequestRevivers2(allRevivers) {
52963
53197
  }
52964
53198
  return extra;
52965
53199
  }
52966
- var defaultUlid2, FRAME_HEADER_SIZE2, MAX_FRAME_SIZE2, WorkflowServerReadableStream2, FRAMED_STREAM_MAX_RECONNECTS2, getFramedStreamMaxReconnects2, FRAMED_STREAM_MAX_TOTAL_RECONNECTS2, getFramedStreamMaxTotalReconnects2, STREAM_FLUSH_INTERVAL_MS2, getStreamFlushIntervalMs2, WorkflowServerWritableStream2, STREAM_AND_REQUEST_KEYS2;
53200
+ var defaultUlid2, FRAME_HEADER_SIZE2, MAX_FRAME_SIZE2, WorkflowServerReadableStream2, FRAMED_STREAM_MAX_RECONNECTS2, getFramedStreamMaxReconnects2, FRAMED_STREAM_MAX_TOTAL_RECONNECTS2, getFramedStreamMaxTotalReconnects2, STREAM_FLUSH_INTERVAL_MS2, getStreamFlushIntervalMs2, WorkflowServerWritableStream2, prepareReplayPayload, STREAM_AND_REQUEST_KEYS2;
52967
53201
  var init_serialization4 = __esm({
52968
53202
  "../core/dist/serialization.js"() {
52969
53203
  "use strict";
@@ -53205,6 +53439,19 @@ var init_serialization4 = __esm({
53205
53439
  w.reject(abortError);
53206
53440
  }
53207
53441
  });
53442
+ Object.defineProperty(this, STREAM_WRITE_BATCH_SYMBOL2, {
53443
+ value: /* @__PURE__ */ __name(async (chunks) => {
53444
+ if (chunks.length === 0)
53445
+ return;
53446
+ if (batchStartAt === void 0)
53447
+ batchStartAt = Date.now();
53448
+ for (const chunk of chunks)
53449
+ buffer3.push(chunk);
53450
+ await flush();
53451
+ }, "value"),
53452
+ enumerable: false,
53453
+ writable: false
53454
+ });
53208
53455
  }
53209
53456
  };
53210
53457
  __name(getAllBaseReducers2, "getAllBaseReducers");
@@ -53226,7 +53473,14 @@ var init_serialization4 = __esm({
53226
53473
  __name(getWorkflowRevivers, "getWorkflowRevivers");
53227
53474
  __name(getStepRevivers2, "getStepRevivers");
53228
53475
  __name(maybeEncrypt, "maybeEncrypt");
53229
- __name(maybeDecrypt2, "maybeDecrypt");
53476
+ prepareReplayPayload = /* @__PURE__ */ __name(async (value, key) => {
53477
+ const compressionStats = {};
53478
+ const prepared = await decompress2(await decrypt4(value, key), compressionStats);
53479
+ await recordCompression2(compressionStats, "deserialize");
53480
+ return { data: prepared };
53481
+ }, "prepareReplayPayload");
53482
+ __name(deserializePreparedReplayPayload, "deserializePreparedReplayPayload");
53483
+ __name(deserializePreparedStepError, "deserializePreparedStepError");
53230
53484
  __name(hydrateWorkflowArguments, "hydrateWorkflowArguments");
53231
53485
  __name(dehydrateWorkflowReturnValue, "dehydrateWorkflowReturnValue");
53232
53486
  __name(hydrateWorkflowReturnValue2, "hydrateWorkflowReturnValue");
@@ -54332,6 +54586,8 @@ var init_error_codes = __esm2({
54332
54586
  REPLAY_DIVERGENCE: "REPLAY_DIVERGENCE",
54333
54587
  /** Run exceeded the maximum number of queue deliveries */
54334
54588
  MAX_DELIVERIES_EXCEEDED: "MAX_DELIVERIES_EXCEEDED",
54589
+ /** Run exceeded the maximum number of events per run */
54590
+ MAX_EVENTS_EXCEEDED: "MAX_EVENTS_EXCEEDED",
54335
54591
  /** Workflow replay exceeded the maximum allowed duration */
54336
54592
  REPLAY_TIMEOUT: "REPLAY_TIMEOUT",
54337
54593
  /** World response violated the SDK contract and cannot be retried safely */
@@ -71113,6 +71369,8 @@ function validateAttributeChanges(changes, context2 = {}) {
71113
71369
  }
71114
71370
  __name(validateAttributeChanges, "validateAttributeChanges");
71115
71371
  var RESERVED_ATTRIBUTE_KEY_PREFIX;
71372
+ var ROOT_RUN_ID_ATTRIBUTE;
71373
+ var PARENT_RUN_ID_ATTRIBUTE;
71116
71374
  var ATTRIBUTE_KEY_MAX_LENGTH;
71117
71375
  var ATTRIBUTE_VALUE_MAX_BYTES;
71118
71376
  var ATTRIBUTE_MAX_PER_RUN;
@@ -71125,6 +71383,8 @@ var init_attributes = __esm2({
71125
71383
  "use strict";
71126
71384
  init_zod();
71127
71385
  RESERVED_ATTRIBUTE_KEY_PREFIX = "$";
71386
+ ROOT_RUN_ID_ATTRIBUTE = `${RESERVED_ATTRIBUTE_KEY_PREFIX}rootRunId`;
71387
+ PARENT_RUN_ID_ATTRIBUTE = `${RESERVED_ATTRIBUTE_KEY_PREFIX}parentRunId`;
71128
71388
  ATTRIBUTE_KEY_MAX_LENGTH = 256;
71129
71389
  ATTRIBUTE_VALUE_MAX_BYTES = 256;
71130
71390
  ATTRIBUTE_MAX_PER_RUN = 64;
@@ -71329,6 +71589,17 @@ var init_events = __esm2({
71329
71589
  // stso.
71330
71590
  stepCount: external_exports.number().int().positive().optional(),
71331
71591
  eventCount: external_exports.number().int().positive().optional(),
71592
+ // Run-started-to-first-step: milliseconds from the `run_started` response
71593
+ // landing (or, under turbo, the local run synthesis instant) until this
71594
+ // step's start POST was issued. A sub-window of ttfs. Only reported
71595
+ // alongside the same eligibility as ttfs.
71596
+ rsfs: external_exports.number().optional(),
71597
+ // Synchronous workflow-function replay duration of only the FINAL replay
71598
+ // pass within the rsfs window (the pass that scheduled the first step),
71599
+ // excluding awaited network I/O — not accumulated across earlier
71600
+ // pre-first-step passes, so it is not "the replay portion of rsfs". Only
71601
+ // present alongside rsfs, and only for the run's first step.
71602
+ finalSchedulingReplay: external_exports.number().optional(),
71332
71603
  // Names of the runtime's optional startup-latency optimizations that were
71333
71604
  // active for this measurement (e.g. 'turbo', 'lazyStepStart',
71334
71605
  // 'optimisticStart'), so latency metrics can be segmented by them.
@@ -71410,6 +71681,7 @@ var init_events = __esm2({
71410
71681
  correlationId: external_exports.string(),
71411
71682
  eventData: external_exports.object({
71412
71683
  token: external_exports.string(),
71684
+ tokenRetentionUntil: external_exports.coerce.date().optional(),
71413
71685
  metadata: SerializedDataSchema.optional(),
71414
71686
  isWebhook: external_exports.boolean().optional(),
71415
71687
  isSystem: external_exports.boolean().optional()
@@ -71577,6 +71849,10 @@ var init_events = __esm2({
71577
71849
  }));
71578
71850
  }
71579
71851
  });
71852
+ function isTerminalWorkflowRunStatus(status) {
71853
+ return TERMINAL_WORKFLOW_RUN_STATUSES.includes(status);
71854
+ }
71855
+ __name(isTerminalWorkflowRunStatus, "isTerminalWorkflowRunStatus");
71580
71856
  var WorkflowRunStatusSchema;
71581
71857
  var TerminalWorkflowRunStatusSchema;
71582
71858
  var TERMINAL_WORKFLOW_RUN_STATUSES;
@@ -71600,6 +71876,7 @@ var init_runs = __esm2({
71600
71876
  "cancelled"
71601
71877
  ]);
71602
71878
  TERMINAL_WORKFLOW_RUN_STATUSES = TerminalWorkflowRunStatusSchema.options;
71879
+ __name2(isTerminalWorkflowRunStatus, "isTerminalWorkflowRunStatus");
71603
71880
  WorkflowRunBaseSchema = external_exports.object({
71604
71881
  runId: external_exports.string(),
71605
71882
  status: WorkflowRunStatusSchema,
@@ -73078,6 +73355,39 @@ var init_devalue = __esm2({
73078
73355
  init_utils();
73079
73356
  }
73080
73357
  });
73358
+ var STABLE_ULID;
73359
+ var STREAM_NAME_SYMBOL;
73360
+ var STREAM_TYPE_SYMBOL;
73361
+ var STREAM_FRAMING_SYMBOL;
73362
+ var STREAM_SERVER_RUN_ID_SYMBOL;
73363
+ var STREAM_SERVER_DEPLOYMENT_ID_SYMBOL;
73364
+ var STREAM_WRITE_BATCH_SYMBOL;
73365
+ var BODY_INIT_SYMBOL;
73366
+ var WEBHOOK_RESPONSE_WRITABLE;
73367
+ var WORKFLOW_CLASS_REGISTRY;
73368
+ var ABORT_STREAM_NAME;
73369
+ var ABORT_HOOK_TOKEN;
73370
+ var ABORT_LISTENER_ATTACHED;
73371
+ var ABORT_READER_CANCEL;
73372
+ var init_symbols = __esm2({
73373
+ "../core/dist/symbols.js"() {
73374
+ "use strict";
73375
+ STABLE_ULID = /* @__PURE__ */ Symbol.for("WORKFLOW_STABLE_ULID");
73376
+ STREAM_NAME_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_NAME");
73377
+ STREAM_TYPE_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_TYPE");
73378
+ STREAM_FRAMING_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_FRAMING");
73379
+ STREAM_SERVER_RUN_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_RUN_ID");
73380
+ STREAM_SERVER_DEPLOYMENT_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_DEPLOYMENT_ID");
73381
+ STREAM_WRITE_BATCH_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_WRITE_BATCH");
73382
+ BODY_INIT_SYMBOL = /* @__PURE__ */ Symbol.for("BODY_INIT");
73383
+ WEBHOOK_RESPONSE_WRITABLE = /* @__PURE__ */ Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
73384
+ WORKFLOW_CLASS_REGISTRY = /* @__PURE__ */ Symbol.for("workflow-class-registry");
73385
+ ABORT_STREAM_NAME = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_STREAM_NAME");
73386
+ ABORT_HOOK_TOKEN = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_HOOK_TOKEN");
73387
+ ABORT_LISTENER_ATTACHED = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_LISTENER_ATTACHED");
73388
+ ABORT_READER_CANCEL = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_READER_CANCEL");
73389
+ }
73390
+ });
73081
73391
  function createFlushableState() {
73082
73392
  const state = {
73083
73393
  ...withResolvers(),
@@ -73162,7 +73472,12 @@ function pollReadableLock(readable, state) {
73162
73472
  state.readablePollingInterval = intervalId;
73163
73473
  }
73164
73474
  __name(pollReadableLock, "pollReadableLock");
73165
- async function flushablePipe(source, sink, state) {
73475
+ function flushablePipe(source, sink, state) {
73476
+ const batchWrite = sink[STREAM_WRITE_BATCH_SYMBOL];
73477
+ return typeof batchWrite === "function" ? flushablePipeCoalescing(source, sink, state, batchWrite) : flushablePipePerChunk(source, sink, state);
73478
+ }
73479
+ __name(flushablePipe, "flushablePipe");
73480
+ async function flushablePipePerChunk(source, sink, state) {
73166
73481
  const reader = source.getReader();
73167
73482
  const writer = sink.getWriter();
73168
73483
  let cancelReason;
@@ -73211,7 +73526,132 @@ async function flushablePipe(source, sink, state) {
73211
73526
  writer.releaseLock();
73212
73527
  }
73213
73528
  }
73214
- __name(flushablePipe, "flushablePipe");
73529
+ __name(flushablePipePerChunk, "flushablePipePerChunk");
73530
+ function wake(ctx, which) {
73531
+ const resolve2 = ctx[which];
73532
+ if (resolve2) {
73533
+ ctx[which] = null;
73534
+ resolve2();
73535
+ }
73536
+ }
73537
+ __name(wake, "wake");
73538
+ function nextBatchSize(ctx) {
73539
+ let count2 = 0;
73540
+ let bytes = 0;
73541
+ for (const chunk of ctx.queue) {
73542
+ if (count2 >= ctx.maxChunksPerBatch) break;
73543
+ if (count2 > 0 && bytes + chunk.byteLength > ctx.maxBytesPerBatch) break;
73544
+ count2++;
73545
+ bytes += chunk.byteLength;
73546
+ }
73547
+ return count2;
73548
+ }
73549
+ __name(nextBatchSize, "nextBatchSize");
73550
+ async function drainBatches(ctx) {
73551
+ while (true) {
73552
+ if (ctx.queue.length === 0) {
73553
+ if (ctx.sourceDone) return;
73554
+ await new Promise((resolve2) => {
73555
+ ctx.wakeConsumer = resolve2;
73556
+ });
73557
+ continue;
73558
+ }
73559
+ const count2 = nextBatchSize(ctx);
73560
+ const batch = ctx.queue.slice(0, count2);
73561
+ ctx.queue = ctx.queue.slice(count2);
73562
+ await ctx.batchWrite(batch);
73563
+ ctx.state.pendingOps -= batch.length;
73564
+ wake(ctx, "wakeProducer");
73565
+ }
73566
+ }
73567
+ __name(drainBatches, "drainBatches");
73568
+ function readNextChunk(reader, writer, consumer) {
73569
+ return Promise.race([
73570
+ reader.read(),
73571
+ writer.closed.then(() => {
73572
+ throw new WorkflowRuntimeError("Writable stream closed prematurely");
73573
+ }),
73574
+ consumer.then(() => {
73575
+ throw new WorkflowRuntimeError("Stream consumer ended prematurely");
73576
+ }, (err) => {
73577
+ throw err;
73578
+ })
73579
+ ]);
73580
+ }
73581
+ __name(readNextChunk, "readNextChunk");
73582
+ async function awaitBackpressureRelief(ctx, consumer, maxInflight) {
73583
+ if (ctx.state.pendingOps < maxInflight) return;
73584
+ await Promise.race([
73585
+ new Promise((resolve2) => {
73586
+ ctx.wakeProducer = resolve2;
73587
+ }),
73588
+ consumer.then(() => void 0, () => void 0)
73589
+ ]);
73590
+ }
73591
+ __name(awaitBackpressureRelief, "awaitBackpressureRelief");
73592
+ async function flushablePipeCoalescing(source, sink, state, batchWrite) {
73593
+ const reader = source.getReader();
73594
+ const writer = sink.getWriter();
73595
+ const maxInflight = getMaxInflightChunks();
73596
+ let cancelReason;
73597
+ const ctx = {
73598
+ state,
73599
+ batchWrite,
73600
+ queue: [],
73601
+ sourceDone: false,
73602
+ wakeConsumer: null,
73603
+ wakeProducer: null,
73604
+ maxChunksPerBatch: getMaxChunksPerBatch(),
73605
+ maxBytesPerBatch: getMaxBytesPerBatch()
73606
+ };
73607
+ const consumer = drainBatches(ctx);
73608
+ try {
73609
+ while (!state.streamEnded) {
73610
+ const readResult = await readNextChunk(reader, writer, consumer);
73611
+ if (state.streamEnded) return;
73612
+ if (readResult.done) {
73613
+ ctx.sourceDone = true;
73614
+ wake(ctx, "wakeConsumer");
73615
+ await consumer;
73616
+ state.streamEnded = true;
73617
+ await writer.close();
73618
+ if (!state.doneResolved) {
73619
+ state.doneResolved = true;
73620
+ state.resolve();
73621
+ }
73622
+ return;
73623
+ }
73624
+ ctx.queue.push(readResult.value);
73625
+ state.pendingOps++;
73626
+ wake(ctx, "wakeConsumer");
73627
+ await awaitBackpressureRelief(ctx, consumer, maxInflight);
73628
+ }
73629
+ } catch (err) {
73630
+ state.streamEnded = true;
73631
+ cancelReason = err;
73632
+ ctx.sourceDone = true;
73633
+ wake(ctx, "wakeConsumer");
73634
+ await consumer.catch(() => {
73635
+ });
73636
+ if (!state.doneResolved) {
73637
+ state.doneResolved = true;
73638
+ state.reject(err);
73639
+ }
73640
+ throw err;
73641
+ } finally {
73642
+ reader.cancel(cancelReason).catch(() => {
73643
+ });
73644
+ reader.releaseLock();
73645
+ writer.releaseLock();
73646
+ }
73647
+ }
73648
+ __name(flushablePipeCoalescing, "flushablePipeCoalescing");
73649
+ var MAX_INFLIGHT_CHUNKS;
73650
+ var getMaxInflightChunks;
73651
+ var MAX_CHUNKS_PER_BATCH;
73652
+ var getMaxChunksPerBatch;
73653
+ var MAX_BYTES_PER_BATCH;
73654
+ var getMaxBytesPerBatch;
73215
73655
  var LOCK_POLL_INTERVAL_MS;
73216
73656
  var getLockPollIntervalMs;
73217
73657
  var init_flushable_stream = __esm2({
@@ -73220,6 +73660,22 @@ var init_flushable_stream = __esm2({
73220
73660
  init_dist2();
73221
73661
  init_dist();
73222
73662
  init_dist4();
73663
+ init_symbols();
73664
+ MAX_INFLIGHT_CHUNKS = 1e3;
73665
+ getMaxInflightChunks = /* @__PURE__ */ __name2(() => envNumber("WORKFLOW_STREAM_MAX_INFLIGHT_CHUNKS", MAX_INFLIGHT_CHUNKS, {
73666
+ integer: true,
73667
+ min: 1
73668
+ }), "getMaxInflightChunks");
73669
+ MAX_CHUNKS_PER_BATCH = 1e3;
73670
+ getMaxChunksPerBatch = /* @__PURE__ */ __name2(() => envNumber("WORKFLOW_STREAM_MAX_CHUNKS_PER_BATCH", MAX_CHUNKS_PER_BATCH, {
73671
+ integer: true,
73672
+ min: 1
73673
+ }), "getMaxChunksPerBatch");
73674
+ MAX_BYTES_PER_BATCH = 1024 * 1024;
73675
+ getMaxBytesPerBatch = /* @__PURE__ */ __name2(() => envNumber("WORKFLOW_STREAM_MAX_BYTES_PER_BATCH", MAX_BYTES_PER_BATCH, {
73676
+ integer: true,
73677
+ min: 1
73678
+ }), "getMaxBytesPerBatch");
73223
73679
  LOCK_POLL_INTERVAL_MS = 10;
73224
73680
  getLockPollIntervalMs = /* @__PURE__ */ __name2(() => envNumber("WORKFLOW_LOCK_POLL_INTERVAL_MS", LOCK_POLL_INTERVAL_MS, {
73225
73681
  integer: true,
@@ -73231,6 +73687,13 @@ var init_flushable_stream = __esm2({
73231
73687
  __name2(pollWritableLock, "pollWritableLock");
73232
73688
  __name2(pollReadableLock, "pollReadableLock");
73233
73689
  __name2(flushablePipe, "flushablePipe");
73690
+ __name2(flushablePipePerChunk, "flushablePipePerChunk");
73691
+ __name2(wake, "wake");
73692
+ __name2(nextBatchSize, "nextBatchSize");
73693
+ __name2(drainBatches, "drainBatches");
73694
+ __name2(readNextChunk, "readNextChunk");
73695
+ __name2(awaitBackpressureRelief, "awaitBackpressureRelief");
73696
+ __name2(flushablePipeCoalescing, "flushablePipeCoalescing");
73234
73697
  }
73235
73698
  });
73236
73699
  function getStepIdAliasCandidates(stepId) {
@@ -73362,37 +73825,6 @@ var init_get_world_lazy = __esm2({
73362
73825
  __name2(getWorldLazy, "getWorldLazy");
73363
73826
  }
73364
73827
  });
73365
- var STABLE_ULID;
73366
- var STREAM_NAME_SYMBOL;
73367
- var STREAM_TYPE_SYMBOL;
73368
- var STREAM_FRAMING_SYMBOL;
73369
- var STREAM_SERVER_RUN_ID_SYMBOL;
73370
- var STREAM_SERVER_DEPLOYMENT_ID_SYMBOL;
73371
- var BODY_INIT_SYMBOL;
73372
- var WEBHOOK_RESPONSE_WRITABLE;
73373
- var WORKFLOW_CLASS_REGISTRY;
73374
- var ABORT_STREAM_NAME;
73375
- var ABORT_HOOK_TOKEN;
73376
- var ABORT_LISTENER_ATTACHED;
73377
- var ABORT_READER_CANCEL;
73378
- var init_symbols = __esm2({
73379
- "../core/dist/symbols.js"() {
73380
- "use strict";
73381
- STABLE_ULID = /* @__PURE__ */ Symbol.for("WORKFLOW_STABLE_ULID");
73382
- STREAM_NAME_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_NAME");
73383
- STREAM_TYPE_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_TYPE");
73384
- STREAM_FRAMING_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_FRAMING");
73385
- STREAM_SERVER_RUN_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_RUN_ID");
73386
- STREAM_SERVER_DEPLOYMENT_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_DEPLOYMENT_ID");
73387
- BODY_INIT_SYMBOL = /* @__PURE__ */ Symbol.for("BODY_INIT");
73388
- WEBHOOK_RESPONSE_WRITABLE = /* @__PURE__ */ Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
73389
- WORKFLOW_CLASS_REGISTRY = /* @__PURE__ */ Symbol.for("workflow-class-registry");
73390
- ABORT_STREAM_NAME = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_STREAM_NAME");
73391
- ABORT_HOOK_TOKEN = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_HOOK_TOKEN");
73392
- ABORT_LISTENER_ATTACHED = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_LISTENER_ATTACHED");
73393
- ABORT_READER_CANCEL = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_READER_CANCEL");
73394
- }
73395
- });
73396
73828
  function getRegistry(global2 = globalThis) {
73397
73829
  const g = global2;
73398
73830
  let registry22 = g[WORKFLOW_CLASS_REGISTRY];
@@ -74667,6 +75099,8 @@ var StepMaxRetries;
74667
75099
  var StepTracePropagated;
74668
75100
  var StepTtfsMs;
74669
75101
  var StepStsoMs;
75102
+ var StepRsfsMs;
75103
+ var StepFinalSchedulingReplayMs;
74670
75104
  var StepLatencyOptimizations;
74671
75105
  var StepSkipped;
74672
75106
  var StepSkipReason;
@@ -74752,6 +75186,8 @@ var init_semantic_conventions = __esm2({
74752
75186
  StepTracePropagated = SemanticConvention("step.trace.propagated");
74753
75187
  StepTtfsMs = SemanticConvention("step.ttfs_ms");
74754
75188
  StepStsoMs = SemanticConvention("step.stso_ms");
75189
+ StepRsfsMs = SemanticConvention("step.rsfs_ms");
75190
+ StepFinalSchedulingReplayMs = SemanticConvention("step.final_scheduling_replay_ms");
74755
75191
  StepLatencyOptimizations = SemanticConvention("step.latency_optimizations");
74756
75192
  StepSkipped = SemanticConvention("step.skipped");
74757
75193
  StepSkipReason = SemanticConvention("step.skip_reason");
@@ -79347,7 +79783,7 @@ var version2;
79347
79783
  var init_version = __esm2({
79348
79784
  "../core/dist/version.js"() {
79349
79785
  "use strict";
79350
- version2 = "5.0.0-beta.34";
79786
+ version2 = "5.0.0-beta.36";
79351
79787
  }
79352
79788
  });
79353
79789
  function getWorkflowQueueName(workflowName, namespace) {
@@ -80694,18 +81130,25 @@ __export2(resume_hook_exports, {
80694
81130
  resumeHook: /* @__PURE__ */ __name(() => resumeHook, "resumeHook"),
80695
81131
  resumeWebhook: /* @__PURE__ */ __name(() => resumeWebhook, "resumeWebhook")
80696
81132
  });
80697
- async function getHookByTokenWithKey(token) {
81133
+ async function getHookAndRun(token) {
80698
81134
  const world = await getWorldLazy();
80699
81135
  const hook = await world.hooks.getByToken(token);
80700
81136
  const run22 = await world.runs.get(hook.runId);
80701
- const rawKey = await world.getEncryptionKeyForRun?.(run22);
81137
+ return {
81138
+ hook,
81139
+ run: run22
81140
+ };
81141
+ }
81142
+ __name(getHookAndRun, "getHookAndRun");
81143
+ async function getHookByTokenWithKey(token) {
81144
+ const { hook, run: run22 } = await getHookAndRun(token);
81145
+ const rawKey = await (await getWorldLazy()).getEncryptionKeyForRun?.(run22);
80702
81146
  const encryptionKey = rawKey ? await importKey(rawKey) : void 0;
80703
81147
  if (typeof hook.metadata !== "undefined") {
80704
81148
  hook.metadata = await hydrateStepArguments(hook.metadata, hook.runId, encryptionKey);
80705
81149
  }
80706
81150
  return {
80707
81151
  hook,
80708
- run: run22,
80709
81152
  encryptionKey
80710
81153
  };
80711
81154
  }
@@ -80722,27 +81165,27 @@ async function resumeHook(tokenOrHook, payload, encryptionKeyOverride) {
80722
81165
  try {
80723
81166
  let hook;
80724
81167
  let workflowRun;
80725
- let encryptionKey;
80726
81168
  if (typeof tokenOrHook === "string") {
80727
- const result = await getHookByTokenWithKey(tokenOrHook);
81169
+ const result = await getHookAndRun(tokenOrHook);
80728
81170
  hook = result.hook;
80729
81171
  workflowRun = result.run;
80730
- encryptionKey = encryptionKeyOverride ?? result.encryptionKey;
80731
81172
  } else {
80732
81173
  hook = tokenOrHook;
80733
81174
  workflowRun = await world.runs.get(hook.runId);
80734
- if (encryptionKeyOverride) {
80735
- encryptionKey = encryptionKeyOverride;
80736
- } else {
80737
- const rawKey = await world.getEncryptionKeyForRun?.(workflowRun);
80738
- encryptionKey = rawKey ? await importKey(rawKey) : void 0;
80739
- }
80740
81175
  }
80741
81176
  span?.setAttributes({
80742
81177
  ...HookToken(hook.token),
80743
81178
  ...HookId(hook.hookId),
80744
81179
  ...WorkflowRunId(hook.runId)
80745
81180
  });
81181
+ if (isTerminalWorkflowRunStatus(workflowRun.status)) {
81182
+ throw new HookNotFoundError(hook.token);
81183
+ }
81184
+ let encryptionKey = encryptionKeyOverride;
81185
+ if (!encryptionKey) {
81186
+ const rawKey = await world.getEncryptionKeyForRun?.(workflowRun);
81187
+ encryptionKey = rawKey ? await importKey(rawKey) : void 0;
81188
+ }
80746
81189
  const rawVersion = workflowRun.executionContext?.workflowCoreVersion;
80747
81190
  const capabilities = getRunCapabilities(typeof rawVersion === "string" ? rawVersion : void 0);
80748
81191
  if (!capabilities.supportedFormats.has(SerializationFormat.ENCRYPTED)) {
@@ -80856,6 +81299,7 @@ var init_resume_hook = __esm2({
80856
81299
  init_get_world_lazy();
80857
81300
  init_helpers();
80858
81301
  init_wait_until();
81302
+ __name2(getHookAndRun, "getHookAndRun");
80859
81303
  __name2(getHookByTokenWithKey, "getHookByTokenWithKey");
80860
81304
  __name2(getHookByToken, "getHookByToken");
80861
81305
  __name2(resumeHook, "resumeHook");
@@ -81989,10 +82433,6 @@ function getStepRevivers(global2 = globalThis, ops, runId, cryptoKey, deployment
81989
82433
  };
81990
82434
  }
81991
82435
  __name(getStepRevivers, "getStepRevivers");
81992
- async function maybeDecrypt(data, key) {
81993
- return decrypt2(data, key);
81994
- }
81995
- __name(maybeDecrypt, "maybeDecrypt");
81996
82436
  async function dehydrateWorkflowArguments(value, runId, key, ops = [], global2 = globalThis, v1Compat = false, framedByteStreams = false, compression = false) {
81997
82437
  if (v1Compat) {
81998
82438
  const str = stringify(value, getExternalReducers(global2, ops, runId, key, framedByteStreams));
@@ -82098,7 +82538,7 @@ async function dehydrateStepReturnValue(value, runId, key, ops = [], global2 = g
82098
82538
  __name(dehydrateStepReturnValue, "dehydrateStepReturnValue");
82099
82539
  async function hydrateRunError(value, runId, key, ops = [], global2 = globalThis, extraRevivers = {}) {
82100
82540
  const compressionStats = {};
82101
- const decrypted = await decompress(await maybeDecrypt(value, key), compressionStats);
82541
+ const decrypted = await decompress(await decrypt2(value, key), compressionStats);
82102
82542
  await recordCompression(compressionStats, "deserialize");
82103
82543
  if (!(decrypted instanceof Uint8Array)) {
82104
82544
  return unflatten(decrypted, {
@@ -82395,6 +82835,16 @@ var init_serialization2 = __esm2({
82395
82835
  for (const w of waiters) w.reject(abortError);
82396
82836
  }
82397
82837
  });
82838
+ Object.defineProperty(this, STREAM_WRITE_BATCH_SYMBOL, {
82839
+ value: /* @__PURE__ */ __name2(async (chunks) => {
82840
+ if (chunks.length === 0) return;
82841
+ if (batchStartAt === void 0) batchStartAt = Date.now();
82842
+ for (const chunk of chunks) buffer22.push(chunk);
82843
+ await flush();
82844
+ }, "value"),
82845
+ enumerable: false,
82846
+ writable: false
82847
+ });
82398
82848
  }
82399
82849
  };
82400
82850
  __name2(getAllBaseReducers, "getAllBaseReducers");
@@ -82413,7 +82863,6 @@ var init_serialization2 = __esm2({
82413
82863
  __name2(getForwardedWritableEncryptionKey, "getForwardedWritableEncryptionKey");
82414
82864
  __name2(getExternalRevivers, "getExternalRevivers");
82415
82865
  __name2(getStepRevivers, "getStepRevivers");
82416
- __name2(maybeDecrypt, "maybeDecrypt");
82417
82866
  __name2(dehydrateWorkflowArguments, "dehydrateWorkflowArguments");
82418
82867
  __name2(hydrateWorkflowReturnValue, "hydrateWorkflowReturnValue");
82419
82868
  __name2(dehydrateStepArguments, "dehydrateStepArguments");
@@ -82609,6 +83058,7 @@ __name2(isRetryableWorldError, "isRetryableWorldError");
82609
83058
  init_encryption();
82610
83059
  init_logger();
82611
83060
  init_serialization2();
83061
+ init_context_storage();
82612
83062
  init_semantic_conventions();
82613
83063
  init_telemetry();
82614
83064
  init_version();
@@ -82618,6 +83068,17 @@ init_wait_until();
82618
83068
  init_world_compatibility();
82619
83069
  var CROSS_DEPLOYMENT_CAPABILITY_PROBE_TIMEOUT_MS = 2e3;
82620
83070
  var ulid3 = monotonicFactory();
83071
+ function resolveLineageAttributes() {
83072
+ const store = contextStorage.getStore();
83073
+ const parentRunId = store?.workflowMetadata?.workflowRunId;
83074
+ if (!parentRunId) return void 0;
83075
+ return {
83076
+ [ROOT_RUN_ID_ATTRIBUTE]: store.rootRunId ?? parentRunId,
83077
+ [PARENT_RUN_ID_ATTRIBUTE]: parentRunId
83078
+ };
83079
+ }
83080
+ __name(resolveLineageAttributes, "resolveLineageAttributes");
83081
+ __name2(resolveLineageAttributes, "resolveLineageAttributes");
82621
83082
  var hasWarnedLatestNoOp = false;
82622
83083
  async function start(workflow, argsOrOptions, options) {
82623
83084
  return await waitedUntil(() => {
@@ -82702,9 +83163,14 @@ async function start(workflow, argsOrOptions, options) {
82702
83163
  value
82703
83164
  ]));
82704
83165
  }
82705
- const attributeSeed = attributes ? {
82706
- attributes,
82707
- ...allowReservedAttributes ? {
83166
+ const lineage = specVersion >= SPEC_VERSION_SUPPORTS_ATTRIBUTES ? resolveLineageAttributes() : void 0;
83167
+ const runAttributes = lineage ? {
83168
+ ...lineage,
83169
+ ...attributes
83170
+ } : attributes;
83171
+ const attributeSeed = runAttributes ? {
83172
+ attributes: runAttributes,
83173
+ ...allowReservedAttributes || lineage != null ? {
82708
83174
  allowReservedAttributes: true
82709
83175
  } : {}
82710
83176
  } : {};
@@ -82819,7 +83285,7 @@ __name2(start, "start");
82819
83285
  value: "start",
82820
83286
  configurable: true
82821
83287
  });
82822
- })(start, "step//@workflow/core/runtime/start@5.0.0-beta.34//start");
83288
+ })(start, "step//@workflow/core/runtime/start@5.0.0-beta.36//start");
82823
83289
  async function wakeUpRun(world, runId, options) {
82824
83290
  try {
82825
83291
  const run22 = await world.runs.get(runId, {
@@ -83155,7 +83621,7 @@ var Run = class _Run {
83155
83621
  value: "wakeUp",
83156
83622
  configurable: true
83157
83623
  });
83158
- })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#wakeUp");
83624
+ })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#wakeUp");
83159
83625
  (function(__wf_fn, __wf_id) {
83160
83626
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83161
83627
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83164,7 +83630,7 @@ var Run = class _Run {
83164
83630
  value: "cancel",
83165
83631
  configurable: true
83166
83632
  });
83167
- })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#cancel");
83633
+ })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#cancel");
83168
83634
  (function(__wf_fn, __wf_id) {
83169
83635
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83170
83636
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83173,7 +83639,7 @@ var Run = class _Run {
83173
83639
  value: "getReadable",
83174
83640
  configurable: true
83175
83641
  });
83176
- })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#getReadable");
83642
+ })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#getReadable");
83177
83643
  (function(__wf_fn, __wf_id) {
83178
83644
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83179
83645
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83182,7 +83648,7 @@ var Run = class _Run {
83182
83648
  value: "exists",
83183
83649
  configurable: true
83184
83650
  });
83185
- })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#exists");
83651
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#exists");
83186
83652
  (function(__wf_fn, __wf_id) {
83187
83653
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83188
83654
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83191,7 +83657,7 @@ var Run = class _Run {
83191
83657
  value: "status",
83192
83658
  configurable: true
83193
83659
  });
83194
- })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#status");
83660
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#status");
83195
83661
  (function(__wf_fn, __wf_id) {
83196
83662
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83197
83663
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83200,7 +83666,7 @@ var Run = class _Run {
83200
83666
  value: "returnValue",
83201
83667
  configurable: true
83202
83668
  });
83203
- })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#returnValue");
83669
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#returnValue");
83204
83670
  (function(__wf_fn, __wf_id) {
83205
83671
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83206
83672
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83209,7 +83675,7 @@ var Run = class _Run {
83209
83675
  value: "workflowName",
83210
83676
  configurable: true
83211
83677
  });
83212
- })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#workflowName");
83678
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#workflowName");
83213
83679
  (function(__wf_fn, __wf_id) {
83214
83680
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83215
83681
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83218,7 +83684,7 @@ var Run = class _Run {
83218
83684
  value: "createdAt",
83219
83685
  configurable: true
83220
83686
  });
83221
- })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#createdAt");
83687
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#createdAt");
83222
83688
  (function(__wf_fn, __wf_id) {
83223
83689
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83224
83690
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83227,7 +83693,7 @@ var Run = class _Run {
83227
83693
  value: "startedAt",
83228
83694
  configurable: true
83229
83695
  });
83230
- })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#startedAt");
83696
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#startedAt");
83231
83697
  (function(__wf_fn, __wf_id) {
83232
83698
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83233
83699
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83236,7 +83702,7 @@ var Run = class _Run {
83236
83702
  value: "completedAt",
83237
83703
  configurable: true
83238
83704
  });
83239
- })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.34//Run#completedAt");
83705
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#completedAt");
83240
83706
  (function(__wf_cls, __wf_id) {
83241
83707
  var __wf_sym = /* @__PURE__ */ Symbol.for("workflow-class-registry"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83242
83708
  __wf_reg.set(__wf_id, __wf_cls);
@@ -83246,7 +83712,7 @@ var Run = class _Run {
83246
83712
  enumerable: false,
83247
83713
  configurable: false
83248
83714
  });
83249
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.34//Run");
83715
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.36//Run");
83250
83716
  async function fetch2(...args) {
83251
83717
  return globalThis.fetch(...args);
83252
83718
  }
@@ -83287,6 +83753,26 @@ async function addTenWorkflow(input) {
83287
83753
  __name(addTenWorkflow, "addTenWorkflow");
83288
83754
  __name2(addTenWorkflow, "addTenWorkflow");
83289
83755
  addTenWorkflow.workflowId = "workflow//./workflows/addition//addTenWorkflow";
83756
+ async function tick(i) {
83757
+ return i;
83758
+ }
83759
+ __name(tick, "tick");
83760
+ __name2(tick, "tick");
83761
+ (function(__wf_fn, __wf_id) {
83762
+ var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83763
+ __wf_reg.set(__wf_id, __wf_fn);
83764
+ __wf_fn.stepId = __wf_id;
83765
+ Object.defineProperty(__wf_fn, "name", {
83766
+ value: "tick",
83767
+ configurable: true
83768
+ });
83769
+ })(tick, "step//./workflows/event-limit//tick");
83770
+ async function runawayWorkflow() {
83771
+ throw new Error("You attempted to execute workflow runawayWorkflow function directly. To start a workflow, use start(runawayWorkflow) from workflow/api");
83772
+ }
83773
+ __name(runawayWorkflow, "runawayWorkflow");
83774
+ __name2(runawayWorkflow, "runawayWorkflow");
83775
+ runawayWorkflow.workflowId = "workflow//./workflows/event-limit//runawayWorkflow";
83290
83776
  init_dist2();
83291
83777
  function redirectStackToCaller(err, stackStartFn) {
83292
83778
  const capture = Error.captureStackTrace;
@@ -83612,13 +84098,56 @@ async function hookWorkflow(token) {
83612
84098
  __name(hookWorkflow, "hookWorkflow");
83613
84099
  __name2(hookWorkflow, "hookWorkflow");
83614
84100
  hookWorkflow.workflowId = "workflow//./workflows/inline-execution//hookWorkflow";
84101
+ async function noop() {
84102
+ }
84103
+ __name(noop, "noop");
84104
+ __name2(noop, "noop");
84105
+ (function(__wf_fn, __wf_id) {
84106
+ var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
84107
+ __wf_reg.set(__wf_id, __wf_fn);
84108
+ __wf_fn.stepId = __wf_id;
84109
+ Object.defineProperty(__wf_fn, "name", {
84110
+ value: "noop",
84111
+ configurable: true
84112
+ });
84113
+ })(noop, "step//./workflows/lineage//noop");
84114
+ async function bodyStartsChild() {
84115
+ throw new Error("You attempted to execute workflow bodyStartsChild function directly. To start a workflow, use start(bodyStartsChild) from workflow/api");
84116
+ }
84117
+ __name(bodyStartsChild, "bodyStartsChild");
84118
+ __name2(bodyStartsChild, "bodyStartsChild");
84119
+ bodyStartsChild.workflowId = "workflow//./workflows/lineage//bodyStartsChild";
84120
+ async function spawnedChild() {
84121
+ throw new Error("You attempted to execute workflow spawnedChild function directly. To start a workflow, use start(spawnedChild) from workflow/api");
84122
+ }
84123
+ __name(spawnedChild, "spawnedChild");
84124
+ __name2(spawnedChild, "spawnedChild");
84125
+ spawnedChild.workflowId = "workflow//./workflows/lineage//spawnedChild";
84126
+ async function chainRoot() {
84127
+ throw new Error("You attempted to execute workflow chainRoot function directly. To start a workflow, use start(chainRoot) from workflow/api");
84128
+ }
84129
+ __name(chainRoot, "chainRoot");
84130
+ __name2(chainRoot, "chainRoot");
84131
+ chainRoot.workflowId = "workflow//./workflows/lineage//chainRoot";
84132
+ async function chainMiddle() {
84133
+ throw new Error("You attempted to execute workflow chainMiddle function directly. To start a workflow, use start(chainMiddle) from workflow/api");
84134
+ }
84135
+ __name(chainMiddle, "chainMiddle");
84136
+ __name2(chainMiddle, "chainMiddle");
84137
+ chainMiddle.workflowId = "workflow//./workflows/lineage//chainMiddle";
84138
+ async function chainLeaf() {
84139
+ throw new Error("You attempted to execute workflow chainLeaf function directly. To start a workflow, use start(chainLeaf) from workflow/api");
84140
+ }
84141
+ __name(chainLeaf, "chainLeaf");
84142
+ __name2(chainLeaf, "chainLeaf");
84143
+ chainLeaf.workflowId = "workflow//./workflows/lineage//chainLeaf";
83615
84144
  var count = 0;
83616
- async function noop(_i) {
84145
+ async function noop2(_i) {
83617
84146
  count++;
83618
84147
  return count;
83619
84148
  }
83620
- __name(noop, "noop");
83621
- __name2(noop, "noop");
84149
+ __name(noop2, "noop2");
84150
+ __name2(noop2, "noop");
83622
84151
  (function(__wf_fn, __wf_id) {
83623
84152
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83624
84153
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83627,7 +84156,7 @@ __name2(noop, "noop");
83627
84156
  value: "noop",
83628
84157
  configurable: true
83629
84158
  });
83630
- })(noop, "step//./workflows/noop//noop");
84159
+ })(noop2, "step//./workflows/noop//noop");
83631
84160
  async function brokenWf() {
83632
84161
  throw new Error("You attempted to execute workflow brokenWf function directly. To start a workflow, use start(brokenWf) from workflow/api");
83633
84162
  }
@@ -83732,7 +84261,7 @@ __export(dist_exports2, {
83732
84261
  parseVersion: () => parseVersion
83733
84262
  });
83734
84263
  init_dist5();
83735
- import { promises as fs6 } from "node:fs";
84264
+ import { promises as fs7 } from "node:fs";
83736
84265
  import { rm } from "node:fs/promises";
83737
84266
  import path10 from "node:path";
83738
84267
 
@@ -83997,6 +84526,18 @@ var config3 = once3(() => {
83997
84526
  const baseUrl = getBaseUrlFromEnv();
83998
84527
  return { dataDir, baseUrl };
83999
84528
  });
84529
+ function resolveRecoverActiveRuns(config4) {
84530
+ if (config4.recoverActiveRuns !== void 0) {
84531
+ return config4.recoverActiveRuns;
84532
+ }
84533
+ const raw = process.env.WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS?.toLowerCase();
84534
+ if (raw === "0" || raw === "false")
84535
+ return false;
84536
+ if (raw === "1" || raw === "true")
84537
+ return true;
84538
+ return true;
84539
+ }
84540
+ __name(resolveRecoverActiveRuns, "resolveRecoverActiveRuns");
84000
84541
  function resolveDirectBaseUrl(config4) {
84001
84542
  return config4.baseUrl ?? process.env.WORKFLOW_LOCAL_BASE_URL ?? createWorkflowBaseUrl("http://localhost");
84002
84543
  }
@@ -84290,6 +84831,21 @@ async function writeExclusive(filePath, data) {
84290
84831
  }
84291
84832
  }
84292
84833
  __name(writeExclusive, "writeExclusive");
84834
+ async function promoteExclusive(stagedPath, filePath) {
84835
+ try {
84836
+ await withEnsuredDirectory(path.dirname(filePath), () => withWindowsRetry(() => fs.link(stagedPath, filePath)));
84837
+ return "linked";
84838
+ } catch (error95) {
84839
+ if (error95.code === "EEXIST") {
84840
+ return "exists";
84841
+ }
84842
+ if (error95.code === "ENOENT") {
84843
+ return "missing";
84844
+ }
84845
+ throw error95;
84846
+ }
84847
+ }
84848
+ __name(promoteExclusive, "promoteExclusive");
84293
84849
  async function listJSONFiles(dirPath) {
84294
84850
  return listFilesByExtension(dirPath, ".json");
84295
84851
  }
@@ -85063,6 +85619,104 @@ async function isHookDisposalCommitted(basedir, hookId, tag) {
85063
85619
  return false;
85064
85620
  }
85065
85621
  __name(isHookDisposalCommitted, "isHookDisposalCommitted");
85622
+ function runTerminalMarkerPath(basedir, runId, tag) {
85623
+ const name = tag ? `${runId}.terminal.${tag}` : `${runId}.terminal`;
85624
+ return resolveWithinBase(basedir, ".locks", "runs", name);
85625
+ }
85626
+ __name(runTerminalMarkerPath, "runTerminalMarkerPath");
85627
+ async function isRunTerminalCommitted(basedir, runId, tag) {
85628
+ const candidates = [runTerminalMarkerPath(basedir, runId)];
85629
+ if (tag) {
85630
+ candidates.push(runTerminalMarkerPath(basedir, runId, tag));
85631
+ }
85632
+ for (const markerPath of candidates) {
85633
+ try {
85634
+ await fs2.access(markerPath);
85635
+ return true;
85636
+ } catch (error95) {
85637
+ if (error95.code !== "ENOENT") {
85638
+ throw error95;
85639
+ }
85640
+ }
85641
+ }
85642
+ return false;
85643
+ }
85644
+ __name(isRunTerminalCommitted, "isRunTerminalCommitted");
85645
+ function pendingHookEventDir(basedir, runId, tag) {
85646
+ const name = tag ? `${runId}.pending.${tag}` : `${runId}.pending`;
85647
+ return resolveWithinBase(basedir, ".locks", "runs", name);
85648
+ }
85649
+ __name(pendingHookEventDir, "pendingHookEventDir");
85650
+ function pendingHookEventPath(basedir, runId, eventId, tag) {
85651
+ return path3.join(pendingHookEventDir(basedir, runId, tag), `${eventId}.json`);
85652
+ }
85653
+ __name(pendingHookEventPath, "pendingHookEventPath");
85654
+ async function reapPendingHookEvents(basedir, runId, tag) {
85655
+ const dirs = [pendingHookEventDir(basedir, runId)];
85656
+ if (tag) {
85657
+ dirs.push(pendingHookEventDir(basedir, runId, tag));
85658
+ }
85659
+ for (const dir of dirs) {
85660
+ let entries;
85661
+ try {
85662
+ entries = await fs2.readdir(dir);
85663
+ } catch (error95) {
85664
+ if (error95.code === "ENOENT") {
85665
+ continue;
85666
+ }
85667
+ throw error95;
85668
+ }
85669
+ for (const entry of entries) {
85670
+ try {
85671
+ await withWindowsRetry(() => fs2.unlink(path3.join(dir, entry)));
85672
+ } catch (error95) {
85673
+ if (error95.code !== "ENOENT") {
85674
+ throw error95;
85675
+ }
85676
+ }
85677
+ }
85678
+ await fs2.rmdir(dir).catch(() => {
85679
+ });
85680
+ }
85681
+ }
85682
+ __name(reapPendingHookEvents, "reapPendingHookEvents");
85683
+ async function mintRunDominantEventKey(basedir, runId, tag) {
85684
+ let files = [];
85685
+ try {
85686
+ files = await fs2.readdir(path3.join(basedir, "events"));
85687
+ } catch (error95) {
85688
+ if (error95.code !== "ENOENT") {
85689
+ throw error95;
85690
+ }
85691
+ }
85692
+ const prefix = `${runId}-`;
85693
+ let maxUlid = null;
85694
+ for (const file3 of files) {
85695
+ if (!file3.startsWith(prefix) || !file3.endsWith(".json")) {
85696
+ continue;
85697
+ }
85698
+ const fileId = file3.slice(0, -".json".length);
85699
+ if (!isUntagged(fileId) && !(tag && hasTag(fileId, tag))) {
85700
+ continue;
85701
+ }
85702
+ const candidate = stripTag(fileId).slice(prefix.length);
85703
+ if (!maxUlid || candidate > maxUlid) {
85704
+ maxUlid = candidate;
85705
+ }
85706
+ }
85707
+ let ts = Date.now();
85708
+ if (maxUlid) {
85709
+ try {
85710
+ const maxTs = decodeTime(maxUlid.replace(/^evnt_/, ""));
85711
+ if (ts <= maxTs) {
85712
+ ts = maxTs + 1;
85713
+ }
85714
+ } catch {
85715
+ }
85716
+ }
85717
+ return { eventId: `evnt_${monotonicUlid(ts)}`, createdAt: new Date(ts) };
85718
+ }
85719
+ __name(mintRunDominantEventKey, "mintRunDominantEventKey");
85066
85720
  function hookTokenClaimPath(basedir, token) {
85067
85721
  return path3.join(basedir, "hooks", "tokens", `${hashToken(token)}.json`);
85068
85722
  }
@@ -85321,7 +85975,7 @@ __name(findNewestIndexedHookCreatedEvent, "findNewestIndexedHookCreatedEvent");
85321
85975
  init_dist7();
85322
85976
  init_dist5();
85323
85977
  init_zod2();
85324
- import fs4 from "node:fs/promises";
85978
+ import fs5 from "node:fs/promises";
85325
85979
  import path7 from "node:path";
85326
85980
 
85327
85981
  // ../world-local/dist/storage/filters.js
@@ -85392,7 +86046,7 @@ function isMatchingHookCreatedEvent(event, matches) {
85392
86046
  __name(isMatchingHookCreatedEvent, "isMatchingHookCreatedEvent");
85393
86047
  async function isTerminalRunCache(basedir, runId, tag) {
85394
86048
  const run3 = await readJSONWithFallback(basedir, "runs", runId, WorkflowRunSchema2, tag);
85395
- return run3 ? isTerminalWorkflowRunStatus(run3.status) : false;
86049
+ return run3 ? isTerminalWorkflowRunStatus2(run3.status) : false;
85396
86050
  }
85397
86051
  __name(isTerminalRunCache, "isTerminalRunCache");
85398
86052
  async function findLiveHookCreatedEvent(basedir, index, matches, tag) {
@@ -85550,12 +86204,36 @@ async function deleteAllHooksForRun(basedir, runId) {
85550
86204
  __name(deleteAllHooksForRun, "deleteAllHooksForRun");
85551
86205
 
85552
86206
  // ../world-local/dist/storage/legacy.js
86207
+ init_dist7();
85553
86208
  init_dist5();
86209
+ import fs4 from "node:fs/promises";
86210
+ async function publishLegacyHookReceived(basedir, runId, eventId, serializedEvent, eventPath, currentRun) {
86211
+ if (isTerminalWorkflowRunStatus2(currentRun.status) || await isRunTerminalCommitted(basedir, runId)) {
86212
+ throw new RunExpiredError(`Workflow run "${runId}" is already in a terminal state`);
86213
+ }
86214
+ const stagedPath = pendingHookEventPath(basedir, runId, eventId);
86215
+ await writeExclusive(stagedPath, serializedEvent);
86216
+ try {
86217
+ if (await isRunTerminalCommitted(basedir, runId)) {
86218
+ throw new RunExpiredError(`Workflow run "${runId}" is already in a terminal state`);
86219
+ }
86220
+ const promoted = await promoteExclusive(stagedPath, eventPath);
86221
+ if (promoted !== "linked") {
86222
+ throw new RunExpiredError(`Workflow run "${runId}" is already in a terminal state`);
86223
+ }
86224
+ } finally {
86225
+ await fs4.unlink(stagedPath).catch(() => {
86226
+ });
86227
+ }
86228
+ }
86229
+ __name(publishLegacyHookReceived, "publishLegacyHookReceived");
85554
86230
  async function handleLegacyEvent(basedir, runId, data, currentRun, params) {
85555
86231
  assertSafeEntityId("runId", runId);
85556
86232
  const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
85557
86233
  switch (data.eventType) {
85558
86234
  case "run_cancelled": {
86235
+ await writeExclusive(runTerminalMarkerPath(basedir, runId), "");
86236
+ await reapPendingHookEvents(basedir, runId);
85559
86237
  const now = /* @__PURE__ */ new Date();
85560
86238
  const run3 = {
85561
86239
  runId: currentRun.runId,
@@ -85595,7 +86273,11 @@ async function handleLegacyEvent(basedir, runId, data, currentRun, params) {
85595
86273
  };
85596
86274
  const compositeKey = `${runId}-${eventId}`;
85597
86275
  const eventPath = resolveWithinBase(basedir, "events", `${compositeKey}.json`);
85598
- await writeJSON(eventPath, event);
86276
+ if (data.eventType === "hook_received") {
86277
+ await publishLegacyHookReceived(basedir, runId, eventId, JSON.stringify(event, jsonReplacer, 2), eventPath, currentRun);
86278
+ } else {
86279
+ await writeJSON(eventPath, event);
86280
+ }
85599
86281
  return { event: stripEventDataRefs(event, resolveData) };
85600
86282
  }
85601
86283
  default:
@@ -85629,16 +86311,32 @@ function withRunFileLock(key, fn) {
85629
86311
  }
85630
86312
  __name(withRunFileLock, "withRunFileLock");
85631
86313
  function createRunsStorage(basedir, tag) {
86314
+ const get = /* @__PURE__ */ __name((async (id, params) => {
86315
+ assertSafeEntityId("runId", id);
86316
+ const run3 = await readJSONWithFallback(basedir, "runs", id, WorkflowRunSchema2, tag);
86317
+ if (!run3) {
86318
+ throw new WorkflowRunNotFoundError2(id);
86319
+ }
86320
+ const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
86321
+ return filterRunData(run3, resolveData);
86322
+ }), "get");
85632
86323
  return {
85633
- get: /* @__PURE__ */ __name((async (id, params) => {
85634
- assertSafeEntityId("runId", id);
85635
- const run3 = await readJSONWithFallback(basedir, "runs", id, WorkflowRunSchema2, tag);
85636
- if (!run3) {
85637
- throw new WorkflowRunNotFoundError2(id);
85638
- }
85639
- const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
85640
- return filterRunData(run3, resolveData);
85641
- }), "get"),
86324
+ get,
86325
+ getMany: /* @__PURE__ */ __name((async (ids, params) => {
86326
+ const uniqueIds = [...new Set(ids)];
86327
+ const runs = await Promise.all(uniqueIds.map(async (id) => {
86328
+ try {
86329
+ return await get(id, params);
86330
+ } catch (error95) {
86331
+ if (error95 instanceof WorkflowRunNotFoundError2) {
86332
+ return null;
86333
+ }
86334
+ throw error95;
86335
+ }
86336
+ }));
86337
+ const runById = new Map(uniqueIds.map((id, i) => [id, runs[i]]));
86338
+ return ids.map((id) => runById.get(id) ?? null);
86339
+ }), "getMany"),
85642
86340
  list: /* @__PURE__ */ __name((async (params) => {
85643
86341
  const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
85644
86342
  const result = await paginatedFileSystemQuery({
@@ -85710,6 +86408,13 @@ function createRunsStorage(basedir, tag) {
85710
86408
  __name(createRunsStorage, "createRunsStorage");
85711
86409
 
85712
86410
  // ../world-local/dist/storage/events-storage.js
86411
+ var DEFAULT_MAX_EVENTS_PER_RUN = 25e3;
86412
+ function getMaxEventsPerRun() {
86413
+ const raw = process.env.WORKFLOW_MAX_EVENTS;
86414
+ const parsed = raw !== void 0 ? Number(raw) : Number.NaN;
86415
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_EVENTS_PER_RUN;
86416
+ }
86417
+ __name(getMaxEventsPerRun, "getMaxEventsPerRun");
85713
86418
  var HookTokenClaimSchema = external_exports2.object({
85714
86419
  // The token-claim writer below has always persisted `hookId`, but
85715
86420
  // this read schema previously omitted it, which is the bug fixed
@@ -85751,7 +86456,7 @@ async function isHookTokenClaimReleasable(basedir, claim, tag) {
85751
86456
  if (!owningRun) {
85752
86457
  return true;
85753
86458
  }
85754
- return isTerminalWorkflowRunStatus(owningRun.status);
86459
+ return isTerminalWorkflowRunStatus2(owningRun.status);
85755
86460
  }
85756
86461
  __name(isHookTokenClaimReleasable, "isHookTokenClaimReleasable");
85757
86462
  async function readHookRecoveryMarker(markerPath) {
@@ -86046,7 +86751,7 @@ function createEventsStorage(basedir, tag) {
86046
86751
  }
86047
86752
  const createsChildEntity = isChildEntityCreationEvent(data);
86048
86753
  const lazyStepStart = createsChildEntity && data.eventType === "step_started";
86049
- if (currentRun && isTerminalWorkflowRunStatus(currentRun.status)) {
86754
+ if (currentRun && isTerminalWorkflowRunStatus2(currentRun.status)) {
86050
86755
  if (data.eventType === "run_cancelled" && currentRun.status === "cancelled") {
86051
86756
  const event2 = {
86052
86757
  ...data,
@@ -86059,7 +86764,8 @@ function createEventsStorage(basedir, tag) {
86059
86764
  const resolveData2 = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
86060
86765
  return {
86061
86766
  event: stripEventDataRefs(event2, resolveData2),
86062
- run: currentRun
86767
+ run: currentRun,
86768
+ ...currentRun ? { maxEvents: getMaxEventsPerRun() } : {}
86063
86769
  };
86064
86770
  }
86065
86771
  if (data.eventType === "run_started") {
@@ -86090,7 +86796,7 @@ function createEventsStorage(basedir, tag) {
86090
86796
  if (isTerminalStepStatus(validatedStep.status)) {
86091
86797
  throw new EntityConflictError2(`Cannot modify step in terminal state "${validatedStep.status}"`);
86092
86798
  }
86093
- if (currentRun && isTerminalWorkflowRunStatus(currentRun.status)) {
86799
+ if (currentRun && isTerminalWorkflowRunStatus2(currentRun.status)) {
86094
86800
  if (validatedStep.status !== "running") {
86095
86801
  throw new RunExpiredError(`Cannot modify non-running step on run in terminal state "${currentRun.status}"`);
86096
86802
  }
@@ -86126,6 +86832,13 @@ function createEventsStorage(basedir, tag) {
86126
86832
  let wait;
86127
86833
  let stepCreatedLazily = false;
86128
86834
  let hookEntityWriteOptions;
86835
+ if (isTerminalRunEventType(data.eventType) && currentRun) {
86836
+ await writeExclusive(runTerminalMarkerPath(basedir, effectiveRunId, tag), "");
86837
+ await reapPendingHookEvents(basedir, effectiveRunId, tag);
86838
+ const dominantKey = await mintRunDominantEventKey(basedir, effectiveRunId, tag);
86839
+ eventId = dominantKey.eventId;
86840
+ event = { ...event, eventId, createdAt: dominantKey.createdAt };
86841
+ }
86129
86842
  if (data.eventType === "run_created" && "eventData" in data) {
86130
86843
  const runData = data.eventData;
86131
86844
  validateAttributeChanges2(Object.entries(runData.attributes ?? {}).map(([key, value]) => ({
@@ -86159,7 +86872,7 @@ function createEventsStorage(basedir, tag) {
86159
86872
  } else if (data.eventType === "run_started") {
86160
86873
  if (currentRun) {
86161
86874
  if (currentRun.status === "running") {
86162
- return { run: currentRun };
86875
+ return { run: currentRun, maxEvents: getMaxEventsPerRun() };
86163
86876
  }
86164
86877
  run3 = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
86165
86878
  runId: currentRun.runId,
@@ -86591,7 +87304,7 @@ function createEventsStorage(basedir, tag) {
86591
87304
  }
86592
87305
  const existingWait = await readJSONWithFallback(basedir, "waits", waitCompositeKey, WaitSchema2, tag);
86593
87306
  if (!existingWait) {
86594
- await fs4.unlink(lockPath).catch(() => {
87307
+ await fs5.unlink(lockPath).catch(() => {
86595
87308
  });
86596
87309
  throw new WorkflowWorldError2(`Wait "${data.correlationId}" not found`);
86597
87310
  }
@@ -86609,7 +87322,34 @@ function createEventsStorage(basedir, tag) {
86609
87322
  const compositeKey = `${effectiveRunId}-${eventId}`;
86610
87323
  const eventPath = taggedPath(basedir, "events", compositeKey, tag);
86611
87324
  const serializedEvent = JSON.stringify(event, jsonReplacer, 2);
86612
- const eventPublished = await writeExclusive(eventPath, serializedEvent);
87325
+ let eventPublished;
87326
+ if (data.eventType === "hook_received") {
87327
+ const terminalByMarker = await isRunTerminalCommitted(basedir, effectiveRunId, tag);
87328
+ const runNow = terminalByMarker ? null : await readJSONWithFallback(basedir, "runs", effectiveRunId, WorkflowRunSchema2, tag);
87329
+ if (terminalByMarker || runNow && isTerminalWorkflowRunStatus2(runNow.status)) {
87330
+ throw new RunExpiredError(`Workflow run "${effectiveRunId}" is already in a terminal state`);
87331
+ }
87332
+ const stagedPath = pendingHookEventPath(basedir, effectiveRunId, eventId, tag);
87333
+ const staged = await writeExclusive(stagedPath, serializedEvent);
87334
+ if (!staged) {
87335
+ throw new EntityConflictError2(`Event "${eventId}" already exists for run "${effectiveRunId}"`);
87336
+ }
87337
+ try {
87338
+ if (await isRunTerminalCommitted(basedir, effectiveRunId, tag)) {
87339
+ throw new RunExpiredError(`Workflow run "${effectiveRunId}" is already in a terminal state`);
87340
+ }
87341
+ const promoted = await promoteExclusive(stagedPath, eventPath);
87342
+ if (promoted === "missing") {
87343
+ throw new RunExpiredError(`Workflow run "${effectiveRunId}" is already in a terminal state`);
87344
+ }
87345
+ eventPublished = promoted === "linked";
87346
+ } finally {
87347
+ await deleteJSON(stagedPath).catch(() => {
87348
+ });
87349
+ }
87350
+ } else {
87351
+ eventPublished = await writeExclusive(eventPath, serializedEvent);
87352
+ }
86613
87353
  if (!eventPublished) {
86614
87354
  if (data.eventType === "hook_created" && data.correlationId) {
86615
87355
  await repairHookEntityFromPersistedEvent(basedir, effectiveRunId, data.correlationId, eventId, tag);
@@ -86664,7 +87404,9 @@ function createEventsStorage(basedir, tag) {
86664
87404
  events,
86665
87405
  cursor,
86666
87406
  hasMore,
86667
- ...stepCreatedLazily ? { stepCreated: true } : {}
87407
+ ...stepCreatedLazily ? { stepCreated: true } : {},
87408
+ // Per-run event ceiling (mirrors the Vercel World).
87409
+ ...run3 ? { maxEvents: getMaxEventsPerRun() } : {}
86668
87410
  };
86669
87411
  }
86670
87412
  __name(createImpl, "createImpl");
@@ -86800,7 +87542,7 @@ __name(createStorage, "createStorage");
86800
87542
  init_node2();
86801
87543
  init_zod2();
86802
87544
  import { EventEmitter } from "node:events";
86803
- import fs5 from "node:fs/promises";
87545
+ import fs6 from "node:fs/promises";
86804
87546
  import path9 from "node:path";
86805
87547
  var monotonicUlid2 = monotonicFactory2(() => Math.random());
86806
87548
  var RunStreamsSchema = external_exports2.object({
@@ -86828,7 +87570,7 @@ function deserializeChunk(serialized) {
86828
87570
  __name(deserializeChunk, "deserializeChunk");
86829
87571
  async function listChunkEntries(chunksDir) {
86830
87572
  try {
86831
- return await fs5.readdir(chunksDir);
87573
+ return await fs6.readdir(chunksDir);
86832
87574
  } catch (error95) {
86833
87575
  if (error95.code === "ENOENT")
86834
87576
  return [];
@@ -87193,7 +87935,7 @@ function createWorld(args) {
87193
87935
  const tag = mergedConfig.tag;
87194
87936
  const queue = createQueue(mergedConfig);
87195
87937
  const { clearCache: clearStorageCache, ...storage } = createStorage(mergedConfig.dataDir, tag);
87196
- const recoverActiveRuns = mergedConfig.recoverActiveRuns ?? true;
87938
+ const recoverActiveRuns = resolveRecoverActiveRuns(mergedConfig);
87197
87939
  return {
87198
87940
  specVersion: SPEC_VERSION_CURRENT2,
87199
87941
  ...queue,
@@ -87255,7 +87997,7 @@ function createWorld(args) {
87255
87997
  const fullIndexDir = path10.join(basedir, "hooks", indexDir);
87256
87998
  let keyDirEntries;
87257
87999
  try {
87258
- keyDirEntries = await fs6.readdir(fullIndexDir, {
88000
+ keyDirEntries = await fs7.readdir(fullIndexDir, {
87259
88001
  withFileTypes: true
87260
88002
  });
87261
88003
  } catch {
@@ -87267,12 +88009,12 @@ function createWorld(args) {
87267
88009
  await Promise.all(taggedEntryFiles.map((f) => deleteJSON(path10.join(keyDir, f))));
87268
88010
  }));
87269
88011
  }
87270
- await fs6.rm(path10.join(basedir, ".locks"), { recursive: true, force: true }).catch(() => {
88012
+ await fs7.rm(path10.join(basedir, ".locks"), { recursive: true, force: true }).catch(() => {
87271
88013
  });
87272
88014
  const chunksDir = path10.join(basedir, "streams", "chunks");
87273
88015
  let streamDirEntries;
87274
88016
  try {
87275
- streamDirEntries = await fs6.readdir(chunksDir, {
88017
+ streamDirEntries = await fs7.readdir(chunksDir, {
87276
88018
  withFileTypes: true
87277
88019
  });
87278
88020
  } catch {
@@ -87281,7 +88023,7 @@ function createWorld(args) {
87281
88023
  await Promise.all(streamDirEntries.filter((entry) => entry.isDirectory()).map(async (entry) => {
87282
88024
  const streamChunkDir = path10.join(chunksDir, entry.name);
87283
88025
  const taggedBinFiles = await listTaggedFilesByExtension(streamChunkDir, tag, ".bin");
87284
- await Promise.all(taggedBinFiles.map((f) => fs6.unlink(path10.join(streamChunkDir, f)).catch(() => {
88026
+ await Promise.all(taggedBinFiles.map((f) => fs7.unlink(path10.join(streamChunkDir, f)).catch(() => {
87285
88027
  })));
87286
88028
  }));
87287
88029
  clearCreatedFilesCache();
@@ -87429,6 +88171,9 @@ function classifyRunError(err) {
87429
88171
  if (CorruptedEventLogError.is(err)) {
87430
88172
  return RUN_ERROR_CODES2.CORRUPTED_EVENT_LOG;
87431
88173
  }
88174
+ if (MaxEventsExceededError.is(err)) {
88175
+ return RUN_ERROR_CODES2.MAX_EVENTS_EXCEEDED;
88176
+ }
87432
88177
  if (isWorldContractError(err) || isRetryableWorldError2(err)) {
87433
88178
  return RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR;
87434
88179
  }
@@ -87630,6 +88375,7 @@ var RUNTIME_ERROR_HINT = "This is an internal workflow SDK error, not a bug in y
87630
88375
  var CORRUPTED_EVENT_LOG_HINT = "The workflow event log contains orphaned or mismatched events and cannot be replayed. This is an internal workflow SDK error; please report it with the runId.";
87631
88376
  var REPLAY_TIMEOUT_HINT = 'The workflow replay between step boundaries took too long. This bounds workflow-VM and event-log replay time only \u2014 step bodies (`"use step"` functions) are excluded. This usually means the event log is unusually large or the workflow function is doing heavy synchronous work in workflow code outside of step bodies. Override the default budget via the WORKFLOW_REPLAY_TIMEOUT_MS env var if needed.';
87632
88377
  var MAX_DELIVERIES_HINT = "The workflow queue exceeded its max-delivery budget. This usually indicates a persistent runtime failure \u2014 check the most recent stack traces for the underlying cause.";
88378
+ var MAX_EVENTS_HINT = "The workflow exceeded the maximum number of events per run. This usually means unbounded work in the workflow function \u2014 e.g. a loop that keeps creating steps without terminating. Break long-running workflows into child workflows to stay under the limit.";
87633
88379
  var WORLD_CONTRACT_HINT = "The workflow backend returned data that violated the SDK contract. This is not retryable; please report it with the stack trace and runId.";
87634
88380
  function describeError(err, errorCode) {
87635
88381
  const effectiveCode = errorCode ?? classifyRunError(err);
@@ -87675,6 +88421,13 @@ function describeError(err, errorCode) {
87675
88421
  hint: MAX_DELIVERIES_HINT
87676
88422
  };
87677
88423
  }
88424
+ if (effectiveCode === RUN_ERROR_CODES2.MAX_EVENTS_EXCEEDED) {
88425
+ return {
88426
+ attribution: "user",
88427
+ errorCode: effectiveCode,
88428
+ hint: MAX_EVENTS_HINT
88429
+ };
88430
+ }
87678
88431
  if (effectiveCode === RUN_ERROR_CODES2.CORRUPTED_EVENT_LOG) {
87679
88432
  return {
87680
88433
  attribution: "sdk",
@@ -87697,6 +88450,129 @@ __name(describeError, "describeError");
87697
88450
  init_global2();
87698
88451
  init_logger2();
87699
88452
 
88453
+ // ../core/dist/replay-payload-cache.js
88454
+ init_serialization4();
88455
+ var MAX_MEMOIZED_PRIMITIVE_LENGTH = 4096;
88456
+ function isMemoizablePrimitive(value) {
88457
+ if (value === null)
88458
+ return true;
88459
+ const type = typeof value;
88460
+ if (type === "object" || type === "function")
88461
+ return false;
88462
+ if (type === "string") {
88463
+ return value.length <= MAX_MEMOIZED_PRIMITIVE_LENGTH;
88464
+ }
88465
+ if (type === "bigint") {
88466
+ return value.toString().length <= MAX_MEMOIZED_PRIMITIVE_LENGTH;
88467
+ }
88468
+ return true;
88469
+ }
88470
+ __name(isMemoizablePrimitive, "isMemoizablePrimitive");
88471
+ var ReplayPayloadCache = class {
88472
+ static {
88473
+ __name(this, "ReplayPayloadCache");
88474
+ }
88475
+ encryptionKey;
88476
+ preparer;
88477
+ preparedPayloads = /* @__PURE__ */ new Map();
88478
+ primitiveStepResults = /* @__PURE__ */ new Map();
88479
+ constructor(encryptionKey, preparer = prepareReplayPayload) {
88480
+ this.encryptionKey = encryptionKey;
88481
+ this.preparer = preparer;
88482
+ }
88483
+ /**
88484
+ * Start every missing binary preparation before workflow execution. Failures
88485
+ * are intentionally retained: the ordered event consumer must observe the
88486
+ * original rejection before that entry becomes retryable.
88487
+ */
88488
+ async prewarm(workflowRun, events) {
88489
+ const preparations = [];
88490
+ const start3 = /* @__PURE__ */ __name((cacheKey, value) => {
88491
+ if (!(value instanceof Uint8Array))
88492
+ return;
88493
+ if (this.preparedPayloads.has(cacheKey))
88494
+ return;
88495
+ preparations.push(this.ensurePreparation(cacheKey, value));
88496
+ }, "start");
88497
+ start3(this.workflowInputKey(workflowRun.runId), workflowRun.input);
88498
+ for (const event of events) {
88499
+ switch (event.eventType) {
88500
+ case "step_completed":
88501
+ start3(this.eventPayloadKey(event.eventId, "result"), event.eventData?.result);
88502
+ break;
88503
+ case "step_failed":
88504
+ start3(this.eventPayloadKey(event.eventId, "error"), event.eventData?.error);
88505
+ break;
88506
+ case "hook_received":
88507
+ start3(this.eventPayloadKey(event.eventId, "payload"), event.eventData?.payload);
88508
+ break;
88509
+ }
88510
+ }
88511
+ await Promise.allSettled(preparations);
88512
+ }
88513
+ /** Return the workflow input after shared host-side preparation. */
88514
+ prepareWorkflowInput(workflowRun) {
88515
+ return this.consumePreparation(this.workflowInputKey(workflowRun.runId), workflowRun.input);
88516
+ }
88517
+ /**
88518
+ * Return an event payload after shared host-side preparation. A rejected
88519
+ * preparation is evicted only after this ordered consumer requests it, so a
88520
+ * later replay can retry without hiding the original failure.
88521
+ */
88522
+ prepareEventPayload(eventId, field, value) {
88523
+ return this.consumePreparation(this.eventPayloadKey(eventId, field), value);
88524
+ }
88525
+ /**
88526
+ * Reuse final step values only when sharing them across VMs is unobservable.
88527
+ * Objects and large strings/bigints always run `hydrate` again, producing a
88528
+ * fresh VM-specific value from the separately cached prepared payload.
88529
+ */
88530
+ async getStepResult(eventId, hydrate) {
88531
+ if (this.primitiveStepResults.has(eventId)) {
88532
+ return this.primitiveStepResults.get(eventId);
88533
+ }
88534
+ const value = await hydrate();
88535
+ if (isMemoizablePrimitive(value)) {
88536
+ this.primitiveStepResults.set(eventId, value);
88537
+ }
88538
+ return value;
88539
+ }
88540
+ /**
88541
+ * Consumer-facing lookup. Binary payloads share preparation; legacy values
88542
+ * bypass the cache because their flattened representation may be mutated.
88543
+ */
88544
+ consumePreparation(cacheKey, value) {
88545
+ if (!(value instanceof Uint8Array))
88546
+ return this.runPreparation(value);
88547
+ const preparation = this.ensurePreparation(cacheKey, value);
88548
+ void preparation.catch(() => {
88549
+ if (this.preparedPayloads.get(cacheKey) === preparation) {
88550
+ this.preparedPayloads.delete(cacheKey);
88551
+ }
88552
+ });
88553
+ return preparation;
88554
+ }
88555
+ /** Start preparation once and share the exact in-flight promise. */
88556
+ ensurePreparation(cacheKey, value) {
88557
+ const cached3 = this.preparedPayloads.get(cacheKey);
88558
+ if (cached3)
88559
+ return cached3;
88560
+ const preparation = this.runPreparation(value);
88561
+ this.preparedPayloads.set(cacheKey, preparation);
88562
+ return preparation;
88563
+ }
88564
+ /** Normalize synchronous and asynchronous preparers to one promise contract. */
88565
+ async runPreparation(value) {
88566
+ return this.preparer(value, this.encryptionKey);
88567
+ }
88568
+ workflowInputKey(runId) {
88569
+ return `run:${runId}:input`;
88570
+ }
88571
+ eventPayloadKey(eventId, field) {
88572
+ return `event:${eventId}:${field}`;
88573
+ }
88574
+ };
88575
+
87700
88576
  // ../core/dist/runtime/constants.js
87701
88577
  init_dist5();
87702
88578
  init_logger2();
@@ -87785,6 +88661,22 @@ function getMaxInlineSteps() {
87785
88661
  return parsed;
87786
88662
  }
87787
88663
  __name(getMaxInlineSteps, "getMaxInlineSteps");
88664
+ var warnedMaxEventsValues = /* @__PURE__ */ new Set();
88665
+ function getMaxEventsOverride() {
88666
+ const raw = process.env.WORKFLOW_MAX_EVENTS_OVERRIDE;
88667
+ if (!raw)
88668
+ return void 0;
88669
+ const parsed = Number(raw);
88670
+ if (!Number.isInteger(parsed) || parsed <= 0) {
88671
+ if (!warnedMaxEventsValues.has(raw)) {
88672
+ warnedMaxEventsValues.add(raw);
88673
+ runtimeLogger2.warn("Ignoring WORKFLOW_MAX_EVENTS_OVERRIDE: not a positive integer; using server limit", { raw });
88674
+ }
88675
+ return void 0;
88676
+ }
88677
+ return parsed;
88678
+ }
88679
+ __name(getMaxEventsOverride, "getMaxEventsOverride");
87788
88680
  function isOptimisticInlineStartEnabled() {
87789
88681
  const raw = process.env.WORKFLOW_OPTIMISTIC_INLINE_START;
87790
88682
  if (raw === void 0 || raw === "")
@@ -87955,13 +88847,155 @@ async function handleReplayBudgetExhausted(args) {
87955
88847
  }
87956
88848
  __name(handleReplayBudgetExhausted, "handleReplayBudgetExhausted");
87957
88849
 
88850
+ // ../world-vercel/dist/run-id/codec.js
88851
+ var ENCODING3 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
88852
+ var DECODE_TABLE = (() => {
88853
+ const table = new Int8Array(128).fill(-1);
88854
+ for (let i = 0; i < ENCODING3.length; i++) {
88855
+ table[ENCODING3.charCodeAt(i)] = i;
88856
+ }
88857
+ for (let i = 0; i < ENCODING3.length; i++) {
88858
+ const lower = ENCODING3[i].toLowerCase();
88859
+ if (lower !== ENCODING3[i]) {
88860
+ table[lower.charCodeAt(0)] = i;
88861
+ }
88862
+ }
88863
+ return table;
88864
+ })();
88865
+ var ULID_LENGTH = 26;
88866
+ var ULID_BYTE_LENGTH = 16;
88867
+ var TAG_BIT_MASK = 128;
88868
+ var REGION_MASK = 252;
88869
+ var VERSION_HIGH_MASK = 3;
88870
+ var VERSION_LOW_MASK = 224;
88871
+ var REGION_BYTE_INDEX = 6;
88872
+ var VERSION_LOW_BYTE_INDEX = 7;
88873
+ var VERSION_BIT_WIDTH = 5;
88874
+ var REGION_BIT_WIDTH = 6;
88875
+ var MAX_VERSION = (1 << VERSION_BIT_WIDTH) - 1;
88876
+ var MAX_REGION = (1 << REGION_BIT_WIDTH) - 1;
88877
+ function ulidToBytes(ulid8) {
88878
+ if (typeof ulid8 !== "string") {
88879
+ throw new TypeError(`Expected ULID string, got ${typeof ulid8}`);
88880
+ }
88881
+ if (ulid8.length !== ULID_LENGTH) {
88882
+ throw new Error(`Invalid ULID length: expected ${ULID_LENGTH}, got ${ulid8.length}`);
88883
+ }
88884
+ const values = new Uint8Array(ULID_LENGTH);
88885
+ for (let i = 0; i < ULID_LENGTH; i++) {
88886
+ const code3 = ulid8.charCodeAt(i);
88887
+ const v = code3 < 128 ? DECODE_TABLE[code3] : -1;
88888
+ if (v < 0) {
88889
+ throw new Error(`Invalid Crockford-Base32 character at index ${i}: ${JSON.stringify(ulid8[i])}`);
88890
+ }
88891
+ values[i] = v;
88892
+ }
88893
+ if ((values[0] & 24) !== 0) {
88894
+ throw new Error(`Invalid ULID: top 2 bits must be zero (first char > '7'): ${JSON.stringify(ulid8[0])}`);
88895
+ }
88896
+ const out = new Uint8Array(ULID_BYTE_LENGTH);
88897
+ let bitBuf = values[0] & 7;
88898
+ let bitCount = 3;
88899
+ let outIdx = 0;
88900
+ for (let i = 1; i < ULID_LENGTH; i++) {
88901
+ bitBuf = bitBuf << 5 | values[i];
88902
+ bitCount += 5;
88903
+ while (bitCount >= 8) {
88904
+ bitCount -= 8;
88905
+ out[outIdx++] = bitBuf >> bitCount & 255;
88906
+ }
88907
+ }
88908
+ if (outIdx !== ULID_BYTE_LENGTH || bitCount !== 0) {
88909
+ throw new Error("Internal error: ULID bit packing did not consume cleanly");
88910
+ }
88911
+ return out;
88912
+ }
88913
+ __name(ulidToBytes, "ulidToBytes");
88914
+ function bytesToUlid(bytes) {
88915
+ if (bytes.length !== ULID_BYTE_LENGTH) {
88916
+ throw new Error(`Invalid byte length: expected ${ULID_BYTE_LENGTH}, got ${bytes.length}`);
88917
+ }
88918
+ let bitBuf = 0;
88919
+ let bitCount = 0;
88920
+ bitBuf = 0;
88921
+ bitCount = 2;
88922
+ let out = "";
88923
+ for (let i = 0; i < ULID_BYTE_LENGTH; i++) {
88924
+ bitBuf = bitBuf << 8 | bytes[i];
88925
+ bitCount += 8;
88926
+ while (bitCount >= 5) {
88927
+ bitCount -= 5;
88928
+ out += ENCODING3[bitBuf >> bitCount & 31];
88929
+ }
88930
+ }
88931
+ if (out.length !== ULID_LENGTH || bitCount !== 0) {
88932
+ throw new Error("Internal error: ULID bit packing did not flush cleanly");
88933
+ }
88934
+ return out;
88935
+ }
88936
+ __name(bytesToUlid, "bytesToUlid");
88937
+
88938
+ // ../world-vercel/dist/run-id/regions.js
88939
+ var REGION_IDS = {
88940
+ unknown: 0,
88941
+ iad1: 1,
88942
+ sfo1: 2,
88943
+ pdx1: 3,
88944
+ cle1: 4,
88945
+ yul1: 5,
88946
+ gru1: 6,
88947
+ dub1: 7,
88948
+ lhr1: 8,
88949
+ cdg1: 9,
88950
+ fra1: 10,
88951
+ bru1: 11,
88952
+ arn1: 12,
88953
+ hel1: 13,
88954
+ zrh1: 14,
88955
+ cpt1: 15,
88956
+ dxb1: 16,
88957
+ bom1: 17,
88958
+ sin1: 18,
88959
+ hkg1: 19,
88960
+ hnd1: 20,
88961
+ icn1: 21,
88962
+ kix1: 22,
88963
+ syd1: 23
88964
+ };
88965
+ var REGION_CODES_BY_ID = new Map(Object.entries(REGION_IDS).filter((entry) => entry[0] !== "unknown").map(([code3, id]) => [id, code3]));
88966
+ function lookupRegion(regionId) {
88967
+ return REGION_CODES_BY_ID.get(regionId) ?? null;
88968
+ }
88969
+ __name(lookupRegion, "lookupRegion");
88970
+
88971
+ // ../world-vercel/dist/run-id/index.js
88972
+ function decode5(taggedUlid) {
88973
+ const bytes = ulidToBytes(taggedUlid);
88974
+ const tagged = (bytes[0] & TAG_BIT_MASK) !== 0;
88975
+ bytes[0] = bytes[0] & ~TAG_BIT_MASK;
88976
+ const ulid8 = bytesToUlid(bytes);
88977
+ if (!tagged) {
88978
+ return { tagged: false, ulid: ulid8, version: null, regionId: null, region: null };
88979
+ }
88980
+ const regionId = (bytes[REGION_BYTE_INDEX] & REGION_MASK) >> 2;
88981
+ const version5 = (bytes[REGION_BYTE_INDEX] & VERSION_HIGH_MASK) << 3 | (bytes[VERSION_LOW_BYTE_INDEX] & VERSION_LOW_MASK) >> 5;
88982
+ return {
88983
+ tagged: true,
88984
+ ulid: ulid8,
88985
+ version: version5,
88986
+ regionId,
88987
+ region: lookupRegion(regionId)
88988
+ };
88989
+ }
88990
+ __name(decode5, "decode");
88991
+
87958
88992
  // ../core/dist/runtime/run-id-time.js
87959
88993
  init_node2();
87960
88994
  var RUN_ID_PREFIX = "wrun_";
87961
88995
  function runIdCreatedAt(runId) {
87962
88996
  const ulidPart = runId.startsWith(RUN_ID_PREFIX) ? runId.slice(RUN_ID_PREFIX.length) : runId;
87963
88997
  try {
87964
- return decodeTime(ulidPart);
88998
+ return decodeTime(decode5(ulidPart).ulid);
87965
88999
  } catch {
87966
89000
  return void 0;
87967
89001
  }
@@ -88107,6 +89141,7 @@ __name(getPortLazy, "getPortLazy");
88107
89141
  init_helpers2();
88108
89142
 
88109
89143
  // ../core/dist/runtime/step-latency.js
89144
+ var MAX_CLOCK_SKEW_MS = 6e4;
88110
89145
  var TTFS_DISQUALIFYING_EVENT_TYPES = /* @__PURE__ */ new Set([
88111
89146
  "step_created",
88112
89147
  "step_started",
@@ -88148,6 +89183,7 @@ function computeStepLatencyTracking(params) {
88148
89183
  stepCount = terminalStepIds.size;
88149
89184
  eventCount = events.length;
88150
89185
  }
89186
+ const rsfsEligible = ttfsEligible && params.runStartedReceivedAtMs !== void 0;
88151
89187
  if (!ttfsEligible && prevStepEndMs === void 0) {
88152
89188
  return void 0;
88153
89189
  }
@@ -88159,6 +89195,10 @@ function computeStepLatencyTracking(params) {
88159
89195
  preStepBlockingMs: preStepAttrStartMs !== void 0 ? params.preStepBlockingBeforeAttrMs ?? 0 : params.preStepBlockingMs,
88160
89196
  ...preStepAttrStartMs !== void 0 ? { preStepAttrStartMs } : {}
88161
89197
  } : {},
89198
+ ...rsfsEligible ? {
89199
+ rsfsAnchorMs: params.runStartedReceivedAtMs,
89200
+ replayMs: params.replayMs
89201
+ } : {},
88162
89202
  ...prevStepEndMs !== void 0 ? { prevStepEndMs, stepCount, eventCount } : {},
88163
89203
  turbo: params.turbo
88164
89204
  };
@@ -88170,8 +89210,12 @@ function computeStepLatencyEventData(params) {
88170
89210
  return void 0;
88171
89211
  }
88172
89212
  const ttfsEndMs = tracking.preStepAttrStartMs ?? params.stepCodeStartedAtMs;
88173
- const ttfs = tracking.ttfsAnchorMs !== void 0 ? Math.max(0, ttfsEndMs - tracking.ttfsAnchorMs - (tracking.preStepBlockingMs ?? 0)) : void 0;
88174
- const stso = tracking.prevStepEndMs !== void 0 ? Math.max(0, params.stepCodeStartedAtMs - tracking.prevStepEndMs) : void 0;
89213
+ const rawTtfs = tracking.ttfsAnchorMs !== void 0 ? ttfsEndMs - tracking.ttfsAnchorMs - (tracking.preStepBlockingMs ?? 0) : void 0;
89214
+ const ttfs = rawTtfs !== void 0 && rawTtfs >= -MAX_CLOCK_SKEW_MS ? Math.max(0, rawTtfs) : void 0;
89215
+ const rawStso = tracking.prevStepEndMs !== void 0 ? params.stepCodeStartedAtMs - tracking.prevStepEndMs : void 0;
89216
+ const stso = rawStso !== void 0 && rawStso >= -MAX_CLOCK_SKEW_MS ? Math.max(0, rawStso) : void 0;
89217
+ const rsfs = tracking.rsfsAnchorMs !== void 0 && params.stepStartPostSentAtMs !== void 0 ? Math.max(0, params.stepStartPostSentAtMs - tracking.rsfsAnchorMs) : void 0;
89218
+ const finalSchedulingReplay = tracking.replayMs !== void 0 ? Math.max(0, tracking.replayMs) : void 0;
88175
89219
  if (ttfs === void 0 && stso === void 0) {
88176
89220
  return void 0;
88177
89221
  }
@@ -88187,6 +89231,8 @@ function computeStepLatencyEventData(params) {
88187
89231
  ...stso !== void 0 ? { stso } : {},
88188
89232
  ...stso !== void 0 && tracking.stepCount !== void 0 ? { stepCount: tracking.stepCount } : {},
88189
89233
  ...stso !== void 0 && tracking.eventCount !== void 0 ? { eventCount: tracking.eventCount } : {},
89234
+ ...rsfs !== void 0 ? { rsfs } : {},
89235
+ ...finalSchedulingReplay !== void 0 ? { finalSchedulingReplay } : {},
88190
89236
  optimizations
88191
89237
  };
88192
89238
  }
@@ -88284,6 +89330,47 @@ async function executeStep(params) {
88284
89330
  span?.setAttributes({
88285
89331
  ...StepMaxRetries2(maxRetries)
88286
89332
  });
89333
+ if (params.authoritativeAttempt !== void 0 && params.authoritativeAttempt > maxRetries + 1) {
89334
+ const retryCount = maxRetries;
89335
+ const errorMessage = `Step "${stepName}" exceeded max retries (${retryCount} ${pluralize2("retry", "retries", retryCount)})`;
89336
+ stepLogger2.error("Step exceeded max retries", {
89337
+ workflowRunId,
89338
+ stepName,
89339
+ stepId,
89340
+ attempt: params.authoritativeAttempt,
89341
+ maxRetries
89342
+ });
89343
+ try {
89344
+ await world.events.create(workflowRunId, {
89345
+ eventType: "step_failed",
89346
+ specVersion: SPEC_VERSION_CURRENT2,
89347
+ correlationId: stepId,
89348
+ eventData: {
89349
+ stepName,
89350
+ error: await dehydrateStepError(new FatalError2(errorMessage), workflowRunId, await getEncryptionKey(), [], globalThis, compression)
89351
+ }
89352
+ });
89353
+ } catch (err) {
89354
+ if (EntityConflictError2.is(err)) {
89355
+ runtimeLogger2.info("Tried failing step for exceeded retries, but step has already finished.", {
89356
+ workflowRunId,
89357
+ stepId,
89358
+ stepName,
89359
+ message: err instanceof Error ? err.message : String(err)
89360
+ });
89361
+ return { type: "skipped" };
89362
+ }
89363
+ if (RunExpiredError.is(err)) {
89364
+ return { type: "gone" };
89365
+ }
89366
+ throw err;
89367
+ }
89368
+ span?.setAttributes({
89369
+ ...StepStatus2("failed"),
89370
+ ...StepRetryExhausted2(true)
89371
+ });
89372
+ return { type: "failed" };
89373
+ }
88287
89374
  const startErrorToResult = /* @__PURE__ */ __name((err) => {
88288
89375
  if (ThrottleError2.is(err)) {
88289
89376
  const retryAfter = Math.max(1, typeof err.retryAfter === "number" ? err.retryAfter : 1);
@@ -88320,8 +89407,12 @@ async function executeStep(params) {
88320
89407
  }
88321
89408
  return void 0;
88322
89409
  }, "startErrorToResult");
88323
- const optimisticStart = params.lazyStepInput !== void 0 && (isOptimisticInlineStartEnabled() || params.forceOptimisticStart === true && !isOptimisticInlineStartExplicitlyDisabled());
89410
+ const optimisticStart = params.lazyStepInput !== void 0 && // Stale-sensitive guarded batches await the claim so the 412 fence
89411
+ // covers the body, not just durable writes — see
89412
+ // StepExecutorParams.suppressOptimisticStart.
89413
+ params.suppressOptimisticStart !== true && (isOptimisticInlineStartEnabled() || params.forceOptimisticStart === true && !isOptimisticInlineStartExplicitlyDisabled());
88324
89414
  let step;
89415
+ let stepStartPostSentAtMs;
88325
89416
  let optimisticStartSettled;
88326
89417
  const reconcileOptimisticStart = /* @__PURE__ */ __name(async () => {
88327
89418
  if (!optimisticStartSettled)
@@ -88335,18 +89426,29 @@ async function executeStep(params) {
88335
89426
  return mapped;
88336
89427
  }, "reconcileOptimisticStart");
88337
89428
  if (optimisticStart) {
88338
- const startedPromise = (params.runReadyBarrier ?? Promise.resolve()).then(() => world.events.create(workflowRunId, {
88339
- eventType: "step_started",
88340
- specVersion: SPEC_VERSION_CURRENT2,
88341
- correlationId: stepId,
88342
- eventData: {
88343
- stepName,
88344
- workflowName,
88345
- input: params.lazyStepInput,
88346
- // Inline-ownership stamp — see StepExecutorParams.ownerMessageId.
88347
- ...params.ownerMessageId !== void 0 ? { ownerMessageId: params.ownerMessageId } : {}
88348
- }
88349
- }));
89429
+ const startedPromise = (params.runReadyBarrier ?? Promise.resolve()).then(() => {
89430
+ stepStartPostSentAtMs = Date.now();
89431
+ return world.events.create(
89432
+ workflowRunId,
89433
+ {
89434
+ eventType: "step_started",
89435
+ specVersion: SPEC_VERSION_CURRENT2,
89436
+ correlationId: stepId,
89437
+ eventData: {
89438
+ stepName,
89439
+ workflowName,
89440
+ input: params.lazyStepInput,
89441
+ // Inline-ownership stamp — see StepExecutorParams.ownerMessageId.
89442
+ ...params.ownerMessageId !== void 0 ? { ownerMessageId: params.ownerMessageId } : {}
89443
+ }
89444
+ },
89445
+ // Guard the claim — see StepExecutorParams.stateUpdatedAt. A stale
89446
+ // (412) rejection surfaces via reconcileOptimisticStart as a
89447
+ // non-translatable error: the body result is discarded and the
89448
+ // rejection propagates to the caller.
89449
+ params.stateUpdatedAt !== void 0 ? { stateUpdatedAt: params.stateUpdatedAt } : void 0
89450
+ );
89451
+ });
88350
89452
  optimisticStartSettled = startedPromise.then(() => ({ ok: true }), (err) => ({ ok: false, err }));
88351
89453
  const now = /* @__PURE__ */ new Date();
88352
89454
  step = {
@@ -88363,17 +89465,26 @@ async function executeStep(params) {
88363
89465
  } else {
88364
89466
  try {
88365
89467
  const ownershipStamp = params.ownerMessageId !== void 0 ? { ownerMessageId: params.ownerMessageId } : {};
88366
- const startResult = await world.events.create(workflowRunId, {
88367
- eventType: "step_started",
88368
- specVersion: SPEC_VERSION_CURRENT2,
88369
- correlationId: stepId,
88370
- eventData: params.lazyStepInput !== void 0 ? {
88371
- stepName,
88372
- workflowName,
88373
- input: params.lazyStepInput,
88374
- ...ownershipStamp
88375
- } : { stepName, ...ownershipStamp }
88376
- });
89468
+ stepStartPostSentAtMs = Date.now();
89469
+ const startResult = await world.events.create(
89470
+ workflowRunId,
89471
+ {
89472
+ eventType: "step_started",
89473
+ specVersion: SPEC_VERSION_CURRENT2,
89474
+ correlationId: stepId,
89475
+ eventData: params.lazyStepInput !== void 0 ? {
89476
+ stepName,
89477
+ workflowName,
89478
+ input: params.lazyStepInput,
89479
+ ...ownershipStamp
89480
+ } : { stepName, ...ownershipStamp }
89481
+ },
89482
+ // Guard the claim — see StepExecutorParams.stateUpdatedAt. A stale
89483
+ // (412) rejection is intentionally NOT translated by
89484
+ // startErrorToResult below, so it propagates to the caller for a
89485
+ // fresh replay.
89486
+ params.stateUpdatedAt !== void 0 ? { stateUpdatedAt: params.stateUpdatedAt } : void 0
89487
+ );
88377
89488
  if (!startResult.step) {
88378
89489
  throw new WorkflowRuntimeError2(`step_started event for "${stepId}" did not return step entity`);
88379
89490
  }
@@ -88442,6 +89553,19 @@ async function executeStep(params) {
88442
89553
  const ops = [];
88443
89554
  let opsSettled = true;
88444
89555
  let latencyEventData;
89556
+ const backfillOptimisticRsfs = /* @__PURE__ */ __name(() => {
89557
+ if (!latencyEventData || latencyEventData.rsfs !== void 0)
89558
+ return;
89559
+ const anchorMs = params.latencyTracking?.rsfsAnchorMs;
89560
+ if (anchorMs === void 0 || stepStartPostSentAtMs === void 0)
89561
+ return;
89562
+ latencyEventData.rsfs = Math.max(0, stepStartPostSentAtMs - anchorMs);
89563
+ if (span) {
89564
+ span.setAttributes({
89565
+ ...StepRsfsMs2(latencyEventData.rsfs)
89566
+ });
89567
+ }
89568
+ }, "backfillOptimisticRsfs");
88445
89569
  try {
88446
89570
  const attempt = step.attempt;
88447
89571
  if (!step.startedAt) {
@@ -88470,12 +89594,15 @@ async function executeStep(params) {
88470
89594
  stepCodeStartedAtMs: executionStartTime,
88471
89595
  attempt,
88472
89596
  lazyStepStart: params.lazyStepInput !== void 0,
88473
- optimisticStart
89597
+ optimisticStart,
89598
+ stepStartPostSentAtMs
88474
89599
  });
88475
89600
  if (latencyEventData) {
88476
89601
  span?.setAttributes({
88477
89602
  ...latencyEventData.ttfs !== void 0 ? StepTtfsMs2(latencyEventData.ttfs) : {},
88478
89603
  ...latencyEventData.stso !== void 0 ? StepStsoMs2(latencyEventData.stso) : {},
89604
+ ...latencyEventData.rsfs !== void 0 ? StepRsfsMs2(latencyEventData.rsfs) : {},
89605
+ ...latencyEventData.finalSchedulingReplay !== void 0 ? StepFinalSchedulingReplayMs2(latencyEventData.finalSchedulingReplay) : {},
88479
89606
  ...StepLatencyOptimizations2(latencyEventData.optimizations ?? [])
88480
89607
  });
88481
89608
  }
@@ -88496,6 +89623,7 @@ async function executeStep(params) {
88496
89623
  features: { encryption: !!encryptionKey }
88497
89624
  },
88498
89625
  workflowDeploymentId: params.workflowDeploymentId,
89626
+ rootRunId: params.rootRunId,
88499
89627
  ops,
88500
89628
  preCompletionOps,
88501
89629
  closureVars: hydratedInput.closureVars,
@@ -88565,6 +89693,7 @@ async function executeStep(params) {
88565
89693
  const reconcile = await reconcileOptimisticStart();
88566
89694
  if (reconcile)
88567
89695
  return reconcile;
89696
+ backfillOptimisticRsfs();
88568
89697
  }
88569
89698
  if (preCompletionOps.length > 0) {
88570
89699
  await Promise.all(preCompletionOps).catch(() => {
@@ -88575,6 +89704,7 @@ async function executeStep(params) {
88575
89704
  const reconcile = await reconcileOptimisticStart();
88576
89705
  if (reconcile)
88577
89706
  return reconcile;
89707
+ backfillOptimisticRsfs();
88578
89708
  }
88579
89709
  if (preCompletionOps.length > 0) {
88580
89710
  await Promise.all(preCompletionOps).catch(() => {
@@ -88782,6 +89912,9 @@ async function executeStep(params) {
88782
89912
  }
88783
89913
  __name(executeStep, "executeStep");
88784
89914
 
89915
+ // ../core/dist/runtime.js
89916
+ init_private2();
89917
+
88785
89918
  // ../core/dist/runtime/step-ownership.js
88786
89919
  function isStepOwnershipActive(step) {
88787
89920
  return step.hasCreatedEvent === true && step.ownerMessageId !== void 0 && step.sawRetrying !== true;
@@ -88853,9 +89986,10 @@ init_logger2();
88853
89986
  init_serialization4();
88854
89987
  init_semantic_conventions2();
88855
89988
  init_util4();
88856
- async function createHookEvent({ world, runId, hookEvent, queueItem, requestId }) {
89989
+ init_helpers2();
89990
+ async function createHookEvent({ runId, hookEvent, queueItem, requestId, createEvent }) {
88857
89991
  try {
88858
- const result = await world.events.create(runId, hookEvent, {
89992
+ const result = await createEvent(hookEvent, {
88859
89993
  requestId
88860
89994
  });
88861
89995
  if (result.event?.eventType === "hook_conflict") {
@@ -88893,7 +90027,7 @@ async function createHookEvent({ world, runId, hookEvent, queueItem, requestId }
88893
90027
  }
88894
90028
  }
88895
90029
  __name(createHookEvent, "createHookEvent");
88896
- async function handleSuspension({ suspension, world, run: run3, span, requestId, runReadyBarrier }) {
90030
+ async function handleSuspension({ suspension, world, run: run3, span, requestId, eventLog, runReadyBarrier }) {
88897
90031
  const runId = run3.runId;
88898
90032
  const ensureRunReady = /* @__PURE__ */ __name(async () => {
88899
90033
  if (runReadyBarrier) {
@@ -88903,6 +90037,12 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
88903
90037
  }
88904
90038
  }
88905
90039
  }, "ensureRunReady");
90040
+ const createGuarded = /* @__PURE__ */ __name((data, params) => {
90041
+ if (!eventLog) {
90042
+ return world.events.create(runId, data, params);
90043
+ }
90044
+ return withPreconditionRetry(runId, eventLog, (stateUpdatedAt) => world.events.create(runId, data, { ...params, stateUpdatedAt }));
90045
+ }, "createGuarded");
88906
90046
  const stepItems = suspension.steps.filter((item) => item.type === "step");
88907
90047
  const allHookItems = suspension.steps.filter((item) => item.type === "hook");
88908
90048
  const waitItems = suspension.steps.filter((item) => item.type === "wait");
@@ -88933,7 +90073,7 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
88933
90073
  }
88934
90074
  };
88935
90075
  try {
88936
- await world.events.create(runId, hookDisposedEvent, { requestId });
90076
+ await createGuarded(hookDisposedEvent, { requestId });
88937
90077
  } catch (err) {
88938
90078
  if (EntityConflictError2.is(err)) {
88939
90079
  runtimeLogger2.info("Hook already disposed, skipping duplicate disposal", {
@@ -88976,17 +90116,18 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
88976
90116
  correlationId: queueItem.correlationId,
88977
90117
  eventData: {
88978
90118
  token: queueItem.token,
90119
+ tokenRetentionUntil: queueItem.tokenRetentionUntil,
88979
90120
  metadata: hookMetadata,
88980
90121
  isWebhook: queueItem.isWebhook ?? false,
88981
90122
  ...queueItem.isSystem && { isSystem: true }
88982
90123
  }
88983
90124
  };
88984
90125
  const result = await createHookEvent({
88985
- world,
88986
90126
  runId,
88987
90127
  hookEvent,
88988
90128
  queueItem,
88989
- requestId
90129
+ requestId,
90130
+ createEvent: createGuarded
88990
90131
  });
88991
90132
  hasHookConflict ||= result.hasHookConflict;
88992
90133
  hasAwaitedHookCreation ||= result.hasAwaitedHookCreation;
@@ -89005,7 +90146,7 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
89005
90146
  await Promise.all(hooksNeedingAbort.map(async (queueItem) => {
89006
90147
  try {
89007
90148
  const abortPayload = await dehydrateStepArguments2({ aborted: true, reason: queueItem.abortReason }, runId, encryptionKey, suspension.globalThis, false, compression);
89008
- await world.events.create(runId, {
90149
+ await createGuarded({
89009
90150
  eventType: "hook_received",
89010
90151
  specVersion: SPEC_VERSION_CURRENT2,
89011
90152
  correlationId: queueItem.correlationId,
@@ -89070,7 +90211,7 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
89070
90211
  };
89071
90212
  try {
89072
90213
  await ensureRunReady();
89073
- await world.events.create(runId, stepEvent, { requestId });
90214
+ await createGuarded(stepEvent, { requestId });
89074
90215
  createdStepCorrelationIds.add(queueItem.correlationId);
89075
90216
  } catch (err) {
89076
90217
  if (EntityConflictError2.is(err)) {
@@ -89099,7 +90240,7 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
89099
90240
  };
89100
90241
  try {
89101
90242
  await ensureRunReady();
89102
- await world.events.create(runId, waitEvent, { requestId });
90243
+ await createGuarded(waitEvent, { requestId });
89103
90244
  } catch (err) {
89104
90245
  if (EntityConflictError2.is(err)) {
89105
90246
  runtimeLogger2.info("Wait already exists, continuing", {
@@ -89277,7 +90418,7 @@ var StringReader = class {
89277
90418
  return idx === -1 ? buffer3.length : idx;
89278
90419
  }
89279
90420
  };
89280
- function decode5(mappings) {
90421
+ function decode6(mappings) {
89281
90422
  const { length } = mappings;
89282
90423
  const reader = new StringReader(mappings);
89283
90424
  const decoded = [];
@@ -89319,7 +90460,7 @@ function decode5(mappings) {
89319
90460
  } while (reader.pos <= length);
89320
90461
  return decoded;
89321
90462
  }
89322
- __name(decode5, "decode");
90463
+ __name(decode6, "decode");
89323
90464
  function sort(line) {
89324
90465
  line.sort(sortComparator);
89325
90466
  }
@@ -89674,7 +90815,7 @@ function cast(map3) {
89674
90815
  __name(cast, "cast");
89675
90816
  function decodedMappings(map3) {
89676
90817
  var _a3;
89677
- return (_a3 = cast(map3))._decoded || (_a3._decoded = decode5(cast(map3)._encoded));
90818
+ return (_a3 = cast(map3))._decoded || (_a3._decoded = decode6(cast(map3)._encoded));
89678
90819
  }
89679
90820
  __name(decodedMappings, "decodedMappings");
89680
90821
  function originalPositionFor(map3, needle) {
@@ -89825,42 +90966,6 @@ function remapErrorStack(stack, filename, workflowCode2) {
89825
90966
  }
89826
90967
  __name(remapErrorStack, "remapErrorStack");
89827
90968
 
89828
- // ../core/dist/step-hydration-cache.js
89829
- var MAX_MEMOIZED_PRIMITIVE_LENGTH = 4096;
89830
- function isMemoizablePrimitive(value) {
89831
- if (value === null)
89832
- return true;
89833
- const t = typeof value;
89834
- if (t === "object" || t === "function")
89835
- return false;
89836
- if (t === "string") {
89837
- return value.length <= MAX_MEMOIZED_PRIMITIVE_LENGTH;
89838
- }
89839
- if (t === "bigint") {
89840
- return value.toString().length <= MAX_MEMOIZED_PRIMITIVE_LENGTH;
89841
- }
89842
- return true;
89843
- }
89844
- __name(isMemoizablePrimitive, "isMemoizablePrimitive");
89845
- function createStepHydrationCache() {
89846
- return /* @__PURE__ */ new Map();
89847
- }
89848
- __name(createStepHydrationCache, "createStepHydrationCache");
89849
- async function getOrHydrateStepReturnValue(cache, eventId, hydrate) {
89850
- if (!cache || eventId === void 0) {
89851
- return hydrate();
89852
- }
89853
- if (cache.has(eventId)) {
89854
- return cache.get(eventId);
89855
- }
89856
- const value = await hydrate();
89857
- if (isMemoizablePrimitive(value)) {
89858
- cache.set(eventId, value);
89859
- }
89860
- return value;
89861
- }
89862
- __name(getOrHydrateStepReturnValue, "getOrHydrateStepReturnValue");
89863
-
89864
90969
  // ../core/dist/runtime.js
89865
90970
  init_semantic_conventions2();
89866
90971
  init_telemetry2();
@@ -89990,7 +91095,8 @@ function createUseStep(ctx) {
89990
91095
  ctx.invocationsQueue.delete(event.correlationId);
89991
91096
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
89992
91097
  try {
89993
- const hydrated = await hydrateStepError(event.eventData.error, ctx.runId, ctx.encryptionKey, ctx.globalThis);
91098
+ const prepared = await ctx.replayPayloadCache.prepareEventPayload(event.eventId, "error", event.eventData.error);
91099
+ const hydrated = await hydrateStepError(event.eventData.error, ctx.runId, ctx.encryptionKey, ctx.globalThis, {}, prepared);
89994
91100
  reject(hydrated);
89995
91101
  } catch (hydrateErr) {
89996
91102
  stepLogger2.error("Failed to hydrate step_failed error", {
@@ -90009,7 +91115,10 @@ function createUseStep(ctx) {
90009
91115
  ctx.pendingDeliveries++;
90010
91116
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
90011
91117
  try {
90012
- const hydratedResult = await getOrHydrateStepReturnValue(ctx.stepHydrationCache, completedEventId, () => hydrateStepReturnValue(serializedResult, ctx.runId, ctx.encryptionKey, ctx.globalThis));
91118
+ const hydratedResult = await ctx.replayPayloadCache.getStepResult(completedEventId, async () => {
91119
+ const prepared = await ctx.replayPayloadCache.prepareEventPayload(completedEventId, "result", serializedResult);
91120
+ return await hydrateStepReturnValue(serializedResult, ctx.runId, ctx.encryptionKey, ctx.globalThis, {}, prepared);
91121
+ });
90013
91122
  resolve2(hydratedResult);
90014
91123
  } catch (error95) {
90015
91124
  reject(error95);
@@ -90657,13 +91766,13 @@ __name(createSetAttributes, "createSetAttributes");
90657
91766
 
90658
91767
  // ../core/dist/workflow/hook.js
90659
91768
  init_dist7();
91769
+ init_dist8();
90660
91770
  init_dist6();
91771
+ init_class_serialization2();
90661
91772
  init_events_consumer2();
90662
91773
  init_global2();
90663
91774
  init_logger2();
90664
91775
  init_private2();
90665
- init_dist8();
90666
- init_class_serialization2();
90667
91776
  init_serialization4();
90668
91777
  function createConflictingRun(ctx, conflictingRunId) {
90669
91778
  if (typeof conflictingRunId !== "string") {
@@ -90682,13 +91791,21 @@ function createCreateHook(ctx) {
90682
91791
  if (options.token === "") {
90683
91792
  throw new Error("`createHook()` was called with an empty string token. Pass a non-empty token, or omit the `token` option to use a randomly generated one.");
90684
91793
  }
91794
+ if (options.isWebhook === true && options.experimental_minRetention !== void 0) {
91795
+ throw new Error("Webhook hooks do not support `experimental_minRetention`. Use a non-webhook `createHook()` with `resumeHook()`.");
91796
+ }
91797
+ if (options.experimental_minRetention !== void 0 && ctx.worldCapabilities?.hookRetention?.active !== true) {
91798
+ throw new FatalError2("The configured World does not support `experimental_minRetention` for Hooks.");
91799
+ }
90685
91800
  const correlationId = `hook_${ctx.generateUlid()}`;
90686
91801
  const token = options.token ?? ctx.generateNanoid();
91802
+ const tokenRetentionUntil = options.experimental_minRetention === void 0 ? void 0 : parseDurationToDate2(options.experimental_minRetention);
90687
91803
  const isWebhook = options.isWebhook ?? false;
90688
91804
  ctx.invocationsQueue.set(correlationId, {
90689
91805
  type: "hook",
90690
91806
  correlationId,
90691
91807
  token,
91808
+ tokenRetentionUntil,
90692
91809
  metadata: options.metadata,
90693
91810
  isWebhook
90694
91811
  });
@@ -90726,6 +91843,7 @@ function createCreateHook(ctx) {
90726
91843
  const queueItem = ctx.invocationsQueue.get(correlationId);
90727
91844
  if (queueItem && queueItem.type === "hook") {
90728
91845
  queueItem.hasCreatedEvent = true;
91846
+ queueItem.tokenRetentionUntil = event.eventData.tokenRetentionUntil;
90729
91847
  }
90730
91848
  hasCreated = true;
90731
91849
  const pendingGetConflictPromises = getConflictPromises.slice();
@@ -90772,7 +91890,8 @@ function createCreateHook(ctx) {
90772
91890
  let hydrateOutcome;
90773
91891
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
90774
91892
  try {
90775
- const payload = await hydrateStepReturnValue(event.eventData.payload, ctx.runId, ctx.encryptionKey, ctx.globalThis);
91893
+ const prepared = await ctx.replayPayloadCache.prepareEventPayload(event.eventId, "payload", event.eventData.payload);
91894
+ const payload = await hydrateStepReturnValue(event.eventData.payload, ctx.runId, ctx.encryptionKey, ctx.globalThis, {}, prepared);
90776
91895
  hydrateOutcome = { ok: true, value: payload };
90777
91896
  } catch (error95) {
90778
91897
  hydrateOutcome = { ok: false, error: error95 };
@@ -90802,7 +91921,8 @@ function createCreateHook(ctx) {
90802
91921
  ctx.pendingDeliveries++;
90803
91922
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
90804
91923
  try {
90805
- const payload = await hydrateStepReturnValue(event.eventData.payload, ctx.runId, ctx.encryptionKey, ctx.globalThis);
91924
+ const prepared = await ctx.replayPayloadCache.prepareEventPayload(event.eventId, "payload", event.eventData.payload);
91925
+ const payload = await hydrateStepReturnValue(event.eventData.payload, ctx.runId, ctx.encryptionKey, ctx.globalThis, {}, prepared);
90806
91926
  outcome = { ok: true, value: payload };
90807
91927
  } catch (error95) {
90808
91928
  outcome = { ok: false, error: error95 };
@@ -91025,7 +92145,7 @@ async function drainPendingQueueItems(runId, pendingQueue, vmGlobalThis, workflo
91025
92145
  }
91026
92146
  }
91027
92147
  __name(drainPendingQueueItems, "drainPendingQueueItems");
91028
- async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, stepHydrationCache, runReadyBarrier) {
92148
+ async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, replayPayloadCache = new ReplayPayloadCache(encryptionKey), runReadyBarrier, worldCapabilities) {
91029
92149
  return trace4(`workflow.run ${workflowRun.workflowName}`, async (span) => {
91030
92150
  span?.setAttributes({
91031
92151
  ...WorkflowName2(workflowRun.workflowName),
@@ -91060,6 +92180,7 @@ async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, st
91060
92180
  const workflowContext = {
91061
92181
  runId: workflowRun.runId,
91062
92182
  encryptionKey,
92183
+ worldCapabilities,
91063
92184
  globalThis: vmGlobalThis,
91064
92185
  onWorkflowError: workflowDiscontinuation.reject,
91065
92186
  eventsConsumer,
@@ -91085,7 +92206,7 @@ async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, st
91085
92206
  },
91086
92207
  pendingDeliveries: 0,
91087
92208
  pendingDeliveryBarriers: /* @__PURE__ */ new Map(),
91088
- stepHydrationCache
92209
+ replayPayloadCache
91089
92210
  };
91090
92211
  workflowContext.eventsConsumer.subscribe((event) => {
91091
92212
  if (!event) {
@@ -91511,7 +92632,8 @@ Learn more: https://workflow-sdk.dev/err/${ERROR_SLUGS2.FETCH_IN_WORKFLOW_FUNCTI
91511
92632
  }
91512
92633
  let args = [];
91513
92634
  workflowContext.promiseQueue = workflowContext.promiseQueue.then(async () => {
91514
- args = await hydrateWorkflowArguments(workflowRun.input, workflowRun.runId, encryptionKey, vmGlobalThis);
92635
+ const prepared = await replayPayloadCache.prepareWorkflowInput(workflowRun);
92636
+ args = await hydrateWorkflowArguments(workflowRun.input, workflowRun.runId, encryptionKey, vmGlobalThis, {}, prepared);
91515
92637
  });
91516
92638
  await workflowContext.promiseQueue;
91517
92639
  span?.setAttributes({
@@ -91585,6 +92707,7 @@ init_capabilities2();
91585
92707
  init_encryption3();
91586
92708
  init_logger2();
91587
92709
  init_serialization4();
92710
+ init_context_storage2();
91588
92711
  init_semantic_conventions2();
91589
92712
  init_telemetry2();
91590
92713
  init_version3();
@@ -91906,6 +93029,13 @@ var Run2 = class _Run2 {
91906
93029
  };
91907
93030
 
91908
93031
  // ../core/dist/runtime.js
93032
+ function clampMaxEvents(serverValue) {
93033
+ const override = getMaxEventsOverride();
93034
+ if (override === void 0)
93035
+ return serverValue;
93036
+ return serverValue === void 0 ? override : Math.min(serverValue, override);
93037
+ }
93038
+ __name(clampMaxEvents, "clampMaxEvents");
91909
93039
  function getWorkflowSetupErrorCode(err) {
91910
93040
  if (WorkflowRuntimeError2.is(err)) {
91911
93041
  return RUN_ERROR_CODES2.RUNTIME_ERROR;
@@ -91961,7 +93091,24 @@ function hasRecordedTerminalRunEvent(events, runId) {
91961
93091
  return true;
91962
93092
  }
91963
93093
  __name(hasRecordedTerminalRunEvent, "hasRecordedTerminalRunEvent");
91964
- function hasOpenHookOrWait(events) {
93094
+ function countStepStartedEvents(events, stepId) {
93095
+ if (!events) {
93096
+ return 0;
93097
+ }
93098
+ let count2 = 0;
93099
+ for (const e of events) {
93100
+ if (e.eventType === "step_started" && e.correlationId === stepId) {
93101
+ count2++;
93102
+ }
93103
+ }
93104
+ return count2;
93105
+ }
93106
+ __name(countStepStartedEvents, "countStepStartedEvents");
93107
+ function rootRunIdFrom(attributes, runId) {
93108
+ return attributes?.[ROOT_RUN_ID_ATTRIBUTE2] ?? runId;
93109
+ }
93110
+ __name(rootRunIdFrom, "rootRunIdFrom");
93111
+ function openHookAndWaitState(events) {
91965
93112
  const disposedHookIds = /* @__PURE__ */ new Set();
91966
93113
  const completedWaitIds = /* @__PURE__ */ new Set();
91967
93114
  for (const e of events) {
@@ -91971,17 +93118,20 @@ function hasOpenHookOrWait(events) {
91971
93118
  completedWaitIds.add(e.correlationId);
91972
93119
  }
91973
93120
  }
93121
+ let openHook = false;
93122
+ let openWait = false;
91974
93123
  for (const e of events) {
91975
93124
  if (e.eventType === "hook_created" && !disposedHookIds.has(e.correlationId)) {
91976
- return true;
91977
- }
91978
- if (e.eventType === "wait_created" && !completedWaitIds.has(e.correlationId)) {
91979
- return true;
93125
+ openHook = true;
93126
+ } else if (e.eventType === "wait_created" && !completedWaitIds.has(e.correlationId)) {
93127
+ openWait = true;
91980
93128
  }
93129
+ if (openHook && openWait)
93130
+ break;
91981
93131
  }
91982
- return false;
93132
+ return { openHook, openWait };
91983
93133
  }
91984
- __name(hasOpenHookOrWait, "hasOpenHookOrWait");
93134
+ __name(openHookAndWaitState, "openHookAndWaitState");
91985
93135
  function workflowEntrypoint(workflowCode2, options) {
91986
93136
  setWorkflowBasePath(options?.basePath);
91987
93137
  const NO_INLINE_REPLAY_AFTER_MS = Number(process.env.WORKFLOW_V2_TIMEOUT_MS) || 12e4;
@@ -92057,13 +93207,14 @@ function workflowEntrypoint(workflowCode2, options) {
92057
93207
  let loopIteration = 0;
92058
93208
  let cachedEvents = null;
92059
93209
  let eventsCursor = null;
92060
- const stepHydrationCache = createStepHydrationCache();
92061
93210
  let pendingInlineDelta = null;
92062
93211
  let workflowRun;
93212
+ let maxEventsLimit;
92063
93213
  let workflowStartedAt = -1;
92064
93214
  let preloadedEvents;
92065
93215
  let preloadedEventsCursor;
92066
93216
  let invocationStartedClean;
93217
+ let runStartedReceivedAtMs;
92067
93218
  let preStepBlockingMs = 0;
92068
93219
  let preStepBlockingBeforeAttrMs;
92069
93220
  const turbo = isTurboEnabled() && runInput !== void 0 && metadata.attempt === 1 && incomingStepId === void 0 && !replayDivergence;
@@ -92100,12 +93251,22 @@ function workflowEntrypoint(workflowCode2, options) {
92100
93251
  }, "reinvoke");
92101
93252
  if (incomingStepId && incomingStepName) {
92102
93253
  try {
92103
- const bgRun = await world.runs.get(runId);
93254
+ const bgRun = await world.runs.get(runId, {
93255
+ resolveData: "none"
93256
+ });
92104
93257
  if (bgRun.status !== "running") {
92105
93258
  runtimeLogger2.debug("Run already finished, skipping background step", { workflowRunId: runId, status: bgRun.status });
92106
93259
  return;
92107
93260
  }
92108
93261
  const bgStartedAt = bgRun.startedAt ? +bgRun.startedAt : Date.now();
93262
+ let bgAuthoritativeAttempt = metadata.attempt;
93263
+ const bgMaxRetries = getStepFunction2(incomingStepName)?.maxRetries ?? DEFAULT_STEP_MAX_RETRIES;
93264
+ if (metadata.attempt > bgMaxRetries + 1) {
93265
+ const loaded = await loadWorkflowRunEvents(runId);
93266
+ cachedEvents = loaded.events;
93267
+ eventsCursor = loaded.cursor;
93268
+ bgAuthoritativeAttempt = countStepStartedEvents(cachedEvents, incomingStepId) + 1;
93269
+ }
92109
93270
  replayBudget.pause();
92110
93271
  let stepResult;
92111
93272
  try {
@@ -92115,9 +93276,14 @@ function workflowEntrypoint(workflowCode2, options) {
92115
93276
  workflowDeploymentId: bgRun.deploymentId,
92116
93277
  workflowName,
92117
93278
  workflowStartedAt: bgStartedAt,
93279
+ rootRunId: rootRunIdFrom(bgRun.attributes, runId),
92118
93280
  stepId: incomingStepId,
92119
93281
  stepName: incomingStepName,
92120
- runSpecVersion: bgRun.specVersion
93282
+ runSpecVersion: bgRun.specVersion,
93283
+ // Retry ceiling: the queue delivery count as a fast
93284
+ // gate, verified against the recorded step_started
93285
+ // count once it crosses the ceiling (see above).
93286
+ authoritativeAttempt: bgAuthoritativeAttempt
92121
93287
  }));
92122
93288
  } finally {
92123
93289
  replayBudget.resume();
@@ -92164,7 +93330,30 @@ function workflowEntrypoint(workflowCode2, options) {
92164
93330
  }
92165
93331
  }
92166
93332
  runtimeLogger2.debug("All parallel steps done, replaying inline after background step", { workflowRunId: runId });
92167
- workflowRun = bgRun;
93333
+ const runCreatedEvent = cachedEvents.find((event) => event.eventType === "run_created");
93334
+ let replayInput;
93335
+ if (runCreatedEvent) {
93336
+ replayInput = runCreatedEvent.eventData.input;
93337
+ } else {
93338
+ if (!isLegacySpecVersion2(bgRun.specVersion)) {
93339
+ throw new WorkflowRuntimeError2(`Workflow run "${runId}" has no "run_created" event`);
93340
+ }
93341
+ const legacyRun = await world.runs.get(runId, {
93342
+ resolveData: "all"
93343
+ });
93344
+ if (legacyRun.status !== "running") {
93345
+ return;
93346
+ }
93347
+ replayInput = legacyRun.input;
93348
+ }
93349
+ workflowRun = {
93350
+ ...bgRun,
93351
+ input: replayInput,
93352
+ status: "running",
93353
+ output: void 0,
93354
+ error: void 0,
93355
+ completedAt: void 0
93356
+ };
92168
93357
  workflowStartedAt = bgStartedAt;
92169
93358
  } else {
92170
93359
  return;
@@ -92228,6 +93417,12 @@ function workflowEntrypoint(workflowCode2, options) {
92228
93417
  { requestId, skipPreload: true }
92229
93418
  );
92230
93419
  runReadyBarrier = startedPromise;
93420
+ startedPromise.then((r) => {
93421
+ const limit = clampMaxEvents(r?.maxEvents);
93422
+ if (limit !== void 0)
93423
+ maxEventsLimit = limit;
93424
+ }, () => {
93425
+ });
92231
93426
  startedPromise.catch(() => {
92232
93427
  });
92233
93428
  preloadedEvents = [];
@@ -92258,6 +93453,7 @@ function workflowEntrypoint(workflowCode2, options) {
92258
93453
  updatedAt: now
92259
93454
  };
92260
93455
  workflowStartedAt = +now;
93456
+ runStartedReceivedAtMs = +now;
92261
93457
  span?.setAttributes({
92262
93458
  ...WorkflowRunStatus2("running"),
92263
93459
  ...WorkflowStartedAt2(workflowStartedAt)
@@ -92270,6 +93466,8 @@ function workflowEntrypoint(workflowCode2, options) {
92270
93466
  throw new WorkflowRuntimeError2(`Event creation for 'run_started' did not return the run entity for run "${runId}"`);
92271
93467
  }
92272
93468
  workflowRun = result.run;
93469
+ maxEventsLimit = clampMaxEvents(result.maxEvents);
93470
+ runStartedReceivedAtMs = Date.now();
92273
93471
  if (result.events && result.events.length > 0 && result.hasMore !== true) {
92274
93472
  preloadedEvents = result.events;
92275
93473
  preloadedEventsCursor = result.cursor;
@@ -92314,6 +93512,7 @@ function workflowEntrypoint(workflowCode2, options) {
92314
93512
  }
92315
93513
  const getEncryptionKey = memoizeEncryptionKey(world, workflowRun);
92316
93514
  const encryptionKey = await getEncryptionKey();
93515
+ const replayPayloadCache = new ReplayPayloadCache(encryptionKey);
92317
93516
  while (true) {
92318
93517
  loopIteration++;
92319
93518
  if (replayBudget.isExhausted()) {
@@ -92406,10 +93605,15 @@ function workflowEntrypoint(workflowCode2, options) {
92406
93605
  }
92407
93606
  }));
92408
93607
  for (const waitEvent of waitsToComplete) {
93608
+ const waitLog = {
93609
+ events,
93610
+ cursor: eventsCursor
93611
+ };
92409
93612
  try {
92410
- await world.events.create(runId, waitEvent, {
92411
- requestId
92412
- });
93613
+ await withPreconditionRetry(runId, waitLog, (stateUpdatedAt) => world.events.create(runId, waitEvent, {
93614
+ requestId,
93615
+ stateUpdatedAt
93616
+ }));
92413
93617
  } catch (err) {
92414
93618
  if (EntityConflictError2.is(err)) {
92415
93619
  runtimeLogger2.info("Wait already completed, skipping", {
@@ -92419,6 +93623,8 @@ function workflowEntrypoint(workflowCode2, options) {
92419
93623
  continue;
92420
93624
  }
92421
93625
  throw err;
93626
+ } finally {
93627
+ eventsCursor = waitLog.cursor;
92422
93628
  }
92423
93629
  }
92424
93630
  if (waitsToComplete.length > 0) {
@@ -92449,6 +93655,9 @@ function workflowEntrypoint(workflowCode2, options) {
92449
93655
  if (hasRecordedTerminalRunEvent(events, runId)) {
92450
93656
  return;
92451
93657
  }
93658
+ if (maxEventsLimit !== void 0 && events.length >= maxEventsLimit) {
93659
+ throw new MaxEventsExceededError(events.length, maxEventsLimit);
93660
+ }
92452
93661
  cachedEvents = events;
92453
93662
  invocationStartedClean ??= events.every((e) => e.eventType === "run_created" || e.eventType === "run_started" || e.eventType === "attr_set");
92454
93663
  preInlineWriteCursor = eventsCursor;
@@ -92458,18 +93667,21 @@ function workflowEntrypoint(workflowCode2, options) {
92458
93667
  eventCount: events.length
92459
93668
  });
92460
93669
  replayStart = Date.now();
93670
+ const payloadPrewarm = replayPayloadCache.prewarm(workflowRun, events);
92461
93671
  const result = await runWorkflow(
92462
93672
  workflowCode2,
92463
93673
  workflowRun,
92464
93674
  events,
92465
93675
  encryptionKey,
92466
- stepHydrationCache,
93676
+ replayPayloadCache,
92467
93677
  // Turbo: the end-of-run drain inside runWorkflow commits
92468
93678
  // fire-and-forget `*_created` events before the terminal
92469
93679
  // `awaitRunReady()` below, so gate those writes on the
92470
93680
  // backgrounded run_started too. Undefined outside turbo.
92471
- runReadyBarrier
93681
+ runReadyBarrier,
93682
+ world.capabilities
92472
93683
  );
93684
+ await payloadPrewarm;
92473
93685
  runtimeLogger2.debug("Workflow replay completed", {
92474
93686
  workflowRunId: runId,
92475
93687
  loopIteration,
@@ -92481,7 +93693,10 @@ function workflowEntrypoint(workflowCode2, options) {
92481
93693
  eventType: "run_completed",
92482
93694
  specVersion: SPEC_VERSION_CURRENT2,
92483
93695
  eventData: { output: result }
92484
- }, { requestId });
93696
+ }, {
93697
+ requestId,
93698
+ stateUpdatedAt: stateUpdatedAtForCreate(events)
93699
+ });
92485
93700
  } catch (err) {
92486
93701
  if (EntityConflictError2.is(err) || RunExpiredError.is(err)) {
92487
93702
  runtimeLogger2.info("Tried completing workflow run, but run has already finished.", { workflowRunId: runId, message: err.message });
@@ -92495,10 +93710,11 @@ function workflowEntrypoint(workflowCode2, options) {
92495
93710
  return;
92496
93711
  } catch (err) {
92497
93712
  if (WorkflowSuspension2.is(err)) {
93713
+ const replayDurationMs = Date.now() - replayStart;
92498
93714
  runtimeLogger2.debug("Workflow suspended", {
92499
93715
  workflowRunId: runId,
92500
93716
  loopIteration,
92501
- replayMs: Date.now() - replayStart,
93717
+ replayMs: replayDurationMs,
92502
93718
  steps: err.stepCount,
92503
93719
  hooks: err.hookCount,
92504
93720
  waits: err.waitCount
@@ -92508,6 +93724,13 @@ function workflowEntrypoint(workflowCode2, options) {
92508
93724
  runtimeLogger2.debug(suspensionMessage);
92509
93725
  }
92510
93726
  const suspensionStart = Date.now();
93727
+ if (!cachedEvents) {
93728
+ throw new Error("Invariant violation: workflow suspended before its event log was loaded");
93729
+ }
93730
+ const suspensionLog = {
93731
+ events: cachedEvents,
93732
+ cursor: eventsCursor
93733
+ };
92511
93734
  let suspensionResult;
92512
93735
  try {
92513
93736
  suspensionResult = await handleSuspension({
@@ -92516,9 +93739,14 @@ function workflowEntrypoint(workflowCode2, options) {
92516
93739
  run: workflowRun,
92517
93740
  span,
92518
93741
  requestId,
93742
+ eventLog: suspensionLog,
92519
93743
  runReadyBarrier
92520
93744
  });
92521
93745
  } catch (suspensionError) {
93746
+ if (PreconditionFailedError.is(suspensionError)) {
93747
+ runtimeLogger2.warn("Suspension event creation rejected as stale after reload retries; re-invoking run for a fresh replay", { workflowRunId: runId, loopIteration });
93748
+ return await reinvoke(0);
93749
+ }
92522
93750
  if (!FatalError2.is(suspensionError)) {
92523
93751
  throw suspensionError;
92524
93752
  }
@@ -92558,6 +93786,7 @@ function workflowEntrypoint(workflowCode2, options) {
92558
93786
  });
92559
93787
  return;
92560
93788
  }
93789
+ eventsCursor = suspensionLog.cursor;
92561
93790
  preStepBlockingMs += suspensionResult.hookCreationMs;
92562
93791
  if (suspensionResult.hasAttributeEvents && preStepBlockingBeforeAttrMs === void 0) {
92563
93792
  preStepBlockingBeforeAttrMs = preStepBlockingMs;
@@ -92661,12 +93890,17 @@ function workflowEntrypoint(workflowCode2, options) {
92661
93890
  }
92662
93891
  return;
92663
93892
  }
92664
- const requestInlineDelta = typeof preInlineWriteCursor === "string" && err.stepCount === 1 && err.hookCount === 0 && err.waitCount === 0 && pendingSteps.length === 1 && lazyInlineSteps.length === 1 && ownedRecoverySteps.length === 0 && !suspensionResult.waitTimeout && !hasOpenHookOrWait(cachedEvents ?? []);
92665
- const forceOptimisticStart = turbo && !suspensionResult.waitTimeout && !suspensionResult.hasHookEvents && !suspensionResult.hasAttributeEvents && !suspensionResult.hasAwaitedHookCreation && !hasOpenHookOrWait(cachedEvents ?? []);
93893
+ const openHookWaitState = openHookAndWaitState(cachedEvents ?? []);
93894
+ const guardEnforced = isPreconditionGuardEnabled() && world.capabilities?.preconditionGuard === true;
93895
+ const requestInlineDelta = typeof preInlineWriteCursor === "string" && err.stepCount === 1 && err.waitCount === 0 && pendingSteps.length === 1 && lazyInlineSteps.length === 1 && ownedRecoverySteps.length === 0 && !suspensionResult.waitTimeout && !openHookWaitState.openWait && (guardEnforced || err.hookCount === 0 && !openHookWaitState.openHook);
93896
+ const suppressOptimisticStart = guardEnforced && (openHookWaitState.openHook || err.hookCount > 0 || suspensionResult.hasHookEvents);
93897
+ const forceOptimisticStart = turbo && !suspensionResult.hasAttributeEvents && !suspensionResult.waitTimeout && !suspensionResult.hasHookEvents && !suspensionResult.hasAwaitedHookCreation && !openHookWaitState.openHook && !openHookWaitState.openWait;
92666
93898
  const latencyTracking = computeStepLatencyTracking({
92667
93899
  events: cachedEvents ?? [],
92668
93900
  invocationStartedClean: invocationStartedClean === true,
92669
93901
  runCreatedAtMs: runIdCreatedAt(runId) ?? (turbo ? void 0 : +workflowRun.createdAt),
93902
+ runStartedReceivedAtMs,
93903
+ replayMs: replayDurationMs,
92670
93904
  preStepBlockingMs,
92671
93905
  preStepBlockingBeforeAttrMs,
92672
93906
  // This suspension's own hook/wait writes are not in
@@ -92675,47 +93909,76 @@ function workflowEntrypoint(workflowCode2, options) {
92675
93909
  suspensionCreatedHooks: err.hookCount > 0 || suspensionResult.hasHookEvents,
92676
93910
  turbo
92677
93911
  });
93912
+ const inlineClaimStateUpdatedAt = stateUpdatedAtForCreate(cachedEvents ?? []);
92678
93913
  replayBudget.pause();
92679
93914
  let stepResults;
93915
+ const stepExecutionPromises = inlineExecutions.map((s, stepIndex) => {
93916
+ const run3 = /* @__PURE__ */ __name(() => executeStep({
93917
+ world,
93918
+ workflowRunId: runId,
93919
+ workflowDeploymentId: workflowRun.deploymentId,
93920
+ workflowName,
93921
+ workflowStartedAt,
93922
+ rootRunId: rootRunIdFrom(workflowRun.attributes, runId),
93923
+ stepId: s.correlationId,
93924
+ stepName: s.stepName,
93925
+ runSpecVersion: workflowRun.specVersion,
93926
+ // Attempt number = prior step_started count + 1
93927
+ // (this execution's start). A lazy step is
93928
+ // brand-new by construction (it enters the batch
93929
+ // only when it has no step_created yet), so it
93930
+ // has zero prior starts and is always attempt 1 —
93931
+ // skip the log scan entirely. Only an
93932
+ // owned-recovery re-run (this message re-executing
93933
+ // a step it crashed/timed out on) can have prior
93934
+ // starts, and that path is uncommon, so reserve
93935
+ // the O(n) scan for it rather than walking the
93936
+ // growing log for every inline step (which would
93937
+ // be O(n²) across a long sequential workflow).
93938
+ authoritativeAttempt: s.lazyStepInput !== void 0 ? 1 : countStepStartedEvents(cachedEvents, s.correlationId) + 1,
93939
+ // Lazy inline start: send the deferred step's
93940
+ // input on step_started so the world creates
93941
+ // the step on the fly. Absent for
93942
+ // owned-recovery steps, whose input hydrates
93943
+ // from the existing step entity.
93944
+ lazyStepInput: s.lazyStepInput,
93945
+ // Inline ownership: stamp (or re-stamp) this
93946
+ // invocation's queue message ID on the
93947
+ // step_started, so wake replays see the body
93948
+ // as in flight here and suppress the
93949
+ // immediate requeue (workflow#2780).
93950
+ ownerMessageId: metadata.messageId,
93951
+ // Turbo: force optimistic start and hold the
93952
+ // lazy step_started until the backgrounded
93953
+ // run_started lands (the body still runs
93954
+ // immediately). Both are undefined/false
93955
+ // outside turbo.
93956
+ forceOptimisticStart,
93957
+ // Guard-enforced batches with an open hook
93958
+ // await the claim before running the body, so
93959
+ // a 412-fenced step never executes user code —
93960
+ // see suppressOptimisticStart above.
93961
+ suppressOptimisticStart,
93962
+ runReadyBarrier,
93963
+ stateUpdatedAt: inlineClaimStateUpdatedAt,
93964
+ ...stepIndex === 0 && s.lazyStepInput !== void 0 && latencyTracking ? { latencyTracking } : {},
93965
+ ...requestInlineDelta && preInlineWriteCursor ? {
93966
+ inlineDeltaSinceCursor: preInlineWriteCursor
93967
+ } : {}
93968
+ }), "run");
93969
+ inFlightOwnedSteps.add(s.correlationId);
93970
+ const executed = s.lazyStepInput === void 0 ? runStepSingleFlight(runId, s.correlationId, run3) : run3();
93971
+ return executed.finally(() => inFlightOwnedSteps.delete(s.correlationId));
93972
+ });
92680
93973
  try {
92681
- stepResults = await Promise.all(inlineExecutions.map((s, stepIndex) => {
92682
- const run3 = /* @__PURE__ */ __name(() => executeStep({
92683
- world,
92684
- workflowRunId: runId,
92685
- workflowDeploymentId: workflowRun.deploymentId,
92686
- workflowName,
92687
- workflowStartedAt,
92688
- stepId: s.correlationId,
92689
- stepName: s.stepName,
92690
- runSpecVersion: workflowRun.specVersion,
92691
- // Lazy inline start: send the deferred step's
92692
- // input on step_started so the world creates
92693
- // the step on the fly. Absent for
92694
- // owned-recovery steps, whose input hydrates
92695
- // from the existing step entity.
92696
- lazyStepInput: s.lazyStepInput,
92697
- // Inline ownership: stamp (or re-stamp) this
92698
- // invocation's queue message ID on the
92699
- // step_started, so wake replays see the body
92700
- // as in flight here and suppress the
92701
- // immediate requeue (workflow#2780).
92702
- ownerMessageId: metadata.messageId,
92703
- // Turbo: force optimistic start and hold the
92704
- // lazy step_started until the backgrounded
92705
- // run_started lands (the body still runs
92706
- // immediately). Both are undefined/false
92707
- // outside turbo.
92708
- forceOptimisticStart,
92709
- runReadyBarrier,
92710
- ...stepIndex === 0 && s.lazyStepInput !== void 0 && latencyTracking ? { latencyTracking } : {},
92711
- ...requestInlineDelta && preInlineWriteCursor ? {
92712
- inlineDeltaSinceCursor: preInlineWriteCursor
92713
- } : {}
92714
- }), "run");
92715
- inFlightOwnedSteps.add(s.correlationId);
92716
- const executed = s.lazyStepInput === void 0 ? runStepSingleFlight(runId, s.correlationId, run3) : run3();
92717
- return executed.finally(() => inFlightOwnedSteps.delete(s.correlationId));
92718
- }));
93974
+ stepResults = await Promise.all(stepExecutionPromises);
93975
+ } catch (stepErr) {
93976
+ if (PreconditionFailedError.is(stepErr)) {
93977
+ await Promise.allSettled(stepExecutionPromises);
93978
+ runtimeLogger2.warn("Inline step claim rejected as stale; re-invoking run for a fresh replay", { workflowRunId: runId, loopIteration });
93979
+ return await reinvoke(0);
93980
+ }
93981
+ throw stepErr;
92719
93982
  } finally {
92720
93983
  replayBudget.resume();
92721
93984
  }
@@ -92797,6 +94060,10 @@ function workflowEntrypoint(workflowCode2, options) {
92797
94060
  }
92798
94061
  }
92799
94062
  } else {
94063
+ if (PreconditionFailedError.is(err)) {
94064
+ runtimeLogger2.warn("Event creation rejected as stale; re-invoking run for a fresh replay", { workflowRunId: runId, loopIteration });
94065
+ return await reinvoke(0);
94066
+ }
92800
94067
  if (isRetryableWorldError2(err)) {
92801
94068
  runLogger.warn("Transient world error during replay; redelivering via queue instead of failing the run", {
92802
94069
  errorName: err instanceof Error ? err.name : "UnknownError",
@@ -93111,6 +94378,19 @@ __name(addTenWorkflow, "addTenWorkflow");
93111
94378
  addTenWorkflow.workflowId = "workflow//./workflows/addition//addTenWorkflow";
93112
94379
  globalThis.__private_workflows.set("workflow//./workflows/addition//addTenWorkflow", addTenWorkflow);
93113
94380
 
94381
+ // workflows/event-limit.ts
94382
+ var tick = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//./workflows/event-limit//tick");
94383
+ async function runawayWorkflow() {
94384
+ let total = 0;
94385
+ for (let i = 0; i < 15; i++) {
94386
+ total += await tick(i);
94387
+ }
94388
+ return total;
94389
+ }
94390
+ __name(runawayWorkflow, "runawayWorkflow");
94391
+ runawayWorkflow.workflowId = "workflow//./workflows/event-limit//runawayWorkflow";
94392
+ globalThis.__private_workflows.set("workflow//./workflows/event-limit//runawayWorkflow", runawayWorkflow);
94393
+
93114
94394
  // ../core/dist/capture-stack.js
93115
94395
  function redirectStackToCaller(err, stackStartFn) {
93116
94396
  const capture = Error.captureStackTrace;
@@ -93661,10 +94941,10 @@ var Run = class _Run {
93661
94941
  return this.getReadable();
93662
94942
  }
93663
94943
  };
93664
- Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#wakeUp");
93665
- Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#cancel");
93666
- Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#getReadable");
93667
- var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#exists");
94944
+ Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#wakeUp");
94945
+ Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#cancel");
94946
+ Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#getReadable");
94947
+ var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#exists");
93668
94948
  Object.defineProperty(Run.prototype, "exists", {
93669
94949
  get() {
93670
94950
  return __step_Run$exists.call(this);
@@ -93672,7 +94952,7 @@ Object.defineProperty(Run.prototype, "exists", {
93672
94952
  configurable: true,
93673
94953
  enumerable: false
93674
94954
  });
93675
- var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#status");
94955
+ var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#status");
93676
94956
  Object.defineProperty(Run.prototype, "status", {
93677
94957
  get() {
93678
94958
  return __step_Run$status.call(this);
@@ -93680,7 +94960,7 @@ Object.defineProperty(Run.prototype, "status", {
93680
94960
  configurable: true,
93681
94961
  enumerable: false
93682
94962
  });
93683
- var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#returnValue");
94963
+ var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#returnValue");
93684
94964
  Object.defineProperty(Run.prototype, "returnValue", {
93685
94965
  get() {
93686
94966
  return __step_Run$returnValue.call(this);
@@ -93688,7 +94968,7 @@ Object.defineProperty(Run.prototype, "returnValue", {
93688
94968
  configurable: true,
93689
94969
  enumerable: false
93690
94970
  });
93691
- var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#workflowName");
94971
+ var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#workflowName");
93692
94972
  Object.defineProperty(Run.prototype, "workflowName", {
93693
94973
  get() {
93694
94974
  return __step_Run$workflowName.call(this);
@@ -93696,7 +94976,7 @@ Object.defineProperty(Run.prototype, "workflowName", {
93696
94976
  configurable: true,
93697
94977
  enumerable: false
93698
94978
  });
93699
- var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#createdAt");
94979
+ var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#createdAt");
93700
94980
  Object.defineProperty(Run.prototype, "createdAt", {
93701
94981
  get() {
93702
94982
  return __step_Run$createdAt.call(this);
@@ -93704,7 +94984,7 @@ Object.defineProperty(Run.prototype, "createdAt", {
93704
94984
  configurable: true,
93705
94985
  enumerable: false
93706
94986
  });
93707
- var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#startedAt");
94987
+ var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#startedAt");
93708
94988
  Object.defineProperty(Run.prototype, "startedAt", {
93709
94989
  get() {
93710
94990
  return __step_Run$startedAt.call(this);
@@ -93712,7 +94992,7 @@ Object.defineProperty(Run.prototype, "startedAt", {
93712
94992
  configurable: true,
93713
94993
  enumerable: false
93714
94994
  });
93715
- var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.34//Run#completedAt");
94995
+ var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.36//Run#completedAt");
93716
94996
  Object.defineProperty(Run.prototype, "completedAt", {
93717
94997
  get() {
93718
94998
  return __step_Run$completedAt.call(this);
@@ -93729,7 +95009,7 @@ Object.defineProperty(Run.prototype, "completedAt", {
93729
95009
  enumerable: false,
93730
95010
  configurable: false
93731
95011
  });
93732
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.34//Run");
95012
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.36//Run");
93733
95013
 
93734
95014
  // ../core/dist/workflow/create-hook.js
93735
95015
  aliasSerializationClass(RUN_CLASS_ID, Run);
@@ -94488,9 +95768,9 @@ function nullish(input) {
94488
95768
  }
94489
95769
  __name(nullish, "nullish");
94490
95770
  function cleanRegex(source) {
94491
- const start = source.startsWith("^") ? 1 : 0;
95771
+ const start2 = source.startsWith("^") ? 1 : 0;
94492
95772
  const end = source.endsWith("$") ? source.length - 1 : source.length;
94493
- return source.slice(start, end);
95773
+ return source.slice(start2, end);
94494
95774
  }
94495
95775
  __name(cleanRegex, "cleanRegex");
94496
95776
  function floatSafeRemainder(val, step) {
@@ -98105,9 +99385,9 @@ var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (i
98105
99385
  }
98106
99386
  const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
98107
99387
  if (!source) throw new Error(\`Invalid template literal part: \${part._zod.traits}\`);
98108
- const start = source.startsWith("^") ? 1 : 0;
99388
+ const start2 = source.startsWith("^") ? 1 : 0;
98109
99389
  const end = source.endsWith("$") ? source.length - 1 : source.length;
98110
- regexParts.push(source.slice(start, end));
99390
+ regexParts.push(source.slice(start2, end));
98111
99391
  } else if (part === null || primitiveTypes.has(typeof part)) {
98112
99392
  regexParts.push(escapeRegex(\`\${part}\`));
98113
99393
  } else {
@@ -108757,6 +110037,9 @@ __name(date4, "date");
108757
110037
  config(en_default());
108758
110038
 
108759
110039
  // ../world/dist/attributes.js
110040
+ var RESERVED_ATTRIBUTE_KEY_PREFIX = "$";
110041
+ var ROOT_RUN_ID_ATTRIBUTE = \`\${RESERVED_ATTRIBUTE_KEY_PREFIX}rootRunId\`;
110042
+ var PARENT_RUN_ID_ATTRIBUTE = \`\${RESERVED_ATTRIBUTE_KEY_PREFIX}parentRunId\`;
108760
110043
  var AttributeChangeSchema = external_exports.object({
108761
110044
  key: external_exports.string(),
108762
110045
  value: external_exports.union([
@@ -108887,6 +110170,17 @@ var stepLatencyTelemetryFields = {
108887
110170
  // stso.
108888
110171
  stepCount: external_exports.number().int().positive().optional(),
108889
110172
  eventCount: external_exports.number().int().positive().optional(),
110173
+ // Run-started-to-first-step: milliseconds from the \`run_started\` response
110174
+ // landing (or, under turbo, the local run synthesis instant) until this
110175
+ // step's start POST was issued. A sub-window of ttfs. Only reported
110176
+ // alongside the same eligibility as ttfs.
110177
+ rsfs: external_exports.number().optional(),
110178
+ // Synchronous workflow-function replay duration of only the FINAL replay
110179
+ // pass within the rsfs window (the pass that scheduled the first step),
110180
+ // excluding awaited network I/O \u2014 not accumulated across earlier
110181
+ // pre-first-step passes, so it is not "the replay portion of rsfs". Only
110182
+ // present alongside rsfs, and only for the run's first step.
110183
+ finalSchedulingReplay: external_exports.number().optional(),
108890
110184
  // Names of the runtime's optional startup-latency optimizations that were
108891
110185
  // active for this measurement (e.g. 'turbo', 'lazyStepStart',
108892
110186
  // 'optimisticStart'), so latency metrics can be segmented by them.
@@ -108968,6 +110262,7 @@ var HookCreatedEventSchema = BaseEventSchema.extend({
108968
110262
  correlationId: external_exports.string(),
108969
110263
  eventData: external_exports.object({
108970
110264
  token: external_exports.string(),
110265
+ tokenRetentionUntil: external_exports.coerce.date().optional(),
108971
110266
  metadata: SerializedDataSchema.optional(),
108972
110267
  isWebhook: external_exports.boolean().optional(),
108973
110268
  isSystem: external_exports.boolean().optional()
@@ -109673,14 +110968,58 @@ __name(hookWorkflow, "hookWorkflow");
109673
110968
  hookWorkflow.workflowId = "workflow//./workflows/inline-execution//hookWorkflow";
109674
110969
  globalThis.__private_workflows.set("workflow//./workflows/inline-execution//hookWorkflow", hookWorkflow);
109675
110970
 
110971
+ // ../core/dist/runtime/start.js
110972
+ var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.0.0-beta.36//start");
110973
+
110974
+ // workflows/lineage.ts
110975
+ var noop = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//./workflows/lineage//noop");
110976
+ async function bodyStartsChild() {
110977
+ await noop();
110978
+ const child = await start(spawnedChild, []);
110979
+ return child.runId;
110980
+ }
110981
+ __name(bodyStartsChild, "bodyStartsChild");
110982
+ bodyStartsChild.workflowId = "workflow//./workflows/lineage//bodyStartsChild";
110983
+ globalThis.__private_workflows.set("workflow//./workflows/lineage//bodyStartsChild", bodyStartsChild);
110984
+ async function spawnedChild() {
110985
+ await noop();
110986
+ return "done";
110987
+ }
110988
+ __name(spawnedChild, "spawnedChild");
110989
+ spawnedChild.workflowId = "workflow//./workflows/lineage//spawnedChild";
110990
+ globalThis.__private_workflows.set("workflow//./workflows/lineage//spawnedChild", spawnedChild);
110991
+ async function chainRoot() {
110992
+ await noop();
110993
+ const middle = await start(chainMiddle, []);
110994
+ return middle.runId;
110995
+ }
110996
+ __name(chainRoot, "chainRoot");
110997
+ chainRoot.workflowId = "workflow//./workflows/lineage//chainRoot";
110998
+ globalThis.__private_workflows.set("workflow//./workflows/lineage//chainRoot", chainRoot);
110999
+ async function chainMiddle() {
111000
+ await noop();
111001
+ const leaf = await start(chainLeaf, []);
111002
+ return leaf.runId;
111003
+ }
111004
+ __name(chainMiddle, "chainMiddle");
111005
+ chainMiddle.workflowId = "workflow//./workflows/lineage//chainMiddle";
111006
+ globalThis.__private_workflows.set("workflow//./workflows/lineage//chainMiddle", chainMiddle);
111007
+ async function chainLeaf() {
111008
+ await noop();
111009
+ return "done";
111010
+ }
111011
+ __name(chainLeaf, "chainLeaf");
111012
+ chainLeaf.workflowId = "workflow//./workflows/lineage//chainLeaf";
111013
+ globalThis.__private_workflows.set("workflow//./workflows/lineage//chainLeaf", chainLeaf);
111014
+
109676
111015
  // workflows/noop.ts
109677
- var noop = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//./workflows/noop//noop");
111016
+ var noop2 = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//./workflows/noop//noop");
109678
111017
  async function brokenWf() {
109679
111018
  const numbers = [];
109680
111019
  {
109681
111020
  const promises = [];
109682
111021
  for (let i = 0; i < 5; i++) {
109683
- promises.push(noop(i));
111022
+ promises.push(noop2(i));
109684
111023
  }
109685
111024
  console.log("await 5");
109686
111025
  numbers.push(...await Promise.all(promises));
@@ -109688,7 +111027,7 @@ async function brokenWf() {
109688
111027
  {
109689
111028
  const promises = [];
109690
111029
  for (let i = 0; i < 15; i++) {
109691
- promises.push(noop(100 + i));
111030
+ promises.push(noop2(100 + i));
109692
111031
  }
109693
111032
  console.log("await 15");
109694
111033
  numbers.push(...await Promise.all(promises));