@workflow/world-testing 5.0.0-beta.35 → 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.
@@ -15204,6 +15204,7 @@ var init_events2 = __esm({
15204
15204
  correlationId: external_exports2.string(),
15205
15205
  eventData: external_exports2.object({
15206
15206
  token: external_exports2.string(),
15207
+ tokenRetentionUntil: external_exports2.coerce.date().optional(),
15207
15208
  metadata: SerializedDataSchema2.optional(),
15208
15209
  isWebhook: external_exports2.boolean().optional(),
15209
15210
  isSystem: external_exports2.boolean().optional()
@@ -15375,7 +15376,7 @@ var init_events2 = __esm({
15375
15376
  });
15376
15377
 
15377
15378
  // ../world/dist/runs.js
15378
- function isTerminalWorkflowRunStatus(status) {
15379
+ function isTerminalWorkflowRunStatus2(status) {
15379
15380
  return TERMINAL_WORKFLOW_RUN_STATUSES2.includes(status);
15380
15381
  }
15381
15382
  var WorkflowRunStatusSchema2, TerminalWorkflowRunStatusSchema2, TERMINAL_WORKFLOW_RUN_STATUSES2, WorkflowRunBaseSchema2, WorkflowRunSchema2;
@@ -15397,7 +15398,7 @@ var init_runs2 = __esm({
15397
15398
  "cancelled"
15398
15399
  ]);
15399
15400
  TERMINAL_WORKFLOW_RUN_STATUSES2 = TerminalWorkflowRunStatusSchema2.options;
15400
- __name(isTerminalWorkflowRunStatus, "isTerminalWorkflowRunStatus");
15401
+ __name(isTerminalWorkflowRunStatus2, "isTerminalWorkflowRunStatus");
15401
15402
  WorkflowRunBaseSchema2 = external_exports2.object({
15402
15403
  runId: external_exports2.string(),
15403
15404
  status: WorkflowRunStatusSchema2,
@@ -16273,7 +16274,7 @@ __export(dist_exports, {
16273
16274
  isTerminalRunEventType: () => isTerminalRunEventType,
16274
16275
  isTerminalStepEventType: () => isTerminalStepEventType,
16275
16276
  isTerminalStepStatus: () => isTerminalStepStatus,
16276
- isTerminalWorkflowRunStatus: () => isTerminalWorkflowRunStatus,
16277
+ isTerminalWorkflowRunStatus: () => isTerminalWorkflowRunStatus2,
16277
16278
  isWaitEventType: () => isWaitEventType,
16278
16279
  parseQueueName: () => parseQueueName,
16279
16280
  reenqueueActiveRuns: () => reenqueueActiveRuns,
@@ -16661,6 +16662,8 @@ var init_error_codes2 = __esm({
16661
16662
  REPLAY_DIVERGENCE: "REPLAY_DIVERGENCE",
16662
16663
  /** Run exceeded the maximum number of queue deliveries */
16663
16664
  MAX_DELIVERIES_EXCEEDED: "MAX_DELIVERIES_EXCEEDED",
16665
+ /** Run exceeded the maximum number of events per run */
16666
+ MAX_EVENTS_EXCEEDED: "MAX_EVENTS_EXCEEDED",
16664
16667
  /** Workflow replay exceeded the maximum allowed duration */
16665
16668
  REPLAY_TIMEOUT: "REPLAY_TIMEOUT",
16666
16669
  /** World response violated the SDK contract and cannot be retried safely */
@@ -16694,7 +16697,7 @@ function buildFramedDetails2(hint3, slug) {
16694
16697
  out.push({ label: "docs", value: `${BASE_URL2}/${slug}` });
16695
16698
  return out;
16696
16699
  }
16697
- var BASE_URL2, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError, ReplayDivergenceError, 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;
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;
16698
16701
  var init_dist7 = __esm({
16699
16702
  "../errors/dist/index.js"() {
16700
16703
  "use strict";
@@ -16849,6 +16852,22 @@ Caused by: ${options.cause.stack}`;
16849
16852
  return isError2(value) && value.name === "ReplayDivergenceError" && typeof value.eventId === "string";
16850
16853
  }
16851
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
+ };
16852
16871
  RuntimeDecryptionError2 = class extends WorkflowRuntimeError2 {
16853
16872
  static {
16854
16873
  __name(this, "RuntimeDecryptionError");
@@ -45533,410 +45552,6 @@ var init_logger2 = __esm({
45533
45552
  }
45534
45553
  });
45535
45554
 
45536
- // ../core/dist/encryption.js
45537
- async function importKey2(raw, usages = ["encrypt", "decrypt"]) {
45538
- if (raw.byteLength !== KEY_LENGTH2) {
45539
- throw new WorkflowRuntimeError2(`Encryption key must be exactly ${KEY_LENGTH2} bytes, got ${raw.byteLength}`);
45540
- }
45541
- return globalThis.crypto.subtle.importKey(
45542
- "raw",
45543
- raw,
45544
- "AES-GCM",
45545
- false,
45546
- // `KeyUsage` is a DOM-lib type that's not in scope under `es2022`.
45547
- // The `ReadonlyArray<'encrypt' | 'decrypt'>` parameter type matches
45548
- // a strict subset of `KeyUsage[]`, so this cast is sound.
45549
- usages
45550
- );
45551
- }
45552
- async function encrypt3(key, data) {
45553
- const nonce = globalThis.crypto.getRandomValues(new Uint8Array(NONCE_LENGTH2));
45554
- let ciphertext;
45555
- try {
45556
- ciphertext = await globalThis.crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, tagLength: TAG_LENGTH2 }, key, data);
45557
- } catch (cause) {
45558
- throw new RuntimeDecryptionError2(`AES-256-GCM encryption failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
45559
- cause,
45560
- context: {
45561
- operation: "encrypt",
45562
- byteLength: data.byteLength
45563
- }
45564
- });
45565
- }
45566
- const result = new Uint8Array(NONCE_LENGTH2 + ciphertext.byteLength);
45567
- result.set(nonce, 0);
45568
- result.set(new Uint8Array(ciphertext), NONCE_LENGTH2);
45569
- return result;
45570
- }
45571
- async function decrypt3(key, data) {
45572
- const minLength = NONCE_LENGTH2 + TAG_LENGTH2 / 8;
45573
- if (data.byteLength < minLength) {
45574
- throw new RuntimeDecryptionError2(`Encrypted data too short: expected at least ${minLength} bytes, got ${data.byteLength}`, {
45575
- context: {
45576
- operation: "decrypt",
45577
- byteLength: data.byteLength
45578
- }
45579
- });
45580
- }
45581
- const nonce = data.subarray(0, NONCE_LENGTH2);
45582
- const ciphertext = data.subarray(NONCE_LENGTH2);
45583
- let plaintext;
45584
- try {
45585
- plaintext = await globalThis.crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, tagLength: TAG_LENGTH2 }, key, ciphertext);
45586
- } catch (cause) {
45587
- const causeMsg = cause instanceof Error ? cause.message : String(cause);
45588
- throw new RuntimeDecryptionError2(`AES-256-GCM decryption failed: ${causeMsg}`, {
45589
- cause,
45590
- context: {
45591
- operation: "decrypt",
45592
- byteLength: data.byteLength
45593
- }
45594
- });
45595
- }
45596
- return new Uint8Array(plaintext);
45597
- }
45598
- var NONCE_LENGTH2, TAG_LENGTH2, KEY_LENGTH2;
45599
- var init_encryption3 = __esm({
45600
- "../core/dist/encryption.js"() {
45601
- "use strict";
45602
- init_dist7();
45603
- NONCE_LENGTH2 = 12;
45604
- TAG_LENGTH2 = 128;
45605
- KEY_LENGTH2 = 32;
45606
- __name(importKey2, "importKey");
45607
- __name(encrypt3, "encrypt");
45608
- __name(decrypt3, "decrypt");
45609
- }
45610
- });
45611
-
45612
- // ../core/dist/version.js
45613
- var version4;
45614
- var init_version3 = __esm({
45615
- "../core/dist/version.js"() {
45616
- "use strict";
45617
- version4 = "5.0.0-beta.35";
45618
- }
45619
- });
45620
-
45621
- // ../core/dist/runtime/get-world-lazy.js
45622
- async function getWorldLazy2() {
45623
- const g = globalThis;
45624
- if (g[WorldCacheKey2]) {
45625
- assertWorldSupportsRuntimeProtocol2(g[WorldCacheKey2]);
45626
- return g[WorldCacheKey2];
45627
- }
45628
- if (g[WorldCachePromiseKey2]) {
45629
- g[WorldCacheKey2] = await g[WorldCachePromiseKey2];
45630
- assertWorldSupportsRuntimeProtocol2(g[WorldCacheKey2]);
45631
- return g[WorldCacheKey2];
45632
- }
45633
- const getWorldFn = g[GetWorldFnKey3];
45634
- if (getWorldFn) {
45635
- const world = await getWorldFn();
45636
- assertWorldSupportsRuntimeProtocol2(world);
45637
- return world;
45638
- }
45639
- 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.");
45640
- }
45641
- var WorldCacheKey2, WorldCachePromiseKey2, GetWorldFnKey3;
45642
- var init_get_world_lazy2 = __esm({
45643
- "../core/dist/runtime/get-world-lazy.js"() {
45644
- "use strict";
45645
- init_world_compatibility2();
45646
- WorldCacheKey2 = /* @__PURE__ */ Symbol.for("@workflow/world//cache");
45647
- WorldCachePromiseKey2 = /* @__PURE__ */ Symbol.for("@workflow/world//cachePromise");
45648
- GetWorldFnKey3 = /* @__PURE__ */ Symbol.for("@workflow/world//getWorldFn");
45649
- __name(getWorldLazy2, "getWorldLazy");
45650
- }
45651
- });
45652
-
45653
- // ../core/dist/runtime/helpers.js
45654
- function getWorkflowQueueName2(workflowName, namespace) {
45655
- if (!SAFE_WORKFLOW_NAME_PATTERN2.test(workflowName)) {
45656
- throw new Error(`Invalid workflow name "${workflowName}": must only contain alphanumeric characters, underscores, hyphens, dots, forward slashes, or at signs`);
45657
- }
45658
- const prefix = getQueueTopicPrefix2("workflow", resolveQueueNamespace2(namespace));
45659
- return `${prefix}${workflowName}`;
45660
- }
45661
- function getHealthCheckStreamName2(correlationId) {
45662
- return `__health_check__${correlationId}`;
45663
- }
45664
- function parseHealthCheckPayload(message) {
45665
- const result = HealthCheckPayloadSchema2.safeParse(message);
45666
- if (result.success) {
45667
- return result.data;
45668
- }
45669
- return void 0;
45670
- }
45671
- function generateHealthCheckRunId2(correlationId) {
45672
- return `wrun_hc_${correlationId}`;
45673
- }
45674
- async function handleHealthCheckMessage(healthCheck3, endpoint, worldSpecVersion) {
45675
- const world = await getWorldLazy2();
45676
- const streamName = getHealthCheckStreamName2(healthCheck3.correlationId);
45677
- const response = JSON.stringify({
45678
- healthy: true,
45679
- endpoint,
45680
- correlationId: healthCheck3.correlationId,
45681
- specVersion: worldSpecVersion ?? SPEC_VERSION_CURRENT2,
45682
- workflowCoreVersion: version4,
45683
- timestamp: Date.now()
45684
- });
45685
- const fakeRunId = generateHealthCheckRunId2(healthCheck3.correlationId);
45686
- await world.streams.write(fakeRunId, streamName, response);
45687
- await world.streams.close(fakeRunId, streamName);
45688
- }
45689
- function eventPaginationContractError(runId, message) {
45690
- return new WorkflowWorldError2(`Event pagination ${message} for workflow run "${runId}".`, { code: RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR });
45691
- }
45692
- function recordRequestedEventCursor(runId, cursor, requestedCursors) {
45693
- if (!cursor) {
45694
- return;
45695
- }
45696
- if (requestedCursors.has(cursor)) {
45697
- throw eventPaginationContractError(runId, "did not advance");
45698
- }
45699
- requestedCursors.add(cursor);
45700
- }
45701
- function appendUniqueEvents(target, targetIds, events) {
45702
- for (const event of events) {
45703
- if (!targetIds.has(event.eventId)) {
45704
- targetIds.add(event.eventId);
45705
- target.push(event);
45706
- }
45707
- }
45708
- }
45709
- function assertEventPaginationProgress(runId, hasMore, cursor, requestedCursors) {
45710
- if (!hasMore) {
45711
- return;
45712
- }
45713
- if (cursor === null) {
45714
- throw eventPaginationContractError(runId, "returned more pages without a cursor");
45715
- }
45716
- if (requestedCursors.has(cursor)) {
45717
- throw eventPaginationContractError(runId, "repeated a cursor");
45718
- }
45719
- }
45720
- function shouldRetryWithoutEventCursor(error95, cursor, alreadyRetried) {
45721
- return cursor !== null && !alreadyRetried && WorkflowWorldError2.is(error95) && error95.status === 400;
45722
- }
45723
- async function loadWorkflowRunEvents(runId, afterCursor) {
45724
- const incremental = afterCursor !== void 0;
45725
- return trace4(incremental ? "workflow.loadNewEvents" : "workflow.loadEvents", async (span) => {
45726
- span?.setAttributes({
45727
- ...WorkflowRunId3(runId)
45728
- });
45729
- const loadedEvents = [];
45730
- const loadedEventIds = /* @__PURE__ */ new Set();
45731
- const requestedCursors = /* @__PURE__ */ new Set();
45732
- let cursor = afterCursor ?? null;
45733
- let hasMore = true;
45734
- let pagesLoaded = 0;
45735
- let retriedWithoutCursor = false;
45736
- const world = await getWorldLazy2();
45737
- const loadStart = Date.now();
45738
- while (hasMore) {
45739
- const pageStart = Date.now();
45740
- const requestedCursor = cursor;
45741
- recordRequestedEventCursor(runId, requestedCursor, requestedCursors);
45742
- let response;
45743
- try {
45744
- response = await world.events.list({
45745
- runId,
45746
- pagination: {
45747
- sortOrder: "asc",
45748
- cursor: requestedCursor ?? void 0
45749
- }
45750
- });
45751
- } catch (error95) {
45752
- if (shouldRetryWithoutEventCursor(error95, requestedCursor, retriedWithoutCursor)) {
45753
- runtimeLogger2.warn("Event cursor was rejected; retrying with a full event reload.", { workflowRunId: runId });
45754
- loadedEvents.length = 0;
45755
- loadedEventIds.clear();
45756
- requestedCursors.clear();
45757
- cursor = null;
45758
- retriedWithoutCursor = true;
45759
- continue;
45760
- }
45761
- throw error95;
45762
- }
45763
- appendUniqueEvents(loadedEvents, loadedEventIds, response.data);
45764
- hasMore = response.hasMore;
45765
- assertEventPaginationProgress(runId, hasMore, response.cursor, requestedCursors);
45766
- cursor = response.cursor ?? cursor;
45767
- pagesLoaded++;
45768
- runtimeLogger2.debug("Loaded event page", {
45769
- workflowRunId: runId,
45770
- incremental,
45771
- page: pagesLoaded,
45772
- pageEvents: response.data.length,
45773
- totalEvents: loadedEvents.length,
45774
- hasMore,
45775
- pageMs: Date.now() - pageStart
45776
- });
45777
- }
45778
- runtimeLogger2.debug("Event load complete", {
45779
- workflowRunId: runId,
45780
- incremental,
45781
- totalEvents: loadedEvents.length,
45782
- pagesLoaded,
45783
- totalMs: Date.now() - loadStart
45784
- });
45785
- span?.setAttributes({
45786
- ...WorkflowEventsCount2(loadedEvents.length),
45787
- ...WorkflowEventsPagesLoaded2(pagesLoaded)
45788
- });
45789
- return { events: loadedEvents, cursor };
45790
- });
45791
- }
45792
- function isPreconditionGuardEnabled() {
45793
- return process.env.WORKFLOW_PRECONDITION_GUARD === "1";
45794
- }
45795
- function latestEventStateUpdatedAt(events) {
45796
- const last = events[events.length - 1];
45797
- if (!last) {
45798
- return void 0;
45799
- }
45800
- const eventId = last.eventId;
45801
- const underscore = eventId.lastIndexOf("_");
45802
- const rawUlid = underscore === -1 ? eventId : eventId.slice(underscore + 1);
45803
- return ulidToDate(rawUlid)?.getTime() ?? void 0;
45804
- }
45805
- function stateUpdatedAtForCreate(events) {
45806
- return isPreconditionGuardEnabled() ? latestEventStateUpdatedAt(events) : void 0;
45807
- }
45808
- async function withPreconditionRetry(runId, log, op) {
45809
- for (let attempt = 0; ; attempt++) {
45810
- try {
45811
- return await op(stateUpdatedAtForCreate(log.events));
45812
- } catch (error95) {
45813
- if (!PreconditionFailedError.is(error95) || attempt >= PRECONDITION_MAX_RELOAD_RETRIES) {
45814
- throw error95;
45815
- }
45816
- runtimeLogger2.info("Event creation rejected as stale; reloading event log and retrying", {
45817
- workflowRunId: runId,
45818
- attempt: attempt + 1,
45819
- maxRetries: PRECONDITION_MAX_RELOAD_RETRIES
45820
- });
45821
- const loaded = await loadWorkflowRunEvents(runId, log.cursor ?? void 0);
45822
- appendUniqueEvents(log.events, new Set(log.events.map((e) => e.eventId)), loaded.events);
45823
- log.cursor = loaded.cursor ?? log.cursor;
45824
- }
45825
- }
45826
- }
45827
- function withHealthCheck(handler, worldSpecVersion) {
45828
- return async (req) => {
45829
- const url3 = new URL(req.url);
45830
- const isHealthCheck = url3.searchParams.has("__health");
45831
- if (isHealthCheck) {
45832
- if (req.method === "OPTIONS") {
45833
- return new Response(null, {
45834
- status: 204,
45835
- headers: HEALTH_CHECK_CORS_HEADERS
45836
- });
45837
- }
45838
- return new Response(JSON.stringify({
45839
- healthy: true,
45840
- endpoint: url3.pathname,
45841
- specVersion: worldSpecVersion ?? SPEC_VERSION_CURRENT2,
45842
- workflowCoreVersion: version4
45843
- }), {
45844
- status: 200,
45845
- headers: {
45846
- "Content-Type": "application/json",
45847
- ...HEALTH_CHECK_CORS_HEADERS
45848
- }
45849
- });
45850
- }
45851
- return await handler(req);
45852
- };
45853
- }
45854
- async function queueMessage(world, ...args) {
45855
- const queueName = args[0];
45856
- await trace4("queue.publish", {
45857
- // Standard OTEL messaging conventions
45858
- attributes: {
45859
- ...MessagingSystem2("vercel-queue"),
45860
- ...MessagingDestinationName2(queueName),
45861
- ...MessagingOperationType2("publish"),
45862
- // Peer service for Datadog service maps
45863
- ...PeerService3("vercel-queue"),
45864
- ...RpcSystem3("vercel-queue"),
45865
- ...RpcService3("vqs"),
45866
- ...RpcMethod3("publish")
45867
- },
45868
- kind: await getSpanKind3("PRODUCER")
45869
- }, async (span) => {
45870
- const { messageId } = await world.queue(...args);
45871
- if (messageId) {
45872
- span?.setAttributes(MessagingMessageId2(messageId));
45873
- }
45874
- });
45875
- }
45876
- function getQueueOverhead(message) {
45877
- if (!message.requestedAt)
45878
- return;
45879
- try {
45880
- return QueueOverheadMs2(Date.now() - message.requestedAt.getTime());
45881
- } catch {
45882
- return;
45883
- }
45884
- }
45885
- function memoizeEncryptionKey(world, runOrId) {
45886
- let cached3;
45887
- return () => {
45888
- if (!cached3) {
45889
- cached3 = (async () => {
45890
- const rawKey = typeof runOrId === "string" ? await world.getEncryptionKeyForRun?.(runOrId) : await world.getEncryptionKeyForRun?.(runOrId);
45891
- return rawKey ? await importKey2(rawKey) : void 0;
45892
- })();
45893
- }
45894
- return cached3;
45895
- };
45896
- }
45897
- var SAFE_WORKFLOW_NAME_PATTERN2, generateId2, PRECONDITION_MAX_RELOAD_RETRIES, HEALTH_CHECK_CORS_HEADERS;
45898
- var init_helpers2 = __esm({
45899
- "../core/dist/runtime/helpers.js"() {
45900
- "use strict";
45901
- init_dist7();
45902
- init_dist5();
45903
- init_node2();
45904
- init_encryption3();
45905
- init_logger2();
45906
- init_semantic_conventions2();
45907
- init_telemetry2();
45908
- init_version3();
45909
- init_get_world_lazy2();
45910
- SAFE_WORKFLOW_NAME_PATTERN2 = /^[a-zA-Z0-9_\-./@]+$/;
45911
- __name(getWorkflowQueueName2, "getWorkflowQueueName");
45912
- generateId2 = monotonicFactory2();
45913
- __name(getHealthCheckStreamName2, "getHealthCheckStreamName");
45914
- __name(parseHealthCheckPayload, "parseHealthCheckPayload");
45915
- __name(generateHealthCheckRunId2, "generateHealthCheckRunId");
45916
- __name(handleHealthCheckMessage, "handleHealthCheckMessage");
45917
- __name(eventPaginationContractError, "eventPaginationContractError");
45918
- __name(recordRequestedEventCursor, "recordRequestedEventCursor");
45919
- __name(appendUniqueEvents, "appendUniqueEvents");
45920
- __name(assertEventPaginationProgress, "assertEventPaginationProgress");
45921
- __name(shouldRetryWithoutEventCursor, "shouldRetryWithoutEventCursor");
45922
- __name(loadWorkflowRunEvents, "loadWorkflowRunEvents");
45923
- PRECONDITION_MAX_RELOAD_RETRIES = 2;
45924
- __name(isPreconditionGuardEnabled, "isPreconditionGuardEnabled");
45925
- __name(latestEventStateUpdatedAt, "latestEventStateUpdatedAt");
45926
- __name(stateUpdatedAtForCreate, "stateUpdatedAtForCreate");
45927
- __name(withPreconditionRetry, "withPreconditionRetry");
45928
- HEALTH_CHECK_CORS_HEADERS = {
45929
- "Access-Control-Allow-Origin": "*",
45930
- "Access-Control-Allow-Methods": "POST, OPTIONS, GET, HEAD",
45931
- "Access-Control-Allow-Headers": "Content-Type"
45932
- };
45933
- __name(withHealthCheck, "withHealthCheck");
45934
- __name(queueMessage, "queueMessage");
45935
- __name(getQueueOverhead, "getQueueOverhead");
45936
- __name(memoizeEncryptionKey, "memoizeEncryptionKey");
45937
- }
45938
- });
45939
-
45940
45555
  // ../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/constants.js
45941
45556
  var UNDEFINED2, HOLE2, NAN2, POSITIVE_INFINITY2, NEGATIVE_INFINITY2, NEGATIVE_ZERO2, SPARSE2, MAX_ARRAY_LEN2, MAX_ARRAY_INDEX2;
45942
45557
  var init_constants2 = __esm({
@@ -46575,6 +46190,109 @@ var init_devalue2 = __esm({
46575
46190
  }
46576
46191
  });
46577
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
+
46578
46296
  // ../core/dist/flushable-stream.js
46579
46297
  function createFlushableState2() {
46580
46298
  const state = {
@@ -46657,7 +46375,11 @@ function pollReadableLock2(readable, state) {
46657
46375
  }, getLockPollIntervalMs2());
46658
46376
  state.readablePollingInterval = intervalId;
46659
46377
  }
46660
- 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) {
46661
46383
  const reader = source.getReader();
46662
46384
  const writer = sink.getWriter();
46663
46385
  let cancelReason;
@@ -46706,13 +46428,147 @@ async function flushablePipe2(source, sink, state) {
46706
46428
  writer.releaseLock();
46707
46429
  }
46708
46430
  }
46709
- 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;
46710
46550
  var init_flushable_stream2 = __esm({
46711
46551
  "../core/dist/flushable-stream.js"() {
46712
46552
  "use strict";
46713
46553
  init_dist7();
46714
46554
  init_dist6();
46715
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");
46716
46572
  LOCK_POLL_INTERVAL_MS2 = 10;
46717
46573
  getLockPollIntervalMs2 = /* @__PURE__ */ __name(() => envNumber2("WORKFLOW_LOCK_POLL_INTERVAL_MS", LOCK_POLL_INTERVAL_MS2, {
46718
46574
  integer: true,
@@ -46724,6 +46580,13 @@ var init_flushable_stream2 = __esm({
46724
46580
  __name(pollWritableLock2, "pollWritableLock");
46725
46581
  __name(pollReadableLock2, "pollReadableLock");
46726
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");
46727
46590
  }
46728
46591
  });
46729
46592
 
@@ -46855,6 +46718,38 @@ var init_private2 = __esm({
46855
46718
  }
46856
46719
  });
46857
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
+
46858
46753
  // ../serde/dist/index.js
46859
46754
  var WORKFLOW_SERIALIZE2, WORKFLOW_DESERIALIZE2;
46860
46755
  var init_dist8 = __esm({
@@ -46865,32 +46760,6 @@ var init_dist8 = __esm({
46865
46760
  }
46866
46761
  });
46867
46762
 
46868
- // ../core/dist/symbols.js
46869
- 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;
46870
- var init_symbols2 = __esm({
46871
- "../core/dist/symbols.js"() {
46872
- "use strict";
46873
- WORKFLOW_USE_STEP = /* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP");
46874
- WORKFLOW_SET_ATTRIBUTES = /* @__PURE__ */ Symbol.for("WORKFLOW_SET_ATTRIBUTES");
46875
- WORKFLOW_CREATE_HOOK = /* @__PURE__ */ Symbol.for("WORKFLOW_CREATE_HOOK");
46876
- WORKFLOW_SLEEP = /* @__PURE__ */ Symbol.for("WORKFLOW_SLEEP");
46877
- WORKFLOW_GET_STREAM_ID = /* @__PURE__ */ Symbol.for("WORKFLOW_GET_STREAM_ID");
46878
- STABLE_ULID2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STABLE_ULID");
46879
- STREAM_NAME_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_NAME");
46880
- STREAM_TYPE_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_TYPE");
46881
- STREAM_FRAMING_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_FRAMING");
46882
- STREAM_SERVER_RUN_ID_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_RUN_ID");
46883
- STREAM_SERVER_DEPLOYMENT_ID_SYMBOL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_DEPLOYMENT_ID");
46884
- BODY_INIT_SYMBOL2 = /* @__PURE__ */ Symbol.for("BODY_INIT");
46885
- WEBHOOK_RESPONSE_WRITABLE2 = /* @__PURE__ */ Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
46886
- WORKFLOW_CLASS_REGISTRY2 = /* @__PURE__ */ Symbol.for("workflow-class-registry");
46887
- ABORT_STREAM_NAME2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_STREAM_NAME");
46888
- ABORT_HOOK_TOKEN2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_HOOK_TOKEN");
46889
- ABORT_LISTENER_ATTACHED2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_LISTENER_ATTACHED");
46890
- ABORT_READER_CANCEL2 = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_READER_CANCEL");
46891
- }
46892
- });
46893
-
46894
46763
  // ../core/dist/class-serialization.js
46895
46764
  function getRegistry2(global2 = globalThis) {
46896
46765
  const g = global2;
@@ -48146,7 +48015,8 @@ function createCreateAbortController(ctx) {
48146
48015
  try {
48147
48016
  if (rawPayload !== void 0) {
48148
48017
  try {
48149
- 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);
48150
48020
  if (hydrated && typeof hydrated === "object" && "reason" in hydrated) {
48151
48021
  reason = hydrated.reason;
48152
48022
  }
@@ -50296,6 +50166,307 @@ var init_capabilities2 = __esm({
50296
50166
  }
50297
50167
  });
50298
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
+
50299
50470
  // ../../node_modules/.pnpm/@vercel+functions@3.4.3_@aws-sdk+credential-provider-web-identity@3.972.49/node_modules/@vercel/functions/headers.js
50300
50471
  var require_headers3 = __commonJS({
50301
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) {
@@ -51441,16 +51612,20 @@ __export(resume_hook_exports2, {
51441
51612
  resumeHook: () => resumeHook2,
51442
51613
  resumeWebhook: () => resumeWebhook2
51443
51614
  });
51444
- async function getHookByTokenWithKey2(token) {
51615
+ async function getHookAndRun2(token) {
51445
51616
  const world = await getWorldLazy2();
51446
51617
  const hook = await world.hooks.getByToken(token);
51447
51618
  const run3 = await world.runs.get(hook.runId);
51448
- 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);
51449
51624
  const encryptionKey = rawKey ? await importKey2(rawKey) : void 0;
51450
51625
  if (typeof hook.metadata !== "undefined") {
51451
51626
  hook.metadata = await hydrateStepArguments2(hook.metadata, hook.runId, encryptionKey);
51452
51627
  }
51453
- return { hook, run: run3, encryptionKey };
51628
+ return { hook, encryptionKey };
51454
51629
  }
51455
51630
  async function getHookByToken2(token) {
51456
51631
  const { hook } = await getHookByTokenWithKey2(token);
@@ -51463,27 +51638,27 @@ async function resumeHook2(tokenOrHook, payload, encryptionKeyOverride) {
51463
51638
  try {
51464
51639
  let hook;
51465
51640
  let workflowRun;
51466
- let encryptionKey;
51467
51641
  if (typeof tokenOrHook === "string") {
51468
- const result = await getHookByTokenWithKey2(tokenOrHook);
51642
+ const result = await getHookAndRun2(tokenOrHook);
51469
51643
  hook = result.hook;
51470
51644
  workflowRun = result.run;
51471
- encryptionKey = encryptionKeyOverride ?? result.encryptionKey;
51472
51645
  } else {
51473
51646
  hook = tokenOrHook;
51474
51647
  workflowRun = await world.runs.get(hook.runId);
51475
- if (encryptionKeyOverride) {
51476
- encryptionKey = encryptionKeyOverride;
51477
- } else {
51478
- const rawKey = await world.getEncryptionKeyForRun?.(workflowRun);
51479
- encryptionKey = rawKey ? await importKey2(rawKey) : void 0;
51480
- }
51481
51648
  }
51482
51649
  span?.setAttributes({
51483
51650
  ...HookToken2(hook.token),
51484
51651
  ...HookId2(hook.hookId),
51485
51652
  ...WorkflowRunId3(hook.runId)
51486
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
+ }
51487
51662
  const rawVersion = workflowRun.executionContext?.workflowCoreVersion;
51488
51663
  const capabilities = getRunCapabilities2(typeof rawVersion === "string" ? rawVersion : void 0);
51489
51664
  if (!capabilities.supportedFormats.has(SerializationFormat2.ENCRYPTED)) {
@@ -51588,6 +51763,7 @@ var init_resume_hook2 = __esm({
51588
51763
  init_get_world_lazy2();
51589
51764
  init_helpers2();
51590
51765
  init_wait_until2();
51766
+ __name(getHookAndRun2, "getHookAndRun");
51591
51767
  __name(getHookByTokenWithKey2, "getHookByTokenWithKey");
51592
51768
  __name(getHookByToken2, "getHookByToken");
51593
51769
  __name(resumeHook2, "resumeHook");
@@ -52826,14 +53002,8 @@ function getStepRevivers2(global2 = globalThis, ops, runId, cryptoKey, deploymen
52826
53002
  async function maybeEncrypt(data, key) {
52827
53003
  return await encrypt4(data, key);
52828
53004
  }
52829
- async function maybeDecrypt2(data, key) {
52830
- return decrypt4(data, key);
52831
- }
52832
- async function hydrateWorkflowArguments(value, _runId, key, global2 = globalThis, extraRevivers = {}) {
52833
- const compressionStats = {};
52834
- const inflated = await decompress2(await maybeDecrypt2(value, key), compressionStats);
52835
- await recordCompression2(compressionStats, "deserialize");
52836
- return deserialize5(inflated, {
53005
+ function deserializePreparedReplayPayload(prepared, global2 = globalThis, extraRevivers = {}) {
53006
+ return deserialize5(prepared.data, {
52837
53007
  global: global2,
52838
53008
  extraRevivers: {
52839
53009
  ...getStreamAndRequestRevivers2(getWorkflowRevivers(global2)),
@@ -52841,6 +53011,27 @@ async function hydrateWorkflowArguments(value, _runId, key, global2 = globalThis
52841
53011
  }
52842
53012
  });
52843
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
+ }
52844
53035
  async function dehydrateWorkflowReturnValue(value, _runId, key, global2 = globalThis, v1Compat = false, compression = false) {
52845
53036
  if (v1Compat) {
52846
53037
  const str = stringify2(value, getWorkflowReducers2(global2));
@@ -52946,25 +53137,8 @@ async function dehydrateStepError(value, runId, key, ops = [], global2 = globalT
52946
53137
  throw new SerializationError2(message, { hint: hint3, cause });
52947
53138
  }
52948
53139
  }
52949
- async function hydrateStepError(value, _runId, key, global2 = globalThis, extraRevivers = {}) {
52950
- const compressionStats = {};
52951
- const decrypted = await decompress2(await maybeDecrypt2(value, key), compressionStats);
52952
- await recordCompression2(compressionStats, "deserialize");
52953
- if (!(decrypted instanceof Uint8Array)) {
52954
- return unflatten2(decrypted, {
52955
- ...getWorkflowRevivers(global2),
52956
- ...extraRevivers
52957
- });
52958
- }
52959
- const { format, payload } = decodeFormatPrefix2(decrypted);
52960
- if (format === SerializationFormat2.DEVALUE_V1) {
52961
- const str = new TextDecoder().decode(payload);
52962
- return parse6(str, {
52963
- ...getWorkflowRevivers(global2),
52964
- ...extraRevivers
52965
- });
52966
- }
52967
- 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);
52968
53142
  }
52969
53143
  async function dehydrateRunError(value, _runId, key, global2 = globalThis, compression = false) {
52970
53144
  try {
@@ -52984,7 +53158,7 @@ async function dehydrateRunError(value, _runId, key, global2 = globalThis, compr
52984
53158
  }
52985
53159
  async function hydrateRunError2(value, runId, key, ops = [], global2 = globalThis, extraRevivers = {}) {
52986
53160
  const compressionStats = {};
52987
- const decrypted = await decompress2(await maybeDecrypt2(value, key), compressionStats);
53161
+ const decrypted = await decompress2(await decrypt4(value, key), compressionStats);
52988
53162
  await recordCompression2(compressionStats, "deserialize");
52989
53163
  if (!(decrypted instanceof Uint8Array)) {
52990
53164
  return unflatten2(decrypted, {
@@ -53002,17 +53176,8 @@ async function hydrateRunError2(value, runId, key, ops = [], global2 = globalThi
53002
53176
  }
53003
53177
  throw new Error(`Unsupported serialization format: ${format}`);
53004
53178
  }
53005
- async function hydrateStepReturnValue(value, _runId, key, global2 = globalThis, extraRevivers = {}) {
53006
- const compressionStats = {};
53007
- const inflated = await decompress2(await maybeDecrypt2(value, key), compressionStats);
53008
- await recordCompression2(compressionStats, "deserialize");
53009
- return deserialize5(inflated, {
53010
- global: global2,
53011
- extraRevivers: {
53012
- ...getStreamAndRequestRevivers2(getWorkflowRevivers(global2)),
53013
- ...extraRevivers
53014
- }
53015
- });
53179
+ async function hydrateStepReturnValue(value, _runId, key, global2 = globalThis, extraRevivers = {}, prepared) {
53180
+ return deserializePreparedReplayPayload(prepared ?? await prepareReplayPayload(value, key), global2, extraRevivers);
53016
53181
  }
53017
53182
  function getStreamAndRequestReducers2(allReducers) {
53018
53183
  const extra = {};
@@ -53032,7 +53197,7 @@ function getStreamAndRequestRevivers2(allRevivers) {
53032
53197
  }
53033
53198
  return extra;
53034
53199
  }
53035
- 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;
53036
53201
  var init_serialization4 = __esm({
53037
53202
  "../core/dist/serialization.js"() {
53038
53203
  "use strict";
@@ -53274,6 +53439,19 @@ var init_serialization4 = __esm({
53274
53439
  w.reject(abortError);
53275
53440
  }
53276
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
+ });
53277
53455
  }
53278
53456
  };
53279
53457
  __name(getAllBaseReducers2, "getAllBaseReducers");
@@ -53295,7 +53473,14 @@ var init_serialization4 = __esm({
53295
53473
  __name(getWorkflowRevivers, "getWorkflowRevivers");
53296
53474
  __name(getStepRevivers2, "getStepRevivers");
53297
53475
  __name(maybeEncrypt, "maybeEncrypt");
53298
- __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");
53299
53484
  __name(hydrateWorkflowArguments, "hydrateWorkflowArguments");
53300
53485
  __name(dehydrateWorkflowReturnValue, "dehydrateWorkflowReturnValue");
53301
53486
  __name(hydrateWorkflowReturnValue2, "hydrateWorkflowReturnValue");
@@ -54401,6 +54586,8 @@ var init_error_codes = __esm2({
54401
54586
  REPLAY_DIVERGENCE: "REPLAY_DIVERGENCE",
54402
54587
  /** Run exceeded the maximum number of queue deliveries */
54403
54588
  MAX_DELIVERIES_EXCEEDED: "MAX_DELIVERIES_EXCEEDED",
54589
+ /** Run exceeded the maximum number of events per run */
54590
+ MAX_EVENTS_EXCEEDED: "MAX_EVENTS_EXCEEDED",
54404
54591
  /** Workflow replay exceeded the maximum allowed duration */
54405
54592
  REPLAY_TIMEOUT: "REPLAY_TIMEOUT",
54406
54593
  /** World response violated the SDK contract and cannot be retried safely */
@@ -71494,6 +71681,7 @@ var init_events = __esm2({
71494
71681
  correlationId: external_exports.string(),
71495
71682
  eventData: external_exports.object({
71496
71683
  token: external_exports.string(),
71684
+ tokenRetentionUntil: external_exports.coerce.date().optional(),
71497
71685
  metadata: SerializedDataSchema.optional(),
71498
71686
  isWebhook: external_exports.boolean().optional(),
71499
71687
  isSystem: external_exports.boolean().optional()
@@ -71661,6 +71849,10 @@ var init_events = __esm2({
71661
71849
  }));
71662
71850
  }
71663
71851
  });
71852
+ function isTerminalWorkflowRunStatus(status) {
71853
+ return TERMINAL_WORKFLOW_RUN_STATUSES.includes(status);
71854
+ }
71855
+ __name(isTerminalWorkflowRunStatus, "isTerminalWorkflowRunStatus");
71664
71856
  var WorkflowRunStatusSchema;
71665
71857
  var TerminalWorkflowRunStatusSchema;
71666
71858
  var TERMINAL_WORKFLOW_RUN_STATUSES;
@@ -71684,6 +71876,7 @@ var init_runs = __esm2({
71684
71876
  "cancelled"
71685
71877
  ]);
71686
71878
  TERMINAL_WORKFLOW_RUN_STATUSES = TerminalWorkflowRunStatusSchema.options;
71879
+ __name2(isTerminalWorkflowRunStatus, "isTerminalWorkflowRunStatus");
71687
71880
  WorkflowRunBaseSchema = external_exports.object({
71688
71881
  runId: external_exports.string(),
71689
71882
  status: WorkflowRunStatusSchema,
@@ -73162,296 +73355,13 @@ var init_devalue = __esm2({
73162
73355
  init_utils();
73163
73356
  }
73164
73357
  });
73165
- function createFlushableState() {
73166
- const state = {
73167
- ...withResolvers(),
73168
- pendingOps: 0,
73169
- doneResolved: false,
73170
- streamEnded: false
73171
- };
73172
- state.promise.catch(() => {
73173
- });
73174
- return state;
73175
- }
73176
- __name(createFlushableState, "createFlushableState");
73177
- function isWritableUnlockedNotClosed(writable) {
73178
- if (writable.locked) return false;
73179
- let writer;
73180
- try {
73181
- writer = writable.getWriter();
73182
- } catch {
73183
- return false;
73184
- }
73185
- try {
73186
- writer.releaseLock();
73187
- } catch {
73188
- return false;
73189
- }
73190
- return true;
73191
- }
73192
- __name(isWritableUnlockedNotClosed, "isWritableUnlockedNotClosed");
73193
- function isReadableUnlockedNotClosed(readable) {
73194
- if (readable.locked) return false;
73195
- let reader;
73196
- try {
73197
- reader = readable.getReader();
73198
- } catch {
73199
- return false;
73200
- }
73201
- try {
73202
- reader.releaseLock();
73203
- } catch {
73204
- return false;
73205
- }
73206
- return true;
73207
- }
73208
- __name(isReadableUnlockedNotClosed, "isReadableUnlockedNotClosed");
73209
- function pollWritableLock(writable, state) {
73210
- if (state.writablePollingInterval !== void 0) {
73211
- return;
73212
- }
73213
- const intervalId = setInterval(() => {
73214
- if (state.doneResolved || state.streamEnded) {
73215
- clearInterval(intervalId);
73216
- state.writablePollingInterval = void 0;
73217
- return;
73218
- }
73219
- if (isWritableUnlockedNotClosed(writable) && state.pendingOps === 0) {
73220
- state.doneResolved = true;
73221
- state.resolve();
73222
- clearInterval(intervalId);
73223
- state.writablePollingInterval = void 0;
73224
- }
73225
- }, getLockPollIntervalMs());
73226
- state.writablePollingInterval = intervalId;
73227
- }
73228
- __name(pollWritableLock, "pollWritableLock");
73229
- function pollReadableLock(readable, state) {
73230
- if (state.readablePollingInterval !== void 0) {
73231
- return;
73232
- }
73233
- const intervalId = setInterval(() => {
73234
- if (state.doneResolved || state.streamEnded) {
73235
- clearInterval(intervalId);
73236
- state.readablePollingInterval = void 0;
73237
- return;
73238
- }
73239
- if (isReadableUnlockedNotClosed(readable) && state.pendingOps === 0) {
73240
- state.doneResolved = true;
73241
- state.resolve();
73242
- clearInterval(intervalId);
73243
- state.readablePollingInterval = void 0;
73244
- }
73245
- }, getLockPollIntervalMs());
73246
- state.readablePollingInterval = intervalId;
73247
- }
73248
- __name(pollReadableLock, "pollReadableLock");
73249
- async function flushablePipe(source, sink, state) {
73250
- const reader = source.getReader();
73251
- const writer = sink.getWriter();
73252
- let cancelReason;
73253
- try {
73254
- while (true) {
73255
- if (state.streamEnded) {
73256
- return;
73257
- }
73258
- const readResult = await Promise.race([
73259
- reader.read(),
73260
- writer.closed.then(() => {
73261
- throw new WorkflowRuntimeError("Writable stream closed prematurely");
73262
- })
73263
- ]);
73264
- if (state.streamEnded) {
73265
- return;
73266
- }
73267
- if (readResult.done) {
73268
- state.streamEnded = true;
73269
- await writer.close();
73270
- if (!state.doneResolved) {
73271
- state.doneResolved = true;
73272
- state.resolve();
73273
- }
73274
- return;
73275
- }
73276
- state.pendingOps++;
73277
- try {
73278
- await writer.write(readResult.value);
73279
- } finally {
73280
- state.pendingOps--;
73281
- }
73282
- }
73283
- } catch (err) {
73284
- state.streamEnded = true;
73285
- cancelReason = err;
73286
- if (!state.doneResolved) {
73287
- state.doneResolved = true;
73288
- state.reject(err);
73289
- }
73290
- throw err;
73291
- } finally {
73292
- reader.cancel(cancelReason).catch(() => {
73293
- });
73294
- reader.releaseLock();
73295
- writer.releaseLock();
73296
- }
73297
- }
73298
- __name(flushablePipe, "flushablePipe");
73299
- var LOCK_POLL_INTERVAL_MS;
73300
- var getLockPollIntervalMs;
73301
- var init_flushable_stream = __esm2({
73302
- "../core/dist/flushable-stream.js"() {
73303
- "use strict";
73304
- init_dist2();
73305
- init_dist();
73306
- init_dist4();
73307
- LOCK_POLL_INTERVAL_MS = 10;
73308
- getLockPollIntervalMs = /* @__PURE__ */ __name2(() => envNumber("WORKFLOW_LOCK_POLL_INTERVAL_MS", LOCK_POLL_INTERVAL_MS, {
73309
- integer: true,
73310
- min: 1
73311
- }), "getLockPollIntervalMs");
73312
- __name2(createFlushableState, "createFlushableState");
73313
- __name2(isWritableUnlockedNotClosed, "isWritableUnlockedNotClosed");
73314
- __name2(isReadableUnlockedNotClosed, "isReadableUnlockedNotClosed");
73315
- __name2(pollWritableLock, "pollWritableLock");
73316
- __name2(pollReadableLock, "pollReadableLock");
73317
- __name2(flushablePipe, "flushablePipe");
73318
- }
73319
- });
73320
- function getStepIdAliasCandidates(stepId) {
73321
- const parts = stepId.split("//");
73322
- if (parts.length !== 3 || parts[0] !== "step") {
73323
- return [];
73324
- }
73325
- const modulePath = parts[1];
73326
- const fnName = parts[2];
73327
- const modulePathAliases = /* @__PURE__ */ new Set();
73328
- const addAlias = /* @__PURE__ */ __name2((aliasModulePath) => {
73329
- if (aliasModulePath !== modulePath) {
73330
- modulePathAliases.add(aliasModulePath);
73331
- }
73332
- }, "addAlias");
73333
- if (modulePath.startsWith("./workflows/")) {
73334
- const workflowRelativePath = modulePath.slice("./".length);
73335
- addAlias(`./example/${workflowRelativePath}`);
73336
- addAlias(`./src/${workflowRelativePath}`);
73337
- } else if (modulePath.startsWith("./example/workflows/")) {
73338
- const workflowRelativePath = modulePath.slice("./example/".length);
73339
- addAlias(`./${workflowRelativePath}`);
73340
- addAlias(`./src/${workflowRelativePath}`);
73341
- } else if (modulePath.startsWith("./src/workflows/")) {
73342
- const workflowRelativePath = modulePath.slice("./src/".length);
73343
- addAlias(`./${workflowRelativePath}`);
73344
- addAlias(`./example/${workflowRelativePath}`);
73345
- }
73346
- return Array.from(modulePathAliases, (aliasModulePath) => `step//${aliasModulePath}//${fnName}`);
73347
- }
73348
- __name(getStepIdAliasCandidates, "getStepIdAliasCandidates");
73349
- function getBuiltinResponseStepAlias(stepId) {
73350
- if (!BUILTIN_RESPONSE_STEP_NAMES.has(stepId)) {
73351
- return void 0;
73352
- }
73353
- for (const [registeredStepId, stepFn] of registeredSteps.entries()) {
73354
- if (registeredStepId.endsWith(`//${stepId}`)) {
73355
- return stepFn;
73356
- }
73357
- }
73358
- return void 0;
73359
- }
73360
- __name(getBuiltinResponseStepAlias, "getBuiltinResponseStepAlias");
73361
- function getStepFunction(stepId) {
73362
- const directMatch = registeredSteps.get(stepId);
73363
- if (directMatch) {
73364
- return directMatch;
73365
- }
73366
- for (const aliasStepId of getStepIdAliasCandidates(stepId)) {
73367
- const aliasMatch = registeredSteps.get(aliasStepId);
73368
- if (aliasMatch) {
73369
- return aliasMatch;
73370
- }
73371
- }
73372
- const builtinAliasMatch = getBuiltinResponseStepAlias(stepId);
73373
- if (builtinAliasMatch) {
73374
- return builtinAliasMatch;
73375
- }
73376
- return void 0;
73377
- }
73378
- __name(getStepFunction, "getStepFunction");
73379
- var RegisteredStepsKey;
73380
- var globalSymbols;
73381
- var registeredSteps;
73382
- var BUILTIN_RESPONSE_STEP_NAMES;
73383
- var init_private = __esm2({
73384
- "../core/dist/private.js"() {
73385
- "use strict";
73386
- init_dist();
73387
- RegisteredStepsKey = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps");
73388
- globalSymbols = globalThis;
73389
- registeredSteps = globalSymbols[RegisteredStepsKey] ??= /* @__PURE__ */ new Map();
73390
- BUILTIN_RESPONSE_STEP_NAMES = /* @__PURE__ */ new Set([
73391
- "__builtin_response_array_buffer",
73392
- "__builtin_response_json",
73393
- "__builtin_response_text"
73394
- ]);
73395
- __name2(getStepIdAliasCandidates, "getStepIdAliasCandidates");
73396
- __name2(getBuiltinResponseStepAlias, "getBuiltinResponseStepAlias");
73397
- __name2(getStepFunction, "getStepFunction");
73398
- }
73399
- });
73400
- function assertWorldSupportsRuntimeProtocol(world) {
73401
- if (world.specVersion === SPEC_VERSION_CURRENT) {
73402
- return;
73403
- }
73404
- const supportedVersion = world.specVersion ?? "none";
73405
- throw new WorkflowRuntimeError(`This Workflow runtime requires a World with matching spec version ${SPEC_VERSION_CURRENT}, but the configured World declares spec version ${supportedVersion}. Install a World package version compatible with the current Workflow runtime.`);
73406
- }
73407
- __name(assertWorldSupportsRuntimeProtocol, "assertWorldSupportsRuntimeProtocol");
73408
- var init_world_compatibility = __esm2({
73409
- "../core/dist/runtime/world-compatibility.js"() {
73410
- "use strict";
73411
- init_dist2();
73412
- init_dist4();
73413
- __name2(assertWorldSupportsRuntimeProtocol, "assertWorldSupportsRuntimeProtocol");
73414
- }
73415
- });
73416
- async function getWorldLazy() {
73417
- const g = globalThis;
73418
- if (g[WorldCacheKey]) {
73419
- assertWorldSupportsRuntimeProtocol(g[WorldCacheKey]);
73420
- return g[WorldCacheKey];
73421
- }
73422
- if (g[WorldCachePromiseKey]) {
73423
- g[WorldCacheKey] = await g[WorldCachePromiseKey];
73424
- assertWorldSupportsRuntimeProtocol(g[WorldCacheKey]);
73425
- return g[WorldCacheKey];
73426
- }
73427
- const getWorldFn = g[GetWorldFnKey];
73428
- if (getWorldFn) {
73429
- const world = await getWorldFn();
73430
- assertWorldSupportsRuntimeProtocol(world);
73431
- return world;
73432
- }
73433
- 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.");
73434
- }
73435
- __name(getWorldLazy, "getWorldLazy");
73436
- var WorldCacheKey;
73437
- var WorldCachePromiseKey;
73438
- var GetWorldFnKey;
73439
- var init_get_world_lazy = __esm2({
73440
- "../core/dist/runtime/get-world-lazy.js"() {
73441
- "use strict";
73442
- init_world_compatibility();
73443
- WorldCacheKey = /* @__PURE__ */ Symbol.for("@workflow/world//cache");
73444
- WorldCachePromiseKey = /* @__PURE__ */ Symbol.for("@workflow/world//cachePromise");
73445
- GetWorldFnKey = /* @__PURE__ */ Symbol.for("@workflow/world//getWorldFn");
73446
- __name2(getWorldLazy, "getWorldLazy");
73447
- }
73448
- });
73449
73358
  var STABLE_ULID;
73450
73359
  var STREAM_NAME_SYMBOL;
73451
73360
  var STREAM_TYPE_SYMBOL;
73452
73361
  var STREAM_FRAMING_SYMBOL;
73453
73362
  var STREAM_SERVER_RUN_ID_SYMBOL;
73454
73363
  var STREAM_SERVER_DEPLOYMENT_ID_SYMBOL;
73364
+ var STREAM_WRITE_BATCH_SYMBOL;
73455
73365
  var BODY_INIT_SYMBOL;
73456
73366
  var WEBHOOK_RESPONSE_WRITABLE;
73457
73367
  var WORKFLOW_CLASS_REGISTRY;
@@ -73468,6 +73378,7 @@ var init_symbols = __esm2({
73468
73378
  STREAM_FRAMING_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_FRAMING");
73469
73379
  STREAM_SERVER_RUN_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_RUN_ID");
73470
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");
73471
73382
  BODY_INIT_SYMBOL = /* @__PURE__ */ Symbol.for("BODY_INIT");
73472
73383
  WEBHOOK_RESPONSE_WRITABLE = /* @__PURE__ */ Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
73473
73384
  WORKFLOW_CLASS_REGISTRY = /* @__PURE__ */ Symbol.for("workflow-class-registry");
@@ -73477,6 +73388,443 @@ var init_symbols = __esm2({
73477
73388
  ABORT_READER_CANCEL = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_READER_CANCEL");
73478
73389
  }
73479
73390
  });
73391
+ function createFlushableState() {
73392
+ const state = {
73393
+ ...withResolvers(),
73394
+ pendingOps: 0,
73395
+ doneResolved: false,
73396
+ streamEnded: false
73397
+ };
73398
+ state.promise.catch(() => {
73399
+ });
73400
+ return state;
73401
+ }
73402
+ __name(createFlushableState, "createFlushableState");
73403
+ function isWritableUnlockedNotClosed(writable) {
73404
+ if (writable.locked) return false;
73405
+ let writer;
73406
+ try {
73407
+ writer = writable.getWriter();
73408
+ } catch {
73409
+ return false;
73410
+ }
73411
+ try {
73412
+ writer.releaseLock();
73413
+ } catch {
73414
+ return false;
73415
+ }
73416
+ return true;
73417
+ }
73418
+ __name(isWritableUnlockedNotClosed, "isWritableUnlockedNotClosed");
73419
+ function isReadableUnlockedNotClosed(readable) {
73420
+ if (readable.locked) return false;
73421
+ let reader;
73422
+ try {
73423
+ reader = readable.getReader();
73424
+ } catch {
73425
+ return false;
73426
+ }
73427
+ try {
73428
+ reader.releaseLock();
73429
+ } catch {
73430
+ return false;
73431
+ }
73432
+ return true;
73433
+ }
73434
+ __name(isReadableUnlockedNotClosed, "isReadableUnlockedNotClosed");
73435
+ function pollWritableLock(writable, state) {
73436
+ if (state.writablePollingInterval !== void 0) {
73437
+ return;
73438
+ }
73439
+ const intervalId = setInterval(() => {
73440
+ if (state.doneResolved || state.streamEnded) {
73441
+ clearInterval(intervalId);
73442
+ state.writablePollingInterval = void 0;
73443
+ return;
73444
+ }
73445
+ if (isWritableUnlockedNotClosed(writable) && state.pendingOps === 0) {
73446
+ state.doneResolved = true;
73447
+ state.resolve();
73448
+ clearInterval(intervalId);
73449
+ state.writablePollingInterval = void 0;
73450
+ }
73451
+ }, getLockPollIntervalMs());
73452
+ state.writablePollingInterval = intervalId;
73453
+ }
73454
+ __name(pollWritableLock, "pollWritableLock");
73455
+ function pollReadableLock(readable, state) {
73456
+ if (state.readablePollingInterval !== void 0) {
73457
+ return;
73458
+ }
73459
+ const intervalId = setInterval(() => {
73460
+ if (state.doneResolved || state.streamEnded) {
73461
+ clearInterval(intervalId);
73462
+ state.readablePollingInterval = void 0;
73463
+ return;
73464
+ }
73465
+ if (isReadableUnlockedNotClosed(readable) && state.pendingOps === 0) {
73466
+ state.doneResolved = true;
73467
+ state.resolve();
73468
+ clearInterval(intervalId);
73469
+ state.readablePollingInterval = void 0;
73470
+ }
73471
+ }, getLockPollIntervalMs());
73472
+ state.readablePollingInterval = intervalId;
73473
+ }
73474
+ __name(pollReadableLock, "pollReadableLock");
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) {
73481
+ const reader = source.getReader();
73482
+ const writer = sink.getWriter();
73483
+ let cancelReason;
73484
+ try {
73485
+ while (true) {
73486
+ if (state.streamEnded) {
73487
+ return;
73488
+ }
73489
+ const readResult = await Promise.race([
73490
+ reader.read(),
73491
+ writer.closed.then(() => {
73492
+ throw new WorkflowRuntimeError("Writable stream closed prematurely");
73493
+ })
73494
+ ]);
73495
+ if (state.streamEnded) {
73496
+ return;
73497
+ }
73498
+ if (readResult.done) {
73499
+ state.streamEnded = true;
73500
+ await writer.close();
73501
+ if (!state.doneResolved) {
73502
+ state.doneResolved = true;
73503
+ state.resolve();
73504
+ }
73505
+ return;
73506
+ }
73507
+ state.pendingOps++;
73508
+ try {
73509
+ await writer.write(readResult.value);
73510
+ } finally {
73511
+ state.pendingOps--;
73512
+ }
73513
+ }
73514
+ } catch (err) {
73515
+ state.streamEnded = true;
73516
+ cancelReason = err;
73517
+ if (!state.doneResolved) {
73518
+ state.doneResolved = true;
73519
+ state.reject(err);
73520
+ }
73521
+ throw err;
73522
+ } finally {
73523
+ reader.cancel(cancelReason).catch(() => {
73524
+ });
73525
+ reader.releaseLock();
73526
+ writer.releaseLock();
73527
+ }
73528
+ }
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;
73655
+ var LOCK_POLL_INTERVAL_MS;
73656
+ var getLockPollIntervalMs;
73657
+ var init_flushable_stream = __esm2({
73658
+ "../core/dist/flushable-stream.js"() {
73659
+ "use strict";
73660
+ init_dist2();
73661
+ init_dist();
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");
73679
+ LOCK_POLL_INTERVAL_MS = 10;
73680
+ getLockPollIntervalMs = /* @__PURE__ */ __name2(() => envNumber("WORKFLOW_LOCK_POLL_INTERVAL_MS", LOCK_POLL_INTERVAL_MS, {
73681
+ integer: true,
73682
+ min: 1
73683
+ }), "getLockPollIntervalMs");
73684
+ __name2(createFlushableState, "createFlushableState");
73685
+ __name2(isWritableUnlockedNotClosed, "isWritableUnlockedNotClosed");
73686
+ __name2(isReadableUnlockedNotClosed, "isReadableUnlockedNotClosed");
73687
+ __name2(pollWritableLock, "pollWritableLock");
73688
+ __name2(pollReadableLock, "pollReadableLock");
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");
73697
+ }
73698
+ });
73699
+ function getStepIdAliasCandidates(stepId) {
73700
+ const parts = stepId.split("//");
73701
+ if (parts.length !== 3 || parts[0] !== "step") {
73702
+ return [];
73703
+ }
73704
+ const modulePath = parts[1];
73705
+ const fnName = parts[2];
73706
+ const modulePathAliases = /* @__PURE__ */ new Set();
73707
+ const addAlias = /* @__PURE__ */ __name2((aliasModulePath) => {
73708
+ if (aliasModulePath !== modulePath) {
73709
+ modulePathAliases.add(aliasModulePath);
73710
+ }
73711
+ }, "addAlias");
73712
+ if (modulePath.startsWith("./workflows/")) {
73713
+ const workflowRelativePath = modulePath.slice("./".length);
73714
+ addAlias(`./example/${workflowRelativePath}`);
73715
+ addAlias(`./src/${workflowRelativePath}`);
73716
+ } else if (modulePath.startsWith("./example/workflows/")) {
73717
+ const workflowRelativePath = modulePath.slice("./example/".length);
73718
+ addAlias(`./${workflowRelativePath}`);
73719
+ addAlias(`./src/${workflowRelativePath}`);
73720
+ } else if (modulePath.startsWith("./src/workflows/")) {
73721
+ const workflowRelativePath = modulePath.slice("./src/".length);
73722
+ addAlias(`./${workflowRelativePath}`);
73723
+ addAlias(`./example/${workflowRelativePath}`);
73724
+ }
73725
+ return Array.from(modulePathAliases, (aliasModulePath) => `step//${aliasModulePath}//${fnName}`);
73726
+ }
73727
+ __name(getStepIdAliasCandidates, "getStepIdAliasCandidates");
73728
+ function getBuiltinResponseStepAlias(stepId) {
73729
+ if (!BUILTIN_RESPONSE_STEP_NAMES.has(stepId)) {
73730
+ return void 0;
73731
+ }
73732
+ for (const [registeredStepId, stepFn] of registeredSteps.entries()) {
73733
+ if (registeredStepId.endsWith(`//${stepId}`)) {
73734
+ return stepFn;
73735
+ }
73736
+ }
73737
+ return void 0;
73738
+ }
73739
+ __name(getBuiltinResponseStepAlias, "getBuiltinResponseStepAlias");
73740
+ function getStepFunction(stepId) {
73741
+ const directMatch = registeredSteps.get(stepId);
73742
+ if (directMatch) {
73743
+ return directMatch;
73744
+ }
73745
+ for (const aliasStepId of getStepIdAliasCandidates(stepId)) {
73746
+ const aliasMatch = registeredSteps.get(aliasStepId);
73747
+ if (aliasMatch) {
73748
+ return aliasMatch;
73749
+ }
73750
+ }
73751
+ const builtinAliasMatch = getBuiltinResponseStepAlias(stepId);
73752
+ if (builtinAliasMatch) {
73753
+ return builtinAliasMatch;
73754
+ }
73755
+ return void 0;
73756
+ }
73757
+ __name(getStepFunction, "getStepFunction");
73758
+ var RegisteredStepsKey;
73759
+ var globalSymbols;
73760
+ var registeredSteps;
73761
+ var BUILTIN_RESPONSE_STEP_NAMES;
73762
+ var init_private = __esm2({
73763
+ "../core/dist/private.js"() {
73764
+ "use strict";
73765
+ init_dist();
73766
+ RegisteredStepsKey = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps");
73767
+ globalSymbols = globalThis;
73768
+ registeredSteps = globalSymbols[RegisteredStepsKey] ??= /* @__PURE__ */ new Map();
73769
+ BUILTIN_RESPONSE_STEP_NAMES = /* @__PURE__ */ new Set([
73770
+ "__builtin_response_array_buffer",
73771
+ "__builtin_response_json",
73772
+ "__builtin_response_text"
73773
+ ]);
73774
+ __name2(getStepIdAliasCandidates, "getStepIdAliasCandidates");
73775
+ __name2(getBuiltinResponseStepAlias, "getBuiltinResponseStepAlias");
73776
+ __name2(getStepFunction, "getStepFunction");
73777
+ }
73778
+ });
73779
+ function assertWorldSupportsRuntimeProtocol(world) {
73780
+ if (world.specVersion === SPEC_VERSION_CURRENT) {
73781
+ return;
73782
+ }
73783
+ const supportedVersion = world.specVersion ?? "none";
73784
+ throw new WorkflowRuntimeError(`This Workflow runtime requires a World with matching spec version ${SPEC_VERSION_CURRENT}, but the configured World declares spec version ${supportedVersion}. Install a World package version compatible with the current Workflow runtime.`);
73785
+ }
73786
+ __name(assertWorldSupportsRuntimeProtocol, "assertWorldSupportsRuntimeProtocol");
73787
+ var init_world_compatibility = __esm2({
73788
+ "../core/dist/runtime/world-compatibility.js"() {
73789
+ "use strict";
73790
+ init_dist2();
73791
+ init_dist4();
73792
+ __name2(assertWorldSupportsRuntimeProtocol, "assertWorldSupportsRuntimeProtocol");
73793
+ }
73794
+ });
73795
+ async function getWorldLazy() {
73796
+ const g = globalThis;
73797
+ if (g[WorldCacheKey]) {
73798
+ assertWorldSupportsRuntimeProtocol(g[WorldCacheKey]);
73799
+ return g[WorldCacheKey];
73800
+ }
73801
+ if (g[WorldCachePromiseKey]) {
73802
+ g[WorldCacheKey] = await g[WorldCachePromiseKey];
73803
+ assertWorldSupportsRuntimeProtocol(g[WorldCacheKey]);
73804
+ return g[WorldCacheKey];
73805
+ }
73806
+ const getWorldFn = g[GetWorldFnKey];
73807
+ if (getWorldFn) {
73808
+ const world = await getWorldFn();
73809
+ assertWorldSupportsRuntimeProtocol(world);
73810
+ return world;
73811
+ }
73812
+ 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.");
73813
+ }
73814
+ __name(getWorldLazy, "getWorldLazy");
73815
+ var WorldCacheKey;
73816
+ var WorldCachePromiseKey;
73817
+ var GetWorldFnKey;
73818
+ var init_get_world_lazy = __esm2({
73819
+ "../core/dist/runtime/get-world-lazy.js"() {
73820
+ "use strict";
73821
+ init_world_compatibility();
73822
+ WorldCacheKey = /* @__PURE__ */ Symbol.for("@workflow/world//cache");
73823
+ WorldCachePromiseKey = /* @__PURE__ */ Symbol.for("@workflow/world//cachePromise");
73824
+ GetWorldFnKey = /* @__PURE__ */ Symbol.for("@workflow/world//getWorldFn");
73825
+ __name2(getWorldLazy, "getWorldLazy");
73826
+ }
73827
+ });
73480
73828
  function getRegistry(global2 = globalThis) {
73481
73829
  const g = global2;
73482
73830
  let registry22 = g[WORKFLOW_CLASS_REGISTRY];
@@ -79435,7 +79783,7 @@ var version2;
79435
79783
  var init_version = __esm2({
79436
79784
  "../core/dist/version.js"() {
79437
79785
  "use strict";
79438
- version2 = "5.0.0-beta.35";
79786
+ version2 = "5.0.0-beta.36";
79439
79787
  }
79440
79788
  });
79441
79789
  function getWorkflowQueueName(workflowName, namespace) {
@@ -80782,18 +81130,25 @@ __export2(resume_hook_exports, {
80782
81130
  resumeHook: /* @__PURE__ */ __name(() => resumeHook, "resumeHook"),
80783
81131
  resumeWebhook: /* @__PURE__ */ __name(() => resumeWebhook, "resumeWebhook")
80784
81132
  });
80785
- async function getHookByTokenWithKey(token) {
81133
+ async function getHookAndRun(token) {
80786
81134
  const world = await getWorldLazy();
80787
81135
  const hook = await world.hooks.getByToken(token);
80788
81136
  const run22 = await world.runs.get(hook.runId);
80789
- 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);
80790
81146
  const encryptionKey = rawKey ? await importKey(rawKey) : void 0;
80791
81147
  if (typeof hook.metadata !== "undefined") {
80792
81148
  hook.metadata = await hydrateStepArguments(hook.metadata, hook.runId, encryptionKey);
80793
81149
  }
80794
81150
  return {
80795
81151
  hook,
80796
- run: run22,
80797
81152
  encryptionKey
80798
81153
  };
80799
81154
  }
@@ -80810,27 +81165,27 @@ async function resumeHook(tokenOrHook, payload, encryptionKeyOverride) {
80810
81165
  try {
80811
81166
  let hook;
80812
81167
  let workflowRun;
80813
- let encryptionKey;
80814
81168
  if (typeof tokenOrHook === "string") {
80815
- const result = await getHookByTokenWithKey(tokenOrHook);
81169
+ const result = await getHookAndRun(tokenOrHook);
80816
81170
  hook = result.hook;
80817
81171
  workflowRun = result.run;
80818
- encryptionKey = encryptionKeyOverride ?? result.encryptionKey;
80819
81172
  } else {
80820
81173
  hook = tokenOrHook;
80821
81174
  workflowRun = await world.runs.get(hook.runId);
80822
- if (encryptionKeyOverride) {
80823
- encryptionKey = encryptionKeyOverride;
80824
- } else {
80825
- const rawKey = await world.getEncryptionKeyForRun?.(workflowRun);
80826
- encryptionKey = rawKey ? await importKey(rawKey) : void 0;
80827
- }
80828
81175
  }
80829
81176
  span?.setAttributes({
80830
81177
  ...HookToken(hook.token),
80831
81178
  ...HookId(hook.hookId),
80832
81179
  ...WorkflowRunId(hook.runId)
80833
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
+ }
80834
81189
  const rawVersion = workflowRun.executionContext?.workflowCoreVersion;
80835
81190
  const capabilities = getRunCapabilities(typeof rawVersion === "string" ? rawVersion : void 0);
80836
81191
  if (!capabilities.supportedFormats.has(SerializationFormat.ENCRYPTED)) {
@@ -80944,6 +81299,7 @@ var init_resume_hook = __esm2({
80944
81299
  init_get_world_lazy();
80945
81300
  init_helpers();
80946
81301
  init_wait_until();
81302
+ __name2(getHookAndRun, "getHookAndRun");
80947
81303
  __name2(getHookByTokenWithKey, "getHookByTokenWithKey");
80948
81304
  __name2(getHookByToken, "getHookByToken");
80949
81305
  __name2(resumeHook, "resumeHook");
@@ -82077,10 +82433,6 @@ function getStepRevivers(global2 = globalThis, ops, runId, cryptoKey, deployment
82077
82433
  };
82078
82434
  }
82079
82435
  __name(getStepRevivers, "getStepRevivers");
82080
- async function maybeDecrypt(data, key) {
82081
- return decrypt2(data, key);
82082
- }
82083
- __name(maybeDecrypt, "maybeDecrypt");
82084
82436
  async function dehydrateWorkflowArguments(value, runId, key, ops = [], global2 = globalThis, v1Compat = false, framedByteStreams = false, compression = false) {
82085
82437
  if (v1Compat) {
82086
82438
  const str = stringify(value, getExternalReducers(global2, ops, runId, key, framedByteStreams));
@@ -82186,7 +82538,7 @@ async function dehydrateStepReturnValue(value, runId, key, ops = [], global2 = g
82186
82538
  __name(dehydrateStepReturnValue, "dehydrateStepReturnValue");
82187
82539
  async function hydrateRunError(value, runId, key, ops = [], global2 = globalThis, extraRevivers = {}) {
82188
82540
  const compressionStats = {};
82189
- const decrypted = await decompress(await maybeDecrypt(value, key), compressionStats);
82541
+ const decrypted = await decompress(await decrypt2(value, key), compressionStats);
82190
82542
  await recordCompression(compressionStats, "deserialize");
82191
82543
  if (!(decrypted instanceof Uint8Array)) {
82192
82544
  return unflatten(decrypted, {
@@ -82483,6 +82835,16 @@ var init_serialization2 = __esm2({
82483
82835
  for (const w of waiters) w.reject(abortError);
82484
82836
  }
82485
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
+ });
82486
82848
  }
82487
82849
  };
82488
82850
  __name2(getAllBaseReducers, "getAllBaseReducers");
@@ -82501,7 +82863,6 @@ var init_serialization2 = __esm2({
82501
82863
  __name2(getForwardedWritableEncryptionKey, "getForwardedWritableEncryptionKey");
82502
82864
  __name2(getExternalRevivers, "getExternalRevivers");
82503
82865
  __name2(getStepRevivers, "getStepRevivers");
82504
- __name2(maybeDecrypt, "maybeDecrypt");
82505
82866
  __name2(dehydrateWorkflowArguments, "dehydrateWorkflowArguments");
82506
82867
  __name2(hydrateWorkflowReturnValue, "hydrateWorkflowReturnValue");
82507
82868
  __name2(dehydrateStepArguments, "dehydrateStepArguments");
@@ -82924,7 +83285,7 @@ __name2(start, "start");
82924
83285
  value: "start",
82925
83286
  configurable: true
82926
83287
  });
82927
- })(start, "step//@workflow/core/runtime/start@5.0.0-beta.35//start");
83288
+ })(start, "step//@workflow/core/runtime/start@5.0.0-beta.36//start");
82928
83289
  async function wakeUpRun(world, runId, options) {
82929
83290
  try {
82930
83291
  const run22 = await world.runs.get(runId, {
@@ -83260,7 +83621,7 @@ var Run = class _Run {
83260
83621
  value: "wakeUp",
83261
83622
  configurable: true
83262
83623
  });
83263
- })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#wakeUp");
83624
+ })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#wakeUp");
83264
83625
  (function(__wf_fn, __wf_id) {
83265
83626
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83266
83627
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83269,7 +83630,7 @@ var Run = class _Run {
83269
83630
  value: "cancel",
83270
83631
  configurable: true
83271
83632
  });
83272
- })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#cancel");
83633
+ })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#cancel");
83273
83634
  (function(__wf_fn, __wf_id) {
83274
83635
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83275
83636
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83278,7 +83639,7 @@ var Run = class _Run {
83278
83639
  value: "getReadable",
83279
83640
  configurable: true
83280
83641
  });
83281
- })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#getReadable");
83642
+ })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#getReadable");
83282
83643
  (function(__wf_fn, __wf_id) {
83283
83644
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83284
83645
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83287,7 +83648,7 @@ var Run = class _Run {
83287
83648
  value: "exists",
83288
83649
  configurable: true
83289
83650
  });
83290
- })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#exists");
83651
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#exists");
83291
83652
  (function(__wf_fn, __wf_id) {
83292
83653
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83293
83654
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83296,7 +83657,7 @@ var Run = class _Run {
83296
83657
  value: "status",
83297
83658
  configurable: true
83298
83659
  });
83299
- })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#status");
83660
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#status");
83300
83661
  (function(__wf_fn, __wf_id) {
83301
83662
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83302
83663
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83305,7 +83666,7 @@ var Run = class _Run {
83305
83666
  value: "returnValue",
83306
83667
  configurable: true
83307
83668
  });
83308
- })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#returnValue");
83669
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#returnValue");
83309
83670
  (function(__wf_fn, __wf_id) {
83310
83671
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83311
83672
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83314,7 +83675,7 @@ var Run = class _Run {
83314
83675
  value: "workflowName",
83315
83676
  configurable: true
83316
83677
  });
83317
- })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#workflowName");
83678
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#workflowName");
83318
83679
  (function(__wf_fn, __wf_id) {
83319
83680
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83320
83681
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83323,7 +83684,7 @@ var Run = class _Run {
83323
83684
  value: "createdAt",
83324
83685
  configurable: true
83325
83686
  });
83326
- })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#createdAt");
83687
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#createdAt");
83327
83688
  (function(__wf_fn, __wf_id) {
83328
83689
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83329
83690
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83332,7 +83693,7 @@ var Run = class _Run {
83332
83693
  value: "startedAt",
83333
83694
  configurable: true
83334
83695
  });
83335
- })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#startedAt");
83696
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#startedAt");
83336
83697
  (function(__wf_fn, __wf_id) {
83337
83698
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83338
83699
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83341,7 +83702,7 @@ var Run = class _Run {
83341
83702
  value: "completedAt",
83342
83703
  configurable: true
83343
83704
  });
83344
- })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#completedAt");
83705
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.36//Run#completedAt");
83345
83706
  (function(__wf_cls, __wf_id) {
83346
83707
  var __wf_sym = /* @__PURE__ */ Symbol.for("workflow-class-registry"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83347
83708
  __wf_reg.set(__wf_id, __wf_cls);
@@ -83351,7 +83712,7 @@ var Run = class _Run {
83351
83712
  enumerable: false,
83352
83713
  configurable: false
83353
83714
  });
83354
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.35//Run");
83715
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.36//Run");
83355
83716
  async function fetch2(...args) {
83356
83717
  return globalThis.fetch(...args);
83357
83718
  }
@@ -83392,6 +83753,26 @@ async function addTenWorkflow(input) {
83392
83753
  __name(addTenWorkflow, "addTenWorkflow");
83393
83754
  __name2(addTenWorkflow, "addTenWorkflow");
83394
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";
83395
83776
  init_dist2();
83396
83777
  function redirectStackToCaller(err, stackStartFn) {
83397
83778
  const capture = Error.captureStackTrace;
@@ -83880,7 +84261,7 @@ __export(dist_exports2, {
83880
84261
  parseVersion: () => parseVersion
83881
84262
  });
83882
84263
  init_dist5();
83883
- import { promises as fs6 } from "node:fs";
84264
+ import { promises as fs7 } from "node:fs";
83884
84265
  import { rm } from "node:fs/promises";
83885
84266
  import path10 from "node:path";
83886
84267
 
@@ -84450,6 +84831,21 @@ async function writeExclusive(filePath, data) {
84450
84831
  }
84451
84832
  }
84452
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");
84453
84849
  async function listJSONFiles(dirPath) {
84454
84850
  return listFilesByExtension(dirPath, ".json");
84455
84851
  }
@@ -85223,6 +85619,104 @@ async function isHookDisposalCommitted(basedir, hookId, tag) {
85223
85619
  return false;
85224
85620
  }
85225
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");
85226
85720
  function hookTokenClaimPath(basedir, token) {
85227
85721
  return path3.join(basedir, "hooks", "tokens", `${hashToken(token)}.json`);
85228
85722
  }
@@ -85481,7 +85975,7 @@ __name(findNewestIndexedHookCreatedEvent, "findNewestIndexedHookCreatedEvent");
85481
85975
  init_dist7();
85482
85976
  init_dist5();
85483
85977
  init_zod2();
85484
- import fs4 from "node:fs/promises";
85978
+ import fs5 from "node:fs/promises";
85485
85979
  import path7 from "node:path";
85486
85980
 
85487
85981
  // ../world-local/dist/storage/filters.js
@@ -85552,7 +86046,7 @@ function isMatchingHookCreatedEvent(event, matches) {
85552
86046
  __name(isMatchingHookCreatedEvent, "isMatchingHookCreatedEvent");
85553
86047
  async function isTerminalRunCache(basedir, runId, tag) {
85554
86048
  const run3 = await readJSONWithFallback(basedir, "runs", runId, WorkflowRunSchema2, tag);
85555
- return run3 ? isTerminalWorkflowRunStatus(run3.status) : false;
86049
+ return run3 ? isTerminalWorkflowRunStatus2(run3.status) : false;
85556
86050
  }
85557
86051
  __name(isTerminalRunCache, "isTerminalRunCache");
85558
86052
  async function findLiveHookCreatedEvent(basedir, index, matches, tag) {
@@ -85710,12 +86204,36 @@ async function deleteAllHooksForRun(basedir, runId) {
85710
86204
  __name(deleteAllHooksForRun, "deleteAllHooksForRun");
85711
86205
 
85712
86206
  // ../world-local/dist/storage/legacy.js
86207
+ init_dist7();
85713
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");
85714
86230
  async function handleLegacyEvent(basedir, runId, data, currentRun, params) {
85715
86231
  assertSafeEntityId("runId", runId);
85716
86232
  const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
85717
86233
  switch (data.eventType) {
85718
86234
  case "run_cancelled": {
86235
+ await writeExclusive(runTerminalMarkerPath(basedir, runId), "");
86236
+ await reapPendingHookEvents(basedir, runId);
85719
86237
  const now = /* @__PURE__ */ new Date();
85720
86238
  const run3 = {
85721
86239
  runId: currentRun.runId,
@@ -85755,7 +86273,11 @@ async function handleLegacyEvent(basedir, runId, data, currentRun, params) {
85755
86273
  };
85756
86274
  const compositeKey = `${runId}-${eventId}`;
85757
86275
  const eventPath = resolveWithinBase(basedir, "events", `${compositeKey}.json`);
85758
- 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
+ }
85759
86281
  return { event: stripEventDataRefs(event, resolveData) };
85760
86282
  }
85761
86283
  default:
@@ -85789,16 +86311,32 @@ function withRunFileLock(key, fn) {
85789
86311
  }
85790
86312
  __name(withRunFileLock, "withRunFileLock");
85791
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");
85792
86323
  return {
85793
- get: /* @__PURE__ */ __name((async (id, params) => {
85794
- assertSafeEntityId("runId", id);
85795
- const run3 = await readJSONWithFallback(basedir, "runs", id, WorkflowRunSchema2, tag);
85796
- if (!run3) {
85797
- throw new WorkflowRunNotFoundError2(id);
85798
- }
85799
- const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
85800
- return filterRunData(run3, resolveData);
85801
- }), "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"),
85802
86340
  list: /* @__PURE__ */ __name((async (params) => {
85803
86341
  const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
85804
86342
  const result = await paginatedFileSystemQuery({
@@ -85870,6 +86408,13 @@ function createRunsStorage(basedir, tag) {
85870
86408
  __name(createRunsStorage, "createRunsStorage");
85871
86409
 
85872
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");
85873
86418
  var HookTokenClaimSchema = external_exports2.object({
85874
86419
  // The token-claim writer below has always persisted `hookId`, but
85875
86420
  // this read schema previously omitted it, which is the bug fixed
@@ -85911,7 +86456,7 @@ async function isHookTokenClaimReleasable(basedir, claim, tag) {
85911
86456
  if (!owningRun) {
85912
86457
  return true;
85913
86458
  }
85914
- return isTerminalWorkflowRunStatus(owningRun.status);
86459
+ return isTerminalWorkflowRunStatus2(owningRun.status);
85915
86460
  }
85916
86461
  __name(isHookTokenClaimReleasable, "isHookTokenClaimReleasable");
85917
86462
  async function readHookRecoveryMarker(markerPath) {
@@ -86206,7 +86751,7 @@ function createEventsStorage(basedir, tag) {
86206
86751
  }
86207
86752
  const createsChildEntity = isChildEntityCreationEvent(data);
86208
86753
  const lazyStepStart = createsChildEntity && data.eventType === "step_started";
86209
- if (currentRun && isTerminalWorkflowRunStatus(currentRun.status)) {
86754
+ if (currentRun && isTerminalWorkflowRunStatus2(currentRun.status)) {
86210
86755
  if (data.eventType === "run_cancelled" && currentRun.status === "cancelled") {
86211
86756
  const event2 = {
86212
86757
  ...data,
@@ -86219,7 +86764,8 @@ function createEventsStorage(basedir, tag) {
86219
86764
  const resolveData2 = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
86220
86765
  return {
86221
86766
  event: stripEventDataRefs(event2, resolveData2),
86222
- run: currentRun
86767
+ run: currentRun,
86768
+ ...currentRun ? { maxEvents: getMaxEventsPerRun() } : {}
86223
86769
  };
86224
86770
  }
86225
86771
  if (data.eventType === "run_started") {
@@ -86250,7 +86796,7 @@ function createEventsStorage(basedir, tag) {
86250
86796
  if (isTerminalStepStatus(validatedStep.status)) {
86251
86797
  throw new EntityConflictError2(`Cannot modify step in terminal state "${validatedStep.status}"`);
86252
86798
  }
86253
- if (currentRun && isTerminalWorkflowRunStatus(currentRun.status)) {
86799
+ if (currentRun && isTerminalWorkflowRunStatus2(currentRun.status)) {
86254
86800
  if (validatedStep.status !== "running") {
86255
86801
  throw new RunExpiredError(`Cannot modify non-running step on run in terminal state "${currentRun.status}"`);
86256
86802
  }
@@ -86286,6 +86832,13 @@ function createEventsStorage(basedir, tag) {
86286
86832
  let wait;
86287
86833
  let stepCreatedLazily = false;
86288
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
+ }
86289
86842
  if (data.eventType === "run_created" && "eventData" in data) {
86290
86843
  const runData = data.eventData;
86291
86844
  validateAttributeChanges2(Object.entries(runData.attributes ?? {}).map(([key, value]) => ({
@@ -86319,7 +86872,7 @@ function createEventsStorage(basedir, tag) {
86319
86872
  } else if (data.eventType === "run_started") {
86320
86873
  if (currentRun) {
86321
86874
  if (currentRun.status === "running") {
86322
- return { run: currentRun };
86875
+ return { run: currentRun, maxEvents: getMaxEventsPerRun() };
86323
86876
  }
86324
86877
  run3 = await writeRunUnderLifecycleLock(basedir, effectiveRunId, tag, {
86325
86878
  runId: currentRun.runId,
@@ -86751,7 +87304,7 @@ function createEventsStorage(basedir, tag) {
86751
87304
  }
86752
87305
  const existingWait = await readJSONWithFallback(basedir, "waits", waitCompositeKey, WaitSchema2, tag);
86753
87306
  if (!existingWait) {
86754
- await fs4.unlink(lockPath).catch(() => {
87307
+ await fs5.unlink(lockPath).catch(() => {
86755
87308
  });
86756
87309
  throw new WorkflowWorldError2(`Wait "${data.correlationId}" not found`);
86757
87310
  }
@@ -86769,7 +87322,34 @@ function createEventsStorage(basedir, tag) {
86769
87322
  const compositeKey = `${effectiveRunId}-${eventId}`;
86770
87323
  const eventPath = taggedPath(basedir, "events", compositeKey, tag);
86771
87324
  const serializedEvent = JSON.stringify(event, jsonReplacer, 2);
86772
- 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
+ }
86773
87353
  if (!eventPublished) {
86774
87354
  if (data.eventType === "hook_created" && data.correlationId) {
86775
87355
  await repairHookEntityFromPersistedEvent(basedir, effectiveRunId, data.correlationId, eventId, tag);
@@ -86824,7 +87404,9 @@ function createEventsStorage(basedir, tag) {
86824
87404
  events,
86825
87405
  cursor,
86826
87406
  hasMore,
86827
- ...stepCreatedLazily ? { stepCreated: true } : {}
87407
+ ...stepCreatedLazily ? { stepCreated: true } : {},
87408
+ // Per-run event ceiling (mirrors the Vercel World).
87409
+ ...run3 ? { maxEvents: getMaxEventsPerRun() } : {}
86828
87410
  };
86829
87411
  }
86830
87412
  __name(createImpl, "createImpl");
@@ -86960,7 +87542,7 @@ __name(createStorage, "createStorage");
86960
87542
  init_node2();
86961
87543
  init_zod2();
86962
87544
  import { EventEmitter } from "node:events";
86963
- import fs5 from "node:fs/promises";
87545
+ import fs6 from "node:fs/promises";
86964
87546
  import path9 from "node:path";
86965
87547
  var monotonicUlid2 = monotonicFactory2(() => Math.random());
86966
87548
  var RunStreamsSchema = external_exports2.object({
@@ -86988,7 +87570,7 @@ function deserializeChunk(serialized) {
86988
87570
  __name(deserializeChunk, "deserializeChunk");
86989
87571
  async function listChunkEntries(chunksDir) {
86990
87572
  try {
86991
- return await fs5.readdir(chunksDir);
87573
+ return await fs6.readdir(chunksDir);
86992
87574
  } catch (error95) {
86993
87575
  if (error95.code === "ENOENT")
86994
87576
  return [];
@@ -87415,7 +87997,7 @@ function createWorld(args) {
87415
87997
  const fullIndexDir = path10.join(basedir, "hooks", indexDir);
87416
87998
  let keyDirEntries;
87417
87999
  try {
87418
- keyDirEntries = await fs6.readdir(fullIndexDir, {
88000
+ keyDirEntries = await fs7.readdir(fullIndexDir, {
87419
88001
  withFileTypes: true
87420
88002
  });
87421
88003
  } catch {
@@ -87427,12 +88009,12 @@ function createWorld(args) {
87427
88009
  await Promise.all(taggedEntryFiles.map((f) => deleteJSON(path10.join(keyDir, f))));
87428
88010
  }));
87429
88011
  }
87430
- 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(() => {
87431
88013
  });
87432
88014
  const chunksDir = path10.join(basedir, "streams", "chunks");
87433
88015
  let streamDirEntries;
87434
88016
  try {
87435
- streamDirEntries = await fs6.readdir(chunksDir, {
88017
+ streamDirEntries = await fs7.readdir(chunksDir, {
87436
88018
  withFileTypes: true
87437
88019
  });
87438
88020
  } catch {
@@ -87441,7 +88023,7 @@ function createWorld(args) {
87441
88023
  await Promise.all(streamDirEntries.filter((entry) => entry.isDirectory()).map(async (entry) => {
87442
88024
  const streamChunkDir = path10.join(chunksDir, entry.name);
87443
88025
  const taggedBinFiles = await listTaggedFilesByExtension(streamChunkDir, tag, ".bin");
87444
- 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(() => {
87445
88027
  })));
87446
88028
  }));
87447
88029
  clearCreatedFilesCache();
@@ -87589,6 +88171,9 @@ function classifyRunError(err) {
87589
88171
  if (CorruptedEventLogError.is(err)) {
87590
88172
  return RUN_ERROR_CODES2.CORRUPTED_EVENT_LOG;
87591
88173
  }
88174
+ if (MaxEventsExceededError.is(err)) {
88175
+ return RUN_ERROR_CODES2.MAX_EVENTS_EXCEEDED;
88176
+ }
87592
88177
  if (isWorldContractError(err) || isRetryableWorldError2(err)) {
87593
88178
  return RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR;
87594
88179
  }
@@ -87790,6 +88375,7 @@ var RUNTIME_ERROR_HINT = "This is an internal workflow SDK error, not a bug in y
87790
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.";
87791
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.';
87792
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.";
87793
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.";
87794
88380
  function describeError(err, errorCode) {
87795
88381
  const effectiveCode = errorCode ?? classifyRunError(err);
@@ -87835,6 +88421,13 @@ function describeError(err, errorCode) {
87835
88421
  hint: MAX_DELIVERIES_HINT
87836
88422
  };
87837
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
+ }
87838
88431
  if (effectiveCode === RUN_ERROR_CODES2.CORRUPTED_EVENT_LOG) {
87839
88432
  return {
87840
88433
  attribution: "sdk",
@@ -87857,6 +88450,129 @@ __name(describeError, "describeError");
87857
88450
  init_global2();
87858
88451
  init_logger2();
87859
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
+
87860
88576
  // ../core/dist/runtime/constants.js
87861
88577
  init_dist5();
87862
88578
  init_logger2();
@@ -87945,6 +88661,22 @@ function getMaxInlineSteps() {
87945
88661
  return parsed;
87946
88662
  }
87947
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");
87948
88680
  function isOptimisticInlineStartEnabled() {
87949
88681
  const raw = process.env.WORKFLOW_OPTIMISTIC_INLINE_START;
87950
88682
  if (raw === void 0 || raw === "")
@@ -88598,6 +89330,47 @@ async function executeStep(params) {
88598
89330
  span?.setAttributes({
88599
89331
  ...StepMaxRetries2(maxRetries)
88600
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
+ }
88601
89374
  const startErrorToResult = /* @__PURE__ */ __name((err) => {
88602
89375
  if (ThrottleError2.is(err)) {
88603
89376
  const retryAfter = Math.max(1, typeof err.retryAfter === "number" ? err.retryAfter : 1);
@@ -88634,7 +89407,10 @@ async function executeStep(params) {
88634
89407
  }
88635
89408
  return void 0;
88636
89409
  }, "startErrorToResult");
88637
- 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());
88638
89414
  let step;
88639
89415
  let stepStartPostSentAtMs;
88640
89416
  let optimisticStartSettled;
@@ -88652,18 +89428,26 @@ async function executeStep(params) {
88652
89428
  if (optimisticStart) {
88653
89429
  const startedPromise = (params.runReadyBarrier ?? Promise.resolve()).then(() => {
88654
89430
  stepStartPostSentAtMs = Date.now();
88655
- return world.events.create(workflowRunId, {
88656
- eventType: "step_started",
88657
- specVersion: SPEC_VERSION_CURRENT2,
88658
- correlationId: stepId,
88659
- eventData: {
88660
- stepName,
88661
- workflowName,
88662
- input: params.lazyStepInput,
88663
- // Inline-ownership stamp — see StepExecutorParams.ownerMessageId.
88664
- ...params.ownerMessageId !== void 0 ? { ownerMessageId: params.ownerMessageId } : {}
88665
- }
88666
- });
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
+ );
88667
89451
  });
88668
89452
  optimisticStartSettled = startedPromise.then(() => ({ ok: true }), (err) => ({ ok: false, err }));
88669
89453
  const now = /* @__PURE__ */ new Date();
@@ -88682,17 +89466,25 @@ async function executeStep(params) {
88682
89466
  try {
88683
89467
  const ownershipStamp = params.ownerMessageId !== void 0 ? { ownerMessageId: params.ownerMessageId } : {};
88684
89468
  stepStartPostSentAtMs = Date.now();
88685
- const startResult = await world.events.create(workflowRunId, {
88686
- eventType: "step_started",
88687
- specVersion: SPEC_VERSION_CURRENT2,
88688
- correlationId: stepId,
88689
- eventData: params.lazyStepInput !== void 0 ? {
88690
- stepName,
88691
- workflowName,
88692
- input: params.lazyStepInput,
88693
- ...ownershipStamp
88694
- } : { stepName, ...ownershipStamp }
88695
- });
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
+ );
88696
89488
  if (!startResult.step) {
88697
89489
  throw new WorkflowRuntimeError2(`step_started event for "${stepId}" did not return step entity`);
88698
89490
  }
@@ -89120,6 +89912,9 @@ async function executeStep(params) {
89120
89912
  }
89121
89913
  __name(executeStep, "executeStep");
89122
89914
 
89915
+ // ../core/dist/runtime.js
89916
+ init_private2();
89917
+
89123
89918
  // ../core/dist/runtime/step-ownership.js
89124
89919
  function isStepOwnershipActive(step) {
89125
89920
  return step.hasCreatedEvent === true && step.ownerMessageId !== void 0 && step.sawRetrying !== true;
@@ -89321,6 +90116,7 @@ async function handleSuspension({ suspension, world, run: run3, span, requestId,
89321
90116
  correlationId: queueItem.correlationId,
89322
90117
  eventData: {
89323
90118
  token: queueItem.token,
90119
+ tokenRetentionUntil: queueItem.tokenRetentionUntil,
89324
90120
  metadata: hookMetadata,
89325
90121
  isWebhook: queueItem.isWebhook ?? false,
89326
90122
  ...queueItem.isSystem && { isSystem: true }
@@ -90170,42 +90966,6 @@ function remapErrorStack(stack, filename, workflowCode2) {
90170
90966
  }
90171
90967
  __name(remapErrorStack, "remapErrorStack");
90172
90968
 
90173
- // ../core/dist/step-hydration-cache.js
90174
- var MAX_MEMOIZED_PRIMITIVE_LENGTH = 4096;
90175
- function isMemoizablePrimitive(value) {
90176
- if (value === null)
90177
- return true;
90178
- const t = typeof value;
90179
- if (t === "object" || t === "function")
90180
- return false;
90181
- if (t === "string") {
90182
- return value.length <= MAX_MEMOIZED_PRIMITIVE_LENGTH;
90183
- }
90184
- if (t === "bigint") {
90185
- return value.toString().length <= MAX_MEMOIZED_PRIMITIVE_LENGTH;
90186
- }
90187
- return true;
90188
- }
90189
- __name(isMemoizablePrimitive, "isMemoizablePrimitive");
90190
- function createStepHydrationCache() {
90191
- return /* @__PURE__ */ new Map();
90192
- }
90193
- __name(createStepHydrationCache, "createStepHydrationCache");
90194
- async function getOrHydrateStepReturnValue(cache, eventId, hydrate) {
90195
- if (!cache || eventId === void 0) {
90196
- return hydrate();
90197
- }
90198
- if (cache.has(eventId)) {
90199
- return cache.get(eventId);
90200
- }
90201
- const value = await hydrate();
90202
- if (isMemoizablePrimitive(value)) {
90203
- cache.set(eventId, value);
90204
- }
90205
- return value;
90206
- }
90207
- __name(getOrHydrateStepReturnValue, "getOrHydrateStepReturnValue");
90208
-
90209
90969
  // ../core/dist/runtime.js
90210
90970
  init_semantic_conventions2();
90211
90971
  init_telemetry2();
@@ -90335,7 +91095,8 @@ function createUseStep(ctx) {
90335
91095
  ctx.invocationsQueue.delete(event.correlationId);
90336
91096
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
90337
91097
  try {
90338
- 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);
90339
91100
  reject(hydrated);
90340
91101
  } catch (hydrateErr) {
90341
91102
  stepLogger2.error("Failed to hydrate step_failed error", {
@@ -90354,7 +91115,10 @@ function createUseStep(ctx) {
90354
91115
  ctx.pendingDeliveries++;
90355
91116
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
90356
91117
  try {
90357
- 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
+ });
90358
91122
  resolve2(hydratedResult);
90359
91123
  } catch (error95) {
90360
91124
  reject(error95);
@@ -91002,13 +91766,13 @@ __name(createSetAttributes, "createSetAttributes");
91002
91766
 
91003
91767
  // ../core/dist/workflow/hook.js
91004
91768
  init_dist7();
91769
+ init_dist8();
91005
91770
  init_dist6();
91771
+ init_class_serialization2();
91006
91772
  init_events_consumer2();
91007
91773
  init_global2();
91008
91774
  init_logger2();
91009
91775
  init_private2();
91010
- init_dist8();
91011
- init_class_serialization2();
91012
91776
  init_serialization4();
91013
91777
  function createConflictingRun(ctx, conflictingRunId) {
91014
91778
  if (typeof conflictingRunId !== "string") {
@@ -91027,13 +91791,21 @@ function createCreateHook(ctx) {
91027
91791
  if (options.token === "") {
91028
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.");
91029
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
+ }
91030
91800
  const correlationId = `hook_${ctx.generateUlid()}`;
91031
91801
  const token = options.token ?? ctx.generateNanoid();
91802
+ const tokenRetentionUntil = options.experimental_minRetention === void 0 ? void 0 : parseDurationToDate2(options.experimental_minRetention);
91032
91803
  const isWebhook = options.isWebhook ?? false;
91033
91804
  ctx.invocationsQueue.set(correlationId, {
91034
91805
  type: "hook",
91035
91806
  correlationId,
91036
91807
  token,
91808
+ tokenRetentionUntil,
91037
91809
  metadata: options.metadata,
91038
91810
  isWebhook
91039
91811
  });
@@ -91071,6 +91843,7 @@ function createCreateHook(ctx) {
91071
91843
  const queueItem = ctx.invocationsQueue.get(correlationId);
91072
91844
  if (queueItem && queueItem.type === "hook") {
91073
91845
  queueItem.hasCreatedEvent = true;
91846
+ queueItem.tokenRetentionUntil = event.eventData.tokenRetentionUntil;
91074
91847
  }
91075
91848
  hasCreated = true;
91076
91849
  const pendingGetConflictPromises = getConflictPromises.slice();
@@ -91117,7 +91890,8 @@ function createCreateHook(ctx) {
91117
91890
  let hydrateOutcome;
91118
91891
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
91119
91892
  try {
91120
- 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);
91121
91895
  hydrateOutcome = { ok: true, value: payload };
91122
91896
  } catch (error95) {
91123
91897
  hydrateOutcome = { ok: false, error: error95 };
@@ -91147,7 +91921,8 @@ function createCreateHook(ctx) {
91147
91921
  ctx.pendingDeliveries++;
91148
91922
  ctx.promiseQueue = ctx.promiseQueue.then(async () => {
91149
91923
  try {
91150
- 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);
91151
91926
  outcome = { ok: true, value: payload };
91152
91927
  } catch (error95) {
91153
91928
  outcome = { ok: false, error: error95 };
@@ -91370,7 +92145,7 @@ async function drainPendingQueueItems(runId, pendingQueue, vmGlobalThis, workflo
91370
92145
  }
91371
92146
  }
91372
92147
  __name(drainPendingQueueItems, "drainPendingQueueItems");
91373
- async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, stepHydrationCache, runReadyBarrier) {
92148
+ async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, replayPayloadCache = new ReplayPayloadCache(encryptionKey), runReadyBarrier, worldCapabilities) {
91374
92149
  return trace4(`workflow.run ${workflowRun.workflowName}`, async (span) => {
91375
92150
  span?.setAttributes({
91376
92151
  ...WorkflowName2(workflowRun.workflowName),
@@ -91405,6 +92180,7 @@ async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, st
91405
92180
  const workflowContext = {
91406
92181
  runId: workflowRun.runId,
91407
92182
  encryptionKey,
92183
+ worldCapabilities,
91408
92184
  globalThis: vmGlobalThis,
91409
92185
  onWorkflowError: workflowDiscontinuation.reject,
91410
92186
  eventsConsumer,
@@ -91430,7 +92206,7 @@ async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, st
91430
92206
  },
91431
92207
  pendingDeliveries: 0,
91432
92208
  pendingDeliveryBarriers: /* @__PURE__ */ new Map(),
91433
- stepHydrationCache
92209
+ replayPayloadCache
91434
92210
  };
91435
92211
  workflowContext.eventsConsumer.subscribe((event) => {
91436
92212
  if (!event) {
@@ -91856,7 +92632,8 @@ Learn more: https://workflow-sdk.dev/err/${ERROR_SLUGS2.FETCH_IN_WORKFLOW_FUNCTI
91856
92632
  }
91857
92633
  let args = [];
91858
92634
  workflowContext.promiseQueue = workflowContext.promiseQueue.then(async () => {
91859
- 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);
91860
92637
  });
91861
92638
  await workflowContext.promiseQueue;
91862
92639
  span?.setAttributes({
@@ -92252,6 +93029,13 @@ var Run2 = class _Run2 {
92252
93029
  };
92253
93030
 
92254
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");
92255
93039
  function getWorkflowSetupErrorCode(err) {
92256
93040
  if (WorkflowRuntimeError2.is(err)) {
92257
93041
  return RUN_ERROR_CODES2.RUNTIME_ERROR;
@@ -92307,11 +93091,24 @@ function hasRecordedTerminalRunEvent(events, runId) {
92307
93091
  return true;
92308
93092
  }
92309
93093
  __name(hasRecordedTerminalRunEvent, "hasRecordedTerminalRunEvent");
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");
92310
93107
  function rootRunIdFrom(attributes, runId) {
92311
93108
  return attributes?.[ROOT_RUN_ID_ATTRIBUTE2] ?? runId;
92312
93109
  }
92313
93110
  __name(rootRunIdFrom, "rootRunIdFrom");
92314
- function hasOpenHookOrWait(events) {
93111
+ function openHookAndWaitState(events) {
92315
93112
  const disposedHookIds = /* @__PURE__ */ new Set();
92316
93113
  const completedWaitIds = /* @__PURE__ */ new Set();
92317
93114
  for (const e of events) {
@@ -92321,17 +93118,20 @@ function hasOpenHookOrWait(events) {
92321
93118
  completedWaitIds.add(e.correlationId);
92322
93119
  }
92323
93120
  }
93121
+ let openHook = false;
93122
+ let openWait = false;
92324
93123
  for (const e of events) {
92325
93124
  if (e.eventType === "hook_created" && !disposedHookIds.has(e.correlationId)) {
92326
- return true;
92327
- }
92328
- if (e.eventType === "wait_created" && !completedWaitIds.has(e.correlationId)) {
92329
- return true;
93125
+ openHook = true;
93126
+ } else if (e.eventType === "wait_created" && !completedWaitIds.has(e.correlationId)) {
93127
+ openWait = true;
92330
93128
  }
93129
+ if (openHook && openWait)
93130
+ break;
92331
93131
  }
92332
- return false;
93132
+ return { openHook, openWait };
92333
93133
  }
92334
- __name(hasOpenHookOrWait, "hasOpenHookOrWait");
93134
+ __name(openHookAndWaitState, "openHookAndWaitState");
92335
93135
  function workflowEntrypoint(workflowCode2, options) {
92336
93136
  setWorkflowBasePath(options?.basePath);
92337
93137
  const NO_INLINE_REPLAY_AFTER_MS = Number(process.env.WORKFLOW_V2_TIMEOUT_MS) || 12e4;
@@ -92407,9 +93207,9 @@ function workflowEntrypoint(workflowCode2, options) {
92407
93207
  let loopIteration = 0;
92408
93208
  let cachedEvents = null;
92409
93209
  let eventsCursor = null;
92410
- const stepHydrationCache = createStepHydrationCache();
92411
93210
  let pendingInlineDelta = null;
92412
93211
  let workflowRun;
93212
+ let maxEventsLimit;
92413
93213
  let workflowStartedAt = -1;
92414
93214
  let preloadedEvents;
92415
93215
  let preloadedEventsCursor;
@@ -92451,12 +93251,22 @@ function workflowEntrypoint(workflowCode2, options) {
92451
93251
  }, "reinvoke");
92452
93252
  if (incomingStepId && incomingStepName) {
92453
93253
  try {
92454
- const bgRun = await world.runs.get(runId);
93254
+ const bgRun = await world.runs.get(runId, {
93255
+ resolveData: "none"
93256
+ });
92455
93257
  if (bgRun.status !== "running") {
92456
93258
  runtimeLogger2.debug("Run already finished, skipping background step", { workflowRunId: runId, status: bgRun.status });
92457
93259
  return;
92458
93260
  }
92459
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
+ }
92460
93270
  replayBudget.pause();
92461
93271
  let stepResult;
92462
93272
  try {
@@ -92469,7 +93279,11 @@ function workflowEntrypoint(workflowCode2, options) {
92469
93279
  rootRunId: rootRunIdFrom(bgRun.attributes, runId),
92470
93280
  stepId: incomingStepId,
92471
93281
  stepName: incomingStepName,
92472
- 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
92473
93287
  }));
92474
93288
  } finally {
92475
93289
  replayBudget.resume();
@@ -92516,7 +93330,30 @@ function workflowEntrypoint(workflowCode2, options) {
92516
93330
  }
92517
93331
  }
92518
93332
  runtimeLogger2.debug("All parallel steps done, replaying inline after background step", { workflowRunId: runId });
92519
- 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
+ };
92520
93357
  workflowStartedAt = bgStartedAt;
92521
93358
  } else {
92522
93359
  return;
@@ -92580,6 +93417,12 @@ function workflowEntrypoint(workflowCode2, options) {
92580
93417
  { requestId, skipPreload: true }
92581
93418
  );
92582
93419
  runReadyBarrier = startedPromise;
93420
+ startedPromise.then((r) => {
93421
+ const limit = clampMaxEvents(r?.maxEvents);
93422
+ if (limit !== void 0)
93423
+ maxEventsLimit = limit;
93424
+ }, () => {
93425
+ });
92583
93426
  startedPromise.catch(() => {
92584
93427
  });
92585
93428
  preloadedEvents = [];
@@ -92623,6 +93466,7 @@ function workflowEntrypoint(workflowCode2, options) {
92623
93466
  throw new WorkflowRuntimeError2(`Event creation for 'run_started' did not return the run entity for run "${runId}"`);
92624
93467
  }
92625
93468
  workflowRun = result.run;
93469
+ maxEventsLimit = clampMaxEvents(result.maxEvents);
92626
93470
  runStartedReceivedAtMs = Date.now();
92627
93471
  if (result.events && result.events.length > 0 && result.hasMore !== true) {
92628
93472
  preloadedEvents = result.events;
@@ -92668,6 +93512,7 @@ function workflowEntrypoint(workflowCode2, options) {
92668
93512
  }
92669
93513
  const getEncryptionKey = memoizeEncryptionKey(world, workflowRun);
92670
93514
  const encryptionKey = await getEncryptionKey();
93515
+ const replayPayloadCache = new ReplayPayloadCache(encryptionKey);
92671
93516
  while (true) {
92672
93517
  loopIteration++;
92673
93518
  if (replayBudget.isExhausted()) {
@@ -92810,6 +93655,9 @@ function workflowEntrypoint(workflowCode2, options) {
92810
93655
  if (hasRecordedTerminalRunEvent(events, runId)) {
92811
93656
  return;
92812
93657
  }
93658
+ if (maxEventsLimit !== void 0 && events.length >= maxEventsLimit) {
93659
+ throw new MaxEventsExceededError(events.length, maxEventsLimit);
93660
+ }
92813
93661
  cachedEvents = events;
92814
93662
  invocationStartedClean ??= events.every((e) => e.eventType === "run_created" || e.eventType === "run_started" || e.eventType === "attr_set");
92815
93663
  preInlineWriteCursor = eventsCursor;
@@ -92819,18 +93667,21 @@ function workflowEntrypoint(workflowCode2, options) {
92819
93667
  eventCount: events.length
92820
93668
  });
92821
93669
  replayStart = Date.now();
93670
+ const payloadPrewarm = replayPayloadCache.prewarm(workflowRun, events);
92822
93671
  const result = await runWorkflow(
92823
93672
  workflowCode2,
92824
93673
  workflowRun,
92825
93674
  events,
92826
93675
  encryptionKey,
92827
- stepHydrationCache,
93676
+ replayPayloadCache,
92828
93677
  // Turbo: the end-of-run drain inside runWorkflow commits
92829
93678
  // fire-and-forget `*_created` events before the terminal
92830
93679
  // `awaitRunReady()` below, so gate those writes on the
92831
93680
  // backgrounded run_started too. Undefined outside turbo.
92832
- runReadyBarrier
93681
+ runReadyBarrier,
93682
+ world.capabilities
92833
93683
  );
93684
+ await payloadPrewarm;
92834
93685
  runtimeLogger2.debug("Workflow replay completed", {
92835
93686
  workflowRunId: runId,
92836
93687
  loopIteration,
@@ -93039,8 +93890,11 @@ function workflowEntrypoint(workflowCode2, options) {
93039
93890
  }
93040
93891
  return;
93041
93892
  }
93042
- 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 ?? []);
93043
- 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;
93044
93898
  const latencyTracking = computeStepLatencyTracking({
93045
93899
  events: cachedEvents ?? [],
93046
93900
  invocationStartedClean: invocationStartedClean === true,
@@ -93055,48 +93909,76 @@ function workflowEntrypoint(workflowCode2, options) {
93055
93909
  suspensionCreatedHooks: err.hookCount > 0 || suspensionResult.hasHookEvents,
93056
93910
  turbo
93057
93911
  });
93912
+ const inlineClaimStateUpdatedAt = stateUpdatedAtForCreate(cachedEvents ?? []);
93058
93913
  replayBudget.pause();
93059
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
+ });
93060
93973
  try {
93061
- stepResults = await Promise.all(inlineExecutions.map((s, stepIndex) => {
93062
- const run3 = /* @__PURE__ */ __name(() => executeStep({
93063
- world,
93064
- workflowRunId: runId,
93065
- workflowDeploymentId: workflowRun.deploymentId,
93066
- workflowName,
93067
- workflowStartedAt,
93068
- rootRunId: rootRunIdFrom(workflowRun.attributes, runId),
93069
- stepId: s.correlationId,
93070
- stepName: s.stepName,
93071
- runSpecVersion: workflowRun.specVersion,
93072
- // Lazy inline start: send the deferred step's
93073
- // input on step_started so the world creates
93074
- // the step on the fly. Absent for
93075
- // owned-recovery steps, whose input hydrates
93076
- // from the existing step entity.
93077
- lazyStepInput: s.lazyStepInput,
93078
- // Inline ownership: stamp (or re-stamp) this
93079
- // invocation's queue message ID on the
93080
- // step_started, so wake replays see the body
93081
- // as in flight here and suppress the
93082
- // immediate requeue (workflow#2780).
93083
- ownerMessageId: metadata.messageId,
93084
- // Turbo: force optimistic start and hold the
93085
- // lazy step_started until the backgrounded
93086
- // run_started lands (the body still runs
93087
- // immediately). Both are undefined/false
93088
- // outside turbo.
93089
- forceOptimisticStart,
93090
- runReadyBarrier,
93091
- ...stepIndex === 0 && s.lazyStepInput !== void 0 && latencyTracking ? { latencyTracking } : {},
93092
- ...requestInlineDelta && preInlineWriteCursor ? {
93093
- inlineDeltaSinceCursor: preInlineWriteCursor
93094
- } : {}
93095
- }), "run");
93096
- inFlightOwnedSteps.add(s.correlationId);
93097
- const executed = s.lazyStepInput === void 0 ? runStepSingleFlight(runId, s.correlationId, run3) : run3();
93098
- return executed.finally(() => inFlightOwnedSteps.delete(s.correlationId));
93099
- }));
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;
93100
93982
  } finally {
93101
93983
  replayBudget.resume();
93102
93984
  }
@@ -93496,6 +94378,19 @@ __name(addTenWorkflow, "addTenWorkflow");
93496
94378
  addTenWorkflow.workflowId = "workflow//./workflows/addition//addTenWorkflow";
93497
94379
  globalThis.__private_workflows.set("workflow//./workflows/addition//addTenWorkflow", addTenWorkflow);
93498
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
+
93499
94394
  // ../core/dist/capture-stack.js
93500
94395
  function redirectStackToCaller(err, stackStartFn) {
93501
94396
  const capture = Error.captureStackTrace;
@@ -94046,10 +94941,10 @@ var Run = class _Run {
94046
94941
  return this.getReadable();
94047
94942
  }
94048
94943
  };
94049
- Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//Run#wakeUp");
94050
- Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//Run#cancel");
94051
- Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//Run#getReadable");
94052
- var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//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");
94053
94948
  Object.defineProperty(Run.prototype, "exists", {
94054
94949
  get() {
94055
94950
  return __step_Run$exists.call(this);
@@ -94057,7 +94952,7 @@ Object.defineProperty(Run.prototype, "exists", {
94057
94952
  configurable: true,
94058
94953
  enumerable: false
94059
94954
  });
94060
- var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//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");
94061
94956
  Object.defineProperty(Run.prototype, "status", {
94062
94957
  get() {
94063
94958
  return __step_Run$status.call(this);
@@ -94065,7 +94960,7 @@ Object.defineProperty(Run.prototype, "status", {
94065
94960
  configurable: true,
94066
94961
  enumerable: false
94067
94962
  });
94068
- var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//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");
94069
94964
  Object.defineProperty(Run.prototype, "returnValue", {
94070
94965
  get() {
94071
94966
  return __step_Run$returnValue.call(this);
@@ -94073,7 +94968,7 @@ Object.defineProperty(Run.prototype, "returnValue", {
94073
94968
  configurable: true,
94074
94969
  enumerable: false
94075
94970
  });
94076
- var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//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");
94077
94972
  Object.defineProperty(Run.prototype, "workflowName", {
94078
94973
  get() {
94079
94974
  return __step_Run$workflowName.call(this);
@@ -94081,7 +94976,7 @@ Object.defineProperty(Run.prototype, "workflowName", {
94081
94976
  configurable: true,
94082
94977
  enumerable: false
94083
94978
  });
94084
- var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//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");
94085
94980
  Object.defineProperty(Run.prototype, "createdAt", {
94086
94981
  get() {
94087
94982
  return __step_Run$createdAt.call(this);
@@ -94089,7 +94984,7 @@ Object.defineProperty(Run.prototype, "createdAt", {
94089
94984
  configurable: true,
94090
94985
  enumerable: false
94091
94986
  });
94092
- var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//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");
94093
94988
  Object.defineProperty(Run.prototype, "startedAt", {
94094
94989
  get() {
94095
94990
  return __step_Run$startedAt.call(this);
@@ -94097,7 +94992,7 @@ Object.defineProperty(Run.prototype, "startedAt", {
94097
94992
  configurable: true,
94098
94993
  enumerable: false
94099
94994
  });
94100
- var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.35//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");
94101
94996
  Object.defineProperty(Run.prototype, "completedAt", {
94102
94997
  get() {
94103
94998
  return __step_Run$completedAt.call(this);
@@ -94114,7 +95009,7 @@ Object.defineProperty(Run.prototype, "completedAt", {
94114
95009
  enumerable: false,
94115
95010
  configurable: false
94116
95011
  });
94117
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.35//Run");
95012
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.36//Run");
94118
95013
 
94119
95014
  // ../core/dist/workflow/create-hook.js
94120
95015
  aliasSerializationClass(RUN_CLASS_ID, Run);
@@ -109367,6 +110262,7 @@ var HookCreatedEventSchema = BaseEventSchema.extend({
109367
110262
  correlationId: external_exports.string(),
109368
110263
  eventData: external_exports.object({
109369
110264
  token: external_exports.string(),
110265
+ tokenRetentionUntil: external_exports.coerce.date().optional(),
109370
110266
  metadata: SerializedDataSchema.optional(),
109371
110267
  isWebhook: external_exports.boolean().optional(),
109372
110268
  isSystem: external_exports.boolean().optional()
@@ -110073,7 +110969,7 @@ hookWorkflow.workflowId = "workflow//./workflows/inline-execution//hookWorkflow"
110073
110969
  globalThis.__private_workflows.set("workflow//./workflows/inline-execution//hookWorkflow", hookWorkflow);
110074
110970
 
110075
110971
  // ../core/dist/runtime/start.js
110076
- var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.0.0-beta.35//start");
110972
+ var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.0.0-beta.36//start");
110077
110973
 
110078
110974
  // workflows/lineage.ts
110079
110975
  var noop = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//./workflows/lineage//noop");