@workflow/world-testing 5.1.2 → 5.1.4

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.
@@ -583,7 +583,7 @@ function buildFramedDetails(hint2, slug) {
583
583
  });
584
584
  return out;
585
585
  }
586
- var BASE_URL, ERROR_SLUGS, WorkflowError, WorkflowWorldError, START_HOOK_ADMISSION_REJECTED, START_HOOK_ADMISSION_DISABLED, START_HOOK_CANDIDATE_CANCELLED, WorkflowStartError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRuntimeError, CorruptedEventLogError, RuntimeDecryptionError, EncryptionKeyLookupError, SerializationError, StepNotRegisteredError, WorkflowRunNotFoundError, HookConflictError, HookForceClaimedError, HookNotFoundError, EntityConflictError, RunExpiredError, StreamError, StreamExpiredError, TooEarlyError, ThrottleError, PreconditionFailedError, IN_BAND_SUPERSEDED_CODE, InBandSupersededError, WorkflowRunCancelledError, RunNotSupportedError, FatalError, RetryableError, FATAL_ERROR_KEY, RETRYABLE_ERROR_KEY, HOOK_CONFLICT_ERROR_KEY, HOOK_FORCE_CLAIMED_ERROR_KEY, RUNTIME_DECRYPTION_ERROR_KEY, STREAM_ERROR_KEY, WORKFLOW_START_ERROR_KEY;
586
+ var BASE_URL, ERROR_SLUGS, WorkflowError, WorkflowWorldError, START_HOOK_ADMISSION_REJECTED, START_HOOK_ADMISSION_DISABLED, START_HOOK_CANDIDATE_CANCELLED, WorkflowStartError, DYNAMIC_WORKFLOWS_ENV_VAR, DYNAMIC_WORKFLOWS_DOCS_URL, DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT, DynamicWorkflowsNotEnabledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRuntimeError, CorruptedEventLogError, RuntimeDecryptionError, EncryptionKeyLookupError, SerializationError, StepNotRegisteredError, WorkflowRunNotFoundError, HookConflictError, HookForceClaimedError, HookNotFoundError, EntityConflictError, RunExpiredError, StreamError, StreamExpiredError, TooEarlyError, ThrottleError, PreconditionFailedError, IN_BAND_SUPERSEDED_CODE, InBandSupersededError, WorkflowRunCancelledError, RunNotSupportedError, FatalError, RetryableError, FATAL_ERROR_KEY, RETRYABLE_ERROR_KEY, HOOK_CONFLICT_ERROR_KEY, HOOK_FORCE_CLAIMED_ERROR_KEY, RUNTIME_DECRYPTION_ERROR_KEY, STREAM_ERROR_KEY, WORKFLOW_START_ERROR_KEY;
587
587
  var init_dist2 = __esm({
588
588
  "../errors/dist/index.js"() {
589
589
  "use strict";
@@ -697,6 +697,37 @@ Caused by: ${options.cause.stack}`;
697
697
  return isError(value) && value.name === "WorkflowStartError";
698
698
  }
699
699
  };
700
+ DYNAMIC_WORKFLOWS_ENV_VAR = "WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS";
701
+ DYNAMIC_WORKFLOWS_DOCS_URL = "https://workflow-sdk.dev/docs/advanced/dynamic-workflows#enabling-dynamic-workflows";
702
+ DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT = `Set the ${DYNAMIC_WORKFLOWS_ENV_VAR}=1 environment variable on your project, then redeploy (or restart your dev server) so the new value takes effect.`;
703
+ DynamicWorkflowsNotEnabledError = class extends WorkflowError {
704
+ static {
705
+ __name(this, "DynamicWorkflowsNotEnabledError");
706
+ }
707
+ fatal = true;
708
+ /**
709
+ * @param message - What was refused, e.g. that `start()` created no run.
710
+ * The fix-it hint and a docs link are appended to it.
711
+ */
712
+ constructor(message, options) {
713
+ super(appendFramedDetails(message, [
714
+ {
715
+ label: "hint",
716
+ value: DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT
717
+ },
718
+ {
719
+ label: "docs",
720
+ value: DYNAMIC_WORKFLOWS_DOCS_URL
721
+ }
722
+ ]), {
723
+ cause: options?.cause
724
+ });
725
+ this.name = "DynamicWorkflowsNotEnabledError";
726
+ }
727
+ static is(value) {
728
+ return isError(value) && value.name === "DynamicWorkflowsNotEnabledError";
729
+ }
730
+ };
700
731
  WorkflowRunFailedError = class extends WorkflowError {
701
732
  static {
702
733
  __name(this, "WorkflowRunFailedError");
@@ -934,8 +965,8 @@ Caused by: ${options.cause.stack}`;
934
965
  static {
935
966
  __name(this, "EntityConflictError");
936
967
  }
937
- constructor(message) {
938
- super(message);
968
+ constructor(message, options) {
969
+ super(message, options);
939
970
  this.name = "EntityConflictError";
940
971
  }
941
972
  static is(value) {
@@ -19182,24 +19213,24 @@ function serializeDefaultValue(value, schema, ctx, json2, params) {
19182
19213
  }
19183
19214
  function toJSONSchema(input2, params) {
19184
19215
  if ("_idmap" in input2) {
19185
- const registry2 = input2;
19216
+ const registry3 = input2;
19186
19217
  const ctx2 = initializeContext({
19187
19218
  ...params,
19188
19219
  processors: allProcessors
19189
19220
  });
19190
19221
  const defs = {};
19191
- for (const entry of registry2._idmap.entries()) {
19222
+ for (const entry of registry3._idmap.entries()) {
19192
19223
  const [_, schema] = entry;
19193
19224
  processSchema(schema, ctx2);
19194
19225
  }
19195
19226
  const schemas = {};
19196
19227
  const external = {
19197
- registry: registry2,
19228
+ registry: registry3,
19198
19229
  uri: params?.uri,
19199
19230
  defs
19200
19231
  };
19201
19232
  ctx2.external = external;
19202
- for (const entry of registry2._idmap.entries()) {
19233
+ for (const entry of registry3._idmap.entries()) {
19203
19234
  const [key, schema] = entry;
19204
19235
  extractDefs(ctx2, schema);
19205
19236
  assignProp(schemas, key, finalize(ctx2, schema));
@@ -24550,7 +24581,7 @@ var init_events = __esm({
24550
24581
  function isTerminalWorkflowRunStatus(status) {
24551
24582
  return TERMINAL_WORKFLOW_RUN_STATUSES.includes(status);
24552
24583
  }
24553
- var WorkflowRunStatusSchema, TerminalWorkflowRunStatusSchema, TERMINAL_WORKFLOW_RUN_STATUSES, WorkflowRunBaseSchema, WorkflowRunSchema, BULK_CANCEL_MAX_RUN_IDS, BulkCancelWorkflowRunsRequestSchema, BulkCancelWorkflowRunResultSchema, BulkCancelWorkflowRunsResultSchema;
24584
+ var WorkflowRunStatusSchema, TerminalWorkflowRunStatusSchema, TERMINAL_WORKFLOW_RUN_STATUSES, WorkflowRunBaseSchema, WorkflowRunSchema, BULK_CANCEL_MAX_RUN_IDS, BulkCancelWorkflowRunsRequestSchema, BulkCancelWorkflowRunResultSchema, BulkCancelWorkflowRunsResultSchema, DELETE_RUNS_DATA_MAX_RUN_IDS, DeleteRunsDataRequestSchema, DeleteRunDataResultSchema, DeleteRunsDataResultSchema;
24554
24585
  var init_runs = __esm({
24555
24586
  "../world/dist/runs.js"() {
24556
24587
  "use strict";
@@ -24750,6 +24781,54 @@ var init_runs = __esm({
24750
24781
  }),
24751
24782
  results: external_exports.array(BulkCancelWorkflowRunResultSchema)
24752
24783
  });
24784
+ DELETE_RUNS_DATA_MAX_RUN_IDS = 100;
24785
+ DeleteRunsDataRequestSchema = external_exports.object({
24786
+ runIds: external_exports.array(external_exports.string()).min(1).max(DELETE_RUNS_DATA_MAX_RUN_IDS).refine((ids) => new Set(ids).size === ids.length, {
24787
+ message: "runIds must not contain duplicates"
24788
+ })
24789
+ });
24790
+ DeleteRunDataResultSchema = external_exports.discriminatedUnion("outcome", [
24791
+ external_exports.object({
24792
+ runId: external_exports.string(),
24793
+ outcome: external_exports.literal("deleted")
24794
+ }),
24795
+ external_exports.object({
24796
+ runId: external_exports.string(),
24797
+ outcome: external_exports.literal("already_deleted")
24798
+ }),
24799
+ external_exports.object({
24800
+ runId: external_exports.string(),
24801
+ outcome: external_exports.literal("skipped"),
24802
+ reason: external_exports.string(),
24803
+ status: external_exports.string()
24804
+ }),
24805
+ external_exports.object({
24806
+ runId: external_exports.string(),
24807
+ outcome: external_exports.literal("not_created")
24808
+ }),
24809
+ external_exports.object({
24810
+ runId: external_exports.string(),
24811
+ outcome: external_exports.literal("not_found")
24812
+ }),
24813
+ external_exports.object({
24814
+ runId: external_exports.string(),
24815
+ outcome: external_exports.literal("failed"),
24816
+ code: external_exports.string(),
24817
+ retryable: external_exports.boolean()
24818
+ })
24819
+ ]);
24820
+ DeleteRunsDataResultSchema = external_exports.object({
24821
+ summary: external_exports.object({
24822
+ requested: external_exports.number(),
24823
+ deleted: external_exports.number(),
24824
+ alreadyDeleted: external_exports.number(),
24825
+ skipped: external_exports.number(),
24826
+ notCreated: external_exports.number(),
24827
+ notFound: external_exports.number(),
24828
+ failed: external_exports.number()
24829
+ }),
24830
+ results: external_exports.array(DeleteRunDataResultSchema)
24831
+ });
24753
24832
  }
24754
24833
  });
24755
24834
 
@@ -25101,7 +25180,7 @@ function mintedSpecVersion(env = process.env, options = {}) {
25101
25180
  }
25102
25181
  return version5;
25103
25182
  }
25104
- warnOnce(`${SPEC_VERSION_ENV_VAR}=${requested}`, `Ignoring ${SPEC_VERSION_ENV_VAR}=${JSON.stringify(requested)}: expected an integer from ${SPEC_VERSION_SUPPORTS_SLOT_IDENTITY} to ${SPEC_VERSION_MAX_SUPPORTED}.`);
25183
+ warnOnce(`${SPEC_VERSION_ENV_VAR}=${requested}`, `Ignoring ${SPEC_VERSION_ENV_VAR}=${JSON.stringify(requested)}: expected an integer from ${SPEC_VERSION_SUPPORTS_SLOT_IDENTITY} to ${SPEC_VERSION_MAX_SUPPORTED}, so new runs use spec ${fallback}.`);
25105
25184
  }
25106
25185
  return fallback;
25107
25186
  }
@@ -25553,7 +25632,16 @@ var init_queue = __esm({
25553
25632
  * delivery of that message and burn the run's delivery budget over a
25554
25633
  * telemetry field. Anything unparseable degrades to "no measurement".
25555
25634
  */
25556
- hookResumeTiming: HookResumeTimingSchema.optional().catch(void 0)
25635
+ hookResumeTiming: HookResumeTimingSchema.optional().catch(void 0),
25636
+ /**
25637
+ * The event an out-of-band writer committed before it sent this wake (a
25638
+ * `resumeHook()`'s `hook_received`). An orchestrator that consumed the log
25639
+ * only below it knows the wake has something new, so it skips the tail
25640
+ * read that decides a no-op wake. A hint only: absent from other wakes and
25641
+ * older producers, and `.catch(undefined)` so a malformed value never fails
25642
+ * the payload's parse.
25643
+ */
25644
+ wakeEventId: external_exports.string().optional().catch(void 0)
25557
25645
  });
25558
25646
  HealthCheckPayloadSchema = external_exports.object({
25559
25647
  __healthCheck: external_exports.literal(true),
@@ -25603,6 +25691,7 @@ var init_queue = __esm({
25603
25691
  runInput: "drop",
25604
25692
  requestedAt: "drop",
25605
25693
  hookResumeTiming: "drop",
25694
+ wakeEventId: "drop",
25606
25695
  recovery: "drop",
25607
25696
  invoke: "drop",
25608
25697
  requestId: "drop",
@@ -28510,7 +28599,7 @@ function SemanticConvention(...names) {
28510
28599
  value
28511
28600
  ]));
28512
28601
  }
28513
- var WorkflowName, WorkflowOperation, WorkflowRunId, WorkflowRunStatus, WorkflowStartedAt, WorkflowEventsCount, WorkflowExecutionMode, WorkflowDynamic, WorkflowStartHook, WorkflowStartHookRetentionUntil, WorkflowStartHookOutcome, WorkflowStartHookConflictingRunId, WorkflowStartHookRejectionReason, WorkflowStartHookErrorCode, WorkflowStartHookConfirmAttempts, WorkflowStartHookEnqueueFailed, WorkflowStartHookTrigger, WorkflowDynamicSourceHash, WorkflowDynamicCodeBytes, WorkflowDynamicCodeStorage, WorkflowBundleCompileCacheHit, WorkflowReplayLoadSource, WorkflowParkedEventsCount, WorkflowParkedEventId, WorkflowParkedEventType, WorkflowParkedStartHookEventsCount, WorkflowArgumentsCount, WorkflowResultType, WorkflowTracePropagated, WorkflowVm, QuickJSOutcome, QuickJSEventsPreloaded, QuickJSEventsFetchedCount, QuickJSEventsFetchedPages, QuickJSPendingOpsCount, QuickJSInlineSteps, QuickJSSnapshotRestored, QuickJSSnapshotDeltaEvents, QuickJSSnapshotRestoreMs, QuickJSSnapshotFallbackReason, QuickJSSnapshotSaveMs, QuickJSSnapshotPlaintextBytes, QuickJSSnapshotStoredBytes, WorkflowTraceMode, WorkflowTurbo, WorkflowNoopDelivery, WorkflowSuperseded, WorkflowDeliveryAttempt, WorkflowDeliveryCount, WorkflowDeliveryExitReason, WorkflowDeliveryHandoff, WorkflowConsecutiveFenceRefusals, WorkflowReenqueueCount, WorkflowReenqueueSkippedTooOld, WorkflowReenqueueRecovery, WorkflowErrorName, WorkflowErrorMessage, WorkflowErrorCode, WorkflowStepsCreated, WorkflowHooksCreated, WorkflowWaitsCreated, WorkflowStepsFailedSerialization, WorkflowOwnedRecoverySteps, WorkflowBackstopWakesArmed, WorkflowInlineEarlyAdvances, WorkflowInlineRunningAtTerminal, WorkflowInlineDiscardedOutcomes, WorkflowInlineSlotsHeldBack, WorkflowDispatchRepublishSkipped, WorkflowRouteType, WorkflowRouteHandlerCached, WorkflowRouteInvocationCount, WorkflowRouteEntrypointAgeMs, WorkflowRouteModuleBodyInitMs, FaasInstance, StepName, StepId, StepAttempt, StepStatus, StepMaxRetries, StepTracePropagated, StepTtfsMs, StepStsoMs, StepRsfsMs, StepFinalSchedulingReplayMs, StepLatencyOptimizations, StepStartStrategy, StepSkipped, StepSkipReason, StepArgumentsCount, StepResultType, StepErrorName, StepErrorMessage, StepFatalError, StepRetryExhausted, StepRetryTimeoutSeconds, StepRetryWillRetry, MessagingSystem, MessagingDestinationName, MessagingMessageId, MessagingOperationType, MessagingBatchMessageCount, QueueOverheadMs, DeploymentId, WorkflowRunPinnedDeploymentId, WorkflowDeploymentMismatchRetryCount, WorkflowDeploymentMismatchRecovered, WorkflowRunSpecVersion, WorkflowRunSpecVersionSource, WorkflowCapabilityProbeLatencyMs, WorkflowCapabilityProbeCached, WorkflowCapabilityProbeError, HookToken, HookId, HookFound, HookResilientResume, HookLookupResult, HookResumeCommitted, HookWakePublished, HookResilientResumeMaterialized, HookResumeSetupSource, StepDispatchPrologue, StepDeliveryDecision, StepDeliveryReason, StepDeliveryLogRead, StepDeliveryTimeoutSeconds, ResumeTotalMs, ResumeProducerPrepMs, ResumeQueueDeliveryMs, ResumeSetupMs, ResumeReplayMs, ResumeStepDispatchMs, ResumeStepClaimMs, ResumeStepPrepareMs, ResumeTrigger, ResumeStrategy, ResumeSetupSource, ResumeStepExecution, WebhookHandlersTriggered, WorkflowSuspensionState, WorkflowSuspensionHookCount, WorkflowSuspensionStepCount, WorkflowSuspensionWaitCount, HttpRequestMethod, HttpRoute, UrlFull, ServerAddress, ServerPort, HttpResponseStatusCode, ErrorType, WorldParseFormat, WorkflowEventsPagesLoaded, WorkflowEventsLoadStoppedAtLimit, WorkflowEventsLimit, QueueDeserializeTimeMs, QueueExecutionTimeMs, QueueSerializeTimeMs, SerializationOperation, SerializationCompressed, SerializationCodec, SerializationUncompressedBytes, SerializationStoredBytes, SerializationCompressionRatio, SerializationGuestCodeExecutions, SerializationGuestCodeDetails, PeerService, RpcSystem, RpcService, RpcMethod, ErrorRetryable, ErrorCategory;
28602
+ var WorkflowName, WorkflowOperation, WorkflowRunId, WorkflowRunStatus, WorkflowStartedAt, WorkflowEventsCount, WorkflowExecutionMode, WorkflowDynamic, WorkflowStartHook, WorkflowStartHookRetentionUntil, WorkflowStartHookOutcome, WorkflowStartHookConflictingRunId, WorkflowStartHookRejectionReason, WorkflowStartHookErrorCode, WorkflowStartHookConfirmAttempts, WorkflowStartHookEnqueueFailed, WorkflowStartHookTrigger, WorkflowDynamicSourceHash, WorkflowDynamicCodeBytes, WorkflowDynamicCodeStorage, WorkflowBundleCompileCacheHit, WorkflowReplayLoadSource, WorkflowParkedEventsCount, WorkflowParkedEventId, WorkflowParkedEventType, WorkflowParkedStartHookEventsCount, WorkflowArgumentsCount, WorkflowResultType, WorkflowTracePropagated, WorkflowVm, QuickJSOutcome, QuickJSEventsPreloaded, QuickJSEventsFetchedCount, QuickJSEventsFetchedPages, QuickJSPendingOpsCount, QuickJSInlineSteps, QuickJSSnapshotRestored, QuickJSSnapshotDeltaEvents, QuickJSSnapshotRestoreMs, QuickJSSnapshotFallbackReason, QuickJSSnapshotSaveMs, QuickJSSnapshotPlaintextBytes, QuickJSSnapshotStoredBytes, WorkflowTraceMode, WorkflowTurbo, WorkflowStartHookFirstDelivery, WorkflowStartHookFirstDeliveryFallback, WorkflowStartHookFirstDeliveryRunEnded, WorkflowNoopDelivery, WorkflowNoopDeliveryReason, WorkflowLingerWaitMs, WorkflowLingerStepMs, WorkflowLingerHookMs, WorkflowNoopCheckSkipped, WorkflowSuperseded, WorkflowStartConflictRestart, WorkflowTurboSkippedMessageAgeMs, WorkflowReplayedFirstDelivery, WorkflowDeliveryAttempt, WorkflowDeliveryCount, WorkflowDeliveryExitReason, WorkflowDeliveryHandoff, WorkflowConsecutiveFenceRefusals, WorkflowReenqueueCount, WorkflowReenqueueSkippedTooOld, WorkflowReenqueueRecovery, WorkflowErrorName, WorkflowErrorMessage, WorkflowErrorCode, WorkflowStepsCreated, WorkflowHooksCreated, WorkflowWaitsCreated, WorkflowStepsFailedSerialization, WorkflowOwnedRecoverySteps, WorkflowBackstopWakesArmed, WorkflowInlineEarlyAdvances, WorkflowInlineRunningAtTerminal, WorkflowInlineDiscardedOutcomes, WorkflowInlineSlotsHeldBack, WorkflowDispatchRepublishSkipped, WorkflowRouteType, WorkflowRouteHandlerCached, WorkflowRouteInvocationCount, WorkflowRouteEntrypointAgeMs, WorkflowRouteModuleBodyInitMs, FaasInstance, StepName, StepId, StepAttempt, StepStatus, StepMaxRetries, StepTracePropagated, StepTtfsMs, StepStsoMs, StepRsfsMs, StepFinalSchedulingReplayMs, StepLatencyOptimizations, StepStartStrategy, StepSkipped, StepSkipReason, StepArgumentsCount, StepResultType, StepErrorName, StepErrorMessage, StepFatalError, StepRetryExhausted, StepRetryTimeoutSeconds, StepRetryWillRetry, MessagingSystem, MessagingDestinationName, MessagingMessageId, MessagingOperationType, MessagingBatchMessageCount, QueueOverheadMs, DeploymentId, WorkflowRunPinnedDeploymentId, WorkflowDeploymentMismatchRetryCount, WorkflowDeploymentMismatchRecovered, WorkflowRunSpecVersion, WorkflowRunSpecVersionSource, WorkflowCapabilityProbeLatencyMs, WorkflowCapabilityProbeCached, WorkflowCapabilityProbeError, HookToken, HookId, HookFound, HookResilientResume, HookLookupResult, HookResumeCommitted, HookWakePublished, HookResilientResumeMaterialized, HookResumeSetupSource, StepDispatchPrologue, StepDeliveryDecision, StepDeliveryReason, StepDeliveryLogRead, StepDeliveryTimeoutSeconds, ResumeTotalMs, ResumeProducerPrepMs, ResumeQueueDeliveryMs, ResumeSetupMs, ResumeReplayMs, ResumeStepDispatchMs, ResumeStepClaimMs, ResumeStepPrepareMs, ResumeTrigger, ResumeStrategy, ResumeSetupSource, ResumeStepExecution, WebhookHandlersTriggered, WorkflowSuspensionState, WorkflowSuspensionHookCount, WorkflowSuspensionStepCount, WorkflowSuspensionWaitCount, HttpRequestMethod, HttpRoute, UrlFull, ServerAddress, ServerPort, HttpResponseStatusCode, ErrorType, WorldParseFormat, WorkflowEventsPagesLoaded, WorkflowEventsLoadStoppedAtLimit, WorkflowEventsLimit, QueueDeserializeTimeMs, QueueExecutionTimeMs, QueueSerializeTimeMs, SerializationOperation, SerializationCompressed, SerializationCodec, SerializationUncompressedBytes, SerializationStoredBytes, SerializationCompressionRatio, SerializationGuestCodeExecutions, SerializationGuestCodeDetails, PeerService, RpcSystem, RpcService, RpcMethod, ErrorRetryable, ErrorCategory;
28514
28603
  var init_semantic_conventions = __esm({
28515
28604
  "../core/dist/telemetry/semantic-conventions.js"() {
28516
28605
  "use strict";
@@ -28560,8 +28649,19 @@ var init_semantic_conventions = __esm({
28560
28649
  QuickJSSnapshotStoredBytes = SemanticConvention("workflow.quickjs.snapshot.stored_bytes");
28561
28650
  WorkflowTraceMode = SemanticConvention("workflow.trace.mode");
28562
28651
  WorkflowTurbo = SemanticConvention("workflow.turbo");
28652
+ WorkflowStartHookFirstDelivery = SemanticConvention("workflow.start_hook.first_delivery");
28653
+ WorkflowStartHookFirstDeliveryFallback = SemanticConvention("workflow.start_hook.first_delivery.fallback");
28654
+ WorkflowStartHookFirstDeliveryRunEnded = SemanticConvention("workflow.start_hook.first_delivery.run_ended");
28563
28655
  WorkflowNoopDelivery = SemanticConvention("workflow.noop_delivery");
28656
+ WorkflowNoopDeliveryReason = SemanticConvention("workflow.noop_delivery.reason");
28657
+ WorkflowLingerWaitMs = SemanticConvention("workflow.linger.wait_ms");
28658
+ WorkflowLingerStepMs = SemanticConvention("workflow.linger.step_ms");
28659
+ WorkflowLingerHookMs = SemanticConvention("workflow.linger.hook_ms");
28660
+ WorkflowNoopCheckSkipped = SemanticConvention("workflow.noop_check_skipped");
28564
28661
  WorkflowSuperseded = SemanticConvention("workflow.superseded");
28662
+ WorkflowStartConflictRestart = SemanticConvention("workflow.start_conflict_restart");
28663
+ WorkflowTurboSkippedMessageAgeMs = SemanticConvention("workflow.turbo_skipped_message_age_ms");
28664
+ WorkflowReplayedFirstDelivery = SemanticConvention("workflow.replayed_first_delivery");
28565
28665
  WorkflowDeliveryAttempt = SemanticConvention("workflow.delivery.attempt");
28566
28666
  WorkflowDeliveryCount = SemanticConvention("workflow.delivery.count");
28567
28667
  WorkflowDeliveryExitReason = SemanticConvention("workflow.delivery.exit_reason");
@@ -31161,6 +31261,79 @@ var init_get_world_lazy = __esm({
31161
31261
  }
31162
31262
  });
31163
31263
 
31264
+ // ../core/dist/serialization/abort-local.js
31265
+ function registry2() {
31266
+ const holder = globalThis;
31267
+ holder[REGISTRY_KEY] ??= {
31268
+ listeners: /* @__PURE__ */ new Map(),
31269
+ published: /* @__PURE__ */ new Map()
31270
+ };
31271
+ return holder[REGISTRY_KEY];
31272
+ }
31273
+ function keyOf(runId, streamName) {
31274
+ return `${runId}\0${streamName}`;
31275
+ }
31276
+ function prune(published, now2) {
31277
+ for (const [key, entry] of published) {
31278
+ if (now2 - entry.at < PUBLISHED_TTL_MS && published.size <= MAX_PUBLISHED) break;
31279
+ published.delete(key);
31280
+ }
31281
+ }
31282
+ function publishLocalAbort(runId, streamName, packet) {
31283
+ const { listeners, published } = registry2();
31284
+ const key = keyOf(runId, streamName);
31285
+ const now2 = Date.now();
31286
+ published.delete(key);
31287
+ published.set(key, {
31288
+ packet,
31289
+ at: now2
31290
+ });
31291
+ prune(published, now2);
31292
+ for (const listener of listeners.get(key) ?? []) {
31293
+ try {
31294
+ listener(packet);
31295
+ } catch {
31296
+ }
31297
+ }
31298
+ }
31299
+ function onLocalAbort(runId, streamName, listener) {
31300
+ const { listeners, published } = registry2();
31301
+ const key = keyOf(runId, streamName);
31302
+ prune(published, Date.now());
31303
+ const recent = published.get(key);
31304
+ if (recent) {
31305
+ listener(recent.packet);
31306
+ return () => {
31307
+ };
31308
+ }
31309
+ let set2 = listeners.get(key);
31310
+ if (!set2) {
31311
+ set2 = /* @__PURE__ */ new Set();
31312
+ listeners.set(key, set2);
31313
+ }
31314
+ set2.add(listener);
31315
+ return () => {
31316
+ const current2 = listeners.get(key);
31317
+ if (!current2) return;
31318
+ current2.delete(listener);
31319
+ if (current2.size === 0) listeners.delete(key);
31320
+ };
31321
+ }
31322
+ var REGISTRY_KEY, PUBLISHED_TTL_MS, MAX_PUBLISHED;
31323
+ var init_abort_local = __esm({
31324
+ "../core/dist/serialization/abort-local.js"() {
31325
+ "use strict";
31326
+ REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@workflow/core//localAbortDelivery");
31327
+ PUBLISHED_TTL_MS = 6e4;
31328
+ MAX_PUBLISHED = 256;
31329
+ __name(registry2, "registry");
31330
+ __name(keyOf, "keyOf");
31331
+ __name(prune, "prune");
31332
+ __name(publishLocalAbort, "publishLocalAbort");
31333
+ __name(onLocalAbort, "onLocalAbort");
31334
+ }
31335
+ });
31336
+
31164
31337
  // ../core/dist/serialization/abort-stream.js
31165
31338
  function frameAbortStreamPayload(payload) {
31166
31339
  if (payload.length < HEADER_SIZE || payload.length > MAX_PACKET_SIZE) {
@@ -31591,12 +31764,12 @@ var init_hardened = __esm({
31591
31764
  // ../core/dist/class-serialization.js
31592
31765
  function getRegistry(global2 = globalThis) {
31593
31766
  const g = global2;
31594
- let registry2 = g[WORKFLOW_CLASS_REGISTRY];
31595
- if (!registry2) {
31596
- registry2 = /* @__PURE__ */ new Map();
31597
- g[WORKFLOW_CLASS_REGISTRY] = registry2;
31767
+ let registry3 = g[WORKFLOW_CLASS_REGISTRY];
31768
+ if (!registry3) {
31769
+ registry3 = /* @__PURE__ */ new Map();
31770
+ g[WORKFLOW_CLASS_REGISTRY] = registry3;
31598
31771
  }
31599
- return registry2;
31772
+ return registry3;
31600
31773
  }
31601
31774
  function getSerializationClass(classId, global2) {
31602
31775
  return getRegistry(global2).get(classId);
@@ -32396,6 +32569,19 @@ function stateSourceId(event) {
32396
32569
  if (event === "run-input") return "run";
32397
32570
  return event.eventType === "hook_received" && event.eventId ? `hook:${event.eventId}` : void 0;
32398
32571
  }
32572
+ function sourceString(node2, path8) {
32573
+ if (!Array.isArray(path8)) return void 0;
32574
+ let at2 = node2;
32575
+ for (const key of path8) {
32576
+ if (typeof at2 === "string" || at2 === void 0) return void 0;
32577
+ if (typeof key !== "string" && typeof key !== "number") return void 0;
32578
+ at2 = at2.get(key);
32579
+ }
32580
+ return typeof at2 === "string" ? at2 : void 0;
32581
+ }
32582
+ function jsonLength(value) {
32583
+ return JSON.stringify(value).length;
32584
+ }
32399
32585
  function base64Bytes(value) {
32400
32586
  const text = globalThis.atob(value === "." ? "" : value);
32401
32587
  const bytes = new Uint8Array(text.length);
@@ -32448,9 +32634,10 @@ function hasBrand(check2) {
32448
32634
  return false;
32449
32635
  }
32450
32636
  }
32451
- function holdsOnlyState(leaf, depth) {
32637
+ function holdsOnlyState(leaf, depth, leaves) {
32452
32638
  const tag = Object.prototype.toString.call(leaf);
32453
32639
  if (tag !== "[object Map]" && tag !== "[object Set]") return true;
32640
+ if ((leaves.get(leaf) ?? -1) >= depth) return true;
32454
32641
  if (depth > MAX_DEPTH) return false;
32455
32642
  let ok = true;
32456
32643
  const check2 = /* @__PURE__ */ __name((entry) => {
@@ -32461,23 +32648,25 @@ function holdsOnlyState(leaf, depth) {
32461
32648
  }
32462
32649
  if (frozenState.has(entry)) return;
32463
32650
  if (isTrustedLeaf(entry)) {
32464
- if (!holdsOnlyState(entry, depth + 1)) ok = false;
32651
+ if (!holdsOnlyState(entry, depth + 1, leaves)) ok = false;
32465
32652
  return;
32466
32653
  }
32467
- if (!isFrozenState(entry, depth + 1)) ok = false;
32654
+ if (!isFrozenState(entry, depth + 1, leaves)) ok = false;
32468
32655
  }, "check");
32469
32656
  if (tag === "[object Map]") Map.prototype.forEach.call(leaf, (value, key) => {
32470
32657
  check2(key);
32471
32658
  check2(value);
32472
32659
  });
32473
32660
  else Set.prototype.forEach.call(leaf, (value) => check2(value));
32661
+ if (ok) leaves.set(leaf, depth);
32474
32662
  return ok;
32475
32663
  }
32476
- function isFrozenState(value, depth = 0) {
32664
+ function isFrozenState(value, depth = 0, leaves) {
32477
32665
  if (value === null || typeof value !== "object") return false;
32478
32666
  if (frozenState.has(value)) return true;
32479
32667
  if (depth > MAX_DEPTH || !Object.isFrozen(value)) return false;
32480
32668
  if (!Array.isArray(value) && !isPlainObject2(value)) return false;
32669
+ leaves ??= /* @__PURE__ */ new Map();
32481
32670
  for (const key of Object.keys(value)) {
32482
32671
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
32483
32672
  if (descriptor === void 0 || !("value" in descriptor)) return false;
@@ -32490,10 +32679,10 @@ function isFrozenState(value, depth = 0) {
32490
32679
  }
32491
32680
  if (frozenState.has(child)) continue;
32492
32681
  if (isTrustedLeaf(child)) {
32493
- if (!holdsOnlyState(child, depth + 1)) return false;
32682
+ if (!holdsOnlyState(child, depth + 1, leaves)) return false;
32494
32683
  continue;
32495
32684
  }
32496
- if (!isFrozenState(child, depth + 1)) return false;
32685
+ if (!isFrozenState(child, depth + 1, leaves)) return false;
32497
32686
  }
32498
32687
  frozenState.add(value);
32499
32688
  return true;
@@ -32531,7 +32720,7 @@ function bindStateContextData(data2, context) {
32531
32720
  function stateContextForData(data2) {
32532
32721
  return data2 !== null && typeof data2 === "object" ? bindings.data.get(data2) : void 0;
32533
32722
  }
32534
- var STATE_REF_REDUCER, STATE_SOURCE_REDUCER, SNAPSHOT_MIN_BYTES, SNAPSHOT_MAX_RECORDS, SOURCE_STRING_MIN, MAX_ID, MAX_PATH, MAX_DEPTH, MAX_RECENT_INPUTS, WorkflowStateMissingError, STATE_REFS_FIELD, StateSourceRef, OPAQUE, DEVALUE_BUILTIN_TAGS, typedArray, VALUE_REVIVERS, frozenState, StateContext, bindings;
32723
+ var STATE_REF_REDUCER, STATE_SOURCE_REDUCER, SNAPSHOT_MIN_BYTES, SNAPSHOT_MAX_RECORDS, SOURCE_STRING_MIN, MAX_SOURCE_STRINGS, MAX_ID, MAX_PATH, MAX_DEPTH, MAX_SCAN, MAX_RECENT_INPUTS, WorkflowStateMissingError, STATE_REFS_FIELD, EMPTY_SOURCE, StateSourceRef, OPAQUE, DEVALUE_BUILTIN_TAGS, typedArray, VALUE_REVIVERS, frozenState, StateContext, bindings;
32535
32724
  var init_state_refs = __esm({
32536
32725
  "../core/dist/serialization/state-refs.js"() {
32537
32726
  "use strict";
@@ -32543,9 +32732,11 @@ var init_state_refs = __esm({
32543
32732
  SNAPSHOT_MIN_BYTES = 64 * 1024;
32544
32733
  SNAPSHOT_MAX_RECORDS = 1e3;
32545
32734
  SOURCE_STRING_MIN = 128;
32735
+ MAX_SOURCE_STRINGS = 1e4;
32546
32736
  MAX_ID = 256;
32547
32737
  MAX_PATH = 64;
32548
32738
  MAX_DEPTH = 256;
32739
+ MAX_SCAN = 1e5;
32549
32740
  MAX_RECENT_INPUTS = 4;
32550
32741
  WorkflowStateMissingError = class extends Error {
32551
32742
  static {
@@ -32555,6 +32746,9 @@ var init_state_refs = __esm({
32555
32746
  };
32556
32747
  STATE_REFS_FIELD = "stateRefs";
32557
32748
  __name(stateSourceId, "stateSourceId");
32749
+ EMPTY_SOURCE = /* @__PURE__ */ new Map();
32750
+ __name(sourceString, "sourceString");
32751
+ __name(jsonLength, "jsonLength");
32558
32752
  StateSourceRef = class {
32559
32753
  static {
32560
32754
  __name(this, "StateSourceRef");
@@ -32702,6 +32896,11 @@ var init_state_refs = __esm({
32702
32896
  * changes must still resolve to the strings that were stored.
32703
32897
  */
32704
32898
  sources = /* @__PURE__ */ new Map();
32899
+ /**
32900
+ * Where each indexed string is held, for writing references to it. At most
32901
+ * {@link MAX_SOURCE_STRINGS}, and only strings longer than their reference:
32902
+ * the rest are written as they are.
32903
+ */
32705
32904
  strings = /* @__PURE__ */ new Map();
32706
32905
  /**
32707
32906
  * The context a step's output is written against (see `forStep`): its
@@ -33014,30 +33213,45 @@ var init_state_refs = __esm({
33014
33213
  addSource(id, value) {
33015
33214
  checkedId(id, "state source id");
33016
33215
  if (this.sources.has(id)) return;
33017
- const captured = /* @__PURE__ */ new Map();
33018
- this.sources.set(id, captured);
33019
- const walk = /* @__PURE__ */ __name((v, path8) => {
33020
- if (path8.length > MAX_PATH) return;
33216
+ const path8 = [];
33217
+ const read3 = /* @__PURE__ */ new Map();
33218
+ const idBytes = jsonLength(id);
33219
+ const walk = /* @__PURE__ */ __name((v, pathBytes) => {
33220
+ if (path8.length > MAX_PATH) return void 0;
33021
33221
  if (typeof v === "string") {
33022
- if (v.length < SOURCE_STRING_MIN) return;
33023
- captured.set(JSON.stringify(path8), v);
33024
- if (!this.strings.has(v)) this.strings.set(v, {
33222
+ if (v.length < SOURCE_STRING_MIN) return void 0;
33223
+ if (idBytes + pathBytes < v.length && this.strings.size < MAX_SOURCE_STRINGS && !this.strings.has(v)) this.strings.set(v, {
33025
33224
  id,
33026
- path: path8
33225
+ path: path8.slice()
33027
33226
  });
33028
- } else if (Array.isArray(v)) {
33029
- for (let i2 = 0; i2 < v.length; i2++) walk(v[i2], [
33030
- ...path8,
33031
- i2
33032
- ]);
33227
+ return v;
33228
+ }
33229
+ if (v === null || typeof v !== "object") return void 0;
33230
+ const depth = path8.length;
33231
+ let atDepth = read3.get(v);
33232
+ if (atDepth?.has(depth)) return atDepth.get(depth);
33233
+ if (atDepth === void 0) {
33234
+ atDepth = /* @__PURE__ */ new Map();
33235
+ read3.set(v, atDepth);
33236
+ }
33237
+ let node2;
33238
+ const visit2 = /* @__PURE__ */ __name((key, child) => {
33239
+ path8.push(key);
33240
+ const found = walk(child, pathBytes + 1 + (typeof key === "number" ? String(key).length : jsonLength(key)));
33241
+ path8.pop();
33242
+ if (found === void 0) return;
33243
+ node2 ??= /* @__PURE__ */ new Map();
33244
+ node2.set(key, found);
33245
+ }, "visit");
33246
+ if (Array.isArray(v)) {
33247
+ for (let i2 = 0; i2 < v.length; i2++) visit2(i2, v[i2]);
33033
33248
  } else if (isPlainObject2(v)) {
33034
- for (const key of Object.keys(v)) walk(v[key], [
33035
- ...path8,
33036
- key
33037
- ]);
33249
+ for (const key of Object.keys(v)) visit2(key, v[key]);
33038
33250
  }
33251
+ atDepth.set(depth, node2);
33252
+ return node2;
33039
33253
  }, "walk");
33040
- walk(value, []);
33254
+ this.sources.set(id, walk(value, 2) ?? EMPTY_SOURCE);
33041
33255
  }
33042
33256
  reviveSource(d) {
33043
33257
  const id = checkedId(d.id, "state source id");
@@ -33070,7 +33284,7 @@ var init_state_refs = __esm({
33070
33284
  if (v instanceof StateSourceRef) {
33071
33285
  const captured = this.sources.get(v.id);
33072
33286
  if (captured === void 0) throw new WorkflowStateMissingError(`Missing workflow state source ${v.id}`);
33073
- const value = captured.get(JSON.stringify(v.path));
33287
+ const value = sourceString(captured, v.path);
33074
33288
  if (value === void 0) throw new WorkflowStateMissingError("Missing workflow state source field");
33075
33289
  return value;
33076
33290
  }
@@ -33094,23 +33308,44 @@ var init_state_refs = __esm({
33094
33308
  this.placeholders.add(text);
33095
33309
  return text;
33096
33310
  }
33097
- holdsPlaceholder(value, depth = 0) {
33098
- if (typeof value === "string") return this.placeholders.has(value);
33099
- if (depth > 256 || value === null || typeof value !== "object") return false;
33100
- for (const child of childrenOf(value)) if (this.holdsPlaceholder(child, depth + 1)) return true;
33101
- return false;
33311
+ /**
33312
+ * Whether a value holds a placeholder. Each object is read once (again only
33313
+ * if reached nearer the top, where the depth limit cuts less), so a value
33314
+ * that holds one object many times is not read once per path to it. Past
33315
+ * {@link MAX_SCAN} objects it is taken to hold one: such a value is then
33316
+ * not remembered, which inspection only needs to rebuild it again.
33317
+ */
33318
+ holdsPlaceholder(value) {
33319
+ const seen = /* @__PURE__ */ new Map();
33320
+ let budget = MAX_SCAN;
33321
+ const scan = /* @__PURE__ */ __name((v, depth) => {
33322
+ if (typeof v === "string") return this.placeholders.has(v);
33323
+ if (depth > MAX_DEPTH || v === null || typeof v !== "object") return false;
33324
+ if ((seen.get(v) ?? Infinity) <= depth) return false;
33325
+ seen.set(v, depth);
33326
+ if (--budget < 0) return true;
33327
+ for (const child of childrenOf(v)) if (scan(child, depth + 1)) return true;
33328
+ return false;
33329
+ }, "scan");
33330
+ return scan(value, 0);
33102
33331
  }
33103
- assertKnownTypes(value, depth = 0) {
33332
+ assertKnownTypes(value) {
33104
33333
  if (this.allowPlaceholders) return;
33105
- if (depth > 256 || value === null || typeof value !== "object") return;
33106
- if (value[OPAQUE] === true) throw new Error("Workflow state holds a value that cannot be recovered without running workflow code");
33107
- const tag = Object.prototype.toString.call(value);
33108
- if (tag === "[object Map]") Map.prototype.forEach.call(value, (entry, key) => {
33109
- this.assertKnownTypes(key, depth + 1);
33110
- this.assertKnownTypes(entry, depth + 1);
33111
- });
33112
- else if (tag === "[object Set]") Set.prototype.forEach.call(value, (entry) => this.assertKnownTypes(entry, depth + 1));
33113
- else for (const key of Object.keys(value)) this.assertKnownTypes(value[key], depth + 1);
33334
+ const seen = /* @__PURE__ */ new Map();
33335
+ const check2 = /* @__PURE__ */ __name((v, depth) => {
33336
+ if (depth > MAX_DEPTH || v === null || typeof v !== "object") return;
33337
+ if ((seen.get(v) ?? Infinity) <= depth) return;
33338
+ seen.set(v, depth);
33339
+ if (v[OPAQUE] === true) throw new Error("Workflow state holds a value that cannot be recovered without running workflow code");
33340
+ const tag = Object.prototype.toString.call(v);
33341
+ if (tag === "[object Map]") Map.prototype.forEach.call(v, (entry, key) => {
33342
+ check2(key, depth + 1);
33343
+ check2(entry, depth + 1);
33344
+ });
33345
+ else if (tag === "[object Set]") Set.prototype.forEach.call(v, (entry) => check2(entry, depth + 1));
33346
+ else for (const key of Object.keys(v)) check2(v[key], depth + 1);
33347
+ }, "check");
33348
+ check2(value, 0);
33114
33349
  }
33115
33350
  /**
33116
33351
  * Cold recovery: reads the state records of one decoded payload (JSON text after
@@ -36312,7 +36547,7 @@ var version2;
36312
36547
  var init_version = __esm({
36313
36548
  "../core/dist/version.js"() {
36314
36549
  "use strict";
36315
- version2 = "5.6.1";
36550
+ version2 = "5.7.1";
36316
36551
  }
36317
36552
  });
36318
36553
 
@@ -36327,9 +36562,9 @@ function awaitChildRunCompletion(childRunId, parentRunId, readValue, readFinishe
36327
36562
  if (!parentRunId) return void 0;
36328
36563
  const g = globalThis;
36329
36564
  const createHook2 = g[WORKFLOW_CREATE_HOOK];
36330
- const sleep5 = g[WORKFLOW_SLEEP];
36565
+ const sleep6 = g[WORKFLOW_SLEEP];
36331
36566
  const ctx = g[WORKFLOW_CONTEXT];
36332
- if (typeof createHook2 !== "function" || typeof sleep5 !== "function" || ctx?.workflowRunId !== parentRunId) {
36567
+ if (typeof createHook2 !== "function" || typeof sleep6 !== "function" || ctx?.workflowRunId !== parentRunId) {
36333
36568
  return void 0;
36334
36569
  }
36335
36570
  let d = g[DISPATCHER];
@@ -36363,7 +36598,7 @@ function awaitChildRunCompletion(childRunId, parentRunId, readValue, readFinishe
36363
36598
  dispatcher.wake?.();
36364
36599
  if (!dispatcher.running) {
36365
36600
  dispatcher.running = true;
36366
- void dispatch(dispatcher, parent, createHook2, sleep5, readFinished);
36601
+ void dispatch(dispatcher, parent, createHook2, sleep6, readFinished);
36367
36602
  }
36368
36603
  await done;
36369
36604
  }
@@ -36420,7 +36655,7 @@ function disarm(d, hook) {
36420
36655
  d.armGeneration++;
36421
36656
  hook[HOOK_RELEASE_AWAITER]?.();
36422
36657
  }
36423
- async function dispatch(d, parentRunId, createHook2, sleep5, readFinished) {
36658
+ async function dispatch(d, parentRunId, createHook2, sleep6, readFinished) {
36424
36659
  d.hook ??= createHook2({
36425
36660
  token: childRunCompletionToken(parentRunId),
36426
36661
  isSystem: true
@@ -36448,7 +36683,7 @@ async function dispatch(d, parentRunId, createHook2, sleep5, readFinished) {
36448
36683
  }
36449
36684
  arm(d, hook);
36450
36685
  if (d.safety === void 0) {
36451
- const safety2 = sleep5(safetyCheckDelayMs(d.safetyIndex));
36686
+ const safety2 = sleep6(safetyCheckDelayMs(d.safetyIndex));
36452
36687
  d.safety = safety2;
36453
36688
  void safety2.then(() => {
36454
36689
  if (d.safety === safety2) d.safety = void 0;
@@ -36947,7 +37182,9 @@ var init_codec = __esm({
36947
37182
 
36948
37183
  // ../world-local/dist/legacy-data.js
36949
37184
  import fs from "node:fs";
37185
+ import { readdir as readdir2, rm, rmdir, unlink } from "node:fs/promises";
36950
37186
  import path2 from "node:path";
37187
+ import { setTimeout as sleep } from "node:timers/promises";
36951
37188
  function legacyEntriesIn(dataDir) {
36952
37189
  return LEGACY_ENTRIES.filter((entry) => {
36953
37190
  try {
@@ -36970,7 +37207,82 @@ function noticeLegacyData(dataDir) {
36970
37207
  const dir = path2.resolve(dataDir);
36971
37208
  console.info(`[world-local] Runs recorded by an earlier version of @workflow/world-local are no longer read (this version keeps its data in ${path2.join(dir, "world.db")}), so the CLI and the web UI do not list them. Their files are still in ${legacy.map((entry) => path2.join(dir, entry)).join(", ")}, and can be deleted.`);
36972
37209
  }
36973
- var LEGACY_ENTRIES;
37210
+ async function removeLegacyData(dataDir, tag) {
37211
+ const entries = legacyEntriesIn(dataDir).map((entry) => path2.join(
37212
+ /* turbopackIgnore: true */
37213
+ dataDir,
37214
+ entry
37215
+ ));
37216
+ if (tag === void 0) {
37217
+ await Promise.all(entries.map((dir) => (
37218
+ // Windows refuses, for a moment, to remove what another clear() or
37219
+ // a virus scanner still has open: `maxRetries` waits for it.
37220
+ rm(dir, {
37221
+ recursive: true,
37222
+ force: true,
37223
+ maxRetries: 5
37224
+ })
37225
+ )));
37226
+ return;
37227
+ }
37228
+ const suffixes = [
37229
+ `.${tag}.json`,
37230
+ `.${tag}.bin`
37231
+ ];
37232
+ const gone = /* @__PURE__ */ __name((error62) => error62.code === "ENOENT", "gone");
37233
+ const removeDir = /* @__PURE__ */ __name((dir) => settled(() => rmdir(dir)).catch((error62) => {
37234
+ if (gone(error62) || error62.code === "ENOTEMPTY") return;
37235
+ throw error62;
37236
+ }), "removeDir");
37237
+ const kept = [];
37238
+ const removeTagged = /* @__PURE__ */ __name(async (dir) => {
37239
+ let entries2;
37240
+ try {
37241
+ entries2 = await settled(() => readdir2(dir, {
37242
+ withFileTypes: true
37243
+ }));
37244
+ } catch (error62) {
37245
+ if (gone(error62)) return false;
37246
+ throw error62;
37247
+ }
37248
+ let left = 0;
37249
+ for (const entry of entries2) {
37250
+ const at2 = path2.join(
37251
+ /* turbopackIgnore: true */
37252
+ dir,
37253
+ entry.name
37254
+ );
37255
+ if (entry.isDirectory()) {
37256
+ if (await removeTagged(at2)) await removeDir(at2);
37257
+ else left++;
37258
+ } else if (entry.isFile() && suffixes.some((suffix) => entry.name.endsWith(suffix))) {
37259
+ await settled(() => unlink(at2)).catch((error62) => {
37260
+ if (!gone(error62)) throw error62;
37261
+ });
37262
+ } else {
37263
+ left++;
37264
+ }
37265
+ }
37266
+ if (left > 0) kept.push(dir);
37267
+ return left === 0;
37268
+ }, "removeTagged");
37269
+ for (const dir of entries) {
37270
+ if (await removeTagged(dir)) await removeDir(dir);
37271
+ }
37272
+ for (const dir of kept) await removeDir(dir);
37273
+ }
37274
+ async function settled(operation) {
37275
+ for (let attempt = 1; ; attempt++) {
37276
+ try {
37277
+ return await operation();
37278
+ } catch (error62) {
37279
+ const code2 = error62.code;
37280
+ if (code2 !== "EPERM" && code2 !== "EBUSY" || attempt === SETTLE_ATTEMPTS) throw error62;
37281
+ }
37282
+ await sleep(attempt * 10);
37283
+ }
37284
+ }
37285
+ var LEGACY_ENTRIES, SETTLE_ATTEMPTS;
36974
37286
  var init_legacy_data = __esm({
36975
37287
  "../world-local/dist/legacy-data.js"() {
36976
37288
  "use strict";
@@ -36986,6 +37298,9 @@ var init_legacy_data = __esm({
36986
37298
  ];
36987
37299
  __name(legacyEntriesIn, "legacyEntriesIn");
36988
37300
  __name(noticeLegacyData, "noticeLegacyData");
37301
+ __name(removeLegacyData, "removeLegacyData");
37302
+ SETTLE_ATTEMPTS = 20;
37303
+ __name(settled, "settled");
36989
37304
  }
36990
37305
  });
36991
37306
 
@@ -37674,7 +37989,7 @@ var init_db = __esm({
37674
37989
 
37675
37990
  // ../world-local/dist/init.js
37676
37991
  import { randomBytes } from "node:crypto";
37677
- import { access, constants, mkdir, readFile as readFile2, unlink, writeFile } from "node:fs/promises";
37992
+ import { access, constants, mkdir, readFile as readFile2, unlink as unlink2, writeFile } from "node:fs/promises";
37678
37993
  import path4 from "node:path";
37679
37994
  import { fileURLToPath } from "node:url";
37680
37995
  function getModuleDir() {
@@ -37759,7 +38074,7 @@ async function ensureDataDir(dataDir) {
37759
38074
  const testFile = path4.join(absolutePath, `.workflow-write-test-${process.pid}-${randomBytes(6).toString("hex")}`);
37760
38075
  try {
37761
38076
  await writeFile(testFile, "");
37762
- await unlink(testFile).catch((e) => {
38077
+ await unlink2(testFile).catch((e) => {
37763
38078
  if (e.code !== "ENOENT") throw e;
37764
38079
  });
37765
38080
  } catch (error62) {
@@ -38388,7 +38703,7 @@ function nodeHttpFetch(url2, init = {}) {
38388
38703
  reject(signal.reason);
38389
38704
  return;
38390
38705
  }
38391
- let settled = false;
38706
+ let settled2 = false;
38392
38707
  let headersTimer;
38393
38708
  let bodyTimer;
38394
38709
  let teardownReason;
@@ -38416,8 +38731,8 @@ function nodeHttpFetch(url2, init = {}) {
38416
38731
  const fail = /* @__PURE__ */ __name((error62) => {
38417
38732
  clearTimers();
38418
38733
  detach();
38419
- if (settled) return;
38420
- settled = true;
38734
+ if (settled2) return;
38735
+ settled2 = true;
38421
38736
  reject(error62);
38422
38737
  }, "fail");
38423
38738
  if (headersTimeoutMs) {
@@ -38444,7 +38759,7 @@ function nodeHttpFetch(url2, init = {}) {
38444
38759
  message.resume();
38445
38760
  clearTimers();
38446
38761
  detach();
38447
- settled = true;
38762
+ settled2 = true;
38448
38763
  resolve2(new Response(null, {
38449
38764
  status,
38450
38765
  statusText,
@@ -38477,7 +38792,7 @@ function nodeHttpFetch(url2, init = {}) {
38477
38792
  // whatever the socket reported.
38478
38793
  failure: /* @__PURE__ */ __name((cause) => teardownReason ?? cause ?? transportError("socket hang up", "ECONNRESET"), "failure")
38479
38794
  });
38480
- settled = true;
38795
+ settled2 = true;
38481
38796
  resolve2(new Response(stream, {
38482
38797
  status,
38483
38798
  statusText,
@@ -66266,6 +66581,9 @@ function resumeOf(message) {
66266
66581
  hookResumeTiming: message.hookResumeTiming,
66267
66582
  ...message.traceCarrier !== void 0 && {
66268
66583
  traceCarrier: message.traceCarrier
66584
+ },
66585
+ ...message.wakeEventId !== void 0 && {
66586
+ wakeEventId: message.wakeEventId
66269
66587
  }
66270
66588
  };
66271
66589
  }
@@ -66316,12 +66634,15 @@ function createQueue(config3, options = {}) {
66316
66634
  });
66317
66635
  }, "deliveryUrl");
66318
66636
  const rerunBody = /* @__PURE__ */ __name((message, resume) => {
66319
- const { hookResumeTiming: _consumed, ...rest } = message;
66637
+ const { hookResumeTiming: _consumed, wakeEventId: _consumedWake, ...rest } = message;
66320
66638
  return transport.serialize(resume ? {
66321
66639
  ...rest,
66322
66640
  hookResumeTiming: resume.hookResumeTiming,
66323
66641
  ...resume.traceCarrier !== void 0 && {
66324
66642
  traceCarrier: resume.traceCarrier
66643
+ },
66644
+ ...resume.wakeEventId !== void 0 && {
66645
+ wakeEventId: resume.wakeEventId
66325
66646
  }
66326
66647
  } : rest);
66327
66648
  }, "rerunBody");
@@ -66860,7 +67181,7 @@ var init_queue2 = __esm({
66860
67181
 
66861
67182
  // ../world-local/dist/queue-auth-key.js
66862
67183
  import { randomBytes as randomBytes2 } from "node:crypto";
66863
- import { chmod, readFile as readFile3, rename, rm, writeFile as writeFile2 } from "node:fs/promises";
67184
+ import { chmod, readFile as readFile3, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
66864
67185
  import path5 from "node:path";
66865
67186
  function stateFor(dir) {
66866
67187
  const { byDir } = keyFiles();
@@ -66898,7 +67219,7 @@ async function writeQueueAuthKeyFile(dir, key) {
66898
67219
  await chmod(tmp, 384);
66899
67220
  await rename(tmp, path5.join(dir, QUEUE_AUTH_KEY_FILE));
66900
67221
  } catch (error62) {
66901
- await rm(tmp, {
67222
+ await rm2(tmp, {
66902
67223
  force: true
66903
67224
  }).catch(() => {
66904
67225
  });
@@ -67039,28 +67360,19 @@ function purgesUserDataOnFinish2(attributes) {
67039
67360
  }
67040
67361
  return retention.mode === "none";
67041
67362
  }
67363
+ function ranPurge(run2) {
67364
+ if (run2 === void 0 || !isTerminalWorkflowRunStatus(run2.status)) {
67365
+ return false;
67366
+ }
67367
+ if (readRunRetention(run2.attributes).mode === "none") return true;
67368
+ return run2.expiredAt !== void 0 && new Date(run2.expiredAt).getTime() <= Date.now();
67369
+ }
67042
67370
  function purgeRunData(db, runId) {
67043
67371
  for (const row of db.all("SELECT step_id, doc FROM steps WHERE run_id = ?", runId)) {
67044
- const step = decode3(row.doc);
67045
- step.input = void 0;
67046
- step.output = void 0;
67047
- step.error = void 0;
67048
- db.run("UPDATE steps SET doc = ? WHERE run_id = ? AND step_id = ?", encode3(step), runId, row.step_id);
67372
+ writeScrubbedStep(db, runId, row.step_id, row.doc);
67049
67373
  }
67050
67374
  for (const row of db.all("SELECT seq, doc FROM events WHERE run_id = ?", runId)) {
67051
- const event = decode3(row.doc);
67052
- const eventData = event.eventData;
67053
- if (!eventData || typeof eventData !== "object") continue;
67054
- for (const field of getEventDataRefFields(String(event.eventType))) {
67055
- delete eventData[field];
67056
- }
67057
- if (event.eventType === "run_created" || event.eventType === "run_started") {
67058
- delete eventData.dynamicWorkflowCode;
67059
- delete eventData.dynamicWorkflowCodeRef;
67060
- const startHook = eventData.startHook;
67061
- if (startHook && typeof startHook === "object") delete startHook.metadata;
67062
- }
67063
- db.run("UPDATE events SET doc = ? WHERE run_id = ? AND seq = ?", encode3(event), runId, row.seq);
67375
+ writeScrubbedEvent(db, runId, row.seq, row.doc);
67064
67376
  }
67065
67377
  for (const row of db.all("SELECT hook_id, doc FROM hooks WHERE run_id = ?", runId)) {
67066
67378
  const hook = decode3(row.doc);
@@ -67068,6 +67380,40 @@ function purgeRunData(db, runId) {
67068
67380
  db.run("UPDATE hooks SET doc = ? WHERE hook_id = ?", encode3(hook), row.hook_id);
67069
67381
  }
67070
67382
  purgeRunStreams(db, runId);
67383
+ db.run("DELETE FROM snapshots WHERE run_id = ?", runId);
67384
+ }
67385
+ function purgeLateStepWrite(db, runId, stepId, seq) {
67386
+ const stepRow = db.get("SELECT doc FROM steps WHERE run_id = ? AND step_id = ?", runId, stepId);
67387
+ if (stepRow) {
67388
+ const step = decode3(stepRow.doc);
67389
+ step.output = void 0;
67390
+ step.error = void 0;
67391
+ db.run("UPDATE steps SET doc = ? WHERE run_id = ? AND step_id = ?", encode3(step), runId, stepId);
67392
+ }
67393
+ const event = db.get("SELECT doc FROM events WHERE run_id = ? AND seq = ?", runId, seq);
67394
+ if (event) writeScrubbedEvent(db, runId, seq, event.doc);
67395
+ }
67396
+ function writeScrubbedStep(db, runId, stepId, doc) {
67397
+ const step = decode3(doc);
67398
+ step.input = void 0;
67399
+ step.output = void 0;
67400
+ step.error = void 0;
67401
+ db.run("UPDATE steps SET doc = ? WHERE run_id = ? AND step_id = ?", encode3(step), runId, stepId);
67402
+ }
67403
+ function writeScrubbedEvent(db, runId, seq, doc) {
67404
+ const event = decode3(doc);
67405
+ const eventData = event.eventData;
67406
+ if (!eventData || typeof eventData !== "object") return;
67407
+ for (const field of getEventDataRefFields(String(event.eventType))) {
67408
+ delete eventData[field];
67409
+ }
67410
+ if (event.eventType === "run_created" || event.eventType === "run_started") {
67411
+ delete eventData.dynamicWorkflowCode;
67412
+ delete eventData.dynamicWorkflowCodeRef;
67413
+ const startHook = eventData.startHook;
67414
+ if (startHook && typeof startHook === "object") delete startHook.metadata;
67415
+ }
67416
+ db.run("UPDATE events SET doc = ? WHERE run_id = ? AND seq = ?", encode3(event), runId, seq);
67071
67417
  }
67072
67418
  function purgeRunStreams(db, runId) {
67073
67419
  const names = db.all("SELECT DISTINCT name, tag FROM stream_chunks WHERE run_id = ?", runId);
@@ -67082,7 +67428,11 @@ var init_run_retention = __esm({
67082
67428
  init_dist4();
67083
67429
  init_codec();
67084
67430
  __name(purgesUserDataOnFinish2, "purgesUserDataOnFinish");
67431
+ __name(ranPurge, "ranPurge");
67085
67432
  __name(purgeRunData, "purgeRunData");
67433
+ __name(purgeLateStepWrite, "purgeLateStepWrite");
67434
+ __name(writeScrubbedStep, "writeScrubbedStep");
67435
+ __name(writeScrubbedEvent, "writeScrubbedEvent");
67086
67436
  __name(purgeRunStreams, "purgeRunStreams");
67087
67437
  }
67088
67438
  });
@@ -67096,10 +67446,10 @@ function waitForRunTerminalSignal(runId, timeoutMs, signal) {
67096
67446
  if (timeoutMs <= 0 || signal?.aborted) return Promise.resolve();
67097
67447
  return new Promise((resolve2) => {
67098
67448
  const key = `run:${runId}`;
67099
- let settled = false;
67449
+ let settled2 = false;
67100
67450
  const settle2 = /* @__PURE__ */ __name(() => {
67101
- if (settled) return;
67102
- settled = true;
67451
+ if (settled2) return;
67452
+ settled2 = true;
67103
67453
  clearTimeout(timer);
67104
67454
  emitter.off(key, settle2);
67105
67455
  signal?.removeEventListener("abort", settle2);
@@ -67242,6 +67592,11 @@ var init_store = __esm({
67242
67592
  seqInBand: Number(row.seq_in_band)
67243
67593
  };
67244
67594
  }
67595
+ /** A run's status alone, without decoding its document. */
67596
+ getRunStatus(runId) {
67597
+ const row = this.db.get(`SELECT status FROM runs WHERE run_id = ? AND ${tagClause("tag", this.tag)}`, runId, ...tagParams(this.tag));
67598
+ return row?.status ?? null;
67599
+ }
67245
67600
  /** A run regardless of tag: the owner of a hook token can be any run. */
67246
67601
  getRunAnyTag(runId) {
67247
67602
  const row = this.db.get("SELECT doc, tag, seq, seq_in_band FROM runs WHERE run_id = ?", runId);
@@ -68046,16 +68401,31 @@ function createEventsStorage(db, tag) {
68046
68401
  db.run(`INSERT INTO hook_resumes (run_id, resume_id, hook_id, seq, payload_digest)
68047
68402
  VALUES (?, ?, ?, ?, ?)`, runId, params.resumeId, data2.correlationId, Number(stored.eventId.slice("evnt_".length)), params.resumePayloadDigest ?? null);
68048
68403
  }
68404
+ const lateOnPurgedRun = !runPurged && step !== void 0 && (data2.eventType === "step_completed" || data2.eventType === "step_failed" || data2.eventType === "step_retrying") && ranPurge(runForLateStepCheck());
68405
+ let reported = stored;
68049
68406
  if (runPurged) {
68050
68407
  purgeRunData(db, runId);
68051
68408
  effects.push(() => db.checkpoint());
68409
+ } else if (lateOnPurgedRun && step) {
68410
+ const seq = Number(stored.eventId.slice("evnt_".length));
68411
+ purgeLateStepWrite(db, runId, step.stepId, seq);
68412
+ effects.push(() => db.checkpoint());
68413
+ step = store.getStep(runId, step.stepId) ?? step;
68414
+ reported = store.getEventAt(runId, seq) ?? stored;
68052
68415
  }
68053
- return finish(stored, resultRun, {
68416
+ return finish(reported, resultRun, {
68054
68417
  step,
68055
68418
  hook,
68056
68419
  wait,
68057
68420
  stepCreatedLazily
68058
68421
  });
68422
+ function runForLateStepCheck() {
68423
+ if (run2) return run2;
68424
+ const status = store.getRunStatus(runId);
68425
+ if (!status || !isTerminalWorkflowRunStatus(status)) return void 0;
68426
+ return store.getRun(runId)?.run;
68427
+ }
68428
+ __name(runForLateStepCheck, "runForLateStepCheck");
68059
68429
  function finish(committed, finalRun, extra = {}) {
68060
68430
  let delta;
68061
68431
  if (data2.eventType === "run_started" && finalRun && !params?.skipPreload) {
@@ -68611,6 +68981,31 @@ function createRunsStorage(db, tag) {
68611
68981
  if (!row) throw new WorkflowRunNotFoundError(id);
68612
68982
  return filterRunData(row.run, params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION);
68613
68983
  }, "get");
68984
+ function deleteRunData(runId) {
68985
+ const row = store.getRun(runId);
68986
+ if (!row) return {
68987
+ runId,
68988
+ outcome: "not_found"
68989
+ };
68990
+ const { run: run2 } = row;
68991
+ if (!isTerminalWorkflowRunStatus(run2.status)) {
68992
+ return {
68993
+ runId,
68994
+ outcome: "skipped",
68995
+ reason: "run_not_terminal",
68996
+ status: run2.status
68997
+ };
68998
+ }
68999
+ const now2 = /* @__PURE__ */ new Date();
69000
+ const alreadyDeleted = run2.expiredAt !== void 0 && run2.expiredAt.getTime() <= now2.getTime();
69001
+ if (!alreadyDeleted) store.updateRun(withRunPayloadsPurged(run2, now2));
69002
+ purgeRunData(db, runId);
69003
+ return {
69004
+ runId,
69005
+ outcome: alreadyDeleted ? "already_deleted" : "deleted"
69006
+ };
69007
+ }
69008
+ __name(deleteRunData, "deleteRunData");
68614
69009
  return {
68615
69010
  get,
68616
69011
  /**
@@ -68703,7 +69098,53 @@ function createRunsStorage(db, tag) {
68703
69098
  attributes
68704
69099
  };
68705
69100
  });
68706
- }, "experimentalSetAttributes")
69101
+ }, "experimentalSetAttributes"),
69102
+ /**
69103
+ * Delete the data of many finished runs. See
69104
+ * `Storage['runs'].deleteDataMany`.
69105
+ */
69106
+ deleteDataMany: /* @__PURE__ */ __name(async (request) => {
69107
+ const { runIds: runIds2 } = DeleteRunsDataRequestSchema.parse(request);
69108
+ const results = [];
69109
+ for (const runId of runIds2) {
69110
+ try {
69111
+ assertSafeEntityId("runId", runId);
69112
+ } catch {
69113
+ results.push({
69114
+ runId,
69115
+ outcome: "not_found"
69116
+ });
69117
+ continue;
69118
+ }
69119
+ try {
69120
+ results.push(await db.transactAsync(() => deleteRunData(runId)));
69121
+ } catch (error62) {
69122
+ console.error(`[world-local] Failed to delete the data of run "${runId}":`, error62);
69123
+ results.push({
69124
+ runId,
69125
+ outcome: "failed",
69126
+ code: "internal_error",
69127
+ retryable: true
69128
+ });
69129
+ }
69130
+ }
69131
+ if (results.some((r) => r.outcome === "deleted" || r.outcome === "already_deleted")) {
69132
+ db.checkpoint();
69133
+ }
69134
+ const count2 = /* @__PURE__ */ __name((outcome) => results.filter((result) => result.outcome === outcome).length, "count");
69135
+ return {
69136
+ summary: {
69137
+ requested: runIds2.length,
69138
+ deleted: count2("deleted"),
69139
+ alreadyDeleted: count2("already_deleted"),
69140
+ skipped: count2("skipped"),
69141
+ notCreated: count2("not_created"),
69142
+ notFound: count2("not_found"),
69143
+ failed: count2("failed")
69144
+ },
69145
+ results
69146
+ };
69147
+ }, "deleteDataMany")
68707
69148
  };
68708
69149
  }
68709
69150
  var init_runs_storage = __esm({
@@ -68714,7 +69155,9 @@ var init_runs_storage = __esm({
68714
69155
  init_config();
68715
69156
  init_codec();
68716
69157
  init_ids();
69158
+ init_events_storage();
68717
69159
  init_filters();
69160
+ init_run_retention();
68718
69161
  init_run_status_signal();
68719
69162
  init_store();
68720
69163
  __name(createRunsStorage, "createRunsStorage");
@@ -68875,10 +69318,19 @@ function createStreamer(basedir, tag) {
68875
69318
  } : void 0;
68876
69319
  }
68877
69320
  __name(lastRow, "lastRow");
69321
+ function runWasPurged(runId) {
69322
+ const row = db.get("SELECT doc FROM runs WHERE run_id = ?", runId);
69323
+ return row !== void 0 && ranPurge(decode3(row.doc));
69324
+ }
69325
+ __name(runWasPurged, "runWasPurged");
68878
69326
  async function append(runId, name, chunks, eof) {
68879
69327
  const appended = await db.transactAsync(() => {
68880
69328
  const last = lastRow(name);
68881
69329
  if (last?.eof) return false;
69330
+ if (!last && runWasPurged(runId)) {
69331
+ db.run("INSERT INTO stream_chunks (name, idx, run_id, tag, data, eof) VALUES (?, 0, ?, ?, NULL, 1)", name, runId, tag ?? null);
69332
+ return true;
69333
+ }
68882
69334
  let idx = last?.idx ?? 0;
68883
69335
  for (const chunk of chunks) {
68884
69336
  idx++;
@@ -68993,86 +69445,98 @@ function createStreamer(basedir, tag) {
68993
69445
  };
68994
69446
  },
68995
69447
  async get(_runId, name, startIndex = 0) {
68996
- let teardown = /* @__PURE__ */ __name(() => {
68997
- }, "teardown");
69448
+ let lastIdx = startIndex;
68998
69449
  let closed = false;
68999
- return new ReadableStream({
69000
- start(controller) {
69001
- let resolvedStart = startIndex;
69002
- if (typeof startIndex === "number" && startIndex < 0) {
69003
- resolvedStart = Math.max(0, info(name).count + startIndex);
69004
- }
69005
- let lastIdx = resolvedStart;
69006
- let reading = false;
69007
- let failures = 0;
69008
- let timer = null;
69009
- const key = signalKey(db, name);
69010
- const finish = /* @__PURE__ */ __name(() => {
69011
- if (closed) return;
69012
- closed = true;
69013
- teardown();
69014
- try {
69015
- controller.close();
69016
- } catch {
69017
- }
69018
- }, "finish");
69019
- const drain = /* @__PURE__ */ __name(() => {
69020
- if (closed || reading) return;
69021
- reading = true;
69022
- try {
69023
- for (const row of rowsAfter(name, lastIdx)) {
69024
- lastIdx = row.idx;
69025
- if (row.eof) {
69026
- finish();
69027
- return;
69028
- }
69029
- if (row.data && row.data.byteLength > 0) {
69030
- controller.enqueue(row.data);
69031
- }
69450
+ let failures = 0;
69451
+ let wake = null;
69452
+ let timer = null;
69453
+ const key = signalKey(db, name);
69454
+ const onSignal = /* @__PURE__ */ __name(() => wake?.(), "onSignal");
69455
+ const stopWaiting = /* @__PURE__ */ __name(() => {
69456
+ wake = null;
69457
+ signals.emitter.off(key, onSignal);
69458
+ if (timer) {
69459
+ clearInterval(timer);
69460
+ timer = null;
69461
+ }
69462
+ }, "stopWaiting");
69463
+ const read3 = /* @__PURE__ */ __name((controller) => {
69464
+ const finish = /* @__PURE__ */ __name(() => {
69465
+ closed = true;
69466
+ try {
69467
+ controller.close();
69468
+ } catch {
69469
+ }
69470
+ }, "finish");
69471
+ try {
69472
+ let delivered = false;
69473
+ for (; ; ) {
69474
+ const rows = rowsAfter(name, lastIdx, READ_BATCH_CHUNKS);
69475
+ failures = 0;
69476
+ for (const row of rows) {
69477
+ lastIdx = row.idx;
69478
+ if (row.eof) {
69479
+ finish();
69480
+ return true;
69032
69481
  }
69033
- failures = 0;
69034
- const last = lastRow(name);
69035
- if (last?.eof && last.idx <= lastIdx) finish();
69036
- } catch (error62) {
69037
- failures++;
69038
- if (!closed && failures >= MAX_CONSECUTIVE_READ_FAILURES) {
69039
- closed = true;
69040
- teardown();
69041
- controller.error(error62);
69482
+ if (row.data && row.data.byteLength > 0) {
69483
+ controller.enqueue(row.data);
69484
+ delivered = true;
69042
69485
  }
69043
- } finally {
69044
- reading = false;
69045
- }
69046
- }, "drain");
69047
- teardown = /* @__PURE__ */ __name(() => {
69048
- signals.emitter.off(key, drain);
69049
- if (timer) {
69050
- clearInterval(timer);
69051
- timer = null;
69052
69486
  }
69053
- }, "teardown");
69054
- signals.emitter.on(key, drain);
69055
- drain();
69056
- if (!closed) {
69057
- timer = setInterval(drain, POLL_INTERVAL_MS);
69487
+ if (delivered) return true;
69488
+ if (rows.length < READ_BATCH_CHUNKS) break;
69058
69489
  }
69490
+ const last = lastRow(name);
69491
+ if (last?.eof && last.idx <= lastIdx) {
69492
+ finish();
69493
+ return true;
69494
+ }
69495
+ return false;
69496
+ } catch (error62) {
69497
+ failures++;
69498
+ if (failures < MAX_CONSECUTIVE_READ_FAILURES) return false;
69499
+ closed = true;
69500
+ controller.error(error62);
69501
+ return true;
69502
+ }
69503
+ }, "read");
69504
+ return new ReadableStream({
69505
+ start() {
69506
+ if (startIndex < 0) lastIdx = Math.max(0, info(name).count + startIndex);
69507
+ },
69508
+ async pull(controller) {
69509
+ if (closed || read3(controller)) return;
69510
+ await new Promise((resolve2) => {
69511
+ wake = /* @__PURE__ */ __name(() => {
69512
+ if (!closed && !read3(controller)) return;
69513
+ stopWaiting();
69514
+ resolve2();
69515
+ }, "wake");
69516
+ signals.emitter.on(key, onSignal);
69517
+ timer = setInterval(onSignal, POLL_INTERVAL_MS);
69518
+ });
69059
69519
  },
69060
69520
  cancel() {
69061
69521
  closed = true;
69062
- teardown();
69522
+ wake?.();
69523
+ stopWaiting();
69063
69524
  }
69064
69525
  });
69065
69526
  }
69066
69527
  }
69067
69528
  };
69068
69529
  }
69069
- var POLL_INTERVAL_MS, MAX_CONSECUTIVE_READ_FAILURES, signals;
69530
+ var POLL_INTERVAL_MS, READ_BATCH_CHUNKS, MAX_CONSECUTIVE_READ_FAILURES, signals;
69070
69531
  var init_streamer = __esm({
69071
69532
  "../world-local/dist/streamer.js"() {
69072
69533
  "use strict";
69073
69534
  init_dist();
69535
+ init_codec();
69074
69536
  init_db();
69537
+ init_run_retention();
69075
69538
  POLL_INTERVAL_MS = 100;
69539
+ READ_BATCH_CHUNKS = 16;
69076
69540
  MAX_CONSECUTIVE_READ_FAILURES = 50;
69077
69541
  signals = globalSingleton("@workflow/world-local//streamSignals", 1, () => {
69078
69542
  const emitter2 = new EventEmitter2();
@@ -69259,6 +69723,7 @@ function createWorld(args) {
69259
69723
  db.run("DELETE FROM stream_chunks WHERE tag = ?", tag);
69260
69724
  db.run("DELETE FROM runs WHERE tag = ?", tag);
69261
69725
  });
69726
+ await removeLegacyData(mergedConfig.dataDir, tag);
69262
69727
  await db.reclaimFreePages();
69263
69728
  }
69264
69729
  };
@@ -69276,6 +69741,7 @@ var init_dist5 = __esm({
69276
69741
  init_db();
69277
69742
  init_init();
69278
69743
  init_instrumentObject();
69744
+ init_legacy_data();
69279
69745
  init_orphaned_steps();
69280
69746
  init_queue2();
69281
69747
  init_queue_auth_key();
@@ -73116,7 +73582,7 @@ var version3;
73116
73582
  var init_version2 = __esm({
73117
73583
  "../world-vercel/dist/version.js"() {
73118
73584
  "use strict";
73119
- version3 = "5.6.1";
73585
+ version3 = "5.7.1";
73120
73586
  }
73121
73587
  });
73122
73588
 
@@ -78890,7 +79356,7 @@ var require_errors2 = __commonJS({
78890
79356
  toVercelCliError: /* @__PURE__ */ __name(() => toVercelCliError, "toVercelCliError")
78891
79357
  });
78892
79358
  module.exports = __toCommonJS(errors_exports2);
78893
- var import_promises5 = __require("node:fs/promises");
79359
+ var import_promises7 = __require("node:fs/promises");
78894
79360
  var VercelCliError2 = class extends Error {
78895
79361
  static {
78896
79362
  __name(this, "VercelCliError");
@@ -78933,7 +79399,7 @@ var require_errors2 = __commonJS({
78933
79399
  __name(getCliNotFoundMessage, "getCliNotFoundMessage");
78934
79400
  async function assertValidCwd(cwd) {
78935
79401
  try {
78936
- if (!(await (0, import_promises5.stat)(cwd)).isDirectory()) {
79402
+ if (!(await (0, import_promises7.stat)(cwd)).isDirectory()) {
78937
79403
  throw new Error("not a directory");
78938
79404
  }
78939
79405
  } catch {
@@ -81308,12 +81774,12 @@ var require_fsutils = __commonJS({
81308
81774
  statIfExists: /* @__PURE__ */ __name(() => statIfExists, "statIfExists")
81309
81775
  });
81310
81776
  module.exports = __toCommonJS(fsutils_exports);
81311
- var import_promises5 = __require("node:fs/promises");
81777
+ var import_promises7 = __require("node:fs/promises");
81312
81778
  var import_node_path6 = __toESM2(__require("node:path"));
81313
81779
  var import_errutils = require_errutils();
81314
81780
  async function getCanonicalPath(filePath) {
81315
81781
  try {
81316
- return await (0, import_promises5.realpath)(filePath);
81782
+ return await (0, import_promises7.realpath)(filePath);
81317
81783
  } catch {
81318
81784
  return filePath;
81319
81785
  }
@@ -81339,7 +81805,7 @@ var require_fsutils = __commonJS({
81339
81805
  async function statIfExists(filePath) {
81340
81806
  try {
81341
81807
  return {
81342
- stats: await (0, import_promises5.stat)(filePath)
81808
+ stats: await (0, import_promises7.stat)(filePath)
81343
81809
  };
81344
81810
  } catch (error62) {
81345
81811
  if ((0, import_errutils.isMissingPathError)(error62)) {
@@ -81429,7 +81895,7 @@ var require_safety = __commonJS({
81429
81895
  getUnsafeStatsReason: /* @__PURE__ */ __name(() => getUnsafeStatsReason, "getUnsafeStatsReason")
81430
81896
  });
81431
81897
  module.exports = __toCommonJS(safety_exports);
81432
- var import_promises5 = __require("node:fs/promises");
81898
+ var import_promises7 = __require("node:fs/promises");
81433
81899
  var import_node_path6 = __toESM2(__require("node:path"));
81434
81900
  var import_errutils = require_errutils();
81435
81901
  var import_fsutils = require_fsutils();
@@ -81519,7 +81985,7 @@ var require_safety = __commonJS({
81519
81985
  }
81520
81986
  __name(getUnsafePackageFileReason, "getUnsafePackageFileReason");
81521
81987
  async function getUnsafeDirectoryReason(directory) {
81522
- const stats = await (0, import_promises5.stat)(directory);
81988
+ const stats = await (0, import_promises7.stat)(directory);
81523
81989
  if (!stats.isDirectory()) {
81524
81990
  return "not a directory";
81525
81991
  }
@@ -81527,7 +81993,7 @@ var require_safety = __commonJS({
81527
81993
  }
81528
81994
  __name(getUnsafeDirectoryReason, "getUnsafeDirectoryReason");
81529
81995
  async function getUnsafeFileReason(filePath) {
81530
- const stats = await (0, import_promises5.stat)(filePath);
81996
+ const stats = await (0, import_promises7.stat)(filePath);
81531
81997
  if (!stats.isFile()) {
81532
81998
  return "not a file";
81533
81999
  }
@@ -81604,7 +82070,7 @@ var require_lookup = __commonJS({
81604
82070
  toVercelCliInvocation: /* @__PURE__ */ __name(() => toVercelCliInvocation, "toVercelCliInvocation")
81605
82071
  });
81606
82072
  module.exports = __toCommonJS(lookup_exports);
81607
- var import_promises5 = __require("node:fs/promises");
82073
+ var import_promises7 = __require("node:fs/promises");
81608
82074
  var import_node_path6 = __toESM2(__require("node:path"));
81609
82075
  var import_envpath = require_envpath();
81610
82076
  var import_errutils = require_errutils();
@@ -81708,7 +82174,7 @@ var require_lookup = __commonJS({
81708
82174
  __name(getPathCommandCandidate, "getPathCommandCandidate");
81709
82175
  async function canAccessCommandCandidate(candidate, localBinSearch, diagnostics) {
81710
82176
  try {
81711
- await (0, import_promises5.access)(candidate, process.platform === "win32" ? import_promises5.constants.F_OK : import_promises5.constants.F_OK | import_promises5.constants.X_OK);
82177
+ await (0, import_promises7.access)(candidate, process.platform === "win32" ? import_promises7.constants.F_OK : import_promises7.constants.F_OK | import_promises7.constants.X_OK);
81712
82178
  return true;
81713
82179
  } catch (error62) {
81714
82180
  if (!(0, import_errutils.isMissingPathError)(error62)) {
@@ -81727,10 +82193,10 @@ var require_lookup = __commonJS({
81727
82193
  }
81728
82194
  __name(recordInaccessibleLocalBinCandidate, "recordInaccessibleLocalBinCandidate");
81729
82195
  async function resolveCommandCandidate(command, candidate, localBinSearch, diagnostics) {
81730
- if (!(await (0, import_promises5.stat)(candidate)).isFile()) {
82196
+ if (!(await (0, import_promises7.stat)(candidate)).isFile()) {
81731
82197
  return null;
81732
82198
  }
81733
- const realPath = await (0, import_promises5.realpath)(candidate);
82199
+ const realPath = await (0, import_promises7.realpath)(candidate);
81734
82200
  const localBinCandidate = await classifyPathLocalBinCandidate(candidate, localBinSearch.directories);
81735
82201
  if (!localBinCandidate) {
81736
82202
  return {
@@ -81834,7 +82300,7 @@ var require_lookup = __commonJS({
81834
82300
  async function getProjectRootMarker(directory) {
81835
82301
  const gitPath = import_node_path6.default.join(directory, ".git");
81836
82302
  try {
81837
- await (0, import_promises5.stat)(gitPath);
82303
+ await (0, import_promises7.stat)(gitPath);
81838
82304
  return {
81839
82305
  path: gitPath
81840
82306
  };
@@ -81847,12 +82313,12 @@ var require_lookup = __commonJS({
81847
82313
  const resolvedFilePath = import_node_path6.default.resolve(filePath);
81848
82314
  let canonicalFilePath = resolvedFilePath;
81849
82315
  try {
81850
- canonicalFilePath = import_node_path6.default.join(await (0, import_promises5.realpath)(import_node_path6.default.dirname(resolvedFilePath)), import_node_path6.default.basename(resolvedFilePath));
82316
+ canonicalFilePath = import_node_path6.default.join(await (0, import_promises7.realpath)(import_node_path6.default.dirname(resolvedFilePath)), import_node_path6.default.basename(resolvedFilePath));
81851
82317
  } catch {
81852
82318
  }
81853
82319
  for (let localBinDirectory of localBinDirectories) {
81854
82320
  try {
81855
- localBinDirectory = await (0, import_promises5.realpath)(localBinDirectory);
82321
+ localBinDirectory = await (0, import_promises7.realpath)(localBinDirectory);
81856
82322
  } catch {
81857
82323
  }
81858
82324
  if (canonicalFilePath.startsWith(`${localBinDirectory}${import_node_path6.default.sep}`)) {
@@ -81868,7 +82334,7 @@ var require_lookup = __commonJS({
81868
82334
  candidateDirectory
81869
82335
  ];
81870
82336
  try {
81871
- const canonicalDirectory = await (0, import_promises5.realpath)(candidateDirectory);
82337
+ const canonicalDirectory = await (0, import_promises7.realpath)(candidateDirectory);
81872
82338
  if (!directories.includes(canonicalDirectory)) {
81873
82339
  directories.push(canonicalDirectory);
81874
82340
  }
@@ -81933,8 +82399,8 @@ var require_lookup = __commonJS({
81933
82399
  __name(getLocalVercelPackageBin, "getLocalVercelPackageBin");
81934
82400
  async function getLocalVercelPackage(nodeModulesDirectory) {
81935
82401
  const packageDirectory = import_node_path6.default.join(nodeModulesDirectory, "vercel");
81936
- const realNodeModulesDirectory = await (0, import_promises5.realpath)(nodeModulesDirectory);
81937
- const realPackageDirectory = await (0, import_promises5.realpath)(packageDirectory);
82402
+ const realNodeModulesDirectory = await (0, import_promises7.realpath)(nodeModulesDirectory);
82403
+ const realPackageDirectory = await (0, import_promises7.realpath)(packageDirectory);
81938
82404
  if (!(0, import_fsutils.isSubpath)(realNodeModulesDirectory, realPackageDirectory)) {
81939
82405
  return {
81940
82406
  reason: "local vercel package resolves outside local node_modules"
@@ -81955,7 +82421,7 @@ var require_lookup = __commonJS({
81955
82421
  __name(getLocalVercelPackage, "getLocalVercelPackage");
81956
82422
  async function readLocalVercelPackageJson(realPackageDirectory) {
81957
82423
  const packageJsonPath = import_node_path6.default.join(realPackageDirectory, "package.json");
81958
- const realPackageJsonPath = await (0, import_promises5.realpath)(packageJsonPath);
82424
+ const realPackageJsonPath = await (0, import_promises7.realpath)(packageJsonPath);
81959
82425
  if (!(0, import_fsutils.isSubpath)(realPackageDirectory, realPackageJsonPath)) {
81960
82426
  return {
81961
82427
  reason: "local vercel package.json resolves outside package"
@@ -81967,7 +82433,7 @@ var require_lookup = __commonJS({
81967
82433
  reason: `local vercel package.json is unsafe: ${unsafePackageJsonReason}`
81968
82434
  };
81969
82435
  }
81970
- const packageJson = JSON.parse(await (0, import_promises5.readFile)(realPackageJsonPath, "utf8"));
82436
+ const packageJson = JSON.parse(await (0, import_promises7.readFile)(realPackageJsonPath, "utf8"));
81971
82437
  if (packageJson.name !== "vercel") {
81972
82438
  return {
81973
82439
  reason: 'local vercel package.json does not have name "vercel"'
@@ -81987,7 +82453,7 @@ var require_lookup = __commonJS({
81987
82453
  };
81988
82454
  }
81989
82455
  const declaredBinPath = import_node_path6.default.resolve(realPackageDirectory, binTarget);
81990
- const realDeclaredBinPath = await (0, import_promises5.realpath)(declaredBinPath);
82456
+ const realDeclaredBinPath = await (0, import_promises7.realpath)(declaredBinPath);
81991
82457
  if (!(0, import_fsutils.isSubpath)(realPackageDirectory, realDeclaredBinPath)) {
81992
82458
  return {
81993
82459
  reason: "local vercel package bin resolves outside package"
@@ -82001,7 +82467,7 @@ var require_lookup = __commonJS({
82001
82467
  }
82002
82468
  if (process.platform !== "win32" && !(0, import_fsutils.isNodeScript)(realDeclaredBinPath)) {
82003
82469
  try {
82004
- await (0, import_promises5.access)(realDeclaredBinPath, import_promises5.constants.F_OK | import_promises5.constants.X_OK);
82470
+ await (0, import_promises7.access)(realDeclaredBinPath, import_promises7.constants.F_OK | import_promises7.constants.X_OK);
82005
82471
  } catch (error62) {
82006
82472
  return {
82007
82473
  reason: `local vercel package bin is not executable: ${(0, import_errutils.getErrorMessage)(error62)}`
@@ -85380,11 +85846,11 @@ ${content.join(`
85380
85846
  return this._map.has(schema);
85381
85847
  }
85382
85848
  };
85383
- function registry2() {
85849
+ function registry3() {
85384
85850
  return new $ZodRegistry2();
85385
85851
  }
85386
- __name(registry2, "registry");
85387
- (_a22 = globalThis).__zod_globalRegistry ?? (_a22.__zod_globalRegistry = registry2());
85852
+ __name(registry3, "registry");
85853
+ (_a22 = globalThis).__zod_globalRegistry ?? (_a22.__zod_globalRegistry = registry3());
85388
85854
  var globalRegistry2 = globalThis.__zod_globalRegistry;
85389
85855
  function snapshotChecks2(def) {
85390
85856
  return def.checks && (def.checks = [
@@ -88363,7 +88829,7 @@ var require_get_vercel_oidc_token_with_refresh = __commonJS({
88363
88829
  getVercelOidcToken: /* @__PURE__ */ __name(() => getVercelOidcToken8, "getVercelOidcToken")
88364
88830
  });
88365
88831
  module.exports = __toCommonJS(get_vercel_oidc_token_with_refresh_exports);
88366
- var import_promises5 = __require("node:fs/promises");
88832
+ var import_promises7 = __require("node:fs/promises");
88367
88833
  var import_exchange_vercel_oidc_token = require_exchange_vercel_oidc_token();
88368
88834
  var import_get_context = require_get_context3();
88369
88835
  var import_get_vercel_oidc_token_sync = require_get_vercel_oidc_token_sync();
@@ -88413,7 +88879,7 @@ ${error62.message}`;
88413
88879
  if (!tokenFile) {
88414
88880
  return null;
88415
88881
  }
88416
- const token = (await (0, import_promises5.readFile)(tokenFile, "utf8")).trim();
88882
+ const token = (await (0, import_promises7.readFile)(tokenFile, "utf8")).trim();
88417
88883
  if (!token) {
88418
88884
  throw new import_token_error.VercelOidcTokenError(`The Vercel OIDC token file is empty: ${tokenFile}`);
88419
88885
  }
@@ -93901,7 +94367,7 @@ function createThrottleWaiter(target2, budget, beforeWait) {
93901
94367
  waitedMs += waitMs;
93902
94368
  console.warn(`[workflow] Throttled (429) ${target2}; retrying in-process in ${waitMs / 1e3}s`);
93903
94369
  await beforeWait?.();
93904
- await sleep(waitMs, signal);
94370
+ await sleep2(waitMs, signal);
93905
94371
  };
93906
94372
  }
93907
94373
  function createStartHookRunPendingWaiter(target2, startedAtMs = Date.now()) {
@@ -93929,7 +94395,7 @@ function createStartHookRunPendingWaiter(target2, startedAtMs = Date.now()) {
93929
94395
  waitMs,
93930
94396
  waitedMs
93931
94397
  });
93932
- await sleep(waitMs);
94398
+ await sleep2(waitMs);
93933
94399
  };
93934
94400
  }
93935
94401
  function throttleBudgetFor(eventType, options) {
@@ -94001,12 +94467,12 @@ async function withEventPostRetry(fn, eventType, options) {
94001
94467
  backoffMs: backoff,
94002
94468
  error: errorMarker(err)
94003
94469
  });
94004
- await sleep(backoff);
94470
+ await sleep2(backoff);
94005
94471
  retried = true;
94006
94472
  }
94007
94473
  }
94008
94474
  }
94009
- var ReplayEventObserverError, AfterCommitError, STEP_OUTCOME_EVENT_TYPES, EVENT_RETRY_ELIGIBILITY, START_HOOK_RUN_PENDING_CODE, START_HOOK_RUN_PENDING_BUDGET_MS, DEFAULT_START_HOOK_RUN_PENDING_RETRY_AFTER_SECONDS, MAX_EVENT_POST_RETRIES, THROTTLE_RETRY_BUDGET_MS, THROTTLE_DEADLINE_RESERVE_MS, THROTTLE_RETRY_MAX_BUDGET_MS, DEFAULT_THROTTLE_RETRY_AFTER_SECONDS, EVENT_POST_RETRY_BASE_MS, EVENT_POST_RETRY_JITTER_MS, TRANSIENT_CODES, sleep, RETRY_DEBUG_ENABLED;
94475
+ var ReplayEventObserverError, AfterCommitError, STEP_OUTCOME_EVENT_TYPES, EVENT_RETRY_ELIGIBILITY, START_HOOK_RUN_PENDING_CODE, START_HOOK_RUN_PENDING_BUDGET_MS, DEFAULT_START_HOOK_RUN_PENDING_RETRY_AFTER_SECONDS, MAX_EVENT_POST_RETRIES, THROTTLE_RETRY_BUDGET_MS, THROTTLE_DEADLINE_RESERVE_MS, THROTTLE_RETRY_MAX_BUDGET_MS, DEFAULT_THROTTLE_RETRY_AFTER_SECONDS, EVENT_POST_RETRY_BASE_MS, EVENT_POST_RETRY_JITTER_MS, TRANSIENT_CODES, sleep2, RETRY_DEBUG_ENABLED;
94010
94476
  var init_event_retry = __esm({
94011
94477
  "../world-vercel/dist/event-retry.js"() {
94012
94478
  "use strict";
@@ -94164,7 +94630,7 @@ var init_event_retry = __esm({
94164
94630
  ]);
94165
94631
  __name(collectErrorMarkers, "collectErrorMarkers");
94166
94632
  __name(isRetryableEventPostError, "isRetryableEventPostError");
94167
- sleep = /* @__PURE__ */ __name((ms2, signal) => new Promise((resolve2, reject) => {
94633
+ sleep2 = /* @__PURE__ */ __name((ms2, signal) => new Promise((resolve2, reject) => {
94168
94634
  if (signal?.aborted) {
94169
94635
  reject(signal.reason);
94170
94636
  return;
@@ -94416,7 +94882,10 @@ function httpLog(method, label, response, ms2) {
94416
94882
  }
94417
94883
  function logCurlRepro(method, url2, headers) {
94418
94884
  if (!process.env.DEBUG) return;
94419
- const stringifiedHeaders = Array.from(headers.entries()).filter(([key]) => key.toLowerCase() !== "authorization").map(([key, value]) => `-H "${key}: ${value}"`).join(" ");
94885
+ const stringifiedHeaders = Array.from(headers.entries()).filter(([key]) => {
94886
+ const name = key.toLowerCase();
94887
+ return name !== "authorization" && name !== "x-vercel-workflow-api-url";
94888
+ }).map(([key, value]) => `-H "${key}: ${value}"`).join(" ");
94420
94889
  console.error(`Failed to fetch, reproduce with:
94421
94890
  curl -X ${method} ${stringifiedHeaders} "${url2}"`);
94422
94891
  }
@@ -94478,7 +94947,16 @@ function errorForResponse(status, message, opts = {}) {
94478
94947
  code: START_HOOK_CANDIDATE_CANCELLED
94479
94948
  });
94480
94949
  }
94481
- if (status === 409) return new EntityConflictError(message);
94950
+ if (status === 409) {
94951
+ return new EntityConflictError(message, {
94952
+ ...code2 !== void 0 ? {
94953
+ code: code2
94954
+ } : {},
94955
+ ...url2 !== void 0 ? {
94956
+ url: url2
94957
+ } : {}
94958
+ });
94959
+ }
94482
94960
  if (status === 410) {
94483
94961
  if (code2 === "stream-expired") {
94484
94962
  const streamDetails = details && typeof details === "object" ? details : void 0;
@@ -94599,7 +95077,7 @@ async function fetchStreamAppend(request, signal) {
94599
95077
  if (retry === STREAM_APPEND_MAX_RETRIES || !code2 || !STREAM_APPEND_CONNECT_ERROR_CODES.has(code2)) {
94600
95078
  throw error62;
94601
95079
  }
94602
- await sleep(500 * 2 ** retry, signal);
95080
+ await sleep2(500 * 2 ** retry, signal);
94603
95081
  continue;
94604
95082
  }
94605
95083
  if (response.status !== 429 || isFirewallChallenge429(response.status, response.headers.get("x-vercel-mitigated")) || retry === STREAM_APPEND_MAX_RETRIES) {
@@ -99216,10 +99694,10 @@ function registerHandlerForFile(filePath, handler, client, options) {
99216
99694
  const absolutePath = path7.isAbsolute(filePath) ? filePath : path7.resolve(process.cwd(), filePath);
99217
99695
  const fileMappings = findMappingsForFile(absolutePath);
99218
99696
  if (fileMappings.length === 0) return false;
99219
- const registry2 = getHandlerRegistry();
99697
+ const registry3 = getHandlerRegistry();
99220
99698
  for (const mapping of fileMappings) {
99221
99699
  const key = mapping.topic;
99222
- const existing = registry2.get(key) ?? [];
99700
+ const existing = registry3.get(key) ?? [];
99223
99701
  const nextEntry = {
99224
99702
  consumerGroup: mapping.consumer,
99225
99703
  handler,
@@ -99232,7 +99710,7 @@ function registerHandlerForFile(filePath, handler, client, options) {
99232
99710
  } else {
99233
99711
  existing.push(nextEntry);
99234
99712
  }
99235
- registry2.set(key, existing);
99713
+ registry3.set(key, existing);
99236
99714
  }
99237
99715
  return true;
99238
99716
  }
@@ -99265,9 +99743,9 @@ Add a trigger to vercel.json:
99265
99743
  }
99266
99744
  }
99267
99745
  function lookupHandlers(topicName) {
99268
- const registry2 = getHandlerRegistry();
99746
+ const registry3 = getHandlerRegistry();
99269
99747
  const result = [];
99270
- for (const [pattern, handlers] of registry2) {
99748
+ for (const [pattern, handlers] of registry3) {
99271
99749
  const matches = pattern.includes("*") ? matchesWildcardPattern(topicName, pattern) : pattern === topicName;
99272
99750
  if (matches) {
99273
99751
  result.push(...handlers);
@@ -99328,10 +99806,10 @@ function isPortListening(port) {
99328
99806
  host: "localhost",
99329
99807
  port
99330
99808
  });
99331
- let settled = false;
99809
+ let settled2 = false;
99332
99810
  const finish = /* @__PURE__ */ __name((listening) => {
99333
- if (settled) return;
99334
- settled = true;
99811
+ if (settled2) return;
99812
+ settled2 = true;
99335
99813
  socket.destroy();
99336
99814
  resolve2(listening);
99337
99815
  }, "finish");
@@ -101966,11 +102444,11 @@ async function withQueueSendRetry(send, options = {}) {
101966
102444
  throw error62;
101967
102445
  }
101968
102446
  options.onRetry?.(error62, attempt, delayMs);
101969
- await sleep2(delayMs);
102447
+ await sleep3(delayMs);
101970
102448
  }
101971
102449
  }
101972
102450
  }
101973
- var QUEUE_SEND_MAX_ATTEMPTS, QUEUE_SEND_RETRY_DELAYS_MS, QUEUE_SEND_RETRY_JITTER_MS, QUEUE_SEND_RETRY_BUDGET_MS, QUEUE_SEND_MAX_RETRY_AFTER_MS, sleep2;
102451
+ var QUEUE_SEND_MAX_ATTEMPTS, QUEUE_SEND_RETRY_DELAYS_MS, QUEUE_SEND_RETRY_JITTER_MS, QUEUE_SEND_RETRY_BUDGET_MS, QUEUE_SEND_MAX_RETRY_AFTER_MS, sleep3;
101974
102452
  var init_queue_send_retry = __esm({
101975
102453
  "../world-vercel/dist/queue-send-retry.js"() {
101976
102454
  "use strict";
@@ -101985,7 +102463,7 @@ var init_queue_send_retry = __esm({
101985
102463
  QUEUE_SEND_MAX_RETRY_AFTER_MS = 5e3;
101986
102464
  __name(queueErrorName, "queueErrorName");
101987
102465
  __name(queueSendRetryDelayMs, "queueSendRetryDelayMs");
101988
- sleep2 = /* @__PURE__ */ __name((ms2) => new Promise((resolve2) => setTimeout(resolve2, ms2)), "sleep");
102466
+ sleep3 = /* @__PURE__ */ __name((ms2) => new Promise((resolve2) => setTimeout(resolve2, ms2)), "sleep");
101989
102467
  __name(withQueueSendRetry, "withQueueSendRetry");
101990
102468
  }
101991
102469
  });
@@ -104291,6 +104769,9 @@ function buildPostFrameMeta(input2) {
104291
104769
  if (input2.replayDivergenceCount !== void 0) {
104292
104770
  meta3.replayDivergenceCount = input2.replayDivergenceCount;
104293
104771
  }
104772
+ if (input2.replayDivergenceEventIds !== void 0) {
104773
+ meta3.replayDivergenceEventIds = input2.replayDivergenceEventIds;
104774
+ }
104294
104775
  if (input2.resumePayloadDigest !== void 0) {
104295
104776
  meta3.resumePayloadDigest = input2.resumePayloadDigest;
104296
104777
  }
@@ -105630,6 +106111,57 @@ async function cancelWorkflowRuns(request, config3) {
105630
106111
  results: orderedResults
105631
106112
  };
105632
106113
  }
106114
+ function deleteRunDataResultFromWire(result) {
106115
+ switch (result.outcome) {
106116
+ case "purged":
106117
+ return {
106118
+ runId: result.runId,
106119
+ outcome: "deleted"
106120
+ };
106121
+ case "already_purged":
106122
+ return {
106123
+ runId: result.runId,
106124
+ outcome: "already_deleted"
106125
+ };
106126
+ default:
106127
+ return result;
106128
+ }
106129
+ }
106130
+ async function deleteWorkflowRunsData(request, config3) {
106131
+ const { runIds: runIds2 } = DeleteRunsDataRequestSchema.parse(request);
106132
+ const response = await makeRequest({
106133
+ endpoint: "/v4/runs/purge",
106134
+ options: {
106135
+ method: "POST"
106136
+ },
106137
+ data: {
106138
+ runIds: runIds2
106139
+ },
106140
+ config: config3,
106141
+ schema: DeleteRunsDataWireResultSchema
106142
+ });
106143
+ const resultByRunId = new Map(response.results.map((result) => [
106144
+ result.runId,
106145
+ result
106146
+ ]));
106147
+ const isBijection = resultByRunId.size === response.results.length && response.results.length === runIds2.length && runIds2.every((runId) => resultByRunId.has(runId));
106148
+ if (!isBijection) {
106149
+ throw new WorkflowWorldError(`Delete-data response did not contain exactly one result per requested run ID (requested ${runIds2.length}, received ${response.results.length}).`);
106150
+ }
106151
+ const { purged, alreadyPurged, ...summary } = response.summary;
106152
+ return {
106153
+ summary: {
106154
+ requested: summary.requested,
106155
+ deleted: purged,
106156
+ alreadyDeleted: alreadyPurged,
106157
+ skipped: summary.skipped,
106158
+ notCreated: summary.notCreated,
106159
+ notFound: summary.notFound,
106160
+ failed: summary.failed
106161
+ },
106162
+ results: runIds2.map((runId) => deleteRunDataResultFromWire(resultByRunId.get(runId)))
106163
+ };
106164
+ }
105633
106165
  async function experimentalSetAttributes(runId, changes, options, config3) {
105634
106166
  try {
105635
106167
  const response = await makeRequest({
@@ -105656,7 +106188,7 @@ async function experimentalSetAttributes(runId, changes, options, config3) {
105656
106188
  throw error62;
105657
106189
  }
105658
106190
  }
105659
- var WorkflowRunWireBaseSchema, WorkflowRunWireSchema, WorkflowRunWireWithRefsSchema, WAIT_TIMEOUT_HEADROOM_MS, LONG_POLL_UNSUPPORTED_TTL_MS, longPoll, ExperimentalSetAttributesResponseSchema;
106191
+ var WorkflowRunWireBaseSchema, WorkflowRunWireSchema, WorkflowRunWireWithRefsSchema, WAIT_TIMEOUT_HEADROOM_MS, LONG_POLL_UNSUPPORTED_TTL_MS, longPoll, DeleteRunsDataWireResultSchema, ExperimentalSetAttributesResponseSchema;
105660
106192
  var init_runs2 = __esm({
105661
106193
  "../world-vercel/dist/runs.js"() {
105662
106194
  "use strict";
@@ -105717,6 +106249,49 @@ var init_runs2 = __esm({
105717
106249
  __name(getWorkflowRuns, "getWorkflowRuns");
105718
106250
  __name(cancelWorkflowRunV1, "cancelWorkflowRunV1");
105719
106251
  __name(cancelWorkflowRuns, "cancelWorkflowRuns");
106252
+ DeleteRunsDataWireResultSchema = external_exports.object({
106253
+ summary: external_exports.object({
106254
+ requested: external_exports.number(),
106255
+ purged: external_exports.number(),
106256
+ alreadyPurged: external_exports.number(),
106257
+ skipped: external_exports.number(),
106258
+ notCreated: external_exports.number(),
106259
+ notFound: external_exports.number(),
106260
+ failed: external_exports.number()
106261
+ }),
106262
+ results: external_exports.array(external_exports.discriminatedUnion("outcome", [
106263
+ external_exports.object({
106264
+ runId: external_exports.string(),
106265
+ outcome: external_exports.literal("purged")
106266
+ }),
106267
+ external_exports.object({
106268
+ runId: external_exports.string(),
106269
+ outcome: external_exports.literal("already_purged")
106270
+ }),
106271
+ external_exports.object({
106272
+ runId: external_exports.string(),
106273
+ outcome: external_exports.literal("skipped"),
106274
+ reason: external_exports.string(),
106275
+ status: external_exports.string()
106276
+ }),
106277
+ external_exports.object({
106278
+ runId: external_exports.string(),
106279
+ outcome: external_exports.literal("not_created")
106280
+ }),
106281
+ external_exports.object({
106282
+ runId: external_exports.string(),
106283
+ outcome: external_exports.literal("not_found")
106284
+ }),
106285
+ external_exports.object({
106286
+ runId: external_exports.string(),
106287
+ outcome: external_exports.literal("failed"),
106288
+ code: external_exports.string(),
106289
+ retryable: external_exports.boolean()
106290
+ })
106291
+ ]))
106292
+ });
106293
+ __name(deleteRunDataResultFromWire, "deleteRunDataResultFromWire");
106294
+ __name(deleteWorkflowRunsData, "deleteWorkflowRunsData");
105720
106295
  ExperimentalSetAttributesResponseSchema = external_exports.object({
105721
106296
  attributes: external_exports.record(external_exports.string(), external_exports.string())
105722
106297
  });
@@ -106172,6 +106747,7 @@ async function createWorkflowRunEventInner(id, data2, params, config3) {
106172
106747
  expectedSeqInBand: params.expectedSeqInBand
106173
106748
  } : {},
106174
106749
  replayDivergenceCount: params?.replayDivergenceCount,
106750
+ replayDivergenceEventIds: params?.replayDivergenceEventIds,
106175
106751
  // In-band writer fence. The backend refuses a stale in-band write with
106176
106752
  // 412 `in-band-superseded` (InBandSupersededError).
106177
106753
  ...params?.inBand !== void 0 ? {
@@ -106828,7 +107404,8 @@ function createStorage2(config3) {
106828
107404
  getMany: /* @__PURE__ */ __name((ids, params) => getWorkflowRuns(ids, params, config3), "getMany"),
106829
107405
  list: /* @__PURE__ */ __name((params) => listWorkflowRuns(params, config3), "list"),
106830
107406
  experimentalSetAttributes: /* @__PURE__ */ __name((runId, changes, options) => experimentalSetAttributes(runId, changes, options, config3), "experimentalSetAttributes"),
106831
- cancelMany: /* @__PURE__ */ __name((request) => cancelWorkflowRuns(request, config3), "cancelMany")
107407
+ cancelMany: /* @__PURE__ */ __name((request) => cancelWorkflowRuns(request, config3), "cancelMany"),
107408
+ deleteDataMany: /* @__PURE__ */ __name((request) => deleteWorkflowRunsData(request, config3), "deleteDataMany")
106832
107409
  },
106833
107410
  steps: {
106834
107411
  get: /* @__PURE__ */ __name((runId, stepId, params) => getStep(runId, stepId, params, config3), "get"),
@@ -107050,10 +107627,10 @@ function beginNormalWsClose(ws, reason) {
107050
107627
  if (ws.readyState === 3) return;
107051
107628
  let timedOut = false;
107052
107629
  const observed = new Promise((resolve2) => {
107053
- let settled = false;
107630
+ let settled2 = false;
107054
107631
  const finish = /* @__PURE__ */ __name(() => {
107055
- if (settled) return;
107056
- settled = true;
107632
+ if (settled2) return;
107633
+ settled2 = true;
107057
107634
  clearTimeout(timer);
107058
107635
  resolve2();
107059
107636
  }, "finish");
@@ -109172,8 +109749,9 @@ async function resumeHookAttempt(world, span, tokenOrHook, payload, encryptionKe
109172
109749
  requireHookResumeDedup: true
109173
109750
  } : {}
109174
109751
  }), "write");
109752
+ let committedEventId;
109175
109753
  try {
109176
- await write(canClaimResume, resolvedHandle && canClaimResume);
109754
+ committedEventId = (await write(canClaimResume, resolvedHandle && canClaimResume))?.event?.eventId;
109177
109755
  } catch (err) {
109178
109756
  if (WorkflowWorldError.is(err) && err.code === "HOOK_RESUME_RETRY_REFUSED") {
109179
109757
  throw err;
@@ -109219,7 +109797,7 @@ async function resumeHookAttempt(world, span, tokenOrHook, payload, encryptionKe
109219
109797
  hook = fresh;
109220
109798
  const freshDedup = (fresh.resumeCapabilities?.hookResumeDedupVersion ?? 0) >= HOOK_RESUME_DEDUP_VERSION || world.capabilities?.hookResumeDedup === true;
109221
109799
  try {
109222
- await write(freshDedup, false);
109800
+ committedEventId = (await write(freshDedup, false))?.event?.eventId;
109223
109801
  } catch (fallbackError) {
109224
109802
  if (isHookGoneError(fallbackError)) throw new HookNotFoundError(hook.token);
109225
109803
  throw fallbackError;
@@ -109238,6 +109816,9 @@ async function resumeHookAttempt(world, span, tokenOrHook, payload, encryptionKe
109238
109816
  runSpecVersion: resumeContext.runSpecVersion
109239
109817
  },
109240
109818
  traceCarrier: resumeContext.traceCarrier ?? void 0,
109819
+ ...committedEventId !== void 0 && {
109820
+ wakeEventId: committedEventId
109821
+ },
109241
109822
  hookResumeTiming: {
109242
109823
  resumeRequestedAtMs,
109243
109824
  queuePublishRequestedAtMs,
@@ -110052,6 +110633,7 @@ function attachAbortListenerOnce(signal, streamName, runId, cryptoKey, ops, fram
110052
110633
  aborted: true,
110053
110634
  reason: signal.reason
110054
110635
  }, runId, key);
110636
+ publishLocalAbort(runId, streamName, payload);
110055
110637
  const writable = new WorkflowServerWritableStream(runId, streamName);
110056
110638
  const writer = writable.getWriter();
110057
110639
  await writer.write(framedAbortStreams ? frameAbortStreamPayload(payload) : payload);
@@ -110340,40 +110922,84 @@ function cancelAbortReaders(...values) {
110340
110922
  __name(walk, "walk");
110341
110923
  for (const v of values) walk(v);
110342
110924
  }
110343
- function setupAbortStreamReader(controller, runId, streamName, ops) {
110925
+ function setupAbortStreamReader(controller, runId, streamName, ops, cryptoKey, untilCancelled) {
110344
110926
  const readerCancel = new AbortController();
110927
+ let resolveLocal;
110928
+ const localPacket = new Promise((resolve2) => {
110929
+ resolveLocal = resolve2;
110930
+ });
110931
+ const stopLocal = onLocalAbort(runId, streamName, (packet) => resolveLocal?.(packet));
110345
110932
  ops.push((async () => {
110346
110933
  let reader;
110934
+ let keepListening = false;
110347
110935
  try {
110348
- const readable = new WorkflowServerReadableStream(runId, streamName);
110349
- reader = readable.getReader();
110350
- const ctxForKey = contextStorage.getStore();
110936
+ let keyPromise;
110351
110937
  let decoded;
110352
110938
  const decodePacket = /* @__PURE__ */ __name(async (packet) => {
110353
- decoded = await hydrateStepArguments(packet, runId, ctxForKey?.encryptionKey);
110939
+ keyPromise ??= resolveEncryptionKey(cryptoKey);
110940
+ decoded = await hydrateStepArguments(packet, runId, await keyPromise);
110354
110941
  }, "decodePacket");
110355
- const result = await Promise.race([
110356
- readAbortStreamPacket(reader, decodePacket),
110357
- new Promise((resolve2) => {
110358
- if (readerCancel.signal.aborted) {
110359
- resolve2(void 0);
110360
- return;
110361
- }
110362
- readerCancel.signal.addEventListener("abort", () => resolve2(void 0), {
110363
- once: true
110364
- });
110365
- })
110366
- ]);
110367
- if (result) {
110942
+ const abortWith = /* @__PURE__ */ __name(async (packet, already) => {
110368
110943
  try {
110369
- if (decoded === void 0) await decodePacket(result);
110944
+ decoded = already;
110945
+ if (decoded === void 0) await decodePacket(packet);
110370
110946
  controller.abort(decoded?.reason);
110371
110947
  } catch {
110372
110948
  controller.abort();
110373
110949
  }
110950
+ }, "abortWith");
110951
+ const cancelled = new Promise((resolve2) => {
110952
+ if (readerCancel.signal.aborted) {
110953
+ resolve2(void 0);
110954
+ return;
110955
+ }
110956
+ readerCancel.signal.addEventListener("abort", () => resolve2(void 0), {
110957
+ once: true
110958
+ });
110959
+ });
110960
+ let streamPacket;
110961
+ try {
110962
+ const readable = new WorkflowServerReadableStream(runId, streamName);
110963
+ reader = readable.getReader();
110964
+ streamPacket = readAbortStreamPacket(reader, decodePacket);
110965
+ } catch {
110966
+ streamPacket = new Promise(() => {
110967
+ });
110968
+ }
110969
+ const local = localPacket.then((packet) => ({
110970
+ packet,
110971
+ local: true
110972
+ }));
110973
+ const winner = await Promise.race([
110974
+ local,
110975
+ untilCancelled ? streamPacket.then((packet) => packet ? {
110976
+ packet,
110977
+ local: false
110978
+ } : void 0, () => void 0) : streamPacket.then((packet) => packet ? {
110979
+ packet,
110980
+ local: false
110981
+ } : void 0),
110982
+ cancelled
110983
+ ]);
110984
+ if (winner) {
110985
+ await abortWith(winner.packet, winner.local ? void 0 : decoded);
110986
+ } else if (untilCancelled && !readerCancel.signal.aborted) {
110987
+ keepListening = true;
110988
+ const expiry = setTimeout(stopLocal, LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS);
110989
+ expiry.unref?.();
110990
+ void Promise.race([
110991
+ local,
110992
+ cancelled
110993
+ ]).then(async (late) => {
110994
+ clearTimeout(expiry);
110995
+ stopLocal();
110996
+ if (late) await abortWith(late.packet, void 0);
110997
+ }).catch(() => {
110998
+ });
110374
110999
  }
110375
111000
  } catch {
110376
111001
  } finally {
111002
+ if (!keepListening) stopLocal();
110377
111003
  void reader?.cancel().catch(() => {
110378
111004
  });
110379
111005
  }
@@ -110405,13 +111031,13 @@ function copyAbortInternals(src2, dest) {
110405
111031
  d[ABORT_READER_CANCEL] = s[ABORT_READER_CANCEL];
110406
111032
  }
110407
111033
  }
110408
- function reviveAbortController(value, ops, runId) {
111034
+ function reviveAbortController(value, ops, runId, cryptoKey, untilCancelled = false) {
110409
111035
  const controller = new AbortController();
110410
111036
  if (value.aborted) {
110411
111037
  tagAbortPair(controller, value);
110412
111038
  controller.abort(value.reason);
110413
111039
  } else if (value.streamName) {
110414
- const readerCancel = setupAbortStreamReader(controller, runId, value.streamName, ops);
111040
+ const readerCancel = setupAbortStreamReader(controller, runId, value.streamName, ops, cryptoKey, untilCancelled);
110415
111041
  tagAbortPair(controller, value, readerCancel);
110416
111042
  } else {
110417
111043
  tagAbortPair(controller, value);
@@ -110428,6 +111054,7 @@ function reviveAbortController(value, ops, runId) {
110428
111054
  aborted: true,
110429
111055
  reason
110430
111056
  }, ctx.workflowMetadata.workflowRunId, ctx.encryptionKey);
111057
+ publishLocalAbort(ctx.workflowMetadata.workflowRunId, value.streamName, payload);
110431
111058
  const writable = new WorkflowServerWritableStream(ctx.workflowMetadata.workflowRunId, value.streamName);
110432
111059
  const writer = writable.getWriter();
110433
111060
  await writer.write(frameAbortStreamPayload(payload));
@@ -110452,13 +111079,13 @@ function reviveAbortController(value, ops, runId) {
110452
111079
  };
110453
111080
  return controller;
110454
111081
  }
110455
- function reviveAbortSignal(value, ops, runId) {
111082
+ function reviveAbortSignal(value, ops, runId, cryptoKey, untilCancelled = false) {
110456
111083
  const controller = new AbortController();
110457
111084
  if (value.aborted) {
110458
111085
  tagAbortPair(controller, value);
110459
111086
  controller.abort(value.reason);
110460
111087
  } else if (value.streamName) {
110461
- const readerCancel = setupAbortStreamReader(controller, runId, value.streamName, ops);
111088
+ const readerCancel = setupAbortStreamReader(controller, runId, value.streamName, ops, cryptoKey, untilCancelled);
110462
111089
  tagAbortPair(controller, value, readerCancel);
110463
111090
  } else {
110464
111091
  tagAbortPair(controller, value);
@@ -110670,8 +111297,8 @@ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey, option
110670
111297
  encryptionPublicKey: value.encryptionPublicKey
110671
111298
  });
110672
111299
  }, "WritableStream"),
110673
- AbortController: /* @__PURE__ */ __name((value) => options?.liveAbortSignals === false ? reviveAbortSnapshot(value) : reviveAbortController(value, ops, runId), "AbortController"),
110674
- AbortSignal: /* @__PURE__ */ __name((value) => options?.liveAbortSignals === false ? reviveAbortSnapshot(value).signal : reviveAbortSignal(value, ops, runId), "AbortSignal")
111300
+ AbortController: /* @__PURE__ */ __name((value) => options?.liveAbortSignals === false ? reviveAbortSnapshot(value) : reviveAbortController(value, ops, runId, cryptoKey), "AbortController"),
111301
+ AbortSignal: /* @__PURE__ */ __name((value) => options?.liveAbortSignals === false ? reviveAbortSnapshot(value).signal : reviveAbortSignal(value, ops, runId, cryptoKey), "AbortSignal")
110675
111302
  };
110676
111303
  }
110677
111304
  function getWorkflowRevivers(global2 = globalThis) {
@@ -110959,8 +111586,10 @@ function getStepRevivers(global2 = globalThis, ops, runId, cryptoKey, deployment
110959
111586
  }
110960
111587
  return writable;
110961
111588
  }, "WritableStream"),
110962
- AbortController: /* @__PURE__ */ __name((value) => reviveAbortController(value, ops, runId), "AbortController"),
110963
- AbortSignal: /* @__PURE__ */ __name((value) => reviveAbortSignal(value, ops, runId), "AbortSignal")
111589
+ // A step's readers are cancelled when the step returns
111590
+ // (`cancelAbortReaders`), so they may outlive an empty stream.
111591
+ AbortController: /* @__PURE__ */ __name((value) => reviveAbortController(value, ops, runId, cryptoKey, true), "AbortController"),
111592
+ AbortSignal: /* @__PURE__ */ __name((value) => reviveAbortSignal(value, ops, runId, cryptoKey, true), "AbortSignal")
110964
111593
  };
110965
111594
  }
110966
111595
  async function maybeEncrypt(data2, key) {
@@ -111297,7 +111926,7 @@ function getStreamAndRequestRevivers(allRevivers) {
111297
111926
  }
111298
111927
  return extra;
111299
111928
  }
111300
- var defaultUlid, FRAME_HEADER_SIZE, MAX_FRAME_SIZE, WorkflowServerReadableStream, FRAMED_STREAM_MAX_RECONNECTS, getFramedStreamMaxReconnects, FRAMED_STREAM_MAX_TOTAL_RECONNECTS, getFramedStreamMaxTotalReconnects, FRAMED_STREAM_MAX_STALLS_BELOW_TAIL, FRAMED_STREAM_MIN_STALL_SESSION_MS, STREAM_FLUSH_INTERVAL_MS, getEnvStreamFlushIntervalMs, WorkflowServerWritableStream, prepareReplayPayload, STREAM_AND_REQUEST_KEYS;
111929
+ var defaultUlid, FRAME_HEADER_SIZE, MAX_FRAME_SIZE, WorkflowServerReadableStream, FRAMED_STREAM_MAX_RECONNECTS, getFramedStreamMaxReconnects, FRAMED_STREAM_MAX_TOTAL_RECONNECTS, getFramedStreamMaxTotalReconnects, FRAMED_STREAM_MAX_STALLS_BELOW_TAIL, FRAMED_STREAM_MIN_STALL_SESSION_MS, STREAM_FLUSH_INTERVAL_MS, getEnvStreamFlushIntervalMs, WorkflowServerWritableStream, LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS, prepareReplayPayload, STREAM_AND_REQUEST_KEYS;
111301
111930
  var init_serialization2 = __esm({
111302
111931
  "../core/dist/serialization.js"() {
111303
111932
  "use strict";
@@ -111313,6 +111942,7 @@ var init_serialization2 = __esm({
111313
111942
  init_private();
111314
111943
  init_get_world_lazy();
111315
111944
  init_sealed_box();
111945
+ init_abort_local();
111316
111946
  init_abort_stream();
111317
111947
  init_client();
111318
111948
  init_compression();
@@ -111579,9 +112209,9 @@ var init_serialization2 = __esm({
111579
112209
  startDispatch();
111580
112210
  return;
111581
112211
  }
111582
- const settled = drainWaiters;
112212
+ const settled2 = drainWaiters;
111583
112213
  drainWaiters = [];
111584
- for (const w of settled) w.resolve();
112214
+ for (const w of settled2) w.resolve();
111585
112215
  }, (error62) => {
111586
112216
  inFlight = null;
111587
112217
  sinkError ??= error62;
@@ -111700,6 +112330,7 @@ var init_serialization2 = __esm({
111700
112330
  __name(getWorkflowReducers, "getWorkflowReducers");
111701
112331
  __name(getStepReducers, "getStepReducers");
111702
112332
  __name(cancelAbortReaders, "cancelAbortReaders");
112333
+ LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS = 60 * 60 * 1e3;
111703
112334
  __name(setupAbortStreamReader, "setupAbortStreamReader");
111704
112335
  __name(tagAbortPair, "tagAbortPair");
111705
112336
  __name(copyAbortInternals, "copyAbortInternals");
@@ -111953,6 +112584,7 @@ init_dist4();
111953
112584
  init_logger();
111954
112585
  init_encryption2();
111955
112586
  init_serialization2();
112587
+ init_context_storage();
111956
112588
 
111957
112589
  // ../core/dist/runtime/dynamic-workflow.js
111958
112590
  init_dist2();
@@ -119366,7 +119998,7 @@ var START_HOOK_CONFIRM_DELAYS_MS = [
119366
119998
  300,
119367
119999
  900
119368
120000
  ];
119369
- var sleep3 = /* @__PURE__ */ __name((ms2) => new Promise((resolve2) => setTimeout(resolve2, ms2)), "sleep");
120001
+ var sleep4 = /* @__PURE__ */ __name((ms2) => new Promise((resolve2) => setTimeout(resolve2, ms2)), "sleep");
119370
120002
  function finalInStep(error62) {
119371
120003
  if (contextStorage.getStore()?.workflowMetadata !== void 0 && error62 instanceof Error) {
119372
120004
  Object.defineProperty(error62, "fatal", {
@@ -119385,7 +120017,7 @@ function isPermanentWorldError(error62) {
119385
120017
  __name(isPermanentWorldError, "isPermanentWorldError");
119386
120018
  function assertDynamicWorkflowsEnabled() {
119387
120019
  if (!isDynamicWorkflowsEnabled()) {
119388
- throw dynamicStartRefusal(`Dynamic workflows are disabled on this deployment, so no run was created. Set ${DYNAMIC_WORKFLOWS_ENV}=1 on the deployment to enable them.`);
120020
+ throw new DynamicWorkflowsNotEnabledError("Dynamic workflows are not enabled for this project, so start() did not create a run for the given workflow source.");
119389
120021
  }
119390
120022
  }
119391
120023
  __name(assertDynamicWorkflowsEnabled, "assertDynamicWorkflowsEnabled");
@@ -119810,7 +120442,7 @@ async function start(workflow, argsOrOptions, options) {
119810
120442
  throw error62;
119811
120443
  }
119812
120444
  if (attempt < START_HOOK_CONFIRM_DELAYS_MS.length) {
119813
- await sleep3(START_HOOK_CONFIRM_DELAYS_MS[attempt]);
120445
+ await sleep4(START_HOOK_CONFIRM_DELAYS_MS[attempt]);
119814
120446
  continue;
119815
120447
  }
119816
120448
  recordConfirmAttempts();
@@ -119833,7 +120465,7 @@ async function start(workflow, argsOrOptions, options) {
119833
120465
  break;
119834
120466
  } catch (error62) {
119835
120467
  if (!isPermanentWorldError(error62) && attempt2 < START_HOOK_CONFIRM_DELAYS_MS.length) {
119836
- await sleep3(START_HOOK_CONFIRM_DELAYS_MS[attempt2]);
120468
+ await sleep4(START_HOOK_CONFIRM_DELAYS_MS[attempt2]);
119837
120469
  continue;
119838
120470
  }
119839
120471
  recordStartHookOutcome(span, "uncertain");
@@ -119941,7 +120573,7 @@ __name(start, "start");
119941
120573
  value: "start",
119942
120574
  configurable: true
119943
120575
  });
119944
- })(start, "step//@workflow/core/runtime/start@5.6.1//start");
120576
+ })(start, "step//@workflow/core/runtime/start@5.7.1//start");
119945
120577
 
119946
120578
  // ../core/dist/runtime/runs.js
119947
120579
  function isSingleOrchestratorRun(run2) {
@@ -119969,6 +120601,100 @@ async function wakeRunAfterOutOfBandWrite(world, run2) {
119969
120601
  }
119970
120602
  }
119971
120603
  __name(wakeRunAfterOutOfBandWrite, "wakeRunAfterOutOfBandWrite");
120604
+ async function deleteRuns(world, runIds2) {
120605
+ if (runIds2.length === 0) {
120606
+ throw new FatalError("deleteRuns requires at least one run ID.");
120607
+ }
120608
+ if (runIds2.length > DELETE_RUNS_DATA_MAX_RUN_IDS) {
120609
+ throw new FatalError(`deleteRuns accepts at most ${DELETE_RUNS_DATA_MAX_RUN_IDS} run IDs (received ${runIds2.length}).`);
120610
+ }
120611
+ if (new Set(runIds2).size !== runIds2.length) {
120612
+ throw new FatalError("deleteRuns requires unique run IDs (duplicates found).");
120613
+ }
120614
+ if (!world.runs.deleteDataMany) {
120615
+ throw new FatalError("The configured World does not support deleting run data.");
120616
+ }
120617
+ const { deleteDataMany } = world.runs;
120618
+ const request = /* @__PURE__ */ __name((ids) => deleteDataMany.call(world.runs, {
120619
+ runIds: ids
120620
+ }), "request");
120621
+ const inStep = contextStorage.getStore() !== void 0;
120622
+ let results = await requestRunDataDeletion(request, runIds2, inStep);
120623
+ if (inStep) {
120624
+ let retryable = retryableFailures(results);
120625
+ if (retryable.length > 0) {
120626
+ await new Promise((resolve2) => setTimeout(resolve2, DELETE_RUNS_IN_CALL_RETRY_DELAY_MS));
120627
+ const retried = await requestRunDataDeletion(request, retryable.map((result) => result.runId), inStep);
120628
+ const retriedById = new Map(retried.map((r) => [
120629
+ r.runId,
120630
+ r
120631
+ ]));
120632
+ results = results.map((result) => retriedById.get(result.runId) ?? result);
120633
+ retryable = retryableFailures(results);
120634
+ }
120635
+ if (retryable.length > 0) {
120636
+ const codes = [
120637
+ ...new Set(retryable.map((result) => result.code))
120638
+ ];
120639
+ throw new RetryableError(`Deleting the data of ${describeRunIds(retryable.map((result) => result.runId))} failed (${codes.join(", ")}) and will be retried.`, {
120640
+ retryAfter: DELETE_RUNS_STEP_RETRY_DELAY_MS
120641
+ });
120642
+ }
120643
+ }
120644
+ return {
120645
+ summary: summarizeRunDataDeletion(results),
120646
+ results
120647
+ };
120648
+ }
120649
+ __name(deleteRuns, "deleteRuns");
120650
+ var DELETE_RUNS_IN_CALL_RETRY_DELAY_MS = 1e3;
120651
+ var DELETE_RUNS_STEP_RETRY_DELAY_MS = 1e4;
120652
+ async function requestRunDataDeletion(request, runIds2, inStep) {
120653
+ let response;
120654
+ try {
120655
+ response = await request(runIds2);
120656
+ } catch (err) {
120657
+ if (inStep && ThrottleError.is(err)) {
120658
+ throw new RetryableError(`The World rate-limited deleting the data of ${describeRunIds(runIds2)}.`, {
120659
+ retryAfter: typeof err.retryAfter === "number" ? err.retryAfter * 1e3 : DELETE_RUNS_STEP_RETRY_DELAY_MS
120660
+ });
120661
+ }
120662
+ throw err;
120663
+ }
120664
+ const resultByRunId = new Map(response.results.map((result) => [
120665
+ result.runId,
120666
+ result
120667
+ ]));
120668
+ if (resultByRunId.size !== response.results.length || response.results.length !== runIds2.length || !runIds2.every((runId) => resultByRunId.has(runId))) {
120669
+ const unanswered = runIds2.filter((runId) => !resultByRunId.has(runId));
120670
+ throw new Error(`The World did not answer the deletion of the data of ${describeRunIds(unanswered.length > 0 ? unanswered : runIds2)} with exactly one result per run (requested ${runIds2.length}, received ${response.results.length}).`);
120671
+ }
120672
+ return runIds2.map((runId) => resultByRunId.get(runId));
120673
+ }
120674
+ __name(requestRunDataDeletion, "requestRunDataDeletion");
120675
+ function retryableFailures(results) {
120676
+ return results.filter((result) => result.outcome === "failed" && result.retryable);
120677
+ }
120678
+ __name(retryableFailures, "retryableFailures");
120679
+ function summarizeRunDataDeletion(results) {
120680
+ const count2 = /* @__PURE__ */ __name((outcome) => results.filter((result) => result.outcome === outcome).length, "count");
120681
+ return {
120682
+ requested: results.length,
120683
+ deleted: count2("deleted"),
120684
+ alreadyDeleted: count2("already_deleted"),
120685
+ skipped: count2("skipped"),
120686
+ notCreated: count2("not_created"),
120687
+ notFound: count2("not_found"),
120688
+ failed: count2("failed")
120689
+ };
120690
+ }
120691
+ __name(summarizeRunDataDeletion, "summarizeRunDataDeletion");
120692
+ function describeRunIds(runIds2) {
120693
+ const shown = runIds2.slice(0, 3).join(", ");
120694
+ const more = runIds2.length > 3 ? ` and ${runIds2.length - 3} more` : "";
120695
+ return `${runIds2.length === 1 ? "run" : "runs"} ${shown}${more}`;
120696
+ }
120697
+ __name(describeRunIds, "describeRunIds");
119972
120698
  var MAX_TRACKED_WAKE_UP_RUNS = 1e3;
119973
120699
  var wakeUps = globalSingleton("@workflow/core//pendingWakeUpWaits", 1, () => ({
119974
120700
  byRun: /* @__PURE__ */ new Map()
@@ -120293,6 +121019,38 @@ var Run = class _Run {
120293
121019
  await wakeRunAfterOutOfBandWrite(world, run2);
120294
121020
  await afterRunCancelled(world, run2);
120295
121021
  }
121022
+ /**
121023
+ * Deletes the stored data of the finished run: its input, output and
121024
+ * error, its steps' and events' payloads, its hook payloads, and its
121025
+ * stream contents, as if it had been started with
121026
+ * `experimental_retention: 0`. This cannot be undone.
121027
+ *
121028
+ * Metadata is not deleted: the run stays listed, and so do its steps,
121029
+ * events and hooks, with their IDs, names, statuses, timestamps and the
121030
+ * run's attributes. Only their payloads go, reading back as expired.
121031
+ *
121032
+ * Only a finished run has its data deleted. A run that has not finished
121033
+ * is answered `skipped` and left running: cancel it first (see
121034
+ * {@link Run.cancel}) to delete its data now.
121035
+ *
121036
+ * Runs as a step. Inside a workflow, a retryable failure (or the World
121037
+ * rate-limiting the request) throws a `RetryableError`, so the step
121038
+ * retries; deletion is idempotent, so a retry finishes what the failed
121039
+ * attempt left. Called outside a workflow, a `failed` result is returned
121040
+ * as is.
121041
+ *
121042
+ * @returns the run's outcome: `deleted`, `already_deleted` (its data was
121043
+ * already gone), `skipped` (with the run's `status`), `not_created`,
121044
+ * `not_found`, or `failed` (with `code`, and `retryable` when retrying
121045
+ * can succeed).
121046
+ * @throws if the configured World does not support deleting run data.
121047
+ */
121048
+ async delete() {
121049
+ const { results } = await deleteRuns(await this.#lazyWorldPromise, [
121050
+ this.runId
121051
+ ]);
121052
+ return results[0];
121053
+ }
120296
121054
  /**
120297
121055
  * Whether the workflow run exists.
120298
121056
  */
@@ -120581,7 +121339,7 @@ var Run = class _Run {
120581
121339
  value: "readFinishedRunIds",
120582
121340
  configurable: true
120583
121341
  });
120584
- })(Run.readFinishedRunIds, "step//@workflow/core/runtime/run@5.6.1//Run.readFinishedRunIds");
121342
+ })(Run.readFinishedRunIds, "step//@workflow/core/runtime/run@5.7.1//Run.readFinishedRunIds");
120585
121343
  (function(__wf_fn, __wf_id) {
120586
121344
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120587
121345
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120590,7 +121348,7 @@ var Run = class _Run {
120590
121348
  value: "wakeUp",
120591
121349
  configurable: true
120592
121350
  });
120593
- })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.6.1//Run#wakeUp");
121351
+ })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.7.1//Run#wakeUp");
120594
121352
  (function(__wf_fn, __wf_id) {
120595
121353
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120596
121354
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120599,7 +121357,16 @@ var Run = class _Run {
120599
121357
  value: "cancel",
120600
121358
  configurable: true
120601
121359
  });
120602
- })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.6.1//Run#cancel");
121360
+ })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.7.1//Run#cancel");
121361
+ (function(__wf_fn, __wf_id) {
121362
+ var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
121363
+ __wf_reg.set(__wf_id, __wf_fn);
121364
+ __wf_fn.stepId = __wf_id;
121365
+ Object.defineProperty(__wf_fn, "name", {
121366
+ value: "delete",
121367
+ configurable: true
121368
+ });
121369
+ })(Run.prototype["delete"], "step//@workflow/core/runtime/run@5.7.1//Run#delete");
120603
121370
  (function(__wf_fn, __wf_id) {
120604
121371
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120605
121372
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120608,7 +121375,7 @@ var Run = class _Run {
120608
121375
  value: "readReturnValue",
120609
121376
  configurable: true
120610
121377
  });
120611
- })(Run.prototype["readReturnValue"], "step//@workflow/core/runtime/run@5.6.1//Run#readReturnValue");
121378
+ })(Run.prototype["readReturnValue"], "step//@workflow/core/runtime/run@5.7.1//Run#readReturnValue");
120612
121379
  (function(__wf_fn, __wf_id) {
120613
121380
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120614
121381
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120617,7 +121384,7 @@ var Run = class _Run {
120617
121384
  value: "getReadable",
120618
121385
  configurable: true
120619
121386
  });
120620
- })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.6.1//Run#getReadable");
121387
+ })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.7.1//Run#getReadable");
120621
121388
  (function(__wf_fn, __wf_id) {
120622
121389
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120623
121390
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120626,7 +121393,7 @@ var Run = class _Run {
120626
121393
  value: "getWritable",
120627
121394
  configurable: true
120628
121395
  });
120629
- })(Run.prototype["getWritable"], "step//@workflow/core/runtime/run@5.6.1//Run#getWritable");
121396
+ })(Run.prototype["getWritable"], "step//@workflow/core/runtime/run@5.7.1//Run#getWritable");
120630
121397
  (function(__wf_fn, __wf_id) {
120631
121398
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120632
121399
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120635,7 +121402,7 @@ var Run = class _Run {
120635
121402
  value: "exists",
120636
121403
  configurable: true
120637
121404
  });
120638
- })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.6.1//Run#exists");
121405
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.7.1//Run#exists");
120639
121406
  (function(__wf_fn, __wf_id) {
120640
121407
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120641
121408
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120644,7 +121411,7 @@ var Run = class _Run {
120644
121411
  value: "status",
120645
121412
  configurable: true
120646
121413
  });
120647
- })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.6.1//Run#status");
121414
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.7.1//Run#status");
120648
121415
  (function(__wf_fn, __wf_id) {
120649
121416
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120650
121417
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120653,7 +121420,7 @@ var Run = class _Run {
120653
121420
  value: "workflowName",
120654
121421
  configurable: true
120655
121422
  });
120656
- })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.6.1//Run#workflowName");
121423
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.7.1//Run#workflowName");
120657
121424
  (function(__wf_fn, __wf_id) {
120658
121425
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120659
121426
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120662,7 +121429,7 @@ var Run = class _Run {
120662
121429
  value: "createdAt",
120663
121430
  configurable: true
120664
121431
  });
120665
- })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.6.1//Run#createdAt");
121432
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.7.1//Run#createdAt");
120666
121433
  (function(__wf_fn, __wf_id) {
120667
121434
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120668
121435
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120671,7 +121438,7 @@ var Run = class _Run {
120671
121438
  value: "startedAt",
120672
121439
  configurable: true
120673
121440
  });
120674
- })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.6.1//Run#startedAt");
121441
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.7.1//Run#startedAt");
120675
121442
  (function(__wf_fn, __wf_id) {
120676
121443
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120677
121444
  __wf_reg.set(__wf_id, __wf_fn);
@@ -120680,7 +121447,7 @@ var Run = class _Run {
120680
121447
  value: "completedAt",
120681
121448
  configurable: true
120682
121449
  });
120683
- })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.6.1//Run#completedAt");
121450
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.7.1//Run#completedAt");
120684
121451
  (function(__wf_cls, __wf_id) {
120685
121452
  var __wf_sym = /* @__PURE__ */ Symbol.for("workflow-class-registry"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
120686
121453
  __wf_reg.set(__wf_id, __wf_cls);
@@ -120690,7 +121457,7 @@ var Run = class _Run {
120690
121457
  enumerable: false,
120691
121458
  configurable: false
120692
121459
  });
120693
- })(Run, "class//@workflow/core/runtime/run@5.6.1//Run");
121460
+ })(Run, "class//@workflow/core/runtime/run@5.7.1//Run");
120694
121461
 
120695
121462
  // ../workflow/dist/stdlib.js
120696
121463
  async function fetch2(...args) {